lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
JavaScript
mit
021f77742c7d2e9cbefecc64435bb0487fdf6e54
0
mhkeller/alphabits
var fs = require('fs'), Scraper = require('../lib/scratch-n-sniff.js'), _ = require('underscore'); var years = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013]; var scrape = Scraper() .data(years) .url('http://www.imdb.com/event/ev0000003/', function(d) { return d }) .extractor(parsePage, function(d) { return d } ) .rateLimit(1000) .format('csv'); // Defaults to json function parsePage($, year, callback, status){ console.log(status) // Print which page we're fetching var movies = []; // This scraper is getting multiple objects per page. You could also give the callback an object and it will still produce a csv $('[class^=alt] strong').each(function(index, el){ var movie = {}; var id = $(el).find('a').attr('href').split('/')[2].replace('tt',''), title = $(el).find('a').html().replace('é', 'é').replace(''' , '\'').replace('&', '&'); // Only include movies we haven't already encountered on this page if (_.chain(movies).map(function(m){ return _.values(m)}).flatten().value().indexOf(id) == -1){ movie.year = year; movie.imdbid = id; movie.title = title; movies.push(movie); } }) callback(movies) } // When all done scrape.done(function(results){ console.log('done') })
examples/noms.js
var fs = require('fs'), Scraper = require('../lib/scratch-n-sniff.js'), _ = require('underscore'); var years = [2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013]; var scrape = Scraper() .data(years) .url('http://www.imdb.com/event/ev0000003/', function(d) { return d }) .extractor(parsePage, function(d) { return d } ) .rateLimit(1000) .format('csv'); // Defaults to json function parsePage($, year, callback, status){ console.log(status) // Print which page we're fetching var movies = []; // This scraper is getting multiple objects per page. You could also give the callback an object and it will still produce a csv $('[class^=alt] strong').each(function(index, el){ var movie = {}; var id = $(el).find('a').attr('href').split('/')[2].replace('tt',''), title = $(el).find('a').html().replace('é', 'é').replace(''' , '\'').replace('&', '&'); // Only include movies we haven't already encountered on this page if (_.chain(movies).map(function(m){ return _.values(m)}).flatten().value().indexOf(id) == -1){ movie.year = year; movie.imdbid = id; movie.title = title; movies.push(movie); } }) callback(movies) } // When all done scrape.done(function(results){ console.log('done') })
format
examples/noms.js
format
<ide><path>xamples/noms.js <ide> .extractor(parsePage, function(d) { return d } ) <ide> .rateLimit(1000) <ide> .format('csv'); // Defaults to json <add> <ide> <ide> function parsePage($, year, callback, status){ <ide> console.log(status) // Print which page we're fetching
Java
apache-2.0
6fc367323a3fba3987b13cde913a2ec232c7340c
0
opensingular/singular-core,opensingular/singular-core,opensingular/singular-core,opensingular/singular-core
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensingular.form.wicket.model; import java.io.Serializable; import org.apache.wicket.model.IChainingModel; import org.apache.wicket.model.IDetachable; import org.apache.wicket.model.IModel; import org.opensingular.form.SIList; import org.opensingular.form.SInstance; public abstract class AbstractSInstanceItemListaModel<I extends SInstance> extends AbstractSInstanceModel<I> implements IChainingModel<I> { private Serializable rootTarget; public AbstractSInstanceItemListaModel(Serializable rootTarget) { this.rootTarget = rootTarget; } public int getIndex() { return index(); } protected abstract int index(); @Override public I getObject() { SIList<I> iLista = getRootTarget(); if (iLista == null || getIndex() < 0 || getIndex() >= iLista.size()) { return null; } return (I) iLista.get(getIndex()); } @SuppressWarnings("unchecked") public SIList<I> getRootTarget() { return (SIList<I>) ((rootTarget instanceof IModel<?>) ? ((IModel<?>) rootTarget).getObject() : rootTarget); } @Override public void detach() { if (rootTarget instanceof IDetachable) { ((IDetachable) rootTarget).detach(); } } @Override public void setChainedModel(IModel<?> rootModel) { this.rootTarget = rootModel; } @Override public IModel<?> getChainedModel() { return (rootTarget instanceof IModel) ? (IModel<?>) rootTarget : null; } @Override public int hashCode() { final I object = this.getObject(); final int prime = 31; int result = 1; result = prime * result + ((object == null) ? 0 : object.getPathFull().hashCode()); return result; } @Override @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final AbstractSInstanceItemListaModel<?> other = (AbstractSInstanceItemListaModel<?>) obj; final I object = this.getObject(); final I otherObject = (I) other.getObject(); if (object == null) { if (otherObject != null) return false; } else if (!object.getPathFull().equals(otherObject.getPathFull())) return false; if (getIndex() != other.getIndex()) return false; return true; } }
form/wicket/src/main/java/org/opensingular/form/wicket/model/AbstractSInstanceItemListaModel.java
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensingular.form.wicket.model; import java.io.Serializable; import org.apache.wicket.model.IChainingModel; import org.apache.wicket.model.IDetachable; import org.apache.wicket.model.IModel; import org.opensingular.form.SIList; import org.opensingular.form.SInstance; public abstract class AbstractSInstanceItemListaModel<I extends SInstance> extends AbstractSInstanceModel<I> implements IChainingModel<I> { private Serializable rootTarget; public AbstractSInstanceItemListaModel(Serializable rootTarget) { this.rootTarget = rootTarget; } public int getIndex() { return index(); } protected abstract int index(); @Override public I getObject() { SIList<I> iLista = getRootTarget(); if (iLista == null || getIndex() < 0 || getIndex() >= iLista.size()) return null; return (I) iLista.get(getIndex()); } @SuppressWarnings("unchecked") public SIList<I> getRootTarget() { return (SIList<I>) ((rootTarget instanceof IModel<?>) ? ((IModel<?>) rootTarget).getObject() : rootTarget); } @Override public void detach() { if (rootTarget instanceof IDetachable) { ((IDetachable) rootTarget).detach(); } } @Override public void setChainedModel(IModel<?> rootModel) { this.rootTarget = rootModel; } @Override public IModel<?> getChainedModel() { return (rootTarget instanceof IModel) ? (IModel<?>) rootTarget : null; } @Override public int hashCode() { final I object = this.getObject(); final int prime = 31; int result = 1; result = prime * result + ((object == null) ? 0 : object.getPathFull().hashCode()); return result; } @Override @SuppressWarnings("unchecked") public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final AbstractSInstanceItemListaModel<?> other = (AbstractSInstanceItemListaModel<?>) obj; final I object = this.getObject(); final I otherObject = (I) other.getObject(); if (object == null) { if (otherObject != null) return false; } else if (!object.getPathFull().equals(otherObject.getPathFull())) return false; if (getIndex() != other.getIndex()) return false; return true; } }
adicionando chaves à condições do getObject para melhoria de legibilidade
form/wicket/src/main/java/org/opensingular/form/wicket/model/AbstractSInstanceItemListaModel.java
adicionando chaves à condições do getObject para melhoria de legibilidade
<ide><path>orm/wicket/src/main/java/org/opensingular/form/wicket/model/AbstractSInstanceItemListaModel.java <ide> @Override <ide> public I getObject() { <ide> SIList<I> iLista = getRootTarget(); <del> if (iLista == null || getIndex() < 0 || getIndex() >= iLista.size()) <add> if (iLista == null || getIndex() < 0 || getIndex() >= iLista.size()) { <ide> return null; <add> } <ide> return (I) iLista.get(getIndex()); <ide> } <ide>
Java
mit
15d1229a2c6c87ebb17d194da590e06f94531154
0
cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic,cacheflowe/haxademic
package com.haxademic.core.draw.context; import com.haxademic.core.app.P; import processing.core.PApplet; import processing.core.PConstants; import processing.core.PGraphics; import processing.opengl.Texture; public class DrawUtil { /** * Clears all drawing properties so we may always have the same starting * point when drawing across classes. * * @param p Processing Applet for reference to p5 core */ public static void resetGlobalProps( PApplet p ) { // p.resetMatrix(); p.colorMode( P.RGB, 255, 255, 255, 255 ); p.fill( 0, 255, 0, 255 ); p.stroke( 0, 255, 0, 255 ); p.strokeWeight( 1 ); p.camera(); setDrawCenter(p); } public static void resetGlobalProps(PGraphics p) { // p.resetMatrix(); p.colorMode( P.RGB, 255, 255, 255, 255 ); p.fill( 0, 255, 0, 255 ); p.stroke( 0, 255, 0, 255 ); p.strokeWeight( 1 ); p.camera(); setDrawCenter(p); } public static void setCenter( PApplet p ) { // p.resetMatrix(); p.translate( 0, 0, 0 ); } public static void setCenter(PGraphics p) { // p.resetMatrix(); p.translate( 0, 0, 0 ); } public static void setCenterScreen( PApplet p ) { // p.resetMatrix(); p.translate( p.width/2, p.height/2, 0 ); } public static void setCenterScreen(PGraphics p) { // p.resetMatrix(); p.translate( p.width/2, p.height/2, 0 ); } public static void setTopLeft( PApplet p ) { // p.resetMatrix(); p.translate( -p.width/2, -p.height/2, 0 ); } public static void setTopLeft( PGraphics p ) { // p.resetMatrix(); p.translate( -p.width/2, -p.height/2, 0 ); } public static void setBasicLights( PApplet p ) { setBasicLights(p.g); } public static void setBasicLights( PGraphics pg ) { pg.shininess(500); pg.lights(); pg.ambientLight(25, 25, 25, 0, 0, 6000); pg.ambientLight(10, 10, 10, 0, 0, -6000); } public static void setBetterLights( PApplet p ) { setBetterLights(p.g); } public static void setBetterLights( PGraphics p ) { // setup lighting props p.ambient(127); p.lightSpecular(230, 230, 230); p.directionalLight(200, 200, 200, -0.0f, -0.0f, 1); p.directionalLight(200, 200, 200, 0.0f, 0.0f, -1); p.specular(p.color(200)); p.shininess(5.0f); } public static void setDrawCorner( PApplet p ) { setDrawCorner(p.g); } public static void setDrawCorner( PGraphics p ) { p.imageMode( PConstants.CORNER ); p.rectMode( PConstants.CORNER ); p.ellipseMode( PConstants.CORNER ); p.shapeMode( PConstants.CORNER ); } public static void setDrawCenter( PApplet p ) { setDrawCenter(p.g); } public static void setDrawCenter( PGraphics p ) { p.imageMode( PConstants.CENTER ); p.rectMode( PConstants.CENTER ); p.ellipseMode( PConstants.CENTER ); p.shapeMode( PConstants.CENTER ); } public static void setColorForPImage( PApplet p ) { setColorForPImage(p.g); } public static void setColorForPImage( PGraphics p ) { p.fill( 255, 255, 255, 255 ); } public static void setPImageAlpha( PApplet p, float alpha ) { setPImageAlpha(p.g, alpha); }; public static void setPImageAlpha( PGraphics p, float alpha ) { p.tint( 255, alpha * 255 ); } public static void resetPImageAlpha( PApplet p ) { resetPImageAlpha(p.g); }; public static void resetPImageAlpha( PGraphics p ) { p.tint( 255 ); } public static void setDrawFlat2d( PApplet p, boolean is2d ) { setDrawFlat2d(p.g, is2d); }; public static void setDrawFlat2d( PGraphics p, boolean is2d ) { if( is2d ) { p.hint( P.DISABLE_DEPTH_TEST ); } else { p.hint( P.ENABLE_DEPTH_TEST ); } } public static void setTextureRepeat( PApplet p, boolean doesRepeat ) { setTextureRepeat(p.g, doesRepeat); }; public static void setTextureRepeat(PGraphics pg, boolean doesRepeat) { if( doesRepeat == true ) pg.textureWrap(Texture.REPEAT); else pg.textureWrap(Texture.CLAMP); } public static void basicCameraFromMouse(PGraphics pg) { basicCameraFromMouse(pg, 1f); } public static void basicCameraFromMouse(PGraphics pg, float amp) { pg.rotateX(P.map(P.p.mousePercentY(), 0, 1, P.PI * amp, -P.PI * amp)); pg.rotateY(P.map(P.p.mousePercentX(), 0, 1, -P.PI * amp, P.PI * amp)); } public static void fadeInOut(PGraphics pg, int color, int startFrame, int stopFrame, int transitionFrames) { int frames = stopFrame - startFrame; DrawUtil.setDrawCorner(pg); if(P.p.frameCount <= startFrame + transitionFrames) { pg.fill(color, P.map(P.p.frameCount, 1f, transitionFrames, 255f, 0)); pg.rect(0,0,pg.width, pg.height); } else if(P.p.frameCount >= frames - transitionFrames) { pg.fill(color, P.map(P.p.frameCount, frames - transitionFrames, frames, 0, 255f)); pg.rect(0, 0, pg.width, pg.height); } } // only works properly on PGraphics buffers // feedback distance should only be even numbers public static void feedback(PGraphics pg, float feedbackDistance) { feedback(pg, -1, -1, feedbackDistance); } public static void feedback(PGraphics pg, int color, float colorFade, float feedbackDistance) { DrawUtil.setDrawCorner(pg); DrawUtil.setDrawFlat2d(pg, true); pg.copy( pg, 0, 0, pg.width, pg.height, P.round(-feedbackDistance), P.round(-feedbackDistance), P.round(pg.width + feedbackDistance * 2f), P.round(pg.height + feedbackDistance * 2f) ); if(color != -1) { pg.fill(color, colorFade * 255f); pg.noStroke(); pg.rect(0, 0, pg.width, pg.height); } DrawUtil.setDrawFlat2d(pg, false); } // from: http://p5art.tumblr.com/post/144205983628/a-small-transparency-tip public static void fadeToBlack(PGraphics pg, float blackVal) { pg.blendMode(P.SUBTRACT); pg.fill(blackVal); pg.rect(0, 0, pg.width * 3, pg.height * 3); pg.blendMode(P.BLEND); } public static void zoomReTexture(PGraphics pg, float amount) { float w = (float) pg.width; float h = (float) pg.height; float newW = w * amount; float newH = h * amount; pg.copy( (int) (w * 0.5f - newW * 0.5f), (int) (h * 0.5f - newH * 0.5f), (int) newW, (int) newH, 0, 0, pg.width, pg.height); } public static void rotateRedraw(PGraphics pg, float radians) { DrawUtil.setDrawCenter(pg); pg.beginDraw(); pg.pushMatrix(); DrawUtil.setCenterScreen(pg); pg.rotate(radians); pg.image(pg, 0, 0); pg.popMatrix(); pg.endDraw(); DrawUtil.setDrawCorner(pg); } public static void drawTestPattern(PGraphics pg) { pg.beginDraw(); pg.noStroke(); for( int x=0; x < pg.width; x+= 50) { for( int y=0; y < pg.height; y+= 50) { if( ( x % 100 == 0 && y % 100 == 0 ) || ( x % 100 == 50 && y % 100 == 50 ) ) { pg.fill(0); } else { pg.fill(255); } pg.rect(x,y,50,50); } } pg.endDraw(); } }
src/com/haxademic/core/draw/context/DrawUtil.java
package com.haxademic.core.draw.context; import com.haxademic.core.app.P; import processing.core.PApplet; import processing.core.PConstants; import processing.core.PGraphics; import processing.opengl.Texture; public class DrawUtil { /** * Clears all drawing properties so we may always have the same starting * point when drawing across classes. * * @param p Processing Applet for reference to p5 core */ public static void resetGlobalProps( PApplet p ) { // p.resetMatrix(); p.colorMode( P.RGB, 255, 255, 255, 255 ); p.fill( 0, 255, 0, 255 ); p.stroke( 0, 255, 0, 255 ); p.strokeWeight( 1 ); p.camera(); setDrawCenter(p); } public static void resetGlobalProps(PGraphics p) { // p.resetMatrix(); p.colorMode( P.RGB, 255, 255, 255, 255 ); p.fill( 0, 255, 0, 255 ); p.stroke( 0, 255, 0, 255 ); p.strokeWeight( 1 ); p.camera(); setDrawCenter(p); } public static void setCenter( PApplet p ) { // p.resetMatrix(); p.translate( 0, 0, 0 ); } public static void setCenter(PGraphics p) { // p.resetMatrix(); p.translate( 0, 0, 0 ); } public static void setCenterScreen( PApplet p ) { // p.resetMatrix(); p.translate( p.width/2, p.height/2, 0 ); } public static void setCenterScreen(PGraphics p) { // p.resetMatrix(); p.translate( p.width/2, p.height/2, 0 ); } public static void setTopLeft( PApplet p ) { // p.resetMatrix(); p.translate( -p.width/2, -p.height/2, 0 ); } public static void setTopLeft( PGraphics p ) { // p.resetMatrix(); p.translate( -p.width/2, -p.height/2, 0 ); } public static void setBasicLights( PApplet p ) { setBasicLights(p.g); } public static void setBasicLights( PGraphics pg ) { pg.shininess(500); pg.lights(); pg.ambientLight(25, 25, 25, 0, 0, 6000); pg.ambientLight(10, 10, 10, 0, 0, -6000); } public static void setBetterLights( PApplet p ) { setBetterLights(p.g); } public static void setBetterLights( PGraphics p ) { // setup lighting props p.ambient(127); p.lightSpecular(230, 230, 230); p.directionalLight(200, 200, 200, -0.0f, -0.0f, 1); p.directionalLight(200, 200, 200, 0.0f, 0.0f, -1); p.specular(p.color(200)); p.shininess(5.0f); } public static void setDrawCorner( PApplet p ) { setDrawCorner(p.g); } public static void setDrawCorner( PGraphics p ) { p.imageMode( PConstants.CORNER ); p.rectMode( PConstants.CORNER ); p.ellipseMode( PConstants.CORNER ); p.shapeMode( PConstants.CORNER ); } public static void setDrawCenter( PApplet p ) { setDrawCenter(p.g); } public static void setDrawCenter( PGraphics p ) { p.imageMode( PConstants.CENTER ); p.rectMode( PConstants.CENTER ); p.ellipseMode( PConstants.CENTER ); p.shapeMode( PConstants.CENTER ); } public static void setColorForPImage( PApplet p ) { setColorForPImage(p.g); } public static void setColorForPImage( PGraphics p ) { p.fill( 255, 255, 255, 255 ); } public static void setPImageAlpha( PApplet p, float alpha ) { setPImageAlpha(p.g, alpha); }; public static void setPImageAlpha( PGraphics p, float alpha ) { p.tint( 255, alpha * 255 ); } public static void resetPImageAlpha( PApplet p ) { resetPImageAlpha(p.g); }; public static void resetPImageAlpha( PGraphics p ) { p.tint( 255 ); } public static void setDrawFlat2d( PApplet p, boolean is2d ) { setDrawFlat2d(p.g, is2d); }; public static void setDrawFlat2d( PGraphics p, boolean is2d ) { if( is2d ) { p.hint( P.DISABLE_DEPTH_TEST ); } else { p.hint( P.ENABLE_DEPTH_TEST ); } } public static void setTextureRepeat( PApplet p, boolean doesRepeat ) { setTextureRepeat(p.g, doesRepeat); }; public static void setTextureRepeat(PGraphics pg, boolean doesRepeat) { if( doesRepeat == true ) pg.textureWrap(Texture.REPEAT); else pg.textureWrap(Texture.CLAMP); } public static void basicCameraFromMouse(PGraphics pg) { pg.rotateX(P.map(P.p.mousePercentY(), 0, 1, P.PI, -P.PI)); pg.rotateY(P.map(P.p.mousePercentX(), 0, 1, -P.PI, P.PI)); } public static void fadeInOut(PGraphics pg, int color, int startFrame, int stopFrame, int transitionFrames) { int frames = stopFrame - startFrame; DrawUtil.setDrawCorner(pg); if(P.p.frameCount <= startFrame + transitionFrames) { pg.fill(color, P.map(P.p.frameCount, 1f, transitionFrames, 255f, 0)); pg.rect(0,0,pg.width, pg.height); } else if(P.p.frameCount >= frames - transitionFrames) { pg.fill(color, P.map(P.p.frameCount, frames - transitionFrames, frames, 0, 255f)); pg.rect(0, 0, pg.width, pg.height); } } // only works properly on PGraphics buffers // feedback distance should only be even numbers public static void feedback(PGraphics pg, float feedbackDistance) { feedback(pg, -1, -1, feedbackDistance); } public static void feedback(PGraphics pg, int color, float colorFade, float feedbackDistance) { DrawUtil.setDrawCorner(pg); DrawUtil.setDrawFlat2d(pg, true); pg.copy( pg, 0, 0, pg.width, pg.height, P.round(-feedbackDistance), P.round(-feedbackDistance), P.round(pg.width + feedbackDistance * 2f), P.round(pg.height + feedbackDistance * 2f) ); if(color != -1) { pg.fill(color, colorFade * 255f); pg.noStroke(); pg.rect(0, 0, pg.width, pg.height); } DrawUtil.setDrawFlat2d(pg, false); } // from: http://p5art.tumblr.com/post/144205983628/a-small-transparency-tip public static void fadeToBlack(PGraphics pg, float blackVal) { pg.blendMode(P.SUBTRACT); pg.fill(blackVal); pg.rect(0, 0, pg.width * 3, pg.height * 3); pg.blendMode(P.BLEND); } public static void zoomReTexture(PGraphics pg, float amount) { float w = (float) pg.width; float h = (float) pg.height; float newW = w * amount; float newH = h * amount; pg.copy( (int) (w * 0.5f - newW * 0.5f), (int) (h * 0.5f - newH * 0.5f), (int) newW, (int) newH, 0, 0, pg.width, pg.height); } public static void rotateRedraw(PGraphics pg, float radians) { DrawUtil.setDrawCenter(pg); pg.beginDraw(); pg.pushMatrix(); DrawUtil.setCenterScreen(pg); pg.rotate(radians); pg.image(pg, 0, 0); pg.popMatrix(); pg.endDraw(); DrawUtil.setDrawCorner(pg); } public static void drawTestPattern(PGraphics pg) { pg.beginDraw(); pg.noStroke(); for( int x=0; x < pg.width; x+= 50) { for( int y=0; y < pg.height; y+= 50) { if( ( x % 100 == 0 && y % 100 == 0 ) || ( x % 100 == 50 && y % 100 == 50 ) ) { pg.fill(0); } else { pg.fill(255); } pg.rect(x,y,50,50); } } pg.endDraw(); } }
Add amplitude to basic mouse camera
src/com/haxademic/core/draw/context/DrawUtil.java
Add amplitude to basic mouse camera
<ide><path>rc/com/haxademic/core/draw/context/DrawUtil.java <ide> } <ide> <ide> public static void basicCameraFromMouse(PGraphics pg) { <del> pg.rotateX(P.map(P.p.mousePercentY(), 0, 1, P.PI, -P.PI)); <del> pg.rotateY(P.map(P.p.mousePercentX(), 0, 1, -P.PI, P.PI)); <add> basicCameraFromMouse(pg, 1f); <add> } <add> <add> public static void basicCameraFromMouse(PGraphics pg, float amp) { <add> pg.rotateX(P.map(P.p.mousePercentY(), 0, 1, P.PI * amp, -P.PI * amp)); <add> pg.rotateY(P.map(P.p.mousePercentX(), 0, 1, -P.PI * amp, P.PI * amp)); <ide> } <ide> <ide> public static void fadeInOut(PGraphics pg, int color, int startFrame, int stopFrame, int transitionFrames) {
JavaScript
mpl-2.0
0496759e168f7d782329b375269feb5aa071d501
0
AdamHillier/activity-stream,mozilla/activity-stream,rlr/activity-streams,AdamHillier/activity-stream,mozilla/activity-streams,rlr/activity-streams,Mardak/activity-stream,rlr/activity-streams,sarracini/activity-stream,mozilla/activity-stream,AdamHillier/activity-stream,Mardak/activity-stream,sarracini/activity-stream,AdamHillier/activity-stream,mozilla/activity-stream,sarracini/activity-stream,mozilla/activity-stream,Mardak/activity-stream,rlr/activity-streams,Mardak/activity-stream,mozilla/activity-streams,sarracini/activity-stream
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; Cu.importGlobalProperties(["fetch"]); ChromeUtils.import("resource://gre/modules/Services.jsm"); ChromeUtils.defineModuleGetter(this, "PluralForm", "resource://gre/modules/PluralForm.jsm"); const {actionTypes: at} = ChromeUtils.import("resource://activity-stream/common/Actions.jsm", {}); const PREFERENCES_LOADED_EVENT = "sync-pane-loaded"; const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; // These "section" objects are formatted in a way to be similar to the ones from // SectionsManager to construct the preferences view. const PREFS_BEFORE_SECTIONS = [ { id: "search", pref: { feed: "showSearch", titleString: "prefs_search_header" }, icon: "chrome://browser/skin/search-glass.svg" }, { id: "topsites", pref: { feed: "feeds.topsites", titleString: "settings_pane_topsites_header", descString: "prefs_topsites_description" }, icon: "topsites", maxRows: 2, rowsPref: "topSitesRows" } ]; const PREFS_AFTER_SECTIONS = [ { id: "snippets", pref: { feed: "feeds.snippets", titleString: "settings_pane_snippets_header", descString: "prefs_snippets_description" }, icon: "info" } ]; // This CSS is added to the whole about:preferences page const CUSTOM_CSS = ` #homeContentsGroup checkbox[src] .checkbox-icon { margin-inline-end: 8px; margin-inline-start: 4px; width: 16px; } #homeContentsGroup [data-subcategory] { margin-top: 14px; } #homeContentsGroup [data-subcategory] > checkbox { font-weight: 600; } #homeContentsGroup [data-subcategory] > vbox menulist { margin-top: 0; margin-bottom: 0; } `; this.AboutPreferences = class AboutPreferences { init() { Services.obs.addObserver(this, PREFERENCES_LOADED_EVENT); } uninit() { Services.obs.removeObserver(this, PREFERENCES_LOADED_EVENT); } onAction(action) { switch (action.type) { case at.INIT: this.init(); break; case at.UNINIT: this.uninit(); break; case at.SETTINGS_OPEN: action._target.browser.ownerGlobal.openPreferences("paneHome", {origin: "aboutHome"}); break; // This is used to open the web extension settings page for an extension case at.OPEN_WEBEXT_SETTINGS: action._target.browser.ownerGlobal.BrowserOpenAddonsMgr(`addons://detail/${encodeURIComponent(action.data)}`); break; } } async observe(window) { this.renderPreferences(window, await this.strings, [...PREFS_BEFORE_SECTIONS, ...this.store.getState().Sections, ...PREFS_AFTER_SECTIONS]); } /** * Get strings from a js file that the content page would have loaded. The * file should be a single variable assignment of a JSON/JS object of strings. */ get strings() { return this._strings || (this._strings = new Promise(async resolve => { let data = {}; try { const locale = Cc["@mozilla.org/browser/aboutnewtab-service;1"] .getService(Ci.nsIAboutNewTabService).activityStreamLocale; const request = await fetch(`resource://activity-stream/prerendered/${locale}/activity-stream-strings.js`); const text = await request.text(); const [json] = text.match(/{[^]*}/); data = JSON.parse(json); } catch (ex) { Cu.reportError("Failed to load strings for Activity Stream about:preferences"); } resolve(data); })); } /** * Render preferences to an about:preferences content window with the provided * strings and preferences structure. */ renderPreferences({document, Preferences}, strings, prefStructure) { // Helper to create a new element and append it const createAppend = (tag, parent) => parent.appendChild( document.createElementNS(XUL_NS, tag)); // Helper to get strings and format with values if necessary const formatString = id => { if (typeof id !== "object") { return strings[id] || id; } let string = strings[id.id] || JSON.stringify(id); if (id.values) { Object.entries(id.values).forEach(([key, val]) => { string = string.replace(new RegExp(`{${key}}`, "g"), val); }); } return string; }; // Helper to link a UI element to a preference for updating const linkPref = (element, name, type) => { const fullPref = `browser.newtabpage.activity-stream.${name}`; element.setAttribute("preference", fullPref); Preferences.add({id: fullPref, type}); // Prevent changing the UI if the preference can't be changed element.disabled = Preferences.get(fullPref).locked; }; // Add in custom styling document.insertBefore(document.createProcessingInstruction("xml-stylesheet", `href="data:text/css,${encodeURIComponent(CUSTOM_CSS)}" type="text/css"`), document.documentElement); // Insert a new group immediately after the homepage one const homeGroup = document.getElementById("homepageGroup"); const contentsGroup = homeGroup.insertAdjacentElement("afterend", homeGroup.cloneNode()); contentsGroup.id = "homeContentsGroup"; contentsGroup.setAttribute("data-subcategory", "contents"); const caption = createAppend("caption", contentsGroup); caption.setAttribute("label", formatString("prefs_home_header")); const description = createAppend("description", contentsGroup); description.textContent = formatString("prefs_home_description"); // Add preferences for each section prefStructure.forEach(sectionData => { const { id, pref: prefData, icon = "webextension", maxRows, rowsPref, shouldHidePref } = sectionData; const { feed: name, titleString, descString, nestedPrefs = [] } = prefData || {}; // Don't show any sections that we don't want to expose in preferences UI if (shouldHidePref) { return; } // Use full icon spec for certain protocols or fall back to packaged icon const iconUrl = !icon.search(/^(chrome|moz-extension|resource):/) ? icon : `resource://activity-stream/data/content/assets/glyph-${icon}-16.svg`; // Add the main preference for turning on/off a section const sectionVbox = createAppend("vbox", contentsGroup); sectionVbox.setAttribute("data-subcategory", id); const checkbox = createAppend("checkbox", sectionVbox); checkbox.setAttribute("label", formatString(titleString)); checkbox.setAttribute("src", iconUrl); linkPref(checkbox, name, "bool"); // Add more details for the section (e.g., description, more prefs) const detailVbox = createAppend("vbox", sectionVbox); detailVbox.classList.add("indent"); if (descString) { const label = createAppend("label", detailVbox); label.classList.add("indent"); label.textContent = formatString(descString); // Specially add a link for stories if (id === "topstories") { const sponsoredHbox = createAppend("hbox", detailVbox); sponsoredHbox.setAttribute("align", "center"); sponsoredHbox.appendChild(label); label.classList.add("tail-with-learn-more"); const link = createAppend("label", sponsoredHbox); link.classList.add("learn-sponsored"); link.classList.add("text-link"); link.setAttribute("href", sectionData.disclaimer.link.href); link.textContent = formatString("prefs_topstories_sponsored_learn_more"); } // Add a rows dropdown if we have a pref to control and a maximum if (rowsPref && maxRows) { const detailHbox = createAppend("hbox", detailVbox); detailHbox.setAttribute("align", "center"); label.setAttribute("flex", 1); detailHbox.appendChild(label); // Add appropriate number of localized entries to the dropdown const menulist = createAppend("menulist", detailHbox); menulist.setAttribute("crop", "none"); const menupopup = createAppend("menupopup", menulist); for (let num = 1; num <= maxRows; num++) { const plurals = formatString({id: "prefs_section_rows_option", values: {num}}); const item = createAppend("menuitem", menupopup); item.setAttribute("label", PluralForm.get(num, plurals)); item.setAttribute("value", num); } linkPref(menulist, rowsPref, "int"); } } // Add a checkbox pref for any nested preferences nestedPrefs.forEach(nested => { const subcheck = createAppend("checkbox", detailVbox); subcheck.classList.add("indent"); subcheck.setAttribute("label", formatString(nested.titleString)); linkPref(subcheck, nested.name, "bool"); }); }); } }; this.PREFERENCES_LOADED_EVENT = PREFERENCES_LOADED_EVENT; const EXPORTED_SYMBOLS = ["AboutPreferences", "PREFERENCES_LOADED_EVENT"];
system-addon/lib/AboutPreferences.jsm
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; Cu.importGlobalProperties(["fetch"]); ChromeUtils.import("resource://gre/modules/Services.jsm"); ChromeUtils.defineModuleGetter(this, "PluralForm", "resource://gre/modules/PluralForm.jsm"); const {actionTypes: at} = ChromeUtils.import("resource://activity-stream/common/Actions.jsm", {}); const PREFERENCES_LOADED_EVENT = "sync-pane-loaded"; const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; // These "section" objects are formatted in a way to be similar to the ones from // SectionsManager to construct the preferences view. const PREFS_BEFORE_SECTIONS = [ { id: "search", pref: { feed: "showSearch", titleString: "prefs_search_header" }, icon: "chrome://browser/skin/search-glass.svg" }, { id: "topsites", pref: { feed: "feeds.topsites", titleString: "settings_pane_topsites_header", descString: "prefs_topsites_description" }, icon: "topsites", maxRows: 2, rowsPref: "topSitesRows" } ]; const PREFS_AFTER_SECTIONS = [ { id: "snippets", pref: { feed: "feeds.snippets", titleString: "settings_pane_snippets_header", descString: "prefs_snippets_description" }, icon: "info" } ]; // This CSS is added to the whole about:preferences page const CUSTOM_CSS = ` #homeContentsGroup checkbox[src] .checkbox-icon { margin-inline-end: 8px; margin-inline-start: 4px; width: 16px; } #homeContentsGroup [data-subcategory] { margin-top: 14px; } #homeContentsGroup [data-subcategory] > checkbox { font-weight: 600; } #homeContentsGroup [data-subcategory] > vbox menulist { margin-top: 0; margin-bottom: 0; } `; this.AboutPreferences = class AboutPreferences { init() { Services.obs.addObserver(this, PREFERENCES_LOADED_EVENT); } uninit() { Services.obs.removeObserver(this, PREFERENCES_LOADED_EVENT); } onAction(action) { switch (action.type) { case at.INIT: this.init(); break; case at.UNINIT: this.uninit(); break; case at.SETTINGS_OPEN: action._target.browser.ownerGlobal.openPreferences("paneHome", {origin: "aboutHome"}); break; // This is used to open the web extension settings page for an extension case at.OPEN_WEBEXT_SETTINGS: action._target.browser.ownerGlobal.BrowserOpenAddonsMgr(`addons://detail/${encodeURIComponent(action.data)}`); break; } } async observe(window) { this.renderPreferences(window, await this.strings, [...PREFS_BEFORE_SECTIONS, ...this.store.getState().Sections, ...PREFS_AFTER_SECTIONS]); } /** * Get strings from a js file that the content page would have loaded. The * file should be a single variable assignment of a JSON/JS object of strings. */ get strings() { return this._strings || (this._strings = new Promise(async resolve => { let data = {}; try { const locale = Cc["@mozilla.org/browser/aboutnewtab-service;1"] .getService(Ci.nsIAboutNewTabService).activityStreamLocale; const request = await fetch(`resource://activity-stream/prerendered/${locale}/activity-stream-strings.js`); const text = await request.text(); const [json] = text.match(/{[^]*}/); data = JSON.parse(json); } catch (ex) { Cu.reportError("Failed to load strings for Activity Stream about:preferences"); } resolve(data); })); } /** * Render preferences to an about:preferences content window with the provided * strings and preferences structure. */ renderPreferences({document, Preferences}, strings, prefStructure) { // Helper to create a new element and append it const createAppend = (tag, parent) => parent.appendChild( document.createElementNS(XUL_NS, tag)); // Helper to get strings and format with values if necessary const formatString = id => { if (typeof id !== "object") { return strings[id] || id; } let string = strings[id.id] || JSON.stringify(id); if (id.values) { Object.entries(id.values).forEach(([key, val]) => { string = string.replace(new RegExp(`{${key}}`, "g"), val); }); } return string; }; // Helper to link a UI element to a preference for updating const linkPref = (element, name, type) => { const fullPref = `browser.newtabpage.activity-stream.${name}`; element.setAttribute("preference", fullPref); Preferences.add({id: fullPref, type}); // Prevent changing the UI if the preference can't be changed element.disabled = Preferences.get(fullPref).locked; }; // Add in custom styling document.insertBefore(document.createProcessingInstruction("xml-stylesheet", `href="data:text/css,${encodeURIComponent(CUSTOM_CSS)}" type="text/css"`), document.documentElement); // Insert a new group immediately after the homepage one const homeGroup = document.getElementById("homepageGroup"); const contentsGroup = homeGroup.insertAdjacentElement("afterend", homeGroup.cloneNode()); contentsGroup.id = "homeContentsGroup"; contentsGroup.setAttribute("data-subcategory", "contents"); const caption = createAppend("caption", contentsGroup); caption.setAttribute("label", formatString("prefs_home_header")); const description = createAppend("description", contentsGroup); description.textContent = formatString("prefs_home_description"); // Add preferences for each section prefStructure.forEach(sectionData => { const { id, pref: prefData, icon = "webextension", maxRows, rowsPref, shouldHidePref } = sectionData; const { feed: name, titleString, descString, nestedPrefs = [] } = prefData || {}; // Don't show any sections that we don't want to expose in preferences UI if (shouldHidePref) { return; } // Use full icon spec for certain protocols or fall back to packaged icon const iconUrl = !icon.search(/^(chrome|moz-extension|resource):/) ? icon : `resource://activity-stream/data/content/assets/glyph-${icon}-16.svg`; // Add the main preference for turning on/off a section const sectionVbox = createAppend("vbox", contentsGroup); sectionVbox.setAttribute("data-subcategory", id); const checkbox = createAppend("checkbox", sectionVbox); checkbox.setAttribute("label", formatString(titleString)); checkbox.setAttribute("src", iconUrl); linkPref(checkbox, name, "bool"); // Add more details for the section (e.g., description, more prefs) const detailVbox = createAppend("vbox", sectionVbox); detailVbox.classList.add("indent"); if (descString) { const label = createAppend("label", detailVbox); label.classList.add("indent"); label.textContent = formatString(descString); // Specially add a link for stories if (id === "topstories") { const sponsoredHbox = createAppend("hbox", detailVbox); sponsoredHbox.setAttribute("align", "center"); sponsoredHbox.appendChild(label); label.classList.add("tail-with-learn-more"); const link = createAppend("label", sponsoredHbox); link.classList.add("learn-sponsored"); link.classList.add("text-link"); link.setAttribute("href", sectionData.disclaimer.link.href); link.textContent = formatString("prefs_topstories_sponsored_learn_more"); } // Add a rows dropdown if we have a pref to control and a maximum if (rowsPref && maxRows) { const detailHbox = createAppend("hbox", detailVbox); detailHbox.setAttribute("align", "center"); label.setAttribute("flex", 1); detailHbox.appendChild(label); // Add appropriate number of localized entries to the dropdown const menulist = createAppend("menulist", detailHbox); const menupopup = createAppend("menupopup", menulist); for (let num = 1; num <= maxRows; num++) { const plurals = formatString({id: "prefs_section_rows_option", values: {num}}); const item = createAppend("menuitem", menupopup); item.setAttribute("label", PluralForm.get(num, plurals)); item.setAttribute("value", num); } linkPref(menulist, rowsPref, "int"); } } // Add a checkbox pref for any nested preferences nestedPrefs.forEach(nested => { const subcheck = createAppend("checkbox", detailVbox); subcheck.classList.add("indent"); subcheck.setAttribute("label", formatString(nested.titleString)); linkPref(subcheck, nested.name, "bool"); }); }); } }; this.PREFERENCES_LOADED_EVENT = PREFERENCES_LOADED_EVENT; const EXPORTED_SYMBOLS = ["AboutPreferences", "PREFERENCES_LOADED_EVENT"];
fix(preferences): Prevent "2 rows" menu item from getting cropped (#4168) Fix Bug 1457239 - Setting for number of rows is truncated making the label not readable unless you click on it
system-addon/lib/AboutPreferences.jsm
fix(preferences): Prevent "2 rows" menu item from getting cropped (#4168)
<ide><path>ystem-addon/lib/AboutPreferences.jsm <ide> <ide> // Add appropriate number of localized entries to the dropdown <ide> const menulist = createAppend("menulist", detailHbox); <add> menulist.setAttribute("crop", "none"); <ide> const menupopup = createAppend("menupopup", menulist); <ide> for (let num = 1; num <= maxRows; num++) { <ide> const plurals = formatString({id: "prefs_section_rows_option", values: {num}});
Java
apache-2.0
8ba7a9b2dccadbab10637d93204988487590a896
0
fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode
package com.fishercoder; import com.fishercoder.solutions._207; import org.junit.BeforeClass; import org.junit.Test; import static junit.framework.Assert.assertEquals; public class _207Test { private static _207.Solution1 solution1; private static _207.Solution2 solution2; private static int[][] prerequisites; private static int numCourses; @BeforeClass public static void setup() { solution1 = new _207.Solution1(); solution2 = new _207.Solution2(); } @Test public void test1() { numCourses = 2; prerequisites = new int[][]{{0, 1}}; assertEquals(true, solution1.canFinish(numCourses, prerequisites)); assertEquals(true, solution2.canFinish(numCourses, prerequisites)); } @Test public void test2() { numCourses = 8; prerequisites = new int[][]{ {3, 0}, {3, 1}, {5, 3}, {5, 2}, {6, 3}, {6, 1}, {7, 3}, {7, 4}, {4, 2}, }; assertEquals(true, solution1.canFinish(numCourses, prerequisites)); assertEquals(true, solution2.canFinish(numCourses, prerequisites)); } @Test public void test3() { numCourses = 8; prerequisites = new int[][]{ {3, 2}, {3, 0}, {5, 3}, {5, 1}, {7, 3}, {7, 0}, {6, 3}, {6, 4}, {4, 1}, }; assertEquals(true, solution1.canFinish(numCourses, prerequisites)); assertEquals(true, solution2.canFinish(numCourses, prerequisites)); } }
src/test/java/com/fishercoder/_207Test.java
package com.fishercoder; import com.fishercoder.solutions._207; import org.junit.BeforeClass; import org.junit.Test; import static junit.framework.Assert.assertEquals; public class _207Test { private static _207.Solution1 test; private static int[][] prerequisites; private static int numCourses; @BeforeClass public static void setup() { test = new _207.Solution1(); } @Test public void test1() { numCourses = 2; prerequisites = new int[][]{{0, 1}}; assertEquals(true, test.canFinish(numCourses, prerequisites)); } @Test public void test2() { numCourses = 8; prerequisites = new int[][]{ {3, 0}, {3, 1}, {5, 3}, {5, 2}, {6, 3}, {6, 1}, {7, 3}, {7, 4}, {4, 2}, }; assertEquals(true, test.canFinish(numCourses, prerequisites)); } }
refactor 207
src/test/java/com/fishercoder/_207Test.java
refactor 207
<ide><path>rc/test/java/com/fishercoder/_207Test.java <ide> import static junit.framework.Assert.assertEquals; <ide> <ide> public class _207Test { <del> private static _207.Solution1 test; <add> private static _207.Solution1 solution1; <add> private static _207.Solution2 solution2; <ide> private static int[][] prerequisites; <ide> private static int numCourses; <ide> <ide> @BeforeClass <ide> public static void setup() { <del> test = new _207.Solution1(); <add> solution1 = new _207.Solution1(); <add> solution2 = new _207.Solution2(); <ide> } <ide> <ide> @Test <ide> public void test1() { <ide> numCourses = 2; <ide> prerequisites = new int[][]{{0, 1}}; <del> assertEquals(true, test.canFinish(numCourses, prerequisites)); <add> assertEquals(true, solution1.canFinish(numCourses, prerequisites)); <add> assertEquals(true, solution2.canFinish(numCourses, prerequisites)); <ide> } <ide> <ide> @Test <ide> {4, 2}, <ide> <ide> }; <del> assertEquals(true, test.canFinish(numCourses, prerequisites)); <add> assertEquals(true, solution1.canFinish(numCourses, prerequisites)); <add> assertEquals(true, solution2.canFinish(numCourses, prerequisites)); <add> } <add> <add> @Test <add> public void test3() { <add> numCourses = 8; <add> prerequisites = new int[][]{ <add> {3, 2}, <add> {3, 0}, <add> {5, 3}, <add> {5, 1}, <add> {7, 3}, <add> {7, 0}, <add> {6, 3}, <add> {6, 4}, <add> {4, 1}, <add> <add> }; <add> assertEquals(true, solution1.canFinish(numCourses, prerequisites)); <add> assertEquals(true, solution2.canFinish(numCourses, prerequisites)); <ide> } <ide> }
JavaScript
mit
9632cf772e6c6ae3569439e9e84068be9202df8e
0
TadeoKondrak/circleclicker,TadeoKondrak/circleclicker
if (localStorage.save) { var game = JSON.parse(atob(localStorage.save)); } else { var game = { clicks: 0, upgrades: [0, 0, 0, 0, 0, 0, 0, 0], cps: 0, upgradePrice: [15, 100, 500, 2000, 7000, 50000, 1000000, 100000000], upgradeCps: [0.1, 0.5, 4, 10, 40, 100, 400, 7000] }; } function saveGame() { localStorage.save = btoa(JSON.stringify(game)); } function gameLoop() { game.clicks += game.cps; updateView(); saveGame(); } function buyUpgrade(x) { if (game.clicks >= game.upgradePrice[x]) { game.clicks -= game.upgradePrice[x]; game.upgradePrice[x] = Math.ceil(game.upgradePrice[x] * 1.15); game.upgrades[x] += 1; game.cps += game.upgradeCps[x]; } } var gameLoopInterval = setInterval(gameLoop, 1000); function updateView() { $("#count").html(Math.round(game.clicks).toLocaleString()); $("#cps").html((Math.round(game.cps * 10) / 10).toFixed(1)); $("#price0").html(game.upgradePrice[0]); $("#price1").html(game.upgradePrice[1]); $("#price2").html(game.upgradePrice[2]); $("#price3").html(game.upgradePrice[3]); $("#price4").html(game.upgradePrice[4]); $("#price5").html(game.upgradePrice[5]); $("#price6").html(game.upgradePrice[6]); $("#price7").html(game.upgradePrice[7]); $("#qty0").html(game.upgrades[0]); $("#qty1").html(game.upgrades[1]); $("#qty2").html(game.upgrades[2]); $("#qty3").html(game.upgrades[3]); $("#qty4").html(game.upgrades[4]); $("#qty5").html(game.upgrades[5]); $("#qty6").html(game.upgrades[6]); $("#qty7").html(game.upgrades[7]); } $(function() { $("#circle").click(function() { if(game.cps>4){ game.clicks += game.cps / 4; } else{ game.clicks += 1; } updateView(); }); }); function exportSave() { prompt('This is your save. Keep it.', btoa(JSON.stringify(game))); } function importSave() { game = JSON.parse(atob(prompt('Enter your save here. Your previous save will not be saved.'))); saveGame(); location.reload(); } function wipeSave() { if (confirm('Are you sure you would like to delete EVERYTHING?')) { clearInterval(gameLoopInterval); localStorage.save = ""; alert('Deleted.'); location.reload(); } else { alert('Cancelled.'); } }
js/main.js
if (localStorage.save) { var game = JSON.parse(atob(localStorage.save)); } else { var game = { clicks: 0, upgrades: [0, 0, 0, 0, 0, 0, 0, 0], cps: 0, upgradePrice: [15, 100, 500, 2000, 7000, 50000, 1000000, 100000000], upgradeCps: [0.1, 0.5, 4, 10, 40, 100, 400, 7000] }; } function saveGame() { localStorage.save = btoa(JSON.stringify(game)); } function gameLoop() { game.clicks += game.cps; updateView(); saveGame(); } function buyUpgrade(x) { if (game.clicks >= game.upgradePrice[x]) { game.clicks -= game.upgradePrice[x]; game.upgradePrice[x] = Math.ceil(game.upgradePrice[x] * 1.15); game.upgrades[x] += 1; game.cps += game.upgradeCps[x]; } } var gameLoopInterval = setInterval(gameLoop, 1000); function updateView() { $("#count").html(Math.round(game.clicks)); $("#cps").html((Math.round(game.cps * 10) / 10).toFixed(1)); $("#price0").html(game.upgradePrice[0]); $("#price1").html(game.upgradePrice[1]); $("#price2").html(game.upgradePrice[2]); $("#price3").html(game.upgradePrice[3]); $("#price4").html(game.upgradePrice[4]); $("#price5").html(game.upgradePrice[5]); $("#price6").html(game.upgradePrice[6]); $("#price7").html(game.upgradePrice[7]); $("#qty0").html(game.upgrades[0]); $("#qty1").html(game.upgrades[1]); $("#qty2").html(game.upgrades[2]); $("#qty3").html(game.upgrades[3]); $("#qty4").html(game.upgrades[4]); $("#qty5").html(game.upgrades[5]); $("#qty6").html(game.upgrades[6]); $("#qty7").html(game.upgrades[7]); } $(function() { $("#circle").click(function() { if(game.cps>4){ game.clicks += game.cps / 4; } else{ game.clicks += 1; } updateView(); }); }); function exportSave() { prompt('This is your save. Keep it.', btoa(JSON.stringify(game))); } function importSave() { game = JSON.parse(atob(prompt('Enter your save here. Your previous save will not be saved.'))); saveGame(); location.reload(); } function wipeSave() { if (confirm('Are you sure you would like to delete EVERYTHING?')) { clearInterval(gameLoopInterval); localStorage.save = ""; alert('Deleted.'); location.reload(); } else { alert('Cancelled.'); } }
Update main.js
js/main.js
Update main.js
<ide><path>s/main.js <ide> var gameLoopInterval = setInterval(gameLoop, 1000); <ide> <ide> function updateView() { <del> $("#count").html(Math.round(game.clicks)); <add> $("#count").html(Math.round(game.clicks).toLocaleString()); <ide> $("#cps").html((Math.round(game.cps * 10) / 10).toFixed(1)); <ide> $("#price0").html(game.upgradePrice[0]); <ide> $("#price1").html(game.upgradePrice[1]);
Java
apache-2.0
6f77c99b2da6301d252d8b6653c5416b2a2c0bf6
0
jdeppe-pivotal/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,smgoller/geode,smgoller/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,smgoller/geode,smgoller/geode,smgoller/geode,jdeppe-pivotal/geode,smgoller/geode,jdeppe-pivotal/geode,smgoller/geode,jdeppe-pivotal/geode
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode; import java.io.Serializable; import org.apache.logging.log4j.Logger; import org.junit.rules.ExternalResource; import org.junit.rules.RuleChain; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.testcontainers.containers.GenericContainer; import org.apache.geode.logging.internal.log4j.api.LogService; import org.apache.geode.test.junit.rules.IgnoreOnWindowsRule; public class NativeRedisTestRule extends ExternalResource implements Serializable { private static final Logger logger = LogService.getLogger(); private GenericContainer<?> redisContainer; private final RuleChain delegate; private final int PORT_TO_EXPOSE = 6379; private int max_clients = 10000; public NativeRedisTestRule() { delegate = RuleChain // Docker compose does not work on windows in CI. Ignore this test on windows // Using a RuleChain to make sure we ignore the test before the rule comes into play .outerRule(new IgnoreOnWindowsRule()); } public int getPort() { return redisContainer.getFirstMappedPort(); } public int getExposedPort() { return redisContainer.getExposedPorts().get(0); } public NativeRedisTestRule withMaxConnections(int max_connections) { this.max_clients = max_connections; return this; } @Override public Statement apply(Statement base, Description description) { Statement containerStatement = new Statement() { @Override public void evaluate() throws Throwable { redisContainer = new GenericContainer<>("redis:5.0.6") .withExposedPorts(PORT_TO_EXPOSE) .withCommand("redis-server --maxclients " + max_clients); redisContainer.start(); int mappedPort = getPort(); logger.info("Started redis container with exposed port {} -> {}", PORT_TO_EXPOSE, mappedPort); try { base.evaluate(); // This will run the test. } finally { redisContainer.stop(); logger.info("Stopped redis container with exposed port {} -> {}", PORT_TO_EXPOSE, mappedPort); } } }; return delegate.apply(containerStatement, description); } }
geode-apis-compatible-with-redis/src/commonTest/java/org/apache/geode/NativeRedisTestRule.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode; import java.io.Serializable; import org.apache.logging.log4j.Logger; import org.junit.rules.ExternalResource; import org.junit.rules.RuleChain; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.testcontainers.containers.GenericContainer; import org.apache.geode.logging.internal.log4j.api.LogService; import org.apache.geode.test.junit.rules.IgnoreOnWindowsRule; public class NativeRedisTestRule extends ExternalResource implements Serializable { private static final Logger logger = LogService.getLogger(); private GenericContainer<?> redisContainer; private final RuleChain delegate; private final int PORT_TO_EXPOSE = 6379; private int max_clients = 10000; public NativeRedisTestRule() { delegate = RuleChain // Docker compose does not work on windows in CI. Ignore this test on windows // Using a RuleChain to make sure we ignore the test before the rule comes into play .outerRule(new IgnoreOnWindowsRule()); } public int getPort() { return redisContainer.getFirstMappedPort(); } public int getExposedPort() { return redisContainer.getExposedPorts().get(0); } public NativeRedisTestRule withMaxConnections(int max_connections) { this.max_clients = max_connections; return this; } @Override public Statement apply(Statement base, Description description) { Statement containerStatement = new Statement() { @Override public void evaluate() throws Throwable { redisContainer = new GenericContainer<>("redis:5.0.6") .withExposedPorts(PORT_TO_EXPOSE) .withCommand("redis-server --maxclients " + max_clients); redisContainer.start(); logger.info("Started redis container with exposed port {} -> {}", PORT_TO_EXPOSE, getPort()); try { base.evaluate(); // This will run the test. } finally { redisContainer.stop(); } } }; return delegate.apply(containerStatement, description); } }
GEODE-9442: Add logging when Native Redis container is stopped (#6791) Authored-by: Donal Evans <[email protected]>
geode-apis-compatible-with-redis/src/commonTest/java/org/apache/geode/NativeRedisTestRule.java
GEODE-9442: Add logging when Native Redis container is stopped (#6791)
<ide><path>eode-apis-compatible-with-redis/src/commonTest/java/org/apache/geode/NativeRedisTestRule.java <ide> .withCommand("redis-server --maxclients " + max_clients); <ide> <ide> redisContainer.start(); <add> int mappedPort = getPort(); <ide> logger.info("Started redis container with exposed port {} -> {}", PORT_TO_EXPOSE, <del> getPort()); <add> mappedPort); <ide> try { <ide> base.evaluate(); // This will run the test. <ide> } finally { <ide> redisContainer.stop(); <add> logger.info("Stopped redis container with exposed port {} -> {}", PORT_TO_EXPOSE, <add> mappedPort); <ide> } <ide> } <ide> };
Java
lgpl-2.1
0a9be109b4b376808954569ba3cd19f36988a9a1
0
concord-consortium/sensor,concord-consortium/sensor
/** * */ package org.concord.sensor.state; import java.util.ArrayList; import java.util.Vector; import org.concord.framework.data.stream.DataListener; import org.concord.framework.data.stream.DataProducer; import org.concord.framework.data.stream.DataStreamDescription; import org.concord.framework.data.stream.DataStreamEvent; import org.concord.framework.startable.StartableInfo; import org.concord.framework.startable.StartableListener; import org.concord.framework.util.Copyable; import org.concord.sensor.ExperimentConfig; import org.concord.sensor.ExperimentRequest; import org.concord.sensor.SensorDataManager; import org.concord.sensor.SensorDataProducer; import org.concord.sensor.impl.DataStreamDescUtil; /** * @author scott * */ public class SensorDataProxy implements DataProducer, Copyable { private SensorDataManager sensorManager; private DataProducer producer = null; private SensorDataProducer sensorDataProducer = null; private ExperimentRequest experimentRequest = null; private boolean running = false; /** * This is a hack to make this refactoring simple. This should be refactored * again so this class doesn't depend on any OT stuff. */ private OTZeroSensor zeroSensor = null; private ArrayList<DataListener> dataListeners = new ArrayList<DataListener>(); private ArrayList<StartableListener> startableListeners = new ArrayList(); /** * should pass in resources.getRequest(); resources.getZeroSensor(); * * @param sdm * @param request */ public void setup(SensorDataManager sdm, ExperimentRequest request, OTZeroSensor zeroSensor) { sensorManager = sdm; experimentRequest = request; // keep a reference to this zero sensor object so it doesn't // get garbage collected before the button is pushed this.zeroSensor = zeroSensor; } public ExperimentRequest getExperimentRequest() { return experimentRequest; } public void setExperimentRequest(ExperimentRequest experimentRequest) { this.experimentRequest = experimentRequest; } public SensorDataManager getSensorManager() { return sensorManager; } public void setSensorManager(SensorDataManager sensorManager) { this.sensorManager = sensorManager; } public OTZeroSensor getZeroSensor() { return zeroSensor; } public void setZeroSensor(OTZeroSensor zeroSensor) { this.zeroSensor = zeroSensor; } /* * (non-Javadoc) * * @see org.concord.framework.data.stream.DataProducer#addDataListener(org.concord.framework.data.stream.DataListener) */ public void addDataListener(DataListener listener) { // people might add data listeners to us // before the real sensor data producer is ready // so we'll need to proxy these listeners // we can either proxy the list of listeners // or we can proxy the events themselves. // one issue might be the event source. Ifresources.getRequest() someone // is testing whether the source matches this object // then they will get screwed up unless we change // the source. if (!dataListeners.contains(listener)) { dataListeners.add(listener); } if (producer != null) { producer.addDataListener(listener); } } /* * (non-Javadoc) * * @see org.concord.framework.data.stream.DataProducer#removeDataListener(org.concord.framework.data.stream.DataListener) */ public void removeDataListener(DataListener listener) { dataListeners.remove(listener); if (producer != null) { producer.removeDataListener(listener); } } /* * (non-Javadoc) * * @see org.concord.framework.data.stream.DataProducer#getDataDescription() */ public DataStreamDescription getDataDescription() { if (producer == null) { DataStreamDescription dDesc = new DataStreamDescription(); DataStreamDescUtil.setupDescription(dDesc, experimentRequest, null); // this should return a partially correct description // before the real device is ready. some fields // will be missing or approximate: period, stepSize // series or sequence return dDesc; } return producer.getDataDescription(); } /* * (non-Javadoc) * * @see org.concord.framework.data.DataFlow#reset() */ public void reset() { if (producer != null) { producer.reset(); } running = false; } /* * (non-Javadoc) * * @see org.concord.framework.data.DataFlow#start() */ public void start() { // ask the devicemanager to configure the device with // our experimentrequest, once the producer from the // device is recieved we should start it and pass // connect up the currently attached data listeners // the datamanager should be careful so it doens't // start two requests at once. ExperimentRequest request = experimentRequest; if (sensorDataProducer != null && !sensorDataProducer.isAttached()){ sensorDataProducer.close(); sensorDataProducer = null; } if (sensorDataProducer == null) { sensorDataProducer = sensorManager.createDataProducer(); producer = sensorDataProducer; if (sensorDataProducer == null) { // we couldn't create the producer return; } for (int i = 0; i < dataListeners.size(); i++) { DataListener listener = (DataListener) dataListeners.get(i); DataStreamEvent changeEvent = new DataStreamEvent( DataStreamEvent.DATA_DESC_CHANGED); changeEvent.setDataDescription(getDataDescription()); listener.dataStreamEvent(changeEvent); producer.addDataListener(listener); } } ExperimentConfig config = sensorDataProducer.configure(request); if (config == null || !config.isValid()) { return; } if (zeroSensor != null) { // need to setup the taring datafilter and wrap it around the // producer DataProducer newProducer = zeroSensor .setupDataFilter(sensorDataProducer); if (producer != newProducer) { // need to transfer all the listeners from the old // producer to the new one for (int i = 0; i < dataListeners.size(); i++) { DataListener listener = (DataListener) dataListeners.get(i); producer.removeDataListener(listener); newProducer.addDataListener(listener); } producer = newProducer; } } producer.start(); running = true; } /* * (non-Javadoc) * * @see org.concord.framework.data.DataFlow#stop() */ public void stop() { // stop the proxied dataProducer // the dataProducer might be stopped already this // could happen if some other proxy started it. // FIXME we might a potential memory leak here unless // we clean up these listeners. if (producer != null) { producer.stop(); } running = false; } /* * (non-Javadoc) * * @see org.concord.framework.util.Copyable#getCopy() */ public Object getCopy() { SensorDataProxy copy = new SensorDataProxy(); copy.setup(sensorManager, experimentRequest, zeroSensor); // We might need to copy the name some how here. return copy; } public void close() { if (sensorDataProducer != null) { sensorDataProducer.close(); } } public boolean isRunning() { if(producer == null){ return false; } return producer.isRunning(); } public boolean isInInitialState() { if(producer == null){ return true; } return producer.isInInitialState(); } public void addStartableListener(StartableListener listener) { if (!startableListeners.contains(listener)) { startableListeners.add(listener); } if (producer != null) { producer.addStartableListener(listener); } } public void removeStartableListener(StartableListener listener) { startableListeners.remove(listener); if (producer != null) { producer.removeStartableListener(listener); } } public StartableInfo getStartableInfo() { if (producer == null) { return null; } return producer.getStartableInfo(); } }
src/org/concord/sensor/state/SensorDataProxy.java
/** * */ package org.concord.sensor.state; import java.util.ArrayList; import java.util.Vector; import org.concord.framework.data.stream.DataListener; import org.concord.framework.data.stream.DataProducer; import org.concord.framework.data.stream.DataStreamDescription; import org.concord.framework.data.stream.DataStreamEvent; import org.concord.framework.startable.StartableInfo; import org.concord.framework.startable.StartableListener; import org.concord.framework.util.Copyable; import org.concord.sensor.ExperimentConfig; import org.concord.sensor.ExperimentRequest; import org.concord.sensor.SensorDataManager; import org.concord.sensor.SensorDataProducer; import org.concord.sensor.impl.DataStreamDescUtil; /** * @author scott * */ public class SensorDataProxy implements DataProducer, Copyable { private SensorDataManager sensorManager; private DataProducer producer = null; private SensorDataProducer sensorDataProducer = null; private ExperimentRequest experimentRequest = null; private boolean running = false; /** * This is a hack to make this refactoring simple. This should be refactored * again so this class doesn't depend on any OT stuff. */ private OTZeroSensor zeroSensor = null; private ArrayList<DataListener> dataListeners = new ArrayList<DataListener>(); private ArrayList<StartableListener> startableListeners = new ArrayList(); /** * should pass in resources.getRequest(); resources.getZeroSensor(); * * @param sdm * @param request */ public void setup(SensorDataManager sdm, ExperimentRequest request, OTZeroSensor zeroSensor) { sensorManager = sdm; experimentRequest = request; // keep a reference to this zero sensor object so it doesn't // get garbage collected before the button is pushed this.zeroSensor = zeroSensor; } public ExperimentRequest getExperimentRequest() { return experimentRequest; } public void setExperimentRequest(ExperimentRequest experimentRequest) { this.experimentRequest = experimentRequest; } public SensorDataManager getSensorManager() { return sensorManager; } public void setSensorManager(SensorDataManager sensorManager) { this.sensorManager = sensorManager; } public OTZeroSensor getZeroSensor() { return zeroSensor; } public void setZeroSensor(OTZeroSensor zeroSensor) { this.zeroSensor = zeroSensor; } /* * (non-Javadoc) * * @see org.concord.framework.data.stream.DataProducer#addDataListener(org.concord.framework.data.stream.DataListener) */ public void addDataListener(DataListener listener) { // people might add data listeners to us // before the real sensor data producer is ready // so we'll need to proxy these listeners // we can either proxy the list of listeners // or we can proxy the events themselves. // one issue might be the event source. Ifresources.getRequest() someone // is testing whether the source matches this object // then they will get screwed up unless we change // the source. if (!dataListeners.contains(listener)) { dataListeners.add(listener); } if (producer != null) { producer.addDataListener(listener); } } /* * (non-Javadoc) * * @see org.concord.framework.data.stream.DataProducer#removeDataListener(org.concord.framework.data.stream.DataListener) */ public void removeDataListener(DataListener listener) { dataListeners.remove(listener); if (producer != null) { producer.removeDataListener(listener); } } /* * (non-Javadoc) * * @see org.concord.framework.data.stream.DataProducer#getDataDescription() */ public DataStreamDescription getDataDescription() { if (producer == null) { DataStreamDescription dDesc = new DataStreamDescription(); DataStreamDescUtil.setupDescription(dDesc, experimentRequest, null); // this should return a partially correct description // before the real device is ready. some fields // will be missing or approximate: period, stepSize // series or sequence return dDesc; } return producer.getDataDescription(); } /* * (non-Javadoc) * * @see org.concord.framework.data.DataFlow#reset() */ public void reset() { if (producer != null) { producer.reset(); } running = false; } /* * (non-Javadoc) * * @see org.concord.framework.data.DataFlow#start() */ public void start() { // ask the devicemanager to configure the device with // our experimentrequest, once the producer from the // device is recieved we should start it and pass // connect up the currently attached data listeners // the datamanager should be careful so it doens't // start two requests at once. ExperimentRequest request = experimentRequest; if (sensorDataProducer == null) { sensorDataProducer = sensorManager.createDataProducer(); producer = sensorDataProducer; if (sensorDataProducer == null) { // we couldn't create the producer return; } for (int i = 0; i < dataListeners.size(); i++) { DataListener listener = (DataListener) dataListeners.get(i); DataStreamEvent changeEvent = new DataStreamEvent( DataStreamEvent.DATA_DESC_CHANGED); changeEvent.setDataDescription(getDataDescription()); listener.dataStreamEvent(changeEvent); producer.addDataListener(listener); } } ExperimentConfig config = sensorDataProducer.configure(request); if (config == null || !config.isValid()) { return; } if (zeroSensor != null) { // need to setup the taring datafilter and wrap it around the // producer DataProducer newProducer = zeroSensor .setupDataFilter(sensorDataProducer); if (producer != newProducer) { // need to transfer all the listeners from the old // producer to the new one for (int i = 0; i < dataListeners.size(); i++) { DataListener listener = (DataListener) dataListeners.get(i); producer.removeDataListener(listener); newProducer.addDataListener(listener); } producer = newProducer; } } producer.start(); running = true; } /* * (non-Javadoc) * * @see org.concord.framework.data.DataFlow#stop() */ public void stop() { // stop the proxied dataProducer // the dataProducer might be stopped already this // could happen if some other proxy started it. // FIXME we might a potential memory leak here unless // we clean up these listeners. if (producer != null) { producer.stop(); } running = false; } /* * (non-Javadoc) * * @see org.concord.framework.util.Copyable#getCopy() */ public Object getCopy() { SensorDataProxy copy = new SensorDataProxy(); copy.setup(sensorManager, experimentRequest, zeroSensor); // We might need to copy the name some how here. return copy; } public void close() { if (sensorDataProducer != null) { sensorDataProducer.close(); } } public boolean isRunning() { if(producer == null){ return false; } return producer.isRunning(); } public boolean isInInitialState() { if(producer == null){ return true; } return producer.isInInitialState(); } public void addStartableListener(StartableListener listener) { if (!startableListeners.contains(listener)) { startableListeners.add(listener); } if (producer != null) { producer.addStartableListener(listener); } } public void removeStartableListener(StartableListener listener) { startableListeners.remove(listener); if (producer != null) { producer.removeStartableListener(listener); } } public StartableInfo getStartableInfo() { if (producer == null) { return null; } return producer.getStartableInfo(); } }
Improved scanning of devices when the current device is no longer attached. git-svn-id: 3690ca8e8b93aad95f5b520fc409c00b09b1d475@19483 6e01202a-0783-4428-890a-84243c50cc2b
src/org/concord/sensor/state/SensorDataProxy.java
Improved scanning of devices when the current device is no longer attached.
<ide><path>rc/org/concord/sensor/state/SensorDataProxy.java <ide> // start two requests at once. <ide> <ide> ExperimentRequest request = experimentRequest; <add> if (sensorDataProducer != null && !sensorDataProducer.isAttached()){ <add> sensorDataProducer.close(); <add> sensorDataProducer = null; <add> } <add> <ide> if (sensorDataProducer == null) { <ide> sensorDataProducer = sensorManager.createDataProducer(); <ide> producer = sensorDataProducer;
Java
lgpl-2.1
129198b4fd28ff6e7bfae55d2dd4dff42de68d03
0
KengoTODA/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,sewe/spotbugs,sewe/spotbugs,sewe/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs,KengoTODA/spotbugs
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2004-2005 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableSet; import java.io.File; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import edu.umd.cs.findbugs.ba.ClassHash; import edu.umd.cs.findbugs.filter.AndMatcher; import edu.umd.cs.findbugs.filter.BugMatcher; import edu.umd.cs.findbugs.filter.ClassMatcher; import edu.umd.cs.findbugs.filter.CompoundMatcher; import edu.umd.cs.findbugs.filter.DesignationMatcher; import edu.umd.cs.findbugs.filter.FieldMatcher; import edu.umd.cs.findbugs.filter.Filter; import edu.umd.cs.findbugs.filter.FirstVersionMatcher; import edu.umd.cs.findbugs.filter.LastVersionMatcher; import edu.umd.cs.findbugs.filter.LocalMatcher; import edu.umd.cs.findbugs.filter.Matcher; import edu.umd.cs.findbugs.filter.MethodMatcher; import edu.umd.cs.findbugs.filter.NotMatcher; import edu.umd.cs.findbugs.filter.OrMatcher; import edu.umd.cs.findbugs.filter.PriorityMatcher; import edu.umd.cs.findbugs.filter.RankMatcher; import edu.umd.cs.findbugs.model.ClassFeatureSet; import edu.umd.cs.findbugs.util.MapCache; import edu.umd.cs.findbugs.util.Strings; /** * Build a BugCollection based on SAX events. This is intended to replace the * old DOM-based parsing of XML bug result files, which was very slow. * * @author David Hovemeyer */ public class SAXBugCollectionHandler extends DefaultHandler { private static final String FIND_BUGS_FILTER = "FindBugsFilter"; private static final String PROJECT = "Project"; private static final String BUG_COLLECTION = "BugCollection"; private static final Logger LOGGER = Logger.getLogger(SAXBugCollectionHandler.class.getName()); /** * @param attributes * @param qName * @return */ public String getOptionalAttribute(Attributes attributes, String qName) { return memoized(attributes.getValue(qName)); } @CheckForNull private final BugCollection bugCollection; @CheckForNull private final Project project; private final Stack<CompoundMatcher> matcherStack = new Stack<CompoundMatcher>(); private Filter filter; private final MapCache<String, String> cache = new MapCache<String, String>(2000); private final ArrayList<String> elementStack; private final StringBuilder textBuffer; private BugInstance bugInstance; private BugAnnotationWithSourceLines bugAnnotationWithSourceLines; private AnalysisError analysisError; // private ClassHash classHash; private ClassFeatureSet classFeatureSet; private final ArrayList<String> stackTrace; private int nestingOfIgnoredElements = 0; private final @CheckForNull File base; private final String topLevelName; private String cloudPropertyKey; private SAXBugCollectionHandler(String topLevelName, @CheckForNull BugCollection bugCollection, @CheckForNull Project project, @CheckForNull File base) { this.topLevelName = topLevelName; this.bugCollection = bugCollection; this.project = project; this.elementStack = new ArrayList<String>(); this.textBuffer = new StringBuilder(); this.stackTrace = new ArrayList<String>(); this.base = base; } public SAXBugCollectionHandler(BugCollection bugCollection, @CheckForNull File base) { this(BUG_COLLECTION, bugCollection, bugCollection.getProject(), base); } public SAXBugCollectionHandler(BugCollection bugCollection) { this(BUG_COLLECTION, bugCollection, bugCollection.getProject(), null); } public SAXBugCollectionHandler(Project project, File base) { this(PROJECT, null, project, base); } public SAXBugCollectionHandler(Filter filter, File base) { this(FIND_BUGS_FILTER, null, null, base); this.filter = filter; pushCompoundMatcher(filter); } Pattern ignoredElement = Pattern.compile("Message|ShortMessage|LongMessage"); public boolean discardedElement(String qName) { return ignoredElement.matcher(qName).matches(); } public String getTextContents() { return memoized(Strings.unescapeXml(textBuffer.toString())); } private String memoized(String s) { if (s == null) return s; String result = cache.get(s); if (result != null) return result; cache.put(s, s); return s; } private static boolean DEBUG = false; @SuppressWarnings("hiding") @Override public void startElement(String uri, String name, String qName, Attributes attributes) throws SAXException { // URI should always be empty. // So, qName is the name of the element. if (discardedElement(qName)) { nestingOfIgnoredElements++; } else if (nestingOfIgnoredElements > 0) { // ignore it } else { // We should be parsing the outer BugCollection element. if (elementStack.isEmpty() && !qName.equals(topLevelName)) throw new SAXException("Invalid top-level element (expected " + topLevelName + ", saw " + qName + ")"); if (qName.equals(BUG_COLLECTION)) { BugCollection bugCollection = this.bugCollection; assert bugCollection != null; // Read and set the sequence number. String version = getOptionalAttribute(attributes, "version"); if (bugCollection instanceof SortedBugCollection) bugCollection.setAnalysisVersion(version); // Read and set the sequence number. String sequence = getOptionalAttribute(attributes, "sequence"); long seqval = parseLong(sequence, 0L); bugCollection.setSequenceNumber(seqval); // Read and set timestamp. String timestamp = getOptionalAttribute(attributes, "timestamp"); long tsval = parseLong(timestamp, -1L); bugCollection.setTimestamp(tsval); // Read and set timestamp. String analysisTimestamp = getOptionalAttribute(attributes, "analysisTimestamp"); if (analysisTimestamp != null) { bugCollection.setAnalysisTimestamp(parseLong(analysisTimestamp, -1L)); } String analysisVersion = getOptionalAttribute(attributes, "version"); if (analysisVersion != null) { bugCollection.setAnalysisVersion(analysisVersion); } // Set release name, if present. String releaseName = getOptionalAttribute(attributes, "release"); bugCollection.setReleaseName((releaseName != null) ? releaseName : ""); } else if (isTopLevelFilter(qName)) { if (project != null) { filter = new Filter(); project.setSuppressionFilter(filter); } matcherStack.clear(); pushCompoundMatcher(filter); } else if (qName.equals(PROJECT)) { Project project = this.project; assert project != null; // Project element String projectName = getOptionalAttribute(attributes, Project.PROJECTNAME_ATTRIBUTE_NAME); if (projectName != null) project.setProjectName(projectName); } else { String outerElement = elementStack.get(elementStack.size() - 1); if (outerElement.equals(BUG_COLLECTION)) { // Parsing a top-level element of the BugCollection if (qName.equals("BugInstance")) { // BugInstance element - get required type and priority // attributes String type = getRequiredAttribute(attributes, "type", qName); String priority = getRequiredAttribute(attributes, "priority", qName); try { int prio = Integer.parseInt(priority); bugInstance = new BugInstance(type, prio); } catch (NumberFormatException e) { throw new SAXException("BugInstance with invalid priority value \"" + priority + "\"", e); } String firstVersion = getOptionalAttribute(attributes, "first"); if (firstVersion != null) { bugInstance.setFirstVersion(Long.parseLong(firstVersion)); } String lastVersion = getOptionalAttribute(attributes, "last"); if (lastVersion != null) { bugInstance.setLastVersion(Long.parseLong(lastVersion)); } if (bugInstance.isDead() && bugInstance.getFirstVersion() > bugInstance.getLastVersion()) throw new IllegalStateException("huh"); String introducedByChange = getOptionalAttribute(attributes, "introducedByChange"); if (introducedByChange != null) { bugInstance.setIntroducedByChangeOfExistingClass(Boolean.parseBoolean(introducedByChange)); } String removedByChange = getOptionalAttribute(attributes, "removedByChange"); if (removedByChange != null) { bugInstance.setRemovedByChangeOfPersistingClass(Boolean.parseBoolean(removedByChange)); } String oldInstanceHash = getOptionalAttribute(attributes, "instanceHash"); if (oldInstanceHash == null) oldInstanceHash = getOptionalAttribute(attributes, "oldInstanceHash"); if (oldInstanceHash != null) { bugInstance.setOldInstanceHash(oldInstanceHash); } String firstSeen = getOptionalAttribute(attributes, "firstSeen"); if (firstSeen != null) { try { bugInstance.getXmlProps().setFirstSeen(BugInstance.firstSeenXMLFormat().parse(firstSeen)); } catch (ParseException e) { LOGGER.warning("Could not parse first seen entry: " + firstSeen); // ignore } } String isInCloud = getOptionalAttribute(attributes, "isInCloud"); if (isInCloud != null) bugInstance.getXmlProps().setIsInCloud(Boolean.parseBoolean(isInCloud)); String reviewCount = getOptionalAttribute(attributes, "reviews"); if (reviewCount != null) { bugInstance.getXmlProps().setReviewCount(Integer.parseInt(reviewCount)); } String consensus = getOptionalAttribute(attributes, "consensus"); if (consensus != null) { bugInstance.getXmlProps().setConsensus(consensus); } } else if (qName.equals("FindBugsSummary")) { BugCollection bugCollection = this.bugCollection; assert bugCollection != null; String timestamp = getRequiredAttribute(attributes, "timestamp", qName); String vmVersion = getOptionalAttribute(attributes, "vm_version"); String totalClasses = getOptionalAttribute(attributes, "total_classes"); if (totalClasses != null && totalClasses.length() > 0) bugCollection.getProjectStats().setTotalClasses(Integer.parseInt(totalClasses)); String totalSize = getOptionalAttribute(attributes, "total_size"); if (totalSize != null && totalSize.length() > 0) bugCollection.getProjectStats().setTotalSize(Integer.parseInt(totalSize)); String referencedClasses = getOptionalAttribute(attributes, "referenced_classes"); if (referencedClasses != null && referencedClasses.length() > 0) bugCollection.getProjectStats().setReferencedClasses(Integer.parseInt(referencedClasses)); bugCollection.getProjectStats().setVMVersion(vmVersion); try { bugCollection.getProjectStats().setTimestamp(timestamp); } catch (java.text.ParseException e) { throw new SAXException("Unparseable sequence number: '" + timestamp + "'", e); } } } else if (outerElement.equals("BugInstance")) { parseBugInstanceContents(qName, attributes); } else if (outerElement.equals("Method") || outerElement.equals("Field") || outerElement.equals("Class") || outerElement.equals("Type")) { if (qName.equals("SourceLine")) { // package member elements can contain nested SourceLine // elements. bugAnnotationWithSourceLines.setSourceLines(createSourceLineAnnotation(qName, attributes)); } } else if (outerElement.equals(BugCollection.ERRORS_ELEMENT_NAME)) { if (qName.equals(BugCollection.ANALYSIS_ERROR_ELEMENT_NAME) || qName.equals(BugCollection.ERROR_ELEMENT_NAME)) { analysisError = new AnalysisError("Unknown error"); stackTrace.clear(); } } else if (outerElement.equals("FindBugsSummary") && qName.equals("PackageStats")) { BugCollection bugCollection = this.bugCollection; assert bugCollection != null; String packageName = getRequiredAttribute(attributes, "package", qName); int numClasses = Integer.valueOf(getRequiredAttribute(attributes, "total_types", qName)); int size = Integer.valueOf(getRequiredAttribute(attributes, "total_size", qName)); bugCollection.getProjectStats().putPackageStats(packageName, numClasses, size); } else if (outerElement.equals("PackageStats")) { BugCollection bugCollection = this.bugCollection; assert bugCollection != null; if (qName.equals("ClassStats")) { String className = getRequiredAttribute(attributes, "class", qName); Boolean isInterface = Boolean.valueOf(getRequiredAttribute(attributes, "interface", qName)); int size = Integer.valueOf(getRequiredAttribute(attributes, "size", qName)); String sourceFile = getOptionalAttribute(attributes, "sourceFile"); bugCollection.getProjectStats().addClass(className, sourceFile, isInterface, size, false); } } else if (isTopLevelFilter(outerElement) || isCompoundElementTag(outerElement)) { parseMatcher(qName, attributes); } else if (outerElement.equals("ClassFeatures")) { if (qName.equals(ClassFeatureSet.ELEMENT_NAME)) { String className = getRequiredAttribute(attributes, "class", qName); classFeatureSet = new ClassFeatureSet(); classFeatureSet.setClassName(className); } } else if (outerElement.equals(ClassFeatureSet.ELEMENT_NAME)) { if (qName.equals(ClassFeatureSet.FEATURE_ELEMENT_NAME)) { String value = getRequiredAttribute(attributes, "value", qName); classFeatureSet.addFeature(value); } } else if (outerElement.equals(BugCollection.HISTORY_ELEMENT_NAME)) { if (qName.equals(AppVersion.ELEMENT_NAME)) { BugCollection bugCollection = this.bugCollection; assert bugCollection != null; try { String sequence = getRequiredAttribute(attributes, "sequence", qName); String timestamp = getOptionalAttribute(attributes, "timestamp"); String releaseName = getOptionalAttribute(attributes, "release"); String codeSize = getOptionalAttribute(attributes, "codeSize"); String numClasses = getOptionalAttribute(attributes, "numClasses"); AppVersion appVersion = new AppVersion(Long.valueOf(sequence)); if (timestamp != null) appVersion.setTimestamp(Long.valueOf(timestamp)); if (releaseName != null) appVersion.setReleaseName(releaseName); if (codeSize != null) appVersion.setCodeSize(Integer.parseInt(codeSize)); if (numClasses != null) appVersion.setNumClasses(Integer.parseInt(numClasses)); bugCollection.addAppVersion(appVersion); } catch (NumberFormatException e) { throw new SAXException("Invalid AppVersion element", e); } } } else if (outerElement.equals(BugCollection.PROJECT_ELEMENT_NAME)) { Project project = this.project; assert project != null; if (qName.equals(Project.CLOUD_ELEMENT_NAME)) { String cloudId = getRequiredAttribute(attributes, Project.CLOUD_ID_ATTRIBUTE_NAME, qName); project.setCloudId(cloudId); if(bugCollection != null){ Map<String,String> map = new HashMap<String, String>(); for (int i = 0; i < attributes.getLength(); i++) { map.put(attributes.getLocalName(i), attributes.getValue(i)); } bugCollection.setXmlCloudDetails(Collections.unmodifiableMap(map)); } } else if (qName.equals(Project.PLUGIN_ELEMENT_NAME)) { String pluginId = getRequiredAttribute(attributes, Project.PLUGIN_ID_ATTRIBUTE_NAME, qName); Boolean enabled = Boolean.valueOf(getRequiredAttribute(attributes, Project.PLUGIN_STATUS_ELEMENT_NAME, qName)); project.setPluginStatusTrinary(pluginId, enabled); } } else if (outerElement.equals(Project.CLOUD_ELEMENT_NAME)) { if (qName.equals(Project.CLOUD_PROPERTY_ELEMENT_NAME)) { cloudPropertyKey = getRequiredAttribute(attributes, "key", qName); } } } } textBuffer.delete(0, textBuffer.length()); elementStack.add(qName); } private boolean isCompoundElementTag(String qName) { return outerElementTags .contains(qName); } private boolean isTopLevelFilter(String qName) { return qName.equals(FIND_BUGS_FILTER) || qName.equals("SuppressionFilter"); } private void addMatcher(Matcher m) { if (m == null) throw new IllegalArgumentException("matcher must not be null"); CompoundMatcher peek = matcherStack.peek(); if (peek == null) throw new NullPointerException("Top of stack is null"); peek.addChild(m); if (nextMatchedIsDisabled) { if (peek instanceof Filter) ((Filter) peek).disable(m); else assert false; nextMatchedIsDisabled = false; } } private void pushCompoundMatcherAsChild(CompoundMatcher m) { addMatcher(m); pushCompoundMatcher(m); } private void pushCompoundMatcher(CompoundMatcher m) { if (m == null) throw new IllegalArgumentException("matcher must not be null"); matcherStack.push(m); } boolean nextMatchedIsDisabled; private final Set<String> outerElementTags = unmodifiableSet(new HashSet<String>(asList("And", "Match", "Or", "Not")));; private void parseMatcher(String qName, Attributes attributes) throws SAXException { if (DEBUG) System.out.println(elementStack + " " + qName + " " + matcherStack); String disabled = getOptionalAttribute(attributes, "disabled"); nextMatchedIsDisabled = "true".equals(disabled); if (qName.equals("Bug")) { addMatcher(new BugMatcher(getOptionalAttribute(attributes, "code"), getOptionalAttribute(attributes, "pattern"), getOptionalAttribute(attributes, "category"))); } else if (qName.equals("Class")) { addMatcher(new ClassMatcher(getRequiredAttribute(attributes, "name", qName))); } else if (qName.equals("FirstVersion")) { addMatcher(new FirstVersionMatcher(getRequiredAttribute(attributes, "value", qName), getRequiredAttribute(attributes, "relOp", qName))); } else if (qName.equals("LastVersion")) { addMatcher(new LastVersionMatcher(getRequiredAttribute(attributes, "value", qName), getRequiredAttribute(attributes, "relOp", qName))); } else if (qName.equals("Designation")) { addMatcher(new DesignationMatcher(getRequiredAttribute(attributes, "designation", qName))); } else if (qName.equals("BugCode")) { addMatcher(new BugMatcher(getRequiredAttribute(attributes, "name", qName), "", "")); } else if (qName.equals("Local")) { addMatcher(new LocalMatcher(getRequiredAttribute(attributes, "name", qName))); } else if (qName.equals("BugPattern")) { addMatcher(new BugMatcher("", getRequiredAttribute(attributes, "name", qName), "")); } else if (qName.equals("Priority") || qName.equals("Confidence")) { addMatcher(new PriorityMatcher(getRequiredAttribute(attributes, "value", qName))); } else if (qName.equals("Rank")) { addMatcher(new RankMatcher(getRequiredAttribute(attributes, "value", qName))); } else if (qName.equals("Package")) { String pName = getRequiredAttribute(attributes, "name", qName); pName = pName.startsWith("~") ? pName : "~" + pName.replace(".", "\\."); addMatcher(new ClassMatcher(pName + "\\.[^.]+")); } else if (qName.equals("Method")) { String name = getOptionalAttribute(attributes, "name"); String params = getOptionalAttribute(attributes, "params"); String returns = getOptionalAttribute(attributes, "returns"); String role = getOptionalAttribute(attributes, "role"); addMatcher(new MethodMatcher(name, params, returns, role)); } else if (qName.equals("Field")) { String name = getOptionalAttribute(attributes, "name"); String type = getOptionalAttribute(attributes, "type"); addMatcher(new FieldMatcher(name, type)); } else if (qName.equals("Or")) { CompoundMatcher matcher = new OrMatcher(); pushCompoundMatcherAsChild(matcher); } else if (qName.equals("And") || qName.equals("Match")) { AndMatcher matcher = new AndMatcher(); pushCompoundMatcherAsChild(matcher); if (qName.equals("Match")) { String classregex = getOptionalAttribute(attributes, "classregex"); String classMatch = getOptionalAttribute(attributes, "class"); if (classregex != null) addMatcher(new ClassMatcher("~" + classregex)); else if (classMatch != null) addMatcher(new ClassMatcher(classMatch)); } } else if(qName.equals("Not")) { NotMatcher matcher = new NotMatcher(); pushCompoundMatcherAsChild(matcher); } nextMatchedIsDisabled = false; } private void parseBugInstanceContents(String qName, Attributes attributes) throws SAXException { // Parsing an attribute or property of a BugInstance BugAnnotation bugAnnotation = null; if (qName.equals("Class")) { String className = getRequiredAttribute(attributes, "classname", qName); bugAnnotation = bugAnnotationWithSourceLines = new ClassAnnotation(className); } else if (qName.equals("Type")) { String typeDescriptor = getRequiredAttribute(attributes, "descriptor", qName); TypeAnnotation typeAnnotation; bugAnnotation = bugAnnotationWithSourceLines = typeAnnotation = new TypeAnnotation(typeDescriptor); String typeParameters = getOptionalAttribute(attributes, "typeParameters"); if (typeParameters != null) typeAnnotation.setTypeParameters(Strings.unescapeXml(typeParameters)); } else if (qName.equals("Method") || qName.equals("Field")) { String classname = getRequiredAttribute(attributes, "classname", qName); String fieldOrMethodName = getRequiredAttribute(attributes, "name", qName); String signature = getRequiredAttribute(attributes, "signature", qName); if (qName.equals("Method")) { String isStatic = getOptionalAttribute(attributes, "isStatic"); if (isStatic == null) { isStatic = "false"; // Hack for old data } bugAnnotation = bugAnnotationWithSourceLines = new MethodAnnotation(classname, fieldOrMethodName, signature, Boolean.valueOf(isStatic)); } else { String isStatic = getRequiredAttribute(attributes, "isStatic", qName); bugAnnotation = bugAnnotationWithSourceLines = new FieldAnnotation(classname, fieldOrMethodName, signature, Boolean.valueOf(isStatic)); } } else if (qName.equals("SourceLine")) { SourceLineAnnotation sourceAnnotation = createSourceLineAnnotation(qName, attributes); if (!sourceAnnotation.isSynthetic()) bugAnnotation = sourceAnnotation; } else if (qName.equals("Int")) { try { String value = getRequiredAttribute(attributes, "value", qName); bugAnnotation = new IntAnnotation(Integer.parseInt(value)); } catch (NumberFormatException e) { throw new SAXException("Bad integer value in Int"); } } else if (qName.equals("String")) { String value = getRequiredAttribute(attributes, "value", qName); bugAnnotation = StringAnnotation.fromXMLEscapedString(value); } else if (qName.equals("LocalVariable")) { try { String varName = getRequiredAttribute(attributes, "name", qName); int register = Integer.parseInt(getRequiredAttribute(attributes, "register", qName)); int pc = Integer.parseInt(getRequiredAttribute(attributes, "pc", qName)); bugAnnotation = new LocalVariableAnnotation(varName, register, pc); } catch (NumberFormatException e) { throw new SAXException("Invalid integer value in attribute of LocalVariable element"); } } else if (qName.equals("Property")) { // A BugProperty. String propName = getRequiredAttribute(attributes, "name", qName); String propValue = getRequiredAttribute(attributes, "value", qName); bugInstance.setProperty(propName, propValue); } else if (qName.equals("UserAnnotation")) { // ignore AnnotationText for now; will handle in endElement String s = getOptionalAttribute(attributes, "designation"); // optional if (s != null) { bugInstance.setUserDesignationKey(s, null); } s = getOptionalAttribute(attributes, "user"); // optional if (s != null) bugInstance.setUser(s); s = getOptionalAttribute(attributes, "timestamp"); // optional if (s != null) try { long timestamp = Long.valueOf(s); bugInstance.setUserAnnotationTimestamp(timestamp); } catch (NumberFormatException nfe) { // ok to contine -- just won't set a timestamp for the user // designation. // but is there anyplace to report this? } s = getOptionalAttribute(attributes, "needsSync"); // optional if (s == null || s.equals("false")) bugInstance.setUserAnnotationDirty(false); } else throw new SAXException("Unknown bug annotation named " + qName); if (bugAnnotation != null) { String role = getOptionalAttribute(attributes, "role"); if (role != null) bugAnnotation.setDescription(role); setAnnotationRole(attributes, bugAnnotation); bugInstance.add(bugAnnotation); } } private long parseLong(String s, long defaultValue) { long value; try { value = (s != null) ? Long.parseLong(s) : defaultValue; } catch (NumberFormatException e) { value = defaultValue; } return value; } /** * Extract a hash value from an element. * * @param qName * name of element containing hash value * @param attributes * element attributes * @return the decoded hash value * @throws SAXException */ private byte[] extractHash(String qName, Attributes attributes) throws SAXException { String encodedHash = getRequiredAttribute(attributes, "value", qName); byte[] hash; try { // System.out.println("Extract hash " + encodedHash); hash = ClassHash.stringToHash(encodedHash); } catch (IllegalArgumentException e) { throw new SAXException("Invalid class hash", e); } return hash; } private void setAnnotationRole(Attributes attributes, BugAnnotation bugAnnotation) { String role = getOptionalAttribute(attributes, "role"); if (role != null) bugAnnotation.setDescription(role); } private SourceLineAnnotation createSourceLineAnnotation(String qName, Attributes attributes) throws SAXException { String classname = getRequiredAttribute(attributes, "classname", qName); String sourceFile = getOptionalAttribute(attributes, "sourcefile"); if (sourceFile == null) sourceFile = SourceLineAnnotation.UNKNOWN_SOURCE_FILE; String startLine = getOptionalAttribute(attributes, "start"); // "start"/"end" // are now // optional String endLine = getOptionalAttribute(attributes, "end"); // (were too // many "-1"s // in the xml) String startBytecode = getOptionalAttribute(attributes, "startBytecode"); String endBytecode = getOptionalAttribute(attributes, "endBytecode"); String synthetic = getOptionalAttribute(attributes, "synthetic"); try { int sl = startLine != null ? Integer.parseInt(startLine) : -1; int el = endLine != null ? Integer.parseInt(endLine) : -1; int sb = startBytecode != null ? Integer.parseInt(startBytecode) : -1; int eb = endBytecode != null ? Integer.parseInt(endBytecode) : -1; SourceLineAnnotation s = new SourceLineAnnotation(classname, sourceFile, sl, el, sb, eb); if ("true".equals(synthetic)) s.setSynthetic(true); return s; } catch (NumberFormatException e) { throw new SAXException("Bad integer value in SourceLine element", e); } } @SuppressWarnings("hiding") @Override public void endElement(String uri, String name, String qName) throws SAXException { // URI should always be empty. // So, qName is the name of the element. if (discardedElement(qName)) { nestingOfIgnoredElements--; } else if (nestingOfIgnoredElements > 0) { // ignore it } else if (qName.equals("Project")) { // noop } else if (elementStack.size() > 1) { String outerElement = elementStack.get(elementStack.size() - 2); if (isTopLevelFilter(qName) || isCompoundElementTag(qName)) { if (DEBUG) System.out.println(" ending " + elementStack + " " + qName + " " + matcherStack); matcherStack.pop(); } else if (outerElement.equals(BUG_COLLECTION)) { BugCollection bugCollection = this.bugCollection; assert bugCollection != null; if (qName.equals("BugInstance")) { bugCollection.add(bugInstance, false); } } else if (outerElement.equals(PROJECT)) { Project project = this.project; assert project != null; if (qName.equals("Jar")) project.addFile(makeAbsolute(getTextContents())); else if (qName.equals("SrcDir")) project.addSourceDir(makeAbsolute(getTextContents())); else if (qName.equals("AuxClasspathEntry")) project.addAuxClasspathEntry(makeAbsolute(getTextContents())); } else if (outerElement.equals(Project.CLOUD_ELEMENT_NAME) && qName.equals(Project.CLOUD_PROPERTY_ELEMENT_NAME)) { Project project = this.project; assert project != null; assert cloudPropertyKey != null; project.getCloudProperties().setProperty(cloudPropertyKey, getTextContents()); cloudPropertyKey = null; } else if (outerElement.equals("BugInstance")) { if (qName.equals("UserAnnotation")) { bugInstance.setAnnotationText(getTextContents(), null); } } else if (outerElement.equals(BugCollection.ERRORS_ELEMENT_NAME)) { BugCollection bugCollection = this.bugCollection; assert bugCollection != null; if (qName.equals(BugCollection.ANALYSIS_ERROR_ELEMENT_NAME)) { analysisError.setMessage(getTextContents()); bugCollection.addError(analysisError); } else if (qName.equals(BugCollection.ERROR_ELEMENT_NAME)) { if (stackTrace.size() > 0) { analysisError.setStackTrace(stackTrace.toArray(new String[stackTrace.size()])); } bugCollection.addError(analysisError); } else if (qName.equals(BugCollection.MISSING_CLASS_ELEMENT_NAME)) { bugCollection.addMissingClass(getTextContents()); } } else if (outerElement.equals(BugCollection.ERROR_ELEMENT_NAME)) { if (qName.equals(BugCollection.ERROR_MESSAGE_ELEMENT_NAME)) { analysisError.setMessage(getTextContents()); } else if (qName.equals(BugCollection.ERROR_EXCEPTION_ELEMENT_NAME)) { analysisError.setExceptionMessage(getTextContents()); } else if (qName.equals(BugCollection.ERROR_STACK_TRACE_ELEMENT_NAME)) { stackTrace.add(getTextContents()); } } else if (outerElement.equals("ClassFeatures")) { if (qName.equals(ClassFeatureSet.ELEMENT_NAME)) { BugCollection bugCollection = this.bugCollection; assert bugCollection != null; bugCollection.setClassFeatureSet(classFeatureSet); classFeatureSet = null; } } } elementStack.remove(elementStack.size() - 1); } private String makeAbsolute(String possiblyRelativePath) { if (possiblyRelativePath.contains("://") || possiblyRelativePath.startsWith("http:") || possiblyRelativePath.startsWith("https:") || possiblyRelativePath.startsWith("file:")) return possiblyRelativePath; if (base == null) return possiblyRelativePath; if (new File(possiblyRelativePath).isAbsolute()) return possiblyRelativePath; return new File(base.getParentFile(), possiblyRelativePath).getAbsolutePath(); } @Override public void characters(char[] ch, int start, int length) { textBuffer.append(ch, start, length); } private String getRequiredAttribute(Attributes attributes, String attrName, String elementName) throws SAXException { String value = attributes.getValue(attrName); if (value == null) throw new SAXException(elementName + " element missing " + attrName + " attribute"); return memoized(Strings.unescapeXml(value)); } } // vim:ts=4
findbugs/src/java/edu/umd/cs/findbugs/SAXBugCollectionHandler.java
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2004-2005 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableSet; import java.io.File; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import edu.umd.cs.findbugs.ba.ClassHash; import edu.umd.cs.findbugs.filter.AndMatcher; import edu.umd.cs.findbugs.filter.BugMatcher; import edu.umd.cs.findbugs.filter.ClassMatcher; import edu.umd.cs.findbugs.filter.CompoundMatcher; import edu.umd.cs.findbugs.filter.DesignationMatcher; import edu.umd.cs.findbugs.filter.FieldMatcher; import edu.umd.cs.findbugs.filter.Filter; import edu.umd.cs.findbugs.filter.FirstVersionMatcher; import edu.umd.cs.findbugs.filter.LastVersionMatcher; import edu.umd.cs.findbugs.filter.LocalMatcher; import edu.umd.cs.findbugs.filter.Matcher; import edu.umd.cs.findbugs.filter.MethodMatcher; import edu.umd.cs.findbugs.filter.NotMatcher; import edu.umd.cs.findbugs.filter.OrMatcher; import edu.umd.cs.findbugs.filter.PriorityMatcher; import edu.umd.cs.findbugs.filter.RankMatcher; import edu.umd.cs.findbugs.model.ClassFeatureSet; import edu.umd.cs.findbugs.util.MapCache; import edu.umd.cs.findbugs.util.Strings; /** * Build a BugCollection based on SAX events. This is intended to replace the * old DOM-based parsing of XML bug result files, which was very slow. * * @author David Hovemeyer */ public class SAXBugCollectionHandler extends DefaultHandler { private static final String FIND_BUGS_FILTER = "FindBugsFilter"; private static final String PROJECT = "Project"; private static final String BUG_COLLECTION = "BugCollection"; private static final Logger LOGGER = Logger.getLogger(SAXBugCollectionHandler.class.getName()); /** * @param attributes * @param qName * @return */ public String getOptionalAttribute(Attributes attributes, String qName) { return memoized(attributes.getValue(qName)); } @CheckForNull private final BugCollection bugCollection; @CheckForNull private final Project project; private final Stack<CompoundMatcher> matcherStack = new Stack<CompoundMatcher>(); private Filter filter; private final MapCache<String, String> cache = new MapCache<String, String>(2000); private final ArrayList<String> elementStack; private final StringBuilder textBuffer; private BugInstance bugInstance; private BugAnnotationWithSourceLines bugAnnotationWithSourceLines; private AnalysisError analysisError; // private ClassHash classHash; private ClassFeatureSet classFeatureSet; private final ArrayList<String> stackTrace; private int nestingOfIgnoredElements = 0; private final @CheckForNull File base; private final String topLevelName; private String cloudPropertyKey; private SAXBugCollectionHandler(String topLevelName, @CheckForNull BugCollection bugCollection, @CheckForNull Project project, @CheckForNull File base) { this.topLevelName = topLevelName; this.bugCollection = bugCollection; this.project = project; this.elementStack = new ArrayList<String>(); this.textBuffer = new StringBuilder(); this.stackTrace = new ArrayList<String>(); this.base = base; } public SAXBugCollectionHandler(BugCollection bugCollection, @CheckForNull File base) { this(BUG_COLLECTION, bugCollection, bugCollection.getProject(), base); } public SAXBugCollectionHandler(BugCollection bugCollection) { this(BUG_COLLECTION, bugCollection, bugCollection.getProject(), null); } public SAXBugCollectionHandler(Project project, File base) { this(PROJECT, null, project, base); } public SAXBugCollectionHandler(Filter filter, File base) { this(FIND_BUGS_FILTER, null, null, base); this.filter = filter; pushCompoundMatcher(filter); } Pattern ignoredElement = Pattern.compile("Message|ShortMessage|LongMessage"); public boolean discardedElement(String qName) { return ignoredElement.matcher(qName).matches(); } public String getTextContents() { return memoized(Strings.unescapeXml(textBuffer.toString())); } private String memoized(String s) { if (s == null) return s; String result = cache.get(s); if (result != null) return result; cache.put(s, s); return s; } private static boolean DEBUG = false; @Override public void startElement(String uri, String name, String qName, Attributes attributes) throws SAXException { // URI should always be empty. // So, qName is the name of the element. if (discardedElement(qName)) { nestingOfIgnoredElements++; } else if (nestingOfIgnoredElements > 0) { // ignore it } else { // We should be parsing the outer BugCollection element. if (elementStack.isEmpty() && !qName.equals(topLevelName)) throw new SAXException("Invalid top-level element (expected " + topLevelName + ", saw " + qName + ")"); if (qName.equals(BUG_COLLECTION)) { // Read and set the sequence number. String version = getOptionalAttribute(attributes, "version"); if (bugCollection instanceof SortedBugCollection) bugCollection.setAnalysisVersion(version); // Read and set the sequence number. String sequence = getOptionalAttribute(attributes, "sequence"); long seqval = parseLong(sequence, 0L); bugCollection.setSequenceNumber(seqval); // Read and set timestamp. String timestamp = getOptionalAttribute(attributes, "timestamp"); long tsval = parseLong(timestamp, -1L); bugCollection.setTimestamp(tsval); // Read and set timestamp. String analysisTimestamp = getOptionalAttribute(attributes, "analysisTimestamp"); if (analysisTimestamp != null) { bugCollection.setAnalysisTimestamp(parseLong(analysisTimestamp, -1L)); } String analysisVersion = getOptionalAttribute(attributes, "version"); if (analysisVersion != null) { bugCollection.setAnalysisVersion(analysisVersion); } // Set release name, if present. String releaseName = getOptionalAttribute(attributes, "release"); bugCollection.setReleaseName((releaseName != null) ? releaseName : ""); } else if (isTopLevelFilter(qName)) { if (project != null) { filter = new Filter(); project.setSuppressionFilter(filter); } matcherStack.clear(); pushCompoundMatcher(filter); } else if (qName.equals(PROJECT)) { // Project element String projectName = getOptionalAttribute(attributes, Project.PROJECTNAME_ATTRIBUTE_NAME); if (projectName != null) project.setProjectName(projectName); } else { String outerElement = elementStack.get(elementStack.size() - 1); if (outerElement.equals(BUG_COLLECTION)) { // Parsing a top-level element of the BugCollection if (qName.equals("BugInstance")) { // BugInstance element - get required type and priority // attributes String type = getRequiredAttribute(attributes, "type", qName); String priority = getRequiredAttribute(attributes, "priority", qName); try { int prio = Integer.parseInt(priority); bugInstance = new BugInstance(type, prio); } catch (NumberFormatException e) { throw new SAXException("BugInstance with invalid priority value \"" + priority + "\"", e); } String firstVersion = getOptionalAttribute(attributes, "first"); if (firstVersion != null) { bugInstance.setFirstVersion(Long.parseLong(firstVersion)); } String lastVersion = getOptionalAttribute(attributes, "last"); if (lastVersion != null) { bugInstance.setLastVersion(Long.parseLong(lastVersion)); } if (bugInstance.isDead() && bugInstance.getFirstVersion() > bugInstance.getLastVersion()) throw new IllegalStateException("huh"); String introducedByChange = getOptionalAttribute(attributes, "introducedByChange"); if (introducedByChange != null) { bugInstance.setIntroducedByChangeOfExistingClass(Boolean.parseBoolean(introducedByChange)); } String removedByChange = getOptionalAttribute(attributes, "removedByChange"); if (removedByChange != null) { bugInstance.setRemovedByChangeOfPersistingClass(Boolean.parseBoolean(removedByChange)); } String oldInstanceHash = getOptionalAttribute(attributes, "instanceHash"); if (oldInstanceHash == null) oldInstanceHash = getOptionalAttribute(attributes, "oldInstanceHash"); if (oldInstanceHash != null) { bugInstance.setOldInstanceHash(oldInstanceHash); } String firstSeen = getOptionalAttribute(attributes, "firstSeen"); if (firstSeen != null) { try { bugInstance.getXmlProps().setFirstSeen(BugInstance.firstSeenXMLFormat().parse(firstSeen)); } catch (ParseException e) { LOGGER.warning("Could not parse first seen entry: " + firstSeen); // ignore } } String isInCloud = getOptionalAttribute(attributes, "isInCloud"); if (isInCloud != null) bugInstance.getXmlProps().setIsInCloud(Boolean.parseBoolean(isInCloud)); String reviewCount = getOptionalAttribute(attributes, "reviews"); if (reviewCount != null) { bugInstance.getXmlProps().setReviewCount(Integer.parseInt(reviewCount)); } String consensus = getOptionalAttribute(attributes, "consensus"); if (consensus != null) { bugInstance.getXmlProps().setConsensus(consensus); } } else if (qName.equals("FindBugsSummary")) { String timestamp = getRequiredAttribute(attributes, "timestamp", qName); String vmVersion = getOptionalAttribute(attributes, "vm_version"); String totalClasses = getOptionalAttribute(attributes, "total_classes"); if (totalClasses != null && totalClasses.length() > 0) bugCollection.getProjectStats().setTotalClasses(Integer.parseInt(totalClasses)); String totalSize = getOptionalAttribute(attributes, "total_size"); if (totalSize != null && totalSize.length() > 0) bugCollection.getProjectStats().setTotalSize(Integer.parseInt(totalSize)); String referencedClasses = getOptionalAttribute(attributes, "referenced_classes"); if (referencedClasses != null && referencedClasses.length() > 0) bugCollection.getProjectStats().setReferencedClasses(Integer.parseInt(referencedClasses)); bugCollection.getProjectStats().setVMVersion(vmVersion); try { bugCollection.getProjectStats().setTimestamp(timestamp); } catch (java.text.ParseException e) { throw new SAXException("Unparseable sequence number: '" + timestamp + "'", e); } } } else if (outerElement.equals("BugInstance")) { parseBugInstanceContents(qName, attributes); } else if (outerElement.equals("Method") || outerElement.equals("Field") || outerElement.equals("Class") || outerElement.equals("Type")) { if (qName.equals("SourceLine")) { // package member elements can contain nested SourceLine // elements. bugAnnotationWithSourceLines.setSourceLines(createSourceLineAnnotation(qName, attributes)); } } else if (outerElement.equals(BugCollection.ERRORS_ELEMENT_NAME)) { if (qName.equals(BugCollection.ANALYSIS_ERROR_ELEMENT_NAME) || qName.equals(BugCollection.ERROR_ELEMENT_NAME)) { analysisError = new AnalysisError("Unknown error"); stackTrace.clear(); } } else if (outerElement.equals("FindBugsSummary") && qName.equals("PackageStats")) { String packageName = getRequiredAttribute(attributes, "package", qName); int numClasses = Integer.valueOf(getRequiredAttribute(attributes, "total_types", qName)); int size = Integer.valueOf(getRequiredAttribute(attributes, "total_size", qName)); bugCollection.getProjectStats().putPackageStats(packageName, numClasses, size); } else if (outerElement.equals("PackageStats")) { if (qName.equals("ClassStats")) { String className = getRequiredAttribute(attributes, "class", qName); Boolean isInterface = Boolean.valueOf(getRequiredAttribute(attributes, "interface", qName)); int size = Integer.valueOf(getRequiredAttribute(attributes, "size", qName)); String sourceFile = getOptionalAttribute(attributes, "sourceFile"); bugCollection.getProjectStats().addClass(className, sourceFile, isInterface, size, false); } } else if (isTopLevelFilter(outerElement) || isCompoundElementTag(outerElement)) { parseMatcher(qName, attributes); } else if (outerElement.equals("ClassFeatures")) { if (qName.equals(ClassFeatureSet.ELEMENT_NAME)) { String className = getRequiredAttribute(attributes, "class", qName); classFeatureSet = new ClassFeatureSet(); classFeatureSet.setClassName(className); } } else if (outerElement.equals(ClassFeatureSet.ELEMENT_NAME)) { if (qName.equals(ClassFeatureSet.FEATURE_ELEMENT_NAME)) { String value = getRequiredAttribute(attributes, "value", qName); classFeatureSet.addFeature(value); } } else if (outerElement.equals(BugCollection.HISTORY_ELEMENT_NAME)) { if (qName.equals(AppVersion.ELEMENT_NAME)) { try { String sequence = getRequiredAttribute(attributes, "sequence", qName); String timestamp = getOptionalAttribute(attributes, "timestamp"); String releaseName = getOptionalAttribute(attributes, "release"); String codeSize = getOptionalAttribute(attributes, "codeSize"); String numClasses = getOptionalAttribute(attributes, "numClasses"); AppVersion appVersion = new AppVersion(Long.valueOf(sequence)); if (timestamp != null) appVersion.setTimestamp(Long.valueOf(timestamp)); if (releaseName != null) appVersion.setReleaseName(releaseName); if (codeSize != null) appVersion.setCodeSize(Integer.parseInt(codeSize)); if (numClasses != null) appVersion.setNumClasses(Integer.parseInt(numClasses)); bugCollection.addAppVersion(appVersion); } catch (NumberFormatException e) { throw new SAXException("Invalid AppVersion element", e); } } } else if (outerElement.equals(BugCollection.PROJECT_ELEMENT_NAME)) { if (qName.equals(Project.CLOUD_ELEMENT_NAME)) { String cloudId = getRequiredAttribute(attributes, Project.CLOUD_ID_ATTRIBUTE_NAME, qName); project.setCloudId(cloudId); if(bugCollection != null){ Map<String,String> map = new HashMap<String, String>(); for (int i = 0; i < attributes.getLength(); i++) { map.put(attributes.getLocalName(i), attributes.getValue(i)); } bugCollection.setXmlCloudDetails(Collections.unmodifiableMap(map)); } } else if (qName.equals(Project.PLUGIN_ELEMENT_NAME)) { String pluginId = getRequiredAttribute(attributes, Project.PLUGIN_ID_ATTRIBUTE_NAME, qName); Boolean enabled = Boolean.valueOf(getRequiredAttribute(attributes, Project.PLUGIN_STATUS_ELEMENT_NAME, qName)); project.setPluginStatusTrinary(pluginId, enabled); } } else if (outerElement.equals(Project.CLOUD_ELEMENT_NAME)) { if (qName.equals(Project.CLOUD_PROPERTY_ELEMENT_NAME)) { cloudPropertyKey = getRequiredAttribute(attributes, "key", qName); } } } } textBuffer.delete(0, textBuffer.length()); elementStack.add(qName); } private boolean isCompoundElementTag(String qName) { return outerElementTags .contains(qName); } private boolean isTopLevelFilter(String qName) { return qName.equals(FIND_BUGS_FILTER) || qName.equals("SuppressionFilter"); } private void addMatcher(Matcher m) { if (m == null) throw new IllegalArgumentException("matcher must not be null"); CompoundMatcher peek = matcherStack.peek(); if (peek == null) throw new NullPointerException("Top of stack is null"); peek.addChild(m); if (nextMatchedIsDisabled) { if (peek instanceof Filter) ((Filter) peek).disable(m); else assert false; nextMatchedIsDisabled = false; } } private void pushCompoundMatcherAsChild(CompoundMatcher m) { addMatcher(m); pushCompoundMatcher(m); } private void pushCompoundMatcher(CompoundMatcher m) { if (m == null) throw new IllegalArgumentException("matcher must not be null"); matcherStack.push(m); } boolean nextMatchedIsDisabled; private final Set<String> outerElementTags = unmodifiableSet(new HashSet<String>(asList("And", "Match", "Or", "Not")));; private void parseMatcher(String qName, Attributes attributes) throws SAXException { if (DEBUG) System.out.println(elementStack + " " + qName + " " + matcherStack); String disabled = getOptionalAttribute(attributes, "disabled"); nextMatchedIsDisabled = "true".equals(disabled); if (qName.equals("Bug")) { addMatcher(new BugMatcher(getOptionalAttribute(attributes, "code"), getOptionalAttribute(attributes, "pattern"), getOptionalAttribute(attributes, "category"))); } else if (qName.equals("Class")) { addMatcher(new ClassMatcher(getRequiredAttribute(attributes, "name", qName))); } else if (qName.equals("FirstVersion")) { addMatcher(new FirstVersionMatcher(getRequiredAttribute(attributes, "value", qName), getRequiredAttribute(attributes, "relOp", qName))); } else if (qName.equals("LastVersion")) { addMatcher(new LastVersionMatcher(getRequiredAttribute(attributes, "value", qName), getRequiredAttribute(attributes, "relOp", qName))); } else if (qName.equals("Designation")) { addMatcher(new DesignationMatcher(getRequiredAttribute(attributes, "designation", qName))); } else if (qName.equals("BugCode")) { addMatcher(new BugMatcher(getRequiredAttribute(attributes, "name", qName), "", "")); } else if (qName.equals("Local")) { addMatcher(new LocalMatcher(getRequiredAttribute(attributes, "name", qName))); } else if (qName.equals("BugPattern")) { addMatcher(new BugMatcher("", getRequiredAttribute(attributes, "name", qName), "")); } else if (qName.equals("Priority") || qName.equals("Confidence")) { addMatcher(new PriorityMatcher(getRequiredAttribute(attributes, "value", qName))); } else if (qName.equals("Rank")) { addMatcher(new RankMatcher(getRequiredAttribute(attributes, "value", qName))); } else if (qName.equals("Package")) { String pName = getRequiredAttribute(attributes, "name", qName); pName = pName.startsWith("~") ? pName : "~" + pName.replace(".", "\\."); addMatcher(new ClassMatcher(pName + "\\.[^.]+")); } else if (qName.equals("Method")) { String name = getOptionalAttribute(attributes, "name"); String params = getOptionalAttribute(attributes, "params"); String returns = getOptionalAttribute(attributes, "returns"); String role = getOptionalAttribute(attributes, "role"); addMatcher(new MethodMatcher(name, params, returns, role)); } else if (qName.equals("Field")) { String name = getOptionalAttribute(attributes, "name"); String type = getOptionalAttribute(attributes, "type"); addMatcher(new FieldMatcher(name, type)); } else if (qName.equals("Or")) { CompoundMatcher matcher = new OrMatcher(); pushCompoundMatcherAsChild(matcher); } else if (qName.equals("And") || qName.equals("Match")) { AndMatcher matcher = new AndMatcher(); pushCompoundMatcherAsChild(matcher); if (qName.equals("Match")) { String classregex = getOptionalAttribute(attributes, "classregex"); String classMatch = getOptionalAttribute(attributes, "class"); if (classregex != null) addMatcher(new ClassMatcher("~" + classregex)); else if (classMatch != null) addMatcher(new ClassMatcher(classMatch)); } } else if(qName.equals("Not")) { NotMatcher matcher = new NotMatcher(); pushCompoundMatcherAsChild(matcher); } nextMatchedIsDisabled = false; } private void parseBugInstanceContents(String qName, Attributes attributes) throws SAXException { // Parsing an attribute or property of a BugInstance BugAnnotation bugAnnotation = null; if (qName.equals("Class")) { String className = getRequiredAttribute(attributes, "classname", qName); bugAnnotation = bugAnnotationWithSourceLines = new ClassAnnotation(className); } else if (qName.equals("Type")) { String typeDescriptor = getRequiredAttribute(attributes, "descriptor", qName); TypeAnnotation typeAnnotation; bugAnnotation = bugAnnotationWithSourceLines = typeAnnotation = new TypeAnnotation(typeDescriptor); String typeParameters = getOptionalAttribute(attributes, "typeParameters"); if (typeParameters != null) typeAnnotation.setTypeParameters(Strings.unescapeXml(typeParameters)); } else if (qName.equals("Method") || qName.equals("Field")) { String classname = getRequiredAttribute(attributes, "classname", qName); String fieldOrMethodName = getRequiredAttribute(attributes, "name", qName); String signature = getRequiredAttribute(attributes, "signature", qName); if (qName.equals("Method")) { String isStatic = getOptionalAttribute(attributes, "isStatic"); if (isStatic == null) { isStatic = "false"; // Hack for old data } bugAnnotation = bugAnnotationWithSourceLines = new MethodAnnotation(classname, fieldOrMethodName, signature, Boolean.valueOf(isStatic)); } else { String isStatic = getRequiredAttribute(attributes, "isStatic", qName); bugAnnotation = bugAnnotationWithSourceLines = new FieldAnnotation(classname, fieldOrMethodName, signature, Boolean.valueOf(isStatic)); } } else if (qName.equals("SourceLine")) { SourceLineAnnotation sourceAnnotation = createSourceLineAnnotation(qName, attributes); if (!sourceAnnotation.isSynthetic()) bugAnnotation = sourceAnnotation; } else if (qName.equals("Int")) { try { String value = getRequiredAttribute(attributes, "value", qName); bugAnnotation = new IntAnnotation(Integer.parseInt(value)); } catch (NumberFormatException e) { throw new SAXException("Bad integer value in Int"); } } else if (qName.equals("String")) { String value = getRequiredAttribute(attributes, "value", qName); bugAnnotation = StringAnnotation.fromXMLEscapedString(value); } else if (qName.equals("LocalVariable")) { try { String varName = getRequiredAttribute(attributes, "name", qName); int register = Integer.parseInt(getRequiredAttribute(attributes, "register", qName)); int pc = Integer.parseInt(getRequiredAttribute(attributes, "pc", qName)); bugAnnotation = new LocalVariableAnnotation(varName, register, pc); } catch (NumberFormatException e) { throw new SAXException("Invalid integer value in attribute of LocalVariable element"); } } else if (qName.equals("Property")) { // A BugProperty. String propName = getRequiredAttribute(attributes, "name", qName); String propValue = getRequiredAttribute(attributes, "value", qName); bugInstance.setProperty(propName, propValue); } else if (qName.equals("UserAnnotation")) { // ignore AnnotationText for now; will handle in endElement String s = getOptionalAttribute(attributes, "designation"); // optional if (s != null) { bugInstance.setUserDesignationKey(s, null); } s = getOptionalAttribute(attributes, "user"); // optional if (s != null) bugInstance.setUser(s); s = getOptionalAttribute(attributes, "timestamp"); // optional if (s != null) try { long timestamp = Long.valueOf(s); bugInstance.setUserAnnotationTimestamp(timestamp); } catch (NumberFormatException nfe) { // ok to contine -- just won't set a timestamp for the user // designation. // but is there anyplace to report this? } s = getOptionalAttribute(attributes, "needsSync"); // optional if (s == null || s.equals("false")) bugInstance.setUserAnnotationDirty(false); } else throw new SAXException("Unknown bug annotation named " + qName); if (bugAnnotation != null) { String role = getOptionalAttribute(attributes, "role"); if (role != null) bugAnnotation.setDescription(role); setAnnotationRole(attributes, bugAnnotation); bugInstance.add(bugAnnotation); } } private long parseLong(String s, long defaultValue) { long value; try { value = (s != null) ? Long.parseLong(s) : defaultValue; } catch (NumberFormatException e) { value = defaultValue; } return value; } /** * Extract a hash value from an element. * * @param qName * name of element containing hash value * @param attributes * element attributes * @return the decoded hash value * @throws SAXException */ private byte[] extractHash(String qName, Attributes attributes) throws SAXException { String encodedHash = getRequiredAttribute(attributes, "value", qName); byte[] hash; try { // System.out.println("Extract hash " + encodedHash); hash = ClassHash.stringToHash(encodedHash); } catch (IllegalArgumentException e) { throw new SAXException("Invalid class hash", e); } return hash; } private void setAnnotationRole(Attributes attributes, BugAnnotation bugAnnotation) { String role = getOptionalAttribute(attributes, "role"); if (role != null) bugAnnotation.setDescription(role); } private SourceLineAnnotation createSourceLineAnnotation(String qName, Attributes attributes) throws SAXException { String classname = getRequiredAttribute(attributes, "classname", qName); String sourceFile = getOptionalAttribute(attributes, "sourcefile"); if (sourceFile == null) sourceFile = SourceLineAnnotation.UNKNOWN_SOURCE_FILE; String startLine = getOptionalAttribute(attributes, "start"); // "start"/"end" // are now // optional String endLine = getOptionalAttribute(attributes, "end"); // (were too // many "-1"s // in the xml) String startBytecode = getOptionalAttribute(attributes, "startBytecode"); String endBytecode = getOptionalAttribute(attributes, "endBytecode"); String synthetic = getOptionalAttribute(attributes, "synthetic"); try { int sl = startLine != null ? Integer.parseInt(startLine) : -1; int el = endLine != null ? Integer.parseInt(endLine) : -1; int sb = startBytecode != null ? Integer.parseInt(startBytecode) : -1; int eb = endBytecode != null ? Integer.parseInt(endBytecode) : -1; SourceLineAnnotation s = new SourceLineAnnotation(classname, sourceFile, sl, el, sb, eb); if ("true".equals(synthetic)) s.setSynthetic(true); return s; } catch (NumberFormatException e) { throw new SAXException("Bad integer value in SourceLine element", e); } } @Override public void endElement(String uri, String name, String qName) throws SAXException { // URI should always be empty. // So, qName is the name of the element. if (discardedElement(qName)) { nestingOfIgnoredElements--; } else if (nestingOfIgnoredElements > 0) { // ignore it } else if (qName.equals("Project")) { // noop } else if (elementStack.size() > 1) { String outerElement = elementStack.get(elementStack.size() - 2); if (isTopLevelFilter(qName) || isCompoundElementTag(qName)) { if (DEBUG) System.out.println(" ending " + elementStack + " " + qName + " " + matcherStack); matcherStack.pop(); } else if (outerElement.equals(BUG_COLLECTION)) { if (qName.equals("BugInstance")) { bugCollection.add(bugInstance, false); } } else if (outerElement.equals(PROJECT)) { if (qName.equals("Jar")) project.addFile(makeAbsolute(getTextContents())); else if (qName.equals("SrcDir")) project.addSourceDir(makeAbsolute(getTextContents())); else if (qName.equals("AuxClasspathEntry")) project.addAuxClasspathEntry(makeAbsolute(getTextContents())); } else if (outerElement.equals(Project.CLOUD_ELEMENT_NAME) && qName.equals(Project.CLOUD_PROPERTY_ELEMENT_NAME)) { assert cloudPropertyKey != null; project.getCloudProperties().setProperty(cloudPropertyKey, getTextContents()); cloudPropertyKey = null; } else if (outerElement.equals("BugInstance")) { if (qName.equals("UserAnnotation")) { bugInstance.setAnnotationText(getTextContents(), null); } } else if (outerElement.equals(BugCollection.ERRORS_ELEMENT_NAME)) { if (qName.equals(BugCollection.ANALYSIS_ERROR_ELEMENT_NAME)) { analysisError.setMessage(getTextContents()); bugCollection.addError(analysisError); } else if (qName.equals(BugCollection.ERROR_ELEMENT_NAME)) { if (stackTrace.size() > 0) { analysisError.setStackTrace(stackTrace.toArray(new String[stackTrace.size()])); } bugCollection.addError(analysisError); } else if (qName.equals(BugCollection.MISSING_CLASS_ELEMENT_NAME)) { bugCollection.addMissingClass(getTextContents()); } } else if (outerElement.equals(BugCollection.ERROR_ELEMENT_NAME)) { if (qName.equals(BugCollection.ERROR_MESSAGE_ELEMENT_NAME)) { analysisError.setMessage(getTextContents()); } else if (qName.equals(BugCollection.ERROR_EXCEPTION_ELEMENT_NAME)) { analysisError.setExceptionMessage(getTextContents()); } else if (qName.equals(BugCollection.ERROR_STACK_TRACE_ELEMENT_NAME)) { stackTrace.add(getTextContents()); } } else if (outerElement.equals("ClassFeatures")) { if (qName.equals(ClassFeatureSet.ELEMENT_NAME)) { bugCollection.setClassFeatureSet(classFeatureSet); classFeatureSet = null; } } } elementStack.remove(elementStack.size() - 1); } private String makeAbsolute(String possiblyRelativePath) { if (possiblyRelativePath.contains("://") || possiblyRelativePath.startsWith("http:") || possiblyRelativePath.startsWith("https:") || possiblyRelativePath.startsWith("file:")) return possiblyRelativePath; if (base == null) return possiblyRelativePath; if (new File(possiblyRelativePath).isAbsolute()) return possiblyRelativePath; return new File(base.getParentFile(), possiblyRelativePath).getAbsolutePath(); } @Override public void characters(char[] ch, int start, int length) { textBuffer.append(ch, start, length); } private String getRequiredAttribute(Attributes attributes, String attrName, String elementName) throws SAXException { String value = attributes.getValue(attrName); if (value == null) throw new SAXException(elementName + " element missing " + attrName + " attribute"); return memoized(Strings.unescapeXml(value)); } } // vim:ts=4
fix for null pointer warnings git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@14475 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/SAXBugCollectionHandler.java
fix for null pointer warnings
<ide><path>indbugs/src/java/edu/umd/cs/findbugs/SAXBugCollectionHandler.java <ide> <ide> private static boolean DEBUG = false; <ide> <add> @SuppressWarnings("hiding") <ide> @Override <ide> public void startElement(String uri, String name, String qName, Attributes attributes) throws SAXException { <ide> // URI should always be empty. <ide> throw new SAXException("Invalid top-level element (expected " + topLevelName + ", saw " + qName + ")"); <ide> <ide> if (qName.equals(BUG_COLLECTION)) { <add> BugCollection bugCollection = this.bugCollection; <add> assert bugCollection != null; <ide> // Read and set the sequence number. <ide> String version = getOptionalAttribute(attributes, "version"); <ide> if (bugCollection instanceof SortedBugCollection) <ide> matcherStack.clear(); <ide> pushCompoundMatcher(filter); <ide> } else if (qName.equals(PROJECT)) { <add> Project project = this.project; <add> assert project != null; <ide> // Project element <ide> String projectName = getOptionalAttribute(attributes, Project.PROJECTNAME_ATTRIBUTE_NAME); <ide> if (projectName != null) <ide> } else { <ide> String outerElement = elementStack.get(elementStack.size() - 1); <ide> if (outerElement.equals(BUG_COLLECTION)) { <add> <ide> // Parsing a top-level element of the BugCollection <ide> if (qName.equals("BugInstance")) { <ide> // BugInstance element - get required type and priority <ide> } <ide> <ide> } else if (qName.equals("FindBugsSummary")) { <add> BugCollection bugCollection = this.bugCollection; <add> assert bugCollection != null; <ide> String timestamp = getRequiredAttribute(attributes, "timestamp", qName); <ide> String vmVersion = getOptionalAttribute(attributes, "vm_version"); <ide> String totalClasses = getOptionalAttribute(attributes, "total_classes"); <ide> stackTrace.clear(); <ide> } <ide> } else if (outerElement.equals("FindBugsSummary") && qName.equals("PackageStats")) { <add> BugCollection bugCollection = this.bugCollection; <add> assert bugCollection != null; <ide> String packageName = getRequiredAttribute(attributes, "package", qName); <ide> int numClasses = Integer.valueOf(getRequiredAttribute(attributes, "total_types", qName)); <ide> int size = Integer.valueOf(getRequiredAttribute(attributes, "total_size", qName)); <ide> bugCollection.getProjectStats().putPackageStats(packageName, numClasses, size); <ide> <ide> } else if (outerElement.equals("PackageStats")) { <add> BugCollection bugCollection = this.bugCollection; <add> assert bugCollection != null; <ide> if (qName.equals("ClassStats")) { <ide> String className = getRequiredAttribute(attributes, "class", qName); <ide> Boolean isInterface = Boolean.valueOf(getRequiredAttribute(attributes, "interface", qName)); <ide> } <ide> } else if (outerElement.equals(BugCollection.HISTORY_ELEMENT_NAME)) { <ide> if (qName.equals(AppVersion.ELEMENT_NAME)) { <add> BugCollection bugCollection = this.bugCollection; <add> assert bugCollection != null; <add> <ide> try { <ide> String sequence = getRequiredAttribute(attributes, "sequence", qName); <ide> String timestamp = getOptionalAttribute(attributes, "timestamp"); <ide> } <ide> } <ide> } else if (outerElement.equals(BugCollection.PROJECT_ELEMENT_NAME)) { <add> Project project = this.project; <add> assert project != null; <ide> if (qName.equals(Project.CLOUD_ELEMENT_NAME)) { <ide> String cloudId = getRequiredAttribute(attributes, Project.CLOUD_ID_ATTRIBUTE_NAME, qName); <ide> project.setCloudId(cloudId); <ide> } <ide> } <ide> <add> @SuppressWarnings("hiding") <ide> @Override <ide> public void endElement(String uri, String name, String qName) throws SAXException { <ide> // URI should always be empty. <ide> <ide> matcherStack.pop(); <ide> } else if (outerElement.equals(BUG_COLLECTION)) { <add> BugCollection bugCollection = this.bugCollection; <add> assert bugCollection != null; <ide> if (qName.equals("BugInstance")) { <ide> bugCollection.add(bugInstance, false); <ide> } <ide> } else if (outerElement.equals(PROJECT)) { <add> Project project = this.project; <add> assert project != null; <ide> if (qName.equals("Jar")) <ide> project.addFile(makeAbsolute(getTextContents())); <ide> else if (qName.equals("SrcDir")) <ide> <ide> <ide> } else if (outerElement.equals(Project.CLOUD_ELEMENT_NAME) && qName.equals(Project.CLOUD_PROPERTY_ELEMENT_NAME)) { <add> Project project = this.project; <add> assert project != null; <ide> assert cloudPropertyKey != null; <ide> project.getCloudProperties().setProperty(cloudPropertyKey, getTextContents()); <ide> cloudPropertyKey = null; <ide> bugInstance.setAnnotationText(getTextContents(), null); <ide> } <ide> } else if (outerElement.equals(BugCollection.ERRORS_ELEMENT_NAME)) { <add> BugCollection bugCollection = this.bugCollection; <add> assert bugCollection != null; <ide> if (qName.equals(BugCollection.ANALYSIS_ERROR_ELEMENT_NAME)) { <ide> analysisError.setMessage(getTextContents()); <ide> bugCollection.addError(analysisError); <ide> } <ide> } else if (outerElement.equals("ClassFeatures")) { <ide> if (qName.equals(ClassFeatureSet.ELEMENT_NAME)) { <add> BugCollection bugCollection = this.bugCollection; <add> assert bugCollection != null; <add> <ide> bugCollection.setClassFeatureSet(classFeatureSet); <ide> classFeatureSet = null; <ide> }
Java
apache-2.0
a56c70c13040d6242d0d22c89470ca19dcd948c6
0
metaborg/spoofax-modelware
package org.spoofax.modelware.gmf; public class Debouncer { private final int debounceConstant = 500; private long lastText2model; private boolean text2model; private boolean textSelection; private boolean diagramSelection; public Debouncer() { text2model = true; textSelection = true; diagramSelection = true; } public synchronized boolean text2modelAllowed() { boolean result = text2model; if (text2model) lastText2model = System.currentTimeMillis(); else text2model = true; return result; } public synchronized boolean model2textAllowed() { boolean result = lastText2model + debounceConstant < System.currentTimeMillis(); if (result) text2model = false; return result; } public synchronized boolean textSelectionAllowed() { boolean result = textSelection; if (textSelection) diagramSelection = false; else textSelection = true; return result; } public synchronized boolean diagramSelectionAllowed() { boolean result = diagramSelection; if (diagramSelection) textSelection = false; else diagramSelection = true; return result; } }
org.spoofax.modelware.gmf/src/org/spoofax/modelware/gmf/Debouncer.java
package org.spoofax.modelware.gmf; public class Debouncer { private final int debounceConstant = 500; private long lastText2model; private boolean text2model; private boolean textSelection; private boolean diagramSelection; public Debouncer() { text2model = true; textSelection = true; diagramSelection = true; } public synchronized boolean text2modelAllowed() { if (text2model) lastText2model = System.currentTimeMillis(); return text2model; } public synchronized boolean model2textAllowed() { boolean result = lastText2model + debounceConstant < System.currentTimeMillis(); if (result) text2model = false; return result; } public synchronized boolean textSelectionAllowed() { boolean result = textSelection; if (textSelection) diagramSelection = false; else textSelection = true; return result; } public synchronized boolean diagramSelectionAllowed() { boolean result = diagramSelection; if (diagramSelection) textSelection = false; else diagramSelection = true; return result; } }
Bugfix
org.spoofax.modelware.gmf/src/org/spoofax/modelware/gmf/Debouncer.java
Bugfix
<ide><path>rg.spoofax.modelware.gmf/src/org/spoofax/modelware/gmf/Debouncer.java <ide> } <ide> <ide> public synchronized boolean text2modelAllowed() { <add> boolean result = text2model; <add> <ide> if (text2model) <ide> lastText2model = System.currentTimeMillis(); <add> else <add> text2model = true; <ide> <del> return text2model; <add> return result; <ide> } <ide> <ide> public synchronized boolean model2textAllowed() {
Java
lgpl-2.1
8cf5f10ba35c206df1a6e43e0b83f99b211bbf07
0
sbliven/biojava,sbliven/biojava,sbliven/biojava
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * Created on 24.05.2004 * @author Andreas Prlic * */ package org.biojava.bio.structure; import java.util.Iterator; import java.util.NoSuchElementException; /** an iterator over all atoms of a structure / group. * @author Andreas Prlic * @since 1.4 * @version %I% %G% */ public class AtomIterator implements Iterator { Structure structure ; Group group ; int current_atom_pos ; GroupIterator groupiter ; /** * Constructs an AtomIterator object. * * @param struct a Structure object */ public AtomIterator(Structure struct) { structure = struct; current_atom_pos = -1 ; groupiter = new GroupIterator(structure) ; if ( groupiter.hasNext() ) { group = (Group) groupiter.next() ; } else group = null ; } /** get the chain that contains the current atom * * @return a Chain object */ public Chain getCurrentChain(){ return groupiter.getCurrentChain(); } /** * Constructs an AtomIterator object. * * @param g a Group object */ public AtomIterator(Group g) { structure = null; group = g ; current_atom_pos = -1 ; groupiter = null ; } /** is there a next atom ? */ public boolean hasNext() { // trying to iterate over an empty structure... if ( group == null) return false; // if there is another group ... if ( current_atom_pos < group.size()-1 ) { return true ; } else { // search through the next groups if they contain an atom if (groupiter != null) { GroupIterator tmp = (GroupIterator) groupiter.clone() ; while (tmp.hasNext()) { Group tmpg = (Group) tmp.next() ; if ( tmpg.size() > 0 ) { return true ; } } } else { // just an iterator over one group ... return false ; } } return false ; } /** return next atom. * * @return the next Atom * @throws NoSuchElementException ... */ public Object next() throws NoSuchElementException { current_atom_pos++ ; if ( current_atom_pos >= group.size() ) { if ( groupiter == null ) { throw new NoSuchElementException("no more atoms found in group!"); } if ( groupiter.hasNext() ) { group = (Group) groupiter.next() ; current_atom_pos = -1 ; return next(); } else { throw new NoSuchElementException("no more atoms found in structure!"); } } Atom a ; try { a = group.getAtom(current_atom_pos); } catch (StructureException e) { System.out.println("current_atom_pos " + current_atom_pos + " group " + group + "size:" + group.size()); e.printStackTrace(); throw new NoSuchElementException("error wile trying to retrieve atom"); } if ( a.getPDBserial() < 2){ Group g = a.getParent(); Chain c = g.getParent(); System.out.println("c " + c.getName()); } return a ; } /** does nothing. */ public void remove() { } }
src/org/biojava/bio/structure/AtomIterator.java
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * Created on 24.05.2004 * @author Andreas Prlic * */ package org.biojava.bio.structure; import java.util.Iterator; import java.util.NoSuchElementException; /** an iterator over all atoms of a structure / group. * @author Andreas Prlic * @since 1.4 * @version %I% %G% */ public class AtomIterator implements Iterator { Structure structure ; Group group ; int current_atom_pos ; GroupIterator groupiter ; /** * Constructs an AtomIterator object. * * @param struct a Structure object */ public AtomIterator(Structure struct) { structure = struct; current_atom_pos = -1 ; groupiter = new GroupIterator(structure) ; if ( groupiter.hasNext() ) { group = (Group) groupiter.next() ; } else group = null ; } /** * Constructs an AtomIterator object. * * @param g a Group object */ public AtomIterator(Group g) { structure = null; group = g ; current_atom_pos = -1 ; groupiter = null ; } /** is there a next atom ? */ public boolean hasNext() { // trying to iterate over an empty structure... if ( group == null) return false; // if there is another group ... if ( current_atom_pos < group.size()-1 ) { return true ; } else { // search through the next groups if they contain an atom if (groupiter != null) { GroupIterator tmp = (GroupIterator) groupiter.clone() ; while (tmp.hasNext()) { Group tmpg = (Group) tmp.next() ; if ( tmpg.size() > 0 ) { return true ; } } } else { // just an iterator over one group ... return false ; } } return false ; } /** return next atom. * * @return the next Atom * @throws NoSuchElementException ... */ public Object next() throws NoSuchElementException { current_atom_pos++ ; if ( current_atom_pos >= group.size() ) { if ( groupiter == null ) { throw new NoSuchElementException("no more atoms found in group!"); } if ( groupiter.hasNext() ) { group = (Group) groupiter.next() ; current_atom_pos = -1 ; return next(); } else { throw new NoSuchElementException("no more atoms found in structure!"); } } Atom a ; try { a = group.getAtom(current_atom_pos); } catch (StructureException e) { System.out.println("current_atom_pos " + current_atom_pos + " group " + group + "size:" + group.size()); e.printStackTrace(); throw new NoSuchElementException("error wile trying to retrieve atom"); } return a ; } /** does nothing. */ public void remove() { } }
added a mechanism to get the current chain git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@4067 7c6358e6-4a41-0410-a743-a5b2a554c398
src/org/biojava/bio/structure/AtomIterator.java
added a mechanism to get the current chain
<ide><path>rc/org/biojava/bio/structure/AtomIterator.java <ide> } <ide> else <ide> group = null ; <add> } <add> <add> /** get the chain that contains the current atom <add> * <add> * @return a Chain object <add> */ <add> public Chain getCurrentChain(){ <add> return groupiter.getCurrentChain(); <ide> } <ide> <ide> /** <ide> throw new NoSuchElementException("error wile trying to retrieve atom"); <ide> } <ide> <add> if ( a.getPDBserial() < 2){ <add> Group g = a.getParent(); <add> Chain c = g.getParent(); <add> System.out.println("c " + c.getName()); <add> } <add> <ide> return a ; <ide> <ide> }
Java
mit
81da5918087dc38ecb09f5bfa09b68c736d802da
0
leavjenn/Hews
package com.leavjenn.hews.ui; import android.app.Activity; import android.app.Fragment; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.leavjenn.hews.Constants; import com.leavjenn.hews.R; import com.leavjenn.hews.Utils; import com.leavjenn.hews.listener.OnRecyclerViewCreateListener; import com.leavjenn.hews.misc.SharedPrefsManager; import com.leavjenn.hews.model.Comment; import com.leavjenn.hews.model.HNItem; import com.leavjenn.hews.model.Post; import com.leavjenn.hews.network.DataManager; import com.leavjenn.hews.ui.adapter.PostAdapter; import org.parceler.Parcels; import java.util.ArrayList; import java.util.List; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; public class SearchFragment extends Fragment implements PostAdapter.OnReachBottomListener, SharedPreferences.OnSharedPreferenceChangeListener { private static final String KEY_KEYWORD = "key_keyword"; private static final String KEY_TIME_RANGE = "key_time_range"; private static final String KEY_SORT_METHOD = "key_sort_method"; private static final String KEY_POST_ID_LIST = "key_post_id_list"; private static final String KEY_LOADED_POSTS = "key_loaded_posts"; private static final String KEY_LOADED_TIME = "key_loaded_time"; private static final String KEY_LOADING_STATE = "key_loading_state"; private static final String KEY_LAST_TIME_POSITION = "key_last_time_position"; private static final String KEY_SEARCH_RESULT_TOTAL_PAGE = "key_search_result_total_page"; private RelativeLayout layoutRoot; private SwipeRefreshLayout mSwipeRefreshLayout; private RecyclerView mRecyclerView; private Snackbar snackbarNoConnection; private String mKeyword; private String mDateRange; private boolean mIsSortByDate; private int mLoadedTime; private int mLoadingState = Constants.LOADING_IDLE; private int mLastTimeListPosition; private int mSearchResultTotalPages; private List<Long> mPostIdList; private Boolean mShowPostSummary; private PostAdapter.OnItemClickListener mOnItemClickListener; private OnRecyclerViewCreateListener mOnRecyclerViewCreateListener; private LinearLayoutManager mLinearLayoutManager; private PostAdapter mPostAdapter; private SharedPreferences prefs; private DataManager mDataManager; private CompositeSubscription mCompositeSubscription; /** * @param keyword Parameter 1. * @param dateRange Parameter 2. * @return A new instance of fragment SearchFragment. */ public static SearchFragment newInstance(String keyword, String dateRange, boolean isSortByDate) { SearchFragment fragment = new SearchFragment(); Bundle args = new Bundle(); args.putString(KEY_KEYWORD, keyword); args.putString(KEY_TIME_RANGE, dateRange); args.putBoolean(KEY_SORT_METHOD, isSortByDate); fragment.setArguments(args); return fragment; } public SearchFragment() { } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mOnItemClickListener = (PostAdapter.OnItemClickListener) activity; mOnRecyclerViewCreateListener = (OnRecyclerViewCreateListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement (PostAdapter.OnItemClickListener)"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // if (getArguments() != null) { // mKeyword = getArguments().getString(KEY_KEYWORD); // mDateRange = getArguments().getString(KEY_TIME_RANGE); // mIsSortByDate = getArguments().getBoolean(KEY_SORT_METHOD); // } prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); prefs.registerOnSharedPreferenceChangeListener(this); mDataManager = new DataManager(); mCompositeSubscription = new CompositeSubscription(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_search, container, false); layoutRoot = (RelativeLayout) rootView.findViewById(R.id.layout_search_root); mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_layout); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.list_search); return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mLinearLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(mLinearLayoutManager); mOnRecyclerViewCreateListener.onRecyclerViewCreate(mRecyclerView); mPostAdapter = new PostAdapter(this.getActivity(), this, mOnItemClickListener); mRecyclerView.setAdapter(mPostAdapter); mSwipeRefreshLayout.setColorSchemeResources(R.color.orange_600, R.color.orange_900, R.color.orange_900, R.color.orange_600); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refresh(); } }); mShowPostSummary = SharedPrefsManager.getShowPostSummary(prefs, getActivity()); if (savedInstanceState != null) { mKeyword = savedInstanceState.getString(KEY_KEYWORD); mDateRange = savedInstanceState.getString(KEY_TIME_RANGE); mIsSortByDate = savedInstanceState.getBoolean(KEY_SORT_METHOD); mPostIdList = Parcels.unwrap(savedInstanceState.getParcelable(KEY_POST_ID_LIST)); if (mPostAdapter.getItemCount() == 0) { mPostAdapter.addFooter(new HNItem.Footer()); mPostAdapter.addAllPosts((ArrayList<Post>) Parcels.unwrap(savedInstanceState.getParcelable(KEY_LOADED_POSTS))); } mSearchResultTotalPages = savedInstanceState.getInt(KEY_SEARCH_RESULT_TOTAL_PAGE); mLastTimeListPosition = savedInstanceState.getInt(KEY_LAST_TIME_POSITION, 0); mRecyclerView.getLayoutManager().scrollToPosition(mLastTimeListPosition); mLoadedTime = savedInstanceState.getInt(KEY_LOADED_TIME); mLoadingState = savedInstanceState.getInt(KEY_LOADING_STATE); if (mLoadingState == Constants.LOADING_IN_PROGRESS) { loadMore(); } } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_KEYWORD, mKeyword); outState.putString(KEY_TIME_RANGE, mDateRange); outState.putBoolean(KEY_SORT_METHOD, mIsSortByDate); outState.putParcelable(KEY_LOADED_POSTS, Parcels.wrap(mPostAdapter.getPostList())); outState.putParcelable(KEY_POST_ID_LIST, Parcels.wrap(mPostIdList)); outState.putInt(KEY_SEARCH_RESULT_TOTAL_PAGE, mSearchResultTotalPages); mLastTimeListPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager()). findFirstVisibleItemPosition(); outState.putInt(KEY_LAST_TIME_POSITION, mLastTimeListPosition); outState.putInt(KEY_LOADED_TIME, mLoadedTime); outState.putInt(KEY_LOADING_STATE, mLoadingState); } @Override public void onDestroy() { super.onDestroy(); if (mCompositeSubscription.hasSubscriptions()) { mCompositeSubscription.unsubscribe(); } prefs.unregisterOnSharedPreferenceChangeListener(this); } void loadPostListFromSearch(String keyword, String dateRange, int page, boolean isSortByDate) { mCompositeSubscription.add( mDataManager.getSearchResult(keyword, "created_at_i>" + dateRange.substring(0, 10) + "," + "created_at_i<" + dateRange.substring(10), page, isSortByDate) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<HNItem.SearchResult>() { @Override public void call(HNItem.SearchResult searchResult) { if (searchResult.getHits().length == 0) { mSwipeRefreshLayout.setRefreshing(false); mPostAdapter.updatePrompt(R.string.no_search_result_prompt); updateLoadingState(Constants.LOADING_PROMPT_NO_CONTENT); mPostAdapter.notifyDataSetChanged(); return; } List<Long> list = new ArrayList<>(); mSearchResultTotalPages = searchResult.getNbPages(); for (int i = 0; i < searchResult.getHits().length; i++) { list.add(searchResult.getHits()[i].getObjectID()); } loadPostFromList(list); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { mSwipeRefreshLayout.setRefreshing(false); Log.i("loadPostListFromSearch", throwable.toString()); } })); } void loadPostFromList(List<Long> list) { mCompositeSubscription.add(mDataManager.getPosts(list) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Post>() { @Override public void onCompleted() { updateLoadingState(Constants.LOADING_IDLE); } @Override public void onError(Throwable e) { mSwipeRefreshLayout.setRefreshing(false); updateLoadingState(Constants.LOADING_ERROR); Log.e("loadPostFromList", e.toString()); } @Override public void onNext(Post post) { if (mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(false); } mRecyclerView.setVisibility(View.VISIBLE); if (post != null) { post.setIndex(mPostAdapter.getItemCount() - 1); Utils.setupPostUrl(post); mPostAdapter.addPost(post); if (mLoadingState != Constants.LOADING_IN_PROGRESS) { updateLoadingState(Constants.LOADING_IN_PROGRESS); } if (mShowPostSummary && post.getKids() != null) { loadSummary(post); } } } })); } void loadSummary(final Post post) { mCompositeSubscription.add(mDataManager.getSummary(post.getKids()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Comment>() { @Override public void call(Comment comment) { if (comment != null) { post.setSummary(Html.fromHtml(comment.getText()).toString()); mPostAdapter.notifyItemChanged(post.getIndex()); } else { post.setSummary(null); } } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Log.e("loadSummary: " + String.valueOf(post.getId()), throwable.toString()); } }) ); } public void refresh(String keyword, String dateRange, boolean isSortByDate) { mKeyword = keyword; mDateRange = dateRange; mIsSortByDate = isSortByDate; if (Utils.isOnline(getActivity())) { mLoadedTime = 1; mCompositeSubscription.clear(); mSwipeRefreshLayout.setRefreshing(true); if (snackbarNoConnection != null && snackbarNoConnection.isShown()) { snackbarNoConnection.dismiss(); } mPostAdapter.clear(); mPostAdapter.addFooter(new HNItem.Footer()); updateLoadingState(Constants.LOADING_IDLE); loadPostListFromSearch(keyword, dateRange, 0, isSortByDate); } else { if (mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(false); } snackbarNoConnection = Snackbar.make(layoutRoot, R.string.no_connection_prompt, Snackbar.LENGTH_INDEFINITE); Utils.setSnackBarTextColor(snackbarNoConnection, getActivity(), android.R.color.white); snackbarNoConnection.setAction(R.string.snackebar_action_retry, new View.OnClickListener() { @Override public void onClick(View v) { refresh(); } }); snackbarNoConnection.setActionTextColor(getResources().getColor(R.color.orange_600)); snackbarNoConnection.show(); } } public void refresh(String dateRange) { refresh(mKeyword, dateRange, mIsSortByDate); } public void refresh(boolean isSortByDate) { refresh(mKeyword, mDateRange, isSortByDate); } public void refresh() { if (mKeyword != null && mDateRange != null) { refresh(mKeyword, mDateRange, mIsSortByDate); } } public String getKeyword() { return mKeyword; } public void setKeyword(String keyword) { mKeyword = keyword; } public String getDateRange() { return mDateRange; } public void setDateRange(String dateRange) { mDateRange = dateRange; } public boolean getIsSortByDate() { return mIsSortByDate; } public void setSortByDate(boolean isSortByDate) { mIsSortByDate = isSortByDate; } public void setSwipeRefreshLayoutState(boolean isEnable) { mSwipeRefreshLayout.setEnabled(isEnable); } private void updateLoadingState(int loadingState) { mLoadingState = loadingState; mPostAdapter.updateFooter(mLoadingState); } private void loadMore() { if (mLoadedTime < mSearchResultTotalPages) { Log.i(String.valueOf(mSearchResultTotalPages), String.valueOf(mLoadedTime)); updateLoadingState(Constants.LOADING_IN_PROGRESS); loadPostListFromSearch(mKeyword, mDateRange, mLoadedTime++, mIsSortByDate); } else { Utils.showLongToast(getActivity(), R.string.no_more_posts_prompt); updateLoadingState(Constants.LOADING_FINISH); } } private void reformatListStyle() { int position = mLinearLayoutManager.findFirstVisibleItemPosition(); int offset = 0; View firstChild = mLinearLayoutManager.getChildAt(0); if (firstChild != null) { offset = firstChild.getTop(); } PostAdapter newAdapter = (PostAdapter) mRecyclerView.getAdapter(); mRecyclerView.setAdapter(newAdapter); mLinearLayoutManager.scrollToPositionWithOffset(position, offset); } @Override public void OnReachBottom() { if (mLoadingState == Constants.LOADING_IDLE) { loadMore(); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(SharedPrefsManager.KEY_POST_FONT) || key.equals(SharedPrefsManager.KEY_POST_FONT_SIZE) || key.equals(SharedPrefsManager.KEY_POST_LINE_HEIGHT)) { mPostAdapter.updatePostPrefs(); reformatListStyle(); } } }
app/src/main/java/com/leavjenn/hews/ui/SearchFragment.java
package com.leavjenn.hews.ui; import android.app.Activity; import android.app.Fragment; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.Snackbar; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.leavjenn.hews.Constants; import com.leavjenn.hews.R; import com.leavjenn.hews.Utils; import com.leavjenn.hews.listener.OnRecyclerViewCreateListener; import com.leavjenn.hews.misc.SharedPrefsManager; import com.leavjenn.hews.model.Comment; import com.leavjenn.hews.model.HNItem; import com.leavjenn.hews.model.Post; import com.leavjenn.hews.network.DataManager; import com.leavjenn.hews.ui.adapter.PostAdapter; import org.parceler.Parcels; import java.util.ArrayList; import java.util.List; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; import rx.subscriptions.CompositeSubscription; public class SearchFragment extends Fragment implements PostAdapter.OnReachBottomListener, SharedPreferences.OnSharedPreferenceChangeListener { private static final String KEY_KEYWORD = "key_keyword"; private static final String KEY_TIME_RANGE = "key_time_range"; private static final String KEY_SORT_METHOD = "key_sort_method"; private static final String KEY_POST_ID_LIST = "key_post_id_list"; private static final String KEY_LOADED_POSTS = "key_loaded_posts"; private static final String KEY_LOADED_TIME = "key_loaded_time"; private static final String KEY_LOADING_STATE = "key_loading_state"; private static final String KEY_LAST_TIME_POSITION = "key_last_time_position"; private static final String KEY_SEARCH_RESULT_TOTAL_PAGE = "key_search_result_total_page"; private RelativeLayout layoutRoot; private SwipeRefreshLayout mSwipeRefreshLayout; private RecyclerView mRecyclerView; private Snackbar snackbarNoConnection; private String mKeyword; private String mDateRange; private boolean mIsSortByDate; private int mLoadedTime; private int mLoadingState = Constants.LOADING_IDLE; private int mLastTimeListPosition; private int mSearchResultTotalPages; private List<Long> mPostIdList; private Boolean mShowPostSummary; private PostAdapter.OnItemClickListener mOnItemClickListener; private OnRecyclerViewCreateListener mOnRecyclerViewCreateListener; private LinearLayoutManager mLinearLayoutManager; private PostAdapter mPostAdapter; private SharedPreferences prefs; private DataManager mDataManager; private CompositeSubscription mCompositeSubscription; /** * @param keyword Parameter 1. * @param dateRange Parameter 2. * @return A new instance of fragment SearchFragment. */ public static SearchFragment newInstance(String keyword, String dateRange, boolean isSortByDate) { SearchFragment fragment = new SearchFragment(); Bundle args = new Bundle(); args.putString(KEY_KEYWORD, keyword); args.putString(KEY_TIME_RANGE, dateRange); args.putBoolean(KEY_SORT_METHOD, isSortByDate); fragment.setArguments(args); return fragment; } public SearchFragment() { } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mOnItemClickListener = (PostAdapter.OnItemClickListener) activity; mOnRecyclerViewCreateListener = (OnRecyclerViewCreateListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement (PostAdapter.OnItemClickListener)"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // if (getArguments() != null) { // mKeyword = getArguments().getString(KEY_KEYWORD); // mDateRange = getArguments().getString(KEY_TIME_RANGE); // mIsSortByDate = getArguments().getBoolean(KEY_SORT_METHOD); // } prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); prefs.registerOnSharedPreferenceChangeListener(this); mDataManager = new DataManager(); mCompositeSubscription = new CompositeSubscription(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_search, container, false); layoutRoot = (RelativeLayout) rootView.findViewById(R.id.layout_search_root); mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_layout); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.list_search); return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mLinearLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setLayoutManager(mLinearLayoutManager); mOnRecyclerViewCreateListener.onRecyclerViewCreate(mRecyclerView); mPostAdapter = new PostAdapter(this.getActivity(), this, mOnItemClickListener); mRecyclerView.setAdapter(mPostAdapter); mSwipeRefreshLayout.setColorSchemeResources(R.color.orange_600, R.color.orange_900, R.color.orange_900, R.color.orange_600); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refresh(); } }); mShowPostSummary = SharedPrefsManager.getShowPostSummary(prefs, getActivity()); if (savedInstanceState != null) { mKeyword = getArguments().getString(KEY_KEYWORD); mDateRange = getArguments().getString(KEY_TIME_RANGE); mIsSortByDate = getArguments().getBoolean(KEY_SORT_METHOD); mPostIdList = Parcels.unwrap(savedInstanceState.getParcelable(KEY_POST_ID_LIST)); if (mPostAdapter.getItemCount() == 0) { mPostAdapter.addFooter(new HNItem.Footer()); mPostAdapter.addAllPosts((ArrayList<Post>) Parcels.unwrap(savedInstanceState.getParcelable(KEY_LOADED_POSTS))); } mSearchResultTotalPages = savedInstanceState.getInt(KEY_SEARCH_RESULT_TOTAL_PAGE); mLastTimeListPosition = savedInstanceState.getInt(KEY_LAST_TIME_POSITION, 0); mRecyclerView.getLayoutManager().scrollToPosition(mLastTimeListPosition); mLoadedTime = savedInstanceState.getInt(KEY_LOADED_TIME); mLoadingState = savedInstanceState.getInt(KEY_LOADING_STATE); if (mLoadingState == Constants.LOADING_IN_PROGRESS) { loadMore(); } } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(KEY_KEYWORD, mKeyword); outState.putString(KEY_TIME_RANGE, mDateRange); outState.putBoolean(KEY_SORT_METHOD, mIsSortByDate); outState.putParcelable(KEY_LOADED_POSTS, Parcels.wrap(mPostAdapter.getPostList())); outState.putParcelable(KEY_POST_ID_LIST, Parcels.wrap(mPostIdList)); outState.putInt(KEY_SEARCH_RESULT_TOTAL_PAGE, mSearchResultTotalPages); mLastTimeListPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager()). findFirstVisibleItemPosition(); outState.putInt(KEY_LAST_TIME_POSITION, mLastTimeListPosition); outState.putInt(KEY_LOADED_TIME, mLoadedTime); outState.putInt(KEY_LOADING_STATE, mLoadingState); } @Override public void onDestroy() { super.onDestroy(); if (mCompositeSubscription.hasSubscriptions()) { mCompositeSubscription.unsubscribe(); } prefs.unregisterOnSharedPreferenceChangeListener(this); } void loadPostListFromSearch(String keyword, String dateRange, int page, boolean isSortByDate) { mCompositeSubscription.add( mDataManager.getSearchResult(keyword, "created_at_i>" + dateRange.substring(0, 10) + "," + "created_at_i<" + dateRange.substring(10), page, isSortByDate) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<HNItem.SearchResult>() { @Override public void call(HNItem.SearchResult searchResult) { if (searchResult.getHits().length == 0) { mSwipeRefreshLayout.setRefreshing(false); mPostAdapter.updatePrompt(R.string.no_search_result_prompt); updateLoadingState(Constants.LOADING_PROMPT_NO_CONTENT); mPostAdapter.notifyDataSetChanged(); return; } List<Long> list = new ArrayList<>(); mSearchResultTotalPages = searchResult.getNbPages(); for (int i = 0; i < searchResult.getHits().length; i++) { list.add(searchResult.getHits()[i].getObjectID()); } loadPostFromList(list); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { mSwipeRefreshLayout.setRefreshing(false); Log.i("loadPostListFromSearch", throwable.toString()); } })); } void loadPostFromList(List<Long> list) { mCompositeSubscription.add(mDataManager.getPosts(list) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<Post>() { @Override public void onCompleted() { updateLoadingState(Constants.LOADING_IDLE); } @Override public void onError(Throwable e) { mSwipeRefreshLayout.setRefreshing(false); updateLoadingState(Constants.LOADING_ERROR); Log.e("loadPostFromList", e.toString()); } @Override public void onNext(Post post) { if (mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(false); } mRecyclerView.setVisibility(View.VISIBLE); if (post != null) { post.setIndex(mPostAdapter.getItemCount() - 1); Utils.setupPostUrl(post); mPostAdapter.addPost(post); if (mLoadingState != Constants.LOADING_IN_PROGRESS) { updateLoadingState(Constants.LOADING_IN_PROGRESS); } if (mShowPostSummary && post.getKids() != null) { loadSummary(post); } } } })); } void loadSummary(final Post post) { mCompositeSubscription.add(mDataManager.getSummary(post.getKids()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Comment>() { @Override public void call(Comment comment) { if (comment != null) { post.setSummary(Html.fromHtml(comment.getText()).toString()); mPostAdapter.notifyItemChanged(post.getIndex()); } else { post.setSummary(null); } } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { Log.e("loadSummary: " + String.valueOf(post.getId()), throwable.toString()); } }) ); } public void refresh(String keyword, String dateRange, boolean isSortByDate) { mKeyword = keyword; mDateRange = dateRange; mIsSortByDate = isSortByDate; if (Utils.isOnline(getActivity())) { mLoadedTime = 1; mCompositeSubscription.clear(); mSwipeRefreshLayout.setRefreshing(true); if (snackbarNoConnection != null && snackbarNoConnection.isShown()) { snackbarNoConnection.dismiss(); } mPostAdapter.clear(); mPostAdapter.addFooter(new HNItem.Footer()); updateLoadingState(Constants.LOADING_IDLE); loadPostListFromSearch(keyword, dateRange, 0, isSortByDate); } else { if (mSwipeRefreshLayout.isRefreshing()) { mSwipeRefreshLayout.setRefreshing(false); } snackbarNoConnection = Snackbar.make(layoutRoot, R.string.no_connection_prompt, Snackbar.LENGTH_INDEFINITE); Utils.setSnackBarTextColor(snackbarNoConnection, getActivity(), android.R.color.white); snackbarNoConnection.setAction(R.string.snackebar_action_retry, new View.OnClickListener() { @Override public void onClick(View v) { refresh(); } }); snackbarNoConnection.setActionTextColor(getResources().getColor(R.color.orange_600)); snackbarNoConnection.show(); } } public void refresh(String dateRange) { refresh(mKeyword, dateRange, mIsSortByDate); } public void refresh(boolean isSortByDate) { refresh(mKeyword, mDateRange, isSortByDate); } public void refresh() { if (mKeyword != null && mDateRange != null) { refresh(mKeyword, mDateRange, mIsSortByDate); } } public String getKeyword() { return mKeyword; } public void setKeyword(String keyword) { mKeyword = keyword; } public String getDateRange() { return mDateRange; } public void setDateRange(String dateRange) { mDateRange = dateRange; } public boolean getIsSortByDate() { return mIsSortByDate; } public void setSortByDate(boolean isSortByDate) { mIsSortByDate = isSortByDate; } public void setSwipeRefreshLayoutState(boolean isEnable) { mSwipeRefreshLayout.setEnabled(isEnable); } private void updateLoadingState(int loadingState) { mLoadingState = loadingState; mPostAdapter.updateFooter(mLoadingState); } private void loadMore() { if (mLoadedTime < mSearchResultTotalPages) { Log.i(String.valueOf(mSearchResultTotalPages), String.valueOf(mLoadedTime)); updateLoadingState(Constants.LOADING_IN_PROGRESS); loadPostListFromSearch(mKeyword, mDateRange, mLoadedTime++, mIsSortByDate); } else { Utils.showLongToast(getActivity(), R.string.no_more_posts_prompt); updateLoadingState(Constants.LOADING_FINISH); } } private void reformatListStyle() { int position = mLinearLayoutManager.findFirstVisibleItemPosition(); int offset = 0; View firstChild = mLinearLayoutManager.getChildAt(0); if (firstChild != null) { offset = firstChild.getTop(); } PostAdapter newAdapter = (PostAdapter) mRecyclerView.getAdapter(); mRecyclerView.setAdapter(newAdapter); mLinearLayoutManager.scrollToPositionWithOffset(position, offset); } @Override public void OnReachBottom() { if (mLoadingState == Constants.LOADING_IDLE) { loadMore(); } } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(SharedPrefsManager.KEY_POST_FONT) || key.equals(SharedPrefsManager.KEY_POST_FONT_SIZE) || key.equals(SharedPrefsManager.KEY_POST_LINE_HEIGHT)) { mPostAdapter.updatePostPrefs(); reformatListStyle(); } } }
fix (getArguments() NPE): get mKeyword and other stuff from savedInstanceState.
app/src/main/java/com/leavjenn/hews/ui/SearchFragment.java
fix (getArguments() NPE): get mKeyword and other stuff from savedInstanceState.
<ide><path>pp/src/main/java/com/leavjenn/hews/ui/SearchFragment.java <ide> }); <ide> mShowPostSummary = SharedPrefsManager.getShowPostSummary(prefs, getActivity()); <ide> if (savedInstanceState != null) { <del> mKeyword = getArguments().getString(KEY_KEYWORD); <del> mDateRange = getArguments().getString(KEY_TIME_RANGE); <del> mIsSortByDate = getArguments().getBoolean(KEY_SORT_METHOD); <add> mKeyword = savedInstanceState.getString(KEY_KEYWORD); <add> mDateRange = savedInstanceState.getString(KEY_TIME_RANGE); <add> mIsSortByDate = savedInstanceState.getBoolean(KEY_SORT_METHOD); <ide> mPostIdList = Parcels.unwrap(savedInstanceState.getParcelable(KEY_POST_ID_LIST)); <ide> if (mPostAdapter.getItemCount() == 0) { <ide> mPostAdapter.addFooter(new HNItem.Footer());
Java
mit
028781e73b69dfb9bff7d19899f38831f7fc5aea
0
lunaticPenguin/forkJoinAndThreadComparator
package tools; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import process.IProcessAdapter; /** * This class is able to store multiple results from several tests. * It gains interests when it is used with another tool able to draw out these data (, * like a statistics generator :) ). * * For cause of simplicity of use, the implementation is made with the singleton pattern. * * @author Corentin Legros */ final public class Timer { /** * Data relative to thread processes type */ private HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> threadData; /** * Data relative to fork/join processes type */ private HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> fjData; /** * Instance of timer (singleton inside!) */ private static Timer instance; /** * Timestamp when the timer start */ private long timestart; /** * Timestamp when the timer takes end */ private long timeend; /** * Percent range to pick up data during processes */ private int range; /** * Simple reference to establish a shortcut in the code (this reference always * points on the current test (both thread/forkJoin) */ private ArrayList<ArrayList<ArrayList<Integer>>> currentTestReference; /** * Counter which indicates the current test number for the chosen file * using the thread processes */ private HashMap<String, Integer> currentThreadTest; /** * Counter which indicates the current test number for chosen file * using the fork join processes */ private HashMap<String, Integer> currentForkJoinTest; /** * Store the current filename */ private String currentFilename; /** * Indicates the last used process type */ private int currentProcessType; public final String CSV_SEPARATOR = ";"; /** * Get global timer instance * @return */ public static Timer getInstance() { if (instance == null) { instance = new Timer(); } return instance; } private Timer() { init(); } /** * This method is generically able to store a new time value in the internal data. * * @param Integer part_num * @param int percent */ public void addData(Integer part_num) { HashMap<String, Integer> currentFileTestIndex = currentProcessType == IProcessAdapter.PROCESS_TYPE_THREAD ? currentThreadTest : currentForkJoinTest; if (currentTestReference.get(currentFileTestIndex.get(currentFilename)).get(part_num).size() < 100 / range) { currentTestReference.get(currentFileTestIndex.get(currentFilename)).get(part_num).add(Integer.valueOf((int)(System.nanoTime() - timestart))); } } /* * This method allow to generically initialize internal data containers * @param HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> data */ private void init() { fjData = new HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>>(); threadData = new HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>>(); timestart = 0; timeend = 0; range = 15; currentThreadTest = new HashMap<String, Integer>(); currentForkJoinTest = new HashMap<String, Integer>(); } /* * Get a new data container relative to a test (start launch) data */ private ArrayList<ArrayList<ArrayList<Integer>>> getNewTest() { return new ArrayList<ArrayList<ArrayList<Integer>>>(); } /* * Get a new data container relative to a part (thread/worker) data * * @param int nbPart number threads/workers to create */ private ArrayList<ArrayList<Integer>> getNewPart(int nbPart) { nbPart = nbPart <= 0 ? nbPart = 20 : nbPart; return new ArrayList<ArrayList<Integer>>(nbPart); } /* * Get a new data container relative to a percent progress */ private ArrayList<Integer> getNewData() { return new ArrayList<Integer>(); } /** * Initialize and start timer * * @param int dataType type of processes whose results have to be stored * @param String file name of the file which is treated * @param int nbPart number of the thread/workers used in the current test */ public void start(int dataType, String file, int nbPart) { currentFilename = file; currentProcessType = dataType; HashMap<String, Integer> currentFileTestIndex = currentProcessType == IProcessAdapter.PROCESS_TYPE_THREAD ? currentThreadTest : currentForkJoinTest; HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> data; if (currentProcessType == IProcessAdapter.PROCESS_TYPE_THREAD) { data = threadData; } else { data = fjData; } // if we had to create an entire new data structure if (!currentFileTestIndex.containsKey(currentFilename)) { currentFileTestIndex.put(currentFilename, 0); currentTestReference = getNewTest(); data.put(currentFilename, currentTestReference); } else { int tmpIndex = currentFileTestIndex.get(currentFilename); currentFileTestIndex.put(currentFilename, ++tmpIndex); currentTestReference = data.get(currentFilename); } currentTestReference.add(getNewPart(nbPart)); for (int i = 0 ; i < nbPart ; ++i) { currentTestReference.get(currentFileTestIndex.get(currentFilename)).add(getNewData()); } timestart = System.nanoTime(); } /** * Stop timer */ public void stop() { if (timestart != 0) { timeend = System.nanoTime(); } } /** * Indicates if the timer is running * @return boolean */ public boolean isRunning() { return timestart != 0 && timeend != 0; } /** * Clear all internal timer values, and reinitialize them */ public void clear() { clearInternalData(threadData); clearInternalData(fjData); timestart = 0; timeend = 0; init(); init(); } /* * Clear all specified internal values (manually, because I think the JVM's GC sucks) * @param HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> data The specified data */ private void clearInternalData(HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> data) { Set<Map.Entry<String, ArrayList<ArrayList<ArrayList<Integer>>>>> dataSet = data.entrySet(); Iterator<Map.Entry<String, ArrayList<ArrayList<ArrayList<Integer>>>>> itDataSet = dataSet.iterator(); ArrayList<ArrayList<ArrayList<Integer>>> tmpTestAL; Iterator<ArrayList<ArrayList<Integer>>> itTestAL; ArrayList<ArrayList<Integer>> tmpPartAL; Iterator<ArrayList<Integer>> itPartAL; while (itDataSet.hasNext()) { tmpTestAL = itDataSet.next().getValue(); itTestAL = tmpTestAL.iterator(); while (itTestAL.hasNext()) { tmpPartAL = itTestAL.next(); itPartAL = tmpPartAL.iterator(); while (itPartAL.hasNext()) { itPartAL.next().clear(); } tmpPartAL.clear(); } tmpTestAL.clear(); } itDataSet = null; data.clear(); } /** * Get all internal data relative to the thread processes * @return */ public HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> getThreadProcessData() { return threadData; } /** * Get all internal data relative to the forkjoin processes * @return */ public HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> getForkJoinProcessData() { return fjData; } /** * Set the percent range to pick up data regularly during processes * @param int range */ public void setPickUpRange(int range) { if (range < 0) { range -= range; } else if (range == 0) { range = 20; } else if (range > 100) { range = 100; } this.range = range; } /** * Get the percent range * @return int */ public int getPickUpRange() { return range; } /** * This method format specified internal data to csv string format used to * generate statistics into other software like Calc or Excel. * * @param int typeData * @param String filename * @return */ public String getDataAsString(int typeData, String filename) { String processTypeName = typeData == IProcessAdapter.PROCESS_TYPE_THREAD ? "Thread" : "ForkJoin"; HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> data; if (typeData == IProcessAdapter.PROCESS_TYPE_THREAD) { data = threadData; } else { data = fjData; } StringBuilder sbContent = new StringBuilder(); StringBuilder sbDataTitle = new StringBuilder(); StringBuilder sbDataHeader = new StringBuilder(); if (data.containsKey(filename)) { ArrayList<ArrayList<Integer>> testTmp; Iterator<ArrayList<ArrayList<Integer>>> testIterator = data.get(filename).iterator(); Iterator<ArrayList<Integer>> entitiesIterator; ArrayList<Integer> dataTmp; Iterator<Integer> progressIterator; int testCounter = 1; int entityCounter = 1; int percentsCounter = 0; sbDataHeader.append("Percent progress").append("#"); int nbValues = 100 / range; for (int i = 0 ; i < nbValues ; ++i) { sbDataHeader.append(CSV_SEPARATOR).append(percentsCounter + range); percentsCounter += range; } // for each test, rendering of all test data specifications while (testIterator.hasNext()) { testTmp = testIterator.next(); entitiesIterator = testTmp.iterator(); sbDataTitle.setLength(0); sbDataTitle.append("\n\nTest #").append(testCounter).append(" -- ").append(processTypeName); sbContent.append(sbDataTitle).append("\n\n"); sbContent.append(sbDataHeader).append("\n"); entityCounter = 1; // for all test entities while (entitiesIterator.hasNext()) { dataTmp = entitiesIterator.next(); progressIterator = dataTmp.iterator(); sbContent.append(entityCounter); while (progressIterator.hasNext()) { sbContent.append(CSV_SEPARATOR).append(progressIterator.next()); } sbContent.append("\n"); ++entityCounter; } ++testCounter; } } else { System.out.println("A problem occured with this data (no luck!) :("); } return sbContent.toString(); } }
src/tools/Timer.java
package tools; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import process.IProcessAdapter; /** * This class is able to store multiple results from several tests. * It gains interests when it is used with another tool able to draw out these data (, * like a statistics generator :) ). * * For cause of simplicity of use, the implementation is made with the singleton pattern. * * @author Corentin Legros */ final public class Timer { /** * Data relative to thread processes type */ private HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> threadData; /** * Data relative to fork/join processes type */ private HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> fjData; /** * Instance of timer (singleton inside!) */ private static Timer instance; /** * Timestamp when the timer start */ private long timestart; /** * Timestamp when the timer takes end */ private long timeend; /** * Percent range to pick up data during processes */ private int range; /** * Simple reference to establish a shortcut in the code (this reference always * points on the current test (both thread/forkJoin) */ private ArrayList<ArrayList<ArrayList<Integer>>> currentTestReference; /** * Counter which indicates the current test number for the chosen file * using the thread processes */ private HashMap<String, Integer> currentThreadTest; /** * Counter which indicates the current test number for chosen file * using the fork join processes */ private HashMap<String, Integer> currentForkJoinTest; /** * Store the current filename */ private String currentFilename; /** * Indicates the last used process type */ private int currentProcessType; public final String CSV_SEPARATOR = ";"; /** * Get global timer instance * @return */ public static Timer getInstance() { if (instance == null) { instance = new Timer(); } return instance; } private Timer() { init(); } /** * This method is generically able to store a new time value in the internal data. * * @param Integer part_num * @param int percent */ public void addData(Integer part_num) { HashMap<String, Integer> currentFileTestIndex = currentProcessType == IProcessAdapter.PROCESS_TYPE_THREAD ? currentThreadTest : currentForkJoinTest; if (currentTestReference.get(currentFileTestIndex.get(currentFilename)).get(part_num).size() < 100 / range) { currentTestReference.get(currentFileTestIndex.get(currentFilename)).get(part_num).add(Integer.valueOf((int)(System.nanoTime() - timestart))); } } /* * This method allow to generically initialize internal data containers * @param HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> data */ private void init() { fjData = new HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>>(); threadData = new HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>>(); timestart = 0; timeend = 0; range = 15; currentThreadTest = new HashMap<String, Integer>(); currentForkJoinTest = new HashMap<String, Integer>(); } /* * Get a new data container relative to a test (start launch) data */ private ArrayList<ArrayList<ArrayList<Integer>>> getNewTest() { return new ArrayList<ArrayList<ArrayList<Integer>>>(); } /* * Get a new data container relative to a part (thread/worker) data * * @param int nbPart number threads/workers to create */ private ArrayList<ArrayList<Integer>> getNewPart(int nbPart) { nbPart = nbPart <= 0 ? nbPart = 20 : nbPart; return new ArrayList<ArrayList<Integer>>(nbPart); } /* * Get a new data container relative to a percent progress */ private ArrayList<Integer> getNewData() { return new ArrayList<Integer>(); } /** * Initialize and start timer * * @param int dataType type of processes whose results have to be stored * @param String file name of the file which is treated * @param int nbPart number of the thread/workers used in the current test */ public void start(int dataType, String file, int nbPart) { currentFilename = file; currentProcessType = dataType; HashMap<String, Integer> currentFileTestIndex = currentProcessType == IProcessAdapter.PROCESS_TYPE_THREAD ? currentThreadTest : currentForkJoinTest; HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> data; if (currentProcessType == IProcessAdapter.PROCESS_TYPE_THREAD) { data = threadData; } else { data = fjData; } // if we had to create an entire new data structure if (!currentFileTestIndex.containsKey(currentFilename)) { currentFileTestIndex.put(currentFilename, 0); currentTestReference = getNewTest(); data.put(currentFilename, currentTestReference); } else { int tmpIndex = currentFileTestIndex.get(currentFilename); currentFileTestIndex.put(currentFilename, ++tmpIndex); currentTestReference = data.get(currentFilename); } currentTestReference.add(getNewPart(nbPart)); for (int i = 0 ; i < nbPart ; ++i) { currentTestReference.get(currentFileTestIndex.get(currentFilename)).add(getNewData()); } timestart = System.nanoTime(); } /** * Stop timer */ public void stop() { if (timestart != 0) { timeend = System.nanoTime(); } } /** * Indicates if the timer is running * @return boolean */ public boolean isRunning() { return timestart != 0 && timeend != 0; } /** * Clear all internal timer values, and reinitialize them */ public void clear() { clearInternalData(threadData); clearInternalData(fjData); timestart = 0; timeend = 0; init(); init(); } /* * Clear all specified internal values (manually, because I think the JVM's GC sucks) * @param HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> data The specified data */ private void clearInternalData(HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> data) { Set<Map.Entry<String, ArrayList<ArrayList<ArrayList<Integer>>>>> dataSet = data.entrySet(); Iterator<Map.Entry<String, ArrayList<ArrayList<ArrayList<Integer>>>>> itDataSet = dataSet.iterator(); ArrayList<ArrayList<ArrayList<Integer>>> tmpTestAL; Iterator<ArrayList<ArrayList<Integer>>> itTestAL; ArrayList<ArrayList<Integer>> tmpPartAL; Iterator<ArrayList<Integer>> itPartAL; while (itDataSet.hasNext()) { tmpTestAL = itDataSet.next().getValue(); itTestAL = tmpTestAL.iterator(); while (itTestAL.hasNext()) { tmpPartAL = itTestAL.next(); itPartAL = tmpPartAL.iterator(); while (itPartAL.hasNext()) { itPartAL.next().clear(); } tmpPartAL.clear(); } tmpTestAL.clear(); } itDataSet = null; data.clear(); } /** * Get all internal data relative to the thread processes * @return */ public HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> getThreadProcessData() { return threadData; } /** * Get all internal data relative to the forkjoin processes * @return */ public HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> getForkJoinProcessData() { return fjData; } /** * Set the percent range to pick up data regularly during processes * @param int range */ public void setPickUpRange(int range) { if (range < 0) { range -= range; } else if (range == 0) { range = 20; } else if (range > 100) { range = 100; } this.range = range; } /** * Get the percent range * @return int */ public int getPickUpRange() { return range; } /** * This method format specified internal data to csv string format used to * generate statistics into other software like Calc or Excel. * * @param int typeData * @param String filename * @return */ public String getDataAsString(int typeData, String filename) { String processTypeName = typeData == IProcessAdapter.PROCESS_TYPE_THREAD ? "Thread" : "ForkJoin"; HashMap<String, ArrayList<ArrayList<ArrayList<Integer>>>> data; if (typeData == IProcessAdapter.PROCESS_TYPE_THREAD) { data = threadData; } else { data = fjData; } StringBuilder sbDataTitle = new StringBuilder(); StringBuilder sbData = new StringBuilder(); StringBuilder sbDataHeader = new StringBuilder(); if (data.containsKey(filename)) { data.get(filename); ArrayList<ArrayList<Integer>> testTmp; Iterator<ArrayList<ArrayList<Integer>>> testIterator = data.get(filename).iterator(); Iterator<ArrayList<Integer>> entitiesIterator; ArrayList<Integer> dataTmp; Iterator<Integer> progressIterator; int testCounter = 1; int entityCounter = 1; int percentsCounter = 0; sbDataHeader.append("Percent progress").append("#"); int nbValues = 100 / range; for (int i = 0 ; i < nbValues ; ++i) { sbDataHeader.append(CSV_SEPARATOR).append(percentsCounter + range); percentsCounter += range; } // for each test, rendering of all test data specifications while (testIterator.hasNext()) { testTmp = testIterator.next(); entitiesIterator = testTmp.iterator(); sbData.setLength(0); sbDataTitle.setLength(0); sbDataTitle.append("\n\nTest #").append(testCounter).append(" -- ").append(processTypeName).append("\n"); entityCounter = 1; // for all test entities while (entitiesIterator.hasNext()) { dataTmp = entitiesIterator.next(); progressIterator = dataTmp.iterator(); sbData.append(entityCounter); while (progressIterator.hasNext()) { sbData.append(CSV_SEPARATOR).append(progressIterator.next()); } sbData.append("\n"); ++entityCounter; } ++testCounter; } } else { System.out.println("A problem occured with this data (no luck!) :("); } return sbDataTitle.append("\n") .append(sbDataHeader).append("\n") .append(sbData).append("\n") .toString(); } }
L'export des données fonctionne désormais de façon normale.
src/tools/Timer.java
L'export des données fonctionne désormais de façon normale.
<ide><path>rc/tools/Timer.java <ide> data = fjData; <ide> } <ide> <add> StringBuilder sbContent = new StringBuilder(); <ide> StringBuilder sbDataTitle = new StringBuilder(); <del> StringBuilder sbData = new StringBuilder(); <ide> StringBuilder sbDataHeader = new StringBuilder(); <ide> <ide> if (data.containsKey(filename)) { <del> <del> data.get(filename); <ide> <ide> ArrayList<ArrayList<Integer>> testTmp; <ide> Iterator<ArrayList<ArrayList<Integer>>> testIterator = data.get(filename).iterator(); <ide> testTmp = testIterator.next(); <ide> entitiesIterator = testTmp.iterator(); <ide> <del> sbData.setLength(0); <ide> sbDataTitle.setLength(0); <del> sbDataTitle.append("\n\nTest #").append(testCounter).append(" -- ").append(processTypeName).append("\n"); <add> sbDataTitle.append("\n\nTest #").append(testCounter).append(" -- ").append(processTypeName); <add> <add> sbContent.append(sbDataTitle).append("\n\n"); <add> sbContent.append(sbDataHeader).append("\n"); <ide> <ide> entityCounter = 1; <ide> <ide> <ide> dataTmp = entitiesIterator.next(); <ide> progressIterator = dataTmp.iterator(); <del> <del> sbData.append(entityCounter); <add> sbContent.append(entityCounter); <ide> <ide> while (progressIterator.hasNext()) { <del> sbData.append(CSV_SEPARATOR).append(progressIterator.next()); <add> sbContent.append(CSV_SEPARATOR).append(progressIterator.next()); <ide> } <del> sbData.append("\n"); <add> sbContent.append("\n"); <ide> ++entityCounter; <ide> } <add> <ide> ++testCounter; <ide> } <ide> } else { <ide> System.out.println("A problem occured with this data (no luck!) :("); <ide> } <ide> <del> return sbDataTitle.append("\n") <del> .append(sbDataHeader).append("\n") <del> .append(sbData).append("\n") <del> .toString(); <add> return sbContent.toString(); <ide> } <ide> }
Java
mpl-2.0
eb44fe70a43ada9e3e3afbc77e9a3eab0d144ada
0
RoyalDev/RoyalCommands,joansmith/RoyalCommands
package org.royaldev.royalcommands.rcommands.kits; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.royaldev.royalcommands.RoyalCommands; import org.royaldev.royalcommands.shaded.com.sk89q.util.config.ConfigurationNode; import java.util.ArrayList; import java.util.List; public class Kit { private final String name; private final List<ItemStack> items; private final long cooldown; public Kit(final String name, final ConfigurationNode kit) { this.name = name; this.items = this.getItemStacks(kit.getNodeList("items", new ArrayList<ConfigurationNode>())); this.cooldown = kit.getLong("cooldown", -1L); } private ItemStack addEnchantments(final ItemStack is, final List<ConfigurationNode> enchantments) { for (final ConfigurationNode enchantment : enchantments) { final Enchantment realEnchantment = this.getEnchantment(enchantment); if (realEnchantment == null) continue; is.addUnsafeEnchantment(realEnchantment, enchantment.getInt("level", 1)); } return is; } private Enchantment getEnchantment(final ConfigurationNode enchantment) { return Enchantment.getByName(enchantment.getString("type", "").toUpperCase()); } private ItemStack getItemStack(final ConfigurationNode item) { final ItemStack is = RoyalCommands.inm.getItemStackFromAlias(item.getString("type")); if (is == null) return null; is.setAmount(item.getInt("amount", 1)); is.setDurability(item.getShort("damage", (short) 0)); final ItemMeta im = is.getItemMeta(); im.setDisplayName(item.getString("name")); im.setLore(item.getStringList("lore", new ArrayList<String>())); is.setItemMeta(im); this.addEnchantments(is, item.getNodeList("enchantments", new ArrayList<ConfigurationNode>())); return is; } private List<ItemStack> getItemStacks(final List<ConfigurationNode> items) { final List<ItemStack> itemStacks = new ArrayList<>(); for (final ConfigurationNode item : items) { final ItemStack is = this.getItemStack(item); if (is == null) continue; itemStacks.add(is); } return itemStacks; } public long getCooldown() { return this.cooldown; } public List<ItemStack> getItems() { return new ArrayList<>(this.items); } public String getName() { return this.name; } }
modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/rcommands/kits/Kit.java
package org.royaldev.royalcommands.rcommands.kits; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.royaldev.royalcommands.RoyalCommands; import org.royaldev.royalcommands.shaded.com.sk89q.util.config.ConfigurationNode; import java.util.ArrayList; import java.util.List; public class Kit { private final String name; private final List<ItemStack> items; private final long cooldown; public Kit(final String name, final ConfigurationNode kit) { this.name = name; this.items = this.getItemStacks(kit.getNodeList("items", new ArrayList<ConfigurationNode>())); this.cooldown = kit.getLong("cooldown", -1L); } private ItemStack addEnchantments(final ItemStack is, final List<ConfigurationNode> enchantments) { for (final ConfigurationNode enchantment : enchantments) { final Enchantment realEnchantment = this.getEnchantment(enchantment); if (realEnchantment == null) continue; is.addEnchantment(realEnchantment, enchantment.getInt("level", 1)); } return is; } private Enchantment getEnchantment(final ConfigurationNode enchantment) { return Enchantment.getByName(enchantment.getString("name")); } private ItemStack getItemStack(final ConfigurationNode item) { final ItemStack is = RoyalCommands.inm.getItemStackFromAlias(item.getString("type")); if (is == null) return null; is.setAmount(item.getInt("amount", 1)); is.setDurability(item.getShort("damage", (short) 0)); final ItemMeta im = is.getItemMeta(); im.setDisplayName(item.getString("name")); im.setLore(item.getStringList("lore", new ArrayList<String>())); is.setItemMeta(im); this.addEnchantments(is, item.getNodeList("enchantments", new ArrayList<ConfigurationNode>())); return is; } private List<ItemStack> getItemStacks(final List<ConfigurationNode> items) { final List<ItemStack> itemStacks = new ArrayList<>(); for (final ConfigurationNode item : items) { final ItemStack is = this.getItemStack(item); if (is == null) continue; itemStacks.add(is); } return itemStacks; } public long getCooldown() { return this.cooldown; } public List<ItemStack> getItems() { return new ArrayList<>(this.items); } public String getName() { return this.name; } }
Fixed: Kit enchantments
modules/RoyalCommands/src/main/java/org/royaldev/royalcommands/rcommands/kits/Kit.java
Fixed: Kit enchantments
<ide><path>odules/RoyalCommands/src/main/java/org/royaldev/royalcommands/rcommands/kits/Kit.java <ide> for (final ConfigurationNode enchantment : enchantments) { <ide> final Enchantment realEnchantment = this.getEnchantment(enchantment); <ide> if (realEnchantment == null) continue; <del> is.addEnchantment(realEnchantment, enchantment.getInt("level", 1)); <add> is.addUnsafeEnchantment(realEnchantment, enchantment.getInt("level", 1)); <ide> } <ide> return is; <ide> } <ide> <ide> private Enchantment getEnchantment(final ConfigurationNode enchantment) { <del> return Enchantment.getByName(enchantment.getString("name")); <add> return Enchantment.getByName(enchantment.getString("type", "").toUpperCase()); <ide> } <ide> <ide> private ItemStack getItemStack(final ConfigurationNode item) {
Java
apache-2.0
40f5bebf479b8b4feabadeb34b62f8181a18ca96
0
Sargul/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,serge-rider/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,Sargul/dbeaver,dbeaver/dbeaver,dbeaver/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2016-2016 Karl Griesser ([email protected]) * Copyright (C) 2010-2019 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.exasol.model.cache; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.exasol.model.*; import org.jkiss.dbeaver.ext.exasol.tools.ExasolUtils; import org.jkiss.dbeaver.model.DBPEvaluationContext; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCCompositeCache; import org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.sql.SQLException; import java.util.List; /** * @author Karl */ public final class ExasolTableForeignKeyCache extends JDBCCompositeCache<ExasolSchema, ExasolTable, ExasolTableForeignKey, ExasolTableKeyColumn> { private static final String SQL_FK_TAB = "select\r\n" + " CONSTRAINT_NAME,CONSTRAINT_TABLE,CONSTRAINT_SCHEMA,constraint_owner,c.constraint_enabled,constraint_Type," + "cc.column_name,cc.ordinal_position,cc.referenced_schema,cc.referenced_table,cc.referenced_column" + " from\r\n" + " (SELECT * FROM EXA_ALL_CONSTRAINTS " + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_TABLE = '%s' \r\n" + " ORDER BY 1,2,3 \r\n" + " )c\r\n" + " inner join\r\n" + " (SELECT * FROM EXA_ALL_CONSTRAINT_COLUMNS " + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_TABLE = '%s' \r\n" + " ORDER BY 1,2,3 \r\n" + " ) cc\r\n" + " using\r\n" + " (\r\n" + " CONSTRAINT_SCHEMA, CONSTRAINT_TABLE, CONSTRAINT_NAME, CONSTRAINT_OWNER, CONSTRAINT_TYPE\r\n" + " )\r\n" + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_TABLE = '%s' \r\n" + " order by\r\n" + " ORDINAL_POSITION"; private static final String SQL_FK_ALL = "select\r\n" + " CONSTRAINT_NAME,CONSTRAINT_TABLE,CONSTRAINT_SCHEMA,constraint_owner,c.constraint_enabled,constraint_Type," + "cc.column_name,cc.ordinal_position,cc.referenced_schema,cc.referenced_table,cc.referenced_column" + " from\r\n" + " (SELECT * FROM EXA_ALL_CONSTRAINTS " + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY'\r\n" + " ORDER BY 1,2,3 \r\n" + " )c\r\n" + " inner join\r\n" + " (SELECT * FROM EXA_ALL_CONSTRAINT_COLUMNS " + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY' \r\n" + " ORDER BY 1,2,3 \r\n" + " ) cc\r\n" + " using\r\n" + " (\r\n" + " CONSTRAINT_SCHEMA, CONSTRAINT_TABLE, CONSTRAINT_NAME, CONSTRAINT_OWNER, CONSTRAINT_TYPE\r\n" + " )\r\n" + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY' \r\n" + " order by\r\n" + " ORDINAL_POSITION"; public ExasolTableForeignKeyCache(ExasolTableCache tableCache) { super(tableCache, ExasolTable.class, "CONSTRAINT_TABLE", "CONSTRAINT_NAME"); } @SuppressWarnings("rawtypes") @NotNull @Override protected JDBCStatement prepareObjectsStatement(JDBCSession session, ExasolSchema exasolSchema, ExasolTable forTable) throws SQLException { String sql; if (forTable != null) { sql = String.format(SQL_FK_TAB,ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(forTable.getName()),ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(forTable.getName()),ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(forTable.getName())); } else { sql = String.format(SQL_FK_ALL,ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(exasolSchema.getName())); } JDBCStatement dbStat = session.createStatement(); ((JDBCStatementImpl) dbStat).setQueryString(sql); return dbStat; } @Nullable @Override protected ExasolTableForeignKey fetchObject(JDBCSession session, ExasolSchema ExasolSchema, ExasolTable ExasolTable, String constName, JDBCResultSet dbResult) throws SQLException, DBException { return new ExasolTableForeignKey(session.getProgressMonitor(), ExasolTable, dbResult); } @Nullable @Override protected ExasolTableKeyColumn[] fetchObjectRow(JDBCSession session, ExasolTable ExasolTable, ExasolTableForeignKey object, JDBCResultSet dbResult) throws SQLException, DBException { String colName = JDBCUtils.safeGetString(dbResult, "COLUMN_NAME"); ExasolTableColumn tableColumn = ExasolTable.getAttribute(session.getProgressMonitor(), colName); if (tableColumn == null) { log.info("ExasolTableForeignKeyCache : Column '" + colName + "' not found in table '" + ExasolTable.getFullyQualifiedName(DBPEvaluationContext.UI) + "' ??"); return null; } else { return new ExasolTableKeyColumn[]{ new ExasolTableKeyColumn(object, tableColumn, JDBCUtils.safeGetInt(dbResult, "ORDINAL_POSITION")) }; } } @Override protected void cacheChildren(DBRProgressMonitor monitor, ExasolTableForeignKey constraint, List<ExasolTableKeyColumn> rows) { constraint.setColumns(rows); } }
plugins/org.jkiss.dbeaver.ext.exasol/src/org/jkiss/dbeaver/ext/exasol/model/cache/ExasolTableForeignKeyCache.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2016-2016 Karl Griesser ([email protected]) * Copyright (C) 2010-2019 Serge Rider ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.ext.exasol.model.cache; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ext.exasol.model.*; import org.jkiss.dbeaver.ext.exasol.tools.ExasolUtils; import org.jkiss.dbeaver.model.DBPEvaluationContext; import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet; import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession; import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement; import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils; import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCCompositeCache; import org.jkiss.dbeaver.model.impl.jdbc.exec.JDBCStatementImpl; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import java.sql.SQLException; import java.util.List; /** * @author Karl */ public final class ExasolTableForeignKeyCache extends JDBCCompositeCache<ExasolSchema, ExasolTable, ExasolTableForeignKey, ExasolTableKeyColumn> { private static final String SQL_FK_TAB = "select\r\n" + " CONSTRAINT_NAME,CONSTRAINT_TABLE,CONSTRAINT_SCHEMA,constraint_owner,c.constraint_enabled,constraint_Type," + "cc.column_name,cc.ordinal_position,cc.referenced_schema,cc.referenced_table,cc.referenced_column" + " from\r\n" + " (SELECT * FROM EXA_ALL_CONSTRAINTS " + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_TABLE = '%s' \r\n" + " ORDER BY 1,2,3 \r\n" + " )c\r\n" + " inner join\r\n" + " (SELECT * FROM EXA_ALL_CONSTRAINT_COLUMNS " + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_TABLE = '%s' \r\n" + " ORDER BY 1,2,3 \r\n" + " ) cc\r\n" + " using\r\n" + " (\r\n" + " CONSTRAINT_SCHEMA, CONSTRAINT_TABLE, CONSTRAINT_NAME, CONSTRAINT_OWNER, CONSTRAINT_TYPE\r\n" + " )\r\n" + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_TABLE = '%s' \r\n" + " order by\r\n" + " ORDINAL_POSITION"; private static final String SQL_FK_ALL = "select\r\n" + " CONSTRAINT_NAME,CONSTRAINT_TABLE,CONSTRAINT_SCHEMA,constraint_owner,c.constraint_enabled,constraint_Type," + "cc.column_name,cc.ordinal_position,cc.referenced_schema,cc.referenced_table,cc.referenced_column" + " from\r\n" + " (SELECT * FROM EXA_ALL_CONSTRAINTS " + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY'\r\n" + " ORDER BY 1,2,3 \r\n" + " )c\r\n" + " inner join\r\n" + " (SELECT * FROM EXA_ALL_CONSTRAINT_COLUMNS " + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY' \r\n" + " ORDER BY 1,2,3 c\r\n" + " ) cc\r\n" + " using\r\n" + " (\r\n" + " CONSTRAINT_SCHEMA, CONSTRAINT_TABLE, CONSTRAINT_NAME, CONSTRAINT_OWNER, CONSTRAINT_TYPE\r\n" + " )\r\n" + " where\r\n" + " CONSTRAINT_SCHEMA = '%s' and\r\n" + " CONSTRAINT_TYPE = 'FOREIGN KEY' \r\n" + " order by\r\n" + " ORDINAL_POSITION"; public ExasolTableForeignKeyCache(ExasolTableCache tableCache) { super(tableCache, ExasolTable.class, "CONSTRAINT_TABLE", "CONSTRAINT_NAME"); } @SuppressWarnings("rawtypes") @NotNull @Override protected JDBCStatement prepareObjectsStatement(JDBCSession session, ExasolSchema exasolSchema, ExasolTable forTable) throws SQLException { String sql; if (forTable != null) { sql = String.format(SQL_FK_TAB,ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(forTable.getName()),ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(forTable.getName()),ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(forTable.getName())); } else { sql = String.format(SQL_FK_ALL,ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(exasolSchema.getName()),ExasolUtils.quoteString(exasolSchema.getName())); } JDBCStatement dbStat = session.createStatement(); ((JDBCStatementImpl) dbStat).setQueryString(sql); return dbStat; } @Nullable @Override protected ExasolTableForeignKey fetchObject(JDBCSession session, ExasolSchema ExasolSchema, ExasolTable ExasolTable, String constName, JDBCResultSet dbResult) throws SQLException, DBException { return new ExasolTableForeignKey(session.getProgressMonitor(), ExasolTable, dbResult); } @Nullable @Override protected ExasolTableKeyColumn[] fetchObjectRow(JDBCSession session, ExasolTable ExasolTable, ExasolTableForeignKey object, JDBCResultSet dbResult) throws SQLException, DBException { String colName = JDBCUtils.safeGetString(dbResult, "COLUMN_NAME"); ExasolTableColumn tableColumn = ExasolTable.getAttribute(session.getProgressMonitor(), colName); if (tableColumn == null) { log.info("ExasolTableForeignKeyCache : Column '" + colName + "' not found in table '" + ExasolTable.getFullyQualifiedName(DBPEvaluationContext.UI) + "' ??"); return null; } else { return new ExasolTableKeyColumn[]{ new ExasolTableKeyColumn(object, tableColumn, JDBCUtils.safeGetInt(dbResult, "ORDINAL_POSITION")) }; } } @Override protected void cacheChildren(DBRProgressMonitor monitor, ExasolTableForeignKey constraint, List<ExasolTableKeyColumn> rows) { constraint.setColumns(rows); } }
Typo in SQL to retrieve schema FKs Former-commit-id: cad2ba5f72c14df7db0139b941f8845b53b597b8
plugins/org.jkiss.dbeaver.ext.exasol/src/org/jkiss/dbeaver/ext/exasol/model/cache/ExasolTableForeignKeyCache.java
Typo in SQL to retrieve schema FKs
<ide><path>lugins/org.jkiss.dbeaver.ext.exasol/src/org/jkiss/dbeaver/ext/exasol/model/cache/ExasolTableForeignKeyCache.java <ide> " where\r\n" + <ide> " CONSTRAINT_SCHEMA = '%s' and\r\n" + <ide> " CONSTRAINT_TYPE = 'FOREIGN KEY' \r\n" + <del> " ORDER BY 1,2,3 c\r\n" + <add> " ORDER BY 1,2,3 \r\n" + <ide> " ) cc\r\n" + <ide> " using\r\n" + <ide> " (\r\n" +
Java
epl-1.0
e7173c706ffecc6b907157b2fdd123dafda164e5
0
gnodet/wikitext
/******************************************************************************* * Copyright (c) 2009 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.tasks.tests; import junit.framework.TestCase; import org.eclipse.mylyn.internal.tasks.ui.actions.CopyTaskDetailsAction; import org.eclipse.mylyn.tasks.tests.connector.MockTask; /** * @author Steffen Pingel */ public class CopyDetailsActionTest extends TestCase { // public void testIdLabelIncluded() { // MockRepositoryConnector connector = MockRepositoryConnector.getDefault(); // String oldPrefix = connector.getTaskIdPrefix(); // try { // MockTask task = new MockTask("123"); // task.setSummary("abc"); // // task.setTaskKey("123"); // connector.setTaskIdPrefix("task"); // String text = CopyTaskDetailsAction.getTextForTask(task); // //assertEquals("task 123: abc", text); // assertEquals("123: abc", text); // // connector.setTaskIdPrefix("#"); // assertEquals("#123: abc", CopyTaskDetailsAction.getTextForTask(task)); // // connector.setTaskIdPrefix(""); // assertEquals("123: abc", CopyTaskDetailsAction.getTextForTask(task)); // // task.setTaskKey(null); // assertEquals("abc", CopyTaskDetailsAction.getTextForTask(task)); // } finally { // connector.setTaskIdPrefix(oldPrefix); // } // } public void testGetTextForTask() { MockTask task = new MockTask("123"); task.setSummary("abc"); task.setTaskKey("123"); String text = CopyTaskDetailsAction.getTextForTask(task); assertEquals("123: abc", text); task.setTaskKey(null); assertEquals("abc", CopyTaskDetailsAction.getTextForTask(task)); } }
org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/CopyDetailsActionTest.java
/******************************************************************************* * Copyright (c) 2009 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.tasks.tests; import junit.framework.TestCase; import org.eclipse.mylyn.internal.tasks.ui.actions.CopyTaskDetailsAction; import org.eclipse.mylyn.tasks.tests.connector.MockRepositoryConnector; import org.eclipse.mylyn.tasks.tests.connector.MockTask; /** * @author Steffen Pingel */ public class CopyDetailsActionTest extends TestCase { public void testIdLabelIncluded() { MockRepositoryConnector connector = MockRepositoryConnector.getDefault(); String oldPrefix = connector.getTaskIdPrefix(); try { MockTask task = new MockTask("123"); task.setSummary("abc"); task.setTaskKey("123"); connector.setTaskIdPrefix("task"); String text = CopyTaskDetailsAction.getTextForTask(task); assertEquals("task 123: abc", text); connector.setTaskIdPrefix("#"); assertEquals("#123: abc", CopyTaskDetailsAction.getTextForTask(task)); connector.setTaskIdPrefix(""); assertEquals("123: abc", CopyTaskDetailsAction.getTextForTask(task)); task.setTaskKey(null); assertEquals("abc", CopyTaskDetailsAction.getTextForTask(task)); } finally { connector.setTaskIdPrefix(oldPrefix); } } }
REOPENED - bug 296760: prepend bug prefix to text that is generated by copy details https://bugs.eclipse.org/bugs/show_bug.cgi?id=296760
org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/CopyDetailsActionTest.java
REOPENED - bug 296760: prepend bug prefix to text that is generated by copy details https://bugs.eclipse.org/bugs/show_bug.cgi?id=296760
<ide><path>rg.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/CopyDetailsActionTest.java <ide> import junit.framework.TestCase; <ide> <ide> import org.eclipse.mylyn.internal.tasks.ui.actions.CopyTaskDetailsAction; <del>import org.eclipse.mylyn.tasks.tests.connector.MockRepositoryConnector; <ide> import org.eclipse.mylyn.tasks.tests.connector.MockTask; <ide> <ide> /** <ide> */ <ide> public class CopyDetailsActionTest extends TestCase { <ide> <del> public void testIdLabelIncluded() { <del> MockRepositoryConnector connector = MockRepositoryConnector.getDefault(); <del> String oldPrefix = connector.getTaskIdPrefix(); <del> try { <del> MockTask task = new MockTask("123"); <del> task.setSummary("abc"); <add>// public void testIdLabelIncluded() { <add>// MockRepositoryConnector connector = MockRepositoryConnector.getDefault(); <add>// String oldPrefix = connector.getTaskIdPrefix(); <add>// try { <add>// MockTask task = new MockTask("123"); <add>// task.setSummary("abc"); <add>// <add>// task.setTaskKey("123"); <add>// connector.setTaskIdPrefix("task"); <add>// String text = CopyTaskDetailsAction.getTextForTask(task); <add>// //assertEquals("task 123: abc", text); <add>// assertEquals("123: abc", text); <add>// <add>// connector.setTaskIdPrefix("#"); <add>// assertEquals("#123: abc", CopyTaskDetailsAction.getTextForTask(task)); <add>// <add>// connector.setTaskIdPrefix(""); <add>// assertEquals("123: abc", CopyTaskDetailsAction.getTextForTask(task)); <add>// <add>// task.setTaskKey(null); <add>// assertEquals("abc", CopyTaskDetailsAction.getTextForTask(task)); <add>// } finally { <add>// connector.setTaskIdPrefix(oldPrefix); <add>// } <add>// } <ide> <del> task.setTaskKey("123"); <del> connector.setTaskIdPrefix("task"); <del> String text = CopyTaskDetailsAction.getTextForTask(task); <del> assertEquals("task 123: abc", text); <add> public void testGetTextForTask() { <add> MockTask task = new MockTask("123"); <add> task.setSummary("abc"); <ide> <del> connector.setTaskIdPrefix("#"); <del> assertEquals("#123: abc", CopyTaskDetailsAction.getTextForTask(task)); <add> task.setTaskKey("123"); <add> String text = CopyTaskDetailsAction.getTextForTask(task); <add> assertEquals("123: abc", text); <ide> <del> connector.setTaskIdPrefix(""); <del> assertEquals("123: abc", CopyTaskDetailsAction.getTextForTask(task)); <del> <del> task.setTaskKey(null); <del> assertEquals("abc", CopyTaskDetailsAction.getTextForTask(task)); <del> } finally { <del> connector.setTaskIdPrefix(oldPrefix); <del> } <add> task.setTaskKey(null); <add> assertEquals("abc", CopyTaskDetailsAction.getTextForTask(task)); <ide> } <ide> <ide> }
Java
epl-1.0
018d5b24ee0c8e0055d4bad8de3a66297788c089
0
Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.ui.swt.composites; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.net.URL; import org.apache.commons.codec.binary.Base64; import org.eclipse.birt.chart.model.attribute.EmbeddedImage; import org.eclipse.birt.chart.model.attribute.Fill; import org.eclipse.birt.chart.model.attribute.Image; import org.eclipse.birt.chart.model.attribute.impl.EmbeddedImageImpl; import org.eclipse.birt.chart.model.attribute.impl.ImageImpl; import org.eclipse.birt.chart.ui.extension.i18n.Messages; import org.eclipse.birt.chart.ui.util.ChartHelpContextIds; import org.eclipse.birt.chart.ui.util.ChartUIUtil; import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * Dialog to build the image element. */ public class ImageDialog extends TrayDialog { final private static int URI_TYPE = 0; final private static int EMBEDDED_TYPE = 1; private Button embedded, uri, browseButton, previewButton; private Composite inputArea; private IconCanvas previewCanvas; private Text uriEditor; private int selectedType = -1; private Fill fCurrent; private String imageData; private Label title; /** * The constructor. * * @param parentShell */ public ImageDialog( Shell parentShell, Fill fCurrent ) { super( parentShell ); this.fCurrent = fCurrent; } protected Control createContents( Composite parent ) { Control ct = super.createContents( parent ); ChartUIUtil.bindHelp( parent, ChartHelpContextIds.DIALOG_COLOR_IMAGE ); initDialog( ); return ct; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected Control createDialogArea( Composite parent ) { Composite topCompostie = (Composite) super.createDialogArea( parent ); createSelectionArea( topCompostie ); new Label( topCompostie, SWT.SEPARATOR | SWT.HORIZONTAL ).setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); Composite composite = new Composite( topCompostie, SWT.NONE ); composite.setLayout( new GridLayout( 2, false ) ); createInputArea( composite ); createPreviewArea( composite ); new Label( topCompostie, SWT.SEPARATOR | SWT.HORIZONTAL ).setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); return topCompostie; } private void createSelectionArea( Composite parent ) { Composite composite = new Composite( parent, SWT.NONE ); composite.setLayout( new GridLayout( 2, false ) ); composite.setLayoutData( new GridData( GridData.FILL_BOTH ) ); Label label = new Label( composite, SWT.NONE ); label.setText( Messages.getString( "ImageDialog.label.SelectImageType" ) ); //$NON-NLS-1$ label.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_BEGINNING ) ); Composite selectionArea = new Composite( composite, SWT.NONE ); selectionArea.setLayout( new FillLayout( SWT.VERTICAL ) ); uri = new Button( selectionArea, SWT.RADIO ); uri.setText( Messages.getString( "ImageDialog.label.URLImage" ) ); //$NON-NLS-1$ uri.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { selectedType = URI_TYPE; title.setText( Messages.getString( "ImageDialog.label.EnterURL" ) ); //$NON-NLS-1$ updateButtons( ); } } ); embedded = new Button( selectionArea, SWT.RADIO ); embedded.setText( Messages.getString( "ImageDialog.label.EmbeddedImage" ) ); //$NON-NLS-1$ embedded.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { selectedType = EMBEDDED_TYPE; title.setText( Messages.getString( "ImageDialog.label.EnterEmbed" ) ); //$NON-NLS-1$ updateButtons( ); } } ); } private void createInputArea( Composite parent ) { inputArea = new Composite( parent, SWT.NONE ); GridData gd = new GridData( GridData.FILL_BOTH | GridData.HORIZONTAL_ALIGN_BEGINNING ); gd.widthHint = 300; gd.heightHint = 300; inputArea.setLayoutData( gd ); inputArea.setLayout( new GridLayout( ) ); title = new Label( inputArea, SWT.NONE ); title.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); uriEditor = new Text( inputArea, SWT.SINGLE | SWT.BORDER ); uriEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); uriEditor.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { updateButtons( ); } } ); Composite innerComp = new Composite( inputArea, SWT.NONE ); innerComp.setLayoutData( new GridData( GridData.HORIZONTAL_ALIGN_END ) ); innerComp.setLayout( new GridLayout( 2, false ) ); browseButton = new Button( innerComp, SWT.PUSH ); browseButton.setText( Messages.getString( "ImageDialog.label.Browse" ) ); //$NON-NLS-1$ browseButton.setLayoutData( new GridData( GridData.HORIZONTAL_ALIGN_END ) ); browseButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent event ) { FileDialog fileChooser = new FileDialog( getShell( ), SWT.OPEN ); fileChooser.setText( Messages.getString( "ImageDialog.label.SelectFile" ) ); //$NON-NLS-1$ fileChooser.setFilterExtensions( new String[]{ "*.gif", "*.jpg", "*.png" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } ); try { String fullPath = fileChooser.open( ); if ( fullPath != null ) { String fileName = fileChooser.getFileName( ); if ( fileName != null ) { imageData = null; fullPath = new StringBuffer( "file:///" ).append( fullPath ).toString( ); //$NON-NLS-1$ uriEditor.setText( fullPath ); } } } catch ( Throwable e ) { e.printStackTrace( ); } } } ); browseButton.setVisible( embedded.getSelection( ) ); previewButton = new Button( innerComp, SWT.PUSH ); previewButton.setText( Messages.getString( "ImageDialog.label.Preview" ) ); //$NON-NLS-1$ previewButton.setLayoutData( new GridData( GridData.HORIZONTAL_ALIGN_END ) ); previewButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { preview( removeQuote( uriEditor.getText( ) ) ); } } ); } private void createPreviewArea( Composite composite ) { Composite previewArea = new Composite( composite, SWT.BORDER ); GridData gd = new GridData( GridData.FILL_BOTH ); gd.widthHint = 250; gd.heightHint = 300; previewArea.setLayoutData( gd ); previewArea.setLayout( new FillLayout( ) ); previewCanvas = new IconCanvas( previewArea ); } private void preview( String uri ) { try { if ( imageData != null ) { ByteArrayInputStream bis = new ByteArrayInputStream( Base64.decodeBase64( imageData.getBytes( ) ) ); previewCanvas.loadImage( bis ); } else { previewCanvas.loadImage( new URL( uri ) ); } } catch ( Exception e ) { WizardBase.displayException( e ); } } private void clearPreview( ) { previewCanvas.clear( ); } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.Dialog#okPressed() */ protected void okPressed( ) { switch ( selectedType ) { case URI_TYPE : fCurrent = ImageImpl.create( removeQuote( uriEditor.getText( ).trim( ) ) ); break; case EMBEDDED_TYPE : try { fCurrent = EmbeddedImageImpl.create( new File( uriEditor.getText( ) .trim( ) ).getName( ), imageData ); BufferedInputStream bis = new BufferedInputStream( new URL( uriEditor.getText( ) .trim( ) ).openStream( ) ); ByteArrayOutputStream bos = new ByteArrayOutputStream( ); byte[] buf = new byte[1024]; int count = bis.read( buf ); while ( count != -1 ) { bos.write( buf, 0, count ); count = bis.read( buf ); } String data = new String( Base64.encodeBase64( bos.toByteArray( ) ) ); ( (EmbeddedImage) fCurrent ).setData( data ); } catch ( Exception e ) { WizardBase.displayException( e ); } break; } super.okPressed( ); } protected boolean initDialog( ) { getShell( ).setText( Messages.getString( "ImageDialog.label.SelectImage" ) ); //$NON-NLS-1$ initURIEditor( ); if ( fCurrent instanceof EmbeddedImage ) { embedded.setSelection( true ); selectedType = EMBEDDED_TYPE; } else {// initialize as URI mode by default uri.setSelection( true ); selectedType = URI_TYPE; } if ( selectedType == EMBEDDED_TYPE ) { title.setText( Messages.getString( "ImageDialog.label.EnterEmbed" ) ); //$NON-NLS-1$ } else { title.setText( Messages.getString( "ImageDialog.label.EnterURL" ) ); //$NON-NLS-1$ } getButton( IDialogConstants.OK_ID ).setEnabled( false ); browseButton.setVisible( embedded.getSelection( ) ); return true; } private void initURIEditor( ) { String uri = ""; //$NON-NLS-1$ if ( fCurrent instanceof Image ) { uri = ( (Image) fCurrent ).getURL( ); if ( fCurrent instanceof EmbeddedImage ) { imageData = ( (EmbeddedImage) fCurrent ).getData( ); } } uriEditor.setText( uri ); uriEditor.setFocus( ); // Listener will be called automatically clearPreview( ); } private void updateButtons( ) { boolean complete = uriEditor.getText( ) != null && uriEditor.getText( ).trim( ).length( ) > 0; URL url = null; try { url = new URL( uriEditor.getText( ).trim( ) ); if ( selectedType == EMBEDDED_TYPE ) { File file = new File( url.getPath( ) ); complete = file.exists( ) && file.isAbsolute( ); } } catch ( Exception e ) { complete = false; } previewButton.setEnabled( complete ); getButton( IDialogConstants.OK_ID ).setEnabled( complete ); browseButton.setVisible( embedded.getSelection( ) ); } /** * @return image model in the form of Fill */ public Fill getResult( ) { return fCurrent; } /** * Remove the quote if the string enclosed width quote . * * @param string * @return string */ public String removeQuote( String string ) { if ( string != null && string.length( ) >= 2 && string.startsWith( "\"" ) //$NON-NLS-1$ && string.endsWith( "\"" ) ) //$NON-NLS-1$ { return string.substring( 1, string.length( ) - 1 ); } return string; } }
chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/ImageDialog.java
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.chart.ui.swt.composites; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.net.URL; import org.apache.commons.codec.binary.Base64; import org.eclipse.birt.chart.model.attribute.EmbeddedImage; import org.eclipse.birt.chart.model.attribute.Fill; import org.eclipse.birt.chart.model.attribute.Image; import org.eclipse.birt.chart.model.attribute.impl.EmbeddedImageImpl; import org.eclipse.birt.chart.model.attribute.impl.ImageImpl; import org.eclipse.birt.chart.ui.extension.i18n.Messages; import org.eclipse.birt.chart.ui.util.ChartHelpContextIds; import org.eclipse.birt.chart.ui.util.ChartUIUtil; import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TrayDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * Dialog to build the image element. */ public class ImageDialog extends TrayDialog { final private static int URI_TYPE = 0; final private static int EMBEDDED_TYPE = 1; private Button embedded, uri, browseButton, previewButton; private Composite inputArea; private IconCanvas previewCanvas; private Text uriEditor; private int selectedType = -1; private Fill fCurrent; private String imageData; private Label title; /** * The constructor. * * @param parentShell */ public ImageDialog( Shell parentShell, Fill fCurrent ) { super( parentShell ); this.fCurrent = fCurrent; } protected Control createContents( Composite parent ) { Control ct = super.createContents( parent ); ChartUIUtil.bindHelp( parent, ChartHelpContextIds.DIALOG_COLOR_IMAGE ); initDialog( ); return ct; } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected Control createDialogArea( Composite parent ) { Composite topCompostie = (Composite) super.createDialogArea( parent ); createSelectionArea( topCompostie ); new Label( topCompostie, SWT.SEPARATOR | SWT.HORIZONTAL ).setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); Composite composite = new Composite( topCompostie, SWT.NONE ); composite.setLayout( new GridLayout( 2, false ) ); createInputArea( composite ); createPreviewArea( composite ); new Label( topCompostie, SWT.SEPARATOR | SWT.HORIZONTAL ).setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); return topCompostie; } private void createSelectionArea( Composite parent ) { Composite composite = new Composite( parent, SWT.NONE ); composite.setLayout( new GridLayout( 2, false ) ); composite.setLayoutData( new GridData( GridData.FILL_BOTH ) ); Label label = new Label( composite, SWT.NONE ); label.setText( Messages.getString( "ImageDialog.label.SelectImageType" ) ); //$NON-NLS-1$ label.setLayoutData( new GridData( GridData.VERTICAL_ALIGN_BEGINNING ) ); Composite selectionArea = new Composite( composite, SWT.NONE ); selectionArea.setLayout( new FillLayout( SWT.VERTICAL ) ); uri = new Button( selectionArea, SWT.RADIO ); uri.setText( Messages.getString( "ImageDialog.label.URLImage" ) ); //$NON-NLS-1$ uri.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { selectedType = URI_TYPE; title.setText( Messages.getString( "ImageDialog.label.EnterURL" ) ); //$NON-NLS-1$ updateButtons( ); } } ); embedded = new Button( selectionArea, SWT.RADIO ); embedded.setText( Messages.getString( "ImageDialog.label.EmbeddedImage" ) ); //$NON-NLS-1$ embedded.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { selectedType = EMBEDDED_TYPE; title.setText( Messages.getString( "ImageDialog.label.EnterEmbed" ) ); //$NON-NLS-1$ updateButtons( ); } } ); } private void createInputArea( Composite parent ) { inputArea = new Composite( parent, SWT.NONE ); GridData gd = new GridData( GridData.FILL_BOTH | GridData.HORIZONTAL_ALIGN_BEGINNING ); gd.widthHint = 300; gd.heightHint = 300; inputArea.setLayoutData( gd ); inputArea.setLayout( new GridLayout( ) ); title = new Label( inputArea, SWT.NONE ); title.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); uriEditor = new Text( inputArea, SWT.SINGLE | SWT.BORDER ); uriEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) ); uriEditor.addModifyListener( new ModifyListener( ) { public void modifyText( ModifyEvent e ) { updateButtons( ); } } ); Composite innerComp = new Composite( inputArea, SWT.NONE ); innerComp.setLayoutData( new GridData( GridData.HORIZONTAL_ALIGN_END ) ); innerComp.setLayout( new GridLayout( 2, false ) ); browseButton = new Button( innerComp, SWT.PUSH ); browseButton.setText( Messages.getString( "ImageDialog.label.Browse" ) ); //$NON-NLS-1$ browseButton.setLayoutData( new GridData( GridData.HORIZONTAL_ALIGN_END ) ); browseButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent event ) { FileDialog fileChooser = new FileDialog( getShell( ), SWT.OPEN ); fileChooser.setText( Messages.getString( "ImageDialog.label.SelectFile" ) ); //$NON-NLS-1$ fileChooser.setFilterExtensions( new String[]{ "*.gif", "*.jpg", "*.png" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } ); try { String fullPath = fileChooser.open( ); if ( fullPath != null ) { String fileName = fileChooser.getFileName( ); if ( fileName != null ) { imageData = null; fullPath = new StringBuffer( "file:///" ).append( fullPath ).toString( ); //$NON-NLS-1$ uriEditor.setText( fullPath ); } } } catch ( Throwable e ) { e.printStackTrace( ); } } } ); browseButton.setVisible( embedded.getSelection( ) ); previewButton = new Button( innerComp, SWT.PUSH ); previewButton.setText( Messages.getString( "ImageDialog.label.Preview" ) ); //$NON-NLS-1$ previewButton.setLayoutData( new GridData( GridData.HORIZONTAL_ALIGN_END ) ); previewButton.addSelectionListener( new SelectionAdapter( ) { public void widgetSelected( SelectionEvent e ) { preview( removeQuote( uriEditor.getText( ) ) ); } } ); } private void createPreviewArea( Composite composite ) { Composite previewArea = new Composite( composite, SWT.BORDER ); GridData gd = new GridData( GridData.FILL_BOTH ); gd.widthHint = 250; gd.heightHint = 300; previewArea.setLayoutData( gd ); previewArea.setLayout( new FillLayout( ) ); previewCanvas = new IconCanvas( previewArea ); } private void preview( String uri ) { try { if ( imageData != null ) { ByteArrayInputStream bis = new ByteArrayInputStream( Base64.decodeBase64( imageData.getBytes( ) ) ); previewCanvas.loadImage( bis ); } else { previewCanvas.loadImage( new URL( uri ) ); } } catch ( Exception e ) { WizardBase.displayException( e ); } } private void clearPreview( ) { previewCanvas.clear( ); } /* * (non-Javadoc) * * @see org.eclipse.jface.dialogs.Dialog#okPressed() */ protected void okPressed( ) { switch ( selectedType ) { case URI_TYPE : fCurrent = ImageImpl.create( removeQuote( uriEditor.getText( ).trim( ) ) ); break; case EMBEDDED_TYPE : try { fCurrent = EmbeddedImageImpl.create( new File( uriEditor.getText( ) .trim( ) ).getName( ), imageData ); BufferedInputStream bis = new BufferedInputStream( new URL( uriEditor.getText( ) .trim( ) ).openStream( ) ); ByteArrayOutputStream bos = new ByteArrayOutputStream( ); byte[] buf = new byte[1024]; int count = bis.read( buf ); while ( count != -1 ) { bos.write( buf, 0, count ); count = bis.read( buf ); } String data = new String( Base64.encodeBase64( bos.toByteArray( ) ) ); ( (EmbeddedImage) fCurrent ).setData( data ); } catch ( Exception e ) { WizardBase.displayException( e ); } break; } super.okPressed( ); } protected boolean initDialog( ) { getShell( ).setText( Messages.getString( "ImageDialog.label.SelectImage" ) ); //$NON-NLS-1$ initURIEditor( ); if ( fCurrent instanceof EmbeddedImage ) { embedded.setSelection( true ); selectedType = EMBEDDED_TYPE; } else {// initialize as URI mode by default uri.setSelection( true ); selectedType = URI_TYPE; } if ( selectedType == EMBEDDED_TYPE ) { title.setText( Messages.getString( "ImageDialog.label.EnterEmbed" ) ); //$NON-NLS-1$ } else { title.setText( Messages.getString( "ImageDialog.label.EnterURL" ) ); //$NON-NLS-1$ } getButton( IDialogConstants.OK_ID ).setEnabled( false ); browseButton.setVisible( embedded.getSelection( ) ); return true; } private void initURIEditor( ) { String uri = ""; //$NON-NLS-1$ if ( fCurrent instanceof Image ) { uri = ( (Image) fCurrent ).getURL( ); if ( fCurrent instanceof EmbeddedImage ) { imageData = ( (EmbeddedImage) fCurrent ).getData( ); } } uriEditor.setText( uri ); uriEditor.setFocus( ); // Listener will be called automatically clearPreview( ); } private void updateButtons( ) { boolean complete = uriEditor.getText( ) != null && uriEditor.getText( ).trim( ).length( ) > 0; previewButton.setEnabled( complete ); getButton( IDialogConstants.OK_ID ).setEnabled( complete ); browseButton.setVisible( embedded.getSelection( ) ); } /** * @return image model in the form of Fill */ public Fill getResult( ) { return fCurrent; } /** * Remove the quote if the string enclosed width quote . * * @param string * @return string */ public String removeQuote( String string ) { if ( string != null && string.length( ) >= 2 && string.startsWith( "\"" ) //$NON-NLS-1$ && string.endsWith( "\"" ) ) //$NON-NLS-1$ { return string.substring( 1, string.length( ) - 1 ); } return string; } }
Fix Bug#251048 on behalf of Xingsheng Zhu:Setting scatter chart background with embedded image doesn't work.
chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/ImageDialog.java
Fix Bug#251048 on behalf of Xingsheng Zhu:Setting scatter chart background with embedded image doesn't work.
<ide><path>hart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/ImageDialog.java <ide> { <ide> boolean complete = uriEditor.getText( ) != null <ide> && uriEditor.getText( ).trim( ).length( ) > 0; <add> URL url = null; <add> try <add> { <add> url = new URL( uriEditor.getText( ).trim( ) ); <add> if ( selectedType == EMBEDDED_TYPE ) <add> { <add> File file = new File( url.getPath( ) ); <add> complete = file.exists( ) && file.isAbsolute( ); <add> } <add> } <add> catch ( Exception e ) <add> { <add> complete = false; <add> } <add> <ide> previewButton.setEnabled( complete ); <ide> getButton( IDialogConstants.OK_ID ).setEnabled( complete ); <ide> browseButton.setVisible( embedded.getSelection( ) );
Java
apache-2.0
f0b97ba8ca24a470b2ba010a139da8fa1b8a6a58
0
tbroyer/gwt-maven-plugin,tbroyer/gwt-maven-plugin
package net.ltgt.gwt.maven; import java.io.File; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.surefire.AbstractSurefireMojo; import org.apache.maven.plugin.surefire.SurefireHelper; import org.apache.maven.plugin.surefire.SurefireReportParameters; import org.apache.maven.plugin.surefire.booterclient.ChecksumCalculator; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.surefire.suite.RunResult; /** * Runs the project's tests with the specific setup needed for {@code GWTTestCase} tests. */ @Mojo(name = "test", defaultPhase = LifecyclePhase.TEST, threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST) public class TestMojo extends AbstractSurefireMojo implements SurefireReportParameters, GwtOptions { // GWT-specific properties /** * Specifies the TCP port for the embedded web server (defaults to automatically picking an available port) */ @Parameter(property = "gwt.port") private int port; /** * Specifies the TCP port for the code server (defaults to automatically picking an available port) */ @Parameter(property = "gwt.codeServerPort") private int codeServerPort; /** * The directory into which deployable but not servable output files will be written. */ @Parameter(defaultValue = "${project.build.directory}/gwt-tests/deploy", required = true) private File deploy; /** * The directory into which extra files, not intended for deployment, will be written. */ @Parameter private File extra; /** * The compiler work directory (must be writeable). */ @Parameter(defaultValue = "${project.build.directory}/gwt/work", required = true) private File workDir; /** * Script output style: OBFUSCATED, PRETTY, or DETAILED. */ @Parameter(property = "gwt.style") private String style; /** * Compile quickly with minimal optimizations. */ @Parameter(property = "gwt.draftCompile", defaultValue = "false") private boolean draftCompile; /** * The number of local workers to use when compiling permutations. When terminated * with "C", the number part is multiplied with the number of CPU cores. Floating * point values are only accepted together with "C". */ @Parameter(property = "gwt.localWorkers") private String localWorkers; /** * Sets the level of logging detail. */ @Parameter(property = "gwt.logLevel") private String logLevel; /** * Sets the optimization level used by the compiler. 0=none 9=maximum. */ @Parameter(property = "gwt.optimize") private Integer optimize; /** * Specifies Java source level. */ @Parameter(property = "maven.compiler.source") private String sourceLevel; /** * The directory to write output files into. */ @Parameter(defaultValue = "${project.build.directory}/gwt-tests/www", required = true) private File outDir; /** * Additional arguments to be passed to the GWT compiler. */ @Parameter private List<String> compilerArgs; /** * Additional arguments to be passed to the JUnitShell. */ @Parameter private List<String> testArgs; /** * Whether to prepend {@code #compilerArgs} to {@link #testArgs}. * <p> * This allows reuse when the {@code #compilerArgs} aren't incompatible with JUnitShell. */ @Parameter(defaultValue = "false") private boolean useCompilerArgsForTests; @Override public Map<String, String> getSystemPropertyVariables() { Map<String, String> props = super.getSystemPropertyVariables(); if (props == null) { props = new HashMap<>(2); } if (!props.containsKey("gwt.args")) { StringBuilder sb = new StringBuilder(); if (port > 0) { sb.append(" -port ").append(port); } if (codeServerPort > 0) { sb.append(" -codeServerPort ").append(codeServerPort); } for (String arg : CommandlineBuilder.buildArgs(getLog(), this)) { sb.append(" ").append(quote(arg)); } sb.append(effectiveIsEnableAssertions() ? " -checkAssertions" : " -nocheckAssertions"); if (useCompilerArgsForTests && compilerArgs != null) { for (String arg : compilerArgs) { sb.append(" ").append(quote(arg)); } } if (testArgs != null) { for (String arg : testArgs) { sb.append(" ").append(quote(arg)); } } props.put("gwt.args", sb.toString()); } if (getLog().isDebugEnabled()) { getLog().debug("Using gwt.args: " + props.get("gwt.args")); } return props; } private Object quote(String value) { if (value.matches(".*[\"\\s].*")) { return "\"" + value.replace("\"", "\\\"") + "\""; } return value; } @Override public void setSystemPropertyVariables(Map<String, String> systemPropertyVariables) { if (systemPropertyVariables.containsKey("gwt.args")) { getLog().warn("systemPropertyVariables contains a gwt.args value, this will override all individual options"); } super.setSystemPropertyVariables(systemPropertyVariables); } @Override protected void addPluginSpecificChecksumItems(ChecksumCalculator checksum) { checksum.add(port); checksum.add(codeServerPort); checksum.add(deploy); checksum.add(extra); checksum.add(workDir); checksum.add(style); checksum.add(draftCompile); checksum.add(localWorkers); checksum.add(sourceLevel); checksum.add(testArgs); checksum.add(useCompilerArgsForTests); if (useCompilerArgsForTests) { checksum.add(compilerArgs); } } private String[] computedAdditionalClasspathElements; @Override public String[] getAdditionalClasspathElements() { if (computedAdditionalClasspathElements == null) { List<Resource> resources = new ArrayList<>(); resources.addAll(getProject().getResources()); resources.addAll(getProject().getTestResources()); List<String> sourceRoots = new ArrayList<>(); sourceRoots.addAll(getProject().getCompileSourceRoots()); sourceRoots.addAll(getProject().getTestCompileSourceRoots()); List<String> filteredSourceRoots = SourcesAsResourcesHelper.filterSourceRoots(getLog(), resources, sourceRoots); filteredSourceRoots.addAll(Arrays.asList(super.getAdditionalClasspathElements())); computedAdditionalClasspathElements = sourceRoots.toArray(new String[filteredSourceRoots.size()]); } return computedAdditionalClasspathElements; } // Properties copied from Surefire /** * The directory containing generated classes of the project being tested. This will be included after the test * classes in the test classpath. */ @Parameter(defaultValue = "${project.build.outputDirectory}") private File classesDirectory; /** * Set this to "true" to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on * occasion. */ @Parameter(property = "maven.test.failure.ignore", defaultValue = "false") private boolean testFailureIgnore; /** * Base directory where all reports are written to. */ @Parameter(defaultValue = "${project.build.directory}/surefire-reports") private File reportsDirectory; /** * Specify this parameter to run individual tests by file name, overriding the <code>includes/excludes</code> * parameters. Each pattern you specify here will be used to create an include pattern formatted like * <code>**&#47;${test}.java</code>, so you can just type "-Dtest=MyTest" to run a single test called * "foo/MyTest.java". The test patterns prefixed with a <code>!</code> will be excluded.<br/> * This parameter overrides the <code>includes/excludes</code> parameters, and the TestNG <code>suiteXmlFiles</code> * parameter. * <p/> * Since 2.7.3, you can execute a limited number of methods in the test by adding #myMethod or #my*ethod. For * example, "-Dtest=MyTest#myMethod". This is supported for junit 4.x and testNg.<br/> * <br/> * Since 2.19 a complex syntax is supported in one parameter (JUnit 4, JUnit 4.7+, TestNG):<br/> * "-Dtest=???Test, !Unstable*, pkg&#47;**&#47;Ci*leTest.java, *Test#test*One+testTwo?????, #fast*+slowTest"<br/> * "-Dtest=Basic*, !%regex[.*.Unstable.*], !%regex[.*.MyTest.class#one.*|two.*], %regex[#fast.*|slow.*]"<br/> * <br/> * The Parameterized JUnit runner <em>describes</em> test methods using an index in brackets, so the non-regex * method pattern would become: <em>#testMethod[*]</em>. If using <em>@Parameters(name="{index}: fib({0})={1}")</em> * and selecting the index e.g. 5 in pattern, the non-regex method pattern would become <em>#testMethod[5:*]</em>. * <br/> */ @Parameter(property = "test") private String test; /** * Option to print summary of test suites or just print the test cases that have errors. */ @Parameter(property = "surefire.printSummary", defaultValue = "true") private boolean printSummary; /** * Selects the formatting for the test report to be generated. Can be set as "brief" or "plain". * Only applies to the output format of the output files (target/surefire-reports/testName.txt) */ @Parameter(property = "surefire.reportFormat", defaultValue = "brief") private String reportFormat; /** * Option to generate a file test report or just output the test report to the console. */ @Parameter(property = "surefire.useFile", defaultValue = "true") private boolean useFile; /** * Set this to "true" to cause a failure if the none of the tests specified in -Dtest=... are run. Defaults to * "true". */ @Parameter(property = "surefire.failIfNoSpecifiedTests") private Boolean failIfNoSpecifiedTests; /** * Attach a debugger to the forked JVM. If set to "true", the process will suspend and wait for a debugger to attach * on port 5005. If set to some other string, that string will be appended to the argLine, allowing you to configure * arbitrary debuggability options (without overwriting the other options specified through the <code>argLine</code> * parameter). */ @Parameter(property = "maven.surefire.debug") private String debugForkedProcess; /** * Kill the forked test process after a certain number of seconds. If set to 0, wait forever for the process, never * timing out. */ @Parameter(property = "surefire.timeout") private int forkedProcessTimeoutInSeconds; /** * Forked process is normally terminated without any significant delay after given tests have completed. * If the particular tests started non-daemon Thread(s), the process hangs instead of been properly terminated * by <em>System.exit()</em>. Use this parameter in order to determine the timeout of terminating the process. * <a href="http://maven.apache.org/surefire/maven-surefire-plugin/examples/shutdown.html">see the documentation: * http://maven.apache.org/surefire/maven-surefire-plugin/examples/shutdown.html</a> * Turns to default fallback value of 30 seconds if negative integer. */ @Parameter(property = "surefire.exitTimeout", defaultValue = "30") private int forkedProcessExitTimeoutInSeconds; /** * Stop executing queued parallel JUnit tests after a certain number of seconds. * <br/> * Example values: "3.5", "4"<br/> * <br/> * If set to 0, wait forever, never timing out. * Makes sense with specified <code>parallel</code> different from "none". */ @Parameter(property = "surefire.parallel.timeout") private double parallelTestsTimeoutInSeconds; /** * Stop executing queued parallel JUnit tests * and <em>interrupt</em> currently running tests after a certain number of seconds. * <br/> * Example values: "3.5", "4"<br/> * <br/> * If set to 0, wait forever, never timing out. * Makes sense with specified <code>parallel</code> different from "none". */ @Parameter(property = "surefire.parallel.forcedTimeout") private double parallelTestsTimeoutForcedInSeconds; /** * A list of &lt;include> elements specifying the tests (by pattern) that should be included in testing. When not * specified and when the <code>test</code> parameter is not specified, the default includes will be <code><br/> * &lt;includes><br/> * &nbsp;&lt;include>**&#47;*Suite.java&lt;/include><br/> * &nbsp;&lt;include>**&#47;*SuiteNoBrowser.java&lt;/include><br/> * &lt;/includes><br/> * </code> * <p/> * Each include item may also contain a comma-separated sublist of items, which will be treated as multiple * &nbsp;&lt;include> entries.<br/> * Since 2.19 a complex syntax is supported in one parameter (JUnit 4, JUnit 4.7+, TestNG):<br/> * &nbsp;&lt;include>%regex[.*[Cat|Dog].*], Basic????, !Unstable*&lt;/include><br/> * &nbsp;&lt;include>%regex[.*[Cat|Dog].*], !%regex[pkg.*Slow.*.class], pkg&#47;**&#47;*Fast*.java&lt;/include><br/> * <p/> * This parameter is ignored if the TestNG <code>suiteXmlFiles</code> parameter is specified.<br/> * <br/> * <em>Notice that</em> these values are relative to the directory containing generated test classes of the project * being tested. This directory is declared by the parameter <code>testClassesDirectory</code> which defaults * to the POM property <code>${project.build.testOutputDirectory}</code>, typically <em>src/test/java</em> * unless overridden. */ @Parameter private List<String> includes; /** * (JUnit 4+ providers) * The number of times each failing test will be rerun. If set larger than 0, rerun failing tests immediately after * they fail. If a failing test passes in any of those reruns, it will be marked as pass and reported as a "flake". * However, all the failing attempts will be recorded. */ @Parameter(property = "surefire.rerunFailingTestsCount", defaultValue = "0") private int rerunFailingTestsCount; /** * (TestNG) List of &lt;suiteXmlFile> elements specifying TestNG suite xml file locations. Note that * <code>suiteXmlFiles</code> is incompatible with several other parameters of this plugin, like * <code>includes/excludes</code>.<br/> * This parameter is ignored if the <code>test</code> parameter is specified (allowing you to run a single test * instead of an entire suite). */ @Parameter(property = "surefire.suiteXmlFiles") private File[] suiteXmlFiles; /** * Defines the order the tests will be run in. Supported values are "alphabetical", "reversealphabetical", "random", * "hourly" (alphabetical on even hours, reverse alphabetical on odd hours), "failedfirst", "balanced" and * "filesystem". * <br/> * <br/> * Odd/Even for hourly is determined at the time the of scanning the classpath, meaning it could change during a * multi-module build. * <br/> * <br/> * Failed first will run tests that failed on previous run first, as well as new tests for this run. * <br/> * <br/> * Balanced is only relevant with parallel=classes, and will try to optimize the run-order of the tests reducing the * overall execution time. Initially a statistics file is created and every next test run will reorder classes. * <br/> * <br/> * Note that the statistics are stored in a file named .surefire-XXXXXXXXX beside pom.xml, and should not be checked * into version control. The "XXXXX" is the SHA1 checksum of the entire surefire configuration, so different * configurations will have different statistics files, meaning if you change any config settings you will re-run * once before new statistics data can be established. */ @Parameter(property = "surefire.runOrder", defaultValue = "filesystem") private String runOrder; /** * A file containing include patterns. Blank lines, or lines starting with # are ignored. If {@code includes} are * also specified, these patterns are appended. Example with path, simple and regex includes:<br/> * &#042;&#047;test/*<br/> * &#042;&#042;&#047;NotIncludedByDefault.java<br/> * %regex[.*Test.*|.*Not.*]<br/> */ @Parameter(property = "surefire.includesFile") private File includesFile; /** * A file containing exclude patterns. Blank lines, or lines starting with # are ignored. If {@code excludes} are * also specified, these patterns are appended. Example with path, simple and regex excludes:<br/> * &#042;&#047;test/*<br/> * &#042;&#042;&#047;DontRunTest.*<br/> * %regex[.*Test.*|.*Not.*]<br/> */ @Parameter(property = "surefire.excludesFile") private File excludesFile; /** * Set to error/failure count in order to skip remaining tests. * Due to race conditions in parallel/forked execution this may not be fully guaranteed.<br/> * Enable with system property -Dsurefire.skipAfterFailureCount=1 or any number greater than zero. * Defaults to "0".<br/> * See the prerequisites and limitations in documentation:<br/> * <a href="http://maven.apache.org/plugins/maven-surefire-plugin/examples/skip-after-failure.html"> * http://maven.apache.org/plugins/maven-surefire-plugin/examples/skip-after-failure.html</a> */ @Parameter(property = "surefire.skipAfterFailureCount", defaultValue = "0") private int skipAfterFailureCount; /** * After the plugin process is shutdown by sending SIGTERM signal (CTRL+C), SHUTDOWN command is received by every * forked JVM. By default (shutdown=testset) forked JVM would not continue with new test which means that * the current test may still continue to run.<br/> * The parameter can be configured with other two values "exit" and "kill".<br/> * Using "exit" forked JVM executes System.exit(1) after the plugin process has received SIGTERM signal.<br/> * Using "kill" the JVM executes Runtime.halt(1) and kills itself. */ @Parameter(property = "surefire.shutdown", defaultValue = "testset") private String shutdown; @Override public int getRerunFailingTestsCount() { return rerunFailingTestsCount; } @Override protected void handleSummary(RunResult summary, Exception firstForkException) throws MojoExecutionException, MojoFailureException { SurefireHelper.reportExecution(this, summary, getConsoleLogger(), firstForkException); } @Override public void execute() throws MojoExecutionException, MojoFailureException { if (!isSkipExecution()) { // let super.execute() handle the isSkipExecution case if (!isForking()) { getConsoleLogger().warning("ForkCount=0 is known not to work for GWT tests"); } } super.execute(); } @Override protected boolean isSkipExecution() { return isSkip() || isSkipTests() || isSkipExec(); } @Override protected String getPluginName() { return "GWT tests"; } @Override protected String[] getDefaultIncludes() { return new String[] {"**/*Suite.java", "**/*SuiteNoBrowser.java"}; } @Override public List<String> getIncludes() { return includes; } @Override public void setIncludes(List<String> includes) { this.includes = includes; } @Override protected String getReportSchemaLocation() { return "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report.xsd"; } @Override protected Artifact getMojoArtifact() { final Map<String, Artifact> pluginArtifactMap = getPluginArtifactMap(); return pluginArtifactMap.get("net.ltgt.gwt.maven:gwt-maven-plugin" ); } // @Override public boolean isSkipTests() { return skipTests; } @Override public void setSkipTests(boolean skipTests) { this.skipTests = skipTests; } @Override @SuppressWarnings("deprecation") public boolean isSkipExec() { return skipExec; } @Override @SuppressWarnings("deprecation") public void setSkipExec(boolean skipExec) { this.skipExec = skipExec; } @Override public boolean isSkip() { return skip; } @Override public void setSkip(boolean skip) { this.skip = skip; } @Override public File getBasedir() { return basedir; } @Override public void setBasedir(File basedir) { this.basedir = basedir; } @Override public File getTestClassesDirectory() { return testClassesDirectory; } @Override public void setTestClassesDirectory(File testClassesDirectory) { this.testClassesDirectory = testClassesDirectory; } @Override public File getClassesDirectory() { return classesDirectory; } @Override public void setClassesDirectory(File classesDirectory) { this.classesDirectory = classesDirectory; } @Override public File getReportsDirectory() { return reportsDirectory; } @Override public void setReportsDirectory(File reportsDirectory) { this.reportsDirectory = reportsDirectory; } @Override public String getTest() { return test; } @Override public void setTest(String test) { this.test = test; } @Override public int getSkipAfterFailureCount() { return skipAfterFailureCount; } @Override public String getShutdown() { return shutdown; } @Override public boolean isPrintSummary() { return printSummary; } @Override public void setPrintSummary(boolean printSummary) { this.printSummary = printSummary; } @Override public String getReportFormat() { return reportFormat; } @Override public void setReportFormat(String reportFormat) { this.reportFormat = reportFormat; } @Override public boolean isUseFile() { return useFile; } @Override public void setUseFile(boolean useFile) { this.useFile = useFile; } @Override public String getDebugForkedProcess() { return debugForkedProcess; } @Override public void setDebugForkedProcess(String debugForkedProcess) { this.debugForkedProcess = debugForkedProcess; } @Override public int getForkedProcessTimeoutInSeconds() { return forkedProcessTimeoutInSeconds; } @Override public void setForkedProcessTimeoutInSeconds(int forkedProcessTimeoutInSeconds) { this.forkedProcessTimeoutInSeconds = forkedProcessTimeoutInSeconds; } @Override public int getForkedProcessExitTimeoutInSeconds() { return forkedProcessExitTimeoutInSeconds; } @Override public void setForkedProcessExitTimeoutInSeconds(int forkedProcessExitTimeoutInSeconds) { this.forkedProcessExitTimeoutInSeconds = forkedProcessExitTimeoutInSeconds; } @Override public boolean isUseSystemClassLoader() { // GWTTestCase must use system class-loader return true; } @Override public void setUseSystemClassLoader(boolean useSystemClassLoader) { throw new UnsupportedOperationException("useSystemClassLoader is read-only"); } @Override public boolean isUseManifestOnlyJar() { // GWTTestCase must not use manifest-only JAR return false; } @Override public void setUseManifestOnlyJar(boolean useManifestOnlyJar) { throw new UnsupportedOperationException("useManifestOnlyJar is read-only"); } @Override public Boolean getFailIfNoSpecifiedTests() { return failIfNoSpecifiedTests; } @Override public void setFailIfNoSpecifiedTests(boolean failIfNoSpecifiedTests) { this.failIfNoSpecifiedTests = failIfNoSpecifiedTests; } @Override public boolean isTestFailureIgnore() { return testFailureIgnore; } @Override public void setTestFailureIgnore(boolean testFailureIgnore) { this.testFailureIgnore = testFailureIgnore; } @Override public double getParallelTestsTimeoutInSeconds() { return parallelTestsTimeoutInSeconds; } @Override public void setParallelTestsTimeoutInSeconds(double parallelTestsTimeoutInSeconds) { this.parallelTestsTimeoutInSeconds = parallelTestsTimeoutInSeconds; } @Override public double getParallelTestsTimeoutForcedInSeconds() { return parallelTestsTimeoutForcedInSeconds; } @Override public void setParallelTestsTimeoutForcedInSeconds(double parallelTestsTimeoutForcedInSeconds) { this.parallelTestsTimeoutForcedInSeconds = parallelTestsTimeoutForcedInSeconds; } @Override public File[] getSuiteXmlFiles() { return suiteXmlFiles.clone(); } @Override public void setSuiteXmlFiles(File[] suiteXmlFiles) { this.suiteXmlFiles = suiteXmlFiles.clone(); } @Override public String getRunOrder() { return runOrder; } @Override public void setRunOrder(String runOrder) { this.runOrder = runOrder; } @Override public File getIncludesFile() { return includesFile; } @Override public File getExcludesFile() { return excludesFile; } @Override protected List<File> suiteXmlFiles() { return hasSuiteXmlFiles() ? Arrays.asList( suiteXmlFiles ) : Collections.<File>emptyList(); } @Override protected boolean hasSuiteXmlFiles() { return suiteXmlFiles != null && suiteXmlFiles.length != 0; } // GwtOptions @Nullable @Override public String getLogLevel() { return logLevel; } @Nullable @Override public String getStyle() { return style; } @Nullable @Override public Integer getOptimize() { return optimize; } @Override public File getWarDir() { return outDir; } @Override public File getWorkDir() { return workDir; } @Override public File getDeployDir() { return deploy; } @Nullable @Override public File getExtraDir() { return extra; } @Override public boolean isDraftCompile() { return draftCompile; } @Nullable @Override public String getLocalWorkers() { return localWorkers; } @Nullable @Override public String getSourceLevel() { return sourceLevel; } }
src/main/java/net/ltgt/gwt/maven/TestMojo.java
package net.ltgt.gwt.maven; import java.io.File; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Resource; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.surefire.AbstractSurefireMojo; import org.apache.maven.plugin.surefire.SurefireHelper; import org.apache.maven.plugin.surefire.SurefireReportParameters; import org.apache.maven.plugin.surefire.booterclient.ChecksumCalculator; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.surefire.suite.RunResult; /** * Runs the project's tests with the specific setup needed for {@code GWTTestCase} tests. */ @Mojo(name = "test", defaultPhase = LifecyclePhase.TEST, threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST) public class TestMojo extends AbstractSurefireMojo implements SurefireReportParameters, GwtOptions { // GWT-specific properties /** * Specifies the TCP port for the embedded web server (defaults to automatically picking an available port) */ @Parameter(property = "gwt.port") private int port; /** * Specifies the TCP port for the code server (defaults to automatically picking an available port) */ @Parameter(property = "gwt.codeServerPort") private int codeServerPort; /** * The directory into which deployable but not servable output files will be written. */ @Parameter(defaultValue = "${project.build.directory}/gwt-tests/deploy", required = true) private File deploy; /** * The directory into which extra files, not intended for deployment, will be written. */ @Parameter private File extra; /** * The compiler work directory (must be writeable). */ @Parameter(defaultValue = "${project.build.directory}/gwt/work", required = true) private File workDir; /** * Script output style: OBFUSCATED, PRETTY, or DETAILED. */ @Parameter(property = "gwt.style") private String style; /** * Compile quickly with minimal optimizations. */ @Parameter(property = "gwt.draftCompile", defaultValue = "false") private boolean draftCompile; /** * The number of local workers to use when compiling permutations. When terminated * with "C", the number part is multiplied with the number of CPU cores. Floating * point values are only accepted together with "C". */ @Parameter(property = "gwt.localWorkers") private String localWorkers; /** * Sets the level of logging detail. */ @Parameter(property = "gwt.logLevel") private String logLevel; /** * Sets the optimization level used by the compiler. 0=none 9=maximum. */ @Parameter(property = "gwt.optimize") private Integer optimize; /** * Specifies Java source level. */ @Parameter(property = "maven.compiler.source") private String sourceLevel; /** * The directory to write output files into. */ @Parameter(defaultValue = "${project.build.directory}/gwt-tests/www", required = true) private File outDir; /** * Additional arguments to be passed to the GWT compiler. */ @Parameter private List<String> compilerArgs; /** * Additional arguments to be passed to the JUnitShell. */ @Parameter private List<String> testArgs; /** * Whether to prepend {@code #compilerArgs} to {@link #testArgs}. * <p> * This allows reuse when the {@code #compilerArgs} aren't incompatible with JUnitShell. */ @Parameter(defaultValue = "false") private boolean useCompilerArgsForTests; @Override public Map<String, String> getSystemPropertyVariables() { Map<String, String> props = super.getSystemPropertyVariables(); if (props == null) { props = new HashMap<>(2); } if (!props.containsKey("gwt.args")) { StringBuilder sb = new StringBuilder(); if (port > 0) { sb.append(" -port ").append(port); } if (codeServerPort > 0) { sb.append(" -codeServerPort ").append(codeServerPort); } for (String arg : CommandlineBuilder.buildArgs(getLog(), this)) { sb.append(" ").append(quote(arg)); } sb.append(effectiveIsEnableAssertions() ? " -checkAssertions" : " -nocheckAssertions"); if (useCompilerArgsForTests && compilerArgs != null) { for (String arg : compilerArgs) { sb.append(" ").append(quote(arg)); } } if (testArgs != null) { for (String arg : testArgs) { sb.append(" ").append(quote(arg)); } } props.put("gwt.args", sb.toString()); } if (getLog().isDebugEnabled()) { getLog().debug("Using gwt.args: " + props.get("gwt.args")); } return props; } private Object quote(String value) { if (value.matches(".*[\"\\s].*")) { return "\"" + value.replace("\"", "\\\"") + "\""; } return value; } @Override public void setSystemPropertyVariables(Map<String, String> systemPropertyVariables) { if (systemPropertyVariables.containsKey("gwt.args")) { getLog().warn("systemPropertyVariables contains a gwt.args value, this will override all individual options"); } super.setSystemPropertyVariables(systemPropertyVariables); } @Override protected void addPluginSpecificChecksumItems(ChecksumCalculator checksum) { checksum.add(port); checksum.add(codeServerPort); checksum.add(deploy); checksum.add(extra); checksum.add(workDir); checksum.add(style); checksum.add(draftCompile); checksum.add(localWorkers); checksum.add(sourceLevel); checksum.add(testArgs); checksum.add(useCompilerArgsForTests); if (useCompilerArgsForTests) { checksum.add(compilerArgs); } } private String[] computedAdditionalClasspathElements; @Override public String[] getAdditionalClasspathElements() { if (computedAdditionalClasspathElements == null) { List<Resource> resources = new ArrayList<>(); resources.addAll(getProject().getResources()); resources.addAll(getProject().getTestResources()); List<String> sourceRoots = new ArrayList<>(); sourceRoots.addAll(getProject().getCompileSourceRoots()); sourceRoots.addAll(getProject().getTestCompileSourceRoots()); List<String> filteredSourceRoots = SourcesAsResourcesHelper.filterSourceRoots(getLog(), resources, sourceRoots); filteredSourceRoots.addAll(Arrays.asList(super.getAdditionalClasspathElements())); computedAdditionalClasspathElements = sourceRoots.toArray(new String[filteredSourceRoots.size()]); } return computedAdditionalClasspathElements; } // Properties copied from Surefire /** * The directory containing generated classes of the project being tested. This will be included after the test * classes in the test classpath. */ @Parameter(defaultValue = "${project.build.outputDirectory}") private File classesDirectory; /** * Set this to "true" to ignore a failure during testing. Its use is NOT RECOMMENDED, but quite convenient on * occasion. */ @Parameter(property = "maven.test.failure.ignore", defaultValue = "false") private boolean testFailureIgnore; /** * Base directory where all reports are written to. */ @Parameter(defaultValue = "${project.build.directory}/surefire-reports") private File reportsDirectory; /** * Specify this parameter to run individual tests by file name, overriding the <code>includes/excludes</code> * parameters. Each pattern you specify here will be used to create an include pattern formatted like * <code>**&#47;${test}.java</code>, so you can just type "-Dtest=MyTest" to run a single test called * "foo/MyTest.java". The test patterns prefixed with a <code>!</code> will be excluded.<br/> * This parameter overrides the <code>includes/excludes</code> parameters, and the TestNG <code>suiteXmlFiles</code> * parameter. * <p/> * Since 2.7.3, you can execute a limited number of methods in the test by adding #myMethod or #my*ethod. For * example, "-Dtest=MyTest#myMethod". This is supported for junit 4.x and testNg.<br/> * <br/> * Since 2.19 a complex syntax is supported in one parameter (JUnit 4, JUnit 4.7+, TestNG):<br/> * "-Dtest=???Test, !Unstable*, pkg&#47;**&#47;Ci*leTest.java, *Test#test*One+testTwo?????, #fast*+slowTest"<br/> * "-Dtest=Basic*, !%regex[.*.Unstable.*], !%regex[.*.MyTest.class#one.*|two.*], %regex[#fast.*|slow.*]"<br/> * <br/> * The Parameterized JUnit runner <em>describes</em> test methods using an index in brackets, so the non-regex * method pattern would become: <em>#testMethod[*]</em>. If using <em>@Parameters(name="{index}: fib({0})={1}")</em> * and selecting the index e.g. 5 in pattern, the non-regex method pattern would become <em>#testMethod[5:*]</em>. * <br/> */ @Parameter(property = "test") private String test; /** * Option to print summary of test suites or just print the test cases that have errors. */ @Parameter(property = "surefire.printSummary", defaultValue = "true") private boolean printSummary; /** * Selects the formatting for the test report to be generated. Can be set as "brief" or "plain". * Only applies to the output format of the output files (target/surefire-reports/testName.txt) */ @Parameter(property = "surefire.reportFormat", defaultValue = "brief") private String reportFormat; /** * Option to generate a file test report or just output the test report to the console. */ @Parameter(property = "surefire.useFile", defaultValue = "true") private boolean useFile; /** * Set this to "true" to cause a failure if the none of the tests specified in -Dtest=... are run. Defaults to * "true". */ @Parameter(property = "surefire.failIfNoSpecifiedTests") private Boolean failIfNoSpecifiedTests; /** * Attach a debugger to the forked JVM. If set to "true", the process will suspend and wait for a debugger to attach * on port 5005. If set to some other string, that string will be appended to the argLine, allowing you to configure * arbitrary debuggability options (without overwriting the other options specified through the <code>argLine</code> * parameter). */ @Parameter(property = "maven.surefire.debug") private String debugForkedProcess; /** * Kill the forked test process after a certain number of seconds. If set to 0, wait forever for the process, never * timing out. */ @Parameter(property = "surefire.timeout") private int forkedProcessTimeoutInSeconds; /** * Forked process is normally terminated without any significant delay after given tests have completed. * If the particular tests started non-daemon Thread(s), the process hangs instead of been properly terminated * by <em>System.exit()</em>. Use this parameter in order to determine the timeout of terminating the process. * <a href="http://maven.apache.org/surefire/maven-surefire-plugin/examples/shutdown.html">see the documentation: * http://maven.apache.org/surefire/maven-surefire-plugin/examples/shutdown.html</a> * Turns to default fallback value of 30 seconds if negative integer. */ @Parameter(property = "surefire.exitTimeout", defaultValue = "30") private int forkedProcessExitTimeoutInSeconds; /** * Stop executing queued parallel JUnit tests after a certain number of seconds. * <br/> * Example values: "3.5", "4"<br/> * <br/> * If set to 0, wait forever, never timing out. * Makes sense with specified <code>parallel</code> different from "none". */ @Parameter(property = "surefire.parallel.timeout") private double parallelTestsTimeoutInSeconds; /** * Stop executing queued parallel JUnit tests * and <em>interrupt</em> currently running tests after a certain number of seconds. * <br/> * Example values: "3.5", "4"<br/> * <br/> * If set to 0, wait forever, never timing out. * Makes sense with specified <code>parallel</code> different from "none". */ @Parameter(property = "surefire.parallel.forcedTimeout") private double parallelTestsTimeoutForcedInSeconds; /** * A list of &lt;include> elements specifying the tests (by pattern) that should be included in testing. When not * specified and when the <code>test</code> parameter is not specified, the default includes will be <code><br/> * &lt;includes><br/> * &nbsp;&lt;include>**&#47;Test*.java&lt;/include><br/> * &nbsp;&lt;include>**&#47;*Test.java&lt;/include><br/> * &nbsp;&lt;include>**&#47;*Tests.java&lt;/include><br/> * &nbsp;&lt;include>**&#47;*TestCase.java&lt;/include><br/> * &lt;/includes><br/> * </code> * <p/> * Each include item may also contain a comma-separated sublist of items, which will be treated as multiple * &nbsp;&lt;include> entries.<br/> * Since 2.19 a complex syntax is supported in one parameter (JUnit 4, JUnit 4.7+, TestNG):<br/> * &nbsp;&lt;include>%regex[.*[Cat|Dog].*], Basic????, !Unstable*&lt;/include><br/> * &nbsp;&lt;include>%regex[.*[Cat|Dog].*], !%regex[pkg.*Slow.*.class], pkg&#47;**&#47;*Fast*.java&lt;/include><br/> * <p/> * This parameter is ignored if the TestNG <code>suiteXmlFiles</code> parameter is specified.<br/> * <br/> * <em>Notice that</em> these values are relative to the directory containing generated test classes of the project * being tested. This directory is declared by the parameter <code>testClassesDirectory</code> which defaults * to the POM property <code>${project.build.testOutputDirectory}</code>, typically <em>src/test/java</em> * unless overridden. */ @Parameter private List<String> includes; /** * (JUnit 4+ providers) * The number of times each failing test will be rerun. If set larger than 0, rerun failing tests immediately after * they fail. If a failing test passes in any of those reruns, it will be marked as pass and reported as a "flake". * However, all the failing attempts will be recorded. */ @Parameter(property = "surefire.rerunFailingTestsCount", defaultValue = "0") private int rerunFailingTestsCount; /** * (TestNG) List of &lt;suiteXmlFile> elements specifying TestNG suite xml file locations. Note that * <code>suiteXmlFiles</code> is incompatible with several other parameters of this plugin, like * <code>includes/excludes</code>.<br/> * This parameter is ignored if the <code>test</code> parameter is specified (allowing you to run a single test * instead of an entire suite). */ @Parameter(property = "surefire.suiteXmlFiles") private File[] suiteXmlFiles; /** * Defines the order the tests will be run in. Supported values are "alphabetical", "reversealphabetical", "random", * "hourly" (alphabetical on even hours, reverse alphabetical on odd hours), "failedfirst", "balanced" and * "filesystem". * <br/> * <br/> * Odd/Even for hourly is determined at the time the of scanning the classpath, meaning it could change during a * multi-module build. * <br/> * <br/> * Failed first will run tests that failed on previous run first, as well as new tests for this run. * <br/> * <br/> * Balanced is only relevant with parallel=classes, and will try to optimize the run-order of the tests reducing the * overall execution time. Initially a statistics file is created and every next test run will reorder classes. * <br/> * <br/> * Note that the statistics are stored in a file named .surefire-XXXXXXXXX beside pom.xml, and should not be checked * into version control. The "XXXXX" is the SHA1 checksum of the entire surefire configuration, so different * configurations will have different statistics files, meaning if you change any config settings you will re-run * once before new statistics data can be established. */ @Parameter(property = "surefire.runOrder", defaultValue = "filesystem") private String runOrder; /** * A file containing include patterns. Blank lines, or lines starting with # are ignored. If {@code includes} are * also specified, these patterns are appended. Example with path, simple and regex includes:<br/> * &#042;&#047;test/*<br/> * &#042;&#042;&#047;NotIncludedByDefault.java<br/> * %regex[.*Test.*|.*Not.*]<br/> */ @Parameter(property = "surefire.includesFile") private File includesFile; /** * A file containing exclude patterns. Blank lines, or lines starting with # are ignored. If {@code excludes} are * also specified, these patterns are appended. Example with path, simple and regex excludes:<br/> * &#042;&#047;test/*<br/> * &#042;&#042;&#047;DontRunTest.*<br/> * %regex[.*Test.*|.*Not.*]<br/> */ @Parameter(property = "surefire.excludesFile") private File excludesFile; /** * Set to error/failure count in order to skip remaining tests. * Due to race conditions in parallel/forked execution this may not be fully guaranteed.<br/> * Enable with system property -Dsurefire.skipAfterFailureCount=1 or any number greater than zero. * Defaults to "0".<br/> * See the prerequisites and limitations in documentation:<br/> * <a href="http://maven.apache.org/plugins/maven-surefire-plugin/examples/skip-after-failure.html"> * http://maven.apache.org/plugins/maven-surefire-plugin/examples/skip-after-failure.html</a> */ @Parameter(property = "surefire.skipAfterFailureCount", defaultValue = "0") private int skipAfterFailureCount; /** * After the plugin process is shutdown by sending SIGTERM signal (CTRL+C), SHUTDOWN command is received by every * forked JVM. By default (shutdown=testset) forked JVM would not continue with new test which means that * the current test may still continue to run.<br/> * The parameter can be configured with other two values "exit" and "kill".<br/> * Using "exit" forked JVM executes System.exit(1) after the plugin process has received SIGTERM signal.<br/> * Using "kill" the JVM executes Runtime.halt(1) and kills itself. */ @Parameter(property = "surefire.shutdown", defaultValue = "testset") private String shutdown; @Override public int getRerunFailingTestsCount() { return rerunFailingTestsCount; } @Override protected void handleSummary(RunResult summary, Exception firstForkException) throws MojoExecutionException, MojoFailureException { SurefireHelper.reportExecution(this, summary, getConsoleLogger(), firstForkException); } @Override public void execute() throws MojoExecutionException, MojoFailureException { if (!isSkipExecution()) { // let super.execute() handle the isSkipExecution case if (!isForking()) { getConsoleLogger().warning("ForkCount=0 is known not to work for GWT tests"); } } super.execute(); } @Override protected boolean isSkipExecution() { return isSkip() || isSkipTests() || isSkipExec(); } @Override protected String getPluginName() { return "GWT tests"; } @Override protected String[] getDefaultIncludes() { return new String[] {"**/*Suite.java", "**/*SuiteNoBrowser.java"}; } @Override public List<String> getIncludes() { return includes; } @Override public void setIncludes(List<String> includes) { this.includes = includes; } @Override protected String getReportSchemaLocation() { return "https://maven.apache.org/surefire/maven-surefire-plugin/xsd/surefire-test-report.xsd"; } @Override protected Artifact getMojoArtifact() { final Map<String, Artifact> pluginArtifactMap = getPluginArtifactMap(); return pluginArtifactMap.get("net.ltgt.gwt.maven:gwt-maven-plugin" ); } // @Override public boolean isSkipTests() { return skipTests; } @Override public void setSkipTests(boolean skipTests) { this.skipTests = skipTests; } @Override @SuppressWarnings("deprecation") public boolean isSkipExec() { return skipExec; } @Override @SuppressWarnings("deprecation") public void setSkipExec(boolean skipExec) { this.skipExec = skipExec; } @Override public boolean isSkip() { return skip; } @Override public void setSkip(boolean skip) { this.skip = skip; } @Override public File getBasedir() { return basedir; } @Override public void setBasedir(File basedir) { this.basedir = basedir; } @Override public File getTestClassesDirectory() { return testClassesDirectory; } @Override public void setTestClassesDirectory(File testClassesDirectory) { this.testClassesDirectory = testClassesDirectory; } @Override public File getClassesDirectory() { return classesDirectory; } @Override public void setClassesDirectory(File classesDirectory) { this.classesDirectory = classesDirectory; } @Override public File getReportsDirectory() { return reportsDirectory; } @Override public void setReportsDirectory(File reportsDirectory) { this.reportsDirectory = reportsDirectory; } @Override public String getTest() { return test; } @Override public void setTest(String test) { this.test = test; } @Override public int getSkipAfterFailureCount() { return skipAfterFailureCount; } @Override public String getShutdown() { return shutdown; } @Override public boolean isPrintSummary() { return printSummary; } @Override public void setPrintSummary(boolean printSummary) { this.printSummary = printSummary; } @Override public String getReportFormat() { return reportFormat; } @Override public void setReportFormat(String reportFormat) { this.reportFormat = reportFormat; } @Override public boolean isUseFile() { return useFile; } @Override public void setUseFile(boolean useFile) { this.useFile = useFile; } @Override public String getDebugForkedProcess() { return debugForkedProcess; } @Override public void setDebugForkedProcess(String debugForkedProcess) { this.debugForkedProcess = debugForkedProcess; } @Override public int getForkedProcessTimeoutInSeconds() { return forkedProcessTimeoutInSeconds; } @Override public void setForkedProcessTimeoutInSeconds(int forkedProcessTimeoutInSeconds) { this.forkedProcessTimeoutInSeconds = forkedProcessTimeoutInSeconds; } @Override public int getForkedProcessExitTimeoutInSeconds() { return forkedProcessExitTimeoutInSeconds; } @Override public void setForkedProcessExitTimeoutInSeconds(int forkedProcessExitTimeoutInSeconds) { this.forkedProcessExitTimeoutInSeconds = forkedProcessExitTimeoutInSeconds; } @Override public boolean isUseSystemClassLoader() { // GWTTestCase must use system class-loader return true; } @Override public void setUseSystemClassLoader(boolean useSystemClassLoader) { throw new UnsupportedOperationException("useSystemClassLoader is read-only"); } @Override public boolean isUseManifestOnlyJar() { // GWTTestCase must not use manifest-only JAR return false; } @Override public void setUseManifestOnlyJar(boolean useManifestOnlyJar) { throw new UnsupportedOperationException("useManifestOnlyJar is read-only"); } @Override public Boolean getFailIfNoSpecifiedTests() { return failIfNoSpecifiedTests; } @Override public void setFailIfNoSpecifiedTests(boolean failIfNoSpecifiedTests) { this.failIfNoSpecifiedTests = failIfNoSpecifiedTests; } @Override public boolean isTestFailureIgnore() { return testFailureIgnore; } @Override public void setTestFailureIgnore(boolean testFailureIgnore) { this.testFailureIgnore = testFailureIgnore; } @Override public double getParallelTestsTimeoutInSeconds() { return parallelTestsTimeoutInSeconds; } @Override public void setParallelTestsTimeoutInSeconds(double parallelTestsTimeoutInSeconds) { this.parallelTestsTimeoutInSeconds = parallelTestsTimeoutInSeconds; } @Override public double getParallelTestsTimeoutForcedInSeconds() { return parallelTestsTimeoutForcedInSeconds; } @Override public void setParallelTestsTimeoutForcedInSeconds(double parallelTestsTimeoutForcedInSeconds) { this.parallelTestsTimeoutForcedInSeconds = parallelTestsTimeoutForcedInSeconds; } @Override public File[] getSuiteXmlFiles() { return suiteXmlFiles.clone(); } @Override public void setSuiteXmlFiles(File[] suiteXmlFiles) { this.suiteXmlFiles = suiteXmlFiles.clone(); } @Override public String getRunOrder() { return runOrder; } @Override public void setRunOrder(String runOrder) { this.runOrder = runOrder; } @Override public File getIncludesFile() { return includesFile; } @Override public File getExcludesFile() { return excludesFile; } @Override protected List<File> suiteXmlFiles() { return hasSuiteXmlFiles() ? Arrays.asList( suiteXmlFiles ) : Collections.<File>emptyList(); } @Override protected boolean hasSuiteXmlFiles() { return suiteXmlFiles != null && suiteXmlFiles.length != 0; } // GwtOptions @Nullable @Override public String getLogLevel() { return logLevel; } @Nullable @Override public String getStyle() { return style; } @Nullable @Override public Integer getOptimize() { return optimize; } @Override public File getWarDir() { return outDir; } @Override public File getWorkDir() { return workDir; } @Override public File getDeployDir() { return deploy; } @Nullable @Override public File getExtraDir() { return extra; } @Override public boolean isDraftCompile() { return draftCompile; } @Nullable @Override public String getLocalWorkers() { return localWorkers; } @Nullable @Override public String getSourceLevel() { return sourceLevel; } }
Fix gwt:test's includes documentation wrt the default value Fixes #97
src/main/java/net/ltgt/gwt/maven/TestMojo.java
Fix gwt:test's includes documentation wrt the default value
<ide><path>rc/main/java/net/ltgt/gwt/maven/TestMojo.java <ide> * A list of &lt;include> elements specifying the tests (by pattern) that should be included in testing. When not <ide> * specified and when the <code>test</code> parameter is not specified, the default includes will be <code><br/> <ide> * &lt;includes><br/> <del> * &nbsp;&lt;include>**&#47;Test*.java&lt;/include><br/> <del> * &nbsp;&lt;include>**&#47;*Test.java&lt;/include><br/> <del> * &nbsp;&lt;include>**&#47;*Tests.java&lt;/include><br/> <del> * &nbsp;&lt;include>**&#47;*TestCase.java&lt;/include><br/> <add> * &nbsp;&lt;include>**&#47;*Suite.java&lt;/include><br/> <add> * &nbsp;&lt;include>**&#47;*SuiteNoBrowser.java&lt;/include><br/> <ide> * &lt;/includes><br/> <ide> * </code> <ide> * <p/>
Java
lgpl-2.1
1b18c7c0a73e0d39cd4f757cb031ec9aabe10850
0
CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine
/* * Copyright (c) 2004-2005 Javlin Consulting s.r.o. All rights reserved. * * $Header$ */ package org.jetel.graph; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Random; import org.jetel.data.DataRecord; import org.jetel.data.tape.DataRecordTape; import org.jetel.exception.ComponentNotReadyException; import org.jetel.interpreter.ParseException; import org.jetel.interpreter.TransformLangExecutor; import org.jetel.interpreter.TransformLangParser; import org.jetel.interpreter.ASTnode.CLVFStartExpression; import org.jetel.interpreter.data.TLValue; import org.jetel.metadata.DataRecordMetadata; /** * This class perform buffering data flowing through the edge. * If the edge has defined 'debugFile' attribute, this debugger save data into defined file. * * @author Martin Zatopek * */ public class EdgeDebuger { private boolean isReadMode; private DataRecordTape dataTape; private int debugMaxRecords; // max number of debugged records; 0 -> infinite private int debuggedRecords = 0; // currently number of debugged records private boolean sampleData; private String filterExpression; private DataRecordMetadata metadata; private Filter filter; private Sampler sampler; /** * Constructor. * @param debugFile */ public EdgeDebuger(String debugFile, boolean isReadMode) { this.isReadMode = isReadMode; dataTape = new DataRecordTape(debugFile, !isReadMode, false); } public EdgeDebuger(String debugFile, boolean isReadMode, int debugMaxRecords, String filterExpression, DataRecordMetadata metadata, boolean sampleData) { this(debugFile, isReadMode); this.debugMaxRecords = debugMaxRecords; this.filterExpression = filterExpression; this.metadata = metadata; this.sampleData = sampleData; } public void init() throws IOException { dataTape.open(); dataTape.addDataChunk(); if(isReadMode) dataTape.rewind(); if (filterExpression != null) { try { filter = new Filter(metadata, filterExpression); } catch (ComponentNotReadyException cnre) { throw new IOException(cnre.getMessage()); } } if (sampleData) { sampler = new Sampler(); } } public void writeRecord(DataRecord record) throws IOException { if (isReadMode){ throw new RuntimeException("Error: Mixed read/write operation on DataRecordTape !"); } if (checkRecordToWrite(record)) { dataTape.put(record); debuggedRecords++; } } public void writeRecord(ByteBuffer record) throws IOException { if (isReadMode){ throw new RuntimeException("Error: Mixed read/write operation on DataRecordTape !"); } if (checkRecordToWrite(record)) { dataTape.put(record); debuggedRecords++; } } /** * Decides if record will be debugged. * @param record record * @return true if current record should be debugged; else false */ private boolean checkRecordToWrite(DataRecord record) { return checkNoOfDebuggedRecords() && (filter == null || filter.check(record)) && (!sampleData || sampler.sample()); } /** * Decides if record will be debugged. * @param record record * @return true if current record should be debugged; else false */ private boolean checkRecordToWrite(ByteBuffer record) { return checkNoOfDebuggedRecords() && (filter == null || filter.check(record)) && (!sampleData || sampler.sample()); } /** * Check if number of debugged records is lower * than maximum number of debugged records. * @return false when max number of records was debugged; else true */ private boolean checkNoOfDebuggedRecords() { if (debugMaxRecords == 0 || debuggedRecords < debugMaxRecords) { return true; } return false; } public DataRecord readRecord(DataRecord record) throws IOException { if (!isReadMode) { return null; } if (dataTape.get(record)){ return record; }else{ return null; } } public void close() { try { if(!isReadMode) { dataTape.flush(true); } dataTape.close(); }catch(IOException ex){ throw new RuntimeException("Can't flush/rewind DataRecordTape: " + ex.getMessage()); } } /** * Class for filtering data record. * * @author Miroslav Haupt ([email protected]) * (c) Javlin Consulting (www.javlinconsulting.cz) * @since 20.12.2007 */ private static class Filter { private CLVFStartExpression recordFilter; private TransformLangExecutor executor; private DataRecord tmpRecord; public Filter(DataRecordMetadata metadata, String filterExpression) throws ComponentNotReadyException { TransformLangParser parser = new TransformLangParser(metadata, filterExpression); if (parser != null) { try { recordFilter = parser.StartExpression(); } catch (ParseException pe) { throw new ComponentNotReadyException("Parser error when parsing expression: " + pe.getMessage()); } catch (Exception e) { throw new ComponentNotReadyException("Error when parsing expression: " + e.getMessage()); } try{ recordFilter.init(); } catch (Exception e) { throw new ComponentNotReadyException("Error when initializing expression executor: " + e.getMessage()); } } else { throw new ComponentNotReadyException("Can't create filter expression parser !"); } executor = new TransformLangExecutor(); tmpRecord = new DataRecord(metadata); tmpRecord.init(); } public boolean check(DataRecord record) { executor.setInputRecords(new DataRecord[] {record}); executor.visit(recordFilter, null); if (executor.getResult() == TLValue.TRUE_VAL) { return true; } return false; } public boolean check(ByteBuffer record) { tmpRecord.deserialize(record); return check(tmpRecord); } } /** * Class for sampling data record. * * @author Miroslav Haupt ([email protected]) * (c) Javlin Consulting (www.javlinconsulting.cz) * @since 25.12.2007 */ private static class Sampler { private Random random; private int nextSample; private int sampleAdeptCounter = 0; //currently processes records // 3 -> first, second or third record will be chosen as first sample private final static int FIRST_SAMPLE_RANGE = 3; public Sampler() { random = new Random(); nextSample = random.nextInt(FIRST_SAMPLE_RANGE) + 1; } /** * Decides if current record will be chosen as a sample to debug. * The more records is debugged the less often this method returns true. * @return true if current record should be debugged; else false */ public boolean sample() { sampleAdeptCounter++; if (sampleAdeptCounter >= nextSample) { nextSample += Math.sqrt(random.nextInt(sampleAdeptCounter)) + 1; return true; } return false; } } }
cloveretl.engine/src/org/jetel/graph/EdgeDebuger.java
/* * Copyright (c) 2004-2005 Javlin Consulting s.r.o. All rights reserved. * * $Header$ */ package org.jetel.graph; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Random; import org.jetel.data.DataRecord; import org.jetel.data.tape.DataRecordTape; import org.jetel.exception.ComponentNotReadyException; import org.jetel.interpreter.ParseException; import org.jetel.interpreter.TransformLangExecutor; import org.jetel.interpreter.TransformLangParser; import org.jetel.interpreter.ASTnode.CLVFStartExpression; import org.jetel.interpreter.data.TLValue; import org.jetel.metadata.DataRecordMetadata; /** * This class perform buffering data flowing through the edge. * If the edge has defined 'debugFile' attribute, this debugger save data into defined file. * * @author Martin Zatopek * */ public class EdgeDebuger { private boolean isReadMode; private DataRecordTape dataTape; private int debugMaxRecords; // max number of debugged records; 0 -> infinite private int debuggedRecords = 0; // currently number of debugged records private boolean sampleMode; private String filterExpression; private DataRecordMetadata metadata; private Filter filter; private Sampler sampler; /** * Constructor. * @param debugFile */ public EdgeDebuger(String debugFile, boolean isReadMode) { this.isReadMode = isReadMode; dataTape = new DataRecordTape(debugFile, !isReadMode, false); } public EdgeDebuger(String debugFile, boolean isReadMode, int debugMaxRecords, String filterExpression, DataRecordMetadata metadata, boolean sampleMode) { this(debugFile, isReadMode); this.debugMaxRecords = debugMaxRecords; this.filterExpression = filterExpression; this.metadata = metadata; this.sampleMode = sampleMode; } public void init() throws IOException { dataTape.open(); dataTape.addDataChunk(); if(isReadMode) dataTape.rewind(); if (filterExpression != null) { try { filter = new Filter(metadata, filterExpression); } catch (ComponentNotReadyException cnre) { throw new IOException(cnre.getMessage()); } } if (sampleMode) { sampler = new Sampler(); } } public void writeRecord(DataRecord record) throws IOException { if (isReadMode){ throw new RuntimeException("Error: Mixed read/write operation on DataRecordTape !"); } if (checkRecordToWrite(record)) { dataTape.put(record); debuggedRecords++; } } public void writeRecord(ByteBuffer record) throws IOException { if (isReadMode){ throw new RuntimeException("Error: Mixed read/write operation on DataRecordTape !"); } if (checkRecordToWrite(record)) { dataTape.put(record); debuggedRecords++; } } /** * Decides if record will be debugged. * @param record record * @return true if current record should be debugged; else false */ private boolean checkRecordToWrite(DataRecord record) { return checkNoOfDebuggedRecords() && (filter == null || filter.check(record)) && (!sampleMode || sampler.sample()); } /** * Decides if record will be debugged. * @param record record * @return true if current record should be debugged; else false */ private boolean checkRecordToWrite(ByteBuffer record) { return checkNoOfDebuggedRecords() && (filter == null || filter.check(record)) && (!sampleMode || sampler.sample()); } /** * Check if number of debugged records is lower * than maximum number of debugged records. * @return false when max number of records was debugged; else true */ private boolean checkNoOfDebuggedRecords() { if (debugMaxRecords == 0 || debuggedRecords < debugMaxRecords) { return true; } return false; } public DataRecord readRecord(DataRecord record) throws IOException { if (!isReadMode) { return null; } if (dataTape.get(record)){ return record; }else{ return null; } } public void close() { try { if(!isReadMode) { dataTape.flush(true); } dataTape.close(); }catch(IOException ex){ throw new RuntimeException("Can't flush/rewind DataRecordTape: " + ex.getMessage()); } } /** * Class for filtering data record. * * @author Miroslav Haupt ([email protected]) * (c) Javlin Consulting (www.javlinconsulting.cz) * @since 20.12.2007 */ private static class Filter { private CLVFStartExpression recordFilter; private TransformLangExecutor executor; private DataRecord tmpRecord; public Filter(DataRecordMetadata metadata, String filterExpression) throws ComponentNotReadyException { TransformLangParser parser = new TransformLangParser(metadata, filterExpression); if (parser != null) { try { recordFilter = parser.StartExpression(); } catch (ParseException pe) { throw new ComponentNotReadyException("Parser error when parsing expression: " + pe.getMessage()); } catch (Exception e) { throw new ComponentNotReadyException("Error when parsing expression: " + e.getMessage()); } try{ recordFilter.init(); } catch (Exception e) { throw new ComponentNotReadyException("Error when initializing expression executor: " + e.getMessage()); } } else { throw new ComponentNotReadyException("Can't create filter expression parser !"); } executor = new TransformLangExecutor(); tmpRecord = new DataRecord(metadata); tmpRecord.init(); } public boolean check(DataRecord record) { executor.setInputRecords(new DataRecord[] {record}); executor.visit(recordFilter, null); if (executor.getResult() == TLValue.TRUE_VAL) { return true; } return false; } public boolean check(ByteBuffer record) { tmpRecord.deserialize(record); return check(tmpRecord); } } /** * Class for sampling data record. * * @author Miroslav Haupt ([email protected]) * (c) Javlin Consulting (www.javlinconsulting.cz) * @since 25.12.2007 */ private static class Sampler { private Random random; private int nextSample; private int sampleAdeptCounter = 0; //currently processes records // 3 -> first, second or third record will be chosen as first sample private final static int FIRST_SAMPLE_RANGE = 3; public Sampler() { random = new Random(); nextSample = random.nextInt(FIRST_SAMPLE_RANGE) + 1; } /** * Decides if current record will be chosen as a sample to debug. * The more records is debugged the less often this method returns true. * @return true if current record should be debugged; else false */ public boolean sample() { sampleAdeptCounter++; if (sampleAdeptCounter >= nextSample) { nextSample += Math.sqrt(random.nextInt(sampleAdeptCounter)) + 1; return true; } return false; } } }
MINOR:rename sampleMode to sampleData git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@3812 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
cloveretl.engine/src/org/jetel/graph/EdgeDebuger.java
MINOR:rename sampleMode to sampleData
<ide><path>loveretl.engine/src/org/jetel/graph/EdgeDebuger.java <ide> <ide> private int debugMaxRecords; // max number of debugged records; 0 -> infinite <ide> private int debuggedRecords = 0; // currently number of debugged records <del> private boolean sampleMode; <add> private boolean sampleData; <ide> <ide> private String filterExpression; <ide> private DataRecordMetadata metadata; <ide> } <ide> <ide> public EdgeDebuger(String debugFile, boolean isReadMode, int debugMaxRecords, <del> String filterExpression, DataRecordMetadata metadata, boolean sampleMode) { <add> String filterExpression, DataRecordMetadata metadata, boolean sampleData) { <ide> this(debugFile, isReadMode); <ide> this.debugMaxRecords = debugMaxRecords; <ide> this.filterExpression = filterExpression; <ide> this.metadata = metadata; <del> this.sampleMode = sampleMode; <add> this.sampleData = sampleData; <ide> } <ide> <ide> public void init() throws IOException { <ide> } <ide> } <ide> <del> if (sampleMode) { <add> if (sampleData) { <ide> sampler = new Sampler(); <ide> } <ide> } <ide> private boolean checkRecordToWrite(DataRecord record) { <ide> return checkNoOfDebuggedRecords() && <ide> (filter == null || filter.check(record)) && <del> (!sampleMode || sampler.sample()); <add> (!sampleData || sampler.sample()); <ide> } <ide> <ide> /** <ide> private boolean checkRecordToWrite(ByteBuffer record) { <ide> return checkNoOfDebuggedRecords() && <ide> (filter == null || filter.check(record)) && <del> (!sampleMode || sampler.sample()); <add> (!sampleData || sampler.sample()); <ide> } <ide> <ide> /**
JavaScript
mit
256c58299fddf039b4f1912b7b009ef7aebfe43b
0
ondrejhudek/pinboard,ondrejhudek/hudy-app,ondrejhudek/hudy-app,ondrejhudek/pinboard
import { applyMiddleware, compose, createStore } from 'redux' import { browserHistory } from 'react-router' import { syncHistory } from 'react-router-redux' import thunkMiddleware from 'redux-thunk' import createLogger from 'redux-logger' import DevTools from './../containers/DevTools' import rootReducer from '../reducers' import { fetchNotes } from '../actions/notes' import { fetchTodos } from '../actions/todos' const loggerMiddleware = createLogger() const middleware = syncHistory(browserHistory) const finalCreateStore = compose( applyMiddleware( middleware, thunkMiddleware, loggerMiddleware ), DevTools.instrument() )(createStore) const store = finalCreateStore(rootReducer) middleware.listenForReplays(store) store.dispatch(fetchNotes()) store.dispatch(fetchTodos()) export default store
src/main/app/scripts/store/configureStore.js
import { applyMiddleware, compose, createStore } from 'redux' import { browserHistory } from 'react-router' import { syncHistory } from 'react-router-redux' import thunkMiddleware from 'redux-thunk' import createLogger from 'redux-logger' import DevTools from './../containers/DevTools' import rootReducer from '../reducers' import { fetchNotes } from '../actions/notes' import { fetchTodos } from '../actions/todos' const loggerMiddleware = createLogger() const middleware = syncHistory(browserHistory) const finalCreateStore = compose( applyMiddleware( middleware, thunkMiddleware, loggerMiddleware ), DevTools.instrument() )(createStore) const store = finalCreateStore(rootReducer) middleware.listenForReplays(store) //store.dispatch(fetchNotes()) store.dispatch(fetchTodos()) export default store
Next commit
src/main/app/scripts/store/configureStore.js
Next commit
<ide><path>rc/main/app/scripts/store/configureStore.js <ide> const store = finalCreateStore(rootReducer) <ide> middleware.listenForReplays(store) <ide> <del>//store.dispatch(fetchNotes()) <add>store.dispatch(fetchNotes()) <ide> store.dispatch(fetchTodos()) <ide> <ide> export default store
JavaScript
apache-2.0
95ed851341646b82860929c0c29b908e2b9df445
0
ssunkara1/bqplot,dmadeka/bqplot,SylvainCorlay/bqplot,bloomberg/bqplot,ssunkara1/bqplot,SylvainCorlay/bqplot,bloomberg/bqplot,SylvainCorlay/bqplot,ChakriCherukuri/bqplot,rmenegaux/bqplot,ChakriCherukuri/bqplot,bloomberg/bqplot,rmenegaux/bqplot,dmadeka/bqplot,ChakriCherukuri/bqplot
/* Copyright 2015 Bloomberg Finance L.P. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(["widgets/js/manager", "d3", "./Mark"], function(WidgetManager, d3, mark) { var Mark = mark[0]; var Scatter = Mark.extend({ render: function() { var base_creation_promise = Scatter.__super__.render.apply(this); this.stroke = this.model.get("stroke"); this.default_opacity = this.model.get("default_opacity"); this.dot = d3.svg.symbol().type(this.model.get("marker")).size(this.model.get("default_size")); //container for mouse clicks this.el.append("rect") .attr("class", "mouseeventrect") .attr("x", 0) .attr("y", 0) .attr("width", this.width) .attr("visibility", "hidden") .attr("pointer-events", "all") .attr("height", this.height) .style("pointer-events", "all") .on("click", $.proxy(this.click, this)); var that = this; this.drag_listener = d3.behavior.drag() .on("dragstart", function(d) { return that.drag_start(d, this); }) .on("drag", function(d, i) { return that.on_drag(d, i, this); }) .on("dragend", function(d, i) { return that.drag_ended(d, i, this); }); this.selected_style = this.model.get("selected_style"); this.unselected_style = this.model.get("unselected_style"); this.selected_indices = this.model.get("idx_selected"); var self = this; return base_creation_promise.then(function() { self.color_scale = self.scales["color"]; self.size_scale = self.scales["size"]; self.opacity_scale = self.scales["opacity"]; // the following change handler is for the case when the colors of // the scale change. The data need not have changed. if(self.color_scale) { self.color_scale.on('color_scale_range_changed', self.color_scale_updated, self); } self.create_listeners(); self.draw();}, null); }, create_listeners: function() { Scatter.__super__.create_listeners.apply(this); this.model.on('change:default_color', this.update_default_color, this); this.model.on('change:stroke', this.update_stroke, this); this.model.on('change:default_opacity', this.update_default_opacity, this); this.model.on('data_updated', this.draw, this); this.model.on('change:marker', this.update_marker, this); this.model.on('change:default_size', this.update_default_size, this); this.model.on('change:fill', this.update_fill, this); this.model.on('change:display_names', this.update_display_names, this); this.listenTo(this.model, 'change:idx_selected', this.update_idx_selected); this.model.on('change:selected_style', this.selected_style_updated, this); this.model.on('change:unselected_style', this.unselected_style_updated, this); }, update_default_color: function(model, new_color) { var that = this; this.el.selectAll(".dot") .style("fill", this.model.get("fill") ? function(d) { return that.get_element_color(d);} : "none") .style("stroke", this.stroke ? this.stroke : function(d) { return that.get_element_color(d);}); if (this.legend_el) { this.legend_el.select("path") .style("fill", new_color) .style("stroke", this.stroke ? this.stroke : new_color); this.legend_el.select("text") .style("fill", this.model.get("fill") ? new_color : "none"); } }, update_fill: function(model, fill) { var default_color = this.model.get("default_color"); var that = this; this.el.selectAll(".dot").style("fill", fill ? function(d) { return that.get_element_color(d);} : "none") if (this.legend_el) { this.legend_el.selectAll("path") .style("fill", fill ? default_color : "none"); } }, update_stroke: function(model, fill) { this.stroke = this.model.get('stroke'); var that = this; this.el.selectAll(".dot") .style("stroke", this.stroke ? this.stroke : function(d) { return that.get_element_color(d);}); if (this.legend_el) { this.legend_el.selectAll("path") .style("stroke", this.stroke); } }, update_default_opacity: function() { this.default_opacity = this.model.get("default_opacity"); // update opacity scale range? var that = this; this.el.selectAll(".dot") .style("opacity", function(data) { return that.get_element_opacity(data);}) if (this.legend_el) { this.legend_el.select("path") .style("opacity", this.default_opacity) .style("fill", this.model.get("default_color")); } }, update_marker: function(model, marker) { this.dot.type(this.model.get("marker")) this.el.selectAll(".dot").attr("d", this.dot); if (this.legend_el) { this.legend_el.select("path").attr("d", this.dot.size(64)); } }, update_default_size: function(model, new_size) { // update size scale range? var that = this; this.el.selectAll(".dot").attr("d", this.dot.size(function(data) { return that.get_element_size(data);})); }, // The following three functions are convenience functions to get // the fill color / opacity / size of an element given the data. // In fact they are more than convenience functions as they limit the // points of entry to that logic which makes it easier to manage and to // keep consistent across different places where we use it. get_element_color: function(data) { if(this.color_scale != undefined && data.z != undefined) return this.color_scale.scale(data.z); return this.model.get("default_color"); }, get_element_size: function(data) { if(this.size_scale != undefined && data.size != undefined) return this.size_scale.scale(data.size); return this.model.get("default_size"); }, get_element_opacity: function(data) { if(this.opacity_scale != undefined && data.opacity != undefined) return this.opacity_scale.scale(data.opacity); return this.model.get("default_opacity"); }, rescale: function() { Scatter.__super__.rescale.apply(this); this.set_ranges(); this.el.select(".mouseeventrect") .attr("width", this.width) .attr("height", this.height); var that = this; this.el.selectAll(".dot_grp").transition().duration(this.model.get('animate_dur')) .attr("transform", function(d) { return "translate(" + (that.x_scale.scale(d.x) + that.x_offset) + "," + (that.y_scale.scale(d.y) + that.y_offset) + ")"; }) }, update_array: function(d, i) { if (!this.model.get("restrict_y")){ var x_data = []; this.model.get_typed_field("x").forEach( function(elem) { x_data.push(elem); } ); x_data[i] = this.x_scale.scale.invert(d[0]); this.model.set_typed_field("x", x_data); } if (!this.model.get("restrict_x")){ var y_data = []; this.model.get_typed_field("y").forEach( function(elem) { y_data.push(elem); } ); y_data[i] = this.y_scale.scale.invert(d[1]); this.model.set_typed_field("y", y_data); } this.touch(); }, drag_start: function(d, dragged_node) { if (!this.model.get("enable_move")) return; this.drag_started = true var dot = this.dot; dot.size(5 * this.model.get("default_size")); d3.select(dragged_node) .select("path") .transition() .attr("d", dot) .style("fill", this.model.get("drag_color")) .style("stroke", this.model.get("drag_color")); }, on_drag: function(d, i, dragged_node) { if(!this.drag_started){ return; } if(!this.model.get("enable_move")) return; var that = this; // If restrict_x is true, then the move is restricted only to the X // direction. if (!(this.model.get("restrict_y")) && this.model.get("restrict_x")) { d[0] = d3.event.x; d[1] = that.y_scale.scale(d.y); } else if (!(this.model.get("restrict_x")) && this.model.get("restrict_y")) { d[0] = that.x_scale.scale(d.x); d[1] = d3.event.y; } else if (this.model.get("restrict_x") && this.model.get("restrict_y")) { return; } else { d[0] = d3.event.x; d[1] = d3.event.y; } d3.select(dragged_node) .attr("transform", function() { return "translate(" + d[0] + "," + d[1] + ")";}); if(this.model.get("update_on_move")) { // saving on move if flag is set this.update_array(d, i); } }, drag_ended: function(d, i, dragged_node) { if (!this.model.get("enable_move")) return; if(!this.drag_started) return; var dot = this.dot; dot.size(this.model.get("default_size")); var that = this; d3.select(dragged_node) .select("path") .transition() .attr("d", dot) .style("fill", that.model.get("default_color")) .style("stroke", that.model.get("default_color")); this.update_array(d, i); this.send({event: 'drag_end', point: {'x': d.x, 'y': d.y}, index: i}); }, selected_deleter: function() { d3.event.stopPropagation(); return; }, click: function() { if (!this.model.get("enable_add")) return; var mouse_pos = d3.mouse(this.el.node()); var curr_pos = [mouse_pos[0], mouse_pos[1]]; var that = this; //add the new point to dat var x_data = []; this.model.get_typed_field("x").forEach( function(d) { x_data.push(d); } ); var y_data = []; this.model.get_typed_field("y").forEach( function(d) { y_data.push(d); } ); x_data.push(this.x_scale.scale.invert(curr_pos[0])); y_data.push(this.y_scale.scale.invert(curr_pos[1])); this.model.set_typed_field("x", x_data); this.model.set_typed_field("y", y_data); this.touch(); //adding the point and saving the model automatically triggers a //draw which adds the new point because the data now has a new //point }, draw: function() { this.set_ranges(); var that = this; var default_color = this.model.get("default_color"); var labels = this.model.get("labels"); var fill = this.model.get("fill"); var elements = this.el.selectAll(".dot_grp").data(this.model.mark_data, function(d) { return d.name; }); var elements_added = elements.enter().append("g").attr("class", "dot_grp"); var animate_dur = this.model.get('animate_dur'); elements_added.append("path").attr("class", "dot"); elements_added.append("text").attr("class", "dot_text"); elements.transition().duration(animate_dur) .attr("transform", function(d) { return "translate(" + (that.x_scale.scale(d.x) + that.x_offset) + "," + (that.y_scale.scale(d.y) + that.y_offset) + ")"; }) var text_loc = Math.sqrt(this.model.get("default_size")) / 2.0; elements.select("path") .attr("d", this.dot.size(function(d) { return that.get_element_size(d);})); elements.call(this.drag_listener); var names = this.model.get_typed_field("names") var show_names = (this.model.get("display_names") && names.length != 0); elements.select("text") .text(function(d) { return d.name; }) .attr("transform", function(d) { return "translate(" + (text_loc) + "," + (-text_loc) + ")"; }) .attr("display", function(d) { return (show_names) ? "inline": "none";}); elements.exit().transition().delay(animate_dur).remove(); this.apply_styles(this.selected_indices); }, color_scale_updated: function() { var that = this; var default_color = this.model.get("default_color"); var fill = this.model.get("fill"); this.el.selectAll(".dot_grp") .select("path") .style("fill", fill ? function(d) { return that.get_element_color(d);} : "none") .style("stroke", this.stroke ? this.stroke : function(d) { return that.get_element_color(d);}) }, draw_legend: function(elem, x_disp, y_disp, inter_x_disp, inter_y_disp) { this.legend_el = elem.selectAll(".legend" + this.uuid) .data([this.model.mark_data]); var default_color = this.model.get("default_color"); var that = this; var rect_dim = inter_y_disp * 0.8; this.legend_el.enter() .append("g") .attr("class", "legend" + this.uuid) .attr("transform", function(d, i) { return "translate(0, " + (i * inter_y_disp + y_disp) + ")"; }) .on("mouseover", $.proxy(this.highlight_axis, this)) .on("mouseout", $.proxy(this.unhighlight_axis, this)) .append("path") .attr("transform", function(d, i) { return "translate( " + rect_dim / 2 + ", " + rect_dim / 2 + ")"; }) .attr("d", this.dot.size(64)) .style("fill", this.model.get("fill") ? default_color : "none") .style("stroke", this.stroke ? this.stroke : default_color); this.legend_el.append("text") .attr("class","legendtext") .attr("x", rect_dim * 1.2) .attr("y", rect_dim / 2) .attr("dy", "0.35em") .text(function(d, i) { return that.model.get("labels")[i]; }) .style("fill", default_color); var max_length = d3.max(this.model.get("labels"), function(d) { return d.length; }); this.legend_el.exit().remove(); return [1, max_length]; }, update_display_names: function(model, value) { var names = this.model.get_typed_field("names") var show_names = (value && names.length != 0); this.el.selectAll(".dot_grp").select("text") .attr("display", function(d) { return (show_names) ? "inline": "none";}); }, invert_2d_range: function(x_start, x_end, y_start, y_end) { if(x_end == undefined) { this.model.set("idx_selected", null); this.touch(); return _.range(this.model.mark_data.length); } var xmin = this.x_scale.scale.invert(x_start), xmax = this.x_scale.scale.invert(x_end), ymin = this.y_scale.scale.invert(y_start), ymax = this.y_scale.scale.invert(y_end); var indices = _.range(this.model.mark_data.length); var that = this; var idx_selected = _.filter(indices, function(index) { var elem = that.model.mark_data[index]; return (elem.x >= xmin && elem.x <= xmax && elem.y >= ymin && elem.y <= ymax);}); this.model.set("idx_selected", idx_selected); this.touch(); return idx_selected; }, update_idx_selected: function(model, value) { this.selected_indices = value; this.apply_styles(value); }, set_style_on_elements: function(style, indices) { // If the index array is undefined or of length=0, exit the // function without doing anything if(indices == undefined || indices.length == 0) { return; } // Also, return if the style object itself is blank if(Object.keys(style).length == 0) return; var elements = this.el.selectAll(".dot"); elements = elements.filter(function(data, index) { return indices.indexOf(index) != -1; }); elements.style(style); }, set_default_style: function(indices) { // For all the elements with index in the list indices, the default // style is applied. if(indices == undefined || indices.length == 0) { return; } var elements = this.el.selectAll(".dot").filter(function(data, index) { return indices.indexOf(index) != -1; }); var fill = this.model.get("fill"); var that = this; elements.style("fill", fill ? function(d) { return that.get_element_color(d);} : "none") .style("stroke", this.stroke ? this.stroke : function(d) { return that.get_element_color(d);}) .style("opacity", function(d) { return that.get_element_opacity(d);}); }, clear_style: function(style_dict, indices) { // Function to clear the style of a dict on some or all the elements of the // chart.If indices is null, clears the style on all elements. If // not, clears on only the elements whose indices are mathcing. // // This function is not used right now. But it can be used if we // decide to accomodate more properties than those set by default. // Because those have to cleared specifically. var elements = this.el.selectAll(".dot"); if(indices != undefined) { elements = elements.filter(function(d, index) { return indices.indexOf(index) != -1; }); } var clearing_style = {}; for(var key in style_dict) { clearing_style[key] = null; } elements.style(clearing_style); }, }); WidgetManager.WidgetManager.register_widget_view("bqplot.Scatter", Scatter); });
bqplot/nbextension/bqplot/Scatter.js
/* Copyright 2015 Bloomberg Finance L.P. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(["widgets/js/manager", "d3", "./Mark"], function(WidgetManager, d3, mark) { var Mark = mark[0]; var Scatter = Mark.extend({ render: function() { var base_creation_promise = Scatter.__super__.render.apply(this); this.stroke = this.model.get("stroke"); this.default_opacity = this.model.get("default_opacity"); this.dot = d3.svg.symbol().type(this.model.get("marker")).size(this.model.get("default_size")); //container for mouse clicks this.el.append("rect") .attr("class", "intselmouse") .attr("x", 0) .attr("y", 0) .attr("width", this.width) .attr("visibility", "hidden") .attr("pointer-events", "all") .attr("height", this.height) .on("click", $.proxy(this.click, this)); var that = this; this.drag_listener = d3.behavior.drag() .on("dragstart", function(d) { return that.drag_start(d, this); }) .on("drag", function(d, i) { return that.on_drag(d, i, this); }) .on("dragend", function(d, i) { return that.drag_ended(d, i, this); }); this.selected_style = this.model.get("selected_style"); this.unselected_style = this.model.get("unselected_style"); this.selected_indices = this.model.get("idx_selected"); var self = this; return base_creation_promise.then(function() { self.color_scale = self.scales["color"]; self.size_scale = self.scales["size"]; self.opacity_scale = self.scales["opacity"]; // the following change handler is for the case when the colors of // the scale change. The data need not have changed. if(self.color_scale) { self.color_scale.on('color_scale_range_changed', self.color_scale_updated, self); } self.create_listeners(); self.draw();}, null); }, create_listeners: function() { Scatter.__super__.create_listeners.apply(this); this.model.on('change:default_color', this.update_default_color, this); this.model.on('change:stroke', this.update_stroke, this); this.model.on('change:default_opacity', this.update_default_opacity, this); this.model.on('data_updated', this.draw, this); this.model.on('change:marker', this.update_marker, this); this.model.on('change:default_size', this.update_default_size, this); this.model.on('change:fill', this.update_fill, this); this.model.on('change:display_names', this.update_display_names, this); this.listenTo(this.model, 'change:idx_selected', this.update_idx_selected); this.model.on('change:selected_style', this.selected_style_updated, this); this.model.on('change:unselected_style', this.unselected_style_updated, this); }, update_default_color: function(model, new_color) { var that = this; this.el.selectAll(".dot") .style("fill", this.model.get("fill") ? function(d) { return that.get_element_color(d);} : "none") .style("stroke", this.stroke ? this.stroke : function(d) { return that.get_element_color(d);}); if (this.legend_el) { this.legend_el.select("path") .style("fill", new_color) .style("stroke", this.stroke ? this.stroke : new_color); this.legend_el.select("text") .style("fill", this.model.get("fill") ? new_color : "none"); } }, update_fill: function(model, fill) { var default_color = this.model.get("default_color"); var that = this; this.el.selectAll(".dot").style("fill", fill ? function(d) { return that.get_element_color(d);} : "none") if (this.legend_el) { this.legend_el.selectAll("path") .style("fill", fill ? default_color : "none"); } }, update_stroke: function(model, fill) { this.stroke = this.model.get('stroke'); var that = this; this.el.selectAll(".dot") .style("stroke", this.stroke ? this.stroke : function(d) { return that.get_element_color(d);}); if (this.legend_el) { this.legend_el.selectAll("path") .style("stroke", this.stroke); } }, update_default_opacity: function() { this.default_opacity = this.model.get("default_opacity"); // update opacity scale range? var that = this; this.el.selectAll(".dot") .style("opacity", function(data) { return that.get_element_opacity(data);}) if (this.legend_el) { this.legend_el.select("path") .style("opacity", this.default_opacity) .style("fill", this.model.get("default_color")); } }, update_marker: function(model, marker) { this.dot.type(this.model.get("marker")) this.el.selectAll(".dot").attr("d", this.dot); if (this.legend_el) { this.legend_el.select("path").attr("d", this.dot.size(64)); } }, update_default_size: function(model, new_size) { // update size scale range? var that = this; this.el.selectAll(".dot").attr("d", this.dot.size(function(data) { return that.get_element_size(data);})); }, // The following three functions are convenience functions to get // the fill color / opacity / size of an element given the data. // In fact they are more than convenience functions as they limit the // points of entry to that logic which makes it easier to manage and to // keep consistent across different places where we use it. get_element_color: function(data) { if(this.color_scale != undefined && data.z != undefined) return this.color_scale.scale(data.z); return this.model.get("default_color"); }, get_element_size: function(data) { if(this.size_scale != undefined && data.size != undefined) return this.size_scale.scale(data.size); return this.model.get("default_size"); }, get_element_opacity: function(data) { if(this.opacity_scale != undefined && data.opacity != undefined) return this.opacity_scale.scale(data.opacity); return this.model.get("default_opacity"); }, rescale: function() { Scatter.__super__.rescale.apply(this); this.set_ranges(); this.el.select(".intselmouse") .attr("width", this.width) .attr("height", this.height); var that = this; this.el.selectAll(".dot_grp").transition().duration(this.model.get('animate_dur')) .attr("transform", function(d) { return "translate(" + (that.x_scale.scale(d.x) + that.x_offset) + "," + (that.y_scale.scale(d.y) + that.y_offset) + ")"; }) }, update_array: function(d, i) { if (!this.model.get("restrict_y")){ var x_data = []; this.model.get_typed_field("x").forEach( function(elem) { x_data.push(elem); } ); x_data[i] = this.x_scale.scale.invert(d[0]); this.model.set_typed_field("x", x_data); } if (!this.model.get("restrict_x")){ var y_data = []; this.model.get_typed_field("y").forEach( function(elem) { y_data.push(elem); } ); y_data[i] = this.y_scale.scale.invert(d[1]); this.model.set_typed_field("y", y_data); } this.touch(); }, drag_start: function(d, dragged_node) { if (!this.model.get("enable_move")) return; this.drag_started = true var dot = this.dot; dot.size(5 * this.model.get("default_size")); d3.select(dragged_node) .select("path") .transition() .attr("d", dot) .style("fill", this.model.get("drag_color")) .style("stroke", this.model.get("drag_color")); }, on_drag: function(d, i, dragged_node) { if(!this.drag_started){ return; } if(!this.model.get("enable_move")) return; var that = this; // If restrict_x is true, then the move is restricted only to the X // direction. if (!(this.model.get("restrict_y")) && this.model.get("restrict_x")) { d[0] = d3.event.x; d[1] = that.y_scale.scale(d.y); } else if (!(this.model.get("restrict_x")) && this.model.get("restrict_y")) { d[0] = that.x_scale.scale(d.x); d[1] = d3.event.y; } else if (this.model.get("restrict_x") && this.model.get("restrict_y")) { return; } else { d[0] = d3.event.x; d[1] = d3.event.y; } d3.select(dragged_node) .attr("transform", function() { return "translate(" + d[0] + "," + d[1] + ")";}); if(this.model.get("update_on_move")) { // saving on move if flag is set this.update_array(d, i); } }, drag_ended: function(d, i, dragged_node) { if (!this.model.get("enable_move")) return; if(!this.drag_started) return; var dot = this.dot; dot.size(this.model.get("default_size")); var that = this; d3.select(dragged_node) .select("path") .transition() .attr("d", dot) .style("fill", that.model.get("default_color")) .style("stroke", that.model.get("default_color")); this.update_array(d, i); this.send({event: 'drag_end', point: {'x': d.x, 'y': d.y}, index: i}); }, selected_deleter: function() { d3.event.stopPropagation(); return; }, click: function() { if (!this.model.get("enable_add")) return; var mouse_pos = d3.mouse(this.el.node()); var curr_pos = [mouse_pos[0], mouse_pos[1]]; var that = this; //add the new point to dat var x_data = []; this.model.get_typed_field("x").forEach( function(d) { x_data.push(d); } ); var y_data = []; this.model.get_typed_field("y").forEach( function(d) { y_data.push(d); } ); x_data.push(this.x_scale.scale.invert(curr_pos[0])); y_data.push(this.y_scale.scale.invert(curr_pos[1])); this.model.set_typed_field("x", x_data); this.model.set_typed_field("y", y_data); this.touch(); //adding the point and saving the model automatically triggers a //draw which adds the new point because the data now has a new //point }, draw: function() { this.set_ranges(); var that = this; var default_color = this.model.get("default_color"); var labels = this.model.get("labels"); var fill = this.model.get("fill"); var elements = this.el.selectAll(".dot_grp").data(this.model.mark_data, function(d) { return d.name; }); var elements_added = elements.enter().append("g").attr("class", "dot_grp"); var animate_dur = this.model.get('animate_dur'); elements_added.append("path").attr("class", "dot"); elements_added.append("text").attr("class", "dot_text"); elements.transition().duration(animate_dur) .attr("transform", function(d) { return "translate(" + (that.x_scale.scale(d.x) + that.x_offset) + "," + (that.y_scale.scale(d.y) + that.y_offset) + ")"; }) var text_loc = Math.sqrt(this.model.get("default_size")) / 2.0; elements.select("path") .attr("d", this.dot.size(function(d) { return that.get_element_size(d);})); elements.call(this.drag_listener); var names = this.model.get_typed_field("names") var show_names = (this.model.get("display_names") && names.length != 0); elements.select("text") .text(function(d) { return d.name; }) .attr("transform", function(d) { return "translate(" + (text_loc) + "," + (-text_loc) + ")"; }) .attr("display", function(d) { return (show_names) ? "inline": "none";}); elements.exit().transition().delay(animate_dur).remove(); this.apply_styles(this.selected_indices); }, color_scale_updated: function() { var that = this; var default_color = this.model.get("default_color"); var fill = this.model.get("fill"); this.el.selectAll(".dot_grp") .select("path") .style("fill", fill ? function(d) { return that.get_element_color(d);} : "none") .style("stroke", this.stroke ? this.stroke : function(d) { return that.get_element_color(d);}) }, draw_legend: function(elem, x_disp, y_disp, inter_x_disp, inter_y_disp) { this.legend_el = elem.selectAll(".legend" + this.uuid) .data([this.model.mark_data]); var default_color = this.model.get("default_color"); var that = this; var rect_dim = inter_y_disp * 0.8; this.legend_el.enter() .append("g") .attr("class", "legend" + this.uuid) .attr("transform", function(d, i) { return "translate(0, " + (i * inter_y_disp + y_disp) + ")"; }) .on("mouseover", $.proxy(this.highlight_axis, this)) .on("mouseout", $.proxy(this.unhighlight_axis, this)) .append("path") .attr("transform", function(d, i) { return "translate( " + rect_dim / 2 + ", " + rect_dim / 2 + ")"; }) .attr("d", this.dot.size(64)) .style("fill", this.model.get("fill") ? default_color : "none") .style("stroke", this.stroke ? this.stroke : default_color); this.legend_el.append("text") .attr("class","legendtext") .attr("x", rect_dim * 1.2) .attr("y", rect_dim / 2) .attr("dy", "0.35em") .text(function(d, i) { return that.model.get("labels")[i]; }) .style("fill", default_color); var max_length = d3.max(this.model.get("labels"), function(d) { return d.length; }); this.legend_el.exit().remove(); return [1, max_length]; }, update_display_names: function(model, value) { var names = this.model.get_typed_field("names") var show_names = (value && names.length != 0); this.el.selectAll(".dot_grp").select("text") .attr("display", function(d) { return (show_names) ? "inline": "none";}); }, invert_2d_range: function(x_start, x_end, y_start, y_end) { if(x_end == undefined) { this.model.set("idx_selected", null); this.touch(); return _.range(this.model.mark_data.length); } var xmin = this.x_scale.scale.invert(x_start), xmax = this.x_scale.scale.invert(x_end), ymin = this.y_scale.scale.invert(y_start), ymax = this.y_scale.scale.invert(y_end); var indices = _.range(this.model.mark_data.length); var that = this; var idx_selected = _.filter(indices, function(index) { var elem = that.model.mark_data[index]; return (elem.x >= xmin && elem.x <= xmax && elem.y >= ymin && elem.y <= ymax);}); this.model.set("idx_selected", idx_selected); this.touch(); return idx_selected; }, update_idx_selected: function(model, value) { this.selected_indices = value; this.apply_styles(value); }, set_style_on_elements: function(style, indices) { // If the index array is undefined or of length=0, exit the // function without doing anything if(indices == undefined || indices.length == 0) { return; } // Also, return if the style object itself is blank if(Object.keys(style).length == 0) return; var elements = this.el.selectAll(".dot"); elements = elements.filter(function(data, index) { return indices.indexOf(index) != -1; }); elements.style(style); }, set_default_style: function(indices) { // For all the elements with index in the list indices, the default // style is applied. if(indices == undefined || indices.length == 0) { return; } var elements = this.el.selectAll(".dot").filter(function(data, index) { return indices.indexOf(index) != -1; }); var fill = this.model.get("fill"); var that = this; elements.style("fill", fill ? function(d) { return that.get_element_color(d);} : "none") .style("stroke", this.stroke ? this.stroke : function(d) { return that.get_element_color(d);}) .style("opacity", function(d) { return that.get_element_opacity(d);}); }, clear_style: function(style_dict, indices) { // Function to clear the style of a dict on some or all the elements of the // chart.If indices is null, clears the style on all elements. If // not, clears on only the elements whose indices are mathcing. // // This function is not used right now. But it can be used if we // decide to accomodate more properties than those set by default. // Because those have to cleared specifically. var elements = this.el.selectAll(".dot"); if(indices != undefined) { elements = elements.filter(function(d, index) { return indices.indexOf(index) != -1; }); } var clearing_style = {}; for(var key in style_dict) { clearing_style[key] = null; } elements.style(clearing_style); }, }); WidgetManager.WidgetManager.register_widget_view("bqplot.Scatter", Scatter); });
Scatter bug fix for adding points
bqplot/nbextension/bqplot/Scatter.js
Scatter bug fix for adding points
<ide><path>qplot/nbextension/bqplot/Scatter.js <ide> <ide> //container for mouse clicks <ide> this.el.append("rect") <del> .attr("class", "intselmouse") <add> .attr("class", "mouseeventrect") <ide> .attr("x", 0) <ide> .attr("y", 0) <ide> .attr("width", this.width) <ide> .attr("visibility", "hidden") <ide> .attr("pointer-events", "all") <ide> .attr("height", this.height) <add> .style("pointer-events", "all") <ide> .on("click", $.proxy(this.click, this)); <add> <ide> var that = this; <ide> this.drag_listener = d3.behavior.drag() <ide> .on("dragstart", function(d) { return that.drag_start(d, this); }) <ide> rescale: function() { <ide> Scatter.__super__.rescale.apply(this); <ide> this.set_ranges(); <del> this.el.select(".intselmouse") <add> this.el.select(".mouseeventrect") <ide> .attr("width", this.width) <ide> .attr("height", this.height); <ide>
Java
apache-2.0
63895c8e9fed65d2ad99f32703a2d20f6d833567
0
haroldcarr/rdf-triple-browser,haroldcarr/rdf-triple-browser
// // Created : 2006 Jun 14 (Wed) 18:29:38 by Harold Carr. // Last Modified : 2006 Sep 16 (Sat) 08:19:23 by Harold Carr. // package com.differentity.client; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Frame; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.differentity.client.Main; public class SPVItem { private final String spvCategory; private final String expandedName; private final String collapsedName; private String expandCollapseState; private final Button button; private final Label label; private final HorizontalPanel horizontalPanel; private final VerticalPanel verticalPanel; SPVItem(String spvCategory, String expandedName, String collapsedName, String expandCollapseState) { this.spvCategory = spvCategory; this.expandedName = expandedName; this.collapsedName = collapsedName; this.expandCollapseState = expandCollapseState; button = new Button(Main.plusSymbol); label = new Label(expandedName); horizontalPanel = new HorizontalPanel(); verticalPanel = new VerticalPanel(); // Item layout. horizontalPanel.add(button); horizontalPanel.add(label); verticalPanel.add(horizontalPanel); if (expandCollapseState.equals(Main.collapse)){ label.setText(collapsedName); } else { button.setText(Main.minusSymbol); verticalPanel.add(new Frame(expandedName)); } } String getSPVCategory() { return spvCategory; } String getExpandedName() { return expandedName; } String getCollapsedName() { return collapsedName; } Button getButton() { return button; } Label getLabel() { return label; } HorizontalPanel getHorizontalPanel() { return horizontalPanel; } VerticalPanel getVerticalPanel() { return verticalPanel; } String getCurrentExpandCollapseState() { return Main.getExpandCollapseState(expandCollapseState, false); } String getPendingExpandCollapseState() { return Main.getExpandCollapseState(expandCollapseState, true); } void setExpandCollapseState(String x) { expandCollapseState = x; } } // End of file.
gwt/src/main/java/org/openhc/triplebrowser/gwt/client/SPVItem.java
// // Created : 2006 Jun 14 (Wed) 18:29:38 by Harold Carr. // Last Modified : 2006 Sep 12 (Tue) 18:30:12 by Harold Carr. // package com.differentity.client; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Frame; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Hyperlink; import com.google.gwt.user.client.ui.VerticalPanel; import com.differentity.client.Main; public class SPVItem { private final String spvCategory; private final String expandedName; private final String collapsedName; private String expandCollapseState; private final Button button; private final Hyperlink hyperlink; private final HorizontalPanel horizontalPanel; private final VerticalPanel verticalPanel; SPVItem(String spvCategory, String expandedName, String collapsedName, String expandCollapseState) { this.spvCategory = spvCategory; this.expandedName = expandedName; this.collapsedName = collapsedName; this.expandCollapseState = expandCollapseState; button = new Button(Main.plusSymbol); hyperlink = new Hyperlink(expandedName, spvCategory + Main.blankSpace+ expandedName); horizontalPanel = new HorizontalPanel(); verticalPanel = new VerticalPanel(); // Item layout. horizontalPanel.add(button); horizontalPanel.add(hyperlink); verticalPanel.add(horizontalPanel); if (expandCollapseState.equals(Main.collapse)){ hyperlink.setText(collapsedName); } else { button.setText(Main.minusSymbol); verticalPanel.add(new Frame(expandedName)); } } String getSPVCategory() { return spvCategory; } String getExpandedName() { return expandedName; } String getCollapsedName() { return collapsedName; } Button getButton() { return button; } Hyperlink getHyperlink() { return hyperlink; } HorizontalPanel getHorizontalPanel() { return horizontalPanel; } VerticalPanel getVerticalPanel() { return verticalPanel; } String getCurrentExpandCollapseState() { return Main.getExpandCollapseState(expandCollapseState, false); } String getPendingExpandCollapseState() { return Main.getExpandCollapseState(expandCollapseState, true); } void setExpandCollapseState(String x) { expandCollapseState = x; } } // End of file.
["on my way to history\n", "And replaced incorrect use of GWT Hyperlink with label.\n", ""]
gwt/src/main/java/org/openhc/triplebrowser/gwt/client/SPVItem.java
["on my way to history\n", "And replaced incorrect use of GWT Hyperlink with label.\n", ""]
<ide><path>wt/src/main/java/org/openhc/triplebrowser/gwt/client/SPVItem.java <ide> // <ide> // Created : 2006 Jun 14 (Wed) 18:29:38 by Harold Carr. <del>// Last Modified : 2006 Sep 12 (Tue) 18:30:12 by Harold Carr. <add>// Last Modified : 2006 Sep 16 (Sat) 08:19:23 by Harold Carr. <ide> // <ide> <ide> package com.differentity.client; <ide> import com.google.gwt.user.client.ui.Button; <ide> import com.google.gwt.user.client.ui.Frame; <ide> import com.google.gwt.user.client.ui.HorizontalPanel; <del>import com.google.gwt.user.client.ui.Hyperlink; <add>import com.google.gwt.user.client.ui.Label; <ide> import com.google.gwt.user.client.ui.VerticalPanel; <ide> <ide> import com.differentity.client.Main; <ide> private final String collapsedName; <ide> private String expandCollapseState; <ide> private final Button button; <del> private final Hyperlink hyperlink; <add> private final Label label; <ide> private final HorizontalPanel horizontalPanel; <ide> private final VerticalPanel verticalPanel; <ide> <ide> this.collapsedName = collapsedName; <ide> this.expandCollapseState = expandCollapseState; <ide> button = new Button(Main.plusSymbol); <del> hyperlink = new Hyperlink(expandedName, <del> spvCategory + Main.blankSpace+ expandedName); <add> label = new Label(expandedName); <ide> horizontalPanel = new HorizontalPanel(); <ide> verticalPanel = new VerticalPanel(); <ide> <ide> // Item layout. <ide> horizontalPanel.add(button); <del> horizontalPanel.add(hyperlink); <add> horizontalPanel.add(label); <ide> verticalPanel.add(horizontalPanel); <ide> <ide> if (expandCollapseState.equals(Main.collapse)){ <del> hyperlink.setText(collapsedName); <add> label.setText(collapsedName); <ide> } else { <ide> button.setText(Main.minusSymbol); <ide> verticalPanel.add(new Frame(expandedName)); <ide> String getExpandedName() { return expandedName; } <ide> String getCollapsedName() { return collapsedName; } <ide> Button getButton() { return button; } <del> Hyperlink getHyperlink() { return hyperlink; } <add> Label getLabel() { return label; } <ide> HorizontalPanel getHorizontalPanel() { return horizontalPanel; } <ide> VerticalPanel getVerticalPanel() { return verticalPanel; } <ide>
Java
apache-2.0
2e979b4bc436949442e4ac18f2376c9746d78892
0
Kirezzz/java_programming
package ru.stqa.java.sandbox; /** * Created by Sony on 03.10.2016. */ public class Collections { public static void main(String args[]) { String[] langs = {"Java","C#","Python", "PHP"}; } }
sandbox/src/main/java/ru/stqa/java/sandbox/Collections.java
package ru.stqa.java.sandbox; /** * Created by Sony on 03.10.2016. */ public class Collections { public static void main(String args[]) { String[] langs = new String[4]; langs[0] = "Java"; langs[1] = "C#"; langs[2] = "Python"; langs[3] = "PHP"; } }
Упрощенная версия реализации массива
sandbox/src/main/java/ru/stqa/java/sandbox/Collections.java
Упрощенная версия реализации массива
<ide><path>andbox/src/main/java/ru/stqa/java/sandbox/Collections.java <ide> */ <ide> public class Collections { <ide> public static void main(String args[]) { <del> String[] langs = new String[4]; <del> langs[0] = "Java"; <del> langs[1] = "C#"; <del> langs[2] = "Python"; <del> langs[3] = "PHP"; <add> String[] langs = {"Java","C#","Python", "PHP"}; <ide> } <ide> }
Java
mit
b56543c75a54b41464d71a02706d1954492c91ab
0
CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab
package org.xcolab.view.pages.contestmanagement.controller.manager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.xcolab.client.activities.ActivitiesClientUtil; import org.xcolab.client.admin.AdminClient; import org.xcolab.client.admin.pojo.Notification; import org.xcolab.client.contest.ContestClientUtil; import org.xcolab.client.contest.pojo.Contest; import org.xcolab.client.contest.pojo.phases.ContestPhase; import org.xcolab.client.members.MembersClient; import org.xcolab.client.members.exceptions.MemberNotFoundException; import org.xcolab.client.members.PermissionsClient; import org.xcolab.client.members.pojo.Member; import org.xcolab.client.proposals.ProposalMemberRatingClientUtil; import org.xcolab.util.enums.contest.ContestPhaseTypeValue; import org.xcolab.util.html.LabelStringValue; import org.xcolab.util.html.LabelValue; import org.xcolab.view.activityentry.ActivityEntryHelper; import org.xcolab.view.errors.AccessDeniedPage; import org.xcolab.view.errors.ErrorText; import org.xcolab.view.pages.contestmanagement.beans.ProposalReportBean; import org.xcolab.view.pages.contestmanagement.beans.VotingReportBean; import org.xcolab.view.pages.contestmanagement.beans.BatchRegisterBean; import org.xcolab.view.pages.contestmanagement.entities.ContestManagerTabs; import org.xcolab.view.pages.contestmanagement.utils.ActivityCsvWriter; import org.xcolab.view.pages.contestmanagement.utils.ContestCsvWriter; import org.xcolab.view.pages.contestmanagement.utils.ProposalCsvWriter; import org.xcolab.view.pages.contestmanagement.utils.ProposalExportType; import org.xcolab.view.pages.contestmanagement.utils.VoteCsvWriter; import org.xcolab.view.pages.contestmanagement.utils.WinnerCsvWriter; import org.xcolab.view.pages.loginregister.LoginRegisterService; import org.xcolab.view.taglibs.xcolab.wrapper.TabWrapper; import org.xcolab.view.util.entity.EntityIdListUtil; import org.xcolab.view.util.entity.enums.MemberRole; import org.xcolab.view.util.entity.flash.AlertMessage; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.stream.Collectors; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Controller @RequestMapping("/admin/contest/manager") public class AdminTabController extends AbstractTabController { private static final Logger log = LoggerFactory.getLogger(AdminTabController.class); private static final ContestManagerTabs tab = ContestManagerTabs.ADMIN; private static final String TAB_VIEW = "contestmanagement/manager/adminTab"; private static final Attributes.Name MANIFEST_ATTRIBUTE_GIT_COMMIT = new Attributes.Name("Git-Commit"); private final LoginRegisterService loginRegisterService; private final ServletContext servletContext; private final ActivityEntryHelper activityEntryHelper; @Autowired public AdminTabController(LoginRegisterService loginRegisterService, ServletContext servletContext, ActivityEntryHelper activityEntryHelper) { this.loginRegisterService = loginRegisterService; this.servletContext = servletContext; this.activityEntryHelper = activityEntryHelper; } @ModelAttribute("currentTabWrapped") @Override public TabWrapper populateCurrentTabWrapped(HttpServletRequest request) { tabWrapper = new TabWrapper(tab, request, tabContext); request.getSession().setAttribute("tabWrapper", tabWrapper); return tabWrapper; } @ModelAttribute("votingPhaseSelectionItems") public List<LabelValue> votingPhaseSelectionItems() { final List<ContestPhase> contestPhasesByType = new ArrayList<>(ContestClientUtil .getContestPhasesByType(ContestPhaseTypeValue.VOTING_PHASE_SOLVE.getTypeId())); //TODO COLAB-2613: don't hard code phase types contestPhasesByType.addAll(ContestClientUtil.getContestPhasesByType(20L)); final Date now = new Date(); return contestPhasesByType .stream() .filter(p -> p.getContestPK() != 0L) .filter(p -> p.getPhaseStartDateDt().before(now)) .sorted(Comparator.comparing(ContestPhase::getPhaseStartDate).reversed()) .map(contestPhase -> { final String contestName = contestPhase.getContest().getContestShortName(); final Long phaseId = contestPhase.getContestPhasePK(); return new LabelValue(phaseId, String.format("%d in %s", phaseId, contestName)); }) .collect(Collectors.toList()); } @ModelAttribute("contestSelectionItems") public List<LabelValue> contestSelectionItems() { return ContestClientUtil.getAllContests() .stream() .sorted(Comparator.comparing(Contest::getContestPK).reversed()) .map(contest -> { final String contestName = contest.getContestShortName(); final Long contestId = contest.getContestPK(); return new LabelValue(contestId, String.format("%d - %s", contestId, contestName)); }) .collect(Collectors.toList()); } @ModelAttribute("proposalExportTypeSelectionItems") public List<LabelStringValue> proposalExportTypeSelectionItems() { return Arrays.stream(ProposalExportType.values()) .map(proposalExportType -> new LabelStringValue( proposalExportType.name(), proposalExportType.getDescription())) .collect(Collectors.toList()); } @GetMapping("tab/ADMIN") public String showAdminTabController(HttpServletRequest request, HttpServletResponse response, Model model, Member member) { if (!tabWrapper.getCanView()) { return new AccessDeniedPage(member).toViewName(response); } List<Notification> list = AdminClient.getNotifications(); model.addAttribute("listOfNotifications", list); model.addAttribute("buildCommit", getBuildCommit()); model.addAttribute("javaVersion", Runtime.class.getPackage().getImplementationVersion()); model.addAttribute("javaVendor", Runtime.class.getPackage().getImplementationVendor()); return TAB_VIEW; } private String getBuildCommit() { try (final InputStream manifestInputStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF")) { if (manifestInputStream != null) { final Manifest manifest = new Manifest(manifestInputStream); final Attributes mainAttributes = manifest.getMainAttributes(); if (mainAttributes.containsKey(MANIFEST_ATTRIBUTE_GIT_COMMIT)) { return (String) mainAttributes.get(MANIFEST_ATTRIBUTE_GIT_COMMIT); } else { log.warn("Manifest does not contain 'Git-Commit' attribute."); } } else { log.error("Could not open input stream for manifest."); } } catch (IOException e) { log.error("Exception while opening input stream for manifest: {}", e.getMessage() ); } return "unknown"; } @GetMapping("tab/ADMIN/votingReport") public void generateVotingReport(HttpServletRequest request, HttpServletResponse response, VotingReportBean votingReportBean) throws IOException { if (!tabWrapper.getCanView()) { ErrorText.ACCESS_DENIED.flashAndRedirect(request, response); return; } try (VoteCsvWriter csvWriter = new VoteCsvWriter(response)) { votingReportBean.getVotingPhaseIds().stream() .map(ProposalMemberRatingClientUtil::getProposalVotesInPhase) .forEach(csvWriter::writeVotes); } } @GetMapping("tab/ADMIN/proposalReport") public void generateProposalReport(HttpServletRequest request, HttpServletResponse response, ProposalReportBean proposalReportBean) throws IOException { if (!tabWrapper.getCanView()) { ErrorText.ACCESS_DENIED.flashAndRedirect(request, response); return; } final List<Contest> contests = EntityIdListUtil.CONTESTS.fromIdList(proposalReportBean.getContestIds()); switch (proposalReportBean.getProposalExportType()) { case ALL: { try (ProposalCsvWriter csvWriter = new ProposalCsvWriter(response)) { contests.forEach(csvWriter::writeProposalsInContest); } break; } case WINNING_CONTRIBUTORS: { try (WinnerCsvWriter csvWriter = new WinnerCsvWriter(response)) { contests.forEach(csvWriter::writeProposalsInContest); } break; } default: ErrorText.NOT_FOUND.flashAndRedirect(request, response); break; } } @GetMapping("tab/ADMIN/contestReport") public void generateContestReport(HttpServletRequest request, HttpServletResponse response) throws IOException { if (!tabWrapper.getCanView()) { ErrorText.ACCESS_DENIED.flashAndRedirect(request, response); return; } try (ContestCsvWriter csvWriter = new ContestCsvWriter(response)) { csvWriter.writeContests(ContestClientUtil.getAllContests()); } } @PostMapping("tab/ADMIN/exportActivities") public void exportActivities(HttpServletRequest request, HttpServletResponse response) throws IOException { if (!tabWrapper.getCanView()) { ErrorText.ACCESS_DENIED.flashAndRedirect(request, response); return; } try (ActivityCsvWriter csvWriter = new ActivityCsvWriter(response, activityEntryHelper)) { ActivitiesClientUtil.getActivityEntries(0, Integer.MAX_VALUE, null, null) .forEach(csvWriter::writeActivity); } } @PostMapping("tab/ADMIN/batchRegister") public String batchRegisterMembers(HttpServletRequest request, HttpServletResponse response, BatchRegisterBean batchRegisterBean) throws IOException { if (!tabWrapper.getCanView()) { return ErrorText.ACCESS_DENIED.flashAndReturnView(request); } final String[] memberStrings = batchRegisterBean.getBatchText().split("\\r\\n|\\n|\\r"); for (String memberString : memberStrings) { final String[] values = memberString.split(";"); if (values.length != 3) { AlertMessage.danger("Batch registration: Invalid format.").flash(request); return TAB_VIEW; //return "redirect:" + tab.getTabUrl(); } String email = values[0]; java.util.regex.Pattern p = java.util.regex.Pattern.compile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"); java.util.regex.Matcher m = p.matcher(email); if (!m.matches()) { AlertMessage.danger("Batch registration: Invalid email address.").flash(request); return "redirect:" + tab.getTabUrl(); } try { MembersClient.findMemberByEmailAddress(email); // If member is found there is no exception and we continue. AlertMessage.danger("Batch registration: Email address already used.").flash(request); return "redirect:" + tab.getTabUrl(); } catch (MemberNotFoundException e) { // Do Nothing. } } for (String memberString : memberStrings) { final String[] values = memberString.split(";"); String email = values[0]; String firstName = values[1]; String lastName = values[2]; Member member = loginRegisterService.autoRegister(email, firstName, lastName); if (batchRegisterBean.getAsGuests()) { MembersClient.assignMemberRole(member.getId_(), MemberRole.GUEST.getRoleId()); MembersClient.removeMemberRole(member.getId_(), MemberRole.MEMBER.getRoleId()); } } AlertMessage.CHANGES_SAVED.flash(request); return "redirect:" + tab.getTabUrl(); } @PostMapping("tab/ADMIN/notificationMessageDelete") public String saveNotification(HttpServletRequest request, HttpServletResponse response, @RequestParam String notificationId, Member loggedInMember) throws IOException { if (!PermissionsClient.canAdminAll(loggedInMember)) { return new AccessDeniedPage(loggedInMember).toViewName(response); } AdminClient.deleteNotifications(notificationId); AlertMessage.DELETED.flash(request); return "redirect:" + tab.getTabUrl(); } @PostMapping("tab/ADMIN/notificationMessageCreate") public String saveNotification(HttpServletRequest request, HttpServletResponse response, Member member, @RequestParam String notificationText, @RequestParam String expiretime) throws IOException, ParseException { if (!PermissionsClient.canAdminAll(member)) { return new AccessDeniedPage(member).toViewName(response); } SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); expiretime = expiretime.replace("T", " "); if (expiretime.length() < "yyyy-MM-dd hh:mm:ss".length()) { expiretime = expiretime + ":00"; } Date endDate = formatter.parse(expiretime); if (endDate.before(new Date())) { AlertMessage.danger("Expiry date cannot be in the past. " + "Notification will not be saved!") .flash(request); return "redirect:" + tab.getTabUrl(); } Notification newNotification = new Notification(); newNotification.setNotificationText(notificationText); newNotification.setEndTime(endDate); AdminClient.setNotifications(newNotification); AlertMessage.CREATED.flash(request); return "redirect:" + tab.getTabUrl(); } }
view/src/main/java/org/xcolab/view/pages/contestmanagement/controller/manager/AdminTabController.java
package org.xcolab.view.pages.contestmanagement.controller.manager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.xcolab.client.activities.ActivitiesClientUtil; import org.xcolab.client.admin.AdminClient; import org.xcolab.client.admin.pojo.Notification; import org.xcolab.client.contest.ContestClientUtil; import org.xcolab.client.contest.pojo.Contest; import org.xcolab.client.contest.pojo.phases.ContestPhase; import org.xcolab.client.members.MembersClient; import org.xcolab.client.members.exceptions.MemberNotFoundException; import org.xcolab.client.members.PermissionsClient; import org.xcolab.client.members.pojo.Member; import org.xcolab.client.proposals.ProposalMemberRatingClientUtil; import org.xcolab.util.enums.contest.ContestPhaseTypeValue; import org.xcolab.util.html.LabelStringValue; import org.xcolab.util.html.LabelValue; import org.xcolab.view.activityentry.ActivityEntryHelper; import org.xcolab.view.errors.AccessDeniedPage; import org.xcolab.view.errors.ErrorText; import org.xcolab.view.pages.contestmanagement.beans.ProposalReportBean; import org.xcolab.view.pages.contestmanagement.beans.VotingReportBean; import org.xcolab.view.pages.contestmanagement.beans.BatchRegisterBean; import org.xcolab.view.pages.contestmanagement.entities.ContestManagerTabs; import org.xcolab.view.pages.contestmanagement.utils.ActivityCsvWriter; import org.xcolab.view.pages.contestmanagement.utils.ContestCsvWriter; import org.xcolab.view.pages.contestmanagement.utils.ProposalCsvWriter; import org.xcolab.view.pages.contestmanagement.utils.ProposalExportType; import org.xcolab.view.pages.contestmanagement.utils.VoteCsvWriter; import org.xcolab.view.pages.contestmanagement.utils.WinnerCsvWriter; import org.xcolab.view.pages.loginregister.LoginRegisterService; import org.xcolab.view.taglibs.xcolab.wrapper.TabWrapper; import org.xcolab.view.util.entity.EntityIdListUtil; import org.xcolab.view.util.entity.enums.MemberRole; import org.xcolab.view.util.entity.flash.AlertMessage; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.stream.Collectors; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Controller @RequestMapping("/admin/contest/manager") public class AdminTabController extends AbstractTabController { private static final Logger log = LoggerFactory.getLogger(AdminTabController.class); private static final ContestManagerTabs tab = ContestManagerTabs.ADMIN; private static final String TAB_VIEW = "contestmanagement/manager/adminTab"; private static final Attributes.Name MANIFEST_ATTRIBUTE_GIT_COMMIT = new Attributes.Name("Git-Commit"); private final LoginRegisterService loginRegisterService; private final ServletContext servletContext; private final ActivityEntryHelper activityEntryHelper; @Autowired public AdminTabController(LoginRegisterService loginRegisterService, ServletContext servletContext, ActivityEntryHelper activityEntryHelper) { this.loginRegisterService = loginRegisterService; this.servletContext = servletContext; this.activityEntryHelper = activityEntryHelper; } @ModelAttribute("currentTabWrapped") @Override public TabWrapper populateCurrentTabWrapped(HttpServletRequest request) { tabWrapper = new TabWrapper(tab, request, tabContext); request.getSession().setAttribute("tabWrapper", tabWrapper); return tabWrapper; } @ModelAttribute("votingPhaseSelectionItems") public List<LabelValue> votingPhaseSelectionItems() { final List<ContestPhase> contestPhasesByType = new ArrayList<>(ContestClientUtil .getContestPhasesByType(ContestPhaseTypeValue.VOTING_PHASE_SOLVE.getTypeId())); //TODO COLAB-2613: don't hard code phase types contestPhasesByType.addAll(ContestClientUtil.getContestPhasesByType(20L)); final Date now = new Date(); return contestPhasesByType .stream() .filter(p -> p.getContestPK() != 0L) .filter(p -> p.getPhaseStartDateDt().before(now)) .sorted(Comparator.comparing(ContestPhase::getPhaseStartDate).reversed()) .map(contestPhase -> { final String contestName = contestPhase.getContest().getContestShortName(); final Long phaseId = contestPhase.getContestPhasePK(); return new LabelValue(phaseId, String.format("%d in %s", phaseId, contestName)); }) .collect(Collectors.toList()); } @ModelAttribute("contestSelectionItems") public List<LabelValue> contestSelectionItems() { return ContestClientUtil.getAllContests() .stream() .sorted(Comparator.comparing(Contest::getContestPK).reversed()) .map(contest -> { final String contestName = contest.getContestShortName(); final Long contestId = contest.getContestPK(); return new LabelValue(contestId, String.format("%d - %s", contestId, contestName)); }) .collect(Collectors.toList()); } @ModelAttribute("proposalExportTypeSelectionItems") public List<LabelStringValue> proposalExportTypeSelectionItems() { return Arrays.stream(ProposalExportType.values()) .map(proposalExportType -> new LabelStringValue( proposalExportType.name(), proposalExportType.getDescription())) .collect(Collectors.toList()); } @GetMapping("tab/ADMIN") public String showAdminTabController(HttpServletRequest request, HttpServletResponse response, Model model, Member member) { if (!tabWrapper.getCanView()) { return new AccessDeniedPage(member).toViewName(response); } List<Notification> list = AdminClient.getNotifications(); model.addAttribute("listOfNotifications", list); model.addAttribute("buildCommit", getBuildCommit()); model.addAttribute("javaVersion", Runtime.class.getPackage().getImplementationVersion()); model.addAttribute("javaVendor", Runtime.class.getPackage().getImplementationVendor()); return TAB_VIEW; } private String getBuildCommit() { try (final InputStream manifestInputStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF")) { if (manifestInputStream != null) { final Manifest manifest = new Manifest(manifestInputStream); final Attributes mainAttributes = manifest.getMainAttributes(); if (mainAttributes.containsKey(MANIFEST_ATTRIBUTE_GIT_COMMIT)) { return (String) mainAttributes.get(MANIFEST_ATTRIBUTE_GIT_COMMIT); } else { log.warn("Manifest does not contain 'Git-Commit' attribute."); } } else { log.error("Could not open input stream for manifest."); } } catch (IOException e) { log.error("Exception while opening input stream for manifest: {}", e.getMessage() ); } return "unknown"; } @GetMapping("tab/ADMIN/votingReport") public void generateVotingReport(HttpServletRequest request, HttpServletResponse response, VotingReportBean votingReportBean) throws IOException { if (!tabWrapper.getCanView()) { ErrorText.ACCESS_DENIED.flashAndRedirect(request, response); return; } try (VoteCsvWriter csvWriter = new VoteCsvWriter(response)) { votingReportBean.getVotingPhaseIds().stream() .map(ProposalMemberRatingClientUtil::getProposalVotesInPhase) .forEach(csvWriter::writeVotes); } } @GetMapping("tab/ADMIN/proposalReport") public void generateProposalReport(HttpServletRequest request, HttpServletResponse response, ProposalReportBean proposalReportBean) throws IOException { if (!tabWrapper.getCanView()) { ErrorText.ACCESS_DENIED.flashAndRedirect(request, response); return; } final List<Contest> contests = EntityIdListUtil.CONTESTS.fromIdList(proposalReportBean.getContestIds()); switch (proposalReportBean.getProposalExportType()) { case ALL: { try (ProposalCsvWriter csvWriter = new ProposalCsvWriter(response)) { contests.forEach(csvWriter::writeProposalsInContest); } break; } case WINNING_CONTRIBUTORS: { try (WinnerCsvWriter csvWriter = new WinnerCsvWriter(response)) { contests.forEach(csvWriter::writeProposalsInContest); } break; } default: ErrorText.NOT_FOUND.flashAndRedirect(request, response); break; } } @GetMapping("tab/ADMIN/contestReport") public void generateContestReport(HttpServletRequest request, HttpServletResponse response) throws IOException { if (!tabWrapper.getCanView()) { ErrorText.ACCESS_DENIED.flashAndRedirect(request, response); return; } try (ContestCsvWriter csvWriter = new ContestCsvWriter(response)) { csvWriter.writeContests(ContestClientUtil.getAllContests()); } } @PostMapping("tab/ADMIN/exportActivities") public void exportActivities(HttpServletRequest request, HttpServletResponse response) throws IOException { if (!tabWrapper.getCanView()) { ErrorText.ACCESS_DENIED.flashAndRedirect(request, response); return; } try (ActivityCsvWriter csvWriter = new ActivityCsvWriter(response, activityEntryHelper)) { ActivitiesClientUtil.getActivityEntries(0, Integer.MAX_VALUE, null, null) .forEach(csvWriter::writeActivity); } } @PostMapping("tab/ADMIN/batchRegister") public String batchRegisterMembers(HttpServletRequest request, HttpServletResponse response, BatchRegisterBean batchRegisterBean) throws IOException { if (!tabWrapper.getCanView()) { return ErrorText.ACCESS_DENIED.flashAndReturnView(request); } final String[] memberStrings = batchRegisterBean.getBatchText().split("\\r\\n|\\n|\\r"); for (String memberString : memberStrings) { final String[] values = memberString.split(";"); if (values.length != 3) { AlertMessage.danger("Batch registration: Three entries per row.").flash(request); return TAB_VIEW; //return "redirect:" + tab.getTabUrl(); } String email = values[0]; java.util.regex.Pattern p = java.util.regex.Pattern.compile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"); java.util.regex.Matcher m = p.matcher(email); if (!m.matches()) { AlertMessage.danger("Batch registration: Invalid email address.").flash(request); return "redirect:" + tab.getTabUrl(); } try { MembersClient.findMemberByEmailAddress(email); // If member is found there is no exception and we continue. AlertMessage.danger("Batch registration: Email address already used.").flash(request); return "redirect:" + tab.getTabUrl(); } catch (MemberNotFoundException e) { // Do Nothing. } } for (String memberString : memberStrings) { final String[] values = memberString.split(";"); String email = values[0]; String firstName = values[1]; String lastName = values[2]; Member member = loginRegisterService.autoRegister(email, firstName, lastName); if (batchRegisterBean.getAsGuests()) { MembersClient.assignMemberRole(member.getId_(), MemberRole.GUEST.getRoleId()); MembersClient.removeMemberRole(member.getId_(), MemberRole.MEMBER.getRoleId()); } } AlertMessage.CHANGES_SAVED.flash(request); return "redirect:" + tab.getTabUrl(); } @PostMapping("tab/ADMIN/notificationMessageDelete") public String saveNotification(HttpServletRequest request, HttpServletResponse response, @RequestParam String notificationId, Member loggedInMember) throws IOException { if (!PermissionsClient.canAdminAll(loggedInMember)) { return new AccessDeniedPage(loggedInMember).toViewName(response); } AdminClient.deleteNotifications(notificationId); AlertMessage.DELETED.flash(request); return "redirect:" + tab.getTabUrl(); } @PostMapping("tab/ADMIN/notificationMessageCreate") public String saveNotification(HttpServletRequest request, HttpServletResponse response, Member member, @RequestParam String notificationText, @RequestParam String expiretime) throws IOException, ParseException { if (!PermissionsClient.canAdminAll(member)) { return new AccessDeniedPage(member).toViewName(response); } SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); expiretime = expiretime.replace("T", " "); if (expiretime.length() < "yyyy-MM-dd hh:mm:ss".length()) { expiretime = expiretime + ":00"; } Date endDate = formatter.parse(expiretime); if (endDate.before(new Date())) { AlertMessage.danger("Expiry date cannot be in the past. " + "Notification will not be saved!") .flash(request); return "redirect:" + tab.getTabUrl(); } Notification newNotification = new Notification(); newNotification.setNotificationText(notificationText); newNotification.setEndTime(endDate); AdminClient.setNotifications(newNotification); AlertMessage.CREATED.flash(request); return "redirect:" + tab.getTabUrl(); } }
Change invalid format error message
view/src/main/java/org/xcolab/view/pages/contestmanagement/controller/manager/AdminTabController.java
Change invalid format error message
<ide><path>iew/src/main/java/org/xcolab/view/pages/contestmanagement/controller/manager/AdminTabController.java <ide> for (String memberString : memberStrings) { <ide> final String[] values = memberString.split(";"); <ide> if (values.length != 3) { <del> AlertMessage.danger("Batch registration: Three entries per row.").flash(request); <add> AlertMessage.danger("Batch registration: Invalid format.").flash(request); <ide> return TAB_VIEW; <ide> //return "redirect:" + tab.getTabUrl(); <ide> }
Java
apache-2.0
883a74040942a605d43625ea6a5996077039d2b3
0
BrotherlyBoiler/Sunshine
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine.app; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.text.format.Time; import android.util.Log; import android.widget.ArrayAdapter; import com.example.android.sunshine.app.data.WeatherContract; import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Vector; public class FetchWeatherTask extends AsyncTask<String, Void, String[]> { private final String LOG_TAG = FetchWeatherTask.class.getSimpleName(); private ArrayAdapter<String> mForecastAdapter; private final Context mContext; public FetchWeatherTask(Context context, ArrayAdapter<String> forecastAdapter) { mContext = context; mForecastAdapter = forecastAdapter; } private boolean DEBUG = true; /* The date/time conversion code is going to be moved outside the asynctask later, * so for convenience we're breaking it out into its own method now. */ private String getReadableDateString(long time) { // Because the API returns a unix timestamp (measured in seconds), // it must be converted to milliseconds in order to be converted to valid date. Date date = new Date(time); SimpleDateFormat format = new SimpleDateFormat("E, MMM d", Locale.ENGLISH); return format.format(date); } /** * Prepare the weather high/lows for presentation. */ private String formatHighLows(double high, double low) { // Data is fetched in Celsius by default. // If user prefers to see in Fahrenheit, convert the values here. // We do this rather than fetching in Fahrenheit so that the user can // change this option without us having to re-fetch the data once // we start storing the values in a database. SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); String unitType = sharedPrefs.getString( mContext.getString(R.string.pref_units_key), mContext.getString(R.string.pref_units_metric)); if (unitType.equals(mContext.getString(R.string.pref_units_imperial))) { high = (high * 1.8) + 32; low = (low * 1.8) + 32; } else if (!unitType.equals(mContext.getString(R.string.pref_units_metric))) { Log.d(LOG_TAG, "Unit type not found: " + unitType); } // For presentation, assume the user doesn't care about tenths of a degree. long roundedHigh = Math.round(high); long roundedLow = Math.round(low); String highLowStr = roundedHigh + "/" + roundedLow; return highLowStr; } /** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city * @param lon the longitude of the city * @return the row ID of the added location. */ long addLocation(String locationSetting, String cityName, double lat, double lon) { // Students: First, check if the location with this city name exists in the db // If it exists, return the current ID // Otherwise, insert it using the content resolver and the base URI long locationId = -1; Cursor locationCursor = mContext.getContentResolver().query( WeatherContract.LocationEntry.CONTENT_URI, new String[]{WeatherContract.LocationEntry._ID}, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[]{locationSetting}, null ); if (locationCursor.moveToFirst()) { int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationId = locationCursor.getLong(locationIdIndex); } else { ContentValues locationValues = new ContentValues(); locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); Uri insertedUri = mContext.getContentResolver().insert( WeatherContract.LocationEntry.CONTENT_URI, locationValues ); } locationCursor.close(); return locationId; } /* Students: This code will allow the FetchWeatherTask to continue to return the strings that the UX expects so that we can continue to test the application even once we begin using the database. */ String[] convertContentValuesToUXFormat(Vector<ContentValues> cvv) { // return strings to keep UI functional for now String[] resultStrs = new String[cvv.size()]; for (int i = 0; i < cvv.size(); i++) { ContentValues weatherValues = cvv.elementAt(i); String highAndLow = formatHighLows( weatherValues.getAsDouble(WeatherEntry.COLUMN_MAX_TEMP), weatherValues.getAsDouble(WeatherEntry.COLUMN_MIN_TEMP)); resultStrs[i] = getReadableDateString( weatherValues.getAsLong(WeatherEntry.COLUMN_DATE)) + " - " + weatherValues.getAsString(WeatherEntry.COLUMN_SHORT_DESC) + " - " + highAndLow; } return resultStrs; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * <p/> * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } // add to database if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here } // Sort order: Ascending, by date. String sortOrder = WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate( locationSetting, System.currentTimeMillis()); // Students: Uncomment the next lines to display what what you stored in the bulkInsert // Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, // null, null, null, sortOrder); // // cVVector = new Vector<ContentValues>(cur.getCount()); // if ( cur.moveToFirst() ) { // do { // ContentValues cv = new ContentValues(); // DatabaseUtils.cursorRowToContentValues(cur, cv); // cVVector.add(cv); // } while (cur.moveToNext()); // } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); String[] resultStrs = convertContentValuesToUXFormat(cVVector); return resultStrs; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; } @Override protected String[] doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; } String locationQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon() .appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { return getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } // This will only happen if there was an error getting or parsing the forecast. return null; } @Override protected void onPostExecute(String[] result) { if (result != null && mForecastAdapter != null) { mForecastAdapter.clear(); for (String dayForecastStr : result) { mForecastAdapter.add(dayForecastStr); } // New data is back from the server. Hooray! } } }
app/src/main/java/com/example/android/sunshine/app/FetchWeatherTask.java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.sunshine.app; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.text.format.Time; import android.util.Log; import android.widget.ArrayAdapter; import com.example.android.sunshine.app.data.WeatherContract; import com.example.android.sunshine.app.data.WeatherContract.WeatherEntry; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Vector; public class FetchWeatherTask extends AsyncTask<String, Void, String[]> { private final String LOG_TAG = FetchWeatherTask.class.getSimpleName(); private ArrayAdapter<String> mForecastAdapter; private final Context mContext; public FetchWeatherTask(Context context, ArrayAdapter<String> forecastAdapter) { mContext = context; mForecastAdapter = forecastAdapter; } private boolean DEBUG = true; /* The date/time conversion code is going to be moved outside the asynctask later, * so for convenience we're breaking it out into its own method now. */ private String getReadableDateString(long time) { // Because the API returns a unix timestamp (measured in seconds), // it must be converted to milliseconds in order to be converted to valid date. Date date = new Date(time); SimpleDateFormat format = new SimpleDateFormat("E, MMM d", Locale.ENGLISH); return format.format(date); } /** * Prepare the weather high/lows for presentation. */ private String formatHighLows(double high, double low) { // Data is fetched in Celsius by default. // If user prefers to see in Fahrenheit, convert the values here. // We do this rather than fetching in Fahrenheit so that the user can // change this option without us having to re-fetch the data once // we start storing the values in a database. SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); String unitType = sharedPrefs.getString( mContext.getString(R.string.pref_units_key), mContext.getString(R.string.pref_units_metric)); if (unitType.equals(mContext.getString(R.string.pref_units_imperial))) { high = (high * 1.8) + 32; low = (low * 1.8) + 32; } else if (!unitType.equals(mContext.getString(R.string.pref_units_metric))) { Log.d(LOG_TAG, "Unit type not found: " + unitType); } // For presentation, assume the user doesn't care about tenths of a degree. long roundedHigh = Math.round(high); long roundedLow = Math.round(low); String highLowStr = roundedHigh + "/" + roundedLow; return highLowStr; } /** * Helper method to handle insertion of a new location in the weather database. * * @param locationSetting The location string used to request updates from the server. * @param cityName A human-readable city name, e.g "Mountain View" * @param lat the latitude of the city * @param lon the longitude of the city * @return the row ID of the added location. */ long addLocation(String locationSetting, String cityName, double lat, double lon) { // Students: First, check if the location with this city name exists in the db // If it exists, return the current ID // Otherwise, insert it using the content resolver and the base URI long locationId = -1; Cursor locationCursor = mContext.getContentResolver().query( WeatherContract.LocationEntry.CONTENT_URI, new String[]{WeatherContract.LocationEntry._ID}, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[]{locationSetting}, null ); if (locationCursor.moveToFirst()) { int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID); locationId = locationCursor.getLong(locationIdIndex); } else { ContentValues locationValues = new ContentValues(); locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName); locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat); locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon); Uri insertedUri = mContext.getContentResolver().insert( WeatherContract.LocationEntry.CONTENT_URI, locationValues ); } locationCursor.close(); return locationId; } /* Students: This code will allow the FetchWeatherTask to continue to return the strings that the UX expects so that we can continue to test the application even once we begin using the database. */ String[] convertContentValuesToUXFormat(Vector<ContentValues> cvv) { // return strings to keep UI functional for now String[] resultStrs = new String[cvv.size()]; for (int i = 0; i < cvv.size(); i++) { ContentValues weatherValues = cvv.elementAt(i); String highAndLow = formatHighLows( weatherValues.getAsDouble(WeatherEntry.COLUMN_MAX_TEMP), weatherValues.getAsDouble(WeatherEntry.COLUMN_MIN_TEMP)); resultStrs[i] = getReadableDateString( weatherValues.getAsLong(WeatherEntry.COLUMN_DATE)) + " - " + weatherValues.getAsString(WeatherEntry.COLUMN_SHORT_DESC) + " - " + highAndLow; } return resultStrs; } /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * <p/> * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } // add to database if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here } // Sort order: Ascending, by date. String sortOrder = WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate( locationSetting, System.currentTimeMillis()); // Students: Uncomment the next lines to display what what you stored in the bulkInsert // Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, // null, null, null, sortOrder); // // cVVector = new Vector<ContentValues>(cur.getCount()); // if ( cur.moveToFirst() ) { // do { // ContentValues cv = new ContentValues(); // DatabaseUtils.cursorRowToContentValues(cur, cv); // cVVector.add(cv); // } while (cur.moveToNext()); // } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); String[] resultStrs = convertContentValuesToUXFormat(cVVector); return resultStrs; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; } @Override protected String[] doInBackground(String... params) { // If there's no zip code, there's nothing to look up. Verify size of params. if (params.length == 0) { return null; } String locationQuery = params[0]; // These two need to be declared outside the try/catch // so that they can be closed in the finally block. HttpURLConnection urlConnection = null; BufferedReader reader = null; // Will contain the raw JSON response as a string. String forecastJsonStr = null; String format = "json"; String units = "metric"; int numDays = 14; try { // Construct the URL for the OpenWeatherMap query // Possible parameters are avaiable at OWM's forecast API page, at // http://openweathermap.org/API#forecast final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?"; final String QUERY_PARAM = "q"; final String FORMAT_PARAM = "mode"; final String UNITS_PARAM = "units"; final String DAYS_PARAM = "cnt"; Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon() .appendQueryParameter(QUERY_PARAM, params[0]) .appendQueryParameter(FORMAT_PARAM, format) .appendQueryParameter(UNITS_PARAM, units) .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)) .build(); URL url = new URL(builtUri.toString()); // Create the request to OpenWeatherMap, and open the connection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // Read the input stream into a String InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) // But it does make debugging a *lot* easier if you print out the completed // buffer for debugging. buffer.append(line + "\n"); } if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } forecastJsonStr = buffer.toString(); } catch (IOException e) { Log.e(LOG_TAG, "Error ", e); // If the code didn't successfully get the weather data, there's no point in attemping // to parse it. return null; } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e(LOG_TAG, "Error closing stream", e); } } } try { return getWeatherDataFromJson(forecastJsonStr, locationQuery); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } // This will only happen if there was an error getting or parsing the forecast. return null; } @Override protected void onPostExecute(String[] result) { if (result != null && mForecastAdapter != null) { mForecastAdapter.clear(); for (String dayForecastStr : result) { mForecastAdapter.add(dayForecastStr); } // New data is back from the server. Hooray! } } }
Fix FetchWeatherTask according to solution
app/src/main/java/com/example/android/sunshine/app/FetchWeatherTask.java
Fix FetchWeatherTask according to solution
<ide><path>pp/src/main/java/com/example/android/sunshine/app/FetchWeatherTask.java <ide> */ <ide> package com.example.android.sunshine.app; <ide> <add>import android.content.ContentUris; <ide> import android.content.ContentValues; <ide> import android.content.Context; <ide> import android.content.SharedPreferences;
Java
apache-2.0
b8ae1e9815f2788e176cb7a2837312ffe6008787
0
cosmocode/cosmocode-commons
/** * Copyright 2010 CosmoCode GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.cosmocode.collections.utility; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import de.cosmocode.commons.DateMode; import de.cosmocode.commons.Enums; import de.cosmocode.commons.Patterns; /** * Utility class providing method to convert * genericly typed parameters into strongly * typed primitives or well known * and widely used objects. * * @author Willi Schoenborn */ public final class Convert { private static final Logger LOG = LoggerFactory.getLogger(Convert.class); /** * Prevent instantiation. */ private Convert() { } private static RuntimeException fail(Object value, Class<?> type) { final String message = "'" + value + "' couldn't be converted into '" + type.getName() + "'"; return new IllegalArgumentException(message); } @edu.umd.cs.findbugs.annotations.SuppressWarnings("NP_BOOLEAN_RETURN_NULL") private static Boolean doIntoBoolean(Object value) { if (value == null) return null; if (value instanceof Boolean) return Boolean.class.cast(value); final String converted = doIntoString(value); if ("true".equalsIgnoreCase(converted)) { return Boolean.TRUE; } else if ("false".equalsIgnoreCase(converted)) { return Boolean.FALSE; } else { return null; } } /** * Parses a value of a generic type * into a boolean. * * @param value the value being parsed * @return the parsed boolean * @throws IllegalArgumentException if conversion failed */ public static boolean intoBoolean(Object value) { final Boolean b = doIntoBoolean(value); if (b == null) { throw fail(value, boolean.class); } else { return b.booleanValue(); } } /** * Parses a value of a generic type * into a boolean. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a boolean * @return the parsed boolean or the defaultValue if value can't be parsed into a boolean */ public static boolean intoBoolean(Object value, boolean defaultValue) { final Boolean b = doIntoBoolean(value); return b == null ? defaultValue : b.booleanValue(); } private static Long doIntoLong(Object value) { if (value == null) return null; if (value instanceof Long) return Long.class.cast(value); if (value instanceof Number) return Number.class.cast(value).longValue(); final String s = doIntoString(value); try { return Long.valueOf(s); } catch (NumberFormatException e) { return null; } } /** * Parses a value of a generic type * into a long. * * @param value the value being parsed * @return the parsed long * @throws IllegalArgumentException if conversion failed */ public static long intoLong(Object value) { final Long l = doIntoLong(value); if (l == null) { throw fail(value, long.class); } else { return l.longValue(); } } /** * Parses a value of a generic type * into a long. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a long * @return the parsed long or the defaultValue if value can't be parsed into a long */ public static long intoLong(Object value, long defaultValue) { final Long l = doIntoLong(value); return l == null ? defaultValue : l.longValue(); } private static Double doIntoDouble(Object value) { if (value == null) return null; if (value instanceof Double) return Double.class.cast(value); if (value instanceof Number) return Number.class.cast(value).doubleValue(); final String s = doIntoString(value); try { final Double d = Double.valueOf(s); LOG.debug("Converted {} into {}", value, d); if (d.isInfinite() || d.isNaN()) return null; return d; } catch (NumberFormatException e) { return null; } } /** * Parses a value of a generic type * into a double. * * @param value the value being parsed * @return the parsed double * @throws IllegalArgumentException if conversion failed */ public static double intoDouble(Object value) { final Double d = doIntoDouble(value); if (d == null) { throw fail(value, double.class); } else { return d.doubleValue(); } } /** * Parses a value of a generic type * into a double. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a double * @return the parsed double or the defaultValue if value can't be parsed into a double */ public static double intoDouble(Object value, double defaultValue) { final Double d = doIntoDouble(value); return d == null ? defaultValue : d.doubleValue(); } private static Date doIntoDate(Object value, DateMode dateMode) { Preconditions.checkNotNull(dateMode, "DateMode"); if (value == null) return null; if (value instanceof Date) return Date.class.cast(value); if (value instanceof Calendar) return Calendar.class.cast(value).getTime(); final Long time = doIntoLong(value); return time == null || time.longValue() < 0 ? null : dateMode.parse(time.longValue()); } /** * Parses a value of a generic type * into a {@link Date}. * * @param value the value being parsed * @return the parsed {@link Date} * @throws IllegalArgumentException if conversion failed */ public static Date intoDate(Object value) { return intoDate(value, DateMode.JAVA); } /** * Parses a value of a generic type * into a {@link Date}. * * @param value the value being parsed * @param dateMode a {@link DateMode} instance handling the long to time conversion * @return the parsed {@link Date} * @throws NullPointerException if dateMode is null * @throws IllegalArgumentException if conversion failed */ public static Date intoDate(Object value, DateMode dateMode) { final Date date = doIntoDate(value, dateMode); if (date == null) { throw fail(value, Date.class); } else { return date; } } /** * Parses a value of a generic type * into a {@link Date}. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link Date} * @return the parsed {@link Date} */ public static Date intoDate(Object value, Date defaultValue) { return intoDate(value, DateMode.JAVA, defaultValue); } /** * Parses a value of a generic type * into a {@link Date}. * * @param value the value being parsed * @param dateMode the {@link DateMode} being used to convert long to {@link Date} * @param defaultValue the default value if value can't be parsed into a {@link Date} * @return the parsed {@link Date} or the defaultValue if value can't be parsed into a {@link Date} * @throws NullPointerException if dateMode is null */ public static Date intoDate(Object value, DateMode dateMode, Date defaultValue) { final Date date = doIntoDate(value, dateMode); return date == null ? defaultValue : date; } private static <E extends Enum<E>> E doIntoEnum(Object value, Class<E> enumType) { Preconditions.checkNotNull(enumType, "EnumType"); if (enumType.isInstance(value)) return enumType.cast(value); final Long ordinal = doIntoLong(value); if (ordinal == null) { final String name = doIntoString(value); if (name == null) return null; try { return Enum.valueOf(enumType, name.toUpperCase()); } catch (IllegalArgumentException e) { return null; } } else { try { return Enums.valueOf(enumType, ordinal.intValue()); } catch (IndexOutOfBoundsException e) { return null; } } } /** * Parses a value of a generic type * into an {@link Enum}. * The value must be either a valid enum constant * name or ordinal. * * @param <E> the generic enum type * @param value the value being parsed * @param enumType the enum type's class * @return the parsed {@link Enum} * @throws NullPointerException if enumType is null * @throws IllegalArgumentException if conversion failed */ public static <E extends Enum<E>> E intoEnum(Object value, Class<E> enumType) { final E e = doIntoEnum(value, enumType); if (e == null) { throw fail(value, enumType); } else { return e; } } /** * Parses a value of a generic type * into an {@link Enum}. * * @param <E> the generic enum type * @param value the value being parsed * @param enumType the enum type's class * @param defaultValue the default value if value can't be parsed into an {@link Enum} * @return the parsed {@link Enum} or the defaultValue if value can't be parsed into an {@link Enum} */ public static <E extends Enum<E>> E intoEnum(Object value, Class<E> enumType, E defaultValue) { final E e = doIntoEnum(value, enumType); return e == null ? defaultValue : e; } private static String doIntoString(Object value) { return value == null ? null : value.toString(); } /** * Parses a value of a generic type * into a {@link String}. * * @param value the value being parsed * @return the parsed {@link String} * @throws IllegalArgumentException if conversion failed */ public static String intoString(Object value) { final String converted = doIntoString(value); if (value == null) { throw fail(value, String.class); } else { return converted; } } /** * Parses a value of a generic type * into a {@link String}. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link String} * @return the parsed {@link String} or the defaultValue if value can't be parsed into a {@link String} */ public static String intoString(Object value, String defaultValue) { final String converted = doIntoString(value); return value == null ? defaultValue : converted; } private static Locale doIntoLocale(Object value) { if (value == null) return null; if (value instanceof Locale) return Locale.class.cast(value); final String string = doIntoString(value); final Matcher matcher = Patterns.LOCALE.matcher(string); if (matcher.matches()) { final String language = StringUtils.defaultString(matcher.group(1)); final String country = StringUtils.defaultString(matcher.group(2)); final String variant = StringUtils.defaultString(matcher.group(3)); return new Locale(language, country, variant); } else { return null; } } /** * Parses a value of a generic type into a {@link Locale}. * * @param value the value being parsed * @return the parsed {@link Locale} * @throws IllegalArgumentException if conversion failed */ public static Locale intoLocale(Object value) { final Locale locale = doIntoLocale(value); if (locale == null) { throw fail(value, Locale.class); } else { return locale; } } /** * Parses a value of a generic type into a {@link Locale}. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link Locale} * @return the parsed {@link Locale} of the defaultValue if value can't be parsed into a {@link Locale} */ public static Locale intoLocale(Object value, Locale defaultValue) { final Locale locale = doIntoLocale(value); return locale == null ? defaultValue : locale; } private static List<Object> doIntoList(Object value) { if (value == null) return null; if (value instanceof List<?>) { // cast is safe, because everything is an object @SuppressWarnings("unchecked") final List<Object> list = List.class.cast(value); return list; } else if (value.getClass().isArray()) { final Object[] array = Object[].class.cast(value); return Lists.newArrayList(array); } else if (value instanceof Iterable<?>) { final Iterable<?> iterable = Iterable.class.cast(value); return Lists.newArrayList(iterable); } else if (value instanceof Iterator<?>) { final Iterator<?> iterator = Iterator.class.cast(value); return Lists.newArrayList(iterator); } else { return null; } } /** * Parses a value of a generic type into a {@link List}. * * This method transforms any kind of the following into a {@link List}. * <ul> * <li>{@link List}</li> * <li>Array</li> * <li>{@link Iterable}</li> * <li>{@link Iterator}</li> * </ul> * * @param value the value being parsed * @return the parsed {@link List} * @throws IllegalArgumentException if conversion failed */ public static List<Object> intoList(Object value) { final List<Object> list = doIntoList(value); if (list == null) { throw fail(value, List.class); } else { return list; } } /** * Parses a value of a generic type into a {@link List}. * * This method transforms any kind of the following into a {@link List}. * <ul> * <li>{@link List}</li> * <li>Array</li> * <li>{@link Iterable}</li> * <li>{@link Iterator}</li> * </ul> * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link List} * @return the parsed {@link List} or the defaultValue if value can't be parsed into a {@link List} */ public static List<Object> intoList(Object value, List<Object> defaultValue) { final List<Object> list = doIntoList(value); return list == null ? defaultValue : list; } /** * Parses a value of a generic type into a {@link UtilityList}. * * This method uses the same features as {@link Convert#intoList(Object)}. * * @param value the value being parsed * @return the parses {@link UtilityList} * @throws IllegalArgumentException if conversion failed */ public static UtilityList<Object> intoUtilityList(Object value) { final List<Object> list = doIntoList(value); if (list == null) { throw fail(value, UtilityList.class); } else { return Utility.asUtilityList(list); } } /** * Parses a value of a generic type into a {@link UtilityList}. * * This method uses the same features as {@link Convert#intoList(Object)}. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link UtilityList} * @return the parsed {@link UtilityList} or the defaultValue if value can't be parsed into a {@link UtilityList} */ public static UtilityList<Object> intoUtilityList(Object value, UtilityList<Object> defaultValue) { final List<Object> list = doIntoList(value); return list == null ? defaultValue : Utility.asUtilityList(list); } private static Map<Object, Object> doIntoMap(Object value) { if (value == null) return null; if (value instanceof Map<?, ?>) { // cast is safe, because everything is an object @SuppressWarnings("unchecked") final Map<Object, Object> map = Map.class.cast(value); return map; } else if (value instanceof Multimap<?, ?>) { // cast is safe, because everything is an object @SuppressWarnings("unchecked") final Map<Object, Object> map = Multimap.class.cast(value).asMap(); return map; } else { return null; } } /** * Parses a value of a generic type into a {@link Map}. * * This method transforms any kind of the following into a {@link Map}. * <ul> * <li>{@link Map}</li> * <li>{@link Multimap}</li> * </ul> * * @param value the value being parsed * @return the parsed {@link Map} * @throws IllegalArgumentException if conversion failed */ public static Map<Object, Object> intoMap(Object value) { final Map<Object, Object> map = doIntoMap(value); if (map == null) { throw fail(value, Map.class); } else { return map; } } /** * Parses a value of a generic type into a {@link Map}. * * This method transforms any kind of the following into a {@link Map}. * <ul> * <li>{@link Map}</li> * <li>{@link Multimap}</li> * </ul> * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link Map} * @return the parsed {@link Map} or the defaultValue if value can't be parsed into a {@link Map} */ public static Map<Object, Object> intoMap(Object value, Map<Object, Object> defaultValue) { final Map<Object, Object> map = doIntoMap(value); return map == null ? defaultValue : map; } /** * Parses a value of a generic type into a {@link UtilityMap}. * * This method uses the same features as {@link Convert#intoMap(Object)}. * * @param value the value being parsed * @return the parsed {@link UtilityMap} * @throws IllegalArgumentException if conversion failed */ public static UtilityMap<Object, Object> intoUtilityMap(Object value) { final Map<Object, Object> map = doIntoMap(value); if (map == null) { throw fail(value, UtilityMap.class); } else { return Utility.asUtilityMap(map); } } /** * Parses a value of a generic type into a {@link UtilityMap}. * * This method uses the same features as {@link Convert#intoMap(Object, Map)}. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link UtilityMap} * @return the parsed {@link UtilityMap} or the defaultValue if value can't be parsed into a {@link UtilityMap} */ public static UtilityMap<Object, Object> intoUtilityMap(Object value, UtilityMap<Object, Object> defaultValue) { final Map<Object, Object> map = doIntoMap(value); return map == null ? defaultValue : Utility.asUtilityMap(map); } }
src/main/java/de/cosmocode/collections/utility/Convert.java
/** * Copyright 2010 CosmoCode GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.cosmocode.collections.utility; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import de.cosmocode.commons.DateMode; import de.cosmocode.commons.Enums; import de.cosmocode.commons.Patterns; /** * Utility class providing method to convert * genericly typed parameters into strongly * typed primitives or well known * and widely used objects. * * @author Willi Schoenborn */ public final class Convert { private static final Logger LOG = LoggerFactory.getLogger(Convert.class); /** * Prevent instantiation. */ private Convert() { } private static RuntimeException fail(Object value, Class<?> type) { final String message = "'" + value + "' couldn't be converted into '" + type.getName() + "'"; return new IllegalArgumentException(message); } private static Boolean doIntoBoolean(Object value) { if (value == null) return null; if (value instanceof Boolean) return Boolean.class.cast(value); final String converted = doIntoString(value); if ("true".equalsIgnoreCase(converted)) { return Boolean.TRUE; } else if ("false".equalsIgnoreCase(converted)) { return Boolean.FALSE; } else { return null; } } /** * Parses a value of a generic type * into a boolean. * * @param value the value being parsed * @return the parsed boolean * @throws IllegalArgumentException if conversion failed */ public static boolean intoBoolean(Object value) { final Boolean b = doIntoBoolean(value); if (b == null) { throw fail(value, boolean.class); } else { return b.booleanValue(); } } /** * Parses a value of a generic type * into a boolean. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a boolean * @return the parsed boolean or the defaultValue if value can't be parsed into a boolean */ public static boolean intoBoolean(Object value, boolean defaultValue) { final Boolean b = doIntoBoolean(value); return b == null ? defaultValue : b.booleanValue(); } private static Long doIntoLong(Object value) { if (value == null) return null; if (value instanceof Long) return Long.class.cast(value); if (value instanceof Number) return Number.class.cast(value).longValue(); final String s = doIntoString(value); try { return Long.valueOf(s); } catch (NumberFormatException e) { return null; } } /** * Parses a value of a generic type * into a long. * * @param value the value being parsed * @return the parsed long * @throws IllegalArgumentException if conversion failed */ public static long intoLong(Object value) { final Long l = doIntoLong(value); if (l == null) { throw fail(value, long.class); } else { return l.longValue(); } } /** * Parses a value of a generic type * into a long. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a long * @return the parsed long or the defaultValue if value can't be parsed into a long */ public static long intoLong(Object value, long defaultValue) { final Long l = doIntoLong(value); return l == null ? defaultValue : l.longValue(); } private static Double doIntoDouble(Object value) { if (value == null) return null; if (value instanceof Double) return Double.class.cast(value); if (value instanceof Number) return Number.class.cast(value).doubleValue(); final String s = doIntoString(value); try { final Double d = Double.valueOf(s); LOG.debug("Converted {} into {}", value, d); if (d.isInfinite() || d.isNaN()) return null; return d; } catch (NumberFormatException e) { return null; } } /** * Parses a value of a generic type * into a double. * * @param value the value being parsed * @return the parsed double * @throws IllegalArgumentException if conversion failed */ public static double intoDouble(Object value) { final Double d = doIntoDouble(value); if (d == null) { throw fail(value, double.class); } else { return d.doubleValue(); } } /** * Parses a value of a generic type * into a double. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a double * @return the parsed double or the defaultValue if value can't be parsed into a double */ public static double intoDouble(Object value, double defaultValue) { final Double d = doIntoDouble(value); return d == null ? defaultValue : d.doubleValue(); } private static Date doIntoDate(Object value, DateMode dateMode) { Preconditions.checkNotNull(dateMode, "DateMode"); if (value == null) return null; if (value instanceof Date) return Date.class.cast(value); if (value instanceof Calendar) return Calendar.class.cast(value).getTime(); final Long time = doIntoLong(value); return time == null || time.longValue() < 0 ? null : dateMode.parse(time.longValue()); } /** * Parses a value of a generic type * into a {@link Date}. * * @param value the value being parsed * @return the parsed {@link Date} * @throws IllegalArgumentException if conversion failed */ public static Date intoDate(Object value) { return intoDate(value, DateMode.JAVA); } /** * Parses a value of a generic type * into a {@link Date}. * * @param value the value being parsed * @param dateMode a {@link DateMode} instance handling the long to time conversion * @return the parsed {@link Date} * @throws NullPointerException if dateMode is null * @throws IllegalArgumentException if conversion failed */ public static Date intoDate(Object value, DateMode dateMode) { final Date date = doIntoDate(value, dateMode); if (date == null) { throw fail(value, Date.class); } else { return date; } } /** * Parses a value of a generic type * into a {@link Date}. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link Date} * @return the parsed {@link Date} */ public static Date intoDate(Object value, Date defaultValue) { return intoDate(value, DateMode.JAVA, defaultValue); } /** * Parses a value of a generic type * into a {@link Date}. * * @param value the value being parsed * @param dateMode the {@link DateMode} being used to convert long to {@link Date} * @param defaultValue the default value if value can't be parsed into a {@link Date} * @return the parsed {@link Date} or the defaultValue if value can't be parsed into a {@link Date} * @throws NullPointerException if dateMode is null */ public static Date intoDate(Object value, DateMode dateMode, Date defaultValue) { final Date date = doIntoDate(value, dateMode); return date == null ? defaultValue : date; } private static <E extends Enum<E>> E doIntoEnum(Object value, Class<E> enumType) { Preconditions.checkNotNull(enumType, "EnumType"); if (enumType.isInstance(value)) return enumType.cast(value); final Long ordinal = doIntoLong(value); if (ordinal == null) { final String name = doIntoString(value); if (name == null) return null; try { return Enum.valueOf(enumType, name.toUpperCase()); } catch (IllegalArgumentException e) { return null; } } else { try { return Enums.valueOf(enumType, ordinal.intValue()); } catch (IndexOutOfBoundsException e) { return null; } } } /** * Parses a value of a generic type * into an {@link Enum}. * The value must be either a valid enum constant * name or ordinal. * * @param <E> the generic enum type * @param value the value being parsed * @param enumType the enum type's class * @return the parsed {@link Enum} * @throws NullPointerException if enumType is null * @throws IllegalArgumentException if conversion failed */ public static <E extends Enum<E>> E intoEnum(Object value, Class<E> enumType) { final E e = doIntoEnum(value, enumType); if (e == null) { throw fail(value, enumType); } else { return e; } } /** * Parses a value of a generic type * into an {@link Enum}. * * @param <E> the generic enum type * @param value the value being parsed * @param enumType the enum type's class * @param defaultValue the default value if value can't be parsed into an {@link Enum} * @return the parsed {@link Enum} or the defaultValue if value can't be parsed into an {@link Enum} */ public static <E extends Enum<E>> E intoEnum(Object value, Class<E> enumType, E defaultValue) { final E e = doIntoEnum(value, enumType); return e == null ? defaultValue : e; } private static String doIntoString(Object value) { return value == null ? null : value.toString(); } /** * Parses a value of a generic type * into a {@link String}. * * @param value the value being parsed * @return the parsed {@link String} * @throws IllegalArgumentException if conversion failed */ public static String intoString(Object value) { final String converted = doIntoString(value); if (value == null) { throw fail(value, String.class); } else { return converted; } } /** * Parses a value of a generic type * into a {@link String}. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link String} * @return the parsed {@link String} or the defaultValue if value can't be parsed into a {@link String} */ public static String intoString(Object value, String defaultValue) { final String converted = doIntoString(value); return value == null ? defaultValue : converted; } private static Locale doIntoLocale(Object value) { if (value == null) return null; if (value instanceof Locale) return Locale.class.cast(value); final String string = doIntoString(value); final Matcher matcher = Patterns.LOCALE.matcher(string); if (matcher.matches()) { final String language = StringUtils.defaultString(matcher.group(1)); final String country = StringUtils.defaultString(matcher.group(2)); final String variant = StringUtils.defaultString(matcher.group(3)); return new Locale(language, country, variant); } else { return null; } } /** * Parses a value of a generic type into a {@link Locale}. * * @param value the value being parsed * @return the parsed {@link Locale} * @throws IllegalArgumentException if conversion failed */ public static Locale intoLocale(Object value) { final Locale locale = doIntoLocale(value); if (locale == null) { throw fail(value, Locale.class); } else { return locale; } } /** * Parses a value of a generic type into a {@link Locale}. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link Locale} * @return the parsed {@link Locale} of the defaultValue if value can't be parsed into a {@link Locale} */ public static Locale intoLocale(Object value, Locale defaultValue) { final Locale locale = doIntoLocale(value); return locale == null ? defaultValue : locale; } private static List<Object> doIntoList(Object value) { if (value == null) return null; if (value instanceof List<?>) { // cast is safe, because everything is an object @SuppressWarnings("unchecked") final List<Object> list = List.class.cast(value); return list; } else if (value.getClass().isArray()) { final Object[] array = Object[].class.cast(value); return Lists.newArrayList(array); } else if (value instanceof Iterable<?>) { final Iterable<?> iterable = Iterable.class.cast(value); return Lists.newArrayList(iterable); } else if (value instanceof Iterator<?>) { final Iterator<?> iterator = Iterator.class.cast(value); return Lists.newArrayList(iterator); } else { return null; } } /** * Parses a value of a generic type into a {@link List}. * * This method transforms any kind of the following into a {@link List}. * <ul> * <li>{@link List}</li> * <li>Array</li> * <li>{@link Iterable}</li> * <li>{@link Iterator}</li> * </ul> * * @param value the value being parsed * @return the parsed {@link List} * @throws IllegalArgumentException if conversion failed */ public static List<Object> intoList(Object value) { final List<Object> list = doIntoList(value); if (list == null) { throw fail(value, List.class); } else { return list; } } /** * Parses a value of a generic type into a {@link List}. * * This method transforms any kind of the following into a {@link List}. * <ul> * <li>{@link List}</li> * <li>Array</li> * <li>{@link Iterable}</li> * <li>{@link Iterator}</li> * </ul> * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link List} * @return the parsed {@link List} or the defaultValue if value can't be parsed into a {@link List} */ public static List<Object> intoList(Object value, List<Object> defaultValue) { final List<Object> list = doIntoList(value); return list == null ? defaultValue : list; } /** * Parses a value of a generic type into a {@link UtilityList}. * * This method uses the same features as {@link Convert#intoList(Object)}. * * @param value the value being parsed * @return the parses {@link UtilityList} * @throws IllegalArgumentException if conversion failed */ public static UtilityList<Object> intoUtilityList(Object value) { final List<Object> list = doIntoList(value); if (list == null) { throw fail(value, UtilityList.class); } else { return Utility.asUtilityList(list); } } /** * Parses a value of a generic type into a {@link UtilityList}. * * This method uses the same features as {@link Convert#intoList(Object)}. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link UtilityList} * @return the parsed {@link UtilityList} or the defaultValue if value can't be parsed into a {@link UtilityList} */ public static UtilityList<Object> intoUtilityList(Object value, UtilityList<Object> defaultValue) { final List<Object> list = doIntoList(value); return list == null ? defaultValue : Utility.asUtilityList(list); } private static Map<Object, Object> doIntoMap(Object value) { if (value == null) return null; if (value instanceof Map<?, ?>) { // cast is safe, because everything is an object @SuppressWarnings("unchecked") final Map<Object, Object> map = Map.class.cast(value); return map; } else if (value instanceof Multimap<?, ?>) { // cast is safe, because everything is an object @SuppressWarnings("unchecked") final Map<Object, Object> map = Multimap.class.cast(value).asMap(); return map; } else { return null; } } /** * Parses a value of a generic type into a {@link Map}. * * This method transforms any kind of the following into a {@link Map}. * <ul> * <li>{@link Map}</li> * <li>{@link Multimap}</li> * </ul> * * @param value the value being parsed * @return the parsed {@link Map} * @throws IllegalArgumentException if conversion failed */ public static Map<Object, Object> intoMap(Object value) { final Map<Object, Object> map = doIntoMap(value); if (map == null) { throw fail(value, Map.class); } else { return map; } } /** * Parses a value of a generic type into a {@link Map}. * * This method transforms any kind of the following into a {@link Map}. * <ul> * <li>{@link Map}</li> * <li>{@link Multimap}</li> * </ul> * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link Map} * @return the parsed {@link Map} or the defaultValue if value can't be parsed into a {@link Map} */ public static Map<Object, Object> intoMap(Object value, Map<Object, Object> defaultValue) { final Map<Object, Object> map = doIntoMap(value); return map == null ? defaultValue : map; } /** * Parses a value of a generic type into a {@link UtilityMap}. * * This method uses the same features as {@link Convert#intoMap(Object)}. * * @param value the value being parsed * @return the parsed {@link UtilityMap} * @throws IllegalArgumentException if conversion failed */ public static UtilityMap<Object, Object> intoUtilityMap(Object value) { final Map<Object, Object> map = doIntoMap(value); if (map == null) { throw fail(value, UtilityMap.class); } else { return Utility.asUtilityMap(map); } } /** * Parses a value of a generic type into a {@link UtilityMap}. * * This method uses the same features as {@link Convert#intoMap(Object, Map)}. * * @param value the value being parsed * @param defaultValue the default value if value can't be parsed into a {@link UtilityMap} * @return the parsed {@link UtilityMap} or the defaultValue if value can't be parsed into a {@link UtilityMap} */ public static UtilityMap<Object, Object> intoUtilityMap(Object value, UtilityMap<Object, Object> defaultValue) { final Map<Object, Object> map = doIntoMap(value); return map == null ? defaultValue : Utility.asUtilityMap(map); } }
suppressed findbugs warning
src/main/java/de/cosmocode/collections/utility/Convert.java
suppressed findbugs warning
<ide><path>rc/main/java/de/cosmocode/collections/utility/Convert.java <ide> return new IllegalArgumentException(message); <ide> } <ide> <add> @edu.umd.cs.findbugs.annotations.SuppressWarnings("NP_BOOLEAN_RETURN_NULL") <ide> private static Boolean doIntoBoolean(Object value) { <ide> if (value == null) return null; <ide> if (value instanceof Boolean) return Boolean.class.cast(value);
Java
epl-1.0
7d42d5ad6f2c80405d235a1dcdeb96cf6f9c4bca
0
laercioferracini/junit,marcphilipp/junit,UnimibSoftEngCourse1516/lab2-es3-e.nani1,Clairebi/JUnit-Clone,UnimibSoftEngCourse1516/lab2-es3-i.pigazzini,feisuo/junit,edwardmlyte/junit,alb-i986/junit,mnk/junit,feisuo/junit,UnimibSoftEngCourse1516/lab2-es3-i.pigazzini,UrsMetz/junit,janocat/junit,freezhan/junit,yusuke/junit,UnimibSoftEngCourse1516/lab2-es3-f.giannini3,schauder/junit,smayoorans/junit,UnimibSoftEngCourse1516/lab2-es3-m.scarpone,chrisvest/junit,mnk/junit,quentin9696/junit,cherryleer/junit,UnimibSoftEngCourse1516/lab2-es3-m.polonioli,panchenko/junit,chrisvest/junit,hansjoachim/junit,UnimibSoftEngCourse1516/lab2-es3-f.spinardi,JoaquinSiabra/junit,dvberkel/junit,rwarren14/junit,junit-team/junit,baev/junit,UnimibSoftEngCourse1516/lab2-es3-m.vella6,adko-pl/junit,vorburger/junit,rwarren14/junit,jhfjhfj1/junit,UnimibSoftEngCourse1516/lab2-es3-m.scarpone,mekwin87/junit4,mekwin87/junit4,songfj/junit,UnimibSoftEngCourse1516/lab2-es3-m.vella6,janocat/junit,kobe73er/dUnit,paulduffin/junit,stefanbirkner/junit,powazny/junit4,onesfreedom/junit,UnimibSoftEngCourse1516/lab2-es3-m.vella6,marcphilipp/junit,jordancheah/junit,jhfjhfj1/junit,hhariri/junit,JoaquinSiabra/junit,slezier/junit,UnimibSoftEngCourse1516/lab2-es3-f.cirelli1,kcooney/junit,yusuke/junit,edwardmlyte/junit,Siddartha07/junit,junit-team/junit,UnimibSoftEngCourse1516/lab2-es3-m.polonioli,moinuddin14/junit,moinuddin14/junit,onesfreedom/junit,UnimibSoftEngCourse1516/lab2-es3-m.polonioli,MattiasBuelens/junit,junit-team/junit4,smayoorans/junit,UnimibSoftEngCourse1516/lab2-es3-o.sertori,adko-pl/junit,UnimibSoftEngCourse1516/lab2-es3-a.mosini,freezhan/junit,larrychen1990/junit,flomotlik/junit,avandeursen/junit,arjenw/junit,rws-github/junit,dvberkel/junit,UnimibSoftEngCourse1516/lab2-es3-s.ravetta,kobe73er/MyUnit,easyMan-zzy/junit,yusuke/junit,laercioferracini/junit,Clairebi/JUnit-Clone,Thothius/junit,remus32/junit,jhfjhfj1/junit,eamonnmcmanus/junit,rwarren14/junit,janocat/junit,MattiasBuelens/junit,UnimibSoftEngCourse1516/lab2-es3-o.sertori,larrychen1990/junit,rws-github/junit,panchenko/junit,AxelMonroyX/junit4,UnimibSoftEngCourse1516/lab2-es3-a.tundo,UnimibSoftEngCourse1516/lab2-es3-a.mosini,mekwin87/junit4,kobe73er/MyUnit,arjenw/junit,julien-sobczak/junit,chrisvest/junit,jordancheah/junit,MichaelJY91/junit,openhardnudd/junit,y-kt/junit,schauder/junit,UnimibSoftEngCourse1516/lab2-es3-f.spinardi,schauder/junit,quentin9696/junit,kobe73er/dUnit,VikingDen/junit,songfj/junit,UnimibSoftEngCourse1516/lab2-es3-s.renzo,UnimibSoftEngCourse1516/lab2-es3-f.cirelli1,MattiasBuelens/junit,paulduffin/junit,kcooney/junit-test,laercioferracini/junit,kobe73er/dUnit,quentin9696/junit,feisuo/junit,arjenw/junit,MingxuanChen/junit,stefanbirkner/junit,UnimibSoftEngCourse1516/lab2-es3-f.spinardi,junit-team/junit4,MattiasBuelens/junit,junit-team/junit4,rws-github/junit,MingxuanChen/junit,0359xiaodong/junit,alb-i986/junit,witcxc/junit,1234-/junit,MichaelJY91/junit,MingxuanChen/junit,elijah513/junit,UnimibSoftEngCourse1516/lab2-es3-o.sertori,UnimibSoftEngCourse1516/lab2-es3-l.salvestrini,sposam/junit,alohageck0/junit,slezier/junit,larrychen1990/junit,nathanchen/JUnitCodeReading,UnimibSoftEngCourse1516/lab2-es3-l.salvestrini,easyMan-zzy/junit,julien-sobczak/junit,UnimibSoftEngCourse1516/lab2-es3-f.giannini3,moinuddin14/junit,flomotlik/junit,nathanchen/JUnitCodeReading,freezhan/junit,hhariri/junit,arjenw/junit,jordancheah/junit,y-kt/junit,UnimibSoftEngCourse1516/lab2-es3-i.pigazzini,ashleyfrieze/junit,smayoorans/junit,adko-pl/junit,witcxc/junit,flomotlik/junit,baev/junit,UnimibSoftEngCourse1516/lab2-es3-e.nani1,ashleyfrieze/junit,songfj/junit,kcooney/junit,UnimibSoftEngCourse1516/lab2-es3-m.scarpone,UnimibSoftEngCourse1516/lab2-es3-s.renzo,alb-i986/junit,avandeursen/junit,witcxc/junit,remus32/junit,junit-team/junit,kcooney/junit-test,VikingDen/junit,remus32/junit,1234-/junit,UrsMetz/junit,JoaquinSiabra/junit,UnimibSoftEngCourse1516/lab2-es3-a.tundo,julien-sobczak/junit,hansjoachim/junit,MichaelJY91/junit,mnk/junit,dvberkel/junit,vorburger/junit,UrsMetz/junit,1234-/junit,ashleyfrieze/junit,mekwin87/junit4,vorburger/junit,UnimibSoftEngCourse1516/lab2-es3-a.mosini,UrsMetz/junit,paulduffin/junit,alohageck0/junit,UnimibSoftEngCourse1516/lab2-es3-s.ravetta,elijah513/junit,rws-github/junit,UnimibSoftEngCourse1516/lab2-es3-f.cirelli1,openhardnudd/junit,panchenko/junit,hhariri/junit,UnimibSoftEngCourse1516/lab2-es3-s.ravetta,slezier/junit,sposam/junit,Thothius/junit,kobe73er/MyUnit,Siddartha07/junit,stefanbirkner/junit,UnimibSoftEngCourse1516/lab2-es3-a.tundo,UnimibSoftEngCourse1516/lab2-es3-e.nani1,avandeursen/junit,rws-github/junit,cherryleer/junit,GeeChao/junit,0359xiaodong/junit,y-kt/junit,easyMan-zzy/junit,GeeChao/junit,elijah513/junit,nathanchen/JUnitCodeReading,powazny/junit4,hansjoachim/junit,cherryleer/junit,kcooney/junit,Siddartha07/junit,eamonnmcmanus/junit,0359xiaodong/junit,Thothius/junit,VikingDen/junit,powazny/junit4,UnimibSoftEngCourse1516/lab2-es3-s.renzo,GeeChao/junit,alohageck0/junit,AxelMonroyX/junit4,vorburger/junit,onesfreedom/junit,kcooney/junit-test,UnimibSoftEngCourse1516/lab2-es3-l.salvestrini,nathanchen/JUnitCodeReading,baev/junit,AxelMonroyX/junit4,marcphilipp/junit,sposam/junit,eamonnmcmanus/junit,openhardnudd/junit,UnimibSoftEngCourse1516/lab2-es3-f.giannini3,Clairebi/JUnit-Clone,edwardmlyte/junit
package junit.swingui; import java.awt.*; import javax.swing.*; /** * A panel with test run counters */ public class CounterPanel extends JPanel { private JTextField fNumberOfErrors; private JTextField fNumberOfFailures; private JTextField fNumberOfRuns; private Icon fFailureIcon= TestRunner.getIconResource(getClass(), "icons/failure.gif"); private Icon fErrorIcon= TestRunner.getIconResource(getClass(), "icons/error.gif"); private int fTotal; public CounterPanel() { super(new GridBagLayout()); fNumberOfErrors= createOutputField(5); fNumberOfFailures= createOutputField(5); fNumberOfRuns= createOutputField(9); addToGrid(new JLabel("Runs:", JLabel.CENTER), 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0)); addToGrid(fNumberOfRuns, 1, 0, 1, 1, 0.33, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 8, 0, 0)); addToGrid(new JLabel("Errors:", fErrorIcon, SwingConstants.LEFT), 2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 8, 0, 0)); addToGrid(fNumberOfErrors, 3, 0, 1, 1, 0.33, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 8, 0, 0)); addToGrid(new JLabel("Failures:", fFailureIcon, SwingConstants.LEFT), 4, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 8, 0, 0)); addToGrid(fNumberOfFailures, 5, 0, 1, 1, 0.33, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 8, 0, 0)); } private JTextField createOutputField(int width) { JTextField field= new JTextField("0", width); field.setHorizontalAlignment(JTextField.LEFT); field.setFont(StatusLine.BOLD_FONT); field.setEditable(false); field.setBorder(BorderFactory.createEmptyBorder()); return field; } public void addToGrid(Component comp, int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets) { GridBagConstraints constraints= new GridBagConstraints(); constraints.gridx= gridx; constraints.gridy= gridy; constraints.gridwidth= gridwidth; constraints.gridheight= gridheight; constraints.weightx= weightx; constraints.weighty= weighty; constraints.anchor= anchor; constraints.fill= fill; constraints.insets= insets; add(comp, constraints); } public void reset() { setLabelValue(fNumberOfErrors, 0); setLabelValue(fNumberOfFailures, 0); setLabelValue(fNumberOfRuns, 0); fTotal= 0; } public void setTotal(int value) { fTotal= value; } public void setRunValue(int value) { fNumberOfRuns.setText(Integer.toString(value) + "/" + fTotal); } public void setErrorValue(int value) { setLabelValue(fNumberOfErrors, value); } public void setFailureValue(int value) { setLabelValue(fNumberOfFailures, value); } private String asString(int value) { return Integer.toString(value); } private void setLabelValue(JTextField label, int value) { label.setText(Integer.toString(value)); } }
junit/swingui/CounterPanel.java
package junit.swingui; import java.awt.*; import java.awt.GridLayout; import javax.swing.*; /** * A panel with test run counters */ public class CounterPanel extends JPanel { private JTextField fNumberOfErrors; private JTextField fNumberOfFailures; private JTextField fNumberOfRuns; private Icon fFailureIcon= TestRunner.getIconResource(getClass(), "icons/failure.gif"); private Icon fErrorIcon= TestRunner.getIconResource(getClass(), "icons/error.gif"); private int fTotal; public CounterPanel() { super(new GridBagLayout()); fNumberOfErrors= createOutputField(5); fNumberOfFailures= createOutputField(5); fNumberOfRuns= createOutputField(9); addToGrid(new JLabel("Runs:", JLabel.CENTER), 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0)); addToGrid(fNumberOfRuns, 1, 0, 1, 1, 0.33, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 8, 0, 0)); addToGrid(new JLabel("Errors:", fErrorIcon, SwingConstants.LEFT), 2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 8, 0, 0)); addToGrid(fNumberOfErrors, 3, 0, 1, 1, 0.33, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 8, 0, 0)); addToGrid(new JLabel("Failures:", fFailureIcon, SwingConstants.LEFT), 4, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 8, 0, 0)); addToGrid(fNumberOfFailures, 5, 0, 1, 1, 0.33, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(0, 8, 0, 0)); } private JTextField createOutputField(int width) { JTextField field= new JTextField("0", width); field.setHorizontalAlignment(JTextField.LEFT); field.setFont(StatusLine.BOLD_FONT); field.setEditable(false); field.setBorder(BorderFactory.createEmptyBorder()); return field; } public void addToGrid(Component comp, int gridx, int gridy, int gridwidth, int gridheight, double weightx, double weighty, int anchor, int fill, Insets insets) { GridBagConstraints constraints= new GridBagConstraints(); constraints.gridx= gridx; constraints.gridy= gridy; constraints.gridwidth= gridwidth; constraints.gridheight= gridheight; constraints.weightx= weightx; constraints.weighty= weighty; constraints.anchor= anchor; constraints.fill= fill; constraints.insets= insets; add(comp, constraints); } public void reset() { setLabelValue(fNumberOfErrors, 0); setLabelValue(fNumberOfFailures, 0); setLabelValue(fNumberOfRuns, 0); fTotal= 0; } public void setTotal(int value) { fTotal= value; } public void setRunValue(int value) { fNumberOfRuns.setText(Integer.toString(value) + "/" + fTotal); } public void setErrorValue(int value) { setLabelValue(fNumberOfErrors, value); } public void setFailureValue(int value) { setLabelValue(fNumberOfFailures, value); } private String asString(int value) { return Integer.toString(value); } private void setLabelValue(JTextField label, int value) { label.setText(Integer.toString(value)); } }
Remove extra import.
junit/swingui/CounterPanel.java
Remove extra import.
<ide><path>unit/swingui/CounterPanel.java <ide> package junit.swingui; <ide> <ide> import java.awt.*; <del>import java.awt.GridLayout; <ide> <ide> import javax.swing.*; <ide> <ide> private Icon fErrorIcon= TestRunner.getIconResource(getClass(), "icons/error.gif"); <ide> <ide> private int fTotal; <del> <add> <ide> public CounterPanel() { <del> super(new GridBagLayout()); <add> super(new GridBagLayout()); <ide> fNumberOfErrors= createOutputField(5); <ide> fNumberOfFailures= createOutputField(5); <del> fNumberOfRuns= createOutputField(9); <del> <add> fNumberOfRuns= createOutputField(9); <add> <ide> addToGrid(new JLabel("Runs:", JLabel.CENTER), <ide> 0, 0, 1, 1, 0.0, 0.0, <ide> GridBagConstraints.CENTER, GridBagConstraints.NONE, <ide> 1, 0, 1, 1, 0.33, 0.0, <ide> GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, <ide> new Insets(0, 8, 0, 0)); <del> <add> <ide> addToGrid(new JLabel("Errors:", fErrorIcon, SwingConstants.LEFT), <ide> 2, 0, 1, 1, 0.0, 0.0, <ide> GridBagConstraints.CENTER, GridBagConstraints.NONE, <ide> 3, 0, 1, 1, 0.33, 0.0, <ide> GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, <ide> new Insets(0, 8, 0, 0)); <del> <add> <ide> addToGrid(new JLabel("Failures:", fFailureIcon, SwingConstants.LEFT), <ide> 4, 0, 1, 1, 0.0, 0.0, <ide> GridBagConstraints.CENTER, GridBagConstraints.NONE, <ide> 5, 0, 1, 1, 0.33, 0.0, <ide> GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, <ide> new Insets(0, 8, 0, 0)); <del> } <del> <add> } <add> <ide> private JTextField createOutputField(int width) { <ide> JTextField field= new JTextField("0", width); <ide> field.setHorizontalAlignment(JTextField.LEFT); <ide> double weightx, double weighty, <ide> int anchor, int fill, <ide> Insets insets) { <del> <add> <ide> GridBagConstraints constraints= new GridBagConstraints(); <ide> constraints.gridx= gridx; <ide> constraints.gridy= gridy; <ide> constraints.insets= insets; <ide> add(comp, constraints); <ide> } <del> <add> <ide> public void reset() { <ide> setLabelValue(fNumberOfErrors, 0); <ide> setLabelValue(fNumberOfFailures, 0); <ide> setLabelValue(fNumberOfRuns, 0); <ide> fTotal= 0; <ide> } <del> <add> <ide> public void setTotal(int value) { <ide> fTotal= value; <ide> } <del> <add> <ide> public void setRunValue(int value) { <ide> fNumberOfRuns.setText(Integer.toString(value) + "/" + fTotal); <ide> } <del> <add> <ide> public void setErrorValue(int value) { <ide> setLabelValue(fNumberOfErrors, value); <ide> } <del> <add> <ide> public void setFailureValue(int value) { <ide> setLabelValue(fNumberOfFailures, value); <ide> } <del> <add> <ide> private String asString(int value) { <ide> return Integer.toString(value); <ide> } <del> <add> <ide> private void setLabelValue(JTextField label, int value) { <ide> label.setText(Integer.toString(value)); <ide> }
Java
mit
862f8f30ea1f34416abc8c8149b22a324c63a78d
0
sephiroth74/Material-BottomNavigation,sephiroth74/Material-BottomNavigation
/** * The MIT License (MIT) * <p> * Copyright (c) 2016 Alessandro Crugnola * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package it.sephiroth.android.library.bottomnavigation; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.LayerDrawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.IdRes; import android.support.annotation.MenuRes; import android.support.design.widget.CoordinatorLayout; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.readystatesoftware.systembartint.SystemBarTintManager; import java.lang.ref.SoftReference; import it.sephiroth.android.library.bottonnavigation.R; import static android.util.Log.INFO; import static android.util.Log.VERBOSE; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static it.sephiroth.android.library.bottomnavigation.MiscUtils.log; /** * Created by alessandro crugnola on 4/2/16. * BottomNavigation */ public class BottomNavigation extends FrameLayout implements OnItemClickListener { private static final String TAG = BottomNavigation.class.getSimpleName(); public static final boolean DEBUG = true; static final int PENDING_ACTION_NONE = 0x0; static final int PENDING_ACTION_EXPANDED = 0x1; static final int PENDING_ACTION_COLLAPSED = 0x2; static final int PENDING_ACTION_ANIMATE_ENABLED = 0x4; /** * Current pending action (used inside the BottomBehavior instance) */ private int mPendingAction = PENDING_ACTION_NONE; /** * This is the amount of space we have to cover in case there's a translucent navigation * enabled. */ private int bottomInset; /** * This is the amount of space we have to cover in case there's a translucent status * enabled. */ private int topInset; /** * This is the current view height. It does take into account the extra space * used in case we have to cover the navigation translucent area, and neither the shadow height. */ private int defaultHeight; /** * Same as defaultHeight, but for tablet mode. */ private int defaultWidth; /** * Shadow is created above the widget background. It simulates the * elevation. */ private int shadowHeight; /** * Layout container used to create and manage the UI items. * It can be either Fixed or Shifting, based on the widget `mode` */ private ItemsLayoutContainer itemsContainer; /** * This is where the color animation is happening */ private View backgroundOverlay; /** * current menu */ private MenuParser.Menu menu; private MenuParser.Menu pendingMenu; /** * Default selected index. * After the items are populated changing this * won't have any effect */ private int defaultSelectedIndex = 0; /** * View visible background color */ private ColorDrawable backgroundDrawable; /** * Animation duration for the background color change */ private long backgroundColorAnimation; /** * Optional typeface used for the items' text labels */ SoftReference<Typeface> typeface; /** * Current BottomBehavior assigned from the CoordinatorLayout */ private Object mBehavior; /** * Menu selection listener */ private OnMenuItemSelectionListener listener; /** * The user defined layout_gravity */ private int gravity; /** * View is attached */ private boolean attached; public BottomNavigation(final Context context) { this(context, null); } public BottomNavigation(final Context context, final AttributeSet attrs) { super(context, attrs); initialize(context, attrs, 0, 0); } public BottomNavigation(final Context context, final AttributeSet attrs, final int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(context, attrs, defStyleAttr, 0); } @TargetApi (Build.VERSION_CODES.LOLLIPOP) public BottomNavigation(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initialize(context, attrs, defStyleAttr, defStyleRes); } @Override protected Parcelable onSaveInstanceState() { log(TAG, INFO, "onSaveInstanceState"); Parcelable parcelable = super.onSaveInstanceState(); SavedState savedState = new SavedState(parcelable); savedState.selectedIndex = getSelectedIndex(); return savedState; } @Override protected void onRestoreInstanceState(final Parcelable state) { log(TAG, INFO, "onRestoreInstanceState"); SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); defaultSelectedIndex = savedState.selectedIndex; log(TAG, Log.DEBUG, "saved selectedIndex: %d", defaultSelectedIndex); } private void initialize(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes) { final Activity activity = (Activity) context; final SystemBarTintManager systembarTint = new SystemBarTintManager(activity); typeface = new SoftReference<>(Typeface.DEFAULT); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.BottomNavigation, defStyleAttr, defStyleRes); final int menuResId = array.getResourceId(R.styleable.BottomNavigation_bbn_entries, 0); pendingMenu = MenuParser.inflateMenu(context, menuResId); array.recycle(); backgroundColorAnimation = getResources().getInteger(R.integer.bbn_background_animation_duration); defaultHeight = getResources().getDimensionPixelSize(R.dimen.bbn_bottom_navigation_height); defaultWidth = getResources().getDimensionPixelSize(R.dimen.bbn_bottom_navigation_width); shadowHeight = getResources().getDimensionPixelOffset(R.dimen.bbn_top_shadow_height); // check if the bottom navigation is translucent if (MiscUtils.hasTranslucentNavigation(activity) && systembarTint.getConfig().isNavigationAtBottom() && systembarTint.getConfig().hasNavigtionBar()) { bottomInset = systembarTint.getConfig().getNavigationBarHeight(); } else { bottomInset = 0; } topInset = systembarTint.getConfig().getStatusBarHeight(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT); backgroundOverlay = new View(getContext()); backgroundOverlay.setLayoutParams(params); addView(backgroundOverlay); } int getPendingAction() { return mPendingAction; } void resetPendingAction() { mPendingAction = PENDING_ACTION_NONE; } @Override public void setLayoutParams(final ViewGroup.LayoutParams params) { log(TAG, INFO, "setLayoutParams: %s", params); super.setLayoutParams(params); } private boolean isTablet(final int gravity) { return MiscUtils.isGravitiyLeft(gravity) || MiscUtils.isGravityRight(gravity); } @SuppressWarnings ("unused") public void setSelectedIndex(final int position, final boolean animate) { if (null != itemsContainer) { setSelectedItemInternal(itemsContainer, ((ViewGroup) itemsContainer).getChildAt(position), position, animate, false); } else { defaultSelectedIndex = position; } } @SuppressWarnings ("unused") public int getSelectedIndex() { if (null != itemsContainer) { return itemsContainer.getSelectedIndex(); } return -1; } @SuppressWarnings ("unused") public void setExpanded(boolean expanded, boolean animate) { log(TAG, INFO, "setExpanded(%b, %b)", expanded, animate); mPendingAction = (expanded ? PENDING_ACTION_EXPANDED : PENDING_ACTION_COLLAPSED) | (animate ? PENDING_ACTION_ANIMATE_ENABLED : 0); requestLayout(); } public boolean isExpanded() { if (null != mBehavior && mBehavior instanceof BottomBehavior) { return ((BottomBehavior) mBehavior).isExpanded(); } return false; } public void setOnMenuItemClickListener(final OnMenuItemSelectionListener listener) { this.listener = listener; } public void setMenuItems(@MenuRes final int menuResId) { defaultSelectedIndex = 0; if (isAttachedToWindow()) { setItems(MenuParser.inflateMenu(getContext(), menuResId)); pendingMenu = null; } else { pendingMenu = MenuParser.inflateMenu(getContext(), menuResId); } } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); log(TAG, INFO, "onMeasure: %d", gravity); if (MiscUtils.isGravityBottom(gravity)) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int widthSize = MeasureSpec.getSize(widthMeasureSpec); if (widthMode == MeasureSpec.AT_MOST) { throw new IllegalArgumentException("layout_width must be equal to `match_parent`"); } setMeasuredDimension(widthSize, defaultHeight + bottomInset + shadowHeight); } else if (MiscUtils.isGravitiyLeft(gravity) || MiscUtils.isGravityRight(gravity)) { final int heightMode = MeasureSpec.getMode(heightMeasureSpec); final int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (heightMode == MeasureSpec.AT_MOST) { throw new IllegalArgumentException("layout_height must be equal to `match_parent`"); } setMeasuredDimension(defaultWidth, heightSize); } else { throw new IllegalArgumentException("invalid layout_gravity. Only one start, end, left, right or bottom is allowed"); } } @SuppressWarnings ("unused") public int getNavigationHeight() { return defaultHeight; } @SuppressWarnings ("unused") public int getNavigationWidth() { return defaultWidth; } @Override protected void onSizeChanged(final int w, final int h, final int oldw, final int oldh) { log(TAG, INFO, "onSizeChanged(%d, %d)", w, h); super.onSizeChanged(w, h, oldw, oldh); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) getLayoutParams(); marginLayoutParams.bottomMargin = -bottomInset; } public boolean isAttachedToWindow() { if (Build.VERSION.SDK_INT >= 19) { return super.isAttachedToWindow(); } return attached; } @Override protected void onAttachedToWindow() { log(TAG, INFO, "onAttachedToWindow"); super.onAttachedToWindow(); attached = true; final CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) getLayoutParams(); this.gravity = GravityCompat.getAbsoluteGravity(params.gravity, ViewCompat.getLayoutDirection(this)); initializeUI(gravity); if (null != pendingMenu) { setItems(pendingMenu); pendingMenu = null; } if (null == mBehavior) { if (CoordinatorLayout.LayoutParams.class.isInstance(params)) { mBehavior = params.getBehavior(); if (BottomBehavior.class.isInstance(mBehavior)) { ((BottomBehavior) mBehavior).setLayoutValues(defaultHeight, bottomInset); } else if (TabletBehavior.class.isInstance(mBehavior)) { boolean translucentStatus = MiscUtils.hasTranslucentStatusBar((Activity) getContext()); ((TabletBehavior) mBehavior).setLayoutValues(defaultWidth, topInset, translucentStatus); } } } } private void setItems(MenuParser.Menu menu) { log(TAG, INFO, "setItems: %s", menu); this.menu = menu; if (null != menu) { if (menu.getItemsCount() < 3 || menu.getItemsCount() > 5) { throw new IllegalArgumentException("BottomNavigation expects 3 to 5 items. " + menu.getItemsCount() + " found"); } menu.setTabletMode(isTablet(gravity)); initializeBackgroundColor(menu); initializeContainer(menu); initializeItems(menu); } requestLayout(); } private void initializeUI(final int gravity) { log(TAG, INFO, "initializeUI(%d)", gravity); final LayerDrawable layerDrawable; final boolean tablet = isTablet(gravity); final int elevation = !tablet ? getResources().getDimensionPixelSize(R.dimen.bbn_elevation) : 0; final int bgResId = !tablet ? R.drawable.bbn_background : (MiscUtils.isGravityRight(gravity) ? R.drawable.bbn_background_tablet_right : R.drawable.bbn_background_tablet_left); final int paddingBottom = !tablet ? shadowHeight : 0; // View elevation ViewCompat.setElevation(this, elevation); // Main background layerDrawable = (LayerDrawable) ContextCompat.getDrawable(getContext(), bgResId); backgroundDrawable = (ColorDrawable) layerDrawable.findDrawableByLayerId(R.id.bbn_background); setBackground(layerDrawable); // Padding bottom setPadding(0, paddingBottom, 0, 0); } private void initializeBackgroundColor(final MenuParser.Menu menu) { log(TAG, INFO, "initializeBackgroundColor"); final int color = menu.getBackground(); log(TAG, VERBOSE, "background: %x", color); backgroundDrawable.setColor(color); } private void initializeContainer(final MenuParser.Menu menu) { log(TAG, INFO, "initializeContainer"); if (null != itemsContainer) { if (menu.isTablet() && !TabletLayout.class.isInstance(itemsContainer)) { removeView((View) itemsContainer); itemsContainer = null; } else if ((menu.isShifting() && !ShiftingLayout.class.isInstance(itemsContainer)) || (!menu.isShifting() && !FixedLayout.class.isInstance(itemsContainer))) { removeView((View) itemsContainer); itemsContainer = null; } else { itemsContainer.removeAll(); } } if (null == itemsContainer) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( menu.isTablet() ? defaultWidth : MATCH_PARENT, menu.isTablet() ? MATCH_PARENT : defaultHeight ); if (menu.isTablet()) { itemsContainer = new TabletLayout(getContext()); } else if (menu.isShifting()) { itemsContainer = new ShiftingLayout(getContext()); } else { itemsContainer = new FixedLayout(getContext()); } itemsContainer.setLayoutParams(params); addView((View) itemsContainer); } } private void initializeItems(final MenuParser.Menu menu) { log(TAG, INFO, "initializeItems"); itemsContainer.setSelectedIndex(defaultSelectedIndex, false); itemsContainer.populate(menu); itemsContainer.setOnItemClickListener(this); if (menu.getItemAt(defaultSelectedIndex).hasColor()) { backgroundDrawable.setColor(menu.getItemAt(defaultSelectedIndex).getColor()); } } @Override public void onItemClick(final ItemsLayoutContainer parent, final View view, final int index, boolean animate) { log(TAG, INFO, "onItemClick: %d", index); setSelectedItemInternal(parent, view, index, animate, true); } private void setSelectedItemInternal( final ItemsLayoutContainer layoutContainer, final View view, final int index, final boolean animate, final boolean fromUser) { final BottomNavigationItem item = menu.getItemAt(index); if (layoutContainer.getSelectedIndex() != index) { layoutContainer.setSelectedIndex(index, animate); if (item.hasColor() && !menu.isTablet()) { if (animate) { MiscUtils.animate( this, view, backgroundOverlay, backgroundDrawable, item.getColor(), backgroundColorAnimation ); } else { MiscUtils.switchColor( this, view, backgroundOverlay, backgroundDrawable, item.getColor() ); } } if (null != listener && fromUser) { listener.onMenuItemSelect(item.getId(), index); } } else { if (null != listener && fromUser) { listener.onMenuItemReselect(item.getId(), index); } } } public void setDefaultTypeface(final Typeface typeface) { this.typeface = new SoftReference<>(typeface); } public void setDefaultSelectedIndex(final int defaultSelectedIndex) { this.defaultSelectedIndex = defaultSelectedIndex; } public interface OnMenuItemSelectionListener { void onMenuItemSelect(@IdRes final int itemId, final int position); void onMenuItemReselect(@IdRes final int itemId, final int position); } static class SavedState extends BaseSavedState { int selectedIndex; public SavedState(Parcel in) { super(in); selectedIndex = in.readInt(); } public SavedState(final Parcelable superState) { super(superState); } @Override public void writeToParcel(final Parcel out, final int flags) { super.writeToParcel(out, flags); out.writeInt(selectedIndex); } @Override public int describeContents() { return super.describeContents(); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/BottomNavigation.java
package it.sephiroth.android.library.bottomnavigation; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.LayerDrawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.IdRes; import android.support.annotation.MenuRes; import android.support.design.widget.CoordinatorLayout; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.readystatesoftware.systembartint.SystemBarTintManager; import java.lang.ref.SoftReference; import it.sephiroth.android.library.bottonnavigation.R; import static android.util.Log.INFO; import static android.util.Log.VERBOSE; import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; import static it.sephiroth.android.library.bottomnavigation.MiscUtils.log; /** * Created by alessandro crugnola on 4/2/16. */ public class BottomNavigation extends FrameLayout implements OnItemClickListener { private static final String TAG = BottomNavigation.class.getSimpleName(); public static final boolean DEBUG = true; static final int PENDING_ACTION_NONE = 0x0; static final int PENDING_ACTION_EXPANDED = 0x1; static final int PENDING_ACTION_COLLAPSED = 0x2; static final int PENDING_ACTION_ANIMATE_ENABLED = 0x4; /** * Current pending action (used inside the BottomBehavior instance) */ private int mPendingAction = PENDING_ACTION_NONE; /** * This is the amount of space we have to cover in case there's a translucent navigation * enabled. */ private int bottomInset; /** * This is the amount of space we have to cover in case there's a translucent status * enabled. */ private int topInset; /** * This is the current view height. It does take into account the extra space * used in case we have to cover the navigation translucent area, and neither the shadow height. */ private int defaultHeight; private int defaultWidth; /** * Shadow is created above the widget background. It simulates the * elevation. */ private int shadowHeight; /** * Layout container used to create and manage the UI items. * It can be either Fixed or Shifting, based on the widget `mode` */ private ItemsLayoutContainer itemsContainer; /** * This is where the color animation is happening */ private View backgroundOverlay; /** * current menu */ private MenuParser.Menu menu; private MenuParser.Menu pendingMenu; /** * Default selected index. * After the items are populated changing this * won't have any effect */ private int defaultSelectedIndex = 0; /** * View visible background color */ private ColorDrawable backgroundDrawable; /** * Animation duration for the background color change */ private long backgroundColorAnimation; /** * Optional typeface used for the items' text labels */ SoftReference<Typeface> typeface; /** * Current BottomBehavior assigned from the CoordinatorLayout */ private Object mBehavior; private OnMenuItemSelectionListener listener; private int gravity; private boolean attached; public BottomNavigation(final Context context) { this(context, null); } public BottomNavigation(final Context context, final AttributeSet attrs) { super(context, attrs); initialize(context, attrs, 0, 0); } public BottomNavigation(final Context context, final AttributeSet attrs, final int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(context, attrs, defStyleAttr, 0); } @TargetApi (Build.VERSION_CODES.LOLLIPOP) public BottomNavigation(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initialize(context, attrs, defStyleAttr, defStyleRes); } @Override protected Parcelable onSaveInstanceState() { log(TAG, INFO, "onSaveInstanceState"); Parcelable parcelable = super.onSaveInstanceState(); SavedState savedState = new SavedState(parcelable); savedState.selectedIndex = getSelectedIndex(); return savedState; } @Override protected void onRestoreInstanceState(final Parcelable state) { log(TAG, INFO, "onRestoreInstanceState"); SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); defaultSelectedIndex = savedState.selectedIndex; log(TAG, Log.DEBUG, "saved selectedIndex: %d", defaultSelectedIndex); } private void initialize(final Context context, final AttributeSet attrs, final int defStyleAttr, final int defStyleRes) { final Activity activity = (Activity) context; final SystemBarTintManager systembarTint = new SystemBarTintManager(activity); typeface = new SoftReference<>(Typeface.DEFAULT); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.BottomNavigation, defStyleAttr, defStyleRes); final int menuResId = array.getResourceId(R.styleable.BottomNavigation_bbn_entries, 0); pendingMenu = MenuParser.inflateMenu(context, menuResId); array.recycle(); backgroundColorAnimation = getResources().getInteger(R.integer.bbn_background_animation_duration); defaultHeight = getResources().getDimensionPixelSize(R.dimen.bbn_bottom_navigation_height); defaultWidth = getResources().getDimensionPixelSize(R.dimen.bbn_bottom_navigation_width); shadowHeight = getResources().getDimensionPixelOffset(R.dimen.bbn_top_shadow_height); // check if the bottom navigation is translucent if (MiscUtils.hasTranslucentNavigation(activity) && systembarTint.getConfig().isNavigationAtBottom() && systembarTint.getConfig().hasNavigtionBar()) { bottomInset = systembarTint.getConfig().getNavigationBarHeight(); } else { bottomInset = 0; } topInset = systembarTint.getConfig().getStatusBarHeight(); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT); backgroundOverlay = new View(getContext()); backgroundOverlay.setLayoutParams(params); addView(backgroundOverlay); } int getPendingAction() { return mPendingAction; } void resetPendingAction() { mPendingAction = PENDING_ACTION_NONE; } @Override public void setLayoutParams(final ViewGroup.LayoutParams params) { log(TAG, INFO, "setLayoutParams: %s", params); super.setLayoutParams(params); } private boolean isTablet(final int gravity) { return MiscUtils.isGravitiyLeft(gravity) || MiscUtils.isGravityRight(gravity); } @SuppressWarnings ("unused") public void setSelectedIndex(final int position, final boolean animate) { if (null != itemsContainer) { setSelectedItemInternal(itemsContainer, ((ViewGroup) itemsContainer).getChildAt(position), position, animate, false); } else { defaultSelectedIndex = position; } } @SuppressWarnings ("unused") public int getSelectedIndex() { if (null != itemsContainer) { return itemsContainer.getSelectedIndex(); } return -1; } @SuppressWarnings ("unused") public void setExpanded(boolean expanded, boolean animate) { log(TAG, INFO, "setExpanded(%b, %b)", expanded, animate); mPendingAction = (expanded ? PENDING_ACTION_EXPANDED : PENDING_ACTION_COLLAPSED) | (animate ? PENDING_ACTION_ANIMATE_ENABLED : 0); requestLayout(); } public boolean isExpanded() { if (null != mBehavior && mBehavior instanceof BottomBehavior) { return ((BottomBehavior) mBehavior).isExpanded(); } return false; } public void setOnMenuItemClickListener(final OnMenuItemSelectionListener listener) { this.listener = listener; } public void setMenuItems(@MenuRes final int menuResId) { defaultSelectedIndex = 0; if (isAttachedToWindow()) { setItems(MenuParser.inflateMenu(getContext(), menuResId)); pendingMenu = null; } else { pendingMenu = MenuParser.inflateMenu(getContext(), menuResId); } } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); log(TAG, INFO, "onMeasure: %d", gravity); if (MiscUtils.isGravityBottom(gravity)) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int widthSize = MeasureSpec.getSize(widthMeasureSpec); if (widthMode == MeasureSpec.AT_MOST) { throw new IllegalArgumentException("layout_width must be equal to `match_parent`"); } setMeasuredDimension(widthSize, defaultHeight + bottomInset + shadowHeight); } else if (MiscUtils.isGravitiyLeft(gravity) || MiscUtils.isGravityRight(gravity)) { final int heightMode = MeasureSpec.getMode(heightMeasureSpec); final int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (heightMode == MeasureSpec.AT_MOST) { throw new IllegalArgumentException("layout_height must be equal to `match_parent`"); } setMeasuredDimension(defaultWidth, heightSize); } else { throw new IllegalArgumentException("invalid layout_gravity. Only one start, end, left, right or bottom is allowed"); } } public int getNavigationHeight() { return defaultHeight; } public int getNavigationWidth() { return defaultWidth; } @Override protected void onSizeChanged(final int w, final int h, final int oldw, final int oldh) { log(TAG, INFO, "onSizeChanged(%d, %d)", w, h); super.onSizeChanged(w, h, oldw, oldh); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) getLayoutParams(); marginLayoutParams.bottomMargin = -bottomInset; } public boolean isAttachedToWindow() { if (Build.VERSION.SDK_INT >= 19) { return super.isAttachedToWindow(); } return attached; } @Override protected void onAttachedToWindow() { log(TAG, INFO, "onAttachedToWindow"); super.onAttachedToWindow(); attached = true; final CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) getLayoutParams(); this.gravity = GravityCompat.getAbsoluteGravity(params.gravity, ViewCompat.getLayoutDirection(this)); initializeUI(gravity); if (null != pendingMenu) { setItems(pendingMenu); pendingMenu = null; } if (null == mBehavior) { if (CoordinatorLayout.LayoutParams.class.isInstance(params)) { mBehavior = params.getBehavior(); if (BottomBehavior.class.isInstance(mBehavior)) { ((BottomBehavior) mBehavior).setLayoutValues(defaultHeight, bottomInset); } else if (TabletBehavior.class.isInstance(mBehavior)) { boolean translucentStatus = MiscUtils.hasTranslucentStatusBar((Activity) getContext()); ((TabletBehavior) mBehavior).setLayoutValues(defaultWidth, topInset, translucentStatus); } } } } private void setItems(MenuParser.Menu menu) { log(TAG, INFO, "setItems: %s", menu); this.menu = menu; if (null != menu) { if (menu.getItemsCount() < 3 || menu.getItemsCount() > 5) { throw new IllegalArgumentException("BottomNavigation expects 3 to 5 items. " + menu.getItemsCount() + " found"); } menu.setTabletMode(isTablet(gravity)); initializeBackgroundColor(menu); initializeContainer(menu); initializeItems(menu); } requestLayout(); } private void initializeUI(final int gravity) { log(TAG, INFO, "initializeUI(%d)", gravity); final LayerDrawable layerDrawable; final boolean tablet = isTablet(gravity); final int elevation = !tablet ? getResources().getDimensionPixelSize(R.dimen.bbn_elevation) : 0; final int bgResId = !tablet ? R.drawable.bbn_background : (MiscUtils.isGravityRight(gravity) ? R.drawable.bbn_background_tablet_right : R.drawable.bbn_background_tablet_left); final int paddingBottom = !tablet ? shadowHeight : 0; // View elevation ViewCompat.setElevation(this, elevation); // Main background layerDrawable = (LayerDrawable) ContextCompat.getDrawable(getContext(), bgResId); backgroundDrawable = (ColorDrawable) layerDrawable.findDrawableByLayerId(R.id.bbn_background); setBackground(layerDrawable); // Padding bottom setPadding(0, paddingBottom, 0, 0); } private void initializeBackgroundColor(final MenuParser.Menu menu) { log(TAG, INFO, "initializeBackgroundColor"); final int color = menu.getBackground(); log(TAG, VERBOSE, "background: %x", color); backgroundDrawable.setColor(color); } private void initializeContainer(final MenuParser.Menu menu) { log(TAG, INFO, "initializeContainer"); if (null != itemsContainer) { if (menu.isTablet() && !TabletLayout.class.isInstance(itemsContainer)) { removeView((View) itemsContainer); itemsContainer = null; } else if ((menu.isShifting() && !ShiftingLayout.class.isInstance(itemsContainer)) || (!menu.isShifting() && !FixedLayout.class.isInstance(itemsContainer))) { removeView((View) itemsContainer); itemsContainer = null; } else { itemsContainer.removeAll(); } } if (null == itemsContainer) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( menu.isTablet() ? defaultWidth : MATCH_PARENT, menu.isTablet() ? MATCH_PARENT : defaultHeight ); if (menu.isTablet()) { itemsContainer = new TabletLayout(getContext()); } else if (menu.isShifting()) { itemsContainer = new ShiftingLayout(getContext()); } else { itemsContainer = new FixedLayout(getContext()); } itemsContainer.setLayoutParams(params); addView((View) itemsContainer); } } private void initializeItems(final MenuParser.Menu menu) { log(TAG, INFO, "initializeItems"); itemsContainer.setSelectedIndex(defaultSelectedIndex, false); itemsContainer.populate(menu); itemsContainer.setOnItemClickListener(this); if (menu.getItemAt(defaultSelectedIndex).hasColor()) { backgroundDrawable.setColor(menu.getItemAt(defaultSelectedIndex).getColor()); } } @Override public void onItemClick(final ItemsLayoutContainer parent, final View view, final int index, boolean animate) { log(TAG, INFO, "onItemClick: %d", index); setSelectedItemInternal(parent, view, index, animate, true); } private void setSelectedItemInternal( final ItemsLayoutContainer layoutContainer, final View view, final int index, final boolean animate, final boolean fromUser) { final BottomNavigationItem item = menu.getItemAt(index); if (layoutContainer.getSelectedIndex() != index) { layoutContainer.setSelectedIndex(index, animate); if (item.hasColor() && !menu.isTablet()) { if (animate) { MiscUtils.animate( this, view, backgroundOverlay, backgroundDrawable, item.getColor(), backgroundColorAnimation ); } else { MiscUtils.switchColor( this, view, backgroundOverlay, backgroundDrawable, item.getColor() ); } } if (null != listener && fromUser) { listener.onMenuItemSelect(item.getId(), index); } } else { if (null != listener && fromUser) { listener.onMenuItemReselect(item.getId(), index); } } } public void setDefaultTypeface(final Typeface typeface) { this.typeface = new SoftReference<>(typeface); } public void setDefaultSelectedIndex(final int defaultSelectedIndex) { this.defaultSelectedIndex = defaultSelectedIndex; } public interface OnMenuItemSelectionListener { void onMenuItemSelect(@IdRes final int itemId, final int position); void onMenuItemReselect(@IdRes final int itemId, final int position); } static class SavedState extends BaseSavedState { int selectedIndex; public SavedState(Parcel in) { super(in); selectedIndex = in.readInt(); } public SavedState(final Parcelable superState) { super(superState); } @Override public void writeToParcel(final Parcel out, final int flags) { super.writeToParcel(out, flags); out.writeInt(selectedIndex); } @Override public int describeContents() { return super.describeContents(); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
comments
bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/BottomNavigation.java
comments
<ide><path>ottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/BottomNavigation.java <add>/** <add> * The MIT License (MIT) <add> * <p> <add> * Copyright (c) 2016 Alessandro Crugnola <add> * <p> <add> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation <add> * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, <add> * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software <add> * is furnished to do so, subject to the following conditions: <add> * <p> <add> * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. <add> * <p> <add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE <add> * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR <add> * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, <add> * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <add> */ <add> <ide> package it.sephiroth.android.library.bottomnavigation; <ide> <ide> import android.annotation.TargetApi; <ide> <ide> /** <ide> * Created by alessandro crugnola on 4/2/16. <add> * BottomNavigation <ide> */ <ide> public class BottomNavigation extends FrameLayout implements OnItemClickListener { <ide> private static final String TAG = BottomNavigation.class.getSimpleName(); <ide> * used in case we have to cover the navigation translucent area, and neither the shadow height. <ide> */ <ide> private int defaultHeight; <add> <add> /** <add> * Same as defaultHeight, but for tablet mode. <add> */ <ide> private int defaultWidth; <ide> <ide> /** <ide> */ <ide> private Object mBehavior; <ide> <add> /** <add> * Menu selection listener <add> */ <ide> private OnMenuItemSelectionListener listener; <ide> <add> /** <add> * The user defined layout_gravity <add> */ <ide> private int gravity; <add> <add> /** <add> * View is attached <add> */ <ide> private boolean attached; <ide> <ide> public BottomNavigation(final Context context) { <ide> } <ide> } <ide> <add> @SuppressWarnings ("unused") <ide> public int getNavigationHeight() { <ide> return defaultHeight; <ide> } <ide> <add> @SuppressWarnings ("unused") <ide> public int getNavigationWidth() { <ide> return defaultWidth; <ide> }
Java
mit
ef31810310f9ae0dd1505868b03ff2848738a586
0
Obeyed/authentication-and-access-control
package dk.obeid; import dk.obeid.unused.TrustedThirdParty; //import javax.crypto.*; //import java.io.UnsupportedEncodingException; import java.rmi.Naming; import java.sql.Date; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Scanner; //import static dk.obeid.Client.AES.decrypt; //import static dk.obeid.Client.AES.encryptData; //import static dk.obeid.Client.RSA.rsaDecrypt; //import static dk.obeid.Client.RSA.rsaEncryptPriv; public class Client { private static PrintService service; private static Timestamp session; // private static PrivateKey privateKey; // private static SecretKey sharedKey; // private static String initialServerResponse; // private static String initialNonceResponse; // private static boolean publicKeyHandshake = false; private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS"); // private static Date decryptedSession; private static final TrustedThirdParty ttp = new TrustedThirdParty(); public static void main(String[] args) throws Exception { /* user | password * ---------------------- * obeid | 1234 */ Scanner input = new Scanner(System.in); boolean authenticated = false, terminate = false; String user = null, password = null; service = (PrintService) Naming.lookup("rmi://localhost:8090/print"); /** * We assume that this key has had been received offline, * but for this purpose we generate a new key pair */ // sharedKey = service.getSharedKey(); // for (byte b : sharedKey.getEncoded()) // System.out.print(b); // System.out.println(); // System.out.println("Requested Key Pair.."); // privateKey = ttp.getPrivateKey("obeid"); // for (byte b : privateKey.getEncoded()) // System.out.print(b); // System.out.println(); while (!terminate){ // System.out.println("In ourtermost loop.."); authenticated = false; // while (!authenticated && !publicKeyHandshake) { while (!authenticated) { // System.out.println("In innermost loop.."); authenticated = giveAccessInfo(input, user, password); // if (!publicKeyHandshake) { // System.out.println("Asymmetric handshake unsuccesful..\nGoodbye."); // System.exit(1); // } } terminate = whatToChose(input); } } /** * * @param input * @param user * @param password * @return whether or not the user can continue to the services * @throws InterruptedException */ private static boolean giveAccessInfo(Scanner input, String user, String password) throws Exception { // if (session != null && service.verifySession(encryptData(session.toString(), sharedKey))) { if (session != null) System.out.println("Verifying session.."); if (session != null && service.verifySession(session)) { System.out.println("Verified"); return true; } if(session != null) System.out.println("Session expired! Sign in again."); System.out.print("Enter username: "); user = input.nextLine(); System.out.print("Enter password: "); password = input.nextLine(); // if(!sendInitialHandshake(user)){ // publicKeyHandshake = false; // return false; // } // // if(!sendResponseAndFinalize(initialServerResponse, initialNonceResponse)) { // publicKeyHandshake = false; // return false; // } // if (service.signon(encryptData(user, sharedKey), encryptData(password, sharedKey))) { if (service.signon(user, password)) { System.out.println("Verifying sign in.."); System.out.println("Receiving session info.."); // decryptedSession = (Date) dateFormat.parse(decrypt(service.getSession(), sharedKey)); session = service.getSession(); // System.out.println("new session: " + session.toString()); System.out.println("Welcome to print service!"); // publicKeyHandshake = true; return true; } else { System.out.println("Verifying sign in.."); // publicKeyHandshake = false; Thread.sleep(5000); System.out.println("ACCESS DENIED"); return false; } } // private static boolean sendInitialHandshake(String user) throws Exception { // Timestamp handshakeTime = new Timestamp(System.currentTimeMillis()); // // System.out.println("-- TEST CLIENT INITIAL HANDSHAKE TIMESTAMP: " + handshakeTime.toString()); // // System.out.println("-- Initiating public key handshake.."); // // byte[][] response = PrintServant.initialHandshake(rsaEncryptPriv(user.getBytes(), privateKey), // RSA.rsaEncryptPub(handshakeTime.toString().getBytes(), "servant")); // // System.out.println("-- Reading response.."); // // if (response[1] == null) { // System.out.println("+++ Response from server: " + rsaDecrypt(response[0], "servant")); // return false; // } // // initialServerResponse = rsaDecrypt(response[0], "servant"); // initialNonceResponse = rsaDecrypt(response[1], privateKey); // // System.out.println("-- Initial handshake completed.."); // // return true; // } // // private static boolean sendResponseAndFinalize(String initialServerResponse, String initialNonceResponse) throws Exception { // String replyTime = new Timestamp(System.currentTimeMillis()).toString(); // System.out.print("-- Client response time: " + replyTime); // // byte[] finalReply = PrintServant.handshakeResponse(rsaEncryptPriv(initialServerResponse.getBytes(), // privateKey), // RSA.rsaEncryptPub(initialNonceResponse.getBytes(), "servant"), // RSA.rsaEncryptPub(replyTime.getBytes(), "servant")); // // if(finalReply == null) { // System.out.println("--- Server did not accept. See server response.."); // return false; // } // // rsaDecrypt(finalReply, privateKey); // // sharedKey = new SecretKeySpec(finalReply, 0, finalReply.length, "AES"); // System.out.println("--- TEST CLIENT KEY: " + sharedKey.toString()); // // return true; // } /** * actions are encrypted before sent to the server * @param input * @return whether or not to terminate * @throws Exception */ private static boolean whatToChose(Scanner input) throws Exception { String choiceStr = null, arg1Str = null, arg2Str = null; int choice = 0; System.out.println(); System.out.println("Possible actions:"); System.out.println("1 - print\n" + "2 - queue\n" + "3 - top queue\n" + "4 - start\n" + "5 - stop\n" + "6 - restart\n" + "7 - status\n" + "8 - read configuration\n" + "9 - set configuration\n" + "00 - exit"); choiceStr= input.nextLine(); choice = Integer.parseInt(choiceStr); switch (choice) { case 1: System.out.println("What to print: "); arg1Str = input.nextLine(); System.out.println("On which printer: "); arg2Str = input.nextLine(); System.out.println(send(choiceStr, arg1Str, arg2Str)); break; case 2: System.out.println(send(choiceStr)); break; case 3: System.out.println("Which job do you want moved to top: "); arg1Str = input.nextLine(); System.out.println(send(choiceStr, arg1Str)); break; case 4: System.out.println(send(choiceStr)); break; case 5: System.out.println(send(choiceStr)); break; case 6: System.out.println(send(choiceStr)); break; case 7: System.out.println(send(choiceStr)); break; case 8: System.out.println("What parameter: "); arg1Str = input.nextLine(); System.out.println(send(choiceStr, arg1Str)); break; case 9: System.out.println("What parameter: "); arg1Str = input.nextLine(); System.out.println("What value: "); arg2Str = input.nextLine(); System.out.println(send(choiceStr, arg1Str, arg2Str)); break; case 00: System.out.println("Goodbye"); return true; default: System.out.println("Unknown command.."); break; } Thread.sleep(1000); return false; } private static String send(String choice) throws Exception { return send(choice, null); } private static String send(String choice, String arg1) throws Exception { return send(choice, arg1, null); } private static String send(String choice, String arg1, String arg2) throws Exception { // byte[] encrypted = service.incoming( // encryptData(choice, sharedKey), // encryptData(arg1, sharedKey), // encryptData(arg2, sharedKey) // ); // return decrypt(encrypted, sharedKey); return service.incoming(choice, arg1, arg2); } /** * modified from https://gist.github.com/bricef/2436364 * same as from PrintServant but only with the relevant methods. */ // protected static class AES { // /** // * // * @param data // * @param secretKey // * @return data encrypted // */ // protected static byte[] encryptData(String data, SecretKey secretKey){ // byte[] encrypted = null; // try { // encrypted = encrypt(data, secretKey); // } catch (Exception e) { // e.printStackTrace(); // } // return encrypted; // } // // /** // * // * @param plain // * @param key // * @return data encrypted with key // * @throws Exception // */ // protected static byte[] encrypt(String plain, SecretKey key) throws Exception { // Cipher cipher = Cipher.getInstance("AES", "SunJCE"); // cipher.init(Cipher.ENCRYPT_MODE, key); // return cipher.doFinal(plain.getBytes("UTF-8")); // } // // /** // * // * @param cipherText // * @param key // * @return decrypted bytes of cipher text // * @throws Exception // */ // protected static String decrypt(byte[] cipherText, SecretKey key) throws Exception{ // Cipher cipher = Cipher.getInstance("AES", "SunJCE"); // cipher.init(Cipher.DECRYPT_MODE, key); // return new String(cipher.doFinal(cipherText),"UTF-8"); // } // } // /** // * modified from http://stackoverflow.com/questions/3441501/java-asymmetric-encryption-preferred-way-to-store-public-private-keys // * and http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml // */ // protected static class RSA { // /** // * Encrypts data with public key of owner. // * @param data // * @param owner // * @return If owner is known, data is encrypted with public key of owner. // * Otherwise, an empty byte is returned. // * @throws javax.crypto.NoSuchPaddingException // * @throws NoSuchAlgorithmException // * @throws javax.crypto.BadPaddingException // * @throws javax.crypto.IllegalBlockSizeException // * @throws java.security.InvalidKeyException // */ // protected static byte[] rsaEncryptPub(byte[] data, String owner) throws Exception { // System.out.println("RSA ENCRYPT PUBLIC!"); // PublicKey pubKey = ttp.getPublicKey(owner); // // Cipher cipher = Cipher.getInstance("RSA"); // cipher.init(Cipher.ENCRYPT_MODE, pubKey); // byte[] cipherData = cipher.doFinal(data); // return cipherData; // } // // /** // * // * @param data // * @param privKey // * @return Encrypted data with private key. // * @throws NoSuchPaddingException // * @throws NoSuchAlgorithmException // * @throws BadPaddingException // * @throws IllegalBlockSizeException // * @throws InvalidKeyException // */ // protected static byte[] rsaEncryptPriv(byte[] data, PrivateKey privKey) throws NoSuchPaddingException, // NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, NoSuchProviderException { // // System.out.println("RSA ENCRYPT PRIVATE!"); // // Cipher cipher = Cipher.getInstance("RSA"); // cipher.init(Cipher.ENCRYPT_MODE, privKey); // byte[] cipherData = cipher.doFinal(data); // return cipherData; // } // // /** // * // * @param data // * @param privKey public or private key // * @return decrypted version of data // * @throws NoSuchPaddingException // * @throws NoSuchAlgorithmException // * @throws BadPaddingException // * @throws IllegalBlockSizeException // * @throws InvalidKeyException // */ // protected static String rsaDecrypt(byte[] data, PrivateKey privKey) throws NoSuchPaddingException, // NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, UnsupportedEncodingException, NoSuchProviderException { // System.out.println("RSA DECRYPT PRIVATE"); // // Cipher cipher = Cipher.getInstance("RSA"); // cipher.init(Cipher.DECRYPT_MODE, privKey); // byte[] plainData = cipher.doFinal(data); // return new String(cipher.doFinal(plainData),"UTF-8"); // } // // protected static String rsaDecrypt(byte[] data, String owner) throws Exception { // // System.out.println("RSA DECRYPT!"); // PublicKey pubKey = ttp.getPublicKey(owner); // // Cipher cipher = Cipher.getInstance("RSA"); // cipher.init(Cipher.DECRYPT_MODE, pubKey); // byte[] plainData = cipher.doFinal(data); // return new String(cipher.doFinal(plainData),"UTF-8"); // } // } }
rmi-print/src/dk/obeid/Client.java
package dk.obeid; import dk.obeid.unused.TrustedThirdParty; //import javax.crypto.*; //import java.io.UnsupportedEncodingException; import java.rmi.Naming; import java.sql.Date; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Scanner; //import static dk.obeid.Client.AES.decrypt; //import static dk.obeid.Client.AES.encryptData; //import static dk.obeid.Client.RSA.rsaDecrypt; //import static dk.obeid.Client.RSA.rsaEncryptPriv; public class Client { private static PrintService service; private static Timestamp session; // private static PrivateKey privateKey; // private static SecretKey sharedKey; // private static String initialServerResponse; // private static String initialNonceResponse; // private static boolean publicKeyHandshake = false; private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS"); // private static Date decryptedSession; private static final TrustedThirdParty ttp = new TrustedThirdParty(); public static void main(String[] args) throws Exception { /* user | password * ---------------------- * obeid | 1234 */ Scanner input = new Scanner(System.in); boolean authenticated = false, terminate = false; String user = null, password = null; service = (PrintService) Naming.lookup("rmi://localhost:8090/print"); /** * We assume that this key has had been received offline, * but for this purpose we generate a new key pair */ // sharedKey = service.getSharedKey(); // for (byte b : sharedKey.getEncoded()) // System.out.print(b); // System.out.println(); // System.out.println("Requested Key Pair.."); // privateKey = ttp.getPrivateKey("obeid"); // for (byte b : privateKey.getEncoded()) // System.out.print(b); // System.out.println(); while (!terminate){ // System.out.println("In ourtermost loop.."); authenticated = false; // while (!authenticated && !publicKeyHandshake) { while (!authenticated) { // System.out.println("In innermost loop.."); authenticated = giveAccessInfo(input, user, password); // if (!publicKeyHandshake) { // System.out.println("Asymmetric handshake unsuccesful..\nGoodbye."); // System.exit(1); // } } terminate = whatToChose(input); } } /** * * @param input * @param user * @param password * @return whether or not the user can continue to the services * @throws InterruptedException */ private static boolean giveAccessInfo(Scanner input, String user, String password) throws Exception { // if (session != null && service.verifySession(encryptData(session.toString(), sharedKey))) { if (session != null && service.verifySession(session)) { System.out.println("Verified"); return true; } if(session != null) System.out.println("Session expired! Sign in again."); System.out.print("Enter username: "); user = input.nextLine(); System.out.print("Enter password: "); password = input.nextLine(); // if(!sendInitialHandshake(user)){ // publicKeyHandshake = false; // return false; // } // // if(!sendResponseAndFinalize(initialServerResponse, initialNonceResponse)) { // publicKeyHandshake = false; // return false; // } // if (service.signon(encryptData(user, sharedKey), encryptData(password, sharedKey))) { if (service.signon(user, password)) { System.out.println("Verifying sign in.."); System.out.println("Receiving session info.."); // decryptedSession = (Date) dateFormat.parse(decrypt(service.getSession(), sharedKey)); session = service.getSession(); System.out.println("new session: " + session.toString()); System.out.println("Welcome to print service!"); // publicKeyHandshake = true; return true; } else { System.out.println("Verifying sign in.."); // publicKeyHandshake = false; Thread.sleep(5000); System.out.println("ACCESS DENIED"); return false; } } // private static boolean sendInitialHandshake(String user) throws Exception { // Timestamp handshakeTime = new Timestamp(System.currentTimeMillis()); // // System.out.println("-- TEST CLIENT INITIAL HANDSHAKE TIMESTAMP: " + handshakeTime.toString()); // // System.out.println("-- Initiating public key handshake.."); // // byte[][] response = PrintServant.initialHandshake(rsaEncryptPriv(user.getBytes(), privateKey), // RSA.rsaEncryptPub(handshakeTime.toString().getBytes(), "servant")); // // System.out.println("-- Reading response.."); // // if (response[1] == null) { // System.out.println("+++ Response from server: " + rsaDecrypt(response[0], "servant")); // return false; // } // // initialServerResponse = rsaDecrypt(response[0], "servant"); // initialNonceResponse = rsaDecrypt(response[1], privateKey); // // System.out.println("-- Initial handshake completed.."); // // return true; // } // // private static boolean sendResponseAndFinalize(String initialServerResponse, String initialNonceResponse) throws Exception { // String replyTime = new Timestamp(System.currentTimeMillis()).toString(); // System.out.print("-- Client response time: " + replyTime); // // byte[] finalReply = PrintServant.handshakeResponse(rsaEncryptPriv(initialServerResponse.getBytes(), // privateKey), // RSA.rsaEncryptPub(initialNonceResponse.getBytes(), "servant"), // RSA.rsaEncryptPub(replyTime.getBytes(), "servant")); // // if(finalReply == null) { // System.out.println("--- Server did not accept. See server response.."); // return false; // } // // rsaDecrypt(finalReply, privateKey); // // sharedKey = new SecretKeySpec(finalReply, 0, finalReply.length, "AES"); // System.out.println("--- TEST CLIENT KEY: " + sharedKey.toString()); // // return true; // } /** * actions are encrypted before sent to the server * @param input * @return whether or not to terminate * @throws Exception */ private static boolean whatToChose(Scanner input) throws Exception { String choiceStr = null, arg1Str = null, arg2Str = null; int choice = 0; System.out.println(); System.out.println("Possible actions:"); System.out.println("1 - print\n" + "2 - queue\n" + "3 - top queue\n" + "4 - start\n" + "5 - stop\n" + "6 - restart\n" + "7 - status\n" + "8 - read configuration\n" + "9 - set configuration\n" + "00 - exit"); choiceStr= input.nextLine(); choice = Integer.parseInt(choiceStr); switch (choice) { case 1: System.out.println("What to print: "); arg1Str = input.nextLine(); System.out.println("On which printer: "); arg2Str = input.nextLine(); System.out.println(send(choiceStr, arg1Str, arg2Str)); break; case 2: System.out.println(send(choiceStr)); break; case 3: System.out.println("Which job do you want moved to top: "); arg1Str = input.nextLine(); System.out.println(send(choiceStr, arg1Str)); break; case 4: System.out.println(send(choiceStr)); break; case 5: System.out.println(send(choiceStr)); break; case 6: System.out.println(send(choiceStr)); break; case 7: System.out.println(send(choiceStr)); break; case 8: System.out.println("What parameter: "); arg1Str = input.nextLine(); System.out.println(send(choiceStr, arg1Str)); break; case 9: System.out.println("What parameter: "); arg1Str = input.nextLine(); System.out.println("What value: "); arg2Str = input.nextLine(); System.out.println(send(choiceStr, arg1Str, arg2Str)); break; case 00: System.out.println("Goodbye"); return true; default: System.out.println("Unknown command.."); break; } Thread.sleep(1000); return false; } private static String send(String choice) throws Exception { return send(choice, null); } private static String send(String choice, String arg1) throws Exception { return send(choice, arg1, null); } private static String send(String choice, String arg1, String arg2) throws Exception { // byte[] encrypted = service.incoming( // encryptData(choice, sharedKey), // encryptData(arg1, sharedKey), // encryptData(arg2, sharedKey) // ); // return decrypt(encrypted, sharedKey); return service.incoming(choice, arg1, arg2); } /** * modified from https://gist.github.com/bricef/2436364 * same as from PrintServant but only with the relevant methods. */ // protected static class AES { // /** // * // * @param data // * @param secretKey // * @return data encrypted // */ // protected static byte[] encryptData(String data, SecretKey secretKey){ // byte[] encrypted = null; // try { // encrypted = encrypt(data, secretKey); // } catch (Exception e) { // e.printStackTrace(); // } // return encrypted; // } // // /** // * // * @param plain // * @param key // * @return data encrypted with key // * @throws Exception // */ // protected static byte[] encrypt(String plain, SecretKey key) throws Exception { // Cipher cipher = Cipher.getInstance("AES", "SunJCE"); // cipher.init(Cipher.ENCRYPT_MODE, key); // return cipher.doFinal(plain.getBytes("UTF-8")); // } // // /** // * // * @param cipherText // * @param key // * @return decrypted bytes of cipher text // * @throws Exception // */ // protected static String decrypt(byte[] cipherText, SecretKey key) throws Exception{ // Cipher cipher = Cipher.getInstance("AES", "SunJCE"); // cipher.init(Cipher.DECRYPT_MODE, key); // return new String(cipher.doFinal(cipherText),"UTF-8"); // } // } // /** // * modified from http://stackoverflow.com/questions/3441501/java-asymmetric-encryption-preferred-way-to-store-public-private-keys // * and http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml // */ // protected static class RSA { // /** // * Encrypts data with public key of owner. // * @param data // * @param owner // * @return If owner is known, data is encrypted with public key of owner. // * Otherwise, an empty byte is returned. // * @throws javax.crypto.NoSuchPaddingException // * @throws NoSuchAlgorithmException // * @throws javax.crypto.BadPaddingException // * @throws javax.crypto.IllegalBlockSizeException // * @throws java.security.InvalidKeyException // */ // protected static byte[] rsaEncryptPub(byte[] data, String owner) throws Exception { // System.out.println("RSA ENCRYPT PUBLIC!"); // PublicKey pubKey = ttp.getPublicKey(owner); // // Cipher cipher = Cipher.getInstance("RSA"); // cipher.init(Cipher.ENCRYPT_MODE, pubKey); // byte[] cipherData = cipher.doFinal(data); // return cipherData; // } // // /** // * // * @param data // * @param privKey // * @return Encrypted data with private key. // * @throws NoSuchPaddingException // * @throws NoSuchAlgorithmException // * @throws BadPaddingException // * @throws IllegalBlockSizeException // * @throws InvalidKeyException // */ // protected static byte[] rsaEncryptPriv(byte[] data, PrivateKey privKey) throws NoSuchPaddingException, // NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, NoSuchProviderException { // // System.out.println("RSA ENCRYPT PRIVATE!"); // // Cipher cipher = Cipher.getInstance("RSA"); // cipher.init(Cipher.ENCRYPT_MODE, privKey); // byte[] cipherData = cipher.doFinal(data); // return cipherData; // } // // /** // * // * @param data // * @param privKey public or private key // * @return decrypted version of data // * @throws NoSuchPaddingException // * @throws NoSuchAlgorithmException // * @throws BadPaddingException // * @throws IllegalBlockSizeException // * @throws InvalidKeyException // */ // protected static String rsaDecrypt(byte[] data, PrivateKey privKey) throws NoSuchPaddingException, // NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, UnsupportedEncodingException, NoSuchProviderException { // System.out.println("RSA DECRYPT PRIVATE"); // // Cipher cipher = Cipher.getInstance("RSA"); // cipher.init(Cipher.DECRYPT_MODE, privKey); // byte[] plainData = cipher.doFinal(data); // return new String(cipher.doFinal(plainData),"UTF-8"); // } // // protected static String rsaDecrypt(byte[] data, String owner) throws Exception { // // System.out.println("RSA DECRYPT!"); // PublicKey pubKey = ttp.getPublicKey(owner); // // Cipher cipher = Cipher.getInstance("RSA"); // cipher.init(Cipher.DECRYPT_MODE, pubKey); // byte[] plainData = cipher.doFinal(data); // return new String(cipher.doFinal(plainData),"UTF-8"); // } // } }
this version was handed in for the assignment
rmi-print/src/dk/obeid/Client.java
this version was handed in for the assignment
<ide><path>mi-print/src/dk/obeid/Client.java <ide> */ <ide> private static boolean giveAccessInfo(Scanner input, String user, String password) throws Exception { <ide> // if (session != null && service.verifySession(encryptData(session.toString(), sharedKey))) { <add> if (session != null) System.out.println("Verifying session.."); <ide> if (session != null && service.verifySession(session)) { <ide> System.out.println("Verified"); <ide> return true; <ide> <ide> // decryptedSession = (Date) dateFormat.parse(decrypt(service.getSession(), sharedKey)); <ide> session = service.getSession(); <del> System.out.println("new session: " + session.toString()); <add>// System.out.println("new session: " + session.toString()); <ide> <ide> System.out.println("Welcome to print service!"); <ide> // publicKeyHandshake = true;
Java
apache-2.0
62993e64a6ef94be7462bde863ec2e5dc998a5b9
0
Sumei1009/HubTurbo,saav/HubTurbo,Honoo/HubTurbo,Sumei1009/HubTurbo,gaieepo/HubTurbo,ianngiaw/HubTurbo,saav/HubTurbo,gaieepo/HubTurbo,ianngiaw/HubTurbo,Honoo/HubTurbo,HyungJon/HubTurbo,HyungJon/HubTurbo
package backend.json; import backend.interfaces.RepoStore; import backend.resource.Model; import backend.resource.serialization.SerializableModel; import java.util.concurrent.CompletableFuture; /** * Same as JSONStore, but with the save function disabled. * Saves the effort of tearing down every time a test is written. * (explicit command line argument required for proper JSON Store to * activate during test mode) */ public class JSONStoreStub extends JSONStore { @Override public void saveRepository(String repoId, SerializableModel model) {} }
src/main/java/backend/json/JSONStoreStub.java
package backend.json; import backend.interfaces.RepoStore; import backend.resource.Model; import backend.resource.serialization.SerializableModel; import java.util.concurrent.CompletableFuture; /** * Same as JSONStore, but with the save function disabled. * Saves the effort of tearing down every time a test is written. * (explicit command line argument required for proper JSON Store to * activate during test mode) */ public class JSONStoreStub extends RepoStore { @Override public CompletableFuture<Model> loadRepository(String repoId) { CompletableFuture<Model> response = new CompletableFuture<>(); addTask(new ReadTask(repoId, response)); return response; } @Override public void saveRepository(String repoId, SerializableModel model) {} }
Fixed bug where StoreTest did not test JSONStore loadRepository function
src/main/java/backend/json/JSONStoreStub.java
Fixed bug where StoreTest did not test JSONStore loadRepository function
<ide><path>rc/main/java/backend/json/JSONStoreStub.java <ide> * (explicit command line argument required for proper JSON Store to <ide> * activate during test mode) <ide> */ <del>public class JSONStoreStub extends RepoStore { <del> <del> @Override <del> public CompletableFuture<Model> loadRepository(String repoId) { <del> CompletableFuture<Model> response = new CompletableFuture<>(); <del> addTask(new ReadTask(repoId, response)); <del> return response; <del> } <add>public class JSONStoreStub extends JSONStore { <ide> <ide> @Override <ide> public void saveRepository(String repoId, SerializableModel model) {}
Java
apache-2.0
a0c81857a79788f6dd54471fb0868642077ae447
0
tacoo/monex-stock-summary,tacoo/monex-stock-summary
package tacoo.monex.stock.summary; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; public class AllPrint { private static final String YYYY_MM_DD = "yyyy/MM/dd"; static String baseDate = "受渡日"; // public static void main(String[] args) { // AllPrint.printSummary(new File("19990101-20151218.csv")); // } public static void printSummary(File csvFile) { try (CSVParser parser = CSVFormat.EXCEL.parse(new InputStreamReader( new FileInputStream(csvFile), "sjis"))) { final Map<String, Integer> headerMap = new HashMap<>(); Map<String, Money> sums = new HashMap<>(); List<CSVRecord> csvDataList = new ArrayList<>(); filterHeaderAndMRF(parser, headerMap, csvDataList); csvDataList.sort(new CSVRecordComparator(headerMap)); String year = ""; SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD); DecimalFormat df = new DecimalFormat("###,###.###"); Map<String, Stock> stocks = new HashMap<>(); Map<String, String> stockCodeAndName = new HashMap<>(); for (CSVRecord r : csvDataList) { Date date = sdf.parse(r.get(headerMap.get(baseDate))); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); String tmp = calendar.get(Calendar.YEAR) + ""; if (!"".equals(year) && !tmp.equals(year)) { Money lastOne = sums.get(year); Map<String, Stock> carryOverStocks = new HashMap<>(); for (String k : stocks.keySet()) { Stock stock = stocks.get(k); carryOverStocks.put(k, stock.clone()); } lastOne.stocks = carryOverStocks; } year = calendar.get(Calendar.YEAR) + ""; Money money = sums.get(year); if (money == null) { money = new Money(); sums.put(year, money); } String tradeType = r.get(headerMap.get("取引")); if ("ご入金".equals(tradeType) || "口座振替(外国株口座から)".equals(tradeType)) { money.credit += df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); } else if ("口座振替(外国株口座へ)".equals(tradeType)) { money.credit -= df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); } else if ("源泉徴収税(所得税)".equals(tradeType) || "源泉徴収税(住民税)".equals(tradeType)) { int tax = -df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); money.incomeTax += tax; } else if ("還付金(所得税)".equals(tradeType) || "還付金(住民税)".equals(tradeType)) { int tax = df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); money.incomeTax += tax; } else if ("MRF再投資".equals(tradeType) || "配当金".equals(tradeType)) { money.yield += df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); } else if ("お買付".equals(tradeType)) { int value = df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); int qty = df.parse(r.get(headerMap.get("数量(株/口)/返済数量"))).intValue(); int salesTax1 = df.parse(r.get(headerMap.get("手数料"))).intValue(); int salesTax2 = df.parse(r.get(headerMap.get("税金(手数料消費税及び譲渡益税)"))).intValue(); value += salesTax1; value += salesTax2; money.salesTax += salesTax1; money.salesTax += salesTax2; String stockCode = r.get(headerMap.get("銘柄コード")).trim(); String stockName = r.get(headerMap.get("銘柄名")).trim(); stockCodeAndName.put(stockCode, stockName); Stock stock = stocks.get(stockCode); if (stock == null) { stock = new Stock(); stocks.put(stockCode, stock); } int ave = ave(stock.total, stock.quantity, value, qty); stock.name = stockCode + "-" + stockName; stock.quantity += qty; stock.total -= value; stock.averagePrice = ave; } else if ("ご売却".equals(tradeType)) { int value = df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); int qty = df.parse(r.get(headerMap.get("数量(株/口)/返済数量"))).intValue(); int salesTax1 = df.parse(r.get(headerMap.get("手数料"))).intValue(); int salesTax2 = df.parse(r.get(headerMap.get("税金(手数料消費税及び譲渡益税)"))).intValue(); value -= salesTax1; value -= salesTax2; money.salesTax += salesTax1; money.salesTax += salesTax2; String stockCode = r.get(headerMap.get("銘柄コード")).trim(); String stockName = r.get(headerMap.get("銘柄名")).trim(); stockCodeAndName.put(stockCode, stockName); Stock stock = stocks.get(stockCode); if (stock == null) { stock = new Stock(); stocks.put(stockCode, stock); } stock.name = stockCode + "-" + stockName; if (stock.quantity == qty) { money.gain += (stock.total + value); stocks.remove(stockCode); } else { int basePrice = stock.averagePrice * qty; stock.quantity -= qty; stock.total += basePrice; money.gain += value - basePrice; } } else { System.out.println("unknown record found: " + r); } } Money lastOne = sums.get(year); Map<String, Stock> carryOverStocks = new HashMap<>(); for (String k : stocks.keySet()) { Stock stock = stocks.get(k); carryOverStocks.put(k, stock.clone()); } lastOne.stocks = carryOverStocks; String[] keys = sums.keySet().toArray(new String[0]); Arrays.sort(keys, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareTo(o2); } }); System.out.println(String.format("%7s%13s%13s%13s%13s%13s" , "Year" , "Credit" , "Gain" , "Yield" , "SalesTax" , "IncomeTax")); int totalCredit = 0; int totalGain = 0; int totalYeild = 0; int totalSalesTax = 0; int totalIncomeTax = 0; for (String k : keys) { Money money = sums.get(k); System.out.println(String.format("%7s%13d%13d%13d%13s%13d" , k , money.credit , money.gain , money.yield , "(" + money.salesTax + ")" , money.incomeTax)); totalCredit += money.credit; totalGain += money.gain; totalYeild += money.yield; totalSalesTax += money.salesTax; totalIncomeTax += money.incomeTax; } System.out.println(); System.out.println("Current Stocks"); System.out.println(String.format("%8s%13s%10s" , "Quantity" , "Amount" , "Name")); Money money = sums.get(keys[keys.length - 1]); int totalStock = 0; for (String id : money.stocks.keySet()) { Stock stock = money.stocks.get(id); System.out.println(String.format("%8d%13d %s", stock.quantity, stock.total, stock.name)); totalStock += stock.total; } System.out.println(); System.out.println("Total"); System.out.println(String.format("%13s%13s%13s%13s%13s" , "Credit" , "Gain" , "Yield" , "SalesTax" , "IncomeTax")); System.out.println(String.format("%13d%13d%13d%13s%13d" , totalCredit , totalGain , totalYeild , "(" + totalSalesTax + ")" , totalIncomeTax)); System.out.println(); double doubleValue = BigDecimal.valueOf(totalGain + totalYeild).divide(BigDecimal.valueOf(totalCredit), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)) .doubleValue(); System.out.println(String.format("%-20s%,.2f%%", "Performance:", doubleValue)); System.out.println(String.format("%-20s%13d", "Total Stock Amount:", totalStock)); } catch (Exception e) { e.printStackTrace(); } } private static int ave(int baseValue, int baseQty, int addedValue, int addedQty) { int totalValue = Math.abs(baseValue) + Math.abs(addedValue); int totalQty = Math.abs(baseQty) + Math.abs(addedQty); return BigDecimal.valueOf(totalValue).divide(BigDecimal.valueOf(totalQty), 0, RoundingMode.UP).intValue(); } private static void filterHeaderAndMRF(CSVParser parser, final Map<String, Integer> headerMap, List<CSVRecord> csvDataList) { for (CSVRecord r : parser) { if (r.getRecordNumber() == 1) { continue; } if (r.getRecordNumber() == 2) { headerMap.putAll(getHeader(r)); } else { String name = r.get(headerMap.get("銘柄名")); if ("日興MRF".equals(name)) { continue; } csvDataList.add(r); } } } private static Map<String, Integer> getHeader(CSVRecord r) { Map<String, Integer> headerMap = new HashMap<String, Integer>(); int i = 0; for (String k : r) { headerMap.put(k, i); i++; } return headerMap; } private static final class CSVRecordComparator implements Comparator<CSVRecord> { private final SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD); private final Map<String, Integer> headerMap; private CSVRecordComparator(Map<String, Integer> headerMap) { this.headerMap = headerMap; } @Override public int compare(CSVRecord r1, CSVRecord r2) { try { Date d1 = sdf.parse(r1.get(headerMap.get(baseDate))); Date d2 = sdf.parse(r2.get(headerMap.get(baseDate))); int comp1 = d1.compareTo(d2); if (comp1 != 0) { return comp1; } String t1 = r1.get(headerMap.get("取引")); String t2 = r2.get(headerMap.get("取引")); if (t1.equals("ご売却") && t2.equals("ご売却")) { return 0; } else if (t1.equals("ご売却")) { return 1; } else if (t2.equals("ご売却")) { return -1; } } catch (ParseException e) { e.printStackTrace(); } return 0; } } static class Money { int credit = 0; int yield = 0; int incomeTax = 0; int salesTax = 0; int gain = 0; Map<String, Stock> stocks = new HashMap<String, Stock>(); @Override public String toString() { return "Money [credit=" + credit + ", yield=" + yield + ", incomeTax=" + incomeTax + ", salesTax=" + salesTax + ", gain=" + gain + ", stocks=" + stocks + "]"; } } static class Stock { String name; int quantity; int total; int averagePrice; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Stock other = (Stock) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Stock [name=" + name + ", quantity=" + quantity + ", total=" + total + ", averagePrice=" + averagePrice + "]"; } public Stock clone() { Stock stock = new Stock(); stock.name = this.name; stock.quantity = this.quantity; stock.total = this.total; stock.averagePrice = this.averagePrice; return stock; } } }
src/main/java/tacoo/monex/stock/summary/AllPrint.java
package tacoo.monex.stock.summary; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.lang3.StringUtils; public class AllPrint { private static final String YYYY_MM_DD = "yyyy/MM/dd"; static String baseDate = "受渡日"; // static String baseDate = "約定日"; public static void printSummary(File csvFile) { try (CSVParser parser = CSVFormat.EXCEL.parse(new InputStreamReader( new FileInputStream(csvFile), "sjis"))) { final Map<String, Integer> headerMap = new HashMap<>(); Map<String, Money> sums = new HashMap<>(); List<CSVRecord> csvDataList = new ArrayList<>(); filterHeaderAndMRF(parser, headerMap, csvDataList); csvDataList.sort(new CSVRecordComparator(headerMap)); String year = ""; SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD); DecimalFormat df = new DecimalFormat("###,###.###"); Map<String, Stock> stocks = new HashMap<>(); Map<String, String> stockCodeAndName = new HashMap<>(); for (CSVRecord r : csvDataList) { Date date = sdf.parse(r.get(headerMap.get(baseDate))); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); String tmp = calendar.get(Calendar.YEAR) + ""; if (!"".equals(year) && !tmp.equals(year)) { Money lastOne = sums.get(year); Map<String, Stock> carryOverStocks = new HashMap<>(); for (String k : stocks.keySet()) { Stock stock = stocks.get(k); carryOverStocks.put(k, stock.clone()); } lastOne.stocks = carryOverStocks; } year = calendar.get(Calendar.YEAR) + ""; Money money = sums.get(year); if (money == null) { money = new Money(); sums.put(year, money); } String tradeType = r.get(headerMap.get("取引")); if ("ご入金".equals(tradeType) || "口座振替(外国株口座から)".equals(tradeType)) { money.credit += df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); } else if ("口座振替(外国株口座へ)".equals(tradeType)) { money.credit -= df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); } else if ("源泉徴収税(所得税)".equals(tradeType) || "源泉徴収税(住民税)".equals(tradeType)) { int tax = -df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); money.incomeTax += tax; } else if ("還付金(所得税)".equals(tradeType) || "還付金(住民税)".equals(tradeType)) { int tax = df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); money.incomeTax += tax; } else if ("MRF再投資".equals(tradeType) || "配当金".equals(tradeType)) { money.yield += df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); } else if ("お買付".equals(tradeType)) { int value = df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); int qty = df.parse(r.get(headerMap.get("数量(株/口)/返済数量"))).intValue(); int salesTax1 = df.parse(r.get(headerMap.get("手数料"))).intValue(); int salesTax2 = df.parse(r.get(headerMap.get("税金(手数料消費税及び譲渡益税)"))).intValue(); value += salesTax1; value += salesTax2; money.salesTax += salesTax1; money.salesTax += salesTax2; String stockCode = r.get(headerMap.get("銘柄コード")).trim(); String stockName = r.get(headerMap.get("銘柄名")).trim(); stockCodeAndName.put(stockCode, stockName); Stock stock = stocks.get(stockCode); if (stock == null) { stock = new Stock(); stocks.put(stockCode, stock); } stock.name = stockCode + "-" + stockName; stock.quantity += qty; stock.total -= value; } else if ("ご売却".equals(tradeType)) { int value = df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); int qty = df.parse(r.get(headerMap.get("数量(株/口)/返済数量"))).intValue(); int salesTax1 = df.parse(r.get(headerMap.get("手数料"))).intValue(); int salesTax2 = df.parse(r.get(headerMap.get("税金(手数料消費税及び譲渡益税)"))).intValue(); value -= salesTax1; value -= salesTax2; money.salesTax += salesTax1; money.salesTax += salesTax2; String stockCode = r.get(headerMap.get("銘柄コード")).trim(); String stockName = r.get(headerMap.get("銘柄名")).trim(); stockCodeAndName.put(stockCode, stockName); Stock stock = stocks.get(stockCode); if (stock == null) { stock = new Stock(); stocks.put(stockCode, stock); } stock.name = stockCode + "-" + stockName; if (stock.quantity == qty) { money.gain += (stock.total + value); stocks.remove(stockCode); } else { // int ave = -stock.total / stock.quantity; // int soldAve = value / qty; // System.out.println(String.format("%s\t%s=%d", date, // stockName, ((soldAve - ave) * qty))); // money.gain += ((soldAve - ave) * qty); stock.quantity -= qty; // stock.total += value - ((soldAve - ave) * qty); stock.total += value; } } else { System.out.println("unknown record found: " + r); } } Money lastOne = sums.get(year); Map<String, Stock> carryOverStocks = new HashMap<>(); for (String k : stocks.keySet()) { Stock stock = stocks.get(k); carryOverStocks.put(k, stock.clone()); } lastOne.stocks = carryOverStocks; String[] keys = sums.keySet().toArray(new String[0]); Arrays.sort(keys, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareTo(o2); } }); System.out.println(String.format("%s%s%s%s%s%s" , StringUtils.leftPad("Year", 7) , StringUtils.leftPad("Credit", 13) , StringUtils.leftPad("Gain", 13) , StringUtils.leftPad("Yield", 13) , StringUtils.leftPad("SalesTax", 13) , StringUtils.leftPad("IncomeTax", 13))); int totalCredit = 0; int totalGain = 0; int totalYeild = 0; int totalSalesTax = 0; int totalIncomeTax = 0; for (String k : keys) { System.out.print(StringUtils.leftPad(k, 7)); Money money = sums.get(k); System.out.print(StringUtils.leftPad("" + money.credit, 13)); System.out.print(StringUtils.leftPad("" + money.gain, 13)); System.out.print(StringUtils.leftPad("" + money.yield, 13)); System.out.print(StringUtils.leftPad("" + money.salesTax, 13)); System.out.println(StringUtils.leftPad("" + money.incomeTax, 13)); totalCredit += money.credit; totalGain += money.gain; totalYeild += money.yield; totalSalesTax += money.salesTax; totalIncomeTax += money.incomeTax; } System.out.println(); System.out.println("Current Stocks"); System.out.println(String.format("%s%s\t%s" , StringUtils.leftPad("Quantity", 8) , StringUtils.leftPad("Amount", 13) , "Name")); Money money = sums.get(keys[keys.length - 1]); int totalStock = 0; for (String id : money.stocks.keySet()) { Stock stock = money.stocks.get(id); System.out.println(StringUtils.leftPad("" + stock.quantity, 8) + StringUtils.leftPad("" + stock.total, 13) + "\t" + stock.name); totalStock += stock.total; } System.out.println(); System.out.println("Total"); System.out.println(String.format("%s%s%s%s%s" , StringUtils.leftPad("Credit", 13) , StringUtils.leftPad("Gain", 13) , StringUtils.leftPad("Yield", 13) , StringUtils.leftPad("SalesTax", 13) , StringUtils.leftPad("IncomeTax", 13))); System.out.print(StringUtils.leftPad("" + totalCredit, 13)); System.out.print(StringUtils.leftPad("" + totalGain, 13)); System.out.print(StringUtils.leftPad("" + totalYeild, 13)); System.out.print(StringUtils.leftPad("" + totalSalesTax, 13)); System.out.println(StringUtils.leftPad("" + totalIncomeTax, 13)); System.out.println(); System.out.println(StringUtils.leftPad("Total Stock Amount:" + totalStock, 13)); } catch (Exception e) { e.printStackTrace(); } } private static void filterHeaderAndMRF(CSVParser parser, final Map<String, Integer> headerMap, List<CSVRecord> csvDataList) { for (CSVRecord r : parser) { if (r.getRecordNumber() == 1) { continue; } if (r.getRecordNumber() == 2) { headerMap.putAll(getHeader(r)); } else { String name = r.get(headerMap.get("銘柄名")); if ("日興MRF".equals(name)) { continue; } csvDataList.add(r); } } } private static Map<String, Integer> getHeader(CSVRecord r) { Map<String, Integer> headerMap = new HashMap<String, Integer>(); int i = 0; for (String k : r) { headerMap.put(k, i); i++; } return headerMap; } private static final class CSVRecordComparator implements Comparator<CSVRecord> { private final SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD); private final Map<String, Integer> headerMap; private CSVRecordComparator(Map<String, Integer> headerMap) { this.headerMap = headerMap; } @Override public int compare(CSVRecord r1, CSVRecord r2) { try { Date d1 = sdf.parse(r1.get(headerMap.get(baseDate))); Date d2 = sdf.parse(r2.get(headerMap.get(baseDate))); int comp1 = d1.compareTo(d2); if (comp1 != 0) { return comp1; } String t1 = r1.get(headerMap.get("取引")); String t2 = r2.get(headerMap.get("取引")); if (t1.equals("ご売却") && t2.equals("ご売却")) { return 0; } else if (t1.equals("ご売却")) { return 1; } else if (t2.equals("ご売却")) { return -1; } } catch (ParseException e) { e.printStackTrace(); } return 0; } } static class Money { int credit = 0; int yield = 0; int incomeTax = 0; int salesTax = 0; int gain = 0; Map<String, Stock> stocks = new HashMap<String, Stock>(); @Override public String toString() { return "Money [credit=" + credit + ", yield=" + yield + ", incomeTax=" + incomeTax + ", salesTax=" + salesTax + ", gain=" + gain + ", stocks=" + stocks + "]"; } } static class Stock { String name; int quantity; int total; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Stock other = (Stock) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Stock [name=" + name + ", quantity=" + quantity + ", total=" + total + "]"; } public Stock clone() { Stock stock = new Stock(); stock.name = this.name; stock.quantity = this.quantity; stock.total = this.total; return stock; } } }
refactoring
src/main/java/tacoo/monex/stock/summary/AllPrint.java
refactoring
<ide><path>rc/main/java/tacoo/monex/stock/summary/AllPrint.java <ide> import java.io.File; <ide> import java.io.FileInputStream; <ide> import java.io.InputStreamReader; <add>import java.math.BigDecimal; <add>import java.math.RoundingMode; <ide> import java.text.DecimalFormat; <ide> import java.text.ParseException; <ide> import java.text.SimpleDateFormat; <ide> import org.apache.commons.csv.CSVFormat; <ide> import org.apache.commons.csv.CSVParser; <ide> import org.apache.commons.csv.CSVRecord; <del>import org.apache.commons.lang3.StringUtils; <ide> <ide> public class AllPrint { <ide> <ide> private static final String YYYY_MM_DD = "yyyy/MM/dd"; <ide> static String baseDate = "受渡日"; <ide> <del> // static String baseDate = "約定日"; <add> // public static void main(String[] args) { <add> // AllPrint.printSummary(new File("19990101-20151218.csv")); <add> // } <ide> <ide> public static void printSummary(File csvFile) { <ide> try (CSVParser parser = CSVFormat.EXCEL.parse(new InputStreamReader( <ide> stock = new Stock(); <ide> stocks.put(stockCode, stock); <ide> } <add> int ave = ave(stock.total, stock.quantity, value, qty); <ide> stock.name = stockCode + "-" + stockName; <ide> stock.quantity += qty; <ide> stock.total -= value; <add> stock.averagePrice = ave; <ide> } else if ("ご売却".equals(tradeType)) { <ide> int value = df.parse(r.get(headerMap.get("受渡金額(円)"))).intValue(); <ide> int qty = df.parse(r.get(headerMap.get("数量(株/口)/返済数量"))).intValue(); <ide> stocks.put(stockCode, stock); <ide> } <ide> stock.name = stockCode + "-" + stockName; <add> <ide> if (stock.quantity == qty) { <ide> money.gain += (stock.total + value); <ide> stocks.remove(stockCode); <ide> } else { <del> // int ave = -stock.total / stock.quantity; <del> // int soldAve = value / qty; <del> // System.out.println(String.format("%s\t%s=%d", date, <del> // stockName, ((soldAve - ave) * qty))); <del> // money.gain += ((soldAve - ave) * qty); <add> int basePrice = stock.averagePrice * qty; <ide> stock.quantity -= qty; <del> // stock.total += value - ((soldAve - ave) * qty); <del> stock.total += value; <add> stock.total += basePrice; <add> money.gain += value - basePrice; <ide> } <ide> } else { <ide> System.out.println("unknown record found: " + r); <ide> return o1.compareTo(o2); <ide> } <ide> }); <del> System.out.println(String.format("%s%s%s%s%s%s" <del> , StringUtils.leftPad("Year", 7) <del> , StringUtils.leftPad("Credit", 13) <del> , StringUtils.leftPad("Gain", 13) <del> , StringUtils.leftPad("Yield", 13) <del> , StringUtils.leftPad("SalesTax", 13) <del> , StringUtils.leftPad("IncomeTax", 13))); <add> System.out.println(String.format("%7s%13s%13s%13s%13s%13s" <add> , "Year" <add> , "Credit" <add> , "Gain" <add> , "Yield" <add> , "SalesTax" <add> , "IncomeTax")); <ide> int totalCredit = 0; <ide> int totalGain = 0; <ide> int totalYeild = 0; <ide> int totalSalesTax = 0; <ide> int totalIncomeTax = 0; <ide> for (String k : keys) { <del> System.out.print(StringUtils.leftPad(k, 7)); <ide> Money money = sums.get(k); <del> System.out.print(StringUtils.leftPad("" + money.credit, 13)); <del> System.out.print(StringUtils.leftPad("" + money.gain, 13)); <del> System.out.print(StringUtils.leftPad("" + money.yield, 13)); <del> System.out.print(StringUtils.leftPad("" + money.salesTax, 13)); <del> System.out.println(StringUtils.leftPad("" + money.incomeTax, 13)); <add> System.out.println(String.format("%7s%13d%13d%13d%13s%13d" <add> , k <add> , money.credit <add> , money.gain <add> , money.yield <add> , "(" + money.salesTax + ")" <add> , money.incomeTax)); <add> <ide> totalCredit += money.credit; <ide> totalGain += money.gain; <ide> totalYeild += money.yield; <ide> } <ide> System.out.println(); <ide> System.out.println("Current Stocks"); <del> System.out.println(String.format("%s%s\t%s" <del> , StringUtils.leftPad("Quantity", 8) <del> , StringUtils.leftPad("Amount", 13) <add> System.out.println(String.format("%8s%13s%10s" <add> , "Quantity" <add> , "Amount" <ide> , "Name")); <ide> <ide> Money money = sums.get(keys[keys.length - 1]); <ide> int totalStock = 0; <ide> for (String id : money.stocks.keySet()) { <ide> Stock stock = money.stocks.get(id); <del> System.out.println(StringUtils.leftPad("" + stock.quantity, 8) <del> + StringUtils.leftPad("" + stock.total, 13) <del> + "\t" + stock.name); <add> System.out.println(String.format("%8d%13d %s", stock.quantity, stock.total, stock.name)); <ide> totalStock += stock.total; <ide> } <ide> System.out.println(); <ide> System.out.println("Total"); <del> System.out.println(String.format("%s%s%s%s%s" <del> , StringUtils.leftPad("Credit", 13) <del> , StringUtils.leftPad("Gain", 13) <del> , StringUtils.leftPad("Yield", 13) <del> , StringUtils.leftPad("SalesTax", 13) <del> , StringUtils.leftPad("IncomeTax", 13))); <del> System.out.print(StringUtils.leftPad("" + totalCredit, 13)); <del> System.out.print(StringUtils.leftPad("" + totalGain, 13)); <del> System.out.print(StringUtils.leftPad("" + totalYeild, 13)); <del> System.out.print(StringUtils.leftPad("" + totalSalesTax, 13)); <del> System.out.println(StringUtils.leftPad("" + totalIncomeTax, 13)); <add> System.out.println(String.format("%13s%13s%13s%13s%13s" <add> , "Credit" <add> , "Gain" <add> , "Yield" <add> , "SalesTax" <add> , "IncomeTax")); <add> System.out.println(String.format("%13d%13d%13d%13s%13d" <add> , totalCredit <add> , totalGain <add> , totalYeild <add> , "(" + totalSalesTax + ")" <add> , totalIncomeTax)); <ide> System.out.println(); <ide> <del> System.out.println(StringUtils.leftPad("Total Stock Amount:" + totalStock, 13)); <add> double doubleValue = BigDecimal.valueOf(totalGain + totalYeild).divide(BigDecimal.valueOf(totalCredit), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)) <add> .doubleValue(); <add> System.out.println(String.format("%-20s%,.2f%%", "Performance:", doubleValue)); <add> System.out.println(String.format("%-20s%13d", "Total Stock Amount:", totalStock)); <ide> } catch (Exception e) { <ide> e.printStackTrace(); <ide> } <ide> <add> } <add> <add> private static int ave(int baseValue, int baseQty, int addedValue, int addedQty) { <add> int totalValue = Math.abs(baseValue) + Math.abs(addedValue); <add> int totalQty = Math.abs(baseQty) + Math.abs(addedQty); <add> return BigDecimal.valueOf(totalValue).divide(BigDecimal.valueOf(totalQty), 0, RoundingMode.UP).intValue(); <ide> } <ide> <ide> private static void filterHeaderAndMRF(CSVParser parser, final Map<String, Integer> headerMap, List<CSVRecord> csvDataList) { <ide> public String toString() { <ide> return "Money [credit=" + credit + ", yield=" + yield + ", incomeTax=" + incomeTax + ", salesTax=" + salesTax + ", gain=" + gain + ", stocks=" + stocks + "]"; <ide> } <del> <ide> } <ide> <ide> static class Stock { <ide> String name; <ide> int quantity; <ide> int total; <add> int averagePrice; <ide> <ide> @Override <ide> public int hashCode() { <ide> <ide> @Override <ide> public String toString() { <del> return "Stock [name=" + name + ", quantity=" + quantity + ", total=" + total + "]"; <add> return "Stock [name=" + name + ", quantity=" + quantity + ", total=" + total + ", averagePrice=" + averagePrice + "]"; <ide> } <ide> <ide> public Stock clone() { <ide> stock.name = this.name; <ide> stock.quantity = this.quantity; <ide> stock.total = this.total; <add> stock.averagePrice = this.averagePrice; <ide> return stock; <ide> } <del> <del> } <del> <add> } <ide> }
Java
apache-2.0
d1e08acb61f5ec0a247714e65dafbf5d077922d9
0
Whiley/WhileyCompiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler
// Copyright (c) 2011, David J. Pearce (David J. [email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyil.lang; import java.util.*; import wyil.util.*; /** * Represents a WYIL bytecode. The Whiley Intermediate Language (WYIL) employs * register-based bytecodes (as opposed to say the Java Virtual Machine, which * uses stack-based bytecodes). During execution, one can think of the "machine" * as maintaining a call stack made up of "frames". For each function or method * on the call stack, the corresponding frame consists of zero or more <i>local * variables</i> (a.k.a registers). Bytecodes may read/write values from local * variables. Like the Java Virtual Machine, WYIL uses unstructured * control-flow. However, unlike the JVM, it also allows variables to take on * different types at different points. The following illustrates: * * <pre> * int sum([int] data): * r = 0 * for item in data: * r = r + item * return r * </pre> * * This function is compiled into the following WYIL bytecode: * * <pre> * int sum([int] data): * body: * var r, $2, item * const %1 = 0 // int * assign %2 = %0 // [int] * forall %3 in %2 () // [int] * assign %4 = %1 // int * add %1 = %4, %3 // int * return %1 // int * </pre> * * Here, we can see that every bytecode is associated with one (or more) types. * These types are inferred by the compiler during type propagation. * * @author David J. Pearce */ public abstract class Code { /** * Provided to aid readability of client code. */ public final static int NULL_REG = -1; /** * Provided to aid readability of client code. */ public final static int REG_0 = 0; /** * Provided to aid readability of client code. */ public final static int REG_1 = 1; /** * Provided to aid readability of client code. */ public final static int REG_2 = 2; /** * Provided to aid readability of client code. */ public final static int REG_3 = 3; /** * Provided to aid readability of client code. */ public final static int REG_4 = 4; /** * Provided to aid readability of client code. */ public final static int REG_5 = 5; /** * Provided to aid readability of client code. */ public final static int REG_6 = 6; /** * Provided to aid readability of client code. */ public final static int REG_7 = 7; /** * Provided to aid readability of client code. */ public final static int REG_8 = 8; /** * Provided to aid readability of client code. */ public final static int REG_9 = 9; // =============================================================== // Bytecode Constructors // =============================================================== /** * Construct an <code>assert</code> bytecode which raises an assertion * failure with the given if the given condition evaluates to false. * * @param message * --- message to report upon failure. * @return */ public static Assert Assert(Type type, int leftOperand, int rightOperand, Comparator cop, String message) { return get(new Assert(type, leftOperand, rightOperand, cop, message)); } /** * Construct an <code>assumet</code> bytecode which raises an assertion * failure with the given if the given condition evaluates to false. * * @param message * --- message to report upon failure. * @return */ public static Assume Assume(Type type, int leftOperand, int rightOperand, Comparator cop, String message) { return get(new Assume(type, leftOperand, rightOperand, cop, message)); } public static ArithOp ArithOp(Type type, int target, int leftOperand, int rightOperand, ArithOperation op) { return get(new ArithOp(type, target, leftOperand, rightOperand, op)); } /** * Construct a <code>const</code> bytecode which loads a given constant onto * the stack. * * @param afterType * --- record type. * @param field * --- field to write. * @return */ public static Const Const(int target, Value constant) { return get(new Const(target, constant)); } /** * Construct a <code>copy</code> bytecode which copies the value from a * given operand register into a given target register. * * @param type * --- record type. * @param reg * --- reg to load. * @return */ public static Assign Assign(Type type, int target, int operand) { return get(new Assign(type, target, operand)); } public static Convert Convert(Type from, int target, int operand, Type to) { return get(new Convert(from, target, operand, to)); } public static final Debug Debug(int operand) { return get(new Debug(operand)); } public static LoopEnd End(String label) { return get(new LoopEnd(label)); } /** * Construct a <code>fieldload</code> bytecode which reads a given field * from a record of a given type. * * @param type * --- record type. * @param field * --- field to load. * @return */ public static FieldLoad FieldLoad(Type.EffectiveRecord type, int target, int operand, String field) { return get(new FieldLoad(type, target, operand, field)); } /** * Construct a <code>goto</code> bytecode which branches unconditionally to * a given label. * * @param label * --- destination label. * @return */ public static Goto Goto(String label) { return get(new Goto(label)); } public static Invoke Invoke(Type.FunctionOrMethod fun, int target, Collection<Integer> operands, NameID name) { return get(new Invoke(fun, target, toIntArray(operands), name)); } public static Invoke Invoke(Type.FunctionOrMethod fun, int target, int[] operands, NameID name) { return get(new Invoke(fun, target, operands, name)); } public static Not Not(int target, int operand) { return get(new Not(target, operand)); } public static LengthOf LengthOf(Type.EffectiveCollection type, int target, int operand) { return get(new LengthOf(type, target, operand)); } public static Move Move(Type type, int target, int operand) { return get(new Move(type, target, operand)); } public static SubList SubList(Type.EffectiveList type, int target, int sourceOperand, int leftOperand, int rightOperand) { int[] operands = new int[] { sourceOperand, leftOperand, rightOperand }; return get(new SubList(type, target, operands)); } private static SubList SubList(Type.EffectiveList type, int target, int[] operands) { return get(new SubList(type, target, operands)); } public static ListOp ListOp(Type.EffectiveList type, int target, int leftOperand, int rightOperand, ListOperation dir) { return get(new ListOp(type, target, leftOperand, rightOperand, dir)); } /** * Construct a <code>listload</code> bytecode which reads a value from a * given index in a given list. * * @param type * --- list type. * @return */ public static IndexOf IndexOf(Type.EffectiveMap type, int target, int leftOperand, int rightOperand) { return get(new IndexOf(type, target, leftOperand, rightOperand)); } public static Loop Loop(String label, Collection<Integer> operands) { return get(new Loop(label, toIntArray(operands))); } public static Loop Loop(String label, int[] modifies) { return get(new Loop(label, modifies)); } public static ForAll ForAll(Type.EffectiveCollection type, int sourceOperand, int indexOperand, Collection<Integer> modifiedOperands, String label) { return get(new ForAll(type, sourceOperand, indexOperand, toIntArray(modifiedOperands), label)); } public static ForAll ForAll(Type.EffectiveCollection type, int sourceOperand, int indexOperand, int[] modifiedOperands, String label) { return get(new ForAll(type, sourceOperand, indexOperand, modifiedOperands, label)); } /** * Construct a <code>newdict</code> bytecode which constructs a new * dictionary and puts it on the stack. * * @param type * @return */ public static NewMap NewMap(Type.Dictionary type, int target, Collection<Integer> operands) { return get(new NewMap(type, target, toIntArray(operands))); } public static NewMap NewMap(Type.Dictionary type, int target, int[] operands) { return get(new NewMap(type, target, operands)); } /** * Construct a <code>newset</code> bytecode which constructs a new set and * puts it on the stack. * * @param type * @return */ public static NewSet NewSet(Type.Set type, int target, Collection<Integer> operands) { return get(new NewSet(type, target, toIntArray(operands))); } public static NewSet NewSet(Type.Set type, int target, int[] operands) { return get(new NewSet(type, target, operands)); } /** * Construct a <code>newlist</code> bytecode which constructs a new list and * puts it on the stack. * * @param type * @return */ public static NewList NewList(Type.List type, int target, Collection<Integer> operands) { return get(new NewList(type, target, toIntArray(operands))); } public static NewList NewList(Type.List type, int target, int[] operands) { return get(new NewList(type, target, operands)); } /** * Construct a <code>newtuple</code> bytecode which constructs a new tuple * and puts it on the stack. * * @param type * @return */ public static NewTuple NewTuple(Type.Tuple type, int target, Collection<Integer> operands) { return get(new NewTuple(type, target, toIntArray(operands))); } public static NewTuple NewTuple(Type.Tuple type, int target, int[] operands) { return get(new NewTuple(type, target, operands)); } /** * Construct a <code>newrecord</code> bytecode which constructs a new record * and puts it on the stack. * * @param type * @return */ public static NewRecord NewRecord(Type.Record type, int target, Collection<Integer> operands) { return get(new NewRecord(type, target, toIntArray(operands))); } public static NewRecord NewRecord(Type.Record type, int target, int[] operands) { return get(new NewRecord(type, target, operands)); } /** * Construct a return bytecode which does return a value and, hence, its * type automatically defaults to void. * * @return */ public static Return Return() { return get(new Return(Type.T_VOID, NULL_REG)); } /** * Construct a return bytecode which reads a value from the operand register * and returns it. * * @param type * --- type of the value to be returned (cannot be void). * @param operand * --- register to read return value from. * @return */ public static Return Return(Type type, int operand) { return get(new Return(type, operand)); } public static If If(Type type, int leftOperand, int rightOperand, Comparator cop, String label) { return get(new If(type, leftOperand, rightOperand, cop, label)); } public static IfIs IfIs(Type type, int leftOperand, Type rightOperand, String label) { return get(new IfIs(type, leftOperand, rightOperand, label)); } public static IndirectSend IndirectSend(Type.Message msg, int target, int operand, Collection<Integer> operands, boolean synchronous) { return get(new IndirectSend(msg, synchronous, target, operand, toIntArray(operands))); } public static IndirectSend IndirectSend(Type.Message msg, int target, int operand, int[] operands, boolean synchronous) { return get(new IndirectSend(msg, synchronous, target, operand, operands)); } public static IndirectInvoke IndirectInvoke(Type.FunctionOrMethod fun, int target, int operand, Collection<Integer> operands) { return get(new IndirectInvoke(fun, target, operand, toIntArray(operands))); } public static IndirectInvoke IndirectInvoke(Type.FunctionOrMethod fun, int target, int operand, int[] operands) { return get(new IndirectInvoke(fun, target, operand, operands)); } public static Invert Invert(Type type, int target, int operand) { return get(new Invert(type, target, operand)); } public static Label Label(String label) { return get(new Label(label)); } public static final Nop Nop = new Nop(); public static SetOp SetOp(Type.EffectiveSet type, int target, int leftOperand, int rightOperand, SetOperation operation) { return get(new SetOp(type, target, leftOperand, rightOperand, operation)); } public static StringOp StringOp(int target, int leftOperand, int rightOperand, StringOperation operation) { return get(new StringOp(target, leftOperand, rightOperand, operation)); } public static SubString SubString(int target, int sourceOperand, int leftOperand, int rightOperand) { int[] operands = new int[] { sourceOperand, leftOperand, rightOperand }; return get(new SubString(target, operands)); } private static SubString SubString(int target, int[] operands) { return get(new SubString(target, operands)); } /** * Construct an <code>send</code> bytecode which sends a message to an * actor. This may be either synchronous or asynchronous. * * @param label * --- destination label. * @return */ public static Send Send(Type.Message meth, int target, Collection<Integer> operands, NameID name, boolean synchronous) { return get(new Send(meth, target, toIntArray(operands), name, synchronous)); } public static Send Send(Type.Message meth, int target, int[] operands, NameID name, boolean synchronous) { return get(new Send(meth, target, operands, name, synchronous)); } /** * Construct a <code>switch</code> bytecode which pops a value off the * stack, and switches to a given label based on it. * * @param type * --- value type to switch on. * @param defaultLabel * --- target for the default case. * @param cases * --- map from values to destination labels. * @return */ public static Switch Switch(Type type, int operand, String defaultLabel, Collection<Pair<Value, String>> cases) { return get(new Switch(type, operand, defaultLabel, cases)); } /** * Construct a <code>throw</code> bytecode which pops a value off the stack * and throws it. * * @param afterType * --- value type to throw * @return */ public static Throw Throw(Type type, int operand) { return get(new Throw(type, operand)); } /** * Construct a <code>trycatch</code> bytecode which defines a region of * bytecodes which are covered by one or more catch handles. * * @param target * --- identifies end-of-block label. * @param catches * --- map from types to destination labels. * @return */ public static TryCatch TryCatch(int operand, String target, Collection<Pair<Type, String>> catches) { return get(new TryCatch(operand, target, catches)); } public static TryEnd TryEnd(String label) { return get(new TryEnd(label)); } /** * Construct a <code>tupleload</code> bytecode which reads the value at a * given index in a tuple * * @param type * --- dictionary type. * @return */ public static TupleLoad TupleLoad(Type.EffectiveTuple type, int target, int operand, int index) { return get(new TupleLoad(type, target, operand, index)); } public static Neg Neg(Type type, int target, int operand) { return get(new Neg(type, target, operand)); } public static NewObject NewObject(Type.Reference type, int target, int operand) { return get(new NewObject(type, target, operand)); } public static Dereference Dereference(Type.Reference type, int target, int operand) { return get(new Dereference(type, target, operand)); } /** * Construct a <code>update</code> bytecode which writes a value into a * compound structure, as determined by a given access path. * * @param afterType * --- record type. * @param field * --- field to write. * @return */ public static Update Update(Type beforeType, int target, int operand, Collection<Integer> operands, Type afterType, Collection<String> fields) { return get(new Update(beforeType, target, operand, toIntArray(operands), afterType, fields)); } public static Update Update(Type beforeType, int target, int operand, int[] operands, Type afterType, Collection<String> fields) { return get(new Update(beforeType, target, operand, operands, afterType, fields)); } public static Void Void(Type type, int[] operands) { return get(new Void(type, operands)); } // =============================================================== // Abstract Methods // =============================================================== /** * Determine which registers are used in this bytecode. This can be used, * for example, to determine the size of the register file required for a * given method. * * @param register */ public void registers(java.util.Set<Integer> register) { // default implementation does nothing } /** * Remaps all registers according to a given binding. Registers not * mentioned in the binding retain their original value. * * @param binding * --- map from (existing) registers to (new) registers. * @return */ public Code remap(Map<Integer, Integer> binding) { return this; } /** * Relabel all labels according to the given map. * * @param labels * @return */ public Code relabel(Map<String, String> labels) { return this; } // =============================================================== // Abstract Bytecodes // =============================================================== public static abstract class AbstractAssignable extends Code { public final int target; private AbstractAssignable(int target) { this.target = target; } } /** * Represents the set of bytcodes which take a single register operand and * write a result to the target register. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractUnaryAssignable<T> extends AbstractAssignable { public final T type; public final int operand; private AbstractUnaryAssignable(T type, int target, int operand) { super(target); if (type == null) { throw new IllegalArgumentException( "AbstractUnOp type argument cannot be null"); } this.type = type; this.operand = operand; } @Override public final void registers(java.util.Set<Integer> registers) { registers.add(target); registers.add(operand); } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nTarget = binding.get(target); Integer nOperand = binding.get(operand); if (nTarget != null || nOperand != null) { nTarget = nTarget != null ? nTarget : target; nOperand = nOperand != null ? nOperand : operand; return clone(nTarget, nOperand); } return this; } protected abstract Code clone(int nTarget, int nOperand); public int hashCode() { return type.hashCode() + target + operand; } public boolean equals(Object o) { if (o instanceof AbstractUnaryAssignable) { AbstractUnaryAssignable bo = (AbstractUnaryAssignable) o; return target == bo.target && operand == bo.operand && type.equals(bo.type); } return false; } } /** * Represents the set of bytcodes which take a single register operand, and * do not write any result. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractUnaryOp<T> extends Code { public final T type; public final int operand; private AbstractUnaryOp(T type, int operand) { if (type == null) { throw new IllegalArgumentException( "AbstractUnaryOp type argument cannot be null"); } this.type = type; this.operand = operand; } @Override public final void registers(java.util.Set<Integer> registers) { registers.add(operand); } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nOperand = binding.get(operand); if (nOperand != null) { return clone(nOperand); } return this; } protected abstract Code clone(int nOperand); public int hashCode() { return type.hashCode() + operand; } public boolean equals(Object o) { if (o instanceof AbstractUnaryOp) { AbstractUnaryOp bo = (AbstractUnaryOp) o; return operand == bo.operand && type.equals(bo.type); } return false; } } /** * Represents the set of bytcodes which take two register operands and write * a result to the target register. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractBinaryAssignable<T> extends AbstractAssignable { public final T type; public final int leftOperand; public final int rightOperand; private AbstractBinaryAssignable(T type, int target, int leftOperand, int rightOperand) { super(target); if (type == null) { throw new IllegalArgumentException( "AbstractBinOp type argument cannot be null"); } this.type = type; this.leftOperand = leftOperand; this.rightOperand = rightOperand; } @Override public final void registers(java.util.Set<Integer> registers) { registers.add(target); registers.add(leftOperand); registers.add(rightOperand); } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nTarget = binding.get(target); Integer nLeftOperand = binding.get(leftOperand); Integer nRightOperand = binding.get(rightOperand); if (nTarget != null || nLeftOperand != null || nRightOperand != null) { nTarget = nTarget != null ? nTarget : target; nLeftOperand = nLeftOperand != null ? nLeftOperand : leftOperand; nRightOperand = nRightOperand != null ? nRightOperand : rightOperand; return clone(nTarget, nLeftOperand, nRightOperand); } return this; } protected abstract Code clone(int nTarget, int nLeftOperand, int nRightOperand); public int hashCode() { return type.hashCode() + target + leftOperand + rightOperand; } public boolean equals(Object o) { if (o instanceof AbstractBinaryAssignable) { AbstractBinaryAssignable bo = (AbstractBinaryAssignable) o; return target == bo.target && leftOperand == bo.leftOperand && rightOperand == bo.rightOperand && type.equals(bo.type); } return false; } } /** * Represents the set of bytcodes which take an arbitrary number of register * operands and write a result to the target register. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractNaryAssignable<T> extends AbstractAssignable { public final T type; public final int[] operands; private AbstractNaryAssignable(T type, int target, int[] operands) { super(target); if (type == null) { throw new IllegalArgumentException( "AbstractBinOp type argument cannot be null"); } this.type = type; this.operands = operands; } @Override public final void registers(java.util.Set<Integer> registers) { if (target >= 0) { registers.add(target); } for (int i = 0; i != operands.length; ++i) { registers.add(operands[i]); } } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nTarget = binding.get(target); int[] nOperands = remap(binding, operands); if (nTarget != null || nOperands != operands) { nTarget = nTarget != null ? nTarget : target; return clone(nTarget, nOperands); } return this; } protected abstract Code clone(int nTarget, int[] nOperands); public int hashCode() { return type.hashCode() + target + Arrays.hashCode(operands); } public boolean equals(Object o) { if (o instanceof AbstractNaryAssignable) { AbstractNaryAssignable bo = (AbstractNaryAssignable) o; return target == bo.target && Arrays.equals(operands, bo.operands) && type.equals(bo.type); } return false; } } /** * Represents the set of bytcodes which take an arbitrary number of register * operands and write a result to the target register. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractSplitNaryAssignable<T> extends AbstractAssignable { public final T type; public final int operand; public final int[] operands; private AbstractSplitNaryAssignable(T type, int target, int operand, int[] operands) { super(target); if (type == null) { throw new IllegalArgumentException( "AbstractSplitNaryAssignable type argument cannot be null"); } this.type = type; this.operand = operand; this.operands = operands; } @Override public final void registers(java.util.Set<Integer> registers) { if (target >= 0) { registers.add(target); } registers.add(operand); for (int i = 0; i != operands.length; ++i) { registers.add(operands[i]); } } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nTarget = binding.get(target); Integer nOperand = binding.get(target); int[] nOperands = remap(binding, operands); if (nTarget != null || nOperand != null || nOperands != operands) { nTarget = nTarget != null ? nTarget : target; nOperand = nOperand != null ? nOperand : operand; return clone(nTarget, nOperand, nOperands); } return this; } protected abstract Code clone(int nTarget, int nOperand, int[] nOperands); public int hashCode() { return type.hashCode() + target + operand + Arrays.hashCode(operands); } public boolean equals(Object o) { if (o instanceof AbstractSplitNaryAssignable) { AbstractSplitNaryAssignable bo = (AbstractSplitNaryAssignable) o; return target == bo.target && operand == bo.operand && Arrays.equals(operands, bo.operands) && type.equals(bo.type); } return false; } } /** * Represents the set of bytcodes which take two register operands and * perform a comparison of their values. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractBinaryOp<T> extends Code { public final T type; public final int leftOperand; public final int rightOperand; private AbstractBinaryOp(T type, int leftOperand, int rightOperand) { if (type == null) { throw new IllegalArgumentException( "AbstractBinCond type argument cannot be null"); } this.type = type; this.leftOperand = leftOperand; this.rightOperand = rightOperand; } @Override public final void registers(java.util.Set<Integer> registers) { registers.add(leftOperand); registers.add(rightOperand); } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nLeftOperand = binding.get(leftOperand); Integer nRightOperand = binding.get(rightOperand); if (nLeftOperand != null || nRightOperand != null) { nLeftOperand = nLeftOperand != null ? nLeftOperand : leftOperand; nRightOperand = nRightOperand != null ? nRightOperand : rightOperand; return clone(nLeftOperand, nRightOperand); } return this; } protected abstract Code clone(int nLeftOperand, int nRightOperand); public int hashCode() { return type.hashCode() + leftOperand + rightOperand; } public boolean equals(Object o) { if (o instanceof AbstractBinaryOp) { AbstractBinaryOp bo = (AbstractBinaryOp) o; return leftOperand == bo.leftOperand && rightOperand == bo.rightOperand && type.equals(bo.type); } return false; } } // =============================================================== // Bytecode Implementations // =============================================================== /** * Represents a binary operator (e.g. '+','-',etc) that is provided to a * <code>BinOp</code> bytecode. * * @author David J. Pearce * */ public enum ArithOperation { ADD { public String toString() { return "add"; } }, SUB { public String toString() { return "sub"; } }, MUL { public String toString() { return "mul"; } }, DIV { public String toString() { return "div"; } }, REM { public String toString() { return "rem"; } }, RANGE { public String toString() { return "range"; } }, BITWISEOR { public String toString() { return "or"; } }, BITWISEXOR { public String toString() { return "xor"; } }, BITWISEAND { public String toString() { return "and"; } }, LEFTSHIFT { public String toString() { return "shl"; } }, RIGHTSHIFT { public String toString() { return "shr"; } }, }; /** * <p> * A binary operation which reads two numeric values from the operand * registers, performs an operation on them and writes the result to the * target register. The binary operators are: * </p> * <ul> * <li><i>add, subtract, multiply, divide, remainder</i>. Both operands must * be either integers or reals (but not one or the other). A value of the * same type is produced.</li> * <li><i>range</i></li> * <li><i>bitwiseor, bitwisexor, bitwiseand</i></li> * <li><i>leftshift,rightshift</i></li> * </ul> * For example, the following Whiley code: * * <pre> * int f(int x, int y): * return ((x * y) + 1) / 2 * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int x, int y): * body: * mul %2 = %0, %1 : int * const %3 = 1 : int * add %2 = %2, %3 : int * const %3 = 2 : int * const %4 = 0 : int * assertne %3, %4 "division by zero" : int * div %2 = %2, %3 : int * return %2 : int * </pre> * * Here, the <code>assertne</code> bytecode has been included to check * against division-by-zero. In this particular case the assertion is known * true at compile time and, in practice, would be compiled away. * * @author David J. Pearce * */ public static final class ArithOp extends AbstractBinaryAssignable<Type> { public final ArithOperation bop; private ArithOp(Type type, int target, int lhs, int rhs, ArithOperation bop) { super(type, target, lhs, rhs); if (bop == null) { throw new IllegalArgumentException( "BinOp bop argument cannot be null"); } this.bop = bop; } @Override public Code clone(int nTarget, int nLeftOperand, int nRightOperand) { return Code.ArithOp(type, nTarget, nLeftOperand, nRightOperand, bop); } public int hashCode() { return bop.hashCode() + super.hashCode(); } public boolean equals(Object o) { if (o instanceof ArithOp) { ArithOp bo = (ArithOp) o; return bop.equals(bo.bop) && super.equals(bo); } return false; } public String toString() { return bop + " %" + target + " = %" + leftOperand + ", %" + rightOperand + " : " + type; } } /** * Reads a value from the operand register, converts it to a given type and * writes the result to the target register. This bytecode is the only way * to change the type of a value. It's purpose is to simplify * implementations which have different representations of data types. A * convert bytecode must be inserted whenever the type of a register * changes. This includes at control-flow meet points, when the value is * passed as a parameter, assigned to a field, etc. For example, the * following Whiley code: * * <pre> * real f(int x): * return x + 1 * </pre> * * can be translated into the following WYIL code: * * <pre> * real f(int x): * body: * const %2 = 1 : int * add %1 = %0, %2 : int * convert %1 = %1 real : int * return %1 : real * </pre> * <p> * Here, we see that the <code>int</code> value in register <code>%1</code> * must be explicitly converted into a <code>real</code> value before it can * be returned from this function. * </p> * <p> * <b>NOTE:</b> In many cases, this bytecode may correspond to a nop on the * hardware. Consider converting from <code>[any]</code> to <code>any</code> * . On the JVM, <code>any</code> translates to <code>Object</code>, whilst * <code>[any]</code> translates to <code>List</code> (which is an instance * of <code>Object</code>). Thus, no conversion is necessary since * <code>List</code> can safely flow into <code>Object</code>. * </p> * */ public static final class Convert extends AbstractUnaryAssignable<Type> { public final Type result; private Convert(Type from, int target, int operand, Type result) { super(from, target, operand); if (result == null) { throw new IllegalArgumentException( "Convert to argument cannot be null"); } this.result = result; } public Code clone(int nTarget, int nOperand) { return Code.Convert(type, nTarget, nOperand, result); } public int hashCode() { return result.hashCode() + super.hashCode(); } public boolean equals(Object o) { if (o instanceof Convert) { Convert c = (Convert) o; return super.equals(c) && result.equals(c.result); } return false; } public String toString() { return "convert %" + target + " = %" + operand + " " + result + " : " + type; } } /** * Writes a constant value to a target register. This includes * <i>integers</i>, <i>rationals</i>, <i>lists</i>, <i>sets</i>, * <i>maps</i>, etc. For example, the following Whiley code: * * <pre> * int f(int x): * xs = {1,2.12} * return |xs| + 1 * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int x): * body: * var xs * const %2 = 1 : int * convert %2 = % 2 int|real : int * const %3 = 2.12 : real * convert %3 = % 3 int|real : real * newset %1 = (%2, %3) : {int|real} * assign %3 = %1 : {int|real} * lengthof %3 = % 3 : {int|real} * const %4 = 1 : int * add %2 = % 3, %4 : int * return %2 : int * </pre> * * Here, we see two kinds of constants values being used: integers (i.e. * <code>const %2 = 1</code>) and rationals (i.e. <code>const %3 = 2.12</code>). * * @author David J. Pearce * */ public static final class Const extends AbstractAssignable { public final Value constant; private Const(int target, Value constant) { super(target); this.constant = constant; } @Override public void registers(java.util.Set<Integer> registers) { registers.add(target); } @Override public Code remap(Map<Integer, Integer> binding) { Integer nTarget = binding.get(target); if (nTarget != null) { return Code.Const(nTarget, constant); } return this; } public int hashCode() { return constant.hashCode() + target; } public boolean equals(Object o) { if (o instanceof Const) { Const c = (Const) o; return constant.equals(c.constant) && target == c.target; } return false; } public String toString() { return "const %" + target + " = " + constant + " : " + constant.type(); } } /** * Copy the contents from a given operand register into a given target * register. For example, the following Whiley code: * * <pre> * int f(int x): * x = x + 1 * return x * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int x): * body: * assign %1 = %0 : int * const %2 = 1 : int * add %0 = %1, %2 : int * return %0 : int * </pre> * * Here we see that an initial assignment is made from register * <code>%0</code> to register <code>%1</code>. In fact, this assignment is * unecessary but is useful to illustrate the <code>assign</code> bytecode. * * <p> * <b>NOTE:</b> on many architectures this operation may not actually clone * the data in question. Rather, it may copy the <i>reference</i> to the * data and then increment its <i>reference count</i>. This is to ensure * efficient treatment of large compound structures (e.g. lists, sets, maps * and records). * </p> * * @author David J. Pearce * */ public static final class Assign extends AbstractUnaryAssignable<Type> { private Assign(Type type, int target, int operand) { super(type, target, operand); } public Code clone(int nTarget, int nOperand) { return Code.Assign(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof Assign) { return super.equals(o); } return false; } public String toString() { return "assign %" + target + " = %" + operand + " " + " : " + type; } } /** * Read a string from the operand register and prints it to the debug * console. For example, the following Whiley code: * * <pre> * void f(int x): * debug "X = " + x * </pre> * * can be translated into the following WYIL code: * * <pre> * void f(int x): * body: * const %2 = "X = " : string * convert %0 = %0 any : int * invoke %0 (%0) whiley/lang/Any:toString : string(any) * strappend %1 = %2, %0 : string * debug %1 : string * return * </pre> * * <b>NOTE</b> This bytecode is not intended to form part of the program's * operation. Rather, it is to facilitate debugging within functions (since * they cannot have side-effects). Furthermore, if debugging is disabled, * this bytecode is a nop. * * @author David J. Pearce * */ public static final class Debug extends AbstractUnaryOp<Type.Strung> { private Debug(int operand) { super(Type.T_STRING, operand); } @Override public Code clone(int nOperand) { return Code.Debug(nOperand); } public boolean equals(Object o) { return o instanceof Debug && super.equals(o); } public String toString() { return "debug %" + operand + " " + " : " + type; } } /** * Marks the end of a loop block. * * @author David J. Pearce * */ public static final class LoopEnd extends Label { LoopEnd(String label) { super(label); } public LoopEnd relabel(Map<String, String> labels) { String nlabel = labels.get(label); if (nlabel == null) { return this; } else { return End(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if (o instanceof LoopEnd) { LoopEnd e = (LoopEnd) o; return e.label.equals(label); } return false; } public String toString() { return "end " + label; } } /** * An abstract class representing either an <code>assert</code> or * <code>assume</code> bytecode. * * @author David J. Pearce * */ public static abstract class AssertOrAssume extends AbstractBinaryOp<Type> { public final Comparator op; public final String msg; private AssertOrAssume(Type type, int leftOperand, int rightOperand, Comparator cop, String msg) { super(type, leftOperand, rightOperand); if (cop == null) { throw new IllegalArgumentException( "Assert op argument cannot be null"); } this.op = cop; this.msg = msg; } } /** * Reads two operand registers, compares their values and raises an * assertion failure with the given message if comparison is false. For * example, the following Whiley code: * * <pre> * int f([int] xs, int i): * return xs[i] * </pre> * * can be translated into the following WYIL code: * * <pre> * int f([int] xs, int i): * body: * const %2 = 0 : int * assertge %1, %2 "index out of bounds (negative)" : int * lengthof %3 = %0 : [int] * assertlt %2, %3 "index out of bounds (not less than length)" : int * indexof %1 = %0, %1 : [int] * return %1 : int * </pre> * * Here, we see <code>assert</code> bytecodes being used to check list * access is not out-of-bounds. * * @author David J. Pearce * */ public static final class Assert extends AssertOrAssume { private Assert(Type type, int leftOperand, int rightOperand, Comparator cop, String msg) { super(type, leftOperand, rightOperand, cop, msg); } @Override public Code clone(int nLeftOperand, int nRightOperand) { return Code.Assert(type, nLeftOperand, nRightOperand, op, msg); } public boolean equals(Object o) { if (o instanceof Assert) { Assert ig = (Assert) o; return op == ig.op && msg.equals(ig.msg) && super.equals(ig); } return false; } public String toString() { return "assert" + op + " %" + leftOperand + ", %" + rightOperand + " \"" + msg + "\"" + " : " + type; } } /** * Reads two operand registers, compares their values and raises an * assertion failure with the given message is raised if comparison is * false. Whilst this is very similar to an assert statement, it causes a * slightly different interaction with the type checker and/or theorem * prover. More specifically, they will not attempt to show the condition is * true and, instead, will simply assume it is (and leave an appropriate * runtime check). This is useful for override these processes in situations * where they are not smart enough to prove something is true. * * @author David J. Pearce * */ public static final class Assume extends AssertOrAssume { private Assume(Type type, int leftOperand, int rightOperand, Comparator cop, String msg) { super(type, leftOperand, rightOperand, cop, msg); } @Override public Code clone(int nLeftOperand, int nRightOperand) { return Code.Assume(type, nLeftOperand, nRightOperand, op, msg); } public boolean equals(Object o) { if (o instanceof Assume) { Assume ig = (Assume) o; return op == ig.op && msg.equals(ig.msg) && super.equals(ig); } return false; } public String toString() { return "assume" + op + " %" + leftOperand + ", %" + rightOperand + " \"" + msg + "\"" + " : " + type; } } /** * Reads a record value from an operand register, extracts the value of a * given field and writes this to the target register. For example, the * following Whiley code: * * <pre> * define Point as {int x, int y} * * int f(Point p): * return p.x + p.y * </pre> * * can be translated into the following WYIL code: * * <pre> * int f({int x,int y} p): * body: * fieldload %2 = %0 x : {int x,int y} * fieldload %3 = %0 y : {int x,int y} * add %1 = %2, %3 : int * return %1 : int * </pre> * * @author David J. Pearce * */ public static final class FieldLoad extends AbstractUnaryAssignable<Type.EffectiveRecord> { public final String field; private FieldLoad(Type.EffectiveRecord type, int target, int operand, String field) { super(type, target, operand); if (field == null) { throw new IllegalArgumentException( "FieldLoad field argument cannot be null"); } this.field = field; } @Override public Code clone(int nTarget, int nOperand) { return Code.FieldLoad(type, nTarget, nOperand, field); } public int hashCode() { return super.hashCode() + field.hashCode(); } public Type fieldType() { return type.fields().get(field); } public boolean equals(Object o) { if (o instanceof FieldLoad) { FieldLoad i = (FieldLoad) o; return super.equals(i) && field.equals(i.field); } return false; } public String toString() { return "fieldload %" + target + " = %" + operand + " " + field + " : " + type; } } /** * Branches unconditionally to the given label. This is typically used for * if/else statements. For example, the following Whiley code: * * <pre> * int f(int x): * if x >= 0: * x = 1 * else: * x = -1 * return x * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int x): * body: * const %1 = 0 : int * iflt %0, %1 goto blklab0 : int * const %0 = 1 : int * goto blklab1 * .blklab0 * const %0 = 1 : int * neg %0 = % 0 : int * .blklab1 * return %0 : int * </pre> * * Here, we see the <code>goto</code> bytecode being used to jump from the * end of the true branch over the false branch. * * <p> * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, a <code>goto</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * </p> * * @author David J. Pearce * */ public static final class Goto extends Code { public final String target; private Goto(String target) { this.target = target; } public Goto relabel(Map<String, String> labels) { String nlabel = labels.get(target); if (nlabel == null) { return this; } else { return Goto(nlabel); } } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if (o instanceof Goto) { return target.equals(((Goto) o).target); } return false; } public String toString() { return "goto " + target; } } /** * <p> * Branches conditionally to the given label by reading the values from two * operand registers and comparing them. The possible comparators are: * </p> * <ul> * <li><i>equals (eq) and not-equals (ne)</i>. Both operands must have the * given type.</li> * <li><i>less-than (lt), less-than-or-equals (le), greater-than (gt) and * great-than-or-equals (ge).</i> Both operands must have the given type, * which additionally must by either <code>char</code>, <code>int</code> or * <code>real</code>.</li> * <li><i>element of (in).</i> The second operand must be a set whose * element type is that of the first.</li> * <li><i>subset (ss) and subset-equals (sse)</i>. Both operands must have * the given type, which additionally must be a set.</li> * </ul> * For example, the following Whiley code: * * <pre> * int f(int x, int y): * if x < y: * return -1 * else if x > y: * return 1 * else: * return 0 * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int x, int y): * body: * ifge %0, %1 goto blklab0 : int * const %2 = -1 : int * return %2 : int * .blklab0 * ifle %0, %1 goto blklab2 : int * const %2 = 1 : int * return %2 : int * .blklab2 * const %2 = 0 : int * return %2 : int * </pre> * * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, an <code>ifgoto</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * * @author David J. Pearce * */ public static final class If extends AbstractBinaryOp<Type> { public final String target; public final Comparator op; private If(Type type, int leftOperand, int rightOperand, Comparator op, String target) { super(type, leftOperand, rightOperand); if (op == null) { throw new IllegalArgumentException( "IfGoto op argument cannot be null"); } if (target == null) { throw new IllegalArgumentException( "IfGoto target argument cannot be null"); } this.op = op; this.target = target; } public If relabel(Map<String, String> labels) { String nlabel = labels.get(target); if (nlabel == null) { return this; } else { return If(type, leftOperand, rightOperand, op, nlabel); } } @Override public Code clone(int nLeftOperand, int nRightOperand) { return Code.If(type, nLeftOperand, nRightOperand, op, target); } public int hashCode() { return super.hashCode() + op.hashCode() + target.hashCode(); } public boolean equals(Object o) { if (o instanceof If) { If ig = (If) o; return op == ig.op && target.equals(ig.target) && super.equals(ig); } return false; } public String codeString() { return null; } public String toString() { return "if" + op + " %" + leftOperand + ", %" + rightOperand + " goto " + target + " : " + type; } } /** * Represents a comparison operator (e.g. '==','!=',etc) that is provided to * a <code>IfGoto</code> bytecode. * * @author David J. Pearce * */ public enum Comparator { EQ() { public String toString() { return "eq"; } }, NEQ { public String toString() { return "ne"; } }, LT { public String toString() { return "lt"; } }, LTEQ { public String toString() { return "le"; } }, GT { public String toString() { return "gt"; } }, GTEQ { public String toString() { return "ge"; } }, ELEMOF { public String toString() { return "in"; } }, SUBSET { public String toString() { return "sb"; } }, SUBSETEQ { public String toString() { return "sbe"; } } }; /** * Determine the inverse comparator, or null if no inverse exists. * * @param cop * @return */ public static Code.Comparator invert(Code.Comparator cop) { switch (cop) { case EQ: return Code.Comparator.NEQ; case NEQ: return Code.Comparator.EQ; case LT: return Code.Comparator.GTEQ; case LTEQ: return Code.Comparator.GT; case GT: return Code.Comparator.LTEQ; case GTEQ: return Code.Comparator.LT; } return null; } /** * Branches conditionally to the given label based on the result of a * runtime type test against a value from the operand register. More * specifically, it checks whether the value is a subtype of the type test. * The operand register is automatically <i>retyped</i> as a result of the * type test. On the true branch, its type is intersected with type test. On * the false branch, its type is intersected with the <i>negation</i> of the * type test. For example, the following Whiley code: * * <pre> * int f(int|[int] x): * if x is [int]: * return |x| * else: * return x * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int|[int] x): * body: * ifis %0, [int] goto lab : int|[int] * return %0 : int * .lab * lengthof %0 = %0 : [int] * return %0 : int * </pre> * * Here, we see that, on the false branch, register <code>%0</code> is * automatically given type <code>int</code>, whilst on the true branch it * is automatically given type <code>[int]</code>. * * <p> * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, an <code>iftype</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * </p> * * @author David J. Pearce * */ public static final class IfIs extends Code { public final Type type; public final String target; public final int leftOperand; public final Type rightOperand; private IfIs(Type type, int leftOperand, Type rightOperand, String target) { if (type == null) { throw new IllegalArgumentException( "IfUs type argument cannot be null"); } if (rightOperand == null) { throw new IllegalArgumentException( "IfIs test argument cannot be null"); } if (target == null) { throw new IllegalArgumentException( "IfIs target argument cannot be null"); } this.type = type; this.target = target; this.leftOperand = leftOperand; this.rightOperand = rightOperand; } public IfIs relabel(Map<String, String> labels) { String nlabel = labels.get(target); if (nlabel == null) { return this; } else { return IfIs(type, leftOperand, rightOperand, nlabel); } } @Override public void registers(java.util.Set<Integer> registers) { registers.add(leftOperand); } @Override public Code remap(Map<Integer, Integer> binding) { Integer nLeftOperand = binding.get(leftOperand); if (nLeftOperand != null) { return Code.IfIs(type, nLeftOperand, rightOperand, target); } return this; } public int hashCode() { return type.hashCode() + rightOperand.hashCode() + target.hashCode() + leftOperand + rightOperand.hashCode(); } public boolean equals(Object o) { if (o instanceof IfIs) { IfIs ig = (IfIs) o; return leftOperand == ig.leftOperand && rightOperand.equals(ig.rightOperand) && target.equals(ig.target) && type.equals(ig.type); } return false; } public String toString() { return "ifis" + " %" + leftOperand + ", " + rightOperand + " goto " + target + " : " + type; } } /** * Represents an indirect function call. For example, consider the * following: * * <pre> * int function(int(int) f, int x): * return f(x) * </pre> * * Here, the function call <code>f(x)</code> is indirect as the called * function is determined by the variable <code>f</code>. * * @author David J. Pearce * */ public static final class IndirectInvoke extends AbstractSplitNaryAssignable<Type.FunctionOrMethod> { private IndirectInvoke(Type.FunctionOrMethod type, int target, int operand, int[] operands) { super(type, target, operand, operands); } @Override public Code clone(int nTarget, int nOperand, int[] nOperands) { return IndirectInvoke(type, nTarget, nOperand, nOperands); } public boolean equals(Object o) { return o instanceof IndirectInvoke && super.equals(o); } public String toString() { if (target != Code.NULL_REG) { return "indirectinvoke " + target + " " + operand + " " + toString(operands) + " : " + type; } else { return "indirectinvoke " + operand + " " + toString(operands) + " : " + type; } } } /** * Represents an indirect message send (either synchronous or asynchronous). * For example, consider the following: * * <pre> * int ::method(Rec::int(int) m, Rec r, int x): * return r.m(x) * </pre> * * Here, the message send <code>r.m(x)</code> is indirect as the message * sent is determined by the variable <code>m</code>. * * @author David J. Pearce * */ public static final class IndirectSend extends AbstractSplitNaryAssignable<Type.Message> { public final boolean synchronous; private IndirectSend(Type.Message type, boolean synchronous, int target, int operand, int[] operands) { super(type, target, operand, operands); this.synchronous = synchronous; } @Override public Code clone(int nTarget, int nOperand, int[] nOperands) { return IndirectSend(type, nTarget, nOperand, nOperands, synchronous); } public boolean equals(Object o) { return o instanceof IndirectSend && super.equals(o); } public String toString() { if (synchronous) { if (target != Code.NULL_REG) { return "isend " + target + " " + operand + " " + toString(operands) + " : " + type; } else { return "ivsend" + operand + " " + toString(operands) + " : " + type; } } else { return "iasend" + operand + " " + toString(operands) + " : " + type; } } } /** * Read a boolean value from the operand register, inverts it and writes the * result to the target register. For example, the following Whiley code: * * <pre> * bool f(bool x): * return !x * </pre> * * can be translated into the following WYIL: * * <pre> * bool f(bool x): * body: * not %0 = %0 : int * return %0 : int * </pre> * * This simply reads the parameter <code>x</code> stored in register * <code>%0</code>, inverts it and then returns the inverted value. * * @author David J. Pearce * */ public static final class Not extends AbstractUnaryAssignable<Type.Bool> { private Not(int target, int operand) { super(Type.T_BOOL, target, operand); } @Override public Code clone(int nTarget, int nOperand) { return Code.Not(nTarget, nOperand); } public int hashCode() { return super.hashCode(); } public boolean equals(Object o) { if (o instanceof Not) { Not n = (Not) o; return super.equals(n); } return false; } public String toString() { return "not %" + target + " = %" + operand + " : " + type; } } /** * Corresponds to a function or method call whose parameters are read from * zero or more operand registers. If a return value is required, this is * written to a target register afterwards. For example, the following * Whiley code: * * <pre> * int g(int x, int y, int z): * return x * y * z * * int f(int x, int y): * r = g(x,y,3) * return r + 1 * </pre> * * can be translated into the following WYIL code: * * <pre> * int g(int x, int y, int z): * body: * mul %3 = %0, %1 : int * mul %3 = %3, %2 : int * return %3 : int * * int f(int x, int y): * body: * const %2 = 3 : int * invoke %2 = (%0, %1, %2) test:g : int(int,int,int) * const %3 = 1 : int * add %2 = (%2, %3) : int * return %2 : int * </pre> * * Here, we see that arguments to the <code>invoke</code> bytecode are * supplied in the order they are given in the function or method's * declaration. * * @author David J. Pearce * */ public static final class Invoke extends AbstractNaryAssignable<Type.FunctionOrMethod> { public final NameID name; private Invoke(Type.FunctionOrMethod type, int target, int[] operands, NameID name) { super(type, target, operands); this.name = name; } public int hashCode() { return name.hashCode() + super.hashCode(); } @Override public Code clone(int nTarget, int[] nOperands) { return Code.Invoke(type, nTarget, nOperands, name); } public boolean equals(Object o) { if (o instanceof Invoke) { Invoke i = (Invoke) o; return name.equals(i.name) && super.equals(i); } return false; } public String toString() { if (target != Code.NULL_REG) { return "invoke %" + target + " " + toString(operands) + " " + name + " : " + type; } else { return "invoke %" + toString(operands) + " " + name + " : " + type; } } } /** * Represents the labelled destination of a branch or loop statement. * * @author David J. Pearce * */ public static class Label extends Code { public final String label; private Label(String label) { this.label = label; } public Label relabel(Map<String, String> labels) { String nlabel = labels.get(label); if (nlabel == null) { return this; } else { return Label(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if (o instanceof Label) { return label.equals(((Label) o).label); } return false; } public String toString() { return "." + label; } } public enum ListOperation { LEFT_APPEND { public String toString() { return "lappend"; } }, RIGHT_APPEND { public String toString() { return "rappend"; } }, APPEND { public String toString() { return "append"; } } } /** * Reads the (effective) list values from two operand registers, performs an * operation (e.g. append) on them and writes the result back to a target * register. For example, the following Whiley code: * * <pre> * [int] f([int] xs, [int] ys): * return xs ++ ys * </pre> * * can be translated into the following WYIL code: * * <pre> * [int] f([int] xs, [int] ys): * body: * append %2 = %0, %1 : [int] * return %2 : [int] * </pre> * * This appends two the parameter lists together writting the new list into * register <code>%2</code>. * * @author David J. Pearce * */ public static final class ListOp extends AbstractBinaryAssignable<Type.EffectiveList> { public final ListOperation operation; private ListOp(Type.EffectiveList type, int target, int leftOperand, int rightOperand, ListOperation operation) { super(type, target, leftOperand, rightOperand); if (operation == null) { throw new IllegalArgumentException( "ListAppend direction cannot be null"); } this.operation = operation; } @Override public Code clone(int nTarget, int nLeftOperand, int nRightOperand) { return Code.ListOp(type, nTarget, nLeftOperand, nRightOperand, operation); } public int hashCode() { return super.hashCode() + operation.hashCode(); } public boolean equals(Object o) { if (o instanceof ListOp) { ListOp setop = (ListOp) o; return super.equals(setop) && operation.equals(setop.operation); } return false; } public String toString() { return operation + " %" + target + " = %" + leftOperand + ", %" + rightOperand + " : " + type; } } /** * Reads an (effective) collection (i.e. a set, list or map) from the * operand register, and writes its length into the target register. For * example, the following Whiley code: * * <pre> * int f([int] ls): * return |ls| * </pre> * * translates to the following WYIL code: * * <pre> * int f([int] ls): * body: * lengthof %0 = %0 : [int] * return %0 : int * </pre> * * @author David J. Pearce * */ public static final class LengthOf extends AbstractUnaryAssignable<Type.EffectiveCollection> { private LengthOf(Type.EffectiveCollection type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.LengthOf(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof LengthOf) { return super.equals(o); } return false; } public String toString() { return "lengthof %" + target + " = %" + operand + " : " + type; } } /** * Reads the (effective) list value from a source operand register, and the * integer values from two index operand registers, computes the sublist and * writes the result back to a target register. * * @author David J. Pearce * */ public static final class SubList extends AbstractNaryAssignable<Type.EffectiveList> { private SubList(Type.EffectiveList type, int target, int[] operands) { super(type, target, operands); } @Override public final Code clone(int nTarget, int[] nOperands) { return Code.SubList(type, nTarget, nOperands); } public boolean equals(Object o) { return o instanceof SubList && super.equals(o); } public String toString() { return "sublist %" + target + " = %" + operands[0] + ", %" + operands[1] + ", %" + operands[2] + " : " + type; } } /** * Reads an effective list or map from the source (left) operand register, * and a key value from the key (right) operand register and returns the * value associated with that key. If the key does not exist, then a fault * is raised. For example, the following Whiley code: * * <pre> * string f({int=>string} map, int key): * return map[key] * </pre> * * can be translated into the following WYIL code: * * <pre> * string f({int->string} map, int key): * body: * assertky %1, %0 "invalid key" : {int->string} * indexof %2 = %0, %1 : {int->string} * return %2 : string * </pre> * * Here, we see the <code>assertky</code> bytecode is used to first check * that the given key exists in <code>map</code>, otherwise a fault is * raised. * * @author David J. Pearce * */ public static final class IndexOf extends AbstractBinaryAssignable<Type.EffectiveMap> { private IndexOf(Type.EffectiveMap type, int target, int sourceOperand, int keyOperand) { super(type, target, sourceOperand, keyOperand); } protected Code clone(int nTarget, int nLeftOperand, int nRightOperand) { return Code.IndexOf(type, nTarget, nLeftOperand, nRightOperand); } public boolean equals(Object o) { if (o instanceof IndexOf) { return super.equals(o); } return false; } public String toString() { return "indexof %" + target + " = %" + leftOperand + ", %" + rightOperand + " : " + type; } } /** * Moves the contents of a given operand register into a given target * register. This is similar to an <code>assign</code> bytecode, except that * the register's contents are <i>voided</i> afterwards. This guarantees * that the register is no longer live, which is useful for determining the * live ranges of registers in a function or method. For example, the * following Whiley code: * * <pre> * int f(int x, int y): * x = x + 1 * return x * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int x, int y): * body: * ifge %0, %1 goto blklab0 : int * move %0 = %1 : int * .blklab0 * return %0 : int * </pre> * * Here we see that when <code>x < y</code> the value of <code>y</code> * (held in register <code>%1</code>) is <i>moved</i> into variable * <code>x</code> (held in register <code>%0</code>). This is safe because * register <code>%1</code> is no longer live at that point. * * @author David J. Pearce * */ public static final class Move extends AbstractUnaryAssignable<Type> { private Move(Type type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.Move(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof Move) { return super.equals(o); } return false; } public String toString() { return "move %" + target + " = %" + operand + " : " + type; } } /** * Represents a block of code which loops continuously until e.g. a * conditional branch is taken out of the block. For example: * * <pre> * int f(): * r = 0 * while r < 10: * r = r + 1 * return r * </pre> * can be translated into the following WYIL code: * <pre> * int f(): * body: * const %0 = 0 : int * loop (%0) * const %1 = 10 : int * ifge %0, %1 goto blklab0 : int * const %1 = 1 : int * add %0 = %0, %1 : int * .blklab0 * return %0 : int * </pre> * * <p> * Here, we see a loop which increments an accumulator register * <code>%0</code> until it reaches <code>10</code>, and then exits the loop * block. * </p> * <p> * The <i>modified operands</i> of a loop bytecode (shown in brackets * alongside the bytecode) indicate those operands which are modified at * some point within the loop. * </p> * * @author David J. Pearce * */ public static class Loop extends Code { public final String target; public final int[] modifiedOperands; private Loop(String target, int[] modifies) { this.target = target; this.modifiedOperands = modifies; } public Loop relabel(Map<String, String> labels) { String nlabel = labels.get(target); if (nlabel == null) { return this; } else { return Loop(nlabel, modifiedOperands); } } @Override public void registers(java.util.Set<Integer> registers) { for (int operand : modifiedOperands) { registers.add(operand); } } @Override public Code remap(Map<Integer, Integer> binding) { int[] nOperands = remap(binding, modifiedOperands); if (nOperands != modifiedOperands) { return Code.Loop(target, nOperands); } else { return this; } } public int hashCode() { return target.hashCode() + Arrays.hashCode(modifiedOperands); } public boolean equals(Object o) { if (o instanceof Loop) { Loop f = (Loop) o; return target.equals(f.target) && Arrays.equals(modifiedOperands, f.modifiedOperands); } return false; } public String toString() { return "loop " + toString(modifiedOperands); } } /** * Pops a set, list or dictionary from the stack and iterates over every * element it contains. A register is identified to hold the current value * being iterated over. * * @author David J. Pearce * */ public static final class ForAll extends Loop { public final int sourceOperand; public final int indexOperand; public final Type.EffectiveCollection type; private ForAll(Type.EffectiveCollection type, int sourceOperand, int indexOperand, int[] modifies, String target) { super(target, modifies); this.type = type; this.sourceOperand = sourceOperand; this.indexOperand = indexOperand; } public ForAll relabel(Map<String, String> labels) { String nlabel = labels.get(target); if (nlabel == null) { return this; } else { return ForAll(type, sourceOperand, indexOperand, modifiedOperands, nlabel); } } @Override public void registers(java.util.Set<Integer> registers) { registers.add(indexOperand); registers.add(sourceOperand); super.registers(registers); } @Override public Code remap(Map<Integer, Integer> binding) { int[] nModifiedOperands = remap(binding, modifiedOperands); Integer nIndexOperand = binding.get(indexOperand); Integer nSourceOperand = binding.get(sourceOperand); if (nSourceOperand != null || nIndexOperand != null || nModifiedOperands != modifiedOperands) { nSourceOperand = nSourceOperand != null ? nSourceOperand : sourceOperand; nIndexOperand = nIndexOperand != null ? nIndexOperand : indexOperand; return Code.ForAll(type, nSourceOperand, nIndexOperand, nModifiedOperands, target); } else { return this; } } public int hashCode() { return super.hashCode() + indexOperand + Arrays.hashCode(modifiedOperands); } public boolean equals(Object o) { if (o instanceof ForAll) { ForAll f = (ForAll) o; return target.equals(f.target) && type.equals(f.type) && indexOperand == f.indexOperand && Arrays.equals(modifiedOperands, f.modifiedOperands); } return false; } public String toString() { return "forall %" + indexOperand + " in %" + sourceOperand + " " + toString(modifiedOperands) + " : " + type; } } /** * Represents a type which may appear on the left of an assignment * expression. Lists, Dictionaries, Strings, Records and References are the * only valid types for an lval. * * @author David J. Pearce * */ public static abstract class LVal { protected Type type; public LVal(Type t) { this.type = t; } public Type rawType() { return type; } } /** * An LVal with dictionary type. * * @author David J. Pearce * */ public static final class DictLVal extends LVal { public final int keyOperand; public DictLVal(Type t, int keyOperand) { super(t); if (!(t instanceof Type.EffectiveDictionary)) { throw new IllegalArgumentException("Invalid Dictionary Type"); } this.keyOperand = keyOperand; } public Type.EffectiveDictionary type() { return (Type.EffectiveDictionary) type; } } /** * An LVal with list type. * * @author David J. Pearce * */ public static final class ListLVal extends LVal { public final int indexOperand; public ListLVal(Type t, int indexOperand) { super(t); if (!(t instanceof Type.EffectiveList)) { throw new IllegalArgumentException("invalid List Type"); } this.indexOperand = indexOperand; } public Type.EffectiveList type() { return (Type.EffectiveList) type; } } /** * An LVal with list type. * * @author David J. Pearce * */ public static final class ReferenceLVal extends LVal { public ReferenceLVal(Type t) { super(t); if (Type.effectiveReference(t) == null) { throw new IllegalArgumentException("invalid reference type"); } } public Type.Reference type() { return Type.effectiveReference(type); } } /** * An LVal with string type. * * @author David J. Pearce * */ public static final class StringLVal extends LVal { public final int indexOperand; public StringLVal(int indexOperand) { super(Type.T_STRING); this.indexOperand = indexOperand; } } /** * An LVal with record type. * * @author David J. Pearce * */ public static final class RecordLVal extends LVal { public final String field; public RecordLVal(Type t, String field) { super(t); this.field = field; if (!(t instanceof Type.EffectiveRecord) || !((Type.EffectiveRecord) t).fields().containsKey(field)) { throw new IllegalArgumentException("Invalid Record Type"); } } public Type.EffectiveRecord type() { return (Type.EffectiveRecord) type; } } private static final class UpdateIterator implements Iterator<LVal> { private final ArrayList<String> fields; private final int[] operands; private Type iter; private int fieldIndex; private int operandIndex; private int index; public UpdateIterator(Type type, int level, int[] operands, ArrayList<String> fields) { this.fields = fields; this.iter = type; this.index = level; this.operands = operands; } public LVal next() { Type raw = iter; index--; if (Type.isSubtype(Type.T_STRING, iter)) { iter = Type.T_CHAR; return new StringLVal(operands[operandIndex++]); } else if (Type.isSubtype(Type.Reference(Type.T_ANY), iter)) { Type.Reference proc = Type.effectiveReference(iter); iter = proc.element(); return new ReferenceLVal(raw); } else if (iter instanceof Type.EffectiveList) { Type.EffectiveList list = (Type.EffectiveList) iter; iter = list.element(); return new ListLVal(raw, operands[operandIndex++]); } else if (iter instanceof Type.EffectiveDictionary) { Type.EffectiveDictionary dict = (Type.EffectiveDictionary) iter; iter = dict.value(); return new DictLVal(raw, operands[operandIndex++]); } else if (iter instanceof Type.EffectiveRecord) { Type.EffectiveRecord rec = (Type.EffectiveRecord) iter; String field = fields.get(fieldIndex++); iter = rec.fields().get(field); return new RecordLVal(raw, field); } else { throw new IllegalArgumentException( "Invalid type for Code.Update"); } } public boolean hasNext() { return index > 0; } public void remove() { throw new UnsupportedOperationException( "UpdateIterator is unmodifiable"); } } /** * <p> * Pops a compound structure, zero or more indices and a value from the * stack and updates the compound structure with the given value. Valid * compound structures are lists, dictionaries, strings, records and * references. * </p> * <p> * Ideally, this operation is done in-place, meaning the operation is * constant time. However, to support Whiley's value semantics this bytecode * may require (in some cases) a clone of the underlying data-structure. * Thus, the worst-case runtime of this operation is linear in the size of * the compound structure. * </p> * * @author David J. Pearce * */ public static final class Update extends AbstractSplitNaryAssignable<Type> implements Iterable<LVal> { public final Type afterType; public final ArrayList<String> fields; private Update(Type beforeType, int target, int operand, int[] operands, Type afterType, Collection<String> fields) { super(beforeType, target, operand, operands); if (fields == null) { throw new IllegalArgumentException( "FieldStore fields argument cannot be null"); } this.afterType = afterType; this.fields = new ArrayList<String>(fields); } public int level() { int base = 0; if (type instanceof Type.Reference) { base++; } return base + fields.size() + operands.length; } public Iterator<LVal> iterator() { return new UpdateIterator(afterType, level(), operands, fields); } /** * Extract the type for the right-hand side of this assignment. * * @return */ public Type rhs() { Type iter = afterType; int fieldIndex = 0; for (int i = 0; i != level(); ++i) { if (Type.isSubtype(Type.T_STRING, iter)) { iter = Type.T_CHAR; } else if (Type.isSubtype(Type.Reference(Type.T_ANY), iter)) { Type.Reference proc = Type.effectiveReference(iter); iter = proc.element(); } else if (iter instanceof Type.EffectiveList) { Type.EffectiveList list = (Type.EffectiveList) iter; iter = list.element(); } else if (iter instanceof Type.EffectiveDictionary) { Type.EffectiveDictionary dict = (Type.EffectiveDictionary) iter; iter = dict.value(); } else if (iter instanceof Type.EffectiveRecord) { Type.EffectiveRecord rec = (Type.EffectiveRecord) iter; String field = fields.get(fieldIndex++); iter = rec.fields().get(field); } else { throw new IllegalArgumentException( "Invalid type for Code.Update"); } } return iter; } @Override public final Code clone(int nTarget, int nOperand, int[] nOperands) { return Code.Update(type, nTarget, nOperand, nOperands, afterType, fields); } public boolean equals(Object o) { if (o instanceof Update) { Update i = (Update) o; return super.equals(o) && afterType.equals(i.afterType) && fields.equals(i.fields); } return false; } public String toString() { String r = "%" + target; for (LVal lv : this) { if (lv instanceof ListLVal) { ListLVal l = (ListLVal) lv; r = r + "[%" + l.indexOperand + "]"; } else if (lv instanceof StringLVal) { StringLVal l = (StringLVal) lv; r = r + "[%" + l.indexOperand + "]"; } else if (lv instanceof DictLVal) { DictLVal l = (DictLVal) lv; r = r + "[%" + l.keyOperand + "]"; } else if (lv instanceof RecordLVal) { RecordLVal l = (RecordLVal) lv; r = r + "." + l.field; } else { ReferenceLVal l = (ReferenceLVal) lv; r = "(*" + r + ")"; } } return "update " + r + " %" + operand + " : " + type + " -> " + afterType; } } /** * Constructs a dictionary value from zero or more key-value pairs on the * stack. For each pair, the key must occur directly before the value on the * stack. For example, consider the following Whiley function * <code>f()</code>: * * <pre> * {int=>string} f(): * return {1=>"Hello",2=>"World"} * </pre> * * This could be compiled into the following WYIL code using this bytecode: * * <pre> * {int->string} f(): * body: * const %1 = 1 : int * const %2 = "Hello" : string * const %3 = 2 : int * const %4 = "World" : string * newmap %0 = (%1, %2, %3, %4) : {int=>string} * return %0 : {int=>string} * </pre> * * * @author David J. Pearce * */ public static final class NewMap extends AbstractNaryAssignable<Type.Dictionary> { private NewMap(Type.Dictionary type, int target, int[] operands) { super(type, target, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.NewMap(type, nTarget, nOperands); } public boolean equals(Object o) { if (o instanceof NewMap) { return super.equals(o); } return false; } public String toString() { return "newmap %" + target + " " + toString(operands) + " : " + type; } } /** * Constructs a new record value from the values of zero or more operand * register, each of which is associated with a field name. The new record * value is then written into the target register. For example, the * following Whiley code: * * <pre> * define Point as {real x, real y} * * Point f(real x, real y): * return {x: x, y: x} * </pre> * * can be translated into the following WYIL: * * <pre> * {real x,real y} f(real x, real y): * body: * assign %3 = %0 : real * assign %4 = %0 : real * newrecord %2 (%3, %4) : {real x,real y} * return %2 : {real x,real y} * </pre> * * @author David J. Pearce * */ public static final class NewRecord extends AbstractNaryAssignable<Type.Record> { private NewRecord(Type.Record type, int target, int[] operands) { super(type, target, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.NewRecord(type, nTarget, nOperands); } public boolean equals(Object o) { if (o instanceof NewRecord) { return super.equals(o); } return false; } public String toString() { return "newrecord %" + target + " " + toString(operands) + " : " + type; } } /** * Constructs a new tuple value from the values given by zero or more * operand registers. The new tuple is then written into the target * register. For example, the following Whiley code: * * <pre> * (int,int) f(int x, int y): * return x,y * </pre> * * can be translated into the following WYIL code: * * <pre> * (int,int) f(int x, int y): * body: * assign %3 = %0 : int * assign %4 = %1 : int * newtuple %2 = (%3, %4) : (int,int) * return %2 : (int,int) * </pre> * * This writes the tuple value generated from <code>(x,y)</code> into * register <code>%2</code> and returns it. * * @author David J. Pearce * */ public static final class NewTuple extends AbstractNaryAssignable<Type.Tuple> { private NewTuple(Type.Tuple type, int target, int[] operands) { super(type, target, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.NewTuple(type, nTarget, nOperands); } public boolean equals(Object o) { if (o instanceof NewTuple) { return super.equals(o); } return false; } public String toString() { return "newtuple %" + target + " = " + toString(operands) + " : " + type; } } /** * Constructs a new set value from the values given by zero or more operand * registers. The new set is then written into the target register. For * example, the following Whiley code: * * <pre> * {int} f(int x, int y, int z): * return {x,y,z} * </pre> * * can be translated into the following WYIL code: * * <pre> * [int] f(int x, int y, int z): * body: * assign %4 = %0 : int * assign %5 = %1 : int * assign %6 = %2 : int * newset %3 = (%4, %5, %6) : [int] * return %3 : [int] * </pre> * * Writes the set value given by <code>{x,y,z}</code> into register * <code>%3</code> and returns it. * * @author David J. Pearce * */ public static final class NewSet extends AbstractNaryAssignable<Type.Set> { private NewSet(Type.Set type, int target, int[] operands) { super(type, target, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.NewSet(type, nTarget, nOperands); } public boolean equals(Object o) { if (o instanceof NewSet) { return super.equals(o); } return false; } public String toString() { return "newset %" + target + " = " + toString(operands) + " : " + type; } } /** * Constructs a new list value from the values given by zero or more operand * registers. The new list is then written into the target register. For * example, the following Whiley code: * * <pre> * [int] f(int x, int y, int z): * return [x,y,z] * </pre> * * can be translated into the following WYIL code: * * <pre> * [int] f(int x, int y, int z): * body: * assign %4 = %0 : int * assign %5 = %1 : int * assign %6 = %2 : int * newlist %3 = (%4, %5, %6) : [int] * return %3 : [int] * </pre> * * Writes the list value given by <code>[x,y,z]</code> into register * <code>%3</code> and returns it. * * @author David J. Pearce * */ public static final class NewList extends AbstractNaryAssignable<Type.List> { private NewList(Type.List type, int target, int[] operands) { super(type, target, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.NewList(type, nTarget, nOperands); } public boolean equals(Object o) { if (o instanceof NewList) { return super.equals(operands); } return false; } public String toString() { return "newlist %" + target + " = " + toString(operands) + " : " + type; } } /** * Represents a no-operation bytecode which, as the name suggests, does * nothing. * * @author David J. Pearce * */ public static final class Nop extends Code { private Nop() { } public String toString() { return "nop"; } } /** * Returns from the enclosing function or method, possibly returning a * value. For example, the following Whiley code: * * <pre> * int f(int x, int y): * return x + y * </pre> * * can be translated into the following WYIL: * * <pre> * int f(int x, int y): * body: * assign %3 = %0 : int * assign %4 = %1 : int * add %2 = % 3, %4 : int * return %2 : int * </pre> * * Here, the * <code>return<code> bytecode returns the value of its operand register. * * @author David J. Pearce * */ public static final class Return extends AbstractUnaryOp<Type> { private Return(Type type, int operand) { super(type, operand); if (type == Type.T_VOID && operand != NULL_REG) { throw new IllegalArgumentException( "Return with void type cannot have target register."); } else if (type != Type.T_VOID && operand == NULL_REG) { throw new IllegalArgumentException( "Return with non-void type must have target register."); } } public Code clone(int nOperand) { return new Return(type, nOperand); } public boolean equals(Object o) { if (o instanceof Return) { return super.equals(o); } return false; } public String toString() { if (operand != Code.NULL_REG) { return "return %" + operand + " : " + type; } else { return "return"; } } } public enum SetOperation { LEFT_UNION { public String toString() { return "lunion"; } }, RIGHT_UNION { public String toString() { return "runion"; } }, UNION { public String toString() { return "union"; } }, LEFT_INTERSECTION { public String toString() { return "lintersect"; } }, RIGHT_INTERSECTION { public String toString() { return "rintersect"; } }, INTERSECTION { public String toString() { return "intersect"; } }, LEFT_DIFFERENCE { public String toString() { return "ldiff"; } }, DIFFERENCE { public String toString() { return "diff"; } } } public static final class SetOp extends AbstractBinaryAssignable<Type.EffectiveSet> { public final SetOperation operation; private SetOp(Type.EffectiveSet type, int target, int leftOperand, int rightOperand, SetOperation operation) { super(type, target, leftOperand, rightOperand); if (operation == null) { throw new IllegalArgumentException( "SetOp operation cannot be null"); } this.operation = operation; } protected Code clone(int nTarget, int nLeftOperand, int nRightOperand) { return Code.SetOp(type, nTarget, nLeftOperand, nRightOperand, operation); } public int hashCode() { return operation.hashCode() + super.hashCode(); } public boolean equals(Object o) { if (o instanceof SetOp) { SetOp setop = (SetOp) o; return operation.equals(setop.operation) && super.equals(o); } return false; } public String toString() { return operation + " %" + target + " = %" + leftOperand + ", %" + rightOperand + " : " + type; } } public enum StringOperation { LEFT_APPEND { public String toString() { return "strappend_l"; } }, RIGHT_APPEND { public String toString() { return "strappend_r"; } }, APPEND { public String toString() { return "strappend"; } } } public static final class StringOp extends AbstractBinaryAssignable<Type.Strung> { public final StringOperation operation; private StringOp(int target, int leftOperand, int rightOperand, StringOperation operation) { super(Type.T_STRING, target, leftOperand, rightOperand); if (operation == null) { throw new IllegalArgumentException( "StringBinOp operation cannot be null"); } this.operation = operation; } protected Code clone(int nTarget, int nLeftOperand, int nRightOperand) { return Code.StringOp(nTarget, nLeftOperand, nRightOperand, operation); } public boolean equals(Object o) { if (o instanceof StringOp) { StringOp setop = (StringOp) o; return operation.equals(setop.operation) && super.equals(o); } return false; } public String toString() { return operation + " %" + target + " = %" + leftOperand + ", %" + rightOperand + " : " + type; } } /** * Reads the string value from a source operand register, and the integer * values from two index operand registers, computes the substring and * writes the result back to a target register. * * @author David J. Pearce * */ public static final class SubString extends AbstractNaryAssignable { private SubString(int target, int[] operands) { super(Type.T_STRING, target, operands); } @Override public final Code clone(int nTarget, int[] nOperands) { return Code.SubString(nTarget, nOperands); } public boolean equals(Object o) { return o instanceof SubString && super.equals(o); } public String toString() { return "substr %" + target + " = %" + operands[0] + ", %" + operands[1] + ", %" + operands[2] + " : " + type; } } /** * Performs a multi-way branch based on the value contained in the operand * register. A <i>dispatch table</i> is provided which maps individual * matched values to their destination labels. For example, the following * Whiley code: * * <pre> * string f(int x): * switch x: * case 1: * return "ONE" * case 2: * return "TWO" * default: * return "OTHER" * </pre> * * can be translated into the following WYIL code: * * <pre> * string f(int x): * body: * switch %0 1->blklab1, 2->blklab2, *->blklab3 * .blklab1 * const %1 = "ONE" : string * return %1 : string * .blklab2 * const %1 = "TWO" : string * return %1 : string * .blklab3 * const %1 = "OTHER" : string * return %1 : string * </pre> * * Here, we see how e.g. value <code>1</code> is mapped to the label * <code>blklab1</code>. Thus, if the operand register <code>%0</code> * contains value <code>1</code>, then control will be transferred to that * label. The final mapping <code>*->blklab3</code> covers the default case * where the value in the operand is not otherwise matched. * * @author David J. Pearce * */ public static final class Switch extends Code { public final Type type; public final int operand; public final ArrayList<Pair<Value, String>> branches; public final String defaultTarget; Switch(Type type, int operand, String defaultTarget, Collection<Pair<Value, String>> branches) { this.type = type; this.operand = operand; this.branches = new ArrayList<Pair<Value, String>>(branches); this.defaultTarget = defaultTarget; } public Switch relabel(Map<String, String> labels) { ArrayList<Pair<Value, String>> nbranches = new ArrayList(); for (Pair<Value, String> p : branches) { String nlabel = labels.get(p.second()); if (nlabel == null) { nbranches.add(p); } else { nbranches.add(new Pair(p.first(), nlabel)); } } String nlabel = labels.get(defaultTarget); if (nlabel == null) { return Code.Switch(type, operand, defaultTarget, nbranches); } else { return Code.Switch(type, operand, nlabel, nbranches); } } public int hashCode() { return type.hashCode() + operand + defaultTarget.hashCode() + branches.hashCode(); } public boolean equals(Object o) { if (o instanceof Switch) { Switch ig = (Switch) o; return operand == ig.operand && defaultTarget.equals(ig.defaultTarget) && branches.equals(ig.branches) && type.equals(ig.type); } return false; } public String toString() { String table = ""; boolean firstTime = true; for (Pair<Value, String> p : branches) { if (!firstTime) { table += ", "; } firstTime = false; table += p.first() + "->" + p.second(); } table += ", *->" + defaultTarget; return "switch %" + operand + " " + table; } @Override public void registers(java.util.Set<Integer> registers) { registers.add(operand); } @Override public Code remap(Map<Integer, Integer> binding) { Integer nOperand = binding.get(operand); if (nOperand != null) { return new Return(type, nOperand); } return this; } } public static final class Send extends AbstractNaryAssignable<Type.Message> { public final boolean synchronous; public final NameID name; private Send(Type.Message type, int target, int[] operands, NameID name, boolean synchronous) { super(type, target, operands); this.name = name; this.synchronous = synchronous; } @Override public Code clone(int nTarget, int[] nOperands) { return Send(type, nTarget, nOperands, name, synchronous); } public boolean equals(Object o) { if (o instanceof Send) { Send i = (Send) o; return synchronous == i.synchronous && type.equals(i.type) && name.equals(i.name) && super.equals(o); } return false; } public String toString() { if (synchronous) { if (target != Code.NULL_REG) { return "send " + target + " " + toString(operands) + " : " + type; } else { return "vsend" + toString(operands) + " : " + type; } } else { return "asend" + toString(operands) + " : " + type; } } } /** * Throws an exception containing the value in the given operand register. * For example, the following Whiley Code: * * <pre> * int f(int x) throws string: * if x < 0: * throw "ERROR" * else: * return 1 * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int x) throws string: * body: * const %1 = 0 : int * ifge %0, %1 goto blklab0 : int * const %1 = "ERROR" : string * throw %1 : string * .blklab0 * const %1 = 1 : int * return %1 : int * </pre> * * Here, we see an exception containing a <code>string</code> value will be * thrown when the parameter <code>x</code> is negative. * * @author David J. Pearce * */ public static final class Throw extends AbstractUnaryOp<Type> { private Throw(Type type, int operand) { super(type, operand); } @Override public Code clone(int nOperand) { return Code.Throw(type, nOperand); } public boolean equals(Object o) { if (o instanceof Throw) { return super.equals(o); } return false; } public String toString() { return "throw %" + operand + " : " + type; } } /** * Represents a try-catch block within which specified exceptions will * caught and processed within a handler. For example, the following Whiley * code: * * <pre> * int f(int x) throws Error: * ... * * int g(int x): * try: * x = f(x) * catch(Error e): * return 0 * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int x): * body: * ... * * int g(int x): * body: * trycatch Error -> lab2 * assign %3 = %0 : int * invoke %0 = (%3) test:f : int(int) throws {string msg} * return * .lab2 * const %3 = 0 : int * return %3 : int * </pre> * * Here, we see that within the try-catch block control is transferred to * <code>lab2</code> if an exception of type <code>Error</code> is thrown. * * @author David J. Pearce * */ public static final class TryCatch extends Code { public final int operand; public final String label; public final ArrayList<Pair<Type, String>> catches; TryCatch(int operand, String label, Collection<Pair<Type, String>> catches) { this.operand = operand; this.catches = new ArrayList<Pair<Type, String>>(catches); this.label = label; } @Override public void registers(java.util.Set<Integer> registers) { registers.add(operand); } @Override public Code remap(Map<Integer, Integer> binding) { Integer nOperand = binding.get(operand); if (nOperand != null) { return Code.TryCatch(nOperand, label, catches); } return this; } public TryCatch relabel(Map<String, String> labels) { ArrayList<Pair<Type, String>> nbranches = new ArrayList(); for (Pair<Type, String> p : catches) { String nlabel = labels.get(p.second()); if (nlabel == null) { nbranches.add(p); } else { nbranches.add(new Pair(p.first(), nlabel)); } } String ntarget = labels.get(label); if (ntarget != null) { return TryCatch(operand, ntarget, nbranches); } else { return TryCatch(operand, label, nbranches); } } public int hashCode() { return operand + label.hashCode() + catches.hashCode(); } public boolean equals(Object o) { if (o instanceof TryCatch) { TryCatch ig = (TryCatch) o; return operand == ig.operand && label.equals(ig.label) && catches.equals(ig.catches); } return false; } public String toString() { String table = ""; boolean firstTime = true; for (Pair<Type, String> p : catches) { if (!firstTime) { table += ", "; } firstTime = false; table += p.first() + "->" + p.second(); } return "trycatch " + table; } } /** * Marks the end of a try-catch block. * * @author David J. Pearce * */ public static final class TryEnd extends Label { TryEnd(String label) { super(label); } public TryEnd relabel(Map<String, String> labels) { String nlabel = labels.get(label); if (nlabel == null) { return this; } else { return TryEnd(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if (o instanceof TryEnd) { TryEnd e = (TryEnd) o; return e.label.equals(label); } return false; } public String toString() { return "tryend " + label; } } /** * Read a number (int or real) from the operand register, negates it and * writes the result to the target register. For example, the following * Whiley code: * * <pre> * int f(int x): * return -x * </pre> * * can be translated into the following WYIL: * * <pre> * int f(int x): * body: * neg %0 = %0 : int * return %0 : int * </pre> * * This simply reads the parameter <code>x</code> stored in register * <code>%0</code>, negates it and then returns the negated value. * * @author David J. Pearce * */ public static final class Neg extends AbstractUnaryAssignable<Type> { private Neg(Type type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.Neg(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof Neg) { return super.equals(o); } return false; } public String toString() { return "neg %" + target + " = %" + operand + " : " + type; } } /** * Corresponds to a bitwise inversion operation, which reads a byte value * from the operand register, inverts it and writes the result to the target * resgister. For example, the following Whiley code: * * <pre> * byte f(byte x): * return ~x * </pre> * * can be translated into the following WYIL code: * * <pre> * byte f(byte x): * body: * invert %0 = %0 : byte * return %0 : byte * </pre> * * Here, the expression <code>~x</code> generates an <code>invert</code> * bytecode. * * @author David J. Pearce * */ public static final class Invert extends AbstractUnaryAssignable<Type> { private Invert(Type type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.Invert(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof Invert) { return super.equals(o); } return false; } public String toString() { return "invert %" + target + " = %" + operand + " : " + type; } } /** * Instantiate a new object from the value in a given operand register, and * write the result (a reference to that object) to a given target register. * For example, the following Whiley code: * * <pre> * define PointObj as ref {real x, real y} * * PointObj f(real x, real y): * return new {x: x, y: y} * </pre> * * can be translated into the following WYIL code: * * <pre> * ref {real x,real y} f(int x, int y): * body: * newrecord %2 = (%0, %1) : {real x,real y} * newobject %2 = %2 : ref {real x,real y} * return %2 : ref {real x,real y} * </pre> * * <b>NOTE:</b> objects are unlike other data types in WYIL, in that they * represent mutable state allocated on a heap. Thus, changes to an object * within a method are visible to those outside of the method. * * @author David J. Pearce * */ public static final class NewObject extends AbstractUnaryAssignable<Type.Reference> { private NewObject(Type.Reference type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.NewObject(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof NewObject) { return super.equals(o); } return false; } public String toString() { return "newobject %" + target + " = %" + operand + " : " + type; } } /** * Read a tuple value from the operand register, extract the value it * contains at a given index and write that to the target register. For * example, the following Whiley code: * * <pre> * int f(int,int tup): * return tup[0] * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int,int tup): * body: * tupleload %0 = %0 0 : int,int * return %0 : int * </pre> * * This simply reads the parameter <code>x</code> stored in register * <code>%0</code>, and returns the value stored at index <code>0</code>. * * @author David J. Pearce * */ public static final class TupleLoad extends AbstractUnaryAssignable<Type.EffectiveTuple> { public final int index; private TupleLoad(Type.EffectiveTuple type, int target, int operand, int index) { super(type, target, operand); this.index = index; } protected Code clone(int nTarget, int nOperand) { return Code.TupleLoad(type, nTarget, nOperand, index); } public boolean equals(Object o) { if (o instanceof TupleLoad) { TupleLoad i = (TupleLoad) o; return index == i.index && super.equals(o); } return false; } public String toString() { return "tupleload %" + target + " = %" + operand + " " + index + " : " + type; } } /** * Reads a reference value from the operand register, dereferences it (i.e. * extracts the value it refers to) and writes this to the target register. * * @author David J. Pearce * */ public static final class Dereference extends AbstractUnaryAssignable<Type.Reference> { private Dereference(Type.Reference type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.Dereference(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof Dereference) { return super.equals(o); } return false; } public String toString() { return "deref %" + target + " = %" + operand + " : " + type; } } /** * The void bytecode is used to indicate that the given register(s) are no * longer live. This is useful for communicating information to the memory * management system about which values could in principle be collected. * * @author David J. Pearce * */ public static class Void extends AbstractNaryAssignable<Type> { private Void(Type type, int[] operands) { super(type, NULL_REG, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.Void(type, nOperands); } public boolean equals(Object o) { if (o instanceof Void) { return super.equals(o); } return false; } public String toString() { return "void " + toString(operands); } } private static String toString(int... operands) { String r = "("; for (int i = 0; i != operands.length; ++i) { if (i != 0) { r = r + ", "; } r = r + "%" + operands[i]; } return r + ")"; } private static int[] toIntArray(Collection<Integer> operands) { int[] ops = new int[operands.size()]; int i = 0; for (Integer o : operands) { ops[i++] = o; } return ops; } private static int[] remap(Map<Integer, Integer> binding, int[] operands) { int[] nOperands = operands; for (int i = 0; i != nOperands.length; ++i) { int o = operands[i]; Integer nOperand = binding.get(o); if (nOperand != null) { if (nOperands == operands) { nOperands = Arrays.copyOf(operands, operands.length); } nOperands[i] = nOperand; } } return nOperands; } private static final ArrayList<Code> values = new ArrayList<Code>(); private static final HashMap<Code, Integer> cache = new HashMap<Code, Integer>(); private static <T extends Code> T get(T type) { Integer idx = cache.get(type); if (idx != null) { return (T) values.get(idx); } else { cache.put(type, values.size()); values.add(type); return type; } } }
src/wyil/lang/Code.java
// Copyright (c) 2011, David J. Pearce (David J. [email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the <organization> nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL DAVID J. PEARCE BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package wyil.lang; import java.util.*; import wyil.util.*; /** * Represents a WYIL bytecode. The Whiley Intermediate Language (WYIL) employs * register-based bytecodes (as opposed to say the Java Virtual Machine, which * uses stack-based bytecodes). During execution, one can think of the "machine" * as maintaining a call stack made up of "frames". For each function or method * on the call stack, the corresponding frame consists of zero or more <i>local * variables</i> (a.k.a registers). Bytecodes may read/write values from local * variables. Like the Java Virtual Machine, WYIL uses unstructured * control-flow. However, unlike the JVM, it also allows variables to take on * different types at different points. The following illustrates: * * <pre> * int sum([int] data): * r = 0 * for item in data: * r = r + item * return r * </pre> * * This function is compiled into the following WYIL bytecode: * * <pre> * int sum([int] data): * body: * var r, $2, item * const %1 = 0 // int * assign %2 = %0 // [int] * forall %3 in %2 () // [int] * assign %4 = %1 // int * add %1 = %4, %3 // int * return %1 // int * </pre> * * Here, we can see that every bytecode is associated with one (or more) types. * These types are inferred by the compiler during type propagation. * * @author David J. Pearce */ public abstract class Code { /** * Provided to aid readability of client code. */ public final static int NULL_REG = -1; /** * Provided to aid readability of client code. */ public final static int REG_0 = 0; /** * Provided to aid readability of client code. */ public final static int REG_1 = 1; /** * Provided to aid readability of client code. */ public final static int REG_2 = 2; /** * Provided to aid readability of client code. */ public final static int REG_3 = 3; /** * Provided to aid readability of client code. */ public final static int REG_4 = 4; /** * Provided to aid readability of client code. */ public final static int REG_5 = 5; /** * Provided to aid readability of client code. */ public final static int REG_6 = 6; /** * Provided to aid readability of client code. */ public final static int REG_7 = 7; /** * Provided to aid readability of client code. */ public final static int REG_8 = 8; /** * Provided to aid readability of client code. */ public final static int REG_9 = 9; // =============================================================== // Bytecode Constructors // =============================================================== /** * Construct an <code>assert</code> bytecode which raises an assertion * failure with the given if the given condition evaluates to false. * * @param message * --- message to report upon failure. * @return */ public static Assert Assert(Type type, int leftOperand, int rightOperand, Comparator cop, String message) { return get(new Assert(type, leftOperand, rightOperand, cop, message)); } /** * Construct an <code>assumet</code> bytecode which raises an assertion * failure with the given if the given condition evaluates to false. * * @param message * --- message to report upon failure. * @return */ public static Assume Assume(Type type, int leftOperand, int rightOperand, Comparator cop, String message) { return get(new Assume(type, leftOperand, rightOperand, cop, message)); } public static ArithOp ArithOp(Type type, int target, int leftOperand, int rightOperand, ArithOperation op) { return get(new ArithOp(type, target, leftOperand, rightOperand, op)); } /** * Construct a <code>const</code> bytecode which loads a given constant onto * the stack. * * @param afterType * --- record type. * @param field * --- field to write. * @return */ public static Const Const(int target, Value constant) { return get(new Const(target, constant)); } /** * Construct a <code>copy</code> bytecode which copies the value from a * given operand register into a given target register. * * @param type * --- record type. * @param reg * --- reg to load. * @return */ public static Assign Assign(Type type, int target, int operand) { return get(new Assign(type, target, operand)); } public static Convert Convert(Type from, int target, int operand, Type to) { return get(new Convert(from, target, operand, to)); } public static final Debug Debug(int operand) { return get(new Debug(operand)); } public static LoopEnd End(String label) { return get(new LoopEnd(label)); } /** * Construct a <code>fieldload</code> bytecode which reads a given field * from a record of a given type. * * @param type * --- record type. * @param field * --- field to load. * @return */ public static FieldLoad FieldLoad(Type.EffectiveRecord type, int target, int operand, String field) { return get(new FieldLoad(type, target, operand, field)); } /** * Construct a <code>goto</code> bytecode which branches unconditionally to * a given label. * * @param label * --- destination label. * @return */ public static Goto Goto(String label) { return get(new Goto(label)); } public static Invoke Invoke(Type.FunctionOrMethod fun, int target, Collection<Integer> operands, NameID name) { return get(new Invoke(fun, target, toIntArray(operands), name)); } public static Invoke Invoke(Type.FunctionOrMethod fun, int target, int[] operands, NameID name) { return get(new Invoke(fun, target, operands, name)); } public static Not Not(int target, int operand) { return get(new Not(target, operand)); } public static LengthOf LengthOf(Type.EffectiveCollection type, int target, int operand) { return get(new LengthOf(type, target, operand)); } public static Move Move(Type type, int target, int operand) { return get(new Move(type, target, operand)); } public static SubList SubList(Type.EffectiveList type, int target, int sourceOperand, int leftOperand, int rightOperand) { int[] operands = new int[] { sourceOperand, leftOperand, rightOperand }; return get(new SubList(type, target, operands)); } private static SubList SubList(Type.EffectiveList type, int target, int[] operands) { return get(new SubList(type, target, operands)); } public static ListOp ListOp(Type.EffectiveList type, int target, int leftOperand, int rightOperand, ListOperation dir) { return get(new ListOp(type, target, leftOperand, rightOperand, dir)); } /** * Construct a <code>listload</code> bytecode which reads a value from a * given index in a given list. * * @param type * --- list type. * @return */ public static IndexOf IndexOf(Type.EffectiveMap type, int target, int leftOperand, int rightOperand) { return get(new IndexOf(type, target, leftOperand, rightOperand)); } public static Loop Loop(String label, Collection<Integer> operands) { return get(new Loop(label, toIntArray(operands))); } public static Loop Loop(String label, int[] modifies) { return get(new Loop(label, modifies)); } public static ForAll ForAll(Type.EffectiveCollection type, int sourceOperand, int indexOperand, Collection<Integer> modifiedOperands, String label) { return get(new ForAll(type, sourceOperand, indexOperand, toIntArray(modifiedOperands), label)); } public static ForAll ForAll(Type.EffectiveCollection type, int sourceOperand, int indexOperand, int[] modifiedOperands, String label) { return get(new ForAll(type, sourceOperand, indexOperand, modifiedOperands, label)); } /** * Construct a <code>newdict</code> bytecode which constructs a new * dictionary and puts it on the stack. * * @param type * @return */ public static NewMap NewMap(Type.Dictionary type, int target, Collection<Integer> operands) { return get(new NewMap(type, target, toIntArray(operands))); } public static NewMap NewMap(Type.Dictionary type, int target, int[] operands) { return get(new NewMap(type, target, operands)); } /** * Construct a <code>newset</code> bytecode which constructs a new set and * puts it on the stack. * * @param type * @return */ public static NewSet NewSet(Type.Set type, int target, Collection<Integer> operands) { return get(new NewSet(type, target, toIntArray(operands))); } public static NewSet NewSet(Type.Set type, int target, int[] operands) { return get(new NewSet(type, target, operands)); } /** * Construct a <code>newlist</code> bytecode which constructs a new list and * puts it on the stack. * * @param type * @return */ public static NewList NewList(Type.List type, int target, Collection<Integer> operands) { return get(new NewList(type, target, toIntArray(operands))); } public static NewList NewList(Type.List type, int target, int[] operands) { return get(new NewList(type, target, operands)); } /** * Construct a <code>newtuple</code> bytecode which constructs a new tuple * and puts it on the stack. * * @param type * @return */ public static NewTuple NewTuple(Type.Tuple type, int target, Collection<Integer> operands) { return get(new NewTuple(type, target, toIntArray(operands))); } public static NewTuple NewTuple(Type.Tuple type, int target, int[] operands) { return get(new NewTuple(type, target, operands)); } /** * Construct a <code>newrecord</code> bytecode which constructs a new record * and puts it on the stack. * * @param type * @return */ public static NewRecord NewRecord(Type.Record type, int target, Collection<Integer> operands) { return get(new NewRecord(type, target, toIntArray(operands))); } public static NewRecord NewRecord(Type.Record type, int target, int[] operands) { return get(new NewRecord(type, target, operands)); } /** * Construct a return bytecode which does return a value and, hence, its * type automatically defaults to void. * * @return */ public static Return Return() { return get(new Return(Type.T_VOID, NULL_REG)); } /** * Construct a return bytecode which reads a value from the operand register * and returns it. * * @param type * --- type of the value to be returned (cannot be void). * @param operand * --- register to read return value from. * @return */ public static Return Return(Type type, int operand) { return get(new Return(type, operand)); } public static If If(Type type, int leftOperand, int rightOperand, Comparator cop, String label) { return get(new If(type, leftOperand, rightOperand, cop, label)); } public static IfIs IfIs(Type type, int leftOperand, Type rightOperand, String label) { return get(new IfIs(type, leftOperand, rightOperand, label)); } public static IndirectSend IndirectSend(Type.Message msg, int target, int operand, Collection<Integer> operands, boolean synchronous) { return get(new IndirectSend(msg, synchronous, target, operand, toIntArray(operands))); } public static IndirectSend IndirectSend(Type.Message msg, int target, int operand, int[] operands, boolean synchronous) { return get(new IndirectSend(msg, synchronous, target, operand, operands)); } public static IndirectInvoke IndirectInvoke(Type.FunctionOrMethod fun, int target, int operand, Collection<Integer> operands) { return get(new IndirectInvoke(fun, target, operand, toIntArray(operands))); } public static IndirectInvoke IndirectInvoke(Type.FunctionOrMethod fun, int target, int operand, int[] operands) { return get(new IndirectInvoke(fun, target, operand, operands)); } public static Invert Invert(Type type, int target, int operand) { return get(new Invert(type, target, operand)); } public static Label Label(String label) { return get(new Label(label)); } public static final Nop Nop = new Nop(); public static SetOp SetOp(Type.EffectiveSet type, int target, int leftOperand, int rightOperand, SetOperation operation) { return get(new SetOp(type, target, leftOperand, rightOperand, operation)); } public static StringOp StringOp(int target, int leftOperand, int rightOperand, StringOperation operation) { return get(new StringOp(target, leftOperand, rightOperand, operation)); } public static SubString SubString(int target, int sourceOperand, int leftOperand, int rightOperand) { int[] operands = new int[] { sourceOperand, leftOperand, rightOperand }; return get(new SubString(target, operands)); } private static SubString SubString(int target, int[] operands) { return get(new SubString(target, operands)); } /** * Construct an <code>send</code> bytecode which sends a message to an * actor. This may be either synchronous or asynchronous. * * @param label * --- destination label. * @return */ public static Send Send(Type.Message meth, int target, Collection<Integer> operands, NameID name, boolean synchronous) { return get(new Send(meth, target, toIntArray(operands), name, synchronous)); } public static Send Send(Type.Message meth, int target, int[] operands, NameID name, boolean synchronous) { return get(new Send(meth, target, operands, name, synchronous)); } /** * Construct a <code>switch</code> bytecode which pops a value off the * stack, and switches to a given label based on it. * * @param type * --- value type to switch on. * @param defaultLabel * --- target for the default case. * @param cases * --- map from values to destination labels. * @return */ public static Switch Switch(Type type, int operand, String defaultLabel, Collection<Pair<Value, String>> cases) { return get(new Switch(type, operand, defaultLabel, cases)); } /** * Construct a <code>throw</code> bytecode which pops a value off the stack * and throws it. * * @param afterType * --- value type to throw * @return */ public static Throw Throw(Type type, int operand) { return get(new Throw(type, operand)); } /** * Construct a <code>trycatch</code> bytecode which defines a region of * bytecodes which are covered by one or more catch handles. * * @param target * --- identifies end-of-block label. * @param catches * --- map from types to destination labels. * @return */ public static TryCatch TryCatch(int operand, String target, Collection<Pair<Type, String>> catches) { return get(new TryCatch(operand, target, catches)); } public static TryEnd TryEnd(String label) { return get(new TryEnd(label)); } /** * Construct a <code>tupleload</code> bytecode which reads the value at a * given index in a tuple * * @param type * --- dictionary type. * @return */ public static TupleLoad TupleLoad(Type.EffectiveTuple type, int target, int operand, int index) { return get(new TupleLoad(type, target, operand, index)); } public static Neg Neg(Type type, int target, int operand) { return get(new Neg(type, target, operand)); } public static NewObject NewObject(Type.Reference type, int target, int operand) { return get(new NewObject(type, target, operand)); } public static Dereference Dereference(Type.Reference type, int target, int operand) { return get(new Dereference(type, target, operand)); } /** * Construct a <code>update</code> bytecode which writes a value into a * compound structure, as determined by a given access path. * * @param afterType * --- record type. * @param field * --- field to write. * @return */ public static Update Update(Type beforeType, int target, int operand, Collection<Integer> operands, Type afterType, Collection<String> fields) { return get(new Update(beforeType, target, operand, toIntArray(operands), afterType, fields)); } public static Update Update(Type beforeType, int target, int operand, int[] operands, Type afterType, Collection<String> fields) { return get(new Update(beforeType, target, operand, operands, afterType, fields)); } public static Void Void(Type type, int[] operands) { return get(new Void(type, operands)); } // =============================================================== // Abstract Methods // =============================================================== /** * Determine which registers are used in this bytecode. This can be used, * for example, to determine the size of the register file required for a * given method. * * @param register */ public void registers(java.util.Set<Integer> register) { // default implementation does nothing } /** * Remaps all registers according to a given binding. Registers not * mentioned in the binding retain their original value. * * @param binding * --- map from (existing) registers to (new) registers. * @return */ public Code remap(Map<Integer, Integer> binding) { return this; } /** * Relabel all labels according to the given map. * * @param labels * @return */ public Code relabel(Map<String, String> labels) { return this; } // =============================================================== // Abstract Bytecodes // =============================================================== public static abstract class AbstractAssignable extends Code { public final int target; private AbstractAssignable(int target) { this.target = target; } } /** * Represents the set of bytcodes which take a single register operand and * write a result to the target register. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractUnaryAssignable<T> extends AbstractAssignable { public final T type; public final int operand; private AbstractUnaryAssignable(T type, int target, int operand) { super(target); if (type == null) { throw new IllegalArgumentException( "AbstractUnOp type argument cannot be null"); } this.type = type; this.operand = operand; } @Override public final void registers(java.util.Set<Integer> registers) { registers.add(target); registers.add(operand); } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nTarget = binding.get(target); Integer nOperand = binding.get(operand); if (nTarget != null || nOperand != null) { nTarget = nTarget != null ? nTarget : target; nOperand = nOperand != null ? nOperand : operand; return clone(nTarget, nOperand); } return this; } protected abstract Code clone(int nTarget, int nOperand); public int hashCode() { return type.hashCode() + target + operand; } public boolean equals(Object o) { if (o instanceof AbstractUnaryAssignable) { AbstractUnaryAssignable bo = (AbstractUnaryAssignable) o; return target == bo.target && operand == bo.operand && type.equals(bo.type); } return false; } } /** * Represents the set of bytcodes which take a single register operand, and * do not write any result. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractUnaryOp<T> extends Code { public final T type; public final int operand; private AbstractUnaryOp(T type, int operand) { if (type == null) { throw new IllegalArgumentException( "AbstractUnaryOp type argument cannot be null"); } this.type = type; this.operand = operand; } @Override public final void registers(java.util.Set<Integer> registers) { registers.add(operand); } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nOperand = binding.get(operand); if (nOperand != null) { return clone(nOperand); } return this; } protected abstract Code clone(int nOperand); public int hashCode() { return type.hashCode() + operand; } public boolean equals(Object o) { if (o instanceof AbstractUnaryOp) { AbstractUnaryOp bo = (AbstractUnaryOp) o; return operand == bo.operand && type.equals(bo.type); } return false; } } /** * Represents the set of bytcodes which take two register operands and write * a result to the target register. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractBinaryAssignable<T> extends AbstractAssignable { public final T type; public final int leftOperand; public final int rightOperand; private AbstractBinaryAssignable(T type, int target, int leftOperand, int rightOperand) { super(target); if (type == null) { throw new IllegalArgumentException( "AbstractBinOp type argument cannot be null"); } this.type = type; this.leftOperand = leftOperand; this.rightOperand = rightOperand; } @Override public final void registers(java.util.Set<Integer> registers) { registers.add(target); registers.add(leftOperand); registers.add(rightOperand); } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nTarget = binding.get(target); Integer nLeftOperand = binding.get(leftOperand); Integer nRightOperand = binding.get(rightOperand); if (nTarget != null || nLeftOperand != null || nRightOperand != null) { nTarget = nTarget != null ? nTarget : target; nLeftOperand = nLeftOperand != null ? nLeftOperand : leftOperand; nRightOperand = nRightOperand != null ? nRightOperand : rightOperand; return clone(nTarget, nLeftOperand, nRightOperand); } return this; } protected abstract Code clone(int nTarget, int nLeftOperand, int nRightOperand); public int hashCode() { return type.hashCode() + target + leftOperand + rightOperand; } public boolean equals(Object o) { if (o instanceof AbstractBinaryAssignable) { AbstractBinaryAssignable bo = (AbstractBinaryAssignable) o; return target == bo.target && leftOperand == bo.leftOperand && rightOperand == bo.rightOperand && type.equals(bo.type); } return false; } } /** * Represents the set of bytcodes which take an arbitrary number of register * operands and write a result to the target register. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractNaryAssignable<T> extends AbstractAssignable { public final T type; public final int[] operands; private AbstractNaryAssignable(T type, int target, int[] operands) { super(target); if (type == null) { throw new IllegalArgumentException( "AbstractBinOp type argument cannot be null"); } this.type = type; this.operands = operands; } @Override public final void registers(java.util.Set<Integer> registers) { if (target >= 0) { registers.add(target); } for (int i = 0; i != operands.length; ++i) { registers.add(operands[i]); } } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nTarget = binding.get(target); int[] nOperands = remap(binding, operands); if (nTarget != null || nOperands != operands) { nTarget = nTarget != null ? nTarget : target; return clone(nTarget, nOperands); } return this; } protected abstract Code clone(int nTarget, int[] nOperands); public int hashCode() { return type.hashCode() + target + Arrays.hashCode(operands); } public boolean equals(Object o) { if (o instanceof AbstractNaryAssignable) { AbstractNaryAssignable bo = (AbstractNaryAssignable) o; return target == bo.target && Arrays.equals(operands, bo.operands) && type.equals(bo.type); } return false; } } /** * Represents the set of bytcodes which take an arbitrary number of register * operands and write a result to the target register. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractSplitNaryAssignable<T> extends AbstractAssignable { public final T type; public final int operand; public final int[] operands; private AbstractSplitNaryAssignable(T type, int target, int operand, int[] operands) { super(target); if (type == null) { throw new IllegalArgumentException( "AbstractSplitNaryAssignable type argument cannot be null"); } this.type = type; this.operand = operand; this.operands = operands; } @Override public final void registers(java.util.Set<Integer> registers) { if (target >= 0) { registers.add(target); } registers.add(operand); for (int i = 0; i != operands.length; ++i) { registers.add(operands[i]); } } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nTarget = binding.get(target); Integer nOperand = binding.get(target); int[] nOperands = remap(binding, operands); if (nTarget != null || nOperand != null || nOperands != operands) { nTarget = nTarget != null ? nTarget : target; nOperand = nOperand != null ? nOperand : operand; return clone(nTarget, nOperand, nOperands); } return this; } protected abstract Code clone(int nTarget, int nOperand, int[] nOperands); public int hashCode() { return type.hashCode() + target + operand + Arrays.hashCode(operands); } public boolean equals(Object o) { if (o instanceof AbstractSplitNaryAssignable) { AbstractSplitNaryAssignable bo = (AbstractSplitNaryAssignable) o; return target == bo.target && operand == bo.operand && Arrays.equals(operands, bo.operands) && type.equals(bo.type); } return false; } } /** * Represents the set of bytcodes which take two register operands and * perform a comparison of their values. * * @author David J. Pearce * * @param <T> * --- the type associated with this bytecode. */ public static abstract class AbstractBinaryOp<T> extends Code { public final T type; public final int leftOperand; public final int rightOperand; private AbstractBinaryOp(T type, int leftOperand, int rightOperand) { if (type == null) { throw new IllegalArgumentException( "AbstractBinCond type argument cannot be null"); } this.type = type; this.leftOperand = leftOperand; this.rightOperand = rightOperand; } @Override public final void registers(java.util.Set<Integer> registers) { registers.add(leftOperand); registers.add(rightOperand); } @Override public final Code remap(Map<Integer, Integer> binding) { Integer nLeftOperand = binding.get(leftOperand); Integer nRightOperand = binding.get(rightOperand); if (nLeftOperand != null || nRightOperand != null) { nLeftOperand = nLeftOperand != null ? nLeftOperand : leftOperand; nRightOperand = nRightOperand != null ? nRightOperand : rightOperand; return clone(nLeftOperand, nRightOperand); } return this; } protected abstract Code clone(int nLeftOperand, int nRightOperand); public int hashCode() { return type.hashCode() + leftOperand + rightOperand; } public boolean equals(Object o) { if (o instanceof AbstractBinaryOp) { AbstractBinaryOp bo = (AbstractBinaryOp) o; return leftOperand == bo.leftOperand && rightOperand == bo.rightOperand && type.equals(bo.type); } return false; } } // =============================================================== // Bytecode Implementations // =============================================================== /** * Represents a binary operator (e.g. '+','-',etc) that is provided to a * <code>BinOp</code> bytecode. * * @author David J. Pearce * */ public enum ArithOperation { ADD { public String toString() { return "add"; } }, SUB { public String toString() { return "sub"; } }, MUL { public String toString() { return "mul"; } }, DIV { public String toString() { return "div"; } }, REM { public String toString() { return "rem"; } }, RANGE { public String toString() { return "range"; } }, BITWISEOR { public String toString() { return "or"; } }, BITWISEXOR { public String toString() { return "xor"; } }, BITWISEAND { public String toString() { return "and"; } }, LEFTSHIFT { public String toString() { return "shl"; } }, RIGHTSHIFT { public String toString() { return "shr"; } }, }; /** * <p> * A binary operation which reads two numeric values from the operand * registers, performs an operation on them and writes the result to the * target register. The binary operators are: * </p> * <ul> * <li><i>add, subtract, multiply, divide, remainder</i>. Both operands must * be either integers or reals (but not one or the other). A value of the * same type is produced.</li> * <li><i>range</i></li> * <li><i>bitwiseor, bitwisexor, bitwiseand</i></li> * <li><i>leftshift,rightshift</i></li> * </ul> * For example, the following Whiley code: * * <pre> * int f(int x, int y): * return ((x * y) + 1) / 2 * </pre> * * translates into the following WYIL code: * * <pre> * int f(int x, int y): * body: * mul %2 = %0, %1 : int * const %3 = 1 : int * add %2 = %2, %3 : int * const %3 = 2 : int * const %4 = 0 : int * assertne %3, %4 "division by zero" : int * div %2 = %2, %3 : int * return %2 : int * </pre> * * Here, the <code>assertne</code> bytecode has been included to check * against division-by-zero. In this particular case the assertion is known * true at compile time and, in practice, would be compiled away. * * @author David J. Pearce * */ public static final class ArithOp extends AbstractBinaryAssignable<Type> { public final ArithOperation bop; private ArithOp(Type type, int target, int lhs, int rhs, ArithOperation bop) { super(type, target, lhs, rhs); if (bop == null) { throw new IllegalArgumentException( "BinOp bop argument cannot be null"); } this.bop = bop; } @Override public Code clone(int nTarget, int nLeftOperand, int nRightOperand) { return Code.ArithOp(type, nTarget, nLeftOperand, nRightOperand, bop); } public int hashCode() { return bop.hashCode() + super.hashCode(); } public boolean equals(Object o) { if (o instanceof ArithOp) { ArithOp bo = (ArithOp) o; return bop.equals(bo.bop) && super.equals(bo); } return false; } public String toString() { return bop + " %" + target + " = %" + leftOperand + ", %" + rightOperand + " : " + type; } } /** * Reads a value from the operand register, converts it to a given type and * writes the result to the target register. This bytecode is the only way * to change the type of a value. It's purpose is to simplify * implementations which have different representations of data types. A * convert bytecode must be inserted whenever the type of a register * changes. This includes at control-flow meet points, when the value is * passed as a parameter, assigned to a field, etc. For example, the * following Whiley code: * * <pre> * real f(int x): * return x + 1 * </pre> * * translates into the following WYIL code: * * <pre> * real f(int x): * body: * const %2 = 1 : int * add %1 = %0, %2 : int * convert %1 = %1 real : int * return %1 : real * </pre> * <p> * Here, we see that the <code>int</code> value in register <code>%1</code> * must be explicitly converted into a <code>real</code> value before it can * be returned from this function. * </p> * <p> * <b>NOTE:</b> In many cases, this bytecode may correspond to a nop on the * hardware. Consider converting from <code>[any]</code> to <code>any</code> * . On the JVM, <code>any</code> translates to <code>Object</code>, whilst * <code>[any]</code> translates to <code>List</code> (which is an instance * of <code>Object</code>). Thus, no conversion is necessary since * <code>List</code> can safely flow into <code>Object</code>. * </p> * */ public static final class Convert extends AbstractUnaryAssignable<Type> { public final Type result; private Convert(Type from, int target, int operand, Type result) { super(from, target, operand); if (result == null) { throw new IllegalArgumentException( "Convert to argument cannot be null"); } this.result = result; } public Code clone(int nTarget, int nOperand) { return Code.Convert(type, nTarget, nOperand, result); } public int hashCode() { return result.hashCode() + super.hashCode(); } public boolean equals(Object o) { if (o instanceof Convert) { Convert c = (Convert) o; return super.equals(c) && result.equals(c.result); } return false; } public String toString() { return "convert %" + target + " = %" + operand + " " + result + " : " + type; } } /** * Writes a constant value to a target register. This includes * <i>integers</i>, <i>rationals</i>, <i>lists</i>, <i>sets</i>, * <i>maps</i>, etc. For example, the following Whiley code: * * <pre> * int f(int x): * xs = {1,2.12} * return |xs| + 1 * </pre> * * translates into the following WYIL code: * * <pre> * int f(int x): * body: * var xs * const %2 = 1 : int * convert %2 = % 2 int|real : int * const %3 = 2.12 : real * convert %3 = % 3 int|real : real * newset %1 = (%2, %3) : {int|real} * assign %3 = %1 : {int|real} * lengthof %3 = % 3 : {int|real} * const %4 = 1 : int * add %2 = % 3, %4 : int * return %2 : int * </pre> * * Here, we see two kinds of constants values being used: integers (i.e. * <code>const %2 = 1</code>) and rationals (i.e. <code>const %3 = 2.12</code>). * * @author David J. Pearce * */ public static final class Const extends AbstractAssignable { public final Value constant; private Const(int target, Value constant) { super(target); this.constant = constant; } @Override public void registers(java.util.Set<Integer> registers) { registers.add(target); } @Override public Code remap(Map<Integer, Integer> binding) { Integer nTarget = binding.get(target); if (nTarget != null) { return Code.Const(nTarget, constant); } return this; } public int hashCode() { return constant.hashCode() + target; } public boolean equals(Object o) { if (o instanceof Const) { Const c = (Const) o; return constant.equals(c.constant) && target == c.target; } return false; } public String toString() { return "const %" + target + " = " + constant + " : " + constant.type(); } } /** * Copy the contents from a given operand register into a given target * register. For example, the following Whiley code: * * <pre> * int f(int x): * x = x + 1 * return x * </pre> * * translates into the following WYIL code: * * <pre> * int f(int x): * body: * assign %1 = %0 : int * const %2 = 1 : int * add %0 = %1, %2 : int * return %0 : int * </pre> * * Here we see that an initial assignment is made from register * <code>%0</code> to register <code>%1</code>. In fact, this assignment is * unecessary but is useful to illustrate the <code>assign</code> bytecode. * * <p> * <b>NOTE:</b> on many architectures this operation may not actually clone * the data in question. Rather, it may copy the <i>reference</i> to the * data and then increment its <i>reference count</i>. This is to ensure * efficient treatment of large compound structures (e.g. lists, sets, maps * and records). * </p> * * @author David J. Pearce * */ public static final class Assign extends AbstractUnaryAssignable<Type> { private Assign(Type type, int target, int operand) { super(type, target, operand); } public Code clone(int nTarget, int nOperand) { return Code.Assign(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof Assign) { return super.equals(o); } return false; } public String toString() { return "assign %" + target + " = %" + operand + " " + " : " + type; } } /** * Read a string from the operand register and prints it to the debug * console. For example, the following Whiley code: * * <pre> * void f(int x): * debug "X = " + x * </pre> * * translates into the following WYIL code: * * <pre> * void f(int x): * body: * const %2 = "X = " : string * convert %0 = %0 any : int * invoke %0 (%0) whiley/lang/Any:toString : string(any) * strappend %1 = %2, %0 : string * debug %1 : string * return * </pre> * * <b>NOTE</b> This bytecode is not intended to form part of the program's * operation. Rather, it is to facilitate debugging within functions (since * they cannot have side-effects). Furthermore, if debugging is disabled, * this bytecode is a nop. * * @author David J. Pearce * */ public static final class Debug extends AbstractUnaryOp<Type.Strung> { private Debug(int operand) { super(Type.T_STRING, operand); } @Override public Code clone(int nOperand) { return Code.Debug(nOperand); } public boolean equals(Object o) { return o instanceof Debug && super.equals(o); } public String toString() { return "debug %" + operand + " " + " : " + type; } } /** * Marks the end of a loop block. * * @author David J. Pearce * */ public static final class LoopEnd extends Label { LoopEnd(String label) { super(label); } public LoopEnd relabel(Map<String, String> labels) { String nlabel = labels.get(label); if (nlabel == null) { return this; } else { return End(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if (o instanceof LoopEnd) { LoopEnd e = (LoopEnd) o; return e.label.equals(label); } return false; } public String toString() { return "end " + label; } } /** * An abstract class representing either an <code>assert</code> or * <code>assume</code> bytecode. * * @author David J. Pearce * */ public static abstract class AssertOrAssume extends AbstractBinaryOp<Type> { public final Comparator op; public final String msg; private AssertOrAssume(Type type, int leftOperand, int rightOperand, Comparator cop, String msg) { super(type, leftOperand, rightOperand); if (cop == null) { throw new IllegalArgumentException( "Assert op argument cannot be null"); } this.op = cop; this.msg = msg; } } /** * Reads two operand registers, compares their values and raises an * assertion failure with the given message if comparison is false. For * example, the following Whiley code: * * <pre> * int f([int] xs, int i): * return xs[i] * </pre> * * translates into the following WYIL code: * * <pre> * int f([int] xs, int i): * body: * const %2 = 0 : int * assertge %1, %2 "index out of bounds (negative)" : int * lengthof %3 = %0 : [int] * assertlt %2, %3 "index out of bounds (not less than length)" : int * indexof %1 = %0, %1 : [int] * return %1 : int * </pre> * * Here, we see <code>assert</code> bytecodes being used to check list * access is not out-of-bounds. * * @author David J. Pearce * */ public static final class Assert extends AssertOrAssume { private Assert(Type type, int leftOperand, int rightOperand, Comparator cop, String msg) { super(type, leftOperand, rightOperand, cop, msg); } @Override public Code clone(int nLeftOperand, int nRightOperand) { return Code.Assert(type, nLeftOperand, nRightOperand, op, msg); } public boolean equals(Object o) { if (o instanceof Assert) { Assert ig = (Assert) o; return op == ig.op && msg.equals(ig.msg) && super.equals(ig); } return false; } public String toString() { return "assert" + op + " %" + leftOperand + ", %" + rightOperand + " \"" + msg + "\"" + " : " + type; } } /** * Reads two operand registers, compares their values and raises an * assertion failure with the given message is raised if comparison is * false. Whilst this is very similar to an assert statement, it causes a * slightly different interaction with the type checker and/or theorem * prover. More specifically, they will not attempt to show the condition is * true and, instead, will simply assume it is (and leave an appropriate * runtime check). This is useful for override these processes in situations * where they are not smart enough to prove something is true. * * @author David J. Pearce * */ public static final class Assume extends AssertOrAssume { private Assume(Type type, int leftOperand, int rightOperand, Comparator cop, String msg) { super(type, leftOperand, rightOperand, cop, msg); } @Override public Code clone(int nLeftOperand, int nRightOperand) { return Code.Assume(type, nLeftOperand, nRightOperand, op, msg); } public boolean equals(Object o) { if (o instanceof Assume) { Assume ig = (Assume) o; return op == ig.op && msg.equals(ig.msg) && super.equals(ig); } return false; } public String toString() { return "assume" + op + " %" + leftOperand + ", %" + rightOperand + " \"" + msg + "\"" + " : " + type; } } /** * Reads a record value from an operand register, extracts the value of a * given field and writes this to the target register. For example, the * following Whiley code: * * <pre> * define Point as {int x, int y} * * int f(Point p): * return p.x + p.y * </pre> * * translates into the following WYIL code: * * <pre> * int f({int x,int y} p): * body: * fieldload %2 = %0 x : {int x,int y} * fieldload %3 = %0 y : {int x,int y} * add %1 = %2, %3 : int * return %1 : int * </pre> * * @author David J. Pearce * */ public static final class FieldLoad extends AbstractUnaryAssignable<Type.EffectiveRecord> { public final String field; private FieldLoad(Type.EffectiveRecord type, int target, int operand, String field) { super(type, target, operand); if (field == null) { throw new IllegalArgumentException( "FieldLoad field argument cannot be null"); } this.field = field; } @Override public Code clone(int nTarget, int nOperand) { return Code.FieldLoad(type, nTarget, nOperand, field); } public int hashCode() { return super.hashCode() + field.hashCode(); } public Type fieldType() { return type.fields().get(field); } public boolean equals(Object o) { if (o instanceof FieldLoad) { FieldLoad i = (FieldLoad) o; return super.equals(i) && field.equals(i.field); } return false; } public String toString() { return "fieldload %" + target + " = %" + operand + " " + field + " : " + type; } } /** * Branches unconditionally to the given label. This is typically used for * if/else statements. For example, the following Whiley code: * * <pre> * int f(int x): * if x >= 0: * x = 1 * else: * x = -1 * return x * </pre> * * translates into the following WYIL code: * * <pre> * int f(int x): * body: * const %1 = 0 : int * iflt %0, %1 goto blklab0 : int * const %0 = 1 : int * goto blklab1 * .blklab0 * const %0 = 1 : int * neg %0 = % 0 : int * .blklab1 * return %0 : int * </pre> * * Here, we see the <code>goto</code> bytecode being used to jump from the * end of the true branch over the false branch. * * <p> * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, a <code>goto</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * </p> * * @author David J. Pearce * */ public static final class Goto extends Code { public final String target; private Goto(String target) { this.target = target; } public Goto relabel(Map<String, String> labels) { String nlabel = labels.get(target); if (nlabel == null) { return this; } else { return Goto(nlabel); } } public int hashCode() { return target.hashCode(); } public boolean equals(Object o) { if (o instanceof Goto) { return target.equals(((Goto) o).target); } return false; } public String toString() { return "goto " + target; } } /** * <p> * Branches conditionally to the given label by reading the values from two * operand registers and comparing them. The possible comparators are: * </p> * <ul> * <li><i>equals (eq) and not-equals (ne)</i>. Both operands must have the * given type.</li> * <li><i>less-than (lt), less-than-or-equals (le), greater-than (gt) and * great-than-or-equals (ge).</i> Both operands must have the given type, * which additionally must by either <code>char</code>, <code>int</code> or * <code>real</code>.</li> * <li><i>element of (in).</i> The second operand must be a set whose * element type is that of the first.</li> * <li><i>subset (ss) and subset-equals (sse)</i>. Both operands must have * the given type, which additionally must be a set.</li> * </ul> * For example, the following Whiley code: * * <pre> * int f(int x, int y): * if x < y: * return -1 * else if x > y: * return 1 * else: * return 0 * </pre> * * translates into the following WYIL code: * * <pre> * int f(int x, int y): * body: * ifge %0, %1 goto blklab0 : int * const %2 = -1 : int * return %2 : int * .blklab0 * ifle %0, %1 goto blklab2 : int * const %2 = 1 : int * return %2 : int * .blklab2 * const %2 = 0 : int * return %2 : int * </pre> * * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, an <code>ifgoto</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * * @author David J. Pearce * */ public static final class If extends AbstractBinaryOp<Type> { public final String target; public final Comparator op; private If(Type type, int leftOperand, int rightOperand, Comparator op, String target) { super(type, leftOperand, rightOperand); if (op == null) { throw new IllegalArgumentException( "IfGoto op argument cannot be null"); } if (target == null) { throw new IllegalArgumentException( "IfGoto target argument cannot be null"); } this.op = op; this.target = target; } public If relabel(Map<String, String> labels) { String nlabel = labels.get(target); if (nlabel == null) { return this; } else { return If(type, leftOperand, rightOperand, op, nlabel); } } @Override public Code clone(int nLeftOperand, int nRightOperand) { return Code.If(type, nLeftOperand, nRightOperand, op, target); } public int hashCode() { return super.hashCode() + op.hashCode() + target.hashCode(); } public boolean equals(Object o) { if (o instanceof If) { If ig = (If) o; return op == ig.op && target.equals(ig.target) && super.equals(ig); } return false; } public String codeString() { return null; } public String toString() { return "if" + op + " %" + leftOperand + ", %" + rightOperand + " goto " + target + " : " + type; } } /** * Represents a comparison operator (e.g. '==','!=',etc) that is provided to * a <code>IfGoto</code> bytecode. * * @author David J. Pearce * */ public enum Comparator { EQ() { public String toString() { return "eq"; } }, NEQ { public String toString() { return "ne"; } }, LT { public String toString() { return "lt"; } }, LTEQ { public String toString() { return "le"; } }, GT { public String toString() { return "gt"; } }, GTEQ { public String toString() { return "ge"; } }, ELEMOF { public String toString() { return "in"; } }, SUBSET { public String toString() { return "sb"; } }, SUBSETEQ { public String toString() { return "sbe"; } } }; /** * Determine the inverse comparator, or null if no inverse exists. * * @param cop * @return */ public static Code.Comparator invert(Code.Comparator cop) { switch (cop) { case EQ: return Code.Comparator.NEQ; case NEQ: return Code.Comparator.EQ; case LT: return Code.Comparator.GTEQ; case LTEQ: return Code.Comparator.GT; case GT: return Code.Comparator.LTEQ; case GTEQ: return Code.Comparator.LT; } return null; } /** * Branches conditionally to the given label based on the result of a * runtime type test against a value from the operand register. More * specifically, it checks whether the value is a subtype of the type test. * The operand register is automatically <i>retyped</i> as a result of the * type test. On the true branch, its type is intersected with type test. On * the false branch, its type is intersected with the <i>negation</i> of the * type test. For example, the following Whiley code: * * <pre> * int f(int|[int] x): * if x is [int]: * return |x| * else: * return x * </pre> * * translates into the following WYIL code: * * <pre> * int f(int|[int] x): * body: * ifis %0, [int] goto lab : int|[int] * return %0 : int * .lab * lengthof %0 = %0 : [int] * return %0 : int * </pre> * * Here, we see that, on the false branch, register <code>%0</code> is * automatically given type <code>int</code>, whilst on the true branch it * is automatically given type <code>[int]</code>. * * <p> * <b>Note:</b> in WYIL bytecode, <i>such branches may only go forward</i>. * Thus, an <code>iftype</code> bytecode cannot be used to implement the * back-edge of a loop. Rather, a loop block must be used for this purpose. * </p> * * @author David J. Pearce * */ public static final class IfIs extends Code { public final Type type; public final String target; public final int leftOperand; public final Type rightOperand; private IfIs(Type type, int leftOperand, Type rightOperand, String target) { if (type == null) { throw new IllegalArgumentException( "IfUs type argument cannot be null"); } if (rightOperand == null) { throw new IllegalArgumentException( "IfIs test argument cannot be null"); } if (target == null) { throw new IllegalArgumentException( "IfIs target argument cannot be null"); } this.type = type; this.target = target; this.leftOperand = leftOperand; this.rightOperand = rightOperand; } public IfIs relabel(Map<String, String> labels) { String nlabel = labels.get(target); if (nlabel == null) { return this; } else { return IfIs(type, leftOperand, rightOperand, nlabel); } } @Override public void registers(java.util.Set<Integer> registers) { registers.add(leftOperand); } @Override public Code remap(Map<Integer, Integer> binding) { Integer nLeftOperand = binding.get(leftOperand); if (nLeftOperand != null) { return Code.IfIs(type, nLeftOperand, rightOperand, target); } return this; } public int hashCode() { return type.hashCode() + rightOperand.hashCode() + target.hashCode() + leftOperand + rightOperand.hashCode(); } public boolean equals(Object o) { if (o instanceof IfIs) { IfIs ig = (IfIs) o; return leftOperand == ig.leftOperand && rightOperand.equals(ig.rightOperand) && target.equals(ig.target) && type.equals(ig.type); } return false; } public String toString() { return "ifis" + " %" + leftOperand + ", " + rightOperand + " goto " + target + " : " + type; } } /** * Represents an indirect function call. For example, consider the * following: * * <pre> * int function(int(int) f, int x): * return f(x) * </pre> * * Here, the function call <code>f(x)</code> is indirect as the called * function is determined by the variable <code>f</code>. * * @author David J. Pearce * */ public static final class IndirectInvoke extends AbstractSplitNaryAssignable<Type.FunctionOrMethod> { private IndirectInvoke(Type.FunctionOrMethod type, int target, int operand, int[] operands) { super(type, target, operand, operands); } @Override public Code clone(int nTarget, int nOperand, int[] nOperands) { return IndirectInvoke(type, nTarget, nOperand, nOperands); } public boolean equals(Object o) { return o instanceof IndirectInvoke && super.equals(o); } public String toString() { if (target != Code.NULL_REG) { return "indirectinvoke " + target + " " + operand + " " + toString(operands) + " : " + type; } else { return "indirectinvoke " + operand + " " + toString(operands) + " : " + type; } } } /** * Represents an indirect message send (either synchronous or asynchronous). * For example, consider the following: * * <pre> * int ::method(Rec::int(int) m, Rec r, int x): * return r.m(x) * </pre> * * Here, the message send <code>r.m(x)</code> is indirect as the message * sent is determined by the variable <code>m</code>. * * @author David J. Pearce * */ public static final class IndirectSend extends AbstractSplitNaryAssignable<Type.Message> { public final boolean synchronous; private IndirectSend(Type.Message type, boolean synchronous, int target, int operand, int[] operands) { super(type, target, operand, operands); this.synchronous = synchronous; } @Override public Code clone(int nTarget, int nOperand, int[] nOperands) { return IndirectSend(type, nTarget, nOperand, nOperands, synchronous); } public boolean equals(Object o) { return o instanceof IndirectSend && super.equals(o); } public String toString() { if (synchronous) { if (target != Code.NULL_REG) { return "isend " + target + " " + operand + " " + toString(operands) + " : " + type; } else { return "ivsend" + operand + " " + toString(operands) + " : " + type; } } else { return "iasend" + operand + " " + toString(operands) + " : " + type; } } } /** * Read a boolean value from the operand register, inverts it and writes the * result to the target register. For example, the following Whiley code: * * <pre> * bool f(bool x): * return !x * </pre> * * translates into the following WYIL: * * <pre> * bool f(bool x): * body: * not %0 = %0 : int * return %0 : int * </pre> * * This simply reads the parameter <code>x</code> stored in register * <code>%0</code>, inverts it and then returns the inverted value. * * @author David J. Pearce * */ public static final class Not extends AbstractUnaryAssignable<Type.Bool> { private Not(int target, int operand) { super(Type.T_BOOL, target, operand); } @Override public Code clone(int nTarget, int nOperand) { return Code.Not(nTarget, nOperand); } public int hashCode() { return super.hashCode(); } public boolean equals(Object o) { if (o instanceof Not) { Not n = (Not) o; return super.equals(n); } return false; } public String toString() { return "not %" + target + " = %" + operand + " : " + type; } } /** * Corresponds to a function or method call whose parameters are read from * zero or more operand registers. If a return value is required, this is * written to a target register afterwards. For example, the following * Whiley code: * * <pre> * int g(int x, int y, int z): * return x * y * z * * int f(int x, int y): * r = g(x,y,3) * return r + 1 * </pre> * * translates into the following WYIL code: * * <pre> * int g(int x, int y, int z): * body: * mul %3 = %0, %1 : int * mul %3 = %3, %2 : int * return %3 : int * * int f(int x, int y): * body: * const %2 = 3 : int * invoke %2 = (%0, %1, %2) test:g : int(int,int,int) * const %3 = 1 : int * add %2 = (%2, %3) : int * return %2 : int * </pre> * * Here, we see that arguments to the <code>invoke</code> bytecode are * supplied in the order they are given in the function or method's * declaration. * * @author David J. Pearce * */ public static final class Invoke extends AbstractNaryAssignable<Type.FunctionOrMethod> { public final NameID name; private Invoke(Type.FunctionOrMethod type, int target, int[] operands, NameID name) { super(type, target, operands); this.name = name; } public int hashCode() { return name.hashCode() + super.hashCode(); } @Override public Code clone(int nTarget, int[] nOperands) { return Code.Invoke(type, nTarget, nOperands, name); } public boolean equals(Object o) { if (o instanceof Invoke) { Invoke i = (Invoke) o; return name.equals(i.name) && super.equals(i); } return false; } public String toString() { if (target != Code.NULL_REG) { return "invoke %" + target + " " + toString(operands) + " " + name + " : " + type; } else { return "invoke %" + toString(operands) + " " + name + " : " + type; } } } /** * Represents the labelled destination of a branch or loop statement. * * @author David J. Pearce * */ public static class Label extends Code { public final String label; private Label(String label) { this.label = label; } public Label relabel(Map<String, String> labels) { String nlabel = labels.get(label); if (nlabel == null) { return this; } else { return Label(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if (o instanceof Label) { return label.equals(((Label) o).label); } return false; } public String toString() { return "." + label; } } public enum ListOperation { LEFT_APPEND { public String toString() { return "lappend"; } }, RIGHT_APPEND { public String toString() { return "rappend"; } }, APPEND { public String toString() { return "append"; } } } /** * Reads the (effective) list values from two operand registers, performs an * operation (e.g. append) on them and writes the result back to a target * register. For example, the following Whiley code: * * <pre> * [int] f([int] xs, [int] ys): * return xs ++ ys * </pre> * * translates into the following WYIL code: * * <pre> * [int] f([int] xs, [int] ys): * body: * append %2 = %0, %1 : [int] * return %2 : [int] * </pre> * * This appends two the parameter lists together writting the new list into * register <code>%2</code>. * * @author David J. Pearce * */ public static final class ListOp extends AbstractBinaryAssignable<Type.EffectiveList> { public final ListOperation operation; private ListOp(Type.EffectiveList type, int target, int leftOperand, int rightOperand, ListOperation operation) { super(type, target, leftOperand, rightOperand); if (operation == null) { throw new IllegalArgumentException( "ListAppend direction cannot be null"); } this.operation = operation; } @Override public Code clone(int nTarget, int nLeftOperand, int nRightOperand) { return Code.ListOp(type, nTarget, nLeftOperand, nRightOperand, operation); } public int hashCode() { return super.hashCode() + operation.hashCode(); } public boolean equals(Object o) { if (o instanceof ListOp) { ListOp setop = (ListOp) o; return super.equals(setop) && operation.equals(setop.operation); } return false; } public String toString() { return operation + " %" + target + " = %" + leftOperand + ", %" + rightOperand + " : " + type; } } /** * Reads an (effective) collection (i.e. a set, list or map) from the * operand register, and writes its length into the target register. For * example, the following Whiley code: * * <pre> * int f([int] ls): * return |ls| * </pre> * * translates to the following WYIL code: * * <pre> * int f([int] ls): * body: * lengthof %0 = %0 : [int] * return %0 : int * </pre> * * @author David J. Pearce * */ public static final class LengthOf extends AbstractUnaryAssignable<Type.EffectiveCollection> { private LengthOf(Type.EffectiveCollection type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.LengthOf(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof LengthOf) { return super.equals(o); } return false; } public String toString() { return "lengthof %" + target + " = %" + operand + " : " + type; } } /** * Reads the (effective) list value from a source operand register, and the * integer values from two index operand registers, computes the sublist and * writes the result back to a target register. * * @author David J. Pearce * */ public static final class SubList extends AbstractNaryAssignable<Type.EffectiveList> { private SubList(Type.EffectiveList type, int target, int[] operands) { super(type, target, operands); } @Override public final Code clone(int nTarget, int[] nOperands) { return Code.SubList(type, nTarget, nOperands); } public boolean equals(Object o) { return o instanceof SubList && super.equals(o); } public String toString() { return "sublist %" + target + " = %" + operands[0] + ", %" + operands[1] + ", %" + operands[2] + " : " + type; } } /** * Reads an effective list or map from the source (left) operand register, * and a key value from the key (right) operand register and returns the * value associated with that key. If the key does not exist, then a fault * is raised. For example, the following Whiley code: * * <pre> * string f({int=>string} map, int key): * return map[key] * </pre> * * translates into the following WYIL code: * * <pre> * string f({int->string} map, int key): * body: * assertky %1, %0 "invalid key" : {int->string} * indexof %2 = %0, %1 : {int->string} * return %2 : string * </pre> * * Here, we see the <code>assertky</code> bytecode is used to first check * that the given key exists in <code>map</code>, otherwise a fault is * raised. * * @author David J. Pearce * */ public static final class IndexOf extends AbstractBinaryAssignable<Type.EffectiveMap> { private IndexOf(Type.EffectiveMap type, int target, int sourceOperand, int keyOperand) { super(type, target, sourceOperand, keyOperand); } protected Code clone(int nTarget, int nLeftOperand, int nRightOperand) { return Code.IndexOf(type, nTarget, nLeftOperand, nRightOperand); } public boolean equals(Object o) { if (o instanceof IndexOf) { return super.equals(o); } return false; } public String toString() { return "indexof %" + target + " = %" + leftOperand + ", %" + rightOperand + " : " + type; } } /** * Moves the contents of a given operand register into a given target * register. This is similar to an <code>assign</code> bytecode, except that * the register's contents are <i>voided</i> afterwards. This guarantees * that the register is no longer live, which is useful for determining the * live ranges of registers in a function or method. For example, the * following Whiley code: * * <pre> * int f(int x, int y): * x = x + 1 * return x * </pre> * * can be translated into the following WYIL code: * * <pre> * int f(int x, int y): * body: * ifge %0, %1 goto blklab0 : int * move %0 = %1 : int * .blklab0 * return %0 : int * </pre> * * Here we see that when <code>x < y</code> the value of <code>y</code> * (held in register <code>%1</code>) is <i>moved</i> into variable * <code>x</code> (held in register <code>%0</code>). This is safe because * register <code>%1</code> is no longer live at that point. * * @author David J. Pearce * */ public static final class Move extends AbstractUnaryAssignable<Type> { private Move(Type type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.Move(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof Move) { return super.equals(o); } return false; } public String toString() { return "move %" + target + " = %" + operand + " : " + type; } } /** * Represents a block of code which loops continuously until e.g. a * conditional branch is taken out of the block. For example: * * <pre> * int f(): * r = 0 * while r < 10: * r = r + 1 * return r * </pre> * translates into the following WYIL code: * <pre> * int f(): * body: * const %0 = 0 : int * loop (%0) * const %1 = 10 : int * ifge %0, %1 goto blklab0 : int * const %1 = 1 : int * add %0 = %0, %1 : int * .blklab0 * return %0 : int * </pre> * * <p> * Here, we see a loop which increments an accumulator register * <code>%0</code> until it reaches <code>10</code>, and then exits the loop * block. * </p> * <p> * The <i>modified operands</i> of a loop bytecode (shown in brackets * alongside the bytecode) indicate those operands which are modified at * some point within the loop. * </p> * * @author David J. Pearce * */ public static class Loop extends Code { public final String target; public final int[] modifiedOperands; private Loop(String target, int[] modifies) { this.target = target; this.modifiedOperands = modifies; } public Loop relabel(Map<String, String> labels) { String nlabel = labels.get(target); if (nlabel == null) { return this; } else { return Loop(nlabel, modifiedOperands); } } @Override public void registers(java.util.Set<Integer> registers) { for (int operand : modifiedOperands) { registers.add(operand); } } @Override public Code remap(Map<Integer, Integer> binding) { int[] nOperands = remap(binding, modifiedOperands); if (nOperands != modifiedOperands) { return Code.Loop(target, nOperands); } else { return this; } } public int hashCode() { return target.hashCode() + Arrays.hashCode(modifiedOperands); } public boolean equals(Object o) { if (o instanceof Loop) { Loop f = (Loop) o; return target.equals(f.target) && Arrays.equals(modifiedOperands, f.modifiedOperands); } return false; } public String toString() { return "loop " + toString(modifiedOperands); } } /** * Pops a set, list or dictionary from the stack and iterates over every * element it contains. A register is identified to hold the current value * being iterated over. * * @author David J. Pearce * */ public static final class ForAll extends Loop { public final int sourceOperand; public final int indexOperand; public final Type.EffectiveCollection type; private ForAll(Type.EffectiveCollection type, int sourceOperand, int indexOperand, int[] modifies, String target) { super(target, modifies); this.type = type; this.sourceOperand = sourceOperand; this.indexOperand = indexOperand; } public ForAll relabel(Map<String, String> labels) { String nlabel = labels.get(target); if (nlabel == null) { return this; } else { return ForAll(type, sourceOperand, indexOperand, modifiedOperands, nlabel); } } @Override public void registers(java.util.Set<Integer> registers) { registers.add(indexOperand); registers.add(sourceOperand); super.registers(registers); } @Override public Code remap(Map<Integer, Integer> binding) { int[] nModifiedOperands = remap(binding, modifiedOperands); Integer nIndexOperand = binding.get(indexOperand); Integer nSourceOperand = binding.get(sourceOperand); if (nSourceOperand != null || nIndexOperand != null || nModifiedOperands != modifiedOperands) { nSourceOperand = nSourceOperand != null ? nSourceOperand : sourceOperand; nIndexOperand = nIndexOperand != null ? nIndexOperand : indexOperand; return Code.ForAll(type, nSourceOperand, nIndexOperand, nModifiedOperands, target); } else { return this; } } public int hashCode() { return super.hashCode() + indexOperand + Arrays.hashCode(modifiedOperands); } public boolean equals(Object o) { if (o instanceof ForAll) { ForAll f = (ForAll) o; return target.equals(f.target) && type.equals(f.type) && indexOperand == f.indexOperand && Arrays.equals(modifiedOperands, f.modifiedOperands); } return false; } public String toString() { return "forall %" + indexOperand + " in %" + sourceOperand + " " + toString(modifiedOperands) + " : " + type; } } /** * Represents a type which may appear on the left of an assignment * expression. Lists, Dictionaries, Strings, Records and References are the * only valid types for an lval. * * @author David J. Pearce * */ public static abstract class LVal { protected Type type; public LVal(Type t) { this.type = t; } public Type rawType() { return type; } } /** * An LVal with dictionary type. * * @author David J. Pearce * */ public static final class DictLVal extends LVal { public final int keyOperand; public DictLVal(Type t, int keyOperand) { super(t); if (!(t instanceof Type.EffectiveDictionary)) { throw new IllegalArgumentException("Invalid Dictionary Type"); } this.keyOperand = keyOperand; } public Type.EffectiveDictionary type() { return (Type.EffectiveDictionary) type; } } /** * An LVal with list type. * * @author David J. Pearce * */ public static final class ListLVal extends LVal { public final int indexOperand; public ListLVal(Type t, int indexOperand) { super(t); if (!(t instanceof Type.EffectiveList)) { throw new IllegalArgumentException("invalid List Type"); } this.indexOperand = indexOperand; } public Type.EffectiveList type() { return (Type.EffectiveList) type; } } /** * An LVal with list type. * * @author David J. Pearce * */ public static final class ReferenceLVal extends LVal { public ReferenceLVal(Type t) { super(t); if (Type.effectiveReference(t) == null) { throw new IllegalArgumentException("invalid reference type"); } } public Type.Reference type() { return Type.effectiveReference(type); } } /** * An LVal with string type. * * @author David J. Pearce * */ public static final class StringLVal extends LVal { public final int indexOperand; public StringLVal(int indexOperand) { super(Type.T_STRING); this.indexOperand = indexOperand; } } /** * An LVal with record type. * * @author David J. Pearce * */ public static final class RecordLVal extends LVal { public final String field; public RecordLVal(Type t, String field) { super(t); this.field = field; if (!(t instanceof Type.EffectiveRecord) || !((Type.EffectiveRecord) t).fields().containsKey(field)) { throw new IllegalArgumentException("Invalid Record Type"); } } public Type.EffectiveRecord type() { return (Type.EffectiveRecord) type; } } private static final class UpdateIterator implements Iterator<LVal> { private final ArrayList<String> fields; private final int[] operands; private Type iter; private int fieldIndex; private int operandIndex; private int index; public UpdateIterator(Type type, int level, int[] operands, ArrayList<String> fields) { this.fields = fields; this.iter = type; this.index = level; this.operands = operands; } public LVal next() { Type raw = iter; index--; if (Type.isSubtype(Type.T_STRING, iter)) { iter = Type.T_CHAR; return new StringLVal(operands[operandIndex++]); } else if (Type.isSubtype(Type.Reference(Type.T_ANY), iter)) { Type.Reference proc = Type.effectiveReference(iter); iter = proc.element(); return new ReferenceLVal(raw); } else if (iter instanceof Type.EffectiveList) { Type.EffectiveList list = (Type.EffectiveList) iter; iter = list.element(); return new ListLVal(raw, operands[operandIndex++]); } else if (iter instanceof Type.EffectiveDictionary) { Type.EffectiveDictionary dict = (Type.EffectiveDictionary) iter; iter = dict.value(); return new DictLVal(raw, operands[operandIndex++]); } else if (iter instanceof Type.EffectiveRecord) { Type.EffectiveRecord rec = (Type.EffectiveRecord) iter; String field = fields.get(fieldIndex++); iter = rec.fields().get(field); return new RecordLVal(raw, field); } else { throw new IllegalArgumentException( "Invalid type for Code.Update"); } } public boolean hasNext() { return index > 0; } public void remove() { throw new UnsupportedOperationException( "UpdateIterator is unmodifiable"); } } /** * <p> * Pops a compound structure, zero or more indices and a value from the * stack and updates the compound structure with the given value. Valid * compound structures are lists, dictionaries, strings, records and * references. * </p> * <p> * Ideally, this operation is done in-place, meaning the operation is * constant time. However, to support Whiley's value semantics this bytecode * may require (in some cases) a clone of the underlying data-structure. * Thus, the worst-case runtime of this operation is linear in the size of * the compound structure. * </p> * * @author David J. Pearce * */ public static final class Update extends AbstractSplitNaryAssignable<Type> implements Iterable<LVal> { public final Type afterType; public final ArrayList<String> fields; private Update(Type beforeType, int target, int operand, int[] operands, Type afterType, Collection<String> fields) { super(beforeType, target, operand, operands); if (fields == null) { throw new IllegalArgumentException( "FieldStore fields argument cannot be null"); } this.afterType = afterType; this.fields = new ArrayList<String>(fields); } public int level() { int base = 0; if (type instanceof Type.Reference) { base++; } return base + fields.size() + operands.length; } public Iterator<LVal> iterator() { return new UpdateIterator(afterType, level(), operands, fields); } /** * Extract the type for the right-hand side of this assignment. * * @return */ public Type rhs() { Type iter = afterType; int fieldIndex = 0; for (int i = 0; i != level(); ++i) { if (Type.isSubtype(Type.T_STRING, iter)) { iter = Type.T_CHAR; } else if (Type.isSubtype(Type.Reference(Type.T_ANY), iter)) { Type.Reference proc = Type.effectiveReference(iter); iter = proc.element(); } else if (iter instanceof Type.EffectiveList) { Type.EffectiveList list = (Type.EffectiveList) iter; iter = list.element(); } else if (iter instanceof Type.EffectiveDictionary) { Type.EffectiveDictionary dict = (Type.EffectiveDictionary) iter; iter = dict.value(); } else if (iter instanceof Type.EffectiveRecord) { Type.EffectiveRecord rec = (Type.EffectiveRecord) iter; String field = fields.get(fieldIndex++); iter = rec.fields().get(field); } else { throw new IllegalArgumentException( "Invalid type for Code.Update"); } } return iter; } @Override public final Code clone(int nTarget, int nOperand, int[] nOperands) { return Code.Update(type, nTarget, nOperand, nOperands, afterType, fields); } public boolean equals(Object o) { if (o instanceof Update) { Update i = (Update) o; return super.equals(o) && afterType.equals(i.afterType) && fields.equals(i.fields); } return false; } public String toString() { String r = "%" + target; for (LVal lv : this) { if (lv instanceof ListLVal) { ListLVal l = (ListLVal) lv; r = r + "[%" + l.indexOperand + "]"; } else if (lv instanceof StringLVal) { StringLVal l = (StringLVal) lv; r = r + "[%" + l.indexOperand + "]"; } else if (lv instanceof DictLVal) { DictLVal l = (DictLVal) lv; r = r + "[%" + l.keyOperand + "]"; } else if (lv instanceof RecordLVal) { RecordLVal l = (RecordLVal) lv; r = r + "." + l.field; } else { ReferenceLVal l = (ReferenceLVal) lv; r = "(*" + r + ")"; } } return "update " + r + " %" + operand + " : " + type + " -> " + afterType; } } /** * Constructs a dictionary value from zero or more key-value pairs on the * stack. For each pair, the key must occur directly before the value on the * stack. For example, consider the following Whiley function * <code>f()</code>: * * <pre> * {int=>string} f(): * return {1=>"Hello",2=>"World"} * </pre> * * This could be compiled into the following WYIL code using this bytecode: * * <pre> * {int->string} f(): * body: * const %1 = 1 : int * const %2 = "Hello" : string * const %3 = 2 : int * const %4 = "World" : string * newmap %0 = (%1, %2, %3, %4) : {int=>string} * return %0 : {int=>string} * </pre> * * * @author David J. Pearce * */ public static final class NewMap extends AbstractNaryAssignable<Type.Dictionary> { private NewMap(Type.Dictionary type, int target, int[] operands) { super(type, target, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.NewMap(type, nTarget, nOperands); } public boolean equals(Object o) { if (o instanceof NewMap) { return super.equals(o); } return false; } public String toString() { return "newmap %" + target + " " + toString(operands) + " : " + type; } } /** * Constructs a new record value from the values of zero or more operand * register, each of which is associated with a field name. The new record * value is then written into the target register. For example, the * following Whiley code: * * <pre> * define Point as {real x, real y} * * Point f(real x, real y): * return {x: x, y: x} * </pre> * * translates into the following WYIL: * * <pre> * {real x,real y} f(real x, real y): * body: * assign %3 = %0 : real * assign %4 = %0 : real * newrecord %2 (%3, %4) : {real x,real y} * return %2 : {real x,real y} * </pre> * * @author David J. Pearce * */ public static final class NewRecord extends AbstractNaryAssignable<Type.Record> { private NewRecord(Type.Record type, int target, int[] operands) { super(type, target, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.NewRecord(type, nTarget, nOperands); } public boolean equals(Object o) { if (o instanceof NewRecord) { return super.equals(o); } return false; } public String toString() { return "newrecord %" + target + " " + toString(operands) + " : " + type; } } /** * Constructs a new tuple value from the values given by zero or more * operand registers. The new tuple is then written into the target * register. For example, the following Whiley code: * * <pre> * (int,int) f(int x, int y): * return x,y * </pre> * * translates into the following WYIL code: * * <pre> * (int,int) f(int x, int y): * body: * assign %3 = %0 : int * assign %4 = %1 : int * newtuple %2 = (%3, %4) : (int,int) * return %2 : (int,int) * </pre> * * This writes the tuple value generated from <code>(x,y)</code> into * register <code>%2</code> and returns it. * * @author David J. Pearce * */ public static final class NewTuple extends AbstractNaryAssignable<Type.Tuple> { private NewTuple(Type.Tuple type, int target, int[] operands) { super(type, target, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.NewTuple(type, nTarget, nOperands); } public boolean equals(Object o) { if (o instanceof NewTuple) { return super.equals(o); } return false; } public String toString() { return "newtuple %" + target + " = " + toString(operands) + " : " + type; } } /** * Constructs a new set value from the values given by zero or more operand * registers. The new set is then written into the target register. For * example, the following Whiley code: * * <pre> * {int} f(int x, int y, int z): * return {x,y,z} * </pre> * * translates into the following WYIL code: * * <pre> * [int] f(int x, int y, int z): * body: * assign %4 = %0 : int * assign %5 = %1 : int * assign %6 = %2 : int * newset %3 = (%4, %5, %6) : [int] * return %3 : [int] * </pre> * * Writes the set value given by <code>{x,y,z}</code> into register * <code>%3</code> and returns it. * * @author David J. Pearce * */ public static final class NewSet extends AbstractNaryAssignable<Type.Set> { private NewSet(Type.Set type, int target, int[] operands) { super(type, target, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.NewSet(type, nTarget, nOperands); } public boolean equals(Object o) { if (o instanceof NewSet) { return super.equals(o); } return false; } public String toString() { return "newset %" + target + " = " + toString(operands) + " : " + type; } } /** * Constructs a new list value from the values given by zero or more operand * registers. The new list is then written into the target register. For * example, the following Whiley code: * * <pre> * [int] f(int x, int y, int z): * return [x,y,z] * </pre> * * translates into the following WYIL code: * * <pre> * [int] f(int x, int y, int z): * body: * assign %4 = %0 : int * assign %5 = %1 : int * assign %6 = %2 : int * newlist %3 = (%4, %5, %6) : [int] * return %3 : [int] * </pre> * * Writes the list value given by <code>[x,y,z]</code> into register * <code>%3</code> and returns it. * * @author David J. Pearce * */ public static final class NewList extends AbstractNaryAssignable<Type.List> { private NewList(Type.List type, int target, int[] operands) { super(type, target, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.NewList(type, nTarget, nOperands); } public boolean equals(Object o) { if (o instanceof NewList) { return super.equals(operands); } return false; } public String toString() { return "newlist %" + target + " = " + toString(operands) + " : " + type; } } /** * Represents a no-operation bytecode which, as the name suggests, does * nothing. * * @author David J. Pearce * */ public static final class Nop extends Code { private Nop() { } public String toString() { return "nop"; } } /** * Returns from the enclosing function or method, possibly returning a * value. For example, the following Whiley code: * * <pre> * int f(int x, int y): * return x + y * </pre> * * translates into the following WYIL: * * <pre> * int f(int x, int y): * body: * assign %3 = %0 : int * assign %4 = %1 : int * add %2 = % 3, %4 : int * return %2 : int * </pre> * * Here, the * <code>return<code> bytecode returns the value of its operand register. * * @author David J. Pearce * */ public static final class Return extends AbstractUnaryOp<Type> { private Return(Type type, int operand) { super(type, operand); if (type == Type.T_VOID && operand != NULL_REG) { throw new IllegalArgumentException( "Return with void type cannot have target register."); } else if (type != Type.T_VOID && operand == NULL_REG) { throw new IllegalArgumentException( "Return with non-void type must have target register."); } } public Code clone(int nOperand) { return new Return(type, nOperand); } public boolean equals(Object o) { if (o instanceof Return) { return super.equals(o); } return false; } public String toString() { if (operand != Code.NULL_REG) { return "return %" + operand + " : " + type; } else { return "return"; } } } public enum SetOperation { LEFT_UNION { public String toString() { return "lunion"; } }, RIGHT_UNION { public String toString() { return "runion"; } }, UNION { public String toString() { return "union"; } }, LEFT_INTERSECTION { public String toString() { return "lintersect"; } }, RIGHT_INTERSECTION { public String toString() { return "rintersect"; } }, INTERSECTION { public String toString() { return "intersect"; } }, LEFT_DIFFERENCE { public String toString() { return "ldiff"; } }, DIFFERENCE { public String toString() { return "diff"; } } } public static final class SetOp extends AbstractBinaryAssignable<Type.EffectiveSet> { public final SetOperation operation; private SetOp(Type.EffectiveSet type, int target, int leftOperand, int rightOperand, SetOperation operation) { super(type, target, leftOperand, rightOperand); if (operation == null) { throw new IllegalArgumentException( "SetOp operation cannot be null"); } this.operation = operation; } protected Code clone(int nTarget, int nLeftOperand, int nRightOperand) { return Code.SetOp(type, nTarget, nLeftOperand, nRightOperand, operation); } public int hashCode() { return operation.hashCode() + super.hashCode(); } public boolean equals(Object o) { if (o instanceof SetOp) { SetOp setop = (SetOp) o; return operation.equals(setop.operation) && super.equals(o); } return false; } public String toString() { return operation + " %" + target + " = %" + leftOperand + ", %" + rightOperand + " : " + type; } } public enum StringOperation { LEFT_APPEND { public String toString() { return "strappend_l"; } }, RIGHT_APPEND { public String toString() { return "strappend_r"; } }, APPEND { public String toString() { return "strappend"; } } } public static final class StringOp extends AbstractBinaryAssignable<Type.Strung> { public final StringOperation operation; private StringOp(int target, int leftOperand, int rightOperand, StringOperation operation) { super(Type.T_STRING, target, leftOperand, rightOperand); if (operation == null) { throw new IllegalArgumentException( "StringBinOp operation cannot be null"); } this.operation = operation; } protected Code clone(int nTarget, int nLeftOperand, int nRightOperand) { return Code.StringOp(nTarget, nLeftOperand, nRightOperand, operation); } public boolean equals(Object o) { if (o instanceof StringOp) { StringOp setop = (StringOp) o; return operation.equals(setop.operation) && super.equals(o); } return false; } public String toString() { return operation + " %" + target + " = %" + leftOperand + ", %" + rightOperand + " : " + type; } } /** * Reads the string value from a source operand register, and the integer * values from two index operand registers, computes the substring and * writes the result back to a target register. * * @author David J. Pearce * */ public static final class SubString extends AbstractNaryAssignable { private SubString(int target, int[] operands) { super(Type.T_STRING, target, operands); } @Override public final Code clone(int nTarget, int[] nOperands) { return Code.SubString(nTarget, nOperands); } public boolean equals(Object o) { return o instanceof SubString && super.equals(o); } public String toString() { return "substr %" + target + " = %" + operands[0] + ", %" + operands[1] + ", %" + operands[2] + " : " + type; } } /** * Performs a multi-way branch based on the value contained in the operand * register. A <i>dispatch table</i> is provided which maps individual * matched values to their destination labels. For example, the following * Whiley code: * * <pre> * string f(int x): * switch x: * case 1: * return "ONE" * case 2: * return "TWO" * default: * return "OTHER" * </pre> * * translates into the following WYIL code: * * <pre> * string f(int x): * body: * switch %0 1->blklab1, 2->blklab2, *->blklab3 * .blklab1 * const %1 = "ONE" : string * return %1 : string * .blklab2 * const %1 = "TWO" : string * return %1 : string * .blklab3 * const %1 = "OTHER" : string * return %1 : string * </pre> * * Here, we see how e.g. value <code>1</code> is mapped to the label * <code>blklab1</code>. Thus, if the operand register <code>%0</code> * contains value <code>1</code>, then control will be transferred to that * label. The final mapping <code>*->blklab3</code> covers the default case * where the value in the operand is not otherwise matched. * * @author David J. Pearce * */ public static final class Switch extends Code { public final Type type; public final int operand; public final ArrayList<Pair<Value, String>> branches; public final String defaultTarget; Switch(Type type, int operand, String defaultTarget, Collection<Pair<Value, String>> branches) { this.type = type; this.operand = operand; this.branches = new ArrayList<Pair<Value, String>>(branches); this.defaultTarget = defaultTarget; } public Switch relabel(Map<String, String> labels) { ArrayList<Pair<Value, String>> nbranches = new ArrayList(); for (Pair<Value, String> p : branches) { String nlabel = labels.get(p.second()); if (nlabel == null) { nbranches.add(p); } else { nbranches.add(new Pair(p.first(), nlabel)); } } String nlabel = labels.get(defaultTarget); if (nlabel == null) { return Code.Switch(type, operand, defaultTarget, nbranches); } else { return Code.Switch(type, operand, nlabel, nbranches); } } public int hashCode() { return type.hashCode() + operand + defaultTarget.hashCode() + branches.hashCode(); } public boolean equals(Object o) { if (o instanceof Switch) { Switch ig = (Switch) o; return operand == ig.operand && defaultTarget.equals(ig.defaultTarget) && branches.equals(ig.branches) && type.equals(ig.type); } return false; } public String toString() { String table = ""; boolean firstTime = true; for (Pair<Value, String> p : branches) { if (!firstTime) { table += ", "; } firstTime = false; table += p.first() + "->" + p.second(); } table += ", *->" + defaultTarget; return "switch %" + operand + " " + table; } @Override public void registers(java.util.Set<Integer> registers) { registers.add(operand); } @Override public Code remap(Map<Integer, Integer> binding) { Integer nOperand = binding.get(operand); if (nOperand != null) { return new Return(type, nOperand); } return this; } } public static final class Send extends AbstractNaryAssignable<Type.Message> { public final boolean synchronous; public final NameID name; private Send(Type.Message type, int target, int[] operands, NameID name, boolean synchronous) { super(type, target, operands); this.name = name; this.synchronous = synchronous; } @Override public Code clone(int nTarget, int[] nOperands) { return Send(type, nTarget, nOperands, name, synchronous); } public boolean equals(Object o) { if (o instanceof Send) { Send i = (Send) o; return synchronous == i.synchronous && type.equals(i.type) && name.equals(i.name) && super.equals(o); } return false; } public String toString() { if (synchronous) { if (target != Code.NULL_REG) { return "send " + target + " " + toString(operands) + " : " + type; } else { return "vsend" + toString(operands) + " : " + type; } } else { return "asend" + toString(operands) + " : " + type; } } } /** * Throws an exception containing the value in the given operand register. * For example, the following Whiley Code: * * <pre> * int f(int x) throws string: * if x < 0: * throw "ERROR" * else: * return 1 * </pre> * * translates into the following WYIL code: * * <pre> * int f(int x) throws string: * body: * const %1 = 0 : int * ifge %0, %1 goto blklab0 : int * const %1 = "ERROR" : string * throw %1 : string * .blklab0 * const %1 = 1 : int * return %1 : int * </pre> * * Here, we see an exception containing a <code>string</code> value will be * thrown when the parameter <code>x</code> is negative. * * @author David J. Pearce * */ public static final class Throw extends AbstractUnaryOp<Type> { private Throw(Type type, int operand) { super(type, operand); } @Override public Code clone(int nOperand) { return Code.Throw(type, nOperand); } public boolean equals(Object o) { if (o instanceof Throw) { return super.equals(o); } return false; } public String toString() { return "throw %" + operand + " : " + type; } } public static final class TryCatch extends Code { public final int operand; public final String label; public final ArrayList<Pair<Type, String>> catches; TryCatch(int operand, String label, Collection<Pair<Type, String>> catches) { this.operand = operand; this.catches = new ArrayList<Pair<Type, String>>(catches); this.label = label; } @Override public void registers(java.util.Set<Integer> registers) { registers.add(operand); } @Override public Code remap(Map<Integer, Integer> binding) { Integer nOperand = binding.get(operand); if (nOperand != null) { return Code.TryCatch(nOperand, label, catches); } return this; } public TryCatch relabel(Map<String, String> labels) { ArrayList<Pair<Type, String>> nbranches = new ArrayList(); for (Pair<Type, String> p : catches) { String nlabel = labels.get(p.second()); if (nlabel == null) { nbranches.add(p); } else { nbranches.add(new Pair(p.first(), nlabel)); } } String ntarget = labels.get(label); if (ntarget != null) { return TryCatch(operand, ntarget, nbranches); } else { return TryCatch(operand, label, nbranches); } } public int hashCode() { return operand + label.hashCode() + catches.hashCode(); } public boolean equals(Object o) { if (o instanceof TryCatch) { TryCatch ig = (TryCatch) o; return operand == ig.operand && label.equals(ig.label) && catches.equals(ig.catches); } return false; } public String toString() { String table = ""; boolean firstTime = true; for (Pair<Type, String> p : catches) { if (!firstTime) { table += ", "; } firstTime = false; table += p.first() + "->" + p.second(); } return "trycatch " + table; } } /** * Marks the end of a try-catch block. * * @author David J. Pearce * */ public static final class TryEnd extends Label { TryEnd(String label) { super(label); } public TryEnd relabel(Map<String, String> labels) { String nlabel = labels.get(label); if (nlabel == null) { return this; } else { return TryEnd(nlabel); } } public int hashCode() { return label.hashCode(); } public boolean equals(Object o) { if (o instanceof TryEnd) { TryEnd e = (TryEnd) o; return e.label.equals(label); } return false; } public String toString() { return "tryend " + label; } } /** * Read a number (int or real) from the operand register, negates it and * writes the result to the target register. For example, the following * Whiley code: * * <pre> * int f(int x): * return -x * </pre> * * translates into the following WYIL: * * <pre> * int f(int x): * body: * neg %0 = %0 : int * return %0 : int * </pre> * * This simply reads the parameter <code>x</code> stored in register * <code>%0</code>, negates it and then returns the negated value. * * @author David J. Pearce * */ public static final class Neg extends AbstractUnaryAssignable<Type> { private Neg(Type type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.Neg(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof Neg) { return super.equals(o); } return false; } public String toString() { return "neg %" + target + " = %" + operand + " : " + type; } } /** * Corresponds to a bitwise inversion operation, which reads a byte value * from the operand register, inverts it and writes the result to the target * resgister. For example, the following Whiley code: * * <pre> * byte f(byte x): * return ~x * </pre> * * translates into the following WYIL code: * * <pre> * byte f(byte x): * body: * invert %0 = %0 : byte * return %0 : byte * </pre> * * Here, the expression <code>~x</code> generates an <code>invert</code> * bytecode. * * @author David J. Pearce * */ public static final class Invert extends AbstractUnaryAssignable<Type> { private Invert(Type type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.Invert(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof Invert) { return super.equals(o); } return false; } public String toString() { return "invert %" + target + " = %" + operand + " : " + type; } } /** * Instantiate a new object from the value in a given operand register, and * write the result to a given target register. * * @author David J. Pearce * */ public static final class NewObject extends AbstractUnaryAssignable<Type.Reference> { private NewObject(Type.Reference type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.NewObject(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof NewObject) { return super.equals(o); } return false; } public String toString() { return "newobject %" + target + " = %" + operand + " : " + type; } } /** * Read a tuple value from the operand register, extract the value it * contains at a given index and write that to the target register. For * example, the following Whiley code: * * <pre> * int f(int,int tup): * return tup[0] * </pre> * * translates into the following WYIL code: * * <pre> * int f(int,int tup): * body: * tupleload %0 = %0 0 : int,int * return %0 : int * </pre> * * This simply reads the parameter <code>x</code> stored in register * <code>%0</code>, and returns the value stored at index <code>0</code>. * * @author David J. Pearce * */ public static final class TupleLoad extends AbstractUnaryAssignable<Type.EffectiveTuple> { public final int index; private TupleLoad(Type.EffectiveTuple type, int target, int operand, int index) { super(type, target, operand); this.index = index; } protected Code clone(int nTarget, int nOperand) { return Code.TupleLoad(type, nTarget, nOperand, index); } public boolean equals(Object o) { if (o instanceof TupleLoad) { TupleLoad i = (TupleLoad) o; return index == i.index && super.equals(o); } return false; } public String toString() { return "tupleload %" + target + " = %" + operand + " " + index + " : " + type; } } /** * Reads a reference value from the operand register, dereferences it (i.e. * extracts the value it refers to) and writes this to the target register. * * @author David J. Pearce * */ public static final class Dereference extends AbstractUnaryAssignable<Type.Reference> { private Dereference(Type.Reference type, int target, int operand) { super(type, target, operand); } protected Code clone(int nTarget, int nOperand) { return Code.Dereference(type, nTarget, nOperand); } public boolean equals(Object o) { if (o instanceof Dereference) { return super.equals(o); } return false; } public String toString() { return "deref %" + target + " = %" + operand + " : " + type; } } /** * The void bytecode is used to indicate that the given register(s) are no * longer live. This is useful for communicating information to the memory * management system about which values could in principle be collected. * * @author David J. Pearce * */ public static class Void extends AbstractNaryAssignable<Type> { private Void(Type type, int[] operands) { super(type, NULL_REG, operands); } protected Code clone(int nTarget, int[] nOperands) { return Code.Void(type, nOperands); } public boolean equals(Object o) { if (o instanceof Void) { return super.equals(o); } return false; } public String toString() { return "void " + toString(operands); } } private static String toString(int... operands) { String r = "("; for (int i = 0; i != operands.length; ++i) { if (i != 0) { r = r + ", "; } r = r + "%" + operands[i]; } return r + ")"; } private static int[] toIntArray(Collection<Integer> operands) { int[] ops = new int[operands.size()]; int i = 0; for (Integer o : operands) { ops[i++] = o; } return ops; } private static int[] remap(Map<Integer, Integer> binding, int[] operands) { int[] nOperands = operands; for (int i = 0; i != nOperands.length; ++i) { int o = operands[i]; Integer nOperand = binding.get(o); if (nOperand != null) { if (nOperands == operands) { nOperands = Arrays.copyOf(operands, operands.length); } nOperands[i] = nOperand; } } return nOperands; } private static final ArrayList<Code> values = new ArrayList<Code>(); private static final HashMap<Code, Integer> cache = new HashMap<Code, Integer>(); private static <T extends Code> T get(T type) { Integer idx = cache.get(type); if (idx != null) { return (T) values.get(idx); } else { cache.put(type, values.size()); values.add(type); return type; } } }
More documentation. Basically, almost done on that.
src/wyil/lang/Code.java
More documentation. Basically, almost done on that.
<ide><path>rc/wyil/lang/Code.java <ide> * return ((x * y) + 1) / 2 <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int f(int x, int y): <ide> * return x + 1 <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * real f(int x): <ide> * return |xs| + 1 <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int f(int x): <ide> * return x <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int f(int x): <ide> * debug "X = " + x <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * void f(int x): <ide> * return xs[i] <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int f([int] xs, int i): <ide> * return p.x + p.y <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int f({int x,int y} p): <ide> * return x <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int f(int x): <ide> * return 0 <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int f(int x, int y): <ide> * return x <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int f(int|[int] x): <ide> * return !x <ide> * </pre> <ide> * <del> * translates into the following WYIL: <add> * can be translated into the following WYIL: <ide> * <ide> * <pre> <ide> * bool f(bool x): <ide> * return r + 1 <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int g(int x, int y, int z): <ide> * return xs ++ ys <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * [int] f([int] xs, [int] ys): <ide> * return map[key] <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * string f({int->string} map, int key): <ide> * r = r + 1 <ide> * return r <ide> * </pre> <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <pre> <ide> * int f(): <ide> * body: <ide> * <pre> <ide> * {int->string} f(): <ide> * body: <del> * const %1 = 1 : int <del> * const %2 = "Hello" : string <del> * const %3 = 2 : int <del> * const %4 = "World" : string <add> * const %1 = 1 : int <add> * const %2 = "Hello" : string <add> * const %3 = 2 : int <add> * const %4 = "World" : string <ide> * newmap %0 = (%1, %2, %3, %4) : {int=>string} <del> * return %0 : {int=>string} <add> * return %0 : {int=>string} <ide> * </pre> <ide> * <ide> * <ide> * return {x: x, y: x} <ide> * </pre> <ide> * <del> * translates into the following WYIL: <add> * can be translated into the following WYIL: <ide> * <ide> * <pre> <ide> * {real x,real y} f(real x, real y): <ide> * return x,y <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * (int,int) f(int x, int y): <ide> * return {x,y,z} <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * [int] f(int x, int y, int z): <ide> * body: <del> * assign %4 = %0 : int <del> * assign %5 = %1 : int <del> * assign %6 = %2 : int <add> * assign %4 = %0 : int <add> * assign %5 = %1 : int <add> * assign %6 = %2 : int <ide> * newset %3 = (%4, %5, %6) : [int] <del> * return %3 : [int] <add> * return %3 : [int] <ide> * </pre> <ide> * <ide> * Writes the set value given by <code>{x,y,z}</code> into register <ide> * return [x,y,z] <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * [int] f(int x, int y, int z): <ide> * body: <del> * assign %4 = %0 : int <del> * assign %5 = %1 : int <del> * assign %6 = %2 : int <add> * assign %4 = %0 : int <add> * assign %5 = %1 : int <add> * assign %6 = %2 : int <ide> * newlist %3 = (%4, %5, %6) : [int] <del> * return %3 : [int] <add> * return %3 : [int] <ide> * </pre> <ide> * <ide> * Writes the list value given by <code>[x,y,z]</code> into register <ide> * return x + y <ide> * </pre> <ide> * <del> * translates into the following WYIL: <add> * can be translated into the following WYIL: <ide> * <ide> * <pre> <ide> * int f(int x, int y): <ide> * body: <del> * assign %3 = %0 : int <del> * assign %4 = %1 : int <del> * add %2 = % 3, %4 : int <del> * return %2 : int <add> * assign %3 = %0 : int <add> * assign %4 = %1 : int <add> * add %2 = % 3, %4 : int <add> * return %2 : int <ide> * </pre> <ide> * <ide> * Here, the <ide> * return "OTHER" <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * string f(int x): <ide> * return 1 <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int f(int x) throws string: <ide> } <ide> } <ide> <add> /** <add> * Represents a try-catch block within which specified exceptions will <add> * caught and processed within a handler. For example, the following Whiley <add> * code: <add> * <add> * <pre> <add> * int f(int x) throws Error: <add> * ... <add> * <add> * int g(int x): <add> * try: <add> * x = f(x) <add> * catch(Error e): <add> * return 0 <add> * </pre> <add> * <add> * can be translated into the following WYIL code: <add> * <add> * <pre> <add> * int f(int x): <add> * body: <add> * ... <add> * <add> * int g(int x): <add> * body: <add> * trycatch Error -> lab2 <add> * assign %3 = %0 : int <add> * invoke %0 = (%3) test:f : int(int) throws {string msg} <add> * return <add> * .lab2 <add> * const %3 = 0 : int <add> * return %3 : int <add> * </pre> <add> * <add> * Here, we see that within the try-catch block control is transferred to <add> * <code>lab2</code> if an exception of type <code>Error</code> is thrown. <add> * <add> * @author David J. Pearce <add> * <add> */ <ide> public static final class TryCatch extends Code { <ide> public final int operand; <ide> public final String label; <ide> * return -x <ide> * </pre> <ide> * <del> * translates into the following WYIL: <add> * can be translated into the following WYIL: <ide> * <ide> * <pre> <ide> * int f(int x): <ide> * return ~x <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * byte f(byte x): <ide> <ide> /** <ide> * Instantiate a new object from the value in a given operand register, and <del> * write the result to a given target register. <add> * write the result (a reference to that object) to a given target register. <add> * For example, the following Whiley code: <add> * <add> * <pre> <add> * define PointObj as ref {real x, real y} <add> * <add> * PointObj f(real x, real y): <add> * return new {x: x, y: y} <add> * </pre> <add> * <add> * can be translated into the following WYIL code: <add> * <add> * <pre> <add> * ref {real x,real y} f(int x, int y): <add> * body: <add> * newrecord %2 = (%0, %1) : {real x,real y} <add> * newobject %2 = %2 : ref {real x,real y} <add> * return %2 : ref {real x,real y} <add> * </pre> <add> * <add> * <b>NOTE:</b> objects are unlike other data types in WYIL, in that they <add> * represent mutable state allocated on a heap. Thus, changes to an object <add> * within a method are visible to those outside of the method. <ide> * <ide> * @author David J. Pearce <ide> * <ide> * return tup[0] <ide> * </pre> <ide> * <del> * translates into the following WYIL code: <add> * can be translated into the following WYIL code: <ide> * <ide> * <pre> <ide> * int f(int,int tup):
Java
apache-2.0
89ce193228e5fae2341de69276af5a739cf1cc86
0
ouzman/frisbee,gdg-x/frisbee,PareshMayani/frisbee,Splaktar/frisbee,PareshMayani/frisbee,gdg-x/frisbee,gdg-x/frisbee,PareshMayani/frisbee,fnk0/frisbee,Splaktar/frisbee,ouzman/frisbee,fnk0/frisbee,ouzman/frisbee
/* * Copyright 2013-2015 The GDG Frisbee Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gdg.frisbee.android.onboarding; import android.os.Bundle; import android.support.annotation.StringRes; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.Filter; import android.widget.Toast; import android.widget.ViewSwitcher; import org.gdg.frisbee.android.Const; import org.gdg.frisbee.android.R; import org.gdg.frisbee.android.api.Callback; import org.gdg.frisbee.android.api.model.Chapter; import org.gdg.frisbee.android.api.model.Directory; import org.gdg.frisbee.android.app.App; import org.gdg.frisbee.android.cache.ModelCache; import org.gdg.frisbee.android.chapter.ChapterAdapter; import org.gdg.frisbee.android.chapter.ChapterComparator; import org.gdg.frisbee.android.common.BaseFragment; import org.gdg.frisbee.android.utils.PrefUtils; import org.gdg.frisbee.android.view.AutoCompleteSpinnerView; import org.gdg.frisbee.android.view.BaseTextWatcher; import org.gdg.frisbee.android.view.ColoredSnackBar; import org.joda.time.DateTime; import java.util.Collections; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; public class FirstStartStep1Fragment extends BaseFragment { private static final String ARG_SELECTED_CHAPTER = "selected_chapter"; @Bind(R.id.chapter_spinner) AutoCompleteSpinnerView mChapterSpinnerView; @Bind(R.id.chapter_spinner_text_input_layout) TextInputLayout mChapterSpinnerTextInputLayout; @Bind(R.id.confirm) Button mConfirmButton; @Bind(R.id.viewSwitcher) ViewSwitcher mLoadSwitcher; private ChapterAdapter mChapterAdapter; private Chapter mSelectedChapter; private ChapterComparator mLocationComparator; private final TextWatcher disableConfirmAfterTextChanged = new BaseTextWatcher() { @Override public void afterTextChanged(Editable s) { mConfirmButton.setEnabled(false); } }; @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mChapterAdapter != null && mChapterAdapter.getCount() > 0) { outState.putParcelable(ARG_SELECTED_CHAPTER, mSelectedChapter); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mLocationComparator = new ChapterComparator(PrefUtils.getHomeChapterId(getActivity()), App.getInstance().getLastLocation()); mChapterAdapter = new ChapterAdapter(getActivity(), R.layout.spinner_item_welcome); mChapterAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item); if (savedInstanceState != null) { mSelectedChapter = savedInstanceState.getParcelable(ARG_SELECTED_CHAPTER); } App.getInstance().getModelCache().getAsync( Const.CACHE_KEY_CHAPTER_LIST_HUB, new ModelCache.CacheListener() { @Override public void onGet(Object item) { Directory directory = (Directory) item; addChapters(directory.getGroups()); mLoadSwitcher.setDisplayedChild(1); } @Override public void onNotFound(String key) { fetchChapters(); } } ); mChapterSpinnerView.setThreshold(1); Filter.FilterListener enableConfirmOnUniqueFilterResult = new Filter.FilterListener() { @Override public void onFilterComplete(int count) { mConfirmButton.setEnabled(count == 1); if (count == 1) { mSelectedChapter = mChapterAdapter.getItem(0); updateAutoCompleteHint(mSelectedChapter); } else { resetAutoCompleteHint(); } } }; AdapterView.OnItemClickListener enableConfirmOnChapterClick = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mSelectedChapter = mChapterAdapter.getItem(position); mConfirmButton.setEnabled(true); resetAutoCompleteHint(); } }; mChapterSpinnerView.setFilterCompletionListener(enableConfirmOnUniqueFilterResult); mChapterSpinnerView.setOnItemClickListener(enableConfirmOnChapterClick); mChapterSpinnerView.addTextChangedListener(disableConfirmAfterTextChanged); mChapterSpinnerView.setOnTouchListener(new ChapterSpinnerTouchListener()); mConfirmButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { if (getActivity() instanceof Step1Listener) { ((Step1Listener) getActivity()).onConfirmedChapter(mSelectedChapter); } } } ); } private void updateAutoCompleteHint(Chapter selectedChapter) { if (mChapterSpinnerView.getText().toString().equals(selectedChapter.toString())) { resetAutoCompleteHint(); } else { mChapterSpinnerTextInputLayout.setHint(getString(R.string.home_gdg_with_city, selectedChapter.toString())); } } private void resetAutoCompleteHint() { mChapterSpinnerTextInputLayout.setHint(getString(R.string.home_gdg)); } private void fetchChapters() { App.getInstance().getGdgXHub().getDirectory().enqueue(new Callback<Directory>() { @Override public void success(Directory directory) { if (isContextValid()) { addChapters(directory.getGroups()); mLoadSwitcher.setDisplayedChild(1); } App.getInstance().getModelCache().putAsync(Const.CACHE_KEY_CHAPTER_LIST_HUB, directory, DateTime.now().plusDays(4), null); } @Override public void failure(Throwable error) { showError(R.string.fetch_chapters_failed); } @Override public void networkFailure(Throwable error) { showError(R.string.offline_alert); } }); } @Override protected void showError(@StringRes int errorStringRes) { if (isContextValid()) { if (getView() != null) { Snackbar snackbar = Snackbar.make(getView(), errorStringRes, Snackbar.LENGTH_INDEFINITE); snackbar.setAction("Retry", new View.OnClickListener() { @Override public void onClick(View v) { fetchChapters(); } }); ColoredSnackBar.alert(snackbar).show(); } else { Toast.makeText(getActivity(), errorStringRes, Toast.LENGTH_SHORT).show(); } } } private void addChapters(List<Chapter> chapterList) { Collections.sort(chapterList, mLocationComparator); mChapterAdapter.clear(); mChapterAdapter.addAll(chapterList); mChapterSpinnerView.setAdapter(mChapterAdapter); if (mSelectedChapter == null) { //if the location is available, select the first chapter by default. if (App.getInstance().getLastLocation() != null && chapterList.size() > 0) { mSelectedChapter = chapterList.get(0); } } if (mSelectedChapter != null) { mChapterSpinnerView.setText(mSelectedChapter.toString(), true); } else { mChapterSpinnerView.showDropDown(); mConfirmButton.setEnabled(false); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_welcome_step1, container, false); ButterKnife.bind(this, v); return v; } public interface Step1Listener { void onConfirmedChapter(Chapter chapter); } private class ChapterSpinnerTouchListener implements View.OnTouchListener { @Override public boolean onTouch(View v, MotionEvent event) { final int drawableRight = 2; if (event.getAction() == MotionEvent.ACTION_UP) { if (event.getRawX() >= (mChapterSpinnerView.getRight() - mChapterSpinnerView.getCompoundDrawables()[drawableRight].getBounds().width())) { mChapterSpinnerView.showDropDown(); return true; } } return false; } } }
app/src/main/java/org/gdg/frisbee/android/onboarding/FirstStartStep1Fragment.java
/* * Copyright 2013-2015 The GDG Frisbee Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gdg.frisbee.android.onboarding; import android.os.Bundle; import android.support.annotation.StringRes; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputLayout; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.Filter; import android.widget.Toast; import android.widget.ViewSwitcher; import org.gdg.frisbee.android.Const; import org.gdg.frisbee.android.R; import org.gdg.frisbee.android.api.Callback; import org.gdg.frisbee.android.api.model.Chapter; import org.gdg.frisbee.android.api.model.Directory; import org.gdg.frisbee.android.app.App; import org.gdg.frisbee.android.cache.ModelCache; import org.gdg.frisbee.android.chapter.ChapterAdapter; import org.gdg.frisbee.android.chapter.ChapterComparator; import org.gdg.frisbee.android.common.BaseFragment; import org.gdg.frisbee.android.utils.PrefUtils; import org.gdg.frisbee.android.view.AutoCompleteSpinnerView; import org.gdg.frisbee.android.view.BaseTextWatcher; import org.gdg.frisbee.android.view.ColoredSnackBar; import org.joda.time.DateTime; import java.util.Collections; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; public class FirstStartStep1Fragment extends BaseFragment { private static final String ARG_SELECTED_CHAPTER = "selected_chapter"; @Bind(R.id.chapter_spinner) AutoCompleteSpinnerView mChapterSpinnerView; @Bind(R.id.chapter_spinner_text_input_layout) TextInputLayout mChapterSpinnerTextInputLayout; @Bind(R.id.confirm) Button mConfirmButton; @Bind(R.id.viewSwitcher) ViewSwitcher mLoadSwitcher; private ChapterAdapter mChapterAdapter; private Chapter mSelectedChapter; private ChapterComparator mLocationComparator; private final TextWatcher disableConfirmAfterTextChanged = new BaseTextWatcher() { @Override public void afterTextChanged(Editable s) { mConfirmButton.setEnabled(false); } }; @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mChapterAdapter != null && mChapterAdapter.getCount() > 0) { outState.putParcelable(ARG_SELECTED_CHAPTER, mSelectedChapter); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mLocationComparator = new ChapterComparator(PrefUtils.getHomeChapterId(getActivity()), App.getInstance().getLastLocation()); mChapterAdapter = new ChapterAdapter(getActivity(), R.layout.spinner_item_welcome); mChapterAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item); if (savedInstanceState != null) { mSelectedChapter = savedInstanceState.getParcelable(ARG_SELECTED_CHAPTER); } App.getInstance().getModelCache().getAsync( Const.CACHE_KEY_CHAPTER_LIST_HUB, new ModelCache.CacheListener() { @Override public void onGet(Object item) { Directory directory = (Directory) item; addChapters(directory.getGroups()); mLoadSwitcher.setDisplayedChild(1); } @Override public void onNotFound(String key) { fetchChapters(); } } ); mChapterSpinnerView.setThreshold(1); Filter.FilterListener enableConfirmOnUniqueFilterResult = new Filter.FilterListener() { @Override public void onFilterComplete(int count) { mConfirmButton.setEnabled(count == 1); if (count == 1) { mSelectedChapter = mChapterAdapter.getItem(0); updateAutoCompleteHint(mSelectedChapter); } else { resetAutoCompleteHint(); } } }; AdapterView.OnItemClickListener enableConfirmOnChapterClick = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mSelectedChapter = mChapterAdapter.getItem(position); mConfirmButton.setEnabled(true); resetAutoCompleteHint(); } }; mChapterSpinnerView.setFilterCompletionListener(enableConfirmOnUniqueFilterResult); mChapterSpinnerView.setOnItemClickListener(enableConfirmOnChapterClick); mChapterSpinnerView.addTextChangedListener(disableConfirmAfterTextChanged); mChapterSpinnerView.setOnTouchListener(new ChapterSpinnerTouchListener()); mConfirmButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { if (getActivity() instanceof Step1Listener) { ((Step1Listener) getActivity()).onConfirmedChapter(mSelectedChapter); } } } ); } private void updateAutoCompleteHint(Chapter selectedChapter) { if (mChapterSpinnerView.getText().toString().equals(selectedChapter.toString())) { resetAutoCompleteHint(); } else { mChapterSpinnerTextInputLayout.setHint(getString(R.string.home_gdg_with_city, selectedChapter.toString())); } } private void resetAutoCompleteHint() { mChapterSpinnerTextInputLayout.setHint(getString(R.string.home_gdg)); } private void fetchChapters() { App.getInstance().getGdgXHub().getDirectory().enqueue(new Callback<Directory>() { @Override public void success(Directory directory) { if (isContextValid()) { addChapters(directory.getGroups()); mLoadSwitcher.setDisplayedChild(1); } App.getInstance().getModelCache().putAsync(Const.CACHE_KEY_CHAPTER_LIST_HUB, directory, DateTime.now().plusDays(4), null); } @Override public void failure(Throwable error) { showError(R.string.fetch_chapters_failed); } @Override public void networkFailure(Throwable error) { showError(R.string.offline_alert); } }); } @Override protected void showError(@StringRes int errorStringRes) { if (isContextValid()) { if (getView() != null) { Snackbar snackbar = Snackbar.make(getView(), errorStringRes, Snackbar.LENGTH_INDEFINITE); snackbar.setAction("Retry", new View.OnClickListener() { @Override public void onClick(View v) { fetchChapters(); } }); ColoredSnackBar.alert(snackbar).show(); } else { Toast.makeText(getActivity(), errorStringRes, Toast.LENGTH_SHORT).show(); } } } private void addChapters(List<Chapter> chapterList) { Collections.sort(chapterList, mLocationComparator); mChapterAdapter.clear(); mChapterAdapter.addAll(chapterList); mChapterSpinnerView.setAdapter(mChapterAdapter); if (mSelectedChapter == null) { //if the location is available, select the first chapter by default. if (App.getInstance().getLastLocation() != null && chapterList.size() > 0) { mSelectedChapter = chapterList.get(0); } } if (mSelectedChapter != null) { mChapterSpinnerView.setText(mSelectedChapter.toString(), true); } else { mChapterSpinnerView.showDropDown(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_welcome_step1, container, false); ButterKnife.bind(this, v); return v; } public interface Step1Listener { void onConfirmedChapter(Chapter chapter); } private class ChapterSpinnerTouchListener implements View.OnTouchListener { @Override public boolean onTouch(View v, MotionEvent event) { final int drawableRight = 2; if (event.getAction() == MotionEvent.ACTION_UP) { if (event.getRawX() >= (mChapterSpinnerView.getRight() - mChapterSpinnerView.getCompoundDrawables()[drawableRight].getBounds().width())) { mChapterSpinnerView.showDropDown(); return true; } } return false; } } }
fix NPE by disabling the confirm button when location not available on startup
app/src/main/java/org/gdg/frisbee/android/onboarding/FirstStartStep1Fragment.java
fix NPE by disabling the confirm button when location not available on startup
<ide><path>pp/src/main/java/org/gdg/frisbee/android/onboarding/FirstStartStep1Fragment.java <ide> mChapterSpinnerView.setText(mSelectedChapter.toString(), true); <ide> } else { <ide> mChapterSpinnerView.showDropDown(); <add> mConfirmButton.setEnabled(false); <ide> } <ide> } <ide>
Java
apache-2.0
0be6d1b35444ba4d7e10bf2d51d5fbeb5bc62661
0
smkniazi/HDFS-Distributed-BenchMark,smkniazi/hammer-bench,smkniazi/hammer-bench,smkniazi/HDFS-Distributed-BenchMark
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.hops.experiments.benchmarks.blockreporting; import com.google.common.collect.Lists; import io.hops.experiments.benchmarks.common.BenchMarkFileSystemName; import io.hops.experiments.benchmarks.common.Benchmark; import io.hops.experiments.controller.Logger; import io.hops.experiments.controller.commands.BenchmarkCommand; import io.hops.experiments.controller.commands.WarmUpCommand; import io.hops.experiments.utils.BenchmarkUtils; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.Time; import java.io.IOException; import java.util.List; import java.util.Random; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class BlockReportingBenchmark extends Benchmark { private static final Random rand = new Random(UUID.randomUUID().getLeastSignificantBits()); private long startTime; private AtomicInteger successfulOps = new AtomicInteger(0); private AtomicInteger failedOps = new AtomicInteger(0); private DescriptiveStatistics getNewNameNodeElapsedTime = new DescriptiveStatistics(); private DescriptiveStatistics brElapsedTimes = new DescriptiveStatistics(); private TinyDatanodes datanodes; private final int slaveId; private final BenchMarkFileSystemName fsName; public BlockReportingBenchmark(Configuration conf, int numThreads, int slaveID, BenchMarkFileSystemName fsName) { super(conf, numThreads,fsName); this.slaveId = slaveID; this.fsName = fsName; } @Override protected WarmUpCommand.Response warmUp(WarmUpCommand.Request warmUp) throws Exception { try{ BlockReportingWarmUp.Request request = (BlockReportingWarmUp.Request) warmUp; datanodes = new TinyDatanodes(conf, request.getBaseDir(), numThreads, request.getBlocksPerReport(), request.getBlocksPerFile(), request.getFilesPerDir(), request.getReplication(), request.getMaxBlockSize(), slaveId, request .getDatabaseConnection(), fsName); long t = Time.now(); datanodes.generateInput(request.isSkipCreations(), executor); Logger.printMsg("WarmUp done in " + (Time.now() - t) / 1000 + " seconds"); }catch(Exception e){ Logger.error(e); throw e; } return new BlockReportingWarmUp.Response(); } @Override protected BenchmarkCommand.Response processCommandInternal( BenchmarkCommand.Request command) throws IOException, InterruptedException { BlockReportingBenchmarkCommand.Request request = (BlockReportingBenchmarkCommand.Request) command; List workers = Lists.newArrayList(); for (int dn = 0; dn < numThreads; dn++) { workers.add(new Reporter(dn, request .getMinTimeBeforeNextReport(), request.getMaxTimeBeforeNextReport())); } startTime = Time.now(); executor.invokeAll(workers, request.getBlockReportBenchMarkDuration(), TimeUnit.MILLISECONDS); double speed = currentSpeed(); datanodes.printStats(); return new BlockReportingBenchmarkCommand.Response(successfulOps.get(), failedOps.get(), speed, brElapsedTimes.getMean(), getNewNameNodeElapsedTime.getMean(),getAliveNNsCount()); } private class Reporter implements Callable { private final int dnIdx; private final int minTimeBeforeNextReport; private final int maxTimeBeforeNextReport; public Reporter(int dnIdx, int minTimeBeforeNextReport, int maxTimeBeforeNextReport) { this.dnIdx = dnIdx; this.minTimeBeforeNextReport = minTimeBeforeNextReport; this.maxTimeBeforeNextReport = maxTimeBeforeNextReport; } @Override public Object call() throws Exception { while (true) { try { if (minTimeBeforeNextReport > 0 && maxTimeBeforeNextReport > 0) { long sleep = minTimeBeforeNextReport + rand.nextInt(maxTimeBeforeNextReport - minTimeBeforeNextReport); Thread.sleep(sleep); } long[] ts = datanodes.executeOp(dnIdx); successfulOps.incrementAndGet(); getNewNameNodeElapsedTime.addValue(ts[0]); brElapsedTimes.addValue(ts[1]); if (Logger.canILog()) { Logger.printMsg("Successful Rpts: " + successfulOps.get() + ", Failed Rpts: " + failedOps.get() + ", Speed: " + currentSpeed() + " ops/sec, Select NN for Rpt [Avg,Min,Max]: [" +BenchmarkUtils.round(getNewNameNodeElapsedTime.getMean())+", " +BenchmarkUtils.round(getNewNameNodeElapsedTime.getMin())+", " +BenchmarkUtils.round(getNewNameNodeElapsedTime.getMax())+"] " +" Blk Rept [Avg,Min,Max]: ["+ +BenchmarkUtils.round(brElapsedTimes.getMean())+", " +BenchmarkUtils.round(brElapsedTimes.getMin())+", " +BenchmarkUtils.round(brElapsedTimes.getMax())+"]" ); } } catch (Exception e) { failedOps.incrementAndGet(); System.out.println(e); Logger.error(e); } } } } double currentSpeed() { double timePassed = Time.now() - startTime; double opsPerMSec = (double) (successfulOps.get()) / timePassed; return BenchmarkUtils.round(opsPerMSec * 1000); } }
src/main/java/io/hops/experiments/benchmarks/blockreporting/BlockReportingBenchmark.java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.hops.experiments.benchmarks.blockreporting; import com.google.common.collect.Lists; import io.hops.experiments.benchmarks.common.BenchMarkFileSystemName; import io.hops.experiments.benchmarks.common.Benchmark; import io.hops.experiments.controller.Logger; import io.hops.experiments.controller.commands.BenchmarkCommand; import io.hops.experiments.controller.commands.WarmUpCommand; import io.hops.experiments.utils.BenchmarkUtils; import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.util.Time; import java.io.IOException; import java.util.List; import java.util.Random; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class BlockReportingBenchmark extends Benchmark { private static final Random rand = new Random(UUID.randomUUID().getLeastSignificantBits()); private long startTime; private AtomicInteger successfulOps = new AtomicInteger(0); private AtomicInteger failedOps = new AtomicInteger(0); private DescriptiveStatistics getNewNameNodeElapsedTime = new DescriptiveStatistics(); private DescriptiveStatistics brElapsedTimes = new DescriptiveStatistics(); private TinyDatanodes datanodes; private final int slaveId; private final BenchMarkFileSystemName fsName; public BlockReportingBenchmark(Configuration conf, int numThreads, int slaveID, BenchMarkFileSystemName fsName) { super(conf, numThreads,fsName); this.slaveId = slaveID; this.fsName = fsName; } @Override protected WarmUpCommand.Response warmUp(WarmUpCommand.Request warmUp) throws Exception { try{ BlockReportingWarmUp.Request request = (BlockReportingWarmUp.Request) warmUp; datanodes = new TinyDatanodes(conf, request.getBaseDir(), numThreads, request.getBlocksPerReport(), request.getBlocksPerFile(), request.getFilesPerDir(), request.getReplication(), request.getMaxBlockSize(), slaveId, request .getDatabaseConnection(), fsName); long t = Time.now(); datanodes.generateInput(request.isSkipCreations(), executor); Logger.printMsg("WarmUp done in " + (Time.now() - t) / 1000 + " seconds"); }catch(Exception e){ Logger.error(e); throw e; } return new BlockReportingWarmUp.Response(); } @Override protected BenchmarkCommand.Response processCommandInternal( BenchmarkCommand.Request command) throws IOException, InterruptedException { BlockReportingBenchmarkCommand.Request request = (BlockReportingBenchmarkCommand.Request) command; List workers = Lists.newArrayList(); for (int dn = 0; dn < numThreads; dn++) { workers.add(new Reporter(dn, request .getMinTimeBeforeNextReport(), request.getMaxTimeBeforeNextReport())); } startTime = Time.now(); executor.invokeAll(workers, request.getBlockReportBenchMarkDuration(), TimeUnit.MILLISECONDS); double speed = currentSpeed(); datanodes.printStats(); return new BlockReportingBenchmarkCommand.Response(successfulOps.get(), failedOps.get(), speed, brElapsedTimes.getMean(), getNewNameNodeElapsedTime.getMean(),getAliveNNsCount()); } private class Reporter implements Callable { private final int dnIdx; private final int minTimeBeforeNextReport; private final int maxTimeBeforeNextReport; public Reporter(int dnIdx, int minTimeBeforeNextReport, int maxTimeBeforeNextReport) { this.dnIdx = dnIdx; this.minTimeBeforeNextReport = minTimeBeforeNextReport; this.maxTimeBeforeNextReport = maxTimeBeforeNextReport; } @Override public Object call() throws Exception { while (true) { try { if (minTimeBeforeNextReport > 0 && maxTimeBeforeNextReport > 0) { long sleep = minTimeBeforeNextReport + rand.nextInt(maxTimeBeforeNextReport - minTimeBeforeNextReport); Thread.sleep(sleep); } long[] ts = datanodes.executeOp(dnIdx); successfulOps.incrementAndGet(); getNewNameNodeElapsedTime.addValue(ts[0]); brElapsedTimes.addValue(ts[1]); if (Logger.canILog()) { Logger.printMsg("Successful Rpts: " + successfulOps.get() + ", Failed Rpts: " + failedOps.get() + ", Speed: " + currentSpeed() + " ops/sec, Select NN for Rpt [Avg,Min,Max]: [" +BenchmarkUtils.round(getNewNameNodeElapsedTime.getMean())+", " +BenchmarkUtils.round(getNewNameNodeElapsedTime.getMin())+", " +BenchmarkUtils.round(getNewNameNodeElapsedTime.getMax())+"] " +" Blk Rept [Avg,Min,Max]: ["+ +BenchmarkUtils.round(brElapsedTimes.getMean())+", " +BenchmarkUtils.round(brElapsedTimes.getMin())+", " +BenchmarkUtils.round(brElapsedTimes.getMax())+"]" ); } } catch (Exception e) { failedOps.incrementAndGet(); Logger.error(e); } } } } double currentSpeed() { double timePassed = Time.now() - startTime; double opsPerMSec = (double) (successfulOps.get()) / timePassed; return BenchmarkUtils.round(opsPerMSec * 1000); } }
updates
src/main/java/io/hops/experiments/benchmarks/blockreporting/BlockReportingBenchmark.java
updates
<ide><path>rc/main/java/io/hops/experiments/benchmarks/blockreporting/BlockReportingBenchmark.java <ide> } <ide> } catch (Exception e) { <ide> failedOps.incrementAndGet(); <add> System.out.println(e); <ide> Logger.error(e); <ide> } <ide> }
Java
apache-2.0
d11d984705af3ec5aadd068ce059a4aaae31dbd8
0
Hipparchus-Math/hipparchus,apache/commons-math,Hipparchus-Math/hipparchus,apache/commons-math,sdinot/hipparchus,Hipparchus-Math/hipparchus,apache/commons-math,apache/commons-math,Hipparchus-Math/hipparchus,sdinot/hipparchus,sdinot/hipparchus,sdinot/hipparchus
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.optimization.linear; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.math.linear.RealMatrix; import org.apache.commons.math.linear.RealMatrixImpl; import org.apache.commons.math.linear.RealVector; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.RealPointValuePair; /** * A tableau for use in the Simplex method. * * <p> * Example: * <pre> * W | Z | x1 | x2 | x- | s1 | s2 | a1 | RHS * --------------------------------------------------- * -1 0 0 0 0 0 0 1 0 &lt;= phase 1 objective * 0 1 -15 -10 0 0 0 0 0 &lt;= phase 2 objective * 0 0 1 0 0 1 0 0 2 &lt;= constraint 1 * 0 0 0 1 0 0 1 0 3 &lt;= constraint 2 * 0 0 1 1 0 0 0 1 4 &lt;= constraint 3 * </pre> * W: Phase 1 objective function</br> * Z: Phase 2 objective function</br> * x1 &amp; x2: Decision variables</br> * x-: Extra decision variable to allow for negative values</br> * s1 &amp; s2: Slack/Surplus variables</br> * a1: Artificial variable</br> * RHS: Right hand side</br> * </p> * @version $Revision$ $Date$ * @since 2.0 */ class SimplexTableau implements Serializable { /** Serializable version identifier. */ private static final long serialVersionUID = -1369660067587938365L; /** Linear objective function. */ private final LinearObjectiveFunction f; /** Linear constraints. */ private final Collection<LinearConstraint> constraints; /** Whether to restrict the variables to non-negative values. */ private final boolean restrictToNonNegative; /** Simple tableau. */ protected RealMatrix tableau; /** Number of decision variables. */ protected final int numDecisionVariables; /** Number of slack variables. */ protected final int numSlackVariables; /** Number of artificial variables. */ protected int numArtificialVariables; /** * Build a tableau for a linear problem. * @param f linear objective function * @param constraints linear constraints * @param goalType type of optimization goal: either {@link GoalType#MAXIMIZE} * or {@link GoalType#MINIMIZE} * @param restrictToNonNegative whether to restrict the variables to non-negative values */ SimplexTableau(final LinearObjectiveFunction f, final Collection<LinearConstraint> constraints, final GoalType goalType, final boolean restrictToNonNegative) { this.f = f; this.constraints = constraints; this.restrictToNonNegative = restrictToNonNegative; this.numDecisionVariables = getNumVariables() + (restrictToNonNegative ? 0 : 1); this.numSlackVariables = getConstraintTypeCounts(Relationship.LEQ) + getConstraintTypeCounts(Relationship.GEQ); this.numArtificialVariables = getConstraintTypeCounts(Relationship.EQ) + getConstraintTypeCounts(Relationship.GEQ); this.tableau = new RealMatrixImpl(createTableau(goalType == GoalType.MAXIMIZE)); initialize(); } /** * Create the tableau by itself. * @param maximize if true, goal is to maximize the objective function * @return created tableau */ protected double[][] createTableau(final boolean maximize) { // create a matrix of the correct size List<LinearConstraint> constraints = getNormalizedConstraints(); int width = numDecisionVariables + numSlackVariables + numArtificialVariables + getNumObjectiveFunctions() + 1; // + 1 is for RHS int height = constraints.size() + getNumObjectiveFunctions(); double[][] matrix = new double[height][width]; // initialize the objective function rows if (getNumObjectiveFunctions() == 2) { matrix[0][0] = -1; } int zIndex = (getNumObjectiveFunctions() == 1) ? 0 : 1; matrix[zIndex][zIndex] = maximize ? 1 : -1; RealVector objectiveCoefficients = maximize ? f.getCoefficients().mapMultiply(-1) : f.getCoefficients(); copyArray(objectiveCoefficients.getData(), matrix[zIndex], getNumObjectiveFunctions()); matrix[zIndex][width - 1] = maximize ? f.getConstantTerm() : -1 * f.getConstantTerm(); if (!restrictToNonNegative) { matrix[zIndex][getSlackVariableOffset() - 1] = getInvertedCoeffiecientSum(objectiveCoefficients); } // initialize the constraint rows int slackVar = 0; int artificialVar = 0; for (int i = 0; i < constraints.size(); i++) { LinearConstraint constraint = constraints.get(i); int row = getNumObjectiveFunctions() + i; // decision variable coefficients copyArray(constraint.getCoefficients().getData(), matrix[row], 1); // x- if (!restrictToNonNegative) { matrix[row][getSlackVariableOffset() - 1] = getInvertedCoeffiecientSum(constraint.getCoefficients()); } // RHS matrix[row][width - 1] = constraint.getValue(); // slack variables if (constraint.getRelationship() == Relationship.LEQ) { matrix[row][getSlackVariableOffset() + slackVar++] = 1; // slack } else if (constraint.getRelationship() == Relationship.GEQ) { matrix[row][getSlackVariableOffset() + slackVar++] = -1; // excess } // artificial variables if ((constraint.getRelationship() == Relationship.EQ) || (constraint.getRelationship() == Relationship.GEQ)) { matrix[0][getArtificialVariableOffset() + artificialVar] = 1; matrix[row][getArtificialVariableOffset() + artificialVar++] = 1; } } return matrix; } /** Get the number of variables. * @return number of variables */ public int getNumVariables() { return f.getCoefficients().getDimension(); } /** * Get new versions of the constraints which have positive right hand sides. * @return new versions of the constraints */ public List<LinearConstraint> getNormalizedConstraints() { List<LinearConstraint> normalized = new ArrayList<LinearConstraint>(); for (LinearConstraint constraint : constraints) { normalized.add(normalize(constraint)); } return normalized; } /** * Get a new equation equivalent to this one with a positive right hand side. * @param constraint reference constraint * @return new equation */ private LinearConstraint normalize(final LinearConstraint constraint) { if (constraint.getValue() < 0) { return new LinearConstraint(constraint.getCoefficients().mapMultiply(-1), constraint.getRelationship().oppositeRelationship(), -1 * constraint.getValue()); } return new LinearConstraint(constraint.getCoefficients(), constraint.getRelationship(), constraint.getValue()); } /** * Get the number of objective functions in this tableau. * @return 2 for Phase 1. 1 for Phase 2. */ protected final int getNumObjectiveFunctions() { return this.numArtificialVariables > 0 ? 2 : 1; } /** * Get a count of constraints corresponding to a specified relationship. * @param relationship relationship to count * @return number of constraint with the specified relationship */ private int getConstraintTypeCounts(final Relationship relationship) { int count = 0; for (final LinearConstraint constraint : constraints) { if (constraint.getRelationship() == relationship) { ++count; } } return count; } /** * Puts the tableau in proper form by zeroing out the artificial variables * in the objective function via elementary row operations. */ private void initialize() { for (int artificialVar = 0; artificialVar < numArtificialVariables; artificialVar++) { int row = getBasicRow(getArtificialVariableOffset() + artificialVar); subtractRow(0, row, 1.0); } } /** * Get the -1 times the sum of all coefficients in the given array. * @param coefficients coefficients to sum * @return the -1 times the sum of all coefficients in the given array. */ protected static double getInvertedCoeffiecientSum(final RealVector coefficients) { double sum = 0; for (double coefficient : coefficients.getData()) { sum -= coefficient; } return sum; } /** * Checks whether the given column is basic. * @param col index of the column to check * @return the row that the variable is basic in. null if the column is not basic */ private Integer getBasicRow(final int col) { Integer row = null; for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) { if (getEntry(i, col) != 0.0) { if (row == null) { row = i; } else { return null; } } } return row; } /** * Removes the phase 1 objective function and artificial variables from this tableau. */ protected void discardArtificialVariables() { if (numArtificialVariables == 0) { return; } int width = getWidth() - numArtificialVariables - 1; int height = getHeight() - 1; double[][] matrix = new double[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width - 1; j++) { matrix[i][j] = getEntry(i + 1, j + 1); } matrix[i][width - 1] = getEntry(i + 1, getRhsOffset()); } this.tableau = new RealMatrixImpl(matrix); this.numArtificialVariables = 0; } /** * @param src the source array * @param dest the destination array * @param destPos the destination position */ private void copyArray(final double[] src, final double[] dest, final int destPos) { System.arraycopy(src, 0, dest, getNumObjectiveFunctions(), src.length); } /** * Get the current solution. * <p> * {@link #solve} should be called first for this to be the optimal solution. * </p> * @return current solution */ protected RealPointValuePair getSolution() { double[] coefficients = new double[getOriginalNumDecisionVariables()]; double mostNegative = getDecisionVariableValue(getOriginalNumDecisionVariables()); for (int i = 0; i < coefficients.length; i++) { coefficients[i] = getDecisionVariableValue(i) - (restrictToNonNegative ? 0 : mostNegative); } return new RealPointValuePair(coefficients, f.getValue(coefficients)); } /** * Get the value of the given decision variable. This is not the actual * value as it is guaranteed to be >= 0 and thus must be corrected before * being returned to the user. * * @param decisionVariable The index of the decision variable * @return The value of the given decision variable. */ protected double getDecisionVariableValue(final int decisionVariable) { Integer basicRow = getBasicRow(getNumObjectiveFunctions() + decisionVariable); return basicRow == null ? 0 : getEntry(basicRow, getRhsOffset()); } /** * Subtracts a multiple of one row from another. * <p> * After application of this operation, the following will hold: * minuendRow = minuendRow - multiple * subtrahendRow * </p> * @param dividendRow index of the row * @param divisor value of the divisor */ protected void divideRow(final int dividendRow, final double divisor) { for (int j = 0; j < getWidth(); j++) { tableau.setEntry(dividendRow, j, tableau.getEntry(dividendRow, j) / divisor); } } /** * Subtracts a multiple of one row from another. * <p> * After application of this operation, the following will hold: * minuendRow = minuendRow - multiple * subtrahendRow * </p> * @param minuendRow row index * @param subtrahendRow row index * @param multiple multiplication factor */ protected void subtractRow(final int minuendRow, final int subtrahendRow, final double multiple) { for (int j = 0; j < getWidth(); j++) { tableau.setEntry(minuendRow, j, tableau.getEntry(minuendRow, j) - multiple * tableau.getEntry(subtrahendRow, j)); } } /** * Get the width of the tableau. * @return width of the tableau */ protected final int getWidth() { return tableau.getColumnDimension(); } /** * Get the height of the tableau. * @return height of the tableau */ protected final int getHeight() { return tableau.getRowDimension(); } /** Get an entry of the tableau. * @param row row index * @param column column index * @return entry at (row, column) */ protected final double getEntry(final int row, final int column) { return tableau.getEntry(row, column); } /** Set an entry of the tableau. * @param row row index * @param column column index * @param value for the entry */ protected final void setEntry(final int row, final int column, final double value) { tableau.setEntry(row, column, value); } /** * Get the offset of the first slack variable. * @return offset of the first slack variable */ protected final int getSlackVariableOffset() { return getNumObjectiveFunctions() + numDecisionVariables; } /** * Get the offset of the first artificial variable. * @return offset of the first artificial variable */ protected final int getArtificialVariableOffset() { return getNumObjectiveFunctions() + numDecisionVariables + numSlackVariables; } /** * Get the offset of the right hand side. * @return offset of the right hand side */ protected final int getRhsOffset() { return getWidth() - 1; } /** * Get the number of decision variables. * <p> * If variables are not restricted to positive values, this will include 1 * extra decision variable to represent the absolute value of the most * negative variable. * </p> * @return number of decision variables * @see #getOriginalNumDecisionVariables() */ protected final int getNumDecisionVariables() { return numDecisionVariables; } /** * Get the original number of decision variables. * @return original number of decision variables * @see #getNumDecisionVariables() */ protected final int getOriginalNumDecisionVariables() { return restrictToNonNegative ? numDecisionVariables : numDecisionVariables - 1; } /** * Get the number of slack variables. * @return number of slack variables */ protected final int getNumSlackVariables() { return numSlackVariables; } /** * Get the number of artificial variables. * @return number of artificial variables */ protected final int getNumArtificialVariables() { return numArtificialVariables; } /** * Get the tableau data. * @return tableau data */ protected final double[][] getData() { return tableau.getData(); } }
src/java/org/apache/commons/math/optimization/linear/SimplexTableau.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.optimization.linear; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.math.linear.RealMatrix; import org.apache.commons.math.linear.RealMatrixImpl; import org.apache.commons.math.linear.RealVector; import org.apache.commons.math.optimization.GoalType; import org.apache.commons.math.optimization.RealPointValuePair; /** * A tableau for use in the Simplex method. * * <p> * Example: * <pre> * W | Z | x1 | x2 | x- | s1 | s2 | a1 | RHS * --------------------------------------------------- * -1 0 0 0 0 0 0 1 0 &lt;= phase 1 objective * 0 1 -15 -10 0 0 0 0 0 &lt;= phase 2 objective * 0 0 1 0 0 1 0 0 2 &lt;= constraint 1 * 0 0 0 1 0 0 1 0 3 &lt;= constraint 2 * 0 0 1 1 0 0 0 1 4 &lt;= constraint 3 * </pre> * W: Phase 1 objective function</br> * Z: Phase 2 objective function</br> * x1 &amp; x2: Decision variables</br> * x-: Extra decision variable to allow for negative values</br> * s1 &amp; s2: Slack/Surplus variables</br> * a1: Artificial variable</br> * RHS: Right hand side</br> * </p> * @version $Revision$ $Date$ * @since 2.0 */ class SimplexTableau implements Serializable { /** Serializable version identifier. */ private static final long serialVersionUID = -1369660067587938365L; /** Linear objective function. */ private final LinearObjectiveFunction f; /** Linear constraints. */ private final Collection<LinearConstraint> constraints; /** Whether to restrict the variables to non-negative values. */ private final boolean restrictToNonNegative; /** Simple tableau. */ protected RealMatrix tableau; /** Number of decision variables. */ protected final int numDecisionVariables; /** Number of slack variables. */ protected final int numSlackVariables; /** Number of artificial variables. */ protected int numArtificialVariables; /** * Build a tableau for a linear problem. * @param f linear objective function * @param constraints linear constraints * @param goalType type of optimization goal: either {@link GoalType#MAXIMIZE} * or {@link GoalType#MINIMIZE} * @param restrictToNonNegative whether to restrict the variables to non-negative values */ SimplexTableau(final LinearObjectiveFunction f, final Collection<LinearConstraint> constraints, final GoalType goalType, final boolean restrictToNonNegative) { this.f = f; this.constraints = constraints; this.restrictToNonNegative = restrictToNonNegative; this.numDecisionVariables = getNumVariables() + (restrictToNonNegative ? 0 : 1); this.numSlackVariables = getConstraintTypeCounts(Relationship.LEQ) + getConstraintTypeCounts(Relationship.GEQ); this.numArtificialVariables = getConstraintTypeCounts(Relationship.EQ) + getConstraintTypeCounts(Relationship.GEQ); this.tableau = new RealMatrixImpl(createTableau(goalType == GoalType.MAXIMIZE)); initialize(); } /** * Create the tableau by itself. * @param maximize if true, goal is to maximize the objective function * @return created tableau */ protected double[][] createTableau(final boolean maximize) { // create a matrix of the correct size List<LinearConstraint> constraints = getNormalizedConstraints(); int width = numDecisionVariables + numSlackVariables + numArtificialVariables + getNumObjectiveFunctions() + 1; // + 1 is for RHS int height = constraints.size() + getNumObjectiveFunctions(); double[][] matrix = new double[height][width]; // initialize the objective function rows if (getNumObjectiveFunctions() == 2) { matrix[0][0] = -1; } int zIndex = (getNumObjectiveFunctions() == 1) ? 0 : 1; matrix[zIndex][zIndex] = maximize ? 1 : -1; RealVector objectiveCoefficients = maximize ? f.getCoefficients().mapMultiply(-1) : f.getCoefficients(); copyArray(objectiveCoefficients.getData(), matrix[zIndex], getNumObjectiveFunctions()); matrix[zIndex][width - 1] = maximize ? f.getConstantTerm() : -1 * f.getConstantTerm(); if (!restrictToNonNegative) { matrix[zIndex][getSlackVariableOffset() - 1] = getInvertedCoeffiecientSum(objectiveCoefficients); } // initialize the constraint rows int slackVar = 0; int artificialVar = 0; for (int i = 0; i < constraints.size(); i++) { LinearConstraint constraint = constraints.get(i); int row = getNumObjectiveFunctions() + i; // decision variable coefficients copyArray(constraint.getCoefficients().getData(), matrix[row], 1); // x- if (!restrictToNonNegative) { matrix[row][getSlackVariableOffset() - 1] = getInvertedCoeffiecientSum(constraint.getCoefficients()); } // RHS matrix[row][width - 1] = constraint.getValue(); // slack variables if (constraint.getRelationship() == Relationship.LEQ) { matrix[row][getSlackVariableOffset() + slackVar++] = 1; // slack } else if (constraint.getRelationship() == Relationship.GEQ) { matrix[row][getSlackVariableOffset() + slackVar++] = -1; // excess } // artificial variables if ((constraint.getRelationship() == Relationship.EQ) || (constraint.getRelationship() == Relationship.GEQ)) { matrix[0][getArtificialVariableOffset() + artificialVar] = 1; matrix[row][getArtificialVariableOffset() + artificialVar++] = 1; } } return matrix; } /** Get the number of variables. * @return number of variables */ public int getNumVariables() { return f.getCoefficients().getDimension(); } /** * Get new versions of the constraints which have positive right hand sides. * @return new versions of the constraints */ public List<LinearConstraint> getNormalizedConstraints() { List<LinearConstraint> normalized = new ArrayList<LinearConstraint>(); for (LinearConstraint constraint : constraints) { normalized.add(normalize(constraint)); } return normalized; } /** * Get a new equation equivalent to this one with a positive right hand side. * @param constraint reference constraint * @return new equation */ private LinearConstraint normalize(final LinearConstraint constraint) { if (constraint.getValue() < 0) { return new LinearConstraint(constraint.getCoefficients().mapMultiply(-1), constraint.getRelationship().oppositeRelationship(), -1 * constraint.getValue()); } return new LinearConstraint(constraint.getCoefficients(), constraint.getRelationship(), constraint.getValue()); } /** * Get the number of objective functions in this tableau. * @return 2 for Phase 1. 1 for Phase 2. */ protected final int getNumObjectiveFunctions() { return this.numArtificialVariables > 0 ? 2 : 1; } /** * Get a count of constraints corresponding to a specified relationship. * @param relationship relationship to count * @return number of constraint with the specified relationship */ private int getConstraintTypeCounts(final Relationship relationship) { int count = 0; for (final LinearConstraint constraint : constraints) { if (constraint.getRelationship() == relationship) { ++count; } } return count; } /** * Puts the tableau in proper form by zeroing out the artificial variables * in the objective function via elementary row operations. */ private void initialize() { for (int artificialVar = 0; artificialVar < numArtificialVariables; artificialVar++) { int row = getBasicRow(getArtificialVariableOffset() + artificialVar); subtractRow(0, row, 1.0); } } /** * Get the -1 times the sum of all coefficients in the given array. * @param coefficients coefficients to sum * @return the -1 times the sum of all coefficients in the given array. */ protected static double getInvertedCoeffiecientSum(final RealVector coefficients) { double sum = 0; for (double coefficient : coefficients.getData()) { sum -= coefficient; } return sum; } /** * Checks whether the given column is basic. * @param col index of the column to check * @return the row that the variable is basic in. null if the column is not basic */ private Integer getBasicRow(final int col) { Integer row = null; for (int i = getNumObjectiveFunctions(); i < getHeight(); i++) { if (getEntry(i, col) != 0.0) { if (row == null) { row = i; } else { return null; } } } return row; } /** * Removes the phase 1 objective function and artificial variables from this tableau. */ protected void discardArtificialVariables() { if (numArtificialVariables == 0) { return; } int width = getWidth() - numArtificialVariables - 1; int height = getHeight() - 1; double[][] matrix = new double[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width - 1; j++) { matrix[i][j] = getEntry(i + 1, j + 1); } matrix[i][width - 1] = getEntry(i + 1, getRhsOffset()); } this.tableau = new RealMatrixImpl(matrix); this.numArtificialVariables = 0; } /** * @param src the source array * @param dest the destination array * @param destPos the destination position */ private void copyArray(final double[] src, final double[] dest, final int destPos) { System.arraycopy(src, 0, dest, getNumObjectiveFunctions(), src.length); } /** * Get the current solution. * <p> * {@link #solve} should be called first for this to be the optimal solution. * </p> * @return current solution */ protected RealPointValuePair getSolution() { double[] coefficients = new double[getOriginalNumDecisionVariables()]; double mostNegative = getDecisionVariableValue(getOriginalNumDecisionVariables()); for (int i = 0; i < coefficients.length; i++) { coefficients[i] = getDecisionVariableValue(i) - (restrictToNonNegative ? 0 : mostNegative); } return new RealPointValuePair(coefficients, f.getValue(coefficients)); } /** * Get the value of the given decision variable. This is not the actual * value as it is guaranteed to be >= 0 and thus must be corrected before * being returned to the user. * * @param decisionVariable The index of the decision variable * @return The value of the given decision variable. */ protected double getDecisionVariableValue(final int decisionVariable) { Integer basicRow = getBasicRow(getNumObjectiveFunctions() + decisionVariable); return basicRow == null ? 0 : getEntry(basicRow, getRhsOffset()); } /** * Subtracts a multiple of one row from another. * <p> * After application of this operation, the following will hold: * minuendRow = minuendRow - multiple * subtrahendRow * </p> * @param dividendRow index of the row * @param divisor value of the divisor */ protected void divideRow(final int dividendRow, final double divisor) { for (int j = 0; j < getWidth(); j++) { tableau.setEntry(dividendRow, j, tableau.getEntry(dividendRow, j) / divisor); } } /** * Subtracts a multiple of one row from another. * <p> * After application of this operation, the following will hold: * minuendRow = minuendRow - multiple * subtrahendRow * </p> * @param minuendRow row index * @param subtrahendRow row index * @param multiple multiplication factor */ protected void subtractRow(final int minuendRow, final int subtrahendRow, final double multiple) { for (int j = 0; j < getWidth(); j++) { tableau.setEntry(minuendRow, j, tableau.getEntry(minuendRow, j) - multiple * tableau.getEntry(subtrahendRow, j)); } } /** * Get the width of the tableau. * @return width of the tableau */ protected final int getWidth() { return tableau.getColumnDimension(); } /** * Get the height of the tableau. * @return height of the tableau */ protected final int getHeight() { return tableau.getRowDimension(); } /** Get an entry of the tableau. * @param row row index * @param column column index * @return entry at (row, column) */ protected final double getEntry(final int row, final int column) { return tableau.getEntry(row, column); } /** Set an entry of the tableau. * @param row row index * @param column column index * param value for the entry */ protected final void setEntry(final int row, final int column, final double value) { tableau.setEntry(row, column, value); } /** * Get the offset of the first slack variable. * @return offset of the first slack variable */ protected final int getSlackVariableOffset() { return getNumObjectiveFunctions() + numDecisionVariables; } /** * Get the offset of the first artificial variable. * @return offset of the first artificial variable */ protected final int getArtificialVariableOffset() { return getNumObjectiveFunctions() + numDecisionVariables + numSlackVariables; } /** * Get the offset of the right hand side. * @return offset of the right hand side */ protected final int getRhsOffset() { return getWidth() - 1; } /** * Get the number of decision variables. * <p> * If variables are not restricted to positive values, this will include 1 * extra decision variable to represent the absolute value of the most * negative variable. * </p> * @return number of decision variables * @see #getOriginalNumDecisionVariables() */ protected final int getNumDecisionVariables() { return numDecisionVariables; } /** * Get the original number of decision variables. * @return original number of decision variables * @see #getNumDecisionVariables() */ protected final int getOriginalNumDecisionVariables() { return restrictToNonNegative ? numDecisionVariables : numDecisionVariables - 1; } /** * Get the number of slack variables. * @return number of slack variables */ protected final int getNumSlackVariables() { return numSlackVariables; } /** * Get the number of artificial variables. * @return number of artificial variables */ protected final int getNumArtificialVariables() { return numArtificialVariables; } /** * Get the tableau data. * @return tableau data */ protected final double[][] getData() { return tableau.getData(); } }
fixed javadoc error git-svn-id: 80d496c472b8b763a5e941dba212da9bf48aeceb@758924 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/math/optimization/linear/SimplexTableau.java
fixed javadoc error
<ide><path>rc/java/org/apache/commons/math/optimization/linear/SimplexTableau.java <ide> /** Set an entry of the tableau. <ide> * @param row row index <ide> * @param column column index <del> * param value for the entry <add> * @param value for the entry <ide> */ <ide> protected final void setEntry(final int row, final int column, <ide> final double value) {
JavaScript
apache-2.0
51cf63e89a0cb55cf12fac5598eef2e3de37071b
0
chinarustin/uproxy,jpevarnek/uproxy,IveWong/uproxy,uProxy/uproxy,MinFu/uproxy,MinFu/uproxy,itplanes/uproxy,dhkong88/uproxy,uProxy/uproxy,qida/uproxy,MinFu/uproxy,jpevarnek/uproxy,MinFu/uproxy,roceys/uproxy,qida/uproxy,IveWong/uproxy,IveWong/uproxy,uProxy/uproxy,IveWong/uproxy,qida/uproxy,chinarustin/uproxy,dhkong88/uproxy,jpevarnek/uproxy,dhkong88/uproxy,roceys/uproxy,dhkong88/uproxy,roceys/uproxy,itplanes/uproxy,itplanes/uproxy,qida/uproxy,qida/uproxy,roceys/uproxy,MinFu/uproxy,chinarustin/uproxy,itplanes/uproxy,roceys/uproxy,itplanes/uproxy,uProxy/uproxy,chinarustin/uproxy,jpevarnek/uproxy,jpevarnek/uproxy,dhkong88/uproxy,chinarustin/uproxy,uProxy/uproxy
#!/usr/bin/env nodejs var child_process = require('child_process'); var fs = require('fs'); var Promise = require('es6-promise').Promise; console.log('Setup repos script...\n '+ ' * to test: `ssh -T [email protected]` \n ' + ' * to list your ssh agents: `ssh-add -l` \n '); var args = []; process.argv.slice(2).forEach(function (a) { args.push(a); }); var repoNames = [ {repo: '[email protected]:uProxy/uProxy.git', dir: 'uproxy' }, {repo: '[email protected]:uProxy/socks-rtc.git', dir: 'uproxy-networking' }, {repo: '[email protected]:uProxy/sas-rtc.git', dir: 'uproxy-sas-rtc' }, {repo: '[email protected]:uProxy/uTransformers.git', dir: 'uproxy-uTransformers' }, {repo: '[email protected]:uProxy/uproxy-lib.git', dir: 'uproxy-lib' }, {repo: '[email protected]:uProxy/libfte.git', dir: 'libfte' }, {repo: '[email protected]:uProxy/uProbe.git', dir: 'uproxy-logging' }, {repo: '[email protected]:uProxy/turn-relay.git', dir: 'uproxy-churn' }, {repo: '[email protected]:uProxy/uproxy-website.git', dir: 'uproxy-website' }, {repo: '[email protected]:freedomjs/freedom.git', dir: 'freedom' }, {repo: '[email protected]:freedomjs/freedom-typescript-api.git', dir: 'freedom-typescript-api' }, {repo: '[email protected]:freedomjs/freedom-for-chrome.git', dir: 'freedom-for-chrome' }, {repo: '[email protected]:freedomjs/freedom-for-firefox.git', dir: 'fredom-for-firefox' }, {repo: '[email protected]:freedomjs/freedom-for-node.git', dir: 'freedom-for-node' }, {repo: '[email protected]:freedomjs/freedom-social-xmpp.git', dir: 'freedom-social-xmpp' }, ]; var running = true; function checkSshAgent() { var cmd = 'ssh -T [email protected]'; // TODO complete this. return Promise.reject('Not yet implemented.') } function cloneAll(repos) { var promises = []; var cmd = ''; repoNames.forEach(function (r) { if(!fs.existsSync(r.dir)) { cmd = 'git clone ' + r.repo + ' ' + r.dir; console.log('executing: ' + cmd); promises.push(new Promise(function (F,R) { child_process.exec(cmd, {}, function (error, stdout, stderr) { if(stdout) { console.log('stdout: ' + stdout); } if(stderr) { console.log('stderr: ' + stderr); } if (error !== null) { console.log('exec error: ' + error); R(error); } else { F(); } }); })); } // if repo didn't exist }); return Promise.all(promises).then(function () { running = false; console.log('All sub-command promises complete.'); }); } cloneAll();
tools/setup_repos.js
#!/usr/bin/env nodejs var child_process = require('child_process'); var fs = require('fs'); var Promise = require('es6-promise').Promise; console.log('Setup repos script...\n '+ ' * to test: `ssh -T [email protected]` \n ' + ' * to list your ssh agents: `ssh-add -l` \n '); var args = []; process.argv.slice(2).forEach(function (a) { args.push(a); }); var repoNames = [ 'uProxy', 'socks-rtc', 'sas-rtc', 'uTransformers', 'uproxy-lib', 'libfte', 'uProbe', 'turn-relay', 'uproxy-website', ]; var running = true; function checkSshAgent() { var cmd = 'ssh -T [email protected]'; // TODO complete this. return Promise.reject('Not yet implemented.') } function cloneAll() { var promises = []; var cmd = ''; repoNames.forEach(function (n) { if(!fs.existsSync(n)) { cmd = 'git clone [email protected]:uProxy/' + n + '.git'; console.log('executing: ' + cmd); promises.push(new Promise(function (F,R) { child_process.exec(cmd, {}, function (error, stdout, stderr) { console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); R(error); } else { F(); } }); })); } // if }); return Promise.all(promises).then(function () { running = false; console.log('All sub-command promises complete.'); }); } cloneAll();
added handling of freedom repos + allow different directory names
tools/setup_repos.js
added handling of freedom repos + allow different directory names
<ide><path>ools/setup_repos.js <ide> }); <ide> <ide> var repoNames = [ <del> 'uProxy', <del> 'socks-rtc', <del> 'sas-rtc', <del> 'uTransformers', <del> 'uproxy-lib', <del> 'libfte', <del> 'uProbe', <del> 'turn-relay', <del> 'uproxy-website', <add> {repo: '[email protected]:uProxy/uProxy.git', dir: 'uproxy' }, <add> {repo: '[email protected]:uProxy/socks-rtc.git', dir: 'uproxy-networking' }, <add> {repo: '[email protected]:uProxy/sas-rtc.git', dir: 'uproxy-sas-rtc' }, <add> {repo: '[email protected]:uProxy/uTransformers.git', dir: 'uproxy-uTransformers' }, <add> {repo: '[email protected]:uProxy/uproxy-lib.git', dir: 'uproxy-lib' }, <add> {repo: '[email protected]:uProxy/libfte.git', dir: 'libfte' }, <add> {repo: '[email protected]:uProxy/uProbe.git', dir: 'uproxy-logging' }, <add> {repo: '[email protected]:uProxy/turn-relay.git', dir: 'uproxy-churn' }, <add> {repo: '[email protected]:uProxy/uproxy-website.git', dir: 'uproxy-website' }, <add> {repo: '[email protected]:freedomjs/freedom.git', dir: 'freedom' }, <add> {repo: '[email protected]:freedomjs/freedom-typescript-api.git', dir: 'freedom-typescript-api' }, <add> {repo: '[email protected]:freedomjs/freedom-for-chrome.git', dir: 'freedom-for-chrome' }, <add> {repo: '[email protected]:freedomjs/freedom-for-firefox.git', dir: 'fredom-for-firefox' }, <add> {repo: '[email protected]:freedomjs/freedom-for-node.git', dir: 'freedom-for-node' }, <add> {repo: '[email protected]:freedomjs/freedom-social-xmpp.git', dir: 'freedom-social-xmpp' }, <ide> ]; <ide> <ide> var running = true; <ide> return Promise.reject('Not yet implemented.') <ide> } <ide> <del>function cloneAll() { <add>function cloneAll(repos) { <ide> var promises = []; <ide> var cmd = ''; <del> repoNames.forEach(function (n) { <del> if(!fs.existsSync(n)) { <del> cmd = 'git clone [email protected]:uProxy/' + n + '.git'; <add> repoNames.forEach(function (r) { <add> if(!fs.existsSync(r.dir)) { <add> cmd = 'git clone ' + r.repo + ' ' + r.dir; <ide> console.log('executing: ' + cmd); <ide> promises.push(new Promise(function (F,R) { <ide> child_process.exec(cmd, {}, <ide> function (error, stdout, stderr) { <del> console.log('stdout: ' + stdout); <del> console.log('stderr: ' + stderr); <add> if(stdout) { console.log('stdout: ' + stdout); } <add> if(stderr) { console.log('stderr: ' + stderr); } <ide> if (error !== null) { <ide> console.log('exec error: ' + error); <ide> R(error); <ide> } <ide> }); <ide> })); <del> } // if <add> } // if repo didn't exist <ide> }); <ide> return Promise.all(promises).then(function () { <ide> running = false;
JavaScript
mit
16b941a37c90c01d2fd4beb1bfbdd4f7885aef3b
0
Seldaek/rustdoc_web,Seldaek/rustdoc_web
/*jslint node: true, stupid: true, es5: true, regexp: true, nomen: true */ "use strict"; /* * This file is part of the rustdoc_web package. * * (c) Jordi Boggiano <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ var Twig = require("twig"), fs = require("fs"), globsync = require('glob-whatev'); // params (inputDir, outputDir, faviconUrl, logoUrl, menu, title, baseSourceUrls, knownCrates) var config = JSON.parse(fs.readFileSync('config.json')); config.inputDir = config.inputDir || "input"; config.outputDir = config.outputDir.replace(/\/*$/, '/') || "build/"; config.logoUrl = config.logoUrl || "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png"; config.baseSourceUrls = config.baseSourceUrls || {}; config.menu = config.menu || []; config.title = config.title || ''; config.rustVersion = config.rustVersion || '0.8'; // TODO should be current once the latest version is built as current config.knownCrates = config.knownCrates || {}; config.docBlockRenderer = 'markdown'; var renderDocs; if (config.docBlockRenderer === 'markdown') { renderDocs = (function () { var marked = require('marked'), hljs = require('highlight.js'), options = { gfm: true, highlight: function (code, lang) { return hljs.highlightAuto(code).value; //return hljs.highlight(lang || 'rust', code).value; }, tables: true, breaks: false, pedantic: false, sanitize: false, smartLists: true, smartypants: false, langPrefix: 'lang-' }; marked.setOptions(options); return function (str) { var tokens; if (str === '') { return str; } tokens = marked.lexer(str, options); return marked.parser(tokens); }; }()); } else { throw new Error('Invalid docblock renderer: ' + config.docBlockRenderer); } // merge in default known crates [ {name: 'std', url: "http://seld.be/rustdoc/%rustVersion%/", type: "rustdoc_web"}, {name: 'extra', url: "http://seld.be/rustdoc/%rustVersion%/", type: "rustdoc_web"}, ].forEach(function (crate) { if (config.knownCrates[crate.name] === undefined) { config.knownCrates[crate.name] = {url: crate.url, type: crate.type}; } }); var transTexts = { 'mods': 'Modules', 'structs': 'Structs', 'enums': 'Enums', 'traits': 'Traits', 'typedefs': 'Type Definitions', 'statics': 'Statics', 'fns': 'Functions', 'reexports': 'Re-exports', 'crates': 'Crates', 'mod': 'Module', 'struct': 'Struct', 'enum': 'Enum', 'trait': 'Trait', 'typedef': 'Type Definition', 'static': 'Static', 'fn': 'Function', 'reexport': 'Re-export', }; Twig.extendFilter('trans', function (str) { if (transTexts[str] !== undefined) { return transTexts[str]; } return str; }); Twig.extendFilter('substring', function (str, args) { var from = args[0], to = args[1]; if (to < 0) { to = str.length + to; } return str.substring(from, to); }); function createTypeTreeNode(name, parent) { parent = parent || null; return { // special metadata name: name, parent: parent, submods: {}, // list of elements mods: {}, structs: {}, enums: {}, traits: {}, typedefs: {}, fns: {}, reexports: {}, statics: {}, // reuse the instance of the parent tree so all trees share the impls because they need to be discoverable across the board impls: parent ? parent.impls : {}, // implementations for a given struct implsfor: parent ? parent.implsfor : {}, // implementations of traits for a given struct implsof: parent ? parent.implsof : {}, // implementations of a given trait }; } function shortenType(type) { return type.match(/s$/) ? type.substring(0, type.length - 1) : type; } function extract(data, key) { var res = ''; data.forEach(function (attr) { if ((attr.variant === "NameValue" || attr.variant === "List") && attr.fields[0] === key) { res = attr.fields[1]; } }); return res; } function extractDocs(elem, skipFormatting, returnFalseIfNotDocable) { var docs = extract(elem.attrs, 'doc'); if (docs instanceof Array && docs[0].fields[0] === 'hidden') { return returnFalseIfNotDocable === true ? false : ''; } if (returnFalseIfNotDocable === true && elem.visibility === 'hidden') { return false; } docs = docs.toString(); return skipFormatting === true ? docs : renderDocs(docs); } function shortDescription(elem, skipFormatting) { var match, docblock = extractDocs(elem, true); if (docblock === false) { return ''; } match = docblock.match(/^([\s\S]+?)\r?\n[ \t\*]*\r?\n([\s\S]+)/); if (match) { docblock = match[1]; } return skipFormatting === true ? docblock : renderDocs(docblock); } function getPath(tree) { var bits = []; bits.push(tree.name || ''); while (tree.parent) { tree = tree.parent; bits.push(tree.name); } bits.reverse(); return bits; } function getDecl(element) { if (element.decl !== undefined) { return element.decl; } return element.inner.fields[0].decl; } function getGenerics(element) { if (element.inner === undefined || element.inner.fields === undefined) { throw new Error('Invalid element: ' + JSON.stringify(element)); } return element.inner.fields[0].generics; } function primitiveType(type) { var foundType = typeof type === 'string' ? type.substring(3) : type.fields[0].substring(3), typeAliases = { u: 'uint', f: 'float', i: 'int', }, knownTypes = [ "char", "u", "u8", "u16", "u32", "u64", "i", "i8", "i16", "i32", "i64", "f", "f8", "f16", "f32", "f64" ]; if (knownTypes.indexOf(foundType) === -1) { throw new Error('Unknown type: ' + JSON.stringify(type)); } if (typeAliases[foundType] !== undefined) { return typeAliases[foundType]; } return foundType; } function render(template, vars, references, version, cb) { vars.settings = { views: "templates/", 'twig options': { strict_variables: true } }; function relativePath(fromTree, toTree) { var fromPath, toPath; if (fromTree === toTree) { return ''; } fromPath = getPath(fromTree); toPath = getPath(toTree); while (toPath.length && fromPath.length && toPath[0] === fromPath[0]) { toPath.shift(); fromPath.shift(); } return (new Array(fromPath.length + 1).join('../') + toPath.join('/') + '/').replace(/\/+$/, '/'); } function modPath(typeTree) { var path = getPath(typeTree).join('::'); return path + (path ? '::' : ''); } // helpers vars.short_description = shortDescription; vars.long_description = function (elem) { var match, docblock = extractDocs(elem, true); if (docblock === false) { return ''; } match = docblock.match(/^([\s\S]+?)\r?\n[ \t\*]*\r?\n([\s\S]+)/); return match ? renderDocs(match[2]) : ''; }; vars.link_to_element = function (id, currentTree) { var modPrefix = ''; if (!currentTree) { throw new Error('Missing currentTree arg #2'); } modPrefix = modPath(references[id].tree); return '<a class="' + shortenType(references[id].type) + '" href="' + vars.url_to_element(id, currentTree) + '" title="' + modPrefix + references[id].def.name + '">' + references[id].def.name + '</a>'; }; vars.link_to_external = function (name, type, knownCrates, version) { var crate, path, match, url, localCrate; match = name.match(/^([^:]+)(::.*)?$/); crate = match[1]; path = name.replace(/::/g, '/') + '.html'; path = path.replace(/([^\/]+)$/, type + '.$1'); version.crates.forEach(function (cr) { if (cr.name === crate) { localCrate = true; } }); if (localCrate) { // crate is part of this build url = vars.root_path + version.version + '/' + path; } else { // crate is known at another URL if (knownCrates[crate] === undefined) { return name; } if (knownCrates[crate].type !== 'rustdoc_web') { console.log('WARNING: Unknown crate type ' + knownCrates[crate].type); return name; } url = knownCrates[crate].url .replace(/%rustVersion%/g, config.rustVersion) .replace(/%version%/g, version.version) .replace(/\/*$/, '/'); url += path; } return '<a class="' + shortenType(type) + '" href="' + url + '">' + name + '</a>'; }; vars.element_by_id = function (id) { return references[id]; }; vars.url_to_element = function (id, currentTree) { if (!currentTree) { throw new Error('Missing currentTree arg #2'); } if (references[id].type === 'mods') { return relativePath(currentTree, references[id].tree) + references[id].def.name + '/index.html'; } return relativePath(currentTree, references[id].tree) + shortenType(references[id].type) + '.' + references[id].def.name + '.html'; }; vars.breadcrumb = function (typeTree, currentTree) { var path = [], out = '', tmpTree; currentTree = currentTree || typeTree; path.push(typeTree); tmpTree = typeTree; while (tmpTree.parent) { tmpTree = tmpTree.parent; path.push(tmpTree); } path.reverse(); path.forEach(function (targetTree) { out += '&#8203;' + (out ? '::' : '') + '<a href="' + relativePath(currentTree, targetTree) + 'index.html">' + targetTree.name + '</a>'; }); return out + '::'; }; vars.filter_priv_traits = function (traits) { var pubTraits = []; if (traits === null || traits === undefined) { return traits; } traits.forEach(function (trait) { if (trait.visibility !== 'private') { pubTraits.push(trait); } }); return pubTraits; }; vars.filter_docable = function (elems, type) { var key, filtered = {}; for (key in elems) { if (type === 'reexports') { if (elems[key].visibility === 'public') { filtered[key] = elems[key]; } } else if (extractDocs(references[key].def, true, true) !== false) { filtered[key] = elems[key]; } } return filtered; }; vars.extract_docs = extractDocs; vars.short_enum_type = function (type, currentTree) { if (type === 'CLikeVariant') { return ''; } return vars.short_type(type, currentTree); }; vars.sort = function (obj) { var key, elems = []; for (key in obj) { elems.push({id: key, name: obj[key]}); } return elems.sort(function (a, b) { return a.name.localeCompare(b.name); }); }; vars.extract_parent_docs = function (impl, methodName) { var foundDocs = ''; if (impl.inner.fields[0].trait_ === null) { return ''; } if (impl.inner.fields[0].trait_.variant !== 'ResolvedPath') { return ''; } references[impl.inner.fields[0].trait_.fields[2]].def.inner.fields[0].methods.forEach(function (method) { if (method.fields[0].name === methodName) { foundDocs = extractDocs(method.fields[0]); } }); return foundDocs; }; vars.unique_sorted_trait_impls = function (id, currentTree) { var impls, knownStructIds = [], uniqueImpls = []; impls = currentTree.implsof[id] || []; // TODO possibly collect implsof in a version.implsof instead of the tree, // so that crates can share it and we can display every implementor here impls.forEach(function (impl) { var structId; if (impl.inner.fields[0].for_.variant === 'ResolvedPath') { structId = impl.inner.fields[0].for_.fields[2]; if (knownStructIds.indexOf(structId) === -1) { uniqueImpls.push(impl); knownStructIds.push(structId); } } else { uniqueImpls.push(impl); } }); return uniqueImpls.sort(function (a, b) { var aResolved = a.inner.fields[0].for_.variant === 'ResolvedPath', bResolved = b.inner.fields[0].for_.variant === 'ResolvedPath'; if (aResolved && bResolved) { return references[a.inner.fields[0].for_.fields[2]].def.name.localeCompare(references[b.inner.fields[0].for_.fields[2]].def.name); } if (aResolved) { return -1; } if (bResolved) { return 1; } return 0; }); }; vars.extract_required_methods = function (trait) { var res = []; trait.inner.fields[0].methods.forEach(function (method) { if (method.variant === "Required") { res.push(method.fields[0]); } }); return res; }; vars.extract_provided_methods = function (trait) { var res = []; trait.inner.fields[0].methods.forEach(function (method) { if (method.variant === "Provided") { res.push(method.fields[0]); } }); return res; }; vars.count = function (data) { var key, count = 0; if (data instanceof Array) { return data.length; } for (key in data) { count += 1; } return count; }; vars.short_type = function shortType(type, currentTree, realType, pureLink) { var types, path; if (!currentTree) { throw new Error('Missing currentTree arg #2'); } if (typeof type === 'string') { type = {variant: type, fields: []}; } switch (realType || type.variant) { case 'Primitive': return primitiveType(type.fields[0]); case 'ResolvedPath': if (!references[type.fields[2]]) { throw new Error('Invalid resolved ref id: ' + type.fields[2]); } return vars.link_to_element(type.fields[2], currentTree) + (pureLink === true ? '' : vars.render_generics(type.fields[0], currentTree, 'arg')); case 'External': // external path external type return vars.link_to_external(type.fields[0], type.fields[1], config.knownCrates, version); case 'Tuple': case 'TupleVariant': types = type.fields[0].map(function (t) { return shortType(t, currentTree, realType); }).join(', '); return '(' + types + ')'; case 'ViewItemItem': return 'pub use ' + shortType(type.fields[0].inner, currentTree, realType) + ';'; case 'Import': return type.fields[0].map(function (t) { return shortType(t, currentTree, realType); }).join(', '); case 'SimpleImport': path = type.fields[1].segments.map(function (s) { return s.name; }).join('::'); if (type.fields[0] === path || path.substring(path.length - type.fields[0].length - 2) === '::' + type.fields[0]) { return path; } return type.fields[0] + ' = ' + path; case 'GlobImport': return type.fields[0].segments.map(function (s) { return s.name; }).join('::') + '::*'; case 'ImportList': return type.fields[0].segments.map(function (s) { return s.name; }).join('::') + '::{' + type.fields[1].join(', ') + '}'; case 'String': return 'str'; case 'Bool': return 'bool'; case 'Managed': return '@' + (type.fields[0] === 'Mutable' ? 'mut ' : '') + shortType(type.fields[1], currentTree, realType); case 'RawPointer': return '*' + (type.fields[0] === 'Mutable' ? 'mut ' : '') + shortType(type.fields[1], currentTree, realType); case 'BorrowedRef': return '&amp;' + (type.fields[0] ? "'" + type.fields[0]._field0 + ' ' : '') + (type.fields[1] === 'Mutable' ? 'mut ' : '') + shortType(type.fields[2], currentTree, realType); case 'Unique': return '~' + shortType(type.fields[0], currentTree, realType); case 'Vector': return '[' + shortType(type.fields[0], currentTree, realType) + ']'; case 'FixedVector': return '[' + shortType(type.fields[0], currentTree, realType) + ', ..' + type.fields[1] + ']'; case 'Bottom': return '!'; case 'Self': return 'Self'; case 'SelfStatic': return ''; case 'SelfValue': return 'self'; case 'SelfOwned': return '~self'; case 'SelfManaged': return '@' + (type.fields[0] === 'Mutable' ? 'mut ' : '') + 'self'; case 'SelfBorrowed': return '&amp;' + (type.fields[0] ? type.fields[0]._field0 + ' ' : '') + (type.fields[1] === 'Mutable' ? 'mut ' : '') + 'self'; case 'Closure': return vars.render_fn(type.fields[0], currentTree, 'Closure'); case 'Generic': if (references[type.fields[0]] === undefined) { throw new Error('Invalid generic reference id in ' + JSON.stringify(type)); } return references[type.fields[0]].def.name; case 'Unit': return '()'; case 'BareFunction': return (type.fields[0].abi ? 'extern ' + type.fields[0].abi + ' ' : '') + vars.render_fn(type.fields[0], currentTree, 'BareFunction'); } throw new Error('Can not render short type: ' + (realType || type.variant) + ' ' + JSON.stringify(type)); }; vars.render_fn = function (fn, currentTree, fnType) { var output = '', decl = getDecl(fn), temp; if (fn.inner && fn.inner.fields && fn.inner.fields[0].purity === 'unsafe_fn') { output += 'unsafe '; } if (fnType === 'Closure') { if (fn.sigil) { if (fn.sigil === 'BorrowedSigil') { output += '&amp;'; } else if (fn.sigil === 'ManagedSigil') { output += '@'; } else if (fn.sigil === 'OwnedSigil') { output += '~'; } else { throw new Error('Unknown sigil type ' + fn.sigil); } } if (fn.region) { output += "'" + fn.region._field0 + " "; } if (fn.onceness === 'once') { output += 'once '; } } output += 'fn' + (fn.name ? ' ' + fn.name : '') + vars.render_generics(fn, currentTree, fnType) + '(\n '; if (fn.inner && fn.inner.fields && fn.inner.fields[0].self_) { temp = vars.short_type(fn.inner.fields[0].self_, currentTree); if (temp) { output += temp; if (decl.inputs.length > 0) { output += ', \n '; } } } output += decl.inputs.map(function (arg) { return (arg.name ? arg.name + ': ' : '') + vars.short_type(arg.type_, currentTree); }).join(', \n '); output += '\n)'; if (decl.output !== 'Unit') { output += ' -&gt; ' + vars.short_type(decl.output, currentTree); } Twig.extend(function (Twig) { if (Twig.lib.strip_tags(output).replace(/&(gt|lt)/g, '').length < 100 || fnType !== 'fn') { output = output.replace(/\n {4}|\n/g, ''); } }); return output; }; vars.render_generics = function renderGenerics(element, currentTree, type) { var type_params, lifetimes, output = '', generics; if (type === 'Closure') { generics = {type_params: [], lifetimes: element.lifetimes}; } else if (type === 'BareFunction') { generics = element.generics; } else if (type === 'arg' || type === 'bound') { generics = {type_params: element.typarams, lifetimes: element.lifetime ? [element.lifetime] : null}; } else { generics = getGenerics(element); } if (!generics) { throw new Error('Element has invalid generics defined ' + JSON.stringify(element)); } function renderBounds(bound) { var res = ''; if (bound === 'RegionBound') { return "'static"; } if (bound.variant === 'TraitBound') { return vars.short_type(bound.fields[0], currentTree); } if (bound.fields === undefined || bound.fields[0].path === undefined) { throw new Error("Unknown bound type " + JSON.stringify(bound)); } bound = bound.fields[0].path; if (bound.name) { res += bound.name; } res += renderGenerics(bound, currentTree, 'bound'); return res; } type_params = generics.type_params || []; lifetimes = generics.lifetimes || []; if (type_params.length || lifetimes.length) { output += '&lt;'; if (lifetimes.length) { output += "'" + lifetimes.map(function (l) { return l._field0; }).join(", '"); } if (type_params.length && lifetimes.length) { output += ', '; } output += type_params.map(function (t) { var res; if (t.name) { res = t.name; } else { res = vars.short_type(t, currentTree); } if (t.bounds && t.bounds[0] !== undefined) { res += ": " + t.bounds.map(renderBounds).join(' + '); } return res; }).join(', '); output += '&gt;'; } return output; }; vars.source_url = function (element, crate) { var matches; if (!element.source) { throw new Error('Element has no source: ' + JSON.stringify(element)); } if (element.source.match(/^<std-macros>:/)) { return ''; } matches = element.source.match(/^([a-z0-9_.\/\-]+):(\d+):\d+:? (\d+):\d+$/i); if (!matches) { throw new Error('Could not parse element.source for ' + JSON.stringify(element)); } return config.baseSourceUrls[crate.name].replace('%version%', crate.version) + matches[1] + '#L' + matches[2] + '-' + matches[3]; }; Twig.renderFile("templates/" + template, vars, function (dummy, out) { cb(out); }); } function indexModule(path, module, typeTree, references, searchIndex) { var uid = 1, delayedIndexations = [], types = { ModuleItem: 'mods', StructItem: 'structs', EnumItem: 'enums', TraitItem: 'traits', TypedefItem: 'typedefs', FunctionItem: 'fns', StaticItem: 'statics', ImplItem: 'impls', ViewItemItem: 'reexports', }; function indexTyparams(typarams) { typarams.forEach(function (typaram) { references[typaram.id] = {type: 'typaram', def: typaram, tree: typeTree}; }); } function indexMethods(methods, parentName, parentType) { methods.forEach(function (method) { var generics; method = method.fields ? method.fields[0] : method; generics = getGenerics(method); if (generics && generics.type_params) { indexTyparams(generics.type_params); } searchIndex.push({type: 'method', name: method.name, parent: parentName, parentType: parentType, desc: shortDescription(method, true), path: getPath(typeTree).join('::')}); }); } function indexVariants(variants, parentName, parentType) { variants.forEach(function (variant) { searchIndex.push({type: 'variant', name: variant.name, parent: parentName, parentType: parentType, desc: '', path: getPath(typeTree).join('::')}); }); } function indexImpl(def) { var generics, forId = null, ofId = null; if (def.inner.fields[0].for_.variant === 'ResolvedPath') { forId = def.inner.fields[0].for_.fields[2]; } if (def.inner.fields[0].trait_) { if (def.inner.fields[0].trait_.variant === 'ResolvedPath') { ofId = def.inner.fields[0].trait_.fields[2]; } else if (def.inner.fields[0].trait_.variant === 'External') { ofId = 'trait ' + def.inner.fields[0].trait_.fields[0]; } else { throw new Error('Unknown trait definition: ' + JSON.stringify(def)); } } generics = getGenerics(def); if (generics && generics.type_params) { indexTyparams(generics.type_params); } if (ofId) { if (typeTree.implsfor[forId] === undefined) { typeTree.implsfor[forId] = []; } if (typeTree.implsof[ofId] === undefined) { typeTree.implsof[ofId] = []; } typeTree.implsfor[forId].push(def); typeTree.implsof[ofId].push(def); } else if (forId) { if (typeTree.impls[forId] === undefined) { typeTree.impls[forId] = []; } typeTree.impls[forId].push(def); } else { throw new Error('Impls should be for something or of something for a generic type ' + JSON.stringify(def)); } if (forId) { delayedIndexations.push(function () { indexMethods(def.inner.fields[0].methods, references[forId].def.name, shortenType(references[forId].type)); }); } } function indexItem(type, def) { var name = def.name, generics; if (type === 'impls') { indexImpl(def); return; } if (type === 'reexports') { typeTree[type][uid] = def; uid += 1; return; } if (type === 'mods') { def.id = path + name; typeTree.submods[name] = createTypeTreeNode(name, typeTree); delayedIndexations = delayedIndexations.concat(indexModule(path + '::' + name, def, typeTree.submods[name], references, searchIndex)); } else if (type === 'statics') { def.id = path + '::' + name; } else if (def.id === undefined) { throw new Error('Missing id on type ' + type + ' content: ' + JSON.stringify(def)); } generics = getGenerics(def); if (generics && generics.type_params) { indexTyparams(generics.type_params); } if (type === 'traits') { indexMethods(def.inner.fields[0].methods, name, shortenType(type)); } if (type === 'enums') { indexVariants(def.inner.fields[0].variants, name, shortenType(type)); } typeTree[type][def.id] = name; searchIndex.push({type: shortenType(type), name: name, path: getPath(typeTree).join('::'), desc: shortDescription(def, true)}); references[def.id] = {type: type, def: def, tree: typeTree}; } if (module.inner.variant !== 'ModuleItem') { throw new Error('Invalid module, should contain an inner module item'); } module.inner.fields.forEach(function (field) { field.items.forEach(function (item) { if (types[item.inner.variant] === undefined) { throw new Error('Unknown variant ' + item.inner.variant); } indexItem(types[item.inner.variant], item); }); }); return delayedIndexations; } function dumpModule(path, module, typeTree, references, crate, crates, version, versions) { var rootPath, matches, types, buildPath = config.outputDir + crate.version + "/" + path.replace(/::/g, '/') + '/'; types = { ModuleItem: 'mods', StructItem: 'structs', EnumItem: 'enums', TraitItem: 'traits', TypedefItem: 'typedefs', FunctionItem: 'fns', StaticItem: false, ImplItem: false, ViewItemItem: false, }; matches = path.match(/::/g); rootPath = '../../' + (matches ? new Array(matches.length + 1).join('../') : ''); function renderTemplate(type, def, filename) { var data, cb; data = { path: path, type_tree: typeTree, type: shortenType(type), root_path: rootPath, element: def, crates: crates, crate: crate, versions: versions, cur_version: crate.version, config: config, }; if (!fs.existsSync(buildPath)) { fs.mkdirSync(buildPath); } cb = function (out) { fs.writeFile(buildPath + filename, out); }; render(type + '.twig', data, references, version, cb); } renderTemplate('mods', module, "index.html"); module.inner.fields.forEach(function (field) { field.items.forEach(function (item) { var type = types[item.inner.variant]; if (type === undefined) { throw new Error('Unknown variant ' + item.inner.variant); } if (type === false) { return; } if (type === 'mods') { dumpModule(path + '::' + item.name, item, typeTree.submods[item.name], references, crate, crates, version, versions); } else { renderTemplate(type, item, shortenType(type) + '.' + item.name + '.html'); } }); }); } function renderCratesIndex(version, versions) { var data, cb; data = { root_path: '../', crates: version.crates, config: config, versions: versions, cur_version: version.version, // dummy object because we are not in a crate but the layout needs one crate: {version: version.version} }; cb = function (out) { fs.writeFile(config.outputDir + version.version + '/index.html', out); }; if (version.crates.length === 1) { cb('<DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=' + version.crates[0].name + '/index.html"></head><body></body></html>'); } else { render('crates.twig', data, {}, version, cb); } } function renderVersionsIndex(versions) { var data, cb; data = { root_path: '', versions: versions, config: config, }; cb = function (out) { fs.writeFile(config.outputDir + '/index.html', out); }; if (versions.length === 1) { cb('<DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=' + versions[0].version + '/index.html"></head><body></body></html>'); } else { render('versions.twig', data, {}, {}, cb); } } function initCrate(crate, searchIndex) { var sourceUrl, delayedIndexations, data = JSON.parse(fs.readFileSync(crate.path)); if (data.schema !== '0.8.0') { throw new Error('Unsupported schema ' + data.schema); } crate.name = data.crate.name; crate.data = data.crate.module; crate.typeTree = createTypeTreeNode(crate.name); crate.references = {}; crate.data.name = crate.name; crate.license = extract(data.crate.module.attrs, 'license').toString(); // read the link.url of the crate and take that as default if the config has no url configured sourceUrl = extract(data.crate.module.attrs, 'link'); if (sourceUrl !== '' && config.baseSourceUrls[crate.name] === undefined) { sourceUrl = extract(sourceUrl, 'url').toString(); if (sourceUrl !== '') { config.baseSourceUrls[crate.name] = sourceUrl.replace(/\/*$/, '/'); } } delayedIndexations = indexModule(crate.name, crate.data, crate.typeTree, crate.references, searchIndex); delayedIndexations.forEach(function (cb) { cb(); }); } function dumpCrate(crate, crates, version, versions) { dumpModule(crate.name, crate.data, crate.typeTree, crate.references, crate, crates, version, versions); } (function main() { var versions = []; if (!fs.existsSync(config.outputDir)) { fs.mkdirSync(config.outputDir); } globsync.glob(config.inputDir.replace(/\/*$/, '/') + '*').forEach(function (path) { var crates = [], version = path.replace(/.*?\/([^\/]+)\/$/, '$1'); globsync.glob(path + '*.json').forEach(function (path) { var crate = path.replace(/.*?\/([^\/]+)\.json$/, '$1'); crates.push({path: path, version: version}); }); versions.push({ version: version, crates: crates, prerelease: !!require('semver').valid(version), }); if (!fs.existsSync(config.outputDir + version)) { fs.mkdirSync(config.outputDir + version); } }); versions.sort(function (a, b) { if (!a.prerelease && !b.prerelease) { return require('semver').rcompare(a.version, b.version); } if (a.prerelease && !b.prerelease) { return 1; } if (b.prerelease) { return -1; } return 0; }); versions.forEach(function (version) { var searchIndex = []; version.crates.forEach(function (crate) { initCrate(crate, searchIndex); }); version.crates.sort(function (a, b) { return a.name.localeCompare(b.name); }); fs.writeFile(config.outputDir + version.version + '/search-index.js', "searchIndex = " + JSON.stringify(searchIndex)); searchIndex = []; version.crates.forEach(function (crate) { dumpCrate(crate, version.crates, version, versions); }); renderCratesIndex(version, versions); }); renderVersionsIndex(versions); }());
rustdoc.js
/*jslint node: true, stupid: true, es5: true, regexp: true, nomen: true */ "use strict"; /* * This file is part of the rustdoc_web package. * * (c) Jordi Boggiano <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ var Twig = require("twig"), fs = require("fs"), globsync = require('glob-whatev'); // params (inputDir, outputDir, faviconUrl, logoUrl, menu, title, baseSourceUrls, knownCrates) var config = JSON.parse(fs.readFileSync('config.json')); config.inputDir = config.inputDir || "input"; config.outputDir = config.outputDir.replace(/\/*$/, '/') || "build/"; config.logoUrl = config.logoUrl || "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png"; config.baseSourceUrls = config.baseSourceUrls || {}; config.menu = config.menu || []; config.title = config.title || ''; config.rustVersion = config.rustVersion || '0.8'; // TODO should be current once the latest version is built as current config.knownCrates = config.knownCrates || {}; config.docBlockRenderer = 'markdown'; var renderDocs; if (config.docBlockRenderer === 'markdown') { renderDocs = (function () { var marked = require('marked'), hljs = require('highlight.js'), options = { gfm: true, highlight: function (code, lang) { return hljs.highlightAuto(code).value; //return hljs.highlight(lang || 'rust', code).value; }, tables: true, breaks: false, pedantic: false, sanitize: false, smartLists: true, smartypants: false, langPrefix: 'lang-' }; marked.setOptions(options); return function (str) { var tokens; if (str === '') { return str; } tokens = marked.lexer(str, options); return marked.parser(tokens); }; }()); } else { throw new Error('Invalid docblock renderer: ' + config.docBlockRenderer); } // merge in default known crates [ {name: 'std', url: "http://seld.be/rustdoc/%rustVersion%/", type: "rustdoc_web"}, {name: 'extra', url: "http://seld.be/rustdoc/%rustVersion%/", type: "rustdoc_web"}, ].forEach(function (crate) { if (config.knownCrates[crate.name] === undefined) { config.knownCrates[crate.name] = {url: crate.url, type: crate.type}; } }); var transTexts = { 'mods': 'Modules', 'structs': 'Structs', 'enums': 'Enums', 'traits': 'Traits', 'typedefs': 'Type Definitions', 'statics': 'Statics', 'fns': 'Functions', 'reexports': 'Re-exports', 'crates': 'Crates', 'mod': 'Module', 'struct': 'Struct', 'enum': 'Enum', 'trait': 'Trait', 'typedef': 'Type Definition', 'static': 'Static', 'fn': 'Function', 'reexport': 'Re-export', }; Twig.extendFilter('trans', function (str) { if (transTexts[str] !== undefined) { return transTexts[str]; } return str; }); Twig.extendFilter('substring', function (str, args) { var from = args[0], to = args[1]; if (to < 0) { to = str.length + to; } return str.substring(from, to); }); function createTypeTreeNode(name, parent) { parent = parent || null; return { // special metadata name: name, parent: parent, submods: {}, // list of elements mods: {}, structs: {}, enums: {}, traits: {}, typedefs: {}, fns: {}, reexports: {}, statics: {}, // reuse the instance of the parent tree so all trees share the impls because they need to be discoverable across the board impls: parent ? parent.impls : {}, // implementations for a given struct implsfor: parent ? parent.implsfor : {}, // implementations of traits for a given struct implsof: parent ? parent.implsof : {}, // implementations of a given trait }; } function shortenType(type) { return type.match(/s$/) ? type.substring(0, type.length - 1) : type; } function extract(data, key) { var res = ''; data.forEach(function (attr) { if ((attr.variant === "NameValue" || attr.variant === "List") && attr.fields[0] === key) { res = attr.fields[1]; } }); return res; } function extractDocs(elem, skipFormatting, returnFalseIfNotDocable) { var docs = extract(elem.attrs, 'doc'); if (docs instanceof Array && docs[0].fields[0] === 'hidden') { return returnFalseIfNotDocable === true ? false : ''; } if (returnFalseIfNotDocable === true && elem.visibility === 'hidden') { return false; } docs = docs.toString(); return skipFormatting === true ? docs : renderDocs(docs); } function shortDescription(elem, skipFormatting) { var match, docblock = extractDocs(elem, true); if (docblock === false) { return ''; } match = docblock.match(/^([\s\S]+?)\r?\n[ \t\*]*\r?\n([\s\S]+)/); if (match) { docblock = match[1]; } return skipFormatting === true ? docblock : renderDocs(docblock); } function getPath(tree) { var bits = []; bits.push(tree.name || ''); while (tree.parent) { tree = tree.parent; bits.push(tree.name); } bits.reverse(); return bits; } function getDecl(element) { if (element.decl !== undefined) { return element.decl; } return element.inner.fields[0].decl; } function getGenerics(element) { if (element.inner === undefined || element.inner.fields === undefined) { throw new Error('Invalid element: ' + JSON.stringify(element)); } return element.inner.fields[0].generics; } function primitiveType(type) { var foundType = typeof type === 'string' ? type.substring(3) : type.fields[0].substring(3), typeAliases = { u: 'uint', f: 'float', i: 'int', }, knownTypes = [ "char", "u", "u8", "u16", "u32", "u64", "i", "i8", "i16", "i32", "i64", "f", "f8", "f16", "f32", "f64" ]; if (knownTypes.indexOf(foundType) === -1) { throw new Error('Unknown type: ' + JSON.stringify(type)); } if (typeAliases[foundType] !== undefined) { return typeAliases[foundType]; } return foundType; } function render(template, vars, references, version, cb) { vars.settings = { views: "templates/", 'twig options': { strict_variables: true } }; function relativePath(fromTree, toTree) { var fromPath, toPath; if (fromTree === toTree) { return ''; } fromPath = getPath(fromTree); toPath = getPath(toTree); while (toPath.length && fromPath.length && toPath[0] === fromPath[0]) { toPath.shift(); fromPath.shift(); } return (new Array(fromPath.length + 1).join('../') + toPath.join('/') + '/').replace(/\/+$/, '/'); } function modPath(typeTree) { var path = getPath(typeTree).join('::'); return path + (path ? '::' : ''); } // helpers vars.short_description = shortDescription; vars.long_description = function (elem) { var match, docblock = extractDocs(elem, true); if (docblock === false) { return ''; } match = docblock.match(/^([\s\S]+?)\r?\n[ \t\*]*\r?\n([\s\S]+)/); return match ? renderDocs(match[2]) : ''; }; vars.link_to_element = function (id, currentTree) { var modPrefix = ''; if (!currentTree) { throw new Error('Missing currentTree arg #2'); } modPrefix = modPath(references[id].tree); return '<a class="' + shortenType(references[id].type) + '" href="' + vars.url_to_element(id, currentTree) + '" title="' + modPrefix + references[id].def.name + '">' + references[id].def.name + '</a>'; }; vars.link_to_external = function (name, type, knownCrates, version) { var crate, path, match, url, localCrate; match = name.match(/^([^:]+)(::.*)?$/); crate = match[1]; path = name.replace(/::/g, '/') + '.html'; path = path.replace(/([^\/]+)$/, type + '.$1'); version.crates.forEach(function (cr) { if (cr.name === crate) { localCrate = true; } }); if (localCrate) { // crate is part of this build url = vars.root_path + version.version + '/' + path; } else { // crate is known at another URL if (knownCrates[crate] === undefined) { return name; } if (knownCrates[crate].type !== 'rustdoc_web') { console.log('WARNING: Unknown crate type ' + knownCrates[crate].type); return name; } url = knownCrates[crate].url .replace(/%rustVersion%/g, config.rustVersion) .replace(/%version%/g, version.version) .replace(/\/*$/, '/'); url += path; } return '<a class="' + shortenType(type) + '" href="' + url + '">' + name + '</a>'; }; vars.element_by_id = function (id) { return references[id]; }; vars.url_to_element = function (id, currentTree) { if (!currentTree) { throw new Error('Missing currentTree arg #2'); } if (references[id].type === 'mods') { return relativePath(currentTree, references[id].tree) + references[id].def.name + '/index.html'; } return relativePath(currentTree, references[id].tree) + shortenType(references[id].type) + '.' + references[id].def.name + '.html'; }; vars.breadcrumb = function (typeTree, currentTree) { var path = [], out = '', tmpTree; currentTree = currentTree || typeTree; path.push(typeTree); tmpTree = typeTree; while (tmpTree.parent) { tmpTree = tmpTree.parent; path.push(tmpTree); } path.reverse(); path.forEach(function (targetTree) { out += '&#8203;' + (out ? '::' : '') + '<a href="' + relativePath(currentTree, targetTree) + 'index.html">' + targetTree.name + '</a>'; }); return out + '::'; }; vars.filter_priv_traits = function (traits) { var pubTraits = []; if (traits === null || traits === undefined) { return traits; } traits.forEach(function (trait) { if (trait.visibility !== 'private') { pubTraits.push(trait); } }); return pubTraits; }; vars.filter_docable = function (elems, type) { var key, filtered = {}; for (key in elems) { if (type === 'reexports') { if (elems[key].visibility === 'public') { filtered[key] = elems[key]; } } else if (extractDocs(references[key].def, true, true) !== false) { filtered[key] = elems[key]; } } return filtered; }; vars.extract_docs = extractDocs; vars.short_enum_type = function (type, currentTree) { if (type === 'CLikeVariant') { return ''; } return vars.short_type(type, currentTree); }; vars.sort = function (obj) { var key, elems = []; for (key in obj) { elems.push({id: key, name: obj[key]}); } return elems.sort(function (a, b) { return a.name.localeCompare(b.name); }); }; vars.extract_parent_docs = function (impl, methodName) { var foundDocs = ''; if (impl.inner.fields[0].trait_ === null) { return ''; } if (impl.inner.fields[0].trait_.variant !== 'ResolvedPath') { return ''; } references[impl.inner.fields[0].trait_.fields[2]].def.inner.fields[0].methods.forEach(function (method) { if (method.fields[0].name === methodName) { foundDocs = extractDocs(method.fields[0]); } }); return foundDocs; }; vars.unique_sorted_trait_impls = function (id, currentTree) { var impls, knownStructIds = [], uniqueImpls = []; impls = currentTree.implsof[id] || []; // TODO possibly collect implsof in a version.implsof instead of the tree, // so that crates can share it and we can display every implementor here impls.forEach(function (impl) { var structId; if (impl.inner.fields[0].for_.variant === 'ResolvedPath') { structId = impl.inner.fields[0].for_.fields[2]; if (knownStructIds.indexOf(structId) === -1) { uniqueImpls.push(impl); knownStructIds.push(structId); } } else { uniqueImpls.push(impl); } }); return uniqueImpls.sort(function (a, b) { var aResolved = a.inner.fields[0].for_.variant === 'ResolvedPath', bResolved = b.inner.fields[0].for_.variant === 'ResolvedPath'; if (aResolved && bResolved) { return references[a.inner.fields[0].for_.fields[2]].def.name.localeCompare(references[b.inner.fields[0].for_.fields[2]].def.name); } if (aResolved) { return -1; } if (bResolved) { return 1; } return 0; }); }; vars.extract_required_methods = function (trait) { var res = []; trait.inner.fields[0].methods.forEach(function (method) { if (method.variant === "Required") { res.push(method.fields[0]); } }); return res; }; vars.extract_provided_methods = function (trait) { var res = []; trait.inner.fields[0].methods.forEach(function (method) { if (method.variant === "Provided") { res.push(method.fields[0]); } }); return res; }; vars.count = function (data) { var key, count = 0; if (data instanceof Array) { return data.length; } for (key in data) { count += 1; } return count; }; vars.short_type = function shortType(type, currentTree, realType, pureLink) { var types, path; if (!currentTree) { throw new Error('Missing currentTree arg #2'); } if (typeof type === 'string') { type = {variant: type, fields: []}; } switch (realType || type.variant) { case 'Primitive': return primitiveType(type.fields[0]); case 'ResolvedPath': if (!references[type.fields[2]]) { throw new Error('Invalid resolved ref id: ' + type.fields[2]); } return vars.link_to_element(type.fields[2], currentTree) + (pureLink === true ? '' : vars.render_generics(type.fields[0], currentTree, 'arg')); case 'External': // external path external type return vars.link_to_external(type.fields[0], type.fields[1], config.knownCrates, version); case 'Tuple': case 'TupleVariant': types = type.fields[0].map(function (t) { return shortType(t, currentTree, realType); }).join(', '); return '(' + types + ')'; case 'ViewItemItem': return 'pub use ' + shortType(type.fields[0].inner, currentTree, realType) + ';'; case 'Import': return type.fields[0].map(function (t) { return shortType(t, currentTree, realType); }).join(', '); case 'SimpleImport': path = type.fields[1].segments.map(function (s) { return s.name; }).join('::'); if (type.fields[0] === path || path.substring(path.length - type.fields[0].length - 2) === '::' + type.fields[0]) { return path; } return type.fields[0] + ' = ' + path; case 'GlobImport': return type.fields[0].segments.map(function (s) { return s.name; }).join('::') + '::*'; case 'ImportList': return type.fields[0].segments.map(function (s) { return s.name; }).join('::') + '::{' + type.fields[1].join(', ') + '}'; case 'String': return 'str'; case 'Bool': return 'bool'; case 'Managed': return '@' + (type.fields[0] === 'Mutable' ? 'mut ' : '') + shortType(type.fields[1], currentTree, realType); case 'RawPointer': return '*' + (type.fields[0] === 'Mutable' ? 'mut ' : '') + shortType(type.fields[1], currentTree, realType); case 'BorrowedRef': return '&amp;' + (type.fields[0] ? "'" + type.fields[0]._field0 + ' ' : '') + (type.fields[1] === 'Mutable' ? 'mut ' : '') + shortType(type.fields[2], currentTree, realType); case 'Unique': return '~' + shortType(type.fields[0], currentTree, realType); case 'Vector': return '[' + shortType(type.fields[0], currentTree, realType) + ']'; case 'FixedVector': return '[' + shortType(type.fields[0], currentTree, realType) + ', ..' + type.fields[1] + ']'; case 'Bottom': return '!'; case 'Self': return 'Self'; case 'SelfStatic': return ''; case 'SelfValue': return 'self'; case 'SelfOwned': return '~self'; case 'SelfManaged': return '@' + (type.fields[0] === 'Mutable' ? 'mut ' : '') + 'self'; case 'SelfBorrowed': return '&amp;' + (type.fields[0] ? type.fields[0]._field0 + ' ' : '') + (type.fields[1] === 'Mutable' ? 'mut ' : '') + 'self'; case 'Closure': return vars.render_fn(type.fields[0], currentTree, 'Closure'); case 'Generic': if (references[type.fields[0]] === undefined) { throw new Error('Invalid generic reference id in ' + JSON.stringify(type)); } return references[type.fields[0]].def.name; case 'Unit': return '()'; case 'BareFunction': return (type.fields[0].abi ? 'extern ' + type.fields[0].abi + ' ' : '') + vars.render_fn(type.fields[0], currentTree, 'BareFunction'); } throw new Error('Can not render short type: ' + (realType || type.variant) + ' ' + JSON.stringify(type)); }; vars.render_fn = function (fn, currentTree, fnType) { var output = '', decl = getDecl(fn), temp; if (fn.inner && fn.inner.fields && fn.inner.fields[0].purity === 'unsafe_fn') { output += 'unsafe '; } if (fnType === 'Closure') { if (fn.sigil) { if (fn.sigil === 'BorrowedSigil') { output += '&amp;'; } else if (fn.sigil === 'ManagedSigil') { output += '@'; } else if (fn.sigil === 'OwnedSigil') { output += '~'; } else { throw new Error('Unknown sigil type ' + fn.sigil); } } if (fn.region) { output += "'" + fn.region._field0 + " "; } if (fn.onceness === 'once') { output += 'once '; } } output += 'fn' + (fn.name ? ' ' + fn.name : '') + vars.render_generics(fn, currentTree, fnType) + '(\n '; if (fn.inner && fn.inner.fields && fn.inner.fields[0].self_) { temp = vars.short_type(fn.inner.fields[0].self_, currentTree); if (temp) { output += temp; if (decl.inputs.length > 0) { output += ', \n '; } } } output += decl.inputs.map(function (arg) { return (arg.name ? arg.name + ': ' : '') + vars.short_type(arg.type_, currentTree); }).join(', \n '); output += '\n)'; if (decl.output !== 'Unit') { output += ' -&gt; ' + vars.short_type(decl.output, currentTree); } Twig.extend(function (Twig) { if (Twig.lib.strip_tags(output).replace(/&(gt|lt)/g, '').length < 100 || fnType !== 'fn') { output = output.replace(/\n {4}|\n/g, ''); } }); return output; }; vars.render_generics = function renderGenerics(element, currentTree, type) { var type_params, lifetimes, output = '', generics; if (type === 'Closure') { generics = {type_params: [], lifetimes: element.lifetimes}; } else if (type === 'BareFunction') { generics = element.generics; } else if (type === 'arg' || type === 'bound') { generics = {type_params: element.typarams, lifetimes: element.lifetime ? [element.lifetime] : null}; } else { generics = getGenerics(element); } if (!generics) { throw new Error('Element has invalid generics defined ' + JSON.stringify(element)); } function renderBounds(bound) { var res = ''; if (bound === 'RegionBound') { return "'static"; } if (bound.variant === 'TraitBound') { return vars.short_type(bound.fields[0], currentTree); } if (bound.fields === undefined || bound.fields[0].path === undefined) { throw new Error("Unknown bound type " + JSON.stringify(bound)); } bound = bound.fields[0].path; if (bound.name) { res += bound.name; } res += renderGenerics(bound, currentTree, 'bound'); return res; } type_params = generics.type_params || []; lifetimes = generics.lifetimes || []; if (type_params.length || lifetimes.length) { output += '&lt;'; if (lifetimes.length) { output += "'" + lifetimes.map(function (l) { return l._field0; }).join(", '"); } if (type_params.length && lifetimes.length) { output += ', '; } output += type_params.map(function (t) { var res; if (t.name) { res = t.name; } else { res = vars.short_type(t, currentTree); } if (t.bounds && t.bounds[0] !== undefined) { res += ": " + t.bounds.map(renderBounds).join(' + '); } return res; }).join(', '); output += '&gt;'; } return output; }; vars.source_url = function (element, crate) { var matches; if (!element.source) { throw new Error('Element has no source: ' + JSON.stringify(element)); } matches = element.source.match(/^([a-z0-9_.\/\-]+):(\d+):\d+:? (\d+):\d+$/i); if (!matches) { throw new Error('Could not parse element.source for ' + JSON.stringify(element)); } return config.baseSourceUrls[crate.name].replace('%version%', crate.version) + matches[1] + '#L' + matches[2] + '-' + matches[3]; }; Twig.renderFile("templates/" + template, vars, function (dummy, out) { cb(out); }); } function indexModule(path, module, typeTree, references, searchIndex) { var uid = 1, delayedIndexations = [], types = { ModuleItem: 'mods', StructItem: 'structs', EnumItem: 'enums', TraitItem: 'traits', TypedefItem: 'typedefs', FunctionItem: 'fns', StaticItem: 'statics', ImplItem: 'impls', ViewItemItem: 'reexports', }; function indexTyparams(typarams) { typarams.forEach(function (typaram) { references[typaram.id] = {type: 'typaram', def: typaram, tree: typeTree}; }); } function indexMethods(methods, parentName, parentType) { methods.forEach(function (method) { var generics; method = method.fields ? method.fields[0] : method; generics = getGenerics(method); if (generics && generics.type_params) { indexTyparams(generics.type_params); } searchIndex.push({type: 'method', name: method.name, parent: parentName, parentType: parentType, desc: shortDescription(method, true), path: getPath(typeTree).join('::')}); }); } function indexVariants(variants, parentName, parentType) { variants.forEach(function (variant) { searchIndex.push({type: 'variant', name: variant.name, parent: parentName, parentType: parentType, desc: '', path: getPath(typeTree).join('::')}); }); } function indexImpl(def) { var generics, forId = null, ofId = null; if (def.inner.fields[0].for_.variant === 'ResolvedPath') { forId = def.inner.fields[0].for_.fields[2]; } if (def.inner.fields[0].trait_) { if (def.inner.fields[0].trait_.variant === 'ResolvedPath') { ofId = def.inner.fields[0].trait_.fields[2]; } else if (def.inner.fields[0].trait_.variant === 'External') { ofId = 'trait ' + def.inner.fields[0].trait_.fields[0]; } else { throw new Error('Unknown trait definition: ' + JSON.stringify(def)); } } generics = getGenerics(def); if (generics && generics.type_params) { indexTyparams(generics.type_params); } if (ofId) { if (typeTree.implsfor[forId] === undefined) { typeTree.implsfor[forId] = []; } if (typeTree.implsof[ofId] === undefined) { typeTree.implsof[ofId] = []; } typeTree.implsfor[forId].push(def); typeTree.implsof[ofId].push(def); } else if (forId) { if (typeTree.impls[forId] === undefined) { typeTree.impls[forId] = []; } typeTree.impls[forId].push(def); } else { throw new Error('Impls should be for something or of something for a generic type ' + JSON.stringify(def)); } if (forId) { delayedIndexations.push(function () { indexMethods(def.inner.fields[0].methods, references[forId].def.name, shortenType(references[forId].type)); }); } } function indexItem(type, def) { var name = def.name, generics; if (type === 'impls') { indexImpl(def); return; } if (type === 'reexports') { typeTree[type][uid] = def; uid += 1; return; } if (type === 'mods') { def.id = path + name; typeTree.submods[name] = createTypeTreeNode(name, typeTree); delayedIndexations = delayedIndexations.concat(indexModule(path + '::' + name, def, typeTree.submods[name], references, searchIndex)); } else if (type === 'statics') { def.id = path + '::' + name; } else if (def.id === undefined) { throw new Error('Missing id on type ' + type + ' content: ' + JSON.stringify(def)); } generics = getGenerics(def); if (generics && generics.type_params) { indexTyparams(generics.type_params); } if (type === 'traits') { indexMethods(def.inner.fields[0].methods, name, shortenType(type)); } if (type === 'enums') { indexVariants(def.inner.fields[0].variants, name, shortenType(type)); } typeTree[type][def.id] = name; searchIndex.push({type: shortenType(type), name: name, path: getPath(typeTree).join('::'), desc: shortDescription(def, true)}); references[def.id] = {type: type, def: def, tree: typeTree}; } if (module.inner.variant !== 'ModuleItem') { throw new Error('Invalid module, should contain an inner module item'); } module.inner.fields.forEach(function (field) { field.items.forEach(function (item) { if (types[item.inner.variant] === undefined) { throw new Error('Unknown variant ' + item.inner.variant); } indexItem(types[item.inner.variant], item); }); }); return delayedIndexations; } function dumpModule(path, module, typeTree, references, crate, crates, version, versions) { var rootPath, matches, types, buildPath = config.outputDir + crate.version + "/" + path.replace(/::/g, '/') + '/'; types = { ModuleItem: 'mods', StructItem: 'structs', EnumItem: 'enums', TraitItem: 'traits', TypedefItem: 'typedefs', FunctionItem: 'fns', StaticItem: false, ImplItem: false, ViewItemItem: false, }; matches = path.match(/::/g); rootPath = '../../' + (matches ? new Array(matches.length + 1).join('../') : ''); function renderTemplate(type, def, filename) { var data, cb; data = { path: path, type_tree: typeTree, type: shortenType(type), root_path: rootPath, element: def, crates: crates, crate: crate, versions: versions, cur_version: crate.version, config: config, }; if (!fs.existsSync(buildPath)) { fs.mkdirSync(buildPath); } cb = function (out) { fs.writeFile(buildPath + filename, out); }; render(type + '.twig', data, references, version, cb); } renderTemplate('mods', module, "index.html"); module.inner.fields.forEach(function (field) { field.items.forEach(function (item) { var type = types[item.inner.variant]; if (type === undefined) { throw new Error('Unknown variant ' + item.inner.variant); } if (type === false) { return; } if (type === 'mods') { dumpModule(path + '::' + item.name, item, typeTree.submods[item.name], references, crate, crates, version, versions); } else { renderTemplate(type, item, shortenType(type) + '.' + item.name + '.html'); } }); }); } function renderCratesIndex(version, versions) { var data, cb; data = { root_path: '../', crates: version.crates, config: config, versions: versions, cur_version: version.version, // dummy object because we are not in a crate but the layout needs one crate: {version: version.version} }; cb = function (out) { fs.writeFile(config.outputDir + version.version + '/index.html', out); }; if (version.crates.length === 1) { cb('<DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=' + version.crates[0].name + '/index.html"></head><body></body></html>'); } else { render('crates.twig', data, {}, version, cb); } } function renderVersionsIndex(versions) { var data, cb; data = { root_path: '', versions: versions, config: config, }; cb = function (out) { fs.writeFile(config.outputDir + '/index.html', out); }; if (versions.length === 1) { cb('<DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=' + versions[0].version + '/index.html"></head><body></body></html>'); } else { render('versions.twig', data, {}, {}, cb); } } function initCrate(crate, searchIndex) { var sourceUrl, delayedIndexations, data = JSON.parse(fs.readFileSync(crate.path)); if (data.schema !== '0.8.0') { throw new Error('Unsupported schema ' + data.schema); } crate.name = data.crate.name; crate.data = data.crate.module; crate.typeTree = createTypeTreeNode(crate.name); crate.references = {}; crate.data.name = crate.name; crate.license = extract(data.crate.module.attrs, 'license').toString(); // read the link.url of the crate and take that as default if the config has no url configured sourceUrl = extract(data.crate.module.attrs, 'link'); if (sourceUrl !== '' && config.baseSourceUrls[crate.name] === undefined) { sourceUrl = extract(sourceUrl, 'url').toString(); if (sourceUrl !== '') { config.baseSourceUrls[crate.name] = sourceUrl.replace(/\/*$/, '/'); } } delayedIndexations = indexModule(crate.name, crate.data, crate.typeTree, crate.references, searchIndex); delayedIndexations.forEach(function (cb) { cb(); }); } function dumpCrate(crate, crates, version, versions) { dumpModule(crate.name, crate.data, crate.typeTree, crate.references, crate, crates, version, versions); } (function main() { var versions = []; if (!fs.existsSync(config.outputDir)) { fs.mkdirSync(config.outputDir); } globsync.glob(config.inputDir.replace(/\/*$/, '/') + '*').forEach(function (path) { var crates = [], version = path.replace(/.*?\/([^\/]+)\/$/, '$1'); globsync.glob(path + '*.json').forEach(function (path) { var crate = path.replace(/.*?\/([^\/]+)\.json$/, '$1'); crates.push({path: path, version: version}); }); versions.push({ version: version, crates: crates, prerelease: !!require('semver').valid(version), }); if (!fs.existsSync(config.outputDir + version)) { fs.mkdirSync(config.outputDir + version); } }); versions.sort(function (a, b) { if (!a.prerelease && !b.prerelease) { return require('semver').rcompare(a.version, b.version); } if (a.prerelease && !b.prerelease) { return 1; } if (b.prerelease) { return -1; } return 0; }); versions.forEach(function (version) { var searchIndex = []; version.crates.forEach(function (crate) { initCrate(crate, searchIndex); }); version.crates.sort(function (a, b) { return a.name.localeCompare(b.name); }); fs.writeFile(config.outputDir + version.version + '/search-index.js', "searchIndex = " + JSON.stringify(searchIndex)); searchIndex = []; version.crates.forEach(function (crate) { dumpCrate(crate, version.crates, version, versions); }); renderCratesIndex(version, versions); }); renderVersionsIndex(versions); }());
Ignore broken std-macros links
rustdoc.js
Ignore broken std-macros links
<ide><path>ustdoc.js <ide> if (!element.source) { <ide> throw new Error('Element has no source: ' + JSON.stringify(element)); <ide> } <add> if (element.source.match(/^<std-macros>:/)) { <add> return ''; <add> } <ide> matches = element.source.match(/^([a-z0-9_.\/\-]+):(\d+):\d+:? (\d+):\d+$/i); <ide> if (!matches) { <ide> throw new Error('Could not parse element.source for ' + JSON.stringify(element));
JavaScript
agpl-3.0
eebc8bd441817c34521f00ad6aafb6c6832f5839
0
Kagee/fixmystreet-mobile,FiksGataMi/fixmystreet-mobile,ciudadanointeligente/fixmystreet-mobile,altinukshini/fixmystreet-mobile,Kagee/fixmystreet-mobile,otmezger/fixmystreet-mobile,otmezger/fixmystreet-mobile,otmezger/fixmystreet-mobile,FiksGataMi/fixmystreet-mobile,opencorato/fixmystreet-mobile,opencorato/fixmystreet-mobile,FiksGataMi/fixmystreet-mobile,altinukshini/fixmystreet-mobile,Kagee/fixmystreet-mobile,Kagee/fixmystreet-mobile,ciudadanointeligente/fixmystreet-mobile,opencorato/fixmystreet-mobile,opencorato/fixmystreet-mobile,otmezger/fixmystreet-mobile,otmezger/fixmystreet-mobile,ciudadanointeligente/fixmystreet-mobile,ciudadanointeligente/fixmystreet-mobile,altinukshini/fixmystreet-mobile,otmezger/fixmystreet-mobile,opencorato/fixmystreet-mobile,Kagee/fixmystreet-mobile,altinukshini/fixmystreet-mobile,ciudadanointeligente/fixmystreet-mobile,Kagee/fixmystreet-mobile,opencorato/fixmystreet-mobile,FiksGataMi/fixmystreet-mobile,otmezger/fixmystreet-mobile,opencorato/fixmystreet-mobile,ciudadanointeligente/fixmystreet-mobile,ciudadanointeligente/fixmystreet-mobile,Kagee/fixmystreet-mobile
var can_geolocate = false; Storage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value)); }; Storage.prototype.getObject = function(key) { var item = this.getItem(key); // if we try to parse an empty thing on Android then // it falls over :( if ( item ) { return JSON.parse(item); } else { return null; } }; function touchmove(e) { e.preventDefault(); } function show_around( lat, long ) { pc = $('#pc').val(); localStorage.latitude = lat; localStorage.longitude = long; localStorage.pc = pc || ''; $.mobile.changePage('around.html'); return false; } function valid_postcode(pc) { var out_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])'; var in_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}'; var full_pattern = '^' + out_pattern + in_pattern + '$'; var postcode_regex = new RegExp(full_pattern); pc = pc.toUpperCase().replace(/\s+/, ''); if ( postcode_regex.test(pc) ) { return true; } return false; } function location_error( msg ) { if ( msg === '' ) { $('#location_error').remove(); return; } if ( !$('#location_error') ) { $('#postcodeForm').after('<p id="location_error"></p>'); } $('#location_error').text( msg ); } function lookup_string(q) { q = q.toLowerCase(); q = q.replace(/[^\-&\w ']/, ' '); q = q.replace(/\s+/, ' '); if (!q) { location_error("Please enter location"); return false; } var url = "http://dev.virtualearth.net/REST/v1/Locations?q=" + escape(q); url += '&c=en-GB&key=' + CONFIG.BING_API_KEY; var x = jQuery.get( url, function(data, status) { if ( status == 'success' ) { var valid_locations = 0; var latitude = 0; var longitude = 0; var multiple = []; for ( i = 0; i < data.resourceSets[0].resources.length; i++ ) { var details = data.resourceSets[0].resources[i]; if ( details.address.countryRegion != 'United Kingdom' ) { continue; } var address = details.name; latitude = details.point.coordinates[0]; longitude = details.point.coordinates[1]; latitude = latitude.toPrecision(6); longitude = longitude.toPrecision(6); multiple.push( { 'address': address, 'latitude': latitude, 'longitude': longitude } ); valid_locations += 1; } if ( valid_locations == 1 ) { show_around( latitude, longitude ); } else if ( valid_locations === 0 ) { location_error('Location not found'); $('#pc').select(); } else { location_error(''); $('#multiple').remove(); var multiple_html = '<ul id="multiple"><li>Multiple locations found, please select one:'; for ( i = 0; i < multiple.length; i++ ) { multiple_html += '<li><a href="#" onclick="show_around( ' + multiple[i].latitude + ',' + multiple[i].longitude +')">' + multiple[i].address + '</a></li>'; } multiple_html += '</ul>'; $('#front-howto').hide(); $('#postcodeForm').after( multiple_html ); } } else { location_error("Could not find your location"); } }); return false; } function locate() { $("#multiple").remove(); var pc = $('#pc').val(); if (!pc) { location_error( "Please enter your location" ); return false; } if ( valid_postcode( pc ) ) { jQuery.get( CONFIG.MAPIT_URL + 'postcode/' + pc + '.json', function(data, status) { if ( status == 'success' ) { show_around( data.wgs84_lat, data.wgs84_lon ); } else { alert('Could not locate postcode'); } }); } else { lookup_string(pc); } return false; } var watch_id = null; var watch_count = 0; function foundLocation(myLocation) { var lat = myLocation.coords.latitude; var long = myLocation.coords.longitude; watch_count++; if ( myLocation.coords.accuracy < 100 ) { navigator.geolocation.clearWatch(watch_id); show_around( lat, long ); watch_id = null; } else if ( watch_count > 10 ) { navigator.geolocation.clearWatch(watch_id); watch_id = null; $.mobile.changePage( 'frontpage-form.html' ); } } function notFoundLocation() { if ( watch_id ) { location_error( 'Could not find location' ); } else { console.log('should not be here'); } } function getPosition() { if ( !can_geolocate ) { window.setTimeout( getPosition, 200 ); return; } if ( !watch_id ) { watch_count = 0; watch_id = navigator.geolocation.watchPosition(foundLocation, notFoundLocation, { timeout: 60000, enableHighAccuracy: true } ); } else { alert('currently locating'); } } function have_gps(myLocation) { navigator.geolocation.clearWatch(watch_id); if ( watch_id ) { watch_id = null; var lat = myLocation.coords.latitude; var long = myLocation.coords.longitude; $('#have-gps').text('Determined location using GPS'); $('#make-report').show(); localStorage.latitude = lat; localStorage.longitude = long; } } function do_not_have_gps(err) { console.log(err); if ( watch_id ) { navigator.geolocation.clearWatch(watch_id); watch_id = null; $('#have-gps').text('Cannot determine location'); $('#make-report').hide(); } } function check_for_gps() { if ( !can_geolocate ) { window.setTimeout( check_for_gps, 200 ); return; } if ( !watch_id ) { watch_count = 0; watch_id = navigator.geolocation.watchPosition(have_gps, do_not_have_gps, { timeout: 60000, enableHighAccuracy: true } ); } else { alert('currently locating'); } } function create_offline() { $.mobile.changePage('submit-problem.html'); } function takePhotoSuccess(imageURI) { $('#form_photo').val(imageURI); $('#photo').attr('src', imageURI ); $('#add_photo').hide(); $('#display_photo').show(); } function delPhoto() { $('#form_photo').val(''); $('#photo').attr('src', '' ); $('#display_photo').hide(); $('#add_photo').show(); } function takePhotoFail(message) { alert('There was a problem taking your photo'); console.log('error taking picture: ' + message); } function takePhoto(type) { var save_to_album = false; if ( type == navigator.camera.PictureSourceType.CAMERA ) { save_to_album = true; } navigator.camera.getPicture(takePhotoSuccess, takePhotoFail, { saveToPhotoAlbum: save_to_album, quality: 50, destinationType: Camera.DestinationType.FILE_URI, sourceType: type }); } function check_name( name, msg ) { $('#email_label').hide(); $('#form_email').hide(); $('#now_submit').hide(); $('#have_password').hide(); $('#form_sign_in_yes').hide(); $('#let_me_confirm').hide(); $('#password_register').hide(); $('#password_surround').hide(); $('#providing_password').hide(); $('#form_name').val( name ); if ( msg ) { $('#form_name').focus(); if ( $('#form_name_error').length ) { $('#form_name_error').text(msg); } else { $('#form_name').before('<div class="form-error" id="form_name_error">' + msg + '</div>' ); } } } function remove_saved_report() { if ( localStorage.currentReport ) { var r = new Report(); r.remove(localStorage.currentReport); delete localStorage.currentReport; } } function fileUploadSuccess(r) { if ( r.response ) { var data; try { data = JSON.parse( decodeURIComponent(r.response) ); } catch(err) { data = {}; } if ( data.success ) { if ( data.report ) { localStorage.report = data.report; $.mobile.changePage('report_created.html'); } else { $.mobile.changePage('email_sent.html'); } remove_saved_report(); } else { if ( data.check_name ) { check_name( data.check_name, data.errors.name ); } else { alert('Could not submit report'); } $('input[type=submit]').prop("disabled", false); } } else { alert('Could not submit report'); $('input[type=submit]').prop("disabled", false); } } function fileUploadFail() { alert('Could not submit report'); $('input[type=submit]').prop("disabled", false); } var submit_clicked = null; function postReport(e) { $.mobile.loading( 'show' ); if ( e ) { e.preventDefault(); } // the .stopImmediatePropogation call in invalidHandler should render this // redundant but it doesn't seem to work so belt and braces :( if ( !$('#mapForm').valid() ) { return; } var params = { service: 'iphone', title: $('#form_title').val(), detail: $('#form_detail').val(), may_show_name: $('#form_may_show_name').attr('checked') ? 1 : 0, category: $('#form_category').val(), lat: $('#fixmystreet\\.latitude').val(), lon: $('#fixmystreet\\.longitude').val(), phone: $('#form_phone').val(), pc: $('#pc').val() }; if ( localStorage.username && localStorage.password && localStorage.name ) { params.name = localStorage.name; params.email = localStorage.username; params.password_sign_in = localStorage.password; params.submit_sign_in = 1; } else { if ( $('#form_name').val() !== '' ) { params.name = $('#form_name').val(); } params.email = $('#form_email').val(); params.password_sign_in = $('#password_sign_in').val(); if ( submit_clicked.attr('id') == 'submit_sign_in' ) { params.submit_sign_in = 1; } else { params.submit_register = 1; } } if ( $('#form_photo').val() !== '' ) { fileURI = $('#form_photo').val(); var options = new FileUploadOptions(); options.fileKey="photo"; options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1); options.mimeType="image/jpeg"; options.params = params; options.chunkedMode = false; var ft = new FileTransfer(); ft.upload(fileURI, CONFIG.FMS_URL + "report/new/mobile", fileUploadSuccess, fileUploadFail, options); } else { jQuery.ajax( { url: CONFIG.FMS_URL + "report/new/mobile", type: 'POST', data: params, timeout: 30000, success: function(data) { if ( data.success ) { localStorage.pc = null; localStorage.lat = null; localStorage.long = null; if ( data.report ) { localStorage.report = data.report; if ( !localStorage.name && $('#password_sign_in').val() ) { localStorage.name = $('#form_name').val(); localStorage.username = $('#form_email').val(); localStorage.password = $('#password_sign_in').val(); } $.mobile.changePage('report_created.html'); } else { $.mobile.changePage('email_sent.html'); } remove_saved_report(); } else { if ( data.check_name ) { check_name( data.check_name, data.errors.name ); } $('input[type=submit]').prop("disabled", false); } }, error: function (data, status, errorThrown ) { alert( 'There was a problem submitting your report, please try again (' + status + '): ' + JSON.stringify(data), function(){}, 'Submit report' ); $('input[type=submit]').prop("disabled", false); } } ); } return false; } function sign_in() { $('#form_email').blur(); $('#password_sign_in').blur(); jQuery.ajax( { url: CONFIG.FMS_URL + "auth/ajax/sign_in", type: 'POST', data: { email: $('#form_email').val(), password_sign_in: $('#password_sign_in').val(), remember_me: 1 }, success: function(data) { if ( data.name ) { localStorage.name = data.name; localStorage.username = $('#form_email').val(); localStorage.password = $('#password_sign_in').val(); $('#user-meta').html('<p>You are signed in as ' + localStorage.username + '.</p>'); $('#form_sign_in_only').hide(); $('#forget_button').show(); $('#form_email').val(''); $('#password_sign_in').val(''); } else { $('#form_email').before('<div class="form-error">There was a problem with your email/password combination.</div>'); } } } ); } function display_account_page() { if ( localStorage.signed_out == 1 ) { $('#user-meta').html('<p>You&rsquo;ve been signed out.</p>'); $('#form_sign_in_only').show(); localStorage.signed_out = null; } if ( localStorage.username ) { $('#user-meta').html('<p>You are signed in as ' + localStorage.username + '.</p>'); $('#form_sign_in_only').hide(); $('#forget_button').show(); } else { $('#forget_button').hide(); $('#form_sign_in_only').show(); } } function set_location() { var cross = fixmystreet.map.getControlsByClass( "OpenLayers.Control.Crosshairs"); var position = cross[0].getMapPosition(); position.transform( fixmystreet.map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326") ); localStorage.latitude = position.lat; localStorage.longitude = position.lon; $.mobile.changePage('submit-problem.html'); } function mark_here() { fixmystreet.state_pins_were_hidden = true; if ( fixmystreet.markers.getVisibility() ) { fixmystreet.state_pins_were_hidden = false; fixmystreet.markers.setVisibility(false); fixmystreet.select_feature.deactivate(); } fixmystreet.nav.deactivate(); $('#sub_map_links').hide(); var $map_box = $('#map_box'); $map_box.append( '<p id="mob_sub_map_links">' + '<a href="#" id="try_again">Try again</a>' + '<a href="#ok" id="mob_ok">Confirm</a>' + '</p>' ); $('#mark-here').hide(); $('#try_again').on('vclick', function(e){ e.preventDefault(); fixmystreet.bbox_strategy.activate(); fixmystreet.markers.refresh( { force: true } ); if ( !fixmystreet.state_pins_were_hidden ) { // If we had pins hidden when we clicked map (which had to show the pin layer as I'm doing it in one layer), hide them again. fixmystreet.markers.setVisibility(true); fixmystreet.select_feature.activate(); } $('#sub_map_links').show(); $('#mob_sub_map_links').remove(); $('#mark-here').show(); fixmystreet.nav.activate(); }); $('#mob_ok').on('vclick', set_location ); } function forget_user_details() { delete localStorage.name; delete localStorage.username; delete localStorage.password; localStorage.signed_out = 1; display_account_page(); } function onDeviceReady() { can_geolocate = true; } function get_report_params () { var params = { service: 'iphone', title: $('#form_title').val(), detail: $('#form_detail').val(), may_show_name: $('#form_may_show_name').attr('checked') ? 1 : 0, category: $('#form_category').val(), lat: $('#fixmystreet\\.latitude').val(), lon: $('#fixmystreet\\.longitude').val(), phone: $('#form_phone').val(), pc: $('#pc').val(), time: new Date() }; if ( localStorage.username && localStorage.password && localStorage.name ) { params.name = localStorage.name; params.email = localStorage.username; params.password_sign_in = localStorage.password; } else { params.name = $('#form_name').val(); params.email = $('#form_email').val(); params.password_sign_in = $('#password_sign_in').val(); } if ( $('#form_photo').val() !== '' ) { fileURI = $('#form_photo').val(); params.file = fileURI; } return params; } function _submit_save_report() { var params = get_report_params(); var r; if ( localStorage.currentReport ) { r = new Report(); r.load( localStorage.currentReport ); r.update(params); } else { r = new Report(params); } r.save(); return r; } function save_report() { _submit_save_report(); $.mobile.changePage('my_reports.html'); } function submit_back() { var r = _submit_save_report(); localStorage.currentReport = r.id(); } function display_saved_reports() { if ( localStorage.getObject( 'reports' ) ) { var r = localStorage.getObject('reports'); var list = $('<ul id="current" class="issue-list-a tab open"></ul>'); for ( i = 0; i < r.length; i++ ) { if ( r[i] && r[i].title ) { var item = $('<li class="saved-report" id="' + i + '"></li>'); var date; if ( r[i].time ) { var date_o = new Date( r[i].time ); date = date_o.getDate() + '-' + ( date_o.getMonth() + 1 ) + '-' + date_o.getFullYear(); date = date + ' ' + date_o.getHours() + ':' + date_o.getMinutes(); } else { date = ''; } var content = $('<a class="text"><h4>' + r[i].title + '</h4><small>' + date + '</small></a>'); if ( r[i].file ) { $('<img class="img" src="' + r[i].file + '" height="60" width="90">').prependTo(content); } content.appendTo(item); item.appendTo(list); } } list.appendTo('#reports'); } else { $("#reports").innerHTML('No Reports'); } } function open_saved_report_page(e) { localStorage.currentReport = this.id; $.mobile.changePage('report.html'); } function display_saved_report() { var r = new Report(); r.load(localStorage.currentReport); fixmystreet.latitude = r.lat(); fixmystreet.longitude = r.lon(); fixmystreet.pins = [ [ r.lat(), r.lon(), 'yellow', '', "", 'big' ] ]; $('#title').text(r.title); $('#details').text(r.detail); if ( r.file() ) { $('#photo').attr('src', r.file()); $('#report-img').show(); } else { $('#report-img').hide(); } } function complete_report() { var r = new Report(); r.load(localStorage.currentReport); if ( r.lat() && r.lon() ) { show_around( r.lat(), r.lon() ); } else { getPosition(); } } function delete_report() { var r = new Report(); r.load(localStorage.currentReport); r.remove(); $.mobile.changePage('my_reports.html'); } function submit_problem_show() { if ( localStorage.currentReport ) { var r = new Report(); r.load(localStorage.currentReport); $('#form_title').val(r.title()); $('#form_detail').val(r.detail()); if ( r.may_show_name() === 0 ) { $('#form_may_show_name').attr('checked', 'off'); } //category: $('#form_category').val(); $('#form_phone').val(r.phone()); $('#pc').val(r.pc()); if ( r.file() ) { $('#form_photo').val(r.file()); $('#photo').attr('src', r.file() ); $('#add_photo').hide(); $('#display_photo').show(); } } $('#mapForm').on('submit', postReport); $('#side-form, #site-logo').show(); $('#pc').val(localStorage.pc); $('#fixmystreet\\.latitude').val(localStorage.latitude); $('#fixmystreet\\.longitude').val(localStorage.longitude); if ( localStorage.offline == 1 ) { $('#councils_text').html("You are currently operating in offline mode so you can save the details of the problem but you'll need to finish reporting when you have internet access."); $('#form_category_row').hide(); $('#email_label').hide(); $('#form_email').hide(); $('#form_sign_in').hide(); } else { if ( localStorage.name ) { check_name( localStorage.name ); $('.form-focus-hidden').show(); } else { $('.form-focus-hidden').hide(); } $.getJSON( CONFIG.FMS_URL + 'report/new/ajax', { latitude: $('#fixmystreet\\.latitude').val(), longitude: $('#fixmystreet\\.longitude').val() }, function(data) { if (data.error) { // XXX If they then click back and click somewhere in the area, this error will still show. $('#side-form').html('<h1>Reporting a problem</h1><p>' + data.error + '</p>'); return; } $('#councils_text').html(data.councils_text); $('#form_category_row').html(data.category); }); } } function decide_front_page() { $.mobile.loading( 'show' ); if ( !can_geolocate ) { window.setTimeout( decide_front_page, 100 ); return; } localStorage.offline = 0; delete localStorage.currentReport; if ( navigator.network.connection.type == Connection.NONE || navigator.network.connection.type == Connection.UNKNOWN ) { localStorage.offline = 1; $.mobile.changePage( 'no_connection.html' ); } else { getPosition(); } } document.addEventListener("deviceready", onDeviceReady, false); $(document).on('pageshow', '#report-created', function() { var uri = CONFIG.FMS_URL + 'report/' + localStorage.report; $('#report_url').html( '<a href="' + uri + '">' + uri + '</a>' ); }); $(document).on('pageshow', '#front-page', decide_front_page); $(document).on('pageshow', '#account-page', display_account_page); $(document).on('pageshow', '#my-reports-page', display_saved_reports); $(document).on('pageshow', '#report-page', display_saved_report); $(document).on('pageshow', '#submit-problem', submit_problem_show); $(document).on('pageshow', '#no-connection-page', check_for_gps); $(document).bind('pageinit', function() { $('#signInForm').on('submit', sign_in); $('#postcodeForm').on('submit', locate); }); $(document).on('vclick', '#save_report', save_report); $(document).on('vclick', '#forget', forget_user_details); $(document).on('vclick', '.saved-report', open_saved_report_page); $(document).on('vclick', '#mark-here', mark_here); $(document).on('vclick', '#create_report', create_offline); $(document).on('vclick', '#complete_report', complete_report); $(document).on('vclick', '#delete_report', delete_report); $(document).on('vclick', '#id_photo_button', function() {takePhoto(navigator.camera.PictureSourceType.CAMERA);}); $(document).on('vclick', '#id_existing', function() {takePhoto(navigator.camera.PictureSourceType.SAVEDPHOTOALBUM);}); $(document).on('vclick', '#mapForm :input[type=submit]', function() { submit_clicked = $(this); }); $(document).on('vclick', '#id_del_photo_button', delPhoto); $(document).on('vclick', '#submit-header a.ui-btn-left', submit_back);
www/js/mobile.js
var can_geolocate = false; Storage.prototype.setObject = function(key, value) { this.setItem(key, JSON.stringify(value)); }; Storage.prototype.getObject = function(key) { var item = this.getItem(key); // if we try to parse an empty thing on Android then // it falls over :( if ( item ) { return JSON.parse(item); } else { return null; } }; function touchmove(e) { e.preventDefault(); } function show_around( lat, long ) { pc = $('#pc').val(); localStorage.latitude = lat; localStorage.longitude = long; localStorage.pc = pc || ''; $.mobile.changePage('around.html'); return false; } function valid_postcode(pc) { var out_pattern = '[A-PR-UWYZ]([0-9]{1,2}|([A-HIK-Y][0-9](|[0-9]|[ABEHMNPRVWXY]))|[0-9][A-HJKSTUW])'; var in_pattern = '[0-9][ABD-HJLNP-UW-Z]{2}'; var full_pattern = '^' + out_pattern + in_pattern + '$'; var postcode_regex = new RegExp(full_pattern); pc = pc.toUpperCase().replace(/\s+/, ''); if ( postcode_regex.test(pc) ) { return true; } return false; } function location_error( msg ) { if ( msg === '' ) { $('#location_error').remove(); return; } if ( !$('#location_error') ) { $('#postcodeForm').after('<p id="location_error"></p>'); } $('#location_error').text( msg ); } function lookup_string(q) { q = q.toLowerCase(); q = q.replace(/[^\-&\w ']/, ' '); q = q.replace(/\s+/, ' '); if (!q) { location_error("Please enter location"); return false; } var url = "http://dev.virtualearth.net/REST/v1/Locations?q=" + escape(q); url += '&c=en-GB&key=' + CONFIG.BING_API_KEY; var x = jQuery.get( url, function(data, status) { if ( status == 'success' ) { var valid_locations = 0; var latitude = 0; var longitude = 0; var multiple = []; for ( i = 0; i < data.resourceSets[0].resources.length; i++ ) { var details = data.resourceSets[0].resources[i]; if ( details.address.countryRegion != 'United Kingdom' ) { continue; } var address = details.name; latitude = details.point.coordinates[0]; longitude = details.point.coordinates[1]; latitude = latitude.toPrecision(6); longitude = longitude.toPrecision(6); multiple.push( { 'address': address, 'latitude': latitude, 'longitude': longitude } ); valid_locations += 1; } if ( valid_locations == 1 ) { show_around( latitude, longitude ); } else if ( valid_locations === 0 ) { location_error('Location not found'); $('#pc').select(); } else { location_error(''); $('#multiple').remove(); var multiple_html = '<ul id="multiple"><li>Multiple locations found, please select one:'; for ( i = 0; i < multiple.length; i++ ) { multiple_html += '<li><a href="#" onclick="show_around( ' + multiple[i].latitude + ',' + multiple[i].longitude +')">' + multiple[i].address + '</a></li>'; } multiple_html += '</ul>'; $('#front-howto').hide(); $('#postcodeForm').after( multiple_html ); } } else { location_error("Could not find your location"); } }); return false; } function locate() { $("#multiple").remove(); var pc = $('#pc').val(); if (!pc) { location_error( "Please enter your location" ); return false; } if ( valid_postcode( pc ) ) { jQuery.get( CONFIG.MAPIT_URL + 'postcode/' + pc + '.json', function(data, status) { if ( status == 'success' ) { show_around( data.wgs84_lat, data.wgs84_lon ); } else { alert('Could not locate postcode'); } }); } else { lookup_string(pc); } return false; } var watch_id = null; var watch_count = 0; function foundLocation(myLocation) { var lat = myLocation.coords.latitude; var long = myLocation.coords.longitude; watch_count++; if ( myLocation.coords.accuracy < 100 ) { navigator.geolocation.clearWatch(watch_id); show_around( lat, long ); watch_id = null; } else if ( watch_count > 10 ) { navigator.geolocation.clearWatch(watch_id); watch_id = null; $.mobile.changePage( 'frontpage-form.html' ); } } function notFoundLocation() { if ( watch_id ) { location_error( 'Could not find location' ); } else { console.log('should not be here'); } } function getPosition() { if ( !can_geolocate ) { window.setTimeout( getPosition, 200 ); return; } if ( !watch_id ) { watch_count = 0; watch_id = navigator.geolocation.watchPosition(foundLocation, notFoundLocation, { timeout: 60000, enableHighAccuracy: true } ); } else { alert('currently locating'); } } function have_gps(myLocation) { navigator.geolocation.clearWatch(watch_id); if ( watch_id ) { watch_id = null; var lat = myLocation.coords.latitude; var long = myLocation.coords.longitude; $('#have-gps').text('Determined location using GPS'); $('#make-report').show(); localStorage.latitude = lat; localStorage.longitude = long; } } function do_not_have_gps(err) { console.log(err); if ( watch_id ) { navigator.geolocation.clearWatch(watch_id); watch_id = null; $('#have-gps').text('Cannot determine location'); $('#make-report').hide(); } } function check_for_gps() { if ( !can_geolocate ) { window.setTimeout( check_for_gps, 200 ); return; } if ( !watch_id ) { watch_count = 0; watch_id = navigator.geolocation.watchPosition(have_gps, do_not_have_gps, { timeout: 60000, enableHighAccuracy: true } ); } else { alert('currently locating'); } } function create_offline() { $.mobile.changePage('submit-problem.html'); } function takePhotoSuccess(imageURI) { $('#form_photo').val(imageURI); $('#photo').attr('src', imageURI ); $('#add_photo').hide(); $('#display_photo').show(); } function delPhoto() { $('#form_photo').val(''); $('#photo').attr('src', '' ); $('#display_photo').hide(); $('#add_photo').show(); } function takePhotoFail(message) { alert('There was a problem taking your photo'); console.log('error taking picture: ' + message); } function takePhoto(type) { var save_to_album = false; if ( type == navigator.camera.PictureSourceType.CAMERA ) { save_to_album = true; } navigator.camera.getPicture(takePhotoSuccess, takePhotoFail, { saveToPhotoAlbum: save_to_album, quality: 50, destinationType: Camera.DestinationType.FILE_URI, sourceType: type }); } function check_name( name, msg ) { $('#email_label').hide(); $('#form_email').hide(); $('#now_submit').hide(); $('#have_password').hide(); $('#form_sign_in_yes').hide(); $('#let_me_confirm').hide(); $('#password_register').hide(); $('#password_surround').hide(); $('#providing_password').hide(); $('#form_name').val( name ); if ( msg ) { $('#form_name').focus(); if ( $('#form_name_error').length ) { $('#form_name_error').text(msg); } else { $('#form_name').before('<div class="form-error" id="form_name_error">' + msg + '</div>' ); } } } function remove_saved_report() { if ( localStorage.currentReport ) { var r = new Report(); r.remove(localStorage.currentReport); delete localStorage.currentReport; } } function fileUploadSuccess(r) { if ( r.response ) { var data; try { data = JSON.parse( decodeURIComponent(r.response) ); } catch(err) { data = {}; } if ( data.success ) { if ( data.report ) { localStorage.report = data.report; $.mobile.changePage('report_created.html'); } else { $.mobile.changePage('email_sent.html'); } remove_saved_report(); } else { if ( data.check_name ) { check_name( data.check_name, data.errors.name ); } else { alert('Could not submit report'); } $('input[type=submit]').prop("disabled", false); } } else { alert('Could not submit report'); $('input[type=submit]').prop("disabled", false); } } function fileUploadFail() { alert('Could not submit report'); $('input[type=submit]').prop("disabled", false); } var submit_clicked = null; function postReport(e) { if ( e ) { e.preventDefault(); } // the .stopImmediatePropogation call in invalidHandler should render this // redundant but it doesn't seem to work so belt and braces :( if ( !$('#mapForm').valid() ) { return; } var params = { service: 'iphone', title: $('#form_title').val(), detail: $('#form_detail').val(), may_show_name: $('#form_may_show_name').attr('checked') ? 1 : 0, category: $('#form_category').val(), lat: $('#fixmystreet\\.latitude').val(), lon: $('#fixmystreet\\.longitude').val(), phone: $('#form_phone').val(), pc: $('#pc').val() }; if ( localStorage.username && localStorage.password && localStorage.name ) { params.name = localStorage.name; params.email = localStorage.username; params.password_sign_in = localStorage.password; params.submit_sign_in = 1; } else { if ( $('#form_name').val() !== '' ) { params.name = $('#form_name').val(); } params.email = $('#form_email').val(); params.password_sign_in = $('#password_sign_in').val(); if ( submit_clicked.attr('id') == 'submit_sign_in' ) { params.submit_sign_in = 1; } else { params.submit_register = 1; } } if ( $('#form_photo').val() !== '' ) { fileURI = $('#form_photo').val(); var options = new FileUploadOptions(); options.fileKey="photo"; options.fileName=fileURI.substr(fileURI.lastIndexOf('/')+1); options.mimeType="image/jpeg"; options.params = params; options.chunkedMode = false; var ft = new FileTransfer(); ft.upload(fileURI, CONFIG.FMS_URL + "report/new/mobile", fileUploadSuccess, fileUploadFail, options); } else { jQuery.ajax( { url: CONFIG.FMS_URL + "report/new/mobile", type: 'POST', data: params, timeout: 30000, success: function(data) { if ( data.success ) { localStorage.pc = null; localStorage.lat = null; localStorage.long = null; if ( data.report ) { localStorage.report = data.report; if ( !localStorage.name && $('#password_sign_in').val() ) { localStorage.name = $('#form_name').val(); localStorage.username = $('#form_email').val(); localStorage.password = $('#password_sign_in').val(); } $.mobile.changePage('report_created.html'); } else { $.mobile.changePage('email_sent.html'); } remove_saved_report(); } else { if ( data.check_name ) { check_name( data.check_name, data.errors.name ); } $('input[type=submit]').prop("disabled", false); } }, error: function (data, status, errorThrown ) { alert( 'There was a problem submitting your report, please try again (' + status + '): ' + JSON.stringify(data), function(){}, 'Submit report' ); $('input[type=submit]').prop("disabled", false); } } ); } return false; } function sign_in() { $('#form_email').blur(); $('#password_sign_in').blur(); jQuery.ajax( { url: CONFIG.FMS_URL + "auth/ajax/sign_in", type: 'POST', data: { email: $('#form_email').val(), password_sign_in: $('#password_sign_in').val(), remember_me: 1 }, success: function(data) { if ( data.name ) { localStorage.name = data.name; localStorage.username = $('#form_email').val(); localStorage.password = $('#password_sign_in').val(); $('#user-meta').html('<p>You are signed in as ' + localStorage.username + '.</p>'); $('#form_sign_in_only').hide(); $('#forget_button').show(); $('#form_email').val(''); $('#password_sign_in').val(''); } else { $('#form_email').before('<div class="form-error">There was a problem with your email/password combination.</div>'); } } } ); } function display_account_page() { if ( localStorage.signed_out == 1 ) { $('#user-meta').html('<p>You&rsquo;ve been signed out.</p>'); $('#form_sign_in_only').show(); localStorage.signed_out = null; } if ( localStorage.username ) { $('#user-meta').html('<p>You are signed in as ' + localStorage.username + '.</p>'); $('#form_sign_in_only').hide(); $('#forget_button').show(); } else { $('#forget_button').hide(); $('#form_sign_in_only').show(); } } function set_location() { var cross = fixmystreet.map.getControlsByClass( "OpenLayers.Control.Crosshairs"); var position = cross[0].getMapPosition(); position.transform( fixmystreet.map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326") ); localStorage.latitude = position.lat; localStorage.longitude = position.lon; $.mobile.changePage('submit-problem.html'); } function mark_here() { fixmystreet.state_pins_were_hidden = true; if ( fixmystreet.markers.getVisibility() ) { fixmystreet.state_pins_were_hidden = false; fixmystreet.markers.setVisibility(false); fixmystreet.select_feature.deactivate(); } fixmystreet.nav.deactivate(); $('#sub_map_links').hide(); var $map_box = $('#map_box'); $map_box.append( '<p id="mob_sub_map_links">' + '<a href="#" id="try_again">Try again</a>' + '<a href="#ok" id="mob_ok">Confirm</a>' + '</p>' ); $('#mark-here').hide(); $('#try_again').on('vclick', function(e){ e.preventDefault(); fixmystreet.bbox_strategy.activate(); fixmystreet.markers.refresh( { force: true } ); if ( !fixmystreet.state_pins_were_hidden ) { // If we had pins hidden when we clicked map (which had to show the pin layer as I'm doing it in one layer), hide them again. fixmystreet.markers.setVisibility(true); fixmystreet.select_feature.activate(); } $('#sub_map_links').show(); $('#mob_sub_map_links').remove(); $('#mark-here').show(); fixmystreet.nav.activate(); }); $('#mob_ok').on('vclick', set_location ); } function forget_user_details() { delete localStorage.name; delete localStorage.username; delete localStorage.password; localStorage.signed_out = 1; display_account_page(); } function onDeviceReady() { can_geolocate = true; } function get_report_params () { var params = { service: 'iphone', title: $('#form_title').val(), detail: $('#form_detail').val(), may_show_name: $('#form_may_show_name').attr('checked') ? 1 : 0, category: $('#form_category').val(), lat: $('#fixmystreet\\.latitude').val(), lon: $('#fixmystreet\\.longitude').val(), phone: $('#form_phone').val(), pc: $('#pc').val(), time: new Date() }; if ( localStorage.username && localStorage.password && localStorage.name ) { params.name = localStorage.name; params.email = localStorage.username; params.password_sign_in = localStorage.password; } else { params.name = $('#form_name').val(); params.email = $('#form_email').val(); params.password_sign_in = $('#password_sign_in').val(); } if ( $('#form_photo').val() !== '' ) { fileURI = $('#form_photo').val(); params.file = fileURI; } return params; } function _submit_save_report() { var params = get_report_params(); var r; if ( localStorage.currentReport ) { r = new Report(); r.load( localStorage.currentReport ); r.update(params); } else { r = new Report(params); } r.save(); return r; } function save_report() { _submit_save_report(); $.mobile.changePage('my_reports.html'); } function submit_back() { var r = _submit_save_report(); localStorage.currentReport = r.id(); } function display_saved_reports() { if ( localStorage.getObject( 'reports' ) ) { var r = localStorage.getObject('reports'); var list = $('<ul id="current" class="issue-list-a tab open"></ul>'); for ( i = 0; i < r.length; i++ ) { if ( r[i] && r[i].title ) { var item = $('<li class="saved-report" id="' + i + '"></li>'); var date; if ( r[i].time ) { var date_o = new Date( r[i].time ); date = date_o.getDate() + '-' + ( date_o.getMonth() + 1 ) + '-' + date_o.getFullYear(); date = date + ' ' + date_o.getHours() + ':' + date_o.getMinutes(); } else { date = ''; } var content = $('<a class="text"><h4>' + r[i].title + '</h4><small>' + date + '</small></a>'); if ( r[i].file ) { $('<img class="img" src="' + r[i].file + '" height="60" width="90">').prependTo(content); } content.appendTo(item); item.appendTo(list); } } list.appendTo('#reports'); } else { $("#reports").innerHTML('No Reports'); } } function open_saved_report_page(e) { localStorage.currentReport = this.id; $.mobile.changePage('report.html'); } function display_saved_report() { var r = new Report(); r.load(localStorage.currentReport); fixmystreet.latitude = r.lat(); fixmystreet.longitude = r.lon(); fixmystreet.pins = [ [ r.lat(), r.lon(), 'yellow', '', "", 'big' ] ]; $('#title').text(r.title); $('#details').text(r.detail); if ( r.file() ) { $('#photo').attr('src', r.file()); $('#report-img').show(); } else { $('#report-img').hide(); } } function complete_report() { var r = new Report(); r.load(localStorage.currentReport); if ( r.lat() && r.lon() ) { show_around( r.lat(), r.lon() ); } else { getPosition(); } } function delete_report() { var r = new Report(); r.load(localStorage.currentReport); r.remove(); $.mobile.changePage('my_reports.html'); } function submit_problem_show() { if ( localStorage.currentReport ) { var r = new Report(); r.load(localStorage.currentReport); $('#form_title').val(r.title()); $('#form_detail').val(r.detail()); if ( r.may_show_name() === 0 ) { $('#form_may_show_name').attr('checked', 'off'); } //category: $('#form_category').val(); $('#form_phone').val(r.phone()); $('#pc').val(r.pc()); if ( r.file() ) { $('#form_photo').val(r.file()); $('#photo').attr('src', r.file() ); $('#add_photo').hide(); $('#display_photo').show(); } } $('#mapForm').on('submit', postReport); $('#side-form, #site-logo').show(); $('#pc').val(localStorage.pc); $('#fixmystreet\\.latitude').val(localStorage.latitude); $('#fixmystreet\\.longitude').val(localStorage.longitude); if ( localStorage.offline == 1 ) { $('#councils_text').html("You are currently operating in offline mode so you can save the details of the problem but you'll need to finish reporting when you have internet access."); $('#form_category_row').hide(); $('#email_label').hide(); $('#form_email').hide(); $('#form_sign_in').hide(); } else { if ( localStorage.name ) { check_name( localStorage.name ); $('.form-focus-hidden').show(); } else { $('.form-focus-hidden').hide(); } $.getJSON( CONFIG.FMS_URL + 'report/new/ajax', { latitude: $('#fixmystreet\\.latitude').val(), longitude: $('#fixmystreet\\.longitude').val() }, function(data) { if (data.error) { // XXX If they then click back and click somewhere in the area, this error will still show. $('#side-form').html('<h1>Reporting a problem</h1><p>' + data.error + '</p>'); return; } $('#councils_text').html(data.councils_text); $('#form_category_row').html(data.category); }); } } function decide_front_page() { if ( !can_geolocate ) { window.setTimeout( decide_front_page, 100 ); return; } localStorage.offline = 0; delete localStorage.currentReport; if ( navigator.network.connection.type == Connection.NONE || navigator.network.connection.type == Connection.UNKNOWN ) { localStorage.offline = 1; $.mobile.changePage( 'no_connection.html' ); } else { getPosition(); } } document.addEventListener("deviceready", onDeviceReady, false); $(document).on('pageshow', '#report-created', function() { var uri = CONFIG.FMS_URL + 'report/' + localStorage.report; $('#report_url').html( '<a href="' + uri + '">' + uri + '</a>' ); }); $(document).on('pageshow', '#front-page', decide_front_page); $(document).on('pageshow', '#account-page', display_account_page); $(document).on('pageshow', '#my-reports-page', display_saved_reports); $(document).on('pageshow', '#report-page', display_saved_report); $(document).on('pageshow', '#submit-problem', submit_problem_show); $(document).on('pageshow', '#no-connection-page', check_for_gps); $(document).bind('pageinit', function() { $('#signInForm').on('submit', sign_in); $('#postcodeForm').on('submit', locate); }); $(document).on('vclick', '#save_report', save_report); $(document).on('vclick', '#forget', forget_user_details); $(document).on('vclick', '.saved-report', open_saved_report_page); $(document).on('vclick', '#mark-here', mark_here); $(document).on('vclick', '#create_report', create_offline); $(document).on('vclick', '#complete_report', complete_report); $(document).on('vclick', '#delete_report', delete_report); $(document).on('vclick', '#id_photo_button', function() {takePhoto(navigator.camera.PictureSourceType.CAMERA);}); $(document).on('vclick', '#id_existing', function() {takePhoto(navigator.camera.PictureSourceType.SAVEDPHOTOALBUM);}); $(document).on('vclick', '#mapForm :input[type=submit]', function() { submit_clicked = $(this); }); $(document).on('vclick', '#id_del_photo_button', delPhoto); $(document).on('vclick', '#submit-header a.ui-btn-left', submit_back);
show loading screen a bit earlier for locate and report posting
www/js/mobile.js
show loading screen a bit earlier for locate and report posting
<ide><path>ww/js/mobile.js <ide> var submit_clicked = null; <ide> <ide> function postReport(e) { <add> $.mobile.loading( 'show' ); <ide> if ( e ) { <ide> e.preventDefault(); <ide> } <ide> <ide> <ide> function decide_front_page() { <add> $.mobile.loading( 'show' ); <ide> if ( !can_geolocate ) { <ide> window.setTimeout( decide_front_page, 100 ); <ide> return;
JavaScript
mit
601de2d6843a0c19c627c7d17b1047afe7dafb3d
0
jonbnewman/footwork,footworkjs/footwork,jonbnewman/footwork,reflectiveSingleton/footwork,reflectiveSingleton/footwork,footworkjs/footwork
define(['footwork', 'lodash', 'jquery', 'tools'], function(fw, _, $, tools) { describe('router', function() { beforeEach(tools.prepareTestEnv); afterEach(tools.cleanTestEnv); beforeAll(function() { fw.router.disableHistory(true); }); it('has the ability to create a router', function() { var BadRouter = function Router() { var self = fw.router.boot(); }; expect(function() { new BadRouter() }).toThrow(); var Router = function Router() { var self = fw.router.boot(this); expect(self).toBe(this); }; var vm = new Router(); expect(vm).toBeA('router'); expect(vm).toBeInstanceOf(Router); }); it('has the ability to create a router with a correctly defined namespace whos name we can retrieve', function() { var namespaceName = tools.generateNamespaceName(); var Model = function () { var self = fw.router.boot(this, { namespace: namespaceName }); }; var modelA = new Model(); expect(modelA.$namespace).toBeAn('object'); expect(modelA.$namespace.getName()).toBe(namespaceName); }); it('calls afterRender after initialize with the correct target element when creating and binding a new instance', function() { var checkForClass = 'check-for-class'; var initializeSpy; var afterRenderSpy; var ModelA = tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { afterRender: tools.expectCallOrder(1, afterRenderSpy = jasmine.createSpy('afterRenderSpy', function(containingElement) { expect(containingElement.className.indexOf(checkForClass)).not.toBe(-1); }).and.callThrough()) }); expect(afterRenderSpy).not.toHaveBeenCalled(); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(afterRenderSpy).toBe(undefined); fw.applyBindings(new ModelA(), testContainer = tools.getFixtureContainer('', '<div class="' + checkForClass + '"></div>')); expect(initializeSpy).toHaveBeenCalled(); expect(afterRenderSpy).toHaveBeenCalled(); }); it('can register and get a registered router', function() { var namespaceName = tools.generateNamespaceName(); expect(fw.router.isRegistered(namespaceName)).toBe(false); var Model = jasmine.createSpy('Model'); fw.router.register(namespaceName, Model); expect(fw.router.isRegistered(namespaceName)).toBe(true); expect(fw.router.getRegistered(namespaceName)).toBe(Model); expect(Model).not.toHaveBeenCalled(); }); it('can get all instantiated routers', function() { var Router = function() { fw.router.boot(this); }; var routers = [ new Router(), new Router() ]; expect(_.keys(fw.router.get())).lengthToBeGreaterThan(0); }); it('can get instantiated routers', function() { var routers = []; var specificRouterNamespace = tools.generateNamespaceName(); var Router = function() { fw.router.boot(this, { namespace: specificRouterNamespace }); }; var numToMake = _.random(2,15); for(var x = numToMake; x; x--) { routers.push(new Router()); } var singleRouterNamespace = tools.generateNamespaceName(); new (function() { fw.router.boot(this, { namespace: singleRouterNamespace }); })(); expect(fw.router.get(singleRouterNamespace)).toBeAn('object'); expect(fw.router.get(tools.generateNamespaceName())).toBe(undefined); expect(fw.router.get(specificRouterNamespace)).lengthToBe(numToMake); }); it('can bind to the DOM using a router declaration', function(done) { var wasInitialized = false; var namespaceName = tools.generateNamespaceName(); var RouterSpy = jasmine.createSpy('RouterSpy', function() { fw.router.boot(this, { namespace: namespaceName }); }).and.callThrough(); fw.router.register(namespaceName, RouterSpy); expect(RouterSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(RouterSpy).toHaveBeenCalledTimes(1); done(); }, ajaxWait); }); it('can bind to the DOM using a shared instance', function(done) { var namespaceName = tools.generateNamespaceName(); var boundPropertyValue = tools.randomString(); fw.viewModel.register(namespaceName, { instance: { boundProperty: boundPropertyValue } }); testContainer = tools.getFixtureContainer('<viewModel module="' + namespaceName + '">\ <span class="result" data-bind="text: boundProperty"></span>\ </viewModel>'); expect(testContainer.innerHTML.indexOf(boundPropertyValue)).toBe(-1); fw.start(testContainer); setTimeout(function() { expect(testContainer.innerHTML.indexOf(boundPropertyValue)).not.toBe(-1); done(); }, ajaxWait); }); it('can bind to the DOM using a generated instance', function(done) { var namespaceName = tools.generateNamespaceName(); var boundPropertyValue = tools.randomString(); var boundPropertyValueElement = boundPropertyValue + '-element'; var createViewModelInstance; fw.viewModel.register(namespaceName, { createViewModel: tools.expectCallOrder(0, createViewModelInstance = jasmine.createSpy('createViewModel', function(params, info) { expect(params.thing).toBe(boundPropertyValue); expect(info.element.id).toBe(boundPropertyValueElement); return { boundProperty: boundPropertyValue }; }).and.callThrough()) }); expect(createViewModelInstance).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<viewModel module="' + namespaceName + '" id="' + boundPropertyValueElement + '" params="thing: \'' + boundPropertyValue + '\'">\ <span class="result" data-bind="text: boundProperty"></span>\ </viewModel>'); fw.start(testContainer); expect(testContainer.children[0].innerHTML.indexOf(boundPropertyValue)).toBe(-1); setTimeout(function() { expect(createViewModelInstance).toHaveBeenCalled(); expect(testContainer.innerHTML.indexOf(boundPropertyValue)).not.toBe(-1); done(); }, ajaxWait); }); it('has the animation classes applied properly', function(done) { var namespaceName = tools.generateNamespaceName(); var theElement; var initializeSpy; var afterRenderSpy; fw.viewModel.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.viewModel.boot(this, { namespace: namespaceName, afterRender: tools.expectCallOrder(1, afterRenderSpy = jasmine.createSpy('afterRenderSpy', function(element) { theElement = element; expect(theElement.className.indexOf(footworkAnimationClass)).toBe(-1); }).and.callThrough()) }); }).and.callThrough())); expect(initializeSpy).not.toHaveBeenCalled(); expect(afterRenderSpy).toBe(undefined); fw.start(testContainer = tools.getFixtureContainer('<viewModel module="' + namespaceName + '"></viewModel>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); expect(afterRenderSpy).toHaveBeenCalled(); expect(theElement.className.indexOf(footworkAnimationClass)).not.toBe(-1); done(); }, ajaxWait); }); it('can nest router declarations', function(done) { var namespaceNameOuter = tools.randomString(); var namespaceNameInner = tools.randomString(); var initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this); }); fw.router.register(namespaceNameOuter, tools.expectCallOrder(0, initializeSpy)); fw.router.register(namespaceNameInner, tools.expectCallOrder(1, initializeSpy)); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceNameOuter + '">\ <router module="' + namespaceNameInner + '"></router>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalledTimes(2); done(); }, ajaxWait); }); it('can pass parameters through a router declaration', function(done) { var namespaceName = tools.generateNamespaceName(); var initializeSpy; fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function(params) { fw.router.boot(this); expect(params.testValueOne).toBe(1); expect(params.testValueTwo).toEqual([1,2,3]); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '" params="testValueOne: 1, testValueTwo: [1,2,3]"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('calls onDispose when the containing element is removed from the DOM', function(done) { var namespaceName = tools.generateNamespaceName(); var theElement; var initializeSpy; var afterRenderSpy; var onDisposeSpy; var WrapperRouter = tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this); this.showIt = fw.observable(true); }).and.callThrough()); fw.router.register(namespaceName, function() { fw.router.boot(this, { namespace: namespaceName, afterRender: tools.expectCallOrder(1, afterRenderSpy = jasmine.createSpy('afterRenderSpy', function(element) { theElement = element; expect(theElement.tagName).toBe('ROUTER'); }).and.callThrough()), onDispose: tools.expectCallOrder(2, onDisposeSpy = jasmine.createSpy('onDisposeSpy', function(element) { expect(element).toBe(theElement); }).and.callThrough()) }); }); expect(initializeSpy).not.toHaveBeenCalled(); expect(afterRenderSpy).toBe(undefined); var wrapper = new WrapperRouter(); expect(initializeSpy).toHaveBeenCalled(); expect(afterRenderSpy).toBe(undefined); fw.applyBindings(wrapper, testContainer = tools.getFixtureContainer('<div data-bind="if: showIt">\ <router module="' + namespaceName + '"></router>\ </div>')); setTimeout(function() { expect(onDisposeSpy).not.toHaveBeenCalled(); wrapper.showIt(false); expect(afterRenderSpy).toHaveBeenCalled(); expect(onDisposeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can have a registered location set and retrieved proplerly', function() { var namespaceName = tools.generateNamespaceName(); fw.router.registerLocation(namespaceName, '/bogus/path'); expect(fw.router.getLocation(namespaceName)).toBe('/bogus/path'); fw.router.registerLocation(/regexp.*/, '/bogus/path'); expect(fw.router.getLocation('regexp-model')).toBe('/bogus/path'); }); it('can have an array of models registered to a location and retrieved proplerly', function() { var namespaceNames = [ tools.generateNamespaceName(), tools.generateNamespaceName() ]; fw.router.registerLocation(namespaceNames, '/bogus/path'); expect(fw.router.getLocation(namespaceNames[0])).toBe('/bogus/path'); expect(fw.router.getLocation(namespaceNames[1])).toBe('/bogus/path'); }); it('can have a registered location with filename set and retrieved proplerly', function() { var namespaceName = tools.generateNamespaceName(); fw.router.registerLocation(namespaceName, '/bogus/path/__file__.js'); expect(fw.router.getLocation(namespaceName)).toBe('/bogus/path/__file__.js'); }); it('can have a specific file extension set and used correctly', function() { var namespaceName = tools.generateNamespaceName(); var customExtension = '.jscript'; fw.router.fileExtensions(customExtension); fw.router.registerLocation(namespaceName, '/bogus/path/'); expect(fw.router.getFileName(namespaceName)).toBe(namespaceName + customExtension); fw.router.fileExtensions('.js'); }); it('can have a callback specified as the extension with it invoked and the return value used', function() { var namespaceName = tools.generateNamespaceName(); var customExtension = '.jscriptFunction'; fw.router.fileExtensions(function(moduleName) { expect(moduleName).toBe(namespaceName); return customExtension; }); fw.router.registerLocation(namespaceName, '/bogus/path/'); expect(fw.router.getFileName(namespaceName)).toBe(namespaceName + customExtension); fw.router.fileExtensions('.js'); }); it('can load via registered router with a declarative initialization', function(done) { var namespaceName = tools.generateNamespaceName(); var initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName }); }); fw.router.register(namespaceName, initializeSpy); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can load via requirejs with a declarative initialization from a specified location', function(done) { var namespaceName = 'AMDRouter'; fw.router.registerLocation(namespaceName, 'tests/assets/fixtures/'); expect(namespaceName).not.toBeLoaded(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(namespaceName).toBeLoaded(); done(); }, ajaxWait); }); it('can load via requirejs with a declarative initialization from a specified RegExp-based location', function(done) { var namespaceName = 'AMDRouterRegexp-test'; fw.router.registerLocation(/AMDRouterRegexp-.*/, 'tests/assets/fixtures/'); expect(namespaceName).not.toBeLoaded(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(namespaceName).toBeLoaded(); done(); }, ajaxWait); }); it('can load via requirejs with a declarative initialization from a specified location with the full file name', function(done) { var namespaceName = 'AMDRouterFullName'; fw.router.registerLocation(namespaceName, 'tests/assets/fixtures/' + namespaceName + '.js'); expect(namespaceName).not.toBeLoaded(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(namespaceName).toBeLoaded(); done(); }, ajaxWait); }); it('can be nested and initialized declaratively', function(done) { var outerInitializeSpy; var innerInitializeSpy; var outerNamespaceName = tools.randomString(); var innerNamespaceName = tools.randomString(); fw.router.register(outerNamespaceName, outerInitializeSpy = jasmine.createSpy('outerInitializeSpy', function() { fw.router.boot(this, { namespace: outerNamespaceName }); }).and.callThrough()); fw.router.register(innerNamespaceName, innerInitializeSpy = jasmine.createSpy('innerInitializeSpy', function() { fw.router.boot(this, { namespace: innerNamespaceName }); }).and.callThrough()); expect(outerInitializeSpy).not.toHaveBeenCalled(); expect(innerInitializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + outerNamespaceName + '">\ <router module="' + innerNamespaceName + '"></router>\ </router>')); setTimeout(function() { expect(outerInitializeSpy).toHaveBeenCalled(); expect(innerInitializeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can trigger the unknownRoute', function(done) { var namespaceName = 'unknownRouteCheck'; var unknownRouteControllerSpy = jasmine.createSpy('unknownRouteControllerSpy'); var initializeSpy; var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: 'unknownRouteCheck', routes: [ { unknown: true, controller: tools.expectCallOrder(1, unknownRouteControllerSpy) } ] }); router = this; }).and.callThrough())); expect(unknownRouteControllerSpy).not.toHaveBeenCalled(); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.replaceState(tools.generateUrl()); expect(unknownRouteControllerSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can trigger a specified route', function(done) { var mockUrl = tools.generateUrl(); var mockUrl2 = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var routeControllerSpy = jasmine.createSpy('routeControllerSpy'); var initializeSpy; var router; fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeControllerSpy }, { route: mockUrl2, controller: routeControllerSpy } ] }); router = this; }).and.callThrough()); expect(routeControllerSpy).not.toHaveBeenCalled(); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.pushState(mockUrl); expect(routeControllerSpy).toHaveBeenCalled(); expect(router.$currentRoute().route).toBe(mockUrl); router.pushState(mockUrl2); expect(routeControllerSpy).toHaveBeenCalledTimes(2); expect(router.$currentRoute().route).toBe(mockUrl2); done(); }, ajaxWait); }); it('can trigger a specified name-based route', function(done) { var mockNamedState = tools.randomString(); var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var routeControllerSpy = jasmine.createSpy('routeControllerSpy'); var initializeSpy; var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, name: mockNamedState, controller: routeControllerSpy } ] }); router = this; }).and.callThrough())); expect(routeControllerSpy).not.toHaveBeenCalled(); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.pushState(mockNamedState, { named: true }); expect(routeControllerSpy).toHaveBeenCalled(); expect(function() {router.pushState('state-that-does-not-exist', { named: true })}).toThrow(); done(); }, ajaxWait); }); it('can trigger a specified route that is defined within an array of route strings', function(done) { var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var routeControllerSpy = jasmine.createSpy('routeControllerSpy'); var initializeSpy; var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: [ mockUrl, mockUrl + '2' ], controller: routeControllerSpy } ] }); router = this; }).and.callThrough())); expect(routeControllerSpy).not.toHaveBeenCalled(); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.replaceState(mockUrl + '2'); expect(routeControllerSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can trigger a specified route with a required parameter', function(done) { var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var routeControllerSpy; var initializeSpy; var testParam = tools.randomString(); var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl + '/:testParam', controller: tools.expectCallOrder(1, routeControllerSpy = jasmine.createSpy('routeControllerSpy', function(passedTestParam) { expect(passedTestParam).toBe(testParam); }).and.callThrough()) } ] }); router = this; }).and.callThrough())); expect(routeControllerSpy).toBe(undefined); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.replaceState(mockUrl + '/' + testParam); expect(routeControllerSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can trigger a specified route with an optional parameter with and without the parameter', function(done) { var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var routeControllerSpy; var initializeSpy; var optParamNotSuppliedSpy; var optParamSuppliedSpy; var testParam = tools.randomString(); var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl + '/optParamNotSupplied(/:testParam)', controller: tools.expectCallOrder(1, optParamNotSuppliedSpy = jasmine.createSpy('optParamNotSuppliedSpy', function(testParam) { expect(testParam).toBe(undefined); }).and.callThrough()) }, { route: mockUrl + '/optParamSupplied(/:testParam)', controller: tools.expectCallOrder(2, optParamSuppliedSpy = jasmine.createSpy('optParamSuppliedSpy', function(passedTestParam) { expect(passedTestParam).toBe(testParam); }).and.callThrough()) } ] }); router = this; }).and.callThrough())); expect(initializeSpy).not.toHaveBeenCalled(); expect(optParamNotSuppliedSpy).toBe(undefined); expect(optParamSuppliedSpy).toBe(undefined); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { router.replaceState(mockUrl + '/optParamNotSupplied'); expect(optParamNotSuppliedSpy).toHaveBeenCalled(); router.replaceState(mockUrl + '/optParamSupplied/' + testParam); expect(optParamSuppliedSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can manipulate an outlet', function(done) { var manipulateOutletUrl = tools.generateUrl(); var manipulateOutletComponentNamespace = tools.randomString(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var afterRenderSpy; var manipulateOutletControllerSpy; var clearOutletControllerSpy; var emptyOutletControllerSpy; var manipulateOutletComponentSpy; var outletOnCompleteSpy = jasmine.createSpy(); var router; var testContainer; var $testContainer; var passedInParams = { params: true }; fw.components.register(manipulateOutletComponentNamespace, { viewModel: manipulateOutletComponentSpy = jasmine.createSpy('manipulateOutletComponentSpy', function(params) { expect(params).toBe(passedInParams); }).and.callThrough(), template: '<div class="component-loaded"></div>' }); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, afterRender: afterRenderSpy = jasmine.createSpy('afterRenderSpy'), routes: [ { route: manipulateOutletUrl, controller: manipulateOutletControllerSpy = jasmine.createSpy('manipulateOutletControllerSpy', function(params) { this.outlet('output', manipulateOutletComponentNamespace, { params: passedInParams, onComplete: outletOnCompleteSpy }); }).and.callThrough() }, { route: '/clearOutlet', controller: clearOutletControllerSpy = jasmine.createSpy('clearOutletControllerSpy', function() { this.outlet('output', false); }).and.callThrough() } ] }); router = this; }).and.callThrough()); expect(manipulateOutletControllerSpy).toBe(undefined); expect(initializeSpy).not.toHaveBeenCalled(); expect(afterRenderSpy).toBe(undefined); expect(clearOutletControllerSpy).toBe(undefined); expect(manipulateOutletComponentSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <outlet name="output"></outlet>\ </router>')); $testContainer = $(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); expect(afterRenderSpy).toHaveBeenCalled(); expect($testContainer.find('outlet[name="output"]').attr('data-rendered')).not.toBe(manipulateOutletComponentNamespace); router.replaceState(manipulateOutletUrl); expect(manipulateOutletControllerSpy).toHaveBeenCalled(); setTimeout(function() { expect($testContainer.find('outlet[name="output"]').attr('data-rendered')).toBe(manipulateOutletComponentNamespace); expect($testContainer.find('outlet[name="output"] .component-loaded').length).toBe(1); router.replaceState('/clearOutlet'); expect(clearOutletControllerSpy).toHaveBeenCalled(); setTimeout(function() { expect($testContainer.find('outlet[name="output"]').attr('data-rendered')).not.toBe(manipulateOutletComponentNamespace); expect($testContainer.find('outlet[name="output"] .component-loaded').length).toBe(0); expect(outletOnCompleteSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, ajaxWait); }, ajaxWait); }); it('can see all/multiple referenced outlets defined in its context', function(done) { var namespaceName = tools.generateNamespaceName(); var initializeSpy; var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName }); router = this; }).and.callThrough())); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <outlet name="output1"></outlet>\ <outlet name="output2"></outlet>\ <outlet name="output3"></outlet>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); expect(_.keys(fw.utils.getPrivateData(router).outlets)).toEqual([ 'output1', 'output2', 'output3' ]); done(); }, ajaxWait); }); it('can properly unregister an outlet with its parent router', function(done) { var namespaceName = tools.generateNamespaceName(); var initializeSpy; var router; var outletName = tools.randomString(); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName }); this.show = fw.observable(true); router = this; }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <!-- ko if: show -->\ <outlet name="' + outletName + '"></outlet>\ <!-- /ko -->\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); expect(fw.utils.getPrivateData(router).outlets[outletName]).not.toBe(undefined); router.show(false); expect(fw.utils.getPrivateData(router).outlets[outletName]).toBe(undefined); done(); }, ajaxWait); }); it('can have callback triggered after outlet component is resolved and composed', function(done) { var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var outletCallbackName = tools.randomString(); var initializeSpy; var outletCallbackComponentSpy; var triggerOutletCallbackControllerSpy; var router; fw.components.register(outletCallbackName, { viewModel: tools.expectCallOrder(1, outletCallbackComponentSpy = jasmine.createSpy('outletCallbackComponentSpy')), template: '<div class="' + outletCallbackName + '"></div>' }); fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: function() { this.outlet('output', outletCallbackName, tools.expectCallOrder(2, triggerOutletCallbackControllerSpy = jasmine.createSpy('triggerOutletCallbackControllerSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletCallbackName).length).toBe(1); }))); } } ] }); router = this; }).and.callThrough())); expect(initializeSpy).not.toHaveBeenCalled(); expect(outletCallbackComponentSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <outlet name="output"></outlet>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.replaceState(mockUrl); expect(triggerOutletCallbackControllerSpy).not.toHaveBeenCalled(); setTimeout(function() { expect(triggerOutletCallbackControllerSpy).toHaveBeenCalled(); expect(outletCallbackComponentSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, ajaxWait); }); it('can instantiate and properly render an outlet after its router has initialized', function(done) { var outletControlingViewModelNamespace = tools.randomString(); var outletComponentNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var initializeSpy; var changeOutletControllerSpy; var outletCallbackSpy; var initializeViewModelSpy; var initializeComponentViewModelSpy; var router; var viewModel; fw.components.register(outletComponentNamespace, { viewModel: tools.expectCallOrder(3, initializeComponentViewModelSpy = jasmine.createSpy('initializeComponentViewModelSpy')), template: '<div class="' + outletComponentNamespace + '"></div>' }); fw.viewModel.register(outletControlingViewModelNamespace, tools.expectCallOrder(1, initializeViewModelSpy = jasmine.createSpy('initializeViewModelSpy', function() { fw.viewModel.boot(this, { namespace: outletControlingViewModelNamespace }); viewModel = this; this.outletVisible = fw.observable(false); }).and.callThrough())); fw.router.register(routerNamespace, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: routerNamespace, routes: [ { route: '/outletAfterRouter', controller: tools.expectCallOrder(2, changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletComponentNamespace, tools.expectCallOrder(4, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletComponentNamespace).length).toBe(1); }).and.callThrough())); }).and.callThrough()) } ] }); router = this; }).and.callThrough())); expect(initializeSpy).not.toHaveBeenCalled(); expect(initializeViewModelSpy).not.toHaveBeenCalled(); expect(initializeComponentViewModelSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <viewModel module="' + outletControlingViewModelNamespace + '">\ <div data-bind="if: outletVisible">\ <outlet name="output"></outlet>\ </div>\ </viewModel>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); expect(initializeViewModelSpy).toHaveBeenCalled(); router.replaceState('/outletAfterRouter'); expect(outletCallbackSpy).not.toHaveBeenCalled(); expect(viewModel).toBeAn('object'); viewModel.outletVisible(true); setTimeout(function() { expect(outletCallbackSpy).toHaveBeenCalled(); expect(initializeComponentViewModelSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, ajaxWait); }); it('can display a temporary loading component in place of a component that is being downloaded', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadingSpy; var outletLoaderTestLoadedSpy; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadingNamespace, { viewModel: tools.expectCallOrder(0, outletLoaderTestLoadingSpy = jasmine.createSpy('outletLoaderTestLoadingSpy')), template: '<div class="' + outletLoaderTestLoadingNamespace + '"></div>', synchronous: true }); fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: tools.expectCallOrder(2, outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy')), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: outletLoaderTestLoadingNamespace, routes: [ { route: mockUrl, controller: tools.expectCallOrder(1, changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, tools.expectCallOrder(3, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletLoaderTestLoadedNamespace).length).toBe(1); }).and.callThrough())); }).and.callThrough()) } ] }); }); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); expect(outletLoaderTestLoadingSpy).toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, 0); }); it('can display the default temporary loading component in place of a component that is being downloaded', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadedSpy; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy'), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: true, routes: [ { route: mockUrl, controller: changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.default-loading-display').length).toBe(1); }).and.callThrough()); }).and.callThrough() } ] }); }); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, 0); }); it('can display a temporary loading component (source from callback) in place of a component that is being downloaded', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadingSpy; var outletLoaderTestLoadedSpy; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadingNamespace, { viewModel: outletLoaderTestLoadingSpy = jasmine.createSpy('outletLoaderTestLoadingSpy'), template: '<div class="' + outletLoaderTestLoadingNamespace + '"></div>', synchronous: true }); fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy'), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: showDuringLoadSpy = jasmine.createSpy('showDuringLoadSpy', function(outletName, componentToDisplay) { expect(outletName).toBe('output'); return outletLoaderTestLoadingNamespace; }).and.callThrough(), routes: [ { route: mockUrl, controller: changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletLoaderTestLoadedNamespace).length).toBe(1); }).and.callThrough()); }).and.callThrough() } ] }); }); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); expect(outletLoaderTestLoadingSpy).toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, 0); }); it('can display a temporary loading component (source from callback) in place of a component that is being downloaded', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadingSpy; var outletLoaderTestLoadedSpy; var initializeRouterSpy; var showDuringLoadSpy; var theRouter; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadingNamespace, { viewModel: outletLoaderTestLoadingSpy = jasmine.createSpy('outletLoaderTestLoadingSpy'), template: '<div class="' + outletLoaderTestLoadingNamespace + '"></div>' }); fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy'), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, initializeRouterSpy = jasmine.createSpy('initializeRouterSpy', function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: showDuringLoadSpy = jasmine.createSpy('showDuringLoadSpy', function(outletName, componentToDisplay) { expect(outletName).toBe('output'); return outletLoaderTestLoadingNamespace; }).and.callThrough(), routes: [ { route: mockUrl, controller: changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletLoaderTestLoadedNamespace).length).toBe(1); }).and.callThrough()); }).and.callThrough() } ] }); theRouter = this; }).and.callThrough()); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); expect(outletLoaderTestLoadingSpy).not.toHaveBeenCalled(); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); expect(outletLoaderTestLoadingSpy).toHaveBeenCalled(); setTimeout(function() { expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, 0); }, 0); }); it('can display a temporary loading component in place of a component that is being downloaded with a custom minimum transition time', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadingSpy; var outletLoaderTestLoadedSpy; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadingNamespace, { viewModel: outletLoaderTestLoadingSpy = jasmine.createSpy('outletLoaderTestLoadingSpy'), template: '<div class="' + outletLoaderTestLoadingNamespace + '"></div>' }); fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy'), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: outletLoaderTestLoadingNamespace, minTransitionPeriod: 75, routes: [ { route: mockUrl, controller: changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletLoaderTestLoadedNamespace).length).toBe(1); }).and.callThrough()); }).and.callThrough() } ] }); }); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); expect(outletLoaderTestLoadingSpy).toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect($(testContainer).find('.fw-loaded-display.' + footworkAnimationClass)).lengthToBe(0); expect(outletCallbackSpy).not.toHaveBeenCalled(); setTimeout(function() { expect($(testContainer).find('.fw-loaded-display.' + footworkAnimationClass)).lengthToBeGreaterThan(0); expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, 140); }, 0); }, 0); }); it('can display a temporary loading component in place of a component that is being downloaded with a custom minimum transition time from callback', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadingSpy; var outletLoaderTestLoadedSpy; var minTransitionPeriodSpy; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadingNamespace, { viewModel: outletLoaderTestLoadingSpy = jasmine.createSpy('outletLoaderTestLoadingSpy'), template: '<div class="' + outletLoaderTestLoadingNamespace + '"></div>', synchronous: true }); fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy'), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: outletLoaderTestLoadingNamespace, minTransitionPeriod: minTransitionPeriodSpy = jasmine.createSpy('minTransitionPeriodSpy', function(outletName, componentToDisplay) { expect(outletName).toBe('output'); expect(componentToDisplay).toBe(outletLoaderTestLoadedNamespace); return 75; }).and.callThrough(), routes: [ { route: mockUrl, controller: changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletLoaderTestLoadedNamespace).length).toBe(1); }).and.callThrough()); }).and.callThrough() } ] }); }); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); expect(minTransitionPeriodSpy).toBe(undefined); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); expect(outletLoaderTestLoadingSpy).not.toHaveBeenCalled(); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(outletLoaderTestLoadingSpy).toHaveBeenCalled(); expect(minTransitionPeriodSpy).toHaveBeenCalled(); expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); setTimeout(function() { expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, 140); }, 0); }, 0); }); it('can have a $route bound link correctly composed with an href attribute using passed in string route', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var hashMockUrl = '#hash-only-url'; var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); function router(name) { return fw.router.get(name); } expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a class="mockUrl" data-bind="$route: \'' + mockUrl + '\'"></a>\ <a class="hashMockUrl" data-bind="$route: \'' + hashMockUrl + '\'"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); var $link = $(testContainer).find('a.mockUrl'); var $hashLink = $(testContainer).find('a.hashMockUrl'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.attr('href')).toBe(mockUrl); expect($hashLink.attr('href')).toBe(hashMockUrl); $link.click(); expect(routeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can have a $route bound link correctly composed using the elements existing href attribute', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); function router(name) { return fw.router.get(name); } expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a href="' + mockUrl + '" data-bind="$route"></a>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.attr('href')).toBe(mockUrl); $link.click(); expect(routeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can have a $route bound link correctly composed with an href attribute using an observable', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var routerNamespaceName = tools.randomString(); var viewModelNamespaceName = tools.randomString(); var viewModelInitializeSpy; var routerInitializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); var changedRouteSpy = jasmine.createSpy('changedRouteSpy'); fw.router.register(routerNamespaceName, routerInitializeSpy = jasmine.createSpy('routerInitializeSpy', function() { fw.router.boot(this, { namespace: routerNamespaceName, routes: [ { route: '/routeHrefBindingObservable', controller: routeSpy }, { route: '/routeHrefBindingObservableChangedRoute', controller: changedRouteSpy } ], }); }).and.callThrough()); fw.viewModel.register(viewModelNamespaceName, viewModelInitializeSpy = jasmine.createSpy('viewModelInitializeSpy', function() { fw.viewModel.boot(this, { namespace: viewModelNamespaceName, }); this.routeHrefBindingObservable = fw.observable('/routeHrefBindingObservable'); }).and.callThrough()); function viewModel(name) { return fw.viewModel.get(name); } expect(routerInitializeSpy).not.toHaveBeenCalled(); expect(viewModelInitializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); expect(changedRouteSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + routerNamespaceName + '">\ <viewModel module="' + viewModelNamespaceName + '">\ <a data-bind="$route: routeHrefBindingObservable"></a>\ </viewModel>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(routerInitializeSpy).toHaveBeenCalled(); expect(viewModelInitializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect(changedRouteSpy).not.toHaveBeenCalled(); expect($link.attr('href')).toBe('/routeHrefBindingObservable'); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect(changedRouteSpy).not.toHaveBeenCalled(); viewModel(viewModelNamespaceName).routeHrefBindingObservable('/routeHrefBindingObservableChangedRoute'); expect($link.attr('href')).toBe('/routeHrefBindingObservableChangedRoute'); $link.click(); expect(changedRouteSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that uses replaceState on its parent router', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); var $testContainer = $(testContainer); var routerInitialized = false; var routeTouched = false; fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', replaceState: false }"></a>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that expresses the default active class when the route matches', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); var $testContainer = $(testContainer); var routerInitialized = false; var routeTouched = false; fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: \'' + mockUrl + '\'"></a>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that expresses a custom \'active\' class when the route matches', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var activeClassName = tools.randomString(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', activeClass: \'' + activeClassName + '\' }"></a>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass(activeClassName)).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass(activeClassName)).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that expresses a custom \'active\' class on the direct parent element', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var activeClassName = tools.randomString(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <div>\ <a data-bind="$route: { url: \'' + mockUrl + '\', activeClass: \'' + activeClassName + '\', parentHasState: true }"></a>\ </div>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.parent().hasClass(activeClassName)).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.parent().hasClass(activeClassName)).toBe(true); done(); }, ajaxWait); }); it('can have a $route bound link that expresses an \'active\' class on the selected parent element', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var activeClassName = tools.randomString(); var parentClassName = tools.randomString(); var initializeSpy = jasmine.createSpy('initializeSpy'); var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <div class="parent-class-name">\ <div>\ <a data-bind="$route: { url: \'' + mockUrl + '\', activeClass: \'' + activeClassName + '\', parentHasState: \'.parent-class-name\' }"></a>\ <a data-bind="$route: { url: \'' + mockUrl + '\', activeClass: \'' + activeClassName + '\', parentHasState: \'.parent-class-name-graceful-failure-does-not-exist\' }"></a>\ </div>\ </div>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $testContainer = $(testContainer); var $link = $testContainer.find('a'); var $elementThatHasState = $testContainer.find('.parent-class-name'); expect(routeSpy).not.toHaveBeenCalled(); expect($elementThatHasState.hasClass(activeClassName)).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($elementThatHasState.hasClass(activeClassName)).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that expresses a custom \'active\' class defined by an observable when the route matches', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var routerNamespaceName = tools.randomString(); var viewModelNamespaceName = tools.randomString(); var activeClassName = tools.randomString(); var parentClassName = tools.randomString(); var viewModelInitializeSpy; var routerInitializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.viewModel.register(viewModelNamespaceName, viewModelInitializeSpy = jasmine.createSpy('viewModelInitializeSpy', function() { fw.viewModel.boot(this, { namespace: viewModelNamespaceName, }); this.activeClassObservable = fw.observable(activeClassName); }).and.callThrough()); fw.router.register(routerNamespaceName, routerInitializeSpy = jasmine.createSpy('routerInitializeSpy', function() { fw.router.boot(this, { namespace: routerNamespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(viewModelInitializeSpy).not.toHaveBeenCalled(); expect(routerInitializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + routerNamespaceName + '">\ <viewModel module="' + viewModelNamespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', activeClass: activeClassObservable }"></a>\ </viewModel>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(routerInitializeSpy).toHaveBeenCalled(); expect(viewModelInitializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass(activeClassName)).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass(activeClassName)).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that disables the active class state based on a raw boolean flag', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', addActiveClass: false }"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that disables the active class state using an observable', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); this.disableActiveClass = fw.observable(false); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', addActiveClass: disableActiveClass }"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link with its active class removed properly when the route switches away from it', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var mockUrl2 = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); var theRouter; fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy }, { route: mockUrl2, controller: routeSpy } ] }); theRouter = this; }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a class="' + mockUrl.replace('/', '') + '" data-bind="$route: \'' + mockUrl + '\'"></a>\ <a class="' + mockUrl2.replace('/', '') + '" data-bind="$route: \'' + mockUrl2 + '\'"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $mockUrl = $(testContainer).find('a.' + mockUrl.replace('/', '')); var $mockUrl2 = $(testContainer).find('a.' + mockUrl2.replace('/', '')); expect(routeSpy).not.toHaveBeenCalled(); expect($mockUrl.hasClass('active')).toBe(false); expect($mockUrl2.hasClass('active')).toBe(false); $mockUrl.click(); expect(routeSpy).toHaveBeenCalled(); expect($mockUrl.hasClass('active')).toBe(true); expect($mockUrl2.hasClass('active')).toBe(false); $mockUrl2.click(); expect(routeSpy).toHaveBeenCalledTimes(2); expect($mockUrl.hasClass('active')).toBe(false); expect($mockUrl2.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 10); }); it('can have a $route bound link that triggers based on a custom event defined by a string', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', on: \'dblclick\' }"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.dblclick(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that triggers based on a custom event defined by a callback/observable', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); this.customEvent = fw.observable('dblclick'); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', on: customEvent }"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.dblclick(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link correctly composed with a custom callback handler', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var routerNamespaceName = tools.randomString(); var viewModelNamespaceName = tools.randomString(); var viewModelInitializeSpy; var routerInitializeSpy; var customHandlerSpy; var routeSpy = jasmine.createSpy('routeSpy'); var allowHandlerEvent; fw.router.register(routerNamespaceName, routerInitializeSpy = jasmine.createSpy('routerInitializeSpy', function() { fw.router.boot(this, { namespace: routerNamespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); this.customEvent = fw.observable('dblclick'); }).and.callThrough()); fw.viewModel.register(viewModelNamespaceName, viewModelInitializeSpy = jasmine.createSpy('viewModelInitializeSpy', function() { fw.viewModel.boot(this, { namespace: viewModelNamespaceName, }); this.routeHrefBindingCustomHandler = customHandlerSpy = jasmine.createSpy('customHandlerSpy', function(event, url) { expect(event).toBeAn('object'); expect(url).toBeA('string'); return allowHandlerEvent; }).and.callThrough(); }).and.callThrough()); expect(routerInitializeSpy).not.toHaveBeenCalled(); expect(viewModelInitializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + routerNamespaceName + '">\ <viewModel module="' + viewModelNamespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', handler: routeHrefBindingCustomHandler }"></a>\ </viewModel>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(customHandlerSpy).not.toHaveBeenCalled(); expect(routerInitializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); expect($link.attr('href')).toBe(mockUrl); allowHandlerEvent = false; $link.click(); expect(routeSpy).not.toHaveBeenCalled(); expect(customHandlerSpy).toHaveBeenCalledTimes(1); expect($link.hasClass('active')).toBe(false); allowHandlerEvent = true; $link.click(); expect(routeSpy).toHaveBeenCalled(); expect(customHandlerSpy).toHaveBeenCalledTimes(2); expect($link.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link correctly composed with a custom URL callback', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var routerNamespaceName = tools.randomString(); var viewModelNamespaceName = tools.randomString(); var viewModelInitializeSpy; var initializeSpy; var urlResolverSpy; var allowHandlerEvent; fw.router.register(routerNamespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: routerNamespaceName }); this.routeHrefBindingCustomUrlCallback = urlResolverSpy = jasmine.createSpy('urlResolverSpy', function() { return mockUrl; }).and.callThrough(); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + routerNamespaceName + '">\ <a data-bind="$route: { url: routeHrefBindingCustomUrlCallback }"></a>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(urlResolverSpy).toHaveBeenCalled(); expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect($link.hasClass('active')).toBe(false); expect($link.attr('href')).toBe(mockUrl); done(); }, ajaxWait); }, 0); }); it('can trigger a route via the pushState command', function() { var namespaceName = tools.generateNamespaceName(); var mockUrl = tools.generateUrl(); var routeSpy = jasmine.createSpy('routeSpy'); var MyRouter = function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }; var router = new MyRouter(); expect(routeSpy).not.toHaveBeenCalled(); router.$activated(true); expect(routeSpy).not.toHaveBeenCalled(); fw.namespace(namespaceName).command('pushState', mockUrl); expect(routeSpy).toHaveBeenCalled(); }); it('can trigger a route via the replaceState command', function() { var namespaceName = tools.generateNamespaceName(); var mockUrl = tools.generateUrl(); var routeSpy = jasmine.createSpy('routeSpy'); var MyRouter = function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }; var router = new MyRouter(); expect(routeSpy).not.toHaveBeenCalled(); router.$activated(true); expect(routeSpy).not.toHaveBeenCalled(); fw.namespace(namespaceName).command('replaceState', mockUrl); expect(routeSpy).toHaveBeenCalled(); }); }); } );
tests/spec/router.spec.js
define(['footwork', 'lodash', 'jquery', 'tools'], function(fw, _, $, tools) { describe('router', function() { beforeEach(tools.prepareTestEnv); afterEach(tools.cleanTestEnv); beforeAll(function() { fw.router.disableHistory(true); }); it('has the ability to create a router', function() { var BadRouter = function Router() { var self = fw.router.boot(); }; expect(function() { new BadRouter() }).toThrow(); var Router = function Router() { var self = fw.router.boot(this); expect(self).toBe(this); }; var vm = new Router(); expect(vm).toBeA('router'); expect(vm).toBeInstanceOf(Router); }); it('has the ability to create a router with a correctly defined namespace whos name we can retrieve', function() { var namespaceName = tools.generateNamespaceName(); var Model = function () { var self = fw.router.boot(this, { namespace: namespaceName }); }; var modelA = new Model(); expect(modelA.$namespace).toBeAn('object'); expect(modelA.$namespace.getName()).toBe(namespaceName); }); it('calls afterRender after initialize with the correct target element when creating and binding a new instance', function() { var checkForClass = 'check-for-class'; var initializeSpy; var afterRenderSpy; var ModelA = tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { afterRender: tools.expectCallOrder(1, afterRenderSpy = jasmine.createSpy('afterRenderSpy', function(containingElement) { expect(containingElement.className.indexOf(checkForClass)).not.toBe(-1); }).and.callThrough()) }); expect(afterRenderSpy).not.toHaveBeenCalled(); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(afterRenderSpy).toBe(undefined); fw.applyBindings(new ModelA(), testContainer = tools.getFixtureContainer('', '<div class="' + checkForClass + '"></div>')); expect(initializeSpy).toHaveBeenCalled(); expect(afterRenderSpy).toHaveBeenCalled(); }); it('can register and get a registered router', function() { var namespaceName = tools.generateNamespaceName(); expect(fw.router.isRegistered(namespaceName)).toBe(false); var Model = jasmine.createSpy('Model'); fw.router.register(namespaceName, Model); expect(fw.router.isRegistered(namespaceName)).toBe(true); expect(fw.router.getRegistered(namespaceName)).toBe(Model); expect(Model).not.toHaveBeenCalled(); }); it('can get all instantiated routers', function() { var Router = function() { fw.router.boot(this); }; var routers = [ new Router(), new Router() ]; expect(_.keys(fw.router.get())).lengthToBeGreaterThan(0); }); it('can get instantiated routers', function() { var routers = []; var specificRouterNamespace = tools.generateNamespaceName(); var Router = function() { fw.router.boot(this, { namespace: specificRouterNamespace }); }; var numToMake = _.random(2,15); for(var x = numToMake; x; x--) { routers.push(new Router()); } var singleRouterNamespace = tools.generateNamespaceName(); new (function() { fw.router.boot(this, { namespace: singleRouterNamespace }); })(); expect(fw.router.get(singleRouterNamespace)).toBeAn('object'); expect(fw.router.get(tools.generateNamespaceName())).toBe(undefined); expect(fw.router.get(specificRouterNamespace)).lengthToBe(numToMake); }); it('can bind to the DOM using a router declaration', function(done) { var wasInitialized = false; var namespaceName = tools.generateNamespaceName(); var RouterSpy = jasmine.createSpy('RouterSpy', function() { fw.router.boot(this, { namespace: namespaceName }); }).and.callThrough(); fw.router.register(namespaceName, RouterSpy); expect(RouterSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(RouterSpy).toHaveBeenCalledTimes(1); done(); }, ajaxWait); }); it('can bind to the DOM using a shared instance', function(done) { var namespaceName = tools.generateNamespaceName(); var boundPropertyValue = tools.randomString(); fw.viewModel.register(namespaceName, { instance: { boundProperty: boundPropertyValue } }); testContainer = tools.getFixtureContainer('<viewModel module="' + namespaceName + '">\ <span class="result" data-bind="text: boundProperty"></span>\ </viewModel>'); expect(testContainer.innerHTML.indexOf(boundPropertyValue)).toBe(-1); fw.start(testContainer); setTimeout(function() { expect(testContainer.innerHTML.indexOf(boundPropertyValue)).not.toBe(-1); done(); }, ajaxWait); }); it('can bind to the DOM using a generated instance', function(done) { var namespaceName = tools.generateNamespaceName(); var boundPropertyValue = tools.randomString(); var boundPropertyValueElement = boundPropertyValue + '-element'; var createViewModelInstance; fw.viewModel.register(namespaceName, { createViewModel: tools.expectCallOrder(0, createViewModelInstance = jasmine.createSpy('createViewModel', function(params, info) { expect(params.thing).toBe(boundPropertyValue); expect(info.element.id).toBe(boundPropertyValueElement); return { boundProperty: boundPropertyValue }; }).and.callThrough()) }); expect(createViewModelInstance).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<viewModel module="' + namespaceName + '" id="' + boundPropertyValueElement + '" params="thing: \'' + boundPropertyValue + '\'">\ <span class="result" data-bind="text: boundProperty"></span>\ </viewModel>'); fw.start(testContainer); expect(testContainer.children[0].innerHTML.indexOf(boundPropertyValue)).toBe(-1); setTimeout(function() { expect(createViewModelInstance).toHaveBeenCalled(); expect(testContainer.innerHTML.indexOf(boundPropertyValue)).not.toBe(-1); done(); }, ajaxWait); }); it('has the animation classes applied properly', function(done) { var namespaceName = tools.generateNamespaceName(); var theElement; var initializeSpy; var afterRenderSpy; fw.viewModel.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.viewModel.boot(this, { namespace: namespaceName, afterRender: tools.expectCallOrder(1, afterRenderSpy = jasmine.createSpy('afterRenderSpy', function(element) { theElement = element; expect(theElement.className.indexOf(footworkAnimationClass)).toBe(-1); }).and.callThrough()) }); }).and.callThrough())); expect(initializeSpy).not.toHaveBeenCalled(); expect(afterRenderSpy).toBe(undefined); fw.start(testContainer = tools.getFixtureContainer('<viewModel module="' + namespaceName + '"></viewModel>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); expect(afterRenderSpy).toHaveBeenCalled(); expect(theElement.className.indexOf(footworkAnimationClass)).not.toBe(-1); done(); }, ajaxWait); }); it('can nest router declarations', function(done) { var namespaceNameOuter = tools.randomString(); var namespaceNameInner = tools.randomString(); var initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this); }); fw.router.register(namespaceNameOuter, tools.expectCallOrder(0, initializeSpy)); fw.router.register(namespaceNameInner, tools.expectCallOrder(1, initializeSpy)); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceNameOuter + '">\ <router module="' + namespaceNameInner + '"></router>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalledTimes(2); done(); }, ajaxWait); }); it('can pass parameters through a router declaration', function(done) { var namespaceName = tools.generateNamespaceName(); var initializeSpy; fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function(params) { fw.router.boot(this); expect(params.testValueOne).toBe(1); expect(params.testValueTwo).toEqual([1,2,3]); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '" params="testValueOne: 1, testValueTwo: [1,2,3]"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('calls onDispose when the containing element is removed from the DOM', function(done) { var namespaceName = tools.generateNamespaceName(); var theElement; var initializeSpy; var afterRenderSpy; var onDisposeSpy; var WrapperRouter = tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this); this.showIt = fw.observable(true); }).and.callThrough()); fw.router.register(namespaceName, function() { fw.router.boot(this, { namespace: namespaceName, afterRender: tools.expectCallOrder(1, afterRenderSpy = jasmine.createSpy('afterRenderSpy', function(element) { theElement = element; expect(theElement.tagName).toBe('ROUTER'); }).and.callThrough()), onDispose: tools.expectCallOrder(2, onDisposeSpy = jasmine.createSpy('onDisposeSpy', function(element) { expect(element).toBe(theElement); }).and.callThrough()) }); }); expect(initializeSpy).not.toHaveBeenCalled(); expect(afterRenderSpy).toBe(undefined); var wrapper = new WrapperRouter(); expect(initializeSpy).toHaveBeenCalled(); expect(afterRenderSpy).toBe(undefined); fw.applyBindings(wrapper, testContainer = tools.getFixtureContainer('<div data-bind="if: showIt">\ <router module="' + namespaceName + '"></router>\ </div>')); setTimeout(function() { expect(onDisposeSpy).not.toHaveBeenCalled(); wrapper.showIt(false); expect(afterRenderSpy).toHaveBeenCalled(); expect(onDisposeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can have a registered location set and retrieved proplerly', function() { var namespaceName = tools.generateNamespaceName(); fw.router.registerLocation(namespaceName, '/bogus/path'); expect(fw.router.getLocation(namespaceName)).toBe('/bogus/path'); fw.router.registerLocation(/regexp.*/, '/bogus/path'); expect(fw.router.getLocation('regexp-model')).toBe('/bogus/path'); }); it('can have an array of models registered to a location and retrieved proplerly', function() { var namespaceNames = [ tools.generateNamespaceName(), tools.generateNamespaceName() ]; fw.router.registerLocation(namespaceNames, '/bogus/path'); expect(fw.router.getLocation(namespaceNames[0])).toBe('/bogus/path'); expect(fw.router.getLocation(namespaceNames[1])).toBe('/bogus/path'); }); it('can have a registered location with filename set and retrieved proplerly', function() { var namespaceName = tools.generateNamespaceName(); fw.router.registerLocation(namespaceName, '/bogus/path/__file__.js'); expect(fw.router.getLocation(namespaceName)).toBe('/bogus/path/__file__.js'); }); it('can have a specific file extension set and used correctly', function() { var namespaceName = tools.generateNamespaceName(); var customExtension = '.jscript'; fw.router.fileExtensions(customExtension); fw.router.registerLocation(namespaceName, '/bogus/path/'); expect(fw.router.getFileName(namespaceName)).toBe(namespaceName + customExtension); fw.router.fileExtensions('.js'); }); it('can have a callback specified as the extension with it invoked and the return value used', function() { var namespaceName = tools.generateNamespaceName(); var customExtension = '.jscriptFunction'; fw.router.fileExtensions(function(moduleName) { expect(moduleName).toBe(namespaceName); return customExtension; }); fw.router.registerLocation(namespaceName, '/bogus/path/'); expect(fw.router.getFileName(namespaceName)).toBe(namespaceName + customExtension); fw.router.fileExtensions('.js'); }); it('can load via registered router with a declarative initialization', function(done) { var namespaceName = tools.generateNamespaceName(); var initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName }); }); fw.router.register(namespaceName, initializeSpy); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can load via requirejs with a declarative initialization from a specified location', function(done) { var namespaceName = 'AMDRouter'; fw.router.registerLocation(namespaceName, 'tests/assets/fixtures/'); expect(namespaceName).not.toBeLoaded(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(namespaceName).toBeLoaded(); done(); }, ajaxWait); }); it('can load via requirejs with a declarative initialization from a specified RegExp-based location', function(done) { var namespaceName = 'AMDRouterRegexp-test'; fw.router.registerLocation(/AMDRouterRegexp-.*/, 'tests/assets/fixtures/'); expect(namespaceName).not.toBeLoaded(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(namespaceName).toBeLoaded(); done(); }, ajaxWait); }); it('can load via requirejs with a declarative initialization from a specified location with the full file name', function(done) { var namespaceName = 'AMDRouterFullName'; fw.router.registerLocation(namespaceName, 'tests/assets/fixtures/' + namespaceName + '.js'); expect(namespaceName).not.toBeLoaded(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(namespaceName).toBeLoaded(); done(); }, ajaxWait); }); it('can be nested and initialized declaratively', function(done) { var outerInitializeSpy; var innerInitializeSpy; var outerNamespaceName = tools.randomString(); var innerNamespaceName = tools.randomString(); fw.router.register(outerNamespaceName, outerInitializeSpy = jasmine.createSpy('outerInitializeSpy', function() { fw.router.boot(this, { namespace: outerNamespaceName }); }).and.callThrough()); fw.router.register(innerNamespaceName, innerInitializeSpy = jasmine.createSpy('innerInitializeSpy', function() { fw.router.boot(this, { namespace: innerNamespaceName }); }).and.callThrough()); expect(outerInitializeSpy).not.toHaveBeenCalled(); expect(innerInitializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + outerNamespaceName + '">\ <router module="' + innerNamespaceName + '"></router>\ </router>')); setTimeout(function() { expect(outerInitializeSpy).toHaveBeenCalled(); expect(innerInitializeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can trigger the unknownRoute', function(done) { var namespaceName = 'unknownRouteCheck'; var unknownRouteControllerSpy = jasmine.createSpy('unknownRouteControllerSpy'); var initializeSpy; var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: 'unknownRouteCheck', routes: [ { unknown: true, controller: tools.expectCallOrder(1, unknownRouteControllerSpy) } ] }); router = this; }).and.callThrough())); expect(unknownRouteControllerSpy).not.toHaveBeenCalled(); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.replaceState(tools.generateUrl()); expect(unknownRouteControllerSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can trigger a specified route', function(done) { var mockUrl = tools.generateUrl(); var mockUrl2 = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var routeControllerSpy = jasmine.createSpy('routeControllerSpy'); var initializeSpy; var router; fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeControllerSpy }, { route: mockUrl2, controller: routeControllerSpy } ] }); router = this; }).and.callThrough()); expect(routeControllerSpy).not.toHaveBeenCalled(); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.pushState(mockUrl); expect(routeControllerSpy).toHaveBeenCalled(); expect(router.$currentRoute().route).toBe(mockUrl); router.pushState(mockUrl2); expect(routeControllerSpy).toHaveBeenCalledTimes(2); expect(router.$currentRoute().route).toBe(mockUrl2); done(); }, ajaxWait); }); it('can trigger a specified name-based route', function(done) { var mockNamedState = tools.randomString(); var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var routeControllerSpy = jasmine.createSpy('routeControllerSpy'); var initializeSpy; var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, name: mockNamedState, controller: routeControllerSpy } ] }); router = this; }).and.callThrough())); expect(routeControllerSpy).not.toHaveBeenCalled(); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.replaceState(mockNamedState, { named: true }); expect(routeControllerSpy).toHaveBeenCalled(); expect(function() {router.replaceState('state-that-does-not-exist', { named: true })}).toThrow(); done(); }, ajaxWait); }); it('can trigger a specified route that is defined within an array of route strings', function(done) { var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var routeControllerSpy = jasmine.createSpy('routeControllerSpy'); var initializeSpy; var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: [ mockUrl, mockUrl + '2' ], controller: routeControllerSpy } ] }); router = this; }).and.callThrough())); expect(routeControllerSpy).not.toHaveBeenCalled(); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.replaceState(mockUrl + '2'); expect(routeControllerSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can trigger a specified route with a required parameter', function(done) { var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var routeControllerSpy; var initializeSpy; var testParam = tools.randomString(); var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl + '/:testParam', controller: tools.expectCallOrder(1, routeControllerSpy = jasmine.createSpy('routeControllerSpy', function(passedTestParam) { expect(passedTestParam).toBe(testParam); }).and.callThrough()) } ] }); router = this; }).and.callThrough())); expect(routeControllerSpy).toBe(undefined); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.replaceState(mockUrl + '/' + testParam); expect(routeControllerSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can trigger a specified route with an optional parameter with and without the parameter', function(done) { var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var routeControllerSpy; var initializeSpy; var optParamNotSuppliedSpy; var optParamSuppliedSpy; var testParam = tools.randomString(); var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl + '/optParamNotSupplied(/:testParam)', controller: tools.expectCallOrder(1, optParamNotSuppliedSpy = jasmine.createSpy('optParamNotSuppliedSpy', function(testParam) { expect(testParam).toBe(undefined); }).and.callThrough()) }, { route: mockUrl + '/optParamSupplied(/:testParam)', controller: tools.expectCallOrder(2, optParamSuppliedSpy = jasmine.createSpy('optParamSuppliedSpy', function(passedTestParam) { expect(passedTestParam).toBe(testParam); }).and.callThrough()) } ] }); router = this; }).and.callThrough())); expect(initializeSpy).not.toHaveBeenCalled(); expect(optParamNotSuppliedSpy).toBe(undefined); expect(optParamSuppliedSpy).toBe(undefined); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '"></router>')); setTimeout(function() { router.replaceState(mockUrl + '/optParamNotSupplied'); expect(optParamNotSuppliedSpy).toHaveBeenCalled(); router.replaceState(mockUrl + '/optParamSupplied/' + testParam); expect(optParamSuppliedSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can manipulate an outlet', function(done) { var manipulateOutletUrl = tools.generateUrl(); var manipulateOutletComponentNamespace = tools.randomString(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var afterRenderSpy; var manipulateOutletControllerSpy; var clearOutletControllerSpy; var emptyOutletControllerSpy; var manipulateOutletComponentSpy; var outletOnCompleteSpy = jasmine.createSpy(); var router; var testContainer; var $testContainer; var passedInParams = { params: true }; fw.components.register(manipulateOutletComponentNamespace, { viewModel: manipulateOutletComponentSpy = jasmine.createSpy('manipulateOutletComponentSpy', function(params) { expect(params).toBe(passedInParams); }).and.callThrough(), template: '<div class="component-loaded"></div>' }); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, afterRender: afterRenderSpy = jasmine.createSpy('afterRenderSpy'), routes: [ { route: manipulateOutletUrl, controller: manipulateOutletControllerSpy = jasmine.createSpy('manipulateOutletControllerSpy', function(params) { this.outlet('output', manipulateOutletComponentNamespace, { params: passedInParams, onComplete: outletOnCompleteSpy }); }).and.callThrough() }, { route: '/clearOutlet', controller: clearOutletControllerSpy = jasmine.createSpy('clearOutletControllerSpy', function() { this.outlet('output', false); }).and.callThrough() } ] }); router = this; }).and.callThrough()); expect(manipulateOutletControllerSpy).toBe(undefined); expect(initializeSpy).not.toHaveBeenCalled(); expect(afterRenderSpy).toBe(undefined); expect(clearOutletControllerSpy).toBe(undefined); expect(manipulateOutletComponentSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <outlet name="output"></outlet>\ </router>')); $testContainer = $(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); expect(afterRenderSpy).toHaveBeenCalled(); expect($testContainer.find('outlet[name="output"]').attr('data-rendered')).not.toBe(manipulateOutletComponentNamespace); router.replaceState(manipulateOutletUrl); expect(manipulateOutletControllerSpy).toHaveBeenCalled(); setTimeout(function() { expect($testContainer.find('outlet[name="output"]').attr('data-rendered')).toBe(manipulateOutletComponentNamespace); expect($testContainer.find('outlet[name="output"] .component-loaded').length).toBe(1); router.replaceState('/clearOutlet'); expect(clearOutletControllerSpy).toHaveBeenCalled(); setTimeout(function() { expect($testContainer.find('outlet[name="output"]').attr('data-rendered')).not.toBe(manipulateOutletComponentNamespace); expect($testContainer.find('outlet[name="output"] .component-loaded').length).toBe(0); expect(outletOnCompleteSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, ajaxWait); }, ajaxWait); }); it('can see all/multiple referenced outlets defined in its context', function(done) { var namespaceName = tools.generateNamespaceName(); var initializeSpy; var router; fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName }); router = this; }).and.callThrough())); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <outlet name="output1"></outlet>\ <outlet name="output2"></outlet>\ <outlet name="output3"></outlet>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); expect(_.keys(fw.utils.getPrivateData(router).outlets)).toEqual([ 'output1', 'output2', 'output3' ]); done(); }, ajaxWait); }); it('can properly unregister an outlet with its parent router', function(done) { var namespaceName = tools.generateNamespaceName(); var initializeSpy; var router; var outletName = tools.randomString(); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName }); this.show = fw.observable(true); router = this; }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <!-- ko if: show -->\ <outlet name="' + outletName + '"></outlet>\ <!-- /ko -->\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); expect(fw.utils.getPrivateData(router).outlets[outletName]).not.toBe(undefined); router.show(false); expect(fw.utils.getPrivateData(router).outlets[outletName]).toBe(undefined); done(); }, ajaxWait); }); it('can have callback triggered after outlet component is resolved and composed', function(done) { var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var outletCallbackName = tools.randomString(); var initializeSpy; var outletCallbackComponentSpy; var triggerOutletCallbackControllerSpy; var router; fw.components.register(outletCallbackName, { viewModel: tools.expectCallOrder(1, outletCallbackComponentSpy = jasmine.createSpy('outletCallbackComponentSpy')), template: '<div class="' + outletCallbackName + '"></div>' }); fw.router.register(namespaceName, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: function() { this.outlet('output', outletCallbackName, tools.expectCallOrder(2, triggerOutletCallbackControllerSpy = jasmine.createSpy('triggerOutletCallbackControllerSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletCallbackName).length).toBe(1); }))); } } ] }); router = this; }).and.callThrough())); expect(initializeSpy).not.toHaveBeenCalled(); expect(outletCallbackComponentSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <outlet name="output"></outlet>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); router.replaceState(mockUrl); expect(triggerOutletCallbackControllerSpy).not.toHaveBeenCalled(); setTimeout(function() { expect(triggerOutletCallbackControllerSpy).toHaveBeenCalled(); expect(outletCallbackComponentSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, ajaxWait); }); it('can instantiate and properly render an outlet after its router has initialized', function(done) { var outletControlingViewModelNamespace = tools.randomString(); var outletComponentNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var initializeSpy; var changeOutletControllerSpy; var outletCallbackSpy; var initializeViewModelSpy; var initializeComponentViewModelSpy; var router; var viewModel; fw.components.register(outletComponentNamespace, { viewModel: tools.expectCallOrder(3, initializeComponentViewModelSpy = jasmine.createSpy('initializeComponentViewModelSpy')), template: '<div class="' + outletComponentNamespace + '"></div>' }); fw.viewModel.register(outletControlingViewModelNamespace, tools.expectCallOrder(1, initializeViewModelSpy = jasmine.createSpy('initializeViewModelSpy', function() { fw.viewModel.boot(this, { namespace: outletControlingViewModelNamespace }); viewModel = this; this.outletVisible = fw.observable(false); }).and.callThrough())); fw.router.register(routerNamespace, tools.expectCallOrder(0, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: routerNamespace, routes: [ { route: '/outletAfterRouter', controller: tools.expectCallOrder(2, changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletComponentNamespace, tools.expectCallOrder(4, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletComponentNamespace).length).toBe(1); }).and.callThrough())); }).and.callThrough()) } ] }); router = this; }).and.callThrough())); expect(initializeSpy).not.toHaveBeenCalled(); expect(initializeViewModelSpy).not.toHaveBeenCalled(); expect(initializeComponentViewModelSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <viewModel module="' + outletControlingViewModelNamespace + '">\ <div data-bind="if: outletVisible">\ <outlet name="output"></outlet>\ </div>\ </viewModel>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); expect(initializeViewModelSpy).toHaveBeenCalled(); router.replaceState('/outletAfterRouter'); expect(outletCallbackSpy).not.toHaveBeenCalled(); expect(viewModel).toBeAn('object'); viewModel.outletVisible(true); setTimeout(function() { expect(outletCallbackSpy).toHaveBeenCalled(); expect(initializeComponentViewModelSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, ajaxWait); }); it('can display a temporary loading component in place of a component that is being downloaded', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadingSpy; var outletLoaderTestLoadedSpy; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadingNamespace, { viewModel: tools.expectCallOrder(0, outletLoaderTestLoadingSpy = jasmine.createSpy('outletLoaderTestLoadingSpy')), template: '<div class="' + outletLoaderTestLoadingNamespace + '"></div>', synchronous: true }); fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: tools.expectCallOrder(2, outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy')), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: outletLoaderTestLoadingNamespace, routes: [ { route: mockUrl, controller: tools.expectCallOrder(1, changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, tools.expectCallOrder(3, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletLoaderTestLoadedNamespace).length).toBe(1); }).and.callThrough())); }).and.callThrough()) } ] }); }); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); expect(outletLoaderTestLoadingSpy).toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, 0); }); it('can display the default temporary loading component in place of a component that is being downloaded', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadedSpy; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy'), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: true, routes: [ { route: mockUrl, controller: changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.default-loading-display').length).toBe(1); }).and.callThrough()); }).and.callThrough() } ] }); }); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, 0); }); it('can display a temporary loading component (source from callback) in place of a component that is being downloaded', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadingSpy; var outletLoaderTestLoadedSpy; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadingNamespace, { viewModel: outletLoaderTestLoadingSpy = jasmine.createSpy('outletLoaderTestLoadingSpy'), template: '<div class="' + outletLoaderTestLoadingNamespace + '"></div>', synchronous: true }); fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy'), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: showDuringLoadSpy = jasmine.createSpy('showDuringLoadSpy', function(outletName, componentToDisplay) { expect(outletName).toBe('output'); return outletLoaderTestLoadingNamespace; }).and.callThrough(), routes: [ { route: mockUrl, controller: changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletLoaderTestLoadedNamespace).length).toBe(1); }).and.callThrough()); }).and.callThrough() } ] }); }); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); expect(outletLoaderTestLoadingSpy).toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, 0); }); it('can display a temporary loading component (source from callback) in place of a component that is being downloaded', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadingSpy; var outletLoaderTestLoadedSpy; var initializeRouterSpy; var showDuringLoadSpy; var theRouter; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadingNamespace, { viewModel: outletLoaderTestLoadingSpy = jasmine.createSpy('outletLoaderTestLoadingSpy'), template: '<div class="' + outletLoaderTestLoadingNamespace + '"></div>' }); fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy'), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, initializeRouterSpy = jasmine.createSpy('initializeRouterSpy', function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: showDuringLoadSpy = jasmine.createSpy('showDuringLoadSpy', function(outletName, componentToDisplay) { expect(outletName).toBe('output'); return outletLoaderTestLoadingNamespace; }).and.callThrough(), routes: [ { route: mockUrl, controller: changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletLoaderTestLoadedNamespace).length).toBe(1); }).and.callThrough()); }).and.callThrough() } ] }); theRouter = this; }).and.callThrough()); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); expect(outletLoaderTestLoadingSpy).not.toHaveBeenCalled(); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); expect(outletLoaderTestLoadingSpy).toHaveBeenCalled(); setTimeout(function() { expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, 0); }, 0); }); it('can display a temporary loading component in place of a component that is being downloaded with a custom minimum transition time', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadingSpy; var outletLoaderTestLoadedSpy; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadingNamespace, { viewModel: outletLoaderTestLoadingSpy = jasmine.createSpy('outletLoaderTestLoadingSpy'), template: '<div class="' + outletLoaderTestLoadingNamespace + '"></div>' }); fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy'), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: outletLoaderTestLoadingNamespace, minTransitionPeriod: 75, routes: [ { route: mockUrl, controller: changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletLoaderTestLoadedNamespace).length).toBe(1); }).and.callThrough()); }).and.callThrough() } ] }); }); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); expect(outletLoaderTestLoadingSpy).toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect($(testContainer).find('.fw-loaded-display.' + footworkAnimationClass)).lengthToBe(0); expect(outletCallbackSpy).not.toHaveBeenCalled(); setTimeout(function() { expect($(testContainer).find('.fw-loaded-display.' + footworkAnimationClass)).lengthToBeGreaterThan(0); expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, 140); }, 0); }, 0); }); it('can display a temporary loading component in place of a component that is being downloaded with a custom minimum transition time from callback', function(done) { var mockUrl = tools.generateUrl(); var outletLoaderTestLoadingNamespace = tools.randomString(); var outletLoaderTestLoadedNamespace = tools.randomString(); var routerNamespace = tools.randomString(); var changeOutletControllerSpy; var outletCallbackSpy; var outletLoaderTestLoadingSpy; var outletLoaderTestLoadedSpy; var minTransitionPeriodSpy; function router(name) { return fw.router.get(name); } fw.components.register(outletLoaderTestLoadingNamespace, { viewModel: outletLoaderTestLoadingSpy = jasmine.createSpy('outletLoaderTestLoadingSpy'), template: '<div class="' + outletLoaderTestLoadingNamespace + '"></div>', synchronous: true }); fw.components.register(outletLoaderTestLoadedNamespace, { viewModel: outletLoaderTestLoadedSpy = jasmine.createSpy('outletLoaderTestLoadedSpy'), template: '<div class="' + outletLoaderTestLoadedNamespace + '"></div>' }); fw.router.register(routerNamespace, function() { fw.router.boot(this, { namespace: routerNamespace, showDuringLoad: outletLoaderTestLoadingNamespace, minTransitionPeriod: minTransitionPeriodSpy = jasmine.createSpy('minTransitionPeriodSpy', function(outletName, componentToDisplay) { expect(outletName).toBe('output'); expect(componentToDisplay).toBe(outletLoaderTestLoadedNamespace); return 75; }).and.callThrough(), routes: [ { route: mockUrl, controller: changeOutletControllerSpy = jasmine.createSpy('changeOutletControllerSpy', function() { this.outlet('output', outletLoaderTestLoadedNamespace, outletCallbackSpy = jasmine.createSpy('outletCallbackSpy', function(element) { expect(element.tagName.toLowerCase()).toBe('outlet'); expect($(element).find('.' + outletLoaderTestLoadedNamespace).length).toBe(1); }).and.callThrough()); }).and.callThrough() } ] }); }); expect(changeOutletControllerSpy).toBe(undefined); expect(outletLoaderTestLoadedSpy).not.toHaveBeenCalled(); expect(minTransitionPeriodSpy).toBe(undefined); fw.start(testContainer = tools.getFixtureContainer('<router module="' + routerNamespace + '">\ <outlet name="output"></outlet>\ </router>')); expect(outletLoaderTestLoadingSpy).not.toHaveBeenCalled(); setTimeout(function() { router(routerNamespace).replaceState(mockUrl); expect(outletLoaderTestLoadingSpy).toHaveBeenCalled(); expect(minTransitionPeriodSpy).toHaveBeenCalled(); expect(changeOutletControllerSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); setTimeout(function() { expect(outletLoaderTestLoadedSpy).toHaveBeenCalled(); expect(outletCallbackSpy).not.toHaveBeenCalled(); setTimeout(function() { expect(outletCallbackSpy).toHaveBeenCalled(); done(); }, 140); }, 0); }, 0); }); it('can have a $route bound link correctly composed with an href attribute using passed in string route', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var hashMockUrl = '#hash-only-url'; var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); function router(name) { return fw.router.get(name); } expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a class="mockUrl" data-bind="$route: \'' + mockUrl + '\'"></a>\ <a class="hashMockUrl" data-bind="$route: \'' + hashMockUrl + '\'"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); var $link = $(testContainer).find('a.mockUrl'); var $hashLink = $(testContainer).find('a.hashMockUrl'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.attr('href')).toBe(mockUrl); expect($hashLink.attr('href')).toBe(hashMockUrl); $link.click(); expect(routeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can have a $route bound link correctly composed using the elements existing href attribute', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); function router(name) { return fw.router.get(name); } expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a href="' + mockUrl + '" data-bind="$route"></a>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.attr('href')).toBe(mockUrl); $link.click(); expect(routeSpy).toHaveBeenCalled(); done(); }, ajaxWait); }); it('can have a $route bound link correctly composed with an href attribute using an observable', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var routerNamespaceName = tools.randomString(); var viewModelNamespaceName = tools.randomString(); var viewModelInitializeSpy; var routerInitializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); var changedRouteSpy = jasmine.createSpy('changedRouteSpy'); fw.router.register(routerNamespaceName, routerInitializeSpy = jasmine.createSpy('routerInitializeSpy', function() { fw.router.boot(this, { namespace: routerNamespaceName, routes: [ { route: '/routeHrefBindingObservable', controller: routeSpy }, { route: '/routeHrefBindingObservableChangedRoute', controller: changedRouteSpy } ], }); }).and.callThrough()); fw.viewModel.register(viewModelNamespaceName, viewModelInitializeSpy = jasmine.createSpy('viewModelInitializeSpy', function() { fw.viewModel.boot(this, { namespace: viewModelNamespaceName, }); this.routeHrefBindingObservable = fw.observable('/routeHrefBindingObservable'); }).and.callThrough()); function viewModel(name) { return fw.viewModel.get(name); } expect(routerInitializeSpy).not.toHaveBeenCalled(); expect(viewModelInitializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); expect(changedRouteSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + routerNamespaceName + '">\ <viewModel module="' + viewModelNamespaceName + '">\ <a data-bind="$route: routeHrefBindingObservable"></a>\ </viewModel>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(routerInitializeSpy).toHaveBeenCalled(); expect(viewModelInitializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect(changedRouteSpy).not.toHaveBeenCalled(); expect($link.attr('href')).toBe('/routeHrefBindingObservable'); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect(changedRouteSpy).not.toHaveBeenCalled(); viewModel(viewModelNamespaceName).routeHrefBindingObservable('/routeHrefBindingObservableChangedRoute'); expect($link.attr('href')).toBe('/routeHrefBindingObservableChangedRoute'); $link.click(); expect(changedRouteSpy).toHaveBeenCalled(); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that uses replaceState on its parent router', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); var $testContainer = $(testContainer); var routerInitialized = false; var routeTouched = false; fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', replaceState: false }"></a>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that expresses the default active class when the route matches', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); var $testContainer = $(testContainer); var routerInitialized = false; var routeTouched = false; fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: \'' + mockUrl + '\'"></a>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that expresses a custom \'active\' class when the route matches', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var activeClassName = tools.randomString(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', activeClass: \'' + activeClassName + '\' }"></a>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass(activeClassName)).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass(activeClassName)).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that expresses a custom \'active\' class on the direct parent element', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var activeClassName = tools.randomString(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <div>\ <a data-bind="$route: { url: \'' + mockUrl + '\', activeClass: \'' + activeClassName + '\', parentHasState: true }"></a>\ </div>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.parent().hasClass(activeClassName)).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.parent().hasClass(activeClassName)).toBe(true); done(); }, ajaxWait); }); it('can have a $route bound link that expresses an \'active\' class on the selected parent element', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var activeClassName = tools.randomString(); var parentClassName = tools.randomString(); var initializeSpy = jasmine.createSpy('initializeSpy'); var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <div class="parent-class-name">\ <div>\ <a data-bind="$route: { url: \'' + mockUrl + '\', activeClass: \'' + activeClassName + '\', parentHasState: \'.parent-class-name\' }"></a>\ <a data-bind="$route: { url: \'' + mockUrl + '\', activeClass: \'' + activeClassName + '\', parentHasState: \'.parent-class-name-graceful-failure-does-not-exist\' }"></a>\ </div>\ </div>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $testContainer = $(testContainer); var $link = $testContainer.find('a'); var $elementThatHasState = $testContainer.find('.parent-class-name'); expect(routeSpy).not.toHaveBeenCalled(); expect($elementThatHasState.hasClass(activeClassName)).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($elementThatHasState.hasClass(activeClassName)).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that expresses a custom \'active\' class defined by an observable when the route matches', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var routerNamespaceName = tools.randomString(); var viewModelNamespaceName = tools.randomString(); var activeClassName = tools.randomString(); var parentClassName = tools.randomString(); var viewModelInitializeSpy; var routerInitializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.viewModel.register(viewModelNamespaceName, viewModelInitializeSpy = jasmine.createSpy('viewModelInitializeSpy', function() { fw.viewModel.boot(this, { namespace: viewModelNamespaceName, }); this.activeClassObservable = fw.observable(activeClassName); }).and.callThrough()); fw.router.register(routerNamespaceName, routerInitializeSpy = jasmine.createSpy('routerInitializeSpy', function() { fw.router.boot(this, { namespace: routerNamespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(viewModelInitializeSpy).not.toHaveBeenCalled(); expect(routerInitializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + routerNamespaceName + '">\ <viewModel module="' + viewModelNamespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', activeClass: activeClassObservable }"></a>\ </viewModel>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(routerInitializeSpy).toHaveBeenCalled(); expect(viewModelInitializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass(activeClassName)).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass(activeClassName)).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that disables the active class state based on a raw boolean flag', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', addActiveClass: false }"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that disables the active class state using an observable', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); this.disableActiveClass = fw.observable(false); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', addActiveClass: disableActiveClass }"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.click(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link with its active class removed properly when the route switches away from it', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var mockUrl2 = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); var theRouter; fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy }, { route: mockUrl2, controller: routeSpy } ] }); theRouter = this; }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a class="' + mockUrl.replace('/', '') + '" data-bind="$route: \'' + mockUrl + '\'"></a>\ <a class="' + mockUrl2.replace('/', '') + '" data-bind="$route: \'' + mockUrl2 + '\'"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $mockUrl = $(testContainer).find('a.' + mockUrl.replace('/', '')); var $mockUrl2 = $(testContainer).find('a.' + mockUrl2.replace('/', '')); expect(routeSpy).not.toHaveBeenCalled(); expect($mockUrl.hasClass('active')).toBe(false); expect($mockUrl2.hasClass('active')).toBe(false); $mockUrl.click(); expect(routeSpy).toHaveBeenCalled(); expect($mockUrl.hasClass('active')).toBe(true); expect($mockUrl2.hasClass('active')).toBe(false); $mockUrl2.click(); expect(routeSpy).toHaveBeenCalledTimes(2); expect($mockUrl.hasClass('active')).toBe(false); expect($mockUrl2.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 10); }); it('can have a $route bound link that triggers based on a custom event defined by a string', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', on: \'dblclick\' }"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.dblclick(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link that triggers based on a custom event defined by a callback/observable', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var namespaceName = tools.generateNamespaceName(); var initializeSpy; var routeSpy = jasmine.createSpy('routeSpy'); fw.router.register(namespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); this.customEvent = fw.observable('dblclick'); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); fw.start(testContainer = tools.getFixtureContainer('<router module="' + namespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', on: customEvent }"></a>\ </router>')); setTimeout(function() { expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); $link.dblclick(); expect(routeSpy).toHaveBeenCalled(); expect($link.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link correctly composed with a custom callback handler', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var routerNamespaceName = tools.randomString(); var viewModelNamespaceName = tools.randomString(); var viewModelInitializeSpy; var routerInitializeSpy; var customHandlerSpy; var routeSpy = jasmine.createSpy('routeSpy'); var allowHandlerEvent; fw.router.register(routerNamespaceName, routerInitializeSpy = jasmine.createSpy('routerInitializeSpy', function() { fw.router.boot(this, { namespace: routerNamespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); this.customEvent = fw.observable('dblclick'); }).and.callThrough()); fw.viewModel.register(viewModelNamespaceName, viewModelInitializeSpy = jasmine.createSpy('viewModelInitializeSpy', function() { fw.viewModel.boot(this, { namespace: viewModelNamespaceName, }); this.routeHrefBindingCustomHandler = customHandlerSpy = jasmine.createSpy('customHandlerSpy', function(event, url) { expect(event).toBeAn('object'); expect(url).toBeA('string'); return allowHandlerEvent; }).and.callThrough(); }).and.callThrough()); expect(routerInitializeSpy).not.toHaveBeenCalled(); expect(viewModelInitializeSpy).not.toHaveBeenCalled(); expect(routeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + routerNamespaceName + '">\ <viewModel module="' + viewModelNamespaceName + '">\ <a data-bind="$route: { url: \'' + mockUrl + '\', handler: routeHrefBindingCustomHandler }"></a>\ </viewModel>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(customHandlerSpy).not.toHaveBeenCalled(); expect(routerInitializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect(routeSpy).not.toHaveBeenCalled(); expect($link.hasClass('active')).toBe(false); expect($link.attr('href')).toBe(mockUrl); allowHandlerEvent = false; $link.click(); expect(routeSpy).not.toHaveBeenCalled(); expect(customHandlerSpy).toHaveBeenCalledTimes(1); expect($link.hasClass('active')).toBe(false); allowHandlerEvent = true; $link.click(); expect(routeSpy).toHaveBeenCalled(); expect(customHandlerSpy).toHaveBeenCalledTimes(2); expect($link.hasClass('active')).toBe(true); done(); }, ajaxWait); }, 0); }); it('can have a $route bound link correctly composed with a custom URL callback', function(done) { var testContainer; var mockUrl = tools.generateUrl(); var routerNamespaceName = tools.randomString(); var viewModelNamespaceName = tools.randomString(); var viewModelInitializeSpy; var initializeSpy; var urlResolverSpy; var allowHandlerEvent; fw.router.register(routerNamespaceName, initializeSpy = jasmine.createSpy('initializeSpy', function() { fw.router.boot(this, { namespace: routerNamespaceName }); this.routeHrefBindingCustomUrlCallback = urlResolverSpy = jasmine.createSpy('urlResolverSpy', function() { return mockUrl; }).and.callThrough(); }).and.callThrough()); expect(initializeSpy).not.toHaveBeenCalled(); testContainer = tools.getFixtureContainer('<router module="' + routerNamespaceName + '">\ <a data-bind="$route: { url: routeHrefBindingCustomUrlCallback }"></a>\ </router>'); fw.start(testContainer); setTimeout(function() { expect(urlResolverSpy).toHaveBeenCalled(); expect(initializeSpy).toHaveBeenCalled(); setTimeout(function() { var $link = $(testContainer).find('a'); expect($link.hasClass('active')).toBe(false); expect($link.attr('href')).toBe(mockUrl); done(); }, ajaxWait); }, 0); }); it('can trigger a route via the pushState command', function() { var namespaceName = tools.generateNamespaceName(); var mockUrl = tools.generateUrl(); var routeSpy = jasmine.createSpy('routeSpy'); var MyRouter = function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }; var router = new MyRouter(); expect(routeSpy).not.toHaveBeenCalled(); router.$activated(true); expect(routeSpy).not.toHaveBeenCalled(); fw.namespace(namespaceName).command('pushState', mockUrl); expect(routeSpy).toHaveBeenCalled(); }); it('can trigger a route via the replaceState command', function() { var namespaceName = tools.generateNamespaceName(); var mockUrl = tools.generateUrl(); var routeSpy = jasmine.createSpy('routeSpy'); var MyRouter = function() { fw.router.boot(this, { namespace: namespaceName, routes: [ { route: mockUrl, controller: routeSpy } ] }); }; var router = new MyRouter(); expect(routeSpy).not.toHaveBeenCalled(); router.$activated(true); expect(routeSpy).not.toHaveBeenCalled(); fw.namespace(namespaceName).command('replaceState', mockUrl); expect(routeSpy).toHaveBeenCalled(); }); }); } );
router test now using pushState
tests/spec/router.spec.js
router test now using pushState
<ide><path>ests/spec/router.spec.js <ide> <ide> setTimeout(function() { <ide> expect(initializeSpy).toHaveBeenCalled(); <del> router.replaceState(mockNamedState, { named: true }); <add> router.pushState(mockNamedState, { named: true }); <ide> expect(routeControllerSpy).toHaveBeenCalled(); <ide> <del> expect(function() {router.replaceState('state-that-does-not-exist', { named: true })}).toThrow(); <add> expect(function() {router.pushState('state-that-does-not-exist', { named: true })}).toThrow(); <ide> <ide> done(); <ide> }, ajaxWait);
Java
apache-2.0
7275eed576bbae437a8c8bdd37e7093ff0a49e85
0
cloudant/sync-android,cloudant/sync-android
/* * Copyright (c) 2013, 2016 IBM Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.cloudant.sync.replication; import com.cloudant.sync.datastore.DocumentRevsList; import com.google.common.base.Preconditions; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; /** * Handles calling CouchClient.getDocWithOpenRevisions() for a batch of revisions IDs, with * multiple simultaneous HTTP threads, returning the results back in a manner which can be iterated * over (to avoid deserialising the entire result into memory). * * For each revision ID, gets the revision tree for a given document ID and lists of open * revision IDs * and "atts_since" (revision IDs for which we know we have attachments) * * The document id and open revisions are from one row of change feeds. For example, for the * following change feed: * * { * "last_seq": 35, * "results": [ * { "changes": * [ { "rev": "1-bd42b942b8b672f0289cf3cd1f67044c" } ], * "id": "2013-09-23T20:50:56.251Z", * "seq": 27 * }, * { "changes": * [ { "rev": "29-3f4dabfb32290e557ac1d16b2e8f069c" }, * { "rev": "29-01fcbf8a3f1457eff21e18f7766d3b45" }, * { "rev": "26-30722da17ad35cf1860f126dba391d67" } * ], * "id": "2013-09-10T17:47:17.770Z", * "seq": 35 * } * ] * } * * For document with id "2013-09-10T17:47:17.770Z", it has open revisions: * * [ * { "rev": "29-3f4dabfb32290e557ac1d16b2e8f069c" }, * { "rev": "29-01fcbf8a3f1457eff21e18f7766d3b45" }, * { "rev": "26-30722da17ad35cf1860f126dba391d67" } * ] */ class GetRevisionTaskThreaded implements Iterable<DocumentRevsList> { private static final Logger logger = Logger.getLogger(GetRevisionTaskThreaded.class .getCanonicalName()); // this should be a sensible number of threads but we may make this configurable in future private static final int threads = Runtime.getRuntime().availableProcessors() * 2; private static final ThreadPoolExecutor executorService; static { // A static thread pool allows it to be shared between all tasks, reducing the overheads of // thread creation and destruction, but at the expense of sharing threads between all // replications (within the classloader/android application). // On a large number of batches this offers a 4-5% improvement over creating a thread pool // for each task instance. ThreadPoolExecutor tpe = new ThreadPoolExecutor(threads, threads, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()); // Allowing core threads to timeout means we don't keep threads in memory except when // replication tasks are running. tpe.allowCoreThreadTimeOut(true); executorService = tpe; } // members used to make requests: private final QueuingExecutorCompletionService<BulkGetRequest, DocumentRevsList> completionService; private final CouchDB sourceDb; private final Queue<BulkGetRequest> requests = new ConcurrentLinkedQueue<BulkGetRequest>(); private final boolean pullAttachmentsInline; // members used to handle responses: private boolean iteratorValid = true; // timeout for poll() int responseTimeout = 5; TimeUnit responseTimeoutUnits = TimeUnit.MINUTES; public GetRevisionTaskThreaded(CouchDB sourceDb, List<BulkGetRequest> requests, boolean pullAttachmentsInline) { Preconditions.checkNotNull(sourceDb, "sourceDb cannot be null"); Preconditions.checkNotNull(requests, "requests cannot be null"); for (BulkGetRequest request : requests) { Preconditions.checkNotNull(request.id, "id cannot be null"); Preconditions.checkNotNull(request.revs, "revs cannot be null"); } this.sourceDb = sourceDb; this.requests.addAll(requests); this.pullAttachmentsInline = pullAttachmentsInline; this.completionService = new QueuingExecutorCompletionService<BulkGetRequest, DocumentRevsList>(executorService, this.requests, threads + 1) { @Override public DocumentRevsList executeRequest(BulkGetRequest request) { // since this is part of a thread pool, we'll rename each thread as it takes a task. Thread.currentThread().setName("GetRevisionThread: "+GetRevisionTaskThreaded.this.sourceDb.getIdentifier()); return new DocumentRevsList(GetRevisionTaskThreaded.this.sourceDb.getRevisions (request.id, request.revs, request.atts_since, GetRevisionTaskThreaded.this.pullAttachmentsInline)); } }; } @Override public Iterator<DocumentRevsList> iterator() { return new GetRevisionTaskIterator(); } @Override public String toString() { return "GetRevisionTask{" + "sourceDb=" + sourceDb + ", requests=" + requests + ", pullAttachmentsInline=" + pullAttachmentsInline + '}'; } private class GetRevisionTaskIterator implements Iterator<DocumentRevsList> { @Override public boolean hasNext() { // can't advance iterator as there was a problem in call() if (!iteratorValid) { return false; } boolean next = completionService.hasRequestsOutstanding(); // if we have returned all of our results, we can shut down the executor if (!next) { iteratorValid = false; } return next; } @Override public DocumentRevsList next() { // can't advance iterator as there was a problem in call() if (!iteratorValid) { throw new NoSuchElementException("Iterator has been invalidated"); } try { Future<DocumentRevsList> pollResult = completionService.poll(responseTimeout, responseTimeoutUnits); if (pollResult == null) { throw new NoSuchElementException("Poll timed out"); } return pollResult.get(); } catch (InterruptedException ie) { iteratorValid = false; throw new RuntimeException(ie); } catch (ExecutionException ee) { iteratorValid = false; throw new RuntimeException("Problem getting response from queue because the " + "original request threw an exception: ", ee.getCause()); } } @Override public void remove() { throw new UnsupportedOperationException("Not supported"); } } }
cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/replication/GetRevisionTaskThreaded.java
/* * Copyright (c) 2013, 2016 IBM Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.cloudant.sync.replication; import com.cloudant.sync.datastore.DocumentRevsList; import com.google.common.base.Preconditions; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; /** * Handles calling CouchClient.getDocWithOpenRevisions() for a batch of revisions IDs, with * multiple simultaneous HTTP threads, returning the results back in a manner which can be iterated * over (to avoid deserialising the entire result into memory). * * For each revision ID, gets the revision tree for a given document ID and lists of open * revision IDs * and "atts_since" (revision IDs for which we know we have attachments) * * The document id and open revisions are from one row of change feeds. For example, for the * following change feed: * * { * "last_seq": 35, * "results": [ * { "changes": * [ { "rev": "1-bd42b942b8b672f0289cf3cd1f67044c" } ], * "id": "2013-09-23T20:50:56.251Z", * "seq": 27 * }, * { "changes": * [ { "rev": "29-3f4dabfb32290e557ac1d16b2e8f069c" }, * { "rev": "29-01fcbf8a3f1457eff21e18f7766d3b45" }, * { "rev": "26-30722da17ad35cf1860f126dba391d67" } * ], * "id": "2013-09-10T17:47:17.770Z", * "seq": 35 * } * ] * } * * For document with id "2013-09-10T17:47:17.770Z", it has open revisions: * * [ * { "rev": "29-3f4dabfb32290e557ac1d16b2e8f069c" }, * { "rev": "29-01fcbf8a3f1457eff21e18f7766d3b45" }, * { "rev": "26-30722da17ad35cf1860f126dba391d67" } * ] */ class GetRevisionTaskThreaded implements Iterable<DocumentRevsList> { private static final Logger logger = Logger.getLogger(GetRevisionTaskThreaded.class .getCanonicalName()); // this should be a sensible number of threads but we may make this configurable in future private static final int threads = Runtime.getRuntime().availableProcessors() * 2; private static final ThreadPoolExecutor executorService; static { // A static thread pool allows it to be shared between all tasks, reducing the overheads of // thread creation and destruction, but at the expense of sharing threads between all // replications (within the classloader/android application). // On a large number of batches this offers a 4-5% improvement over creating a thread pool // for each task instance. ThreadPoolExecutor tpe = new ThreadPoolExecutor(threads, threads, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()); // Allowing core threads to timeout means we don't keep threads in memory except when // replication tasks are running. tpe.allowCoreThreadTimeOut(true); executorService = tpe; } // members used to make requests: private final QueuingExecutorCompletionService<BulkGetRequest, DocumentRevsList> completionService; private final CouchDB sourceDb; private final Queue<BulkGetRequest> requests = new ConcurrentLinkedQueue<BulkGetRequest>(); private final boolean pullAttachmentsInline; // members used to handle responses: private boolean iteratorValid = true; // timeout for poll() int responseTimeout = 5; TimeUnit responseTimeoutUnits = TimeUnit.MINUTES; public GetRevisionTaskThreaded(CouchDB sourceDb, List<BulkGetRequest> requests, boolean pullAttachmentsInline) { Preconditions.checkNotNull(sourceDb, "sourceDb cannot be null"); Preconditions.checkNotNull(requests, "requests cannot be null"); for (BulkGetRequest request : requests) { Preconditions.checkNotNull(request.id, "id cannot be null"); Preconditions.checkNotNull(request.revs, "revs cannot be null"); } this.sourceDb = sourceDb; this.requests.addAll(requests); this.pullAttachmentsInline = pullAttachmentsInline; this.completionService = new QueuingExecutorCompletionService<BulkGetRequest, DocumentRevsList>(executorService, this.requests, threads + 1) { @Override public DocumentRevsList executeRequest(BulkGetRequest request) { return new DocumentRevsList(GetRevisionTaskThreaded.this.sourceDb.getRevisions (request.id, request.revs, request.atts_since, GetRevisionTaskThreaded.this.pullAttachmentsInline)); } }; } @Override public Iterator<DocumentRevsList> iterator() { return new GetRevisionTaskIterator(); } @Override public String toString() { return "GetRevisionTask{" + "sourceDb=" + sourceDb + ", requests=" + requests + ", pullAttachmentsInline=" + pullAttachmentsInline + '}'; } private class GetRevisionTaskIterator implements Iterator<DocumentRevsList> { @Override public boolean hasNext() { // can't advance iterator as there was a problem in call() if (!iteratorValid) { return false; } boolean next = completionService.hasRequestsOutstanding(); // if we have returned all of our results, we can shut down the executor if (!next) { iteratorValid = false; } return next; } @Override public DocumentRevsList next() { // can't advance iterator as there was a problem in call() if (!iteratorValid) { throw new NoSuchElementException("Iterator has been invalidated"); } try { Future<DocumentRevsList> pollResult = completionService.poll(responseTimeout, responseTimeoutUnits); if (pollResult == null) { throw new NoSuchElementException("Poll timed out"); } return pollResult.get(); } catch (InterruptedException ie) { iteratorValid = false; throw new RuntimeException(ie); } catch (ExecutionException ee) { iteratorValid = false; throw new RuntimeException("Problem getting response from queue because the " + "original request threw an exception: ", ee.getCause()); } } @Override public void remove() { throw new UnsupportedOperationException("Not supported"); } } }
Name Threads in the ThreadPool for PullReplications Each time a request is being made the remote, the thread will be renamed to be in the form of "GetRevisionThread: <RemoteIdentifier>". The name is set during the executeRequest call because the threads are reused between replicator instances.
cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/replication/GetRevisionTaskThreaded.java
Name Threads in the ThreadPool for PullReplications
<ide><path>loudant-sync-datastore-core/src/main/java/com/cloudant/sync/replication/GetRevisionTaskThreaded.java <ide> import java.util.concurrent.ExecutionException; <ide> import java.util.concurrent.Future; <ide> import java.util.concurrent.LinkedBlockingQueue; <add>import java.util.concurrent.ThreadFactory; <ide> import java.util.concurrent.ThreadPoolExecutor; <ide> import java.util.concurrent.TimeUnit; <ide> import java.util.logging.Logger; <ide> DocumentRevsList>(executorService, this.requests, threads + 1) { <ide> @Override <ide> public DocumentRevsList executeRequest(BulkGetRequest request) { <add> // since this is part of a thread pool, we'll rename each thread as it takes a task. <add> Thread.currentThread().setName("GetRevisionThread: "+GetRevisionTaskThreaded.this.sourceDb.getIdentifier()); <ide> return new DocumentRevsList(GetRevisionTaskThreaded.this.sourceDb.getRevisions <ide> (request.id, request.revs, request.atts_since, <ide> GetRevisionTaskThreaded.this.pullAttachmentsInline));
Java
apache-2.0
b5eb956ddb90ac2c19d775034d6a251c7bfe9af1
0
FasterXML/jackson-core,FasterXML/jackson-core
package com.fasterxml.jackson.core.io; import java.math.BigDecimal; import java.util.Arrays; // Based on a great idea of Eric Obermühlner to use a tree of smaller BigDecimals for parsing // really big numbers with O(n^1.5) complexity instead of O(n^2) when using the constructor // for a decimal representation from JDK 8/11: // // https://github.com/eobermuhlner/big-math/commit/7a5419aac8b2adba2aa700ccf00197f97b2ad89f /** * Helper class used to implement more optimized parsing of {@link BigDecimal} for REALLY * big values (over 500 characters) *<p> * Based on ideas from this * <a href="https://github.com/eobermuhlner/big-math/commit/7a5419aac8b2adba2aa700ccf00197f97b2ad89f">this * git commit</a>. * * @since 2.13 */ public final class BigDecimalParser { private final static int MAX_CHARS_TO_REPORT = 1000; private final char[] chars; BigDecimalParser(char[] chars) { this.chars = chars; } public static BigDecimal parse(String valueStr) { return parse(valueStr.toCharArray()); } public static BigDecimal parse(char[] chars, int off, int len) { try { if (len < 500) { return new BigDecimal(chars, off, len); } chars = Arrays.copyOfRange(chars, off, off+len); return new BigDecimalParser(chars).parseBigDecimal(len / 10); } catch (NumberFormatException e) { String desc = e.getMessage(); // 05-Feb-2021, tatu: Alas, JDK mostly has null message so: if (desc == null) { desc = "Not a valid number representation"; } String stringToReport; if (len <= MAX_CHARS_TO_REPORT) { stringToReport = new String(chars, off, len); } else { stringToReport = new String(Arrays.copyOfRange(chars, off, MAX_CHARS_TO_REPORT)) + "(truncated, full length is " + chars.length + " chars)"; } throw new NumberFormatException("Value \"" + stringToReport + "\" can not be represented as `java.math.BigDecimal`, reason: " + desc); } } public static BigDecimal parse(char[] chars) { return parse(chars, 0, chars.length); } private BigDecimal parseBigDecimal(final int splitLen) { boolean numHasSign = false; boolean expHasSign = false; boolean neg = false; int numIdx = 0; int expIdx = -1; int dotIdx = -1; int scale = 0; final int len = chars.length; for (int i = 0; i < len; i++) { char c = chars[i]; switch (c) { case '+': if (expIdx >= 0) { if (expHasSign) { throw new NumberFormatException("Multiple signs in exponent"); } expHasSign = true; } else { if (numHasSign) { throw new NumberFormatException("Multiple signs in number"); } numHasSign = true; numIdx = i + 1; } break; case '-': if (expIdx >= 0) { if (expHasSign) { throw new NumberFormatException("Multiple signs in exponent"); } expHasSign = true; } else { if (numHasSign) { throw new NumberFormatException("Multiple signs in number"); } numHasSign = true; neg = true; numIdx = i + 1; } break; case 'e': case 'E': if (expIdx >= 0) { throw new NumberFormatException("Multiple exponent markers"); } expIdx = i; break; case '.': if (dotIdx >= 0) { throw new NumberFormatException("Multiple decimal points"); } dotIdx = i; break; default: if (dotIdx >= 0 && expIdx == -1) { scale++; } } } int numEndIdx; int exp = 0; if (expIdx >= 0) { numEndIdx = expIdx; String expStr = new String(chars, expIdx + 1, len - expIdx - 1); exp = Integer.parseInt(expStr); scale = adjustScale(scale, exp); } else { numEndIdx = len; } BigDecimal res; if (dotIdx >= 0) { int leftLen = dotIdx - numIdx; BigDecimal left = toBigDecimalRec(numIdx, leftLen, exp, splitLen); int rightLen = numEndIdx - dotIdx - 1; BigDecimal right = toBigDecimalRec(dotIdx + 1, rightLen, exp - rightLen, splitLen); res = left.add(right); } else { res = toBigDecimalRec(numIdx, numEndIdx - numIdx, exp, splitLen); } if (scale != 0) { res = res.setScale(scale); } if (neg) { res = res.negate(); } return res; } private int adjustScale(int scale, long exp) { long adjScale = scale - exp; if (adjScale > Integer.MAX_VALUE || adjScale < Integer.MIN_VALUE) { throw new NumberFormatException( "Scale out of range: " + adjScale + " while adjusting scale " + scale + " to exponent " + exp); } return (int) adjScale; } private BigDecimal toBigDecimalRec(int off, int len, int scale, int splitLen) { if (len > splitLen) { int mid = len / 2; BigDecimal left = toBigDecimalRec(off, mid, scale + len - mid, splitLen); BigDecimal right = toBigDecimalRec(off + mid, len - mid, scale, splitLen); return left.add(right); } return len == 0 ? BigDecimal.ZERO : new BigDecimal(chars, off, len).movePointRight(scale); } }
src/main/java/com/fasterxml/jackson/core/io/BigDecimalParser.java
package com.fasterxml.jackson.core.io; import java.math.BigDecimal; import java.util.Arrays; // Based on a great idea of Eric Obermühlner to use a tree of smaller BigDecimals for parsing // really big numbers with O(n^1.5) complexity instead of O(n^2) when using the constructor // for a decimal representation from JDK 8/11: // // https://github.com/eobermuhlner/big-math/commit/7a5419aac8b2adba2aa700ccf00197f97b2ad89f /** * Helper class used to implement more optimized parsing of {@link BigDecimal} for REALLY * big values (over 500 characters) *<p> * Based on ideas from this * <a href="https://github.com/eobermuhlner/big-math/commit/7a5419aac8b2adba2aa700ccf00197f97b2ad89f">this * git commit</a>. * * @since 2.13 */ public final class BigDecimalParser { private final static int MAX_CHARS_TO_REPORT = 1000; private final char[] chars; BigDecimalParser(char[] chars) { this.chars = chars; } public static BigDecimal parse(String valueStr) { return parse(valueStr.toCharArray()); } public static BigDecimal parse(char[] chars, int off, int len) { if (off > 0 || len != chars.length) { chars = Arrays.copyOfRange(chars, off, off+len); } return parse(chars); } public static BigDecimal parse(char[] chars) { final int len = chars.length; try { if (len < 500) { return new BigDecimal(chars); } return new BigDecimalParser(chars).parseBigDecimal(len / 10); } catch (NumberFormatException e) { String desc = e.getMessage(); // 05-Feb-2021, tatu: Alas, JDK mostly has null message so: if (desc == null) { desc = "Not a valid number representation"; } String stringToReport; if (chars.length <= MAX_CHARS_TO_REPORT) { stringToReport = new String(chars); } else { stringToReport = new String(Arrays.copyOfRange(chars, 0, MAX_CHARS_TO_REPORT)) + "(truncated, full length is " + chars.length + " chars)"; } throw new NumberFormatException("Value \"" + stringToReport + "\" can not be represented as `java.math.BigDecimal`, reason: " + desc); } } private BigDecimal parseBigDecimal(final int splitLen) { boolean numHasSign = false; boolean expHasSign = false; boolean neg = false; int numIdx = 0; int expIdx = -1; int dotIdx = -1; int scale = 0; final int len = chars.length; for (int i = 0; i < len; i++) { char c = chars[i]; switch (c) { case '+': if (expIdx >= 0) { if (expHasSign) { throw new NumberFormatException("Multiple signs in exponent"); } expHasSign = true; } else { if (numHasSign) { throw new NumberFormatException("Multiple signs in number"); } numHasSign = true; numIdx = i + 1; } break; case '-': if (expIdx >= 0) { if (expHasSign) { throw new NumberFormatException("Multiple signs in exponent"); } expHasSign = true; } else { if (numHasSign) { throw new NumberFormatException("Multiple signs in number"); } numHasSign = true; neg = true; numIdx = i + 1; } break; case 'e': case 'E': if (expIdx >= 0) { throw new NumberFormatException("Multiple exponent markers"); } expIdx = i; break; case '.': if (dotIdx >= 0) { throw new NumberFormatException("Multiple decimal points"); } dotIdx = i; break; default: if (dotIdx >= 0 && expIdx == -1) { scale++; } } } int numEndIdx; int exp = 0; if (expIdx >= 0) { numEndIdx = expIdx; String expStr = new String(chars, expIdx + 1, len - expIdx - 1); exp = Integer.parseInt(expStr); scale = adjustScale(scale, exp); } else { numEndIdx = len; } BigDecimal res; if (dotIdx >= 0) { int leftLen = dotIdx - numIdx; BigDecimal left = toBigDecimalRec(numIdx, leftLen, exp, splitLen); int rightLen = numEndIdx - dotIdx - 1; BigDecimal right = toBigDecimalRec(dotIdx + 1, rightLen, exp - rightLen, splitLen); res = left.add(right); } else { res = toBigDecimalRec(numIdx, numEndIdx - numIdx, exp, splitLen); } if (scale != 0) { res = res.setScale(scale); } if (neg) { res = res.negate(); } return res; } private int adjustScale(int scale, long exp) { long adjScale = scale - exp; if (adjScale > Integer.MAX_VALUE || adjScale < Integer.MIN_VALUE) { throw new NumberFormatException( "Scale out of range: " + adjScale + " while adjusting scale " + scale + " to exponent " + exp); } return (int) adjScale; } private BigDecimal toBigDecimalRec(int off, int len, int scale, int splitLen) { if (len > splitLen) { int mid = len / 2; BigDecimal left = toBigDecimalRec(off, mid, scale + len - mid, splitLen); BigDecimal right = toBigDecimalRec(off + mid, len - mid, scale, splitLen); return left.add(right); } return len == 0 ? BigDecimal.ZERO : new BigDecimal(chars, off, len).movePointRight(scale); } }
Avoid copy when parsing BigDecimal (#798)
src/main/java/com/fasterxml/jackson/core/io/BigDecimalParser.java
Avoid copy when parsing BigDecimal (#798)
<ide><path>rc/main/java/com/fasterxml/jackson/core/io/BigDecimalParser.java <ide> } <ide> <ide> public static BigDecimal parse(char[] chars, int off, int len) { <del> if (off > 0 || len != chars.length) { <del> chars = Arrays.copyOfRange(chars, off, off+len); <del> } <del> return parse(chars); <del> } <del> <del> public static BigDecimal parse(char[] chars) { <del> final int len = chars.length; <ide> try { <ide> if (len < 500) { <del> return new BigDecimal(chars); <add> return new BigDecimal(chars, off, len); <ide> } <add> chars = Arrays.copyOfRange(chars, off, off+len); <ide> return new BigDecimalParser(chars).parseBigDecimal(len / 10); <ide> } catch (NumberFormatException e) { <ide> String desc = e.getMessage(); <ide> desc = "Not a valid number representation"; <ide> } <ide> String stringToReport; <del> if (chars.length <= MAX_CHARS_TO_REPORT) { <del> stringToReport = new String(chars); <add> if (len <= MAX_CHARS_TO_REPORT) { <add> stringToReport = new String(chars, off, len); <ide> } else { <del> stringToReport = new String(Arrays.copyOfRange(chars, 0, MAX_CHARS_TO_REPORT)) <add> stringToReport = new String(Arrays.copyOfRange(chars, off, MAX_CHARS_TO_REPORT)) <ide> + "(truncated, full length is " + chars.length + " chars)"; <ide> } <ide> throw new NumberFormatException("Value \"" + stringToReport <ide> + "\" can not be represented as `java.math.BigDecimal`, reason: " + desc); <ide> } <add> } <add> <add> public static BigDecimal parse(char[] chars) { <add> return parse(chars, 0, chars.length); <ide> } <ide> <ide> private BigDecimal parseBigDecimal(final int splitLen) {
JavaScript
mit
7690bbd7fa28de7d167ddd937932c32e776351cd
0
bevacqua/grunt-testling
var fs = require('fs'); var path = require('path'); var spawn = require('child_process').spawn; module.exports = function (grunt) { grunt.registerTask('testling', function () { var done = this.async(); var local = path.join(process.cwd(), 'node_modules/testling/bin/cmd.js'); var isLocal = fs.existsSync(local); var opts = { stdio: 'inherit' }; var process; process = spawn(isLocal ? local : 'testling', [], opts); process.on('close', function(code) { done(!code); }); }); };
tasks/testling.js
var fs = require('fs'); var path = require('path'); var spawn = require('child_process').spawn; module.exports = function (grunt) { grunt.registerTask('testling', function () { var done = this.async(); var local = path.join(process.cwd(), 'node_modules/testling/bin/cmd.js'); var isLocal = fs.existsSync(local); var opts = { stdio: 'inherit' }; spawn(isLocal ? local : 'testling', [], opts).on('exit', done); }); };
Ensure grunt fails when tests fail The previous code was just calling grunt async done when the tests failed. It needs to pass a boolean for whether the task actually failed or not. The code returned will be 0 if successful and a number (usually 1) if not. So we pass the inverse of this to fail or pass the task.
tasks/testling.js
Ensure grunt fails when tests fail
<ide><path>asks/testling.js <ide> var local = path.join(process.cwd(), 'node_modules/testling/bin/cmd.js'); <ide> var isLocal = fs.existsSync(local); <ide> var opts = { stdio: 'inherit' }; <add> var process; <ide> <del> spawn(isLocal ? local : 'testling', [], opts).on('exit', done); <add> process = spawn(isLocal ? local : 'testling', [], opts); <add> process.on('close', function(code) { <add> done(!code); <add> }); <ide> }); <ide> };
Java
bsd-3-clause
e206d6d2d774c2e477ffc3fdba13fe2cb3be09b1
0
Kingsford-Group/kourami,Kingsford-Group/kourami
/* Part of Kourami HLA typer/assembler (c) 2017 by Heewook Lee, Carl Kingsford, and Carnegie Mellon University. See LICENSE for licensing. */ import java.util.*; import java.io.*; public class FormatIMGT{ public static void main(String[] args){ if(args.length != 3){ System.err.println("USAGE: java FormatIMGT <path-to-IMGT-alignment-directory> <IMGT_version> <outputDir>"); System.exit(1); } String imgtpath = null; String imgtVer = null; String outbase = null; if(args[0].endsWith(File.separator)) imgtpath = args[0].substring(0, args[0].length() - 1); else imgtpath = args[0]; if(args[1].equals("0")){ imgtVer = getVersionNum(imgtpath + File.separator + "A_gen.txt"); if(imgtVer != null) System.err.println("IMGTver " + imgtVer); else{ System.err.println("IMGTver could not be found. Please consider reruning the script with user-input ver_number"); System.exit(1); } }else imgtVer = args[1]; if(args[2].endsWith(File.separator)) outbase = args[2].substring(0, args[2].length() - 1); else outbase = args[2]; //String outpath = args[0] + File.separator + "kouramiFormatted"; String outpath = outbase + File.separator + imgtVer; File outdir = null; try{ File imgtdir = new File(imgtpath); if(!imgtdir.exists() || !imgtdir.isDirectory()){ System.err.println(imgtpath + " either doesn't exist or it is not a directory."); System.exit(1); } outdir = new File(outpath); if(outdir.exists()){ if(!outdir.isDirectory()){ System.err.println(outpath + " exists but it is NOT a writable directory."); System.exit(1); } }else outdir.mkdirs(); System.err.println("#Input IMGT/HLA MSA Allignments:\t" + imgtpath); System.err.println("#Output (Kourami panel/db) :\t" + outpath); if(!args[1].equals("0")) System.err.println("#Version number (user-input) :\t" + imgtVer); else System.err.println("#Version number (detected) :\t" + imgtVer); boolean missingFiles = false; for(int i=0; i<FormatIMGT.expList.length; i++){ File genFile = new File(imgtpath + File.separator + FormatIMGT.expList[i] + "_gen.txt"); File nucFile = new File(imgtpath + File.separator + FormatIMGT.expList[i] + "_nuc.txt"); if(FormatIMGT.expList[i].startsWith("DRB")) nucFile = new File(imgtpath + File.separator + "DRB_nuc.txt"); if(!genFile.exists()){ if(FormatIMGT.expList[i].equals("DRB5")){ } System.err.println("Missing :\t" + genFile.getAbsolutePath()); System.err.println("A gen file is required for each gene."); missingFiles = true; } if(!nucFile.exists()){ if(!FormatIMGT.expList[i].equals("P")){ System.err.println("Missing :\t" + nucFile.getAbsolutePath()); missingFiles = true; }else{ System.err.println("Processing HLA-P with just gen sequences."); } } } if(missingFiles) System.exit(1); for(int i=0; i<FormatIMGT.expList.length; i++){ String geneName = FormatIMGT.expList[i]; System.err.println(">>>>>>>>> Processing\t[" + geneName + "] <<<<<<<<<<"); FormatIMGT.processGene(imgtpath, outpath, geneName); } }catch(Exception e){ e.printStackTrace(); System.exit(1); } } public static String getVersionNum(String agenfile){ BufferedReader br = null; String ver = null; try{ br = new BufferedReader(new FileReader(agenfile)); String curline = null; while((curline=br.readLine()) != null){ if(curline.startsWith("IPD-IMGT/HLA Release:") || curline.startsWith("IMGT/HLA Release:")){ ver = curline.split(":")[1].trim(); break; } } br.close(); }catch(IOException ioe){ ioe.printStackTrace(); } return ver; } public static void processGene(String imgtpath, String outpath, String geneName){ String genfile = imgtpath + File.separator + geneName + "_gen.txt"; String nucfile = imgtpath + File.separator + geneName + "_nuc.txt"; String genoutfile = outpath + File.separator + geneName + "_gen.txt"; String nucoutfile = outpath + File.separator + geneName + "_nuc.txt"; if(geneName.startsWith("DRB")) nucfile = imgtpath + File.separator + "DRB_nuc.txt"; IMGTReformatter nuc = null; IMGTReformatter gen = null; if(new File(nucfile).exists()) nuc = new IMGTReformatter(nucfile, geneName); else System.err.println("[WARNING]: Missing < " + nucfile + " >. Proceeding without.\nHowever, it is STRONGLY recommended to run FormatIMGT\nwith both nuc and gen files for each gene."); if(new File(genfile).exists()) gen = new IMGTReformatter(genfile, geneName); else{ System.err.println("[ERROR]: Missing < " + genfile + " >.\n"); System.err.println("A gen file is required for each gene!"); System.exit(1); } String nucRefAl = null; if(nuc != null) nucRefAl = nuc.getRefAlleleName(); String genRefAl = gen.getRefAlleleName(); System.err.println("nucRefAl:\t" + nucRefAl + "\tgenRefAl:\t" + genRefAl); //if both ref alleles are same if(nuc == null || nucRefAl.equals(genRefAl)){ if(nuc != null) System.err.println("\trefGeneName on nuc and gen are same"); System.err.println("\tWrting to :\t" + genoutfile); gen.outToFile(genoutfile); if(nuc !=null){ System.err.println("\tWrting to :\t" + nucoutfile); nuc.outToFile(nucoutfile); } } //if NOT same, then genRefAl must be in nucRefAl //because nucRef is the superset. else{ System.err.println("\trefGeneName on nuc and gen are NOT same"); if(nuc.contains(genRefAl)){ System.err.println("\tSWAPPING refGenes on nuc and gen"); nuc.swap(genRefAl); System.err.println("\tWrting to :\t" + genoutfile); gen.outToFile(genoutfile); System.err.println("\tWrting to :\t" + nucoutfile); nuc.outToFile(nucoutfile); }else{ System.err.println("Reference sequence entry [" + genRefAl + "] is " + "NOT found in nuc alignments.\n" + "Check the alignment files."); System.exit(1); } ;//swap then outToFile(); } MergeMSFs mm = new MergeMSFs(); if(!mm.merge(nucoutfile, genoutfile, false)){ System.err.println("ERROR in MSA merging. CANNOT proceed further. Exiting.."); System.exit(1); }else{ //if merging is successful, write the output as fasta mm.outToFasta(outpath + File.separator, false); } } public static final String[] list = {"A" , "B" , "C" , "DQA1" , "DQB1" , "DRB1"}; /* list of genes used in DB */ public static final String[] expList = {"A", "B", "C", "DMA", "DMB", "DOA" , "DPA1", "DPB1", "DPB2", "DQA1", "DQB1", "DRA" , "DRB1", "DRB3", "DRB4", "DRB5" , "E", "F", "G", "H", "HFE", "J", "K" , "L", "MICA", "MICB", "TAP1", "TAP2", "V", "Y"}; } class IMGTReformatter{ private ArrayList<Allele> alleles; private StringBuffer header; private StringBuffer dnaCoordinate; private StringBuffer AACoordinate; private StringBuffer tick; private int startPos; private Allele newRef; private int newRefIndex; private String geneName; public IMGTReformatter(){ this.alleles = new ArrayList<Allele>(); this.header = new StringBuffer(); this.dnaCoordinate = null; this.AACoordinate = null; this.tick = null; this.startPos = -1; this.newRef = null; this.newRefIndex = 0; this.geneName = null; } public IMGTReformatter(String msf, String gn){ this(); this.geneName = gn; this.loadAlleles(msf); } public int getNewRefIndex(){ return this.newRefIndex; } public boolean contains(String newRefName){ for(int i=1; i < this.alleles.size(); i++){ if(this.alleles.get(i).getName().equals(newRefName)){ this.newRef = this.alleles.get(i); this.newRefIndex = i; return true; } } return false; } //performs the swap of curRef to newRef public void swap(String newRefName){ Allele curRef = this.alleles.get(0); for(int i=1; i < this.alleles.size(); i++){ if(i!=this.newRefIndex) this.alleles.get(i).update(curRef, this.newRef); } Allele.swapRef(curRef, newRef); } public void swapAndDiscard(String newRefName){ this.swap(newRefName); } private boolean isAlleleLine(String[] tokens){ //tokens[0].startsWith(this.geneName + "*") && tokens[0].matches("[A-Z]+\\d{0,1}\\*\\d+(:\\d+){0,3}[A-Z]*") if(tokens.length > 0){ if(tokens[0].matches("[A-Z]+\\d{0,1}\\*\\d+(:\\d+){0,3}[A-Z]*")) return true; /*else{ System.err.print("[" + this.geneName + "]: " + tokens[0] + "\t"); //System.err.print(tokens[0].startsWith(this.geneName + "*") + "\t"); System.err.println(tokens[0].matches("[A-Z]+\\d{0,1}\\*\\d+(:\\d+){0,3}[A-Z]*")); }*/ } return false; } /* * Parses alignment format from IMGT db */ public void loadAlleles(String msf){ BufferedReader br = null; String curline = null; try{ br = new BufferedReader(new FileReader(msf)); boolean inMSF = false; //flag to split header and post-header int alleleIndex = 0; while((curline=br.readLine())!=null){ String stripped = curline.trim(); String[] tokens = stripped.split("\\s+"); //parse headers if(!inMSF){ if(stripped.startsWith("cDNA") || stripped.startsWith("gDNA")){ inMSF = true;//turn it on this.dnaCoordinate = new StringBuffer(curline); this.startPos = this.getStartIndex(curline, tokens); if(this.startPos < 0){ System.err.println("Check the input file:\t" + msf); System.exit(1); } }else//must be headers header.append(curline + "\n"); }else{ if(stripped.startsWith("|")){ if(this.tick == null) this.tick = new StringBuffer(curline); else this.tick.append(stripped); } // if it's cDNA gDNA tag else if(stripped.startsWith("cDNA") || stripped.startsWith("gDNA")){ this.dnaCoordinate.append(this.stripHeader(curline, this.startPos)); alleleIndex = 0; // reset alleleIndex } else if(stripped.startsWith("AA codon")){ if(this.AACoordinate == null) this.AACoordinate = new StringBuffer(curline); else this.AACoordinate.append(this.stripHeader(curline, this.startPos)); } else if(isAlleleLine(tokens)){ //System.err.println("allelesSize:\t" + this.alleles.size() + "\talleleIndex:\t" + alleleIndex ); // -------------------------------------------- // ONLY add or update if allele is the reference allele (alleleIndex == 0) // in the given msf or it is from same gene // -------------------------------------------- if(alleleIndex == 0 || tokens[0].startsWith(this.geneName + "*")){ //add if(this.alleles.size() == alleleIndex){ //System.err.println("ADDING "); this.alleles.add(new Allele(curline.substring(0 , this.startPos), curline.substring(this.startPos))); }else//update this.alleles.get(alleleIndex).appendSequence(tokens[0], curline.substring(this.startPos)); //append correct number of white spaces for coordinate and tick lines if(alleleIndex == 0) this.appendNPadding(this.alleles.get(alleleIndex).curStringLength(this.startPos)); alleleIndex++; } } } } }catch(IOException ioe){ ioe.printStackTrace(); } } //if newRefIndex == 0 --> no swapping was necessary //if newRefIndex > 0 --> oldRefIndex is 0, and newRefIndex is given public void outToFile(String merged){ BufferedWriter bw = null; try{ bw = new BufferedWriter(new FileWriter(merged)); bw.write("Nuc+Gen merged MSA for Kourami\n"); bw.write(this.header.toString()); bw.write(this.dnaCoordinate.toString().replaceFirst("\\s++$", "") + "\n"); if(this.AACoordinate != null) bw.write(this.AACoordinate.toString().replaceFirst("\\s++$", "") + "\n"); bw.write(this.tick.toString().replaceFirst("\\s++$", "") + "\n"); //if no swapping was applied if(this.newRefIndex == 0){ for(Allele a : this.alleles) bw.write(a.toString() + "\n"); } //if there was a swapping else if(this.newRefIndex > 0){ //write newRefAllele first bw.write(this.alleles.get(this.newRefIndex).toString() + "\n"); for(int i=0; i<this.alleles.size(); i++){ Allele curAllele = this.alleles.get(i); if(i != this.newRefIndex && curAllele.isFromGene(this.geneName)) bw.write(this.alleles.get(i).toString() + "\n"); } } bw.close(); }catch(IOException ioe){ ioe.printStackTrace(); } } public String getRefAlleleName(){ return this.alleles.get(0).getName(); } private void appendNPadding(int alleleLength){ if(this.dnaCoordinate != null) this.appendNPadding(this.dnaCoordinate, alleleLength - this.dnaCoordinate.length()); if(this.AACoordinate != null) this.appendNPadding(this.AACoordinate, alleleLength - this.AACoordinate.length()); if(this.tick !=null) this.appendNPadding(this.tick, alleleLength - this.tick.length()); } private void appendNPadding(StringBuffer sb, int n){ for(int i =0; i<n; i++) sb.append(" "); } private String stripHeader(String curline, int pos){ return curline.substring(pos); } private int getStartIndex(String dnaLine, String[] tokens){ if(tokens.length > 1) return dnaLine.indexOf(tokens[1]); else{ System.err.println("Unusual gDNA header line. Check the input file file"); return -1; } } } class Allele{ private String nameWS; private String name; private StringBuffer sequence; //n may have leading and trailing whitespaces public Allele(String n, String seq){ this.nameWS = n; this.name = n.trim(); this.sequence = new StringBuffer(seq); } public boolean appendSequence(String n, String seq){ if(this.name.equals(n)){ this.sequence.append(seq); return true; } return false; } public boolean isFromGene(String genename){ if(this.name.equals(genename)) return true; return false; } public int curStringLength(int startPos){ return startPos + this.sequence.length(); } public String toString(int startPos){ StringBuffer bf = new StringBuffer(name); int numSpaces = startPos - name.length(); for(int i = 0; i < numSpaces; i++) bf.append(" "); bf.append(sequence); return bf.toString(); } public String toString(){ return this.nameWS + this.sequence; } public String getName(){ return this.name; } public StringBuffer getSequenceBuffer(){ return this.sequence; } //symbols // . --> gap // - --> same as curRef // * --> unknownbase // [aAcCgGtT] --> base public void update(Allele curref, Allele newref){ for(int i=0; i<this.sequence.length(); i++){ char crc = curref.charAt(i); char nrc = newref.charAt(i); //if crc and nrc are same if(crc == nrc || nrc == '-')//both gaps, both unknown, or same bases. ;//not do anything else if(crc != nrc){ // [crc] : [nrc] // base : */./dBase // * : ./base // . : */base char c = this.charAt(i); //if it's a gap '.' or unknown base '*' if( c == '.' || c == '*') ;//not do anything else if(c == '-')//base is same as crc but diff from nrc, so need to actually write crc base. this.setCharAt(i, crc); else{ // c is a letter base if(c == nrc)//base is differenct from crc but same as nrc, so need to set it '-' --> meaing same as nrc this.setCharAt(i, '-'); else//base is different from crc and also difeferent from nrc, so keep it as it is ; } } } } public static void swapRef(Allele curref, Allele newref){ for(int i=0; i<curref.getSequenceBuffer().length(); i++){ char crc = curref.charAt(i); char nrc = newref.charAt(i); if(crc == nrc){ // gap:gap unknown:unknonwn .:. *:* ; }else if(nrc == '-'){ // crc must be a base newref.setCharAt(i, crc); curref.setCharAt(i, nrc); } } } public void setCharAt(int n, char c){ this.sequence.setCharAt(n, c); } public char charAt(int n){ return this.sequence.charAt(n); } public boolean sameCharAt(int n, Allele other){ if(this.charAt(n) == other.charAt(n)) return true; return false; } } /* public void loadAlleles(String msf){ BufferedReader br = null; String curline = null; try{ br = new BufferedReader(new FileReader(msf)); boolean inMSF = false; boolnea inAllele = false; int alleleIndex = 0; //index for allele int startPos = 0; while((curline=br.readLine())!=null){ String stripped = curline.trim(); if(!inMSF){ if(stripped.startsWith("cDNA") || stripped.startsWith("gDNA")){ inMSF = true;//turn it on this.dnaCoordinate = new StringBuffer(curline); startPos = this.getStartIndex(curline); }else//must be headers header.append(curline + "\n"); }else{ if(inAlleles){ if(stripped.equals("")){//this is the end of MSA block inAlleles = false; //turn off now alleleIndex = 0; //reset counter }else{ if(this.alleles.size() == alleleIndex){//this must be the first block this.alleles.add(new StringBuffer(curline)); // so we add this.names.add(stripped.substring(0,stripped.indexOf(" "))); }else{//otherwise if(this.names.get(alleleIndex).equals(stripped.substring(0,stripped.indexOf(" ")))) this.alleles.get(alleleIndex).append(this.stripHeader(curline, startPos));//not first block so we append the sequence portion else{ System.err.println("****ALLELE NAME NOT MATCHING: expected (" + this.names.get(alleleIndex) + ")\tFound (" + stripped.substring(0,stripped.indexOf(" "))); System.err.println(curline); System.err.println("While processing:\t" + msf); System.exit(-1); } } if(alleleIndex == 0){ this.appendNPadding(this.alleles.get(alleleIndex).length()); } alleleIndex++; } } } } }catch(IOException ioe){ ioe.printStackTrace(); } } */
src/FormatIMGT.java
/* Part of Kourami HLA typer/assembler (c) 2017 by Heewook Lee, Carl Kingsford, and Carnegie Mellon University. See LICENSE for licensing. */ import java.util.*; import java.io.*; public class FormatIMGT{ public static void main(String[] args){ if(args.length != 3){ System.err.println("USAGE: java FormatIMGT <path-to-IMGT-alignment-directory> <IMGT_version> <outputDir>"); System.exit(1); } String imgtpath = null; String imgtVer = null; String outbase = null; if(args[0].endsWith(File.separator)) imgtpath = args[0].substring(0, args[0].length() - 1); else imgtpath = args[0]; if(args[1].equals("0")){ imgtVer = getVersionNum(imgtpath + File.separator + "A_gen.txt"); System.err.println("IMGTver " + imgtVer); }else imgtVer = args[1]; if(args[2].endsWith(File.separator)) outbase = args[2].substring(0, args[2].length() - 1); else outbase = args[2]; //String outpath = args[0] + File.separator + "kouramiFormatted"; String outpath = outbase + File.separator + imgtVer; File outdir = null; try{ File imgtdir = new File(imgtpath); if(!imgtdir.exists() || !imgtdir.isDirectory()){ System.err.println(imgtpath + " either doesn't exist or it is not a directory."); System.exit(1); } outdir = new File(outpath); if(outdir.exists()){ if(!outdir.isDirectory()){ System.err.println(outpath + " exists but it is NOT a writable directory."); System.exit(1); } }else outdir.mkdirs(); System.err.println("#Input IMGT/HLA MSA Allignments:\t" + imgtpath); System.err.println("#Output (Kourami panel/db) :\t" + outpath); if(!args[1].equals("0")) System.err.println("#Version number (user-input) :\t" + imgtVer); else System.err.println("#Version number (detected) :\t" + imgtVer); boolean missingFiles = false; for(int i=0; i<FormatIMGT.expList.length; i++){ File genFile = new File(imgtpath + File.separator + FormatIMGT.expList[i] + "_gen.txt"); File nucFile = new File(imgtpath + File.separator + FormatIMGT.expList[i] + "_nuc.txt"); if(FormatIMGT.expList[i].startsWith("DRB")) nucFile = new File(imgtpath + File.separator + "DRB_nuc.txt"); if(!genFile.exists()){ if(FormatIMGT.expList[i].equals("DRB5")){ } System.err.println("Missing :\t" + genFile.getAbsolutePath()); System.err.println("A gen file is required for each gene."); missingFiles = true; } if(!nucFile.exists()){ if(!FormatIMGT.expList[i].equals("P")){ System.err.println("Missing :\t" + nucFile.getAbsolutePath()); missingFiles = true; }else{ System.err.println("Processing HLA-P with just gen sequences."); } } } if(missingFiles) System.exit(1); for(int i=0; i<FormatIMGT.expList.length; i++){ String geneName = FormatIMGT.expList[i]; System.err.println(">>>>>>>>> Processing\t[" + geneName + "] <<<<<<<<<<"); FormatIMGT.processGene(imgtpath, outpath, geneName); } }catch(Exception e){ e.printStackTrace(); System.exit(1); } } public static String getVersionNum(String agenfile){ BufferedReader br = null; String ver = null; try{ br = new BufferedReader(new FileReader(agenfile)); String curline = null; while((curline=br.readLine()) != null){ if(curline.startsWith("IPD-IMGT/HLA Release:")){ ver = curline.split(":")[1].trim(); break; } } br.close(); }catch(IOException ioe){ ioe.printStackTrace(); } return ver; } public static void processGene(String imgtpath, String outpath, String geneName){ String genfile = imgtpath + File.separator + geneName + "_gen.txt"; String nucfile = imgtpath + File.separator + geneName + "_nuc.txt"; String genoutfile = outpath + File.separator + geneName + "_gen.txt"; String nucoutfile = outpath + File.separator + geneName + "_nuc.txt"; if(geneName.startsWith("DRB")) nucfile = imgtpath + File.separator + "DRB_nuc.txt"; IMGTReformatter nuc = null; IMGTReformatter gen = null; if(new File(nucfile).exists()) nuc = new IMGTReformatter(nucfile, geneName); else System.err.println("[WARNING]: Missing < " + nucfile + " >. Proceeding without.\nHowever, it is STRONGLY recommended to run FormatIMGT\nwith both nuc and gen files for each gene."); if(new File(genfile).exists()) gen = new IMGTReformatter(genfile, geneName); else{ System.err.println("[ERROR]: Missing < " + genfile + " >.\n"); System.err.println("A gen file is required for each gene!"); System.exit(1); } String nucRefAl = null; if(nuc != null) nucRefAl = nuc.getRefAlleleName(); String genRefAl = gen.getRefAlleleName(); System.err.println("nucRefAl:\t" + nucRefAl + "\tgenRefAl:\t" + genRefAl); //if both ref alleles are same if(nuc == null || nucRefAl.equals(genRefAl)){ if(nuc != null) System.err.println("\trefGeneName on nuc and gen are same"); System.err.println("\tWrting to :\t" + genoutfile); gen.outToFile(genoutfile); if(nuc !=null){ System.err.println("\tWrting to :\t" + nucoutfile); nuc.outToFile(nucoutfile); } } //if NOT same, then genRefAl must be in nucRefAl //because nucRef is the superset. else{ System.err.println("\trefGeneName on nuc and gen are NOT same"); if(nuc.contains(genRefAl)){ System.err.println("\tSWAPPING refGenes on nuc and gen"); nuc.swap(genRefAl); System.err.println("\tWrting to :\t" + genoutfile); gen.outToFile(genoutfile); System.err.println("\tWrting to :\t" + nucoutfile); nuc.outToFile(nucoutfile); }else{ System.err.println("Reference sequence entry [" + genRefAl + "] is " + "NOT found in nuc alignments.\n" + "Check the alignment files."); System.exit(1); } ;//swap then outToFile(); } MergeMSFs mm = new MergeMSFs(); if(!mm.merge(nucoutfile, genoutfile, false)){ System.err.println("ERROR in MSA merging. CANNOT proceed further. Exiting.."); System.exit(1); }else{ //if merging is successful, write the output as fasta mm.outToFasta(outpath + File.separator, false); } } public static final String[] list = {"A" , "B" , "C" , "DQA1" , "DQB1" , "DRB1"}; /* list of genes used in DB */ public static final String[] expList = {"A", "B", "C", "DMA", "DMB", "DOA" , "DPA1", "DPB1", "DPB2", "DQA1", "DQB1", "DRA" , "DRB1", "DRB3", "DRB4", "DRB5" , "E", "F", "G", "H", "HFE", "J", "K" , "L", "MICA", "MICB", "TAP1", "TAP2", "V", "Y"}; } class IMGTReformatter{ private ArrayList<Allele> alleles; private StringBuffer header; private StringBuffer dnaCoordinate; private StringBuffer AACoordinate; private StringBuffer tick; private int startPos; private Allele newRef; private int newRefIndex; private String geneName; public IMGTReformatter(){ this.alleles = new ArrayList<Allele>(); this.header = new StringBuffer(); this.dnaCoordinate = null; this.AACoordinate = null; this.tick = null; this.startPos = -1; this.newRef = null; this.newRefIndex = 0; this.geneName = null; } public IMGTReformatter(String msf, String gn){ this(); this.geneName = gn; this.loadAlleles(msf); } public int getNewRefIndex(){ return this.newRefIndex; } public boolean contains(String newRefName){ for(int i=1; i < this.alleles.size(); i++){ if(this.alleles.get(i).getName().equals(newRefName)){ this.newRef = this.alleles.get(i); this.newRefIndex = i; return true; } } return false; } //performs the swap of curRef to newRef public void swap(String newRefName){ Allele curRef = this.alleles.get(0); for(int i=1; i < this.alleles.size(); i++){ if(i!=this.newRefIndex) this.alleles.get(i).update(curRef, this.newRef); } Allele.swapRef(curRef, newRef); } public void swapAndDiscard(String newRefName){ this.swap(newRefName); } private boolean isAlleleLine(String[] tokens){ //tokens[0].startsWith(this.geneName + "*") && tokens[0].matches("[A-Z]+\\d{0,1}\\*\\d+(:\\d+){0,3}[A-Z]*") if(tokens.length > 0){ if(tokens[0].matches("[A-Z]+\\d{0,1}\\*\\d+(:\\d+){0,3}[A-Z]*")) return true; /*else{ System.err.print("[" + this.geneName + "]: " + tokens[0] + "\t"); //System.err.print(tokens[0].startsWith(this.geneName + "*") + "\t"); System.err.println(tokens[0].matches("[A-Z]+\\d{0,1}\\*\\d+(:\\d+){0,3}[A-Z]*")); }*/ } return false; } /* * Parses alignment format from IMGT db */ public void loadAlleles(String msf){ BufferedReader br = null; String curline = null; try{ br = new BufferedReader(new FileReader(msf)); boolean inMSF = false; //flag to split header and post-header int alleleIndex = 0; while((curline=br.readLine())!=null){ String stripped = curline.trim(); String[] tokens = stripped.split("\\s+"); //parse headers if(!inMSF){ if(stripped.startsWith("cDNA") || stripped.startsWith("gDNA")){ inMSF = true;//turn it on this.dnaCoordinate = new StringBuffer(curline); this.startPos = this.getStartIndex(curline, tokens); if(this.startPos < 0){ System.err.println("Check the input file:\t" + msf); System.exit(1); } }else//must be headers header.append(curline + "\n"); }else{ if(stripped.startsWith("|")){ if(this.tick == null) this.tick = new StringBuffer(curline); else this.tick.append(stripped); } // if it's cDNA gDNA tag else if(stripped.startsWith("cDNA") || stripped.startsWith("gDNA")){ this.dnaCoordinate.append(this.stripHeader(curline, this.startPos)); alleleIndex = 0; // reset alleleIndex } else if(stripped.startsWith("AA codon")){ if(this.AACoordinate == null) this.AACoordinate = new StringBuffer(curline); else this.AACoordinate.append(this.stripHeader(curline, this.startPos)); } else if(isAlleleLine(tokens)){ //System.err.println("allelesSize:\t" + this.alleles.size() + "\talleleIndex:\t" + alleleIndex ); // -------------------------------------------- // ONLY add or update if allele is the reference allele (alleleIndex == 0) // in the given msf or it is from same gene // -------------------------------------------- if(alleleIndex == 0 || tokens[0].startsWith(this.geneName + "*")){ //add if(this.alleles.size() == alleleIndex){ //System.err.println("ADDING "); this.alleles.add(new Allele(curline.substring(0 , this.startPos), curline.substring(this.startPos))); }else//update this.alleles.get(alleleIndex).appendSequence(tokens[0], curline.substring(this.startPos)); //append correct number of white spaces for coordinate and tick lines if(alleleIndex == 0) this.appendNPadding(this.alleles.get(alleleIndex).curStringLength(this.startPos)); alleleIndex++; } } } } }catch(IOException ioe){ ioe.printStackTrace(); } } //if newRefIndex == 0 --> no swapping was necessary //if newRefIndex > 0 --> oldRefIndex is 0, and newRefIndex is given public void outToFile(String merged){ BufferedWriter bw = null; try{ bw = new BufferedWriter(new FileWriter(merged)); bw.write("Nuc+Gen merged MSA for Kourami\n"); bw.write(this.header.toString()); bw.write(this.dnaCoordinate.toString().replaceFirst("\\s++$", "") + "\n"); if(this.AACoordinate != null) bw.write(this.AACoordinate.toString().replaceFirst("\\s++$", "") + "\n"); bw.write(this.tick.toString().replaceFirst("\\s++$", "") + "\n"); //if no swapping was applied if(this.newRefIndex == 0){ for(Allele a : this.alleles) bw.write(a.toString() + "\n"); } //if there was a swapping else if(this.newRefIndex > 0){ //write newRefAllele first bw.write(this.alleles.get(this.newRefIndex).toString() + "\n"); for(int i=0; i<this.alleles.size(); i++){ Allele curAllele = this.alleles.get(i); if(i != this.newRefIndex && curAllele.isFromGene(this.geneName)) bw.write(this.alleles.get(i).toString() + "\n"); } } bw.close(); }catch(IOException ioe){ ioe.printStackTrace(); } } public String getRefAlleleName(){ return this.alleles.get(0).getName(); } private void appendNPadding(int alleleLength){ if(this.dnaCoordinate != null) this.appendNPadding(this.dnaCoordinate, alleleLength - this.dnaCoordinate.length()); if(this.AACoordinate != null) this.appendNPadding(this.AACoordinate, alleleLength - this.AACoordinate.length()); if(this.tick !=null) this.appendNPadding(this.tick, alleleLength - this.tick.length()); } private void appendNPadding(StringBuffer sb, int n){ for(int i =0; i<n; i++) sb.append(" "); } private String stripHeader(String curline, int pos){ return curline.substring(pos); } private int getStartIndex(String dnaLine, String[] tokens){ if(tokens.length > 1) return dnaLine.indexOf(tokens[1]); else{ System.err.println("Unusual gDNA header line. Check the input file file"); return -1; } } } class Allele{ private String nameWS; private String name; private StringBuffer sequence; //n may have leading and trailing whitespaces public Allele(String n, String seq){ this.nameWS = n; this.name = n.trim(); this.sequence = new StringBuffer(seq); } public boolean appendSequence(String n, String seq){ if(this.name.equals(n)){ this.sequence.append(seq); return true; } return false; } public boolean isFromGene(String genename){ if(this.name.equals(genename)) return true; return false; } public int curStringLength(int startPos){ return startPos + this.sequence.length(); } public String toString(int startPos){ StringBuffer bf = new StringBuffer(name); int numSpaces = startPos - name.length(); for(int i = 0; i < numSpaces; i++) bf.append(" "); bf.append(sequence); return bf.toString(); } public String toString(){ return this.nameWS + this.sequence; } public String getName(){ return this.name; } public StringBuffer getSequenceBuffer(){ return this.sequence; } //symbols // . --> gap // - --> same as curRef // * --> unknownbase // [aAcCgGtT] --> base public void update(Allele curref, Allele newref){ for(int i=0; i<this.sequence.length(); i++){ char crc = curref.charAt(i); char nrc = newref.charAt(i); //if crc and nrc are same if(crc == nrc || nrc == '-')//both gaps, both unknown, or same bases. ;//not do anything else if(crc != nrc){ // [crc] : [nrc] // base : */./dBase // * : ./base // . : */base char c = this.charAt(i); //if it's a gap '.' or unknown base '*' if( c == '.' || c == '*') ;//not do anything else if(c == '-')//base is same as crc but diff from nrc, so need to actually write crc base. this.setCharAt(i, crc); else{ // c is a letter base if(c == nrc)//base is differenct from crc but same as nrc, so need to set it '-' --> meaing same as nrc this.setCharAt(i, '-'); else//base is different from crc and also difeferent from nrc, so keep it as it is ; } } } } public static void swapRef(Allele curref, Allele newref){ for(int i=0; i<curref.getSequenceBuffer().length(); i++){ char crc = curref.charAt(i); char nrc = newref.charAt(i); if(crc == nrc){ // gap:gap unknown:unknonwn .:. *:* ; }else if(nrc == '-'){ // crc must be a base newref.setCharAt(i, crc); curref.setCharAt(i, nrc); } } } public void setCharAt(int n, char c){ this.sequence.setCharAt(n, c); } public char charAt(int n){ return this.sequence.charAt(n); } public boolean sameCharAt(int n, Allele other){ if(this.charAt(n) == other.charAt(n)) return true; return false; } } /* public void loadAlleles(String msf){ BufferedReader br = null; String curline = null; try{ br = new BufferedReader(new FileReader(msf)); boolean inMSF = false; boolnea inAllele = false; int alleleIndex = 0; //index for allele int startPos = 0; while((curline=br.readLine())!=null){ String stripped = curline.trim(); if(!inMSF){ if(stripped.startsWith("cDNA") || stripped.startsWith("gDNA")){ inMSF = true;//turn it on this.dnaCoordinate = new StringBuffer(curline); startPos = this.getStartIndex(curline); }else//must be headers header.append(curline + "\n"); }else{ if(inAlleles){ if(stripped.equals("")){//this is the end of MSA block inAlleles = false; //turn off now alleleIndex = 0; //reset counter }else{ if(this.alleles.size() == alleleIndex){//this must be the first block this.alleles.add(new StringBuffer(curline)); // so we add this.names.add(stripped.substring(0,stripped.indexOf(" "))); }else{//otherwise if(this.names.get(alleleIndex).equals(stripped.substring(0,stripped.indexOf(" ")))) this.alleles.get(alleleIndex).append(this.stripHeader(curline, startPos));//not first block so we append the sequence portion else{ System.err.println("****ALLELE NAME NOT MATCHING: expected (" + this.names.get(alleleIndex) + ")\tFound (" + stripped.substring(0,stripped.indexOf(" "))); System.err.println(curline); System.err.println("While processing:\t" + msf); System.exit(-1); } } if(alleleIndex == 0){ this.appendNPadding(this.alleles.get(alleleIndex).length()); } alleleIndex++; } } } } }catch(IOException ioe){ ioe.printStackTrace(); } } */
update version fetching conditional
src/FormatIMGT.java
update version fetching conditional
<ide><path>rc/FormatIMGT.java <ide> <ide> if(args[1].equals("0")){ <ide> imgtVer = getVersionNum(imgtpath + File.separator + "A_gen.txt"); <del> System.err.println("IMGTver " + imgtVer); <add> if(imgtVer != null) <add> System.err.println("IMGTver " + imgtVer); <add> else{ <add> System.err.println("IMGTver could not be found. Please consider reruning the script with user-input ver_number"); <add> System.exit(1); <add> } <ide> }else <ide> imgtVer = args[1]; <ide> <ide> br = new BufferedReader(new FileReader(agenfile)); <ide> String curline = null; <ide> while((curline=br.readLine()) != null){ <del> if(curline.startsWith("IPD-IMGT/HLA Release:")){ <add> if(curline.startsWith("IPD-IMGT/HLA Release:") || curline.startsWith("IMGT/HLA Release:")){ <ide> ver = curline.split(":")[1].trim(); <ide> break; <ide> }
Java
mit
467544e6de1641fae9a12f429b9c180bb53ef45a
0
edrdo/jdbdt,edrdo/jdbdt
package org.jdbdt; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Data set. * * <p>A data set represents a collection of rows.</p> * * @since 0.1 * */ public class DataSet implements Iterable<Row> { /** * Data source. */ final DataSource source; /** * Rows in the data set. */ private final List<Row> rows; /** * Read-only flag. */ private final boolean readOnly; /** * Constructs a new data set. * @param ds Data source. */ DataSet(DataSource ds) { this(ds, new ArrayList<>(), false); } /** * Constructs a new data set. * @param ds Data source. * @param readOnly Read-only flag. */ DataSet(DataSource ds, boolean readOnly) { this(ds, new ArrayList<>(), readOnly); } /** * Constructs a new row set. * @param ds Data source. * @param list Row list. * @param readOnly Read-only flag */ DataSet(DataSource ds, List<Row> list, boolean readOnly) { this.source = ds; this.rows = list; this.readOnly = readOnly; } /** * Get data source. * @return The data source associated to this * data set. */ public final DataSource getSource() { return source; } /** * Check if the data set is read-only. * * <p> * Adding rows to the data set will result in an exception * of type {@link InvalidOperationException}. * </p> * * @return <code>true</code> if data set is read-only. */ public final boolean isReadOnly() { return readOnly; } /** * Test if set is empty. * @return <code>true</code> is set is empty. */ final boolean isEmpty() { return rows.isEmpty(); } /** * Get size of data set. * @return The number of rows in the set. */ public int size() { return rows.size(); } /** * Clear contents (package-private). */ final void clear() { rows.clear(); } /** * Add a row to the data set. * @param columnValues Column values forming a row. * @return The data set instance (for chained calls). * @throws InvalidOperationException if this data set is read-only. * @see #row(Object[][]) * @see #add(DataSet) * @see #isReadOnly() */ public final DataSet row(Object... columnValues) { checkIfNotReadOnly(); if (columnValues.length != source.getColumnCount()) { throw new InvalidOperationException(source.getColumnCount() + " columns expected, not " + columnValues.length + "."); } addRow(new RowImpl(columnValues)); return this; } /** * Add rows to the data set. * @param rows Array of rows. * @return The data set instance (for chained calls). * @throws InvalidOperationException if this data set is read-only. * @see #row(Object...) * @see #add(DataSet) * @see #isReadOnly() */ public final DataSet row(Object[][] rows) { checkIfNotReadOnly(); for (Object[] columnValues : rows) { addRow(new RowImpl(columnValues)); } return this; } /** * Add rows of given data set to this data set. * * @param other The other data set. * @return The data set instance (for chained calls). * @throws InvalidOperationException if this data set is read-only. * @see #row(Object...) * @see #row(Object[][]) * @see #isReadOnly() */ public DataSet add(DataSet other) { checkIfNotReadOnly(); rows.addAll(other.rows); return this; } /** * Add a row to the set (package-private version; ignores read-only setting). * @param r Row to add. */ final void addRow(Row r) { rows.add(r); } /** * Get an iterator for the row set. * @return An iterator object. */ @Override public Iterator<Row> iterator() { return !readOnly ? rows.iterator() : Collections.unmodifiableList(rows).iterator(); } @Override public boolean equals(Object o) { return o == this || ( o instanceof DataSet && rows.equals(((DataSet) o).rows) ); } /** * Create sub-set of a given data set. * @param data Data set. * @param startIndex Start index. * @param endIndex End index. * @return A new data set containing * the rows in the specified range. */ public static DataSet subset(DataSet data, int startIndex, int endIndex) { DataSet sub = new DataSet(data.getSource()); ListIterator<Row> itr = data.rows.listIterator(startIndex); int index = startIndex; while (itr.hasNext() && index < endIndex) { sub.rows.add(itr.next()); } return sub; } @SuppressWarnings("javadoc") private void checkIfNotReadOnly() { if (readOnly) { throw new InvalidOperationException("Data set is read-only."); } } /** * Sort data set by row hash code (for testing purposes only). */ void enforceHOrdering() { Collections.sort(rows, (a,b) -> Integer.compare(a.hashCode(), b.hashCode())); } }
src/main/java/org/jdbdt/DataSet.java
package org.jdbdt; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Data set. * * <p>A data set represents a collection of rows.</p> * * @since 0.1 * */ public class DataSet implements Iterable<Row> { /** * Data source. */ final DataSource source; /** * Rows in the data set. */ private final List<Row> rows; /** * Read-only flag. */ private final boolean readOnly; /** * Constructs a new data set. * @param ds Data source. */ DataSet(DataSource ds) { this(ds, new ArrayList<>(), false); } /** * Constructs a new data set. * @param ds Data source. * @param readOnly Read-only flag. */ DataSet(DataSource ds, boolean readOnly) { this(ds, new ArrayList<>(), readOnly); } /** * Constructs a new row set. * @param ds Data source. * @param list Row list. * @param readOnly Read-only flag */ DataSet(DataSource ds, List<Row> list, boolean readOnly) { this.source = ds; this.rows = list; this.readOnly = readOnly; } /** * Get data source. * @return The data source associated to this * data set. */ public final DataSource getSource() { return source; } /** * Check if the data set is read-only. * * <p> * Adding rows to the data set will result in an exception * of type {@link InvalidOperationException}. * </p> * * @return <code>true</code> if data set is read-only. */ public final boolean isReadOnly() { return readOnly; } /** * Test if set is empty. * @return <code>true</code> is set is empty. */ final boolean isEmpty() { return rows.isEmpty(); } /** * Get size of data set. * @return The number of rows in the set. */ public int size() { return rows.size(); } /** * Clear contents (package-private). */ final void clear() { rows.clear(); } /** * Add a row to the data set. * @param columnValues Column values forming a row. * @return The data set instance (for chained calls). */ public final DataSet row(Object... columnValues) { checkIfNotReadOnly(); if (columnValues.length != source.getColumnCount()) { throw new InvalidOperationException(source.getColumnCount() + " columns expected, not " + columnValues.length + "."); } addRow(new RowImpl(columnValues)); return this; } /** * Add rows to the data set. * @param rows Array of rows. * @return The data set instance (for chained calls). */ public final DataSet row(Object[][] rows) { checkIfNotReadOnly(); for (Object[] columnValues : rows) { addRow(new RowImpl(columnValues)); } return this; } /** * Add a row to the set (package-private version; ignores read-only setting). * @param r Row to add. */ final void addRow(Row r) { rows.add(r); } /** * Get an iterator for the row set. * @return An iterator object. */ @Override public Iterator<Row> iterator() { return !readOnly ? rows.iterator() : Collections.unmodifiableList(rows).iterator(); } @Override public boolean equals(Object o) { return o == this || ( o instanceof DataSet && rows.equals(((DataSet) o).rows) ); } /** * Create sub-set of a given data set. * @param data Data set. * @param startIndex Start index. * @param endIndex End index. * @return A new data set containing * the rows in the specified range. */ public static DataSet subset(DataSet data, int startIndex, int endIndex) { DataSet sub = new DataSet(data.getSource()); ListIterator<Row> itr = data.rows.listIterator(startIndex); int index = startIndex; while (itr.hasNext() && index < endIndex) { sub.rows.add(itr.next()); } return sub; } /** * Add rows of given data set to this set. * @param other This data set. * @return The data set instance (for chained calls). */ public DataSet add(DataSet other) { checkIfNotReadOnly(); rows.addAll(other.rows); return this; } @SuppressWarnings("javadoc") private void checkIfNotReadOnly() { if (readOnly) { throw new InvalidOperationException("Data set is read-only."); } } /** * Sort data set by row hash code (for testing purposes only). */ void enforceHOrdering() { Collections.sort(rows, (a,b) -> Integer.compare(a.hashCode(), b.hashCode())); } }
DataSet: Javadoc improvements
src/main/java/org/jdbdt/DataSet.java
DataSet: Javadoc improvements
<ide><path>rc/main/java/org/jdbdt/DataSet.java <ide> * Data source. <ide> */ <ide> final DataSource source; <del> <add> <ide> /** <ide> * Rows in the data set. <ide> */ <ide> private final List<Row> rows; <del> <add> <ide> /** <ide> * Read-only flag. <ide> */ <ide> private final boolean readOnly; <del> <add> <ide> /** <ide> * Constructs a new data set. <ide> * @param ds Data source. <ide> DataSet(DataSource ds, boolean readOnly) { <ide> this(ds, new ArrayList<>(), readOnly); <ide> } <del> <add> <ide> /** <ide> * Constructs a new row set. <ide> * @param ds Data source. <ide> this.rows = list; <ide> this.readOnly = readOnly; <ide> } <del> <add> <ide> /** <ide> * Get data source. <ide> * @return The data source associated to this <ide> public final DataSource getSource() { <ide> return source; <ide> } <del> <add> <ide> /** <ide> * Check if the data set is read-only. <ide> * <ide> final boolean isEmpty() { <ide> return rows.isEmpty(); <ide> } <del> <add> <ide> /** <ide> * Get size of data set. <ide> * @return The number of rows in the set. <ide> public int size() { <ide> return rows.size(); <ide> } <del> <add> <ide> /** <ide> * Clear contents (package-private). <ide> */ <ide> final void clear() { <ide> rows.clear(); <ide> } <del> <add> <ide> /** <ide> * Add a row to the data set. <ide> * @param columnValues Column values forming a row. <ide> * @return The data set instance (for chained calls). <add> * @throws InvalidOperationException if this data set is read-only. <add> * @see #row(Object[][]) <add> * @see #add(DataSet) <add> * @see #isReadOnly() <ide> */ <ide> public final DataSet row(Object... columnValues) { <ide> checkIfNotReadOnly(); <ide> if (columnValues.length != source.getColumnCount()) { <ide> throw new InvalidOperationException(source.getColumnCount() + <del> " columns expected, not " + columnValues.length + "."); <add> " columns expected, not " + columnValues.length + "."); <ide> } <ide> addRow(new RowImpl(columnValues)); <ide> return this; <ide> } <ide> <del> <add> <ide> /** <ide> * Add rows to the data set. <ide> * @param rows Array of rows. <ide> * @return The data set instance (for chained calls). <add> * @throws InvalidOperationException if this data set is read-only. <add> * @see #row(Object...) <add> * @see #add(DataSet) <add> * @see #isReadOnly() <ide> */ <ide> public final DataSet row(Object[][] rows) { <ide> checkIfNotReadOnly(); <ide> } <ide> <ide> /** <add> * Add rows of given data set to this data set. <add> * <add> * @param other The other data set. <add> * @return The data set instance (for chained calls). <add> * @throws InvalidOperationException if this data set is read-only. <add> * @see #row(Object...) <add> * @see #row(Object[][]) <add> * @see #isReadOnly() <add> */ <add> public DataSet add(DataSet other) { <add> checkIfNotReadOnly(); <add> rows.addAll(other.rows); <add> return this; <add> } <add> <add> /** <ide> * Add a row to the set (package-private version; ignores read-only setting). <ide> * @param r Row to add. <ide> */ <ide> final void addRow(Row r) { <ide> rows.add(r); <ide> } <del> <add> <ide> /** <ide> * Get an iterator for the row set. <ide> * @return An iterator object. <ide> @Override <ide> public Iterator<Row> iterator() { <ide> return !readOnly ? rows.iterator() <del> : Collections.unmodifiableList(rows).iterator(); <del> } <del> <add> : Collections.unmodifiableList(rows).iterator(); <add> } <add> <ide> @Override <ide> public boolean equals(Object o) { <ide> return o == this || <del> ( o instanceof DataSet && <del> rows.equals(((DataSet) o).rows) ); <del> } <del> <add> ( o instanceof DataSet && <add> rows.equals(((DataSet) o).rows) ); <add> } <add> <ide> /** <ide> * Create sub-set of a given data set. <ide> * @param data Data set. <ide> } <ide> return sub; <ide> } <del> <del> /** <del> * Add rows of given data set to this set. <del> * @param other This data set. <del> * @return The data set instance (for chained calls). <del> */ <del> public DataSet add(DataSet other) { <del> checkIfNotReadOnly(); <del> rows.addAll(other.rows); <del> return this; <del> } <add> <add> <ide> <ide> @SuppressWarnings("javadoc") <ide> private void checkIfNotReadOnly() {
Java
unlicense
c249fe0fd74c99b6d9d3658feab430fd341e6504
0
paulo-raca/jts-polygonizer
import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; public class RangeMultiMap<V> { Map<Double, SortedMap<Envelope1D, Collection<V>>> scaleMapss = new HashMap<>(); private double discreteLen(double len) { return len == 0 ? 0 : Math.exp(Math.ceil(Math.log(len))); } public boolean put(Envelope1D range, V value) { double scaleLength = discreteLen(range.len()); SortedMap<Envelope1D, Collection<V>> scaleData = scaleMapss.get(scaleLength); if (scaleData == null) { scaleData = new TreeMap<>(); scaleMapss.put(scaleLength, scaleData); } Collection<V> values = scaleData.get(range); if (values == null) { values = new ArrayList<>(); scaleData.put(range, values); } return values.add(value); } public boolean remove(Envelope1D range, V value) { double scaleLength = discreteLen(range.len()); SortedMap<Envelope1D, Collection<V>> scaleData = scaleMapss.get(scaleLength); if (scaleData == null) { return false; } Collection<V> values = scaleData.get(range); if (values == null) { return false; } if (!values.remove(value)) { return false; } if (values.isEmpty()) { scaleData.remove(range); if (scaleData.isEmpty()) { scaleMapss.remove(scaleLength); } } return true; } public Iterable<Envelope1D> getKeys(Envelope1D query) { return Iterables.transform(getEntries(query), new Function<Map.Entry<Envelope1D, Collection<V>>, Envelope1D>() { public Envelope1D apply(Map.Entry<Envelope1D, Collection<V>> entry) { return entry.getKey(); }; }); } public Iterable<V> getValues(Envelope1D query) { return Iterables.concat(Iterables.transform(getEntries(query), new Function<Map.Entry<Envelope1D, Collection<V>>, Collection<V>>() { public Collection<V> apply(Map.Entry<Envelope1D, Collection<V>> entry) { return entry.getValue(); }; })); } public Iterable<Map.Entry<Envelope1D, Collection<V>>> getEntries(final Envelope1D query) { Collection<Iterable<Map.Entry<Envelope1D, Collection<V>>>> scaleIterators = new ArrayList<>(); for (Map.Entry<Double, SortedMap<Envelope1D, Collection<V>>> entry : scaleMapss.entrySet()) { Double scale = entry.getKey(); SortedMap<Envelope1D, Collection<V>> scaleValues = entry.getValue(); scaleIterators.add(Iterables.filter( scaleValues.subMap( new Envelope1D(query.min - scale, Double.NEGATIVE_INFINITY), new Envelope1D(query.max, Double.POSITIVE_INFINITY)).entrySet(), new Predicate<Map.Entry<Envelope1D, Collection<V>>>() { @Override public boolean apply(Entry<Envelope1D, Collection<V>> entry) { return query.intersects(entry.getKey()) ; } })); } return Iterables.mergeSorted(scaleIterators, new Comparator<Map.Entry<Envelope1D, Collection<V>>>() { @Override public int compare(Entry<Envelope1D, Collection<V>> o1, Entry<Envelope1D, Collection<V>> o2) { return o1.getKey().compareTo(o2.getKey()); } }); } }
src/RangeMultiMap.java
import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; import com.google.common.base.Function; import com.google.common.collect.AbstractIterator; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; public class RangeMultiMap<V> { Map<Double, SortedMap<Envelope1D, Collection<V>>> scaleMapss = new HashMap<>(); private double discreteLen(double len) { return len == 0 ? 0 : Math.exp(Math.ceil(Math.log(len))); } public boolean put(Envelope1D range, V value) { double scaleLength = discreteLen(range.len()); SortedMap<Envelope1D, Collection<V>> scaleData = scaleMapss.get(scaleLength); if (scaleData == null) { scaleData = new TreeMap<>(); scaleMapss.put(scaleLength, scaleData); } Collection<V> values = scaleData.get(range); if (values == null) { values = new ArrayList<>(); scaleData.put(range, values); } return values.add(value); } public boolean remove(Envelope1D range, V value) { double scaleLength = discreteLen(range.len()); SortedMap<Envelope1D, Collection<V>> scaleData = scaleMapss.get(scaleLength); if (scaleData == null) { return false; } Collection<V> values = scaleData.get(range); if (values == null) { return false; } if (!values.remove(value)) { return false; } if (values.isEmpty()) { scaleData.remove(range); if (scaleData.isEmpty()) { scaleMapss.remove(scaleLength); } } return true; } public Iterable<Envelope1D> getKeys(Envelope1D query) { return Iterables.transform(getEntries(query), new Function<Map.Entry<Envelope1D, Collection<V>>, Envelope1D>() { public Envelope1D apply(Map.Entry<Envelope1D, Collection<V>> entry) { return entry.getKey(); }; }); } public Iterable<V> getValues(Envelope1D query) { return Iterables.concat(Iterables.transform(getEntries(query), new Function<Map.Entry<Envelope1D, Collection<V>>, Collection<V>>() { public Collection<V> apply(Map.Entry<Envelope1D, Collection<V>> entry) { return entry.getValue(); }; })); } public Iterable<Map.Entry<Envelope1D, Collection<V>>> getEntries(final Envelope1D query) { return new Iterable<Map.Entry<Envelope1D, Collection<V>>>() { @Override public Iterator<Entry<Envelope1D, Collection<V>>> iterator() { Collection<Iterator<Map.Entry<Envelope1D, Collection<V>>>> scaleIterators = new ArrayList<>(); for (Map.Entry<Double, SortedMap<Envelope1D, Collection<V>>> entry : scaleMapss.entrySet()) { Double scale = entry.getKey(); SortedMap<Envelope1D, Collection<V>> scaleValues = entry.getValue(); scaleValues = scaleValues.tailMap( new Envelope1D(query.min - scale, Double.NEGATIVE_INFINITY) ); final Iterator<Entry<Envelope1D, Collection<V>>> preFilterIterator = scaleValues.entrySet().iterator(); scaleIterators.add(new AbstractIterator<Entry<Envelope1D, Collection<V>>>() { @Override protected Entry<Envelope1D, Collection<V>> computeNext() { while (true) { if (!preFilterIterator.hasNext()) { return endOfData(); } Entry<Envelope1D, Collection<V>> entry = preFilterIterator.next(); if (entry.getKey().min > query.max) { return endOfData(); } if (query.intersects(entry.getKey())) { return entry; } } } }); } return Iterators.mergeSorted(scaleIterators, new Comparator<Map.Entry<Envelope1D, Collection<V>>>() { @Override public int compare(Entry<Envelope1D, Collection<V>> o1, Entry<Envelope1D, Collection<V>> o2) { return o1.getKey().compareTo(o2.getKey()); } }); } }; } }
Better search implementation on RangeMultiMap
src/RangeMultiMap.java
Better search implementation on RangeMultiMap
<ide><path>rc/RangeMultiMap.java <ide> import java.util.Collection; <ide> import java.util.Comparator; <ide> import java.util.HashMap; <del>import java.util.Iterator; <ide> import java.util.Map; <ide> import java.util.Map.Entry; <ide> import java.util.SortedMap; <ide> import java.util.TreeMap; <ide> <ide> import com.google.common.base.Function; <del>import com.google.common.collect.AbstractIterator; <add>import com.google.common.base.Predicate; <ide> import com.google.common.collect.Iterables; <del>import com.google.common.collect.Iterators; <ide> <ide> public class RangeMultiMap<V> { <ide> Map<Double, SortedMap<Envelope1D, Collection<V>>> scaleMapss = new HashMap<>(); <ide> } <ide> <ide> public Iterable<Map.Entry<Envelope1D, Collection<V>>> getEntries(final Envelope1D query) { <del> return new Iterable<Map.Entry<Envelope1D, Collection<V>>>() { <add> Collection<Iterable<Map.Entry<Envelope1D, Collection<V>>>> scaleIterators = new ArrayList<>(); <add> for (Map.Entry<Double, SortedMap<Envelope1D, Collection<V>>> entry : scaleMapss.entrySet()) { <add> Double scale = entry.getKey(); <add> SortedMap<Envelope1D, Collection<V>> scaleValues = entry.getValue(); <add> <add> scaleIterators.add(Iterables.filter( <add> scaleValues.subMap( <add> new Envelope1D(query.min - scale, Double.NEGATIVE_INFINITY), <add> new Envelope1D(query.max, Double.POSITIVE_INFINITY)).entrySet(), <add> new Predicate<Map.Entry<Envelope1D, Collection<V>>>() { <add> @Override <add> public boolean apply(Entry<Envelope1D, Collection<V>> entry) { <add> return query.intersects(entry.getKey()) <add> ; <add> } <add> })); <add> } <add> <add> return Iterables.mergeSorted(scaleIterators, new Comparator<Map.Entry<Envelope1D, Collection<V>>>() { <ide> @Override <del> public Iterator<Entry<Envelope1D, Collection<V>>> iterator() { <del> Collection<Iterator<Map.Entry<Envelope1D, Collection<V>>>> scaleIterators = new ArrayList<>(); <del> for (Map.Entry<Double, SortedMap<Envelope1D, Collection<V>>> entry : scaleMapss.entrySet()) { <del> Double scale = entry.getKey(); <del> SortedMap<Envelope1D, Collection<V>> scaleValues = entry.getValue(); <del> <del> scaleValues = scaleValues.tailMap( new Envelope1D(query.min - scale, Double.NEGATIVE_INFINITY) ); <del> <del> final Iterator<Entry<Envelope1D, Collection<V>>> preFilterIterator = scaleValues.entrySet().iterator(); <del> <del> scaleIterators.add(new AbstractIterator<Entry<Envelope1D, Collection<V>>>() { <del> @Override <del> protected Entry<Envelope1D, Collection<V>> computeNext() { <del> while (true) { <del> if (!preFilterIterator.hasNext()) { <del> return endOfData(); <del> } <del> <del> Entry<Envelope1D, Collection<V>> entry = preFilterIterator.next(); <del> <del> if (entry.getKey().min > query.max) { <del> return endOfData(); <del> } <del> <del> if (query.intersects(entry.getKey())) { <del> return entry; <del> } <del> } <del> } <del> }); <del> } <del> return Iterators.mergeSorted(scaleIterators, new Comparator<Map.Entry<Envelope1D, Collection<V>>>() { <del> @Override <del> public int compare(Entry<Envelope1D, Collection<V>> o1, Entry<Envelope1D, Collection<V>> o2) { <del> return o1.getKey().compareTo(o2.getKey()); <del> } <del> }); <add> public int compare(Entry<Envelope1D, Collection<V>> o1, Entry<Envelope1D, Collection<V>> o2) { <add> return o1.getKey().compareTo(o2.getKey()); <ide> } <del> }; <add> }); <ide> } <ide> } <add>
JavaScript
mit
ba29804b0b3ea8c94bd8b4943ecdfc18e252eefa
0
edrap/edrap.github.io,edrap/edrap.github.io,edrap/edrap.github.io
function leaflet_alert() { var newLine = "\r\n" var brows = "The map was tested on Firefox and Safari. To use it on Chrome you must allow mixed contents." var resp = "The users take full responsibility for using the map for outdoor activities." msg = brows + newLine + newLine + resp; alert(msg); } function onEachFeature(feature, layer) { //var popupContent = null; if (feature.properties && feature.properties.description) { //popupContent += feature.properties.description; popupContent = feature.properties.description; } layer.bindPopup(popupContent, { maxWidth: "200", maxHeight : "300", closeOnClick: true, closeButton: false, offset: [110, 10] }); //layer.bringToFront(); } function onEachLoadedFeature(feature, layer) { //var popupContent = null; //console.log(feature) if (feature.properties && feature.properties.name) { //popupContent += feature.properties.description; popupContent = feature.properties.name; } layer.bindPopup(popupContent, { maxWidth: "200", maxHeight : "300", closeOnClick: true, closeButton: false, //offset: [10, 10] }); //layer.bringToFront(); } function readTextFile(feature, layer) { var rawFile = new XMLHttpRequest(); rawFile.open("GET", "https://www.meteoaquilano.it/abruzzo/filedate.txt", false); rawFile.onreadystatechange = function () { if(rawFile.readyState === 4) { if(rawFile.status === 200 || rawFile.status == 0) { popupContent = rawFile.responseText; layer.bindPopup(popupContent, { maxWidth: "200", maxHeight : "300", closeOnClick: true, closeButton: false, //offset: [10, 10] }); } } } }
leaflet/js/custom_funct.js
function leaflet_alert() { var newLine = "\r\n" var brows = "The map was tested on Firefox and Safari. To use it on Chrome you must allow mixed contents." var resp = "The users take full responsibility for using the map for outdoor activities." msg = brows + newLine + newLine + resp; alert(msg); } function onEachFeature(feature, layer) { //var popupContent = null; if (feature.properties && feature.properties.description) { //popupContent += feature.properties.description; popupContent = feature.properties.description; } layer.bindPopup(popupContent, { maxWidth: "200", maxHeight : "300", closeOnClick: true, closeButton: false, offset: [110, 10] }); //layer.bringToFront(); } function onEachLoadedFeature(feature, layer) { //var popupContent = null; //console.log(feature) if (feature.properties && feature.properties.name) { //popupContent += feature.properties.description; popupContent = feature.properties.name; } layer.bindPopup(popupContent, { maxWidth: "200", maxHeight : "300", closeOnClick: true, closeButton: false, //offset: [10, 10] }); //layer.bringToFront(); } function readTextFile(file) { var rawFile = new XMLHttpRequest(); rawFile.open("GET", file, false); rawFile.onreadystatechange = function () { snowdate = "" if(rawFile.readyState === 4) { if(rawFile.status === 200 || rawFile.status == 0) { snowdate = rawFile.responseText; } } } return snowdate; }
Update custom_funct.js
leaflet/js/custom_funct.js
Update custom_funct.js
<ide><path>eaflet/js/custom_funct.js <ide> //layer.bringToFront(); <ide> } <ide> <del>function readTextFile(file) <add>function readTextFile(feature, layer) <ide> { <ide> var rawFile = new XMLHttpRequest(); <del> rawFile.open("GET", file, false); <add> rawFile.open("GET", "https://www.meteoaquilano.it/abruzzo/filedate.txt", false); <ide> rawFile.onreadystatechange = function () <ide> { <del> snowdate = "" <ide> if(rawFile.readyState === 4) <ide> { <ide> if(rawFile.status === 200 || rawFile.status == 0) <ide> { <del> snowdate = rawFile.responseText; <add> popupContent = rawFile.responseText; <add> layer.bindPopup(popupContent, { <add> maxWidth: "200", <add> maxHeight : "300", <add> closeOnClick: true, <add> closeButton: false, <add> //offset: [10, 10] <add> }); <ide> } <ide> } <ide> } <del> return snowdate; <ide> }
JavaScript
unlicense
8d0ba2c73a421e8e227bf6a5c5cadd902c3748ec
0
lamassu/lamassu-server,lamassu/lamassu-server,naconner/lamassu-server,naconner/lamassu-server,lamassu/lamassu-server,naconner/lamassu-server
const qs = require('querystring') const axios = require('axios') const _ = require('lodash/fp') const { fetchRBF } = require('../../wallet/bitcoind/bitcoind') module.exports = { authorize } function highConfidence (confidence, txref) { if (txref.double_spend) return 0 if (txref.rbf) return 0 if (txref.confirmations > 0 || txref.confidence * 100 >= confidence) return txref.value return 0 } function authorize (account, toAddress, cryptoAtoms, cryptoCode, isBitcoindAvailable) { let promise = [] return Promise.resolve() .then(() => { if (cryptoCode !== 'BTC') throw new Error('Unsupported crypto: ' + cryptoCode) const query = qs.stringify({ token: account.token, includeConfidence: true }) const confidence = account.confidenceFactor const isRBFEnabled = account.rbf const url = `https://api.blockcypher.com/v1/btc/main/addrs/${toAddress}?${query}` return axios.get(url) .then(r => { const data = r.data if (isBitcoindAvailable && isRBFEnabled && data.unconfirmed_txrefs) { _.map(unconfirmedTxref => { promise.push(new Promise((resolve, reject) => { resolve(fetchRBF(unconfirmedTxref.tx_hash)) })) }, data.unconfirmed_txrefs) return Promise.all(promise) .then(values => { _.map(rbfInfo => { _.map(unconfirmedTxref => { if (rbfInfo.tx_hash === unconfirmedTxref.tx_hash) unconfirmedTxref.rbf = rbfInfo['bip125-replaceable'] }, data.unconfirmed_txrefs) }, values) const sumTxRefs = txrefs => _.sumBy(txref => highConfidence(confidence, txref), txrefs) const authorizedValue = sumTxRefs(data.txrefs) + sumTxRefs(data.unconfirmed_txrefs) return cryptoAtoms.lte(authorizedValue) }) } else { const sumTxRefs = txrefs => _.sumBy(txref => highConfidence(confidence, txref), txrefs) const authorizedValue = sumTxRefs(data.txrefs) + sumTxRefs(data.unconfirmed_txrefs) return cryptoAtoms.lte(authorizedValue) } }) }) }
lib/plugins/zero-conf/blockcypher/blockcypher.js
const qs = require('querystring') const axios = require('axios') const _ = require('lodash/fp') const { fetchRBF } = require('../../wallet/bitcoind/bitcoind') module.exports = { authorize } function highConfidence (confidence, txref) { if (txref.double_spend) return 0 if (txref.rbf) return 0 if (txref.confirmations > 0 || txref.confidence * 100 >= confidence) return txref.value return 0 } function authorize (account, toAddress, cryptoAtoms, cryptoCode, isBitcoindAvailable) { var promise = [] return Promise.resolve() .then(() => { if (cryptoCode !== 'BTC') throw new Error('Unsupported crypto: ' + cryptoCode) const query = qs.stringify({ token: account.token, includeConfidence: true }) const confidence = account.confidenceFactor const verifyRBF = account.rbf const url = `https://api.blockcypher.com/v1/btc/main/addrs/${toAddress}?${query}` return axios.get(url) .then(r => { const data = r.data if (isBitcoindAvailable && verifyRBF && data.unconfirmed_txrefs) { _.map(unconfirmedTxref => { promise.push(new Promise((resolve, reject) => { resolve(fetchRBF(unconfirmedTxref.tx_hash)) })) }, data.unconfirmed_txrefs) return Promise.all(promise) .then(values => { _.map(rbfInfo => { _.map(unconfirmedTxref => { if (rbfInfo.tx_hash === unconfirmedTxref.tx_hash) unconfirmedTxref.rbf = rbfInfo['bip125-replaceable'] }, data.unconfirmed_txrefs) }, values) const sumTxRefs = txrefs => _.sumBy(txref => highConfidence(confidence, txref), txrefs) const authorizedValue = sumTxRefs(data.txrefs) + sumTxRefs(data.unconfirmed_txrefs) return cryptoAtoms.lte(authorizedValue) }) } else { const sumTxRefs = txrefs => _.sumBy(txref => highConfidence(confidence, txref), txrefs) const authorizedValue = sumTxRefs(data.txrefs) + sumTxRefs(data.unconfirmed_txrefs) return cryptoAtoms.lte(authorizedValue) } }) }) }
refactor: variable rename and remove trailing spaces
lib/plugins/zero-conf/blockcypher/blockcypher.js
refactor: variable rename and remove trailing spaces
<ide><path>ib/plugins/zero-conf/blockcypher/blockcypher.js <ide> } <ide> <ide> function authorize (account, toAddress, cryptoAtoms, cryptoCode, isBitcoindAvailable) { <del> var promise = [] <add> let promise = [] <ide> return Promise.resolve() <ide> .then(() => { <ide> if (cryptoCode !== 'BTC') throw new Error('Unsupported crypto: ' + cryptoCode) <add> <ide> const query = qs.stringify({ <ide> token: account.token, <ide> includeConfidence: true <ide> }) <add> <ide> const confidence = account.confidenceFactor <del> const verifyRBF = account.rbf <add> const isRBFEnabled = account.rbf <ide> const url = `https://api.blockcypher.com/v1/btc/main/addrs/${toAddress}?${query}` <add> <ide> return axios.get(url) <ide> .then(r => { <ide> const data = r.data <del> if (isBitcoindAvailable && verifyRBF && data.unconfirmed_txrefs) { <add> if (isBitcoindAvailable && isRBFEnabled && data.unconfirmed_txrefs) { <ide> _.map(unconfirmedTxref => { <ide> promise.push(new Promise((resolve, reject) => { resolve(fetchRBF(unconfirmedTxref.tx_hash)) })) <ide> }, data.unconfirmed_txrefs)
Java
mit
35ba3b83bb27a5fa8c62ec02c572f0e20bd6111a
0
judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin,judovana/jenkins-scm-koji-plugin
package org.fakekoji.api.xmlrpc; import hudson.plugins.scm.koji.model.Build; import hudson.plugins.scm.koji.model.RPM; import org.fakekoji.DataGenerator; import org.fakekoji.core.AccessibleSettings; import org.fakekoji.core.FakeKojiDB; import org.fakekoji.jobmanager.JenkinsJobTemplateBuilder; import org.fakekoji.xmlrpc.server.xmlrpcrequestparams.GetBuildList; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.fakekoji.DataGenerator.RELEASE_1; import static org.fakekoji.DataGenerator.RELEASE_2; import static org.fakekoji.DataGenerator.SUFFIX; public class NewApiTest { @ClassRule public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); private static FakeKojiDB kojiDB; @BeforeClass public static void setup() throws IOException { final DataGenerator.FolderHolder folderHolder = DataGenerator.initFolders(temporaryFolder); DataGenerator.initBuildsRoot(folderHolder.buildsRoot); final AccessibleSettings settings = DataGenerator.getSettings(folderHolder); kojiDB = new FakeKojiDB(settings); } @Test public void getSourcesOfBuilt() { final int expectedNumberOfBuilds = 0; final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=release buildPlatform=f29.x86_64", JenkinsJobTemplateBuilder.SOURCES, false ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); } @Test public void getSourcesOfPartiallyNotBuilt() { final int expectedNumberOfBuilds = 2; final Set<String> expectedArchives = new HashSet<>(Arrays.asList( "java-1.8.0-openjdk-version2-" + RELEASE_1 + ".uName.src" + SUFFIX, "java-1.8.0-openjdk-version2-" + RELEASE_2 + ".uName.src" + SUFFIX )); final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=fastdebug buildPlatform=f29.x86_64", JenkinsJobTemplateBuilder.SOURCES, false ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); for (final Build build : buildList) { Assert.assertEquals(1, build.getRpms().size()); final RPM rpm = build.getRpms().get(0); Assert.assertTrue(expectedArchives.contains(rpm.getFilename(SUFFIX))); } } @Test public void getSourcesOfNotBuiltAtAll() { final int expectedNumberOfBuilds = 4; final Set<String> expectedArchives = new HashSet<>(Arrays.asList( "java-1.8.0-openjdk-version1-" + RELEASE_1 + ".uName.src" + SUFFIX, "java-1.8.0-openjdk-version1-" + RELEASE_2 + ".uName.src" + SUFFIX, "java-1.8.0-openjdk-version2-" + RELEASE_1 + ".uName.src" + SUFFIX, "java-1.8.0-openjdk-version2-" + RELEASE_2 + ".uName.src" + SUFFIX )); final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=slowdebug buildPlatform=f29.x86_64", JenkinsJobTemplateBuilder.SOURCES, false ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); for (final Build build : buildList) { Assert.assertEquals(1, build.getRpms().size()); final RPM rpm = build.getRpms().get(0); Assert.assertTrue(expectedArchives.contains(rpm.getFilename(SUFFIX))); } } @Test public void getArchiveOfBuilt() { final int expectedNumberOfBuilds = 4; final Set<String> expectedArchives = new HashSet<>(Arrays.asList( "java-1.8.0-openjdk-version1-" + RELEASE_1 + ".uName.release.hotspot.f29.x86_64" + SUFFIX, "java-1.8.0-openjdk-version1-" + RELEASE_2 + ".uName.release.hotspot.f29.x86_64" + SUFFIX, "java-1.8.0-openjdk-version2-" + RELEASE_1 + ".uName.release.hotspot.f29.x86_64" + SUFFIX, "java-1.8.0-openjdk-version2-" + RELEASE_2 + ".uName.release.hotspot.f29.x86_64" + SUFFIX )); final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=release", "f29.x86_64", true ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); for (final Build build : buildList) { Assert.assertEquals(1, build.getRpms().size()); final RPM rpm = build.getRpms().get(0); Assert.assertTrue(expectedArchives.contains(rpm.getFilename(SUFFIX))); } } @Test public void getArchiveOfPartiallyNotBuilt() { final int expectedNumberOfBuilds = 2; final Set<String> expectedArchives = new HashSet<>(Arrays.asList( "java-1.8.0-openjdk-version1-" + RELEASE_1 + ".uName.fastdebug.hotspot.f29.x86_64" + SUFFIX, "java-1.8.0-openjdk-version1-" + RELEASE_2 + ".uName.fastdebug.hotspot.f29.x86_64" + SUFFIX )); final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=fastdebug", "f29.x86_64", true ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); for (final Build build : buildList) { Assert.assertEquals(1, build.getRpms().size()); final RPM rpm = build.getRpms().get(0); Assert.assertTrue(expectedArchives.contains(rpm.getFilename(SUFFIX))); } } @Test public void getArchiveOfNotBuiltAtAll() { final int expectedNumberOfBuilds = 0; final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=slowdebug", "f29.x86_64", false ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); } private String getBuildNumberMessage(final int expected, final int actual) { return "Expected number of builds: " + expected + ", got: " + actual; } }
fake-koji/src/test/java/org/fakekoji/api/xmlrpc/NewApiTest.java
package org.fakekoji.api.xmlrpc; import hudson.plugins.scm.koji.model.Build; import hudson.plugins.scm.koji.model.RPM; import org.fakekoji.DataGenerator; import org.fakekoji.core.AccessibleSettings; import org.fakekoji.core.FakeKojiDB; import org.fakekoji.jobmanager.JenkinsJobTemplateBuilder; import org.fakekoji.xmlrpc.server.xmlrpcrequestparams.GetBuildList; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static org.fakekoji.DataGenerator.RELEASE_1; import static org.fakekoji.DataGenerator.RELEASE_2; import static org.fakekoji.DataGenerator.SUFFIX; public class NewApiTest { @ClassRule public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); private static FakeKojiDB kojiDB; @BeforeClass public static void setup() throws IOException { final File builds = temporaryFolder.newFolder("builds"); final DataGenerator.FolderHolder folderHolder = DataGenerator.initFolders(temporaryFolder); DataGenerator.initBuildsRoot(builds); final AccessibleSettings settings = DataGenerator.getSettings(folderHolder); kojiDB = new FakeKojiDB(settings); } @Test public void getSourcesOfBuilt() { final int expectedNumberOfBuilds = 0; final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=release buildPlatform=f29.x86_64", JenkinsJobTemplateBuilder.SOURCES, false ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); } @Test public void getSourcesOfPartiallyNotBuilt() { final int expectedNumberOfBuilds = 2; final Set<String> expectedArchives = new HashSet<>(Arrays.asList( "java-1.8.0-openjdk-version2-" + RELEASE_1 + ".uName.src" + SUFFIX, "java-1.8.0-openjdk-version2-" + RELEASE_2 + ".uName.src" + SUFFIX )); final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=fastdebug buildPlatform=f29.x86_64", JenkinsJobTemplateBuilder.SOURCES, false ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); for (final Build build : buildList) { Assert.assertEquals(1, build.getRpms().size()); final RPM rpm = build.getRpms().get(0); Assert.assertTrue(expectedArchives.contains(rpm.getFilename(SUFFIX))); } } @Test public void getSourcesOfNotBuiltAtAll() { final int expectedNumberOfBuilds = 4; final Set<String> expectedArchives = new HashSet<>(Arrays.asList( "java-1.8.0-openjdk-version1-" + RELEASE_1 + ".uName.src" + SUFFIX, "java-1.8.0-openjdk-version1-" + RELEASE_2 + ".uName.src" + SUFFIX, "java-1.8.0-openjdk-version2-" + RELEASE_1 + ".uName.src" + SUFFIX, "java-1.8.0-openjdk-version2-" + RELEASE_2 + ".uName.src" + SUFFIX )); final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=slowdebug buildPlatform=f29.x86_64", JenkinsJobTemplateBuilder.SOURCES, false ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); for (final Build build : buildList) { Assert.assertEquals(1, build.getRpms().size()); final RPM rpm = build.getRpms().get(0); Assert.assertTrue(expectedArchives.contains(rpm.getFilename(SUFFIX))); } } @Test public void getArchiveOfBuilt() { final int expectedNumberOfBuilds = 4; final Set<String> expectedArchives = new HashSet<>(Arrays.asList( "java-1.8.0-openjdk-version1-" + RELEASE_1 + ".uName.release.hotspot.f29.x86_64" + SUFFIX, "java-1.8.0-openjdk-version1-" + RELEASE_2 + ".uName.release.hotspot.f29.x86_64" + SUFFIX, "java-1.8.0-openjdk-version2-" + RELEASE_1 + ".uName.release.hotspot.f29.x86_64" + SUFFIX, "java-1.8.0-openjdk-version2-" + RELEASE_2 + ".uName.release.hotspot.f29.x86_64" + SUFFIX )); final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=release", "f29.x86_64", true ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); for (final Build build : buildList) { Assert.assertEquals(1, build.getRpms().size()); final RPM rpm = build.getRpms().get(0); Assert.assertTrue(expectedArchives.contains(rpm.getFilename(SUFFIX))); } } @Test public void getArchiveOfPartiallyNotBuilt() { final int expectedNumberOfBuilds = 2; final Set<String> expectedArchives = new HashSet<>(Arrays.asList( "java-1.8.0-openjdk-version1-" + RELEASE_1 + ".uName.fastdebug.hotspot.f29.x86_64" + SUFFIX, "java-1.8.0-openjdk-version1-" + RELEASE_2 + ".uName.fastdebug.hotspot.f29.x86_64" + SUFFIX )); final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=fastdebug", "f29.x86_64", true ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); for (final Build build : buildList) { Assert.assertEquals(1, build.getRpms().size()); final RPM rpm = build.getRpms().get(0); Assert.assertTrue(expectedArchives.contains(rpm.getFilename(SUFFIX))); } } @Test public void getArchiveOfNotBuiltAtAll() { final int expectedNumberOfBuilds = 0; final GetBuildList params = new GetBuildList( DataGenerator.PROJECT_NAME_U, "jvm=hotspot debugMode=slowdebug", "f29.x86_64", false ); List<Build> buildList = kojiDB.getBuildList(params); Assert.assertEquals( getBuildNumberMessage(expectedNumberOfBuilds, buildList.size()), expectedNumberOfBuilds, buildList.size() ); } private String getBuildNumberMessage(final int expected, final int actual) { return "Expected number of builds: " + expected + ", got: " + actual; } }
Fix test setup
fake-koji/src/test/java/org/fakekoji/api/xmlrpc/NewApiTest.java
Fix test setup
<ide><path>ake-koji/src/test/java/org/fakekoji/api/xmlrpc/NewApiTest.java <ide> import org.junit.Test; <ide> import org.junit.rules.TemporaryFolder; <ide> <del>import java.io.File; <ide> import java.io.IOException; <ide> import java.util.Arrays; <ide> import java.util.HashSet; <ide> <ide> @BeforeClass <ide> public static void setup() throws IOException { <del> final File builds = temporaryFolder.newFolder("builds"); <ide> final DataGenerator.FolderHolder folderHolder = DataGenerator.initFolders(temporaryFolder); <del> DataGenerator.initBuildsRoot(builds); <add> DataGenerator.initBuildsRoot(folderHolder.buildsRoot); <ide> final AccessibleSettings settings = DataGenerator.getSettings(folderHolder); <ide> <ide> kojiDB = new FakeKojiDB(settings);
Java
apache-2.0
180f0be3aa26e271853547746e5319141bccd0a3
0
reactor/reactor-netty,reactor/reactor-netty
/* * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.ipc.netty.resources; import java.net.SocketAddress; import java.util.function.Supplier; import io.netty.bootstrap.Bootstrap; import io.netty.channel.pool.ChannelHealthChecker; import io.netty.channel.pool.ChannelPool; import io.netty.channel.pool.FixedChannelPool; import io.netty.channel.pool.SimpleChannelPool; import reactor.core.Disposable; /** * A {@link io.netty.channel.pool.ChannelPool} selector with associated factories. * * @author Stephane Maldini * @since 0.6 */ @FunctionalInterface public interface PoolResources extends Disposable { /** * Default max connection, if -1 will never wait to acquire before opening new * connection in an unboundd fashion. Fallback to * available number of processors. */ int DEFAULT_POOL_MAX_CONNECTION = Integer.parseInt(System.getProperty("reactor.ipc.netty.pool.maxConnections", "" + Math.max(Runtime.getRuntime() .availableProcessors(), 8))); /** * Default acquisition timeout before error. If -1 will never wait to * acquire before opening new * connection in an unboundd fashion. Fallback to * available number of processors. */ long DEFAULT_POOL_ACQUIRE_TIMEOUT = Long.parseLong(System.getProperty( "reactor.ipc.netty.pool.acquireTimeout", "" + 45000)); /** * Create an uncapped {@link PoolResources} to provide automatically for {@link * ChannelPool}. * <p>An elastic {@link PoolResources} will never wait before opening a new * connection. The reuse window is limited but it cannot starve an undetermined volume * of clients using it. * * @param name the channel pool map name * * @return a new {@link PoolResources} to provide automatically for {@link * ChannelPool} */ static PoolResources elastic(String name) { return new DefaultPoolResources(name, SimpleChannelPool::new); } /** * Create a capped {@link PoolResources} to provide automatically for {@link * ChannelPool}. * <p>A Fixed {@link PoolResources} will open up to the given max number of * processors observed by this jvm (minimum 4). * Further connections will be pending acquisition indefinitely. * * @param name the channel pool map name * * @return a new {@link PoolResources} to provide automatically for {@link * ChannelPool} */ static PoolResources fixed(String name) { return fixed(name, DEFAULT_POOL_MAX_CONNECTION); } /** * Create a capped {@link PoolResources} to provide automatically for {@link * ChannelPool}. * <p>A Fixed {@link PoolResources} will open up to the given max connection value. * Further connections will be pending acquisition indefinitely. * * @param name the channel pool map name * @param maxConnections the maximum number of connections before starting pending * acquisition on existing ones * * @return a new {@link PoolResources} to provide automatically for {@link * ChannelPool} */ static PoolResources fixed(String name, int maxConnections) { return fixed(name, maxConnections, DEFAULT_POOL_ACQUIRE_TIMEOUT); } /** * Create a capped {@link PoolResources} to provide automatically for {@link * ChannelPool}. * <p>A Fixed {@link PoolResources} will open up to the given max connection value. * Further connections will be pending acquisition indefinitely. * * @param name the channel pool map name * @param maxConnections the maximum number of connections before starting pending * @param acquireTimeout the maximum time in millis to wait for aquiring * * @return a new {@link PoolResources} to provide automatically for {@link * ChannelPool} */ static PoolResources fixed(String name, int maxConnections, long acquireTimeout) { if (maxConnections != -1 && maxConnections <= 0) { throw new IllegalArgumentException("Max Connections value must be strictly " + "positive"); } if (acquireTimeout != -1L && acquireTimeout < 0) { throw new IllegalArgumentException("Acquire Timeout value must " + "be " + "positive"); } return new DefaultPoolResources(name, (bootstrap, handler) -> new FixedChannelPool(bootstrap, handler, ChannelHealthChecker.ACTIVE, FixedChannelPool.AcquireTimeoutAction.FAIL, acquireTimeout, maxConnections, Integer.MAX_VALUE )); } /** * Return an existing or new {@link ChannelPool}. The implementation will take care * of * pulling {@link Bootstrap} lazily when a {@link ChannelPool} creation is actually * needed. * * @param address the remote address to resolve for existing or * new {@link ChannelPool} * @param bootstrap the {@link Bootstrap} supplier if a {@link ChannelPool} must be * created * @return an existing or new {@link ChannelPool} */ ChannelPool selectOrCreate(SocketAddress address, Supplier<? extends Bootstrap> bootstrap); @Override default void dispose() { //noop default } }
src/main/java/reactor/ipc/netty/resources/PoolResources.java
/* * Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package reactor.ipc.netty.resources; import java.net.SocketAddress; import java.util.function.Supplier; import io.netty.bootstrap.Bootstrap; import io.netty.channel.pool.ChannelHealthChecker; import io.netty.channel.pool.ChannelPool; import io.netty.channel.pool.FixedChannelPool; import io.netty.channel.pool.SimpleChannelPool; import reactor.core.Disposable; /** * A {@link io.netty.channel.pool.ChannelPool} selector with associated factories. * * @author Stephane Maldini * @since 0.6 */ @FunctionalInterface public interface PoolResources extends Disposable { /** * Default max connection, if -1 will never wait to acquire before opening new * connection in an unboundd fashion. Fallback to * available number of processors. */ int DEFAULT_POOL_MAX_CONNECTION = Integer.parseInt(System.getProperty("reactor.ipc.netty.pool.maxConnections", "" + Runtime.getRuntime() .availableProcessors())); /** * Default acquisition timeout before error. If -1 will never wait to * acquire before opening new * connection in an unboundd fashion. Fallback to * available number of processors. */ long DEFAULT_POOL_ACQUIRE_TIMEOUT = Long.parseLong(System.getProperty( "reactor.ipc.netty.pool.acquireTimeout", "" + 45000)); /** * Create an uncapped {@link PoolResources} to provide automatically for {@link * ChannelPool}. * <p>An elastic {@link PoolResources} will never wait before opening a new * connection. The reuse window is limited but it cannot starve an undetermined volume * of clients using it. * * @param name the channel pool map name * * @return a new {@link PoolResources} to provide automatically for {@link * ChannelPool} */ static PoolResources elastic(String name) { return new DefaultPoolResources(name, SimpleChannelPool::new); } /** * Create a capped {@link PoolResources} to provide automatically for {@link * ChannelPool}. * <p>A Fixed {@link PoolResources} will open up to the given max number of * processors observed by this jvm (minimum 4). * Further connections will be pending acquisition indefinitely. * * @param name the channel pool map name * * @return a new {@link PoolResources} to provide automatically for {@link * ChannelPool} */ static PoolResources fixed(String name) { return fixed(name, DEFAULT_POOL_MAX_CONNECTION); } /** * Create a capped {@link PoolResources} to provide automatically for {@link * ChannelPool}. * <p>A Fixed {@link PoolResources} will open up to the given max connection value. * Further connections will be pending acquisition indefinitely. * * @param name the channel pool map name * @param maxConnections the maximum number of connections before starting pending * acquisition on existing ones * * @return a new {@link PoolResources} to provide automatically for {@link * ChannelPool} */ static PoolResources fixed(String name, int maxConnections) { return fixed(name, maxConnections, DEFAULT_POOL_ACQUIRE_TIMEOUT); } /** * Create a capped {@link PoolResources} to provide automatically for {@link * ChannelPool}. * <p>A Fixed {@link PoolResources} will open up to the given max connection value. * Further connections will be pending acquisition indefinitely. * * @param name the channel pool map name * @param maxConnections the maximum number of connections before starting pending * @param acquireTimeout the maximum time in millis to wait for aquiring * * @return a new {@link PoolResources} to provide automatically for {@link * ChannelPool} */ static PoolResources fixed(String name, int maxConnections, long acquireTimeout) { if (maxConnections != -1 && maxConnections <= 0) { throw new IllegalArgumentException("Max Connections value must be strictly " + "positive"); } if (acquireTimeout != -1L && acquireTimeout < 0) { throw new IllegalArgumentException("Acquire Timeout value must " + "be " + "positive"); } return new DefaultPoolResources(name, (bootstrap, handler) -> new FixedChannelPool(bootstrap, handler, ChannelHealthChecker.ACTIVE, FixedChannelPool.AcquireTimeoutAction.FAIL, acquireTimeout, maxConnections, Integer.MAX_VALUE )); } /** * Return an existing or new {@link ChannelPool}. The implementation will take care * of * pulling {@link Bootstrap} lazily when a {@link ChannelPool} creation is actually * needed. * * @param address the remote address to resolve for existing or * new {@link ChannelPool} * @param bootstrap the {@link Bootstrap} supplier if a {@link ChannelPool} must be * created * @return an existing or new {@link ChannelPool} */ ChannelPool selectOrCreate(SocketAddress address, Supplier<? extends Bootstrap> bootstrap); @Override default void dispose() { //noop default } }
increase default pool size
src/main/java/reactor/ipc/netty/resources/PoolResources.java
increase default pool size
<ide><path>rc/main/java/reactor/ipc/netty/resources/PoolResources.java <ide> */ <ide> int DEFAULT_POOL_MAX_CONNECTION = <ide> Integer.parseInt(System.getProperty("reactor.ipc.netty.pool.maxConnections", <del> "" + Runtime.getRuntime() <del> .availableProcessors())); <add> "" + Math.max(Runtime.getRuntime() <add> .availableProcessors(), 8))); <ide> <ide> /** <ide> * Default acquisition timeout before error. If -1 will never wait to
Java
apache-2.0
44f41b13d3a397be11630ab35a9daee4e2c1fa7b
0
b2ihealthcare/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl
/* * Copyright 2011-2017 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.snomed.api.rest; import static com.b2international.snowowl.test.commons.rest.RestExtensions.givenAuthenticatedRequest; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.Date; import java.util.Map; import com.b2international.snowowl.core.api.IBranchPath; import com.b2international.snowowl.core.date.DateFormats; import com.b2international.snowowl.core.date.EffectiveTimes; import com.google.common.collect.ImmutableMap; import com.jayway.restassured.http.ContentType; import com.jayway.restassured.response.ValidatableResponse; /** * @since 5.0 */ public class SnomedRefSetRestRequests { public static ValidatableResponse updateRefSetComponent(IBranchPath branchPath, SnomedComponentType type, String id, Map<?, ?> requestBody, boolean force) { assertThat(type, anyOf(equalTo(SnomedComponentType.REFSET), equalTo(SnomedComponentType.MEMBER))); return givenAuthenticatedRequest(SnomedApiTestConstants.SCT_API) .contentType(ContentType.JSON) .body(requestBody) .queryParam("force", force) .put("/{path}/{componentType}/{id}", branchPath.getPath(), type.toLowerCasePlural(), id) .then(); } public static ValidatableResponse bulkUpdateMembers(IBranchPath branchPath, String refSetId, Map<?, ?> bulkRequest) { return givenAuthenticatedRequest(SnomedApiTestConstants.SCT_API) .contentType(ContentType.JSON) .body(bulkRequest) .put("/{path}/refsets/{id}/members", branchPath.getPath(), refSetId) .then(); } public static void updateRefSetMemberEffectiveTime(IBranchPath memberPath, String memberId, Date effectiveTime) { String effectiveTimeAsString = EffectiveTimes.format(effectiveTime, DateFormats.SHORT); Map<?, ?> parentRequest = ImmutableMap.builder() .put("effectiveTime", effectiveTimeAsString) .put("commitComment", "Updated effective time on reference set member") .build(); updateRefSetComponent(memberPath, SnomedComponentType.MEMBER, memberId, parentRequest, true).statusCode(204); } private SnomedRefSetRestRequests() { throw new UnsupportedOperationException("This class is not supposed to be instantiated."); } }
snomed/com.b2international.snowowl.snomed.api.rest.tests/src/com/b2international/snowowl/snomed/api/rest/SnomedRefSetRestRequests.java
/* * Copyright 2011-2017 B2i Healthcare Pte Ltd, http://b2i.sg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.b2international.snowowl.snomed.api.rest; import static com.b2international.snowowl.test.commons.rest.RestExtensions.givenAuthenticatedRequest; import static org.hamcrest.CoreMatchers.anyOf; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.Date; import java.util.Map; import com.b2international.snowowl.core.api.IBranchPath; import com.b2international.snowowl.core.date.DateFormats; import com.b2international.snowowl.core.date.EffectiveTimes; import com.google.common.collect.ImmutableMap; import com.jayway.restassured.http.ContentType; import com.jayway.restassured.response.ValidatableResponse; /** * @since 5.0 */ public class SnomedRefSetRestRequests { public static ValidatableResponse updateRefSetComponent(IBranchPath branchPath, SnomedComponentType type, String id, Map<?, ?> requestBody, boolean force) { assertThat(type, anyOf(equalTo(SnomedComponentType.REFSET), equalTo(SnomedComponentType.MEMBER))); return givenAuthenticatedRequest(SnomedApiTestConstants.SCT_API) .contentType(ContentType.JSON) .body(requestBody) .queryParam("force", force) .put("/{path}/{componentType}/{id}", branchPath.getPath(), type.toLowerCasePlural(), id) .then(); } public static void updateRefSetMemberEffectiveTime(IBranchPath memberPath, String memberId, Date effectiveTime) { String effectiveTimeAsString = EffectiveTimes.format(effectiveTime, DateFormats.SHORT); Map<?, ?> parentRequest = ImmutableMap.builder() .put("effectiveTime", effectiveTimeAsString) .put("commitComment", "Updated effective time on reference set member") .build(); updateRefSetComponent(memberPath, SnomedComponentType.MEMBER, memberId, parentRequest, true).statusCode(204); } private SnomedRefSetRestRequests() { throw new UnsupportedOperationException("This class is not supposed to be instantiated."); } }
SO-2154 Add bulk member update method to SnomedRefSetRestRequests
snomed/com.b2international.snowowl.snomed.api.rest.tests/src/com/b2international/snowowl/snomed/api/rest/SnomedRefSetRestRequests.java
SO-2154 Add bulk member update method to SnomedRefSetRestRequests
<ide><path>nomed/com.b2international.snowowl.snomed.api.rest.tests/src/com/b2international/snowowl/snomed/api/rest/SnomedRefSetRestRequests.java <ide> .then(); <ide> } <ide> <add> public static ValidatableResponse bulkUpdateMembers(IBranchPath branchPath, String refSetId, Map<?, ?> bulkRequest) { <add> return givenAuthenticatedRequest(SnomedApiTestConstants.SCT_API) <add> .contentType(ContentType.JSON) <add> .body(bulkRequest) <add> .put("/{path}/refsets/{id}/members", branchPath.getPath(), refSetId) <add> .then(); <add> } <add> <ide> public static void updateRefSetMemberEffectiveTime(IBranchPath memberPath, String memberId, Date effectiveTime) { <ide> String effectiveTimeAsString = EffectiveTimes.format(effectiveTime, DateFormats.SHORT); <ide>
JavaScript
bsd-2-clause
423a3c60d34d760188123b3bb85869c80b778b01
0
BeerShift/BeerShift
function createDrankDetailWindow(e) { var windowBeerDetails = Ti.UI.createWindow({ width : 320, height : 480, top : 0, left : 0, backgroundColor : 'black', title : L('winBeerDetails'), barImage : 'images/navbar.png' }); var detailsView = Ti.UI.createView({ width : 320, height : windowBeerDetails.height - 134, left : 0, top : 0, backgroundColor : 'black', borderRadius : 5 }); // Let start adding our UI elements var beerImage = Titanium.UI.createImageView({ image : 'images/pitcher.jpg', width : 80, height : 62, left : 10, top : 20 }); var labelBeerDetailName = Titanium.UI.createLabel({ width : 'auto', height : 30, top : 40, left : 100, color : 'white', font : { fontSize : 14, fontFamily : 'Helvetica', fontWeight : 'bold' }, text : e._title }); var labelWhenDrank = Titanium.UI.createLabel({ width : 'auto', height : 30, top : 58, left : 100, color : 'white', font : { fontSize : 14, fontFamily : 'Helvetica', fontWeight : 'bold' }, text : e._when }); // Add our UI elements to our view detailsView.add(labelBeerDetailName); detailsView.add(labelWhenDrank); detailsView.add(beerImage); windowBeerDetails.add(detailsView); return windowBeerDetails; }
Resources/whereDrank.js
function createDrankDetailWindow(e) { var windowBeerDetails = Ti.UI.createWindow({ width : 320, height : 480, top : 0, left : 0, backgroundColor : 'black', title : L('winBeerDetails'), barImage : 'images/navbar.png' }); var detailsView = Ti.UI.createView({ width : 320, height : windowBeerDetails.height - 134, left : 0, top : 0, backgroundColor : 'black', borderRadius : 5 }); // Let start adding our UI elements var beerImage = Titanium.UI.createImageView({ image : 'images/pitcher.jpg', width : 80, height : 62, left : 10, top : 20 }); var labelBeerDetailName = Titanium.UI.createLabel({ width : 'auto', height : 30, top : 40, left : 100, color : 'white', font : { fontSize : 14, fontFamily : 'Helvetica', fontWeight : 'bold' }, text : e._title }); var labelWhenDrank = Titanium.UI.createLabel({ width : 'auto', height : 30, top : 58, left : 100, color : 'white', font : { fontSize : 14, fontFamily : 'Helvetica', fontWeight : 'bold' }, text : e._when }); // Add our UI elements to our view var beerAnnotation = Titanium.Map.createAnnotation({ latitude : 41.88925, longitude : -87.632638, title : e._title, subtitle : e._when, pincolor : Titanium.Map.ANNOTATION_RED, animate : true }); var mapview = Titanium.Map.createView({ top : 110, height : 350, mapType : Titanium.Map.STANDARD_TYPE, region : { latitude : 41.88925, longitude : -87.632638, latitudeDelta : 0.5, longitudeDelta : 0.5 }, animate : true, regionFit : true, userLocation : true, annotations:[beerAnnotation] }); detailsView.add(mapview); detailsView.add(labelBeerDetailName); detailsView.add(labelWhenDrank); detailsView.add(beerImage); windowBeerDetails.add(detailsView); return windowBeerDetails; }
Cleanup
Resources/whereDrank.js
Cleanup
<ide><path>esources/whereDrank.js <ide> }); <ide> <ide> // Add our UI elements to our view <del> var beerAnnotation = Titanium.Map.createAnnotation({ <del> latitude : 41.88925, <del> longitude : -87.632638, <del> title : e._title, <del> subtitle : e._when, <del> pincolor : Titanium.Map.ANNOTATION_RED, <del> animate : true <del> }); <del> <del> var mapview = Titanium.Map.createView({ <del> top : 110, <del> height : 350, <del> mapType : Titanium.Map.STANDARD_TYPE, <del> region : { <del> latitude : 41.88925, <del> longitude : -87.632638, <del> latitudeDelta : 0.5, <del> longitudeDelta : 0.5 <del> }, <del> animate : true, <del> regionFit : true, <del> userLocation : true, <del> annotations:[beerAnnotation] <del> }); <del> detailsView.add(mapview); <ide> <ide> detailsView.add(labelBeerDetailName); <ide> detailsView.add(labelWhenDrank);
JavaScript
mit
7070b8331f2e10a23747175b03448a7d7ac31a41
0
umd-mith/TILE,umd-mith/TILE
///TILE LOGBAR //TODO: make proper documentation //TILE_ENGINE: {Object} main engine for running the LogBar and Layout of TILE interface //Global Constants that other plugins can use var URL_LIST=[]; (function($){ var TILE=this; var jsonTags={"schema":"","transcript":"","group":"","shape":""}; /**Main Engine **/ //loads in html layout from columns.json, parses JSON and sends to all // other objects // // Creates: // TileLogBar - _log // ImageTagger - _Itag // Functions // getBase - checks TILECONSTANTS.json for base http data // setUp - makes TileLogBar, ImageTagger, sets global binds // addNewTool - sets a new tool - users must define tool in .js code and proper JSON format // saveSettings - starts prompt to save all data in session // start_New_Session - // clear_Image_Tags - clears the log bar of all tags for a particular image // clear_All_Tags - clears the LogBar completely var TILE_ENGINE=Monomyth.Class.extend({ init:function(args){ //get HTML from PHP script and attach to passed container this.loc=(args.attach)?args.attach:$("body"); var self=this; self.toolSet=args.toolSet; self.json=null; //check if there is json data self.checkJSON(); }, checkJSON:function(){ var self=this; var d=$.ajax({ url:'PHP/isJSON.php', dataType:"text", async:false }).responseText; if(d) self.json=eval('('+d+')'); self.getBase(); }, getBase:function(){ //check JSON file to configure main path var self=this; $.ajax({url:'TILECONSTANTS.json',dataType:'json',success:function(d){ //d refers to the JSON data self._base=d.base; self._importDefault=d.importDefault; $.ajax({ dataType:"json", url:"./lib/JSONHTML/columns.json", success:function(d){ //d represents JSON data // $(d.body).appendTo($("body")); self.DOM=$("body"); //this.startURL=args.URL; //self.json=(args.json)?args.json:false; self.schemaFile=null; self.preLoadData=null; //global bind for sidebar completion event to loadCanvas() self.setUp(d); } }); },async:false}); }, /**Get Schema**/ //taken from setMultiFileImport Custom Event call from ImportDialog getSchema:function(e,file,schema){ var obj=e.data.obj; //We are just getting the file with images // and the transcripts obj.imageFile=file; //make ajax call to file $.ajax({ url:obj.imageFile, dataType:'json', success:function(d){ //d refers to JSON object retrieved from imageFile URL_LIST=d; var dt=new Date(); var tlines=[]; //searching for transcripts for(tr in d){ if(d[tr].transcript){ $.merge(tlines,d[tr].transcript); } } //TODO: get correct json format for loading/saving if(!obj.json) obj.json=d; $("body:first").trigger("loadImageList"); $("body:first").trigger("closeImpD"); obj._log._addLines(tlines); //if(tlines.length) $("body:first").trigger("addLogBarItem",[{"items":tlines}]); } }); // obj.jsonReader.readSchemaFromFile(obj.schemaFile); }, setUp:function(d){ var self=this; //store JSON html data - has everything for layout this.columnslayout=d; //create log - goes towards left area //this._log=new TileLogBar({html:this.columnslayout,json:this.json}); this._log=new Transcript({loc:"logbar_list",text:null}); this._activeBox=new ActiveBox({loc:"az_activeBox"}); this._transcriptBar=new TileToolBar({loc:"transcript_toolbar"}); $("body").bind("tagRulesSet",{obj:this},this.TRSetHandle); //get dialog JSON data $.ajax({ url:"lib/JSONHTML/dialogs.json", dataType:"json", success:function(x){ self.dialogJSON=x; self.addDialogBoxes(); } }); //important variables //finishes the rest of init this.toolbarArea=$("#header"); //JSON Reader this.jsonReader=new jsonReader({}); //start ImageTagger if(this.toolSet){ //send to toolbar this._transcriptBar.setChoices(this.toolSet); this.setUpTool("imagetagger"); } $("body").bind("schemaFileImported",{obj:this},this.getSchema); //$("body").bind("saveAllSettings",{obj:this},this.saveSettings); //TODO:create restartALL procedure $("body").bind("restartAll",{obj:this},this.start_New_Session); //global bind for clearing all tags on current image $("body").bind("clearPage",{obj:this},this.clear_Image_Tags); //global bind for clearing all tags on every image $("body").bind("clearSession",{obj:this},this.clear_All_Tags); //global bind for when user selects a new tool from LogBar $("body").bind("toolSelected",{obj:this},this.addNewTool); //global bind for when data is ready to be passed as JSON to user $("body").bind("JSONreadyToSave",{obj:this},this._saveToUser); //global bind for when user clicks on transcript object $("body").bind("TranscriptLineSelected",{obj:this},this._transcriptSelectHandle); //for when user clicks on save $("body").bind("saveAllSettings",{obj:this},this._saveSettingsHandle); if(this.json){ //parse data //var p=this.jsonReader.read(this.json); //if(!p) window.location("."); //$("body").bind("tagRulesSet",{obj:this},this.loadJSONImages); this.jsonReader.readSchemaFromFile(this.json.schema); URL_LIST=this.json.images; // $("body:first").trigger("loadImageList"); //$("body").trigger("loadJSONList",[this.json.images]); // this.DOM.trigger("schemaLoaded",[p]); } }, TRSetHandle:function(e,c){ var obj=e.data.obj; $("body").unbind("tagRulesSet",obj.TRSetHandle); //c is the schema data obj._log.setChoices(c); obj.schemaData=c; $.ajax({ url:obj.imageFile, dataType:'json', success:function(d){ URL_LIST=d; var dt=new Date(); var tlines=[]; //searching for transcripts for(tr in d){ if(d[tr].transcript){ for(line in d[tr].transcript){ //create an item for manifest.tags if(d[tr].transcript[line].length>0){ tlines.push({ 'type':'transcript', 'uri':d[tr].uri, 'name':(d[tr].transcript[line].substring(0,5)+"..."), 'uid':'t'+dt.getTime('milliseconds')+tlines.length, 'etc':{"text":d[tr].transcript[line]} }); } } } } $("body:first").trigger("loadImageList"); $("body:first").trigger("closeImpD"); if(tlines.length) $("body:first").trigger("addLogBarItem",[{"items":tlines}]); } }); }, addDialogBoxes:function(){ //load dialog boxes this.importDialog=new ImportDialog({ loc:$("body"), html:this.dialogJSON.dialogimport, auto:this._importDefault }); this.loadTagsDialog=new LoadTags({ loc:$("body"), html:this.dialogJSON.dialogloadtags }); //new Image Dialog this.nImgD=new NewImageDialog({loc:"body",html:this.dialogJSON.dialogaddimage}); //if json data present, set up urls if(!this.json) { this.DOM.trigger("openImport"); } }, setUpTool:function(toolname){ var obj=this; toolname=toolname.toLowerCase().replace(" ",""); if(obj.curTool&&(obj.curTool.name==toolname)) return; if(obj.toolSet){ for(tool in obj.toolSet){ if(obj.toolSet[tool].name==toolname){ //select in toolSelect obj._transcriptBar.setChoice(toolname); if(!obj.toolSet[tool].constructed){ obj.toolSet[tool].start(null,self._base,(obj.json)?obj.json:null); //give place where it opens into obj.toolSet[tool].constructed=true; obj.curTool=obj.toolSet[tool]; $("body").bind(obj.toolSet[tool].done,{obj:obj,tool:obj.toolSet[tool]},obj._toolDoneHandle); } else { //tool already constructed, restart tool obj.curTool=obj.toolSet[tool]; obj.curTool.restart(); } break; } } } // //replace the main log area with whatever // var mv='-='+$(".az.main > #az_log").width(); // $(".az.main > #az_log").animate({left:mv,opacity:0.25},400,function(e){ // $(".az.main > #az_log").children().hide(); // $(".az.main > #az_log").removeClass("log").addClass("tool"); // $(".az.main > #az_log").animate({opacity:1,left:0},200); // // toolname=toolname.toLowerCase().replace(" ",""); // // //NEW: accessing autorecognizer tools // // //AUTORECOGNIZER // // $("body").bind("ARStart",{obj:obj},function(e){ // // //stop the imagetagger from listening // // $("body").trigger("closeDownVD",[true]); // // }); // // }); }, //responds to custom event - toolSelected addNewTool:function(e,toolname){ var obj=e.data.obj; //replace the main log area with whatever toolname=toolname.toLowerCase().replace(" ",""); if(toolname==obj.curTool.name) return; // //NEW: accessing autorecognizer tools // //AUTORECOGNIZER // $("body").bind("ARStart",{obj:obj},function(e){ // //stop the imagetagger from listening // $("body").trigger("closeDownVD",[true]); // }); obj.curTool.close(); if(obj.toolSet){ for(tool in obj.toolSet){ if(obj.toolSet[tool].name==toolname){ //select in toolSelect obj._transcriptBar.setChoice(toolname); if(!obj.toolSet[tool].constructed){ obj.toolSet[tool].start(null,obj.schemaData,obj._log.exportLines()); //give place where it opens into obj.toolSet[tool].constructed=true; obj.curTool=obj.toolSet[tool]; $("body").bind(obj.toolSet[tool].done,{obj:obj,tool:obj.toolSet[tool]},obj._toolDoneHandle); if(obj.toolSet[tool].outputData) $("body").bind(obj.toolSet[tool].outputData,{obj:obj},obj._toolOutputHandle); } else { //tool already constructed, restart tool obj.curTool=obj.toolSet[tool]; obj.toolSet[tool].restart(obj._log.exportLines()); } break; } } } }, _toolDoneHandle:function(e){ var self=e.data.obj; //$("#az_log").removeClass("tool").addClass("log"); self.curTool=null; self.setUpTool("imagetagger"); }, _toolOutputHandle:function(e,data){ var self=e.data.obj; self._log._addLines(data); }, _transcriptSelectHandle:function(e,data){ var self=e.data.obj; self._activeBox._addItem(data); }, saveSettings:function(e){ var obj=e.data.obj; }, start_New_Session:function(e){ var obj=e.data.obj; //restart the entire session //erases images, tags, shapes //obj._Itag.restart(); obj.curTool.restart(); obj._log.restart(); //if(obj.Scroller) obj.Scroller._resetContainer(); //if(obj.SideBar) obj.SideBar._resetAllTags(); //open up import dialog obj.DOM.trigger("openImport"); }, //clear only the shapes and tags drawn on the current image clear_Image_Tags:function(e){ var obj=e.data.obj; // obj.SideBar.reset_Curr_Manifest(); // obj.raphael._resetCurrImage(); }, clear_All_Tags:function(e){ var obj=e.data.obj; // obj.SideBar._resetAllTags(); // obj.raphael._eraseAllShapes(); }, _saveSettingsHandle:function(e){ var self=e.data.obj; //curTool is imagetagger self.json=self.curTool.bundleData(self.json); if(!self.save) self.save=new Save({loc:"azglobalmenu"}); self.save.userPrompt(self.json); // j.schema=self.jsonReader.schemaFile; // //get elements from plugins // for(b in self.toolSet){ // j=self.toolSet[b].bundleData(j); // } // // if(!self.save) self.save=new Save({loc:"azglobalmenu"}); // self.save.userPrompt(j); } }); /** Dialog Boxes: Import, New Image, Load Tags **/ //ImportDialog /** Called by openImport CustomEvent **/ var ImportDialog=Dialog.extend({ init:function(args){ this.$super(args); this.index=($("#dialog").length+this.loc.width()); this.autoFill=args.auto; // this.loc.append($.ajax({ // async:false, // dataType:'html', // url:'lib/Dialog/dialogImport.html' // }).responseText); //lightbox content this.light=$("#light"); this.fade=$("#fade"); this.DOM=$("#dialogImport"); this.closeB=$("#importDataClose"); this.closeB.click(function(e){ $(this).trigger("closeImpD"); }); //this.schemaFileInput=$("#importDataFormInputSingle"); //this.schemaFileFormSubmit=$("#importDataFormSubmitSingle"); //this.schemaFileFormSubmit.bind("click",{obj:this},this.handleSchemaForm); this.multiFileInput=$("#importDataFormInputMulti").val(this.autoFill); this.multiFileFormSubmit=$("#importDataFormSubmitMulti"); this.multiFileFormSubmit.bind("click",{obj:this},this.handleMultiForm); $("body").bind("openNewImage",{obj:this},this.close); $("body").bind("closeImpD",{obj:this},this.close); $("body").bind("openLoadTags",{obj:this},this.close); $("body").bind("openImport",{obj:this},this.display); }, display:function(e){ var obj=e.data.obj; obj.fade.show(); obj.DOM.show(); obj.light.show(); }, close:function(e){ var obj=e.data.obj; obj.light.hide(); obj.DOM.hide(); obj.fade.hide(); }, handleSchemaForm:function(e){ e.preventDefault(); var obj=e.data.obj; var file=obj.schemaFileInput.text(); if(/http:\/\//.test(file)){ obj.DOM.trigger("schemaFileImported",[file]); } else { //show warning: not a valid URI } }, //finds the transcript/image file that the user // has input and sends it off in a CustomEvent trigger // schemaFileImported handleMultiForm:function(e){ e.preventDefault(); var obj=e.data.obj; var file=obj.multiFileInput.val(); //var schema=obj.schemaFileInput.attr("value"); if(file.length){ if(/http:\/\//.test(file)){ //trigger an event that sends both the schema and the list of files to listener obj.DOM.trigger("schemaFileImported",[file]); // obj.DOM.trigger("schemaLoaded",[{schema:schema}]); // obj.DOM.trigger("multiFileListImported",[file]); } else { //show warning: not a valid URI } } } }); TILE.ImportDialog=ImportDialog; var LoadTags=Dialog.extend({ init:function(args){ this.$super(args); // this.loc.append($.ajax({ // async:false, // url:'lib/Dialog/DialogLoadTags.html', // dataType:'html' // }).responseText); this.DOM=$("#loadTagsDialog"); this.closeB=$("#loadTagsClose"); this.closeB.click(function(e){ $(this).trigger("closeLoadTags"); }); this.light=$("#LTlight"); this.fade=$("#LTfade"); $("body").bind("openNewImage",{obj:this},this.close); $("body").bind("openImport",{obj:this},this.close); $("body").bind("openLoadTags",{obj:this},this.display); $("body").bind("closeLoadTags",{obj:this},this.close); }, display:function(e){ var obj=e.data.obj; obj.light.show(); obj.DOM.show(); obj.fade.show(); }, close:function(e){ var obj=e.data.obj; obj.light.hide(); obj.DOM.hide(); obj.fade.hide(); } }); TILE.LoadTags=LoadTags; // New Image Box var NewImageDialog=Dialog.extend({ init:function(args){ this.$super(args); // this.loc.append($.ajax({ // async:false, // url:'lib/Dialog/dialogNewImg.html', // dataType:'html' // }).responseText); this.DOM=$("#dialogNewImg"); this.closeB=$("#newImgClose"); this.closeB.click(function(e){ $(this).trigger("closeNewImage"); }); this.uriInput=$("#newImgURIInput"); this.submitB=$("#newImgSubmit"); this.submitB.bind("click",{obj:this},this.handleImageForm); $("body").bind("openImport",{obj:this},this.close); $("body").bind("openLoadTags",{obj:this},this.close); $("body").bind("openNewImage",{obj:this},this.display); $("body").bind("closeNewImage",{obj:this},this.close); }, display:function(e){ var obj=e.data.obj; obj.DOM.show(); obj.DOM.css({"z-index":"1001"}); }, close:function(e){ var obj=e.data.obj; obj.DOM.hide(); }, handleImageForm:function(e){ var obj=e.data.obj; if(obj.uriInput.val().length>0){ obj.DOM.trigger("newImageAdded",[obj.uriInput.val()]); obj.uriInput.attr("value",""); obj.DOM.trigger("closeNewImage"); } } }); TILE.NewImageDialog=NewImageDialog; /** Log Toolbar: Toolbar that contains objects that reflect a log of what is going on in main tagging/workspace area. //receives html in form of text **/ var Log=Monomyth.Class.extend({ init:function(args){ if(!args.html) throw "no JSON data passed to Log{}"; this.html=args.html; this.DOM=$("#az_log"); $(this.html.log).appendTo(this.DOM); } }); TileToolBar=Monomyth.Class.extend({ init:function(args){ //getting HTML that is already loaded - no need to attach anything var self=this; self.loc=args.loc; self.LoadB=$("#"+self.loc+" > .menuitem > ul > li > #load_tags"); self.SaveB=$("#"+self.loc+" > .menuitem > ul > li > #save_tags"); self.ToolSelect=$("#"+self.loc+" > #ddown > .menuitem.ddown > select"); self.ToolSelect.change(function(e){ var choice=self.ToolSelect.children("option:selected"); $(this).trigger("toolSelected",[choice.text().toLowerCase()]); }); //set up loading and saving windows self.LoadB.click(function(e){ e.preventDefault(); $(this).trigger("openLoadTags"); }); self.SaveB.click(function(e){ e.preventDefault(); $(this).trigger("saveAllSettings"); }); }, setChoices:function(data){ var self=this; self.ToolSelect.children("option").remove(); for(d in data){ if(data[d].name){ var el=$("<option>"+data[d].name+"</option>"); self.ToolSelect.append(el); } } }, setChoice:function(name){ var self=this; self.ToolSelect.children("option").each(function(i,o){ if(name==$(o).text().toLowerCase().replace(" ","")){ $(o)[0].selected=true; } else { $(o)[0].selected=false; } }); } }); /** TILE LogBar Inherits from Log in base.js **/ var TileLogBar=Log.extend({ init:function(args){ this.$super(args); this.DOM=$("#az_log > .az.inner"); this.toolbar=$("#az_log > .az.inner > .toolbar"); this.jsondata=(args.json||null); this.toolSelect=$("#az_log > .az.inner > .toolbar > #ddown > div.menuitem.ddown:nth-child(1) > select"); this.tagSelect=$("#az_log > .az.inner > .toolbar > #ddown > div.menuitem.ddown:nth-child(2) > select"); var hadjust=(this.toolbar.height()+((this.toolbar.css("border-width")+this.toolbar.css("padding"))*2)+2+127); this.logInsertPoint=$("#az_log > .az.inner > #logbar_list").height((this.DOM.height()-hadjust)).css("overflow","auto"); this.logActiveArea=$("#az_log > .az.inner > #logbar_activearea"); //group select element - user selects a group to add current active item into this.groupSelect=$("#"+this.logActiveArea.attr("id")+" > select"); var self=this; this.doneB=$("#logbar_activearea > div.activearea_head > div#logbar_done").click(function(e){ $("body").trigger("addedTag"); self._createListItem(); }); this.deleteB=$("#logbar_activearea > div.activearea_head > div#logbar_delete").click(function(e){ self._deleteListItem(); }); this.logbar_next=$("#az_log > .az.inner > #logNav > #logbar_next").click(function(e){ self._paginate(1); }); this.logbar_prev=$("#az_log > .az.inner > #logNav > #logbar_prev").click(function(e){ self._paginate(-1); });; this.pageSelectTool=$("#az_log > .az.inner > #logNav > #paginateInfo > #pageSelect"); this.pageSelectTool.change(function(e){ var target=$("#pageSelect > option:selected"); $(this).trigger("paginateTo",[parseInt(target.text(),10)]); }); //adding key listener for creating list items this.DOM.keypress(function(e){ if(e.keyCode==13){ $("body").trigger("addedTag"); self._createListItem(); } else if(e.keyCode==27){ self._deleteListItem(); } }); //this.logitemhtml=args.html.logitem; this.rules=null; this.GroupId=null; this.setUpToolBar(); //array for items about to be put in loglist this.emptytags=[]; //manifest array for all items in log_list this.manifest={"tags":[]}; this.tagCount=0; this.maxTags=6; this.showTags=[]; //local listeners this.DOM.bind("itemDropped",{obj:this},this.itemDroppedHandle); //global listeners $("body").bind("shapeDrawn",{obj:this},function(e,shape){ e.data.obj.addShape(shape,null); }); $("body").bind("tagRulesSet",{obj:this},this.initTagRules); $("body").bind("setGroup",{obj:this},this.setGroupHandle); $("body").bind("logGroupClosed",{obj:this},this.logGroupClosedHandle); $("body").bind("logGroupOpen",{obj:this},this.logGroupOpenHandle); $("body").bind("tagSelected",{obj:this},this.tagSelectedHandle); $("body").bind("saveAllSettings",{obj:this},this._saveP); $("body").bind("paginateTo",{obj:this},this._paginateToHandle); }, setUpToolBar:function(){ var self=this; self.loadB=$("#az_log > .az.inner > .toolbar > .menuitem > ul > li > #load_tags").click(function(e){ e.preventDefault(); $(this).trigger("openLoadTags"); }); self.saveB=$("#az_log > .az.inner > .toolbar > .menuitem > ul > li > #save_tags").click(function(e){ e.preventDefault(); $(this).trigger("saveAllSettings"); }); self.logInsertPoint.sortable({ items:'div.tag' }); //set up group select item self.groupSelect.children().each(function(i,o){ if(!$(o).attr('id')=='null'){ $(o).click(function(e){ //force-initiate the itemDropped call $(this).trigger("itemDropped",[$(this).parent().children("div.tag:visible").attr("id"),$(this).val()]); }); } }); //self.setChoices(); }, setChoices:function(d){ var self=this; self.rules=d; var c=[]; //var c=["Group","Transcript"];//TODO: make default that's changed by user? for(di in d.topLevelTags){ var diu=d.topLevelTags[di]; for(tag in d.tags){ if(diu==d.tags[tag].uid){ c.push({tname:d.tags[tag].name,tid:diu}); } } } //attach the addItem listener - listens for changes //in select and adds objects based on type paramater $("body").bind("addLogBarItem",{obj:self},self._addItemR); //bind a separate local listener to only listen to the menu items being clicked this.DOM.bind("addLogBarItem",{obj:this},function(e,t){ var obj=e.data.obj; e.stopPropagation(); //kill this from getting to "body" //based on what select returns, make that object appear in log if(t!=null){ switch(t.toLowerCase()){ case 'group': obj.addGroup(); break; case 'tag': obj.addTag(); break; case 'transcript': obj.addTranscript(); break; case 'shape': obj.addBlankShape(); break; default: obj.addTag(t); break; } } }); $.each(c,function(i,o){ //var elwrap=$("<option id=\"\">"+o.tname+"</option>").val(o.tid).appendTo(self.tagSelect); // var el=null; if(o.tname){ //el=$("<a href=\"\">"+o.tname+"</a>").val(o.tid).appendTo(elwrap); var el=$("<option>"+o.tname+"</option>").val(o.tid).appendTo(self.tagSelect); el.click(function(e){ e.preventDefault(); $(this).trigger("addLogBarItem",[$(this).val()]); }); } else { var el=$("<option>"+o+"</option>").val(o).appendTo(self.tagSelect); el.click(function(e){ e.preventDefault(); $(this).trigger("addLogBarItem",[$(this).val().toLowerCase()]); }); } }); //set finalHeight (fH) as data in the tagSelect object //self.heights[1]=(self.tagSelect.children().length*30); //set ToolChoices var bd=["Auto Recognizer"]; //engine handles when tool is selected - changes layout $.each(bd,function(i,o){ var el=$("<option>"+o+"</option>").val(o).appendTo(self.toolSelect); el.click(function(e){ e.preventDefault(); $(this).trigger("toolSelected",[$(this).val().toLowerCase()]); }); }); //set finalHeight for the toolSelect //self.heights[0]=(self.toolSelect.children().length*35); //set up pre-loaded tags, if json data exists if(self.jsondata&&self.jsondata.tags){ var items=$.merge(self.jsondata.groups,self.jsondata.tags); $("body:first").trigger("addLogBarItem",[{"items":items}]); } }, /** called by CustomEvent from LogBar **/ setGroupHandle:function(e,guid){ //group has been added to logbar var obj=e.data.obj; if(obj.GroupId&&obj.manifest.groups[obj.GroupId]){ obj.manifest.groups[obj.GroupId].setCloseState(); } obj.GroupId=guid; }, //for when a user drops something into a group's area itemDroppedHandle:function(e,id,gid){ var obj=e.data.obj; //called when a group object adds an item id=id.replace("copy",""); gid=gid.replace("copy",""); //just to be sure if(obj.manifest.tags[id]&&obj.manifest.tags[gid]){ obj.manifest.tags[gid].o.pushItem(obj.manifest.tags[id]); //if the group is in active area, display list var ctag=$("#"+obj.logActiveArea.attr('id')+" > div:not(.activearea_head)"); if(ctag.attr('id')==gid) obj.manifest.tags[gid].o._showList(); } // if(!gid){ // if(obj.GroupId&&(obj.manifest.groups[obj.GroupId])){ // var s=null; // var id=id.replace(/copy/,""); // if(obj.manifest.tags[id]){ // s=obj.manifest.tags[id].o; // // obj.manifest.groups[obj.GroupId].o.pushItem(s); // } else if(obj.manifest.groups[id]) { // //it's a group in a group // s=obj.manifest.groups[id].o; // // } // if(s) obj.manifest.groups[obj.GroupId].o.pushItem(s); // } // } else { // //find element // var item=null; // for(i in obj.manifest.tags){ // if(i==id){ // item=obj.manifest.tags[i]; // break; // } // } // // //gid is given-find group and add item to it // for(g in obj.manifest.groups){ // if(g==gid){ // var s=obj.manifest.groups[g]; // if(!s.manifest[item.uid]) s.o.pushItem(item); // break; // } // } // // } }, logGroupClosedHandle:function(e,guid){ var obj=e.data.obj; //change the GroupId obj.GroupId=null; }, logGroupOpenHandle:function(e,guid){ var obj=e.data.obj; obj.GroupId=guid; for(g in obj.manifest.groups){ if(obj.manifest.groups[g].o.uid!=guid) obj.manifest.groups[g].o.setCloseState(); } }, tagSelectedHandle:function(e,tid){ var self=e.data.obj; tid=tid.replace(/copy/,""); if(self.manifest.tags[tid]){ var t=self.manifest.tags[tid]; self.logActiveArea.children("div.tag").remove(); self.logActiveArea.children("div.group").remove(); t.o.DOM.appendTo(self.logActiveArea); if(t.type=='shape') $("body:first").trigger("_showShape",[t.o.shape.id]); if(t.type=='group') t.o._showList(); self.curItem=t; } }, /** Set as sortable list of objects **/ _draggableDroppable:function(){ $("#logbar_list").sortable({ items:"div", //restrict to only tags, transcripts, and shapes handle:'span.moveme' }); }, //adds an item to the activeArea - not yet in manifest, though, //until the user clicks 'done' _addItem:function(obj){ var self=this; self._updateListItem(); if($.inArray(obj.n,self.showTags)>-1){ self.logActiveArea.children("div.tag").remove(); self.logActiveArea.children("div.group").remove(); switch(obj.type){ case 'shape': if(!obj.o){ obj.o=new TileLogShape({ uid:obj.uid, name:(obj.name||obj.uid), html:obj.html, loc:self.logActiveArea.attr("id"), copyloc:self.logInsertPoint.attr("id"), shape:(obj.shape)?obj.shape:obj, etc:(obj.etc||null) }); obj.act=obj.o.DOM; if(!self.manifest.tags[obj.uid]) self.emptytags[obj.uid]=obj; } else { obj.o.DOM.appendTo(self.logActiveArea); } self.curItem=obj; break; case 'transcript': if(!obj.o){ if(!obj.etc); obj.o=new TileTranscriptTag({ uid:obj.uid, name:(obj.name||obj.uid), html:obj.html, loc:self.logActiveArea.attr("id"), copyloc:self.logInsertPoint.attr("id"), etc:(obj.etc||null) }); obj.act=obj.o.DOM; if(!self.manifest.tags[obj.uid]) self.emptytags[obj.uid]=obj; } else { obj.o.DOM.appendTo(self.logActiveArea); } self.curItem=obj; break; case 'schema': if(!obj.o){ obj.o=new TileLogTag({ uid:obj.uid, name:(obj.name||obj.uid), html:obj.html, loc:self.logActiveArea.attr('id'), copyloc:self.logInsertPoint.attr('id'), tagRules:self.rules, tagId:obj.tagId }); // obj.cur=new TagCopy({ // html:"<div id=\"\" class=\"tag transcript\">"+obj.o.DOM.html()+"</div>", // loc:self.logInsertPoint.attr("id"), // uid:obj.uid, // name:obj.o.name // }); obj.act=obj.o.DOM; if(!self.manifest.tags[obj.uid]) self.emptytags[obj.uid]=obj; } else { obj.o.DOM.appendTo(self.logActiveArea); } self.curItem=obj; break; case 'group': if(!obj.o){ //need to insert objects into etc - for(n in obj.etc){ var tag=self.manifest.tags[obj.etc[n]]; obj.etc[n]=tag; } if(obj.etc.length<self.maxTags){ //make group obj.o=new TileLogGroup({ loc:self.logActiveArea.attr('id'), html:obj.html, copyloc:self.logInsertPoint.attr('id'), etc:obj.etc, name:obj.name, uid:obj.uid }); obj.act=obj.o.DOM; } if(!self.manifest.tags[obj.uid]) self.emptytags[obj.uid]=obj; //add to list of groups in groupselect self.groupSelect.append($("<option>"+obj.o.name+"</option>").val(obj.uid).click(function(e){ var p=$(this).closest("div"); //alert($("#"+$(p).attr('id')+" > div:nth-child(2)").attr("id")); $(this).trigger("itemDropped",[$(p).children("div:visible").attr("id").substring(1),$(this).val()]); })); } else { obj.o.DOM.appendTo(self.logActiveArea); } self.curItem=obj; break; } } }, //adds the item to the manifest and makes a _copy object //to put in loginsertarea _createListItem:function(){ var self=this; if(self.curItem){ var check=false; if(self.curItem.n) check=true; //check if number of list items has gone over limit if(self.logInsertPoint.children("div").length>self.maxTags){ self._reOrderPages(); } switch(self.curItem.type){ case 'shape': if(!(self.logInsertPoint.children("#"+self.curItem.o.DOM.attr("id")+"copy").length>0)){ var copy=new TagCopy({ html:self.html.tagshape, type:self.curItem.type, shape:self.curItem.shape, uid:self.curItem.uid, loc:self.logInsertPoint.attr('id'), name:self.curItem.o.name }); } // else if(!self.logInsertPoint.children("#"+self.curItem.o._copy.DOM.attr("id")).length>0) { // self.curItem.o._copy.DOM.appendTo(self.logInsertPoint); // } self.curItem.o._tagUpdate(); break; case 'transcript': if(!(self.logInsertPoint.children("#"+self.curItem.o.DOM.attr("id")+"copy").length>0)){ var copy=new TagCopy({ html:self.html.tagtranscript, type:self.curItem.type, uid:self.curItem.uid, etc:self.curItem.etc, loc:self.logInsertPoint.attr('id'), name:self.curItem.o.name }); } // else if(!(self.logInsertPoint.children("#"+self.curItem.o._copy.DOM.attr("id")).length>0)){ // // self.curItem.o._copy.DOM.appendTo(self.logInsertPoint); // } self.curItem.o._tagUpdate(); break; case 'schema': if(!(self.logInsertPoint.children("#"+self.curItem.o.DOM.attr("id")+"copy").length>0)){ var copy=new TagCopy({ html:self.html.tilelogtag, type:self.curItem.type, uid:self.curItem.uid, loc:self.logInsertPoint.attr('id'), name:self.curItem.o.name }); } // else if(!self.logInsertPoint.children("#"+self.curItem.o._copy.DOM.attr("id")).length>0){ // self.curItem.o._copy.DOM.appendTo(self.logInsertPoint); // } self.curItem.o._tagUpdate(); break; case 'group': if(!(self.logInsertPoint.children("#"+self.curItem.o.DOM.attr("id")+"copy").length>0)){ var copy=new GroupCopy({ html:self.html.taggroup, type:self.curItem.type, uid:self.curItem.uid, etc:self.curItem.etc, loc:self.logInsertPoint.attr("id"), name:(self.curItem.o.name||self.curItem.uid) }); } // else if(!self.logInsertPoint.children("#"+self.curItem.o._copy.DOM.attr("id")).length>0){ // self.curItem.o._copy.DOM.appendTo(self.logInsertPoint); // } self.curItem.o._tagUpdate(); break; } if(!self.manifest.tags[self.curItem.uid]){ //Remove from emptytags and put in manifest self.manifest.tags[self.curItem.uid]=self.curItem; self.emptytags[self.curItem.uid]=null; self.emptytags=$.grep(self.emptytags,function(o,n){ return (o!=null); }); } if((self.curItem.type!='shape')){ //build another item of same type var d=new Date(); var uid="t"+d.getTime("milliseconds"); var nItem={ html:self.curItem.html, type:self.curItem.type, uid:uid, cur:null, etc:[], o:null, n:self.tagCount }; self.tagCount++; self.curItem=null; // so it isn't deleted self.manifest.tags[uid]=nItem; self.showTags.push(nItem.n); self._addItem(nItem); if ((self.curItem.type == 'transcript')) { $(".tagcontent>form>textarea").focus(); } } else if(self.curItem.type=='shape') { self.curItem.o.DOM.remove(); self.curItem=null; } self._overFlowHandle(); } }, //user went to next tag, while tag still present in activearea _updateListItem:function(obj){ var self=this; if(!obj) var obj=self.manifest.tags[$("#logbar_activearea > div.tag").attr('id')]; if(!obj) var obj=self.emptytags[$("#logbar_activearea > div.tag").attr('id')]; if(obj){ //check to see whether this item is in the emptytags or the manifest array if(self.manifest.tags[obj.uid]){ //update the tag and remove from logActiveArea obj.o._tagUpdate(); obj.o.DOM.remove(); } else if(self.emptytags[obj.uid]){ //not going to use this one - remove it completely //if it's a shape, also destroy the shape it came with if(obj.type=='shape') $("body").trigger("VD_REMOVESHAPE",[obj.uid]); self.emptytags[obj.uid]=null; self.emptytags=$.grep(self.emptytags,function(o,n){ return (o!=null); }); self.tagCount--; obj.o.DOM.remove(); if(obj.o._copy) obj.o._copy.DOM.remove(); } } }, //user clicked Delete _deleteListItem:function(obj){ var self=this; if(!obj) var obj=self.manifest.tags[$("#logbar_activearea > div:not(.activearea_head)").attr('id')]; if(!obj) obj=self.emptytags[$("#logbar_activearea > div.tag").attr('id')]; if(obj){ //check to see whether this item is in the emptytags or the manifest array if(self.manifest.tags[obj.uid]){ //delete the tag and remove from logActiveArea obj.o.DOM.remove(); $("#"+obj.uid+"copy").remove(); if(obj.type=='shape') $("body:first").trigger("VD_REMOVESHAPE",[obj.uid]); //if(obj.o._copy) obj.o._copy.DOM.remove(); self.manifest.tags[obj.uid]=null; self.tagCount--; } else if(self.emptytags[obj.uid]){ //not going to use this one - remove it completely //if it's a shape, also destroy the shape it came with if(obj.type=='shape') $("body").trigger("VD_REMOVESHAPE",[obj.uid]); //remove from DOM if(obj.o) obj.o.DOM.remove(); if(obj.o._copy) obj.o._copy.DOM.remove(); self.emptytags[obj.uid]=null; self.tagCount--; } if(self.logInsertPoint.children("div").length==0){ //empty log area - reset pages var t=parseInt(self.pageSelectTool.children(".pageChoice:selected").text(),10); self._reOrderPages(); $("body:first").trigger("paginateTo",[t]); } } }, /** Called from body tag using addLogBarItem Custom Event Loads a tag using JSON Items: array of items to add Group: (optional) add a group and an optional string to name that group - all items are added to this group **/ _addItemR:function(e,json){ var self=e.data.obj; if(json.shapes){ $("body:first").trigger("loadShapes",[json.shapes]); } //get json data and parse into element if(json.items){ for(it in json.items){ var item=json.items[it]; //determine type - if any //defaults to item name //var itemtype=item.name; if(item.type){ switch(item.type){ case "shape": case "rect": //create a shape tag if(!item.n){ var o={ uid:item.uid, cur:null, o:null, html:self.html.tagshape, name:(item.name)?item.name:null, type:'shape', shape:item.shape, etc:item.etc, n:self.tagCount }; //add shape to manifest self.manifest.tags[o.uid]=o; self.tagCount++; //if there's a group, create that group tag //must be a new group, otherwise add to that group's etc if(o.etc&&o.etc.groups){ //each subsequent group is added into the previous one var addGroup=[]; for(g in o.etc.groups){ var guid=o.etc.groups[g]; if(!self.manifest.tags[guid]){ self.manifest.tags[guid]={ cur:null, o:null, uid:guid, name:(item.name||null), html:self.html.taggroup, type:'group', group:null, etc:[o.uid], n:self.tagCount }; for(sub in addGroup){ self.manifest.tags[addGroup[sub]].etc.push(guid); } addGroup.push(guid); self.tagCount++; } else { self.manifest.tags[guid].etc.push(o.uid); addGroup.push(guid); } } } $.map(["width","height","x","y","cx","cy","rx","ry","path"],function(p){ if(p in item){ o.etc[p]=item[p]; } }); } else { //loaded from a JSON file - only need to copy contents //into _keepers item.html=self.html.tagshape; self.manifest.tags[item.uid]=item; self.tagCount=item.n; } break; case "transcript": if(!item.n){ //loaded from AR or from user input //create a transcript tag //could be loading something that is already loaded - check to see if(self.manifest.tags[item.uid]&&self.manifest.tags[item.uid].o) { self.manifest.tags[item.uid].o.DOM.remove(); if(self.manifest.tags[item.uid].o._copy) self.manifest.tags[item.uid].o._copy.DOM.remove(); self.manifest.tags[item.uid]=null; } self.manifest.tags[item.uid]={ cur:null, o:null, name:(item.name||null), uid:item.uid, type:'transcript', html:self.html.tagtranscript, etc:(item.etc||{"text":"Blank"}), n:self.tagCount }; self.tagCount++; //if there's a group, create that group tag //must be a new group, otherwise add to that group's etc if(item.etc&&item.etc.groups){ for(g in item.etc.groups){ var addGroup=[]; var guid=item.etc.groups[g]; if(!self.manifest.tags[guid]){ self.manifest.tags[guid]={ cur:null, o:null, uid:guid, html:self.html.taggroup, name:(item.etc.text)?item.etc.text:guid, type:'group', group:null, etc:[item.uid], n:self.tagCount }; for(sub in addGroup){ self.manifest.tags[addGroup[sub]].etc.push(guid); } addGroup.push(guid); self.tagCount++; } else { self.manifest.tags[guid].etc.push(item.uid); if(item.etc.text&&(self.manifest.tags[guid].name!=item.etc.text)){ self.manifest.tags[guid].name=item.etc.text; } addGroup.push(guid); } } } } else { //loaded from a JSON file - only need to copy contents //into _keepers item.html=self.html.tagtranscript; self.manifest.tags[item.uid]=item; self.tagCount=item.n; } //self.addTranscript(item); break; case "schema": if(!item.n){ //loaded from AR or from user input //create a transcript tag self.manifest.tags[item.uid]={ cur:null, o:null, name:(item.name||null), uid:item.uid, type:'schema', html:self.html, group:item.group, etc:(item.etc||"Blank"), n:self.tagCount }; self.tagCount++; //if there's a group, create that group tag //must be a new group, otherwise add to that group's etc if(o.etc&&o.etc.groups){ for(g in o.etc.groups){ var guid=o.etc.groups[g]; if(!self.manifest.tags[guid]){ self.manifest.tags[guid]={ cur:null, o:null, uid:guid, html:self.html.taggroup, type:'group', group:null, etc:[o.uid], n:self.tagCount }; for(sub in addGroup){ self.manifest.tags[addGroup[sub]].etc.push(guid); } addGroup.push(guid); self.tagCount++; } else { self.manifest.tags[guid].etc.push(o.uid); addGroup.push(guid); } } } } else { //loaded from a JSON file - only need to copy contents //into _keepers item.html=self.html.tagtranscript; self.manifest.tags[item.uid]=item; self.tagCount=item.n; } break; case "group": //create a holder for a group tag if(!item.n){ self.manifest.tags[item.uid]={ cur:null, o:null, uid:item.uid, type:'group', html:self.html.taggroup, group:null, etc:item.etc, n:self.tagCount }; self.tagCount++; //if there's a group, create that group tag //must be a new group, otherwise add to that group's etc if(item.etc&&item.etc.groups){ for(g in item.etc.groups){ var guid=item.etc.groups[g]; if(!self.manifest.tags[guid]){ self.manifest.tags[guid]={ cur:null, o:null, uid:guid, html:self.html.taggroup, type:'group', group:null, etc:[item.uid], n:self.tagCount }; for(sub in addGroup){ self.manifest.tags[addGroup[sub]].etc.push(guid); } addGroup.push(guid); self.tagCount++; } else { self.manifest.tags[guid].etc.push(o.uid); addGroup.push(guid); } } } } else { //loaded from a JSON file - only need to copy contents //into _keepers item.html=self.html.taggroup; self.manifest.tags[item.uid]=item; self.tagCount=item.n; } default: break; } } } // var pages=Math.ceil((self.tagCount/self.maxTags)); // $("#"+self.pageSelectTool.attr('id')+" > .pageChoice").remove(); // while(pages>0){ // var el=$("<option class=\"pageChoice\">"+pages+"</option>");// .click(function(e){ // // $(this).trigger("paginateTo",[parseInt($(this).text(),10)]); // // }); // // self.pageSelectTool.append(el); // // pages--; // } if(self.tagCount<self.maxTags){ for(i in self.manifest.tags){ if(self.manifest.tags[i]){ self.showTags.push(self.manifest.tags[i].n); self._addItem(self.manifest.tags[i]); self._createListItem(); start++; } } } else { //can show the tags that we added - some of them self.showTags=[]; var amount=(self.maxTags-self.logInsertPoint.children("div").length); var start=(self.tagCount-amount>0)?(self.tagCount-amount):0; for(i in self.manifest.tags){ if(self.manifest.tags[i]){ if(start==parseInt(self.manifest.tags[i].n,10)){ self.showTags.push(parseInt(self.manifest.tags[i].n,10)); self._addItem(self.manifest.tags[i]); self._createListItem(); start++; } } } } self._reOrderPages(); //user paginates to the next series of tags in order to see these added //tags } }, //after an object is set in the logInsertPoint area, //logbar needs to check if that object goes beyond the current page //of tags _overFlowHandle:function(){ var self=this; var next=0; var ok=0; if((self.logInsertPoint.children("div.tag").length+self.logInsertPoint.children("div.group").length)>=self.maxTags){ //gone over the limit self.logInsertPoint.empty(); self.showTags=[]; //add a new page or create pages self._reOrderPages(); var t=Math.ceil(self.tagCount/self.maxTags); var tm=self.tagCount-(self.tagCount-((t-1)*self.maxTags)); for(i in self.manifest.tags){ if(tm==parseInt(self.manifest.tags[i].n,10)){ self.showTags.push(parseInt(self.manifest.tags[i].n,10)); self._addItem(self.manifest.tags[i]); self._createListItem(); tm++; } } // for(s in self.manifest.tags){ // if(ok==0){ // next++; // if(next==(self.tagCount-1)){ // ok=1; // } // }else{ // self.showTags.push(self.manifest.tags[s].n); // self._addItem(self.manifest.tags[s]); // // if(!self.manifest.tags[s].o){ // // self._addItem(self.manifest.tags[s]); // // } else { // // self.manifest.tags[s].cur.appendTo(self.logInsertPoint); // // } // ok++; // if(ok==self.maxTags) break; // //next.push(self.manifest.tags[s].cur._copy.DOM); // } // } } // else { // //we're ok - add away // self.showTags.push(obj.n); // self._addItem(obj); // } }, //takes the amount of current tags (tagCount), then //divides by MaxTags, this new amount is how many option //tags are put in the pageSelect area _reOrderPages:function(){ var self=this; var totalp=Math.ceil(self.tagCount/self.maxTags); self.pageSelectTool.children(".pageChoice").remove(); for(i=1;i!=totalp;i++){ var el=$("<option class=\"pageChoice\">"+(i)+"</option>"); self.pageSelectTool.append(el); } self.pageSelectTool.children(".pageChoice:last-child")[0].selected=true; }, //called by paginateTo custom event //@p is the integer value for which set of tags to go to _paginateToHandle:function(e,p){ var self=e.data.obj; self.showTags=[]; var t=Math.floor((p*self.maxTags)); var mt=(t-self.maxTags); self.logInsertPoint.animate({opacity:0.25},200,function(){ self.logInsertPoint.empty(); self.logInsertPoint.append("<p>Loading...</p>"); for(i in self.manifest.tags){ if(self.manifest.tags[i]){ //see which ones belong to this set var item=self.manifest.tags[i]; var count=parseInt(item.n,10); if((count>mt)&&(count<t)){ self.showTags.push(count); self._addItem(item); self._createListItem(); } } } self.logInsertPoint.children("p").remove(); self.logInsertPoint.animate({opacity:1},200); }); }, _paginate:function(dir){ var self=this; //dir is either 1 or -1 var start=parseInt($("#pageSelect > option:selected").text(),10); if(!start) start=1; if(dir<0){ //go back if(start!=1) start--; // var start=self.showTags[0]; // start=start-self.maxTags; // if(start<0) return; // var end=self.showTags[0]; // } else if(dir>0){ //go forward if(start!=Math.ceil(self.tagCount/self.maxTags)) start++; // var start=self.showTags[(self.showTags.length-1)]; // if(start>self.tagCount) return; // var end=((start+self.maxTags)>self.tagCount)?self.tagCount:(start+self.maxTags); } self.pageSelectTool.children("option").each(function(n,o){ if(start==parseInt($(o).text(),10)){ $(o)[0].selected=true; $(o).trigger("paginateTo",[parseInt($(o).text(),10)]); } }); }, addTag:function(id){ var self=this; //id refers to a string representing the id in the tag rules // var T=null; //find matching uid in rules for(i in self.rules.tags){ if(self.rules.tags[i].uid==id){ T=self.rules.tags[i]; break; } } // var logtag=new TileLogTag({ // loc:self.logActiveArea.attr('id'), // copyloc:self.logInsertPoint.attr('id'), // tagRules:self.rules, // tagId:id, // html:self.html // }); var _d=new Date(); var uid="t"+_d.getTime("milliseconds"); //create empty object - created later in _addItem var l={ o:null, uid:uid, act:null, cur:null, html:self.html, type:'schema', tagId:id, n:self.tagCount }; // self.manifest.tags[l.uid]={o:logtag,act:logtag.DOM,cur:logtag._copy.DOM,type:'schema',n:self.tagCount}; self.emptytags[l.uid]=l; self.tagCount++; //add item or correct loglist space self.showTags.push(l.n); self._addItem(l); }, //for when a user is prompted to create a shape - shape is created and user //has to adjust its position addBlankShape:function(){ var self=this; var _d=new Date(); //create blank shape object to be passed var s={ con:"rect", uid:"s"+_d.getTime("milliseconds"), x:0, y:0, width:0.1, height:0.1, args:[0,0,0.1,0.1], uri:$("#srcImageForCanvas").attr("src") }; //send shape to drawer //$("body").trigger("VD_ADDSHAPE",[[s],{}]); }, addShape:function(shape,args){ var obj=this; var l=null; //must be a new shape if(!obj.manifest.tags[shape.id]){ l={ uid:shape.id,name:"shape_"+shape.id,html:obj.html.tagshape,cur:null,o:null,act:null,etc:(obj.etc||null),type:'shape',shape:shape,n:obj.tagCount }; //add to master manifest obj.emptytags[shape.id]=l; obj.tagCount++; if(l.etc&&l.etc.groups){ for(g in l.etc.groups){ var guid=l.etc.groups[g]; if(!self.manifest.tags[guid]){ self.emptytags[guid]={ cur:null, o:null, uid:guid, html:self.html.taggroup, type:'group', group:null, etc:[l.uid], n:self.tagCount }; self.tagCount++; } else { self.emptytags[guid].etc.push(l.uid); } } } } //add item or correct loglist space obj.showTags.push(l.n); obj._addItem(l); }, //can add an optional name parameter - Group is given this name addGroup:function(args){ if(args){ var groupname=(args.name||null); var guid=(args.uid||null); } var l=null; if(this.rules){ //close all other groups // for(g in this.manifest.groups){ // this.manifest.groups[g].o.setCloseState(); // } if(groupname) groupname+=$(".groupname > input:contains("+groupname+")").length; // l=new TileLogGroup({ // loc:this.logInsertPoint.attr("id"), // html:this.html.taggroup, // name:(groupname||null), // uid:(guid||null) // }); var _d=new Date(); l={ o:null, cur:null, html:this.html.taggroup, uid:(guid||"g"+_d.getTime("milliseconds")), type:'group', etc:[], n:this.tagCount }; this.tagCount++; //this.GroupId=l.uid; //make the JSON data associated with group this.emptytags[l.uid]=l; } //add item or correct loglist space this.showTags(l.n); this._addItem(l); }, addTranscript:function(item,args){ var self=this; if(this.rules){ var _d=new Date(); var uid="t"+_d.getTime("milliseconds"); var l={ o:null, act:null, cur:null, html:self.html.tagtranscript, type:'transcript', n:self.tagCount, etc:(args&&args.etc)?args.etc:{"text":"Blank"}, uid:uid }; //add to master manifest self.emptytags[l.uid]=l; self.tagCount++; if(l.etc&&l.etc.groups){ for(g in l.etc.groups){ var guid=l.etc.groups[g]; if(!self.manifest.tags[guid]){ self.emptytags[guid]={ cur:null, o:null, uid:guid, html:self.html.taggroup, type:'group', group:null, etc:[l.uid], n:self.tagCount }; self.tagCount++; } else { self.emptytags[guid].etc.push(l.uid); } } } self.showTags.push(l.n); self._addItem(l); } }, initTagRules:function(e,rules){ var obj=e.data.obj; //store rules - if already present, erase all log items and start over //TODO: finalize this action if(obj.rules){ obj.clearLogItems(); } obj.rules=rules; $("body").unbind("tagRulesSet",obj.initTagRules); }, restart:function(){ this.clearLogItems(); this.rules=null; }, _saveP:function(e){ e.preventDefault(); var self=e.data.obj; self._log.bundleData(); //if(!self._saveObj) self._saveObj=new Save({loc:"azglobalmenu"}); //get all the logbar items' data // var jsondata=self.bundleData(); // jsondata.images=URL_LIST; // for(g in jsondata.images){ // if(jsondata.images[g].transcript){ // for(_t in jsondata.images[g].transcript){ // jsondata.images[g].transcript[_t]=jsondata.images[g].transcript[_t].replace("'",""); // } // } // } // self.DOM.trigger("JSONreadyToSave",[jsondata]); //var saveDiv=$("<iframe id=\"__saveP\" src=\"PHP/forceJSON.php\" style=\"display:none;\"></iframe>").appendTo("body"); //output as attachment //self._saveObj.userPrompt(jsondata); }, //wrap all log items (shapes, groups, transcripts, tags) into a JSON object bundleData:function(){ var self=this; var j={"tags":[],"groups":[]}; for(f in self.manifest.tags){ if(self.manifest.tags[f]){ var obj=self.manifest.tags[f]; if(obj.o){ //get recent data from object obj.etc=obj.o.etc; if(obj.etc.text) obj.etc.text=obj.etc.text.replace("'","apos"); obj.name=obj.o.name.replace("'","apos"); } $.map(["region","html","o","cur","act"],function(o,i){ if(o in obj) obj[o]=null; }); //add to appropriate division if(obj.type=='group'){ j.groups.push(obj); } else { j.tags.push(obj); } } } return j; }, clearLogItems:function(){ var self=this; $.each(self.manifest,function(i,x){ $(x.cur).remove(); }); //$(".logitem").remove(); } }); TILE.TileLogBar=TileLogBar; /** Log Item Object that handles one instance of a logged event in the main workspace area Can be given an ID in order to 'copy' another object - can do this using uid: {string} parameter **/ var LogItem=Monomyth.Class.extend({ init:function(args){ if(!args.html) throw "no JSON data passed to LogItem{}"; this.loc=args.loc; this.html=args.html; if(this.loc) $(this.html).appendTo($("#"+this.loc)); var d=new Date(); this.uid=(args.uid)?args.uid:"logitem_"+d.getTime('milliseconds'); //optional tag type attribute if(args.type){ this._type=args.type; } } }); TILE.LogItem=LogItem; var TagCopy=LogItem.extend({ init:function(args){ this.$super(args); var self=this; self.uid=args.uid+"copy"; self.DOM=$("#"+self.loc+" > #empty"+args.type); self.DOM.attr("id",self.uid); self.name =(args.name||self.uid); //disable input elements or any clickable options $("#"+this.DOM.attr('id')+" > div.tagname > div.tagmenu > div:not(.menuitem)").remove(); $("#"+this.DOM.attr('id')+" > div.tagname > input").remove(); $("#"+this.DOM.attr('id')+" > div.tagname > p").text(self.name); switch(args.type){ case 'transcript': $("#"+self.uid+" > div.tagcontent > p").show(); $("#"+self.uid+" > div.tagcontent > form").remove(); break; case 'shape': self.shapeIcon=$("#"+this.DOM.attr('id')+" > div.tagname > div.tagmenu > div.menuitem > span.btnIconLarge.poly"); if(args.shape) { self.shapeIcon.removeClass("poly").addClass(args.shape.type); } break; case 'schema': $("#"+this.DOM.attr('id')+" > div.tagcontent > div.tagattr").remove(); //$("#"+this.DOM.attr('id')+" > div.tagcontent > div.tagattr > .nameValue > .button").hide(); break; } //universal items self.collapseIcon=$("#"+self.DOM.attr('id')+" > div.tagname > a.open.btnIcon").show(); self.contentArea=$("#"+self.DOM.attr('id')+" > div.tagcontent").show(); var tid=self.uid.replace("copy",""); //set up listener for when tag copy is selected $("#"+self.DOM.attr("id")+" > .tagname > *:not(> .tagmenu > .menuitem > .btnIconLarge.hand)").click(function(e){ //tell logbar to open this up in active window $(this).trigger("tagSelected",[tid]); $("#"+self.loc+" > div").removeClass("selected"); self.DOM.addClass("selected"); }); //set collapse icon listeners self.collapseIcon.click(function(e){ e.stopPropagation(); if(self.contentArea.css("display")=="block"){ self._collapse(); } else { self._uncollapse(); } }); }, _draggDrop:function(){ //all copy tags are in list and therefore draggable and droppable var self=this; self.DOM.draggable({ handle:$("#"+self.DOM.attr('id')+" > div.tagname > div.menuitem > span.btnIconLarge.hand"), axis:'y', revert:true }); }, _collapse:function(){ var self=this; //$("#"+self.DOM.attr('id')+" > div.tagcontent").hide(); self.collapseIcon.removeClass("open").addClass("closed"); self.contentArea.hide(); }, _uncollapse:function(){ var self=this; self.contentArea.show(); self.collapseIcon.removeClass("closed").addClass("open"); }, updateCopy:function(e){ var self=e.data.obj; self.name=$("#"+self.uid+" > div.tagname > p").text(); // for(o in updates){ // if($("#"+self.DOM.attr('id')+" > "+o).length){ // $("#"+self.DOM.attr('id')+" > "+o).html(updates[o]); // } // } // self.transContent=$("#"+self.DOM.attr('id')+" > div.tagcontent > p"); // //adjust and hide any editable elements // $("#"+self.DOM.attr('id')+" > div.tagcontent > div.tagattr > .nameValue > .button").hide(); //schema-defined tags // $("#"+self.DOM.attr('id')+" > div.tagcontent > div.tagattr > .nameValue > select").hide(); //schema-defined tags } }); var TileLogShape=LogItem.extend({ init:function(args){ this.$super(args); //using optional type attr this.type='shape'; //is this a clone? this.isClone=(args.isClone)||false; var self=this; self.groups=[]; self.copyloc=args.copyloc; self.etc=(args.etc)?args.etc:[]; self.shape=args.shape; self.shapeId=self.shape.id; if(args.uid) self.uid=args.uid; self.DOM=$("#emptyshape").attr("id",self.uid).addClass("selected"); // $("div.tag.shape").each(function(a){ // if(!$(this).attr("id")){ // self.DOM=$(this); // self.DOM.attr("id",self.uid); // // } // }); //active state - just added, so set class to "selected" // $("#"+self.loc+" > .tag").removeClass("selected"); // $("#"+self.loc+" > .tag").hide(); // self.DOM.addClass("selected").show(); //set up the collapse-icon behavior self.collapseIcon=$("#"+self.DOM.attr('id')+" > .tagname > a.btnIcon").hide(); self.shapeIcon=$("#"+self.DOM.attr('id')+" > div.tagname > div.tagmenu > div.menuitem > span.btnIconLarge.poly"); //configure the name for this log item self.name=(args.name)?args.name:"Shape_"+self.shapeId; self.shapeName=$("#"+self.DOM.attr('id')+" > div.tagname > p.shapename").attr("id",self.DOM.attr('id')+"_shapeName"); self.shapeName.text(self.name); self.shapeName.css("display","inline-block"); self.inputTitle=$("#"+self.DOM.attr('id')+" > div.tagname > input").attr("id",self.DOM.attr('id')+"_titleInput"); self.inputTitle.val(self.name); self.inputTitle.blur(function(e){ $(this).trigger("setSInput"); }); self.shapeSpan=$("#"+self.DOM.attr("id")+" > div.tagcontent > ul"); //fill in elements self.shapeName.hide(); self.handleShapeIcon(); self.setShapeObj(); self.clones=[]; //set up listeners $("#"+self.DOM.attr('id')+" > .tagname").click(function(e){ $(".tag.shape").removeClass("selected"); $(this).addClass("selected"); self.itemSelectedHandle(); }); self.shapeName.click(function(e){ $(this).parent().children("input").val($(this).text()); $(this).parent().children("input").show(); $(this).hide(); }); //local self.DOM.bind("setSInput",{obj:self},self.setName); //this._dragg(); //self.DOM.trigger("shapeDisplayChange",["a",self.shape.id]); $("body:first").trigger("_showShape",[self.shape.id]); }, /** Based on what the shape's type is, pick the right background style for the shape icon area **/ handleShapeIcon:function(){ switch(this.shape.type){ case 'rect': this.shapeIcon.removeClass('poly').addClass('rect'); break; case 'ellipse': this.shapeIcon.removeClass('poly').addClass("elli"); break; } }, _dragg:function(){ //make the entire DOM draggable - must be dropped into a Group if(!this.isClone){ this.DOM.draggable({ handle:'#'+this.DOM.attr('id')+' > menuitem > div.btnIconLarge.hand', revert:true, axis:'y' }); } }, //happens when user selects this shape itemSelectedHandle:function(){ var self=this; $("body").trigger("_showShape",[self.shape.id]); }, setEdit:function(){ if(this.editSelect){ var self=this; // self.editSelectB.click(function(e){ // $(this).hide(); // $(this).parent().children("select").click(); // }); // self.editSelect.blur(function(e){ // $(this).parent().children("span").show(); // }); //setup function to handle custom even itemMenuSelect call self.DOM.bind("itemMenuSelect",{obj:self},self.menuHandle); self.groupSelect.children().each(function(i,n){ $(this).click(function(e){ if(self.isClone&&(($(this).text().toLowerCase()=="edit")||($(this).text().toLowerCase()=="delete"))){ $(this).trigger("itemMenuSelect",[$(this).text()]); } else { $(this).trigger("itemMenuSelect",[$(this).text()]); } }); }); if(self.isClone){ self.inputTitle.hide(); self.shapeName.text(self.inputTitle.val()).show(); self.editSelect.css({"top":"0px"}); //change items if a clone self.editSelect.children().each(function(i,o){ if(($(o).text().toLowerCase()!="edit")||($(o).text().toLowerCase()!="delete")){ $(o).remove(); } }); } //when user inputs a name and clicks away, input goes away self.inputTitle.blur(function(e){ $(this).hide(); $(this).parent().children("p").text($(this).val()).show(); }).keypress(function(e){ if(e.keyCode==13){ $(this).hide(); $(this).parent().children("p").text($(this).val()).show(); } }); } }, //user clicked outside of input area setName:function(e){ var obj=e.data.obj; obj.shapeName.show().text(obj.inputTitle.val()); obj.inputTitle.hide(); // obj.DOM.trigger("tagUpdate",[{".tagname > p.shapename":obj.shapeName.html()}]); }, _tagUpdate:function(){ var obj=this; obj.shapeName.text(obj.inputTitle.val()); obj.name=obj.shapeName.text(); //update any and all copies of this $("#"+obj.uid+"copy > .tagname > p.shapename").text(obj.shapeName.text()); $("#"+obj.uid+"copy > .tagname > .tagmenu > .menuitem > span.btnIconLarge.poly").removeClass("poly").addClass(obj.shape.con); //show that we're not selected anymore $("#"+obj.loc+" > div").removeClass("selected"); }, menuHandle:function(e,m){ //m refers to which option the user chose var obj=e.data.obj; switch(m.toLowerCase().replace(" ","")){ case 'edit': obj.editShape(); break; case 'delete': obj.delItem(); break; case 'addtogroup': break; } }, editShape:function(){ var self=this; self.shapeName.hide(); self.inputTitle.val(self.shapeName.text()).show(); }, setShapeObj:function(){ var self=this; if(self.shapeSpan.children().length>0) self.shapeSpan.empty(); self.shapeSpan.append($("<li><span class=\"attrbname\">scale</span>: <span class=\"attrb\">"+self.shape.scale+"</span></li>")); // $.map(["scale","width","height","x","y","cx","cy","rx","ry","points"],function(v){ // if(v in self.shape){ // self.shapeSpan.append($("<li><span class=\"attrbname\">"+v+"</span>: <span class=\"attrb\">"+self.shape[v]+"</span></li>")); // } // }); for(i in self.shape.posInfo){ self.shapeSpan.append($("<li><span=\"attrbname\">"+i+":</span> <span class=\"\">"+self.shape.posInfo[i]+"</span></li>")); } }, //called whenever shapeChangeCall from shape is triggered //supposed to be during resize and dragging of shape shapeChangeHandle:function(e,_newShape){ var obj=e.data.obj; //make _newShape the current shape - overwrite old obj.shape=_newShape; var self=obj; //update information in shapeSpan self.shapeSpan.empty(); var liarray=[]; $.map(["scale","width","height","x","y","cx","cy","rx","ry"],function(v){ if(v in self.shape){ var d=$("<li><span class=\"attrbname\">"+v+"</span>: <span class=\"attrb\">"+self.shape[v]+"</span></li>"); liarray.push(d); self.shapeSpan.append(d); self.etc[v]=self.shape[v]; } }); //update all clones - if any for(o in self.clones){ //if user hasn't edited the clone's shape - then it still //should listen to changes in this shape if(self.clones[o].isClone){ var s=self.clones[o]; s.shapeSpan.empty(); for(li in liarray){ s.shapeSpan.append(liarray[li].clone()); } } } //update copies //self.DOM.trigger("tagUpdate",[{".tagcontent > ul":$("#"+self.DOM.attr('id')+" > .tagcontent > ul").html()}]); }, // Used to create a 'copy' of this object to be passed // to a group object clone:function(nloc){ var self=this; if($.inArray(nloc,self.groups)>-1){ return false; } self.groups.push(nloc); //make new id var n=$("div[id*="+this.DOM.attr('id')+"copy]").length; //how many other divs are copied? var id=this.DOM.attr('id')+"copy"+n; var self=this; //add shape object var clone=new TileLogShape({ uid:id, shape:self.shape, html:self.html, loc:nloc, isClone:true }); //$("body").unbind(self.shape.shapeChangeCall); //$("body").bind(self.shape.shapeChangeCall,{obj:self},self.shapeChangeHandle); //add to clone array self.clones.push(clone); return clone; }, delItem:function(){ //notify drawer that this shape is deleted from logbar $(this.shape.cur.node).trigger("VD_REMOVESHAPE",[this.shape.id]); this.DOM.remove(); }, _open:function(){ var self=this; $("#"+self.loc+" > .tag").hide().removeClass("selected"); self.DOM.show().addClass("selected"); $("body").trigger("shapeDisplayChange",["a",self.shapeId]); }, _close:function(){ var self=this; } }); var TileLogGroup=LogItem.extend({ init:function(args){ this.$super(args); var self=this; //adjust name/uid if provided by user self.type='group'; self.uid=(args.uid)?args.uid:self.uid; self.DOM=$("#emptygroup").attr("id",self.uid); //adjust height of parent // $("#"+self.loc).height($("#"+self.loc).height()+self.DOM.height()); // $("div.group").each(function(d){ // if($(this).attr("id")==""){ // self.DOM=$(this); // //self.DOM.removeClass("logitem").addClass("loggroup"); // $(this).attr("id","g"+d); // } // }); // if(args.uid) { // self.uid=args.uid; // self.DOM.attr("id",self.uid); // } self.name=(args.name||"Group"+self.uid); //toggle for display name self.nameToggle=$("#"+self.DOM.attr("id")+" > div.groupname > a").click(function(e){ $(this).trigger("setClose"); }); //display for group name self.groupNameSpan=$("#"+self.DOM.attr("id")+" > div.groupname > span").text(self.name).hide();// .click(function(e){ // $(this).hide(); // $(this).parent().children("input").show(); // }); // this.groupNameSpan.hide(); //input for making group name self.groupNameInput=$("#"+self.DOM.attr("id")+" > div.groupname > input").blur(function(e){ // $(this).hide(); // $(this).parent().children("span").text($(this).val()).show(); }).keydown(function(e){ //also handle when user presses 'enter' if(e.keyCode==13) { $(this).hide(); $(this).parent().children("span").text($(this).val()).show(); } }); $("#"+self.DOM.attr("id")+" > .groupname > a").remove(); // self.collapseIcon=$("#"+self.DOM.attr("id")+" > .groupname > a").click(function(e){ // if($(this).closest("div.group").children(".grouplist:visible").length){ // $(this).closest("div.group").children(".grouplist:visible").hide(); // } else { // $(this).closest("div.group").children(".grouplist:hidden").show(); // // } // }); self.groupNameInput.val(self.groupNameSpan.text()); self.dropInsertArea=$("#"+self.DOM.attr('id')+" > div.grouplist").attr('id',(self.uid+"gdrop")); self._dropp(); //for storing data to be passed on in JSON format self.etc=(args.etc)?args.etc:{"tags":[]}; if(self.etc){ for(o in self.etc){ self._loadItem(self.etc[o]); self.etc[o]=self.etc[o].uid; } } //local listeners //bind for toggle display edit //this.DOM.bind("toggleNameEdit",{obj:this},this.toggleNameEditHandle); self.DOM.bind("setClose",{obj:self},self.setClosedState); self.DOM.bind("setOpen",{obj:self},self.setOpenState); self.DOM.bind("removeItem",{obj:self},self.removeItem); }, _dropp:function(){ var self=this; //not draggable - in logbar active area by itself $("#"+self.DOM.attr("id")+" > .groupname > .menuitem > .btnIconLarge.hand").remove(); // self.DOM.draggable({ // axis:'y', // handle:$("#"+self.DOM.attr("id")+" > .groupname > .menuitem > .btnIconLarge.hand"), // revert:true // }); self.DOM.droppable({ addClasses:false, drop:function(e,o){ e.preventDefault(); $(this).droppable("disable"); $(this).trigger("itemDropped",[$(o.draggable).attr('id'),self.uid]); } //this.addItem }); //change initial height so area is more droppable //figure out height difference $("#"+self.DOM.attr("id")+" > div.groupname").css({"overflow":"none"}); self.DOM.css("overflow","none").height(120); self.dropInsertArea.height(self.DOM.height()-$("#"+self.DOM.attr("id")+" > div.groupname").height()); //this.DOM.height(120).css("overflow","auto"); }, //handles event when user clicks on nameToggle toggleNameEditHandle:function(e){ var obj=e.data.obj; obj.groupNameSpan.hide(); obj.groupNameInput.val(obj.groupNameSpan.text()).show(); }, setOpenState:function(e){ var obj=e.data.obj; obj.DOM.height(120).css("overflow","auto"); obj.groupNameInput.val(obj.groupNameSpan.text()).show(); obj.groupNameSpan.hide(); obj.nameToggle.removeClass("closed").addClass("open"); //switch out the click command for nameToggle obj.nameToggle.unbind("click"); obj.nameToggle.click(function(e){ $(this).trigger("setClose"); }); //inform logbar which group is open obj.DOM.trigger("logGroupOpen",[obj.uid]); //change initial height so area is more droppable //figure out height difference $("#"+obj.DOM.attr("id")+" > div.groupname").css({"overflow":"none"}); var th=0; $("#"+obj.DOM.attr("id")+" > div.tag").each(function(i,o){ th+=$(o).height(); }); obj.DOM.css("overflow","none").height(((th==0)?120:th)); obj.dropInsertArea.height(obj.DOM.height()-$("#"+obj.DOM.attr("id")+" > div.groupname").height()); }, setCloseState:function(){ //does the same thing as setClosedState but isn't called by CustomEvent this.nameToggle.removeClass("open").addClass("closed"); this.groupNameSpan.show(); this.groupNameSpan.text(this.groupNameInput.val()); this.groupNameInput.hide(); this.DOM.height($("#"+this.DOM.attr('id')+" > div.groupname").height()); this.nameToggle.unbind('click'); //switching out the trigger for nameToggle this.nameToggle.click(function(e){ $(this).trigger("setOpen"); }); }, setClosedState:function(e){ var obj=e.data.obj; obj.nameToggle.removeClass("open").addClass("closed"); obj.groupNameSpan.show(); obj.groupNameSpan.text(obj.groupNameInput.val()); obj.groupNameInput.hide(); obj.DOM.height($("#"+obj.DOM.attr('id')+" > div.groupname").height()); obj.nameToggle.click(function(e){ $(this).trigger("setOpenState"); }); //change out the click event for nameToggle obj.nameToggle.unbind("click"); obj.nameToggle.click(function(e){ $(this).trigger("setOpen"); }); //event called by user and not logbar - notify logbar obj.DOM.trigger("logGroupClosed",[obj.uid]); }, //called by parent Object - //@item {Object} - whatever tag Object is given to attach to DOM pushItem:function(item){ //push html onto the DOM - if not already present // if($("#"+this.DOM.attr('id')+" > #"+(item.DOM.attr('id')+"copy")).length){ // return; // } else { var self=this; if(!item){ return; } if(self.etc[item.uid]) { return; } if(item.type=='group'){ // var copy=new GroupCopy({ // loc:self.dropInsertArea.attr("id"), // name:item.name, // html:"<div id=\"emptygroup\" class=\"group\">"+item.DOM.html()+"</div>", // uid:item.uid // }); if($.inArray(item.uid,self.etc)<0) self.etc.push(item); } else { // var copy=new TagCopy({ // loc:self.dropInsertArea.attr("id"), // name:item.name, // html:item.html, // type:item.type, // uid:item.uid // }); if($.inArray(item.uid,self.etc)<0) self.etc.push(item); } }, //display all items in etc _showList:function(){ var self=this; for(i in self.etc){ var item=self.etc[i]; if(!item) continue; if(item.type&&($("#"+self.dropInsertArea.attr("id")+" > #"+item.uid+"copy").length==0)) { if(item.type=='group'){ var copy=new GroupCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:"<div id=\"emptygroup\" class=\"group\">"+item.DOM.html()+"</div>", uid:item.uid }); self.etc[i]=item.uid; } else { var copy=new TagCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:item.html, type:item.type, uid:item.uid }); self.etc[i]=item.uid; } } } }, _loadItem:function(item){ var self=this; if(!item){ return; } if(item.type=='group'){ var copy=new GroupCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:item.html, uid:item.uid }); } else { var copy=new TagCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:item.html, type:item.type, uid:item.uid }); } }, removeItem:function(e,id){ var obj=e.data.obj; //remove an item from the group - doesn't effect original //TODO: make prompts to user obj.etc=$.grep(obj.etc,function(o,n){ return (o!=id); }); $("#"+id).remove(); }, _tagUpdate:function(){ var self=this; self.name=self.groupNameInput.val(); if(self.name=="") self.name=self.uid; self.groupNameSpan.text(self.name); //update all copies of this $("#"+self.uid+"copy > .groupname > span").text(self.name); $("#"+self.uid+"copy > .groupname > span").trigger("tagUpdate"); //$("body").trigger("tagUpdate",[{".groupname > span":self.groupNameSpan.html()}]); //show that we're not selected anymore $("#"+self.loc+" > div").removeClass("selected"); } }); var GroupCopy=Monomyth.Class.extend({ init:function(args){ var self=this; self.loc=args.loc; self.html=args.html; self.uid=args.uid+"copy"; $("#"+self.loc).append($(self.html)); self.DOM=$("#"+self.loc+" > #emptygroup").attr("id",self.uid); $("#"+self.uid+" > .grouplist").remove(); //remove input from name $("#"+self.uid+" > .groupname > input").remove(); $("#"+self.uid+" > .groupname > span").text(args.name); self.DOM.click(function(e){ $(this).trigger("tagSelected",[self.uid.replace("copy","")]); }); self._dropp(); }, _dropp:function(){ var self=this; //also draggable self.DOM.draggable({ axis:'y', handle:$("#"+self.DOM.attr("id")+" > .groupname > .menuitem > .btnIconLarge.hand"), revert:true }); self.DOM.droppable({ addClasses:false, drop:function(e,o){ e.preventDefault(); $(this).trigger("itemDropped",[$(o.draggable).attr('id'),self.uid.replace("copy","")]); } //this.addItem }); }, _tagUpdateHandle:function(e,args){ var self=e.data.obj; self.name=$("#"+self.uid+" > .groupname > span").text(); }, _loadItem:function(item){ var self=this; if(!item){ return; } if(item.type=='group'){ var copy=new GroupCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:item.html, uid:item.uid }); } else { var copy=new TagCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:jsonTags[item.type], type:item.type, uid:item.uid }); } } }); /** TranscriptTag **/ var TileTranscriptTag=LogItem.extend({ init:function(args){ this.$super(args); var self=this; self.copyloc=args.copyloc; self.type='transcript'; self.groups=[]; if(args.uid) self.uid=args.uid; self.isClone=(args.isClone)||false; self.DOM=$("#emptytranscript").attr("id",self.uid); // $("div.tag.transcript").each(function(e){ // if($(this).attr("id")==""){ // self.DOM=$(this).attr("id","t"+self.uid); // } // }); self.DOM.addClass("selected").show(); //get elements - hide elements that don't exist in main logbar activearea $("#"+self.DOM.attr('id')+" > div.tagname > a.btnIcon").hide(); this.name=(args.name)?args.name:"Transcript"+$("#"+self.loc+" > .tag.transcript").length; this.transName=$("#"+this.DOM.attr('id')+" > div.tagname > p.transname").text(this.name).css("display","inline-block").hide(); this.transNameInput=$("#"+this.DOM.attr('id')+" > div.tagname > input").val(this.transName.text()).show(); this.transDisplay=$("#"+this.DOM.attr('id')+" > div.tagcontent > p.transcript").hide(); this.menuSelectB=$("#"+this.DOM.attr('id')+" > div.tagname > div.tagmenu > #ddown > div.menuitem.ddown > span").show(); this.menuSelect=$("#"+this.DOM.attr('id')+" > div.tagname > div.tagmenu > #ddown > div.menuitem.ddown > select").attr("id","ddown_"+this.uid); this.txtArea=$("#"+this.DOM.attr('id')+" > div.tagcontent > form > textarea"); this.etc=(args.etc)?args.etc:{"text":this.txtArea.val()}; this.txtArea.val(this.etc.text); this.transDisplay.text(this.etc.text); //this.setEdit(); ///local listeners this.DOM.bind("deleteTranscript",{obj:this},this.eraseTranscript); this.DOM.bind("doneTranscript",{obj:this},this.doneTranscriptHandle); this.DOM.click(function(e){ $(this).removeClass("inactive").addClass("active"); }); }, _dragg:function(){ this.DOM.draggable({ handle:'#'+this.DOM.attr('id')+' > div.menuitem > div.btnIconLarge.hand', axis:'y', revert:true }); }, setEdit:function(){ if(this.menuSelect){ var self=this; //define layout variables for drop down // self.heights=[self.menuSelect.height()+8]; // self.startingHeight=21; // self.speed=300; // //make visible // // self.menuSelect.css({visibility:"visible","z-index":"1000"}).height(self.startingHeight); // // //setting up the stylized drop down menu // self.menuSelect.mouseover(function () { // $(this).stop().animate({height:self.heights[0]},{queue:false, duration:self.speed}); // }); // self.menuSelect.mouseout(function () { // $(this).stop().animate({height:self.startingHeight+'px'}, {queue:false, duration:self.speed}); // }); //setup click function to show menuSelect self.menuSelectB.click(function(e){ $(this).hide(); self.menuSelect.click(); }); //setup function to handle custom even itemMenuSelect call this.DOM.bind("itemMenuSelect",{obj:this},this.menuHandle); this.menuSelect.children().each(function(i,n){ $(this).click(function(e){ if(i==0) $(this).select(); $(this).trigger("itemMenuSelect",[$(this).text()]); }); }); //change items if a clone if(self.isClone){ self.menuSelect.children().each(function(i,o){ if(($(o).text().toLowerCase()!="edit")||($(o).text().toLowerCase()!="delete")){ $(o).remove(); } }); } } }, menuHandle:function(e,m){ //m refers to which option the user chose var obj=e.data.obj; switch(m.toLowerCase().replace(" ","")){ case 'edit': obj.editTranscript(); break; case 'delete': obj.delItem(); break; case 'addtogroup': break; } }, editTranscript:function(){ //open up text area to edit - limit chars //hide the text display area this.transDisplay.hide(); this.txtArea.parent().show(); this.txtArea.val(this.transDisplay.text()); this.transName.hide(); this.transNameInput.val(this.transName.text()).show(); }, eraseTranscript:function(e){ //user clicked on the Delete button from the transcript area var obj=e.data.obj; obj.txtArea.val(""); }, //when user clicks 'Done', logbar carries out its functions, //transcript finishes its own _tagUpdate:function(){ var obj=this; //user clicked on the 'done' button //hide the transcript editing area and display text from txtarea obj.transDisplay.text(obj.txtArea.val()); obj.transName.text(obj.transNameInput.val()); obj.name=obj.transName.text(); if(obj.name=="") obj.name=obj.uid; obj.etc.text=obj.txtArea.val(); //now change all of the copies of this transcript that may //exist inside groups $("#"+obj.DOM.attr("id")+"copy > .tagname > p").html($("#"+obj.DOM.attr('id')+" > .tagname > p").html()); $("#"+obj.DOM.attr("id")+"copy > .tagcontent > p").html($("#"+obj.DOM.attr('id')+" > .tagcontent > p").html()); $("#"+obj.DOM.attr("id")+"copy > .tagcontent").trigger("tagUpdate"); //$("body").trigger("tagUpdate",[{".tagcontent":$("#"+obj.DOM.attr('id')+" > .tagcontent").html()}]); //show that we're not selected anymore $("#"+obj.loc+" > div").removeClass("selected"); }, clone:function(nloc){ var self=this; if($.inArray(nloc,self.groups)>-1){ return; } self.groups.push(nloc); //make new id var n=$("div[id*="+this.DOM.attr('id')+"copy]").length; //how many other divs are copied? var id=this.DOM.attr('id')+"copy"+n; //add shape object var self=this; var clone=new TileTranscriptTag({ uid:id, html:self.html, loc:nloc, isClone:true }); return clone; }, delItem:function(){ this.DOM.remove(); }, _open:function(){ var self=this; $("#"+self.loc+" > .tag").hide().removeClass("selected"); self.DOM.addClass("selected").show(); } }); /** TileLogTag same functionality as the TileTag, but uses JSON html and loads same functionality as other LogItems parentClass: LogItem (base.js) **/ var TileLogTag=LogItem.extend({ init:function(args){ var self=this; //hack the args.html self.nvhtml=args.html.nvitem; args.html=args.html.tilelogtag; self.type='schema'; this.$super(args); self.copyloc=args.copyloc; self.isClone=(args.isClone)||false; self.tagRules=args.tagRules; self.tagId=args.tagId; //has same HTML as the TranscripTag, only without form // self.shapeId=(args.shapeId)?args.shapeId:null; self.json=(args.json)?args.json:null; self.values=(args.values)?args.values:null; if(args.uid) self.uid=args.uid; self.DOM=$("#emptyschema").attr('id',"t"+self.uid).addClass("selected"); //remove all other tags from this area $("#"+self.loc+" > div.tag:not(#"+self.DOM.attr('id')+")").hide(); //tagname self.name=self.tagId+"_"+$(".tag").length; self.nameInput=$("#"+self.DOM.attr('id')+" > div.tagname > input").val(self.name); self.nameP=$("#"+self.DOM.attr('id')+" > div.tagname > p.tagnamep").text(self.name).hide(); //collapse icon self.collapseIcon=$("#"+self.DOM.attr('id')+" > div.tagname > a").hide(); //nameInput changes when blurred or user presses enter self.nameInput.val(self.nameP.text()).blur(function(e){ $(this).hide(); $(this).parent().children("p").text($(this).val()).show(); }).keypress(function(e){ if(e.keyCode==13){ $(this).hide(); $(this).parent().children("p").text($(this).val()).show(); } }); //tagmenu self.tagMenu=$("#"+self.DOM.attr("id")+" > div.tagmenu").attr('id',self.uid+'_tagmenu'); self.setTagMenu(); //tagcontent self.tagContent=$("#"+self.DOM.attr("id")+" > div.tagcontent"); self.tagAttrInsertArea=$("#"+self.DOM.attr("id")+" > div.tagcontent > div.tagattr").attr('id',self.uid+"_tagattr"); //load in previous tags or start a new tag system self.etc={"tags":[]}; self.items=[]; self._display=true; self._edit=true; // self.titleEl=$("#tagtitle_").attr("id","tagtitle_"+self.uid); // self.titleEl.bind("click",{obj:this},function(e){ // var obj=e.data.obj; // $(this).trigger("toggleTagState",[obj.htmlindex,obj]); // }); // // self.titleElText=$("#tagtitle_"+self.htmlindex+" > span"); // self.titleElText.hide(); // self.titleElText.click(function(e){ // $(this).trigger("titleSet"); // }); // // self.titleInputArea=$("#tagTitleInput_").attr("id","tagTitleInput_"+self.uid); // self.titleInputArea.val(self.title); // self.titleInputArea.blur(function(e){ // e.preventDefault(); // $(this).trigger("titleSet"); // }); // // // self.tagDel=$("#tagdel_").attr("id","tagdel_"+self.uid); // self.tagDel.bind("click",{obj:this},self.deleteTag); // self.attrBody=$("#tagAtr_").attr("id","tagAtr_"+self.uid); // // self.editB=$("#tagedit_").attr("id","tagedit_"+self.uid); // // self.editB.bind("click",{obj:this},self.doneEdit); self._getNVRules(); self.setTitleChoices(); // self.DOM.bind("toggleTagState",{obj:this},self.toggleTagState); self.DOM.bind("titleOptionClicked",{obj:this},self.titleOptionClickHandle); self.DOM.bind("titleSet",{obj:this},self.setTitle); self.DOM.bind("nvItemChanged",{obj:self},self._updateLogBar); //constructed, notify other objects this is the active element self.DOM.trigger("tagOpen",[self.htmlindex,this]); self.DOM.trigger("activateShapeBar"); self.DOM.trigger("deactivateShapeDelete"); //global listeners //$("body").bind("shapeCommit",{obj:this},self.ingestCoordData); if(args.etc){ //preloaded tags self._loadTagAttrs(args.etc); } }, setTagMenu:function(){ var self=this; self.menuDDown=$("#"+self.tagMenu.attr('id')+" > #ddown > div.menuitem > ul").attr('id',self.uid+"_ddown"); if(self.menuDDown){ // //animation variables set here // self.startingHeight=21; // self.speed=300; // self.endHeight=self.menuDDown.height(); // self.menuDDown.css({"visibility":"visible","z-index":"1000"}).height(self.startingHeight); // // //setting up the stylized drop down menu // self.menuDDown.mouseover(function () { // $(this).stop().animate({height:self.endHeight},{queue:false, duration:self.speed}); // }); // self.menuDDown.mouseout(function () { // $(this).stop().animate({height:self.startingHeight+'px'}, {queue:false, duration:self.speed}); // }); //Make draggable self._draggable(); } else { throw "Error"; } }, _draggable:function(){ var self=this; //snaps back into place when user moves it self.DOM.draggable({ axis:'y', revert:true, handle:$("#"+self.tagMenu.attr('id')+" > div.menuitem > span.btnIconLarge.hand ") }); }, //figure out what to pass on to NV item _getNVRules:function(){ var self=this; if(self.tagRules&&self.tagId){ for(r in self.tagRules.tags){ //see if uid matches tagId if(self.tagRules.tags[r].uid==self.tagId){ self.NVRules=self.tagRules.tags[r]; break; } } } //set new name self.name=self.NVRules.name; self.nameInput.val(self.name+"_"+self.uid); self.nameP.text(self.name+"_"+self.uid); //self.DOM.trigger("tagUpdate",{".tagname":$("#"+self.DOM.attr('id')+" > div.tagname").html()}); }, _tagUpdate:function(){ var self=this; self.name=self.nameInput.val(); if(self.name=="") self.name=self.uid; self.nameP.text(self.name); $("#"+self.uid+"copy > .tagname > p").text(self.name); $("#"+self.uid+"copy > .tagname").trigger("tagUpdate"); //show that we're not selected anymore $("#"+self.uid+"copy").removeClass("selected"); }, //SET BY JSON {Object} setTitleChoices:function(){ var self=this; //set by tagRules (see init constructor) //set up selection for first-level tags //use the NameValue object to do toplevel tags - handles other values self.NV=new NVItem({ loc:self.tagAttrInsertArea.attr('id'), tagRules:self.tagRules, tagUID:self.tagId, json:self.json, tagData:self.NVRules, html:self.nvhtml }); }, _open:function(){ var self=this; $("#"+self.loc+" > .tag").hide().removeClass("selected"); self.DOM.show().addClass("selected"); $("body").trigger("shapeDisplayChange",["a",self.shapeId]); }, //NEW: load shape based solely on its ID //NOT passed a shape object, just uses this.shapeId loadJSONShape:function(){ if(this.mainRegion) this.mainRegion.destroy(); //create shape object from stored JSON data //match up data first var shape=null; for(o in this.json){ if(this.json[o].shapes){ for(sh in this.json[o].shapes){ if(this.json[o].shapes[sh].uid==this.shapeId){ shape=this.json[o].shapes[sh].points; break; } } } } if(!shape) shape=this.shapeId; this.mainRegion=new TagRegion({ loc:this.attrBody, name:"mainRegion"+this.htmlindex, shapeId:this.shapeId, shape:shape }); }, titleOptionClickHandle:function(e,id){ var obj=e.data.obj; if(id!=null){ //user has defined what title they want // obj.title=obj.items[id].title; obj._rules=obj.items[id].rules; obj.setTagAttr(); } }, //can be triggered by setTitle or called externally setTitle:function(e){ if(e){ var obj=e.data.obj; //check if titleInput is hidden or not - if class set to locked, hidden if(obj.titleInputArea.hasClass("locked")){ obj.titleElText.hide(); //open input area and set value to stored title obj.titleInputArea.removeClass("locked").addClass("edit"); obj.titleInputArea.val(obj.title); } else { obj.title=obj.titleInputArea.val().replace(/\n+\s+\t/g,"%"); obj.titleInputArea.removeClass("edit").addClass("locked"); // this.tagChoice.hide(); obj.titleElText.text(obj.title); obj.titleElText.show(); } } else { this.title=this.titleInputArea.val().replace(/\n+\s+\t/g,"%"); this.titleInputArea.removeClass("edit").addClass("locked"); // this.tagChoice.hide(); this.titleElText.text(this.title); this.titleElText.show(); } }, setTagAttr:function(){ var self=this; if(this.attrs.length>0){ $.each(this.attrs,function(i,a){ a.destroy(); }); } if(this._rules){ //this.attrs=[]; var a=new NameValue({ loc:this.attrBody, id:this.uid, rules:this._rules }); self.etc.tags.push(a.uid); //this.attrs.push(a); } }, _loadTagAttrs:function(items){ var self=this; for(it in items.tags){ var T=items.tags[it]; } }, openTagState:function(){ if(this.titleEl.hasClass("closed")){ this.titleEl.removeClass('closed').addClass('open'); //being turned back on (opening the box) this.titleInputArea.removeClass("locked").addClass("edit").val(this.titleElText.text()); this.editB.show(); this.attrBody.show(); this.titleElText.hide(); if(this.mainRegion&&this._display){ this.mainRegion.listenOn(); //obj.DOM.trigger("deactivateShapeBar"); this.DOM.trigger("activateShapeDelete"); } else if(this._display){ if(this._edit) { this.DOM.trigger("activateShapeBar"); } else { this.DOM.trigger("turnOffShapeBar"); } //obj.DOM.trigger("activateShapeBar"); //$("body").bind("shapeCommit",{obj:this},this.ingestCoordData); } else { this.DOM.trigger("turnOffShapeBar"); } } }, //closes the tag state when another tag is opened //called externally closeTagState:function(){ if(this.titleEl.hasClass("open")){ this.titleEl.removeClass("open").addClass('closed'); //if(!this.titleEl.hasClass("closed")) this.titleEl.addClass("closed"); this.editB.hide(); this.attrBody.hide(); this.setTitle(); $("body").unbind("deleteCurrentShape",this.deleteShape); // if(this.mainRegion){ // this.mainRegion.listenOff(); // } else { // //$("body").unbind("shapeCommit",this.ingestCoordData); // } this.DOM.trigger("turnOffShapeBar"); } }, toggleState:function(){ if(this.titleEl.hasClass("open")){ this.closeTagState(); } else if(this.titleEl.hasClass("closed")) { this.openTagState(); } }, newPage:function(){ //hide the DOM until the next page is loaded this.closeTagState(); this.DOM.hide(); }, //show nothing until reset - opposite is displayOn() function displayOff:function(){ this._display=false; if(this.titleEl.hasClass("open")){ this.trigger("toggleTagState",[this.DOM.attr('id'),this]); } }, //opposite is displayOff() function displayOn:function(){ this._display=true; if(!this.titleEl.hasClass("open")){ this.DOM.trigger("toggleTagState",[this.DOM.attr('id'),this]); } }, //for showing up all the shapes at once - tag doesn't open showcase:function(){ //if display is off, then it is now on this._display=true; if(this.mainRegion){ this.mainRegion.showcase(); } }, deleteTag:function(e){ if(e){ var obj=e.data.obj; if(obj.mainRegion) { obj.mainRegion.destroy(); obj.mainRegion=null; } obj.DOM.trigger("tagDeleted",[obj.htmlindex,obj]); obj.DOM.remove(); } else { this.mainRegion.destroy(); this.mainRegion=null; this.DOM.trigger("tagDeleted",[this.htmlindex,this]); this.DOM.remove(); } }, //fired when user clicks lock in 'lock' mode editTag:function(e){ var obj=e.data.obj; //display lock in 'unlock' mode obj.editB.removeClass("lock"); obj.editB.addClass("unlock"); obj.editB.unbind("click"); obj._edit=true; //display NameValue data as editable if(obj.NV) obj.NV._startEdit(); //recursive function if(obj.mainRegion){ obj.mainRegion.anchorOff(); obj.DOM.trigger("activateShapeDelete"); } else { obj.DOM.trigger("activateShapeBar",[obj.index]); obj.DOM.trigger("deactivateShapeDelete"); } obj.editB.bind("click",{obj:obj},obj.doneEdit); }, //fired when the user first clicks on the 'lock' //afterward, fired after editB is clicked in 'unlock' mode doneEdit:function(e){ //shape and all other data are now locked var obj=e.data.obj; //display 'lock' mode obj.editB.removeClass("unlock"); obj.editB.addClass("lock"); obj.editB.unbind("click"); obj.editB.bind("click",{obj:obj},obj.editTag); if(obj.NV) obj.NV._noEdit(); obj.DOM.trigger("turnOffShapeBar"); obj._edit=false; $.each(obj.attrs,function(i,a){ a.save(); }); if(obj.mainRegion){ obj.mainRegion.anchorOn(); } }, reloadListeners:function(){ // this.titleEl.bind("click",{obj:this},function(e){ // var obj=e.data.obj; // $(this).trigger("toggleTagState",[obj.index,obj]); // }); //this.DOM.bind("toggleTagState",{obj:this},this.toggleTagState); this.DOM.bind("titleOptionClicked",{obj:this},this.titleOptionClickHandle); }, //NEW: VectorDrawer Object sends out the coord data //wrapped in json-like object //Old: @shape,@coords //NEW: @shape: Associative array of shape attributes ingestCoordData:function(e,shape){ var obj=e.data.obj; if(!obj.mainRegion){ obj.shapeId=shape.id; obj.mainRegion=new TagRegion({ loc:obj.attrBody, shape:shape, name:"mainRegion"+obj.htmlindex, shapeId:obj.shapeId }); $("body").unbind("shapeCommit",obj.ingestCoordData); obj.DOM.trigger("activateShapeDelete"); } }, //OLD: called by trigger deleteCurrentShape //NEW: TabBar handles all deletes deleteShape:function(e){ if(this.mainRegion){ this.mainRegion.destroy(); this.shapeId=null; this.mainRegion=null; //$("body").unbind("deleteCurrentShape",this.deleteShape); $("body").bind("shapeCommit",{obj:this},this.ingestCoordData); this.DOM.trigger("deactivateShapeDelete"); } }, removeTag:function(){ this.closeTagState(); this.DOM.remove(); }, bundleData:function(){ //return part of JSON object //only returning values from (each) nameValue pair //var jsontag={"uid":this.htmlindex,"name":this.title,"shapeId:":(this.mainRegion)?this.mainRegion.shapeId:null}; var jsontag=[]; //TabBar already gathers other information on tag - just need to recursively return //namevalue data if(this.NV){ jsontag.push(this.NV.bundleData()); //bundleData for NameValue Obj called } // var jsontag="{"; // jsontag+="uid:"+this.htmlindex+",name:"+this.name+",shapeId:"+this.mainRegion.id+"}"; //j[1]=(this.mainRegion)?this.mainRegion.bundleData():null; return jsontag; } }); /** Name-value object to be used specifically with TILE interface Top-Level Object that generates more, sub-level name-value pairs from Rules .childNodes array **/ var TileNameValue=NameValue.extend({ init:function(args){ this.$super(args); this.parentTagId=args.parentTagId; var d=new Date(); this.uid=d.getTime(); this.htmlId=d.getTime()+"_nv"; //this.rules has to be JSON SCHEMA structure as defined by TILE specs this.DOM=$("<div></div>").attr("id",this.htmlId).addClass("nameValue").appendTo(this.loc); this.select=$("<select></select>").appendTo(this.DOM); this.changeB=$("<a>Change</a>").appendTo(this.DOM).click(function(e){$(this).trigger("NV_StartOver");}).hide(); this.topTag=null; this.items=[]; //set up enum list of tag names //rules.tags: list of top-level tags this.setUpTopLevel(); if(args.values){ this.loadPreChoice(args.values); } }, setUpTopLevel:function(){ for(t in this.rules.topLevelTags){ var uid=this.rules.topLevelTags[t]; var T=null; for(g in this.rules.tags){ if(this.rules.tags[g].uid==uid){ T=this.rules.tags[g]; break; } } if(T){ var id=$("#"+this.DOM.attr("id")+" > option").length+"_"+this.DOM.attr("id"); var o=$("<option></option>").attr("id",id).val(uid).text(T.name).appendTo(this.select); o.click(function(){ $(this).trigger("nameSelect",[$(this).val()]); }); } } this.select.bind("nameSelect",{obj:this},this.nameSelectHandle); this.loc.bind("NV_StartOver",{obj:this},this.startOverHandle); //this.loc.bind("nvItemClick",{obj:this},this.handleItemClick); }, //values from JSON tag object have been added in constructor //use args[0].values to reload the topTag loadPreChoice:function(args){ var T=null; // /alert(args[0].uid+' '+args[0].values); for(x in args[0].values){ var nv=args[0].values[x]; for(g in this.rules.tags){ if(nv.tagUid==this.rules.tags[g].uid){ T=this.rules.tags[g]; break; } } if(T){ this.select.hide(); this.changeB.show(); this.topTag=new NVItem({ loc:this.DOM, tagData:T, tagRules:this.rules, preLoad:nv, level:0 }); } } }, startOverHandle:function(e){ var obj=e.data.obj; //get rid of current top-level area completely if(obj.topTag){ obj.topTag.destroy(); obj.topTag=null; //hide change button and open up select element obj.changeB.hide(); obj.select.show(); } }, _noEdit:function(){ //tell topTag to hide editable items if(this.topTag) this.topTag._noEdit(); this.changeB.hide(); }, _startEdit:function(){ //user can now edit choices this.changeB.show(); //cascade command down if(this.topTag) this.topTag._startEdit(); }, //picks up nameSelect trigger from option element nameSelectHandle:function(e,uid){ var obj=e.data.obj; //Top-Level tag is selected, erase all items that are in items array //so as to get rid of any possible previous selections for(item in obj.items){ obj.items[item].destroy(); } obj.items=[]; //hide the select element and open up change element obj.select.hide(); obj.changeB.show(); //find the tag that is the chosen top-level tag var T=null; for(g in obj.rules.tags){ if(obj.rules.tags[g].uid==uid){ T=obj.rules.tags[g]; //set up the Top-Level NVItem - handles all the other NVItems var ni=new NVItem({ loc:obj.DOM, tagData:T, tagRules:obj.rules, level:0 }); obj.topTag=ni; break; } } }, evalRef:function(e){ //analyze to see if val() refers to a URI or to another Tag's uid var obj=e.data.obj; if(obj.valueEl){ var c=obj.valueEl.text(); var ut=/http:|.html|.htm|.php|.shtml/; if(ut.test(c)){ } } }, bundleData:function(){ var bdJSON={'uid':this.uid,'values':[]}; if(this.topTag){ //bdJSON.type=this.topTag.valueType; bdJSON.values.push(this.topTag.bundleData()); // for(i in this.items){ // var it=this.items[i].bundleData; // bdJSON.values.push(it); // } }else{ bdJSON.value='null'; } return bdJSON; } }); var ALT_COLORS=["#CCC","#DDD"]; var NVItem=Monomyth.Class.extend({ init:function(args){ if(!args.html) throw "Error in constructing NVItem"; this.loc=$("#"+args.loc); this.html=args.html; //append html to DOM $(this.html).appendTo(this.loc); this.rules=args.tagRules; this.preLoad=args.preLoad; this.tagData=args.tagData; this.tagUID=args.tagData.uid; this.level=(args.level)?args.level:0; //generate random unique ID var d=new Date(); this.uid=d.getTime(); this.tagName=this.tagData.name; //get HTML from external page //NEW: get html from JSON // $($.ajax({ // url:'lib/Tag/NameValueArea.php?id='+this.uid, // dataType:'html', // async:false // }).responseText).insertAfter(this.loc); //this.nodeValue=args.nv; //this.DOM=$("<div class=\"subNameValue\"></div>").attr("id","namevaluepair_"+$(".subNameValue").length).insertAfter(this.loc); this.DOM=$("#emptynvitem").attr('id',"nvitem_"+this.uid); //adjust DOMs margin based on level var n=this.level*15; this.DOM.css("margin-left",n+"px"); //this.DOM.css("background-color",((this.level%2)>0)?ALT_COLORS[0]:ALT_COLORS[1]); this.inputArea=$("#"+this.DOM.attr('id')+" > span.nameValue_Input"); //insert title of tag into the inputArea this.inputArea.text(this.tagName); //this.changeB=$("#"+this.uid+"_nvInputArea > a").click(function(e){$(this).trigger("NV_StartOver");}); this.requiredArea=$("#"+this.DOM.attr('id')+" > span.nameValue_RequiredArea").attr('id',this.uid+"_rqa"); this.optionalArea=$("#"+this.DOM.attr('id')+" > span.nameValue_OptionalArea").attr('id',this.uid+"_opa"); // this.optSelect=$("#"+this.uid+"_optSelect"); this.valueEl=null; this.items=[]; this.setUpInput(); if(this.preLoad){ this.setUpPrevious(); } else if(this.tagData.childNodes){ this.setUpChildren(); } }, setUpInput:function(){ //switch for displaying the correct value type switch(this.tagData.valueType){ case 0: //do nothing - null value this.valueEl=$("<p>No value</p>").appendTo(this.inputArea); break; case 1: this.valueEl=$("<input type=\"text\"></input>").attr("id",this.DOM.attr('id')+"_input").val("").appendTo(this.inputArea); // this.DOM.append(this.valueEl); break; case 2: //reference to a url or other tag this.valueEl=$("<input type=\"text\"></input>").attr("id",this.DOM.attr("id")+"_input").val("").appendTo(this.inputArea); //this.valueEl.bind("blur",{obj:this},this.evalRef); break; default: //enum type - set up select tag for(en in this.rules.enums){ if(this.tagData.valueType==this.rules.enums[en].uid){ var em=this.rules.enums[en]; //alert('value el is an enum'); // create select tag then run through JSON values for enum value this.valueEl=$("<select></select>").attr("id",this.DOM.attr('id')+"_input"); for(d in em.values){ //each em.value gets a option tag $("<option></option>").val(em.values[d]).text(em.values[d]).appendTo(this.valueEl); } this.valueEl.appendTo(this.inputArea); //end for loop break; } } } }, setUpChildren:function(){ var optnodes=[]; for(t in this.tagData.childNodes){ var uid=this.tagData.childNodes[t]; for(g in this.rules.tags){ if((uid==this.rules.tags[g].uid)){ if(this.rules.tags[g].optional=="false"){ var tag=this.rules.tags[g]; var el=new NVItem({ loc:this.requiredArea.attr('id'), tagRules:this.rules, tagData:tag, level:(this.level+1), html:this.html }); this.items.push(el); } else { optnodes.push(this.rules.tags[g].uid); } } } } if(optnodes.length>0){ this.optChoice=new NVOptionsItem({ loc:this.optionalArea, options:optnodes, tagRules:this.rules }); } //bind nvItemClick listener to DOM this.DOM.bind("nvItemClick",{obj:this},this.handleItemClick); }, //Optional tag selected from option element //adds an optional tag to the stack - called by nvItemClick handleItemClick:function(e,uid){ e.stopPropagation(); //want to stop this from going up DOM tree var obj=e.data.obj; for(r in obj.rules.tags){ if(uid==obj.rules.tags[r].uid){//found var T=obj.rules.tags[r]; var el=new NVItem({ loc:obj.optionalArea.attr('id'), tagRules:obj.rules, tagData:T, level:(obj.level+1), html:obj.html }); obj.items.push(el); obj.DOM.trigger("nvItemChanged",[obj.uid]); break; //stop loop } } }, //take previously bundled data and re-create previous state setUpPrevious:function(){ if(this.preLoad){ //first, set up any previously set input value this.valueEl.val(this.preLoad.value); if(this.preLoad.values){ for(x=0;x<this.preLoad.values.length;x++){ var cur=this.preLoad.values[x]; for(g in this.rules.tags){ if(cur.tagUid==this.rules.tags[g].uid){ var tag=this.rules.tags[g]; var el=new NVItem({ loc:this.requiredArea, tagRules:this.rules, tagData:tag, preLoad:cur.values, level:(this.level+1) }); this.items.push(el); if(cur.value) el.valueEl.val(cur.value); } } } } } }, //RECURSIVE FUNCTION bundleData:function(){ //return JSON-like string of all items var _Json={"uid":this.uid,"tagUid":this.tagUID,"name":this.tagData.tagName,"type":this.tagData.valueType,"value":this.valueEl.val().replace(/[\n\r\t]+/g,""),"values":[]}; for(i in this.items){ var it=this.items[i].bundleData(); _Json.values.push(it); } return _Json; }, destroy:function(){ for(i in this.items){ this.items[i].destroy(); } this.valueEl.remove(); this.DOM.remove(); }, _noEdit:function(){ //hide editable elements from user if(this.valueEl){ $("#"+this.uid+"_nvInputArea > p").text(this.tagName+": "+this.valueEl.val()); this.valueEl.hide(); } //cascade command down to other items var s=this; for(i=0;i<this.items.length;i++){ setTimeout(function(T){ T._noEdit(); },1,this.items[i]); } }, _startEdit:function(){ //show editable elements for user if(this.valueEl){ $("#"+this.uid+"_nvInputArea > p").text(this.tagName); this.valueEl.show(); } //cascade command down to other items var s=this; for(i=0;i<this.items.length;i++){ setTimeout(function(T){ T._startEdit(); },1,this.items[i]); } } }); //Sub-level version of Name-Value object above var NVOptionsItem=Monomyth.Class.extend({ init:function(args){ this.loc=args.loc; this.rules=args.tagRules; this.options=args.options; //create select element and insert after the args.loc jQuery object this.DOM=$("<select class=\"name_value_Option\"></select>").attr("id","select_"+$(".nameValue").length).insertAfter(this.loc).hide(); //make toggle button to show/hide the DOM this.toggleB=$("<span class=\"button\">Add more data...</span>").insertAfter(this.loc); this.toggleB.bind("click",{obj:this},this.toggleDisplay); this.w=false; if(this.options){ this.setUpNames(); } }, setUpNames:function(){ for(o in this.options){ var id=$("#"+this.DOM.attr("id")+" > option").length+"_"+this.DOM.attr("id"); var opt=$("<option></option>").appendTo(this.DOM); for(t in this.rules.tags){ var T=this.rules.tags[t]; if(this.options[o]==T.uid){ opt.val(T.uid).text(T.name); break; } } //set up listener for when an option is chosen opt.click(function(e){ $(this).trigger("nvItemClick",[$(this).val()]); }); } }, toggleDisplay:function(e){ var obj=e.data.obj; if(!obj.w){ obj.DOM.show('fast'); obj.w=true; } else { obj.DOM.hide('fast'); obj.w=false; } }, destroy:function(){ this.DOM.remove(); } }); TILE.TILE_ENGINE=TILE_ENGINE; TILE.Log=Log; TILE.TileLogShape=TileLogShape; TILE.TileNameValue=TileNameValue; TILE.NVItem=NVItem; TILE.NVOptionsItem=NVOptionsItem; TILE.TileLogTag=TileLogTag; TILE.TileLogGroup=TileLogGroup; })(jQuery);
lib/_Interface/tile_logbar.js
///TILE LOGBAR //TODO: make proper documentation //TILE_ENGINE: {Object} main engine for running the LogBar and Layout of TILE interface //Global Constants that other plugins can use var URL_LIST=[]; (function($){ var TILE=this; var jsonTags={"schema":"","transcript":"","group":"","shape":""}; /**Main Engine **/ //loads in html layout from columns.json, parses JSON and sends to all // other objects // // Creates: // TileLogBar - _log // ImageTagger - _Itag // Functions // getBase - checks TILECONSTANTS.json for base http data // setUp - makes TileLogBar, ImageTagger, sets global binds // addNewTool - sets a new tool - users must define tool in .js code and proper JSON format // saveSettings - starts prompt to save all data in session // start_New_Session - // clear_Image_Tags - clears the log bar of all tags for a particular image // clear_All_Tags - clears the LogBar completely var TILE_ENGINE=Monomyth.Class.extend({ init:function(args){ //get HTML from PHP script and attach to passed container this.loc=(args.attach)?args.attach:$("body"); var self=this; self.toolSet=args.toolSet; self.json=null; //check if there is json data self.checkJSON(); }, checkJSON:function(){ var self=this; var d=$.ajax({ url:'PHP/isJSON.php', dataType:"text", async:false }).responseText; if(d) self.json=eval('('+d+')'); self.getBase(); }, getBase:function(){ //check JSON file to configure main path var self=this; $.ajax({url:'TILECONSTANTS.json',dataType:'json',success:function(d){ //d refers to the JSON data self._base=d.base; self._importDefault=d.importDefault; $.ajax({ dataType:"json", url:"./lib/JSONHTML/columns.json", success:function(d){ //d represents JSON data // $(d.body).appendTo($("body")); self.DOM=$("body"); //this.startURL=args.URL; //self.json=(args.json)?args.json:false; self.schemaFile=null; self.preLoadData=null; //global bind for sidebar completion event to loadCanvas() self.setUp(d); } }); },async:false}); }, /**Get Schema**/ //taken from setMultiFileImport Custom Event call from ImportDialog getSchema:function(e,file,schema){ var obj=e.data.obj; //We are just getting the file with images // and the transcripts obj.imageFile=file; //make ajax call to file $.ajax({ url:obj.imageFile, dataType:'json', success:function(d){ //d refers to JSON object retrieved from imageFile URL_LIST=d; var dt=new Date(); var tlines=[]; //searching for transcripts for(tr in d){ if(d[tr].transcript){ $.merge(tlines,d[tr].transcript); } } if(!obj.json) obj.json=d; $("body:first").trigger("loadImageList"); $("body:first").trigger("closeImpD"); obj._log._addLines(tlines); //if(tlines.length) $("body:first").trigger("addLogBarItem",[{"items":tlines}]); } }); // obj.jsonReader.readSchemaFromFile(obj.schemaFile); }, setUp:function(d){ var self=this; //store JSON html data - has everything for layout this.columnslayout=d; //create log - goes towards left area //this._log=new TileLogBar({html:this.columnslayout,json:this.json}); this._log=new Transcript({loc:"logbar_list",text:null}); this._activeBox=new ActiveBox({loc:"az_activeBox"}); this._transcriptBar=new TileToolBar({loc:"transcript_toolbar"}); $("body").bind("tagRulesSet",{obj:this},this.TRSetHandle); //get dialog JSON data $.ajax({ url:"lib/JSONHTML/dialogs.json", dataType:"json", success:function(x){ self.dialogJSON=x; self.addDialogBoxes(); } }); //important variables //finishes the rest of init this.toolbarArea=$("#header"); //JSON Reader this.jsonReader=new jsonReader({}); //start ImageTagger if(this.toolSet){ //send to toolbar this._transcriptBar.setChoices(this.toolSet); this.setUpTool("imagetagger"); } $("body").bind("schemaFileImported",{obj:this},this.getSchema); //$("body").bind("saveAllSettings",{obj:this},this.saveSettings); //TODO:create restartALL procedure $("body").bind("restartAll",{obj:this},this.start_New_Session); //global bind for clearing all tags on current image $("body").bind("clearPage",{obj:this},this.clear_Image_Tags); //global bind for clearing all tags on every image $("body").bind("clearSession",{obj:this},this.clear_All_Tags); //global bind for when user selects a new tool from LogBar $("body").bind("toolSelected",{obj:this},this.addNewTool); //global bind for when data is ready to be passed as JSON to user $("body").bind("JSONreadyToSave",{obj:this},this._saveToUser); //global bind for when user clicks on transcript object $("body").bind("TranscriptLineSelected",{obj:this},this._transcriptSelectHandle); //for when user clicks on save $("body").bind("saveAllSettings",{obj:this},this._saveSettingsHandle); if(this.json){ //parse data //var p=this.jsonReader.read(this.json); //if(!p) window.location("."); //$("body").bind("tagRulesSet",{obj:this},this.loadJSONImages); this.jsonReader.readSchemaFromFile(this.json.schema); URL_LIST=this.json.images; // $("body:first").trigger("loadImageList"); //$("body").trigger("loadJSONList",[this.json.images]); // this.DOM.trigger("schemaLoaded",[p]); } }, TRSetHandle:function(e,c){ var obj=e.data.obj; $("body").unbind("tagRulesSet",obj.TRSetHandle); //c is the schema data obj._log.setChoices(c); obj.schemaData=c; $.ajax({ url:obj.imageFile, dataType:'json', success:function(d){ URL_LIST=d; var dt=new Date(); var tlines=[]; //searching for transcripts for(tr in d){ if(d[tr].transcript){ for(line in d[tr].transcript){ //create an item for manifest.tags if(d[tr].transcript[line].length>0){ tlines.push({ 'type':'transcript', 'uri':d[tr].uri, 'name':(d[tr].transcript[line].substring(0,5)+"..."), 'uid':'t'+dt.getTime('milliseconds')+tlines.length, 'etc':{"text":d[tr].transcript[line]} }); } } } } $("body:first").trigger("loadImageList"); $("body:first").trigger("closeImpD"); if(tlines.length) $("body:first").trigger("addLogBarItem",[{"items":tlines}]); } }); }, addDialogBoxes:function(){ //load dialog boxes this.importDialog=new ImportDialog({ loc:$("body"), html:this.dialogJSON.dialogimport, auto:this._importDefault }); this.loadTagsDialog=new LoadTags({ loc:$("body"), html:this.dialogJSON.dialogloadtags }); //new Image Dialog this.nImgD=new NewImageDialog({loc:"body",html:this.dialogJSON.dialogaddimage}); //if json data present, set up urls if(!this.json) { this.DOM.trigger("openImport"); } }, setUpTool:function(toolname){ var obj=this; toolname=toolname.toLowerCase().replace(" ",""); if(obj.curTool&&(obj.curTool.name==toolname)) return; if(obj.toolSet){ for(tool in obj.toolSet){ if(obj.toolSet[tool].name==toolname){ //select in toolSelect obj._transcriptBar.setChoice(toolname); if(!obj.toolSet[tool].constructed){ obj.toolSet[tool].start(null,self._base,(obj.json)?obj.json:null); //give place where it opens into obj.toolSet[tool].constructed=true; obj.curTool=obj.toolSet[tool]; $("body").bind(obj.toolSet[tool].done,{obj:obj,tool:obj.toolSet[tool]},obj._toolDoneHandle); } else { //tool already constructed, restart tool obj.curTool=obj.toolSet[tool]; obj.curTool.restart(); } break; } } } // //replace the main log area with whatever // var mv='-='+$(".az.main > #az_log").width(); // $(".az.main > #az_log").animate({left:mv,opacity:0.25},400,function(e){ // $(".az.main > #az_log").children().hide(); // $(".az.main > #az_log").removeClass("log").addClass("tool"); // $(".az.main > #az_log").animate({opacity:1,left:0},200); // // toolname=toolname.toLowerCase().replace(" ",""); // // //NEW: accessing autorecognizer tools // // //AUTORECOGNIZER // // $("body").bind("ARStart",{obj:obj},function(e){ // // //stop the imagetagger from listening // // $("body").trigger("closeDownVD",[true]); // // }); // // }); }, //responds to custom event - toolSelected addNewTool:function(e,toolname){ var obj=e.data.obj; //replace the main log area with whatever toolname=toolname.toLowerCase().replace(" ",""); if(toolname==obj.curTool.name) return; // //NEW: accessing autorecognizer tools // //AUTORECOGNIZER // $("body").bind("ARStart",{obj:obj},function(e){ // //stop the imagetagger from listening // $("body").trigger("closeDownVD",[true]); // }); obj.curTool.close(); if(obj.toolSet){ for(tool in obj.toolSet){ if(obj.toolSet[tool].name==toolname){ //select in toolSelect obj._transcriptBar.setChoice(toolname); if(!obj.toolSet[tool].constructed){ obj.toolSet[tool].start(null,obj.schemaData,obj._log.exportLines()); //give place where it opens into obj.toolSet[tool].constructed=true; obj.curTool=obj.toolSet[tool]; $("body").bind(obj.toolSet[tool].done,{obj:obj,tool:obj.toolSet[tool]},obj._toolDoneHandle); if(obj.toolSet[tool].outputData) $("body").bind(obj.toolSet[tool].outputData,{obj:obj},obj._toolOutputHandle); } else { //tool already constructed, restart tool obj.curTool=obj.toolSet[tool]; obj.toolSet[tool].restart(obj._log.exportLines()); } break; } } } }, _toolDoneHandle:function(e){ var self=e.data.obj; //$("#az_log").removeClass("tool").addClass("log"); self.curTool=null; self.setUpTool("imagetagger"); }, _toolOutputHandle:function(e,data){ var self=e.data.obj; self._log._addLines(data); }, _transcriptSelectHandle:function(e,data){ var self=e.data.obj; self._activeBox._addItem(data); }, saveSettings:function(e){ var obj=e.data.obj; }, start_New_Session:function(e){ var obj=e.data.obj; //restart the entire session //erases images, tags, shapes //obj._Itag.restart(); obj.curTool.restart(); obj._log.restart(); //if(obj.Scroller) obj.Scroller._resetContainer(); //if(obj.SideBar) obj.SideBar._resetAllTags(); //open up import dialog obj.DOM.trigger("openImport"); }, //clear only the shapes and tags drawn on the current image clear_Image_Tags:function(e){ var obj=e.data.obj; // obj.SideBar.reset_Curr_Manifest(); // obj.raphael._resetCurrImage(); }, clear_All_Tags:function(e){ var obj=e.data.obj; // obj.SideBar._resetAllTags(); // obj.raphael._eraseAllShapes(); }, _saveSettingsHandle:function(e){ var self=e.data.obj; //curTool is imagetagger self.json=self.curTool.bundleData(self.json); if(!self.save) self.save=new Save({loc:"azglobalmenu"}); self.save.userPrompt(self.json); // j.schema=self.jsonReader.schemaFile; // //get elements from plugins // for(b in self.toolSet){ // j=self.toolSet[b].bundleData(j); // } // // if(!self.save) self.save=new Save({loc:"azglobalmenu"}); // self.save.userPrompt(j); } }); /** Dialog Boxes: Import, New Image, Load Tags **/ //ImportDialog /** Called by openImport CustomEvent **/ var ImportDialog=Dialog.extend({ init:function(args){ this.$super(args); this.index=($("#dialog").length+this.loc.width()); this.autoFill=args.auto; // this.loc.append($.ajax({ // async:false, // dataType:'html', // url:'lib/Dialog/dialogImport.html' // }).responseText); //lightbox content this.light=$("#light"); this.fade=$("#fade"); this.DOM=$("#dialogImport"); this.closeB=$("#importDataClose"); this.closeB.click(function(e){ $(this).trigger("closeImpD"); }); //this.schemaFileInput=$("#importDataFormInputSingle"); //this.schemaFileFormSubmit=$("#importDataFormSubmitSingle"); //this.schemaFileFormSubmit.bind("click",{obj:this},this.handleSchemaForm); this.multiFileInput=$("#importDataFormInputMulti").val(this.autoFill); this.multiFileFormSubmit=$("#importDataFormSubmitMulti"); this.multiFileFormSubmit.bind("click",{obj:this},this.handleMultiForm); $("body").bind("openNewImage",{obj:this},this.close); $("body").bind("closeImpD",{obj:this},this.close); $("body").bind("openLoadTags",{obj:this},this.close); $("body").bind("openImport",{obj:this},this.display); }, display:function(e){ var obj=e.data.obj; obj.fade.show(); obj.DOM.show(); obj.light.show(); }, close:function(e){ var obj=e.data.obj; obj.light.hide(); obj.DOM.hide(); obj.fade.hide(); }, handleSchemaForm:function(e){ e.preventDefault(); var obj=e.data.obj; var file=obj.schemaFileInput.text(); if(/http:\/\//.test(file)){ obj.DOM.trigger("schemaFileImported",[file]); } else { //show warning: not a valid URI } }, //finds the transcript/image file that the user // has input and sends it off in a CustomEvent trigger // schemaFileImported handleMultiForm:function(e){ e.preventDefault(); var obj=e.data.obj; var file=obj.multiFileInput.val(); //var schema=obj.schemaFileInput.attr("value"); if(file.length){ if(/http:\/\//.test(file)){ //trigger an event that sends both the schema and the list of files to listener obj.DOM.trigger("schemaFileImported",[file]); // obj.DOM.trigger("schemaLoaded",[{schema:schema}]); // obj.DOM.trigger("multiFileListImported",[file]); } else { //show warning: not a valid URI } } } }); TILE.ImportDialog=ImportDialog; var LoadTags=Dialog.extend({ init:function(args){ this.$super(args); // this.loc.append($.ajax({ // async:false, // url:'lib/Dialog/DialogLoadTags.html', // dataType:'html' // }).responseText); this.DOM=$("#loadTagsDialog"); this.closeB=$("#loadTagsClose"); this.closeB.click(function(e){ $(this).trigger("closeLoadTags"); }); this.light=$("#LTlight"); this.fade=$("#LTfade"); $("body").bind("openNewImage",{obj:this},this.close); $("body").bind("openImport",{obj:this},this.close); $("body").bind("openLoadTags",{obj:this},this.display); $("body").bind("closeLoadTags",{obj:this},this.close); }, display:function(e){ var obj=e.data.obj; obj.light.show(); obj.DOM.show(); obj.fade.show(); }, close:function(e){ var obj=e.data.obj; obj.light.hide(); obj.DOM.hide(); obj.fade.hide(); } }); TILE.LoadTags=LoadTags; // New Image Box var NewImageDialog=Dialog.extend({ init:function(args){ this.$super(args); // this.loc.append($.ajax({ // async:false, // url:'lib/Dialog/dialogNewImg.html', // dataType:'html' // }).responseText); this.DOM=$("#dialogNewImg"); this.closeB=$("#newImgClose"); this.closeB.click(function(e){ $(this).trigger("closeNewImage"); }); this.uriInput=$("#newImgURIInput"); this.submitB=$("#newImgSubmit"); this.submitB.bind("click",{obj:this},this.handleImageForm); $("body").bind("openImport",{obj:this},this.close); $("body").bind("openLoadTags",{obj:this},this.close); $("body").bind("openNewImage",{obj:this},this.display); $("body").bind("closeNewImage",{obj:this},this.close); }, display:function(e){ var obj=e.data.obj; obj.DOM.show(); obj.DOM.css({"z-index":"1001"}); }, close:function(e){ var obj=e.data.obj; obj.DOM.hide(); }, handleImageForm:function(e){ var obj=e.data.obj; if(obj.uriInput.val().length>0){ obj.DOM.trigger("newImageAdded",[obj.uriInput.val()]); obj.uriInput.attr("value",""); obj.DOM.trigger("closeNewImage"); } } }); TILE.NewImageDialog=NewImageDialog; /** Log Toolbar: Toolbar that contains objects that reflect a log of what is going on in main tagging/workspace area. //receives html in form of text **/ var Log=Monomyth.Class.extend({ init:function(args){ if(!args.html) throw "no JSON data passed to Log{}"; this.html=args.html; this.DOM=$("#az_log"); $(this.html.log).appendTo(this.DOM); } }); TileToolBar=Monomyth.Class.extend({ init:function(args){ //getting HTML that is already loaded - no need to attach anything var self=this; self.loc=args.loc; self.LoadB=$("#"+self.loc+" > .menuitem > ul > li > #load_tags"); self.SaveB=$("#"+self.loc+" > .menuitem > ul > li > #save_tags"); self.ToolSelect=$("#"+self.loc+" > #ddown > .menuitem.ddown > select"); self.ToolSelect.change(function(e){ var choice=self.ToolSelect.children("option:selected"); $(this).trigger("toolSelected",[choice.text().toLowerCase()]); }); //set up loading and saving windows self.LoadB.click(function(e){ e.preventDefault(); $(this).trigger("openLoadTags"); }); self.SaveB.click(function(e){ e.preventDefault(); $(this).trigger("saveAllSettings"); }); }, setChoices:function(data){ var self=this; self.ToolSelect.children("option").remove(); for(d in data){ if(data[d].name){ var el=$("<option>"+data[d].name+"</option>"); self.ToolSelect.append(el); } } }, setChoice:function(name){ var self=this; self.ToolSelect.children("option").each(function(i,o){ if(name==$(o).text().toLowerCase().replace(" ","")){ $(o)[0].selected=true; } else { $(o)[0].selected=false; } }); } }); /** TILE LogBar Inherits from Log in base.js **/ var TileLogBar=Log.extend({ init:function(args){ this.$super(args); this.DOM=$("#az_log > .az.inner"); this.toolbar=$("#az_log > .az.inner > .toolbar"); this.jsondata=(args.json||null); this.toolSelect=$("#az_log > .az.inner > .toolbar > #ddown > div.menuitem.ddown:nth-child(1) > select"); this.tagSelect=$("#az_log > .az.inner > .toolbar > #ddown > div.menuitem.ddown:nth-child(2) > select"); var hadjust=(this.toolbar.height()+((this.toolbar.css("border-width")+this.toolbar.css("padding"))*2)+2+127); this.logInsertPoint=$("#az_log > .az.inner > #logbar_list").height((this.DOM.height()-hadjust)).css("overflow","auto"); this.logActiveArea=$("#az_log > .az.inner > #logbar_activearea"); //group select element - user selects a group to add current active item into this.groupSelect=$("#"+this.logActiveArea.attr("id")+" > select"); var self=this; this.doneB=$("#logbar_activearea > div.activearea_head > div#logbar_done").click(function(e){ $("body").trigger("addedTag"); self._createListItem(); }); this.deleteB=$("#logbar_activearea > div.activearea_head > div#logbar_delete").click(function(e){ self._deleteListItem(); }); this.logbar_next=$("#az_log > .az.inner > #logNav > #logbar_next").click(function(e){ self._paginate(1); }); this.logbar_prev=$("#az_log > .az.inner > #logNav > #logbar_prev").click(function(e){ self._paginate(-1); });; this.pageSelectTool=$("#az_log > .az.inner > #logNav > #paginateInfo > #pageSelect"); this.pageSelectTool.change(function(e){ var target=$("#pageSelect > option:selected"); $(this).trigger("paginateTo",[parseInt(target.text(),10)]); }); //adding key listener for creating list items this.DOM.keypress(function(e){ if(e.keyCode==13){ $("body").trigger("addedTag"); self._createListItem(); } else if(e.keyCode==27){ self._deleteListItem(); } }); //this.logitemhtml=args.html.logitem; this.rules=null; this.GroupId=null; this.setUpToolBar(); //array for items about to be put in loglist this.emptytags=[]; //manifest array for all items in log_list this.manifest={"tags":[]}; this.tagCount=0; this.maxTags=6; this.showTags=[]; //local listeners this.DOM.bind("itemDropped",{obj:this},this.itemDroppedHandle); //global listeners $("body").bind("shapeDrawn",{obj:this},function(e,shape){ e.data.obj.addShape(shape,null); }); $("body").bind("tagRulesSet",{obj:this},this.initTagRules); $("body").bind("setGroup",{obj:this},this.setGroupHandle); $("body").bind("logGroupClosed",{obj:this},this.logGroupClosedHandle); $("body").bind("logGroupOpen",{obj:this},this.logGroupOpenHandle); $("body").bind("tagSelected",{obj:this},this.tagSelectedHandle); $("body").bind("saveAllSettings",{obj:this},this._saveP); $("body").bind("paginateTo",{obj:this},this._paginateToHandle); }, setUpToolBar:function(){ var self=this; self.loadB=$("#az_log > .az.inner > .toolbar > .menuitem > ul > li > #load_tags").click(function(e){ e.preventDefault(); $(this).trigger("openLoadTags"); }); self.saveB=$("#az_log > .az.inner > .toolbar > .menuitem > ul > li > #save_tags").click(function(e){ e.preventDefault(); $(this).trigger("saveAllSettings"); }); self.logInsertPoint.sortable({ items:'div.tag' }); //set up group select item self.groupSelect.children().each(function(i,o){ if(!$(o).attr('id')=='null'){ $(o).click(function(e){ //force-initiate the itemDropped call $(this).trigger("itemDropped",[$(this).parent().children("div.tag:visible").attr("id"),$(this).val()]); }); } }); //self.setChoices(); }, setChoices:function(d){ var self=this; self.rules=d; var c=[]; //var c=["Group","Transcript"];//TODO: make default that's changed by user? for(di in d.topLevelTags){ var diu=d.topLevelTags[di]; for(tag in d.tags){ if(diu==d.tags[tag].uid){ c.push({tname:d.tags[tag].name,tid:diu}); } } } //attach the addItem listener - listens for changes //in select and adds objects based on type paramater $("body").bind("addLogBarItem",{obj:self},self._addItemR); //bind a separate local listener to only listen to the menu items being clicked this.DOM.bind("addLogBarItem",{obj:this},function(e,t){ var obj=e.data.obj; e.stopPropagation(); //kill this from getting to "body" //based on what select returns, make that object appear in log if(t!=null){ switch(t.toLowerCase()){ case 'group': obj.addGroup(); break; case 'tag': obj.addTag(); break; case 'transcript': obj.addTranscript(); break; case 'shape': obj.addBlankShape(); break; default: obj.addTag(t); break; } } }); $.each(c,function(i,o){ //var elwrap=$("<option id=\"\">"+o.tname+"</option>").val(o.tid).appendTo(self.tagSelect); // var el=null; if(o.tname){ //el=$("<a href=\"\">"+o.tname+"</a>").val(o.tid).appendTo(elwrap); var el=$("<option>"+o.tname+"</option>").val(o.tid).appendTo(self.tagSelect); el.click(function(e){ e.preventDefault(); $(this).trigger("addLogBarItem",[$(this).val()]); }); } else { var el=$("<option>"+o+"</option>").val(o).appendTo(self.tagSelect); el.click(function(e){ e.preventDefault(); $(this).trigger("addLogBarItem",[$(this).val().toLowerCase()]); }); } }); //set finalHeight (fH) as data in the tagSelect object //self.heights[1]=(self.tagSelect.children().length*30); //set ToolChoices var bd=["Auto Recognizer"]; //engine handles when tool is selected - changes layout $.each(bd,function(i,o){ var el=$("<option>"+o+"</option>").val(o).appendTo(self.toolSelect); el.click(function(e){ e.preventDefault(); $(this).trigger("toolSelected",[$(this).val().toLowerCase()]); }); }); //set finalHeight for the toolSelect //self.heights[0]=(self.toolSelect.children().length*35); //set up pre-loaded tags, if json data exists if(self.jsondata&&self.jsondata.tags){ var items=$.merge(self.jsondata.groups,self.jsondata.tags); $("body:first").trigger("addLogBarItem",[{"items":items}]); } }, /** called by CustomEvent from LogBar **/ setGroupHandle:function(e,guid){ //group has been added to logbar var obj=e.data.obj; if(obj.GroupId&&obj.manifest.groups[obj.GroupId]){ obj.manifest.groups[obj.GroupId].setCloseState(); } obj.GroupId=guid; }, //for when a user drops something into a group's area itemDroppedHandle:function(e,id,gid){ var obj=e.data.obj; //called when a group object adds an item id=id.replace("copy",""); gid=gid.replace("copy",""); //just to be sure if(obj.manifest.tags[id]&&obj.manifest.tags[gid]){ obj.manifest.tags[gid].o.pushItem(obj.manifest.tags[id]); //if the group is in active area, display list var ctag=$("#"+obj.logActiveArea.attr('id')+" > div:not(.activearea_head)"); if(ctag.attr('id')==gid) obj.manifest.tags[gid].o._showList(); } // if(!gid){ // if(obj.GroupId&&(obj.manifest.groups[obj.GroupId])){ // var s=null; // var id=id.replace(/copy/,""); // if(obj.manifest.tags[id]){ // s=obj.manifest.tags[id].o; // // obj.manifest.groups[obj.GroupId].o.pushItem(s); // } else if(obj.manifest.groups[id]) { // //it's a group in a group // s=obj.manifest.groups[id].o; // // } // if(s) obj.manifest.groups[obj.GroupId].o.pushItem(s); // } // } else { // //find element // var item=null; // for(i in obj.manifest.tags){ // if(i==id){ // item=obj.manifest.tags[i]; // break; // } // } // // //gid is given-find group and add item to it // for(g in obj.manifest.groups){ // if(g==gid){ // var s=obj.manifest.groups[g]; // if(!s.manifest[item.uid]) s.o.pushItem(item); // break; // } // } // // } }, logGroupClosedHandle:function(e,guid){ var obj=e.data.obj; //change the GroupId obj.GroupId=null; }, logGroupOpenHandle:function(e,guid){ var obj=e.data.obj; obj.GroupId=guid; for(g in obj.manifest.groups){ if(obj.manifest.groups[g].o.uid!=guid) obj.manifest.groups[g].o.setCloseState(); } }, tagSelectedHandle:function(e,tid){ var self=e.data.obj; tid=tid.replace(/copy/,""); if(self.manifest.tags[tid]){ var t=self.manifest.tags[tid]; self.logActiveArea.children("div.tag").remove(); self.logActiveArea.children("div.group").remove(); t.o.DOM.appendTo(self.logActiveArea); if(t.type=='shape') $("body:first").trigger("_showShape",[t.o.shape.id]); if(t.type=='group') t.o._showList(); self.curItem=t; } }, /** Set as sortable list of objects **/ _draggableDroppable:function(){ $("#logbar_list").sortable({ items:"div", //restrict to only tags, transcripts, and shapes handle:'span.moveme' }); }, //adds an item to the activeArea - not yet in manifest, though, //until the user clicks 'done' _addItem:function(obj){ var self=this; self._updateListItem(); if($.inArray(obj.n,self.showTags)>-1){ self.logActiveArea.children("div.tag").remove(); self.logActiveArea.children("div.group").remove(); switch(obj.type){ case 'shape': if(!obj.o){ obj.o=new TileLogShape({ uid:obj.uid, name:(obj.name||obj.uid), html:obj.html, loc:self.logActiveArea.attr("id"), copyloc:self.logInsertPoint.attr("id"), shape:(obj.shape)?obj.shape:obj, etc:(obj.etc||null) }); obj.act=obj.o.DOM; if(!self.manifest.tags[obj.uid]) self.emptytags[obj.uid]=obj; } else { obj.o.DOM.appendTo(self.logActiveArea); } self.curItem=obj; break; case 'transcript': if(!obj.o){ if(!obj.etc); obj.o=new TileTranscriptTag({ uid:obj.uid, name:(obj.name||obj.uid), html:obj.html, loc:self.logActiveArea.attr("id"), copyloc:self.logInsertPoint.attr("id"), etc:(obj.etc||null) }); obj.act=obj.o.DOM; if(!self.manifest.tags[obj.uid]) self.emptytags[obj.uid]=obj; } else { obj.o.DOM.appendTo(self.logActiveArea); } self.curItem=obj; break; case 'schema': if(!obj.o){ obj.o=new TileLogTag({ uid:obj.uid, name:(obj.name||obj.uid), html:obj.html, loc:self.logActiveArea.attr('id'), copyloc:self.logInsertPoint.attr('id'), tagRules:self.rules, tagId:obj.tagId }); // obj.cur=new TagCopy({ // html:"<div id=\"\" class=\"tag transcript\">"+obj.o.DOM.html()+"</div>", // loc:self.logInsertPoint.attr("id"), // uid:obj.uid, // name:obj.o.name // }); obj.act=obj.o.DOM; if(!self.manifest.tags[obj.uid]) self.emptytags[obj.uid]=obj; } else { obj.o.DOM.appendTo(self.logActiveArea); } self.curItem=obj; break; case 'group': if(!obj.o){ //need to insert objects into etc - for(n in obj.etc){ var tag=self.manifest.tags[obj.etc[n]]; obj.etc[n]=tag; } if(obj.etc.length<self.maxTags){ //make group obj.o=new TileLogGroup({ loc:self.logActiveArea.attr('id'), html:obj.html, copyloc:self.logInsertPoint.attr('id'), etc:obj.etc, name:obj.name, uid:obj.uid }); obj.act=obj.o.DOM; } if(!self.manifest.tags[obj.uid]) self.emptytags[obj.uid]=obj; //add to list of groups in groupselect self.groupSelect.append($("<option>"+obj.o.name+"</option>").val(obj.uid).click(function(e){ var p=$(this).closest("div"); //alert($("#"+$(p).attr('id')+" > div:nth-child(2)").attr("id")); $(this).trigger("itemDropped",[$(p).children("div:visible").attr("id").substring(1),$(this).val()]); })); } else { obj.o.DOM.appendTo(self.logActiveArea); } self.curItem=obj; break; } } }, //adds the item to the manifest and makes a _copy object //to put in loginsertarea _createListItem:function(){ var self=this; if(self.curItem){ var check=false; if(self.curItem.n) check=true; //check if number of list items has gone over limit if(self.logInsertPoint.children("div").length>self.maxTags){ self._reOrderPages(); } switch(self.curItem.type){ case 'shape': if(!(self.logInsertPoint.children("#"+self.curItem.o.DOM.attr("id")+"copy").length>0)){ var copy=new TagCopy({ html:self.html.tagshape, type:self.curItem.type, shape:self.curItem.shape, uid:self.curItem.uid, loc:self.logInsertPoint.attr('id'), name:self.curItem.o.name }); } // else if(!self.logInsertPoint.children("#"+self.curItem.o._copy.DOM.attr("id")).length>0) { // self.curItem.o._copy.DOM.appendTo(self.logInsertPoint); // } self.curItem.o._tagUpdate(); break; case 'transcript': if(!(self.logInsertPoint.children("#"+self.curItem.o.DOM.attr("id")+"copy").length>0)){ var copy=new TagCopy({ html:self.html.tagtranscript, type:self.curItem.type, uid:self.curItem.uid, etc:self.curItem.etc, loc:self.logInsertPoint.attr('id'), name:self.curItem.o.name }); } // else if(!(self.logInsertPoint.children("#"+self.curItem.o._copy.DOM.attr("id")).length>0)){ // // self.curItem.o._copy.DOM.appendTo(self.logInsertPoint); // } self.curItem.o._tagUpdate(); break; case 'schema': if(!(self.logInsertPoint.children("#"+self.curItem.o.DOM.attr("id")+"copy").length>0)){ var copy=new TagCopy({ html:self.html.tilelogtag, type:self.curItem.type, uid:self.curItem.uid, loc:self.logInsertPoint.attr('id'), name:self.curItem.o.name }); } // else if(!self.logInsertPoint.children("#"+self.curItem.o._copy.DOM.attr("id")).length>0){ // self.curItem.o._copy.DOM.appendTo(self.logInsertPoint); // } self.curItem.o._tagUpdate(); break; case 'group': if(!(self.logInsertPoint.children("#"+self.curItem.o.DOM.attr("id")+"copy").length>0)){ var copy=new GroupCopy({ html:self.html.taggroup, type:self.curItem.type, uid:self.curItem.uid, etc:self.curItem.etc, loc:self.logInsertPoint.attr("id"), name:(self.curItem.o.name||self.curItem.uid) }); } // else if(!self.logInsertPoint.children("#"+self.curItem.o._copy.DOM.attr("id")).length>0){ // self.curItem.o._copy.DOM.appendTo(self.logInsertPoint); // } self.curItem.o._tagUpdate(); break; } if(!self.manifest.tags[self.curItem.uid]){ //Remove from emptytags and put in manifest self.manifest.tags[self.curItem.uid]=self.curItem; self.emptytags[self.curItem.uid]=null; self.emptytags=$.grep(self.emptytags,function(o,n){ return (o!=null); }); } if((self.curItem.type!='shape')){ //build another item of same type var d=new Date(); var uid="t"+d.getTime("milliseconds"); var nItem={ html:self.curItem.html, type:self.curItem.type, uid:uid, cur:null, etc:[], o:null, n:self.tagCount }; self.tagCount++; self.curItem=null; // so it isn't deleted self.manifest.tags[uid]=nItem; self.showTags.push(nItem.n); self._addItem(nItem); if ((self.curItem.type == 'transcript')) { $(".tagcontent>form>textarea").focus(); } } else if(self.curItem.type=='shape') { self.curItem.o.DOM.remove(); self.curItem=null; } self._overFlowHandle(); } }, //user went to next tag, while tag still present in activearea _updateListItem:function(obj){ var self=this; if(!obj) var obj=self.manifest.tags[$("#logbar_activearea > div.tag").attr('id')]; if(!obj) var obj=self.emptytags[$("#logbar_activearea > div.tag").attr('id')]; if(obj){ //check to see whether this item is in the emptytags or the manifest array if(self.manifest.tags[obj.uid]){ //update the tag and remove from logActiveArea obj.o._tagUpdate(); obj.o.DOM.remove(); } else if(self.emptytags[obj.uid]){ //not going to use this one - remove it completely //if it's a shape, also destroy the shape it came with if(obj.type=='shape') $("body").trigger("VD_REMOVESHAPE",[obj.uid]); self.emptytags[obj.uid]=null; self.emptytags=$.grep(self.emptytags,function(o,n){ return (o!=null); }); self.tagCount--; obj.o.DOM.remove(); if(obj.o._copy) obj.o._copy.DOM.remove(); } } }, //user clicked Delete _deleteListItem:function(obj){ var self=this; if(!obj) var obj=self.manifest.tags[$("#logbar_activearea > div:not(.activearea_head)").attr('id')]; if(!obj) obj=self.emptytags[$("#logbar_activearea > div.tag").attr('id')]; if(obj){ //check to see whether this item is in the emptytags or the manifest array if(self.manifest.tags[obj.uid]){ //delete the tag and remove from logActiveArea obj.o.DOM.remove(); $("#"+obj.uid+"copy").remove(); if(obj.type=='shape') $("body:first").trigger("VD_REMOVESHAPE",[obj.uid]); //if(obj.o._copy) obj.o._copy.DOM.remove(); self.manifest.tags[obj.uid]=null; self.tagCount--; } else if(self.emptytags[obj.uid]){ //not going to use this one - remove it completely //if it's a shape, also destroy the shape it came with if(obj.type=='shape') $("body").trigger("VD_REMOVESHAPE",[obj.uid]); //remove from DOM if(obj.o) obj.o.DOM.remove(); if(obj.o._copy) obj.o._copy.DOM.remove(); self.emptytags[obj.uid]=null; self.tagCount--; } if(self.logInsertPoint.children("div").length==0){ //empty log area - reset pages var t=parseInt(self.pageSelectTool.children(".pageChoice:selected").text(),10); self._reOrderPages(); $("body:first").trigger("paginateTo",[t]); } } }, /** Called from body tag using addLogBarItem Custom Event Loads a tag using JSON Items: array of items to add Group: (optional) add a group and an optional string to name that group - all items are added to this group **/ _addItemR:function(e,json){ var self=e.data.obj; if(json.shapes){ $("body:first").trigger("loadShapes",[json.shapes]); } //get json data and parse into element if(json.items){ for(it in json.items){ var item=json.items[it]; //determine type - if any //defaults to item name //var itemtype=item.name; if(item.type){ switch(item.type){ case "shape": case "rect": //create a shape tag if(!item.n){ var o={ uid:item.uid, cur:null, o:null, html:self.html.tagshape, name:(item.name)?item.name:null, type:'shape', shape:item.shape, etc:item.etc, n:self.tagCount }; //add shape to manifest self.manifest.tags[o.uid]=o; self.tagCount++; //if there's a group, create that group tag //must be a new group, otherwise add to that group's etc if(o.etc&&o.etc.groups){ //each subsequent group is added into the previous one var addGroup=[]; for(g in o.etc.groups){ var guid=o.etc.groups[g]; if(!self.manifest.tags[guid]){ self.manifest.tags[guid]={ cur:null, o:null, uid:guid, name:(item.name||null), html:self.html.taggroup, type:'group', group:null, etc:[o.uid], n:self.tagCount }; for(sub in addGroup){ self.manifest.tags[addGroup[sub]].etc.push(guid); } addGroup.push(guid); self.tagCount++; } else { self.manifest.tags[guid].etc.push(o.uid); addGroup.push(guid); } } } $.map(["width","height","x","y","cx","cy","rx","ry","path"],function(p){ if(p in item){ o.etc[p]=item[p]; } }); } else { //loaded from a JSON file - only need to copy contents //into _keepers item.html=self.html.tagshape; self.manifest.tags[item.uid]=item; self.tagCount=item.n; } break; case "transcript": if(!item.n){ //loaded from AR or from user input //create a transcript tag //could be loading something that is already loaded - check to see if(self.manifest.tags[item.uid]&&self.manifest.tags[item.uid].o) { self.manifest.tags[item.uid].o.DOM.remove(); if(self.manifest.tags[item.uid].o._copy) self.manifest.tags[item.uid].o._copy.DOM.remove(); self.manifest.tags[item.uid]=null; } self.manifest.tags[item.uid]={ cur:null, o:null, name:(item.name||null), uid:item.uid, type:'transcript', html:self.html.tagtranscript, etc:(item.etc||{"text":"Blank"}), n:self.tagCount }; self.tagCount++; //if there's a group, create that group tag //must be a new group, otherwise add to that group's etc if(item.etc&&item.etc.groups){ for(g in item.etc.groups){ var addGroup=[]; var guid=item.etc.groups[g]; if(!self.manifest.tags[guid]){ self.manifest.tags[guid]={ cur:null, o:null, uid:guid, html:self.html.taggroup, name:(item.etc.text)?item.etc.text:guid, type:'group', group:null, etc:[item.uid], n:self.tagCount }; for(sub in addGroup){ self.manifest.tags[addGroup[sub]].etc.push(guid); } addGroup.push(guid); self.tagCount++; } else { self.manifest.tags[guid].etc.push(item.uid); if(item.etc.text&&(self.manifest.tags[guid].name!=item.etc.text)){ self.manifest.tags[guid].name=item.etc.text; } addGroup.push(guid); } } } } else { //loaded from a JSON file - only need to copy contents //into _keepers item.html=self.html.tagtranscript; self.manifest.tags[item.uid]=item; self.tagCount=item.n; } //self.addTranscript(item); break; case "schema": if(!item.n){ //loaded from AR or from user input //create a transcript tag self.manifest.tags[item.uid]={ cur:null, o:null, name:(item.name||null), uid:item.uid, type:'schema', html:self.html, group:item.group, etc:(item.etc||"Blank"), n:self.tagCount }; self.tagCount++; //if there's a group, create that group tag //must be a new group, otherwise add to that group's etc if(o.etc&&o.etc.groups){ for(g in o.etc.groups){ var guid=o.etc.groups[g]; if(!self.manifest.tags[guid]){ self.manifest.tags[guid]={ cur:null, o:null, uid:guid, html:self.html.taggroup, type:'group', group:null, etc:[o.uid], n:self.tagCount }; for(sub in addGroup){ self.manifest.tags[addGroup[sub]].etc.push(guid); } addGroup.push(guid); self.tagCount++; } else { self.manifest.tags[guid].etc.push(o.uid); addGroup.push(guid); } } } } else { //loaded from a JSON file - only need to copy contents //into _keepers item.html=self.html.tagtranscript; self.manifest.tags[item.uid]=item; self.tagCount=item.n; } break; case "group": //create a holder for a group tag if(!item.n){ self.manifest.tags[item.uid]={ cur:null, o:null, uid:item.uid, type:'group', html:self.html.taggroup, group:null, etc:item.etc, n:self.tagCount }; self.tagCount++; //if there's a group, create that group tag //must be a new group, otherwise add to that group's etc if(item.etc&&item.etc.groups){ for(g in item.etc.groups){ var guid=item.etc.groups[g]; if(!self.manifest.tags[guid]){ self.manifest.tags[guid]={ cur:null, o:null, uid:guid, html:self.html.taggroup, type:'group', group:null, etc:[item.uid], n:self.tagCount }; for(sub in addGroup){ self.manifest.tags[addGroup[sub]].etc.push(guid); } addGroup.push(guid); self.tagCount++; } else { self.manifest.tags[guid].etc.push(o.uid); addGroup.push(guid); } } } } else { //loaded from a JSON file - only need to copy contents //into _keepers item.html=self.html.taggroup; self.manifest.tags[item.uid]=item; self.tagCount=item.n; } default: break; } } } // var pages=Math.ceil((self.tagCount/self.maxTags)); // $("#"+self.pageSelectTool.attr('id')+" > .pageChoice").remove(); // while(pages>0){ // var el=$("<option class=\"pageChoice\">"+pages+"</option>");// .click(function(e){ // // $(this).trigger("paginateTo",[parseInt($(this).text(),10)]); // // }); // // self.pageSelectTool.append(el); // // pages--; // } if(self.tagCount<self.maxTags){ for(i in self.manifest.tags){ if(self.manifest.tags[i]){ self.showTags.push(self.manifest.tags[i].n); self._addItem(self.manifest.tags[i]); self._createListItem(); start++; } } } else { //can show the tags that we added - some of them self.showTags=[]; var amount=(self.maxTags-self.logInsertPoint.children("div").length); var start=(self.tagCount-amount>0)?(self.tagCount-amount):0; for(i in self.manifest.tags){ if(self.manifest.tags[i]){ if(start==parseInt(self.manifest.tags[i].n,10)){ self.showTags.push(parseInt(self.manifest.tags[i].n,10)); self._addItem(self.manifest.tags[i]); self._createListItem(); start++; } } } } self._reOrderPages(); //user paginates to the next series of tags in order to see these added //tags } }, //after an object is set in the logInsertPoint area, //logbar needs to check if that object goes beyond the current page //of tags _overFlowHandle:function(){ var self=this; var next=0; var ok=0; if((self.logInsertPoint.children("div.tag").length+self.logInsertPoint.children("div.group").length)>=self.maxTags){ //gone over the limit self.logInsertPoint.empty(); self.showTags=[]; //add a new page or create pages self._reOrderPages(); var t=Math.ceil(self.tagCount/self.maxTags); var tm=self.tagCount-(self.tagCount-((t-1)*self.maxTags)); for(i in self.manifest.tags){ if(tm==parseInt(self.manifest.tags[i].n,10)){ self.showTags.push(parseInt(self.manifest.tags[i].n,10)); self._addItem(self.manifest.tags[i]); self._createListItem(); tm++; } } // for(s in self.manifest.tags){ // if(ok==0){ // next++; // if(next==(self.tagCount-1)){ // ok=1; // } // }else{ // self.showTags.push(self.manifest.tags[s].n); // self._addItem(self.manifest.tags[s]); // // if(!self.manifest.tags[s].o){ // // self._addItem(self.manifest.tags[s]); // // } else { // // self.manifest.tags[s].cur.appendTo(self.logInsertPoint); // // } // ok++; // if(ok==self.maxTags) break; // //next.push(self.manifest.tags[s].cur._copy.DOM); // } // } } // else { // //we're ok - add away // self.showTags.push(obj.n); // self._addItem(obj); // } }, //takes the amount of current tags (tagCount), then //divides by MaxTags, this new amount is how many option //tags are put in the pageSelect area _reOrderPages:function(){ var self=this; var totalp=Math.ceil(self.tagCount/self.maxTags); self.pageSelectTool.children(".pageChoice").remove(); for(i=1;i!=totalp;i++){ var el=$("<option class=\"pageChoice\">"+(i)+"</option>"); self.pageSelectTool.append(el); } self.pageSelectTool.children(".pageChoice:last-child")[0].selected=true; }, //called by paginateTo custom event //@p is the integer value for which set of tags to go to _paginateToHandle:function(e,p){ var self=e.data.obj; self.showTags=[]; var t=Math.floor((p*self.maxTags)); var mt=(t-self.maxTags); self.logInsertPoint.animate({opacity:0.25},200,function(){ self.logInsertPoint.empty(); self.logInsertPoint.append("<p>Loading...</p>"); for(i in self.manifest.tags){ if(self.manifest.tags[i]){ //see which ones belong to this set var item=self.manifest.tags[i]; var count=parseInt(item.n,10); if((count>mt)&&(count<t)){ self.showTags.push(count); self._addItem(item); self._createListItem(); } } } self.logInsertPoint.children("p").remove(); self.logInsertPoint.animate({opacity:1},200); }); }, _paginate:function(dir){ var self=this; //dir is either 1 or -1 var start=parseInt($("#pageSelect > option:selected").text(),10); if(!start) start=1; if(dir<0){ //go back if(start!=1) start--; // var start=self.showTags[0]; // start=start-self.maxTags; // if(start<0) return; // var end=self.showTags[0]; // } else if(dir>0){ //go forward if(start!=Math.ceil(self.tagCount/self.maxTags)) start++; // var start=self.showTags[(self.showTags.length-1)]; // if(start>self.tagCount) return; // var end=((start+self.maxTags)>self.tagCount)?self.tagCount:(start+self.maxTags); } self.pageSelectTool.children("option").each(function(n,o){ if(start==parseInt($(o).text(),10)){ $(o)[0].selected=true; $(o).trigger("paginateTo",[parseInt($(o).text(),10)]); } }); }, addTag:function(id){ var self=this; //id refers to a string representing the id in the tag rules // var T=null; //find matching uid in rules for(i in self.rules.tags){ if(self.rules.tags[i].uid==id){ T=self.rules.tags[i]; break; } } // var logtag=new TileLogTag({ // loc:self.logActiveArea.attr('id'), // copyloc:self.logInsertPoint.attr('id'), // tagRules:self.rules, // tagId:id, // html:self.html // }); var _d=new Date(); var uid="t"+_d.getTime("milliseconds"); //create empty object - created later in _addItem var l={ o:null, uid:uid, act:null, cur:null, html:self.html, type:'schema', tagId:id, n:self.tagCount }; // self.manifest.tags[l.uid]={o:logtag,act:logtag.DOM,cur:logtag._copy.DOM,type:'schema',n:self.tagCount}; self.emptytags[l.uid]=l; self.tagCount++; //add item or correct loglist space self.showTags.push(l.n); self._addItem(l); }, //for when a user is prompted to create a shape - shape is created and user //has to adjust its position addBlankShape:function(){ var self=this; var _d=new Date(); //create blank shape object to be passed var s={ con:"rect", uid:"s"+_d.getTime("milliseconds"), x:0, y:0, width:0.1, height:0.1, args:[0,0,0.1,0.1], uri:$("#srcImageForCanvas").attr("src") }; //send shape to drawer //$("body").trigger("VD_ADDSHAPE",[[s],{}]); }, addShape:function(shape,args){ var obj=this; var l=null; //must be a new shape if(!obj.manifest.tags[shape.id]){ l={ uid:shape.id,name:"shape_"+shape.id,html:obj.html.tagshape,cur:null,o:null,act:null,etc:(obj.etc||null),type:'shape',shape:shape,n:obj.tagCount }; //add to master manifest obj.emptytags[shape.id]=l; obj.tagCount++; if(l.etc&&l.etc.groups){ for(g in l.etc.groups){ var guid=l.etc.groups[g]; if(!self.manifest.tags[guid]){ self.emptytags[guid]={ cur:null, o:null, uid:guid, html:self.html.taggroup, type:'group', group:null, etc:[l.uid], n:self.tagCount }; self.tagCount++; } else { self.emptytags[guid].etc.push(l.uid); } } } } //add item or correct loglist space obj.showTags.push(l.n); obj._addItem(l); }, //can add an optional name parameter - Group is given this name addGroup:function(args){ if(args){ var groupname=(args.name||null); var guid=(args.uid||null); } var l=null; if(this.rules){ //close all other groups // for(g in this.manifest.groups){ // this.manifest.groups[g].o.setCloseState(); // } if(groupname) groupname+=$(".groupname > input:contains("+groupname+")").length; // l=new TileLogGroup({ // loc:this.logInsertPoint.attr("id"), // html:this.html.taggroup, // name:(groupname||null), // uid:(guid||null) // }); var _d=new Date(); l={ o:null, cur:null, html:this.html.taggroup, uid:(guid||"g"+_d.getTime("milliseconds")), type:'group', etc:[], n:this.tagCount }; this.tagCount++; //this.GroupId=l.uid; //make the JSON data associated with group this.emptytags[l.uid]=l; } //add item or correct loglist space this.showTags(l.n); this._addItem(l); }, addTranscript:function(item,args){ var self=this; if(this.rules){ var _d=new Date(); var uid="t"+_d.getTime("milliseconds"); var l={ o:null, act:null, cur:null, html:self.html.tagtranscript, type:'transcript', n:self.tagCount, etc:(args&&args.etc)?args.etc:{"text":"Blank"}, uid:uid }; //add to master manifest self.emptytags[l.uid]=l; self.tagCount++; if(l.etc&&l.etc.groups){ for(g in l.etc.groups){ var guid=l.etc.groups[g]; if(!self.manifest.tags[guid]){ self.emptytags[guid]={ cur:null, o:null, uid:guid, html:self.html.taggroup, type:'group', group:null, etc:[l.uid], n:self.tagCount }; self.tagCount++; } else { self.emptytags[guid].etc.push(l.uid); } } } self.showTags.push(l.n); self._addItem(l); } }, initTagRules:function(e,rules){ var obj=e.data.obj; //store rules - if already present, erase all log items and start over //TODO: finalize this action if(obj.rules){ obj.clearLogItems(); } obj.rules=rules; $("body").unbind("tagRulesSet",obj.initTagRules); }, restart:function(){ this.clearLogItems(); this.rules=null; }, _saveP:function(e){ e.preventDefault(); var self=e.data.obj; self._log.bundleData(); //if(!self._saveObj) self._saveObj=new Save({loc:"azglobalmenu"}); //get all the logbar items' data // var jsondata=self.bundleData(); // jsondata.images=URL_LIST; // for(g in jsondata.images){ // if(jsondata.images[g].transcript){ // for(_t in jsondata.images[g].transcript){ // jsondata.images[g].transcript[_t]=jsondata.images[g].transcript[_t].replace("'",""); // } // } // } // self.DOM.trigger("JSONreadyToSave",[jsondata]); //var saveDiv=$("<iframe id=\"__saveP\" src=\"PHP/forceJSON.php\" style=\"display:none;\"></iframe>").appendTo("body"); //output as attachment //self._saveObj.userPrompt(jsondata); }, //wrap all log items (shapes, groups, transcripts, tags) into a JSON object bundleData:function(){ var self=this; var j={"tags":[],"groups":[]}; for(f in self.manifest.tags){ if(self.manifest.tags[f]){ var obj=self.manifest.tags[f]; if(obj.o){ //get recent data from object obj.etc=obj.o.etc; if(obj.etc.text) obj.etc.text=obj.etc.text.replace("'","apos"); obj.name=obj.o.name.replace("'","apos"); } $.map(["region","html","o","cur","act"],function(o,i){ if(o in obj) obj[o]=null; }); //add to appropriate division if(obj.type=='group'){ j.groups.push(obj); } else { j.tags.push(obj); } } } return j; }, clearLogItems:function(){ var self=this; $.each(self.manifest,function(i,x){ $(x.cur).remove(); }); //$(".logitem").remove(); } }); TILE.TileLogBar=TileLogBar; /** Log Item Object that handles one instance of a logged event in the main workspace area Can be given an ID in order to 'copy' another object - can do this using uid: {string} parameter **/ var LogItem=Monomyth.Class.extend({ init:function(args){ if(!args.html) throw "no JSON data passed to LogItem{}"; this.loc=args.loc; this.html=args.html; if(this.loc) $(this.html).appendTo($("#"+this.loc)); var d=new Date(); this.uid=(args.uid)?args.uid:"logitem_"+d.getTime('milliseconds'); //optional tag type attribute if(args.type){ this._type=args.type; } } }); TILE.LogItem=LogItem; var TagCopy=LogItem.extend({ init:function(args){ this.$super(args); var self=this; self.uid=args.uid+"copy"; self.DOM=$("#"+self.loc+" > #empty"+args.type); self.DOM.attr("id",self.uid); self.name =(args.name||self.uid); //disable input elements or any clickable options $("#"+this.DOM.attr('id')+" > div.tagname > div.tagmenu > div:not(.menuitem)").remove(); $("#"+this.DOM.attr('id')+" > div.tagname > input").remove(); $("#"+this.DOM.attr('id')+" > div.tagname > p").text(self.name); switch(args.type){ case 'transcript': $("#"+self.uid+" > div.tagcontent > p").show(); $("#"+self.uid+" > div.tagcontent > form").remove(); break; case 'shape': self.shapeIcon=$("#"+this.DOM.attr('id')+" > div.tagname > div.tagmenu > div.menuitem > span.btnIconLarge.poly"); if(args.shape) { self.shapeIcon.removeClass("poly").addClass(args.shape.type); } break; case 'schema': $("#"+this.DOM.attr('id')+" > div.tagcontent > div.tagattr").remove(); //$("#"+this.DOM.attr('id')+" > div.tagcontent > div.tagattr > .nameValue > .button").hide(); break; } //universal items self.collapseIcon=$("#"+self.DOM.attr('id')+" > div.tagname > a.open.btnIcon").show(); self.contentArea=$("#"+self.DOM.attr('id')+" > div.tagcontent").show(); var tid=self.uid.replace("copy",""); //set up listener for when tag copy is selected $("#"+self.DOM.attr("id")+" > .tagname > *:not(> .tagmenu > .menuitem > .btnIconLarge.hand)").click(function(e){ //tell logbar to open this up in active window $(this).trigger("tagSelected",[tid]); $("#"+self.loc+" > div").removeClass("selected"); self.DOM.addClass("selected"); }); //set collapse icon listeners self.collapseIcon.click(function(e){ e.stopPropagation(); if(self.contentArea.css("display")=="block"){ self._collapse(); } else { self._uncollapse(); } }); }, _draggDrop:function(){ //all copy tags are in list and therefore draggable and droppable var self=this; self.DOM.draggable({ handle:$("#"+self.DOM.attr('id')+" > div.tagname > div.menuitem > span.btnIconLarge.hand"), axis:'y', revert:true }); }, _collapse:function(){ var self=this; //$("#"+self.DOM.attr('id')+" > div.tagcontent").hide(); self.collapseIcon.removeClass("open").addClass("closed"); self.contentArea.hide(); }, _uncollapse:function(){ var self=this; self.contentArea.show(); self.collapseIcon.removeClass("closed").addClass("open"); }, updateCopy:function(e){ var self=e.data.obj; self.name=$("#"+self.uid+" > div.tagname > p").text(); // for(o in updates){ // if($("#"+self.DOM.attr('id')+" > "+o).length){ // $("#"+self.DOM.attr('id')+" > "+o).html(updates[o]); // } // } // self.transContent=$("#"+self.DOM.attr('id')+" > div.tagcontent > p"); // //adjust and hide any editable elements // $("#"+self.DOM.attr('id')+" > div.tagcontent > div.tagattr > .nameValue > .button").hide(); //schema-defined tags // $("#"+self.DOM.attr('id')+" > div.tagcontent > div.tagattr > .nameValue > select").hide(); //schema-defined tags } }); var TileLogShape=LogItem.extend({ init:function(args){ this.$super(args); //using optional type attr this.type='shape'; //is this a clone? this.isClone=(args.isClone)||false; var self=this; self.groups=[]; self.copyloc=args.copyloc; self.etc=(args.etc)?args.etc:[]; self.shape=args.shape; self.shapeId=self.shape.id; if(args.uid) self.uid=args.uid; self.DOM=$("#emptyshape").attr("id",self.uid).addClass("selected"); // $("div.tag.shape").each(function(a){ // if(!$(this).attr("id")){ // self.DOM=$(this); // self.DOM.attr("id",self.uid); // // } // }); //active state - just added, so set class to "selected" // $("#"+self.loc+" > .tag").removeClass("selected"); // $("#"+self.loc+" > .tag").hide(); // self.DOM.addClass("selected").show(); //set up the collapse-icon behavior self.collapseIcon=$("#"+self.DOM.attr('id')+" > .tagname > a.btnIcon").hide(); self.shapeIcon=$("#"+self.DOM.attr('id')+" > div.tagname > div.tagmenu > div.menuitem > span.btnIconLarge.poly"); //configure the name for this log item self.name=(args.name)?args.name:"Shape_"+self.shapeId; self.shapeName=$("#"+self.DOM.attr('id')+" > div.tagname > p.shapename").attr("id",self.DOM.attr('id')+"_shapeName"); self.shapeName.text(self.name); self.shapeName.css("display","inline-block"); self.inputTitle=$("#"+self.DOM.attr('id')+" > div.tagname > input").attr("id",self.DOM.attr('id')+"_titleInput"); self.inputTitle.val(self.name); self.inputTitle.blur(function(e){ $(this).trigger("setSInput"); }); self.shapeSpan=$("#"+self.DOM.attr("id")+" > div.tagcontent > ul"); //fill in elements self.shapeName.hide(); self.handleShapeIcon(); self.setShapeObj(); self.clones=[]; //set up listeners $("#"+self.DOM.attr('id')+" > .tagname").click(function(e){ $(".tag.shape").removeClass("selected"); $(this).addClass("selected"); self.itemSelectedHandle(); }); self.shapeName.click(function(e){ $(this).parent().children("input").val($(this).text()); $(this).parent().children("input").show(); $(this).hide(); }); //local self.DOM.bind("setSInput",{obj:self},self.setName); //this._dragg(); //self.DOM.trigger("shapeDisplayChange",["a",self.shape.id]); $("body:first").trigger("_showShape",[self.shape.id]); }, /** Based on what the shape's type is, pick the right background style for the shape icon area **/ handleShapeIcon:function(){ switch(this.shape.type){ case 'rect': this.shapeIcon.removeClass('poly').addClass('rect'); break; case 'ellipse': this.shapeIcon.removeClass('poly').addClass("elli"); break; } }, _dragg:function(){ //make the entire DOM draggable - must be dropped into a Group if(!this.isClone){ this.DOM.draggable({ handle:'#'+this.DOM.attr('id')+' > menuitem > div.btnIconLarge.hand', revert:true, axis:'y' }); } }, //happens when user selects this shape itemSelectedHandle:function(){ var self=this; $("body").trigger("_showShape",[self.shape.id]); }, setEdit:function(){ if(this.editSelect){ var self=this; // self.editSelectB.click(function(e){ // $(this).hide(); // $(this).parent().children("select").click(); // }); // self.editSelect.blur(function(e){ // $(this).parent().children("span").show(); // }); //setup function to handle custom even itemMenuSelect call self.DOM.bind("itemMenuSelect",{obj:self},self.menuHandle); self.groupSelect.children().each(function(i,n){ $(this).click(function(e){ if(self.isClone&&(($(this).text().toLowerCase()=="edit")||($(this).text().toLowerCase()=="delete"))){ $(this).trigger("itemMenuSelect",[$(this).text()]); } else { $(this).trigger("itemMenuSelect",[$(this).text()]); } }); }); if(self.isClone){ self.inputTitle.hide(); self.shapeName.text(self.inputTitle.val()).show(); self.editSelect.css({"top":"0px"}); //change items if a clone self.editSelect.children().each(function(i,o){ if(($(o).text().toLowerCase()!="edit")||($(o).text().toLowerCase()!="delete")){ $(o).remove(); } }); } //when user inputs a name and clicks away, input goes away self.inputTitle.blur(function(e){ $(this).hide(); $(this).parent().children("p").text($(this).val()).show(); }).keypress(function(e){ if(e.keyCode==13){ $(this).hide(); $(this).parent().children("p").text($(this).val()).show(); } }); } }, //user clicked outside of input area setName:function(e){ var obj=e.data.obj; obj.shapeName.show().text(obj.inputTitle.val()); obj.inputTitle.hide(); // obj.DOM.trigger("tagUpdate",[{".tagname > p.shapename":obj.shapeName.html()}]); }, _tagUpdate:function(){ var obj=this; obj.shapeName.text(obj.inputTitle.val()); obj.name=obj.shapeName.text(); //update any and all copies of this $("#"+obj.uid+"copy > .tagname > p.shapename").text(obj.shapeName.text()); $("#"+obj.uid+"copy > .tagname > .tagmenu > .menuitem > span.btnIconLarge.poly").removeClass("poly").addClass(obj.shape.con); //show that we're not selected anymore $("#"+obj.loc+" > div").removeClass("selected"); }, menuHandle:function(e,m){ //m refers to which option the user chose var obj=e.data.obj; switch(m.toLowerCase().replace(" ","")){ case 'edit': obj.editShape(); break; case 'delete': obj.delItem(); break; case 'addtogroup': break; } }, editShape:function(){ var self=this; self.shapeName.hide(); self.inputTitle.val(self.shapeName.text()).show(); }, setShapeObj:function(){ var self=this; if(self.shapeSpan.children().length>0) self.shapeSpan.empty(); self.shapeSpan.append($("<li><span class=\"attrbname\">scale</span>: <span class=\"attrb\">"+self.shape.scale+"</span></li>")); // $.map(["scale","width","height","x","y","cx","cy","rx","ry","points"],function(v){ // if(v in self.shape){ // self.shapeSpan.append($("<li><span class=\"attrbname\">"+v+"</span>: <span class=\"attrb\">"+self.shape[v]+"</span></li>")); // } // }); for(i in self.shape.posInfo){ self.shapeSpan.append($("<li><span=\"attrbname\">"+i+":</span> <span class=\"\">"+self.shape.posInfo[i]+"</span></li>")); } }, //called whenever shapeChangeCall from shape is triggered //supposed to be during resize and dragging of shape shapeChangeHandle:function(e,_newShape){ var obj=e.data.obj; //make _newShape the current shape - overwrite old obj.shape=_newShape; var self=obj; //update information in shapeSpan self.shapeSpan.empty(); var liarray=[]; $.map(["scale","width","height","x","y","cx","cy","rx","ry"],function(v){ if(v in self.shape){ var d=$("<li><span class=\"attrbname\">"+v+"</span>: <span class=\"attrb\">"+self.shape[v]+"</span></li>"); liarray.push(d); self.shapeSpan.append(d); self.etc[v]=self.shape[v]; } }); //update all clones - if any for(o in self.clones){ //if user hasn't edited the clone's shape - then it still //should listen to changes in this shape if(self.clones[o].isClone){ var s=self.clones[o]; s.shapeSpan.empty(); for(li in liarray){ s.shapeSpan.append(liarray[li].clone()); } } } //update copies //self.DOM.trigger("tagUpdate",[{".tagcontent > ul":$("#"+self.DOM.attr('id')+" > .tagcontent > ul").html()}]); }, // Used to create a 'copy' of this object to be passed // to a group object clone:function(nloc){ var self=this; if($.inArray(nloc,self.groups)>-1){ return false; } self.groups.push(nloc); //make new id var n=$("div[id*="+this.DOM.attr('id')+"copy]").length; //how many other divs are copied? var id=this.DOM.attr('id')+"copy"+n; var self=this; //add shape object var clone=new TileLogShape({ uid:id, shape:self.shape, html:self.html, loc:nloc, isClone:true }); //$("body").unbind(self.shape.shapeChangeCall); //$("body").bind(self.shape.shapeChangeCall,{obj:self},self.shapeChangeHandle); //add to clone array self.clones.push(clone); return clone; }, delItem:function(){ //notify drawer that this shape is deleted from logbar $(this.shape.cur.node).trigger("VD_REMOVESHAPE",[this.shape.id]); this.DOM.remove(); }, _open:function(){ var self=this; $("#"+self.loc+" > .tag").hide().removeClass("selected"); self.DOM.show().addClass("selected"); $("body").trigger("shapeDisplayChange",["a",self.shapeId]); }, _close:function(){ var self=this; } }); var TileLogGroup=LogItem.extend({ init:function(args){ this.$super(args); var self=this; //adjust name/uid if provided by user self.type='group'; self.uid=(args.uid)?args.uid:self.uid; self.DOM=$("#emptygroup").attr("id",self.uid); //adjust height of parent // $("#"+self.loc).height($("#"+self.loc).height()+self.DOM.height()); // $("div.group").each(function(d){ // if($(this).attr("id")==""){ // self.DOM=$(this); // //self.DOM.removeClass("logitem").addClass("loggroup"); // $(this).attr("id","g"+d); // } // }); // if(args.uid) { // self.uid=args.uid; // self.DOM.attr("id",self.uid); // } self.name=(args.name||"Group"+self.uid); //toggle for display name self.nameToggle=$("#"+self.DOM.attr("id")+" > div.groupname > a").click(function(e){ $(this).trigger("setClose"); }); //display for group name self.groupNameSpan=$("#"+self.DOM.attr("id")+" > div.groupname > span").text(self.name).hide();// .click(function(e){ // $(this).hide(); // $(this).parent().children("input").show(); // }); // this.groupNameSpan.hide(); //input for making group name self.groupNameInput=$("#"+self.DOM.attr("id")+" > div.groupname > input").blur(function(e){ // $(this).hide(); // $(this).parent().children("span").text($(this).val()).show(); }).keydown(function(e){ //also handle when user presses 'enter' if(e.keyCode==13) { $(this).hide(); $(this).parent().children("span").text($(this).val()).show(); } }); $("#"+self.DOM.attr("id")+" > .groupname > a").remove(); // self.collapseIcon=$("#"+self.DOM.attr("id")+" > .groupname > a").click(function(e){ // if($(this).closest("div.group").children(".grouplist:visible").length){ // $(this).closest("div.group").children(".grouplist:visible").hide(); // } else { // $(this).closest("div.group").children(".grouplist:hidden").show(); // // } // }); self.groupNameInput.val(self.groupNameSpan.text()); self.dropInsertArea=$("#"+self.DOM.attr('id')+" > div.grouplist").attr('id',(self.uid+"gdrop")); self._dropp(); //for storing data to be passed on in JSON format self.etc=(args.etc)?args.etc:{"tags":[]}; if(self.etc){ for(o in self.etc){ self._loadItem(self.etc[o]); self.etc[o]=self.etc[o].uid; } } //local listeners //bind for toggle display edit //this.DOM.bind("toggleNameEdit",{obj:this},this.toggleNameEditHandle); self.DOM.bind("setClose",{obj:self},self.setClosedState); self.DOM.bind("setOpen",{obj:self},self.setOpenState); self.DOM.bind("removeItem",{obj:self},self.removeItem); }, _dropp:function(){ var self=this; //not draggable - in logbar active area by itself $("#"+self.DOM.attr("id")+" > .groupname > .menuitem > .btnIconLarge.hand").remove(); // self.DOM.draggable({ // axis:'y', // handle:$("#"+self.DOM.attr("id")+" > .groupname > .menuitem > .btnIconLarge.hand"), // revert:true // }); self.DOM.droppable({ addClasses:false, drop:function(e,o){ e.preventDefault(); $(this).droppable("disable"); $(this).trigger("itemDropped",[$(o.draggable).attr('id'),self.uid]); } //this.addItem }); //change initial height so area is more droppable //figure out height difference $("#"+self.DOM.attr("id")+" > div.groupname").css({"overflow":"none"}); self.DOM.css("overflow","none").height(120); self.dropInsertArea.height(self.DOM.height()-$("#"+self.DOM.attr("id")+" > div.groupname").height()); //this.DOM.height(120).css("overflow","auto"); }, //handles event when user clicks on nameToggle toggleNameEditHandle:function(e){ var obj=e.data.obj; obj.groupNameSpan.hide(); obj.groupNameInput.val(obj.groupNameSpan.text()).show(); }, setOpenState:function(e){ var obj=e.data.obj; obj.DOM.height(120).css("overflow","auto"); obj.groupNameInput.val(obj.groupNameSpan.text()).show(); obj.groupNameSpan.hide(); obj.nameToggle.removeClass("closed").addClass("open"); //switch out the click command for nameToggle obj.nameToggle.unbind("click"); obj.nameToggle.click(function(e){ $(this).trigger("setClose"); }); //inform logbar which group is open obj.DOM.trigger("logGroupOpen",[obj.uid]); //change initial height so area is more droppable //figure out height difference $("#"+obj.DOM.attr("id")+" > div.groupname").css({"overflow":"none"}); var th=0; $("#"+obj.DOM.attr("id")+" > div.tag").each(function(i,o){ th+=$(o).height(); }); obj.DOM.css("overflow","none").height(((th==0)?120:th)); obj.dropInsertArea.height(obj.DOM.height()-$("#"+obj.DOM.attr("id")+" > div.groupname").height()); }, setCloseState:function(){ //does the same thing as setClosedState but isn't called by CustomEvent this.nameToggle.removeClass("open").addClass("closed"); this.groupNameSpan.show(); this.groupNameSpan.text(this.groupNameInput.val()); this.groupNameInput.hide(); this.DOM.height($("#"+this.DOM.attr('id')+" > div.groupname").height()); this.nameToggle.unbind('click'); //switching out the trigger for nameToggle this.nameToggle.click(function(e){ $(this).trigger("setOpen"); }); }, setClosedState:function(e){ var obj=e.data.obj; obj.nameToggle.removeClass("open").addClass("closed"); obj.groupNameSpan.show(); obj.groupNameSpan.text(obj.groupNameInput.val()); obj.groupNameInput.hide(); obj.DOM.height($("#"+obj.DOM.attr('id')+" > div.groupname").height()); obj.nameToggle.click(function(e){ $(this).trigger("setOpenState"); }); //change out the click event for nameToggle obj.nameToggle.unbind("click"); obj.nameToggle.click(function(e){ $(this).trigger("setOpen"); }); //event called by user and not logbar - notify logbar obj.DOM.trigger("logGroupClosed",[obj.uid]); }, //called by parent Object - //@item {Object} - whatever tag Object is given to attach to DOM pushItem:function(item){ //push html onto the DOM - if not already present // if($("#"+this.DOM.attr('id')+" > #"+(item.DOM.attr('id')+"copy")).length){ // return; // } else { var self=this; if(!item){ return; } if(self.etc[item.uid]) { return; } if(item.type=='group'){ // var copy=new GroupCopy({ // loc:self.dropInsertArea.attr("id"), // name:item.name, // html:"<div id=\"emptygroup\" class=\"group\">"+item.DOM.html()+"</div>", // uid:item.uid // }); if($.inArray(item.uid,self.etc)<0) self.etc.push(item); } else { // var copy=new TagCopy({ // loc:self.dropInsertArea.attr("id"), // name:item.name, // html:item.html, // type:item.type, // uid:item.uid // }); if($.inArray(item.uid,self.etc)<0) self.etc.push(item); } }, //display all items in etc _showList:function(){ var self=this; for(i in self.etc){ var item=self.etc[i]; if(!item) continue; if(item.type&&($("#"+self.dropInsertArea.attr("id")+" > #"+item.uid+"copy").length==0)) { if(item.type=='group'){ var copy=new GroupCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:"<div id=\"emptygroup\" class=\"group\">"+item.DOM.html()+"</div>", uid:item.uid }); self.etc[i]=item.uid; } else { var copy=new TagCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:item.html, type:item.type, uid:item.uid }); self.etc[i]=item.uid; } } } }, _loadItem:function(item){ var self=this; if(!item){ return; } if(item.type=='group'){ var copy=new GroupCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:item.html, uid:item.uid }); } else { var copy=new TagCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:item.html, type:item.type, uid:item.uid }); } }, removeItem:function(e,id){ var obj=e.data.obj; //remove an item from the group - doesn't effect original //TODO: make prompts to user obj.etc=$.grep(obj.etc,function(o,n){ return (o!=id); }); $("#"+id).remove(); }, _tagUpdate:function(){ var self=this; self.name=self.groupNameInput.val(); if(self.name=="") self.name=self.uid; self.groupNameSpan.text(self.name); //update all copies of this $("#"+self.uid+"copy > .groupname > span").text(self.name); $("#"+self.uid+"copy > .groupname > span").trigger("tagUpdate"); //$("body").trigger("tagUpdate",[{".groupname > span":self.groupNameSpan.html()}]); //show that we're not selected anymore $("#"+self.loc+" > div").removeClass("selected"); } }); var GroupCopy=Monomyth.Class.extend({ init:function(args){ var self=this; self.loc=args.loc; self.html=args.html; self.uid=args.uid+"copy"; $("#"+self.loc).append($(self.html)); self.DOM=$("#"+self.loc+" > #emptygroup").attr("id",self.uid); $("#"+self.uid+" > .grouplist").remove(); //remove input from name $("#"+self.uid+" > .groupname > input").remove(); $("#"+self.uid+" > .groupname > span").text(args.name); self.DOM.click(function(e){ $(this).trigger("tagSelected",[self.uid.replace("copy","")]); }); self._dropp(); }, _dropp:function(){ var self=this; //also draggable self.DOM.draggable({ axis:'y', handle:$("#"+self.DOM.attr("id")+" > .groupname > .menuitem > .btnIconLarge.hand"), revert:true }); self.DOM.droppable({ addClasses:false, drop:function(e,o){ e.preventDefault(); $(this).trigger("itemDropped",[$(o.draggable).attr('id'),self.uid.replace("copy","")]); } //this.addItem }); }, _tagUpdateHandle:function(e,args){ var self=e.data.obj; self.name=$("#"+self.uid+" > .groupname > span").text(); }, _loadItem:function(item){ var self=this; if(!item){ return; } if(item.type=='group'){ var copy=new GroupCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:item.html, uid:item.uid }); } else { var copy=new TagCopy({ loc:self.dropInsertArea.attr("id"), name:item.name, html:jsonTags[item.type], type:item.type, uid:item.uid }); } } }); /** TranscriptTag **/ var TileTranscriptTag=LogItem.extend({ init:function(args){ this.$super(args); var self=this; self.copyloc=args.copyloc; self.type='transcript'; self.groups=[]; if(args.uid) self.uid=args.uid; self.isClone=(args.isClone)||false; self.DOM=$("#emptytranscript").attr("id",self.uid); // $("div.tag.transcript").each(function(e){ // if($(this).attr("id")==""){ // self.DOM=$(this).attr("id","t"+self.uid); // } // }); self.DOM.addClass("selected").show(); //get elements - hide elements that don't exist in main logbar activearea $("#"+self.DOM.attr('id')+" > div.tagname > a.btnIcon").hide(); this.name=(args.name)?args.name:"Transcript"+$("#"+self.loc+" > .tag.transcript").length; this.transName=$("#"+this.DOM.attr('id')+" > div.tagname > p.transname").text(this.name).css("display","inline-block").hide(); this.transNameInput=$("#"+this.DOM.attr('id')+" > div.tagname > input").val(this.transName.text()).show(); this.transDisplay=$("#"+this.DOM.attr('id')+" > div.tagcontent > p.transcript").hide(); this.menuSelectB=$("#"+this.DOM.attr('id')+" > div.tagname > div.tagmenu > #ddown > div.menuitem.ddown > span").show(); this.menuSelect=$("#"+this.DOM.attr('id')+" > div.tagname > div.tagmenu > #ddown > div.menuitem.ddown > select").attr("id","ddown_"+this.uid); this.txtArea=$("#"+this.DOM.attr('id')+" > div.tagcontent > form > textarea"); this.etc=(args.etc)?args.etc:{"text":this.txtArea.val()}; this.txtArea.val(this.etc.text); this.transDisplay.text(this.etc.text); //this.setEdit(); ///local listeners this.DOM.bind("deleteTranscript",{obj:this},this.eraseTranscript); this.DOM.bind("doneTranscript",{obj:this},this.doneTranscriptHandle); this.DOM.click(function(e){ $(this).removeClass("inactive").addClass("active"); }); }, _dragg:function(){ this.DOM.draggable({ handle:'#'+this.DOM.attr('id')+' > div.menuitem > div.btnIconLarge.hand', axis:'y', revert:true }); }, setEdit:function(){ if(this.menuSelect){ var self=this; //define layout variables for drop down // self.heights=[self.menuSelect.height()+8]; // self.startingHeight=21; // self.speed=300; // //make visible // // self.menuSelect.css({visibility:"visible","z-index":"1000"}).height(self.startingHeight); // // //setting up the stylized drop down menu // self.menuSelect.mouseover(function () { // $(this).stop().animate({height:self.heights[0]},{queue:false, duration:self.speed}); // }); // self.menuSelect.mouseout(function () { // $(this).stop().animate({height:self.startingHeight+'px'}, {queue:false, duration:self.speed}); // }); //setup click function to show menuSelect self.menuSelectB.click(function(e){ $(this).hide(); self.menuSelect.click(); }); //setup function to handle custom even itemMenuSelect call this.DOM.bind("itemMenuSelect",{obj:this},this.menuHandle); this.menuSelect.children().each(function(i,n){ $(this).click(function(e){ if(i==0) $(this).select(); $(this).trigger("itemMenuSelect",[$(this).text()]); }); }); //change items if a clone if(self.isClone){ self.menuSelect.children().each(function(i,o){ if(($(o).text().toLowerCase()!="edit")||($(o).text().toLowerCase()!="delete")){ $(o).remove(); } }); } } }, menuHandle:function(e,m){ //m refers to which option the user chose var obj=e.data.obj; switch(m.toLowerCase().replace(" ","")){ case 'edit': obj.editTranscript(); break; case 'delete': obj.delItem(); break; case 'addtogroup': break; } }, editTranscript:function(){ //open up text area to edit - limit chars //hide the text display area this.transDisplay.hide(); this.txtArea.parent().show(); this.txtArea.val(this.transDisplay.text()); this.transName.hide(); this.transNameInput.val(this.transName.text()).show(); }, eraseTranscript:function(e){ //user clicked on the Delete button from the transcript area var obj=e.data.obj; obj.txtArea.val(""); }, //when user clicks 'Done', logbar carries out its functions, //transcript finishes its own _tagUpdate:function(){ var obj=this; //user clicked on the 'done' button //hide the transcript editing area and display text from txtarea obj.transDisplay.text(obj.txtArea.val()); obj.transName.text(obj.transNameInput.val()); obj.name=obj.transName.text(); if(obj.name=="") obj.name=obj.uid; obj.etc.text=obj.txtArea.val(); //now change all of the copies of this transcript that may //exist inside groups $("#"+obj.DOM.attr("id")+"copy > .tagname > p").html($("#"+obj.DOM.attr('id')+" > .tagname > p").html()); $("#"+obj.DOM.attr("id")+"copy > .tagcontent > p").html($("#"+obj.DOM.attr('id')+" > .tagcontent > p").html()); $("#"+obj.DOM.attr("id")+"copy > .tagcontent").trigger("tagUpdate"); //$("body").trigger("tagUpdate",[{".tagcontent":$("#"+obj.DOM.attr('id')+" > .tagcontent").html()}]); //show that we're not selected anymore $("#"+obj.loc+" > div").removeClass("selected"); }, clone:function(nloc){ var self=this; if($.inArray(nloc,self.groups)>-1){ return; } self.groups.push(nloc); //make new id var n=$("div[id*="+this.DOM.attr('id')+"copy]").length; //how many other divs are copied? var id=this.DOM.attr('id')+"copy"+n; //add shape object var self=this; var clone=new TileTranscriptTag({ uid:id, html:self.html, loc:nloc, isClone:true }); return clone; }, delItem:function(){ this.DOM.remove(); }, _open:function(){ var self=this; $("#"+self.loc+" > .tag").hide().removeClass("selected"); self.DOM.addClass("selected").show(); } }); /** TileLogTag same functionality as the TileTag, but uses JSON html and loads same functionality as other LogItems parentClass: LogItem (base.js) **/ var TileLogTag=LogItem.extend({ init:function(args){ var self=this; //hack the args.html self.nvhtml=args.html.nvitem; args.html=args.html.tilelogtag; self.type='schema'; this.$super(args); self.copyloc=args.copyloc; self.isClone=(args.isClone)||false; self.tagRules=args.tagRules; self.tagId=args.tagId; //has same HTML as the TranscripTag, only without form // self.shapeId=(args.shapeId)?args.shapeId:null; self.json=(args.json)?args.json:null; self.values=(args.values)?args.values:null; if(args.uid) self.uid=args.uid; self.DOM=$("#emptyschema").attr('id',"t"+self.uid).addClass("selected"); //remove all other tags from this area $("#"+self.loc+" > div.tag:not(#"+self.DOM.attr('id')+")").hide(); //tagname self.name=self.tagId+"_"+$(".tag").length; self.nameInput=$("#"+self.DOM.attr('id')+" > div.tagname > input").val(self.name); self.nameP=$("#"+self.DOM.attr('id')+" > div.tagname > p.tagnamep").text(self.name).hide(); //collapse icon self.collapseIcon=$("#"+self.DOM.attr('id')+" > div.tagname > a").hide(); //nameInput changes when blurred or user presses enter self.nameInput.val(self.nameP.text()).blur(function(e){ $(this).hide(); $(this).parent().children("p").text($(this).val()).show(); }).keypress(function(e){ if(e.keyCode==13){ $(this).hide(); $(this).parent().children("p").text($(this).val()).show(); } }); //tagmenu self.tagMenu=$("#"+self.DOM.attr("id")+" > div.tagmenu").attr('id',self.uid+'_tagmenu'); self.setTagMenu(); //tagcontent self.tagContent=$("#"+self.DOM.attr("id")+" > div.tagcontent"); self.tagAttrInsertArea=$("#"+self.DOM.attr("id")+" > div.tagcontent > div.tagattr").attr('id',self.uid+"_tagattr"); //load in previous tags or start a new tag system self.etc={"tags":[]}; self.items=[]; self._display=true; self._edit=true; // self.titleEl=$("#tagtitle_").attr("id","tagtitle_"+self.uid); // self.titleEl.bind("click",{obj:this},function(e){ // var obj=e.data.obj; // $(this).trigger("toggleTagState",[obj.htmlindex,obj]); // }); // // self.titleElText=$("#tagtitle_"+self.htmlindex+" > span"); // self.titleElText.hide(); // self.titleElText.click(function(e){ // $(this).trigger("titleSet"); // }); // // self.titleInputArea=$("#tagTitleInput_").attr("id","tagTitleInput_"+self.uid); // self.titleInputArea.val(self.title); // self.titleInputArea.blur(function(e){ // e.preventDefault(); // $(this).trigger("titleSet"); // }); // // // self.tagDel=$("#tagdel_").attr("id","tagdel_"+self.uid); // self.tagDel.bind("click",{obj:this},self.deleteTag); // self.attrBody=$("#tagAtr_").attr("id","tagAtr_"+self.uid); // // self.editB=$("#tagedit_").attr("id","tagedit_"+self.uid); // // self.editB.bind("click",{obj:this},self.doneEdit); self._getNVRules(); self.setTitleChoices(); // self.DOM.bind("toggleTagState",{obj:this},self.toggleTagState); self.DOM.bind("titleOptionClicked",{obj:this},self.titleOptionClickHandle); self.DOM.bind("titleSet",{obj:this},self.setTitle); self.DOM.bind("nvItemChanged",{obj:self},self._updateLogBar); //constructed, notify other objects this is the active element self.DOM.trigger("tagOpen",[self.htmlindex,this]); self.DOM.trigger("activateShapeBar"); self.DOM.trigger("deactivateShapeDelete"); //global listeners //$("body").bind("shapeCommit",{obj:this},self.ingestCoordData); if(args.etc){ //preloaded tags self._loadTagAttrs(args.etc); } }, setTagMenu:function(){ var self=this; self.menuDDown=$("#"+self.tagMenu.attr('id')+" > #ddown > div.menuitem > ul").attr('id',self.uid+"_ddown"); if(self.menuDDown){ // //animation variables set here // self.startingHeight=21; // self.speed=300; // self.endHeight=self.menuDDown.height(); // self.menuDDown.css({"visibility":"visible","z-index":"1000"}).height(self.startingHeight); // // //setting up the stylized drop down menu // self.menuDDown.mouseover(function () { // $(this).stop().animate({height:self.endHeight},{queue:false, duration:self.speed}); // }); // self.menuDDown.mouseout(function () { // $(this).stop().animate({height:self.startingHeight+'px'}, {queue:false, duration:self.speed}); // }); //Make draggable self._draggable(); } else { throw "Error"; } }, _draggable:function(){ var self=this; //snaps back into place when user moves it self.DOM.draggable({ axis:'y', revert:true, handle:$("#"+self.tagMenu.attr('id')+" > div.menuitem > span.btnIconLarge.hand ") }); }, //figure out what to pass on to NV item _getNVRules:function(){ var self=this; if(self.tagRules&&self.tagId){ for(r in self.tagRules.tags){ //see if uid matches tagId if(self.tagRules.tags[r].uid==self.tagId){ self.NVRules=self.tagRules.tags[r]; break; } } } //set new name self.name=self.NVRules.name; self.nameInput.val(self.name+"_"+self.uid); self.nameP.text(self.name+"_"+self.uid); //self.DOM.trigger("tagUpdate",{".tagname":$("#"+self.DOM.attr('id')+" > div.tagname").html()}); }, _tagUpdate:function(){ var self=this; self.name=self.nameInput.val(); if(self.name=="") self.name=self.uid; self.nameP.text(self.name); $("#"+self.uid+"copy > .tagname > p").text(self.name); $("#"+self.uid+"copy > .tagname").trigger("tagUpdate"); //show that we're not selected anymore $("#"+self.uid+"copy").removeClass("selected"); }, //SET BY JSON {Object} setTitleChoices:function(){ var self=this; //set by tagRules (see init constructor) //set up selection for first-level tags //use the NameValue object to do toplevel tags - handles other values self.NV=new NVItem({ loc:self.tagAttrInsertArea.attr('id'), tagRules:self.tagRules, tagUID:self.tagId, json:self.json, tagData:self.NVRules, html:self.nvhtml }); }, _open:function(){ var self=this; $("#"+self.loc+" > .tag").hide().removeClass("selected"); self.DOM.show().addClass("selected"); $("body").trigger("shapeDisplayChange",["a",self.shapeId]); }, //NEW: load shape based solely on its ID //NOT passed a shape object, just uses this.shapeId loadJSONShape:function(){ if(this.mainRegion) this.mainRegion.destroy(); //create shape object from stored JSON data //match up data first var shape=null; for(o in this.json){ if(this.json[o].shapes){ for(sh in this.json[o].shapes){ if(this.json[o].shapes[sh].uid==this.shapeId){ shape=this.json[o].shapes[sh].points; break; } } } } if(!shape) shape=this.shapeId; this.mainRegion=new TagRegion({ loc:this.attrBody, name:"mainRegion"+this.htmlindex, shapeId:this.shapeId, shape:shape }); }, titleOptionClickHandle:function(e,id){ var obj=e.data.obj; if(id!=null){ //user has defined what title they want // obj.title=obj.items[id].title; obj._rules=obj.items[id].rules; obj.setTagAttr(); } }, //can be triggered by setTitle or called externally setTitle:function(e){ if(e){ var obj=e.data.obj; //check if titleInput is hidden or not - if class set to locked, hidden if(obj.titleInputArea.hasClass("locked")){ obj.titleElText.hide(); //open input area and set value to stored title obj.titleInputArea.removeClass("locked").addClass("edit"); obj.titleInputArea.val(obj.title); } else { obj.title=obj.titleInputArea.val().replace(/\n+\s+\t/g,"%"); obj.titleInputArea.removeClass("edit").addClass("locked"); // this.tagChoice.hide(); obj.titleElText.text(obj.title); obj.titleElText.show(); } } else { this.title=this.titleInputArea.val().replace(/\n+\s+\t/g,"%"); this.titleInputArea.removeClass("edit").addClass("locked"); // this.tagChoice.hide(); this.titleElText.text(this.title); this.titleElText.show(); } }, setTagAttr:function(){ var self=this; if(this.attrs.length>0){ $.each(this.attrs,function(i,a){ a.destroy(); }); } if(this._rules){ //this.attrs=[]; var a=new NameValue({ loc:this.attrBody, id:this.uid, rules:this._rules }); self.etc.tags.push(a.uid); //this.attrs.push(a); } }, _loadTagAttrs:function(items){ var self=this; for(it in items.tags){ var T=items.tags[it]; } }, openTagState:function(){ if(this.titleEl.hasClass("closed")){ this.titleEl.removeClass('closed').addClass('open'); //being turned back on (opening the box) this.titleInputArea.removeClass("locked").addClass("edit").val(this.titleElText.text()); this.editB.show(); this.attrBody.show(); this.titleElText.hide(); if(this.mainRegion&&this._display){ this.mainRegion.listenOn(); //obj.DOM.trigger("deactivateShapeBar"); this.DOM.trigger("activateShapeDelete"); } else if(this._display){ if(this._edit) { this.DOM.trigger("activateShapeBar"); } else { this.DOM.trigger("turnOffShapeBar"); } //obj.DOM.trigger("activateShapeBar"); //$("body").bind("shapeCommit",{obj:this},this.ingestCoordData); } else { this.DOM.trigger("turnOffShapeBar"); } } }, //closes the tag state when another tag is opened //called externally closeTagState:function(){ if(this.titleEl.hasClass("open")){ this.titleEl.removeClass("open").addClass('closed'); //if(!this.titleEl.hasClass("closed")) this.titleEl.addClass("closed"); this.editB.hide(); this.attrBody.hide(); this.setTitle(); $("body").unbind("deleteCurrentShape",this.deleteShape); // if(this.mainRegion){ // this.mainRegion.listenOff(); // } else { // //$("body").unbind("shapeCommit",this.ingestCoordData); // } this.DOM.trigger("turnOffShapeBar"); } }, toggleState:function(){ if(this.titleEl.hasClass("open")){ this.closeTagState(); } else if(this.titleEl.hasClass("closed")) { this.openTagState(); } }, newPage:function(){ //hide the DOM until the next page is loaded this.closeTagState(); this.DOM.hide(); }, //show nothing until reset - opposite is displayOn() function displayOff:function(){ this._display=false; if(this.titleEl.hasClass("open")){ this.trigger("toggleTagState",[this.DOM.attr('id'),this]); } }, //opposite is displayOff() function displayOn:function(){ this._display=true; if(!this.titleEl.hasClass("open")){ this.DOM.trigger("toggleTagState",[this.DOM.attr('id'),this]); } }, //for showing up all the shapes at once - tag doesn't open showcase:function(){ //if display is off, then it is now on this._display=true; if(this.mainRegion){ this.mainRegion.showcase(); } }, deleteTag:function(e){ if(e){ var obj=e.data.obj; if(obj.mainRegion) { obj.mainRegion.destroy(); obj.mainRegion=null; } obj.DOM.trigger("tagDeleted",[obj.htmlindex,obj]); obj.DOM.remove(); } else { this.mainRegion.destroy(); this.mainRegion=null; this.DOM.trigger("tagDeleted",[this.htmlindex,this]); this.DOM.remove(); } }, //fired when user clicks lock in 'lock' mode editTag:function(e){ var obj=e.data.obj; //display lock in 'unlock' mode obj.editB.removeClass("lock"); obj.editB.addClass("unlock"); obj.editB.unbind("click"); obj._edit=true; //display NameValue data as editable if(obj.NV) obj.NV._startEdit(); //recursive function if(obj.mainRegion){ obj.mainRegion.anchorOff(); obj.DOM.trigger("activateShapeDelete"); } else { obj.DOM.trigger("activateShapeBar",[obj.index]); obj.DOM.trigger("deactivateShapeDelete"); } obj.editB.bind("click",{obj:obj},obj.doneEdit); }, //fired when the user first clicks on the 'lock' //afterward, fired after editB is clicked in 'unlock' mode doneEdit:function(e){ //shape and all other data are now locked var obj=e.data.obj; //display 'lock' mode obj.editB.removeClass("unlock"); obj.editB.addClass("lock"); obj.editB.unbind("click"); obj.editB.bind("click",{obj:obj},obj.editTag); if(obj.NV) obj.NV._noEdit(); obj.DOM.trigger("turnOffShapeBar"); obj._edit=false; $.each(obj.attrs,function(i,a){ a.save(); }); if(obj.mainRegion){ obj.mainRegion.anchorOn(); } }, reloadListeners:function(){ // this.titleEl.bind("click",{obj:this},function(e){ // var obj=e.data.obj; // $(this).trigger("toggleTagState",[obj.index,obj]); // }); //this.DOM.bind("toggleTagState",{obj:this},this.toggleTagState); this.DOM.bind("titleOptionClicked",{obj:this},this.titleOptionClickHandle); }, //NEW: VectorDrawer Object sends out the coord data //wrapped in json-like object //Old: @shape,@coords //NEW: @shape: Associative array of shape attributes ingestCoordData:function(e,shape){ var obj=e.data.obj; if(!obj.mainRegion){ obj.shapeId=shape.id; obj.mainRegion=new TagRegion({ loc:obj.attrBody, shape:shape, name:"mainRegion"+obj.htmlindex, shapeId:obj.shapeId }); $("body").unbind("shapeCommit",obj.ingestCoordData); obj.DOM.trigger("activateShapeDelete"); } }, //OLD: called by trigger deleteCurrentShape //NEW: TabBar handles all deletes deleteShape:function(e){ if(this.mainRegion){ this.mainRegion.destroy(); this.shapeId=null; this.mainRegion=null; //$("body").unbind("deleteCurrentShape",this.deleteShape); $("body").bind("shapeCommit",{obj:this},this.ingestCoordData); this.DOM.trigger("deactivateShapeDelete"); } }, removeTag:function(){ this.closeTagState(); this.DOM.remove(); }, bundleData:function(){ //return part of JSON object //only returning values from (each) nameValue pair //var jsontag={"uid":this.htmlindex,"name":this.title,"shapeId:":(this.mainRegion)?this.mainRegion.shapeId:null}; var jsontag=[]; //TabBar already gathers other information on tag - just need to recursively return //namevalue data if(this.NV){ jsontag.push(this.NV.bundleData()); //bundleData for NameValue Obj called } // var jsontag="{"; // jsontag+="uid:"+this.htmlindex+",name:"+this.name+",shapeId:"+this.mainRegion.id+"}"; //j[1]=(this.mainRegion)?this.mainRegion.bundleData():null; return jsontag; } }); /** Name-value object to be used specifically with TILE interface Top-Level Object that generates more, sub-level name-value pairs from Rules .childNodes array **/ var TileNameValue=NameValue.extend({ init:function(args){ this.$super(args); this.parentTagId=args.parentTagId; var d=new Date(); this.uid=d.getTime(); this.htmlId=d.getTime()+"_nv"; //this.rules has to be JSON SCHEMA structure as defined by TILE specs this.DOM=$("<div></div>").attr("id",this.htmlId).addClass("nameValue").appendTo(this.loc); this.select=$("<select></select>").appendTo(this.DOM); this.changeB=$("<a>Change</a>").appendTo(this.DOM).click(function(e){$(this).trigger("NV_StartOver");}).hide(); this.topTag=null; this.items=[]; //set up enum list of tag names //rules.tags: list of top-level tags this.setUpTopLevel(); if(args.values){ this.loadPreChoice(args.values); } }, setUpTopLevel:function(){ for(t in this.rules.topLevelTags){ var uid=this.rules.topLevelTags[t]; var T=null; for(g in this.rules.tags){ if(this.rules.tags[g].uid==uid){ T=this.rules.tags[g]; break; } } if(T){ var id=$("#"+this.DOM.attr("id")+" > option").length+"_"+this.DOM.attr("id"); var o=$("<option></option>").attr("id",id).val(uid).text(T.name).appendTo(this.select); o.click(function(){ $(this).trigger("nameSelect",[$(this).val()]); }); } } this.select.bind("nameSelect",{obj:this},this.nameSelectHandle); this.loc.bind("NV_StartOver",{obj:this},this.startOverHandle); //this.loc.bind("nvItemClick",{obj:this},this.handleItemClick); }, //values from JSON tag object have been added in constructor //use args[0].values to reload the topTag loadPreChoice:function(args){ var T=null; // /alert(args[0].uid+' '+args[0].values); for(x in args[0].values){ var nv=args[0].values[x]; for(g in this.rules.tags){ if(nv.tagUid==this.rules.tags[g].uid){ T=this.rules.tags[g]; break; } } if(T){ this.select.hide(); this.changeB.show(); this.topTag=new NVItem({ loc:this.DOM, tagData:T, tagRules:this.rules, preLoad:nv, level:0 }); } } }, startOverHandle:function(e){ var obj=e.data.obj; //get rid of current top-level area completely if(obj.topTag){ obj.topTag.destroy(); obj.topTag=null; //hide change button and open up select element obj.changeB.hide(); obj.select.show(); } }, _noEdit:function(){ //tell topTag to hide editable items if(this.topTag) this.topTag._noEdit(); this.changeB.hide(); }, _startEdit:function(){ //user can now edit choices this.changeB.show(); //cascade command down if(this.topTag) this.topTag._startEdit(); }, //picks up nameSelect trigger from option element nameSelectHandle:function(e,uid){ var obj=e.data.obj; //Top-Level tag is selected, erase all items that are in items array //so as to get rid of any possible previous selections for(item in obj.items){ obj.items[item].destroy(); } obj.items=[]; //hide the select element and open up change element obj.select.hide(); obj.changeB.show(); //find the tag that is the chosen top-level tag var T=null; for(g in obj.rules.tags){ if(obj.rules.tags[g].uid==uid){ T=obj.rules.tags[g]; //set up the Top-Level NVItem - handles all the other NVItems var ni=new NVItem({ loc:obj.DOM, tagData:T, tagRules:obj.rules, level:0 }); obj.topTag=ni; break; } } }, evalRef:function(e){ //analyze to see if val() refers to a URI or to another Tag's uid var obj=e.data.obj; if(obj.valueEl){ var c=obj.valueEl.text(); var ut=/http:|.html|.htm|.php|.shtml/; if(ut.test(c)){ } } }, bundleData:function(){ var bdJSON={'uid':this.uid,'values':[]}; if(this.topTag){ //bdJSON.type=this.topTag.valueType; bdJSON.values.push(this.topTag.bundleData()); // for(i in this.items){ // var it=this.items[i].bundleData; // bdJSON.values.push(it); // } }else{ bdJSON.value='null'; } return bdJSON; } }); var ALT_COLORS=["#CCC","#DDD"]; var NVItem=Monomyth.Class.extend({ init:function(args){ if(!args.html) throw "Error in constructing NVItem"; this.loc=$("#"+args.loc); this.html=args.html; //append html to DOM $(this.html).appendTo(this.loc); this.rules=args.tagRules; this.preLoad=args.preLoad; this.tagData=args.tagData; this.tagUID=args.tagData.uid; this.level=(args.level)?args.level:0; //generate random unique ID var d=new Date(); this.uid=d.getTime(); this.tagName=this.tagData.name; //get HTML from external page //NEW: get html from JSON // $($.ajax({ // url:'lib/Tag/NameValueArea.php?id='+this.uid, // dataType:'html', // async:false // }).responseText).insertAfter(this.loc); //this.nodeValue=args.nv; //this.DOM=$("<div class=\"subNameValue\"></div>").attr("id","namevaluepair_"+$(".subNameValue").length).insertAfter(this.loc); this.DOM=$("#emptynvitem").attr('id',"nvitem_"+this.uid); //adjust DOMs margin based on level var n=this.level*15; this.DOM.css("margin-left",n+"px"); //this.DOM.css("background-color",((this.level%2)>0)?ALT_COLORS[0]:ALT_COLORS[1]); this.inputArea=$("#"+this.DOM.attr('id')+" > span.nameValue_Input"); //insert title of tag into the inputArea this.inputArea.text(this.tagName); //this.changeB=$("#"+this.uid+"_nvInputArea > a").click(function(e){$(this).trigger("NV_StartOver");}); this.requiredArea=$("#"+this.DOM.attr('id')+" > span.nameValue_RequiredArea").attr('id',this.uid+"_rqa"); this.optionalArea=$("#"+this.DOM.attr('id')+" > span.nameValue_OptionalArea").attr('id',this.uid+"_opa"); // this.optSelect=$("#"+this.uid+"_optSelect"); this.valueEl=null; this.items=[]; this.setUpInput(); if(this.preLoad){ this.setUpPrevious(); } else if(this.tagData.childNodes){ this.setUpChildren(); } }, setUpInput:function(){ //switch for displaying the correct value type switch(this.tagData.valueType){ case 0: //do nothing - null value this.valueEl=$("<p>No value</p>").appendTo(this.inputArea); break; case 1: this.valueEl=$("<input type=\"text\"></input>").attr("id",this.DOM.attr('id')+"_input").val("").appendTo(this.inputArea); // this.DOM.append(this.valueEl); break; case 2: //reference to a url or other tag this.valueEl=$("<input type=\"text\"></input>").attr("id",this.DOM.attr("id")+"_input").val("").appendTo(this.inputArea); //this.valueEl.bind("blur",{obj:this},this.evalRef); break; default: //enum type - set up select tag for(en in this.rules.enums){ if(this.tagData.valueType==this.rules.enums[en].uid){ var em=this.rules.enums[en]; //alert('value el is an enum'); // create select tag then run through JSON values for enum value this.valueEl=$("<select></select>").attr("id",this.DOM.attr('id')+"_input"); for(d in em.values){ //each em.value gets a option tag $("<option></option>").val(em.values[d]).text(em.values[d]).appendTo(this.valueEl); } this.valueEl.appendTo(this.inputArea); //end for loop break; } } } }, setUpChildren:function(){ var optnodes=[]; for(t in this.tagData.childNodes){ var uid=this.tagData.childNodes[t]; for(g in this.rules.tags){ if((uid==this.rules.tags[g].uid)){ if(this.rules.tags[g].optional=="false"){ var tag=this.rules.tags[g]; var el=new NVItem({ loc:this.requiredArea.attr('id'), tagRules:this.rules, tagData:tag, level:(this.level+1), html:this.html }); this.items.push(el); } else { optnodes.push(this.rules.tags[g].uid); } } } } if(optnodes.length>0){ this.optChoice=new NVOptionsItem({ loc:this.optionalArea, options:optnodes, tagRules:this.rules }); } //bind nvItemClick listener to DOM this.DOM.bind("nvItemClick",{obj:this},this.handleItemClick); }, //Optional tag selected from option element //adds an optional tag to the stack - called by nvItemClick handleItemClick:function(e,uid){ e.stopPropagation(); //want to stop this from going up DOM tree var obj=e.data.obj; for(r in obj.rules.tags){ if(uid==obj.rules.tags[r].uid){//found var T=obj.rules.tags[r]; var el=new NVItem({ loc:obj.optionalArea.attr('id'), tagRules:obj.rules, tagData:T, level:(obj.level+1), html:obj.html }); obj.items.push(el); obj.DOM.trigger("nvItemChanged",[obj.uid]); break; //stop loop } } }, //take previously bundled data and re-create previous state setUpPrevious:function(){ if(this.preLoad){ //first, set up any previously set input value this.valueEl.val(this.preLoad.value); if(this.preLoad.values){ for(x=0;x<this.preLoad.values.length;x++){ var cur=this.preLoad.values[x]; for(g in this.rules.tags){ if(cur.tagUid==this.rules.tags[g].uid){ var tag=this.rules.tags[g]; var el=new NVItem({ loc:this.requiredArea, tagRules:this.rules, tagData:tag, preLoad:cur.values, level:(this.level+1) }); this.items.push(el); if(cur.value) el.valueEl.val(cur.value); } } } } } }, //RECURSIVE FUNCTION bundleData:function(){ //return JSON-like string of all items var _Json={"uid":this.uid,"tagUid":this.tagUID,"name":this.tagData.tagName,"type":this.tagData.valueType,"value":this.valueEl.val().replace(/[\n\r\t]+/g,""),"values":[]}; for(i in this.items){ var it=this.items[i].bundleData(); _Json.values.push(it); } return _Json; }, destroy:function(){ for(i in this.items){ this.items[i].destroy(); } this.valueEl.remove(); this.DOM.remove(); }, _noEdit:function(){ //hide editable elements from user if(this.valueEl){ $("#"+this.uid+"_nvInputArea > p").text(this.tagName+": "+this.valueEl.val()); this.valueEl.hide(); } //cascade command down to other items var s=this; for(i=0;i<this.items.length;i++){ setTimeout(function(T){ T._noEdit(); },1,this.items[i]); } }, _startEdit:function(){ //show editable elements for user if(this.valueEl){ $("#"+this.uid+"_nvInputArea > p").text(this.tagName); this.valueEl.show(); } //cascade command down to other items var s=this; for(i=0;i<this.items.length;i++){ setTimeout(function(T){ T._startEdit(); },1,this.items[i]); } } }); //Sub-level version of Name-Value object above var NVOptionsItem=Monomyth.Class.extend({ init:function(args){ this.loc=args.loc; this.rules=args.tagRules; this.options=args.options; //create select element and insert after the args.loc jQuery object this.DOM=$("<select class=\"name_value_Option\"></select>").attr("id","select_"+$(".nameValue").length).insertAfter(this.loc).hide(); //make toggle button to show/hide the DOM this.toggleB=$("<span class=\"button\">Add more data...</span>").insertAfter(this.loc); this.toggleB.bind("click",{obj:this},this.toggleDisplay); this.w=false; if(this.options){ this.setUpNames(); } }, setUpNames:function(){ for(o in this.options){ var id=$("#"+this.DOM.attr("id")+" > option").length+"_"+this.DOM.attr("id"); var opt=$("<option></option>").appendTo(this.DOM); for(t in this.rules.tags){ var T=this.rules.tags[t]; if(this.options[o]==T.uid){ opt.val(T.uid).text(T.name); break; } } //set up listener for when an option is chosen opt.click(function(e){ $(this).trigger("nvItemClick",[$(this).val()]); }); } }, toggleDisplay:function(e){ var obj=e.data.obj; if(!obj.w){ obj.DOM.show('fast'); obj.w=true; } else { obj.DOM.hide('fast'); obj.w=false; } }, destroy:function(){ this.DOM.remove(); } }); TILE.TILE_ENGINE=TILE_ENGINE; TILE.Log=Log; TILE.TileLogShape=TileLogShape; TILE.TileNameValue=TileNameValue; TILE.NVItem=NVItem; TILE.NVOptionsItem=NVOptionsItem; TILE.TileLogTag=TileLogTag; TILE.TileLogGroup=TileLogGroup; })(jQuery);
git-svn-id: http://peach.umd.edu/svn/TILE/postJuly@461 059f972f-e69e-4bc1-b02e-01f4d4c914a7
lib/_Interface/tile_logbar.js
<ide><path>ib/_Interface/tile_logbar.js <ide> $.merge(tlines,d[tr].transcript); <ide> } <ide> } <add> //TODO: get correct json format for loading/saving <ide> if(!obj.json) obj.json=d; <ide> $("body:first").trigger("loadImageList"); <ide> $("body:first").trigger("closeImpD");
Java
apache-2.0
5e29ff1a6f53c6227485f8debcf1737f47cd0351
0
spring-cloud/spring-cloud-commons
/* * Copyright 2013-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.bootstrap.encrypt; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.core.io.Resource; @ConfigurationProperties("encrypt") public class KeyProperties { /** * A symmetric key. As a stronger alternative consider using a keystore. */ private String key; /** * A salt for the symmetric key in the form of a hex-encoded byte array. As a stronger * alternative consider using a keystore. */ private String salt = "deadbeef"; /** * Flag to say that a process should fail if there is an encryption or decryption * error. */ private boolean failOnError = true; /** * The key store properties for locating a key in a Java Key Store (a file in a format * defined and understood by the JVM). */ private KeyStore keyStore = new KeyStore(); public boolean isFailOnError() { return this.failOnError; } public void setFailOnError(boolean failOnError) { this.failOnError = failOnError; } public String getKey() { return this.key; } public void setKey(String key) { this.key = key; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public KeyStore getKeyStore() { return this.keyStore; } public void setKeyStore(KeyProperties.KeyStore keyStore) { this.keyStore = keyStore; } public static class KeyStore { /** * Location of the key store file, e.g. classpath:/keystore.jks. */ private Resource location; /** * Password that locks the keystore. */ private String password; /** * Alias for a key in the store. */ private String alias; /** * Secret protecting the key (defaults to the same as the password). */ private String secret; /** * The KeyStore type. Defaults to jks. */ private String type = "jks"; public String getAlias() { return this.alias; } public void setAlias(String alias) { this.alias = alias; } public Resource getLocation() { return this.location; } public void setLocation(Resource location) { this.location = location; } public String getPassword() { return this.password; } public String getType() { return type; } public void setPassword(String password) { this.password = password; } public String getSecret() { return this.secret == null ? this.password : this.secret; } public void setSecret(String secret) { this.secret = secret; } public void setType(String type) { this.type = type; } } }
spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/KeyProperties.java
/* * Copyright 2013-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.bootstrap.encrypt; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.core.io.Resource; @ConfigurationProperties("encrypt") public class KeyProperties { /** * A symmetric key. As a stronger alternative consider using a keystore. */ private String key; /** * A salt for the symmetric key in the form of a hex-encoded byte array. As a stronger * alternative consider using a keystore. */ private String salt = "deadbeef"; /** * Flag to say that a process should fail if there is an encryption or decryption * error. */ private boolean failOnError = true; /** * The key store properties for locating a key in a Java Key Store (a file in a format * defined and understood by the JVM). */ private KeyStore keyStore = new KeyStore(); public boolean isFailOnError() { return this.failOnError; } public void setFailOnError(boolean failOnError) { this.failOnError = failOnError; } public String getKey() { return this.key; } public void setKey(String key) { this.key = key; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public KeyStore getKeyStore() { return this.keyStore; } public void setKeyStore(KeyProperties.KeyStore keyStore) { this.keyStore = keyStore; } public static class KeyStore { /** * Location of the key store file, e.g. classpath:/keystore.jks. */ private Resource location; /** * Password that locks the keystore. */ private String password; /** * Alias for a key in the store. */ private String alias; /** * Secret protecting the key (defaults to the same as the password). */ private String secret; public String getAlias() { return this.alias; } public void setAlias(String alias) { this.alias = alias; } public Resource getLocation() { return this.location; } public void setLocation(Resource location) { this.location = location; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getSecret() { return this.secret == null ? this.password : this.secret; } public void setSecret(String secret) { this.secret = secret; } } }
Add new type property to KeyStore properties. (#486)
spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/KeyProperties.java
Add new type property to KeyStore properties. (#486)
<ide><path>pring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/KeyProperties.java <ide> */ <ide> private String secret; <ide> <add> /** <add> * The KeyStore type. Defaults to jks. <add> */ <add> private String type = "jks"; <add> <ide> public String getAlias() { <ide> return this.alias; <ide> } <ide> return this.password; <ide> } <ide> <add> public String getType() { <add> return type; <add> } <add> <ide> public void setPassword(String password) { <ide> this.password = password; <ide> } <ide> this.secret = secret; <ide> } <ide> <add> public void setType(String type) { <add> this.type = type; <add> } <add> <ide> } <ide> }
Java
mit
03d443b869c4a5a0d68bbb9cf85229afe80d5957
0
tomsik68/mclauncher-api,tomsik68/mclauncher-api
package sk.tomsik68.mclauncher.impl.versions.mcdownload; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; import org.junit.Before; import org.junit.Test; public final class TestRuleParser { @Test public void parseRuleWithFeatures() { String r = "{ \"action\": \"allow\", \"features\": { \"has_custom_resolution\": true } }"; Rule rule = Rule.fromJson((JSONObject) JSONValue.parse(r)); } @Test public void parseRuleWithOS() { String r = "{\n" + " \"action\": \"allow\",\n" + " \"os\": {\n" + " \"name\": \"osx\"\n" + " }\n" + " }\n"; Rule rule = Rule.fromJson((JSONObject) JSONValue.parse(r)); } @Test public void parseRuleWithArch() { String r = "{ \"action\": \"allow\", \"os\": { \"arch\": \"x86\" } }"; Rule rule = Rule.fromJson((JSONObject) JSONValue.parse(r)); } }
src/test/java/sk/tomsik68/mclauncher/impl/versions/mcdownload/TestRuleParser.java
package sk.tomsik68.mclauncher.impl.versions.mcdownload; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; import org.junit.Before; import org.junit.Test; public final class TestRuleParser { @Test public void parseRuleWithFeatures() { String r = "{ \"action\": \"allow\", \"features\": { \"has_custom_resolution\": true } }"; Rule rule = new Rule((JSONObject) JSONValue.parse(r)); } @Test public void parseRuleWithOS() { String r = "{\n" + " \"action\": \"allow\",\n" + " \"os\": {\n" + " \"name\": \"osx\"\n" + " }\n" + " }\n"; Rule rule = new Rule((JSONObject) JSONValue.parse(r)); } @Test public void parseRuleWithArch() { String r = "{ \"action\": \"allow\", \"os\": { \"arch\": \"x86\" } }"; Rule rule = new Rule((JSONObject) JSONValue.parse(r)); } }
Fix Rule unit tests
src/test/java/sk/tomsik68/mclauncher/impl/versions/mcdownload/TestRuleParser.java
Fix Rule unit tests
<ide><path>rc/test/java/sk/tomsik68/mclauncher/impl/versions/mcdownload/TestRuleParser.java <ide> @Test <ide> public void parseRuleWithFeatures() { <ide> String r = "{ \"action\": \"allow\", \"features\": { \"has_custom_resolution\": true } }"; <del> Rule rule = new Rule((JSONObject) JSONValue.parse(r)); <add> Rule rule = Rule.fromJson((JSONObject) JSONValue.parse(r)); <ide> } <ide> <ide> @Test <ide> public void parseRuleWithOS() { <ide> String r = "{\n" + " \"action\": \"allow\",\n" + " \"os\": {\n" + " \"name\": \"osx\"\n" + " }\n" + " }\n"; <del> Rule rule = new Rule((JSONObject) JSONValue.parse(r)); <add> Rule rule = Rule.fromJson((JSONObject) JSONValue.parse(r)); <ide> } <ide> <ide> @Test <ide> public void parseRuleWithArch() { <ide> String r = "{ \"action\": \"allow\", \"os\": { \"arch\": \"x86\" } }"; <del> Rule rule = new Rule((JSONObject) JSONValue.parse(r)); <add> Rule rule = Rule.fromJson((JSONObject) JSONValue.parse(r)); <ide> } <ide> }
Java
agpl-3.0
ea8e195466c266843c92f12b2c05717961dd789c
0
ianopolous/Peergos,Peergos/Peergos,ianopolous/Peergos,ianopolous/Peergos,Peergos/Peergos,Peergos/Peergos
package peergos.tests; import org.junit.*; import peergos.corenode.*; import peergos.crypto.*; import peergos.fuse.*; import peergos.server.Start; import peergos.user.*; import peergos.util.*; import java.io.*; import java.lang.*; import java.lang.reflect.*; import java.net.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; public class FuseTests { public static int WEB_PORT = 8888; public static int CORE_PORT = 7777; public static String username = "test02"; public static String password = username; public static Path mountPoint; public static FuseProcess fuseProcess; static void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); } public static UserContext ensureSignedUp(String username, String password) throws IOException { DHTClient.HTTP dht = new DHTClient.HTTP(new URL("http://localhost:"+ WEB_PORT +"/")); Btree.HTTP btree = new Btree.HTTP(new URL("http://localhost:"+ WEB_PORT +"/")); HTTPCoreNode coreNode = new HTTPCoreNode(new URL("http://localhost:"+ WEB_PORT +"/")); UserContext userContext = UserContext.ensureSignedUp(username, password, dht, btree, coreNode); return userContext; } @BeforeClass public static void init() throws Exception { // use insecure random otherwise tests take ages setFinalStatic(TweetNaCl.class.getDeclaredField("prng"), new Random()); Args.parse(new String[]{"useIPFS", "false", "-port", Integer.toString(WEB_PORT), "-corenodePort", Integer.toString(CORE_PORT)}); Start.local(); UserContext userContext = ensureSignedUp(username, password); String mountPath = Args.getArg("mountPoint", "/tmp/peergos/tmp"); mountPoint = Paths.get(mountPath); mountPoint = mountPoint.resolve(UUID.randomUUID().toString()); mountPoint.toFile().mkdirs(); System.out.println("\n\nMountpoint "+ mountPoint +"\n\n"); PeergosFS peergosFS = new PeergosFS(userContext); fuseProcess = new FuseProcess(peergosFS, mountPoint); Runtime.getRuntime().addShutdownHook(new Thread(() -> fuseProcess.close())); fuseProcess.start(); } public static String readStdout(Process p) throws IOException { return new String(Serialize.readFully(p.getInputStream())).trim(); } @Test public void variousTests() throws IOException { String homeName = readStdout(Runtime.getRuntime().exec("ls " + mountPoint)); Assert.assertTrue("Correct home directory: "+homeName, homeName.equals(username)); Path home = mountPoint.resolve(username); String data = "Hello Peergos!"; readStdout(Runtime.getRuntime().exec("echo \""+data+"\" > " + home + "/data.txt")); String res = readStdout(Runtime.getRuntime().exec("cat " + home + "/data.txt")); // Assert.assertTrue("Correct file contents: "+res, res.equals(data)); // System.out.println(res); } @AfterClass public static void shutdown() { fuseProcess.close(); } }
src/peergos/tests/FuseTests.java
package peergos.tests; import org.junit.*; import peergos.corenode.*; import peergos.crypto.*; import peergos.fuse.*; import peergos.server.Start; import peergos.user.*; import peergos.util.*; import java.io.*; import java.lang.*; import java.lang.reflect.*; import java.net.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; public class FuseTests { public static int WEB_PORT = 8888; public static int CORE_PORT = 7777; public static String username = "test02"; public static String password = username; public static Path mountPoint; public static FuseProcess fuseProcess; static void setFinalStatic(Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(null, newValue); } public static UserContext ensureSignedUp(String username, String password) throws IOException { DHTClient.HTTP dht = new DHTClient.HTTP(new URL("http://localhost:"+ WEB_PORT +"/")); Btree.HTTP btree = new Btree.HTTP(new URL("http://localhost:"+ WEB_PORT +"/")); HTTPCoreNode coreNode = new HTTPCoreNode(new URL("http://localhost:"+ WEB_PORT +"/")); UserContext userContext = UserContext.ensureSignedUp(username, password, dht, btree, coreNode); return userContext; } @BeforeClass public static void init() throws Exception { Args.parse(new String[]{"useIPFS", "false", "-port", Integer.toString(WEB_PORT), "-corenodePort", Integer.toString(CORE_PORT)}); Start.local(); UserContext userContext = ensureSignedUp(username, password); // use insecure random otherwise tests take ages setFinalStatic(TweetNaCl.class.getDeclaredField("prng"), new Random()); String mountPath = Args.getArg("mountPoint", "/tmp/peergos/tmp"); mountPoint = Paths.get(mountPath); mountPoint = mountPoint.resolve(UUID.randomUUID().toString()); mountPoint.toFile().mkdirs(); System.out.println("\n\nMountpoint "+ mountPoint +"\n\n"); PeergosFS peergosFS = new PeergosFS(userContext); fuseProcess = new FuseProcess(peergosFS, mountPoint); Runtime.getRuntime().addShutdownHook(new Thread(() -> fuseProcess.close())); fuseProcess.start(); } public static String readStdout(Process p) throws IOException { return new String(Serialize.readFully(p.getInputStream())).trim(); } @Test public void variousTests() throws IOException { String homeName = readStdout(Runtime.getRuntime().exec("ls " + mountPoint)); Assert.assertTrue("Correct home directory: "+homeName, homeName.equals(username)); Path home = mountPoint.resolve(username); String data = "Hello Peergos!"; String res = readStdout(Runtime.getRuntime().exec("echo \""+data+"\" > " + home + "/data.txt")); System.out.println(res); } @AfterClass public static void shutdown() { fuseProcess.close(); } }
Make sure FuseTests use insecure random from beginning!
src/peergos/tests/FuseTests.java
Make sure FuseTests use insecure random from beginning!
<ide><path>rc/peergos/tests/FuseTests.java <ide> <ide> @BeforeClass <ide> public static void init() throws Exception { <add> // use insecure random otherwise tests take ages <add> setFinalStatic(TweetNaCl.class.getDeclaredField("prng"), new Random()); <add> <ide> Args.parse(new String[]{"useIPFS", "false", <ide> "-port", Integer.toString(WEB_PORT), <ide> "-corenodePort", Integer.toString(CORE_PORT)}); <ide> Start.local(); <ide> UserContext userContext = ensureSignedUp(username, password); <ide> <del> // use insecure random otherwise tests take ages <del> setFinalStatic(TweetNaCl.class.getDeclaredField("prng"), new Random()); <ide> <ide> String mountPath = Args.getArg("mountPoint", "/tmp/peergos/tmp"); <ide> <ide> Path home = mountPoint.resolve(username); <ide> <ide> String data = "Hello Peergos!"; <del> String res = readStdout(Runtime.getRuntime().exec("echo \""+data+"\" > " + home + "/data.txt")); <del> System.out.println(res); <add> readStdout(Runtime.getRuntime().exec("echo \""+data+"\" > " + home + "/data.txt")); <add> String res = readStdout(Runtime.getRuntime().exec("cat " + home + "/data.txt")); <add>// Assert.assertTrue("Correct file contents: "+res, res.equals(data)); <add>// System.out.println(res); <ide> } <ide> <ide> @AfterClass
JavaScript
apache-2.0
be0d0c95e039849e05607c6abfc54c5a459d9050
0
bird-house/pyramid-phoenix,bird-house/pyramid-phoenix,bird-house/pyramid-phoenix,bird-house/pyramid-phoenix
var map = null; var wmsLayer = null; var animateLayer = null; var animateURL = null; var start_time, end_time; var layerList; var selectedLayer = null; var selectedTimeIndex = null; function initMap() { initGlobe(); initGlobeButtons(); initLayerList(); } function initBaseLayer() { var baseLayer = new OpenLayers.Layer.WMS( "Demis BlueMarble", "http://www2.demis.nl/wms/wms.ashx?WMS=BlueMarble" , {layers: 'Earth Image,Borders,Coastlines'}); map.addLayer(baseLayer); } function initGlobe(show3D) { show3D = show3D || false; if (map != null) { map.destroy(); } //var mapOptions = { maxResolution: 256/512, numZoomLevels: 11, fractionalZoom: true}; //map = new OpenLayers.Map('map',mapOptions); map = new OpenLayers.Map('map', { controls: [] }); map.setupGlobe(); //map.addControl(new OpenLayers.Control.LayerSwitcher()); map.addControl(new OpenLayers.Control.Navigation()); map.addControl(new OpenLayers.Control.PanZoom()); //map.addControl(new OpenLayers.Control.Attribution()); initBaseLayer(); if (selectedLayer) { initWMSLayer(selectedLayer, selectedTimeIndex); } if (animateURL) { //initAnimateLayer(animateURL); } map.finishGlobe(); if (show3D) { map.show3D(); } else { map.show2D(); } } function initLayerList() { wps = new SimpleWPS({ process: "org.malleefowl.wms.layer", onSuccess: function(result) { //console.log(result); var output = []; layerList = [] $.each(result, function(index, layer) { //output.push('<optgroup label="' + layer.service_name + '">'); title = layer.title + " (" + layer.service_name + ")"; output.push('<option label="' + title + '" value="'+ index +'">' + title +'</option>'); //output.push('</optgroup>'); layerList.push(layer); }); $('#select').html(output.join('')); $('#select').change(function() { selectedLayer = layerList[this.selectedIndex]; showWMSLayer(selectedLayer); }); selectedLayer = layerList[0]; showWMSLayer(selectedLayer); }, }); wps.execute(); } function initWMSLayer(layer, step) { wmsLayer = new OpenLayers.Layer.WMS(layer.title, layer.service, {layers: layer.name, transparent: true, format:'image/png', time: layer.timesteps[step]}); map.addLayer(wmsLayer); } function showWMSLayer(layer) { if (wmsLayer != null) { map.removeLayer(wmsLayer); } initWMSLayer(layer, 0); wmsLayer.events.register('loadend', wmsLayer, function(evt){ //map.zoomToExtent(new OpenLayers.Bounds(wmsLayer.getExtent())); }); initTimeSlider(layer); } function dateLabel(timestep) { return timestep.substring(0,16); } function initGlobeButtons() { // 2d button $("#2d").button({ text: true, }).click(function( event ) { show2D(); }); // 3d button $("#3d").button({ text: true, }).click(function( event ) { show3D(); }); } function show2D() { if (map.is3D) { map.show2D(); } } function show3D() { if (!map.is3D) { initGlobe(true); } } function initTimeSlider(layer) { var max = layer.timesteps.length - 1; // slider $("#slider").slider({ value: 0, min: 0, max: max, step: 1, slide: function(e, ui) { var step = parseInt(ui.value); //console.log("sliding ..."); $("#time").text(dateLabel(layer.timesteps[step])); }, change: function(e, ui) { show2D(); //tds_wms.setOpacity(ui.value / 10); var step = parseInt(ui.value); //console.log("step: " + step); $("#time").text(dateLabel(layer.timesteps[step])); wmsLayer.mergeNewParams({'time': layer.timesteps[step]}); selectedTimeIndex = step; } }); $("#time").text(dateLabel(layer.timesteps[0])); // prev button $("#prev").button({ text: false, }).click(function( event ) { //console.log('prev button clicked'); current = $("#slider").slider( "values", 0 ); if (current > 0 ) { show2D(); $("#slider").slider( "value", current - 1 ); } }); // next button $("#next").button({ text: false, }).click(function( event ) { //console.log('next button clicked'); show2D(); current = $("#slider").slider( "values", 0 ); if (current < max ) { $("#slider").slider( "value", current + 1 ); } }); // play button $("#play").button({ text: false, }).click(function( event ) { $("#dialog-play").dialog({ resizable: false, height: 300, modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); show2D(); animate(selectedLayer); }, Cancel: function() { $( this ).dialog( "close" ); } } }); }); // stop button $("#stop").button({ text: false, }).click(function( event ) { if (animateLayer != null) { map.removeLayer(animateLayer); animateLayer = null; } }); // slider range $("#slider-range").slider({ range: true, values: [0, max], min: 0, max: max, step: 1, slide: function(e, ui) { var step0 = parseInt(ui.values[0]); var step1 = parseInt(ui.values[1]); setTimeRange(layer, step0, step1); }, }); setTimeRange(layer, 0, layer.timesteps.length-1); } function setTimeRange(layer, min, max) { $("#time-range").text( dateLabel(layer.timesteps[min]) + " - " + dateLabel(layer.timesteps[max]) ); start_time = layer.timesteps[min]; end_time = layer.timesteps[max]; } function initAnimateLayer(imageURL) { animateLayer = new OpenLayers.Layer.Image( "Animation", imageURL, map.getExtent(), map.getSize(), { isBaseLayer: false, alwaysInRange: true // Necessary to always draw the image }); map.addLayer(animateLayer); } function animate(layer) { if (animateLayer != null) { map.removeLayer(animateLayer); animateLayer = null; } wps = new SimpleWPS({ process: "org.malleefowl.wms.animate", raw: false, format: 'xml', onSuccess: function(xmlDoc) { //console.log(xmlDoc); animateURL = $(xmlDoc).find("wps\\:Reference, Reference").first().attr('href'); initAnimateLayer(animateURL); }, }); wps.execute({ service_url: layer.service, layer: layer.name, start: start_time, end: end_time, resolution: $("#select-resolution").val(), delay: $("#delay").val(), width: map.getSize().w, height: map.getSize().h, bbox: map.getExtent().toBBOX(), }); } /* function animateSlow(step) { if (step < 10) { $("#slider").slider( "value", step ); setTimeout(function() {animate(step+1);}, 500); } } */
phoenix/static/js/map.js
var map = null; var wmsLayer = null; var animateLayer = null; var animateURL = null; var start_time, end_time; var layerList; var selectedLayer = null; var selectedTimeIndex = null; function initMap() { initGlobe(); initGlobeButtons(); initLayerList(); } function initBaseLayer() { var baseLayer = new OpenLayers.Layer.WMS( "Demis BlueMarble", "http://www2.demis.nl/wms/wms.ashx?WMS=BlueMarble" , {layers: 'Earth Image,Borders,Coastlines'}); map.addLayer(baseLayer); } function initGlobe(show3D) { show3D = show3D || false; if (map != null) { map.destroy(); } //var mapOptions = { maxResolution: 256/512, numZoomLevels: 11, fractionalZoom: true}; //map = new OpenLayers.Map('map',mapOptions); map = new OpenLayers.Map('map', { controls: [] }); map.setupGlobe(); //map.addControl(new OpenLayers.Control.LayerSwitcher()); map.addControl(new OpenLayers.Control.Navigation()); map.addControl(new OpenLayers.Control.PanZoom()); //map.addControl(new OpenLayers.Control.Attribution()); initBaseLayer(); if (selectedLayer) { initWMSLayer(selectedLayer, selectedTimeIndex); } if (animateURL) { //initAnimateLayer(animateURL); } map.finishGlobe(); if (show3D) { map.show3D(); } else { map.show2D(); } } function initLayerList() { wps = new SimpleWPS({ process: "org.malleefowl.wms.layer", onSuccess: function(result) { //console.log(result); var output = []; layerList = [] $.each(result, function(index, layer) { //output.push('<optgroup label="' + layer.service_name + '">'); title = layer.title + " (" + layer.service_name + ")"; output.push('<option label="' + title + '" value="'+ index +'">' + title +'</option>'); //output.push('</optgroup>'); layerList.push(layer); }); $('#select').html(output.join('')); $('#select').change(function() { selectedLayer = layerList[this.selectedIndex]; showWMSLayer(selectedLayer); }); selectedLayer = layerList[0]; showWMSLayer(selectedLayer); }, }); wps.execute(); } function initWMSLayer(layer, step) { wmsLayer = new OpenLayers.Layer.WMS(layer.title, layer.service, {layers: layer.name, transparent: true, format:'image/png', time: layer.timesteps[step]}); map.addLayer(wmsLayer); } function showWMSLayer(layer) { if (wmsLayer != null) { map.removeLayer(wmsLayer); } initWMSLayer(layer, 0); wmsLayer.events.register('loadend', wmsLayer, function(evt){ //map.zoomToExtent(new OpenLayers.Bounds(wmsLayer.getExtent())); }); initTimeSlider(layer); } function dateLabel(timestep) { return timestep.substring(0,16); } function initGlobeButtons() { // 2d button $("#2d").button({ text: true, }).click(function( event ) { show2D(); }); // 3d button $("#3d").button({ text: true, }).click(function( event ) { show3D(); }); } function show2D() { if (map.is3D) { map.show2D(); } } function show3D() { if (!map.is3D) { initGlobe(true); } } function initTimeSlider(layer) { var max = layer.timesteps.length - 1; // slider $("#slider").slider({ value: 0, min: 0, max: max, step: 1, slide: function(e, ui) { var step = parseInt(ui.value); //console.log("sliding ..."); $("#time").text(dateLabel(layer.timesteps[step])); }, change: function(e, ui) { show2D(); //tds_wms.setOpacity(ui.value / 10); var step = parseInt(ui.value); //console.log("step: " + step); $("#time").text(dateLabel(layer.timesteps[step])); wmsLayer.mergeNewParams({'time': layer.timesteps[step]}); selectedTimeIndex = step; } }); $("#time").text(dateLabel(layer.timesteps[0])); // prev button $("#prev").button({ text: false, }).click(function( event ) { //console.log('prev button clicked'); current = $("#slider").slider( "values", 0 ); if (current > 0 ) { $("#slider").slider( "value", current - 1 ); } }); // next button $("#next").button({ text: false, }).click(function( event ) { //console.log('next button clicked'); current = $("#slider").slider( "values", 0 ); if (current < max ) { $("#slider").slider( "value", current + 1 ); } }); // play button $("#play").button({ text: false, }).click(function( event ) { $("#dialog-play").dialog({ resizable: false, height: 300, modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); animate(selectedLayer); }, Cancel: function() { $( this ).dialog( "close" ); } } }); }); // stop button $("#stop").button({ text: false, }).click(function( event ) { if (animateLayer != null) { map.removeLayer(animateLayer); animateLayer = null; } }); // slider range $("#slider-range").slider({ range: true, values: [0, max], min: 0, max: max, step: 1, slide: function(e, ui) { var step0 = parseInt(ui.values[0]); var step1 = parseInt(ui.values[1]); $("#time-range").text( dateLabel(layer.timesteps[step0]) + " - " + dateLabel(layer.timesteps[step1]) ); start_time = layer.timesteps[step0]; end_time = layer.timesteps[step1]; }, }); $("#time-range").text( dateLabel(layer.timesteps[0]) + " - " + dateLabel(layer.timesteps[layer.timesteps.length-1]) ); } function initAnimateLayer(imageURL) { animateLayer = new OpenLayers.Layer.Image( "Animation", imageURL, map.getExtent(), map.getSize(), { isBaseLayer: false, alwaysInRange: true // Necessary to always draw the image }); map.addLayer(animateLayer); } function animate(layer) { if (animateLayer != null) { map.removeLayer(animateLayer); animateLayer = null; } wps = new SimpleWPS({ process: "org.malleefowl.wms.animate", raw: false, format: 'xml', onSuccess: function(xmlDoc) { //console.log(xmlDoc); animateURL = $(xmlDoc).find("wps\\:Reference, Reference").first().attr('href'); initAnimateLayer(animateURL); }, }); wps.execute({ service_url: layer.service, layer: layer.name, start: start_time, end: end_time, resolution: $("#select-resolution").val(), delay: $("#delay").val(), width: map.getSize().w, height: map.getSize().h, bbox: map.getExtent().toBBOX(), }); } /* function animateSlow(step) { if (step < 10) { $("#slider").slider( "value", step ); setTimeout(function() {animate(step+1);}, 500); } } */
show2d for play buttons
phoenix/static/js/map.js
show2d for play buttons
<ide><path>hoenix/static/js/map.js <ide> //console.log('prev button clicked'); <ide> current = $("#slider").slider( "values", 0 ); <ide> if (current > 0 ) { <add> show2D(); <ide> $("#slider").slider( "value", current - 1 ); <ide> } <ide> }); <ide> text: false, <ide> }).click(function( event ) { <ide> //console.log('next button clicked'); <add> show2D(); <ide> current = $("#slider").slider( "values", 0 ); <ide> if (current < max ) { <ide> $("#slider").slider( "value", current + 1 ); <ide> buttons: { <ide> Ok: function() { <ide> $( this ).dialog( "close" ); <add> show2D(); <ide> animate(selectedLayer); <ide> }, <ide> Cancel: function() { <ide> var step0 = parseInt(ui.values[0]); <ide> var step1 = parseInt(ui.values[1]); <ide> <del> $("#time-range").text( dateLabel(layer.timesteps[step0]) + " - " + dateLabel(layer.timesteps[step1]) ); <del> start_time = layer.timesteps[step0]; <del> end_time = layer.timesteps[step1]; <del> }, <del> }); <del> $("#time-range").text( dateLabel(layer.timesteps[0]) + " - " + <del> dateLabel(layer.timesteps[layer.timesteps.length-1]) ); <del>} <add> setTimeRange(layer, step0, step1); <add> }, <add> }); <add> <add> setTimeRange(layer, 0, layer.timesteps.length-1); <add>} <add> <add>function setTimeRange(layer, min, max) { <add> $("#time-range").text( dateLabel(layer.timesteps[min]) + " - " + dateLabel(layer.timesteps[max]) ); <add> start_time = layer.timesteps[min]; <add> end_time = layer.timesteps[max]; <add>} <ide> <ide> function initAnimateLayer(imageURL) { <ide> animateLayer = new OpenLayers.Layer.Image(
Java
apache-2.0
780b6f8f97e248d86b7b5c03c4c560b84899e036
0
apache/manifoldcf-integration-solr-3.x
package org.apache.lucene.index; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.analysis.SimpleAnalyzer; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.MockRAMDirectory; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.util._TestUtil; import org.apache.lucene.util.English; import org.apache.lucene.util.LuceneTestCase; import java.io.IOException; import java.io.File; public class TestThreadedOptimize extends LuceneTestCase { private static final Analyzer ANALYZER = new SimpleAnalyzer(); private final static int NUM_THREADS = 3; //private final static int NUM_THREADS = 5; private final static int NUM_ITER = 1; //private final static int NUM_ITER = 10; private final static int NUM_ITER2 = 1; //private final static int NUM_ITER2 = 5; private boolean failed; private void setFailed() { failed = true; } public void runTest(Directory directory, MergeScheduler merger) throws Exception { IndexWriter writer = new IndexWriter(directory, ANALYZER, true, IndexWriter.MaxFieldLength.UNLIMITED); writer.setMaxBufferedDocs(2); if (merger != null) writer.setMergeScheduler(merger); for(int iter=0;iter<NUM_ITER;iter++) { final int iterFinal = iter; writer.setMergeFactor(1000); for(int i=0;i<200;i++) { Document d = new Document(); d.add(new Field("id", Integer.toString(i), Field.Store.YES, Field.Index.NOT_ANALYZED)); d.add(new Field("contents", English.intToEnglish(i), Field.Store.NO, Field.Index.ANALYZED)); writer.addDocument(d); } writer.setMergeFactor(4); //writer.setInfoStream(System.out); Thread[] threads = new Thread[NUM_THREADS]; for(int i=0;i<NUM_THREADS;i++) { final int iFinal = i; final IndexWriter writerFinal = writer; threads[i] = new Thread() { @Override public void run() { try { for(int j=0;j<NUM_ITER2;j++) { writerFinal.optimize(false); for(int k=0;k<17*(1+iFinal);k++) { Document d = new Document(); d.add(new Field("id", iterFinal + "_" + iFinal + "_" + j + "_" + k, Field.Store.YES, Field.Index.NOT_ANALYZED)); d.add(new Field("contents", English.intToEnglish(iFinal+k), Field.Store.NO, Field.Index.ANALYZED)); writerFinal.addDocument(d); } for(int k=0;k<9*(1+iFinal);k++) writerFinal.deleteDocuments(new Term("id", iterFinal + "_" + iFinal + "_" + j + "_" + k)); writerFinal.optimize(); } } catch (Throwable t) { setFailed(); System.out.println(Thread.currentThread().getName() + ": hit exception"); t.printStackTrace(System.out); } } }; } for(int i=0;i<NUM_THREADS;i++) threads[i].start(); for(int i=0;i<NUM_THREADS;i++) threads[i].join(); assertTrue(!failed); final int expectedDocCount = (int) ((1+iter)*(200+8*NUM_ITER2*(NUM_THREADS/2.0)*(1+NUM_THREADS))); // System.out.println("TEST: now index=" + writer.segString()); assertEquals(expectedDocCount, writer.maxDoc()); writer.close(); writer = new IndexWriter(directory, ANALYZER, false, IndexWriter.MaxFieldLength.UNLIMITED); writer.setMaxBufferedDocs(2); IndexReader reader = IndexReader.open(directory, true); assertTrue("reader=" + reader + " numDocs=" + reader.numDocs() + " expectedDocCount=" + expectedDocCount + " iter=" + iter, reader.isOptimized()); assertEquals(expectedDocCount, reader.numDocs()); reader.close(); } writer.close(); } /* Run above stress test against RAMDirectory and then FSDirectory. */ public void testThreadedOptimize() throws Exception { Directory directory = new MockRAMDirectory(); runTest(directory, new SerialMergeScheduler()); runTest(directory, new ConcurrentMergeScheduler()); directory.close(); String tempDir = System.getProperty("tempDir"); if (tempDir == null) throw new IOException("tempDir undefined, cannot run test"); String dirName = tempDir + "/luceneTestThreadedOptimize"; directory = FSDirectory.open(new File(dirName)); runTest(directory, new SerialMergeScheduler()); runTest(directory, new ConcurrentMergeScheduler()); directory.close(); _TestUtil.rmDir(dirName); } }
lucene/backwards/src/test/org/apache/lucene/index/TestThreadedOptimize.java
package org.apache.lucene.index; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.analysis.SimpleAnalyzer; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.MockRAMDirectory; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.util._TestUtil; import org.apache.lucene.util.English; import org.apache.lucene.util.LuceneTestCase; import java.io.IOException; import java.io.File; public class TestThreadedOptimize extends LuceneTestCase { private static final Analyzer ANALYZER = new SimpleAnalyzer(); private final static int NUM_THREADS = 3; //private final static int NUM_THREADS = 5; private final static int NUM_ITER = 1; //private final static int NUM_ITER = 10; private final static int NUM_ITER2 = 1; //private final static int NUM_ITER2 = 5; private boolean failed; private void setFailed() { failed = true; } public void runTest(Directory directory, MergeScheduler merger) throws Exception { IndexWriter writer = new IndexWriter(directory, ANALYZER, true, IndexWriter.MaxFieldLength.UNLIMITED); writer.setMaxBufferedDocs(2); if (merger != null) writer.setMergeScheduler(merger); for(int iter=0;iter<NUM_ITER;iter++) { final int iterFinal = iter; writer.setMergeFactor(1000); for(int i=0;i<200;i++) { Document d = new Document(); d.add(new Field("id", Integer.toString(i), Field.Store.YES, Field.Index.NOT_ANALYZED)); d.add(new Field("contents", English.intToEnglish(i), Field.Store.NO, Field.Index.ANALYZED)); writer.addDocument(d); } writer.setMergeFactor(4); //writer.setInfoStream(System.out); Thread[] threads = new Thread[NUM_THREADS]; for(int i=0;i<NUM_THREADS;i++) { final int iFinal = i; final IndexWriter writerFinal = writer; threads[i] = new Thread() { @Override public void run() { try { for(int j=0;j<NUM_ITER2;j++) { writerFinal.optimize(false); for(int k=0;k<17*(1+iFinal);k++) { Document d = new Document(); d.add(new Field("id", iterFinal + "_" + iFinal + "_" + j + "_" + k, Field.Store.YES, Field.Index.NOT_ANALYZED)); d.add(new Field("contents", English.intToEnglish(iFinal+k), Field.Store.NO, Field.Index.ANALYZED)); writerFinal.addDocument(d); } for(int k=0;k<9*(1+iFinal);k++) writerFinal.deleteDocuments(new Term("id", iterFinal + "_" + iFinal + "_" + j + "_" + k)); writerFinal.optimize(); } } catch (Throwable t) { setFailed(); System.out.println(Thread.currentThread().getName() + ": hit exception"); t.printStackTrace(System.out); } } }; } for(int i=0;i<NUM_THREADS;i++) threads[i].start(); for(int i=0;i<NUM_THREADS;i++) threads[i].join(); assertTrue(!failed); final int expectedDocCount = (int) ((1+iter)*(200+8*NUM_ITER2*(NUM_THREADS/2.0)*(1+NUM_THREADS))); // System.out.println("TEST: now index=" + writer.segString()); assertEquals(expectedDocCount, writer.maxDoc()); writer.close(); writer = new IndexWriter(directory, ANALYZER, false, IndexWriter.MaxFieldLength.UNLIMITED); writer.setMaxBufferedDocs(2); IndexReader reader = IndexReader.open(directory, true); assertTrue(reader.isOptimized()); assertEquals(expectedDocCount, reader.numDocs()); reader.close(); } writer.close(); } /* Run above stress test against RAMDirectory and then FSDirectory. */ public void testThreadedOptimize() throws Exception { Directory directory = new MockRAMDirectory(); runTest(directory, new SerialMergeScheduler()); runTest(directory, new ConcurrentMergeScheduler()); directory.close(); String tempDir = System.getProperty("tempDir"); if (tempDir == null) throw new IOException("tempDir undefined, cannot run test"); String dirName = tempDir + "/luceneTestThreadedOptimize"; directory = FSDirectory.open(new File(dirName)); runTest(directory, new SerialMergeScheduler()); runTest(directory, new ConcurrentMergeScheduler()); directory.close(); _TestUtil.rmDir(dirName); } }
add verbosity on intermittant test failure git-svn-id: 34e8a356306b8ce34b8875a802e5b81f93f12ba3@988505 13f79535-47bb-0310-9956-ffa450edef68
lucene/backwards/src/test/org/apache/lucene/index/TestThreadedOptimize.java
add verbosity on intermittant test failure
<ide><path>ucene/backwards/src/test/org/apache/lucene/index/TestThreadedOptimize.java <ide> writer.setMaxBufferedDocs(2); <ide> <ide> IndexReader reader = IndexReader.open(directory, true); <del> assertTrue(reader.isOptimized()); <add> assertTrue("reader=" + reader + " numDocs=" + reader.numDocs() + " expectedDocCount=" + expectedDocCount + " iter=" + iter, reader.isOptimized()); <ide> assertEquals(expectedDocCount, reader.numDocs()); <ide> reader.close(); <ide> }
Java
mit
77f90a7d017a75ccfd171628c674e87109f3cbb0
0
Przemek625/Spring-MVC-webshop,Przemek625/Spring-MVC-webshop
package com.packt.webstore.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import javax.sql.DataSource; import java.util.Properties; /** * Created by Przemek on 2016-07-27. */ @Configuration @PropertySource(value = { "classpath:jdbc.properties" }) public class DataConfig { @Value("${jdbc.className}") private String className; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean public DriverManagerDataSource dataSource(){ DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); driverManagerDataSource.setDriverClassName(className); driverManagerDataSource.setUrl(url); driverManagerDataSource.setUsername(username); driverManagerDataSource.setPassword(password); return driverManagerDataSource; } @Bean public JdbcTemplate jdbcTemplate(DriverManagerDataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean public LocalSessionFactoryBean localSessionFactoryBean(DataSource dataSource){ LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource); sessionFactoryBean.setPackagesToScan("com.packt.webstore"); Properties properties = new Properties(); properties.setProperty("dialect"," org.hibernate.dialect.MySQLDialect"); sessionFactoryBean.setHibernateProperties(properties); sessionFactoryBean.setHibernateProperties(null); return sessionFactoryBean; } }
webstore/src/main/java/com/packt/webstore/configuration/DataConfig.java
package com.packt.webstore.configuration; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import javax.sql.DataSource; import java.util.Properties; /** * Created by Przemek on 2016-07-27. */ @Configuration @PropertySource(value = { "classpath:jdbc.properties" }) public class DataConfig { @Value("${jdbc.className}") private String className; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){ return new PropertySourcesPlaceholderConfigurer(); } @Bean public DriverManagerDataSource dataSource(){ DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); driverManagerDataSource.setDriverClassName(className); driverManagerDataSource.setUrl(url); driverManagerDataSource.setUsername(username); driverManagerDataSource.setPassword(password); return driverManagerDataSource; } @Bean public JdbcTemplate jdbcTemplate(DriverManagerDataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean public LocalSessionFactoryBean localSessionFactoryBean(DataSource dataSource){ LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource); sessionFactoryBean.setPackagesToScan("com.packt.webstore"); Properties properties = new Properties(); properties.setProperty("dialect"," org.hibernate.dialect.MySQLDialect"); sessionFactoryBean.setHibernateProperties(properties); sessionFactoryBean.setHibernateProperties(null); return sessionFactoryBean; } //JPA configuration @Bean public JpaVendorAdapter jpaVendorAdapter(){ HibernateJpaVendorAdapter hjv = new HibernateJpaVendorAdapter(); hjv.setDatabase(Database.MYSQL); hjv.setShowSql(true); hjv.setGenerateDdl(false); hjv.setDatabasePlatform("org.hibernate.dialect.MySQLDialect"); return hjv; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean( DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { LocalContainerEntityManagerFactoryBean lcemfb = new LocalContainerEntityManagerFactoryBean(); lcemfb.setDataSource(dataSource); lcemfb.setJpaVendorAdapter(jpaVendorAdapter); return lcemfb; } }
I removed JPA from the project.
webstore/src/main/java/com/packt/webstore/configuration/DataConfig.java
I removed JPA from the project.
<ide><path>ebstore/src/main/java/com/packt/webstore/configuration/DataConfig.java <ide> sessionFactoryBean.setHibernateProperties(null); <ide> return sessionFactoryBean; <ide> } <del> <del>//JPA configuration <del> @Bean <del> public JpaVendorAdapter jpaVendorAdapter(){ <del> HibernateJpaVendorAdapter hjv = new HibernateJpaVendorAdapter(); <del> hjv.setDatabase(Database.MYSQL); <del> hjv.setShowSql(true); <del> hjv.setGenerateDdl(false); <del> hjv.setDatabasePlatform("org.hibernate.dialect.MySQLDialect"); <del> return hjv; <del> } <del> <del> @Bean <del> public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean( <del> DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { <del> LocalContainerEntityManagerFactoryBean lcemfb = new LocalContainerEntityManagerFactoryBean(); <del> lcemfb.setDataSource(dataSource); <del> lcemfb.setJpaVendorAdapter(jpaVendorAdapter); <del> return lcemfb; <del> } <del> <ide> }
Java
apache-2.0
bfea7676113fa14926d1fa4b6f3ce79246a65575
0
bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud
package com.planet_ink.coffee_mud.Items.Basic; import com.planet_ink.coffee_mud.Items.Basic.StdPortal; import com.planet_ink.coffee_mud.Items.BasicTech.GenSpaceShip; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Expire; import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Move; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.CMProps.Int; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.core.exceptions.CMException; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.MOB.Attrib; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.AchievementLibrary.Event; /* Copyright 2014-2019 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class GenSailingShip extends StdBoardable implements SailingShip { @Override public String ID() { return "GenSailingShip"; } protected volatile int courseDirection = -1; protected volatile boolean anchorDown = true; protected final List<Integer> courseDirections = new Vector<Integer>(); protected volatile int directionFacing = 0; protected volatile int ticksSinceMove = 0; protected volatile PhysicalAgent targetedShip = null; protected volatile Item tenderShip = null; protected volatile Room shipCombatRoom = null; protected PairList<Item, int[]> coordinates = null; protected PairList<Weapon, int[]> aimings = new PairVector<Weapon, int[]>(); protected List<Item> smallTenderRequests = new SLinkedList<Item>(); protected volatile Room prevItemRoom = null; protected int maxHullPoints = -1; protected volatile int lastSpamCt = 0; protected volatile String lastSpamMsg = ""; public GenSailingShip() { super(); setName("a sailing ship [NEWNAME]"); setDisplayText("a sailing ship [NEWNAME] is here."); setMaterial(RawMaterial.RESOURCE_OAK); basePhyStats().setAbility(2); this.recoverPhyStats(); } @Override public boolean isGeneric() { return true; } @Override public void recoverPhyStats() { super.recoverPhyStats(); if(owner instanceof Room) { if(usesRemaining()>0) phyStats().setDisposition(phyStats().disposition()|PhyStats.IS_SWIMMING); else phyStats().setDisposition(phyStats().disposition()|PhyStats.IS_FALLING); } } @Override protected String getAreaClassType() { return "StdBoardableShip"; } @Override protected Room createFirstRoom() { final Room R=CMClass.getLocale("WoodenDeck"); R.setDisplayText(L("The Deck")); return R; } @Override public Area getShipArea() { if((!destroyed) &&(area==null)) { final Area area=super.getShipArea(); if(area != null) area.setTheme(Area.THEME_FANTASY); return area; } return super.getShipArea(); } private enum SailingCommand { RAISE_ANCHOR, WEIGH_ANCHOR, LOWER_ANCHOR, STEER, SAIL, COURSE, SET_COURSE, TARGET, AIM, SINK, TENDER, RAISE, LOWER, JUMP ; } protected void announceToDeck(final String msgStr) { final CMMsg msg=CMClass.getMsg(null, CMMsg.MSG_OK_ACTION, msgStr); announceToDeck(msg); } @Override public int getShipSpeed() { int speed=phyStats().ability(); if(subjectToWearAndTear()) { if(usesRemaining()<10) return 0; speed=(int)Math.round(speed * CMath.div(usesRemaining(), 100)); } if(speed <= 0) return 1; return speed; } protected void announceToDeck(final CMMsg msg) { MOB mob = null; final MOB msgSrc = msg.source(); try { final Area A=this.getShipArea(); if(A!=null) { Room mobR = null; for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) && ((R.domainType()&Room.INDOORS)==0)) { mobR=R; break; } } if(mobR!=null) { mob = CMClass.getFactoryMOB(name(),phyStats().level(),mobR); msg.setSource(mob); for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) && ((R.domainType()&Room.INDOORS)==0) && (R.okMessage(mob, msg))) { if(R == mobR) R.send(mob, msg); // this lets the source know, i guess else R.sendOthers(mob, msg); // this lets the source know, i guess } } } } } finally { msg.setSource(msgSrc); if(mob != null) mob.destroy(); } } protected void announceActionToDeckOrUnderdeck(final MOB mob, final CMMsg msg, final int INDOORS) { final Area A=this.getShipArea(); final Room mobR=CMLib.map().roomLocation(mob); if(A!=null) { for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) && ((R.domainType()&Room.INDOORS)==INDOORS) && (R.okMessage(mob, msg))) { if(R == mobR) R.send(mob, msg); // this lets the source know, i guess else R.sendOthers(mob, msg); // this lets the source know, i guess } } } } protected void announceActionToDeck(final MOB mob, final String msgStr) { final CMMsg msg=CMClass.getMsg(mob, CMMsg.MSG_OK_ACTION, msgStr); announceActionToDeckOrUnderdeck(mob,msg, 0); } protected void announceActionToDeck(final MOB mob, final Environmental target, final Environmental tool, final String msgStr) { final CMMsg msg=CMClass.getMsg(mob, target, tool, CMMsg.MSG_OK_ACTION, msgStr); announceActionToDeckOrUnderdeck(mob,msg, 0); } protected void announceActionToUnderDeck(final MOB mob, final String msgStr) { final CMMsg msg=CMClass.getMsg(mob, CMMsg.MSG_OK_ACTION, msgStr); announceActionToDeckOrUnderdeck(mob,msg, Room.INDOORS); } protected String getTargetedShipInfo() { final PhysicalAgent targetedShip = this.targetedShip; return getOtherShipInfo(targetedShip); } protected String getOtherShipInfo(final PhysicalAgent targetedShip) { if((targetedShip != null)&&(targetedShip instanceof GenSailingShip)) { final GenSailingShip targetShip = (GenSailingShip)targetedShip; final int[] targetCoords = targetShip.getMyCoords(); final int[] myCoords = this.getMyCoords(); if((myCoords!=null)&&(targetCoords != null)) { final String dist = ""+this.getTacticalDistance(targetShip); final String dir=CMLib.directions().getDirectionName(targetShip.directionFacing); final String speed=""+targetShip.getShipSpeed(); final String dirFromYou = CMLib.directions().getDirectionName(Directions.getRelative11Directions(myCoords, targetCoords)); return L("@x1 is @x2 of you sailing @x3 at a speed of @x4 and a distance of @x5.",targetShip.name(),dirFromYou,dir,speed,dist); } } return ""; } protected int getDirectionToTarget(final PhysicalAgent targetedShip) { if((targetedShip != null)&&(targetedShip instanceof GenSailingShip)) { final GenSailingShip targetShip = (GenSailingShip)targetedShip; final int[] targetCoords = targetShip.getMyCoords(); final int[] myCoords = this.getMyCoords(); if((myCoords!=null)&&(targetCoords != null)) return Directions.getRelative11Directions(myCoords, targetCoords); } return -1; } protected String getDirectionStrToTarget(final PhysicalAgent targetedShip) { if((targetedShip != null)&&(targetedShip instanceof GenSailingShip)) { final GenSailingShip targetShip = (GenSailingShip)targetedShip; final int[] targetCoords = targetShip.getMyCoords(); final int[] myCoords = this.getMyCoords(); if((myCoords!=null)&&(targetCoords != null)) return CMLib.directions().getDirectionName(Directions.getRelative11Directions(myCoords, targetCoords)); } return ""; } protected Room getRandomDeckRoom() { final Area A=this.getShipArea(); if(A!=null) { final List<Room> deckRooms=new ArrayList<Room>(2); for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) && ((R.domainType()&Room.INDOORS)==0) && (R.domainType()!=Room.DOMAIN_OUTDOORS_AIR)) deckRooms.add(R); } if(deckRooms.size()>0) { return deckRooms.get(CMLib.dice().roll(1, deckRooms.size(), -1)); } } return null; } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { switch(msg.sourceMinor()) { case CMMsg.TYP_HUH: case CMMsg.TYP_COMMANDFAIL: case CMMsg.TYP_COMMAND: break; default: if(!confirmAreaMessage(msg, true)) return false; break; } if((msg.target() == this) &&(msg.tool()!=null) &&(msg.tool().ID().equals("AWaterCurrent"))) { if(anchorDown) return false; } else if((msg.sourceMinor()==CMMsg.TYP_HUH) &&(msg.targetMessage()!=null) &&(area == CMLib.map().areaLocation(msg.source()))) { final List<String> cmds=CMParms.parse(msg.targetMessage()); if(cmds.size()==0) return true; final String word=cmds.get(0).toUpperCase(); final String secondWord=(cmds.size()>1) ? cmds.get(1).toUpperCase() : ""; SailingCommand cmd=null; if(secondWord.length()>0) cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word+"_"+secondWord); if(cmd == null) cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word); if(cmd != null) { switch(cmd) { case TARGET: { if(cmds.size()==1) { msg.source().tell(L("You must specify another ship to target.")); return false; } final Room thisRoom = (Room)owner(); if(thisRoom==null) { msg.source().tell(L("This ship is nowhere to be found!")); return false; } final String rest = CMParms.combine(cmds,1); final Boolean result = startAttack(msg.source(),thisRoom,rest); if(result == Boolean.TRUE) { if(this.targetedShip != null) msg.source().tell(L("You are now targeting @x1.",this.targetedShip.Name())); msg.source().tell(getTargetedShipInfo()); } else if(result == Boolean.FALSE) return false; else { msg.source().tell(L("You don't see '@x1' here to target",rest)); return false; } break; } case TENDER: { if(cmds.size()==1) { msg.source().tell(L("You must specify another ship to offer aboard.")); return false; } final Room thisRoom = (Room)owner(); if(thisRoom==null) { msg.source().tell(L("This ship is nowhere to be found!")); return false; } if(this.targetedShip!=null) { msg.source().tell(L("Not while you are in combat!")); return false; } final String rest = CMParms.combine(cmds,1); final Item I=thisRoom.findItem(rest); if((I instanceof GenSailingShip)&&(I!=this)&&(CMLib.flags().canBeSeenBy(I, msg.source()))) { final GenSailingShip otherShip = (GenSailingShip)I; if(otherShip.targetedShip != null) { msg.source().tell(L("Not while @x1 is in in combat!",otherShip.Name())); return false; } final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),thisRoom); try { mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); if(otherShip.tenderShip == this) { if(thisRoom.show(mob, otherShip, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> connect(s) her gangplank with <T-NAME>"))) { this.tenderShip = otherShip; final BoardableShip myArea=(BoardableShip)this.getShipArea(); final BoardableShip hisArea=(BoardableShip)otherShip.getShipArea(); final Room hisExitRoom = hisArea.unDock(false); final Room myExitRoom = myArea.unDock(false); myArea.dockHere(hisExitRoom); hisArea.dockHere(myExitRoom); } } else { if(thisRoom.show(mob, otherShip, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> extend(s) her gangplank toward(s) <T-NAME>"))) this.tenderShip = otherShip; } } finally { mob.destroy(); } } else { msg.source().tell(L("You don't see the ship '@x1' here to board",rest)); return false; } break; } case SINK: { if(!CMSecurity.isAllowedEverywhere(msg.source(), CMSecurity.SecFlag.CMDROOMS)) return true; final CMMsg damageMsg=CMClass.getMsg(msg.source(), this, CMMsg.MSG_DAMAGE, "SINK!!!"); damageMsg.setValue(99999); this.executeMsg(this, damageMsg); return false; } case JUMP: { final Room thisRoom = (Room)owner(); if(thisRoom==null) { msg.source().tell(L("This ship is nowhere to be found!")); return false; } final MOB mob=msg.source(); final Room mobR = mob.location(); if(mobR != null) { if(cmds.size()<2) mobR.show(mob, null, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> jump(s) in place.")); else { final String str=CMParms.combine(cmds,1).toLowerCase(); if(("overboard").startsWith(str) || ("water").startsWith(str)) { if(((mobR.domainType()&Room.INDOORS)==0) && (mobR.domainType()!=Room.DOMAIN_OUTDOORS_AIR)) msg.source().tell(L("You must be on deck to jump overboard.")); else if(mobR.show(mob, null, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> jump(s) overboard."))) CMLib.tracking().walkForced(mob, mobR, thisRoom, true, true, L("<S-NAME> arrive(s) from @x1.",name())); } else msg.source().tell(L("Jump where? Try JUMP OVERBOARD.")); } return false; } return false; } case AIM: { final Room thisRoom = (Room)owner(); if(thisRoom==null) { msg.source().tell(L("This ship is nowhere to be found!")); return false; } if((!this.amInTacticalMode()) ||(this.targetedShip==null) ||(!thisRoom.isContent((Item)this.targetedShip))) { msg.source().tell(L("You ship must be targeting an enemy to aim weapons.")); return false; } if(cmds.size()<3) { msg.source().tell(L("Aim what weapon how far ahead?")); msg.source().tell(getTargetedShipInfo()); return false; } final String leadStr = cmds.remove(cmds.size()-1); final String weaponStr = CMParms.combine(cmds,1); final Room mobR=msg.source().location(); if((!CMath.isInteger(leadStr))||(CMath.s_int(leadStr)<0)) { if(this.targetedShip!=null) msg.source().tell(L("'@x1' is not a valid distance ahead of @x2 to fire.",leadStr,this.targetedShip.name())); else msg.source().tell(L("'@x1' is not a valid distance.",leadStr)); return false; } if(mobR!=null) { final Item I=mobR.findItem(null, weaponStr); if((I==null)||(!CMLib.flags().canBeSeenBy(I,msg.source()))) { msg.source().tell(L("You don't see any siege weapon called '@x1' here.",leadStr)); return false; } if(!CMLib.combat().isAShipSiegeWeapon(I)) { msg.source().tell(L("@x1 is not a useable siege weapon.",leadStr)); return false; } final AmmunitionWeapon weapon=(AmmunitionWeapon)I; int distance = weapon.maxRange(); int[] targetCoords = new int[2]; int leadAmt=0; if(this.targetedShip instanceof GenSailingShip) { targetCoords = ((GenSailingShip)this.targetedShip).getMyCoords(); final int direction = ((GenSailingShip)this.targetedShip).directionFacing; if(targetCoords == null) { msg.source().tell(L("You ship must be targeting an enemy to aim weapons.")); return false; } distance = this.getTacticalDistance(this.targetedShip); leadAmt = CMath.s_int(leadStr); for(int i=0;i<leadAmt;i++) targetCoords = Directions.adjustXYByDirections(targetCoords[0], targetCoords[1], direction); } if((weapon.maxRange() < distance)||(weapon.minRange() > distance)) { msg.source().tell(L("Your target is presently at distance of @x1, but this weapons range is @x2 to @x3.", ""+distance,""+weapon.minRange(),""+weapon.maxRange())); return false; } if(weapon.requiresAmmunition() && (weapon.ammunitionCapacity() > 0) && (weapon.ammunitionRemaining() == 0)) { msg.source().tell(L("@x1 needs to be LOADed first.",weapon.Name())); return false; } final String timeToFire=""+(CMLib.threads().msToNextTick((Tickable)CMLib.combat(), Tickable.TICKID_SUPPORT|Tickable.TICKID_SOLITARYMASK) / 1000); final String msgStr=L("<S-NAME> aim(s) <O-NAME> at <T-NAME> (@x1).",""+leadAmt); if(msg.source().isMonster() && aimings.containsFirst(weapon)) { msg.source().tell(L("@x1 is already aimed.",weapon.Name())); return false; } final CMMsg msg2=CMClass.getMsg(msg.source(), targetedShip, weapon, CMMsg.MSG_NOISYMOVEMENT, msgStr); if(mobR.okMessage(msg.source(), msg2)) { this.aimings.removeFirst(weapon); this.aimings.add(new Pair<Weapon,int[]>(weapon,targetCoords)); mobR.send(msg.source(), msg2); msg.source().tell(L("@x1 is now aimed and will be fired in @x2 seconds.",I.name(),timeToFire)); } } return false; } case RAISE: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } final Room R=CMLib.map().roomLocation(this); final Room targetR=msg.source().location(); if((R!=null)&&(targetR!=null)) { if(((targetR.domainType()&Room.INDOORS)==0) && (targetR.domainType()!=Room.DOMAIN_OUTDOORS_AIR) &&(msg.source().isPlayer())) { msg.source().tell(L("You must be on deck to raise a tendered ship.")); return false; } final String rest = CMParms.combine(cmds,1); final Item I=R.findItem(rest); if((I!=this)&&(CMLib.flags().canBeSeenBy(I, msg.source()))) { if((I instanceof Rideable) &&(((Rideable)I).mobileRideBasis())) { if(smallTenderRequests.contains(I)) { final MOB riderM=getBestRider(R,(Rideable)I); if(((riderM==null)||(R.show(riderM, R, CMMsg.MSG_LEAVE, null))) &&(R.show(msg.source(), I, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> raise(s) <T-NAME> up onto @x1.",name()))) &&((riderM==null)||(R.show(riderM, targetR, CMMsg.MSG_ENTER, null)))) { smallTenderRequests.remove(I); targetR.moveItemTo(I, Expire.Never, Move.Followers); } return false; } else { msg.source().tell(L("You can only raise @x1 once it has tendered itself to this one.",I.name())); return false; } } else { msg.source().tell(L("You don't think @x1 is a suitable boat.",I.name())); return false; } } else { msg.source().tell(L("You don't see '@x1' out there!",rest)); return false; } } break; } case LOWER: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } final Room R=msg.source().location(); final Room targetR=CMLib.map().roomLocation(this); if((R!=null)&&(targetR!=null)) { if(((R.domainType()&Room.INDOORS)==0) && (R.domainType()!=Room.DOMAIN_OUTDOORS_AIR) &&(msg.source().isPlayer())) { msg.source().tell(L("You must be on deck to lower a boat.")); return false; } final String rest = CMParms.combine(cmds,1); final Item I=R.findItem(rest); if((I!=this)&&(CMLib.flags().canBeSeenBy(I, msg.source()))) { if((I instanceof Rideable) &&(((Rideable)I).mobileRideBasis()) &&((((Rideable)I).rideBasis()==Rideable.RIDEABLE_WATER) ||(((Rideable)I).rideBasis()==Rideable.RIDEABLE_AIR))) { final MOB riderM=getBestRider(R,(Rideable)I); if(((riderM==null)||(R.show(riderM, R, CMMsg.MSG_LEAVE, null))) &&(targetR.show(msg.source(), I, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> lower(s) <T-NAME> off of @x1.",name()))) &&((riderM==null)||(R.show(riderM, targetR, CMMsg.MSG_ENTER, null)))) { this.smallTenderRequests.remove(I); targetR.moveItemTo(I, Expire.Never, Move.Followers); } return false; } else { msg.source().tell(L("You don't think @x1 is a suitable thing for lowering.",I.name())); return false; } } else { msg.source().tell(L("You don't see '@x1' out there!",rest)); return false; } } break; } case WEIGH_ANCHOR: case RAISE_ANCHOR: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } if(safetyMove()) { msg.source().tell(L("The ship has moved!")); return false; } final Room R=CMLib.map().roomLocation(this); if(!anchorDown) msg.source().tell(L("The anchor is already up.")); else if(R!=null) { final CMMsg msg2=CMClass.getMsg(msg.source(), this, null, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> raise(s) anchor on <T-NAME>.")); if((R.okMessage(msg.source(), msg2) && this.okAreaMessage(msg2, true))) { R.send(msg.source(), msg2); anchorDown=false; } } return false; } case LOWER_ANCHOR: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } if(safetyMove()) { msg.source().tell(L("The ship has moved!")); return false; } final Room R=CMLib.map().roomLocation(this); if(anchorDown) msg.source().tell(L("The anchor is already down.")); else if(R!=null) { final CMMsg msg2=CMClass.getMsg(msg.source(), this, null, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> lower(s) anchor on <T-NAME>.")); if((R.okMessage(msg.source(), msg2) && this.okAreaMessage(msg2, true))) { R.send(msg.source(), msg2); this.sendAreaMessage(msg2, true); anchorDown=true; } } return false; } case STEER: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } if(CMLib.flags().isFalling(this) || ((this.subjectToWearAndTear() && (usesRemaining()<=0)))) { msg.source().tell(L("The ship won't seem to move!")); return false; } if(safetyMove()) { msg.source().tell(L("The ship has moved!")); return false; } if((courseDirection >=0)||(courseDirections.size()>0)) { if(!this.amInTacticalMode()) msg.source().tell(L("Your previous course has been cancelled.")); courseDirection = -1; courseDirections.clear(); } final int dir=CMLib.directions().getCompassDirectionCode(secondWord); if(dir<0) { msg.source().tell(L("Steer the ship which direction?")); return false; } final Room R=CMLib.map().roomLocation(this); if((R==null)||(msg.source().location()==null)) { msg.source().tell(L("You are nowhere, so you won`t be moving anywhere.")); return false; } if(((msg.source().location().domainType()&Room.INDOORS)==Room.INDOORS) &&(msg.source().isPlayer())) { msg.source().tell(L("You must be on deck to steer your ship.")); return false; } final String dirName = CMLib.directions().getDirectionName(dir); if(!this.amInTacticalMode()) { final Room targetRoom=R.getRoomInDir(dir); final Exit targetExit=R.getExitInDir(dir); if((targetRoom==null)||(targetExit==null)||(!targetExit.isOpen())) { msg.source().tell(L("There doesn't look to be anything in that direction.")); return false; } } else { directionFacing = getDirectionFacing(dir); if(dir == this.directionFacing) { msg.source().tell(L("Your ship is already sailing @x1.",dirName)); return false; } } if(anchorDown) { msg.source().tell(L("The anchor is down, so you won`t be moving anywhere.")); return false; } break; } case SAIL: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } if(CMLib.flags().isFalling(this) || ((this.subjectToWearAndTear() && (usesRemaining()<=0)))) { msg.source().tell(L("The ship won't seem to move!")); return false; } if(safetyMove()) { msg.source().tell(L("The ship has moved!")); return false; } if((courseDirection >=0)||(courseDirections.size()>0)) { if(!this.amInTacticalMode()) msg.source().tell(L("Your previous course has been cancelled.")); courseDirection = -1; courseDirections.clear(); } final Room R=CMLib.map().roomLocation(this); if((R==null)||(msg.source().location()==null)) { msg.source().tell(L("You are nowhere, so you won`t be moving anywhere.")); return false; } if(((msg.source().location().domainType()&Room.INDOORS)==Room.INDOORS) &&(msg.source().isPlayer())) { msg.source().tell(L("You must be on deck to sail your ship.")); return false; } final int dir=CMLib.directions().getCompassDirectionCode(secondWord); if(dir<0) { msg.source().tell(L("Sail the ship which direction?")); return false; } if(!this.amInTacticalMode()) { final Room targetRoom=R.getRoomInDir(dir); final Exit targetExit=R.getExitInDir(dir); if((targetRoom==null)||(targetExit==null)||(!targetExit.isOpen())) { msg.source().tell(L("There doesn't look to be anything in that direction.")); return false; } } else { final String dirName = CMLib.directions().getDirectionName(directionFacing); directionFacing = getDirectionFacing(dir); if(dir != this.directionFacing) { msg.source().tell(L("When in tactical mode, your ship can only SAIL @x1. Use COURSE for more complex maneuvers, or STEER.",dirName)); return false; } } if(anchorDown) { msg.source().tell(L("The anchor is down, so you won`t be moving anywhere.")); return false; } break; } case COURSE: case SET_COURSE: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } if(CMLib.flags().isFalling(this) || ((this.subjectToWearAndTear() && (usesRemaining()<=0)))) { msg.source().tell(L("The ship won't seem to move!")); return false; } if(safetyMove()) { msg.source().tell(L("The ship has moved!")); return false; } if((courseDirection >=0)||(courseDirections.size()>0)) { if(!this.amInTacticalMode()) msg.source().tell(L("Your previous course has been cancelled.")); courseDirection = -1; courseDirections.clear(); } final Room R=CMLib.map().roomLocation(this); if((R==null)||(msg.source().location()==null)) { msg.source().tell(L("You are nowhere, so you won`t be moving anywhere.")); return false; } if(((msg.source().location().domainType()&Room.INDOORS)==Room.INDOORS) &&(msg.source().isPlayer())) { msg.source().tell(L("You must be on deck to steer your ship.")); return false; } int dirIndex = 1; if(word.equals("SET")) dirIndex = 2; int firstDir = -1; this.courseDirections.clear(); if(amInTacticalMode()) { final int speed=getShipSpeed(); final String dirFacingName = CMLib.directions().getDirectionName(directionFacing); if(dirIndex >= cmds.size()) { msg.source().tell(L("Your ship is currently sailing @x1. To set a course, you must specify up to @x2 directions of travel, " + "of which only the last may be something other than @x3.",dirFacingName,""+speed,dirFacingName)); return false; } final List<String> dirNames = new ArrayList<String>(); final int[] coordinates = Arrays.copyOf(getMyCoords(),2); int otherDir = -1; for(;dirIndex<cmds.size();dirIndex++) { final String dirWord=cmds.get(dirIndex); final int dir=CMLib.directions().getCompassDirectionCode(dirWord); if(dir<0) { msg.source().tell(L("@x1 is not a valid direction.",dirWord)); return false; } if((otherDir < 0) && (dir == directionFacing)) { Directions.adjustXYByDirections(coordinates[0], coordinates[1], dir); final Room targetRoom=R.getRoomInDir(dir); final Exit targetExit=R.getExitInDir(dir); if((targetRoom==null)||(targetExit==null)||(!targetExit.isOpen())) { if(getLowestTacticalDistanceFromThis() >= R.maxRange()) { msg.source().tell(L("There doesn't look to be anywhere you can sail in that direction.")); return false; } } } if(this.courseDirections.size() >= speed) { msg.source().tell(L("Your course may not exceed your tactical speed, which is @x1 moves.", ""+speed)); return false; } if(otherDir > 0) { msg.source().tell(L("Your course includes a change of direction, from @x1 to @x2. " + "In tactical maneuvers, a changes of direction must be at the end of the course settings.", dirFacingName,CMLib.directions().getDirectionName(otherDir))); return false; } else if(dir != directionFacing) otherDir = dir; dirNames.add(CMLib.directions().getDirectionName(dir).toLowerCase()); this.courseDirections.add(Integer.valueOf(dir)); } this.courseDirection = this.removeTopCourse(); if((this.courseDirections.size()==0)||(getBottomCourse()>=0)) this.courseDirections.add(Integer.valueOf(-1)); this.announceActionToDeck(msg.source(),L("<S-NAME> order(s) a course setting of @x1.",CMLib.english().toEnglishStringList(dirNames.toArray(new String[0])))); } else { if(dirIndex >= cmds.size()) { msg.source().tell(L("To set a course, you must specify some directions of travel, separated by spaces.")); return false; } for(;dirIndex<cmds.size();dirIndex++) { final String dirWord=cmds.get(dirIndex); final int dir=CMLib.directions().getCompassDirectionCode(dirWord); if(dir<0) { msg.source().tell(L("@x1 is not a valid direction.",dirWord)); return false; } if(firstDir < 0) firstDir = dir; else this.courseDirections.add(Integer.valueOf(dir)); } final Room targetRoom=R.getRoomInDir(firstDir); final Exit targetExit=R.getExitInDir(firstDir); if((targetRoom==null)||(targetExit==null)||(!targetExit.isOpen())) { this.courseDirection=-1; this.courseDirections.clear(); msg.source().tell(L("There doesn't look to be anything in that direction.")); return false; } if((this.courseDirections.size()==0)||(getBottomCourse()>=0)) this.courseDirections.add(Integer.valueOf(-1)); steer(msg.source(),R, firstDir); } if(anchorDown) msg.source().tell(L("The anchor is down, so you won`t be moving anywhere.")); return false; } } } if(cmd != null) { cmds.add(0, "METAMSGCOMMAND"); double speed=getShipSpeed(); if(speed == 0) speed=0; else speed = msg.source().phyStats().speed() / speed; msg.source().enqueCommand(cmds, MUDCmdProcessor.METAFLAG_ASMESSAGE, speed); return false; } } else if((msg.sourceMinor()==CMMsg.TYP_COMMAND) &&(msg.sourceMessage()!=null) &&(area == CMLib.map().areaLocation(msg.source()))) { final List<String> cmds=CMParms.parse(msg.sourceMessage()); if(cmds.size()==0) return true; final String word=cmds.get(0).toUpperCase(); final String secondWord=(cmds.size()>1) ? cmds.get(1).toUpperCase() : ""; SailingCommand cmd = null; if(secondWord.length()>0) cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word+"_"+secondWord); if(cmd == null) cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word); if(cmd == null) return true; switch(cmd) { case SAIL: { final int dir=CMLib.directions().getCompassDirectionCode(secondWord); if(dir<0) return false; final Room R=CMLib.map().roomLocation(this); if(R==null) return false; if(!this.amInTacticalMode()) { this.courseDirections.clear(); // sail eliminates a course this.courseDirections.add(Integer.valueOf(-1)); this.beginSail(msg.source(), R, dir); } else { if(this.courseDirections.size()>0) msg.source().tell(L("Your prior course has been overridden.")); this.courseDirections.clear(); this.courseDirections.add(Integer.valueOf(-1)); this.courseDirection = dir; this.announceActionToDeck(msg.source(),L("<S-NAME> start(s) sailing @x1.",CMLib.directions().getDirectionName(dir))); } return false; } case STEER: { final int dir=CMLib.directions().getCompassDirectionCode(secondWord); if(dir<0) return false; final Room R=CMLib.map().roomLocation(this); if(R==null) return false; if(!this.amInTacticalMode()) { steer(msg.source(),R, dir); } else { if(this.courseDirections.size()>0) msg.source().tell(L("Your prior tactical course has been overridden.")); this.courseDirections.clear(); this.courseDirections.add(Integer.valueOf(-1)); this.courseDirection = dir; this.announceActionToDeck(msg.source(),L("<S-NAME> start(s) steering the ship @x1.",CMLib.directions().getDirectionName(dir))); } return false; } default: // already done... return false; } } else if((msg.targetMinor()==CMMsg.TYP_SIT) &&(msg.target()==this) &&(msg.source().location()==owner()) &&(CMLib.flags().isWateryRoom(msg.source().location())) &&(!CMLib.flags().isFlying(msg.source())) &&(!CMLib.flags().isFalling((Physical)msg.target())) &&(!CMLib.law().doesHavePriviledgesHere(msg.source(), super.getDestinationRoom(msg.source().location())))) { final Rideable ride=msg.source().riding(); if(ticksSinceMove < 2) { if(ride == null) msg.source().tell(CMLib.lang().L("You'll need some assistance to board a ship from the water.")); else msg.source().tell(msg.source(),this,ride,CMLib.lang().L("<S-NAME> chase(s) <T-NAME> around in <O-NAME>.")); return false; } else if(ride == null) { msg.source().tell(CMLib.lang().L("You'll need some assistance to board a ship from the water.")); return false; } else if(!CMLib.flags().isClimbing(msg.source())) { msg.source().tell(CMLib.lang().L("You'll need some assistance to board a ship from @x1, such as some means to climb up.",ride.name(msg.source()))); return false; } else msg.source().setRiding(null); // if you're climbing, you're not riding any more } else if((msg.sourceMinor()==CMMsg.TYP_COMMANDFAIL) &&(msg.targetMessage()!=null) &&(msg.targetMessage().length()>0)) { switch(Character.toUpperCase(msg.targetMessage().charAt(0))) { case 'A': { final List<String> parsedFail = CMParms.parse(msg.targetMessage()); final String cmd=parsedFail.get(0).toUpperCase(); if(("ATTACK".startsWith(cmd))&&(owner() instanceof Room)) { final Room thisRoom = (Room)owner(); final String rest = CMParms.combine(parsedFail,1); if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } final Boolean result = startAttack(msg.source(),thisRoom,rest); if(result == Boolean.FALSE) return false; else if(result == Boolean.TRUE) { msg.source().tell(getTargetedShipInfo()); return false; } } break; } case 'E': case 'L': { final List<String> parsedFail = CMParms.parse(msg.targetMessage()); final String cmd=parsedFail.get(0).toUpperCase(); if(("LOOK".startsWith(cmd)||"LLOOK".startsWith(cmd)||"EXAMINE".startsWith(cmd)) &&(owner() instanceof Room)) { final int msgType = "EXAMINE".startsWith(cmd) ? CMMsg.MSG_EXAMINE : CMMsg.MSG_LOOK; final Room R = (Room)owner(); final String rest = CMParms.combine(parsedFail,1); final Item I = R.findItem(null, rest); if((I instanceof GenSailingShip) ||((I instanceof Rideable)&&(((Rideable)I).rideBasis()==Rideable.RIDEABLE_WATER))) { final CMMsg lookMsg=CMClass.getMsg(msg.source(),I,null,msgType,null,msgType,null,msgType,null); if(R.okMessage(msg.source(),lookMsg)) { R.send(msg.source(),lookMsg); return false; } } } break; } case 'T': // throwing things to another ship, like a grapple { final List<String> parsedFail = CMParms.parse(msg.targetMessage()); final String cmd=parsedFail.get(0).toUpperCase(); if(("THROW".startsWith(cmd)) &&(owner() instanceof Room) &&(msg.source().location()!=null) &&((msg.source().location().domainType()&Room.INDOORS)==0) &&(parsedFail.size()>2)) { parsedFail.remove(0); final MOB mob=msg.source(); final Room R = (Room)owner(); String str=parsedFail.get(parsedFail.size()-1); parsedFail.remove(str); final String what=CMParms.combine(parsedFail,0); Item item=mob.fetchItem(null,Wearable.FILTER_WORNONLY,what); if(item==null) item=mob.findItem(null,what); if((item!=null) &&(CMLib.flags().canBeSeenBy(item,mob)) &&((item.amWearingAt(Wearable.WORN_HELD))||(item.amWearingAt(Wearable.WORN_WIELD)))) { str=str.toLowerCase(); if(str.equals("water")||str.equals("overboard")||CMLib.english().containsString(R.displayText(), str)) { final Room target=R; final CMMsg msg2=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<S-NAME> throw(s) <O-NAME> overboard.")); final CMMsg msg3=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<O-NAME> fl(ys) in from @x1.",name())); if(mob.location().okMessage(mob,msg2)&&target.okMessage(mob,msg3)) { mob.location().send(mob,msg2); target.sendOthers(mob,msg3); } return false; } final Item I = R.findItem(null, str); if(I!=this) { if((I instanceof GenSailingShip) ||((I instanceof Rideable)&&(((Rideable)I).rideBasis()==Rideable.RIDEABLE_WATER))) { if((!amInTacticalMode()) ||(I.maxRange() < getTacticalDistance(I))) { msg.source().tell(L("You can't throw @x1 at @x2, it's too far away!",item.name(msg.source()),I.name(msg.source()))); return false; } else if(getMyCoords()!=null) { final int[] targetCoords = ((GenSailingShip)I).getMyCoords(); if(targetCoords!=null) { final int dir = Directions.getRelativeDirection(getMyCoords(), targetCoords); final String inDir=CMLib.directions().getShipInDirectionName(dir); final String fromDir=CMLib.directions().getFromShipDirectionName(Directions.getOpDirectionCode(dir)); Room target = ((GenSailingShip)I).getRandomDeckRoom(); if(target == null) target=R; final CMMsg msg2=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<S-NAME> throw(s) <O-NAME> @x1.",inDir.toLowerCase())); final CMMsg msg3=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<O-NAME> fl(ys) in from @x1.",fromDir.toLowerCase())); if(mob.location().okMessage(mob,msg2)&&target.okMessage(mob,msg3)) { mob.location().send(mob,msg2); target.sendOthers(mob,msg3); } return false; } else { msg.source().tell(L("You can't throw @x1 at @x2, it's too far away!",item.name(msg.source()),I.name(msg.source()))); return false; } } else { msg.source().tell(L("You can't throw @x1 at @x2, it's too far away!",item.name(msg.source()),I.name(msg.source()))); return false; } } } } } break; } } } else if((msg.targetMinor()==CMMsg.TYP_LEAVE) &&(msg.target() instanceof Room) &&(msg.target() == owner())) { if((msg.source().riding() != null) &&(this.targetedShip == msg.source().riding()) &&(CMLib.flags().isWaterWorthy(msg.source().riding()))) { msg.source().tell(L("Your small vessel can not get away during combat.")); return false; } if(msg.tool() instanceof Exit) { final Room R=msg.source().location(); final int dir=CMLib.map().getExitDir(R,(Exit)msg.tool()); if((dir >= 0) &&(R.getRoomInDir(dir)!=null) &&(R.getRoomInDir(dir).getArea()==this.getShipArea()) &&(msg.othersMessage()!=null) &&(msg.othersMessage().indexOf("<S-NAME>")>=0) &&(msg.othersMessage().indexOf(L(CMLib.flags().getPresentDispositionVerb(msg.source(),CMFlagLibrary.ComingOrGoing.LEAVES)))>=0)) msg.setOthersMessage(L("<S-NAME> board(s) @x1.",Name())); } } else if((msg.targetMinor()==CMMsg.TYP_ENTER) &&(msg.target() == owner()) &&(msg.source().location()!=null) &&(msg.source().location().getArea()==this.getShipArea()) &&(msg.tool() instanceof Exit) &&(msg.othersMessage()!=null) &&(msg.othersMessage().indexOf("<S-NAME>")>=0) &&(msg.othersMessage().indexOf(L(CMLib.flags().getPresentDispositionVerb(msg.source(),CMFlagLibrary.ComingOrGoing.ARRIVES)))>=0)) msg.setOthersMessage(L("<S-NAME> disembark(s) @x1.",Name())); else if((msg.sourceMinor()==CMMsg.TYP_HUH) &&(msg.targetMessage()!=null) &&(msg.source().riding() instanceof Item) &&(msg.source().riding().mobileRideBasis()) &&(owner() == CMLib.map().roomLocation(msg.source()))) { final List<String> cmds=CMParms.parse(msg.targetMessage()); if(cmds.size()==0) return true; final String word=cmds.get(0).toUpperCase(); final String secondWord=(cmds.size()>1) ? cmds.get(1).toUpperCase() : ""; SailingCommand cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word); if((cmd == null)&&(secondWord.length()>0)) cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word+"_"+secondWord); if(cmd != null) { switch(cmd) { default: break; case TENDER: { if(cmds.size()==1) { msg.source().tell(L("You must specify another ship to offer to board.")); return false; } final Room thisRoom = (Room)owner(); if(thisRoom==null) { msg.source().tell(L("This ship is nowhere to be found!")); return false; } /*//TODO: maybe check to see if the lil ship is if(this.targetedShip!=null) { msg.source().tell(L("Not while you are in combat!")); return false; } */ final String rest = CMParms.combine(cmds,1); final Item meI=thisRoom.findItem(rest); if((meI==this) &&(CMLib.flags().canBeSeenBy(this, msg.source()))) { if(targetedShip != null) { msg.source().tell(L("Not while @x1 is in in combat!",Name())); return false; } final Room R=CMLib.map().roomLocation(msg.source()); if((R!=null) &&(R.show(msg.source(), this, CMMsg.TYP_ADVANCE, L("<S-NAME> tender(s) @x1 alonside <T-NAME>, waiting to be raised on board.",msg.source().riding().name())))) { for(final Iterator<Item> i=smallTenderRequests.iterator();i.hasNext();) { final Item I=i.next(); if(!R.isContent(I)) smallTenderRequests.remove(I); } final Rideable sR=msg.source().riding(); if(sR instanceof Item) { final Item isR = (Item)sR; if(!smallTenderRequests.contains(isR)) smallTenderRequests.add(isR); } } } else { msg.source().tell(L("You don't see the ship '@x1' here to tender with",rest)); return false; } break; } } } } if(!super.okMessage(myHost, msg)) return false; return true; } protected Boolean startAttack(final MOB sourceM, final Room thisRoom, final String rest) { final Item I=thisRoom.findItem(rest); if((I instanceof Rideable)&&(I!=this)&&(CMLib.flags().canBeSeenBy(I, sourceM))) { if(!sourceM.mayPhysicallyAttack(I)) { sourceM.tell(L("You are not permitted to attack @x1",I.name())); return Boolean.FALSE; } if(!CMLib.flags().isDeepWaterySurfaceRoom(thisRoom)) { sourceM.tell(L("You are not able to engage in combat with @x1 here.",I.name())); return Boolean.FALSE; } final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),thisRoom); try { mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); final CMMsg maneuverMsg=CMClass.getMsg(mob,I,null,CMMsg.MSG_ADVANCE,null,CMMsg.MASK_MALICIOUS|CMMsg.MSG_ADVANCE,null,CMMsg.MSG_ADVANCE,L("<S-NAME> engage(s) @x1.",I.Name())); if(thisRoom.okMessage(mob, maneuverMsg)) { thisRoom.send(mob, maneuverMsg); targetedShip = I; shipCombatRoom = thisRoom; if(I instanceof GenSailingShip) { final GenSailingShip otherI=(GenSailingShip)I; if(otherI.targetedShip == null) otherI.targetedShip = this; otherI.shipCombatRoom = thisRoom; otherI.amInTacticalMode(); // now he is in combat } amInTacticalMode(); // now he is in combat //also support ENGAGE <shipname> as an alternative to attack? return Boolean.TRUE; } } finally { mob.destroy(); } } return null; } protected int[] getMagicCoords() { final Room R=CMLib.map().roomLocation(this); final int[] coords; final int middle = (int)Math.round(Math.floor(R.maxRange() / 2.0)); final int extreme = R.maxRange()-1; final int midDiff = (middle > 0) ? CMLib.dice().roll(1, middle, -1) : 0; final int midDiff2 = (middle > 0) ? CMLib.dice().roll(1, middle, -1) : 0; final int extremeRandom = (extreme > 0) ? CMLib.dice().roll(1, R.maxRange(), -1) : 0; final int extremeRandom2 = (extreme > 0) ? CMLib.dice().roll(1, R.maxRange(), -1) : 0; switch(this.directionFacing) { case Directions.NORTH: coords = new int[] {extremeRandom,extreme-midDiff}; break; case Directions.SOUTH: coords = new int[] {extremeRandom,midDiff}; break; case Directions.EAST: coords = new int[] {midDiff,extremeRandom}; break; case Directions.WEST: coords = new int[] {extreme-midDiff,extremeRandom}; break; case Directions.UP: coords = new int[] {extremeRandom,extremeRandom2}; break; case Directions.DOWN: coords = new int[] {extremeRandom,extremeRandom2}; break; case Directions.NORTHEAST: coords = new int[] {midDiff,extreme-midDiff2}; break; case Directions.NORTHWEST: coords = new int[] {extreme-midDiff,extreme-midDiff2}; break; case Directions.SOUTHEAST: coords = new int[] {extreme-midDiff,midDiff2}; break; case Directions.SOUTHWEST: coords = new int[] {midDiff,midDiff2}; break; default: coords = new int[] {extremeRandom,extremeRandom2}; break; } return coords; } protected void clearTacticalModeHelper() { synchronized((""+shipCombatRoom + "_SHIP_TACTICAL").intern()) { final PairList<Item,int[]> coords = this.coordinates; if(coords != null) { coords.removeFirst(this); } } this.targetedShip = null; this.shipCombatRoom = null; this.coordinates = null; this.aimings.clear(); } protected synchronized void clearTacticalMode() { final Room shipCombatRoom = this.shipCombatRoom; if(shipCombatRoom != null) { PairList<Item,int[]> coords = null; synchronized((""+shipCombatRoom + "_SHIP_TACTICAL").intern()) { coords = this.coordinates; } clearTacticalModeHelper(); if(coords != null) { for(final Iterator<Item> s = coords.firstIterator();s.hasNext();) { final Item I=s.next(); if((I instanceof GenSailingShip) &&(((GenSailingShip)I).targetedShip == this)) ((GenSailingShip)I).clearTacticalModeHelper(); } } } } protected boolean isAnyoneAtCoords(final int[] xy) { final PairList<Item, int[]> coords = this.coordinates; if(coords != null) { for(final Iterator<int[]> i = coords.secondIterator(); i.hasNext();) { if(Arrays.equals(xy, i.next())) return true; } } return false; } protected int[] getMyCoords() { final PairList<Item, int[]> coords = this.coordinates; if(coords != null) { for(final Iterator<Pair<Item,int[]>> i = coords.iterator(); i.hasNext();) { final Pair<Item,int[]> P=i.next(); if(P.first == this) return P.second; } } return null; } protected synchronized boolean amInTacticalMode() { final Item targetedShip = (Item)this.targetedShip; final Room shipCombatRoom = this.shipCombatRoom; if((targetedShip != null) && (shipCombatRoom != null) && (shipCombatRoom.isContent(targetedShip)) && (shipCombatRoom.isContent(this)) ) { if(coordinates == null) { synchronized((""+shipCombatRoom + "_SHIP_TACTICAL").intern()) { for(int i=0;i<shipCombatRoom.numItems();i++) { final Item I=shipCombatRoom.getItem(i); if((I instanceof GenSailingShip) &&(((GenSailingShip)I).coordinates != null)) { this.coordinates = ((GenSailingShip)I).coordinates; } } if(coordinates == null) { this.coordinates = new SPairList<Item,int[]>(); } } final PairList<Item,int[]> coords = this.coordinates; if(coords != null) { if(!coords.containsFirst(this)) { int[] newCoords = null; for(int i=0;i<10;i++) { newCoords = this.getMagicCoords(); if(!isAnyoneAtCoords(newCoords)) break; } coords.add(new Pair<Item,int[]>(this,newCoords)); } } } return true; } else { this.targetedShip = null; this.shipCombatRoom = null; this.coordinates = null; return false; } } @Override public boolean tick(final Tickable ticking, final int tickID) { final int sailingTickID = amInTacticalMode() ? Tickable.TICKID_SPECIALMANEUVER : Tickable.TICKID_AREA; if(tickID == Tickable.TICKID_AREA) { if(amDestroyed()) return false; final Area area = this.getShipArea(); if(area instanceof BoardableShip) { if((this.tenderShip != null) &&(this.tenderShip.owner()==owner()) &&(this.targetedShip==null) &&(this.tenderShip instanceof GenSailingShip) &&(((GenSailingShip)this.tenderShip).targetedShip==null)) { // yay! } else { this.tenderShip=null; if((((BoardableShip)area).getIsDocked() != owner()) &&(owner() instanceof Room)) { this.dockHere((Room)owner()); } } } } if(tickID == sailingTickID) { ticksSinceMove++; if((!this.anchorDown) && (area != null) && (courseDirection != -1) ) { final int speed=getShipSpeed(); for(int s=0;s<speed && (courseDirection>=0);s++) { switch(sail(courseDirection & 127)) { case CANCEL: { courseDirection=-1; break; } case CONTINUE: { if(this.courseDirections.size()>0) { this.courseDirection = this.removeTopCourse(); } else { if((courseDirection & COURSE_STEER_MASK) == 0) courseDirection = -1; } break; } case REPEAT: { break; } } } if(tickID == Tickable.TICKID_SPECIALMANEUVER) { final Room combatRoom=this.shipCombatRoom; if(combatRoom != null) { final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),null); try { mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); combatRoom.show(mob, this, CMMsg.MSG_ACTIVATE|CMMsg.MASK_MALICIOUS, null); } finally { mob.destroy(); } } final PairList<Item,int[]> coords = this.coordinates; if(coords != null) { for(final Iterator<Item> i= coords.firstIterator(); i.hasNext();) { final Item I=i.next(); if((I instanceof GenSailingShip) &&(((GenSailingShip)I).targetedShip == this)) ((GenSailingShip)I).announceToDeck(((GenSailingShip)I).getTargetedShipInfo()); } } } } } if(tickID == Tickable.TICKID_SPECIALCOMBAT) { if(this.amInTacticalMode()) { final List<Weapon> weapons = new LinkedList<Weapon>(); for(final Enumeration<Room> r=this.getShipArea().getProperMap();r.hasMoreElements();) { try { final Room R=r.nextElement(); if(R!=null) { for(final Enumeration<Item> i=R.items();i.hasMoreElements();) { try { final Item I=i.nextElement(); if(isAShipSiegeWeaponReadyToFire(I)) weapons.add((Weapon)I); } catch(final NoSuchElementException ne) { } } } } catch(final NoSuchElementException ne) { } } if(weapons.size()>0) { final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),null); final int[] coordsToHit; if(this.targetedShip instanceof GenSailingShip) coordsToHit = ((GenSailingShip)this.targetedShip).getMyCoords(); else coordsToHit = new int[2]; try { mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); int notLoaded = 0; int notAimed = 0; final PairList<Weapon,int[]> aimings=this.aimings; for(final Weapon w : weapons) { final Room R=CMLib.map().roomLocation(w); if(R!=null) { mob.setLocation(R); if((w instanceof AmmunitionWeapon) &&(((AmmunitionWeapon)w).requiresAmmunition()) &&(((AmmunitionWeapon)w).ammunitionRemaining() <=0)) notLoaded++; else if(aimings!=null) { //mob.setRangeToTarget(0); final int index = aimings.indexOfFirst(w); if(index >= 0) { final int[] coordsAimedAt = aimings.remove(index).second; final boolean wasHit = Arrays.equals(coordsAimedAt, coordsToHit); CMLib.combat().postShipAttack(mob, this, this.targetedShip, w, wasHit); } else notAimed++; } } } final String spamMsg; if((notLoaded > 0) && (notAimed > 0)) spamMsg = L("@x1 of your weapons were not loaded, and @x2 were ready but not aimed.",""+notLoaded, ""+notAimed); else if(notLoaded > 0) spamMsg = L("@x1 of your weapons were not loaded.",""+notLoaded); else if(notAimed > 0) spamMsg = L("@x1 of your weapons were ready but not aimed.",""+notAimed); else spamMsg = ""; if(spamMsg.length()>0) { if(spamMsg.equals(lastSpamMsg)) { if(lastSpamCt < 3) { announceToDeck(spamMsg); lastSpamCt++; } } else { announceToDeck(spamMsg); lastSpamCt=0; } } lastSpamMsg=spamMsg; } finally { mob.setRangeToTarget(0); mob.destroy(); } } } } return super.tick(ticking, tickID); } protected final boolean isAShipSiegeWeaponReadyToFire(final Item I) { if(CMLib.combat().isAShipSiegeWeapon(I)) { if(((Rideable)I).riderCapacity() > 0) return ((Rideable)I).numRiders() >= ((Rideable)I).riderCapacity(); return true; } return false; } protected static MOB getBestRider(final Room R, final Rideable rI) { MOB bestM=null; for(final Enumeration<Rider> m=rI.riders();m.hasMoreElements();) { final Rider R2=m.nextElement(); if((R2 instanceof MOB) && (R.isInhabitant((MOB)R2))) { if(((MOB)R2).isPlayer()) return (MOB)R2; else if((bestM!=null)&&(bestM.amFollowing()!=null)) bestM=(MOB)R2; else bestM=(MOB)R2; } } return bestM; } protected static String staticL(final String str, final String... xs) { return CMLib.lang().fullSessionTranslation(str, xs); } public static void appendCondition(final StringBuilder visualCondition, final double pct, final String name) { if(pct<=0.0) visualCondition.append(staticL("\n\r^r@x1^r is nothing but wreckage!^N",name)); else if(pct<.10) visualCondition.append(staticL("\n\r^r@x1^r is near destruction!^N",name)); else if(pct<.20) visualCondition.append(staticL("\n\r^r@x1^r is massively splintered and damaged.^N",name)); else if(pct<.30) visualCondition.append(staticL("\n\r^r@x1^r is extremely splintered and damaged.^N",name)); else if(pct<.40) visualCondition.append(staticL("\n\r^y@x1^y is very splintered and damaged.^N",name)); else if(pct<.50) visualCondition.append(staticL("\n\r^y@x1^y is splintered and damaged.^N",name)); else if(pct<.60) visualCondition.append(staticL("\n\r^p@x1^p is splintered and slightly damaged.^N",name)); else if(pct<.70) visualCondition.append(staticL("\n\r^p@x1^p is showing large splinters.^N",name)); else if(pct<.80) visualCondition.append(staticL("\n\r^g@x1^g is showing some splinters.^N",name)); else if(pct<.90) visualCondition.append(staticL("\n\r^g@x1^g is showing small splinters.^N",name)); else if(pct<.99) visualCondition.append(staticL("\n\r^g@x1^g is no longer in perfect condition.^N",name)); else visualCondition.append(staticL("\n\r^c@x1^c is in perfect condition.^N",name)); } protected void cleanMsgForRepeat(final CMMsg msg) { msg.setSourceCode(CMMsg.NO_EFFECT); if(msg.trailerRunnables()!=null) msg.trailerRunnables().clear(); if(msg.trailerMsgs()!=null) { for(final CMMsg msg2 : msg.trailerMsgs()) cleanMsgForRepeat(msg2); } } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { super.executeMsg(myHost,msg); switch(msg.sourceMinor()) { case CMMsg.TYP_HUH: case CMMsg.TYP_COMMANDFAIL: case CMMsg.TYP_COMMAND: break; default: if(msg.source().riding()==this) { sendAreaMessage(msg, true); final ItemPossessor owner = owner(); if((owner instanceof Room) &&(owner != prevItemRoom) &&(this.area instanceof BoardableShip)) { final Room R = (Room)owner; boolean fixSky=false; final Room oldR; synchronized(this) { oldR=this.prevItemRoom; fixSky = ((R!=oldR)&&(oldR!=null)); if(oldR!=R) this.prevItemRoom=R; } if(fixSky) { final boolean wasWater=CMLib.flags().isUnderWateryRoom(oldR); final boolean isWater=CMLib.flags().isUnderWateryRoom(R); final boolean isSunk = isWater && (R.getGridParent()!=null) && (R.getGridParent().roomID().length()==0); if(wasWater || isSunk) { for(final Enumeration<Room> r=area.getProperMap();r.hasMoreElements();) { final Room inR=r.nextElement(); if(((inR.domainType()&Room.INDOORS)==0) &&(inR.roomID().length()>0)) { inR.clearSky(); if(isSunk) { if((inR.getRoomInDir(Directions.UP)==null) &&(inR.getExitInDir(Directions.UP)==null)) { inR.giveASky(0); final Exit redirExit = CMClass.getExit("NamedRedirectable"); redirExit.setDisplayText(R.displayText()); redirExit.setDescription(R.displayText()); redirExit.lastRoomUsedFrom(R); inR.setRawExit(Directions.UP, redirExit); } } else inR.giveASky(0); } } } } } } else if(msg.othersMessage()==null) sendAreaMessage(msg, true); else { final CMMsg msg2=(CMMsg)msg.copyOf(); msg2.setOthersMessage(L("^HOff the deck you see: ^N")+msg.othersMessage()); cleanMsgForRepeat(msg2); sendAreaMessage(msg2, true); } } if(msg.target() == this) { switch(msg.targetMinor()) { case CMMsg.TYP_LOOK: case CMMsg.TYP_EXAMINE: { final StringBuilder visualCondition = new StringBuilder(""); if(this.anchorDown) visualCondition.append(L("^HThe anchor on @x1 is lowered, holding her in place.^.^?",name(msg.source()))); else if((this.courseDirection >= 0) &&(getTopCourse()>=0)) visualCondition.append(L("^H@x1 is under full sail, traveling @x2^.^?",CMStrings.capitalizeFirstLetter(name(msg.source())), CMLib.directions().getDirectionName(courseDirection & 127))); if(this.subjectToWearAndTear() && (usesRemaining() <= 100)) { final double pct=(CMath.div(usesRemaining(),100.0)); appendCondition(visualCondition,pct,name(msg.source())); } if(visualCondition.length()>0) { msg.addTrailerRunnable(new Runnable() { @Override public void run() { msg.source().tell(visualCondition.toString()); msg.trailerRunnables().remove(this); } }); } break; } default: break; } } if((msg.target() instanceof Room) &&(msg.target() == owner())) { switch(msg.targetMinor()) { case CMMsg.TYP_LOOK: case CMMsg.TYP_EXAMINE: if((CMLib.map().areaLocation(msg.source())==area)) { final StringBuilder visualCondition = new StringBuilder(""); if(this.anchorDown) visualCondition.append(L("\n\r^HThe anchor on @x1 is lowered, holding her in place.^.^?",name(msg.source()))); else if((this.courseDirection >= 0) &&(getTopCourse()>=0)) visualCondition.append(L("\n\r^H@x1 is under full sail, traveling @x2^.^?",name(msg.source()), CMLib.directions().getDirectionName(courseDirection & 127))); if(this.subjectToWearAndTear() && (usesRemaining() <= 100) && (this.targetedShip != null)) { final double pct=(CMath.div(usesRemaining(),100.0)); appendCondition(visualCondition,pct,name(msg.source())); } if(visualCondition.length()>0) msg.addTrailerMsg(CMClass.getMsg(msg.source(), null, null, CMMsg.MSG_OK_VISUAL, visualCondition.toString(), -1, null, -1, null)); } break; case CMMsg.TYP_LEAVE: case CMMsg.TYP_ENTER: if((owner() instanceof Room) &&(msg.target() instanceof Room) &&(((Room)msg.target()).getArea()!=area)) { if(((msg.source().riding() == this) &&(msg.source().Name().equals(Name()))) ||((this.targetedShip!=null) &&(msg.source().riding() == targetedShip) &&(msg.source().Name().equals(targetedShip.Name())))) { clearTacticalMode(); } } break; } } else if(msg.target() == this) { switch(msg.targetMinor()) { case CMMsg.TYP_ENTER: break; case CMMsg.TYP_WEAPONATTACK: if(msg.targetMinor()==CMMsg.TYP_WEAPONATTACK) { Weapon weapon=null; if((msg.tool() instanceof Weapon)) weapon=(Weapon)msg.tool(); if((weapon!=null) &&(((msg.source().riding()!=null)&&(owner() instanceof Room)) ||((msg.source().location()!=null) && (weapon.owner()==null)))) { final Room shipRoom=(Room)owner(); final boolean isHit=msg.value()>0; if(isHit && CMLib.combat().isAShipSiegeWeapon(weapon) && (((AmmunitionWeapon)weapon).ammunitionCapacity() > 1)) { int shotsRemaining = ((AmmunitionWeapon)weapon).ammunitionRemaining() + 1; ((AmmunitionWeapon)weapon).setAmmoRemaining(0); final Area A=this.getShipArea(); final ArrayList<Pair<MOB,Room>> targets = new ArrayList<Pair<MOB,Room>>(5); if(A!=null) { for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null)&&((R.domainType()&Room.INDOORS)==0)) { for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();) targets.add(new Pair<MOB,Room>(m.nextElement(),R)); } } } final int chanceToHit = targets.size() * 20; final Room oldRoom=msg.source().location(); try { final double pctLoss = CMath.div(msg.value(), 100.0); while(shotsRemaining-- > 0) { final Pair<MOB,Room> randomPair = (targets.size()>0)? targets.get(CMLib.dice().roll(1,targets.size(),-1)) : null; if((CMLib.dice().rollPercentage() < chanceToHit)&&(randomPair != null)) { msg.source().setLocation(shipRoom); final int pointsLost = (int)Math.round(pctLoss * msg.source().maxState().getHitPoints()); CMLib.combat().postWeaponDamage(msg.source(), randomPair.first, weapon, pointsLost); } else if(randomPair != null) { msg.source().setLocation(shipRoom); CMLib.combat().postWeaponAttackResult(msg.source(), randomPair.first, weapon, false); } else { this.announceActionToDeck(msg.source(), msg.target(), weapon, weapon.missString()); } } } finally { msg.source().setLocation(oldRoom); } } else { PhysicalAgent attacker; if(msg.source().riding() instanceof BoardableShip) attacker=msg.source().riding(); else { final Room R=msg.source().location(); if((R!=null) &&(R.getArea() instanceof BoardableShip)) attacker=((BoardableShip)R.getArea()).getShipItem(); else attacker=null; } if(attacker != null) CMLib.combat().postShipWeaponAttackResult(msg.source(), attacker, this, weapon, isHit); } } } break; case CMMsg.TYP_DAMAGE: if(msg.value() > 0) { final int maxHullPoints = CMLib.combat().getShipHullPoints(this); final double pctLoss = CMath.div(msg.value(), maxHullPoints); final int pointsLost = (int)Math.round(pctLoss * maxHullPoints); if(pointsLost > 0) { final int weaponType = (msg.tool() instanceof Weapon) ? ((Weapon)msg.tool()).weaponDamageType() : Weapon.TYPE_BASHING; final String hitWord = CMLib.combat().standardHitWord(weaponType, pctLoss); final String msgStr = (msg.targetMessage() == null) ? L("<O-NAME> fired from <S-NAME> hits and @x1 @x2.",hitWord,name()) : msg.targetMessage(); final CMMsg deckHitMsg=CMClass.getMsg(msg.source(), this, msg.tool(),CMMsg.MSG_OK_ACTION, msgStr); this.announceActionToDeckOrUnderdeck(msg.source(), deckHitMsg, 0); final CMMsg underdeckHitMsg=CMClass.getMsg(msg.source(), this, msg.tool(),CMMsg.MSG_OK_ACTION, L("Something hits and @x1 the ship.",hitWord)); this.announceActionToDeckOrUnderdeck(msg.source(), underdeckHitMsg, Room.INDOORS); if(pointsLost >= this.usesRemaining()) { this.setUsesRemaining(0); this.recoverPhyStats(); // takes away the swimmability! final Room shipR=CMLib.map().roomLocation(this); if(shipR!=null) { CMLib.tracking().makeSink(this, shipR, false); final String sinkString = L("<T-NAME> start(s) sinking!"); shipR.show(msg.source(), this, CMMsg.MSG_OK_ACTION, sinkString); this.announceActionToUnderDeck(msg.source(), sinkString); } if((msg.source().riding() instanceof BoardableShip) &&((msg.source().Name().equals(msg.source().riding().Name())))) { final Area A=((BoardableShip)msg.source().riding()).getShipArea(); if(A!=null) { for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) &&(R.numInhabitants()>0)) { for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();) { final MOB M=m.nextElement(); final CMMsg msg2=CMClass.getMsg(M, this, CMMsg.MSG_CAUSESINK, null); this.sendAreaMessage(msg2, false); R.showSource(M, this, CMMsg.MSG_CAUSESINK, null); CMLib.achievements().possiblyBumpAchievement(M, Event.SHIPSSUNK, 1, this); } } } } } if(!CMLib.leveler().postExperienceToAllAboard(msg.source().riding(), 500, this)) CMLib.leveler().postExperience(msg.source(), null, null, 500, false); this.clearTacticalMode(); } else { this.setUsesRemaining(this.usesRemaining() - pointsLost); } } } break; } } else if(msg.target() instanceof AmmunitionWeapon) { switch(msg.targetMinor()) { case CMMsg.TYP_RELOAD: if((msg.tool() instanceof Ammunition) &&(CMLib.combat().isAShipSiegeWeapon((Item)msg.target()))) { final MOB tellM=msg.source(); final Item I= (Item)msg.target(); msg.addTrailerRunnable(new Runnable() { @Override public void run() { tellM.tell(L("@x1 is now loaded. Don't forget to aim.",I.name())); } }); } break; } } else { switch(msg.targetMinor()) { case CMMsg.TYP_LOOK: case CMMsg.TYP_EXAMINE: if((msg.target() instanceof BoardableShip) &&(msg.target() instanceof Rideable) &&(msg.target()!=this)) { final String otherShipInfo=getOtherShipInfo((Rideable)msg.target()); if(otherShipInfo.length()>0) { msg.addTrailerRunnable(new Runnable() { @Override public void run() { msg.source().tell(otherShipInfo); } }); } } break; } } } @Override public void setExpirationDate(final long time) { // necessary because stdboardable protects its space ships in rooms this.dispossessionTime=time; } @Override public long expirationDate() { final Room R=CMLib.map().roomLocation(this); if(R==null) return 0; if((!CMLib.flags().isUnderWateryRoom(R)) &&(this.usesRemaining()>0)) return 0; return super.expirationDate(); } @Override protected Room findNearestDocks(final Room R) { if(R!=null) { if(R.domainType()==Room.DOMAIN_OUTDOORS_SEAPORT) return R; TrackingLibrary.TrackingFlags flags; flags = CMLib.tracking().newFlags() .plus(TrackingLibrary.TrackingFlag.AREAONLY) .plus(TrackingLibrary.TrackingFlag.NOEMPTYGRIDS) .plus(TrackingLibrary.TrackingFlag.NOAIR) .plus(TrackingLibrary.TrackingFlag.NOHOMES) .plus(TrackingLibrary.TrackingFlag.UNLOCKEDONLY); final List<Room> rooms=CMLib.tracking().getRadiantRooms(R, flags, 25); for(final Room R2 : rooms) { if(R2.domainType()==Room.DOMAIN_OUTDOORS_SEAPORT) return R2; } for(final Room R2 : rooms) { if(CMLib.flags().isDeepWaterySurfaceRoom(R2)) { for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { final Room adjacentR = R2.getRoomInDir(d); final Exit adjacentE = R2.getExitInDir(d); if((adjacentR!=null) &&(adjacentE!=null) &&(adjacentE.isOpen()) &&(!CMLib.flags().isWateryRoom(adjacentR))) return adjacentR; } } } } return null; } private static enum SailResult { CANCEL, CONTINUE, REPEAT } protected int[] getCoordAdjustments(final int[] newOnes) { final PairList<Item,int[]> coords = this.coordinates; final int[] lowests = new int[2]; if(coords != null) { if(newOnes != null) { if(newOnes[0] < lowests[0]) lowests[0]=newOnes[0]; if(newOnes[1] < lowests[1]) lowests[1]=newOnes[1]; } for(int p=0;p<coords.size();p++) { try { final Pair<Item,int[]> P = coords.get(p); if((newOnes==null)||(P.first!=this)) { if(P.second[0] < lowests[0]) lowests[0]=P.second[0]; if(P.second[1] < lowests[1]) lowests[1]=P.second[1]; } } catch(final Exception e) { } } } lowests[0]=-lowests[0]; lowests[1]=-lowests[1]; return lowests; } protected int getTacticalDistance(final PhysicalAgent targetShip) { final int[] fromCoords = this.getMyCoords(); final PairList<Item,int[]> coords = this.coordinates; int lowest = Integer.MAX_VALUE; if((coords != null) && (fromCoords != null)) { final int p = coords.indexOfFirst((Item)targetShip); if(p >=0) { final Pair<Item,int[]> P=coords.get(p); final int distance = (int)Math.round(Math.ceil(Math.sqrt(Math.pow(P.second[0]-fromCoords[0],2.0) + Math.pow(P.second[1]-fromCoords[1],2.0)))); if(distance < lowest) lowest=distance; } } if(lowest == Integer.MAX_VALUE) return CMLib.map().roomLocation(this).maxRange() + 1; return lowest; } protected int getLowestTacticalDistanceFromThis() { final int[] fromCoords = this.getMyCoords(); final PairList<Item,int[]> coords = this.coordinates; int lowest = Integer.MAX_VALUE; if((coords != null) && (fromCoords != null)) { for(int p=0;p<coords.size();p++) { try { final Pair<Item,int[]> P = coords.get(p); if((P.second != fromCoords) &&(this.shipCombatRoom != null) &&(this.shipCombatRoom.isHere(P.first)) &&(P.first instanceof GenSailingShip) &&(((GenSailingShip)P.first).targetedShip == this)) { final int distance = (int)Math.round(Math.ceil(Math.sqrt(Math.pow(P.second[0]-fromCoords[0],2.0) + Math.pow(P.second[1]-fromCoords[1],2.0)))); if(distance < lowest) lowest=distance; } } catch(final Exception e) { } } } if(lowest == Integer.MAX_VALUE) return CMLib.map().roomLocation(this).maxRange(); return lowest; } protected int getDirectionFacing(final int direction) { final Room thisRoom=CMLib.map().roomLocation(this); if(directionFacing < 0) { if(thisRoom != null) { for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { final Room R2=thisRoom.getRoomInDir(d); if((R2!=null) &&(thisRoom.getExitInDir(d)!=null) &&(thisRoom.getExitInDir(d).isOpen()) &&(!CMLib.flags().isWateryRoom(R2))) { return Directions.getOpDirectionCode(d); } } } return direction; } return directionFacing; } @Override public void setDirectionFacing(final int direction) { this.directionFacing=direction; } protected SailResult sail(final int direction) { final Room thisRoom=CMLib.map().roomLocation(this); if(thisRoom != null) { directionFacing = getDirectionFacing(direction); int[] tacticalCoords = null; if(amInTacticalMode()) { int x=0; try { while((x>=0)&&(this.coordinates!=null)&&(tacticalCoords==null)) { x=this.coordinates.indexOfFirst(this); final Pair<Item,int[]> pair = (x>=0) ? this.coordinates.get(x) : null; if(pair == null) break; else if(pair.first != this) x=this.coordinates.indexOfFirst(this); else tacticalCoords = pair.second; } } catch(final Exception e) { } } if(tacticalCoords != null) { final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),thisRoom); try { mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); if(directionFacing == direction) { final String directionName = CMLib.directions().getDirectionName(direction); final int[] newCoords = Directions.adjustXYByDirections(tacticalCoords[0], tacticalCoords[1], direction); final CMMsg maneuverMsg=CMClass.getMsg(mob, thisRoom, null, CMMsg.MSG_ADVANCE,newCoords[0]+","+newCoords[1], CMMsg.MSG_ADVANCE,directionName, CMMsg.MSG_ADVANCE,L("<S-NAME> maneuver(s) @x1.",directionName)); if(thisRoom.okMessage(mob, maneuverMsg)) { thisRoom.send(mob, maneuverMsg); final int oldDistance = this.getLowestTacticalDistanceFromThis(); tacticalCoords[0] = newCoords[0]; tacticalCoords[1] = newCoords[1]; final int newDistance = this.getLowestTacticalDistanceFromThis(); ticksSinceMove=0; if((newDistance <= oldDistance)||(newDistance < thisRoom.maxRange())) return SailResult.CONTINUE; } else return SailResult.REPEAT; // else we get to make a real Sailing move! } else { final int gradualDirection=Directions.getGradualDirectionCode(directionFacing, direction); final String directionName = CMLib.directions().getDirectionName(gradualDirection); final String finalDirectionName = CMLib.directions().getDirectionName(direction); final CMMsg maneuverMsg=CMClass.getMsg(mob, thisRoom, null, CMMsg.MSG_ADVANCE,directionName, CMMsg.MSG_ADVANCE,finalDirectionName, CMMsg.MSG_ADVANCE,L("<S-NAME> change(s) course, turning @x1.",directionName)); if(thisRoom.okMessage(mob, maneuverMsg)) { thisRoom.send(mob, maneuverMsg); directionFacing = CMLib.directions().getStrictDirectionCode(maneuverMsg.sourceMessage()); } if(direction != directionFacing) return SailResult.REPEAT; else return SailResult.CONTINUE; } } finally { mob.destroy(); } } else { directionFacing = direction; } this.clearTacticalMode(); final Room destRoom=thisRoom.getRoomInDir(direction); final Exit exit=thisRoom.getExitInDir(direction); if((destRoom!=null)&&(exit!=null)) { if((!CMLib.flags().isDeepWaterySurfaceRoom(destRoom)) &&(destRoom.domainType()!=Room.DOMAIN_OUTDOORS_SEAPORT)) { announceToShip(L("As there is no where to sail @x1, <S-NAME> meanders along the waves.",CMLib.directions().getInDirectionName(direction))); courseDirections.clear(); return SailResult.CANCEL; } final int oppositeDirectionFacing=thisRoom.getReverseDir(direction); final String directionName=CMLib.directions().getDirectionName(direction); final String otherDirectionName=CMLib.directions().getDirectionName(oppositeDirectionFacing); final Exit opExit=destRoom.getExitInDir(oppositeDirectionFacing); final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),CMLib.map().roomLocation(this)); mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); try { final boolean isSneaking = CMLib.flags().isSneaking(this); final String sailEnterStr = isSneaking ? null : L("<S-NAME> sail(s) in from @x1.",otherDirectionName); final String sailAwayStr = isSneaking ? null : L("<S-NAME> sail(s) @x1.",directionName); final CMMsg enterMsg=CMClass.getMsg(mob,destRoom,exit,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,sailEnterStr); final CMMsg leaveMsg=CMClass.getMsg(mob,thisRoom,opExit,CMMsg.MSG_LEAVE,null,CMMsg.MSG_LEAVE,null,CMMsg.MSG_LEAVE,sailAwayStr); if((exit.okMessage(mob,enterMsg)) &&(leaveMsg.target().okMessage(mob,leaveMsg)) &&((opExit==null)||(opExit.okMessage(mob,leaveMsg))) &&(enterMsg.target().okMessage(mob,enterMsg))) { exit.executeMsg(mob,enterMsg); thisRoom.sendOthers(mob, leaveMsg); this.unDock(false); ((Room)enterMsg.target()).moveItemTo(this); ticksSinceMove=0; this.dockHere(((Room)enterMsg.target())); //this.sendAreaMessage(leaveMsg, true); if(opExit!=null) opExit.executeMsg(mob,leaveMsg); ((Room)enterMsg.target()).send(mob, enterMsg); haveEveryoneLookOverBow(); return SailResult.CONTINUE; } else { announceToShip(L("<S-NAME> can not seem to travel @x1.",CMLib.directions().getInDirectionName(direction))); courseDirections.clear(); return SailResult.CANCEL; } } finally { mob.destroy(); } } else { announceToShip(L("As there is no where to sail @x1, <S-NAME> meanders along the waves.",CMLib.directions().getInDirectionName(direction))); courseDirections.clear(); return SailResult.CANCEL; } } return SailResult.CANCEL; } protected void haveEveryoneLookOverBow() { if((area != null)&&(owner() instanceof Room)) { final Room targetR=(Room)owner(); for(final Enumeration<Room> r=area.getProperMap(); r.hasMoreElements(); ) { final Room R=r.nextElement(); if((R!=null) &&((R.domainType()&Room.INDOORS)==0)) { final Set<MOB> mobs=CMLib.players().getPlayersHere(R); if(mobs.size()>0) { for(final MOB mob : new XTreeSet<MOB>(mobs)) { if(mob == null) continue; final CMMsg lookMsg=CMClass.getMsg(mob,targetR,null,CMMsg.MSG_LOOK,null); final CMMsg lookExitMsg=CMClass.getMsg(mob,targetR,null,CMMsg.MSG_LOOK_EXITS,null); if((mob.isAttributeSet(MOB.Attrib.AUTOEXITS)) &&(CMProps.getIntVar(CMProps.Int.EXVIEW)!=CMProps.Int.EXVIEW_PARAGRAPH) &&(CMLib.flags().canBeSeenBy(targetR,mob))) { if((CMProps.getIntVar(CMProps.Int.EXVIEW)>=CMProps.Int.EXVIEW_MIXED)!=mob.isAttributeSet(MOB.Attrib.BRIEF)) lookExitMsg.setValue(CMMsg.MASK_OPTIMIZE); lookMsg.addTrailerMsg(lookExitMsg); } if(targetR.okMessage(mob,lookMsg)) targetR.send(mob,lookMsg); } } } } } } protected boolean steer(final MOB mob, final Room R, final int dir) { directionFacing = dir; final String outerStr; final String innerStr = L("@x1 change(s) course, steering @x2.",name(mob),CMLib.directions().getDirectionName(dir)); if(CMLib.flags().isSneaking(this)) outerStr=null; else outerStr=innerStr; final CMMsg msg=CMClass.getMsg(mob, null,null,CMMsg.MSG_NOISYMOVEMENT,innerStr,outerStr,outerStr); final CMMsg msg2=CMClass.getMsg(mob, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> change(s) course, steering @x1 @x2.",name(mob),CMLib.directions().getDirectionName(dir))); if((R.okMessage(mob, msg) && this.okAreaMessage(msg2, true))) { R.sendOthers(mob, msg); this.sendAreaMessage(msg2, true); this.courseDirection=dir | COURSE_STEER_MASK; return true; } return false; } protected boolean beginSail(final MOB mob, final Room R, final int dir) { directionFacing = dir; final String outerStr; final String innerStr = L("<S-NAME> sail(s) @x1 @x2.",name(mob),CMLib.directions().getDirectionName(dir)); if(CMLib.flags().isSneaking(this)) outerStr=null; else outerStr=innerStr; final CMMsg msg2=CMClass.getMsg(mob, R, R.getExitInDir(dir), CMMsg.MSG_NOISYMOVEMENT, innerStr, outerStr,outerStr); if((R.okMessage(mob, msg2) && this.okAreaMessage(msg2, true))) { R.send(mob, msg2); // this lets the source know, i guess //this.sendAreaMessage(msg2, true); // this just sends to "others" this.courseDirection=dir; return true; } return false; } protected int getAnyExitDir(final Room R) { if(R==null) return -1; for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { final Room R2=R.getRoomInDir(d); final Exit E2=R.getExitInDir(d); if((R2!=null)&&(E2!=null)&&(CMLib.map().getExtendedRoomID(R2).length()>0)) return d; } return -1; } protected Room findOceanRoom(final Area A) { if(A==null) return null; for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null)&& CMLib.flags().isDeepWaterySurfaceRoom(R) &&(CMLib.map().getExtendedRoomID(R).length()>0)) return R; } return null; } protected boolean safetyMove() { final Room R=CMLib.map().roomLocation(this); if((R==null) || R.amDestroyed() || ((!CMLib.flags().isFalling(this)) && (R.domainType()!=Room.DOMAIN_INDOORS_UNDERWATER) && (R.domainType()!=Room.DOMAIN_OUTDOORS_UNDERWATER) && (getAnyExitDir(R)<0))) { Room R2=CMLib.map().getRoom(getHomePortID()); if((R2==null)&&(R!=null)&&(R.getArea()!=null)) R2=findOceanRoom(R.getArea()); if(R2==null) { for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) { R2=findOceanRoom(a.nextElement()); if(R2!=null) break; } } if(R2==null) return false; ticksSinceMove=0; this.unDock(false); R2.moveItemTo(this); this.dockHere(R2); return true; } return false; } @Override public boolean isInCombat() { return (targetedShip != null) && (shipCombatRoom != null); } @Override public void setRangeToTarget(final int newRange) { //nothing to do atm } @Override public int rangeToTarget() { return getTacticalDistance(this.targetedShip); } @Override public boolean mayPhysicallyAttack(final PhysicalAgent victim) { if(!mayIFight(victim)) return false; return CMLib.map().roomLocation(this) == CMLib.map().roomLocation(victim); } protected static boolean ownerSecurityCheck(final String ownerName, final MOB mob) { return (ownerName.length()>0) &&(mob!=null) &&((mob.Name().equals(ownerName)) ||(mob.getLiegeID().equals(ownerName)&mob.isMarriedToLiege()) ||(CMLib.clans().checkClanPrivilege(mob, ownerName, Clan.Function.PROPERTY_OWNER))); } @Override public boolean mayIFight(final PhysicalAgent victim) { final Area myArea=this.getShipArea(); final PhysicalAgent defender=victim; MOB mob = null; if(myArea != null) { final LegalLibrary law=CMLib.law(); int legalLevel=0; for(final Enumeration<Room> r=myArea.getProperMap();r.hasMoreElements() && (legalLevel<2);) { final Room R=r.nextElement(); if((R!=null)&&(R.numInhabitants()>0)) { for(final Enumeration<MOB> i=R.inhabitants();i.hasMoreElements();) { final MOB M=i.nextElement(); if(M != null) { if(mob == null) mob = M; if((legalLevel==0)&&(mob.isMonster())&&(law.doesHaveWeakPriviledgesHere(M, R))) { mob=M; legalLevel=1; } if(M.isPlayer()) { if(!mob.isPlayer()) { mob=M; legalLevel=0; } if((legalLevel<2) && (law.doesHavePriviledgesHere(M, R))) { legalLevel=2; mob=M; } if((legalLevel<1) && (law.doesHaveWeakPriviledgesHere(M, R))) { legalLevel=1; mob=M; } } } } } } } if(mob==null) return false; return CMLib.combat().mayIAttackThisVessel(mob, defender); } @Override public void makePeace(final boolean includePlayerFollowers) { clearTacticalMode(); } @Override public PhysicalAgent getCombatant() { return this.targetedShip; } @Override public void setCombatant(final PhysicalAgent other) { final Room R=(owner() instanceof Room)?(Room)owner():CMLib.map().roomLocation(this); if(other == null) clearTacticalMode(); else if(CMLib.flags().isDeepWaterySurfaceRoom(R)) { targetedShip = other; if(R != null) shipCombatRoom = R; if(other instanceof Combatant) { if(((Combatant)other).getCombatant()==null) ((Combatant)other).setCombatant(this); if(other instanceof GenSailingShip) ((GenSailingShip)other).amInTacticalMode(); // now he is in combat } amInTacticalMode(); // now he is in combat } } @Override public int getDirectionToTarget() { return this.getDirectionToTarget(this.targetedShip); } @Override public int getDirectionFacing() { return this.directionFacing; } @Override public boolean isAnchorDown() { return this.anchorDown; } @Override public void setAnchorDown(final boolean truefalse) { this.anchorDown = truefalse; } @Override public PairList<Weapon,int[]> getSiegeWeaponAimings() { return this.aimings; } protected int getTopCourse() { try { if(this.courseDirections.size()>0) return this.courseDirections.get(0).intValue(); } catch(final Exception e) { } return -1; } protected int removeTopCourse() { try { if(this.courseDirections.size()>0) return this.courseDirections.remove(0).intValue(); } catch(final Exception e) { } return -1; } protected int getBottomCourse() { try { final int size=this.courseDirections.size(); if(size>0) return this.courseDirections.get(size-1).intValue(); } catch(final Exception e) { } return -1; } @Override public List<Integer> getCurrentCourse() { if(getTopCourse()>=0) { return this.courseDirections; } return new ArrayList<Integer>(0); } @Override public void setCurrentCourse(final List<Integer> course) { this.courseDirection=-1; this.courseDirections.clear(); for(final Integer dirIndex : course) { final int dir=dirIndex.intValue(); if(dir>=0) { if(courseDirection < 0) { courseDirection = dir; directionFacing = dir; } else this.courseDirections.add(Integer.valueOf(dir)); } } this.courseDirections.add(Integer.valueOf(-1)); } private final static String[] MYCODES={"HASLOCK","HASLID","CAPACITY","CONTAINTYPES", "RESETTIME","RIDEBASIS","MOBSHELD", "AREA","OWNER","PRICE","DEFCLOSED","DEFLOCKED", "EXITNAME", "PUTSTR","MOUNTSTR","DISMOUNTSTR","STATESTR","STATESUBJSTR","RIDERSTR" }; @Override public String getStat(final String code) { if(CMLib.coffeeMaker().getGenItemCodeNum(code)>=0) return CMLib.coffeeMaker().getGenItemStat(this,code); switch(getCodeNum(code)) { case 0: return "" + hasALock(); case 1: return "" + hasADoor(); case 2: return "" + capacity(); case 3: return "" + containTypes(); case 4: return "" + openDelayTicks(); case 5: return "" + rideBasis(); case 6: return "" + riderCapacity(); case 7: return CMLib.coffeeMaker().getAreaObjectXML(getShipArea(), null, null, null, true).toString(); case 8: return getOwnerName(); case 9: return "" + getPrice(); case 10: return "" + defaultsClosed(); case 11: return "" + defaultsLocked(); case 12: return "" + doorName(); case 13: return this.getPutString(); case 14: return this.getMountString(); case 15: return this.getDismountString(); case 16: return this.getStateString(); case 17: return this.getStateStringSubject(); case 18: return this.getRideString(); default: return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code); } } @Override public void setStat(final String code, final String val) { if(CMLib.coffeeMaker().getGenItemCodeNum(code)>=0) CMLib.coffeeMaker().setGenItemStat(this,code,val); else switch(getCodeNum(code)) { case 0: setDoorsNLocks(hasADoor(), isOpen(), defaultsClosed(), CMath.s_bool(val), false, CMath.s_bool(val) && defaultsLocked()); break; case 1: setDoorsNLocks(CMath.s_bool(val), isOpen(), CMath.s_bool(val) && defaultsClosed(), hasALock(), isLocked(), defaultsLocked()); break; case 2: setCapacity(CMath.s_parseIntExpression(val)); break; case 3: setContainTypes(CMath.s_parseBitLongExpression(Container.CONTAIN_DESCS, val)); break; case 4: setOpenDelayTicks(CMath.s_parseIntExpression(val)); break; case 5: break; case 6: break; case 7: setShipArea(val); break; case 8: setOwnerName(val); break; case 9: setPrice(CMath.s_int(val)); break; case 10: setDoorsNLocks(hasADoor(), isOpen(), CMath.s_bool(val), hasALock(), isLocked(), defaultsLocked()); break; case 11: setDoorsNLocks(hasADoor(), isOpen(), defaultsClosed(), hasALock(), isLocked(), CMath.s_bool(val)); break; case 12: this.doorName = val; break; case 13: setPutString(val); break; case 14: setMountString(val); break; case 15: setDismountString(val); break; case 16: setStateString(val); break; case 17: setStateStringSubject(val); break; case 18: setRideString(val); break; default: CMProps.setStatCodeExtensionValue(getStatCodes(), xtraValues, code, val); break; } } @Override protected int getCodeNum(final String code) { for(int i=0;i<MYCODES.length;i++) { if(code.equalsIgnoreCase(MYCODES[i])) return i; } return -1; } private static String[] codes=null; @Override public String[] getStatCodes() { if(codes!=null) return codes; final String[] MYCODES=CMProps.getStatCodesList(GenSailingShip.MYCODES,this); final String[] superCodes=CMParms.toStringArray(GenericBuilder.GenItemCode.values()); codes=new String[superCodes.length+MYCODES.length]; int i=0; for(;i<superCodes.length;i++) codes[i]=superCodes[i]; for(int x=0;x<MYCODES.length;i++,x++) codes[i]=MYCODES[x]; return codes; } @Override public boolean sameAs(final Environmental E) { if(!(E instanceof GenSailingShip)) return false; final String[] codes=getStatCodes(); for(int i=0;i<codes.length;i++) { if((!E.getStat(codes[i]).equals(getStat(codes[i]))) &&(!codes[i].equals("AREA")) &&(!codes[i].equals("ABILITY"))) return false; } final Area eA = ((GenSailingShip)E).getShipArea(); final Area A = this.getShipArea(); final Enumeration<Room> er = eA.getProperMap(); final Enumeration<Room> r = A.getProperMap(); for(;r.hasMoreElements();) { final Room R=r.nextElement(); if(!er.hasMoreElements()) return false; final Room eR = er.nextElement(); if(!R.sameAs(eR)) return false; final Enumeration<Item> i=R.items(); final Enumeration<Item> ei = eR.items(); for(;i.hasMoreElements();) { final Item I=i.nextElement(); if(!ei.hasMoreElements()) return false; final Item eI=ei.nextElement(); if(!I.sameAs(eI)) return false; } if(ei.hasMoreElements()) return false; final Enumeration<MOB> m=R.inhabitants(); final Enumeration<MOB> em = eR.inhabitants(); for(;m.hasMoreElements();) { final MOB M=m.nextElement(); if(!em.hasMoreElements()) return false; final MOB eM=em.nextElement(); if(!M.sameAs(eM)) return false; } if(em.hasMoreElements()) return false; } if(er.hasMoreElements()) return false; return true; } }
com/planet_ink/coffee_mud/Items/Basic/GenSailingShip.java
package com.planet_ink.coffee_mud.Items.Basic; import com.planet_ink.coffee_mud.Items.Basic.StdPortal; import com.planet_ink.coffee_mud.Items.BasicTech.GenSpaceShip; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Expire; import com.planet_ink.coffee_mud.core.interfaces.ItemPossessor.Move; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.CMProps.Int; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.core.exceptions.CMException; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.MOB.Attrib; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.AchievementLibrary.Event; /* Copyright 2014-2019 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class GenSailingShip extends StdBoardable implements SailingShip { @Override public String ID() { return "GenSailingShip"; } protected volatile int courseDirection = -1; protected volatile boolean anchorDown = true; protected final List<Integer> courseDirections = new Vector<Integer>(); protected volatile int directionFacing = 0; protected volatile int ticksSinceMove = 0; protected volatile PhysicalAgent targetedShip = null; protected volatile Item tenderShip = null; protected volatile Room shipCombatRoom = null; protected PairList<Item, int[]> coordinates = null; protected PairList<Weapon, int[]> aimings = new PairVector<Weapon, int[]>(); protected List<Item> smallTenderRequests = new SLinkedList<Item>(); protected volatile Room prevItemRoom = null; protected int maxHullPoints = -1; protected volatile int lastSpamCt = 0; protected volatile String lastSpamMsg = ""; public GenSailingShip() { super(); setName("a sailing ship [NEWNAME]"); setDisplayText("a sailing ship [NEWNAME] is here."); setMaterial(RawMaterial.RESOURCE_OAK); basePhyStats().setAbility(2); this.recoverPhyStats(); } @Override public boolean isGeneric() { return true; } @Override public void recoverPhyStats() { super.recoverPhyStats(); if(owner instanceof Room) { if(usesRemaining()>0) phyStats().setDisposition(phyStats().disposition()|PhyStats.IS_SWIMMING); else phyStats().setDisposition(phyStats().disposition()|PhyStats.IS_FALLING); } } @Override protected String getAreaClassType() { return "StdBoardableShip"; } @Override protected Room createFirstRoom() { final Room R=CMClass.getLocale("WoodenDeck"); R.setDisplayText(L("The Deck")); return R; } @Override public Area getShipArea() { if((!destroyed) &&(area==null)) { final Area area=super.getShipArea(); if(area != null) area.setTheme(Area.THEME_FANTASY); return area; } return super.getShipArea(); } private enum SailingCommand { RAISE_ANCHOR, WEIGH_ANCHOR, LOWER_ANCHOR, STEER, SAIL, COURSE, SET_COURSE, TARGET, AIM, SINK, TENDER, RAISE, LOWER ; } protected void announceToDeck(final String msgStr) { final CMMsg msg=CMClass.getMsg(null, CMMsg.MSG_OK_ACTION, msgStr); announceToDeck(msg); } @Override public int getShipSpeed() { int speed=phyStats().ability(); if(subjectToWearAndTear()) { if(usesRemaining()<10) return 0; speed=(int)Math.round(speed * CMath.div(usesRemaining(), 100)); } if(speed <= 0) return 1; return speed; } protected void announceToDeck(final CMMsg msg) { MOB mob = null; final MOB msgSrc = msg.source(); try { final Area A=this.getShipArea(); if(A!=null) { Room mobR = null; for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) && ((R.domainType()&Room.INDOORS)==0)) { mobR=R; break; } } if(mobR!=null) { mob = CMClass.getFactoryMOB(name(),phyStats().level(),mobR); msg.setSource(mob); for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) && ((R.domainType()&Room.INDOORS)==0) && (R.okMessage(mob, msg))) { if(R == mobR) R.send(mob, msg); // this lets the source know, i guess else R.sendOthers(mob, msg); // this lets the source know, i guess } } } } } finally { msg.setSource(msgSrc); if(mob != null) mob.destroy(); } } protected void announceActionToDeckOrUnderdeck(final MOB mob, final CMMsg msg, final int INDOORS) { final Area A=this.getShipArea(); final Room mobR=CMLib.map().roomLocation(mob); if(A!=null) { for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) && ((R.domainType()&Room.INDOORS)==INDOORS) && (R.okMessage(mob, msg))) { if(R == mobR) R.send(mob, msg); // this lets the source know, i guess else R.sendOthers(mob, msg); // this lets the source know, i guess } } } } protected void announceActionToDeck(final MOB mob, final String msgStr) { final CMMsg msg=CMClass.getMsg(mob, CMMsg.MSG_OK_ACTION, msgStr); announceActionToDeckOrUnderdeck(mob,msg, 0); } protected void announceActionToDeck(final MOB mob, final Environmental target, final Environmental tool, final String msgStr) { final CMMsg msg=CMClass.getMsg(mob, target, tool, CMMsg.MSG_OK_ACTION, msgStr); announceActionToDeckOrUnderdeck(mob,msg, 0); } protected void announceActionToUnderDeck(final MOB mob, final String msgStr) { final CMMsg msg=CMClass.getMsg(mob, CMMsg.MSG_OK_ACTION, msgStr); announceActionToDeckOrUnderdeck(mob,msg, Room.INDOORS); } protected String getTargetedShipInfo() { final PhysicalAgent targetedShip = this.targetedShip; return getOtherShipInfo(targetedShip); } protected String getOtherShipInfo(final PhysicalAgent targetedShip) { if((targetedShip != null)&&(targetedShip instanceof GenSailingShip)) { final GenSailingShip targetShip = (GenSailingShip)targetedShip; final int[] targetCoords = targetShip.getMyCoords(); final int[] myCoords = this.getMyCoords(); if((myCoords!=null)&&(targetCoords != null)) { final String dist = ""+this.getTacticalDistance(targetShip); final String dir=CMLib.directions().getDirectionName(targetShip.directionFacing); final String speed=""+targetShip.getShipSpeed(); final String dirFromYou = CMLib.directions().getDirectionName(Directions.getRelative11Directions(myCoords, targetCoords)); return L("@x1 is @x2 of you sailing @x3 at a speed of @x4 and a distance of @x5.",targetShip.name(),dirFromYou,dir,speed,dist); } } return ""; } protected int getDirectionToTarget(final PhysicalAgent targetedShip) { if((targetedShip != null)&&(targetedShip instanceof GenSailingShip)) { final GenSailingShip targetShip = (GenSailingShip)targetedShip; final int[] targetCoords = targetShip.getMyCoords(); final int[] myCoords = this.getMyCoords(); if((myCoords!=null)&&(targetCoords != null)) return Directions.getRelative11Directions(myCoords, targetCoords); } return -1; } protected String getDirectionStrToTarget(final PhysicalAgent targetedShip) { if((targetedShip != null)&&(targetedShip instanceof GenSailingShip)) { final GenSailingShip targetShip = (GenSailingShip)targetedShip; final int[] targetCoords = targetShip.getMyCoords(); final int[] myCoords = this.getMyCoords(); if((myCoords!=null)&&(targetCoords != null)) return CMLib.directions().getDirectionName(Directions.getRelative11Directions(myCoords, targetCoords)); } return ""; } protected Room getRandomDeckRoom() { final Area A=this.getShipArea(); if(A!=null) { final List<Room> deckRooms=new ArrayList<Room>(2); for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) && ((R.domainType()&Room.INDOORS)==0) && (R.domainType()!=Room.DOMAIN_OUTDOORS_AIR)) deckRooms.add(R); } if(deckRooms.size()>0) { return deckRooms.get(CMLib.dice().roll(1, deckRooms.size(), -1)); } } return null; } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { switch(msg.sourceMinor()) { case CMMsg.TYP_HUH: case CMMsg.TYP_COMMANDFAIL: case CMMsg.TYP_COMMAND: break; default: if(!confirmAreaMessage(msg, true)) return false; break; } if((msg.target() == this) &&(msg.tool()!=null) &&(msg.tool().ID().equals("AWaterCurrent"))) { if(anchorDown) return false; } else if((msg.sourceMinor()==CMMsg.TYP_HUH) &&(msg.targetMessage()!=null) &&(area == CMLib.map().areaLocation(msg.source()))) { final List<String> cmds=CMParms.parse(msg.targetMessage()); if(cmds.size()==0) return true; final String word=cmds.get(0).toUpperCase(); final String secondWord=(cmds.size()>1) ? cmds.get(1).toUpperCase() : ""; SailingCommand cmd=null; if(secondWord.length()>0) cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word+"_"+secondWord); if(cmd == null) cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word); if(cmd != null) { switch(cmd) { case TARGET: { if(cmds.size()==1) { msg.source().tell(L("You must specify another ship to target.")); return false; } final Room thisRoom = (Room)owner(); if(thisRoom==null) { msg.source().tell(L("This ship is nowhere to be found!")); return false; } final String rest = CMParms.combine(cmds,1); final Boolean result = startAttack(msg.source(),thisRoom,rest); if(result == Boolean.TRUE) { if(this.targetedShip != null) msg.source().tell(L("You are now targeting @x1.",this.targetedShip.Name())); msg.source().tell(getTargetedShipInfo()); } else if(result == Boolean.FALSE) return false; else { msg.source().tell(L("You don't see '@x1' here to target",rest)); return false; } break; } case TENDER: { if(cmds.size()==1) { msg.source().tell(L("You must specify another ship to offer aboard.")); return false; } final Room thisRoom = (Room)owner(); if(thisRoom==null) { msg.source().tell(L("This ship is nowhere to be found!")); return false; } if(this.targetedShip!=null) { msg.source().tell(L("Not while you are in combat!")); return false; } final String rest = CMParms.combine(cmds,1); final Item I=thisRoom.findItem(rest); if((I instanceof GenSailingShip)&&(I!=this)&&(CMLib.flags().canBeSeenBy(I, msg.source()))) { final GenSailingShip otherShip = (GenSailingShip)I; if(otherShip.targetedShip != null) { msg.source().tell(L("Not while @x1 is in in combat!",otherShip.Name())); return false; } final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),thisRoom); try { mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); if(otherShip.tenderShip == this) { if(thisRoom.show(mob, otherShip, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> connect(s) her gangplank with <T-NAME>"))) { this.tenderShip = otherShip; final BoardableShip myArea=(BoardableShip)this.getShipArea(); final BoardableShip hisArea=(BoardableShip)otherShip.getShipArea(); final Room hisExitRoom = hisArea.unDock(false); final Room myExitRoom = myArea.unDock(false); myArea.dockHere(hisExitRoom); hisArea.dockHere(myExitRoom); } } else { if(thisRoom.show(mob, otherShip, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> extend(s) her gangplank toward(s) <T-NAME>"))) this.tenderShip = otherShip; } } finally { mob.destroy(); } } else { msg.source().tell(L("You don't see the ship '@x1' here to board",rest)); return false; } break; } case SINK: { if(!CMSecurity.isAllowedEverywhere(msg.source(), CMSecurity.SecFlag.CMDROOMS)) return true; final CMMsg damageMsg=CMClass.getMsg(msg.source(), this, CMMsg.MSG_DAMAGE, "SINK!!!"); damageMsg.setValue(99999); this.executeMsg(this, damageMsg); return false; } case AIM: { final Room thisRoom = (Room)owner(); if(thisRoom==null) { msg.source().tell(L("This ship is nowhere to be found!")); return false; } if((!this.amInTacticalMode()) ||(this.targetedShip==null) ||(!thisRoom.isContent((Item)this.targetedShip))) { msg.source().tell(L("You ship must be targeting an enemy to aim weapons.")); return false; } if(cmds.size()<3) { msg.source().tell(L("Aim what weapon how far ahead?")); msg.source().tell(getTargetedShipInfo()); return false; } final String leadStr = cmds.remove(cmds.size()-1); final String weaponStr = CMParms.combine(cmds,1); final Room mobR=msg.source().location(); if((!CMath.isInteger(leadStr))||(CMath.s_int(leadStr)<0)) { if(this.targetedShip!=null) msg.source().tell(L("'@x1' is not a valid distance ahead of @x2 to fire.",leadStr,this.targetedShip.name())); else msg.source().tell(L("'@x1' is not a valid distance.",leadStr)); return false; } if(mobR!=null) { final Item I=mobR.findItem(null, weaponStr); if((I==null)||(!CMLib.flags().canBeSeenBy(I,msg.source()))) { msg.source().tell(L("You don't see any siege weapon called '@x1' here.",leadStr)); return false; } if(!CMLib.combat().isAShipSiegeWeapon(I)) { msg.source().tell(L("@x1 is not a useable siege weapon.",leadStr)); return false; } final AmmunitionWeapon weapon=(AmmunitionWeapon)I; int distance = weapon.maxRange(); int[] targetCoords = new int[2]; int leadAmt=0; if(this.targetedShip instanceof GenSailingShip) { targetCoords = ((GenSailingShip)this.targetedShip).getMyCoords(); final int direction = ((GenSailingShip)this.targetedShip).directionFacing; if(targetCoords == null) { msg.source().tell(L("You ship must be targeting an enemy to aim weapons.")); return false; } distance = this.getTacticalDistance(this.targetedShip); leadAmt = CMath.s_int(leadStr); for(int i=0;i<leadAmt;i++) targetCoords = Directions.adjustXYByDirections(targetCoords[0], targetCoords[1], direction); } if((weapon.maxRange() < distance)||(weapon.minRange() > distance)) { msg.source().tell(L("Your target is presently at distance of @x1, but this weapons range is @x2 to @x3.", ""+distance,""+weapon.minRange(),""+weapon.maxRange())); return false; } if(weapon.requiresAmmunition() && (weapon.ammunitionCapacity() > 0) && (weapon.ammunitionRemaining() == 0)) { msg.source().tell(L("@x1 needs to be LOADed first.",weapon.Name())); return false; } final String timeToFire=""+(CMLib.threads().msToNextTick((Tickable)CMLib.combat(), Tickable.TICKID_SUPPORT|Tickable.TICKID_SOLITARYMASK) / 1000); final String msgStr=L("<S-NAME> aim(s) <O-NAME> at <T-NAME> (@x1).",""+leadAmt); if(msg.source().isMonster() && aimings.containsFirst(weapon)) { msg.source().tell(L("@x1 is already aimed.",weapon.Name())); return false; } final CMMsg msg2=CMClass.getMsg(msg.source(), targetedShip, weapon, CMMsg.MSG_NOISYMOVEMENT, msgStr); if(mobR.okMessage(msg.source(), msg2)) { this.aimings.removeFirst(weapon); this.aimings.add(new Pair<Weapon,int[]>(weapon,targetCoords)); mobR.send(msg.source(), msg2); msg.source().tell(L("@x1 is now aimed and will be fired in @x2 seconds.",I.name(),timeToFire)); } } return false; } case RAISE: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } final Room R=CMLib.map().roomLocation(this); final Room targetR=msg.source().location(); if((R!=null)&&(targetR!=null)) { if(((targetR.domainType()&Room.INDOORS)==0) && (targetR.domainType()!=Room.DOMAIN_OUTDOORS_AIR) &&(msg.source().isPlayer())) { msg.source().tell(L("You must be on deck to raise a tendered ship.")); return false; } final String rest = CMParms.combine(cmds,1); final Item I=R.findItem(rest); if((I!=this)&&(CMLib.flags().canBeSeenBy(I, msg.source()))) { if((I instanceof Rideable) &&(((Rideable)I).mobileRideBasis())) { if(smallTenderRequests.contains(I)) { final MOB riderM=getBestRider(R,(Rideable)I); if(((riderM==null)||(R.show(riderM, R, CMMsg.MSG_LEAVE, null))) &&(R.show(msg.source(), I, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> raise(s) <T-NAME> up onto @x1.",name()))) &&((riderM==null)||(R.show(riderM, targetR, CMMsg.MSG_ENTER, null)))) { smallTenderRequests.remove(I); targetR.moveItemTo(I, Expire.Never, Move.Followers); } return false; } else { msg.source().tell(L("You can only raise @x1 once it has tendered itself to this one.",I.name())); return false; } } else { msg.source().tell(L("You don't think @x1 is a suitable boat.",I.name())); return false; } } else { msg.source().tell(L("You don't see '@x1' out there!",rest)); return false; } } break; } case LOWER: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } final Room R=msg.source().location(); final Room targetR=CMLib.map().roomLocation(this); if((R!=null)&&(targetR!=null)) { if(((R.domainType()&Room.INDOORS)==0) && (R.domainType()!=Room.DOMAIN_OUTDOORS_AIR) &&(msg.source().isPlayer())) { msg.source().tell(L("You must be on deck to lower a boat.")); return false; } final String rest = CMParms.combine(cmds,1); final Item I=R.findItem(rest); if((I!=this)&&(CMLib.flags().canBeSeenBy(I, msg.source()))) { if((I instanceof Rideable) &&(((Rideable)I).mobileRideBasis()) &&((((Rideable)I).rideBasis()==Rideable.RIDEABLE_WATER) ||(((Rideable)I).rideBasis()==Rideable.RIDEABLE_AIR))) { final MOB riderM=getBestRider(R,(Rideable)I); if(((riderM==null)||(R.show(riderM, R, CMMsg.MSG_LEAVE, null))) &&(targetR.show(msg.source(), I, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> lower(s) <T-NAME> off of @x1.",name()))) &&((riderM==null)||(R.show(riderM, targetR, CMMsg.MSG_ENTER, null)))) { this.smallTenderRequests.remove(I); targetR.moveItemTo(I, Expire.Never, Move.Followers); } return false; } else { msg.source().tell(L("You don't think @x1 is a suitable thing for lowering.",I.name())); return false; } } else { msg.source().tell(L("You don't see '@x1' out there!",rest)); return false; } } break; } case WEIGH_ANCHOR: case RAISE_ANCHOR: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } if(safetyMove()) { msg.source().tell(L("The ship has moved!")); return false; } final Room R=CMLib.map().roomLocation(this); if(!anchorDown) msg.source().tell(L("The anchor is already up.")); else if(R!=null) { final CMMsg msg2=CMClass.getMsg(msg.source(), this, null, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> raise(s) anchor on <T-NAME>.")); if((R.okMessage(msg.source(), msg2) && this.okAreaMessage(msg2, true))) { R.send(msg.source(), msg2); anchorDown=false; } } return false; } case LOWER_ANCHOR: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } if(safetyMove()) { msg.source().tell(L("The ship has moved!")); return false; } final Room R=CMLib.map().roomLocation(this); if(anchorDown) msg.source().tell(L("The anchor is already down.")); else if(R!=null) { final CMMsg msg2=CMClass.getMsg(msg.source(), this, null, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> lower(s) anchor on <T-NAME>.")); if((R.okMessage(msg.source(), msg2) && this.okAreaMessage(msg2, true))) { R.send(msg.source(), msg2); this.sendAreaMessage(msg2, true); anchorDown=true; } } return false; } case STEER: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } if(CMLib.flags().isFalling(this) || ((this.subjectToWearAndTear() && (usesRemaining()<=0)))) { msg.source().tell(L("The ship won't seem to move!")); return false; } if(safetyMove()) { msg.source().tell(L("The ship has moved!")); return false; } if((courseDirection >=0)||(courseDirections.size()>0)) { if(!this.amInTacticalMode()) msg.source().tell(L("Your previous course has been cancelled.")); courseDirection = -1; courseDirections.clear(); } final int dir=CMLib.directions().getCompassDirectionCode(secondWord); if(dir<0) { msg.source().tell(L("Steer the ship which direction?")); return false; } final Room R=CMLib.map().roomLocation(this); if((R==null)||(msg.source().location()==null)) { msg.source().tell(L("You are nowhere, so you won`t be moving anywhere.")); return false; } if(((msg.source().location().domainType()&Room.INDOORS)==Room.INDOORS) &&(msg.source().isPlayer())) { msg.source().tell(L("You must be on deck to steer your ship.")); return false; } final String dirName = CMLib.directions().getDirectionName(dir); if(!this.amInTacticalMode()) { final Room targetRoom=R.getRoomInDir(dir); final Exit targetExit=R.getExitInDir(dir); if((targetRoom==null)||(targetExit==null)||(!targetExit.isOpen())) { msg.source().tell(L("There doesn't look to be anything in that direction.")); return false; } } else { directionFacing = getDirectionFacing(dir); if(dir == this.directionFacing) { msg.source().tell(L("Your ship is already sailing @x1.",dirName)); return false; } } if(anchorDown) { msg.source().tell(L("The anchor is down, so you won`t be moving anywhere.")); return false; } break; } case SAIL: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } if(CMLib.flags().isFalling(this) || ((this.subjectToWearAndTear() && (usesRemaining()<=0)))) { msg.source().tell(L("The ship won't seem to move!")); return false; } if(safetyMove()) { msg.source().tell(L("The ship has moved!")); return false; } if((courseDirection >=0)||(courseDirections.size()>0)) { if(!this.amInTacticalMode()) msg.source().tell(L("Your previous course has been cancelled.")); courseDirection = -1; courseDirections.clear(); } final Room R=CMLib.map().roomLocation(this); if((R==null)||(msg.source().location()==null)) { msg.source().tell(L("You are nowhere, so you won`t be moving anywhere.")); return false; } if(((msg.source().location().domainType()&Room.INDOORS)==Room.INDOORS) &&(msg.source().isPlayer())) { msg.source().tell(L("You must be on deck to sail your ship.")); return false; } final int dir=CMLib.directions().getCompassDirectionCode(secondWord); if(dir<0) { msg.source().tell(L("Sail the ship which direction?")); return false; } if(!this.amInTacticalMode()) { final Room targetRoom=R.getRoomInDir(dir); final Exit targetExit=R.getExitInDir(dir); if((targetRoom==null)||(targetExit==null)||(!targetExit.isOpen())) { msg.source().tell(L("There doesn't look to be anything in that direction.")); return false; } } else { final String dirName = CMLib.directions().getDirectionName(directionFacing); directionFacing = getDirectionFacing(dir); if(dir != this.directionFacing) { msg.source().tell(L("When in tactical mode, your ship can only SAIL @x1. Use COURSE for more complex maneuvers, or STEER.",dirName)); return false; } } if(anchorDown) { msg.source().tell(L("The anchor is down, so you won`t be moving anywhere.")); return false; } break; } case COURSE: case SET_COURSE: { if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } if(CMLib.flags().isFalling(this) || ((this.subjectToWearAndTear() && (usesRemaining()<=0)))) { msg.source().tell(L("The ship won't seem to move!")); return false; } if(safetyMove()) { msg.source().tell(L("The ship has moved!")); return false; } if((courseDirection >=0)||(courseDirections.size()>0)) { if(!this.amInTacticalMode()) msg.source().tell(L("Your previous course has been cancelled.")); courseDirection = -1; courseDirections.clear(); } final Room R=CMLib.map().roomLocation(this); if((R==null)||(msg.source().location()==null)) { msg.source().tell(L("You are nowhere, so you won`t be moving anywhere.")); return false; } if(((msg.source().location().domainType()&Room.INDOORS)==Room.INDOORS) &&(msg.source().isPlayer())) { msg.source().tell(L("You must be on deck to steer your ship.")); return false; } int dirIndex = 1; if(word.equals("SET")) dirIndex = 2; int firstDir = -1; this.courseDirections.clear(); if(amInTacticalMode()) { final int speed=getShipSpeed(); final String dirFacingName = CMLib.directions().getDirectionName(directionFacing); if(dirIndex >= cmds.size()) { msg.source().tell(L("Your ship is currently sailing @x1. To set a course, you must specify up to @x2 directions of travel, " + "of which only the last may be something other than @x3.",dirFacingName,""+speed,dirFacingName)); return false; } final List<String> dirNames = new ArrayList<String>(); final int[] coordinates = Arrays.copyOf(getMyCoords(),2); int otherDir = -1; for(;dirIndex<cmds.size();dirIndex++) { final String dirWord=cmds.get(dirIndex); final int dir=CMLib.directions().getCompassDirectionCode(dirWord); if(dir<0) { msg.source().tell(L("@x1 is not a valid direction.",dirWord)); return false; } if((otherDir < 0) && (dir == directionFacing)) { Directions.adjustXYByDirections(coordinates[0], coordinates[1], dir); final Room targetRoom=R.getRoomInDir(dir); final Exit targetExit=R.getExitInDir(dir); if((targetRoom==null)||(targetExit==null)||(!targetExit.isOpen())) { if(getLowestTacticalDistanceFromThis() >= R.maxRange()) { msg.source().tell(L("There doesn't look to be anywhere you can sail in that direction.")); return false; } } } if(this.courseDirections.size() >= speed) { msg.source().tell(L("Your course may not exceed your tactical speed, which is @x1 moves.", ""+speed)); return false; } if(otherDir > 0) { msg.source().tell(L("Your course includes a change of direction, from @x1 to @x2. " + "In tactical maneuvers, a changes of direction must be at the end of the course settings.", dirFacingName,CMLib.directions().getDirectionName(otherDir))); return false; } else if(dir != directionFacing) otherDir = dir; dirNames.add(CMLib.directions().getDirectionName(dir).toLowerCase()); this.courseDirections.add(Integer.valueOf(dir)); } this.courseDirection = this.removeTopCourse(); if((this.courseDirections.size()==0)||(getBottomCourse()>=0)) this.courseDirections.add(Integer.valueOf(-1)); this.announceActionToDeck(msg.source(),L("<S-NAME> order(s) a course setting of @x1.",CMLib.english().toEnglishStringList(dirNames.toArray(new String[0])))); } else { if(dirIndex >= cmds.size()) { msg.source().tell(L("To set a course, you must specify some directions of travel, separated by spaces.")); return false; } for(;dirIndex<cmds.size();dirIndex++) { final String dirWord=cmds.get(dirIndex); final int dir=CMLib.directions().getCompassDirectionCode(dirWord); if(dir<0) { msg.source().tell(L("@x1 is not a valid direction.",dirWord)); return false; } if(firstDir < 0) firstDir = dir; else this.courseDirections.add(Integer.valueOf(dir)); } final Room targetRoom=R.getRoomInDir(firstDir); final Exit targetExit=R.getExitInDir(firstDir); if((targetRoom==null)||(targetExit==null)||(!targetExit.isOpen())) { this.courseDirection=-1; this.courseDirections.clear(); msg.source().tell(L("There doesn't look to be anything in that direction.")); return false; } if((this.courseDirections.size()==0)||(getBottomCourse()>=0)) this.courseDirections.add(Integer.valueOf(-1)); steer(msg.source(),R, firstDir); } if(anchorDown) msg.source().tell(L("The anchor is down, so you won`t be moving anywhere.")); return false; } } } if(cmd != null) { cmds.add(0, "METAMSGCOMMAND"); double speed=getShipSpeed(); if(speed == 0) speed=0; else speed = msg.source().phyStats().speed() / speed; msg.source().enqueCommand(cmds, MUDCmdProcessor.METAFLAG_ASMESSAGE, speed); return false; } } else if((msg.sourceMinor()==CMMsg.TYP_COMMAND) &&(msg.sourceMessage()!=null) &&(area == CMLib.map().areaLocation(msg.source()))) { final List<String> cmds=CMParms.parse(msg.sourceMessage()); if(cmds.size()==0) return true; final String word=cmds.get(0).toUpperCase(); final String secondWord=(cmds.size()>1) ? cmds.get(1).toUpperCase() : ""; SailingCommand cmd = null; if(secondWord.length()>0) cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word+"_"+secondWord); if(cmd == null) cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word); if(cmd == null) return true; switch(cmd) { case SAIL: { final int dir=CMLib.directions().getCompassDirectionCode(secondWord); if(dir<0) return false; final Room R=CMLib.map().roomLocation(this); if(R==null) return false; if(!this.amInTacticalMode()) { this.courseDirections.clear(); // sail eliminates a course this.courseDirections.add(Integer.valueOf(-1)); this.beginSail(msg.source(), R, dir); } else { if(this.courseDirections.size()>0) msg.source().tell(L("Your prior course has been overridden.")); this.courseDirections.clear(); this.courseDirections.add(Integer.valueOf(-1)); this.courseDirection = dir; this.announceActionToDeck(msg.source(),L("<S-NAME> start(s) sailing @x1.",CMLib.directions().getDirectionName(dir))); } return false; } case STEER: { final int dir=CMLib.directions().getCompassDirectionCode(secondWord); if(dir<0) return false; final Room R=CMLib.map().roomLocation(this); if(R==null) return false; if(!this.amInTacticalMode()) { steer(msg.source(),R, dir); } else { if(this.courseDirections.size()>0) msg.source().tell(L("Your prior tactical course has been overridden.")); this.courseDirections.clear(); this.courseDirections.add(Integer.valueOf(-1)); this.courseDirection = dir; this.announceActionToDeck(msg.source(),L("<S-NAME> start(s) steering the ship @x1.",CMLib.directions().getDirectionName(dir))); } return false; } default: // already done... return false; } } else if((msg.targetMinor()==CMMsg.TYP_SIT) &&(msg.target()==this) &&(msg.source().location()==owner()) &&(CMLib.flags().isWateryRoom(msg.source().location())) &&(!CMLib.flags().isFlying(msg.source())) &&(!CMLib.flags().isFalling((Physical)msg.target())) &&(!CMLib.law().doesHavePriviledgesHere(msg.source(), super.getDestinationRoom(msg.source().location())))) { final Rideable ride=msg.source().riding(); if(ticksSinceMove < 2) { if(ride == null) msg.source().tell(CMLib.lang().L("You'll need some assistance to board a ship from the water.")); else msg.source().tell(msg.source(),this,ride,CMLib.lang().L("<S-NAME> chase(s) <T-NAME> around in <O-NAME>.")); return false; } else if(ride == null) { msg.source().tell(CMLib.lang().L("You'll need some assistance to board a ship from the water.")); return false; } else if(!CMLib.flags().isClimbing(msg.source())) { msg.source().tell(CMLib.lang().L("You'll need some assistance to board a ship from @x1, such as some means to climb up.",ride.name(msg.source()))); return false; } else msg.source().setRiding(null); // if you're climbing, you're not riding any more } else if((msg.sourceMinor()==CMMsg.TYP_COMMANDFAIL) &&(msg.targetMessage()!=null) &&(msg.targetMessage().length()>0)) { switch(Character.toUpperCase(msg.targetMessage().charAt(0))) { case 'A': { final List<String> parsedFail = CMParms.parse(msg.targetMessage()); final String cmd=parsedFail.get(0).toUpperCase(); if(("ATTACK".startsWith(cmd))&&(owner() instanceof Room)) { final Room thisRoom = (Room)owner(); final String rest = CMParms.combine(parsedFail,1); if(!securityCheck(msg.source())) { msg.source().tell(L("The captain does not permit you.")); return false; } final Boolean result = startAttack(msg.source(),thisRoom,rest); if(result == Boolean.FALSE) return false; else if(result == Boolean.TRUE) { msg.source().tell(getTargetedShipInfo()); return false; } } break; } case 'E': case 'L': { final List<String> parsedFail = CMParms.parse(msg.targetMessage()); final String cmd=parsedFail.get(0).toUpperCase(); if(("LOOK".startsWith(cmd)||"LLOOK".startsWith(cmd)||"EXAMINE".startsWith(cmd)) &&(owner() instanceof Room)) { final int msgType = "EXAMINE".startsWith(cmd) ? CMMsg.MSG_EXAMINE : CMMsg.MSG_LOOK; final Room R = (Room)owner(); final String rest = CMParms.combine(parsedFail,1); final Item I = R.findItem(null, rest); if((I instanceof GenSailingShip) ||((I instanceof Rideable)&&(((Rideable)I).rideBasis()==Rideable.RIDEABLE_WATER))) { final CMMsg lookMsg=CMClass.getMsg(msg.source(),I,null,msgType,null,msgType,null,msgType,null); if(R.okMessage(msg.source(),lookMsg)) { R.send(msg.source(),lookMsg); return false; } } } break; } case 'T': // throwing things to another ship, like a grapple { final List<String> parsedFail = CMParms.parse(msg.targetMessage()); final String cmd=parsedFail.get(0).toUpperCase(); if(("THROW".startsWith(cmd)) &&(owner() instanceof Room) &&(msg.source().location()!=null) &&((msg.source().location().domainType()&Room.INDOORS)==0) &&(parsedFail.size()>2)) { parsedFail.remove(0); final MOB mob=msg.source(); final Room R = (Room)owner(); String str=parsedFail.get(parsedFail.size()-1); parsedFail.remove(str); final String what=CMParms.combine(parsedFail,0); Item item=mob.fetchItem(null,Wearable.FILTER_WORNONLY,what); if(item==null) item=mob.findItem(null,what); if((item!=null) &&(CMLib.flags().canBeSeenBy(item,mob)) &&((item.amWearingAt(Wearable.WORN_HELD))||(item.amWearingAt(Wearable.WORN_WIELD)))) { str=str.toLowerCase(); if(str.equals("water")||str.equals("overboard")||CMLib.english().containsString(R.displayText(), str)) { final Room target=R; final CMMsg msg2=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<S-NAME> throw(s) <O-NAME> overboard.")); final CMMsg msg3=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<O-NAME> fl(ys) in from overboard.")); if(mob.location().okMessage(mob,msg2)&&target.okMessage(mob,msg3)) { mob.location().send(mob,msg2); target.sendOthers(mob,msg3); } return false; } final Item I = R.findItem(null, str); if(I!=this) { if((I instanceof GenSailingShip) ||((I instanceof Rideable)&&(((Rideable)I).rideBasis()==Rideable.RIDEABLE_WATER))) { if((!amInTacticalMode()) ||(I.maxRange() < getTacticalDistance(I))) { msg.source().tell(L("You can't throw @x1 at @x2, it's too far away!",item.name(msg.source()),I.name(msg.source()))); return false; } else if(getMyCoords()!=null) { final int[] targetCoords = ((GenSailingShip)I).getMyCoords(); if(targetCoords!=null) { final int dir = Directions.getRelativeDirection(getMyCoords(), targetCoords); final String inDir=CMLib.directions().getShipInDirectionName(dir); final String fromDir=CMLib.directions().getFromShipDirectionName(Directions.getOpDirectionCode(dir)); Room target = ((GenSailingShip)I).getRandomDeckRoom(); if(target == null) target=R; final CMMsg msg2=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<S-NAME> throw(s) <O-NAME> @x1.",inDir.toLowerCase())); final CMMsg msg3=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<O-NAME> fl(ys) in from @x1.",fromDir.toLowerCase())); if(mob.location().okMessage(mob,msg2)&&target.okMessage(mob,msg3)) { mob.location().send(mob,msg2); target.sendOthers(mob,msg3); } return false; } else { msg.source().tell(L("You can't throw @x1 at @x2, it's too far away!",item.name(msg.source()),I.name(msg.source()))); return false; } } else { msg.source().tell(L("You can't throw @x1 at @x2, it's too far away!",item.name(msg.source()),I.name(msg.source()))); return false; } } } } } break; } } } else if((msg.targetMinor()==CMMsg.TYP_LEAVE) &&(msg.target() instanceof Room) &&(msg.target() == owner())) { if((msg.source().riding() != null) &&(this.targetedShip == msg.source().riding()) &&(CMLib.flags().isWaterWorthy(msg.source().riding()))) { msg.source().tell(L("Your small vessel can not get away during combat.")); return false; } if(msg.tool() instanceof Exit) { final Room R=msg.source().location(); final int dir=CMLib.map().getExitDir(R,(Exit)msg.tool()); if((dir >= 0) &&(R.getRoomInDir(dir)!=null) &&(R.getRoomInDir(dir).getArea()==this.getShipArea()) &&(msg.othersMessage()!=null) &&(msg.othersMessage().indexOf("<S-NAME>")>=0) &&(msg.othersMessage().indexOf(L(CMLib.flags().getPresentDispositionVerb(msg.source(),CMFlagLibrary.ComingOrGoing.LEAVES)))>=0)) msg.setOthersMessage(L("<S-NAME> board(s) @x1.",Name())); } } else if((msg.targetMinor()==CMMsg.TYP_ENTER) &&(msg.target() == owner()) &&(msg.source().location()!=null) &&(msg.source().location().getArea()==this.getShipArea()) &&(msg.tool() instanceof Exit) &&(msg.othersMessage()!=null) &&(msg.othersMessage().indexOf("<S-NAME>")>=0) &&(msg.othersMessage().indexOf(L(CMLib.flags().getPresentDispositionVerb(msg.source(),CMFlagLibrary.ComingOrGoing.ARRIVES)))>=0)) msg.setOthersMessage(L("<S-NAME> disembark(s) @x1.",Name())); else if((msg.sourceMinor()==CMMsg.TYP_HUH) &&(msg.targetMessage()!=null) &&(msg.source().riding() instanceof Item) &&(msg.source().riding().mobileRideBasis()) &&(owner() == CMLib.map().roomLocation(msg.source()))) { final List<String> cmds=CMParms.parse(msg.targetMessage()); if(cmds.size()==0) return true; final String word=cmds.get(0).toUpperCase(); final String secondWord=(cmds.size()>1) ? cmds.get(1).toUpperCase() : ""; SailingCommand cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word); if((cmd == null)&&(secondWord.length()>0)) cmd = (SailingCommand)CMath.s_valueOf(SailingCommand.class, word+"_"+secondWord); if(cmd != null) { switch(cmd) { default: break; case TENDER: { if(cmds.size()==1) { msg.source().tell(L("You must specify another ship to offer to board.")); return false; } final Room thisRoom = (Room)owner(); if(thisRoom==null) { msg.source().tell(L("This ship is nowhere to be found!")); return false; } /*//TODO: maybe check to see if the lil ship is if(this.targetedShip!=null) { msg.source().tell(L("Not while you are in combat!")); return false; } */ final String rest = CMParms.combine(cmds,1); final Item meI=thisRoom.findItem(rest); if((meI==this) &&(CMLib.flags().canBeSeenBy(this, msg.source()))) { if(targetedShip != null) { msg.source().tell(L("Not while @x1 is in in combat!",Name())); return false; } final Room R=CMLib.map().roomLocation(msg.source()); if((R!=null) &&(R.show(msg.source(), this, CMMsg.TYP_ADVANCE, L("<S-NAME> tender(s) @x1 alonside <T-NAME>, waiting to be raised on board.",msg.source().riding().name())))) { for(final Iterator<Item> i=smallTenderRequests.iterator();i.hasNext();) { final Item I=i.next(); if(!R.isContent(I)) smallTenderRequests.remove(I); } final Rideable sR=msg.source().riding(); if(sR instanceof Item) { final Item isR = (Item)sR; if(!smallTenderRequests.contains(isR)) smallTenderRequests.add(isR); } } } else { msg.source().tell(L("You don't see the ship '@x1' here to tender with",rest)); return false; } break; } } } } if(!super.okMessage(myHost, msg)) return false; return true; } protected Boolean startAttack(final MOB sourceM, final Room thisRoom, final String rest) { final Item I=thisRoom.findItem(rest); if((I instanceof Rideable)&&(I!=this)&&(CMLib.flags().canBeSeenBy(I, sourceM))) { if(!sourceM.mayPhysicallyAttack(I)) { sourceM.tell(L("You are not permitted to attack @x1",I.name())); return Boolean.FALSE; } if(!CMLib.flags().isDeepWaterySurfaceRoom(thisRoom)) { sourceM.tell(L("You are not able to engage in combat with @x1 here.",I.name())); return Boolean.FALSE; } final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),thisRoom); try { mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); final CMMsg maneuverMsg=CMClass.getMsg(mob,I,null,CMMsg.MSG_ADVANCE,null,CMMsg.MASK_MALICIOUS|CMMsg.MSG_ADVANCE,null,CMMsg.MSG_ADVANCE,L("<S-NAME> engage(s) @x1.",I.Name())); if(thisRoom.okMessage(mob, maneuverMsg)) { thisRoom.send(mob, maneuverMsg); targetedShip = I; shipCombatRoom = thisRoom; if(I instanceof GenSailingShip) { final GenSailingShip otherI=(GenSailingShip)I; if(otherI.targetedShip == null) otherI.targetedShip = this; otherI.shipCombatRoom = thisRoom; otherI.amInTacticalMode(); // now he is in combat } amInTacticalMode(); // now he is in combat //also support ENGAGE <shipname> as an alternative to attack? return Boolean.TRUE; } } finally { mob.destroy(); } } return null; } protected int[] getMagicCoords() { final Room R=CMLib.map().roomLocation(this); final int[] coords; final int middle = (int)Math.round(Math.floor(R.maxRange() / 2.0)); final int extreme = R.maxRange()-1; final int midDiff = (middle > 0) ? CMLib.dice().roll(1, middle, -1) : 0; final int midDiff2 = (middle > 0) ? CMLib.dice().roll(1, middle, -1) : 0; final int extremeRandom = (extreme > 0) ? CMLib.dice().roll(1, R.maxRange(), -1) : 0; final int extremeRandom2 = (extreme > 0) ? CMLib.dice().roll(1, R.maxRange(), -1) : 0; switch(this.directionFacing) { case Directions.NORTH: coords = new int[] {extremeRandom,extreme-midDiff}; break; case Directions.SOUTH: coords = new int[] {extremeRandom,midDiff}; break; case Directions.EAST: coords = new int[] {midDiff,extremeRandom}; break; case Directions.WEST: coords = new int[] {extreme-midDiff,extremeRandom}; break; case Directions.UP: coords = new int[] {extremeRandom,extremeRandom2}; break; case Directions.DOWN: coords = new int[] {extremeRandom,extremeRandom2}; break; case Directions.NORTHEAST: coords = new int[] {midDiff,extreme-midDiff2}; break; case Directions.NORTHWEST: coords = new int[] {extreme-midDiff,extreme-midDiff2}; break; case Directions.SOUTHEAST: coords = new int[] {extreme-midDiff,midDiff2}; break; case Directions.SOUTHWEST: coords = new int[] {midDiff,midDiff2}; break; default: coords = new int[] {extremeRandom,extremeRandom2}; break; } return coords; } protected void clearTacticalModeHelper() { synchronized((""+shipCombatRoom + "_SHIP_TACTICAL").intern()) { final PairList<Item,int[]> coords = this.coordinates; if(coords != null) { coords.removeFirst(this); } } this.targetedShip = null; this.shipCombatRoom = null; this.coordinates = null; this.aimings.clear(); } protected synchronized void clearTacticalMode() { final Room shipCombatRoom = this.shipCombatRoom; if(shipCombatRoom != null) { PairList<Item,int[]> coords = null; synchronized((""+shipCombatRoom + "_SHIP_TACTICAL").intern()) { coords = this.coordinates; } clearTacticalModeHelper(); if(coords != null) { for(final Iterator<Item> s = coords.firstIterator();s.hasNext();) { final Item I=s.next(); if((I instanceof GenSailingShip) &&(((GenSailingShip)I).targetedShip == this)) ((GenSailingShip)I).clearTacticalModeHelper(); } } } } protected boolean isAnyoneAtCoords(final int[] xy) { final PairList<Item, int[]> coords = this.coordinates; if(coords != null) { for(final Iterator<int[]> i = coords.secondIterator(); i.hasNext();) { if(Arrays.equals(xy, i.next())) return true; } } return false; } protected int[] getMyCoords() { final PairList<Item, int[]> coords = this.coordinates; if(coords != null) { for(final Iterator<Pair<Item,int[]>> i = coords.iterator(); i.hasNext();) { final Pair<Item,int[]> P=i.next(); if(P.first == this) return P.second; } } return null; } protected synchronized boolean amInTacticalMode() { final Item targetedShip = (Item)this.targetedShip; final Room shipCombatRoom = this.shipCombatRoom; if((targetedShip != null) && (shipCombatRoom != null) && (shipCombatRoom.isContent(targetedShip)) && (shipCombatRoom.isContent(this)) ) { if(coordinates == null) { synchronized((""+shipCombatRoom + "_SHIP_TACTICAL").intern()) { for(int i=0;i<shipCombatRoom.numItems();i++) { final Item I=shipCombatRoom.getItem(i); if((I instanceof GenSailingShip) &&(((GenSailingShip)I).coordinates != null)) { this.coordinates = ((GenSailingShip)I).coordinates; } } if(coordinates == null) { this.coordinates = new SPairList<Item,int[]>(); } } final PairList<Item,int[]> coords = this.coordinates; if(coords != null) { if(!coords.containsFirst(this)) { int[] newCoords = null; for(int i=0;i<10;i++) { newCoords = this.getMagicCoords(); if(!isAnyoneAtCoords(newCoords)) break; } coords.add(new Pair<Item,int[]>(this,newCoords)); } } } return true; } else { this.targetedShip = null; this.shipCombatRoom = null; this.coordinates = null; return false; } } @Override public boolean tick(final Tickable ticking, final int tickID) { final int sailingTickID = amInTacticalMode() ? Tickable.TICKID_SPECIALMANEUVER : Tickable.TICKID_AREA; if(tickID == Tickable.TICKID_AREA) { if(amDestroyed()) return false; final Area area = this.getShipArea(); if(area instanceof BoardableShip) { if((this.tenderShip != null) &&(this.tenderShip.owner()==owner()) &&(this.targetedShip==null) &&(this.tenderShip instanceof GenSailingShip) &&(((GenSailingShip)this.tenderShip).targetedShip==null)) { // yay! } else { this.tenderShip=null; if((((BoardableShip)area).getIsDocked() != owner()) &&(owner() instanceof Room)) { this.dockHere((Room)owner()); } } } } if(tickID == sailingTickID) { ticksSinceMove++; if((!this.anchorDown) && (area != null) && (courseDirection != -1) ) { final int speed=getShipSpeed(); for(int s=0;s<speed && (courseDirection>=0);s++) { switch(sail(courseDirection & 127)) { case CANCEL: { courseDirection=-1; break; } case CONTINUE: { if(this.courseDirections.size()>0) { this.courseDirection = this.removeTopCourse(); } else { if((courseDirection & COURSE_STEER_MASK) == 0) courseDirection = -1; } break; } case REPEAT: { break; } } } if(tickID == Tickable.TICKID_SPECIALMANEUVER) { final Room combatRoom=this.shipCombatRoom; if(combatRoom != null) { final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),null); try { mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); combatRoom.show(mob, this, CMMsg.MSG_ACTIVATE|CMMsg.MASK_MALICIOUS, null); } finally { mob.destroy(); } } final PairList<Item,int[]> coords = this.coordinates; if(coords != null) { for(final Iterator<Item> i= coords.firstIterator(); i.hasNext();) { final Item I=i.next(); if((I instanceof GenSailingShip) &&(((GenSailingShip)I).targetedShip == this)) ((GenSailingShip)I).announceToDeck(((GenSailingShip)I).getTargetedShipInfo()); } } } } } if(tickID == Tickable.TICKID_SPECIALCOMBAT) { if(this.amInTacticalMode()) { final List<Weapon> weapons = new LinkedList<Weapon>(); for(final Enumeration<Room> r=this.getShipArea().getProperMap();r.hasMoreElements();) { try { final Room R=r.nextElement(); if(R!=null) { for(final Enumeration<Item> i=R.items();i.hasMoreElements();) { try { final Item I=i.nextElement(); if(isAShipSiegeWeaponReadyToFire(I)) weapons.add((Weapon)I); } catch(final NoSuchElementException ne) { } } } } catch(final NoSuchElementException ne) { } } if(weapons.size()>0) { final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),null); final int[] coordsToHit; if(this.targetedShip instanceof GenSailingShip) coordsToHit = ((GenSailingShip)this.targetedShip).getMyCoords(); else coordsToHit = new int[2]; try { mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); int notLoaded = 0; int notAimed = 0; final PairList<Weapon,int[]> aimings=this.aimings; for(final Weapon w : weapons) { final Room R=CMLib.map().roomLocation(w); if(R!=null) { mob.setLocation(R); if((w instanceof AmmunitionWeapon) &&(((AmmunitionWeapon)w).requiresAmmunition()) &&(((AmmunitionWeapon)w).ammunitionRemaining() <=0)) notLoaded++; else if(aimings!=null) { //mob.setRangeToTarget(0); final int index = aimings.indexOfFirst(w); if(index >= 0) { final int[] coordsAimedAt = aimings.remove(index).second; final boolean wasHit = Arrays.equals(coordsAimedAt, coordsToHit); CMLib.combat().postShipAttack(mob, this, this.targetedShip, w, wasHit); } else notAimed++; } } } final String spamMsg; if((notLoaded > 0) && (notAimed > 0)) spamMsg = L("@x1 of your weapons were not loaded, and @x2 were ready but not aimed.",""+notLoaded, ""+notAimed); else if(notLoaded > 0) spamMsg = L("@x1 of your weapons were not loaded.",""+notLoaded); else if(notAimed > 0) spamMsg = L("@x1 of your weapons were ready but not aimed.",""+notAimed); else spamMsg = ""; if(spamMsg.length()>0) { if(spamMsg.equals(lastSpamMsg)) { if(lastSpamCt < 3) { announceToDeck(spamMsg); lastSpamCt++; } } else { announceToDeck(spamMsg); lastSpamCt=0; } } lastSpamMsg=spamMsg; } finally { mob.setRangeToTarget(0); mob.destroy(); } } } } return super.tick(ticking, tickID); } protected final boolean isAShipSiegeWeaponReadyToFire(final Item I) { if(CMLib.combat().isAShipSiegeWeapon(I)) { if(((Rideable)I).riderCapacity() > 0) return ((Rideable)I).numRiders() >= ((Rideable)I).riderCapacity(); return true; } return false; } protected static MOB getBestRider(final Room R, final Rideable rI) { MOB bestM=null; for(final Enumeration<Rider> m=rI.riders();m.hasMoreElements();) { final Rider R2=m.nextElement(); if((R2 instanceof MOB) && (R.isInhabitant((MOB)R2))) { if(((MOB)R2).isPlayer()) return (MOB)R2; else if((bestM!=null)&&(bestM.amFollowing()!=null)) bestM=(MOB)R2; else bestM=(MOB)R2; } } return bestM; } protected static String staticL(final String str, final String... xs) { return CMLib.lang().fullSessionTranslation(str, xs); } public static void appendCondition(final StringBuilder visualCondition, final double pct, final String name) { if(pct<=0.0) visualCondition.append(staticL("\n\r^r@x1^r is nothing but wreckage!^N",name)); else if(pct<.10) visualCondition.append(staticL("\n\r^r@x1^r is near destruction!^N",name)); else if(pct<.20) visualCondition.append(staticL("\n\r^r@x1^r is massively splintered and damaged.^N",name)); else if(pct<.30) visualCondition.append(staticL("\n\r^r@x1^r is extremely splintered and damaged.^N",name)); else if(pct<.40) visualCondition.append(staticL("\n\r^y@x1^y is very splintered and damaged.^N",name)); else if(pct<.50) visualCondition.append(staticL("\n\r^y@x1^y is splintered and damaged.^N",name)); else if(pct<.60) visualCondition.append(staticL("\n\r^p@x1^p is splintered and slightly damaged.^N",name)); else if(pct<.70) visualCondition.append(staticL("\n\r^p@x1^p is showing large splinters.^N",name)); else if(pct<.80) visualCondition.append(staticL("\n\r^g@x1^g is showing some splinters.^N",name)); else if(pct<.90) visualCondition.append(staticL("\n\r^g@x1^g is showing small splinters.^N",name)); else if(pct<.99) visualCondition.append(staticL("\n\r^g@x1^g is no longer in perfect condition.^N",name)); else visualCondition.append(staticL("\n\r^c@x1^c is in perfect condition.^N",name)); } protected void cleanMsgForRepeat(final CMMsg msg) { msg.setSourceCode(CMMsg.NO_EFFECT); if(msg.trailerRunnables()!=null) msg.trailerRunnables().clear(); if(msg.trailerMsgs()!=null) { for(final CMMsg msg2 : msg.trailerMsgs()) cleanMsgForRepeat(msg2); } } @Override public void executeMsg(final Environmental myHost, final CMMsg msg) { super.executeMsg(myHost,msg); switch(msg.sourceMinor()) { case CMMsg.TYP_HUH: case CMMsg.TYP_COMMANDFAIL: case CMMsg.TYP_COMMAND: break; default: if(msg.source().riding()==this) { sendAreaMessage(msg, true); final ItemPossessor owner = owner(); if((owner instanceof Room) &&(owner != prevItemRoom) &&(this.area instanceof BoardableShip)) { final Room R = (Room)owner; boolean fixSky=false; final Room oldR; synchronized(this) { oldR=this.prevItemRoom; fixSky = ((R!=oldR)&&(oldR!=null)); if(oldR!=R) this.prevItemRoom=R; } if(fixSky) { final boolean wasWater=CMLib.flags().isUnderWateryRoom(oldR); final boolean isWater=CMLib.flags().isUnderWateryRoom(R); final boolean isSunk = isWater && (R.getGridParent()!=null) && (R.getGridParent().roomID().length()==0); if(wasWater || isSunk) { for(final Enumeration<Room> r=area.getProperMap();r.hasMoreElements();) { final Room inR=r.nextElement(); if(((inR.domainType()&Room.INDOORS)==0) &&(inR.roomID().length()>0)) { inR.clearSky(); if(isSunk) { if((inR.getRoomInDir(Directions.UP)==null) &&(inR.getExitInDir(Directions.UP)==null)) { inR.giveASky(0); final Exit redirExit = CMClass.getExit("NamedRedirectable"); redirExit.setDisplayText(R.displayText()); redirExit.setDescription(R.displayText()); redirExit.lastRoomUsedFrom(R); inR.setRawExit(Directions.UP, redirExit); } } else inR.giveASky(0); } } } } } } else if(msg.othersMessage()==null) sendAreaMessage(msg, true); else { final CMMsg msg2=(CMMsg)msg.copyOf(); msg2.setOthersMessage(L("^HOff the deck you see: ^N")+msg.othersMessage()); cleanMsgForRepeat(msg2); sendAreaMessage(msg2, true); } } if(msg.target() == this) { switch(msg.targetMinor()) { case CMMsg.TYP_LOOK: case CMMsg.TYP_EXAMINE: { final StringBuilder visualCondition = new StringBuilder(""); if(this.anchorDown) visualCondition.append(L("^HThe anchor on @x1 is lowered, holding her in place.^.^?",name(msg.source()))); else if((this.courseDirection >= 0) &&(getTopCourse()>=0)) visualCondition.append(L("^H@x1 is under full sail, traveling @x2^.^?",CMStrings.capitalizeFirstLetter(name(msg.source())), CMLib.directions().getDirectionName(courseDirection & 127))); if(this.subjectToWearAndTear() && (usesRemaining() <= 100)) { final double pct=(CMath.div(usesRemaining(),100.0)); appendCondition(visualCondition,pct,name(msg.source())); } if(visualCondition.length()>0) { msg.addTrailerRunnable(new Runnable() { @Override public void run() { msg.source().tell(visualCondition.toString()); msg.trailerRunnables().remove(this); } }); } break; } default: break; } } if((msg.target() instanceof Room) &&(msg.target() == owner())) { switch(msg.targetMinor()) { case CMMsg.TYP_LOOK: case CMMsg.TYP_EXAMINE: if((CMLib.map().areaLocation(msg.source())==area)) { final StringBuilder visualCondition = new StringBuilder(""); if(this.anchorDown) visualCondition.append(L("\n\r^HThe anchor on @x1 is lowered, holding her in place.^.^?",name(msg.source()))); else if((this.courseDirection >= 0) &&(getTopCourse()>=0)) visualCondition.append(L("\n\r^H@x1 is under full sail, traveling @x2^.^?",name(msg.source()), CMLib.directions().getDirectionName(courseDirection & 127))); if(this.subjectToWearAndTear() && (usesRemaining() <= 100) && (this.targetedShip != null)) { final double pct=(CMath.div(usesRemaining(),100.0)); appendCondition(visualCondition,pct,name(msg.source())); } if(visualCondition.length()>0) msg.addTrailerMsg(CMClass.getMsg(msg.source(), null, null, CMMsg.MSG_OK_VISUAL, visualCondition.toString(), -1, null, -1, null)); } break; case CMMsg.TYP_LEAVE: case CMMsg.TYP_ENTER: if((owner() instanceof Room) &&(msg.target() instanceof Room) &&(((Room)msg.target()).getArea()!=area)) { if(((msg.source().riding() == this) &&(msg.source().Name().equals(Name()))) ||((this.targetedShip!=null) &&(msg.source().riding() == targetedShip) &&(msg.source().Name().equals(targetedShip.Name())))) { clearTacticalMode(); } } break; } } else if(msg.target() == this) { switch(msg.targetMinor()) { case CMMsg.TYP_ENTER: break; case CMMsg.TYP_WEAPONATTACK: if(msg.targetMinor()==CMMsg.TYP_WEAPONATTACK) { Weapon weapon=null; if((msg.tool() instanceof Weapon)) weapon=(Weapon)msg.tool(); if((weapon!=null) &&(((msg.source().riding()!=null)&&(owner() instanceof Room)) ||((msg.source().location()!=null) && (weapon.owner()==null)))) { final Room shipRoom=(Room)owner(); final boolean isHit=msg.value()>0; if(isHit && CMLib.combat().isAShipSiegeWeapon(weapon) && (((AmmunitionWeapon)weapon).ammunitionCapacity() > 1)) { int shotsRemaining = ((AmmunitionWeapon)weapon).ammunitionRemaining() + 1; ((AmmunitionWeapon)weapon).setAmmoRemaining(0); final Area A=this.getShipArea(); final ArrayList<Pair<MOB,Room>> targets = new ArrayList<Pair<MOB,Room>>(5); if(A!=null) { for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null)&&((R.domainType()&Room.INDOORS)==0)) { for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();) targets.add(new Pair<MOB,Room>(m.nextElement(),R)); } } } final int chanceToHit = targets.size() * 20; final Room oldRoom=msg.source().location(); try { final double pctLoss = CMath.div(msg.value(), 100.0); while(shotsRemaining-- > 0) { final Pair<MOB,Room> randomPair = (targets.size()>0)? targets.get(CMLib.dice().roll(1,targets.size(),-1)) : null; if((CMLib.dice().rollPercentage() < chanceToHit)&&(randomPair != null)) { msg.source().setLocation(shipRoom); final int pointsLost = (int)Math.round(pctLoss * msg.source().maxState().getHitPoints()); CMLib.combat().postWeaponDamage(msg.source(), randomPair.first, weapon, pointsLost); } else if(randomPair != null) { msg.source().setLocation(shipRoom); CMLib.combat().postWeaponAttackResult(msg.source(), randomPair.first, weapon, false); } else { this.announceActionToDeck(msg.source(), msg.target(), weapon, weapon.missString()); } } } finally { msg.source().setLocation(oldRoom); } } else { PhysicalAgent attacker; if(msg.source().riding() instanceof BoardableShip) attacker=msg.source().riding(); else { final Room R=msg.source().location(); if((R!=null) &&(R.getArea() instanceof BoardableShip)) attacker=((BoardableShip)R.getArea()).getShipItem(); else attacker=null; } if(attacker != null) CMLib.combat().postShipWeaponAttackResult(msg.source(), attacker, this, weapon, isHit); } } } break; case CMMsg.TYP_DAMAGE: if(msg.value() > 0) { final int maxHullPoints = CMLib.combat().getShipHullPoints(this); final double pctLoss = CMath.div(msg.value(), maxHullPoints); final int pointsLost = (int)Math.round(pctLoss * maxHullPoints); if(pointsLost > 0) { final int weaponType = (msg.tool() instanceof Weapon) ? ((Weapon)msg.tool()).weaponDamageType() : Weapon.TYPE_BASHING; final String hitWord = CMLib.combat().standardHitWord(weaponType, pctLoss); final String msgStr = (msg.targetMessage() == null) ? L("<O-NAME> fired from <S-NAME> hits and @x1 @x2.",hitWord,name()) : msg.targetMessage(); final CMMsg deckHitMsg=CMClass.getMsg(msg.source(), this, msg.tool(),CMMsg.MSG_OK_ACTION, msgStr); this.announceActionToDeckOrUnderdeck(msg.source(), deckHitMsg, 0); final CMMsg underdeckHitMsg=CMClass.getMsg(msg.source(), this, msg.tool(),CMMsg.MSG_OK_ACTION, L("Something hits and @x1 the ship.",hitWord)); this.announceActionToDeckOrUnderdeck(msg.source(), underdeckHitMsg, Room.INDOORS); if(pointsLost >= this.usesRemaining()) { this.setUsesRemaining(0); this.recoverPhyStats(); // takes away the swimmability! final Room shipR=CMLib.map().roomLocation(this); if(shipR!=null) { CMLib.tracking().makeSink(this, shipR, false); final String sinkString = L("<T-NAME> start(s) sinking!"); shipR.show(msg.source(), this, CMMsg.MSG_OK_ACTION, sinkString); this.announceActionToUnderDeck(msg.source(), sinkString); } if((msg.source().riding() instanceof BoardableShip) &&((msg.source().Name().equals(msg.source().riding().Name())))) { final Area A=((BoardableShip)msg.source().riding()).getShipArea(); if(A!=null) { for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null) &&(R.numInhabitants()>0)) { for(final Enumeration<MOB> m=R.inhabitants();m.hasMoreElements();) { final MOB M=m.nextElement(); final CMMsg msg2=CMClass.getMsg(M, this, CMMsg.MSG_CAUSESINK, null); this.sendAreaMessage(msg2, false); R.showSource(M, this, CMMsg.MSG_CAUSESINK, null); CMLib.achievements().possiblyBumpAchievement(M, Event.SHIPSSUNK, 1, this); } } } } } if(!CMLib.leveler().postExperienceToAllAboard(msg.source().riding(), 500, this)) CMLib.leveler().postExperience(msg.source(), null, null, 500, false); this.clearTacticalMode(); } else { this.setUsesRemaining(this.usesRemaining() - pointsLost); } } } break; } } else if(msg.target() instanceof AmmunitionWeapon) { switch(msg.targetMinor()) { case CMMsg.TYP_RELOAD: if((msg.tool() instanceof Ammunition) &&(CMLib.combat().isAShipSiegeWeapon((Item)msg.target()))) { final MOB tellM=msg.source(); final Item I= (Item)msg.target(); msg.addTrailerRunnable(new Runnable() { @Override public void run() { tellM.tell(L("@x1 is now loaded. Don't forget to aim.",I.name())); } }); } break; } } else { switch(msg.targetMinor()) { case CMMsg.TYP_LOOK: case CMMsg.TYP_EXAMINE: if((msg.target() instanceof BoardableShip) &&(msg.target() instanceof Rideable) &&(msg.target()!=this)) { final String otherShipInfo=getOtherShipInfo((Rideable)msg.target()); if(otherShipInfo.length()>0) { msg.addTrailerRunnable(new Runnable() { @Override public void run() { msg.source().tell(otherShipInfo); } }); } } break; } } } @Override public void setExpirationDate(final long time) { // necessary because stdboardable protects its space ships in rooms this.dispossessionTime=time; } @Override public long expirationDate() { final Room R=CMLib.map().roomLocation(this); if(R==null) return 0; if((!CMLib.flags().isUnderWateryRoom(R)) &&(this.usesRemaining()>0)) return 0; return super.expirationDate(); } @Override protected Room findNearestDocks(final Room R) { if(R!=null) { if(R.domainType()==Room.DOMAIN_OUTDOORS_SEAPORT) return R; TrackingLibrary.TrackingFlags flags; flags = CMLib.tracking().newFlags() .plus(TrackingLibrary.TrackingFlag.AREAONLY) .plus(TrackingLibrary.TrackingFlag.NOEMPTYGRIDS) .plus(TrackingLibrary.TrackingFlag.NOAIR) .plus(TrackingLibrary.TrackingFlag.NOHOMES) .plus(TrackingLibrary.TrackingFlag.UNLOCKEDONLY); final List<Room> rooms=CMLib.tracking().getRadiantRooms(R, flags, 25); for(final Room R2 : rooms) { if(R2.domainType()==Room.DOMAIN_OUTDOORS_SEAPORT) return R2; } for(final Room R2 : rooms) { if(CMLib.flags().isDeepWaterySurfaceRoom(R2)) { for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { final Room adjacentR = R2.getRoomInDir(d); final Exit adjacentE = R2.getExitInDir(d); if((adjacentR!=null) &&(adjacentE!=null) &&(adjacentE.isOpen()) &&(!CMLib.flags().isWateryRoom(adjacentR))) return adjacentR; } } } } return null; } private static enum SailResult { CANCEL, CONTINUE, REPEAT } protected int[] getCoordAdjustments(final int[] newOnes) { final PairList<Item,int[]> coords = this.coordinates; final int[] lowests = new int[2]; if(coords != null) { if(newOnes != null) { if(newOnes[0] < lowests[0]) lowests[0]=newOnes[0]; if(newOnes[1] < lowests[1]) lowests[1]=newOnes[1]; } for(int p=0;p<coords.size();p++) { try { final Pair<Item,int[]> P = coords.get(p); if((newOnes==null)||(P.first!=this)) { if(P.second[0] < lowests[0]) lowests[0]=P.second[0]; if(P.second[1] < lowests[1]) lowests[1]=P.second[1]; } } catch(final Exception e) { } } } lowests[0]=-lowests[0]; lowests[1]=-lowests[1]; return lowests; } protected int getTacticalDistance(final PhysicalAgent targetShip) { final int[] fromCoords = this.getMyCoords(); final PairList<Item,int[]> coords = this.coordinates; int lowest = Integer.MAX_VALUE; if((coords != null) && (fromCoords != null)) { final int p = coords.indexOfFirst((Item)targetShip); if(p >=0) { final Pair<Item,int[]> P=coords.get(p); final int distance = (int)Math.round(Math.ceil(Math.sqrt(Math.pow(P.second[0]-fromCoords[0],2.0) + Math.pow(P.second[1]-fromCoords[1],2.0)))); if(distance < lowest) lowest=distance; } } if(lowest == Integer.MAX_VALUE) return CMLib.map().roomLocation(this).maxRange() + 1; return lowest; } protected int getLowestTacticalDistanceFromThis() { final int[] fromCoords = this.getMyCoords(); final PairList<Item,int[]> coords = this.coordinates; int lowest = Integer.MAX_VALUE; if((coords != null) && (fromCoords != null)) { for(int p=0;p<coords.size();p++) { try { final Pair<Item,int[]> P = coords.get(p); if((P.second != fromCoords) &&(this.shipCombatRoom != null) &&(this.shipCombatRoom.isHere(P.first)) &&(P.first instanceof GenSailingShip) &&(((GenSailingShip)P.first).targetedShip == this)) { final int distance = (int)Math.round(Math.ceil(Math.sqrt(Math.pow(P.second[0]-fromCoords[0],2.0) + Math.pow(P.second[1]-fromCoords[1],2.0)))); if(distance < lowest) lowest=distance; } } catch(final Exception e) { } } } if(lowest == Integer.MAX_VALUE) return CMLib.map().roomLocation(this).maxRange(); return lowest; } protected int getDirectionFacing(final int direction) { final Room thisRoom=CMLib.map().roomLocation(this); if(directionFacing < 0) { if(thisRoom != null) { for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { final Room R2=thisRoom.getRoomInDir(d); if((R2!=null) &&(thisRoom.getExitInDir(d)!=null) &&(thisRoom.getExitInDir(d).isOpen()) &&(!CMLib.flags().isWateryRoom(R2))) { return Directions.getOpDirectionCode(d); } } } return direction; } return directionFacing; } @Override public void setDirectionFacing(final int direction) { this.directionFacing=direction; } protected SailResult sail(final int direction) { final Room thisRoom=CMLib.map().roomLocation(this); if(thisRoom != null) { directionFacing = getDirectionFacing(direction); int[] tacticalCoords = null; if(amInTacticalMode()) { int x=0; try { while((x>=0)&&(this.coordinates!=null)&&(tacticalCoords==null)) { x=this.coordinates.indexOfFirst(this); final Pair<Item,int[]> pair = (x>=0) ? this.coordinates.get(x) : null; if(pair == null) break; else if(pair.first != this) x=this.coordinates.indexOfFirst(this); else tacticalCoords = pair.second; } } catch(final Exception e) { } } if(tacticalCoords != null) { final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),thisRoom); try { mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); if(directionFacing == direction) { final String directionName = CMLib.directions().getDirectionName(direction); final int[] newCoords = Directions.adjustXYByDirections(tacticalCoords[0], tacticalCoords[1], direction); final CMMsg maneuverMsg=CMClass.getMsg(mob, thisRoom, null, CMMsg.MSG_ADVANCE,newCoords[0]+","+newCoords[1], CMMsg.MSG_ADVANCE,directionName, CMMsg.MSG_ADVANCE,L("<S-NAME> maneuver(s) @x1.",directionName)); if(thisRoom.okMessage(mob, maneuverMsg)) { thisRoom.send(mob, maneuverMsg); final int oldDistance = this.getLowestTacticalDistanceFromThis(); tacticalCoords[0] = newCoords[0]; tacticalCoords[1] = newCoords[1]; final int newDistance = this.getLowestTacticalDistanceFromThis(); ticksSinceMove=0; if((newDistance <= oldDistance)||(newDistance < thisRoom.maxRange())) return SailResult.CONTINUE; } else return SailResult.REPEAT; // else we get to make a real Sailing move! } else { final int gradualDirection=Directions.getGradualDirectionCode(directionFacing, direction); final String directionName = CMLib.directions().getDirectionName(gradualDirection); final String finalDirectionName = CMLib.directions().getDirectionName(direction); final CMMsg maneuverMsg=CMClass.getMsg(mob, thisRoom, null, CMMsg.MSG_ADVANCE,directionName, CMMsg.MSG_ADVANCE,finalDirectionName, CMMsg.MSG_ADVANCE,L("<S-NAME> change(s) course, turning @x1.",directionName)); if(thisRoom.okMessage(mob, maneuverMsg)) { thisRoom.send(mob, maneuverMsg); directionFacing = CMLib.directions().getStrictDirectionCode(maneuverMsg.sourceMessage()); } if(direction != directionFacing) return SailResult.REPEAT; else return SailResult.CONTINUE; } } finally { mob.destroy(); } } else { directionFacing = direction; } this.clearTacticalMode(); final Room destRoom=thisRoom.getRoomInDir(direction); final Exit exit=thisRoom.getExitInDir(direction); if((destRoom!=null)&&(exit!=null)) { if((!CMLib.flags().isDeepWaterySurfaceRoom(destRoom)) &&(destRoom.domainType()!=Room.DOMAIN_OUTDOORS_SEAPORT)) { announceToShip(L("As there is no where to sail @x1, <S-NAME> meanders along the waves.",CMLib.directions().getInDirectionName(direction))); courseDirections.clear(); return SailResult.CANCEL; } final int oppositeDirectionFacing=thisRoom.getReverseDir(direction); final String directionName=CMLib.directions().getDirectionName(direction); final String otherDirectionName=CMLib.directions().getDirectionName(oppositeDirectionFacing); final Exit opExit=destRoom.getExitInDir(oppositeDirectionFacing); final MOB mob = CMClass.getFactoryMOB(name(),phyStats().level(),CMLib.map().roomLocation(this)); mob.setRiding(this); if(getOwnerObject() instanceof Clan) mob.setClan(getOwnerObject().name(), ((Clan)getOwnerObject()).getAutoPosition()); mob.basePhyStats().setDisposition(mob.basePhyStats().disposition()|PhyStats.IS_SWIMMING); mob.phyStats().setDisposition(mob.phyStats().disposition()|PhyStats.IS_SWIMMING); try { final boolean isSneaking = CMLib.flags().isSneaking(this); final String sailEnterStr = isSneaking ? null : L("<S-NAME> sail(s) in from @x1.",otherDirectionName); final String sailAwayStr = isSneaking ? null : L("<S-NAME> sail(s) @x1.",directionName); final CMMsg enterMsg=CMClass.getMsg(mob,destRoom,exit,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,null,CMMsg.MSG_ENTER,sailEnterStr); final CMMsg leaveMsg=CMClass.getMsg(mob,thisRoom,opExit,CMMsg.MSG_LEAVE,null,CMMsg.MSG_LEAVE,null,CMMsg.MSG_LEAVE,sailAwayStr); if((exit.okMessage(mob,enterMsg)) &&(leaveMsg.target().okMessage(mob,leaveMsg)) &&((opExit==null)||(opExit.okMessage(mob,leaveMsg))) &&(enterMsg.target().okMessage(mob,enterMsg))) { exit.executeMsg(mob,enterMsg); thisRoom.sendOthers(mob, leaveMsg); this.unDock(false); ((Room)enterMsg.target()).moveItemTo(this); ticksSinceMove=0; this.dockHere(((Room)enterMsg.target())); //this.sendAreaMessage(leaveMsg, true); if(opExit!=null) opExit.executeMsg(mob,leaveMsg); ((Room)enterMsg.target()).send(mob, enterMsg); haveEveryoneLookOverBow(); return SailResult.CONTINUE; } else { announceToShip(L("<S-NAME> can not seem to travel @x1.",CMLib.directions().getInDirectionName(direction))); courseDirections.clear(); return SailResult.CANCEL; } } finally { mob.destroy(); } } else { announceToShip(L("As there is no where to sail @x1, <S-NAME> meanders along the waves.",CMLib.directions().getInDirectionName(direction))); courseDirections.clear(); return SailResult.CANCEL; } } return SailResult.CANCEL; } protected void haveEveryoneLookOverBow() { if((area != null)&&(owner() instanceof Room)) { final Room targetR=(Room)owner(); for(final Enumeration<Room> r=area.getProperMap(); r.hasMoreElements(); ) { final Room R=r.nextElement(); if((R!=null) &&((R.domainType()&Room.INDOORS)==0)) { final Set<MOB> mobs=CMLib.players().getPlayersHere(R); if(mobs.size()>0) { for(final MOB mob : new XTreeSet<MOB>(mobs)) { if(mob == null) continue; final CMMsg lookMsg=CMClass.getMsg(mob,targetR,null,CMMsg.MSG_LOOK,null); final CMMsg lookExitMsg=CMClass.getMsg(mob,targetR,null,CMMsg.MSG_LOOK_EXITS,null); if((mob.isAttributeSet(MOB.Attrib.AUTOEXITS)) &&(CMProps.getIntVar(CMProps.Int.EXVIEW)!=CMProps.Int.EXVIEW_PARAGRAPH) &&(CMLib.flags().canBeSeenBy(targetR,mob))) { if((CMProps.getIntVar(CMProps.Int.EXVIEW)>=CMProps.Int.EXVIEW_MIXED)!=mob.isAttributeSet(MOB.Attrib.BRIEF)) lookExitMsg.setValue(CMMsg.MASK_OPTIMIZE); lookMsg.addTrailerMsg(lookExitMsg); } if(targetR.okMessage(mob,lookMsg)) targetR.send(mob,lookMsg); } } } } } } protected boolean steer(final MOB mob, final Room R, final int dir) { directionFacing = dir; final String outerStr; final String innerStr = L("@x1 change(s) course, steering @x2.",name(mob),CMLib.directions().getDirectionName(dir)); if(CMLib.flags().isSneaking(this)) outerStr=null; else outerStr=innerStr; final CMMsg msg=CMClass.getMsg(mob, null,null,CMMsg.MSG_NOISYMOVEMENT,innerStr,outerStr,outerStr); final CMMsg msg2=CMClass.getMsg(mob, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> change(s) course, steering @x1 @x2.",name(mob),CMLib.directions().getDirectionName(dir))); if((R.okMessage(mob, msg) && this.okAreaMessage(msg2, true))) { R.sendOthers(mob, msg); this.sendAreaMessage(msg2, true); this.courseDirection=dir | COURSE_STEER_MASK; return true; } return false; } protected boolean beginSail(final MOB mob, final Room R, final int dir) { directionFacing = dir; final String outerStr; final String innerStr = L("<S-NAME> sail(s) @x1 @x2.",name(mob),CMLib.directions().getDirectionName(dir)); if(CMLib.flags().isSneaking(this)) outerStr=null; else outerStr=innerStr; final CMMsg msg2=CMClass.getMsg(mob, R, R.getExitInDir(dir), CMMsg.MSG_NOISYMOVEMENT, innerStr, outerStr,outerStr); if((R.okMessage(mob, msg2) && this.okAreaMessage(msg2, true))) { R.send(mob, msg2); // this lets the source know, i guess //this.sendAreaMessage(msg2, true); // this just sends to "others" this.courseDirection=dir; return true; } return false; } protected int getAnyExitDir(final Room R) { if(R==null) return -1; for(int d=0;d<Directions.NUM_DIRECTIONS();d++) { final Room R2=R.getRoomInDir(d); final Exit E2=R.getExitInDir(d); if((R2!=null)&&(E2!=null)&&(CMLib.map().getExtendedRoomID(R2).length()>0)) return d; } return -1; } protected Room findOceanRoom(final Area A) { if(A==null) return null; for(final Enumeration<Room> r=A.getProperMap();r.hasMoreElements();) { final Room R=r.nextElement(); if((R!=null)&& CMLib.flags().isDeepWaterySurfaceRoom(R) &&(CMLib.map().getExtendedRoomID(R).length()>0)) return R; } return null; } protected boolean safetyMove() { final Room R=CMLib.map().roomLocation(this); if((R==null) || R.amDestroyed() || ((!CMLib.flags().isFalling(this)) && (R.domainType()!=Room.DOMAIN_INDOORS_UNDERWATER) && (R.domainType()!=Room.DOMAIN_OUTDOORS_UNDERWATER) && (getAnyExitDir(R)<0))) { Room R2=CMLib.map().getRoom(getHomePortID()); if((R2==null)&&(R!=null)&&(R.getArea()!=null)) R2=findOceanRoom(R.getArea()); if(R2==null) { for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) { R2=findOceanRoom(a.nextElement()); if(R2!=null) break; } } if(R2==null) return false; ticksSinceMove=0; this.unDock(false); R2.moveItemTo(this); this.dockHere(R2); return true; } return false; } @Override public boolean isInCombat() { return (targetedShip != null) && (shipCombatRoom != null); } @Override public void setRangeToTarget(final int newRange) { //nothing to do atm } @Override public int rangeToTarget() { return getTacticalDistance(this.targetedShip); } @Override public boolean mayPhysicallyAttack(final PhysicalAgent victim) { if(!mayIFight(victim)) return false; return CMLib.map().roomLocation(this) == CMLib.map().roomLocation(victim); } protected static boolean ownerSecurityCheck(final String ownerName, final MOB mob) { return (ownerName.length()>0) &&(mob!=null) &&((mob.Name().equals(ownerName)) ||(mob.getLiegeID().equals(ownerName)&mob.isMarriedToLiege()) ||(CMLib.clans().checkClanPrivilege(mob, ownerName, Clan.Function.PROPERTY_OWNER))); } @Override public boolean mayIFight(final PhysicalAgent victim) { final Area myArea=this.getShipArea(); final PhysicalAgent defender=victim; MOB mob = null; if(myArea != null) { final LegalLibrary law=CMLib.law(); int legalLevel=0; for(final Enumeration<Room> r=myArea.getProperMap();r.hasMoreElements() && (legalLevel<2);) { final Room R=r.nextElement(); if((R!=null)&&(R.numInhabitants()>0)) { for(final Enumeration<MOB> i=R.inhabitants();i.hasMoreElements();) { final MOB M=i.nextElement(); if(M != null) { if(mob == null) mob = M; if((legalLevel==0)&&(mob.isMonster())&&(law.doesHaveWeakPriviledgesHere(M, R))) { mob=M; legalLevel=1; } if(M.isPlayer()) { if(!mob.isPlayer()) { mob=M; legalLevel=0; } if((legalLevel<2) && (law.doesHavePriviledgesHere(M, R))) { legalLevel=2; mob=M; } if((legalLevel<1) && (law.doesHaveWeakPriviledgesHere(M, R))) { legalLevel=1; mob=M; } } } } } } } if(mob==null) return false; return CMLib.combat().mayIAttackThisVessel(mob, defender); } @Override public void makePeace(final boolean includePlayerFollowers) { clearTacticalMode(); } @Override public PhysicalAgent getCombatant() { return this.targetedShip; } @Override public void setCombatant(final PhysicalAgent other) { final Room R=(owner() instanceof Room)?(Room)owner():CMLib.map().roomLocation(this); if(other == null) clearTacticalMode(); else if(CMLib.flags().isDeepWaterySurfaceRoom(R)) { targetedShip = other; if(R != null) shipCombatRoom = R; if(other instanceof Combatant) { if(((Combatant)other).getCombatant()==null) ((Combatant)other).setCombatant(this); if(other instanceof GenSailingShip) ((GenSailingShip)other).amInTacticalMode(); // now he is in combat } amInTacticalMode(); // now he is in combat } } @Override public int getDirectionToTarget() { return this.getDirectionToTarget(this.targetedShip); } @Override public int getDirectionFacing() { return this.directionFacing; } @Override public boolean isAnchorDown() { return this.anchorDown; } @Override public void setAnchorDown(final boolean truefalse) { this.anchorDown = truefalse; } @Override public PairList<Weapon,int[]> getSiegeWeaponAimings() { return this.aimings; } protected int getTopCourse() { try { if(this.courseDirections.size()>0) return this.courseDirections.get(0).intValue(); } catch(final Exception e) { } return -1; } protected int removeTopCourse() { try { if(this.courseDirections.size()>0) return this.courseDirections.remove(0).intValue(); } catch(final Exception e) { } return -1; } protected int getBottomCourse() { try { final int size=this.courseDirections.size(); if(size>0) return this.courseDirections.get(size-1).intValue(); } catch(final Exception e) { } return -1; } @Override public List<Integer> getCurrentCourse() { if(getTopCourse()>=0) { return this.courseDirections; } return new ArrayList<Integer>(0); } @Override public void setCurrentCourse(final List<Integer> course) { this.courseDirection=-1; this.courseDirections.clear(); for(final Integer dirIndex : course) { final int dir=dirIndex.intValue(); if(dir>=0) { if(courseDirection < 0) { courseDirection = dir; directionFacing = dir; } else this.courseDirections.add(Integer.valueOf(dir)); } } this.courseDirections.add(Integer.valueOf(-1)); } private final static String[] MYCODES={"HASLOCK","HASLID","CAPACITY","CONTAINTYPES", "RESETTIME","RIDEBASIS","MOBSHELD", "AREA","OWNER","PRICE","DEFCLOSED","DEFLOCKED", "EXITNAME", "PUTSTR","MOUNTSTR","DISMOUNTSTR","STATESTR","STATESUBJSTR","RIDERSTR" }; @Override public String getStat(final String code) { if(CMLib.coffeeMaker().getGenItemCodeNum(code)>=0) return CMLib.coffeeMaker().getGenItemStat(this,code); switch(getCodeNum(code)) { case 0: return "" + hasALock(); case 1: return "" + hasADoor(); case 2: return "" + capacity(); case 3: return "" + containTypes(); case 4: return "" + openDelayTicks(); case 5: return "" + rideBasis(); case 6: return "" + riderCapacity(); case 7: return CMLib.coffeeMaker().getAreaObjectXML(getShipArea(), null, null, null, true).toString(); case 8: return getOwnerName(); case 9: return "" + getPrice(); case 10: return "" + defaultsClosed(); case 11: return "" + defaultsLocked(); case 12: return "" + doorName(); case 13: return this.getPutString(); case 14: return this.getMountString(); case 15: return this.getDismountString(); case 16: return this.getStateString(); case 17: return this.getStateStringSubject(); case 18: return this.getRideString(); default: return CMProps.getStatCodeExtensionValue(getStatCodes(), xtraValues, code); } } @Override public void setStat(final String code, final String val) { if(CMLib.coffeeMaker().getGenItemCodeNum(code)>=0) CMLib.coffeeMaker().setGenItemStat(this,code,val); else switch(getCodeNum(code)) { case 0: setDoorsNLocks(hasADoor(), isOpen(), defaultsClosed(), CMath.s_bool(val), false, CMath.s_bool(val) && defaultsLocked()); break; case 1: setDoorsNLocks(CMath.s_bool(val), isOpen(), CMath.s_bool(val) && defaultsClosed(), hasALock(), isLocked(), defaultsLocked()); break; case 2: setCapacity(CMath.s_parseIntExpression(val)); break; case 3: setContainTypes(CMath.s_parseBitLongExpression(Container.CONTAIN_DESCS, val)); break; case 4: setOpenDelayTicks(CMath.s_parseIntExpression(val)); break; case 5: break; case 6: break; case 7: setShipArea(val); break; case 8: setOwnerName(val); break; case 9: setPrice(CMath.s_int(val)); break; case 10: setDoorsNLocks(hasADoor(), isOpen(), CMath.s_bool(val), hasALock(), isLocked(), defaultsLocked()); break; case 11: setDoorsNLocks(hasADoor(), isOpen(), defaultsClosed(), hasALock(), isLocked(), CMath.s_bool(val)); break; case 12: this.doorName = val; break; case 13: setPutString(val); break; case 14: setMountString(val); break; case 15: setDismountString(val); break; case 16: setStateString(val); break; case 17: setStateStringSubject(val); break; case 18: setRideString(val); break; default: CMProps.setStatCodeExtensionValue(getStatCodes(), xtraValues, code, val); break; } } @Override protected int getCodeNum(final String code) { for(int i=0;i<MYCODES.length;i++) { if(code.equalsIgnoreCase(MYCODES[i])) return i; } return -1; } private static String[] codes=null; @Override public String[] getStatCodes() { if(codes!=null) return codes; final String[] MYCODES=CMProps.getStatCodesList(GenSailingShip.MYCODES,this); final String[] superCodes=CMParms.toStringArray(GenericBuilder.GenItemCode.values()); codes=new String[superCodes.length+MYCODES.length]; int i=0; for(;i<superCodes.length;i++) codes[i]=superCodes[i]; for(int x=0;x<MYCODES.length;i++,x++) codes[i]=MYCODES[x]; return codes; } @Override public boolean sameAs(final Environmental E) { if(!(E instanceof GenSailingShip)) return false; final String[] codes=getStatCodes(); for(int i=0;i<codes.length;i++) { if((!E.getStat(codes[i]).equals(getStat(codes[i]))) &&(!codes[i].equals("AREA")) &&(!codes[i].equals("ABILITY"))) return false; } final Area eA = ((GenSailingShip)E).getShipArea(); final Area A = this.getShipArea(); final Enumeration<Room> er = eA.getProperMap(); final Enumeration<Room> r = A.getProperMap(); for(;r.hasMoreElements();) { final Room R=r.nextElement(); if(!er.hasMoreElements()) return false; final Room eR = er.nextElement(); if(!R.sameAs(eR)) return false; final Enumeration<Item> i=R.items(); final Enumeration<Item> ei = eR.items(); for(;i.hasMoreElements();) { final Item I=i.nextElement(); if(!ei.hasMoreElements()) return false; final Item eI=ei.nextElement(); if(!I.sameAs(eI)) return false; } if(ei.hasMoreElements()) return false; final Enumeration<MOB> m=R.inhabitants(); final Enumeration<MOB> em = eR.inhabitants(); for(;m.hasMoreElements();) { final MOB M=m.nextElement(); if(!em.hasMoreElements()) return false; final MOB eM=em.nextElement(); if(!M.sameAs(eM)) return false; } if(em.hasMoreElements()) return false; } if(er.hasMoreElements()) return false; return true; } }
jump overboard git-svn-id: 0cdf8356e41b2d8ccbb41bb76c82068fe80b2514@19015 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/Items/Basic/GenSailingShip.java
jump overboard
<ide><path>om/planet_ink/coffee_mud/Items/Basic/GenSailingShip.java <ide> SINK, <ide> TENDER, <ide> RAISE, <del> LOWER <add> LOWER, <add> JUMP <ide> ; <ide> } <ide> <ide> final CMMsg damageMsg=CMClass.getMsg(msg.source(), this, CMMsg.MSG_DAMAGE, "SINK!!!"); <ide> damageMsg.setValue(99999); <ide> this.executeMsg(this, damageMsg); <add> return false; <add> } <add> case JUMP: <add> { <add> final Room thisRoom = (Room)owner(); <add> if(thisRoom==null) <add> { <add> msg.source().tell(L("This ship is nowhere to be found!")); <add> return false; <add> } <add> final MOB mob=msg.source(); <add> final Room mobR = mob.location(); <add> if(mobR != null) <add> { <add> if(cmds.size()<2) <add> mobR.show(mob, null, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> jump(s) in place.")); <add> else <add> { <add> final String str=CMParms.combine(cmds,1).toLowerCase(); <add> if(("overboard").startsWith(str) || ("water").startsWith(str)) <add> { <add> if(((mobR.domainType()&Room.INDOORS)==0) <add> && (mobR.domainType()!=Room.DOMAIN_OUTDOORS_AIR)) <add> msg.source().tell(L("You must be on deck to jump overboard.")); <add> else <add> if(mobR.show(mob, null, CMMsg.MSG_NOISYMOVEMENT, L("<S-NAME> jump(s) overboard."))) <add> CMLib.tracking().walkForced(mob, mobR, thisRoom, true, true, L("<S-NAME> arrive(s) from @x1.",name())); <add> } <add> else <add> msg.source().tell(L("Jump where? Try JUMP OVERBOARD.")); <add> } <add> return false; <add> } <ide> return false; <ide> } <ide> case AIM: <ide> { <ide> final Room target=R; <ide> final CMMsg msg2=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<S-NAME> throw(s) <O-NAME> overboard.")); <del> final CMMsg msg3=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<O-NAME> fl(ys) in from overboard.")); <add> final CMMsg msg3=CMClass.getMsg(mob,target,item,CMMsg.MSG_THROW,L("<O-NAME> fl(ys) in from @x1.",name())); <ide> if(mob.location().okMessage(mob,msg2)&&target.okMessage(mob,msg3)) <ide> { <ide> mob.location().send(mob,msg2);
Java
mit
9cb7c0d75772f766cd9bc164548b2661b4668057
0
BakkerTom/happy-news,BakkerTom/happy-news,BakkerTom/happy-news,BakkerTom/happy-news
package nl.fhict.happynews.api; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry .addMapping("/**"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
api/src/main/java/nl/fhict/happynews/api/WebMvcConfig.java
package nl.fhict.happynews.api; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry .addMapping("/**"); } }
Re-add swagger UI
api/src/main/java/nl/fhict/happynews/api/WebMvcConfig.java
Re-add swagger UI
<ide><path>pi/src/main/java/nl/fhict/happynews/api/WebMvcConfig.java <ide> import org.springframework.context.annotation.Configuration; <ide> import org.springframework.web.servlet.config.annotation.CorsRegistry; <ide> import org.springframework.web.servlet.config.annotation.EnableWebMvc; <add>import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; <ide> import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; <ide> <ide> @Configuration <ide> registry <ide> .addMapping("/**"); <ide> } <add> <add> @Override <add> public void addResourceHandlers(ResourceHandlerRegistry registry) { <add> <add> registry.addResourceHandler("swagger-ui.html") <add> .addResourceLocations("classpath:/META-INF/resources/"); <add> <add> registry.addResourceHandler("/webjars/**") <add> .addResourceLocations("classpath:/META-INF/resources/webjars/"); <add> <add> } <ide> }
Java
apache-2.0
bc7933c92a4caaa556bfe66b6719131e9616e709
0
yingyun001/ovirt-engine,walteryang47/ovirt-engine,eayun/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,yapengsong/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,yapengsong/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,yingyun001/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,halober/ovirt-engine,walteryang47/ovirt-engine,halober/ovirt-engine,halober/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine
package org.ovirt.engine.core.bll.gluster; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Callable; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VDSStatus; import org.ovirt.engine.core.common.businessentities.gluster.GlusterClusterService; import org.ovirt.engine.core.common.businessentities.gluster.GlusterServerService; import org.ovirt.engine.core.common.businessentities.gluster.GlusterService; import org.ovirt.engine.core.common.businessentities.gluster.GlusterServiceStatus; import org.ovirt.engine.core.common.businessentities.gluster.ServiceType; import org.ovirt.engine.core.common.constants.gluster.GlusterConstants; import org.ovirt.engine.core.common.gluster.GlusterFeatureSupported; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.common.vdscommands.gluster.GlusterServicesListVDSParameters; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.TransactionScopeOption; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil; import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; public class GlusterServiceSyncJob extends GlusterJob { private static final Log log = LogFactory.getLog(GlusterServiceSyncJob.class); private static final GlusterServiceSyncJob instance = new GlusterServiceSyncJob(); private final Map<String, GlusterService> serviceNameMap = new HashMap<String, GlusterService>(); private GlusterServiceSyncJob() { } public static GlusterServiceSyncJob getInstance() { return instance; } @OnTimerMethodAnnotation("refreshGlusterServices") public void refreshGlusterServices() { if (getServiceNameMap().isEmpty()) { // Lazy loading. Keeping this out of the constructor/getInstance // helps in writing the JUnit test as well. populateServiceMap(); } List<VDSGroup> clusters = getClusterDao().getAll(); for (VDSGroup cluster : clusters) { if (supportsGlusterServicesFeature(cluster)) { try { List<VDS> serversList = getClusterUtils().getAllServers(cluster.getId()); // If there are no servers in the cluster, set the status as unknown if (serversList.isEmpty()) { Map<ServiceType, GlusterServiceStatus> statusMap = new HashMap<>(); for (ServiceType type : getClusterServiceMap(cluster).keySet()) { statusMap.put(type, GlusterServiceStatus.UNKNOWN); } addOrUpdateClusterServices(cluster, statusMap); } else { List<Callable<Map<String, GlusterServiceStatus>>> taskList = createTaskList(serversList); if (taskList != null && taskList.size() > 0) { refreshClusterServices(cluster, ThreadPoolUtil.invokeAll(taskList)); } } } catch (Exception e) { log.errorFormat("Error while refreshing service statuses of cluster {0}!", cluster.getName(), e); } } } } private Map<String, GlusterServiceStatus> updateGlusterServicesStatusForStoppedServer(VDS server) { Map<String, GlusterServiceStatus> retMap = new HashMap<String, GlusterServiceStatus>(); List<GlusterServerService> serviceList = getGlusterServerServiceDao().getByServerId(server.getId()); for (GlusterServerService service : serviceList) { retMap.put(service.getServiceName(), GlusterServiceStatus.UNKNOWN); service.setStatus(GlusterServiceStatus.UNKNOWN); getGlusterServerServiceDao().update(service); } return retMap; } private List<Callable<Map<String, GlusterServiceStatus>>> createTaskList(List<VDS> serversList) { List<Callable<Map<String, GlusterServiceStatus>>> taskList = new ArrayList<Callable<Map<String, GlusterServiceStatus>>>(); for (final VDS server : serversList) { taskList.add(new Callable<Map<String, GlusterServiceStatus>>() { /** * Fetches and updates status of all services of the given server, <br> * and returns a map having key = service name and value = service status */ @Override public Map<String, GlusterServiceStatus> call() throws Exception { return refreshServerServices(server); } }); } return taskList; } /** * Analyses statuses of services from all servers of the cluster, and updates the status of the cluster level * service type accordingly. * * @param cluster * Cluster being processed * @param serviceStatusMaps * List of service name to status maps from each (UP) server of the cluster */ private void refreshClusterServices(VDSGroup cluster, List<Map<String, GlusterServiceStatus>> serviceStatusMaps) { Map<ServiceType, GlusterServiceStatus> fetchedClusterServiceStatusMap = createServiceTypeStatusMap(serviceStatusMaps); addOrUpdateClusterServices(cluster, fetchedClusterServiceStatusMap); } private void addOrUpdateClusterServices(VDSGroup cluster, Map<ServiceType, GlusterServiceStatus> fetchedClusterServiceStatusMap) { Map<ServiceType, GlusterClusterService> existingClusterServiceMap = getClusterServiceMap(cluster); for (Entry<ServiceType, GlusterServiceStatus> entry : fetchedClusterServiceStatusMap.entrySet()) { ServiceType type = entry.getKey(); GlusterServiceStatus status = entry.getValue(); GlusterClusterService existingClusterService = existingClusterServiceMap.get(type); if (existingClusterService == null) { existingClusterServiceMap.put(type, addClusterServiceToDb(cluster, type, status)); } else if (existingClusterService.getStatus() != status) { updateClusterServiceStatus(existingClusterService, status); } } } private Map<ServiceType, GlusterServiceStatus> createServiceTypeStatusMap(List<Map<String, GlusterServiceStatus>> serviceStatusMaps) { Map<ServiceType, GlusterServiceStatus> fetchedServiceTypeStatusMap = new HashMap<ServiceType, GlusterServiceStatus>(); for (Entry<String, GlusterServiceStatus> entry : mergeServiceStatusMaps(serviceStatusMaps).entrySet()) { String serviceName = entry.getKey(); GlusterServiceStatus status = entry.getValue(); ServiceType type = getServiceNameMap().get(serviceName).getServiceType(); GlusterServiceStatus foundStatus = fetchedServiceTypeStatusMap.get(type); if (foundStatus == null) { fetchedServiceTypeStatusMap.put(type, status); } else if (foundStatus != status) { GlusterServiceStatus finalStatus = getFinalStatus(status, foundStatus); fetchedServiceTypeStatusMap.put(type, finalStatus); } } return fetchedServiceTypeStatusMap; } private GlusterServiceStatus getFinalStatus(GlusterServiceStatus firstStatus, GlusterServiceStatus secondStatus) { return firstStatus.getCompositeStatus(secondStatus); } private Map<String, GlusterServiceStatus> mergeServiceStatusMaps(List<Map<String, GlusterServiceStatus>> serviceStatusMaps) { Map<String, GlusterServiceStatus> mergedServiceStatusMap = new HashMap<String, GlusterServiceStatus>(); for (Map<String, GlusterServiceStatus> serviceStatusMap : serviceStatusMaps) { for (Entry<String, GlusterServiceStatus> entry : serviceStatusMap.entrySet()) { String serviceName = entry.getKey(); GlusterServiceStatus status = entry.getValue(); GlusterServiceStatus alreadyFoundStatus = mergedServiceStatusMap.get(serviceName); if (alreadyFoundStatus == null) { mergedServiceStatusMap.put(serviceName, status); } else if (alreadyFoundStatus != status && alreadyFoundStatus != GlusterServiceStatus.MIXED) { GlusterServiceStatus finalStatus = getFinalStatus(status, alreadyFoundStatus); mergedServiceStatusMap.put(serviceName, finalStatus); } } } return mergedServiceStatusMap; } private Map<ServiceType, GlusterClusterService> getClusterServiceMap(VDSGroup cluster) { List<GlusterClusterService> clusterServices = getGlusterClusterServiceDao().getByClusterId(cluster.getId()); if (clusterServices == null) { clusterServices = new ArrayList<GlusterClusterService>(); } Map<ServiceType, GlusterClusterService> clusterServiceMap = new HashMap<ServiceType, GlusterClusterService>(); for (GlusterClusterService clusterService : clusterServices) { clusterServiceMap.put(clusterService.getServiceType(), clusterService); } return clusterServiceMap; } /** * Refreshes statuses of services on given server, and returns a map of service name to it's status * * @param server * The server whose services statuses are to be refreshed * @return map of service name to it's status */ @SuppressWarnings({ "unchecked", "serial" }) private Map<String, GlusterServiceStatus> refreshServerServices(final VDS server) { Map<String, GlusterServiceStatus> serviceStatusMap = new HashMap<String, GlusterServiceStatus>(); if (server.getStatus() != VDSStatus.Up) { // Update the status of all the services of stopped server in single transaction TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Map<String, GlusterServiceStatus>>() { @Override public Map<String, GlusterServiceStatus> runInTransaction() { return updateGlusterServicesStatusForStoppedServer(server); } }); } else { acquireLock(server.getId()); try { Map<Guid, GlusterServerService> existingServicesMap = getExistingServicesMap(server); List<GlusterServerService> servicesToUpdate = new ArrayList<GlusterServerService>(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GlusterServicesList, new GlusterServicesListVDSParameters(server.getId(), getServiceNameMap().keySet())); if (!returnValue.getSucceeded()) { log.errorFormat("Couldn't fetch services statuses from server {0}, error: {1}! " + "Updating statuses of all services on this server to UNKNOWN.", server.getHostName(), returnValue.getVdsError().getMessage()); logUtil.logServerMessage(server, AuditLogType.GLUSTER_SERVICES_LIST_FAILED); return updateStatusToUnknown(existingServicesMap.values()); } for (final GlusterServerService fetchedService : (List<GlusterServerService>) returnValue.getReturnValue()) { serviceStatusMap.put(fetchedService.getServiceName(), fetchedService.getStatus()); GlusterServerService existingService = existingServicesMap.get(fetchedService.getServiceId()); if (existingService == null) { insertServerService(server, fetchedService); } else { final GlusterServiceStatus oldStatus = existingService.getStatus(); final GlusterServiceStatus newStatus = fetchedService.getStatus(); if (oldStatus != newStatus) { log.infoFormat("Status of service {0} on server {1} changed from {2} to {3}. Updating in engine now.", fetchedService.getServiceName(), server.getHostName(), oldStatus.name(), newStatus.name()); logUtil.logAuditMessage(server.getVdsGroupId(), null, server, AuditLogType.GLUSTER_SERVER_SERVICE_STATUS_CHANGED, new HashMap<String, String>() { { put(GlusterConstants.SERVICE_NAME, fetchedService.getServiceName()); put(GlusterConstants.OLD_STATUS, oldStatus.getStatusMsg()); put(GlusterConstants.NEW_STATUS, newStatus.getStatusMsg()); } }); existingService.setStatus(fetchedService.getStatus()); servicesToUpdate.add(existingService); } } } if (servicesToUpdate.size() > 0) { getGlusterServerServiceDao().updateAll(servicesToUpdate); } } finally { releaseLock(server.getId()); } } return serviceStatusMap; } private Map<String, GlusterServiceStatus> updateStatusToUnknown(Collection<GlusterServerService> existingServices) { Map<String, GlusterServiceStatus> serviceStatusMap = new HashMap<String, GlusterServiceStatus>(); for (GlusterServerService existingService : existingServices) { existingService.setStatus(GlusterServiceStatus.UNKNOWN); serviceStatusMap.put(existingService.getServiceName(), existingService.getStatus()); } getGlusterServerServiceDao().updateAll(existingServices); return serviceStatusMap; } private Map<Guid, GlusterServerService> getExistingServicesMap(VDS server) { List<GlusterServerService> existingServices = getGlusterServerServiceDao().getByServerId(server.getId()); Map<Guid, GlusterServerService> existingServicesMap = new HashMap<Guid, GlusterServerService>(); if (existingServices != null) { for (GlusterServerService service : existingServices) { existingServicesMap.put(service.getServiceId(), service); } } return existingServicesMap; } @SuppressWarnings("serial") private void insertServerService(VDS server, final GlusterServerService fetchedService) { fetchedService.setId(Guid.newGuid()); getGlusterServerServiceDao().save(fetchedService); log.infoFormat("Service {0} was not mapped to server {1}. Mapped it now.", fetchedService.getServiceName(), server.getHostName()); logUtil.logAuditMessage(server.getVdsGroupId(), null, server, AuditLogType.GLUSTER_SERVICE_ADDED_TO_SERVER, new HashMap<String, String>() { { put(GlusterConstants.SERVICE_NAME, fetchedService.getServiceName()); } }); } @SuppressWarnings("serial") private void updateClusterServiceStatus(final GlusterClusterService clusterService, final GlusterServiceStatus newStatus) { final GlusterServiceStatus oldStatus = clusterService.getStatus(); clusterService.setStatus(newStatus); getGlusterClusterServiceDao().update(clusterService); log.infoFormat("Status of service type {0} changed on cluster {1} from {2} to {3}.", clusterService.getServiceType().name(), clusterService.getClusterId(), oldStatus, newStatus); logUtil.logAuditMessage(clusterService.getClusterId(), null, null, AuditLogType.GLUSTER_CLUSTER_SERVICE_STATUS_CHANGED, new HashMap<String, String>() { { put(GlusterConstants.SERVICE_TYPE, clusterService.getServiceType().name()); put(GlusterConstants.OLD_STATUS, oldStatus.getStatusMsg()); put(GlusterConstants.NEW_STATUS, newStatus.getStatusMsg()); } }); } @SuppressWarnings("serial") private GlusterClusterService addClusterServiceToDb(VDSGroup cluster, final ServiceType serviceType, final GlusterServiceStatus status) { GlusterClusterService clusterService = new GlusterClusterService(); clusterService.setClusterId(cluster.getId()); clusterService.setServiceType(serviceType); clusterService.setStatus(status); getGlusterClusterServiceDao().save(clusterService); log.infoFormat("Service type {0} not mapped to cluster {1}. Mapped it now.", serviceType, cluster.getName()); logUtil.logAuditMessage(clusterService.getClusterId(), null, null, AuditLogType.GLUSTER_CLUSTER_SERVICE_STATUS_ADDED, new HashMap<String, String>() { { put(GlusterConstants.SERVICE_TYPE, serviceType.name()); put(GlusterConstants.NEW_STATUS, status.getStatusMsg()); } }); return clusterService; } private boolean supportsGlusterServicesFeature(VDSGroup cluster) { return cluster.supportsGlusterService() && GlusterFeatureSupported.glusterServices(cluster.getcompatibility_version()); } private void populateServiceMap() { List<GlusterService> services = getGlusterServiceDao().getAll(); for (GlusterService service : services) { getServiceNameMap().put(service.getServiceName(), service); } } protected Map<String, GlusterService> getServiceNameMap() { return serviceNameMap; } }
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GlusterServiceSyncJob.java
package org.ovirt.engine.core.bll.gluster; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Callable; import org.ovirt.engine.core.common.AuditLogType; import org.ovirt.engine.core.common.businessentities.VDS; import org.ovirt.engine.core.common.businessentities.VDSGroup; import org.ovirt.engine.core.common.businessentities.VDSStatus; import org.ovirt.engine.core.common.businessentities.gluster.GlusterClusterService; import org.ovirt.engine.core.common.businessentities.gluster.GlusterServerService; import org.ovirt.engine.core.common.businessentities.gluster.GlusterService; import org.ovirt.engine.core.common.businessentities.gluster.GlusterServiceStatus; import org.ovirt.engine.core.common.businessentities.gluster.ServiceType; import org.ovirt.engine.core.common.constants.gluster.GlusterConstants; import org.ovirt.engine.core.common.gluster.GlusterFeatureSupported; import org.ovirt.engine.core.common.vdscommands.VDSCommandType; import org.ovirt.engine.core.common.vdscommands.VDSReturnValue; import org.ovirt.engine.core.common.vdscommands.gluster.GlusterServicesListVDSParameters; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.TransactionScopeOption; import org.ovirt.engine.core.utils.log.Log; import org.ovirt.engine.core.utils.log.LogFactory; import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil; import org.ovirt.engine.core.utils.timer.OnTimerMethodAnnotation; import org.ovirt.engine.core.utils.transaction.TransactionMethod; import org.ovirt.engine.core.utils.transaction.TransactionSupport; public class GlusterServiceSyncJob extends GlusterJob { private static final Log log = LogFactory.getLog(GlusterServiceSyncJob.class); private static final GlusterServiceSyncJob instance = new GlusterServiceSyncJob(); private final Map<String, GlusterService> serviceNameMap = new HashMap<String, GlusterService>(); private GlusterServiceSyncJob() { } public static GlusterServiceSyncJob getInstance() { return instance; } @OnTimerMethodAnnotation("refreshGlusterServices") public void refreshGlusterServices() { if (getServiceNameMap().isEmpty()) { // Lazy loading. Keeping this out of the constructor/getInstance // helps in writing the JUnit test as well. populateServiceMap(); } List<VDSGroup> clusters = getClusterDao().getAll(); for (VDSGroup cluster : clusters) { if (supportsGlusterServicesFeature(cluster)) { try { List<VDS> serversList = getClusterUtils().getAllServers(cluster.getId()); List<Callable<Map<String, GlusterServiceStatus>>> taskList = createTaskList(serversList); if (taskList != null && taskList.size() > 0) { refreshClusterServices(cluster, ThreadPoolUtil.invokeAll(taskList)); } } catch (Exception e) { log.errorFormat("Error while refreshing service statuses of cluster {0}!", cluster.getName(), e); } } } } private Map<String, GlusterServiceStatus> updateGlusterServicesStatusForStoppedServer(VDS server) { Map<String, GlusterServiceStatus> retMap = new HashMap<String, GlusterServiceStatus>(); List<GlusterServerService> serviceList = getGlusterServerServiceDao().getByServerId(server.getId()); for (GlusterServerService service : serviceList) { retMap.put(service.getServiceName(), GlusterServiceStatus.UNKNOWN); service.setStatus(GlusterServiceStatus.UNKNOWN); getGlusterServerServiceDao().update(service); } return retMap; } private List<Callable<Map<String, GlusterServiceStatus>>> createTaskList(List<VDS> serversList) { List<Callable<Map<String, GlusterServiceStatus>>> taskList = new ArrayList<Callable<Map<String, GlusterServiceStatus>>>(); for (final VDS server : serversList) { taskList.add(new Callable<Map<String, GlusterServiceStatus>>() { /** * Fetches and updates status of all services of the given server, <br> * and returns a map having key = service name and value = service status */ @Override public Map<String, GlusterServiceStatus> call() throws Exception { return refreshServerServices(server); } }); } return taskList; } /** * Analyses statuses of services from all servers of the cluster, and updates the status of the cluster level * service type accordingly. * * @param cluster * Cluster being processed * @param serviceStatusMaps * List of service name to status maps from each (UP) server of the cluster */ private void refreshClusterServices(VDSGroup cluster, List<Map<String, GlusterServiceStatus>> serviceStatusMaps) { Map<ServiceType, GlusterServiceStatus> fetchedClusterServiceStatusMap = createServiceTypeStatusMap(serviceStatusMaps); addOrUpdateClusterServices(cluster, fetchedClusterServiceStatusMap); } private void addOrUpdateClusterServices(VDSGroup cluster, Map<ServiceType, GlusterServiceStatus> fetchedClusterServiceStatusMap) { Map<ServiceType, GlusterClusterService> existingClusterServiceMap = getClusterServiceMap(cluster); for (Entry<ServiceType, GlusterServiceStatus> entry : fetchedClusterServiceStatusMap.entrySet()) { ServiceType type = entry.getKey(); GlusterServiceStatus status = entry.getValue(); GlusterClusterService existingClusterService = existingClusterServiceMap.get(type); if (existingClusterService == null) { existingClusterServiceMap.put(type, addClusterServiceToDb(cluster, type, status)); } else if (existingClusterService.getStatus() != status) { updateClusterServiceStatus(existingClusterService, status); } } } private Map<ServiceType, GlusterServiceStatus> createServiceTypeStatusMap(List<Map<String, GlusterServiceStatus>> serviceStatusMaps) { Map<ServiceType, GlusterServiceStatus> fetchedServiceTypeStatusMap = new HashMap<ServiceType, GlusterServiceStatus>(); for (Entry<String, GlusterServiceStatus> entry : mergeServiceStatusMaps(serviceStatusMaps).entrySet()) { String serviceName = entry.getKey(); GlusterServiceStatus status = entry.getValue(); ServiceType type = getServiceNameMap().get(serviceName).getServiceType(); GlusterServiceStatus foundStatus = fetchedServiceTypeStatusMap.get(type); if (foundStatus == null) { fetchedServiceTypeStatusMap.put(type, status); } else if (foundStatus != status) { GlusterServiceStatus finalStatus = getFinalStatus(status, foundStatus); fetchedServiceTypeStatusMap.put(type, finalStatus); } } return fetchedServiceTypeStatusMap; } private GlusterServiceStatus getFinalStatus(GlusterServiceStatus firstStatus, GlusterServiceStatus secondStatus) { return firstStatus.getCompositeStatus(secondStatus); } private Map<String, GlusterServiceStatus> mergeServiceStatusMaps(List<Map<String, GlusterServiceStatus>> serviceStatusMaps) { Map<String, GlusterServiceStatus> mergedServiceStatusMap = new HashMap<String, GlusterServiceStatus>(); for (Map<String, GlusterServiceStatus> serviceStatusMap : serviceStatusMaps) { for (Entry<String, GlusterServiceStatus> entry : serviceStatusMap.entrySet()) { String serviceName = entry.getKey(); GlusterServiceStatus status = entry.getValue(); GlusterServiceStatus alreadyFoundStatus = mergedServiceStatusMap.get(serviceName); if (alreadyFoundStatus == null) { mergedServiceStatusMap.put(serviceName, status); } else if (alreadyFoundStatus != status && alreadyFoundStatus != GlusterServiceStatus.MIXED) { GlusterServiceStatus finalStatus = getFinalStatus(status, alreadyFoundStatus); mergedServiceStatusMap.put(serviceName, finalStatus); } } } return mergedServiceStatusMap; } private Map<ServiceType, GlusterClusterService> getClusterServiceMap(VDSGroup cluster) { List<GlusterClusterService> clusterServices = getGlusterClusterServiceDao().getByClusterId(cluster.getId()); if (clusterServices == null) { clusterServices = new ArrayList<GlusterClusterService>(); } Map<ServiceType, GlusterClusterService> clusterServiceMap = new HashMap<ServiceType, GlusterClusterService>(); for (GlusterClusterService clusterService : clusterServices) { clusterServiceMap.put(clusterService.getServiceType(), clusterService); } return clusterServiceMap; } /** * Refreshes statuses of services on given server, and returns a map of service name to it's status * * @param server * The server whose services statuses are to be refreshed * @return map of service name to it's status */ @SuppressWarnings({ "unchecked", "serial" }) private Map<String, GlusterServiceStatus> refreshServerServices(final VDS server) { Map<String, GlusterServiceStatus> serviceStatusMap = new HashMap<String, GlusterServiceStatus>(); if (server.getStatus() != VDSStatus.Up) { // Update the status of all the services of stopped server in single transaction TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Map<String, GlusterServiceStatus>>() { @Override public Map<String, GlusterServiceStatus> runInTransaction() { return updateGlusterServicesStatusForStoppedServer(server); } }); } else { acquireLock(server.getId()); try { Map<Guid, GlusterServerService> existingServicesMap = getExistingServicesMap(server); List<GlusterServerService> servicesToUpdate = new ArrayList<GlusterServerService>(); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GlusterServicesList, new GlusterServicesListVDSParameters(server.getId(), getServiceNameMap().keySet())); if (!returnValue.getSucceeded()) { log.errorFormat("Couldn't fetch services statuses from server {0}, error: {1}! " + "Updating statuses of all services on this server to UNKNOWN.", server.getHostName(), returnValue.getVdsError().getMessage()); logUtil.logServerMessage(server, AuditLogType.GLUSTER_SERVICES_LIST_FAILED); return updateStatusToUnknown(existingServicesMap.values()); } for (final GlusterServerService fetchedService : (List<GlusterServerService>) returnValue.getReturnValue()) { serviceStatusMap.put(fetchedService.getServiceName(), fetchedService.getStatus()); GlusterServerService existingService = existingServicesMap.get(fetchedService.getServiceId()); if (existingService == null) { insertServerService(server, fetchedService); } else { final GlusterServiceStatus oldStatus = existingService.getStatus(); final GlusterServiceStatus newStatus = fetchedService.getStatus(); if (oldStatus != newStatus) { log.infoFormat("Status of service {0} on server {1} changed from {2} to {3}. Updating in engine now.", fetchedService.getServiceName(), server.getHostName(), oldStatus.name(), newStatus.name()); logUtil.logAuditMessage(server.getVdsGroupId(), null, server, AuditLogType.GLUSTER_SERVER_SERVICE_STATUS_CHANGED, new HashMap<String, String>() { { put(GlusterConstants.SERVICE_NAME, fetchedService.getServiceName()); put(GlusterConstants.OLD_STATUS, oldStatus.getStatusMsg()); put(GlusterConstants.NEW_STATUS, newStatus.getStatusMsg()); } }); existingService.setStatus(fetchedService.getStatus()); servicesToUpdate.add(existingService); } } } if (servicesToUpdate.size() > 0) { getGlusterServerServiceDao().updateAll(servicesToUpdate); } } finally { releaseLock(server.getId()); } } return serviceStatusMap; } private Map<String, GlusterServiceStatus> updateStatusToUnknown(Collection<GlusterServerService> existingServices) { Map<String, GlusterServiceStatus> serviceStatusMap = new HashMap<String, GlusterServiceStatus>(); for (GlusterServerService existingService : existingServices) { existingService.setStatus(GlusterServiceStatus.UNKNOWN); serviceStatusMap.put(existingService.getServiceName(), existingService.getStatus()); } getGlusterServerServiceDao().updateAll(existingServices); return serviceStatusMap; } private Map<Guid, GlusterServerService> getExistingServicesMap(VDS server) { List<GlusterServerService> existingServices = getGlusterServerServiceDao().getByServerId(server.getId()); Map<Guid, GlusterServerService> existingServicesMap = new HashMap<Guid, GlusterServerService>(); if (existingServices != null) { for (GlusterServerService service : existingServices) { existingServicesMap.put(service.getServiceId(), service); } } return existingServicesMap; } @SuppressWarnings("serial") private void insertServerService(VDS server, final GlusterServerService fetchedService) { fetchedService.setId(Guid.newGuid()); getGlusterServerServiceDao().save(fetchedService); log.infoFormat("Service {0} was not mapped to server {1}. Mapped it now.", fetchedService.getServiceName(), server.getHostName()); logUtil.logAuditMessage(server.getVdsGroupId(), null, server, AuditLogType.GLUSTER_SERVICE_ADDED_TO_SERVER, new HashMap<String, String>() { { put(GlusterConstants.SERVICE_NAME, fetchedService.getServiceName()); } }); } @SuppressWarnings("serial") private void updateClusterServiceStatus(final GlusterClusterService clusterService, final GlusterServiceStatus newStatus) { final GlusterServiceStatus oldStatus = clusterService.getStatus(); clusterService.setStatus(newStatus); getGlusterClusterServiceDao().update(clusterService); log.infoFormat("Status of service type {0} changed on cluster {1} from {2} to {3}.", clusterService.getServiceType().name(), clusterService.getClusterId(), oldStatus, newStatus); logUtil.logAuditMessage(clusterService.getClusterId(), null, null, AuditLogType.GLUSTER_CLUSTER_SERVICE_STATUS_CHANGED, new HashMap<String, String>() { { put(GlusterConstants.SERVICE_TYPE, clusterService.getServiceType().name()); put(GlusterConstants.OLD_STATUS, oldStatus.getStatusMsg()); put(GlusterConstants.NEW_STATUS, newStatus.getStatusMsg()); } }); } @SuppressWarnings("serial") private GlusterClusterService addClusterServiceToDb(VDSGroup cluster, final ServiceType serviceType, final GlusterServiceStatus status) { GlusterClusterService clusterService = new GlusterClusterService(); clusterService.setClusterId(cluster.getId()); clusterService.setServiceType(serviceType); clusterService.setStatus(status); getGlusterClusterServiceDao().save(clusterService); log.infoFormat("Service type {0} not mapped to cluster {1}. Mapped it now.", serviceType, cluster.getName()); logUtil.logAuditMessage(clusterService.getClusterId(), null, null, AuditLogType.GLUSTER_CLUSTER_SERVICE_STATUS_ADDED, new HashMap<String, String>() { { put(GlusterConstants.SERVICE_TYPE, serviceType.name()); put(GlusterConstants.NEW_STATUS, status.getStatusMsg()); } }); return clusterService; } private boolean supportsGlusterServicesFeature(VDSGroup cluster) { return cluster.supportsGlusterService() && GlusterFeatureSupported.glusterServices(cluster.getcompatibility_version()); } private void populateServiceMap() { List<GlusterService> services = getGlusterServiceDao().getAll(); for (GlusterService service : services) { getServiceNameMap().put(service.getServiceName(), service); } } protected Map<String, GlusterService> getServiceNameMap() { return serviceNameMap; } }
gluster: Correct SWIFT status if no hosts in cluster If there are no hosts available under a cluster the SWIFT status was being displayed as Up. Corrected the same to show Unknown is no hosts available under a cluster or removed all the hosts from the cluster. Change-Id: I17080ac2d3eb5ec87b2efcc86bdca750995bce0e Bug-Url: https://bugzilla.redhat.com/974560 Signed-off-by: Shubhendu Tripathi <[email protected]>
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GlusterServiceSyncJob.java
gluster: Correct SWIFT status if no hosts in cluster
<ide><path>ackend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/gluster/GlusterServiceSyncJob.java <ide> if (supportsGlusterServicesFeature(cluster)) { <ide> try { <ide> List<VDS> serversList = getClusterUtils().getAllServers(cluster.getId()); <del> List<Callable<Map<String, GlusterServiceStatus>>> taskList = createTaskList(serversList); <del> if (taskList != null && taskList.size() > 0) { <del> refreshClusterServices(cluster, ThreadPoolUtil.invokeAll(taskList)); <add> <add> // If there are no servers in the cluster, set the status as unknown <add> if (serversList.isEmpty()) { <add> Map<ServiceType, GlusterServiceStatus> statusMap = new HashMap<>(); <add> for (ServiceType type : getClusterServiceMap(cluster).keySet()) { <add> statusMap.put(type, GlusterServiceStatus.UNKNOWN); <add> } <add> addOrUpdateClusterServices(cluster, statusMap); <add> } else { <add> List<Callable<Map<String, GlusterServiceStatus>>> taskList = createTaskList(serversList); <add> if (taskList != null && taskList.size() > 0) { <add> refreshClusterServices(cluster, ThreadPoolUtil.invokeAll(taskList)); <add> } <ide> } <ide> } catch (Exception e) { <ide> log.errorFormat("Error while refreshing service statuses of cluster {0}!",
JavaScript
mit
065fb4525d4f36f46f01377d50341dcb575ec8e0
0
javuio/MySQLNodeBootstrapAngular,javuio/MySQLNodeBootstrapAngular,javuio/MySQLNodeBootstrapAngular
///global var $javuApp = angular.module('javu',['ngRoute','ui.bootstrap']); $javuApp.config(['$routeProvider',function ($routeProvider) { $routeProvider .when('/', {templateUrl: '/pages/templates/dashboard.html'}) .when('/login', {templateUrl: '/pages/templates/login.html'}) .when('/page1', {templateUrl: '/pages/templates/page1.html'}) .when('/profile',{templateUrl:'/pages/templates/profile.html'}) .when('/register',{templateUrl:'/pages/templates/register.html'}) .when('/forgotPassword', {templateUrl: '/pages/templates/forgotPassword.html'}) .when('/404', {templateUrl: '/pages/templates/404.html'}) .otherwise({redirectTo: '/404/404.html'}); }]); function loadControllers(){ var controllerFiles; if (window.location.hostname != 'localhost' ) { controllerFiles = ['/pages/controllers/all.min.js']; } else { controllerFiles = [ "/scripts/framework/homePageProfileCtrl.js", "/pages/controllers/loginCtrl.js", "/pages/controllers/dashboardCtrl.js", "/pages/controllers/page1Ctrl.js", "/pages/controllers/registerCtrl.js", "/pages/controllers/profileCtrl.js" ] } for (var i = 0; i < controllerFiles.length; i++) document.write('<script type="text/javascript" src="' + controllerFiles[i] + '"></script>'); } loadControllers(); $javuApp.controller('menuCtrl', ['$scope', function ($scope) { $scope.pages = [ {title: 'Dashboard', hash: '', className: ''} , {title: 'Page1', hash: 'page1', className: ''} ]; }]);
client/controlPanel/app.js
///global var $javuApp = angular.module('javu',['ngRoute','ui.bootstrap']); $javuApp.config(['$routeProvider',function ($routeProvider) { $routeProvider .when('/', {templateUrl: '/pages/templates/dashboard.html'}) .when('/login', {templateUrl: '/pages/templates/login.html'}) .when('/page1', {templateUrl: '/pages/templates/page1.html'}) .when('/profile',{templateUrl:'/pages/templates/profile.html'}) .when('/register',{templateUrl:'/pages/templates/register.html'}) .when('/forgotPassword', {templateUrl: '/pages/templates/forgotPassword.html'}) .when('/404', {templateUrl: '/pages/templates/404.html'}) .otherwise({redirectTo: '/404/404.html'}); }]); function loadControllers(){ var controllerFiles; if (window.location.hostname != 'localhost' ) { controllerFiles = ['/pages/controllers/all.min.js']; } else { controllerFiles = [ "/scripts/framework/homePageProfileCtrl.js", "/pages/controllers/loginCtrl.js", "/pages/controllers/dashboardCtrl.js", "/pages/controllers/page1Ctrl.js", "/pages/controllers/registerCtrl.js", "/pages/controllers/profileCtrl.js" ] } for (var i = 0; i < controllerFiles.length; i++) document.write('<script type="text/javascript" src="' + controllerFiles[i] + '"></script>'); } loadControllers(); $javuApp.controller('menuCtrl', ['$scope', function ($scope) { $scope.pages = [ {title: 'Dashboard', hash: '', className: ''} , {title: 'Page1', hash: 'page1', className: ''} ]; }]);
fix routes
client/controlPanel/app.js
fix routes
<ide><path>lient/controlPanel/app.js <ide> , {title: 'Page1', hash: 'page1', className: ''} <ide> ]; <ide> }]); <del> <del> <del>
JavaScript
mit
38fbbb638eb3b965f08dc45eefaf9325765ec01d
0
node4good/asynctrace,TheNodeILs/asynctrace
'use strict'; Error.stackTraceLimit = Infinity; try { var tracing = require('tracing'); } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') throw e; require('async-listener'); tracing = process; } try { var util = require('util'); var debug = util.debuglog('asynctrace'); } catch (e) { debug = console.error.bind(console); } var PATH_PREFIX = process.cwd().toLowerCase(); var sep = require('path').sep; var settings = { // `null`ing a style will remove it from the trace output tracingModuleStyle: null, // tracingModuleStyle: "\x1B[31m", modulesStyle: "\x1B[32m", globalsStyle: "\x1B[33m", coreStyle: "\x1B[34m", ownStyle: "\x1B[1m", mocha: true, BOUNDARY: ' [sync boundary]', useColors: true }; tracing.addAsyncListener({ 'create': asyncFunctionInitialized, 'before': asyncCallbackBefore, 'error': asyncCallbackError, 'after': asyncCallbackAfter }); function asyncFunctionInitialized(oldFrames) { oldFrames = oldFrames || Error._frames || []; var frames = StackError.getStackFrames(asyncFunctionInitialized); if (frames[1] && frames[1].functionName === 'createTCP') return oldFrames; frames.unshift(settings.BOUNDARY); frames.push.apply(frames, oldFrames); Error._frames = frames; return frames; } function asyncCallbackBefore(__, frames) { Error._frames = frames; } function asyncCallbackAfter(__, frames) { Error._frames = frames; } function asyncCallbackError(oldFrames, error) { if (error._passed) return; var frames = (oldFrames || []).reduce(reducer, []); error.stack += v8StackFormating('', frames); error._passed = true; } /* ===================== stack chain util ======================== */ function StackError(otp) { Error.captureStackTrace(this, otp); Error.prepareStackTrace = function justStoreStackStace(error, frames) { error._frames = frames.map(function (frame) { return { string: frame.toString(), fileName: frame.getFileName(), functionName: frame.getFunctionName(), methodName: frame.getMethodName() }; }); return ''; }; this.stack; // jshint ignore:line delete Error.prepareStackTrace; } StackError.getStackFrames = function getStackFrames(otp) { return (new this(otp))._frames; }; util.inherits(StackError, Error); /* ===================== stack chain manipulation & formating ======================== */ function categorizeFrame(frame) { var name = frame && frame.fileName && frame.fileName.toLowerCase(); if (!name) return (frame._section = 'core'); if (name === 'tracing.js') return (frame._section = 'tracingModule'); if (!~name.indexOf(sep)) return (frame._section = 'core'); if (name.indexOf(PATH_PREFIX) !== 0) return (frame._section = 'globals'); if (~(name.replace(PATH_PREFIX, '')).indexOf('node_modules')) return (frame._section = 'modules'); frame._section = 'own'; } function reducer(seed, frame) { if (typeof frame == 'string') { if (frame != seed[seed.length - 1]) seed.push(frame); return seed; } categorizeFrame(frame); seed.push(frame); return seed; } function v8StackFormating(error, frames) { var lines = []; lines.push(error.toString()); frames.push({ string: '<the nexus>\n', _section: 'core' }); for (var i = 0; i < frames.length; i++) { var frame = frames[i]; if (typeof frame == 'string') { lines.push(frame); continue; } var line; try { line = frame.string; } catch (e) { try { line = "<error: " + e + ">"; } catch (ee) { // Any code that reaches this point is seriously nasty! line = "<error>"; } } var style = getStyle(frame._section); var prefix = style + " at "; var suffix = settings.useColors ? "\x1B[0m" : ''; if (typeof style == 'string') lines.push(prefix + line + suffix); } return lines.join("\n"); } function getStyle(sec) { return (settings.useColors) ? settings[sec + 'Style'] : ''; } /* ===================== 3rd party integrations ======================== */ function setupForMocha() { try { var mocha = Object.keys(require.cache) .filter(function (k) { return ~k.search(/mocha.index\.js/); }) .map(function (k) { return require.cache[k].exports; }) .pop(); if (!mocha) return; var shimmer = require('shimmer'); shimmer.wrap(mocha.prototype, 'run', function (original) { return function () { var runner = original.apply(this, arguments); settings.useColors = this.options.useColors; runner.on('test', function () { Error._frames = null; }); }; }); } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') debug(e.stack); } } if (settings.mocha) setupForMocha();
asynctrace.js
'use strict'; Error.stackTraceLimit = Infinity; try { var tracing = require('tracing'); } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') throw e; require('async-listener'); tracing = process; } var util = require('util'); var PATH_PREFIX = process.cwd().toLowerCase(); var sep = require('path').sep; var settings = { // `null`ing a style will remove it from the trace output tracingModuleStyle: null, // tracingModuleStyle: "\x1B[31m", modulesStyle: "\x1B[32m", globalsStyle: "\x1B[33m", coreStyle: "\x1B[34m", ownStyle: "\x1B[1m", mocha: true, BOUNDARY: ' [sync boundary]', useColors: true }; tracing.addAsyncListener({ 'create': asyncFunctionInitialized, 'before': asyncCallbackBefore, 'error': asyncCallbackError, 'after': asyncCallbackAfter }); function asyncFunctionInitialized(oldFrames) { oldFrames = oldFrames || Error._frames || []; var frames = StackError.getStackFrames(asyncFunctionInitialized); if (frames[1] && frames[1].functionName === 'createTCP') return oldFrames; frames.unshift(settings.BOUNDARY); frames.push.apply(frames, oldFrames); Error._frames = frames; return frames; } function asyncCallbackBefore(__, frames) { Error._frames = frames; } function asyncCallbackAfter(__, frames) { Error._frames = frames; } function asyncCallbackError(oldFrames, error) { if (error._passed) return; var frames = (oldFrames || []).reduce(reducer, []); error.stack += v8StackFormating('', frames); error._passed = true; } /* ===================== stack chain util ======================== */ function StackError(otp) { Error.captureStackTrace(this, otp); Error.prepareStackTrace = function justStoreStackStace(error, frames) { error._frames = frames.map(function (frame) { return { string: frame.toString(), fileName: frame.getFileName(), functionName: frame.getFunctionName(), methodName: frame.getMethodName() }; }); return ''; }; this.stack; // jshint ignore:line delete Error.prepareStackTrace; } StackError.getStackFrames = function getStackFrames(otp) { return (new this(otp))._frames; }; util.inherits(StackError, Error); /* ===================== stack chain manipulation & formating ======================== */ function categorizeFrame(frame) { var name = frame && frame.fileName && frame.fileName.toLowerCase(); if (!name) return (frame._section = 'core'); if (name === 'tracing.js') return (frame._section = 'tracingModule'); if (!~name.indexOf(sep)) return (frame._section = 'core'); if (name.indexOf(PATH_PREFIX) !== 0) return (frame._section = 'globals'); if (~(name.replace(PATH_PREFIX, '')).indexOf('node_modules')) return (frame._section = 'modules'); frame._section = 'own'; } function reducer(seed, frame) { if (typeof frame == 'string') { if (frame != seed[seed.length - 1]) seed.push(frame); return seed; } categorizeFrame(frame); seed.push(frame); return seed; } function v8StackFormating(error, frames) { var lines = []; lines.push(error.toString()); frames.push({ string: '<the nexus>\n', _section: 'core' }); for (var i = 0; i < frames.length; i++) { var frame = frames[i]; if (typeof frame == 'string') { lines.push(frame); continue; } var line; try { line = frame.string; } catch (e) { try { line = "<error: " + e + ">"; } catch (ee) { // Any code that reaches this point is seriously nasty! line = "<error>"; } } var style = getStyle(frame._section); var prefix = style + " at "; var suffix = settings.useColors ? "\x1B[0m" : ''; if (typeof style == 'string') lines.push(prefix + line + suffix); } return lines.join("\n"); } function getStyle(sec) { return (settings.useColors) ? settings[sec + 'Style'] : ''; } /* ===================== 3rd party integrations ======================== */ function setupForMocha() { try { var mocha = Object.keys(require.cache) .filter(function (k) { return ~k.search(/mocha.index\.js/); }) .map(function (k) { return require.cache[k].exports; }) .pop(); var shimmer = require('shimmer'); shimmer.wrap(mocha.prototype, 'run', function (original) { return function () { var runner = original.apply(this, arguments); settings.useColors = this.options.useColors; runner.on('test', function () { Error._frames = null; }); }; }); } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') console.error(e); } } if (settings.mocha) setupForMocha();
safer `mocha` detection
asynctrace.js
safer `mocha` detection
<ide><path>synctrace.js <ide> require('async-listener'); <ide> tracing = process; <ide> } <del>var util = require('util'); <add>try { <add> var util = require('util'); <add> var debug = util.debuglog('asynctrace'); <add>} catch (e) { <add> debug = console.error.bind(console); <add>} <ide> var PATH_PREFIX = process.cwd().toLowerCase(); <ide> var sep = require('path').sep; <ide> <ide> .filter(function (k) { return ~k.search(/mocha.index\.js/); }) <ide> .map(function (k) { return require.cache[k].exports; }) <ide> .pop(); <add> if (!mocha) return; <ide> var shimmer = require('shimmer'); <ide> shimmer.wrap(mocha.prototype, 'run', function (original) { <ide> return function () { <ide> }; <ide> }); <ide> } catch (e) { <del> if (e.code !== 'MODULE_NOT_FOUND') console.error(e); <add> if (e.code !== 'MODULE_NOT_FOUND') debug(e.stack); <ide> } <ide> } <ide> if (settings.mocha) setupForMocha();
Java
apache-2.0
9d91a4c6988b12fcf31329bf91812634b6417966
0
nelt/codingmatters-value-objects,nelt/codingmatters-value-objects
package org.codingmatters.value.objects.utils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * Created by nelt on 9/3/16. */ public class Utils { static public InputStream streamFor(String str) throws IOException { return new ByteArrayInputStream(str.getBytes("UTF-8")); } static public StrBuilder string() { return new StrBuilder(); } static public class StrBuilder { private final StringBuilder internal = new StringBuilder(); public StrBuilder line(String str) { return this.apnd(str).apnd("\n"); } public StrBuilder line(String format, Object ... args) { return this.line(String.format(format, args)); } public StrBuilder apnd(String str) { this.internal.append(str); return this; } public StrBuilder apnd(String format, Object ... args) { return this.apnd(String.format(format, args)); } public String build() { return this.internal.toString(); } } }
cdm-value-objects-generation/src/test/java/org/codingmatters/value/objects/utils/Utils.java
package org.codingmatters.value.objects.utils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * Created by nelt on 9/3/16. */ public class Utils { static public InputStream streamFor(String str) throws IOException { return new ByteArrayInputStream(str.getBytes("UTF-8")); } static public StrBuilder string() { return new StrBuilder(); } static public class StrBuilder { private final StringBuilder internal = new StringBuilder(); public StrBuilder line(String str) { return this.apnd(str).apnd("\n"); } public StrBuilder line(String format, Object ... args) { return this.line(String.format(format, args)); } public StrBuilder apnd(String str) { this.internal.append(str); return this; } public StrBuilder apnd(String format, Object ... args) { return this.apnd(String.format(format, args)); } public String build() { System.out.println("builded " + this.internal.toString()); return this.internal.toString(); } } }
cleaned sysout
cdm-value-objects-generation/src/test/java/org/codingmatters/value/objects/utils/Utils.java
cleaned sysout
<ide><path>dm-value-objects-generation/src/test/java/org/codingmatters/value/objects/utils/Utils.java <ide> } <ide> <ide> public String build() { <del> System.out.println("builded " + this.internal.toString()); <ide> return this.internal.toString(); <ide> } <ide> }
Java
apache-2.0
error: pathspec 'web/api/src/test/java/org/onosproject/rest/resources/NetworkConfigWebResourceTest.java' did not match any file(s) known to git
37a5d8c3da358ccfe8a4583cb790626b31c1f699
1
opennetworkinglab/onos,kuujo/onos,mengmoya/onos,Shashikanth-Huawei/bmp,sdnwiselab/onos,VinodKumarS-Huawei/ietf96yang,planoAccess/clonedONOS,LorenzReinhart/ONOSnew,sdnwiselab/onos,oplinkoms/onos,Shashikanth-Huawei/bmp,maheshraju-Huawei/actn,donNewtonAlpha/onos,y-higuchi/onos,VinodKumarS-Huawei/ietf96yang,osinstom/onos,Shashikanth-Huawei/bmp,mengmoya/onos,donNewtonAlpha/onos,mengmoya/onos,opennetworkinglab/onos,kuujo/onos,gkatsikas/onos,sonu283304/onos,osinstom/onos,sdnwiselab/onos,lsinfo3/onos,sdnwiselab/onos,donNewtonAlpha/onos,oplinkoms/onos,sonu283304/onos,planoAccess/clonedONOS,oplinkoms/onos,Shashikanth-Huawei/bmp,gkatsikas/onos,LorenzReinhart/ONOSnew,Shashikanth-Huawei/bmp,sdnwiselab/onos,maheshraju-Huawei/actn,sdnwiselab/onos,sonu283304/onos,osinstom/onos,VinodKumarS-Huawei/ietf96yang,donNewtonAlpha/onos,kuujo/onos,gkatsikas/onos,y-higuchi/onos,y-higuchi/onos,gkatsikas/onos,mengmoya/onos,lsinfo3/onos,y-higuchi/onos,oplinkoms/onos,oplinkoms/onos,planoAccess/clonedONOS,kuujo/onos,kuujo/onos,oplinkoms/onos,kuujo/onos,opennetworkinglab/onos,LorenzReinhart/ONOSnew,sonu283304/onos,opennetworkinglab/onos,LorenzReinhart/ONOSnew,mengmoya/onos,y-higuchi/onos,VinodKumarS-Huawei/ietf96yang,gkatsikas/onos,maheshraju-Huawei/actn,osinstom/onos,opennetworkinglab/onos,maheshraju-Huawei/actn,maheshraju-Huawei/actn,oplinkoms/onos,opennetworkinglab/onos,lsinfo3/onos,planoAccess/clonedONOS,lsinfo3/onos,gkatsikas/onos,VinodKumarS-Huawei/ietf96yang,kuujo/onos,osinstom/onos,donNewtonAlpha/onos,LorenzReinhart/ONOSnew
/* * Copyright 2015 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.rest.resources; import java.net.HttpURLConnection; import java.util.HashSet; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.onlab.osgi.ServiceDirectory; import org.onlab.osgi.TestServiceDirectory; import org.onlab.rest.BaseResource; import org.onosproject.net.DefaultDevice; import org.onosproject.net.Device; import org.onosproject.net.Link; import org.onosproject.net.config.Config; import org.onosproject.net.config.NetworkConfigService; import org.onosproject.net.config.NetworkConfigServiceAdapter; import org.onosproject.net.config.SubjectFactory; import org.onosproject.rest.ResourceTest; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableSet; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.replay; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.fail; /** * Unit tests for network config web resource. */ public class NetworkConfigWebResourceTest extends ResourceTest { MockNetworkConfigService mockNetworkConfigService; public class MockDeviceConfig extends Config<Device> { final String field1Value; final String field2Value; MockDeviceConfig(String value1, String value2) { field1Value = value1; field2Value = value2; } @Override public String key() { return "basic"; } @Override public JsonNode node() { return new ObjectMapper() .createObjectNode() .put("field1", field1Value) .put("field2", field2Value); } } /** * Mock config factory for devices. */ private final SubjectFactory<Device> mockDevicesSubjectFactory = new SubjectFactory<Device>(Device.class, "devices") { @Override public Device createSubject(String subjectKey) { DefaultDevice device = createMock(DefaultDevice.class); replay(device); return device; } @Override public Class<Device> subjectClass() { return Device.class; } }; /** * Mock config factory for links. */ private final SubjectFactory<Link> mockLinksSubjectFactory = new SubjectFactory<Link>(Link.class, "links") { @Override public Link createSubject(String subjectKey) { return null; } @Override public Class<Link> subjectClass() { return Link.class; } }; /** * Mocked config service. */ class MockNetworkConfigService extends NetworkConfigServiceAdapter { Set devicesSubjects = new HashSet<>(); Set devicesConfigs = new HashSet<>(); Set linksSubjects = new HashSet(); Set linksConfigs = new HashSet<>(); @Override public Set<Class> getSubjectClasses() { return ImmutableSet.of(Device.class, Link.class); } @Override public SubjectFactory getSubjectFactory(Class subjectClass) { if (subjectClass == Device.class) { return mockDevicesSubjectFactory; } else if (subjectClass == Link.class) { return mockLinksSubjectFactory; } return null; } @Override public SubjectFactory getSubjectFactory(String subjectClassKey) { if (subjectClassKey.equals("devices")) { return mockDevicesSubjectFactory; } else if (subjectClassKey.equals("links")) { return mockLinksSubjectFactory; } return null; } @SuppressWarnings("unchecked") @Override public <S> Set<S> getSubjects(Class<S> subjectClass) { if (subjectClass == Device.class) { return devicesSubjects; } else if (subjectClass == Link.class) { return linksSubjects; } return null; } @SuppressWarnings("unchecked") @Override public <S> Set<? extends Config<S>> getConfigs(S subject) { if (subject instanceof Device || subject.toString().contains("device")) { return devicesConfigs; } else if (subject.toString().contains("link")) { return linksConfigs; } return null; } @SuppressWarnings("unchecked") @Override public <S, C extends Config<S>> C getConfig(S subject, Class<C> configClass) { if (configClass == MockDeviceConfig.class) { return (C) devicesConfigs.toArray()[0]; } return null; } @Override public Class<? extends Config> getConfigClass(String subjectClassKey, String configKey) { return MockDeviceConfig.class; } } /** * Sets up mocked config service. */ @Before public void setUp() { mockNetworkConfigService = new MockNetworkConfigService(); ServiceDirectory testDirectory = new TestServiceDirectory() .add(NetworkConfigService.class, mockNetworkConfigService); BaseResource.setServiceDirectory(testDirectory); } /** * Sets up test config data. */ @SuppressWarnings("unchecked") public void setUpConfigData() { mockNetworkConfigService.devicesSubjects.add("device1"); mockNetworkConfigService.devicesConfigs.add(new MockDeviceConfig("v1", "v2")); } /** * Tests the result of the rest api GET when there are no configs. */ @Test public void testEmptyConfigs() { final WebResource rs = resource(); final String response = rs.path("network/configuration").get(String.class); assertThat(response, containsString("\"devices\":{}")); assertThat(response, containsString("\"links\":{}")); } /** * Tests the result of the rest api GET for a single subject with no configs. */ @Test public void testEmptyConfig() { final WebResource rs = resource(); final String response = rs.path("network/configuration/devices").get(String.class); assertThat(response, is("{}")); } /** * Tests the result of the rest api GET for a single subject that * is undefined. */ @Test public void testNonExistentConfig() { final WebResource rs = resource(); try { final String response = rs.path("network/configuration/nosuchkey").get(String.class); fail("GET of non-existent key does not produce an exception " + response); } catch (UniformInterfaceException e) { assertThat(e.getResponse().getStatus(), is(HttpURLConnection.HTTP_NOT_FOUND)); } } private void checkBasicAttributes(JsonValue basic) { Assert.assertThat(basic.asObject().get("field1").asString(), is("v1")); Assert.assertThat(basic.asObject().get("field2").asString(), is("v2")); } /** * Tests the result of the rest api GET when there is a config. */ @Test public void testConfigs() { setUpConfigData(); final WebResource rs = resource(); final String response = rs.path("network/configuration").get(String.class); final JsonObject result = JsonObject.readFrom(response); Assert.assertThat(result, notNullValue()); Assert.assertThat(result.names(), hasSize(2)); JsonValue devices = result.get("devices"); Assert.assertThat(devices, notNullValue()); JsonValue device1 = devices.asObject().get("device1"); Assert.assertThat(device1, notNullValue()); JsonValue basic = device1.asObject().get("basic"); Assert.assertThat(basic, notNullValue()); checkBasicAttributes(basic); } /** * Tests the result of the rest api single subject key GET when * there is a config. */ @Test public void testSingleSubjectKeyConfig() { setUpConfigData(); final WebResource rs = resource(); final String response = rs.path("network/configuration/devices").get(String.class); final JsonObject result = JsonObject.readFrom(response); Assert.assertThat(result, notNullValue()); Assert.assertThat(result.names(), hasSize(1)); JsonValue device1 = result.asObject().get("device1"); Assert.assertThat(device1, notNullValue()); JsonValue basic = device1.asObject().get("basic"); Assert.assertThat(basic, notNullValue()); checkBasicAttributes(basic); } /** * Tests the result of the rest api single subject GET when * there is a config. */ @Test public void testSingleSubjectConfig() { setUpConfigData(); final WebResource rs = resource(); final String response = rs.path("network/configuration/devices/device1") .get(String.class); final JsonObject result = JsonObject.readFrom(response); Assert.assertThat(result, notNullValue()); Assert.assertThat(result.names(), hasSize(1)); JsonValue basic = result.asObject().get("basic"); Assert.assertThat(basic, notNullValue()); checkBasicAttributes(basic); } /** * Tests the result of the rest api single subject single config GET when * there is a config. */ @Test public void testSingleSubjectSingleConfig() { setUpConfigData(); final WebResource rs = resource(); final String response = rs.path("network/configuration/devices/device1/basic") .get(String.class); final JsonObject result = JsonObject.readFrom(response); Assert.assertThat(result, notNullValue()); Assert.assertThat(result.names(), hasSize(2)); checkBasicAttributes(result); } // TODO: Add test for DELETE and POST }
web/api/src/test/java/org/onosproject/rest/resources/NetworkConfigWebResourceTest.java
Unit tests for network config REST API. Change-Id: I1b09035ff7aaa463889f62bbc9709a37a920d800
web/api/src/test/java/org/onosproject/rest/resources/NetworkConfigWebResourceTest.java
Unit tests for network config REST API.
<ide><path>eb/api/src/test/java/org/onosproject/rest/resources/NetworkConfigWebResourceTest.java <add>/* <add> * Copyright 2015 Open Networking Laboratory <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.onosproject.rest.resources; <add> <add>import java.net.HttpURLConnection; <add>import java.util.HashSet; <add>import java.util.Set; <add> <add>import org.junit.Assert; <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.onlab.osgi.ServiceDirectory; <add>import org.onlab.osgi.TestServiceDirectory; <add>import org.onlab.rest.BaseResource; <add>import org.onosproject.net.DefaultDevice; <add>import org.onosproject.net.Device; <add>import org.onosproject.net.Link; <add>import org.onosproject.net.config.Config; <add>import org.onosproject.net.config.NetworkConfigService; <add>import org.onosproject.net.config.NetworkConfigServiceAdapter; <add>import org.onosproject.net.config.SubjectFactory; <add>import org.onosproject.rest.ResourceTest; <add> <add>import com.eclipsesource.json.JsonObject; <add>import com.eclipsesource.json.JsonValue; <add>import com.fasterxml.jackson.databind.JsonNode; <add>import com.fasterxml.jackson.databind.ObjectMapper; <add>import com.google.common.collect.ImmutableSet; <add>import com.sun.jersey.api.client.UniformInterfaceException; <add>import com.sun.jersey.api.client.WebResource; <add> <add>import static org.easymock.EasyMock.createMock; <add>import static org.easymock.EasyMock.replay; <add>import static org.hamcrest.MatcherAssert.assertThat; <add>import static org.hamcrest.Matchers.containsString; <add>import static org.hamcrest.Matchers.hasSize; <add>import static org.hamcrest.Matchers.is; <add>import static org.hamcrest.Matchers.notNullValue; <add>import static org.junit.Assert.fail; <add> <add>/** <add> * Unit tests for network config web resource. <add> */ <add>public class NetworkConfigWebResourceTest extends ResourceTest { <add> <add> MockNetworkConfigService mockNetworkConfigService; <add> <add> public class MockDeviceConfig extends Config<Device> { <add> <add> final String field1Value; <add> final String field2Value; <add> <add> MockDeviceConfig(String value1, String value2) { <add> field1Value = value1; <add> field2Value = value2; <add> } <add> <add> @Override <add> public String key() { <add> return "basic"; <add> } <add> <add> @Override <add> public JsonNode node() { <add> return new ObjectMapper() <add> .createObjectNode() <add> .put("field1", field1Value) <add> .put("field2", field2Value); <add> } <add> } <add> <add> /** <add> * Mock config factory for devices. <add> */ <add> private final SubjectFactory<Device> mockDevicesSubjectFactory = <add> new SubjectFactory<Device>(Device.class, "devices") { <add> @Override <add> public Device createSubject(String subjectKey) { <add> DefaultDevice device = createMock(DefaultDevice.class); <add> replay(device); <add> return device; <add> } <add> <add> @Override <add> public Class<Device> subjectClass() { <add> return Device.class; <add> } <add> }; <add> <add> /** <add> * Mock config factory for links. <add> */ <add> private final SubjectFactory<Link> mockLinksSubjectFactory = <add> new SubjectFactory<Link>(Link.class, "links") { <add> @Override <add> public Link createSubject(String subjectKey) { <add> return null; <add> } <add> <add> @Override <add> public Class<Link> subjectClass() { <add> return Link.class; <add> } <add> }; <add> <add> /** <add> * Mocked config service. <add> */ <add> class MockNetworkConfigService extends NetworkConfigServiceAdapter { <add> <add> Set devicesSubjects = new HashSet<>(); <add> Set devicesConfigs = new HashSet<>(); <add> Set linksSubjects = new HashSet(); <add> Set linksConfigs = new HashSet<>(); <add> <add> @Override <add> public Set<Class> getSubjectClasses() { <add> return ImmutableSet.of(Device.class, Link.class); <add> } <add> <add> @Override <add> public SubjectFactory getSubjectFactory(Class subjectClass) { <add> if (subjectClass == Device.class) { <add> return mockDevicesSubjectFactory; <add> } else if (subjectClass == Link.class) { <add> return mockLinksSubjectFactory; <add> } <add> return null; <add> } <add> <add> @Override <add> public SubjectFactory getSubjectFactory(String subjectClassKey) { <add> if (subjectClassKey.equals("devices")) { <add> return mockDevicesSubjectFactory; <add> } else if (subjectClassKey.equals("links")) { <add> return mockLinksSubjectFactory; <add> } <add> return null; <add> } <add> <add> @SuppressWarnings("unchecked") <add> @Override <add> public <S> Set<S> getSubjects(Class<S> subjectClass) { <add> if (subjectClass == Device.class) { <add> return devicesSubjects; <add> } else if (subjectClass == Link.class) { <add> return linksSubjects; <add> } <add> return null; <add> } <add> <add> @SuppressWarnings("unchecked") <add> @Override <add> public <S> Set<? extends Config<S>> getConfigs(S subject) { <add> if (subject instanceof Device || subject.toString().contains("device")) { <add> return devicesConfigs; <add> } else if (subject.toString().contains("link")) { <add> return linksConfigs; <add> } <add> return null; <add> } <add> <add> @SuppressWarnings("unchecked") <add> @Override <add> public <S, C extends Config<S>> C getConfig(S subject, Class<C> configClass) { <add> <add> if (configClass == MockDeviceConfig.class) { <add> return (C) devicesConfigs.toArray()[0]; <add> } <add> return null; <add> } <add> <add> @Override <add> public Class<? extends Config> getConfigClass(String subjectClassKey, String configKey) { <add> return MockDeviceConfig.class; <add> } <add> } <add> <add> /** <add> * Sets up mocked config service. <add> */ <add> @Before <add> public void setUp() { <add> mockNetworkConfigService = new MockNetworkConfigService(); <add> ServiceDirectory testDirectory = <add> new TestServiceDirectory() <add> .add(NetworkConfigService.class, mockNetworkConfigService); <add> BaseResource.setServiceDirectory(testDirectory); <add> } <add> <add> /** <add> * Sets up test config data. <add> */ <add> @SuppressWarnings("unchecked") <add> public void setUpConfigData() { <add> mockNetworkConfigService.devicesSubjects.add("device1"); <add> mockNetworkConfigService.devicesConfigs.add(new MockDeviceConfig("v1", "v2")); <add> } <add> <add> /** <add> * Tests the result of the rest api GET when there are no configs. <add> */ <add> @Test <add> public void testEmptyConfigs() { <add> final WebResource rs = resource(); <add> final String response = rs.path("network/configuration").get(String.class); <add> <add> assertThat(response, containsString("\"devices\":{}")); <add> assertThat(response, containsString("\"links\":{}")); <add> } <add> <add> /** <add> * Tests the result of the rest api GET for a single subject with no configs. <add> */ <add> @Test <add> public void testEmptyConfig() { <add> final WebResource rs = resource(); <add> final String response = rs.path("network/configuration/devices").get(String.class); <add> <add> assertThat(response, is("{}")); <add> } <add> <add> /** <add> * Tests the result of the rest api GET for a single subject that <add> * is undefined. <add> */ <add> @Test <add> public void testNonExistentConfig() { <add> final WebResource rs = resource(); <add> <add> try { <add> final String response = rs.path("network/configuration/nosuchkey").get(String.class); <add> fail("GET of non-existent key does not produce an exception " + response); <add> } catch (UniformInterfaceException e) { <add> assertThat(e.getResponse().getStatus(), is(HttpURLConnection.HTTP_NOT_FOUND)); <add> } <add> } <add> <add> private void checkBasicAttributes(JsonValue basic) { <add> Assert.assertThat(basic.asObject().get("field1").asString(), is("v1")); <add> Assert.assertThat(basic.asObject().get("field2").asString(), is("v2")); <add> } <add> <add> /** <add> * Tests the result of the rest api GET when there is a config. <add> */ <add> @Test <add> <add> public void testConfigs() { <add> setUpConfigData(); <add> final WebResource rs = resource(); <add> final String response = rs.path("network/configuration").get(String.class); <add> <add> final JsonObject result = JsonObject.readFrom(response); <add> Assert.assertThat(result, notNullValue()); <add> <add> Assert.assertThat(result.names(), hasSize(2)); <add> <add> JsonValue devices = result.get("devices"); <add> Assert.assertThat(devices, notNullValue()); <add> <add> JsonValue device1 = devices.asObject().get("device1"); <add> Assert.assertThat(device1, notNullValue()); <add> <add> JsonValue basic = device1.asObject().get("basic"); <add> Assert.assertThat(basic, notNullValue()); <add> <add> checkBasicAttributes(basic); <add> } <add> <add> /** <add> * Tests the result of the rest api single subject key GET when <add> * there is a config. <add> */ <add> @Test <add> public void testSingleSubjectKeyConfig() { <add> setUpConfigData(); <add> final WebResource rs = resource(); <add> final String response = rs.path("network/configuration/devices").get(String.class); <add> <add> final JsonObject result = JsonObject.readFrom(response); <add> Assert.assertThat(result, notNullValue()); <add> <add> Assert.assertThat(result.names(), hasSize(1)); <add> <add> JsonValue device1 = result.asObject().get("device1"); <add> Assert.assertThat(device1, notNullValue()); <add> <add> JsonValue basic = device1.asObject().get("basic"); <add> Assert.assertThat(basic, notNullValue()); <add> <add> checkBasicAttributes(basic); <add> } <add> <add> /** <add> * Tests the result of the rest api single subject GET when <add> * there is a config. <add> */ <add> @Test <add> public void testSingleSubjectConfig() { <add> setUpConfigData(); <add> final WebResource rs = resource(); <add> final String response = <add> rs.path("network/configuration/devices/device1") <add> .get(String.class); <add> <add> final JsonObject result = JsonObject.readFrom(response); <add> Assert.assertThat(result, notNullValue()); <add> <add> Assert.assertThat(result.names(), hasSize(1)); <add> <add> JsonValue basic = result.asObject().get("basic"); <add> Assert.assertThat(basic, notNullValue()); <add> <add> checkBasicAttributes(basic); <add> } <add> <add> /** <add> * Tests the result of the rest api single subject single config GET when <add> * there is a config. <add> */ <add> @Test <add> public void testSingleSubjectSingleConfig() { <add> setUpConfigData(); <add> final WebResource rs = resource(); <add> final String response = <add> rs.path("network/configuration/devices/device1/basic") <add> .get(String.class); <add> <add> final JsonObject result = JsonObject.readFrom(response); <add> Assert.assertThat(result, notNullValue()); <add> <add> Assert.assertThat(result.names(), hasSize(2)); <add> <add> checkBasicAttributes(result); <add> } <add> <add> // TODO: Add test for DELETE and POST <add>}
Java
apache-2.0
096f054d562978a768d346f66b50332c686919a0
0
apache/solr,apache/solr,apache/solr,apache/solr,apache/solr
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.codecs.lucene90; import java.io.IOException; import java.util.Collections; import java.util.Map; import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.codecs.DocValuesFormat; import org.apache.lucene.codecs.FieldInfosFormat; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.DocValuesType; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.FieldInfos; import org.apache.lucene.index.IndexFileNames; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.SegmentInfo; import org.apache.lucene.index.VectorValues; import org.apache.lucene.index.VectorValues.SearchStrategy; import org.apache.lucene.store.ChecksumIndexInput; import org.apache.lucene.store.DataOutput; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; /** * Lucene 9.0 Field Infos format. * * <p>Field names are stored in the field info file, with suffix <code>.fnm</code>. * * <p>FieldInfos (.fnm) --&gt; Header,FieldsCount, &lt;FieldName,FieldNumber, * FieldBits,DocValuesBits,DocValuesGen,Attributes,DimensionCount,DimensionNumBytes&gt; * <sup>FieldsCount</sup>,Footer * * <p>Data types: * * <ul> * <li>Header --&gt; {@link CodecUtil#checkIndexHeader IndexHeader} * <li>FieldsCount --&gt; {@link DataOutput#writeVInt VInt} * <li>FieldName --&gt; {@link DataOutput#writeString String} * <li>FieldBits, IndexOptions, DocValuesBits --&gt; {@link DataOutput#writeByte Byte} * <li>FieldNumber, DimensionCount, DimensionNumBytes --&gt; {@link DataOutput#writeInt VInt} * <li>Attributes --&gt; {@link DataOutput#writeMapOfStrings Map&lt;String,String&gt;} * <li>DocValuesGen --&gt; {@link DataOutput#writeLong(long) Int64} * <li>Footer --&gt; {@link CodecUtil#writeFooter CodecFooter} * </ul> * * Field Descriptions: * * <ul> * <li>FieldsCount: the number of fields in this file. * <li>FieldName: name of the field as a UTF-8 String. * <li>FieldNumber: the field's number. Note that unlike previous versions of Lucene, the fields * are not numbered implicitly by their order in the file, instead explicitly. * <li>FieldBits: a byte containing field options. * <ul> * <li>The low order bit (0x1) is one for fields that have term vectors stored, and zero for * fields without term vectors. * <li>If the second lowest order-bit is set (0x2), norms are omitted for the indexed field. * <li>If the third lowest-order bit is set (0x4), payloads are stored for the indexed * field. * </ul> * <li>IndexOptions: a byte containing index options. * <ul> * <li>0: not indexed * <li>1: indexed as DOCS_ONLY * <li>2: indexed as DOCS_AND_FREQS * <li>3: indexed as DOCS_AND_FREQS_AND_POSITIONS * <li>4: indexed as DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS * </ul> * <li>DocValuesBits: a byte containing per-document value types. The type recorded as two * four-bit integers, with the high-order bits representing <code>norms</code> options, and * the low-order bits representing {@code DocValues} options. Each four-bit integer can be * decoded as such: * <ul> * <li>0: no DocValues for this field. * <li>1: NumericDocValues. ({@link DocValuesType#NUMERIC}) * <li>2: BinaryDocValues. ({@code DocValuesType#BINARY}) * <li>3: SortedDocValues. ({@code DocValuesType#SORTED}) * </ul> * <li>DocValuesGen is the generation count of the field's DocValues. If this is -1, there are no * DocValues updates to that field. Anything above zero means there are updates stored by * {@link DocValuesFormat}. * <li>Attributes: a key-value map of codec-private attributes. * <li>PointDimensionCount, PointNumBytes: these are non-zero only if the field is indexed as * points, e.g. using {@link org.apache.lucene.document.LongPoint} * <li>VectorDimension: it is non-zero if the field is indexed as vectors. * <li>VectorDistFunction: a byte containing distance function used for similarity calculation. * <ul> * <li>0: no distance function is defined for this field. * <li>1: EUCLIDEAN_HNSW distance. ({@link SearchStrategy#EUCLIDEAN_HNSW}) * <li>2: DOT_PRODUCT_HNSW score. ({@link SearchStrategy#DOT_PRODUCT_HNSW}) * </ul> * </ul> * * @lucene.experimental */ public final class Lucene90FieldInfosFormat extends FieldInfosFormat { /** Sole constructor. */ public Lucene90FieldInfosFormat() {} @Override public FieldInfos read( Directory directory, SegmentInfo segmentInfo, String segmentSuffix, IOContext context) throws IOException { final String fileName = IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, EXTENSION); try (ChecksumIndexInput input = directory.openChecksumInput(fileName, context)) { Throwable priorE = null; FieldInfo infos[] = null; try { int version = CodecUtil.checkIndexHeader( input, Lucene90FieldInfosFormat.CODEC_NAME, Lucene90FieldInfosFormat.FORMAT_START, Lucene90FieldInfosFormat.FORMAT_CURRENT, segmentInfo.getId(), segmentSuffix); final int size = input.readVInt(); // read in the size infos = new FieldInfo[size]; // previous field's attribute map, we share when possible: Map<String, String> lastAttributes = Collections.emptyMap(); for (int i = 0; i < size; i++) { String name = input.readString(); final int fieldNumber = input.readVInt(); if (fieldNumber < 0) { throw new CorruptIndexException( "invalid field number for field: " + name + ", fieldNumber=" + fieldNumber, input); } byte bits = input.readByte(); boolean storeTermVector = (bits & STORE_TERMVECTOR) != 0; boolean omitNorms = (bits & OMIT_NORMS) != 0; boolean storePayloads = (bits & STORE_PAYLOADS) != 0; boolean isSoftDeletesField = (bits & SOFT_DELETES_FIELD) != 0; final IndexOptions indexOptions = getIndexOptions(input, input.readByte()); // DV Types are packed in one byte final DocValuesType docValuesType = getDocValuesType(input, input.readByte()); final long dvGen = input.readLong(); Map<String, String> attributes = input.readMapOfStrings(); // just use the last field's map if its the same if (attributes.equals(lastAttributes)) { attributes = lastAttributes; } lastAttributes = attributes; int pointDataDimensionCount = input.readVInt(); int pointNumBytes; int pointIndexDimensionCount = pointDataDimensionCount; if (pointDataDimensionCount != 0) { pointIndexDimensionCount = input.readVInt(); pointNumBytes = input.readVInt(); } else { pointNumBytes = 0; } final int vectorDimension = input.readVInt(); final VectorValues.SearchStrategy vectorDistFunc = getDistFunc(input, input.readByte()); try { infos[i] = new FieldInfo( name, fieldNumber, storeTermVector, omitNorms, storePayloads, indexOptions, docValuesType, dvGen, attributes, pointDataDimensionCount, pointIndexDimensionCount, pointNumBytes, vectorDimension, vectorDistFunc, isSoftDeletesField); infos[i].checkConsistency(); } catch (IllegalStateException e) { throw new CorruptIndexException( "invalid fieldinfo for field: " + name + ", fieldNumber=" + fieldNumber, input, e); } } } catch (Throwable exception) { priorE = exception; } finally { CodecUtil.checkFooter(input, priorE); } return new FieldInfos(infos); } } static { // We "mirror" DocValues enum values with the constants below; let's try to ensure if we add a // new DocValuesType while this format is // still used for writing, we remember to fix this encoding: assert DocValuesType.values().length == 6; } private static byte docValuesByte(DocValuesType type) { switch (type) { case NONE: return 0; case NUMERIC: return 1; case BINARY: return 2; case SORTED: return 3; case SORTED_SET: return 4; case SORTED_NUMERIC: return 5; default: // BUG throw new AssertionError("unhandled DocValuesType: " + type); } } private static DocValuesType getDocValuesType(IndexInput input, byte b) throws IOException { switch (b) { case 0: return DocValuesType.NONE; case 1: return DocValuesType.NUMERIC; case 2: return DocValuesType.BINARY; case 3: return DocValuesType.SORTED; case 4: return DocValuesType.SORTED_SET; case 5: return DocValuesType.SORTED_NUMERIC; default: throw new CorruptIndexException("invalid docvalues byte: " + b, input); } } private static VectorValues.SearchStrategy getDistFunc(IndexInput input, byte b) throws IOException { if (b < 0 || b >= VectorValues.SearchStrategy.values().length) { throw new CorruptIndexException("invalid distance function: " + b, input); } return VectorValues.SearchStrategy.values()[b]; } static { // We "mirror" IndexOptions enum values with the constants below; let's try to ensure if we add // a new IndexOption while this format is // still used for writing, we remember to fix this encoding: assert IndexOptions.values().length == 5; } private static byte indexOptionsByte(IndexOptions indexOptions) { switch (indexOptions) { case NONE: return 0; case DOCS: return 1; case DOCS_AND_FREQS: return 2; case DOCS_AND_FREQS_AND_POSITIONS: return 3; case DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS: return 4; default: // BUG: throw new AssertionError("unhandled IndexOptions: " + indexOptions); } } private static IndexOptions getIndexOptions(IndexInput input, byte b) throws IOException { switch (b) { case 0: return IndexOptions.NONE; case 1: return IndexOptions.DOCS; case 2: return IndexOptions.DOCS_AND_FREQS; case 3: return IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; case 4: return IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; default: // BUG throw new CorruptIndexException("invalid IndexOptions byte: " + b, input); } } @Override public void write( Directory directory, SegmentInfo segmentInfo, String segmentSuffix, FieldInfos infos, IOContext context) throws IOException { final String fileName = IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, EXTENSION); try (IndexOutput output = directory.createOutput(fileName, context)) { CodecUtil.writeIndexHeader( output, Lucene90FieldInfosFormat.CODEC_NAME, Lucene90FieldInfosFormat.FORMAT_CURRENT, segmentInfo.getId(), segmentSuffix); output.writeVInt(infos.size()); for (FieldInfo fi : infos) { fi.checkConsistency(); output.writeString(fi.name); output.writeVInt(fi.number); byte bits = 0x0; if (fi.hasVectors()) bits |= STORE_TERMVECTOR; if (fi.omitsNorms()) bits |= OMIT_NORMS; if (fi.hasPayloads()) bits |= STORE_PAYLOADS; if (fi.isSoftDeletesField()) bits |= SOFT_DELETES_FIELD; output.writeByte(bits); output.writeByte(indexOptionsByte(fi.getIndexOptions())); // pack the DV type and hasNorms in one byte output.writeByte(docValuesByte(fi.getDocValuesType())); output.writeLong(fi.getDocValuesGen()); output.writeMapOfStrings(fi.attributes()); output.writeVInt(fi.getPointDimensionCount()); if (fi.getPointDimensionCount() != 0) { output.writeVInt(fi.getPointIndexDimensionCount()); output.writeVInt(fi.getPointNumBytes()); } output.writeVInt(fi.getVectorDimension()); output.writeByte((byte) fi.getVectorSearchStrategy().ordinal()); } CodecUtil.writeFooter(output); } } /** Extension of field infos */ static final String EXTENSION = "fnm"; // Codec header static final String CODEC_NAME = "Lucene90FieldInfos"; static final int FORMAT_START = 0; static final int FORMAT_CURRENT = FORMAT_START; // Field flags static final byte STORE_TERMVECTOR = 0x1; static final byte OMIT_NORMS = 0x2; static final byte STORE_PAYLOADS = 0x4; static final byte SOFT_DELETES_FIELD = 0x8; }
lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90FieldInfosFormat.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.lucene.codecs.lucene90; import java.io.IOException; import java.util.Collections; import java.util.Map; import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.codecs.DocValuesFormat; import org.apache.lucene.codecs.FieldInfosFormat; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.DocValuesType; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.FieldInfos; import org.apache.lucene.index.IndexFileNames; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.SegmentInfo; import org.apache.lucene.index.VectorValues; import org.apache.lucene.index.VectorValues.SearchStrategy; import org.apache.lucene.store.ChecksumIndexInput; import org.apache.lucene.store.DataOutput; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; /** * Lucene 9.0 Field Infos format. * * <p>Field names are stored in the field info file, with suffix <code>.fnm</code>. * * <p>FieldInfos (.fnm) --&gt; Header,FieldsCount, &lt;FieldName,FieldNumber, * FieldBits,DocValuesBits,DocValuesGen,Attributes,DimensionCount,DimensionNumBytes&gt; * <sup>FieldsCount</sup>,Footer * * <p>Data types: * * <ul> * <li>Header --&gt; {@link CodecUtil#checkIndexHeader IndexHeader} * <li>FieldsCount --&gt; {@link DataOutput#writeVInt VInt} * <li>FieldName --&gt; {@link DataOutput#writeString String} * <li>FieldBits, IndexOptions, DocValuesBits --&gt; {@link DataOutput#writeByte Byte} * <li>FieldNumber, DimensionCount, DimensionNumBytes --&gt; {@link DataOutput#writeInt VInt} * <li>Attributes --&gt; {@link DataOutput#writeMapOfStrings Map&lt;String,String&gt;} * <li>DocValuesGen --&gt; {@link DataOutput#writeLong(long) Int64} * <li>Footer --&gt; {@link CodecUtil#writeFooter CodecFooter} * </ul> * * Field Descriptions: * * <ul> * <li>FieldsCount: the number of fields in this file. * <li>FieldName: name of the field as a UTF-8 String. * <li>FieldNumber: the field's number. Note that unlike previous versions of Lucene, the fields * are not numbered implicitly by their order in the file, instead explicitly. * <li>FieldBits: a byte containing field options. * <ul> * <li>The low order bit (0x1) is one for fields that have term vectors stored, and zero for * fields without term vectors. * <li>If the second lowest order-bit is set (0x2), norms are omitted for the indexed field. * <li>If the third lowest-order bit is set (0x4), payloads are stored for the indexed * field. * </ul> * <li>IndexOptions: a byte containing index options. * <ul> * <li>0: not indexed * <li>1: indexed as DOCS_ONLY * <li>2: indexed as DOCS_AND_FREQS * <li>3: indexed as DOCS_AND_FREQS_AND_POSITIONS * <li>4: indexed as DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS * </ul> * <li>DocValuesBits: a byte containing per-document value types. The type recorded as two * four-bit integers, with the high-order bits representing <code>norms</code> options, and * the low-order bits representing {@code DocValues} options. Each four-bit integer can be * decoded as such: * <ul> * <li>0: no DocValues for this field. * <li>1: NumericDocValues. ({@link DocValuesType#NUMERIC}) * <li>2: BinaryDocValues. ({@code DocValuesType#BINARY}) * <li>3: SortedDocValues. ({@code DocValuesType#SORTED}) * </ul> * <li>DocValuesGen is the generation count of the field's DocValues. If this is -1, there are no * DocValues updates to that field. Anything above zero means there are updates stored by * {@link DocValuesFormat}. * <li>Attributes: a key-value map of codec-private attributes. * <li>PointDimensionCount, PointNumBytes: these are non-zero only if the field is indexed as * points, e.g. using {@link org.apache.lucene.document.LongPoint} * <li>VectorDimension: it is non-zero if the field is indexed as vectors. * <li>VectorDistFunction: a byte containing distance function used for similarity calculation. * <ul> * <li>0: no distance function is defined for this field. * <li>1: EUCLIDEAN_HNSW distance. ({@link SearchStrategy#EUCLIDEAN_HNSW}) * <li>2: DOT_PRODUCT_HNSW score. ({@link SearchStrategy#DOT_PRODUCT_HNSW}) * </ul> * </ul> * * @lucene.experimental */ public final class Lucene90FieldInfosFormat extends FieldInfosFormat { /** Sole constructor. */ public Lucene90FieldInfosFormat() {} @Override public FieldInfos read( Directory directory, SegmentInfo segmentInfo, String segmentSuffix, IOContext context) throws IOException { final String fileName = IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, EXTENSION); try (ChecksumIndexInput input = directory.openChecksumInput(fileName, context)) { Throwable priorE = null; FieldInfo infos[] = null; try { int version = CodecUtil.checkIndexHeader( input, Lucene90FieldInfosFormat.CODEC_NAME, Lucene90FieldInfosFormat.FORMAT_START, Lucene90FieldInfosFormat.FORMAT_CURRENT, segmentInfo.getId(), segmentSuffix); final int size = input.readVInt(); // read in the size infos = new FieldInfo[size]; // previous field's attribute map, we share when possible: Map<String, String> lastAttributes = Collections.emptyMap(); for (int i = 0; i < size; i++) { String name = input.readString(); final int fieldNumber = input.readVInt(); if (fieldNumber < 0) { throw new CorruptIndexException( "invalid field number for field: " + name + ", fieldNumber=" + fieldNumber, input); } byte bits = input.readByte(); boolean storeTermVector = (bits & STORE_TERMVECTOR) != 0; boolean omitNorms = (bits & OMIT_NORMS) != 0; boolean storePayloads = (bits & STORE_PAYLOADS) != 0; boolean isSoftDeletesField = (bits & SOFT_DELETES_FIELD) != 0; final IndexOptions indexOptions = getIndexOptions(input, input.readByte()); // DV Types are packed in one byte final DocValuesType docValuesType = getDocValuesType(input, input.readByte()); final long dvGen = input.readLong(); Map<String, String> attributes = input.readMapOfStrings(); // just use the last field's map if its the same if (attributes.equals(lastAttributes)) { attributes = lastAttributes; } lastAttributes = attributes; int pointDataDimensionCount = input.readVInt(); int pointNumBytes; int pointIndexDimensionCount = pointDataDimensionCount; if (pointDataDimensionCount != 0) { if (version >= Lucene90FieldInfosFormat.FORMAT_SELECTIVE_INDEXING) { pointIndexDimensionCount = input.readVInt(); } pointNumBytes = input.readVInt(); } else { pointNumBytes = 0; } final int vectorDimension = input.readVInt(); final VectorValues.SearchStrategy vectorDistFunc = getDistFunc(input, input.readByte()); try { infos[i] = new FieldInfo( name, fieldNumber, storeTermVector, omitNorms, storePayloads, indexOptions, docValuesType, dvGen, attributes, pointDataDimensionCount, pointIndexDimensionCount, pointNumBytes, vectorDimension, vectorDistFunc, isSoftDeletesField); infos[i].checkConsistency(); } catch (IllegalStateException e) { throw new CorruptIndexException( "invalid fieldinfo for field: " + name + ", fieldNumber=" + fieldNumber, input, e); } } } catch (Throwable exception) { priorE = exception; } finally { CodecUtil.checkFooter(input, priorE); } return new FieldInfos(infos); } } static { // We "mirror" DocValues enum values with the constants below; let's try to ensure if we add a // new DocValuesType while this format is // still used for writing, we remember to fix this encoding: assert DocValuesType.values().length == 6; } private static byte docValuesByte(DocValuesType type) { switch (type) { case NONE: return 0; case NUMERIC: return 1; case BINARY: return 2; case SORTED: return 3; case SORTED_SET: return 4; case SORTED_NUMERIC: return 5; default: // BUG throw new AssertionError("unhandled DocValuesType: " + type); } } private static DocValuesType getDocValuesType(IndexInput input, byte b) throws IOException { switch (b) { case 0: return DocValuesType.NONE; case 1: return DocValuesType.NUMERIC; case 2: return DocValuesType.BINARY; case 3: return DocValuesType.SORTED; case 4: return DocValuesType.SORTED_SET; case 5: return DocValuesType.SORTED_NUMERIC; default: throw new CorruptIndexException("invalid docvalues byte: " + b, input); } } private static VectorValues.SearchStrategy getDistFunc(IndexInput input, byte b) throws IOException { if (b < 0 || b >= VectorValues.SearchStrategy.values().length) { throw new CorruptIndexException("invalid distance function: " + b, input); } return VectorValues.SearchStrategy.values()[b]; } static { // We "mirror" IndexOptions enum values with the constants below; let's try to ensure if we add // a new IndexOption while this format is // still used for writing, we remember to fix this encoding: assert IndexOptions.values().length == 5; } private static byte indexOptionsByte(IndexOptions indexOptions) { switch (indexOptions) { case NONE: return 0; case DOCS: return 1; case DOCS_AND_FREQS: return 2; case DOCS_AND_FREQS_AND_POSITIONS: return 3; case DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS: return 4; default: // BUG: throw new AssertionError("unhandled IndexOptions: " + indexOptions); } } private static IndexOptions getIndexOptions(IndexInput input, byte b) throws IOException { switch (b) { case 0: return IndexOptions.NONE; case 1: return IndexOptions.DOCS; case 2: return IndexOptions.DOCS_AND_FREQS; case 3: return IndexOptions.DOCS_AND_FREQS_AND_POSITIONS; case 4: return IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS; default: // BUG throw new CorruptIndexException("invalid IndexOptions byte: " + b, input); } } @Override public void write( Directory directory, SegmentInfo segmentInfo, String segmentSuffix, FieldInfos infos, IOContext context) throws IOException { final String fileName = IndexFileNames.segmentFileName(segmentInfo.name, segmentSuffix, EXTENSION); try (IndexOutput output = directory.createOutput(fileName, context)) { CodecUtil.writeIndexHeader( output, Lucene90FieldInfosFormat.CODEC_NAME, Lucene90FieldInfosFormat.FORMAT_CURRENT, segmentInfo.getId(), segmentSuffix); output.writeVInt(infos.size()); for (FieldInfo fi : infos) { fi.checkConsistency(); output.writeString(fi.name); output.writeVInt(fi.number); byte bits = 0x0; if (fi.hasVectors()) bits |= STORE_TERMVECTOR; if (fi.omitsNorms()) bits |= OMIT_NORMS; if (fi.hasPayloads()) bits |= STORE_PAYLOADS; if (fi.isSoftDeletesField()) bits |= SOFT_DELETES_FIELD; output.writeByte(bits); output.writeByte(indexOptionsByte(fi.getIndexOptions())); // pack the DV type and hasNorms in one byte output.writeByte(docValuesByte(fi.getDocValuesType())); output.writeLong(fi.getDocValuesGen()); output.writeMapOfStrings(fi.attributes()); output.writeVInt(fi.getPointDimensionCount()); if (fi.getPointDimensionCount() != 0) { output.writeVInt(fi.getPointIndexDimensionCount()); output.writeVInt(fi.getPointNumBytes()); } output.writeVInt(fi.getVectorDimension()); output.writeByte((byte) fi.getVectorSearchStrategy().ordinal()); } CodecUtil.writeFooter(output); } } /** Extension of field infos */ static final String EXTENSION = "fnm"; // Codec header static final String CODEC_NAME = "Lucene90FieldInfos"; static final int FORMAT_START = 0; static final int FORMAT_SOFT_DELETES = 1; static final int FORMAT_SELECTIVE_INDEXING = 2; static final int FORMAT_CURRENT = FORMAT_SELECTIVE_INDEXING; // Field flags static final byte STORE_TERMVECTOR = 0x1; static final byte OMIT_NORMS = 0x2; static final byte STORE_PAYLOADS = 0x4; static final byte SOFT_DELETES_FIELD = 0x8; }
LUCENE-9705: Reset internal version in Lucene90FieldInfosFormat. (#2339) Since this is a fresh format, we can remove older version logic and reset the internal version to 0.
lucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90FieldInfosFormat.java
LUCENE-9705: Reset internal version in Lucene90FieldInfosFormat. (#2339)
<ide><path>ucene/core/src/java/org/apache/lucene/codecs/lucene90/Lucene90FieldInfosFormat.java <ide> int pointNumBytes; <ide> int pointIndexDimensionCount = pointDataDimensionCount; <ide> if (pointDataDimensionCount != 0) { <del> if (version >= Lucene90FieldInfosFormat.FORMAT_SELECTIVE_INDEXING) { <del> pointIndexDimensionCount = input.readVInt(); <del> } <add> pointIndexDimensionCount = input.readVInt(); <ide> pointNumBytes = input.readVInt(); <ide> } else { <ide> pointNumBytes = 0; <ide> // Codec header <ide> static final String CODEC_NAME = "Lucene90FieldInfos"; <ide> static final int FORMAT_START = 0; <del> static final int FORMAT_SOFT_DELETES = 1; <del> static final int FORMAT_SELECTIVE_INDEXING = 2; <del> static final int FORMAT_CURRENT = FORMAT_SELECTIVE_INDEXING; <add> static final int FORMAT_CURRENT = FORMAT_START; <ide> <ide> // Field flags <ide> static final byte STORE_TERMVECTOR = 0x1;
Java
apache-2.0
4ced1775b5da8dae5963a89e4776d99bad37cd41
0
YolandaMDavis/nifi,patricker/nifi,m-hogue/nifi,aperepel/nifi,aperepel/nifi,pvillard31/nifi,YolandaMDavis/nifi,YolandaMDavis/nifi,pvillard31/nifi,m-hogue/nifi,mcgilman/nifi,mattyb149/nifi,trixpan/nifi,mcgilman/nifi,mcgilman/nifi,trixpan/nifi,MikeThomsen/nifi,pvillard31/nifi,mattyb149/nifi,m-hogue/nifi,trixpan/nifi,mcgilman/nifi,YolandaMDavis/nifi,alopresto/nifi,patricker/nifi,m-hogue/nifi,aperepel/nifi,mcgilman/nifi,patricker/nifi,MikeThomsen/nifi,alopresto/nifi,MikeThomsen/nifi,mcgilman/nifi,jfrazee/nifi,mattyb149/nifi,mattyb149/nifi,mattyb149/nifi,MikeThomsen/nifi,alopresto/nifi,patricker/nifi,jfrazee/nifi,m-hogue/nifi,jfrazee/nifi,alopresto/nifi,patricker/nifi,pvillard31/nifi,alopresto/nifi,jfrazee/nifi,alopresto/nifi,jfrazee/nifi,pvillard31/nifi,trixpan/nifi,pvillard31/nifi,aperepel/nifi,jfrazee/nifi,YolandaMDavis/nifi,YolandaMDavis/nifi,m-hogue/nifi,jfrazee/nifi,aperepel/nifi,trixpan/nifi,YolandaMDavis/nifi,mattyb149/nifi,aperepel/nifi,MikeThomsen/nifi,MikeThomsen/nifi,mattyb149/nifi,patricker/nifi,trixpan/nifi,m-hogue/nifi,jfrazee/nifi,pvillard31/nifi,MikeThomsen/nifi,pvillard31/nifi,alopresto/nifi,mcgilman/nifi,patricker/nifi
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.processors.standard; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.nifi.annotation.behavior.EventDriven; import org.apache.nifi.annotation.behavior.InputRequirement; import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; import org.apache.nifi.annotation.behavior.SideEffectFree; import org.apache.nifi.annotation.behavior.SupportsBatching; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.expression.ExpressionLanguageScope; import org.apache.nifi.flowfile.FlowFile; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.processor.AbstractProcessor; import org.apache.nifi.processor.DataUnit; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; import org.apache.nifi.processor.Relationship; import org.apache.nifi.processor.exception.ProcessException; import org.apache.nifi.processor.io.OutputStreamCallback; import org.apache.nifi.processor.io.StreamCallback; import org.apache.nifi.processor.util.StandardValidators; import org.apache.nifi.stream.io.StreamUtils; import org.apache.nifi.util.StopWatch; @EventDriven @SideEffectFree @SupportsBatching @Tags({"binary", "discard", "keep"}) @InputRequirement(Requirement.INPUT_REQUIRED) @CapabilityDescription("Discard byte range at the start and end or all content of a binary file.") public class ModifyBytes extends AbstractProcessor { // Relationships public static final Relationship REL_SUCCESS = new Relationship.Builder() .name("success") .description("Processed flowfiles.") .build(); private final Set<Relationship> relationships; public static final PropertyDescriptor START_OFFSET = new PropertyDescriptor.Builder() .name("Start Offset") .displayName("Start Offset") .description("Number of bytes removed at the beginning of the file.") .required(true) .addValidator(StandardValidators.DATA_SIZE_VALIDATOR) .defaultValue("0 B") .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) .build(); public static final PropertyDescriptor END_OFFSET = new PropertyDescriptor.Builder() .name("End Offset") .displayName("End Offset") .description("Number of bytes removed at the end of the file.") .required(true) .addValidator(StandardValidators.DATA_SIZE_VALIDATOR) .defaultValue("0 B") .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) .build(); public static final PropertyDescriptor REMOVE_ALL = new PropertyDescriptor.Builder() .name("Remove All Content") .displayName("Remove All Content") .description("Remove all content from the FlowFile superseding Start Offset and End Offset properties.") .required(true) .allowableValues("true", "false") .defaultValue("false") .build(); private final List<PropertyDescriptor> propDescriptors; public ModifyBytes() { HashSet<Relationship> r = new HashSet<>(); r.add(REL_SUCCESS); relationships = Collections.unmodifiableSet(r); ArrayList<PropertyDescriptor> pds = new ArrayList<>(); pds.add(START_OFFSET); pds.add(END_OFFSET); pds.add(REMOVE_ALL); propDescriptors = Collections.unmodifiableList(pds); } @Override public Set<Relationship> getRelationships() { return relationships; } @Override protected List<PropertyDescriptor> getSupportedPropertyDescriptors() { return propDescriptors; } @Override public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException { FlowFile ff = session.get(); if (null == ff) { return; } final ComponentLog logger = getLogger(); final long startOffset = context.getProperty(START_OFFSET).evaluateAttributeExpressions(ff).asDataSize(DataUnit.B).longValue(); final long endOffset = context.getProperty(END_OFFSET).evaluateAttributeExpressions(ff).asDataSize(DataUnit.B).longValue(); final boolean removeAll = context.getProperty(REMOVE_ALL).asBoolean(); final long newFileSize = removeAll ? 0L : ff.getSize() - startOffset - endOffset; final StopWatch stopWatch = new StopWatch(true); if (newFileSize <= 0) { ff = session.write(ff, new OutputStreamCallback() { @Override public void process(final OutputStream out) throws IOException { out.write(new byte[0]); } }); } else { ff = session.write(ff, new StreamCallback() { @Override public void process(final InputStream in, final OutputStream out) throws IOException { in.skip(startOffset); StreamUtils.copy(in, out, newFileSize); } }); } logger.info("Transferred {} to 'success'", new Object[]{ff}); session.getProvenanceReporter().modifyContent(ff, stopWatch.getElapsed(TimeUnit.MILLISECONDS)); session.transfer(ff, REL_SUCCESS); } }
nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ModifyBytes.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.nifi.processors.standard; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.nifi.annotation.behavior.EventDriven; import org.apache.nifi.annotation.behavior.InputRequirement; import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; import org.apache.nifi.annotation.behavior.SideEffectFree; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.expression.ExpressionLanguageScope; import org.apache.nifi.flowfile.FlowFile; import org.apache.nifi.logging.ComponentLog; import org.apache.nifi.processor.AbstractProcessor; import org.apache.nifi.processor.DataUnit; import org.apache.nifi.processor.ProcessContext; import org.apache.nifi.processor.ProcessSession; import org.apache.nifi.processor.Relationship; import org.apache.nifi.processor.exception.ProcessException; import org.apache.nifi.processor.io.OutputStreamCallback; import org.apache.nifi.processor.io.StreamCallback; import org.apache.nifi.processor.util.StandardValidators; import org.apache.nifi.stream.io.StreamUtils; import org.apache.nifi.util.StopWatch; @EventDriven @SideEffectFree @Tags({"binary", "discard", "keep"}) @InputRequirement(Requirement.INPUT_REQUIRED) @CapabilityDescription("Discard byte range at the start and end or all content of a binary file.") public class ModifyBytes extends AbstractProcessor { // Relationships public static final Relationship REL_SUCCESS = new Relationship.Builder() .name("success") .description("Processed flowfiles.") .build(); private final Set<Relationship> relationships; public static final PropertyDescriptor START_OFFSET = new PropertyDescriptor.Builder() .name("Start Offset") .description("Number of bytes removed at the beginning of the file.") .required(true) .addValidator(StandardValidators.DATA_SIZE_VALIDATOR) .defaultValue("0 B") .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) .build(); public static final PropertyDescriptor END_OFFSET = new PropertyDescriptor.Builder() .name("End Offset") .description("Number of bytes removed at the end of the file.") .required(true) .addValidator(StandardValidators.DATA_SIZE_VALIDATOR) .defaultValue("0 B") .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) .build(); public static final PropertyDescriptor REMOVE_ALL = new PropertyDescriptor.Builder() .name("Remove All Content") .description("Remove all content from the FlowFile superseding Start Offset and End Offset properties.") .required(true) .allowableValues("true", "false") .defaultValue("false") .build(); private final List<PropertyDescriptor> propDescriptors; public ModifyBytes() { HashSet<Relationship> r = new HashSet<>(); r.add(REL_SUCCESS); relationships = Collections.unmodifiableSet(r); ArrayList<PropertyDescriptor> pds = new ArrayList<>(); pds.add(START_OFFSET); pds.add(END_OFFSET); pds.add(REMOVE_ALL); propDescriptors = Collections.unmodifiableList(pds); } @Override public Set<Relationship> getRelationships() { return relationships; } @Override protected List<PropertyDescriptor> getSupportedPropertyDescriptors() { return propDescriptors; } @Override public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException { FlowFile ff = session.get(); if (null == ff) { return; } final ComponentLog logger = getLogger(); final long startOffset = context.getProperty(START_OFFSET).evaluateAttributeExpressions(ff).asDataSize(DataUnit.B).longValue(); final long endOffset = context.getProperty(END_OFFSET).evaluateAttributeExpressions(ff).asDataSize(DataUnit.B).longValue(); final boolean removeAll = context.getProperty(REMOVE_ALL).asBoolean(); final long newFileSize = removeAll ? 0L : ff.getSize() - startOffset - endOffset; final StopWatch stopWatch = new StopWatch(true); if (newFileSize <= 0) { ff = session.write(ff, new OutputStreamCallback() { @Override public void process(final OutputStream out) throws IOException { out.write(new byte[0]); } }); } else { ff = session.write(ff, new StreamCallback() { @Override public void process(final InputStream in, final OutputStream out) throws IOException { in.skip(startOffset); StreamUtils.copy(in, out, newFileSize); } }); } logger.info("Transferred {} to 'success'", new Object[]{ff}); session.getProvenanceReporter().modifyContent(ff, stopWatch.getElapsed(TimeUnit.MILLISECONDS)); session.transfer(ff, REL_SUCCESS); } }
NIFI-7487 - Added batch support and displayName to ModifyBytes processor Signed-off-by: Pierre Villard <[email protected]> This closes #4302.
nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ModifyBytes.java
NIFI-7487 - Added batch support and displayName to ModifyBytes processor
<ide><path>ifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/main/java/org/apache/nifi/processors/standard/ModifyBytes.java <ide> import org.apache.nifi.annotation.behavior.InputRequirement; <ide> import org.apache.nifi.annotation.behavior.InputRequirement.Requirement; <ide> import org.apache.nifi.annotation.behavior.SideEffectFree; <add>import org.apache.nifi.annotation.behavior.SupportsBatching; <ide> import org.apache.nifi.annotation.documentation.CapabilityDescription; <ide> import org.apache.nifi.annotation.documentation.Tags; <ide> import org.apache.nifi.components.PropertyDescriptor; <ide> <ide> @EventDriven <ide> @SideEffectFree <add>@SupportsBatching <ide> @Tags({"binary", "discard", "keep"}) <ide> @InputRequirement(Requirement.INPUT_REQUIRED) <ide> @CapabilityDescription("Discard byte range at the start and end or all content of a binary file.") <ide> private final Set<Relationship> relationships; <ide> public static final PropertyDescriptor START_OFFSET = new PropertyDescriptor.Builder() <ide> .name("Start Offset") <add> .displayName("Start Offset") <ide> .description("Number of bytes removed at the beginning of the file.") <ide> .required(true) <ide> .addValidator(StandardValidators.DATA_SIZE_VALIDATOR) <ide> .build(); <ide> public static final PropertyDescriptor END_OFFSET = new PropertyDescriptor.Builder() <ide> .name("End Offset") <add> .displayName("End Offset") <ide> .description("Number of bytes removed at the end of the file.") <ide> .required(true) <ide> .addValidator(StandardValidators.DATA_SIZE_VALIDATOR) <ide> .build(); <ide> public static final PropertyDescriptor REMOVE_ALL = new PropertyDescriptor.Builder() <ide> .name("Remove All Content") <add> .displayName("Remove All Content") <ide> .description("Remove all content from the FlowFile superseding Start Offset and End Offset properties.") <ide> .required(true) <ide> .allowableValues("true", "false")
Java
apache-2.0
89c90d0e2789296f5859648927893ca666328f35
0
googleads/googleads-ima-android
package com.google.ads.interactivemedia.v3.samples.videoplayerapp; import android.app.UiModeManager; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.google.android.gms.cast.framework.CastButtonFactory; /** Main Activity. */ public class MyActivity extends AppCompatActivity implements VideoListFragment.OnVideoSelectedListener, VideoListFragment.OnVideoListFragmentResumedListener, VideoFragment.OnVideoFragmentViewCreatedListener { private static final String VIDEO_PLAYLIST_FRAGMENT_TAG = "video_playlist_fragment_tag"; private static final String VIDEO_EXAMPLE_FRAGMENT_TAG = "video_example_fragment_tag"; private CastApplication castApplication; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); // The video list fragment won't exist for phone layouts, so add it dynamically so we can // .replace() it once the user selects a video. FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag(VIDEO_PLAYLIST_FRAGMENT_TAG) == null) { VideoListFragment videoListFragment = new VideoListFragment(); getSupportFragmentManager() .beginTransaction() .add(R.id.video_example_container, videoListFragment, VIDEO_PLAYLIST_FRAGMENT_TAG) .commit(); } UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE); if (uiModeManager.getCurrentModeType() != Configuration.UI_MODE_TYPE_TELEVISION) { // Only create a cast application on devices that support cast. castApplication = new CastApplication(this); } orientAppUi(); } @Override protected void onResume() { super.onResume(); if (castApplication != null) { castApplication.onResume(); } } @Override protected void onPause() { super.onPause(); if (castApplication != null) { castApplication.onPause(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.my, menu); CastButtonFactory.setUpMediaRouteButton( getApplicationContext(), menu, R.id.media_route_menu_item); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return super.onOptionsItemSelected(item); } @Override public void onConfigurationChanged(Configuration configuration) { super.onConfigurationChanged(configuration); orientAppUi(); } private void orientAppUi() { int orientation = getResources().getConfiguration().orientation; boolean isLandscape = (orientation == Configuration.ORIENTATION_LANDSCAPE); // Hide the non-video content when in landscape so the video is as large as possible. FragmentManager fragmentManager = getSupportFragmentManager(); VideoFragment videoFragment = (VideoFragment) fragmentManager.findFragmentByTag(VIDEO_EXAMPLE_FRAGMENT_TAG); Fragment videoListFragment = fragmentManager.findFragmentByTag(VIDEO_PLAYLIST_FRAGMENT_TAG); if (videoFragment != null) { // If the video playlist is onscreen (tablets) then hide that fragment. if (videoListFragment != null) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if (isLandscape) { fragmentTransaction.hide(videoListFragment); } else { fragmentTransaction.show(videoListFragment); } fragmentTransaction.commit(); } videoFragment.makeFullscreen(isLandscape); if (isLandscape) { hideStatusBar(); } else { showStatusBar(); } } else { // If returning to the list from a fullscreen video, check if the video // list fragment exists and is hidden. If so, show it. if (videoListFragment != null && videoListFragment.isHidden()) { fragmentManager.beginTransaction().show(videoListFragment).commit(); showStatusBar(); } } } @Override public void onVideoSelected(VideoItem videoItem) { VideoFragment videoFragment = (VideoFragment) getSupportFragmentManager().findFragmentByTag(VIDEO_EXAMPLE_FRAGMENT_TAG); // Add the video fragment if it's missing (phone form factor), but only if the user // manually selected the video. if (videoFragment == null) { VideoListFragment videoListFragment = (VideoListFragment) getSupportFragmentManager().findFragmentByTag(VIDEO_PLAYLIST_FRAGMENT_TAG); int videoPlaylistFragmentId = videoListFragment.getId(); videoFragment = new VideoFragment(); getSupportFragmentManager() .beginTransaction() .replace(videoPlaylistFragmentId, videoFragment, VIDEO_EXAMPLE_FRAGMENT_TAG) .addToBackStack(null) .commit(); } videoFragment.loadVideo(videoItem); if (castApplication != null) { castApplication.setVideoFragment(videoFragment); } invalidateOptionsMenu(); orientAppUi(); } @Override public void onVideoListFragmentResumed() { invalidateOptionsMenu(); orientAppUi(); } @Override public void onVideoFragmentViewCreated() { orientAppUi(); } private void hideStatusBar() { if (Build.VERSION.SDK_INT >= 16) { getWindow() .getDecorView() .setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); getSupportActionBar().hide(); } } private void showStatusBar() { if (Build.VERSION.SDK_INT >= 16) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); getSupportActionBar().show(); } } }
AdvancedExample/app/src/main/java/com/google/ads/interactivemedia/v3/samples/videoplayerapp/MyActivity.java
package com.google.ads.interactivemedia.v3.samples.videoplayerapp; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.google.android.gms.cast.framework.CastButtonFactory; /** Main Activity. */ public class MyActivity extends AppCompatActivity implements VideoListFragment.OnVideoSelectedListener, VideoListFragment.OnVideoListFragmentResumedListener, VideoFragment.OnVideoFragmentViewCreatedListener { private static final String VIDEO_PLAYLIST_FRAGMENT_TAG = "video_playlist_fragment_tag"; private static final String VIDEO_EXAMPLE_FRAGMENT_TAG = "video_example_fragment_tag"; private CastApplication castApplication; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); // The video list fragment won't exist for phone layouts, so add it dynamically so we can // .replace() it once the user selects a video. FragmentManager fragmentManager = getSupportFragmentManager(); if (fragmentManager.findFragmentByTag(VIDEO_PLAYLIST_FRAGMENT_TAG) == null) { VideoListFragment videoListFragment = new VideoListFragment(); getSupportFragmentManager() .beginTransaction() .add(R.id.video_example_container, videoListFragment, VIDEO_PLAYLIST_FRAGMENT_TAG) .commit(); } castApplication = new CastApplication(this); orientAppUi(); } @Override protected void onResume() { castApplication.onResume(); super.onResume(); } @Override protected void onPause() { super.onPause(); castApplication.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.my, menu); CastButtonFactory.setUpMediaRouteButton( getApplicationContext(), menu, R.id.media_route_menu_item); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); return super.onOptionsItemSelected(item); } @Override public void onConfigurationChanged(Configuration configuration) { super.onConfigurationChanged(configuration); orientAppUi(); } private void orientAppUi() { int orientation = getResources().getConfiguration().orientation; boolean isLandscape = (orientation == Configuration.ORIENTATION_LANDSCAPE); // Hide the non-video content when in landscape so the video is as large as possible. FragmentManager fragmentManager = getSupportFragmentManager(); VideoFragment videoFragment = (VideoFragment) fragmentManager.findFragmentByTag(VIDEO_EXAMPLE_FRAGMENT_TAG); Fragment videoListFragment = fragmentManager.findFragmentByTag(VIDEO_PLAYLIST_FRAGMENT_TAG); if (videoFragment != null) { // If the video playlist is onscreen (tablets) then hide that fragment. if (videoListFragment != null) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if (isLandscape) { fragmentTransaction.hide(videoListFragment); } else { fragmentTransaction.show(videoListFragment); } fragmentTransaction.commit(); } videoFragment.makeFullscreen(isLandscape); if (isLandscape) { hideStatusBar(); } else { showStatusBar(); } } else { // If returning to the list from a fullscreen video, check if the video // list fragment exists and is hidden. If so, show it. if (videoListFragment != null && videoListFragment.isHidden()) { fragmentManager.beginTransaction().show(videoListFragment).commit(); showStatusBar(); } } } @Override public void onVideoSelected(VideoItem videoItem) { VideoFragment videoFragment = (VideoFragment) getSupportFragmentManager().findFragmentByTag(VIDEO_EXAMPLE_FRAGMENT_TAG); // Add the video fragment if it's missing (phone form factor), but only if the user // manually selected the video. if (videoFragment == null) { VideoListFragment videoListFragment = (VideoListFragment) getSupportFragmentManager().findFragmentByTag(VIDEO_PLAYLIST_FRAGMENT_TAG); int videoPlaylistFragmentId = videoListFragment.getId(); videoFragment = new VideoFragment(); getSupportFragmentManager() .beginTransaction() .replace(videoPlaylistFragmentId, videoFragment, VIDEO_EXAMPLE_FRAGMENT_TAG) .addToBackStack(null) .commit(); } videoFragment.loadVideo(videoItem); castApplication.setVideoFragment(videoFragment); invalidateOptionsMenu(); orientAppUi(); } @Override public void onVideoListFragmentResumed() { invalidateOptionsMenu(); orientAppUi(); } @Override public void onVideoFragmentViewCreated() { orientAppUi(); } private void hideStatusBar() { if (Build.VERSION.SDK_INT >= 16) { getWindow() .getDecorView() .setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); getSupportActionBar().hide(); } } private void showStatusBar() { if (Build.VERSION.SDK_INT >= 16) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE); getSupportActionBar().show(); } } }
Internal change PiperOrigin-RevId: 327457051
AdvancedExample/app/src/main/java/com/google/ads/interactivemedia/v3/samples/videoplayerapp/MyActivity.java
Internal change
<ide><path>dvancedExample/app/src/main/java/com/google/ads/interactivemedia/v3/samples/videoplayerapp/MyActivity.java <ide> package com.google.ads.interactivemedia.v3.samples.videoplayerapp; <ide> <add>import android.app.UiModeManager; <ide> import android.content.res.Configuration; <ide> import android.os.Build; <ide> import android.os.Bundle; <ide> .add(R.id.video_example_container, videoListFragment, VIDEO_PLAYLIST_FRAGMENT_TAG) <ide> .commit(); <ide> } <del> castApplication = new CastApplication(this); <add> <add> UiModeManager uiModeManager = (UiModeManager) getSystemService(UI_MODE_SERVICE); <add> if (uiModeManager.getCurrentModeType() != Configuration.UI_MODE_TYPE_TELEVISION) { <add> // Only create a cast application on devices that support cast. <add> castApplication = new CastApplication(this); <add> } <ide> orientAppUi(); <ide> } <ide> <ide> @Override <ide> protected void onResume() { <del> castApplication.onResume(); <ide> super.onResume(); <add> if (castApplication != null) { <add> castApplication.onResume(); <add> } <ide> } <ide> <ide> @Override <ide> protected void onPause() { <ide> super.onPause(); <del> castApplication.onPause(); <add> if (castApplication != null) { <add> castApplication.onPause(); <add> } <ide> } <ide> <ide> @Override <ide> .commit(); <ide> } <ide> videoFragment.loadVideo(videoItem); <del> castApplication.setVideoFragment(videoFragment); <add> <add> if (castApplication != null) { <add> castApplication.setVideoFragment(videoFragment); <add> } <add> <ide> invalidateOptionsMenu(); <ide> orientAppUi(); <ide> }
Java
mit
1d178e11c40c72ff9c90f005cca91c4a659f0185
0
TheDudeFromCI/Talantra-Old,TheDudeFromCI/WraithavensConquest
package com.wraithavens.conquest.SinglePlayer.Particles; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.Comparator; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL31; import org.lwjgl.opengl.GL33; import com.wraithavens.conquest.Launcher.WraithavensConquest; import com.wraithavens.conquest.Math.Vector2f; import com.wraithavens.conquest.Math.Vector3f; import com.wraithavens.conquest.Math.Vector4f; import com.wraithavens.conquest.SinglePlayer.RenderHelpers.Camera; import com.wraithavens.conquest.SinglePlayer.RenderHelpers.ShaderProgram; public class ParticleBatch{ private static final boolean SortParticles = false; private final int vbo; private final int particleBuffer; private final ShaderProgram shader; private FloatBuffer particleData; private final int offsetAttribLocation; private final int scaleAttribLocation; private final int colorAttribLocation; private int maxParticleCount; private final ArrayList<Particle> particles = new ArrayList(maxParticleCount); private final Comparator particleSorter = new Comparator<Particle>(){ public int compare(Particle a, Particle b){ return a.getCameraDistance()==b.getCameraDistance()?0:a.getCameraDistance()<b.getCameraDistance()?1 :-1; } }; private final Camera camera; private final ArrayList<ParticleEngine> engines = new ArrayList(); public ParticleBatch(Camera camera){ this.camera = camera; maxParticleCount = WraithavensConquest.Settings.getParticleCount(); vbo = GL15.glGenBuffers(); particleBuffer = GL15.glGenBuffers(); { FloatBuffer vertexData = BufferUtils.createFloatBuffer(8); vertexData.put(-0.5f).put(-0.5f); vertexData.put(0.5f).put(-0.5f); vertexData.put(-0.5f).put(0.5f); vertexData.put(0.5f).put(0.5f); vertexData.flip(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexData, GL15.GL_STATIC_DRAW); } particleData = BufferUtils.createFloatBuffer(9*maxParticleCount); shader = new ShaderProgram("Particle"); shader.bind(); offsetAttribLocation = shader.getAttributeLocation("att_offset"); scaleAttribLocation = shader.getAttributeLocation("att_scale"); colorAttribLocation = shader.getAttributeLocation("att_color"); GL20.glEnableVertexAttribArray(offsetAttribLocation); GL20.glEnableVertexAttribArray(scaleAttribLocation); GL20.glEnableVertexAttribArray(colorAttribLocation); } public void addParticle(Particle particle){ if(particles.size()>=maxParticleCount) return; particles.add(particle); } public void dispose(){ GL15.glDeleteBuffers(vbo); GL15.glDeleteBuffers(particleBuffer); shader.dispose(); } public void render(){ if(particles.size()==0||maxParticleCount==0) return; shader.bind(); GL11.glEnable(GL11.GL_BLEND); GL33.glVertexAttribDivisor(offsetAttribLocation, 1); GL33.glVertexAttribDivisor(scaleAttribLocation, 1); GL33.glVertexAttribDivisor(colorAttribLocation, 1); GL11.glDepthMask(false); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL11.glVertexPointer(2, GL11.GL_FLOAT, 8, 0); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, particleBuffer); GL20.glVertexAttribPointer(offsetAttribLocation, 3, GL11.GL_FLOAT, false, 36, 0); GL20.glVertexAttribPointer(scaleAttribLocation, 2, GL11.GL_FLOAT, false, 36, 12); GL20.glVertexAttribPointer(colorAttribLocation, 4, GL11.GL_FLOAT, false, 36, 20); GL31.glDrawArraysInstanced(GL11.GL_TRIANGLE_STRIP, 0, 4, particles.size()); GL11.glEnable(GL11.GL_CULL_FACE); GL11.glDisable(GL11.GL_BLEND); GL33.glVertexAttribDivisor(offsetAttribLocation, 0); GL33.glVertexAttribDivisor(scaleAttribLocation, 0); GL33.glVertexAttribDivisor(colorAttribLocation, 0); GL11.glDepthMask(true); } public void setMaxParticles(int count){ maxParticleCount = count; particleData = BufferUtils.createFloatBuffer(9*maxParticleCount); } public void update(double delta, double time){ for(int i = 0; i<engines.size(); i++) engines.get(i).update(time); for(int i = 0; i<particles.size();){ particles.get(i).update(delta, time); if(!particles.get(i).isAlive()){ particles.remove(i); continue; } particles.get(i).setCameraDistance(camera); i++; } // --- // This action sorts the particles in from to back order, to make sure // particle distance is correct. But it does cause a slight bit of lag // when dealing with larger amounts of particles. // --- if(SortParticles) particles.sort(particleSorter); particleData.clear(); Vector4f color; Vector3f location; Vector2f scale; for(int i = 0; i<particles.size(); i++){ if(i>=maxParticleCount) break; location = particles.get(i).getLocation(); scale = particles.get(i).getScale(); color = particles.get(i).getColor(); particleData.put(location.x); particleData.put(location.y); particleData.put(location.z); particleData.put(scale.x); particleData.put(scale.y); particleData.put(color.x); particleData.put(color.y); particleData.put(color.z); particleData.put(color.w); } particleData.flip(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, particleBuffer); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, particleData, GL15.GL_STREAM_DRAW); } void addEngine(ParticleEngine engine){ engines.add(engine); } void removeEngine(ParticleEngine engine){ engines.remove(engine); } }
ConquestRTS/src/com/wraithavens/conquest/SinglePlayer/Particles/ParticleBatch.java
package com.wraithavens.conquest.SinglePlayer.Particles; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.Comparator; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL31; import org.lwjgl.opengl.GL33; import com.wraithavens.conquest.Launcher.WraithavensConquest; import com.wraithavens.conquest.Math.Vector2f; import com.wraithavens.conquest.Math.Vector3f; import com.wraithavens.conquest.Math.Vector4f; import com.wraithavens.conquest.SinglePlayer.RenderHelpers.Camera; import com.wraithavens.conquest.SinglePlayer.RenderHelpers.ShaderProgram; public class ParticleBatch{ private static final boolean SortParticles = false; private final int vbo; private final int particleBuffer; private final ShaderProgram shader; private FloatBuffer particleData; private final int offsetAttribLocation; private final int scaleAttribLocation; private final int colorAttribLocation; private int maxParticleCount; private final ArrayList<Particle> particles = new ArrayList(maxParticleCount); private final Comparator particleSorter = new Comparator<Particle>(){ public int compare(Particle a, Particle b){ return a.getCameraDistance()==b.getCameraDistance()?0:a.getCameraDistance()<b.getCameraDistance()?1 :-1; } }; private final Camera camera; private final ArrayList<ParticleEngine> engines = new ArrayList(); public ParticleBatch(Camera camera){ this.camera = camera; maxParticleCount = WraithavensConquest.Settings.getParticleCount(); vbo = GL15.glGenBuffers(); particleBuffer = GL15.glGenBuffers(); { FloatBuffer vertexData = BufferUtils.createFloatBuffer(8); vertexData.put(-0.5f).put(-0.5f); vertexData.put(0.5f).put(-0.5f); vertexData.put(-0.5f).put(0.5f); vertexData.put(0.5f).put(0.5f); vertexData.flip(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexData, GL15.GL_STATIC_DRAW); } particleData = BufferUtils.createFloatBuffer(9*maxParticleCount); shader = new ShaderProgram("Particle"); shader.bind(); offsetAttribLocation = shader.getAttributeLocation("att_offset"); scaleAttribLocation = shader.getAttributeLocation("att_scale"); colorAttribLocation = shader.getAttributeLocation("att_color"); GL20.glEnableVertexAttribArray(offsetAttribLocation); GL20.glEnableVertexAttribArray(scaleAttribLocation); GL20.glEnableVertexAttribArray(colorAttribLocation); } public void addParticle(Particle particle){ if(particles.size()>=maxParticleCount) return; particles.add(particle); } public void dispose(){ GL15.glDeleteBuffers(vbo); GL15.glDeleteBuffers(particleBuffer); shader.dispose(); } public void render(){ if(particles.size()==0) return; shader.bind(); GL11.glEnable(GL11.GL_BLEND); GL33.glVertexAttribDivisor(offsetAttribLocation, 1); GL33.glVertexAttribDivisor(scaleAttribLocation, 1); GL33.glVertexAttribDivisor(colorAttribLocation, 1); GL11.glDepthMask(false); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo); GL11.glVertexPointer(2, GL11.GL_FLOAT, 8, 0); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, particleBuffer); GL20.glVertexAttribPointer(offsetAttribLocation, 3, GL11.GL_FLOAT, false, 36, 0); GL20.glVertexAttribPointer(scaleAttribLocation, 2, GL11.GL_FLOAT, false, 36, 12); GL20.glVertexAttribPointer(colorAttribLocation, 4, GL11.GL_FLOAT, false, 36, 20); GL31.glDrawArraysInstanced(GL11.GL_TRIANGLE_STRIP, 0, 4, particles.size()); GL11.glEnable(GL11.GL_CULL_FACE); GL11.glDisable(GL11.GL_BLEND); GL33.glVertexAttribDivisor(offsetAttribLocation, 0); GL33.glVertexAttribDivisor(scaleAttribLocation, 0); GL33.glVertexAttribDivisor(colorAttribLocation, 0); GL11.glDepthMask(true); } public void setMaxParticles(int count){ maxParticleCount = count; particleData = BufferUtils.createFloatBuffer(9*maxParticleCount); } public void update(double delta, double time){ for(int i = 0; i<engines.size(); i++) engines.get(i).update(time); for(int i = 0; i<particles.size();){ particles.get(i).update(delta, time); if(!particles.get(i).isAlive()){ particles.remove(i); continue; } particles.get(i).setCameraDistance(camera); i++; } // --- // This action sorts the particles in from to back order, to make sure // particle distance is correct. But it does cause a slight bit of lag // when dealing with larger amounts of particles. // --- if(SortParticles) particles.sort(particleSorter); particleData.clear(); Vector4f color; Vector3f location; Vector2f scale; for(int i = 0; i<particles.size(); i++){ if(i>=maxParticleCount) break; location = particles.get(i).getLocation(); scale = particles.get(i).getScale(); color = particles.get(i).getColor(); particleData.put(location.x); particleData.put(location.y); particleData.put(location.z); particleData.put(scale.x); particleData.put(scale.y); particleData.put(color.x); particleData.put(color.y); particleData.put(color.z); particleData.put(color.w); } particleData.flip(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, particleBuffer); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, particleData, GL15.GL_STREAM_DRAW); } void addEngine(ParticleEngine engine){ engines.add(engine); } void removeEngine(ParticleEngine engine){ engines.remove(engine); } }
Fixed glitch with turning off particles. Signed-off-by: TheDudeFromCI <[email protected]>
ConquestRTS/src/com/wraithavens/conquest/SinglePlayer/Particles/ParticleBatch.java
Fixed glitch with turning off particles.
<ide><path>onquestRTS/src/com/wraithavens/conquest/SinglePlayer/Particles/ParticleBatch.java <ide> shader.dispose(); <ide> } <ide> public void render(){ <del> if(particles.size()==0) <add> if(particles.size()==0||maxParticleCount==0) <ide> return; <ide> shader.bind(); <ide> GL11.glEnable(GL11.GL_BLEND);
Java
apache-2.0
f28d2e97bb53e8e3f5066dda64bf15ef2fe6c93d
0
chibenwa/james,aduprat/james,rouazana/james,rouazana/james,rouazana/james,rouazana/james,aduprat/james,aduprat/james,chibenwa/james,aduprat/james,chibenwa/james,chibenwa/james
/* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software License * version 1.1, a copy of which has been included with this distribution in * the LICENSE file. */ package org.apache.james.core; import org.apache.avalon.framework.activity.Initializable; import org.apache.avalon.framework.component.Component; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.component.ComponentManager; import org.apache.avalon.framework.component.Composable; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.configuration.DefaultConfiguration; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.logger.AbstractLogEnabled; import org.apache.avalon.framework.logger.LogEnabled; import org.apache.james.services.MailRepository; import org.apache.james.services.MailStore; import org.apache.james.services.SpoolRepository; import java.util.HashMap; /** * Provides a registry of mail repositories. A mail repository is uniquely * identified by its destinationURL, type and model. * * @author <a href="mailto:[email protected]">Federico Barbieri</a> * @author Darrell DeBoer <[email protected]> */ public class AvalonMailStore extends AbstractLogEnabled implements Contextualizable, Composable, Configurable, Initializable, MailStore { // Prefix for repository names private static final String REPOSITORY_NAME = "Repository"; // Static variable used to name individual repositories. Should only // be accessed when a lock on the AvalonMailStore.class is held private static long id; // map of [destinationURL + type]->Repository private HashMap repositories; // map of [protocol(destinationURL) + type ]->classname of repository; private HashMap classes; // map of [protocol(destinationURL) + type ]->default config for repository. private HashMap defaultConfigs; /** * The Avalon context used by the instance */ protected Context context; /** * The Avalon configuration used by the instance */ protected Configuration configuration; /** * The Avalon component manager used by the instance */ protected ComponentManager componentManager; private SpoolRepository inboundSpool; /** * Pass the Context to the component. * This method is called after the setLogger() * method and before any other method. * * @param context the context * @throws ContextException if context is invalid */ public void contextualize(final Context context) throws ContextException { this.context = context; } /** * Pass the <code>ComponentManager</code> to the instance. * The instance uses the specified <code>ComponentManager</code> to * acquire the components it needs for execution. * * @param componentManager The <code>ComponentManager</code> which this * <code>Composable</code> uses. * @throws ComponentException if an error occurs */ public void compose( final ComponentManager componentManager ) throws ComponentException { this.componentManager = componentManager; } /** * Pass the <code>Configuration</code> to the instance. * * @param configuration the class configurations. * @throws ConfigurationException if an error occurs */ public void configure( final Configuration configuration ) throws ConfigurationException { this.configuration = configuration; } /** * Initialize the component. Initialization includes * allocating any resources required throughout the * components lifecycle. * * @throws Exception if an error occurs */ public void initialize() throws Exception { getLogger().info("JamesMailStore init..."); repositories = new HashMap(); classes = new HashMap(); defaultConfigs = new HashMap(); Configuration[] registeredClasses = configuration.getChild("repositories").getChildren("repository"); for ( int i = 0; i < registeredClasses.length; i++ ) { registerRepository((Configuration) registeredClasses[i]); } Configuration spoolRepConf = configuration.getChild("spoolRepository").getChild("repository"); try { inboundSpool = (SpoolRepository) select(spoolRepConf); } catch (Exception e) { getLogger().error("Cannot open private SpoolRepository"); throw e; } if (getLogger().isInfoEnabled()) { getLogger().info("SpoolRepository inboundSpool opened: " + inboundSpool.hashCode()); getLogger().info("James MailStore ...init"); } } /** * <p>Registers a new mail repository type in the mail store's * registry based upon a passed in <code>Configuration</code> object.</p> * * <p>This is presumably synchronized to prevent corruption of the * internal registry.</p> * * @param repConf the Configuration object used to register the * repository * * @throws ConfigurationException if an error occurs accessing the * Configuration object */ public synchronized void registerRepository(Configuration repConf) throws ConfigurationException { String className = repConf.getAttribute("class"); boolean infoEnabled = getLogger().isInfoEnabled(); if (infoEnabled) { getLogger().info("Registering Repository " + className); } Configuration[] protocols = repConf.getChild("protocols").getChildren("protocol"); Configuration[] types = repConf.getChild("types").getChildren("type"); for ( int i = 0; i < protocols.length; i++ ) { String protocol = protocols[i].getValue(); // Get the default configuration for these protocol/type combinations. Configuration defConf = repConf.getChild("config"); for ( int j = 0; j < types.length; j++ ) { String type = types[j].getValue(); String key = protocol + type ; if (classes.get(key) != null) { throw new ConfigurationException("The combination of protocol and type comprise a unique key for repositories. This constraint has been violated. Please check your repository configuration."); } classes.put(key, className); if (defConf != null) { defaultConfigs.put(key, defConf); } if (infoEnabled) { StringBuffer logBuffer = new StringBuffer(128) .append("Registered class: ") .append(key) .append("->") .append(className); getLogger().info(logBuffer.toString()); } } } } /** * This method accept a Configuration object as hint and return the * corresponding MailRepository. * The Configuration must be in the form of: * <repository destinationURL="[URL of this mail repository]" * type="[repository type ex. OBJECT or STREAM or MAIL etc.]" * model="[repository model ex. PERSISTENT or CACHE etc.]"> * [addition configuration] * </repository> * * @param hint the Configuration object used to look up the repository * * @return the selected repository * * @throws ComponentException if any error occurs while parsing the * Configuration or retrieving the * MailRepository */ public synchronized Component select(Object hint) throws ComponentException { Configuration repConf = null; try { repConf = (Configuration) hint; } catch (ClassCastException cce) { throw new ComponentException( "hint is of the wrong type. Must be a Configuration", cce); } String destination = null; String protocol = null; try { destination = repConf.getAttribute("destinationURL"); int idx = destination.indexOf(':'); if ( idx == -1 ) throw new ComponentException( "destination is malformed. Must be a valid URL: " + destination); protocol = destination.substring(0,idx); } catch (ConfigurationException ce) { throw new ComponentException( "Malformed configuration has no destinationURL attribute", ce); } try { String type = repConf.getAttribute("type"); String repID = destination + type; MailRepository reply = (MailRepository) repositories.get(repID); StringBuffer logBuffer = null; if (reply != null) { if (getLogger().isDebugEnabled()) { logBuffer = new StringBuffer(128) .append("obtained repository: ") .append(repID) .append(",") .append(reply.getClass()); getLogger().debug(logBuffer.toString()); } return (Component)reply; } else { String key = protocol + type; String repClass = (String) classes.get( key ); if (getLogger().isDebugEnabled()) { logBuffer = new StringBuffer(128) .append("obtained repository: ") .append(repClass) .append(" to handle: ") .append(protocol) .append(",") .append(type); getLogger().debug( logBuffer.toString() ); } // If default values have been set, create a new repository // configuration element using the default values // and the values in the selector. // If no default values, just use the selector. Configuration config; Configuration defConf = (Configuration)defaultConfigs.get(key); if ( defConf == null) { config = repConf; } else { config = new DefaultConfiguration(repConf.getName(), repConf.getLocation()); copyConfig(defConf, (DefaultConfiguration)config); copyConfig(repConf, (DefaultConfiguration)config); } try { reply = (MailRepository) this.getClass().getClassLoader().loadClass(repClass).newInstance(); if (reply instanceof LogEnabled) { setupLogger(reply); } if (reply instanceof Contextualizable) { ((Contextualizable) reply).contextualize(context); } if (reply instanceof Composable) { ((Composable) reply).compose( componentManager ); } if (reply instanceof Configurable) { ((Configurable) reply).configure(config); } if (reply instanceof Initializable) { ((Initializable) reply).initialize(); } repositories.put(repID, reply); if (getLogger().isInfoEnabled()) { logBuffer = new StringBuffer(128) .append("added repository: ") .append(repID) .append("->") .append(repClass); getLogger().info(logBuffer.toString()); } return (Component)reply; } catch (Exception e) { if (getLogger().isWarnEnabled()) { getLogger().warn( "Exception while creating repository:" + e.getMessage(), e ); } e.printStackTrace(); throw new ComponentException("Cannot find or init repository", e); } } } catch( final ConfigurationException ce ) { throw new ComponentException( "Malformed configuration", ce ); } } /** * <p>Returns a new name for a repository.</p> * * <p>Synchronized on the AvalonMailStore.class object to ensure * against duplication of the repository name</p> * * @return a new repository name */ public static final String getName() { synchronized (AvalonMailStore.class) { return REPOSITORY_NAME + id++; } } /** * Returns the mail spool associated with this AvalonMailStore * * @return the mail spool * * @throws IllegalStateException if the inbound spool has not * yet been set */ public SpoolRepository getInboundSpool() { if (inboundSpool != null) { return inboundSpool; } else { throw new IllegalStateException("Inbound spool not defined"); } } /** * Returns whether the mail store has a repository corresponding to * the passed in hint. * * @param hint the Configuration object used to look up the repository * * @return whether the mail store has a repository corresponding to this hint */ public boolean hasComponent( Object hint ) { Component comp = null; try { comp = select(hint); } catch(ComponentException ex) { if (getLogger().isErrorEnabled()) { getLogger().error("Exception AvalonMailStore.hasComponent-" + ex.toString()); } } return (comp != null); } /** * Copies values from one config into another, overwriting duplicate attributes * and merging children. * * @param fromConfig the Configuration to be copied * @param toConfig the Configuration to which data is being copied */ private void copyConfig(Configuration fromConfig, DefaultConfiguration toConfig) { // Copy attributes String[] attrs = fromConfig.getAttributeNames(); for ( int i = 0; i < attrs.length; i++ ) { String attrName = attrs[i]; String attrValue = fromConfig.getAttribute(attrName, null); toConfig.setAttribute(attrName, attrValue); } // Copy children Configuration[] children = fromConfig.getChildren(); for ( int i = 0; i < children.length; i++ ) { Configuration child = children[i]; String childName = child.getName(); Configuration existingChild = toConfig.getChild(childName, false); if ( existingChild == null ) { toConfig.addChild(child); } else { copyConfig(child, (DefaultConfiguration)existingChild); } } // Copy value String val = fromConfig.getValue(null); if ( val != null ) { toConfig.setValue(val); } } /** * Return the <code>Component</code> when you are finished with it. In this * implementation it does nothing * * @param component The Component we are releasing. */ public void release(Component component) {} }
trunk/src/java/org/apache/james/core/AvalonMailStore.java
/* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software License * version 1.1, a copy of which has been included with this distribution in * the LICENSE file. */ package org.apache.james.core; import org.apache.avalon.framework.activity.Initializable; import org.apache.avalon.framework.component.Component; import org.apache.avalon.framework.component.ComponentException; import org.apache.avalon.framework.component.ComponentManager; import org.apache.avalon.framework.component.Composable; import org.apache.avalon.framework.configuration.Configurable; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.ConfigurationException; import org.apache.avalon.framework.configuration.DefaultConfiguration; import org.apache.avalon.framework.context.Context; import org.apache.avalon.framework.context.ContextException; import org.apache.avalon.framework.context.Contextualizable; import org.apache.avalon.framework.logger.AbstractLogEnabled; import org.apache.avalon.framework.logger.LogEnabled; import org.apache.james.services.MailRepository; import org.apache.james.services.MailStore; import org.apache.james.services.SpoolRepository; import java.util.HashMap; /** * Provides a registry of mail repositories. A mail repository is uniquely * identified by its destinationURL, type and model. * * @author <a href="mailto:[email protected]">Federico Barbieri</a> * @author Darrell DeBoer <[email protected]> */ public class AvalonMailStore extends AbstractLogEnabled implements Contextualizable, Composable, Configurable, Initializable, MailStore { // Prefix for repository names private static final String REPOSITORY_NAME = "Repository"; // Static variable used to name individual repositories. Should only // be accessed when a lock on the AvalonMailStore.class is held private static long id; // map of [destinationURL + type]->Repository private HashMap repositories; // map of [protocol(destinationURL) + type ]->classname of repository; private HashMap classes; // map of [Repository Class]->default config for repository. private HashMap defaultConfigs; /** * The Avalon context used by the instance */ protected Context context; /** * The Avalon configuration used by the instance */ protected Configuration configuration; /** * The Avalon component manager used by the instance */ protected ComponentManager componentManager; private SpoolRepository inboundSpool; /** * Pass the Context to the component. * This method is called after the setLogger() * method and before any other method. * * @param context the context * @throws ContextException if context is invalid */ public void contextualize(final Context context) throws ContextException { this.context = context; } /** * Pass the <code>ComponentManager</code> to the instance. * The instance uses the specified <code>ComponentManager</code> to * acquire the components it needs for execution. * * @param componentManager The <code>ComponentManager</code> which this * <code>Composable</code> uses. * @throws ComponentException if an error occurs */ public void compose( final ComponentManager componentManager ) throws ComponentException { this.componentManager = componentManager; } /** * Pass the <code>Configuration</code> to the instance. * * @param configuration the class configurations. * @throws ConfigurationException if an error occurs */ public void configure( final Configuration configuration ) throws ConfigurationException { this.configuration = configuration; } /** * Initialize the component. Initialization includes * allocating any resources required throughout the * components lifecycle. * * @throws Exception if an error occurs */ public void initialize() throws Exception { getLogger().info("JamesMailStore init..."); repositories = new HashMap(); classes = new HashMap(); defaultConfigs = new HashMap(); Configuration[] registeredClasses = configuration.getChild("repositories").getChildren("repository"); for ( int i = 0; i < registeredClasses.length; i++ ) { registerRepository((Configuration) registeredClasses[i]); } Configuration spoolRepConf = configuration.getChild("spoolRepository").getChild("repository"); try { inboundSpool = (SpoolRepository) select(spoolRepConf); } catch (Exception e) { getLogger().error("Cannot open private SpoolRepository"); throw e; } if (getLogger().isInfoEnabled()) { getLogger().info("SpoolRepository inboundSpool opened: " + inboundSpool.hashCode()); getLogger().info("James MailStore ...init"); } } /** * <p>Registers a new mail repository type in the mail store's * registry based upon a passed in <code>Configuration</code> object.</p> * * <p>This is presumably synchronized to prevent corruption of the * internal registry.</p> * * @param repConf the Configuration object used to register the * repository * * @throws ConfigurationException if an error occurs accessing the * Configuration object */ public synchronized void registerRepository(Configuration repConf) throws ConfigurationException { String className = repConf.getAttribute("class"); boolean infoEnabled = getLogger().isInfoEnabled(); if (infoEnabled) { getLogger().info("Registering Repository " + className); } Configuration[] protocols = repConf.getChild("protocols").getChildren("protocol"); Configuration[] types = repConf.getChild("types").getChildren("type"); for ( int i = 0; i < protocols.length; i++ ) { String protocol = protocols[i].getValue(); for ( int j = 0; j < types.length; j++ ) { String type = types[j].getValue(); String key = protocol + type ; classes.put(key, className); if (infoEnabled) { StringBuffer logBuffer = new StringBuffer(128) .append("Registered class: ") .append(key) .append("->") .append(className); getLogger().info(logBuffer.toString()); } } } // Get the default configuration for this Repository class. Configuration defConf = repConf.getChild("config"); if ( defConf != null ) { defaultConfigs.put(className, defConf); } } /** * This method accept a Configuration object as hint and return the * corresponding MailRepository. * The Configuration must be in the form of: * <repository destinationURL="[URL of this mail repository]" * type="[repository type ex. OBJECT or STREAM or MAIL etc.]" * model="[repository model ex. PERSISTENT or CACHE etc.]"> * [addition configuration] * </repository> * * @param hint the Configuration object used to look up the repository * * @return the selected repository * * @throws ComponentException if any error occurs while parsing the * Configuration or retrieving the * MailRepository */ public synchronized Component select(Object hint) throws ComponentException { Configuration repConf = null; try { repConf = (Configuration) hint; } catch (ClassCastException cce) { throw new ComponentException( "hint is of the wrong type. Must be a Configuration", cce); } String destination = null; String protocol = null; try { destination = repConf.getAttribute("destinationURL"); int idx = destination.indexOf(':'); if ( idx == -1 ) throw new ComponentException( "destination is malformed. Must be a valid URL: " + destination); protocol = destination.substring(0,idx); } catch (ConfigurationException ce) { throw new ComponentException( "Malformed configuration has no destinationURL attribute", ce); } try { String type = repConf.getAttribute("type"); String repID = destination + type; MailRepository reply = (MailRepository) repositories.get(repID); StringBuffer logBuffer = null; if (reply != null) { if (getLogger().isDebugEnabled()) { logBuffer = new StringBuffer(128) .append("obtained repository: ") .append(repID) .append(",") .append(reply.getClass()); getLogger().debug(logBuffer.toString()); } return (Component)reply; } else { String repClass = (String) classes.get( protocol + type ); if (getLogger().isDebugEnabled()) { logBuffer = new StringBuffer(128) .append("obtained repository: ") .append(repClass) .append(" to handle: ") .append(protocol) .append(",") .append(type); getLogger().debug( logBuffer.toString() ); } // If default values have been set, create a new repository // configuration element using the default values // and the values in the selector. // If no default values, just use the selector. Configuration config; Configuration defConf = (Configuration)defaultConfigs.get(repClass); if ( defConf == null) { config = repConf; } else { config = new DefaultConfiguration(repConf.getName(), repConf.getLocation()); copyConfig(defConf, (DefaultConfiguration)config); copyConfig(repConf, (DefaultConfiguration)config); } try { reply = (MailRepository) this.getClass().getClassLoader().loadClass(repClass).newInstance(); if (reply instanceof LogEnabled) { setupLogger(reply); } if (reply instanceof Contextualizable) { ((Contextualizable) reply).contextualize(context); } if (reply instanceof Composable) { ((Composable) reply).compose( componentManager ); } if (reply instanceof Configurable) { ((Configurable) reply).configure(config); } if (reply instanceof Initializable) { ((Initializable) reply).initialize(); } repositories.put(repID, reply); if (getLogger().isInfoEnabled()) { logBuffer = new StringBuffer(128) .append("added repository: ") .append(repID) .append("->") .append(repClass); getLogger().info(logBuffer.toString()); } return (Component)reply; } catch (Exception e) { if (getLogger().isWarnEnabled()) { getLogger().warn( "Exception while creating repository:" + e.getMessage(), e ); } e.printStackTrace(); throw new ComponentException("Cannot find or init repository", e); } } } catch( final ConfigurationException ce ) { throw new ComponentException( "Malformed configuration", ce ); } } /** * <p>Returns a new name for a repository.</p> * * <p>Synchronized on the AvalonMailStore.class object to ensure * against duplication of the repository name</p> * * @return a new repository name */ public static final String getName() { synchronized (AvalonMailStore.class) { return REPOSITORY_NAME + id++; } } /** * Returns the mail spool associated with this AvalonMailStore * * @return the mail spool * * @throws IllegalStateException if the inbound spool has not * yet been set */ public SpoolRepository getInboundSpool() { if (inboundSpool != null) { return inboundSpool; } else { throw new IllegalStateException("Inbound spool not defined"); } } /** * Returns whether the mail store has a repository corresponding to * the passed in hint. * * @param hint the Configuration object used to look up the repository * * @return whether the mail store has a repository corresponding to this hint */ public boolean hasComponent( Object hint ) { Component comp = null; try { comp = select(hint); } catch(ComponentException ex) { if (getLogger().isErrorEnabled()) { getLogger().error("Exception AvalonMailStore.hasComponent-" + ex.toString()); } } return (comp != null); } /** * Copies values from one config into another, overwriting duplicate attributes * and merging children. * * @param fromConfig the Configuration to be copied * @param toConfig the Configuration to which data is being copied */ private void copyConfig(Configuration fromConfig, DefaultConfiguration toConfig) { // Copy attributes String[] attrs = fromConfig.getAttributeNames(); for ( int i = 0; i < attrs.length; i++ ) { String attrName = attrs[i]; String attrValue = fromConfig.getAttribute(attrName, null); toConfig.setAttribute(attrName, attrValue); } // Copy children Configuration[] children = fromConfig.getChildren(); for ( int i = 0; i < children.length; i++ ) { Configuration child = children[i]; String childName = child.getName(); Configuration existingChild = toConfig.getChild(childName, false); if ( existingChild == null ) { toConfig.addChild(child); } else { copyConfig(child, (DefaultConfiguration)existingChild); } } // Copy value String val = fromConfig.getValue(null); if ( val != null ) { toConfig.setValue(val); } } /** * Return the <code>Component</code> when you are finished with it. In this * implementation it does nothing * * @param component The Component we are releasing. */ public void release(Component component) {} }
Fixed a major bug that was exposed by a recent change to JDBCMailRepository to restore dbfile capability. This bug caused configurations of one repository to be used by another differently configured repository of the same class. For some configurations, this means that a formerly db repository behaved as if it were a dbfile repository. Before using this code make sure that you don't need anything in var/dbmail. git-svn-id: 88158f914d5603334254b4adf21dfd50ec107162@108115 13f79535-47bb-0310-9956-ffa450edef68
trunk/src/java/org/apache/james/core/AvalonMailStore.java
Fixed a major bug that was exposed by a recent change to JDBCMailRepository to restore dbfile capability.
<ide><path>runk/src/java/org/apache/james/core/AvalonMailStore.java <ide> // map of [protocol(destinationURL) + type ]->classname of repository; <ide> private HashMap classes; <ide> <del> // map of [Repository Class]->default config for repository. <add> // map of [protocol(destinationURL) + type ]->default config for repository. <ide> private HashMap defaultConfigs; <ide> <ide> /** <ide> { <ide> String protocol = protocols[i].getValue(); <ide> <add> // Get the default configuration for these protocol/type combinations. <add> Configuration defConf = repConf.getChild("config"); <add> <ide> for ( int j = 0; j < types.length; j++ ) <ide> { <ide> String type = types[j].getValue(); <ide> String key = protocol + type ; <add> if (classes.get(key) != null) { <add> throw new ConfigurationException("The combination of protocol and type comprise a unique key for repositories. This constraint has been violated. Please check your repository configuration."); <add> } <ide> classes.put(key, className); <add> if (defConf != null) { <add> defaultConfigs.put(key, defConf); <add> } <ide> if (infoEnabled) { <ide> StringBuffer logBuffer = <ide> new StringBuffer(128) <ide> } <ide> } <ide> <del> // Get the default configuration for this Repository class. <del> Configuration defConf = repConf.getChild("config"); <del> if ( defConf != null ) { <del> defaultConfigs.put(className, defConf); <del> } <ide> } <ide> <ide> /** <ide> } <ide> return (Component)reply; <ide> } else { <del> String repClass = (String) classes.get( protocol + type ); <add> String key = protocol + type; <add> String repClass = (String) classes.get( key ); <ide> <ide> if (getLogger().isDebugEnabled()) { <ide> logBuffer = <ide> // and the values in the selector. <ide> // If no default values, just use the selector. <ide> Configuration config; <del> Configuration defConf = (Configuration)defaultConfigs.get(repClass); <add> Configuration defConf = (Configuration)defaultConfigs.get(key); <ide> if ( defConf == null) { <ide> config = repConf; <ide> }
Java
apache-2.0
860903db2972eba0f42cb421e486f12681c3fc9c
0
ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma,ppavlidis/Gemma
/* * The Gemma project * * Copyright (c) 2005 Columbia University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package edu.columbia.gemma.web.controller; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.mail.SimpleMailMessage; import org.springframework.validation.BindException; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import edu.columbia.gemma.common.auditAndSecurity.User; import edu.columbia.gemma.common.auditAndSecurity.UserService; import edu.columbia.gemma.web.Constants; import edu.columbia.gemma.web.util.MailEngine; /** * Implementation of <strong>SimpleFormController</strong> that contains convenience methods for subclasses. For * example, getting the current user and saving messages/errors. This class is intended to be a base class for all Form * controllers. * <p> * From Appfuse. * <hr> * <p> * Copyright (c) 2004-2005 Columbia University * * @author <a href="mailto:[email protected]">Matt Raible</a> * @author pavlidis * @version $Id$ */ public abstract class BaseFormController extends SimpleFormController { protected final transient Log log = LogFactory.getLog( getClass() ); protected MailEngine mailEngine = null; protected SimpleMailMessage message = null; protected String templateName = null; protected UserService userService = null; /** * Convenience method to get the Configuration HashMap from the servlet context. * * @return the user's populated form from the session */ public Map getConfiguration() { Map config = ( HashMap ) getServletContext().getAttribute( Constants.CONFIG ); // so unit tests don't puke when nothing's been set if ( config == null ) { return new HashMap(); } return config; } /** * Convenience method for getting a i18n key's value. Calling getMessageSourceAccessor() is used because the * RequestContext variable is not set in unit tests b/c there's no DispatchServlet Request. * * @param msgKey * @param locale the current locale * @return */ public String getText( String msgKey, Locale locale ) { return getMessageSourceAccessor().getMessage( msgKey, locale ); } /** * Convenience method for getting a i18n key's value with arguments. * * @param msgKey * @param args * @param locale the current locale * @return */ public String getText( String msgKey, Object[] args, Locale locale ) { return getMessageSourceAccessor().getMessage( msgKey, args, locale ); } /** * Convenient method for getting a i18n key's value with a single string argument. * * @param msgKey * @param arg * @param locale the current locale * @return */ public String getText( String msgKey, String arg, Locale locale ) { return getText( msgKey, new Object[] { arg }, locale ); } public UserService getUserService() { return this.userService; } /** * Default behavior for FormControllers - redirect to the successView when the cancel button has been pressed. */ public ModelAndView processFormSubmission( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors ) throws Exception { if ( request.getParameter( "cancel" ) != null ) { return new ModelAndView( getSuccessView() ); } return super.processFormSubmission( request, response, command, errors ); } @SuppressWarnings("unchecked") public void saveMessage( HttpServletRequest request, String msg ) { List<String> messages = ( List<String> ) request.getSession().getAttribute( "messages" ); if ( messages == null ) { messages = new ArrayList<String>(); } messages.add( msg ); request.getSession().setAttribute( "messages", messages ); } public void setMailEngine( MailEngine mailEngine ) { this.mailEngine = mailEngine; } public void setMessage( SimpleMailMessage message ) { this.message = message; } public void setTemplateName( String templateName ) { this.templateName = templateName; } public void setUserService( UserService userService ) { this.userService = userService; } /** * Convenience method to get the user object from the session * * @param request the current request * @return the user's populated object from the session */ protected User getUser( HttpServletRequest request ) { return ( User ) request.getSession().getAttribute( Constants.USER_KEY ); } /** * Set up a custom property editor for converting form inputs to real objects */ @SuppressWarnings("unused") protected void initBinder( HttpServletRequest request, ServletRequestDataBinder binder ) { NumberFormat nf = NumberFormat.getNumberInstance(); binder.registerCustomEditor( Integer.class, null, new CustomNumberEditor( Integer.class, nf, true ) ); binder.registerCustomEditor( Long.class, null, new CustomNumberEditor( Long.class, nf, true ) ); binder.registerCustomEditor( byte[].class, new ByteArrayMultipartFileEditor() ); } /** * Convenience message to send messages to users, includes app URL as footer. * * @param user * @param msg * @param url */ protected void sendEmail( User user, String msg, String url ) { log.debug( "sending e-mail to user [" + user.getEmail() + "]..." ); message.setTo( user.getFullName() + "<" + user.getEmail() + ">" ); Map<String, Object> model = new HashMap<String, Object>(); model.put( "user", user ); model.put( "message", msg ); model.put( "applicationURL", url ); mailEngine.sendMessage( message, templateName, model ); } }
src/web/edu/columbia/gemma/web/controller/BaseFormController.java
/* * The Gemma project * * Copyright (c) 2005 Columbia University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package edu.columbia.gemma.web.controller; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.mail.SimpleMailMessage; import org.springframework.validation.BindException; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import edu.columbia.gemma.common.auditAndSecurity.User; import edu.columbia.gemma.common.auditAndSecurity.UserService; import edu.columbia.gemma.web.Constants; import edu.columbia.gemma.web.util.MailEngine; /** * Implementation of <strong>SimpleFormController</strong> that contains convenience methods for subclasses. For * example, getting the current user and saving messages/errors. This class is intended to be a base class for all Form * controllers. * <p> * From Appfuse. * <hr> * <p> * Copyright (c) 2004-2005 Columbia University * * @author <a href="mailto:[email protected]">Matt Raible</a> * @author pavlidis * @version $Id$ */ public class BaseFormController extends SimpleFormController { protected final transient Log log = LogFactory.getLog( getClass() ); protected MailEngine mailEngine = null; protected SimpleMailMessage message = null; protected String templateName = null; protected UserService userService = null; /** * Convenience method to get the Configuration HashMap from the servlet context. * * @return the user's populated form from the session */ public Map getConfiguration() { Map config = ( HashMap ) getServletContext().getAttribute( Constants.CONFIG ); // so unit tests don't puke when nothing's been set if ( config == null ) { return new HashMap(); } return config; } /** * Convenience method for getting a i18n key's value. Calling getMessageSourceAccessor() is used because the * RequestContext variable is not set in unit tests b/c there's no DispatchServlet Request. * * @param msgKey * @param locale the current locale * @return */ public String getText( String msgKey, Locale locale ) { return getMessageSourceAccessor().getMessage( msgKey, locale ); } /** * Convenience method for getting a i18n key's value with arguments. * * @param msgKey * @param args * @param locale the current locale * @return */ public String getText( String msgKey, Object[] args, Locale locale ) { return getMessageSourceAccessor().getMessage( msgKey, args, locale ); } /** * Convenient method for getting a i18n key's value with a single string argument. * * @param msgKey * @param arg * @param locale the current locale * @return */ public String getText( String msgKey, String arg, Locale locale ) { return getText( msgKey, new Object[] { arg }, locale ); } public UserService getUserService() { return this.userService; } /** * Default behavior for FormControllers - redirect to the successView when the cancel button has been pressed. */ public ModelAndView processFormSubmission( HttpServletRequest request, HttpServletResponse response, Object command, BindException errors ) throws Exception { if ( request.getParameter( "cancel" ) != null ) { return new ModelAndView( getSuccessView() ); } return super.processFormSubmission( request, response, command, errors ); } @SuppressWarnings("unchecked") public void saveMessage( HttpServletRequest request, String msg ) { List<String> messages = ( List<String> ) request.getSession().getAttribute( "messages" ); if ( messages == null ) { messages = new ArrayList<String>(); } messages.add( msg ); request.getSession().setAttribute( "messages", messages ); } public void setMailEngine( MailEngine mailEngine ) { this.mailEngine = mailEngine; } public void setMessage( SimpleMailMessage message ) { this.message = message; } public void setTemplateName( String templateName ) { this.templateName = templateName; } public void setUserService( UserService userService ) { this.userService = userService; } /** * Convenience method to get the user object from the session * * @param request the current request * @return the user's populated object from the session */ protected User getUser( HttpServletRequest request ) { return ( User ) request.getSession().getAttribute( Constants.USER_KEY ); } /** * Set up a custom property editor for converting form inputs to real objects */ @SuppressWarnings("unused") protected void initBinder( HttpServletRequest request, ServletRequestDataBinder binder ) { NumberFormat nf = NumberFormat.getNumberInstance(); binder.registerCustomEditor( Integer.class, null, new CustomNumberEditor( Integer.class, nf, true ) ); binder.registerCustomEditor( Long.class, null, new CustomNumberEditor( Long.class, nf, true ) ); binder.registerCustomEditor( byte[].class, new ByteArrayMultipartFileEditor() ); } /** * Convenience message to send messages to users, includes app URL as footer. * * @param user * @param msg * @param url */ protected void sendEmail( User user, String msg, String url ) { log.debug( "sending e-mail to user [" + user.getEmail() + "]..." ); message.setTo( user.getFullName() + "<" + user.getEmail() + ">" ); Map<String, Object> model = new HashMap<String, Object>(); model.put( "user", user ); model.put( "message", msg ); model.put( "applicationURL", url ); mailEngine.sendMessage( message, templateName, model ); } }
made abstract
src/web/edu/columbia/gemma/web/controller/BaseFormController.java
made abstract
<ide><path>rc/web/edu/columbia/gemma/web/controller/BaseFormController.java <ide> * @author pavlidis <ide> * @version $Id$ <ide> */ <del>public class BaseFormController extends SimpleFormController { <add>public abstract class BaseFormController extends SimpleFormController { <ide> protected final transient Log log = LogFactory.getLog( getClass() ); <ide> protected MailEngine mailEngine = null; <ide> protected SimpleMailMessage message = null;
Java
apache-2.0
2be3288b92d8460f24f43b5e03f5b3e4599b086f
0
SpectraLogic/ds3_java_sdk,DenverM80/ds3_java_sdk,RachelTucker/ds3_java_sdk,rpmoore/ds3_java_sdk,RachelTucker/ds3_java_sdk,RachelTucker/ds3_java_sdk,DenverM80/ds3_java_sdk,SpectraLogic/ds3_java_sdk,rpmoore/ds3_java_sdk,rpmoore/ds3_java_sdk,rpmoore/ds3_java_sdk,SpectraLogic/ds3_java_sdk,SpectraLogic/ds3_java_sdk,DenverM80/ds3_java_sdk,DenverM80/ds3_java_sdk,RachelTucker/ds3_java_sdk
/* * ****************************************************************************** * Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ package com.spectralogic.ds3client.integration; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeThat; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.security.SignatureException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.spectralogic.ds3client.commands.*; import com.spectralogic.ds3client.helpers.Ds3ClientHelpers; import com.spectralogic.ds3client.helpers.JobRecoveryException; import com.spectralogic.ds3client.helpers.options.WriteJobOptions; import com.spectralogic.ds3client.models.Contents; import com.spectralogic.ds3client.models.S3Object; import com.spectralogic.ds3client.models.bulk.Ds3Object; import com.spectralogic.ds3client.models.bulk.JobStatus; import com.spectralogic.ds3client.models.bulk.Priority; import com.spectralogic.ds3client.models.tape.Tape; import com.spectralogic.ds3client.models.tape.Tapes; import com.spectralogic.ds3client.utils.ByteArraySeekableByteChannel; import com.spectralogic.ds3client.utils.ResourceUtils; import org.apache.commons.io.IOUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.spectralogic.ds3client.Ds3Client; import com.spectralogic.ds3client.models.ListBucketResult; import com.spectralogic.ds3client.networking.FailedRequestException; import com.spectralogic.ds3client.serializer.XmlProcessingException; public class BucketIntegration_Test { private static Ds3Client client; @BeforeClass public static void startup() { client = Util.fromEnv(); } @AfterClass public static void teardown() throws IOException { client.close(); } @Test public void createBucket() throws IOException, SignatureException { final String bucketName = "test_create_bucket"; client.putBucket(new PutBucketRequest(bucketName)); HeadBucketResponse response = null; try { response = client.headBucket(new HeadBucketRequest(bucketName)); assertThat(response.getStatus(), is(HeadBucketResponse.Status.EXISTS)); } finally { if (response != null) { client.deleteBucket(new DeleteBucketRequest(bucketName)); } } } @Test public void deleteBucket() throws IOException, SignatureException { final String bucketName = "test_delete_bucket"; client.putBucket(new PutBucketRequest(bucketName)); HeadBucketResponse response = client.headBucket(new HeadBucketRequest( bucketName)); assertThat(response.getStatus(), is(HeadBucketResponse.Status.EXISTS)); client.deleteBucket(new DeleteBucketRequest(bucketName)); response = client.headBucket(new HeadBucketRequest(bucketName)); assertThat(response.getStatus(), is(HeadBucketResponse.Status.DOESNTEXIST)); } @Test public void modifyJob() throws IOException, SignatureException, XmlProcessingException, URISyntaxException { final String bucketName = "test_modify_job"; try { client.putBucket(new PutBucketRequest(bucketName)); final List<Ds3Object> objects = new ArrayList<>(); final Ds3Object obj = new Ds3Object("test", 2); objects.add(obj); final WriteJobOptions jobOptions = WriteJobOptions.create().withPriority(Priority.LOW); final Ds3ClientHelpers.Job job = com.spectralogic.ds3client.helpers.Ds3ClientHelpers .wrap(client).startWriteJob(bucketName, objects, jobOptions); client.modifyJob(new ModifyJobRequest(job.getJobId()).withPriority(Priority.HIGH)); final GetJobResponse response = client.getJob(new GetJobRequest(job.getJobId())); assertThat(response.getMasterObjectList().getPriority(), is(Priority.HIGH)); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void getObjects() throws IOException, SignatureException, URISyntaxException, XmlProcessingException { final String bucketName = "test_get_objs"; try { client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestData(client, bucketName); final HeadObjectResponse headResponse = client.headObject(new HeadObjectRequest( bucketName, "beowulf.txt")); assertThat(headResponse.getStatus(), is(HeadObjectResponse.Status.EXISTS)); final GetObjectsResponse response = client .getObjects(new GetObjectsRequest().withBucket("test_get_objs")); assertFalse(response.getS3ObjectList().getObjects().isEmpty()); assertThat(response.getS3ObjectList().getObjects().size(), is(4)); assertTrue(s3ObjectExists(response.getS3ObjectList().getObjects(), "beowulf.txt")); } finally { Util.deleteAllContents(client,bucketName); } } private boolean s3ObjectExists(final List<S3Object> objects, final String fileName) { for (final S3Object obj : objects) { if (obj.getName().equals(fileName)) { return true; } } return false; } @Test public void deleteFolder() throws IOException, SignatureException, URISyntaxException, XmlProcessingException { final String bucketName = "test_delete_folder"; try { client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestDataWithPrefix(client, bucketName, "folder/"); HeadObjectResponse response = client.headObject(new HeadObjectRequest( bucketName, "folder/beowulf.txt")); assertThat(response.getStatus(), is(HeadObjectResponse.Status.EXISTS)); client.deleteFolder(new DeleteFolderRequest(bucketName, "folder")); response = client.headObject(new HeadObjectRequest( bucketName, "folder/beowulf.txt")); assertThat(response.getStatus(), is(HeadObjectResponse.Status.DOESNTEXIST)); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void emptyBucket() throws IOException, SignatureException { final String bucketName = "test_empty_bucket"; try { client.putBucket(new PutBucketRequest(bucketName)); final GetBucketResponse request = client .getBucket(new GetBucketRequest(bucketName)); final ListBucketResult result = request.getResult(); assertThat(result.getContentsList(), is(notNullValue())); assertTrue(result.getContentsList().isEmpty()); } finally { client.deleteBucket(new DeleteBucketRequest(bucketName)); } } @Test public void listContents() throws IOException, SignatureException, XmlProcessingException, URISyntaxException { final String bucketName = "test_contents_bucket"; try { client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestData(client, bucketName); final GetBucketResponse response = client .getBucket(new GetBucketRequest(bucketName)); final ListBucketResult result = response.getResult(); assertFalse(result.getContentsList().isEmpty()); assertThat(result.getContentsList().size(), is(4)); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void getContents() throws IOException, SignatureException, URISyntaxException, XmlProcessingException { final String bucketName = "test_get_contents"; try { client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestData(client, bucketName); final Ds3ClientHelpers helpers = Ds3ClientHelpers.wrap(client); final Ds3ClientHelpers.Job job = helpers.startReadAllJob(bucketName); final UUID jobId = job.getJobId(); job.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(final String key) throws IOException { final Path filePath = Files.createTempFile("ds3", key); return Files.newByteChannel(filePath, StandardOpenOption.DELETE_ON_CLOSE, StandardOpenOption.WRITE); } }); final GetJobResponse jobResponse = client.getJob(new GetJobRequest(jobId)); assertThat(jobResponse.getMasterObjectList().getStatus(), is(JobStatus.COMPLETED)); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void negativeDeleteNonEmptyBucket() throws IOException, SignatureException, XmlProcessingException, URISyntaxException { final String bucketName = "negative_test_delete_non_empty_bucket"; try { // Create bucket and put objects (4 book .txt files) to it client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestData(client, bucketName); final GetBucketResponse get_response = client .getBucket(new GetBucketRequest(bucketName)); final ListBucketResult get_result = get_response.getResult(); assertFalse(get_result.getContentsList().isEmpty()); assertThat(get_result.getContentsList().size(), is(4)); // Attempt to delete bucket and catch expected // FailedRequestException try { client.deleteBucket(new DeleteBucketRequest(bucketName)); fail("Should have thrown a FailedRequestException when trying to delete a non-empty bucket."); } catch (FailedRequestException e) { assertTrue(409 == e.getStatusCode()); } } finally { Util.deleteAllContents(client, bucketName); } } @Test public void negativeCreateBucketNameConflict() throws SignatureException, IOException { final String bucketName = "negative_test_create_bucket_duplicate_name"; client.putBucket(new PutBucketRequest(bucketName)); // Attempt to create a bucket with a name conflicting with an existing // bucket try { client.putBucket(new PutBucketRequest(bucketName)); fail("Should have thrown a FailedRequestException when trying to create a bucket with a duplicate name."); } catch (FailedRequestException e) { assertTrue(409 == e.getStatusCode()); } finally { client.deleteBucket(new DeleteBucketRequest(bucketName)); } } @Test public void negativeDeleteNonExistentBucket() throws IOException, SignatureException { final String bucketName = "negative_test_delete_non_existent_bucket"; // Attempt to delete bucket and catch expected FailedRequestException try { client.deleteBucket(new DeleteBucketRequest(bucketName)); fail("Should have thrown a FailedRequestException when trying to delete a non-existent bucket."); } catch (FailedRequestException e) { assertTrue(404 == e.getStatusCode()); } } @Test public void negativePutDuplicateObject() throws SignatureException, IOException, XmlProcessingException, URISyntaxException { final String bucketName = "negative_test_put_duplicate_object"; try { client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestData(client, bucketName); final GetBucketResponse response = client .getBucket(new GetBucketRequest(bucketName)); final ListBucketResult result = response.getResult(); assertFalse(result.getContentsList().isEmpty()); assertThat(result.getContentsList().size(), is(4)); try { Util.loadBookTestData(client, bucketName); fail("Should have thrown a FailedRequestException when trying to put duplicate objects."); } catch (FailedRequestException e) { assertTrue(409 == e.getStatusCode()); } } finally { Util.deleteAllContents(client, bucketName); } } @Test public void deleteDirectory() throws IOException, SignatureException, XmlProcessingException { final String bucketName = "delete_directory"; final Ds3ClientHelpers helpers = Ds3ClientHelpers.wrap(client); try { helpers.ensureBucketExists(bucketName); final List<Ds3Object> objects = Lists.newArrayList( new Ds3Object("dirA/obj1.txt", 1024), new Ds3Object("dirA/obj2.txt", 1024), new Ds3Object("dirA/obj3.txt", 1024), new Ds3Object("obj1.txt", 1024)); final Ds3ClientHelpers.Job putJob = helpers.startWriteJob(bucketName, objects); putJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(String key) throws IOException { final byte[] randomData = IOUtils.toByteArray(new RandomDataInputStream(120, 1024)); final ByteBuffer randomBuffer = ByteBuffer.wrap(randomData); final ByteArraySeekableByteChannel channel = new ByteArraySeekableByteChannel(1024); channel.write(randomBuffer); return channel; } }); final Iterable<Contents> objs = helpers.listObjects(bucketName, "dirA"); for (final Contents objContents : objs) { client.deleteObject(new DeleteObjectRequest(bucketName, objContents.getKey())); } final Iterable<Contents> filesLeft = helpers.listObjects(bucketName); assertTrue(Iterables.size(filesLeft) == 1); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void multiObjectDeleteNotQuiet() throws IOException, SignatureException, URISyntaxException, XmlProcessingException { final String bucketName = "multi_object_delete"; final Ds3ClientHelpers wrapper = Ds3ClientHelpers.wrap(client); try { wrapper.ensureBucketExists(bucketName); Util.loadBookTestData(client, bucketName); final Iterable<Contents> objs = wrapper.listObjects(bucketName); final DeleteMultipleObjectsResponse response = client.deleteMultipleObjects(new DeleteMultipleObjectsRequest(bucketName, objs).withQuiet(false)); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(notNullValue())); assertThat(response.getResult().getDeletedList().size(), is(4)); final Iterable<Contents> filesLeft = wrapper.listObjects(bucketName); assertTrue(Iterables.size(filesLeft) == 0); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void multiObjectDeleteQuiet() throws IOException, SignatureException, URISyntaxException, XmlProcessingException { final String bucketName = "multi_object_delete"; final Ds3ClientHelpers wrapper = Ds3ClientHelpers.wrap(client); try { wrapper.ensureBucketExists(bucketName); Util.loadBookTestData(client, bucketName); final Iterable<Contents> objs = wrapper.listObjects(bucketName); final DeleteMultipleObjectsResponse response = client.deleteMultipleObjects(new DeleteMultipleObjectsRequest(bucketName, objs).withQuiet(true)); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(notNullValue())); assertThat(response.getResult().getDeletedList(), is(nullValue())); final Iterable<Contents> filesLeft = wrapper.listObjects(bucketName); assertTrue(Iterables.size(filesLeft) == 0); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void multiObjectDeleteOfUnknownObjects() throws IOException, SignatureException { final String bucketName = "unknown_objects_delete"; final Ds3ClientHelpers wrapper = Ds3ClientHelpers.wrap(client); try { wrapper.ensureBucketExists(bucketName); final List<String> objList = Lists.newArrayList("badObj1.txt", "badObj2.txt", "badObj3.txt"); final DeleteMultipleObjectsResponse response = client.deleteMultipleObjects(new DeleteMultipleObjectsRequest(bucketName, objList)); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(notNullValue())); assertThat(response.getResult().getDeletedList(), is(nullValue())); assertThat(response.getResult().getErrorList(), is(notNullValue())); assertThat(response.getResult().getErrorList().size(), is(3)); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void testRecoverWriteJob() throws SignatureException, IOException, XmlProcessingException, JobRecoveryException, URISyntaxException { final String bucketName = "test_recover_write_job_bucket"; final String book1 = "beowulf.txt"; final String book2 = "ulysses.txt"; final Ds3ClientHelpers helpers = Ds3ClientHelpers.wrap(client); try { client.putBucket(new PutBucketRequest(bucketName)); helpers.ensureBucketExists(bucketName); final File objFile1 = ResourceUtils.loadFileResource(Util.RESOURCE_BASE_NAME + book1); final File objFile2 = ResourceUtils.loadFileResource(Util.RESOURCE_BASE_NAME + book2); final Ds3Object obj1 = new Ds3Object(book1, objFile1.length()); final Ds3Object obj2 = new Ds3Object(book2, objFile2.length()); final Ds3ClientHelpers.Job job = Ds3ClientHelpers.wrap(client).startWriteJob(bucketName, Lists.newArrayList(obj1, obj2)); final PutObjectResponse putResponse1 = client.putObject(new PutObjectRequest( job.getBucketName(), book1, job.getJobId(), objFile1.length(), 0, new ResourceObjectPutter(Util.RESOURCE_BASE_NAME).buildChannel(book1) )); assertThat(putResponse1, is(notNullValue())); assertThat(putResponse1.getStatusCode(), is(equalTo(200))); // Interuption... final Ds3ClientHelpers.Job recoverJob = Ds3ClientHelpers.wrap(client).recoverWriteJob(job.getJobId()); final PutObjectResponse putResponse2 = client.putObject(new PutObjectRequest( recoverJob.getBucketName(), book2, recoverJob.getJobId(), objFile2.length(), 0, new ResourceObjectPutter(Util.RESOURCE_BASE_NAME).buildChannel(book2) )); assertThat(putResponse2, is(notNullValue())); assertThat(putResponse2.getStatusCode(), is(equalTo(200))); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void getTapes() throws IOException, SignatureException { final GetTapesResponse response = client.getTapes(new GetTapesRequest()); final Tapes tapes = response.getTapes(); assumeThat(tapes, is(notNullValue())); assumeThat(tapes.getTapes(), is(notNullValue())); assumeThat(tapes.getTapes().size(), is(not(0))); assertThat(tapes.getTapes().get(0).getId(), is(notNullValue())); } @Test public void getTape() throws IOException, SignatureException { final GetTapesResponse tapesResponse = client.getTapes(new GetTapesRequest()); final Tapes tapes = tapesResponse.getTapes(); assumeThat(tapes, is(notNullValue())); assumeThat(tapes.getTapes(), is(notNullValue())); assumeThat(tapes.getTapes().size(), is(not(0))); final GetTapeResponse tapeResponse = client.getTape(new GetTapeRequest(tapes.getTapes().get(0).getId())); final Tape tape = tapeResponse.getTape(); assertThat(tape, is(notNullValue())); assertThat(tape.getId(), is(notNullValue())); } @Test public void testRecoverReadJob() throws SignatureException, IOException, XmlProcessingException, JobRecoveryException, URISyntaxException { final String bucketName = "test_recover_read_job_bucket"; final String book1 = "beowulf.txt"; final String book2 = "ulysses.txt"; final File objFile1 = ResourceUtils.loadFileResource(Util.RESOURCE_BASE_NAME + book1); final File objFile2 = ResourceUtils.loadFileResource(Util.RESOURCE_BASE_NAME + book2); final Ds3Object obj1 = new Ds3Object(book1, objFile1.length()); final Ds3Object obj2 = new Ds3Object(book2, objFile2.length()); final Path dirPath = FileSystems.getDefault().getPath("output"); if (!Files.exists(dirPath)) { Files.createDirectory(dirPath); } try { client.putBucket(new PutBucketRequest(bucketName)); Ds3ClientHelpers.wrap(client).ensureBucketExists(bucketName); final Ds3ClientHelpers.Job putJob = Ds3ClientHelpers.wrap(client).startWriteJob(bucketName, Lists.newArrayList(obj1, obj2)); putJob.transfer(new ResourceObjectPutter(Util.RESOURCE_BASE_NAME)); final FileChannel channel1 = FileChannel.open( dirPath.resolve(book1), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING ); final Ds3ClientHelpers.Job readJob = Ds3ClientHelpers.wrap(client).startReadJob(bucketName, Lists.newArrayList(obj1, obj2)); final GetObjectResponse readResponse1 = client.getObject(new GetObjectRequest(bucketName, book1, 0, readJob.getJobId(), channel1)); assertThat(readResponse1, is(notNullValue())); assertThat(readResponse1.getStatusCode(), is(equalTo(200))); // Interuption... final Ds3ClientHelpers.Job recoverJob = Ds3ClientHelpers.wrap(client).recoverReadJob(readJob.getJobId()); final FileChannel channel2 = FileChannel.open( dirPath.resolve(book2), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING ); final GetObjectResponse readResponse2 = client.getObject(new GetObjectRequest(bucketName, book2, 0, recoverJob.getJobId(), channel2)); assertThat(readResponse2, is(notNullValue())); assertThat(readResponse2.getStatusCode(), is(equalTo(200))); } finally { Util.deleteAllContents(client, bucketName); for( final Path tempFile : Files.newDirectoryStream(dirPath) ){ Files.delete(tempFile); } Files.delete(dirPath); } } }
ds3-sdk-integration/src/test/java/com/spectralogic/ds3client/integration/BucketIntegration_Test.java
/* * ****************************************************************************** * Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ package com.spectralogic.ds3client.integration; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeThat; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.security.SignatureException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.spectralogic.ds3client.commands.*; import com.spectralogic.ds3client.helpers.Ds3ClientHelpers; import com.spectralogic.ds3client.helpers.JobRecoveryException; import com.spectralogic.ds3client.helpers.options.WriteJobOptions; import com.spectralogic.ds3client.models.Contents; import com.spectralogic.ds3client.models.S3Object; import com.spectralogic.ds3client.models.bulk.Ds3Object; import com.spectralogic.ds3client.models.bulk.JobStatus; import com.spectralogic.ds3client.models.bulk.Priority; import com.spectralogic.ds3client.models.tape.Tape; import com.spectralogic.ds3client.models.tape.Tapes; import com.spectralogic.ds3client.utils.ByteArraySeekableByteChannel; import com.spectralogic.ds3client.utils.ResourceUtils; import org.apache.commons.io.IOUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import com.spectralogic.ds3client.Ds3Client; import com.spectralogic.ds3client.models.ListBucketResult; import com.spectralogic.ds3client.networking.FailedRequestException; import com.spectralogic.ds3client.serializer.XmlProcessingException; public class BucketIntegration_Test { private static Ds3Client client; @BeforeClass public static void startup() { client = Util.fromEnv(); } @AfterClass public static void teardown() throws IOException { client.close(); } @Test public void createBucket() throws IOException, SignatureException { final String bucketName = "test_create_bucket"; client.putBucket(new PutBucketRequest(bucketName)); HeadBucketResponse response = null; try { response = client.headBucket(new HeadBucketRequest(bucketName)); assertThat(response.getStatus(), is(HeadBucketResponse.Status.EXISTS)); } finally { if (response != null) { client.deleteBucket(new DeleteBucketRequest(bucketName)); } } } @Test public void deleteBucket() throws IOException, SignatureException { final String bucketName = "test_delete_bucket"; client.putBucket(new PutBucketRequest(bucketName)); HeadBucketResponse response = client.headBucket(new HeadBucketRequest( bucketName)); assertThat(response.getStatus(), is(HeadBucketResponse.Status.EXISTS)); client.deleteBucket(new DeleteBucketRequest(bucketName)); response = client.headBucket(new HeadBucketRequest(bucketName)); assertThat(response.getStatus(), is(HeadBucketResponse.Status.DOESNTEXIST)); } @Test public void modifyJob() throws IOException, SignatureException, XmlProcessingException, URISyntaxException { final String bucketName = "test_modify_job"; try { client.putBucket(new PutBucketRequest(bucketName)); final List<Ds3Object> objects = new ArrayList<>(); final Ds3Object obj = new Ds3Object("test", 2); objects.add(obj); final WriteJobOptions jobOptions = WriteJobOptions.create().withPriority(Priority.LOW); final Ds3ClientHelpers.Job job = com.spectralogic.ds3client.helpers.Ds3ClientHelpers .wrap(client).startWriteJob(bucketName, objects, jobOptions); client.modifyJob(new ModifyJobRequest(job.getJobId()).withPriority(Priority.HIGH)); final GetJobResponse response = client.getJob(new GetJobRequest(job.getJobId())); assertThat(response.getMasterObjectList().getPriority(), is(Priority.HIGH)); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void getObjects() throws IOException, SignatureException, URISyntaxException, XmlProcessingException { final String bucketName = "test_get_objs"; try { client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestData(client, bucketName); final HeadObjectResponse headResponse = client.headObject(new HeadObjectRequest( bucketName, "beowulf.txt")); assertThat(headResponse.getStatus(), is(HeadObjectResponse.Status.EXISTS)); final GetObjectsResponse response = client .getObjects(new GetObjectsRequest().withBucket("test_get_objs")); assertFalse(response.getS3ObjectList().getObjects().isEmpty()); assertThat(response.getS3ObjectList().getObjects().size(), is(4)); assertTrue(s3ObjectExists(response.getS3ObjectList().getObjects(), "beowulf.txt")); } finally { Util.deleteAllContents(client,bucketName); } } private boolean s3ObjectExists(final List<S3Object> objects, final String fileName) { for (final S3Object obj : objects) { if (obj.getName().equals(fileName)) { return true; } } return false; } @Test public void deleteFolder() throws IOException, SignatureException, URISyntaxException, XmlProcessingException { final String bucketName = "test_delete_folder"; try { client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestDataWithPrefix(client, bucketName, "folder/"); HeadObjectResponse response = client.headObject(new HeadObjectRequest( bucketName, "folder/beowulf.txt")); assertThat(response.getStatus(), is(HeadObjectResponse.Status.EXISTS)); client.deleteFolder(new DeleteFolderRequest(bucketName, "folder")); response = client.headObject(new HeadObjectRequest( bucketName, "folder/beowulf.txt")); assertThat(response.getStatus(), is(HeadObjectResponse.Status.DOESNTEXIST)); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void emptyBucket() throws IOException, SignatureException { final String bucketName = "test_empty_bucket"; try { client.putBucket(new PutBucketRequest(bucketName)); final GetBucketResponse request = client .getBucket(new GetBucketRequest(bucketName)); final ListBucketResult result = request.getResult(); assertThat(result.getContentsList(), is(notNullValue())); assertTrue(result.getContentsList().isEmpty()); } finally { client.deleteBucket(new DeleteBucketRequest(bucketName)); } } @Test public void listContents() throws IOException, SignatureException, XmlProcessingException, URISyntaxException { final String bucketName = "test_contents_bucket"; try { client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestData(client, bucketName); final GetBucketResponse response = client .getBucket(new GetBucketRequest(bucketName)); final ListBucketResult result = response.getResult(); assertFalse(result.getContentsList().isEmpty()); assertThat(result.getContentsList().size(), is(4)); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void getContents() throws IOException, SignatureException, URISyntaxException, XmlProcessingException { final String bucketName = "test_get_contents"; try { client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestData(client, bucketName); final Ds3ClientHelpers helpers = Ds3ClientHelpers.wrap(client); final Ds3ClientHelpers.Job job = helpers.startReadAllJob(bucketName); final UUID jobId = job.getJobId(); job.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(final String key) throws IOException { final Path filePath = Files.createTempFile("ds3", key); return Files.newByteChannel(filePath, StandardOpenOption.DELETE_ON_CLOSE, StandardOpenOption.WRITE); } }); final GetJobResponse jobResponse = client.getJob(new GetJobRequest(jobId)); assertThat(jobResponse.getMasterObjectList().getStatus(), is(JobStatus.COMPLETED)); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void negativeDeleteNonEmptyBucket() throws IOException, SignatureException, XmlProcessingException, URISyntaxException { final String bucketName = "negative_test_delete_non_empty_bucket"; try { // Create bucket and put objects (4 book .txt files) to it client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestData(client, bucketName); final GetBucketResponse get_response = client .getBucket(new GetBucketRequest(bucketName)); final ListBucketResult get_result = get_response.getResult(); assertFalse(get_result.getContentsList().isEmpty()); assertThat(get_result.getContentsList().size(), is(4)); // Attempt to delete bucket and catch expected // FailedRequestException try { client.deleteBucket(new DeleteBucketRequest(bucketName)); fail("Should have thrown a FailedRequestException when trying to delete a non-empty bucket."); } catch (FailedRequestException e) { assertTrue(409 == e.getStatusCode()); } } finally { Util.deleteAllContents(client, bucketName); } } @Test public void negativeCreateBucketNameConflict() throws SignatureException, IOException { final String bucketName = "negative_test_create_bucket_duplicate_name"; client.putBucket(new PutBucketRequest(bucketName)); // Attempt to create a bucket with a name conflicting with an existing // bucket try { client.putBucket(new PutBucketRequest(bucketName)); fail("Should have thrown a FailedRequestException when trying to create a bucket with a duplicate name."); } catch (FailedRequestException e) { assertTrue(409 == e.getStatusCode()); } finally { client.deleteBucket(new DeleteBucketRequest(bucketName)); } } @Test public void negativeDeleteNonExistentBucket() throws IOException, SignatureException { final String bucketName = "negative_test_delete_non_existent_bucket"; // Attempt to delete bucket and catch expected FailedRequestException try { client.deleteBucket(new DeleteBucketRequest(bucketName)); fail("Should have thrown a FailedRequestException when trying to delete a non-existent bucket."); } catch (FailedRequestException e) { assertTrue(404 == e.getStatusCode()); } } @Test public void negativePutDuplicateObject() throws SignatureException, IOException, XmlProcessingException, URISyntaxException { final String bucketName = "negative_test_put_duplicate_object"; try { client.putBucket(new PutBucketRequest(bucketName)); Util.loadBookTestData(client, bucketName); final GetBucketResponse response = client .getBucket(new GetBucketRequest(bucketName)); final ListBucketResult result = response.getResult(); assertFalse(result.getContentsList().isEmpty()); assertThat(result.getContentsList().size(), is(4)); try { Util.loadBookTestData(client, bucketName); fail("Should have thrown a FailedRequestException when trying to put duplicate objects."); } catch (FailedRequestException e) { assertTrue(409 == e.getStatusCode()); } } finally { Util.deleteAllContents(client, bucketName); } } @Test public void deleteDirectory() throws IOException, SignatureException, XmlProcessingException { final String bucketName = "delete_directory"; final Ds3ClientHelpers helpers = Ds3ClientHelpers.wrap(client); try { helpers.ensureBucketExists(bucketName); final List<Ds3Object> objects = Lists.newArrayList( new Ds3Object("dirA/obj1.txt", 1024), new Ds3Object("dirA/obj2.txt", 1024), new Ds3Object("dirA/obj3.txt", 1024), new Ds3Object("obj1.txt", 1024)); final Ds3ClientHelpers.Job putJob = helpers.startWriteJob(bucketName, objects); putJob.transfer(new Ds3ClientHelpers.ObjectChannelBuilder() { @Override public SeekableByteChannel buildChannel(String key) throws IOException { final byte[] randomData = IOUtils.toByteArray(new RandomDataInputStream(120, 1024)); final ByteBuffer randomBuffer = ByteBuffer.wrap(randomData); final ByteArraySeekableByteChannel channel = new ByteArraySeekableByteChannel(1024); channel.write(randomBuffer); return channel; } }); final Iterable<Contents> objs = helpers.listObjects(bucketName, "dirA"); for (final Contents objContents : objs) { client.deleteObject(new DeleteObjectRequest(bucketName, objContents.getKey())); } final Iterable<Contents> filesLeft = helpers.listObjects(bucketName); assertTrue(Iterables.size(filesLeft) == 1); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void multiObjectDeleteNotQuiet() throws IOException, SignatureException, URISyntaxException, XmlProcessingException { final String bucketName = "multi_object_delete"; final Ds3ClientHelpers wrapper = Ds3ClientHelpers.wrap(client); try { wrapper.ensureBucketExists(bucketName); Util.loadBookTestData(client, bucketName); final Iterable<Contents> objs = wrapper.listObjects(bucketName); final DeleteMultipleObjectsResponse response = client.deleteMultipleObjects(new DeleteMultipleObjectsRequest(bucketName, objs).withQuiet(false)); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(notNullValue())); assertThat(response.getResult().getDeletedList().size(), is(4)); final Iterable<Contents> filesLeft = wrapper.listObjects(bucketName); assertTrue(Iterables.size(filesLeft) == 0); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void multiObjectDeleteQuiet() throws IOException, SignatureException, URISyntaxException, XmlProcessingException { final String bucketName = "multi_object_delete"; final Ds3ClientHelpers wrapper = Ds3ClientHelpers.wrap(client); try { wrapper.ensureBucketExists(bucketName); Util.loadBookTestData(client, bucketName); final Iterable<Contents> objs = wrapper.listObjects(bucketName); final DeleteMultipleObjectsResponse response = client.deleteMultipleObjects(new DeleteMultipleObjectsRequest(bucketName, objs).withQuiet(true)); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(notNullValue())); assertThat(response.getResult().getDeletedList(), is(nullValue())); final Iterable<Contents> filesLeft = wrapper.listObjects(bucketName); assertTrue(Iterables.size(filesLeft) == 0); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void multiObjectDeleteOfUnknownObjects() throws IOException, SignatureException { final String bucketName = "unknown_objects_delete"; final Ds3ClientHelpers wrapper = Ds3ClientHelpers.wrap(client); try { wrapper.ensureBucketExists(bucketName); final List<String> objList = Lists.newArrayList("badObj1.txt", "badObj2.txt", "badObj3.txt"); final DeleteMultipleObjectsResponse response = client.deleteMultipleObjects(new DeleteMultipleObjectsRequest(bucketName, objList)); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(notNullValue())); assertThat(response.getResult().getDeletedList(), is(nullValue())); assertThat(response.getResult().getErrorList(), is(notNullValue())); assertThat(response.getResult().getErrorList().size(), is(3)); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void testRecoverWriteJob() throws SignatureException, IOException, XmlProcessingException, JobRecoveryException, URISyntaxException { final String bucketName = "test_recover_write_job_bucket"; final String book1 = "beowulf.txt"; final String book2 = "ulysses.txt"; final Ds3ClientHelpers helpers = Ds3ClientHelpers.wrap(client); try { client.putBucket(new PutBucketRequest(bucketName)); helpers.ensureBucketExists(bucketName); final File objFile1 = ResourceUtils.loadFileResource(Util.RESOURCE_BASE_NAME + book1); final File objFile2 = ResourceUtils.loadFileResource(Util.RESOURCE_BASE_NAME + book2); final Ds3Object obj1 = new Ds3Object(book1, objFile1.length()); final Ds3Object obj2 = new Ds3Object(book2, objFile2.length()); final Ds3ClientHelpers.Job job = Ds3ClientHelpers.wrap(client).startWriteJob(bucketName, Lists.newArrayList(obj1, obj2)); final PutObjectResponse putResponse1 = client.putObject(new PutObjectRequest( job.getBucketName(), book1, job.getJobId(), objFile1.length(), 0, new ResourceObjectPutter(Util.RESOURCE_BASE_NAME).buildChannel(book1) )); assertThat(putResponse1, is(notNullValue())); assertThat(putResponse1.getStatusCode(), is(equalTo(200))); // Interuption... final Ds3ClientHelpers.Job recoverJob = Ds3ClientHelpers.wrap(client).recoverWriteJob(job.getJobId()); final PutObjectResponse putResponse2 = client.putObject(new PutObjectRequest( recoverJob.getBucketName(), book2, recoverJob.getJobId(), objFile2.length(), 0, new ResourceObjectPutter(Util.RESOURCE_BASE_NAME).buildChannel(book2) )); assertThat(putResponse2, is(notNullValue())); assertThat(putResponse2.getStatusCode(), is(equalTo(200))); } finally { Util.deleteAllContents(client, bucketName); } } @Test public void getTapes() throws IOException, SignatureException { final GetTapesResponse response = client.getTapes(new GetTapesRequest()); final Tapes tapes = response.getTapes(); assumeThat(tapes.getTapes().size(), is(not(0))); assertThat(tapes.getTapes().get(0).getId(), is(notNullValue())); } @Test public void getTape() throws IOException, SignatureException { final GetTapesResponse tapesResponse = client.getTapes(new GetTapesRequest()); final Tapes tapes = tapesResponse.getTapes(); assumeThat(tapes.getTapes().size(), is(not(0))); final GetTapeResponse tapeResponse = client.getTape(new GetTapeRequest(tapes.getTapes().get(0).getId())); final Tape tape = tapeResponse.getTape(); assertThat(tape, is(notNullValue())); assertThat(tape.getId(), is(notNullValue())); } @Test public void testRecoverReadJob() throws SignatureException, IOException, XmlProcessingException, JobRecoveryException, URISyntaxException { final String bucketName = "test_recover_read_job_bucket"; final String book1 = "beowulf.txt"; final String book2 = "ulysses.txt"; final File objFile1 = ResourceUtils.loadFileResource(Util.RESOURCE_BASE_NAME + book1); final File objFile2 = ResourceUtils.loadFileResource(Util.RESOURCE_BASE_NAME + book2); final Ds3Object obj1 = new Ds3Object(book1, objFile1.length()); final Ds3Object obj2 = new Ds3Object(book2, objFile2.length()); final Path dirPath = FileSystems.getDefault().getPath("output"); if (!Files.exists(dirPath)) { Files.createDirectory(dirPath); } try { client.putBucket(new PutBucketRequest(bucketName)); Ds3ClientHelpers.wrap(client).ensureBucketExists(bucketName); final Ds3ClientHelpers.Job putJob = Ds3ClientHelpers.wrap(client).startWriteJob(bucketName, Lists.newArrayList(obj1, obj2)); putJob.transfer(new ResourceObjectPutter(Util.RESOURCE_BASE_NAME)); final FileChannel channel1 = FileChannel.open( dirPath.resolve(book1), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING ); final Ds3ClientHelpers.Job readJob = Ds3ClientHelpers.wrap(client).startReadJob(bucketName, Lists.newArrayList(obj1, obj2)); final GetObjectResponse readResponse1 = client.getObject(new GetObjectRequest(bucketName, book1, 0, readJob.getJobId(), channel1)); assertThat(readResponse1, is(notNullValue())); assertThat(readResponse1.getStatusCode(), is(equalTo(200))); // Interuption... final Ds3ClientHelpers.Job recoverJob = Ds3ClientHelpers.wrap(client).recoverReadJob(readJob.getJobId()); final FileChannel channel2 = FileChannel.open( dirPath.resolve(book2), StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING ); final GetObjectResponse readResponse2 = client.getObject(new GetObjectRequest(bucketName, book2, 0, recoverJob.getJobId(), channel2)); assertThat(readResponse2, is(notNullValue())); assertThat(readResponse2.getStatusCode(), is(equalTo(200))); } finally { Util.deleteAllContents(client, bucketName); for( final Path tempFile : Files.newDirectoryStream(dirPath) ){ Files.delete(tempFile); } Files.delete(dirPath); } } }
Adding a fix for the getTape tests so that it does not fail on systems that do not have any tapes
ds3-sdk-integration/src/test/java/com/spectralogic/ds3client/integration/BucketIntegration_Test.java
Adding a fix for the getTape tests so that it does not fail on systems that do not have any tapes
<ide><path>s3-sdk-integration/src/test/java/com/spectralogic/ds3client/integration/BucketIntegration_Test.java <ide> final GetTapesResponse response = client.getTapes(new GetTapesRequest()); <ide> final Tapes tapes = response.getTapes(); <ide> <add> assumeThat(tapes, is(notNullValue())); <add> assumeThat(tapes.getTapes(), is(notNullValue())); <ide> assumeThat(tapes.getTapes().size(), is(not(0))); <ide> <ide> assertThat(tapes.getTapes().get(0).getId(), is(notNullValue())); <ide> final GetTapesResponse tapesResponse = client.getTapes(new GetTapesRequest()); <ide> final Tapes tapes = tapesResponse.getTapes(); <ide> <add> assumeThat(tapes, is(notNullValue())); <add> assumeThat(tapes.getTapes(), is(notNullValue())); <ide> assumeThat(tapes.getTapes().size(), is(not(0))); <ide> <ide> final GetTapeResponse tapeResponse = client.getTape(new GetTapeRequest(tapes.getTapes().get(0).getId()));
Java
mit
d7c792911b552312c86f55fbdbeb3042c18ba87e
0
contentful/blog-app-android
package blog.contentful.loaders; import blog.contentful.adapters.PostListAdapter; import blog.contentful.lib.LinkGenerator; import blog.contentful.vault.Author; import blog.contentful.vault.Post; import com.commonsware.cwac.anddown.AndDown; import com.contentful.vault.Asset; import java.util.List; import org.joda.time.format.ISODateTimeFormat; import static org.apache.commons.lang3.StringUtils.defaultString; public class PostLoader extends AbsAsyncLoader<String> { final String postTitle; final String postBody; final String postDate; final String postImage; final Author author; public PostLoader(Post post) { postTitle = defaultString(post.title(), ""); postBody = defaultString(post.body(), ""); postDate = post.date(); Asset image = post.featuredImage(); postImage = image == null ? null : image.url(); List<Author> authors = post.authors(); if (authors.size() == 0) { author = null; } else { author = authors.get(0); } } @SuppressWarnings("StringBufferReplaceableByString") @Override protected String performLoad() { return new StringBuilder().append("<html>") .append("<head>") .append("<style type=\"text/css\">") .append("a:link, a:visited, a:active { color: #4A90E2; font-weight: normal; }") .append("h3.top { font-weight: normal; }") .append("h4.bottom { font-size: 14px; }") .append(".bottom .date { color: #b7c2cc; font-weight: normal; }") .append(".thumbnail { width: 200px; display: block; margin: 0 auto; }") .append("</style>") .append("</head>") .append("<body>") .append(getThumbnailHtml()) .append("<h3 class=\"top\">").append(postTitle).append("</h3>") .append("<h4 class=\"bottom\">") .append(getDateHtml()) .append(getAuthorHtml()) .append("</h4>") .append(new AndDown().markdownToHtml(postBody)) .append("</body></html>") .toString(); } private String getThumbnailHtml() { String result = ""; if (postImage != null) { result = String.format("<img class=\"thumbnail\" src=\"%s\" />", postImage); } return result; } private String getAuthorHtml() { String result = ""; if (author != null && author.name() != null) { result = String.format("<a style=\"margin-left: 4px;\" href=\"%s\">%s</a>", LinkGenerator.author(author.remoteId()), author.name()); } return result; } private String getDateHtml() { String result = ""; if (postDate != null) { result = String.format("<span class=\"date\">%s</span>", ISODateTimeFormat.dateOptionalTimeParser() .parseDateTime(postDate) .toString(PostListAdapter.DATE_FORMATTER) .toUpperCase()); } return result; } }
app/src/main/java/blog/contentful/loaders/PostLoader.java
package blog.contentful.loaders; import blog.contentful.adapters.PostListAdapter; import blog.contentful.lib.LinkGenerator; import blog.contentful.vault.Author; import blog.contentful.vault.Post; import com.commonsware.cwac.anddown.AndDown; import com.contentful.vault.Asset; import java.util.List; import org.joda.time.format.ISODateTimeFormat; public class PostLoader extends AbsAsyncLoader<String> { final String postTitle; final String postBody; final String postDate; final String postImage; final Author author; public PostLoader(Post post) { postTitle = post.title(); postBody = post.body(); postDate = post.date(); Asset image = post.featuredImage(); postImage = image == null ? null : image.url(); List<Author> authors = post.authors(); if (authors.size() == 0) { author = null; } else { author = authors.get(0); } } @SuppressWarnings("StringBufferReplaceableByString") @Override protected String performLoad() { return new StringBuilder().append("<html>") .append("<head>") .append("<style type=\"text/css\">") .append("a:link, a:visited, a:active { color: #4A90E2; font-weight: normal; }") .append("h3.top { font-weight: normal; }") .append("h4.bottom { font-size: 14px; }") .append(".bottom .date { color: #b7c2cc; font-weight: normal; }") .append(".thumbnail { width: 200px; display: block; margin: 0 auto; }") .append("</style>") .append("</head>") .append("<body>") .append(getThumbnailHtml()) .append("<h3 class=\"top\">").append(postTitle).append("</h3>") .append("<h4 class=\"bottom\">") .append(getDateHtml()) .append(getAuthorHtml()) .append("</h4>") .append(new AndDown().markdownToHtml(postBody)) .append("</body></html>") .toString(); } private String getThumbnailHtml() { String result = ""; if (postImage != null) { result = String.format("<img class=\"thumbnail\" src=\"%s\" />", postImage); } return result; } private String getAuthorHtml() { String result = ""; if (author != null && author.name() != null) { result = String.format("<a style=\"margin-left: 4px;\" href=\"%s\">%s</a>", LinkGenerator.author(author.remoteId()), author.name()); } return result; } private String getDateHtml() { String result = ""; if (postDate != null) { result = String.format("<span class=\"date\">%s</span>", ISODateTimeFormat.dateOptionalTimeParser() .parseDateTime(postDate) .toString(PostListAdapter.DATE_FORMATTER) .toUpperCase()); } return result; } }
Post body is optional
app/src/main/java/blog/contentful/loaders/PostLoader.java
Post body is optional
<ide><path>pp/src/main/java/blog/contentful/loaders/PostLoader.java <ide> import com.contentful.vault.Asset; <ide> import java.util.List; <ide> import org.joda.time.format.ISODateTimeFormat; <add> <add>import static org.apache.commons.lang3.StringUtils.defaultString; <ide> <ide> public class PostLoader extends AbsAsyncLoader<String> { <ide> final String postTitle; <ide> final Author author; <ide> <ide> public PostLoader(Post post) { <del> postTitle = post.title(); <del> postBody = post.body(); <add> postTitle = defaultString(post.title(), ""); <add> postBody = defaultString(post.body(), ""); <ide> postDate = post.date(); <ide> <ide> Asset image = post.featuredImage();
Java
apache-2.0
038f2ff573ca0d457b7b6dcf55b18c786c2296be
0
oliverwehrens/jpowermeter
package com.maxheapsize.jpm; import org.springframework.stereotype.Service; import java.math.BigDecimal; @Service public class ReadingBuffer { private SmartMeterReading smartMeterReading; public SmartMeterReading getSmartMeterReading() { return smartMeterReading; } public void setSmartMeterReading(SmartMeterReading smartMeterReading) { this.smartMeterReading = smartMeterReading; } public SmartMeterReading getSmartMeterReadingInKwh() { SmartMeterReading smartMeterReadingInKwh = new SmartMeterReading(); smartMeterReadingInKwh.consumptionTotal.value = smartMeterReading.consumptionTotal.value.divide(new BigDecimal(1000), BigDecimal.ROUND_DOWN); smartMeterReadingInKwh.consumptionTotal.unit = "kWh"; smartMeterReadingInKwh.consumptionOne.value = smartMeterReading.consumptionOne.value.divide(new BigDecimal(1000), BigDecimal.ROUND_DOWN); smartMeterReadingInKwh.consumptionOne.unit = "kWh"; smartMeterReadingInKwh.consumptionTwo.value = smartMeterReading.consumptionTotal.value.divide(new BigDecimal(1000), BigDecimal.ROUND_DOWN); smartMeterReadingInKwh.consumptionTwo.unit = "kWh"; smartMeterReadingInKwh.consumptionNow.value = smartMeterReading.consumptionNow.value; smartMeterReadingInKwh.consumptionNow.unit = smartMeterReading.consumptionNow.unit; return smartMeterReadingInKwh; } }
src/main/java/com/maxheapsize/jpm/ReadingBuffer.java
package com.maxheapsize.jpm; import org.springframework.stereotype.Service; import java.math.BigDecimal; @Service public class ReadingBuffer { private SmartMeterReading smartMeterReading; public SmartMeterReading getSmartMeterReading() { return smartMeterReading; } public void setSmartMeterReading(SmartMeterReading smartMeterReading) { this.smartMeterReading = smartMeterReading; } public SmartMeterReading getSmartMeterReadingInKwh() { SmartMeterReading smartMeterReadingInKwh = new SmartMeterReading(); smartMeterReadingInKwh.consumptionTotal.value = smartMeterReading.consumptionTotal.value.divide(new BigDecimal(1000)); smartMeterReadingInKwh.consumptionTotal.unit = "kWh"; smartMeterReadingInKwh.consumptionOne.value = smartMeterReading.consumptionOne.value.divide(new BigDecimal(1000)); smartMeterReadingInKwh.consumptionOne.unit = "kWh"; smartMeterReadingInKwh.consumptionTwo.value = smartMeterReading.consumptionTotal.value.divide(new BigDecimal(1000)); smartMeterReadingInKwh.consumptionTwo.unit = "kWh"; smartMeterReadingInKwh.consumptionNow.value = smartMeterReading.consumptionNow.value; smartMeterReadingInKwh.consumptionNow.unit = smartMeterReading.consumptionNow.unit; return smartMeterReadingInKwh; } }
rounding mode
src/main/java/com/maxheapsize/jpm/ReadingBuffer.java
rounding mode
<ide><path>rc/main/java/com/maxheapsize/jpm/ReadingBuffer.java <ide> <ide> public SmartMeterReading getSmartMeterReadingInKwh() { <ide> SmartMeterReading smartMeterReadingInKwh = new SmartMeterReading(); <del> smartMeterReadingInKwh.consumptionTotal.value = smartMeterReading.consumptionTotal.value.divide(new BigDecimal(1000)); <add> smartMeterReadingInKwh.consumptionTotal.value = smartMeterReading.consumptionTotal.value.divide(new BigDecimal(1000), BigDecimal.ROUND_DOWN); <ide> smartMeterReadingInKwh.consumptionTotal.unit = "kWh"; <del> smartMeterReadingInKwh.consumptionOne.value = smartMeterReading.consumptionOne.value.divide(new BigDecimal(1000)); <add> smartMeterReadingInKwh.consumptionOne.value = smartMeterReading.consumptionOne.value.divide(new BigDecimal(1000), BigDecimal.ROUND_DOWN); <ide> smartMeterReadingInKwh.consumptionOne.unit = "kWh"; <del> smartMeterReadingInKwh.consumptionTwo.value = smartMeterReading.consumptionTotal.value.divide(new BigDecimal(1000)); <add> smartMeterReadingInKwh.consumptionTwo.value = smartMeterReading.consumptionTotal.value.divide(new BigDecimal(1000), BigDecimal.ROUND_DOWN); <ide> smartMeterReadingInKwh.consumptionTwo.unit = "kWh"; <ide> smartMeterReadingInKwh.consumptionNow.value = smartMeterReading.consumptionNow.value; <ide> smartMeterReadingInKwh.consumptionNow.unit = smartMeterReading.consumptionNow.unit;
Java
agpl-3.0
20ae9279b3f66665b8e99104f761dd17148d8652
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
fcff0d02-2e61-11e5-9284-b827eb9e62be
hello.java
fcf98102-2e61-11e5-9284-b827eb9e62be
fcff0d02-2e61-11e5-9284-b827eb9e62be
hello.java
fcff0d02-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>fcf98102-2e61-11e5-9284-b827eb9e62be <add>fcff0d02-2e61-11e5-9284-b827eb9e62be
JavaScript
mit
60364f1517490ef43deb58f691e8ba9a71a30cdb
0
sebthedev/PrincetonCourses,sebthedev/PrincetonCourses
//convert time to military time var parseMilitaryTime = function(time) { parsedTime = time.split(" ") parsedTime[0] = parsedTime[0].replace(':', '') mTime = parseInt(parsedTime[0]) if (parsedTime[1] == "PM" && parsedTime[0].substring(0,2) != "12") { mTime += 1200 } return mTime } //check whether two given timeframes have no overlap by using military time //if clash, return true var detectTimeClash = function (startTime1, endTime1, startTime2, endTime2) { if (startTime1 == null || endTime1 == null || startTime2 == null || endTime2 == null) { return false } startTime1m = parseMilitaryTime(startTime1) endTime1m = parseMilitaryTime(endTime1) startTime2m = parseMilitaryTime(startTime2) endTime2m = parseMilitaryTime(endTime2) //start or end at same time if (startTime1m == startTime2m || endTime1m == endTime2m) { return true } //check if time2 begins before time1 ends if (startTime1m < startTime2m) { if (startTime2m < endTime1m) { return true } } //check if time1 begins before time2 ends else { if (startTime1m < endTime2m) { return true } } //classes do not overlap console.log("reached no overlap") return false } var detectSectionClash = function(section1, section2) { if (section1 == null || section2 == null) { return false } for (var i = 0; i < section1.schedule.meetings.length; i++) { for (var j = 0; j < section2.schedule.meetings.length; j++) { days1 = section1.schedule.meetings[i].days days2 = section2.schedule.meetings[j].days //replace Th with Z to help with substring find if (days1 != null && days2 != null) { for (var k = 0; k < days1.length; k++) { for (var l = 0; l < days2.length; l++) { if (days1[k] == days2[l]) { return detectTimeClash(section1.schedule.meetings[i].start_time, section1.schedule.meetings[i].end_time, section2.schedule.meetings[j].start_time, section2.schedule.meetings[j].end_time) } } } } } } console.log("no day overlap") return false } var checkedAll = function(sectionIndex, maxLength) { for (var i = 0; i < sectionIndex.length; i++) { if (sectionIndex[i] != maxLength[i] - 1) return false } return true } /* Seb, if you're reading this, I want you to know, I decided to not use a graph for this because we would have to implement all the aspects of graphs here (data structures and algorithms) and it's not more time efficient than doing the same work with nested arrays. This is because the possible no-clash paths are not something that can be passed on efficiently once the original analysis for favoriteCourses happens, so clash detection would still have to be done for everything due to the nature of the graphs that would be passed on. Thus, I'm doing nested arrays with some additional arrays to hold indices of the sub- arrays. (I know this is complicated, but that's what happens with a problem that's exponential in nature.) Hopefully, this will all work, and fast enough that it doesn't have to make a lot of sense. */ var detectCourseClash = function (favoriteCourses, courses, excludeClashingCourses) { //return all if excludeClashingCourses is false if (!excludeClashingCourses) return courses //if no courses are favorited, or only one is no clashes can exist if (favoriteCourses.length <= 1) return courses //since favorite courses exist, do initial clash detection within them //WARNING: THIS HINGES ON THE SECTIONS BEING ORDERED BY SECTION TYPE //populate all the sections of all the favorite courses var favCourseSectionsAll = [] //holds all the sections var favCourseSectionsInc = [] //holds whether a section can exist in a non-clash schedule var maxLength = [] //lengths of nested arrays in favCourseSectionsAll var sectionIndex = [] //index to be used when looking at possible schedules for (var currentCourse = 0; currentCourse < favoriteCourses.length; currentCourse++) { //each course has new, independent sections var prevSectionType = "" var courseSectionsAll = [] var courseSectionsInc = [] var maxLengthIndex = 0 var favCourse = favoriteCourses[currentCourse] for (var currentClass = 0; currentClass < favCourse.classes.length; currentClass++) { var currentSection = favCourse.classes[currentClass] if (prevSectionType != "" /*&& curSection.section != null*/) { //new section type within a course, push previous information into arrays if (prevSectionType != String(currentSection.section).charAt(0)) { favCourseSectionsAll.push(courseSectionsAll) courseSectionsAll = [] favCourseSectionsInc.push(courseSectionsInc) courseSectionsInc = [] maxLength.push(maxLengthIndex) maxLengthIndex = 0 sectionIndex.push(0) } } courseSectionsAll.push(currentSection) courseSectionsInc.push(false) prevSectionType = String(currentSection.section).charAt(0) maxLengthIndex++ } //all sections seen within course, push information into arrays if (courseSectionsAll.length > 0) { favCourseSectionsAll.push(courseSectionsAll) favCourseSectionsInc.push(courseSectionsInc) maxLength.push(maxLengthIndex) maxLengthIndex = 0 sectionIndex.push(0) } } //if no more than 1 section within all favorite courses (odd but technically possible) return all courses, no clashes if (sectionIndex.length == 0) return courses var done = false var i = 1 //now check for all possible schedules to include only possible sections //note that if sectionIndex[0] >= maxLengthIndex[0] all possibilities have been checked and the algorithm should terminate //while (!checkedAll(sectionIndex, maxLength) && !runBack) { while (!done) { while (i < sectionIndex.length) { for (var j = 0; j < i; j++) { if (detectSectionClash(favCourseSectionsAll[j][sectionIndex[j]], favCourseSectionsAll[i][sectionIndex[i]])) { sectionIndex[i]++ while (sectionIndex[i] >= maxLength[i]) { if (i <= 0) { sectionIndex[0] = 0 done = true break } sectionIndex[i] = 0 i-- sectionIndex[i]++ } j = -1 } if (done) break } if (done) break i++ } if (done) break for (var j = 0; j < sectionIndex.length; j++) { favCourseSectionsInc[j][sectionIndex[j]] = true } //update counters i-- sectionIndex[i]++ while (sectionIndex[i] >= maxLength[i]) { if (i <= 0) { sectionIndex[0] = 0 done = true break } sectionIndex[i] = 0 i-- sectionIndex[i]++ } } console.log(favCourseSectionsInc) //favCourseSectionsInc has been updated and can now be used to populate subgraph var incFavCourseSections = [] for (var i = 0; i < favCourseSectionsAll.length; i++) { var incSections = [] for (var j = 0; j < favCourseSectionsAll[i].length; j++) { if (favCourseSectionsInc[i][j]) incSections.push(favCourseSectionsAll[i][j]) } incFavCourseSections.push(incSections) } console.log(incFavCourseSections) console.log(sectionIndex) /* //now that the original subgraph has been made, run clash on all courses from search results for (var courseIndex in courses) { var thisCourse = courses[courseIndex] //each course has new, independent sections var currentCourseSectionsAll = [] var currentMaxLength = [] var currentSectionIndex = [] var prevSectionType = null var courseSectionsAll = [] var maxLengthIndex = 0 for (var section in thisCourse.classes) { if (prevSectionType != null && section.section != null) { //new section type within a course, push previous information into arrays if (prevSectionType != section.section.charAt(0)) { currentCourseSectionsAll.push(courseSections) courseSections = [] currentMaxLength.push(maxLengthIndex) maxLengthIndex = 0 currentSectionIndex.push(0) } } courseSections.push(section) prevSectionType = section.section.charAt(0) maxLengthIndex++ } //all sections seen within course, push information into arrays if (courseSections != null) { currentCourseSectionsAll.push(courseSections) currentMaxLength.push(maxLengthIndex) currentSectionIndex.push(0) } //combine information to run clash currentCourseSectionsAll = incFavCourseSections.concat(currentCourseSectionsAll) currentMaxLength = maxLength.concat(currentMaxLength) currentSectionIndex = sectionIndex.concat(currentSectionIndex) //run a modified clash var found = false var ranOut = false var i = 1 //now check for all possible schedules to include only possible sections //note that if sectionIndex[0] >= maxLengthIndex[0] all possibilities have been checked and the algorithm should terminate //while (!checkedAll(sectionIndex, maxLength) && !runBack) { while (!found) { while (i < currentSectionIndex.length) { for (var j = 0; j < i; j++) { while (detectSectionClash(currentCourseSectionsAll[currentSectionIndex[j]], currentCourseSectionsAll[currentSectionIndex[i]])) { currentSectionIndex[i]++ while (currentSectionIndex[i] >= currentMaxLength[i]) { if (i <= 0) { ranOut = true break } currentSectionIndex[i] = 0 i-- currentSectionIndex[i]++ } if (ranOut) break } if (ranOut) break } if (ranOut) break i++ } if (ranOut) break found = true if (!found) { thisCourse.clash = true } courses[courseIndex] = thisCourse } } */ //it's all done OMG! return courses } module.exports.detectCourseClash = detectCourseClash
courseClashDetector.js
//convert time to military time var parseMilitaryTime = function(time) { parsedTime = time.split(" ") parsedTime[0] = parsedTime[0].replace(':', '') mTime = parseInt(parsedTime[0]) if (parsedTime[1] == "pm") { mTime += 1200 } return mTime } //check whether two given timeframes have no overlap by using military time //if clash, return true var detectTimeClash = function (startTime1, endTime1, startTime2, endTime2) { if (startTime1 == null || endTime1 == null || startTime2 == null || endTime2 == null) { return false } startTime1m = parseMilitaryTime(startTime1) endTime1m = parseMilitaryTime(endTime1) startTime2m = parseMilitaryTime(startTime2) endTime2m = parseMilitaryTime(endTime2) //start or end at same time if (startTime1m == startTime2m || endTime1m == endTime2m) { return true } //check if time2 begins before time1 ends if (startTime1m < startTime2m) { if (startTime2m < endTime1m) { return true } } //check if time1 begins before time2 ends else { if (startTime1m < endTime2m) { return true } } //classes do not overlap return false } var detectSectionClash = function(section1, section2) { if (section1 == null || section2 == null) { return false } //replace Th with Z to help with substring find days1 = section1days.replace("Th", "Z") days2 = section2days.replace("Th", "Z") if (days1 != null && days2 != null) { for (var i = 0; i < days1.length; i++) { if (days2.includes(days1.charAt(i))) { return detectTimeClash(section1.starttime, section1.endtime, section2.starttime, section2.endtime) } } } return false } var checkedAll = function(sectionIndex, maxLength) { for (var i = 0; i < sectionIndex.length; i++) { if (sectionIndex[i] != maxLength[i] - 1) return false } return true } /* Seb, if you're reading this, I want you to know, I decided to not use a graph for this because we would have to implement all the aspects of graphs here (data structures and algorithms) and it's not more time efficient than doing the same work with nested arrays. This is because the possible no-clash paths are not something that can be passed on efficiently once the original analysis for favoriteCourses happens, so clash detection would still have to be done for everything due to the nature of the graphs that would be passed on. Thus, I'm doing nested arrays with some additional arrays to hold indices of the sub- arrays. (I know this is complicated, but that's what happens with a problem that's exponential in nature.) Hopefully, this will all work, and fast enough that it doesn't have to make a lot of sense. */ var detectCourseClash = function (favoriteCourses, courses, excludeClashingCourses) { //return all if excludeClashingCourses is false if (!excludeClashingCourses) return courses //if no courses are favorited, or only one is no clashes can exist if (favoriteCourses.length <= 1) { return courses } //since favorite courses exist, do initial clash detection within them //WARNING: THIS HINGES ON THE SECTIONS BEING ORDERED BY SECTION TYPE //populate all the sections of all the favorite courses var favCourseSectionsAll = [] //holds all the sections var favCourseSectionsInc = [] //holds whether a section can exist in a non-clash schedule var maxLength = [] //lengths of nested arrays in favCourseSectionsAll var sectionIndex = [] //index to be used when looking at possible schedules for (var currentCourse = 0; currentCourse < favoriteCourses.length; currentCourse++) { //each course has new, independent sections var prevSectionType = "" var courseSectionsAll = [] var courseSectionsInc = [] var maxLengthIndex = 0 var favCourse = favoriteCourses[currentCourse] for (var currentClass = 0; currentClass < favCourse.classes.length; currentClass++) { var currentSection = favCourse.classes[currentClass] console.log(currentSection.schedule) if (prevSectionType != "" /*&& curSection.section != null*/) { //new section type within a course, push previous information into arrays if (prevSectionType != String(currentSection.section).charAt(0)) { favCourseSectionsAll.push(courseSectionsAll) courseSectionsAll = [] favCourseSectionsInc.push(courseSectionsInc) courseSectionsInc = [] maxLength.push(maxLengthIndex) maxLengthIndex = 0 sectionIndex.push(0) } } courseSectionsAll.push(currentSection) courseSectionsInc.push(false) prevSectionType = String(currentSection.section).charAt(0) maxLengthIndex++ } //all sections seen within course, push information into arrays if (courseSectionsAll.length > 0) { favCourseSectionsAll.push(courseSectionsAll) favCourseSectionsInc.push(courseSectionsInc) maxLength.push(maxLengthIndex) maxLengthIndex = 0 sectionIndex.push(0) } } console.log(favCourseSectionsAll) return null /* //if no more than 1 section within all favorite courses (odd but technically possible) return all courses, no clashes if (sectionIndex.length == 0) return courses var done = false var i = 1 //now check for all possible schedules to include only possible sections //note that if sectionIndex[0] >= maxLengthIndex[0] all possibilities have been checked and the algorithm should terminate //while (!checkedAll(sectionIndex, maxLength) && !runBack) { while (!done) { while (i < sectionIndex.length) { for (var j = 0; j < i; j++) { while (detectSectionClash(favCourseSectionsAll[sectionsIndex[j]], favCourseSectionsAll[sectionIndex[i]])) { sectionIndex[i]++ while (sectionIndex[i] >= maxLength[i]) { if (i <= 0) { done = true break } sectionIndex[i] = 0 i-- sectionIndex[i]++ } if (done) break } if (done) break } if (done) break i++ } if (done) break for (var j = 0; j < sectionIndex.length, j++) { favCourseSectionsInc[j][sectionIndex[j]] = true } i-- //update counters sectionIndex[i]++ while (sectionIndex[i] >= maxLength[i]) { if (i <= 0) { done = true break } sectionIndex[i] = 0 i-- sectionIndex[i]++ } } //favCourseSectionsInc has been updated and can now be used to populate subgraph var incFavCourseSections = [] for (var i = 0; i < favCourseSectionsAll.length; i++) { var incSections = [] for (var j = 0; j < favCourseSectionsAll[i].length; j++) { if (favCourseSectionsInc[i][j]) incSections.push(favCourseSectionsAll[i][j]) } incFavCourseSections.push(incSections) } //now that the original subgraph has been made, run clash on all courses from search results for (var courseIndex in courses) { var thisCourse = courses[courseIndex] //each course has new, independent sections var currentCourseSectionsAll = [] var currentMaxLength = [] var currentSectionIndex = [] var prevSectionType = null var courseSectionsAll = [] var maxLengthIndex = 0 for (var section in thisCourse.classes) { if (prevSectionType != null && section.section != null) { //new section type within a course, push previous information into arrays if (prevSectionType != section.section.charAt(0)) { currentCourseSectionsAll.push(courseSections) courseSections = [] currentMaxLength.push(maxLengthIndex) maxLengthIndex = 0 currentSectionIndex.push(0) } } courseSections.push(section) prevSectionType = section.section.charAt(0) maxLengthIndex++ } //all sections seen within course, push information into arrays if (courseSections != null) { currentCourseSectionsAll.push(courseSections) currentMaxLength.push(maxLengthIndex) currentSectionIndex.push(0) } //combine information to run clash currentCourseSectionsAll = incFavCourseSections.concat(currentCourseSectionsAll) currentMaxLength = maxLength.concat(currentMaxLength) currentSectionIndex = sectionIndex.concat(currentSectionIndex) //run a modified clash var found = false var ranOut = false var i = 1 //now check for all possible schedules to include only possible sections //note that if sectionIndex[0] >= maxLengthIndex[0] all possibilities have been checked and the algorithm should terminate //while (!checkedAll(sectionIndex, maxLength) && !runBack) { while (!found) { while (i < currentSectionIndex.length) { for (var j = 0; j < i; j++) { while (detectSectionClash(currentCourseSectionsAll[currentSectionIndex[j]], currentCourseSectionsAll[currentSectionIndex[i]])) { currentSectionIndex[i]++ while (currentSectionIndex[i] >= currentMaxLength[i]) { if (i <= 0) { ranOut = true break } currentSectionIndex[i] = 0 i-- currentSectionIndex[i]++ } if (ranOut) break } if (ranOut) break } if (ranOut) break i++ } if (ranOut) break found = true } if (!found) { thisCourse.clash = true } courses[courseIndex] = thisCourse } //it's all done OMG! return courses */ } module.exports.detectCourseClash = detectCourseClash
Continued debugging for clash algorithm Logic and database access bugs
courseClashDetector.js
Continued debugging for clash algorithm
<ide><path>ourseClashDetector.js <ide> parsedTime = time.split(" ") <ide> parsedTime[0] = parsedTime[0].replace(':', '') <ide> mTime = parseInt(parsedTime[0]) <del> if (parsedTime[1] == "pm") { <add> if (parsedTime[1] == "PM" && parsedTime[0].substring(0,2) != "12") { <ide> mTime += 1200 <ide> } <del> <ide> return mTime <ide> } <ide> <ide> //check whether two given timeframes have no overlap by using military time <ide> //if clash, return true <ide> var detectTimeClash = function (startTime1, endTime1, startTime2, endTime2) { <del> if (startTime1 == null || endTime1 == null || startTime2 == null || endTime2 == null) { <add> if (startTime1 == null || endTime1 == null || <add> startTime2 == null || endTime2 == null) { <ide> return false <ide> } <ide> startTime1m = parseMilitaryTime(startTime1) <ide> } <ide> <ide> //classes do not overlap <add> console.log("reached no overlap") <ide> return false <ide> } <ide> <ide> if (section1 == null || section2 == null) { <ide> return false <ide> } <del> //replace Th with Z to help with substring find <del> days1 = section1days.replace("Th", "Z") <del> days2 = section2days.replace("Th", "Z") <del> if (days1 != null && days2 != null) { <del> for (var i = 0; i < days1.length; i++) { <del> if (days2.includes(days1.charAt(i))) { <del> return detectTimeClash(section1.starttime, section1.endtime, section2.starttime, section2.endtime) <del> } <del> } <del> } <add> <add> for (var i = 0; i < section1.schedule.meetings.length; i++) { <add> for (var j = 0; j < section2.schedule.meetings.length; j++) { <add> <add> days1 = section1.schedule.meetings[i].days <add> days2 = section2.schedule.meetings[j].days <add> //replace Th with Z to help with substring find <add> if (days1 != null && days2 != null) { <add> for (var k = 0; k < days1.length; k++) { <add> for (var l = 0; l < days2.length; l++) { <add> if (days1[k] == days2[l]) { <add> return detectTimeClash(section1.schedule.meetings[i].start_time, <add> section1.schedule.meetings[i].end_time, section2.schedule.meetings[j].start_time, <add> section2.schedule.meetings[j].end_time) <add> } <add> } <add> } <add> } <add> } <add> } <add> console.log("no day overlap") <ide> return false <ide> } <ide> <ide> have to make a lot of sense. */ <ide> <ide> var detectCourseClash = function (favoriteCourses, courses, excludeClashingCourses) { <del> <add> <ide> //return all if excludeClashingCourses is false <ide> if (!excludeClashingCourses) <ide> return courses <ide> <ide> //if no courses are favorited, or only one is no clashes can exist <del> if (favoriteCourses.length <= 1) { <add> if (favoriteCourses.length <= 1) <ide> return courses <del> } <ide> <ide> //since favorite courses exist, do initial clash detection within them <ide> //WARNING: THIS HINGES ON THE SECTIONS BEING ORDERED BY SECTION TYPE <ide> <ide> var favCourse = favoriteCourses[currentCourse] <ide> for (var currentClass = 0; currentClass < favCourse.classes.length; currentClass++) { <del> <add> <ide> var currentSection = favCourse.classes[currentClass] <del> console.log(currentSection.schedule) <ide> if (prevSectionType != "" /*&& curSection.section != null*/) { <ide> //new section type within a course, push previous information into arrays <ide> if (prevSectionType != String(currentSection.section).charAt(0)) { <ide> maxLength.push(maxLengthIndex) <ide> maxLengthIndex = 0 <ide> sectionIndex.push(0) <del> } <add> } <ide> } <ide> courseSectionsAll.push(currentSection) <ide> courseSectionsInc.push(false) <ide> sectionIndex.push(0) <ide> } <ide> } <del> console.log(favCourseSectionsAll) <del> return null <del> /* <add> <add> <ide> //if no more than 1 section within all favorite courses (odd but technically possible) return all courses, no clashes <ide> if (sectionIndex.length == 0) <ide> return courses <del> <ide> <ide> var done = false <ide> var i = 1 <ide> //note that if sectionIndex[0] >= maxLengthIndex[0] all possibilities have been checked and the algorithm should terminate <ide> //while (!checkedAll(sectionIndex, maxLength) && !runBack) { <ide> while (!done) { <del> while (i < sectionIndex.length) { <del> for (var j = 0; j < i; j++) { <del> while (detectSectionClash(favCourseSectionsAll[sectionsIndex[j]], favCourseSectionsAll[sectionIndex[i]])) { <del> sectionIndex[i]++ <del> while (sectionIndex[i] >= maxLength[i]) { <del> if (i <= 0) { <del> done = true <del> break <del> } <del> sectionIndex[i] = 0 <del> i-- <del> sectionIndex[i]++ <del> } <del> if (done) <del> break <del> } <del> if (done) <del> break <del> } <del> if (done) <del> break <del> i++ <del> } <del> if (done) <del> break <del> <del> for (var j = 0; j < sectionIndex.length, j++) { <del> favCourseSectionsInc[j][sectionIndex[j]] = true <del> } <del> i-- <del> //update counters <del> sectionIndex[i]++ <del> while (sectionIndex[i] >= maxLength[i]) { <del> if (i <= 0) <del> { <del> done = true <del> break <del> } <del> sectionIndex[i] = 0 <del> i-- <del> sectionIndex[i]++ <del> } <del> } <add> while (i < sectionIndex.length) { <add> for (var j = 0; j < i; j++) { <add> if (detectSectionClash(favCourseSectionsAll[j][sectionIndex[j]], favCourseSectionsAll[i][sectionIndex[i]])) { <add> sectionIndex[i]++ <add> while (sectionIndex[i] >= maxLength[i]) { <add> if (i <= 0) { <add> sectionIndex[0] = 0 <add> done = true <add> break <add> } <add> sectionIndex[i] = 0 <add> i-- <add> sectionIndex[i]++ <add> } <add> j = -1 <add> } <add> if (done) <add> break <add> } <add> if (done) <add> break <add> i++ <add> } <add> if (done) <add> break <add> <add> for (var j = 0; j < sectionIndex.length; j++) { <add> favCourseSectionsInc[j][sectionIndex[j]] = true <add> } <add> <add> //update counters <add> i-- <add> sectionIndex[i]++ <add> while (sectionIndex[i] >= maxLength[i]) { <add> if (i <= 0) { <add> sectionIndex[0] = 0 <add> done = true <add> break <add> } <add> sectionIndex[i] = 0 <add> i-- <add> sectionIndex[i]++ <add> } <add> } <add> <add> console.log(favCourseSectionsInc) <add> <ide> <ide> //favCourseSectionsInc has been updated and can now be used to populate subgraph <ide> var incFavCourseSections = [] <ide> } <ide> incFavCourseSections.push(incSections) <ide> } <del> <del> <add> <add> console.log(incFavCourseSections) <add> console.log(sectionIndex) <add> <add> /* <ide> //now that the original subgraph has been made, run clash on all courses from search results <ide> for (var courseIndex in courses) { <ide> <del> var thisCourse = courses[courseIndex] <del> <del> //each course has new, independent sections <del> var currentCourseSectionsAll = [] <del> var currentMaxLength = [] <del> var currentSectionIndex = [] <del> <del> var prevSectionType = null <del> var courseSectionsAll = [] <del> var maxLengthIndex = 0 <del> <del> for (var section in thisCourse.classes) { <del> if (prevSectionType != null && section.section != null) { <del> //new section type within a course, push previous information into arrays <del> if (prevSectionType != section.section.charAt(0)) { <del> currentCourseSectionsAll.push(courseSections) <del> courseSections = [] <del> currentMaxLength.push(maxLengthIndex) <del> maxLengthIndex = 0 <del> currentSectionIndex.push(0) <del> } <del> } <del> courseSections.push(section) <del> prevSectionType = section.section.charAt(0) <del> maxLengthIndex++ <del> } <del> <del> //all sections seen within course, push information into arrays <del> if (courseSections != null) { <del> currentCourseSectionsAll.push(courseSections) <del> currentMaxLength.push(maxLengthIndex) <del> currentSectionIndex.push(0) <del> } <del> <del> //combine information to run clash <del> currentCourseSectionsAll = incFavCourseSections.concat(currentCourseSectionsAll) <del> currentMaxLength = maxLength.concat(currentMaxLength) <del> currentSectionIndex = sectionIndex.concat(currentSectionIndex) <del> <del> //run a modified clash <del> var found = false <del> var ranOut = false <del> var i = 1 <del> //now check for all possible schedules to include only possible sections <del> //note that if sectionIndex[0] >= maxLengthIndex[0] all possibilities have been checked and the algorithm should terminate <del> //while (!checkedAll(sectionIndex, maxLength) && !runBack) { <del> while (!found) { <del> while (i < currentSectionIndex.length) { <del> for (var j = 0; j < i; j++) { <del> while (detectSectionClash(currentCourseSectionsAll[currentSectionIndex[j]], currentCourseSectionsAll[currentSectionIndex[i]])) { <del> currentSectionIndex[i]++ <del> while (currentSectionIndex[i] >= currentMaxLength[i]) { <del> if (i <= 0) { <del> ranOut = true <del> break <del> } <del> currentSectionIndex[i] = 0 <del> i-- <del> currentSectionIndex[i]++ <del> } <del> if (ranOut) <del> break <del> } <del> if (ranOut) <del> break <del> } <del> if (ranOut) <del> break <del> i++ <del> } <del> if (ranOut) <del> break <del> found = true <del> } <del> if (!found) { <del> thisCourse.clash = true <del> } <del> <del> courses[courseIndex] = thisCourse <del> } <del> <add> var thisCourse = courses[courseIndex] <add> <add> //each course has new, independent sections <add> var currentCourseSectionsAll = [] <add> var currentMaxLength = [] <add> var currentSectionIndex = [] <add> <add> var prevSectionType = null <add> var courseSectionsAll = [] <add> var maxLengthIndex = 0 <add> <add> for (var section in thisCourse.classes) { <add> if (prevSectionType != null && section.section != null) { <add> //new section type within a course, push previous information into arrays <add> if (prevSectionType != section.section.charAt(0)) { <add> currentCourseSectionsAll.push(courseSections) <add> courseSections = [] <add> currentMaxLength.push(maxLengthIndex) <add> maxLengthIndex = 0 <add> currentSectionIndex.push(0) <add> } <add> } <add> courseSections.push(section) <add> prevSectionType = section.section.charAt(0) <add> maxLengthIndex++ <add> } <add> <add> //all sections seen within course, push information into arrays <add> if (courseSections != null) { <add> currentCourseSectionsAll.push(courseSections) <add> currentMaxLength.push(maxLengthIndex) <add> currentSectionIndex.push(0) <add> } <add> <add> //combine information to run clash <add> currentCourseSectionsAll = incFavCourseSections.concat(currentCourseSectionsAll) <add> currentMaxLength = maxLength.concat(currentMaxLength) <add> currentSectionIndex = sectionIndex.concat(currentSectionIndex) <add> <add> //run a modified clash <add> var found = false <add> var ranOut = false <add> var i = 1 <add> //now check for all possible schedules to include only possible sections <add> //note that if sectionIndex[0] >= maxLengthIndex[0] all possibilities have been checked and the algorithm should terminate <add> //while (!checkedAll(sectionIndex, maxLength) && !runBack) { <add> while (!found) { <add> while (i < currentSectionIndex.length) { <add> for (var j = 0; j < i; j++) { <add> while (detectSectionClash(currentCourseSectionsAll[currentSectionIndex[j]], currentCourseSectionsAll[currentSectionIndex[i]])) { <add> currentSectionIndex[i]++ <add> while (currentSectionIndex[i] >= currentMaxLength[i]) { <add> if (i <= 0) { <add> ranOut = true <add> break <add> } <add> currentSectionIndex[i] = 0 <add> i-- <add> currentSectionIndex[i]++ <add> } <add> if (ranOut) <add> break <add> } <add> if (ranOut) <add> break <add>} <add>if (ranOut) <add> break <add>i++ <add>} <add>if (ranOut) <add> break <add> <add>found = true <add> <add>if (!found) { <add> thisCourse.clash = true <add>} <add> <add>courses[courseIndex] = thisCourse <add>} <add> <add> <add>} <add>*/ <ide> //it's all done OMG! <ide> return courses <del> <del> */ <del>} <del> <del> <add>} <ide> module.exports.detectCourseClash = detectCourseClash
Java
apache-2.0
2765b16a9383638c139fc10f32c347b33d1e0ec7
0
apache/geronimo,apache/geronimo,apache/geronimo,apache/geronimo
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mavenplugins.selenium; import java.io.File; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.FileWriter; import java.net.URL; import java.net.MalformedURLException; import java.util.Map; import org.apache.maven.project.MavenProject; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.geronimo.genesis.ant.AntMojoSupport; import org.apache.geronimo.genesis.util.ObjectHolder; import org.apache.commons.io.IOUtils; import org.apache.tools.ant.taskdefs.Java; import org.apache.tools.ant.types.Environment; import org.apache.tools.ant.types.Path; import org.codehaus.plexus.util.FileUtils; /** * Start the Selenium server. * * @goal start-server * * @version $Rev$ $Date$ */ public class StartServerMojo extends AntMojoSupport { /** * The port number the server will use. * * @parameter expression="${port}" default-value="4444" */ private int port = -1; /** * Timeout for the server in seconds. * * @parameter expression="${timeout}" default-value="-1" */ private int timeout = -1; /** * Enable the server's debug mode.. * * @parameter expression="${debug}" default-value="false" */ private boolean debug = false; /** * The file or resource to use for default user-extentions.js. * * @parameter default-value="org/apache/geronimo/mavenplugins/selenium/default-user-extentions.js" */ private String defaultUserExtensions = null; /** * Enable or disable default user-extentions.js * * @parameter default-value="true" */ private boolean defaultUserExtensionsEnabled = true; /** * Location of the user-extentions.js to load into the server. * If defaultUserExtensionsEnabled is true, then this file will be appended to the defaults. * * @parameter */ private String userExtensions = null; /** * Map of of plugin artifacts. * * @parameter expression="${plugin.artifactMap}" * @required * @readonly */ private Map pluginArtifactMap = null; /** * Working directory where Selenium server will be started from. * * @parameter expression="${project.build.directory}/selenium" * @required */ private File workingDirectory = null; /** * Enable logging mode. * * @parameter expression="${logOutput}" default-value="false" */ protected boolean logOutput = false; /** * The file that Selenium server logs will be written to. * * @parameter expression="${logFile}" default-value="${project.build.directory}/selenium/server.log" * @required */ private File logFile = null; /** * Flag to control if we background the server or block Maven execution. * * @parameter default-value="false" * @required */ private boolean background = false; // // MojoSupport Hooks // /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project = null; protected MavenProject getProject() { return project; } // // Mojo // private File getPluginArchive() { String path = getClass().getProtectionDomain().getCodeSource().getLocation().getFile(); return new File(path); } private Artifact getPluginArtifact(final String name) throws MojoExecutionException { Artifact artifact = (Artifact)pluginArtifactMap.get(name); if (artifact == null) { throw new MojoExecutionException("Unable to locate '" + name + "' in the list of plugin artifacts"); } return artifact; } protected void doExecute() throws Exception { log.info("Starting Selenium server..."); final Java java = (Java)createTask("java"); FileUtils.forceMkdir(workingDirectory); java.setFork(true); java.setDir(workingDirectory); java.setFailonerror(true); if (logOutput) { FileUtils.forceMkdir(logFile.getParentFile()); log.info("Redirecting output to: " + logFile); java.setOutput(logFile); } java.setClassname("org.openqa.selenium.server.SeleniumServer"); Path classpath = java.createClasspath(); classpath.createPathElement().setLocation(getPluginArchive()); classpath.createPathElement().setLocation(getPluginArtifact("log4j:log4j").getFile()); classpath.createPathElement().setLocation(getPluginArtifact("org.openqa.selenium.server:selenium-server").getFile()); Environment.Variable var; var = new Environment.Variable(); var.setKey("selenium.log"); var.setFile(logFile); java.addSysproperty(var); var = new Environment.Variable(); var.setKey("selenium.loglevel"); var.setValue(debug == true ? "DEBUG" : "INFO"); java.addSysproperty(var); var = new Environment.Variable(); var.setKey("log4j.configuration"); var.setValue("org/apache/geronimo/mavenplugins/selenium/log4j.properties"); java.addSysproperty(var); // Server arguments java.createArg().setValue("-port"); java.createArg().setValue(String.valueOf(port)); if (debug) { java.createArg().setValue("-debug"); } if (timeout > 0) { log.info("Timeout after: " + timeout + " seconds"); java.createArg().setValue("-timeout"); java.createArg().setValue(String.valueOf(timeout)); } File userExtentionsFile = getUserExtentionsFile(); if (userExtentionsFile != null) { log.info("User extensions: " + userExtentionsFile); java.createArg().setValue("-userExtensions"); java.createArg().setFile(userExtentionsFile); } // Holds any exception that was thrown during startup final ObjectHolder errorHolder = new ObjectHolder(); // Start the server int a seperate thread Thread t = new Thread("Selenium Server Runner") { public void run() { try { java.execute(); } catch (Exception e) { errorHolder.set(e); // // NOTE: Don't log here, as when the JVM exists an exception will get thrown by Ant // but that should be fine. // } } }; t.start(); log.debug("Waiting for Selenium server..."); // Verify server started URL url = new URL("http://localhost:" + port + "/selenium-server"); boolean started = false; while (!started) { if (errorHolder.isSet()) { throw new MojoExecutionException("Failed to start Selenium server", (Throwable)errorHolder.get()); } log.debug("Trying connection to: " + url); try { Object input = url.openConnection().getContent(); started = true; } catch (Exception e) { // ignore } Thread.sleep(1000); } log.info("Selenium server started"); if (!background) { log.info("Waiting for Selenium to shutdown..."); t.join(); } } /** * Resolve a resource to a file, URL or resource. */ private URL resolveResource(final String name) throws MalformedURLException, MojoFailureException { assert name != null; URL url; File file = new File(name); if (file.exists()) { url = file.toURL(); } else { try { url = new URL(name); } catch (MalformedURLException e) { url = Thread.currentThread().getContextClassLoader().getResource(name); } } if (url == null) { throw new MojoFailureException("Could not resolve resource: " + name); } log.debug("Resolved resource '" + name + "' as: " + url); return url; } /** * Retutn the user-extentions.js file to use, or null if it should not be installed. */ private File getUserExtentionsFile() throws Exception { if (!defaultUserExtensionsEnabled && userExtensions == null) { return null; } // File needs to be named 'user-extensions.js' or Selenium server will puke File file = new File(workingDirectory, "user-extensions.js"); if (file.exists()) { log.debug("Reusing previously generated file: " + file); return file; } PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file))); if (defaultUserExtensionsEnabled) { URL url = resolveResource(defaultUserExtensions); log.debug("Using defaults: " + url); writer.println("//"); writer.println("// Default user extentions; from: " + url); writer.println("//"); IOUtils.copy(url.openStream(), writer); } if (userExtensions != null) { URL url = resolveResource(userExtensions); log.debug("Using user extentions: " + url); writer.println("//"); writer.println("// User extentions; from: " + url); writer.println("//"); IOUtils.copy(url.openStream(), writer); } writer.flush(); writer.close(); return file; } }
maven-plugins/selenium-maven-plugin/src/main/java/org/apache/geronimo/mavenplugins/selenium/StartServerMojo.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.geronimo.mavenplugins.selenium; import java.io.File; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.FileWriter; import java.net.URL; import java.net.MalformedURLException; import java.util.Map; import org.apache.maven.project.MavenProject; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.geronimo.genesis.ant.AntMojoSupport; import org.apache.geronimo.genesis.util.ObjectHolder; import org.apache.commons.io.IOUtils; import org.apache.tools.ant.taskdefs.Java; import org.apache.tools.ant.types.Environment; import org.apache.tools.ant.types.Path; import org.codehaus.plexus.util.FileUtils; /** * Start the Selenium server. * * @goal start-server * * @version $Rev$ $Date$ */ public class StartServerMojo extends AntMojoSupport { /** * The port number the server will use. * * @parameter expression="${port}" default-value="4444" */ private int port = -1; /** * Timeout for the server in seconds. * * @parameter expression="${timeout}" default-value="-1" */ private int timeout = -1; /** * Enable the server's debug mode.. * * @parameter expression="${debug}" default-value="false" */ private boolean debug = false; /** * The file or resource to use for default user-extentions.js. * * @parameter default-value="org/apache/geronimo/mavenplugins/selenium/default-user-extentions.js" */ private String defaultUserExtensions = null; /** * Enable or disable default user-extentions.js * * @parameter default-value="true" */ private boolean defaultUserExtensionsEnabled = true; /** * Location of the user-extentions.js to load into the server. * If defaultUserExtensionsEnabled is true, then this file will be appended to the defaults. * * @parameter */ private String userExtensions = null; /** * Map of of plugin artifacts. * * @parameter expression="${plugin.artifactMap}" * @required * @readonly */ private Map pluginArtifactMap = null; /** * Working directory where Selenium server will be started from. * * @parameter expression="${project.build.directory}/selenium" * @required */ private File workingDirectory = null; /** * Enable logging mode. * * @parameter expression="${logOutput}" default-value="false" */ protected boolean logOutput = false; /** * The file that Selenium server logs will be written to. * * @parameter expression="${logFile}" default-value="${project.build.directory}/selenium/server.log" * @required */ private File logFile = null; /** * Flag to control if we background the server or block Maven execution. * * @parameter default-value="false" * @required */ private boolean background = false; // // MojoSupport Hooks // /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project = null; protected MavenProject getProject() { return project; } // // Mojo // private File getPluginArchive() { String path = getClass().getProtectionDomain().getCodeSource().getLocation().getFile(); return new File(path); } private Artifact getPluginArtifact(final String name) throws MojoExecutionException { Artifact artifact = (Artifact)pluginArtifactMap.get(name); if (artifact == null) { throw new MojoExecutionException("Unable to locate '" + name + "' in the list of plugin artifacts"); } return artifact; } protected void doExecute() throws Exception { log.info("Starting Selenium server..."); final Java java = (Java)createTask("java"); FileUtils.forceMkdir(workingDirectory); java.setFork(true); java.setDir(workingDirectory); java.setFailonerror(true); if (logOutput) { FileUtils.forceMkdir(logFile.getParentFile()); log.info("Redirecting output to: " + logFile); java.setLogError(true); java.setOutput(logFile); } java.setClassname("org.openqa.selenium.server.SeleniumServer"); Path classpath = java.createClasspath(); classpath.createPathElement().setLocation(getPluginArchive()); classpath.createPathElement().setLocation(getPluginArtifact("log4j:log4j").getFile()); classpath.createPathElement().setLocation(getPluginArtifact("org.openqa.selenium.server:selenium-server").getFile()); Environment.Variable var; var = new Environment.Variable(); var.setKey("selenium.log"); var.setFile(logFile); java.addSysproperty(var); var = new Environment.Variable(); var.setKey("selenium.loglevel"); var.setValue(debug == true ? "DEBUG" : "INFO"); java.addSysproperty(var); var = new Environment.Variable(); var.setKey("log4j.configuration"); var.setValue("org/apache/geronimo/mavenplugins/selenium/log4j.properties"); java.addSysproperty(var); // Server arguments java.createArg().setValue("-port"); java.createArg().setValue(String.valueOf(port)); if (debug) { java.createArg().setValue("-debug"); } if (timeout > 0) { log.info("Timeout after: " + timeout + " seconds"); java.createArg().setValue("-timeout"); java.createArg().setValue(String.valueOf(timeout)); } File userExtentionsFile = getUserExtentionsFile(); if (userExtentionsFile != null) { log.info("User extensions: " + userExtentionsFile); java.createArg().setValue("-userExtensions"); java.createArg().setFile(userExtentionsFile); } // Holds any exception that was thrown during startup final ObjectHolder errorHolder = new ObjectHolder(); // Start the server int a seperate thread Thread t = new Thread("Selenium Server Runner") { public void run() { try { java.execute(); } catch (Exception e) { errorHolder.set(e); // // NOTE: Don't log here, as when the JVM exists an exception will get thrown by Ant // but that should be fine. // } } }; t.start(); log.debug("Waiting for Selenium server..."); // Verify server started URL url = new URL("http://localhost:" + port + "/selenium-server"); boolean started = false; while (!started) { if (errorHolder.isSet()) { throw new MojoExecutionException("Failed to start Selenium server", (Throwable)errorHolder.get()); } log.debug("Trying connection to: " + url); try { Object input = url.openConnection().getContent(); started = true; } catch (Exception e) { // ignore } Thread.sleep(1000); } log.info("Selenium server started"); if (!background) { log.info("Waiting for Selenium to shutdown..."); t.join(); } } /** * Resolve a resource to a file, URL or resource. */ private URL resolveResource(final String name) throws MalformedURLException, MojoFailureException { assert name != null; URL url; File file = new File(name); if (file.exists()) { url = file.toURL(); } else { try { url = new URL(name); } catch (MalformedURLException e) { url = Thread.currentThread().getContextClassLoader().getResource(name); } } if (url == null) { throw new MojoFailureException("Could not resolve resource: " + name); } log.debug("Resolved resource '" + name + "' as: " + url); return url; } /** * Retutn the user-extentions.js file to use, or null if it should not be installed. */ private File getUserExtentionsFile() throws Exception { if (!defaultUserExtensionsEnabled && userExtensions == null) { return null; } // File needs to be named 'user-extensions.js' or Selenium server will puke File file = new File(workingDirectory, "user-extensions.js"); if (file.exists()) { log.debug("Reusing previously generated file: " + file); return file; } PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(file))); if (defaultUserExtensionsEnabled) { URL url = resolveResource(defaultUserExtensions); log.debug("Using defaults: " + url); writer.println("//"); writer.println("// Default user extentions; from: " + url); writer.println("//"); IOUtils.copy(url.openStream(), writer); } if (userExtensions != null) { URL url = resolveResource(userExtensions); log.debug("Using user extentions: " + url); writer.println("//"); writer.println("// User extentions; from: " + url); writer.println("//"); IOUtils.copy(url.openStream(), writer); } writer.flush(); writer.close(); return file; } }
Do not let ant log errors... allow all output to be captured by the log file git-svn-id: 0d16bf2c240b8111500ec482b35765e5042f5526@463568 13f79535-47bb-0310-9956-ffa450edef68
maven-plugins/selenium-maven-plugin/src/main/java/org/apache/geronimo/mavenplugins/selenium/StartServerMojo.java
Do not let ant log errors... allow all output to be captured by the log file
<ide><path>aven-plugins/selenium-maven-plugin/src/main/java/org/apache/geronimo/mavenplugins/selenium/StartServerMojo.java <ide> <ide> log.info("Redirecting output to: " + logFile); <ide> <del> java.setLogError(true); <ide> java.setOutput(logFile); <ide> } <ide>
Java
apache-2.0
5f49fa243006cc6e503161ae90862157d57b0ca2
0
mikosik/smooth-build,mikosik/smooth-build
package org.smoothbuild.acceptance.lang; import static com.google.common.truth.Truth.assertThat; import static java.lang.String.format; import java.io.IOException; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.smoothbuild.acceptance.AcceptanceTestCase; import org.smoothbuild.acceptance.testing.StringIdentity; import org.smoothbuild.acceptance.testing.ThrowException; public class FunctionTest extends AcceptanceTestCase { @Nested class parameter_default_argument { @Nested class _in_defined_function { @Test public void is_used_when_parameter_has_no_value_assigned_in_call() throws Exception { createUserModule(""" func(String withDefault = "abc") = withDefault; result = func(); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void is_ignored_when_parameter_is_assigned_in_a_call() throws Exception { createUserModule(""" func(String withDefault = "abc") = withDefault; result = func("def"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("def"); } @Test public void is_not_evaluated_when_not_needed() throws Exception { createNativeJar(ThrowException.class); createUserModule(format(""" @Native("%s.function") Nothing throwException(); func(String withDefault = throwException()) = withDefault; result = func("def"); """, ThrowException.class.getCanonicalName())); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("def"); } } @Nested class _in_native_function { @Test public void is_used_when_parameter_has_no_value_assigned_in_call() throws Exception { createNativeJar(StringIdentity.class); createUserModule(format(""" @Native("%s.function") String stringIdentity(String value = "abc"); result = stringIdentity(); """, StringIdentity.class.getCanonicalName())); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void is_ignored_when_parameter_is_assigned_in_a_call() throws Exception { createNativeJar(StringIdentity.class); createUserModule(format(""" @Native("%s.function") String stringIdentity(String value = "abc"); result = stringIdentity("def"); """, StringIdentity.class.getCanonicalName())); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("def"); } @Test public void is_not_evaluated_when_not_needed() throws Exception { createNativeJar(StringIdentity.class, ThrowException.class); createUserModule(format(""" @Native("%s.function") String stringIdentity(String value = throwException()); @Native("%s.function") Nothing throwException(); result = stringIdentity("def"); """, StringIdentity.class.getCanonicalName(), ThrowException.class.getCanonicalName())); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("def"); } } } @Nested class parameter_that_shadows { @Nested class imported { @Test public void value_makes_it_inaccessible() throws IOException { createUserModule(""" String myFunction(String true) = true; result = myFunction("abc"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void function_makes_it_inaccessible() throws IOException { createUserModule(""" String myFunction(String and) = and; result = myFunction("abc"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } } @Nested class local { @Test public void value_makes_it_inaccessible() throws IOException { createUserModule(""" localValue = true; String myFunction(String localValue) = localValue; result = myFunction("abc"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void function_makes_it_inaccessible() throws IOException { createUserModule(""" localFunction() = true; String myFunction(String localFunction) = localFunction; result = myFunction("abc"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } } } @Test public void calling_defined_function_with_one_parameter() throws Exception { createUserModule(""" func(String string) = "abc"; result = func("def"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void calling_defined_function_that_returns_parameter() throws Exception { createUserModule(""" func(String string) = string; result = func("abc"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void argument_is_not_evaluated_when_assigned_to_not_used_parameter() throws Exception { createNativeJar(ThrowException.class); createUserModule(""" @Native("impl") Nothing throwException(); func(String notUsedParameter) = "abc"; result = func(throwException()); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void function_can_be_argument_to_other_function() throws Exception { createNativeJar(ThrowException.class); createUserModule(""" String returnAbc() = "abc"; A invokeProducer(A() producer) = producer(); result = invokeProducer(returnAbc); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void function_can_be_result_of_other_function() throws Exception { createNativeJar(ThrowException.class); createUserModule(""" String returnAbc() = "abc"; String() createProducer() = returnAbc; result = createProducer()(); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } }
src/acceptance/org/smoothbuild/acceptance/lang/FunctionTest.java
package org.smoothbuild.acceptance.lang; import static com.google.common.truth.Truth.assertThat; import java.io.IOException; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.smoothbuild.acceptance.AcceptanceTestCase; import org.smoothbuild.acceptance.testing.ThrowException; public class FunctionTest extends AcceptanceTestCase { @Nested class parameter_default_argument { @Test public void is_used_when_parameter_has_no_value_assigned_in_call() throws Exception { createUserModule(""" func(String withDefault = "abc") = withDefault; result = func(); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void is_ignored_when_parameter_is_assigned_in_a_call() throws Exception { createUserModule(""" func(String withDefault = "abc") = withDefault; result = func("def"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("def"); } @Test public void is_not_evaluated_when_not_needed() throws Exception { createNativeJar(ThrowException.class); createUserModule(""" @Native("impl") Nothing throwException(); func(String withDefault = throwException()) = withDefault; result = func("def"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("def"); } } @Nested class parameter_that_shadows { @Nested class imported { @Test public void value_makes_it_inaccessible() throws IOException { createUserModule(""" String myFunction(String true) = true; result = myFunction("abc"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void function_makes_it_inaccessible() throws IOException { createUserModule(""" String myFunction(String and) = and; result = myFunction("abc"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } } @Nested class local { @Test public void value_makes_it_inaccessible() throws IOException { createUserModule(""" localValue = true; String myFunction(String localValue) = localValue; result = myFunction("abc"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void function_makes_it_inaccessible() throws IOException { createUserModule(""" localFunction() = true; String myFunction(String localFunction) = localFunction; result = myFunction("abc"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } } } @Test public void calling_defined_function_with_one_parameter() throws Exception { createUserModule(""" func(String string) = "abc"; result = func("def"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void calling_defined_function_that_returns_parameter() throws Exception { createUserModule(""" func(String string) = string; result = func("abc"); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void argument_is_not_evaluated_when_assigned_to_not_used_parameter() throws Exception { createNativeJar(ThrowException.class); createUserModule(""" @Native("impl") Nothing throwException(); func(String notUsedParameter) = "abc"; result = func(throwException()); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void function_can_be_argument_to_other_function() throws Exception { createNativeJar(ThrowException.class); createUserModule(""" String returnAbc() = "abc"; A invokeProducer(A() producer) = producer(); result = invokeProducer(returnAbc); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } @Test public void function_can_be_result_of_other_function() throws Exception { createNativeJar(ThrowException.class); createUserModule(""" String returnAbc() = "abc"; String() createProducer() = returnAbc; result = createProducer()(); """); runSmoothBuild("result"); assertFinishedWithSuccess(); assertThat(artifactFileContentAsString("result")) .isEqualTo("abc"); } }
added test cases to FunctionTest.parameter_default_argument concerning native functions
src/acceptance/org/smoothbuild/acceptance/lang/FunctionTest.java
added test cases to FunctionTest.parameter_default_argument concerning native functions
<ide><path>rc/acceptance/org/smoothbuild/acceptance/lang/FunctionTest.java <ide> package org.smoothbuild.acceptance.lang; <ide> <ide> import static com.google.common.truth.Truth.assertThat; <add>import static java.lang.String.format; <ide> <ide> import java.io.IOException; <ide> <ide> import org.junit.jupiter.api.Nested; <ide> import org.junit.jupiter.api.Test; <ide> import org.smoothbuild.acceptance.AcceptanceTestCase; <add>import org.smoothbuild.acceptance.testing.StringIdentity; <ide> import org.smoothbuild.acceptance.testing.ThrowException; <ide> <ide> public class FunctionTest extends AcceptanceTestCase { <ide> @Nested <ide> class parameter_default_argument { <del> @Test <del> public void is_used_when_parameter_has_no_value_assigned_in_call() throws Exception { <del> createUserModule(""" <add> @Nested <add> class _in_defined_function { <add> @Test <add> public void is_used_when_parameter_has_no_value_assigned_in_call() throws Exception { <add> createUserModule(""" <ide> func(String withDefault = "abc") = withDefault; <ide> result = func(); <ide> """); <del> runSmoothBuild("result"); <del> assertFinishedWithSuccess(); <del> assertThat(artifactFileContentAsString("result")) <del> .isEqualTo("abc"); <del> } <del> <del> @Test <del> public void is_ignored_when_parameter_is_assigned_in_a_call() throws Exception { <del> createUserModule(""" <add> runSmoothBuild("result"); <add> assertFinishedWithSuccess(); <add> assertThat(artifactFileContentAsString("result")) <add> .isEqualTo("abc"); <add> } <add> <add> @Test <add> public void is_ignored_when_parameter_is_assigned_in_a_call() throws Exception { <add> createUserModule(""" <ide> func(String withDefault = "abc") = withDefault; <ide> result = func("def"); <ide> """); <del> runSmoothBuild("result"); <del> assertFinishedWithSuccess(); <del> assertThat(artifactFileContentAsString("result")) <del> .isEqualTo("def"); <del> } <del> <del> @Test <del> public void is_not_evaluated_when_not_needed() throws Exception { <del> createNativeJar(ThrowException.class); <del> createUserModule(""" <del> @Native("impl") <add> runSmoothBuild("result"); <add> assertFinishedWithSuccess(); <add> assertThat(artifactFileContentAsString("result")) <add> .isEqualTo("def"); <add> } <add> <add> @Test <add> public void is_not_evaluated_when_not_needed() throws Exception { <add> createNativeJar(ThrowException.class); <add> createUserModule(format(""" <add> @Native("%s.function") <ide> Nothing throwException(); <ide> func(String withDefault = throwException()) = withDefault; <ide> result = func("def"); <del> """); <del> runSmoothBuild("result"); <del> assertFinishedWithSuccess(); <del> assertThat(artifactFileContentAsString("result")) <del> .isEqualTo("def"); <add> """, ThrowException.class.getCanonicalName())); <add> runSmoothBuild("result"); <add> assertFinishedWithSuccess(); <add> assertThat(artifactFileContentAsString("result")) <add> .isEqualTo("def"); <add> } <add> } <add> <add> @Nested <add> class _in_native_function { <add> @Test <add> public void is_used_when_parameter_has_no_value_assigned_in_call() throws Exception { <add> createNativeJar(StringIdentity.class); <add> createUserModule(format(""" <add> @Native("%s.function") <add> String stringIdentity(String value = "abc"); <add> result = stringIdentity(); <add> """, StringIdentity.class.getCanonicalName())); <add> runSmoothBuild("result"); <add> assertFinishedWithSuccess(); <add> assertThat(artifactFileContentAsString("result")) <add> .isEqualTo("abc"); <add> } <add> <add> @Test <add> public void is_ignored_when_parameter_is_assigned_in_a_call() throws Exception { <add> createNativeJar(StringIdentity.class); <add> createUserModule(format(""" <add> @Native("%s.function") <add> String stringIdentity(String value = "abc"); <add> result = stringIdentity("def"); <add> """, StringIdentity.class.getCanonicalName())); <add> runSmoothBuild("result"); <add> assertFinishedWithSuccess(); <add> assertThat(artifactFileContentAsString("result")) <add> .isEqualTo("def"); <add> } <add> <add> @Test <add> public void is_not_evaluated_when_not_needed() throws Exception { <add> createNativeJar(StringIdentity.class, ThrowException.class); <add> createUserModule(format(""" <add> @Native("%s.function") <add> String stringIdentity(String value = throwException()); <add> @Native("%s.function") <add> Nothing throwException(); <add> result = stringIdentity("def"); <add> """, StringIdentity.class.getCanonicalName(), ThrowException.class.getCanonicalName())); <add> runSmoothBuild("result"); <add> assertFinishedWithSuccess(); <add> assertThat(artifactFileContentAsString("result")) <add> .isEqualTo("def"); <add> } <ide> } <ide> } <ide>
Java
bsd-3-clause
10d11ba6a8ec9d694b795bb9b536b25b816a0b22
0
bdezonia/zorbage,bdezonia/zorbage
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (c) 2016-2021 Barry DeZonia All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the <copyright holder> nor the names of its contributors may * be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package nom.bdezonia.zorbage.dataview; import java.math.BigDecimal; import nom.bdezonia.zorbage.algebra.Allocatable; import nom.bdezonia.zorbage.algebra.Dimensioned; import nom.bdezonia.zorbage.coordinates.CoordinateSpace; import nom.bdezonia.zorbage.coordinates.LinearNdCoordinateSpace; import nom.bdezonia.zorbage.data.DimensionedDataSource; import nom.bdezonia.zorbage.data.DimensionedStorage; /** * * @author Barry DeZonia * * @param <U> */ public class PlaneView<U> implements Dimensioned { private final int axisNumber0; // axis number 1 in parent data source private final int axisNumber1; // axis number 2 in parent data source private final long axisNumber0Size; // dimension of axis number 1 private final long axisNumber1Size; // dimension of axis number 2 private final Accessor<U> accessor; private final DimensionedDataSource<U> data; /** * Construct a view from an {@link DimensionedDataSource} and some dimensions. * * @param data The n-d data source the view is being built around. * @param axis0 The axis number of the "x" component in the data source * @param axis1 The axis number of the "y" component in the data source */ public PlaneView(DimensionedDataSource<U> data, int axis0, int axis1) { int numD = data.numDimensions(); if (numD == 0) throw new IllegalArgumentException( "data source must have at least 1 dimension"); if (axis0 == axis1) throw new IllegalArgumentException("same coordinate axis specified twice"); if (axis0 >= axis1) throw new IllegalArgumentException( "axis specified out of order: all numbers assume left to right declaration"); if (axis0 < 0 || axis0 >= numD) throw new IllegalArgumentException("coordinate component 0 is outside number of dimensions"); if (axis1 < 0 || ((numD == 1 && axis1 > 1) || (numD > 1 && axis1 >= numD))) throw new IllegalArgumentException("coordinate component 1 is outside number of dimensions"); this.data = data; this.axisNumber0 = axis0; this.axisNumber1 = axis1; this.axisNumber0Size = data.dimension(axis0); this.axisNumber1Size = numD == 1 ? 1 : data.dimension(axis1); switch (numD) { case 1: accessor = new Accessor1d<U>(data); break; case 2: accessor = new Accessor2d<U>(data); break; case 3: accessor = new Accessor3d<U>(data); break; case 4: accessor = new Accessor4d<U>(data); break; case 5: accessor = new Accessor5d<U>(data); break; case 6: accessor = new Accessor6d<U>(data); break; case 7: accessor = new Accessor7d<U>(data); break; case 8: accessor = new Accessor8d<U>(data); break; case 9: accessor = new Accessor9d<U>(data); break; case 10: accessor = new Accessor10d<U>(data); break; default: throw new IllegalArgumentException(""+numD+" dimensions not yet supported in PlaneView"); } } /** * Returns the {@link DimensionedDataSource} that the PlaneView is attached to. */ public DimensionedDataSource<U> getDataSource() { return data; } /** * Returns the 0th dimension of the view. */ public long d0() { return axisNumber0Size; } /** * Returns the 1th dimension of the view. */ public long d1() { return axisNumber1Size; } /** * A view.get() call will pull the value at the view input coordinates * from the data set into val. No index out of bounds checking is done. * * @param i0 0th view input coord * @param i1 1th view input coord * @param val The output where the result is placed */ public void get(long i0, long i1, U val) { accessor.get(i0, i1, val); } /** * A planeView.set() call will push the value at the view input * coordinates into the data set. No index out of bounds checking * is done. * * @param i0 0th view input coord * @param i1 1th view input coord * @param val The input that is stored in the underlying data set */ public void set(long i0, long i1, U val) { accessor.set(i0, i1, val); } /** * A planeView.safeGet() call will do a get() call provided the * passed index coordinate values fit within the view's dimensions. * If not an exception is thrown instead. */ public void safeGet(long i0, long i1, U val) { if (outOfBounds(i0, i1)) { throw new IllegalArgumentException("view index out of bounds"); } else get(i0, i1, val); } /** * A planeView.safeSet() call will do a set() call provided the * passed index coordinate values fit within the view's dimensions. * If not an exception is thrown instead. */ public void safeSet(long i0, long i1, U val) { if (outOfBounds(i0, i1)) { throw new IllegalArgumentException("view index out of bounds"); } else set(i0, i1, val); } /** * Return the column number of 0th index view position * (i.e. which column is "x" in the view). */ public int axisNumber0() { return axisNumber0; } /** * Return the column number of 1th index view position * (i.e. which column is "y" in the view). */ public int axisNumber1() { return axisNumber1; } /** * Return the number of dimensions in the view. */ @Override public int numDimensions() { return 2; } /** * Retrieve each view dimension by index. Throws an exception if * the dimension index number is outside the view dimensions. */ @Override public long dimension(int d) { if (d == 0) return axisNumber0Size; if (d == 1) return axisNumber1Size; throw new IllegalArgumentException("dimension out of bounds"); } /** * Returns the number of dimensions beyond 2 that this PlaneView can manipulate. * @return */ public int getPositionsCount() { return accessor.getPositionsCount(); } /** * Set the position value of one of the dimensions of the PlaneView */ public void setPositionValue(int i, long v) { accessor.setPositionValue(i, v); } /** * Get the position value of one of the dimensions of the PlaneView */ public long getPositionValue(int i) { return accessor.getPositionValue(i); } /** * Translates the dimensions associated with sliders into their own * original coordinate position of the parent data source. That's * kind of confusing. Imagine you have a 5d dataset. Your "x" and "y" * coord positions were set to 1 and 3. The planeView stores the 3 * non-planar dims as 0, 1, and 2. But their original coord positions * in the parent data source were 0, 2, and 4. This method maps 0/1/2 * into 0/2/4 in this one case. * * @param extraDimPos * @return */ public int getDataSourceAxisNumber(int extraDimPos) { int counted = 0; for (int i = 0; i < data.numDimensions(); i++) { if (i == axisNumber0 || i == axisNumber1) continue; if (counted == extraDimPos) return i; counted++; } return -1; } /** * Returns the dimension of extra axis i in the parent data source * * @param extraDimPos * @return */ public long getDataSourceAxisSize(int extraDimPos) { int pos = getDataSourceAxisNumber(extraDimPos); return data.dimension(pos); } /** * Returns the model coords of the point on the model currently * associated with the i0/i1 coords and the current slider * positions. * * @param i0 * @param i1 * @param modelCoords */ public void getModelCoords(long i0, long i1, long[] modelCoords) { for (int i = 0; i < getPositionsCount(); i++) { int pos = getDataSourceAxisNumber(i); long value = getPositionValue(i); modelCoords[pos] = value; } modelCoords[axisNumber0] = i0; modelCoords[axisNumber1] = i1; } /** * Get a snapshot of a whole plane of data using the current axis positions * and "x" and "y" axis designations. So one can easily generate a Y/Z plane * where X == 250, for example. * * @param scratchVar A variable that the routine will use in its calcs. * * @return */ @SuppressWarnings("unchecked") public <V extends Allocatable<V>> DimensionedDataSource<U> copyPlane(U scratchVar) { DimensionedDataSource<U> newDs = (DimensionedDataSource<U>) DimensionedStorage.allocate((V) scratchVar, new long[] {axisNumber0Size,axisNumber1Size}); TwoDView<U> view = new TwoDView<>(newDs); for (long y = 0; y < axisNumber1Size; y++) { for (long x = 0; x < axisNumber0Size; x++) { accessor.get(x, y, scratchVar); view.set(x, y, scratchVar); } } String d0Str = data.getAxisType(axisNumber0) == null ? ("dim "+axisNumber0) : data.getAxisType(axisNumber0); String d1Str = data.getAxisType(axisNumber1) == null ? ("dim "+axisNumber1) : data.getAxisType(axisNumber1); String axes = "["+d0Str+":"+d1Str+"]"; String miniTitle = axes + "slice"; newDs.setName(data.getName() == null ? miniTitle : (miniTitle + " of "+data.getName())); newDs.setAxisType(0, data.getAxisType(axisNumber0)); newDs.setAxisType(1, data.getAxisType(axisNumber1)); newDs.setAxisUnit(0, data.getAxisUnit(axisNumber0)); newDs.setAxisUnit(1, data.getAxisUnit(axisNumber1)); newDs.setValueType(data.getValueType()); newDs.setValueUnit(data.getValueUnit()); CoordinateSpace origSpace = data.getCoordinateSpace(); if (origSpace instanceof LinearNdCoordinateSpace) { LinearNdCoordinateSpace origLinSpace = (LinearNdCoordinateSpace) data.getCoordinateSpace(); BigDecimal[] scales = new BigDecimal[2]; scales[0] = origLinSpace.getScale(axisNumber0); scales[1] = origLinSpace.getScale(axisNumber1); BigDecimal[] offsets = new BigDecimal[2]; offsets[0] = origLinSpace.getOffset(axisNumber0); offsets[1] = origLinSpace.getOffset(axisNumber1); LinearNdCoordinateSpace newLinSpace = new LinearNdCoordinateSpace(scales, offsets); newDs.setCoordinateSpace(newLinSpace); } return newDs; } // ---------------------------------------------------------------------- // PRIVATE DECLARATIONS FOLLOW // ---------------------------------------------------------------------- private boolean outOfBounds(long i0, long i1) { if (i0 < 0 || i0 >= axisNumber0Size) return true; if (i1 < 0 || i1 >= axisNumber1Size) return true; return false; } private interface Accessor<X> { void set(long i0, long i1, X value); void get(long i0, long i1, X value); int getPositionsCount(); void setPositionValue(int i, long v); long getPositionValue(int i); } private abstract class AccessorBase { private long[] extraDimPositions; AccessorBase(int numD) { int size = numD - 2; if (size < 0) size = 0; extraDimPositions = new long[size]; } public int getPositionsCount() { return extraDimPositions.length; } public void setPositionValue(int i, long v) { if (i < 0 || i >= extraDimPositions.length) throw new IllegalArgumentException("illegal extra dim position"); extraDimPositions[i] = v; } public long getPositionValue(int i) { if (i < 0 || i >= extraDimPositions.length) throw new IllegalArgumentException("illegal extra dim position"); return extraDimPositions[i]; } } private class Accessor1d<X> extends AccessorBase implements Accessor<X> { private final OneDView<X> view; Accessor1d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new OneDView<>(data); } @Override public void set(long i0, long i1, X value) { view.set(i0, value); } @Override public void get(long i0, long i1, X value) { view.get(i0, value); } } private class Accessor2d<X> extends AccessorBase implements Accessor<X> { private final TwoDView<X> view; Accessor2d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new TwoDView<>(data); } @Override public void set(long i0, long i1, X value) { view.set(i0, i1, value); } @Override public void get(long i0, long i1, X value) { view.get(i0, i1, value); } } private class Accessor3d<X> extends AccessorBase implements Accessor<X> { private final ThreeDView<X> view; private long u0, u1, u2; Accessor3d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new ThreeDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 3d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, value); } } private class Accessor4d<X> extends AccessorBase implements Accessor<X> { private final FourDView<X> view; private long u0, u1, u2, u3; Accessor4d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new FourDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 4d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, value); } } private class Accessor5d<X> extends AccessorBase implements Accessor<X> { private final FiveDView<X> view; private long u0, u1, u2, u3, u4; Accessor5d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new FiveDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 5d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, value); } } private class Accessor6d<X> extends AccessorBase implements Accessor<X> { private final SixDView<X> view; private long u0, u1, u2, u3, u4, u5; Accessor6d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new SixDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); } else if (axisNumber0 == 0 && axisNumber1 == 5) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); } else if (axisNumber0 == 1 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); } else if (axisNumber0 == 2 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; u5 = getPositionValue(3); } else if (axisNumber0 == 3 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = i1; } else if (axisNumber0 == 4 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 6d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, u5, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, u5, value); } } private class Accessor7d<X> extends AccessorBase implements Accessor<X> { private final SevenDView<X> view; private long u0, u1, u2, u3, u4, u5, u6; Accessor7d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new SevenDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 0 && axisNumber1 == 5) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); } else if (axisNumber0 == 0 && axisNumber1 == 6) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 1 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); } else if (axisNumber0 == 1 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 2 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); } else if (axisNumber0 == 2 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 3 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); } else if (axisNumber0 == 3 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; } else if (axisNumber0 == 4 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = i1; u6 = getPositionValue(4); } else if (axisNumber0 == 4 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = i1; } else if (axisNumber0 == 5 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 7d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, u5, u6, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, u5, u6, value); } } private class Accessor8d<X> extends AccessorBase implements Accessor<X> { private final EightDView<X> view; private long u0, u1, u2, u3, u4, u5, u6, u7; Accessor8d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new EightDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 5) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 6) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 7) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 1 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 1 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 1 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 2 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 2 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 2 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 3 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 3 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 3 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 4 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 4 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 4 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 5 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 5 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 6 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = i0; u7 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, u5, u6, u7, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, u5, u6, u7, value); } } private class Accessor9d<X> extends AccessorBase implements Accessor<X> { private final NineDView<X> view; private long u0, u1, u2, u3, u4, u5, u6, u7, u8; Accessor9d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new NineDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 5) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 6) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 7) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 8) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 2 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 2 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 2 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 2 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 3 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 3 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 3 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 3 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 4 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 4 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 4 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 4 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 5 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 5 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 5 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 6 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = i0; u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 6 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = i0; u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 7 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = getPositionValue(6); u7 = i0; u8 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, u5, u6, u7, u8, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, value); } } private class Accessor10d<X> extends AccessorBase implements Accessor<X> { private final TenDView<X> view; private long u0, u1, u2, u3, u4, u5, u6, u7, u8, u9; Accessor10d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new TenDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 0 && axisNumber1 == 5) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 0 && axisNumber1 == 6) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 0 && axisNumber1 == 7) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 0 && axisNumber1 == 8) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; u9 = getPositionValue(7); } else if (axisNumber0 == 0 && axisNumber1 == 9) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = getPositionValue(7); u9 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 1 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 1 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 1 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 1 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; u9 = getPositionValue(7); } else if (axisNumber0 == 1 && axisNumber1 == 9) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = getPositionValue(7); u9 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 2 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 2 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 2 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 2 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; u9 = getPositionValue(7); } else if (axisNumber0 == 2 && axisNumber1 == 9) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = getPositionValue(7); u9 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 3 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 3 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 3 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 3 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; u9 = getPositionValue(7); } else if (axisNumber0 == 3 && axisNumber1 == 9) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = getPositionValue(7); u9 = i1; } else if (axisNumber0 == 4 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 4 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 4 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 4 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; u9 = getPositionValue(7); } else if (axisNumber0 == 4 && axisNumber1 == 9) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = getPositionValue(7); u9 = i1; } else if (axisNumber0 == 5 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 5 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); u9 = getPositionValue(7); } else if (axisNumber0 == 5 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; u9 = getPositionValue(7); } else if (axisNumber0 == 5 && axisNumber1 == 9) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = getPositionValue(7); u9 = i1; } else if (axisNumber0 == 6 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = i0; u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 6 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = i0; u7 = getPositionValue(6); u8 = i1; u9 = getPositionValue(7); } else if (axisNumber0 == 6 && axisNumber1 == 9) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = i0; u7 = getPositionValue(6); u8 = getPositionValue(7); u9 = i1; } else if (axisNumber0 == 7 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = getPositionValue(6); u7 = i0; u8 = i1; u9 = getPositionValue(7); } else if (axisNumber0 == 7 && axisNumber1 == 9) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = getPositionValue(6); u7 = i0; u8 = getPositionValue(7); u9 = i1; } else if (axisNumber0 == 8 && axisNumber1 == 9) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = getPositionValue(6); u7 = getPositionValue(7); u8 = i0; u9 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, value); } } }
src/main/java/nom/bdezonia/zorbage/dataview/PlaneView.java
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (c) 2016-2021 Barry DeZonia All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the <copyright holder> nor the names of its contributors may * be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package nom.bdezonia.zorbage.dataview; import java.math.BigDecimal; import nom.bdezonia.zorbage.algebra.Allocatable; import nom.bdezonia.zorbage.algebra.Dimensioned; import nom.bdezonia.zorbage.coordinates.CoordinateSpace; import nom.bdezonia.zorbage.coordinates.LinearNdCoordinateSpace; import nom.bdezonia.zorbage.data.DimensionedDataSource; import nom.bdezonia.zorbage.data.DimensionedStorage; /** * * @author Barry DeZonia * * @param <U> */ public class PlaneView<U> implements Dimensioned { private final int axisNumber0; // axis number 1 in parent data source private final int axisNumber1; // axis number 2 in parent data source private final long axisNumber0Size; // dimension of axis number 1 private final long axisNumber1Size; // dimension of axis number 2 private final Accessor<U> accessor; private final DimensionedDataSource<U> data; /** * Construct a view from an {@link DimensionedDataSource} and some dimensions. * * @param data The n-d data source the view is being built around. * @param axis0 The axis number of the "x" component in the data source * @param axis1 The axis number of the "y" component in the data source */ public PlaneView(DimensionedDataSource<U> data, int axis0, int axis1) { int numD = data.numDimensions(); if (numD == 0) throw new IllegalArgumentException( "data source must have at least 1 dimension"); if (axis0 == axis1) throw new IllegalArgumentException("same coordinate axis specified twice"); if (axis0 >= axis1) throw new IllegalArgumentException( "axis specified out of order: all numbers assume left to right declaration"); if (axis0 < 0 || axis0 >= numD) throw new IllegalArgumentException("coordinate component 0 is outside number of dimensions"); if (axis1 < 0 || ((numD == 1 && axis1 > 1) || (numD > 1 && axis1 >= numD))) throw new IllegalArgumentException("coordinate component 1 is outside number of dimensions"); this.data = data; this.axisNumber0 = axis0; this.axisNumber1 = axis1; this.axisNumber0Size = data.dimension(axis0); this.axisNumber1Size = numD == 1 ? 1 : data.dimension(axis1); switch (numD) { case 1: accessor = new Accessor1d<U>(data); break; case 2: accessor = new Accessor2d<U>(data); break; case 3: accessor = new Accessor3d<U>(data); break; case 4: accessor = new Accessor4d<U>(data); break; case 5: accessor = new Accessor5d<U>(data); break; case 6: accessor = new Accessor6d<U>(data); break; case 7: accessor = new Accessor7d<U>(data); break; case 8: accessor = new Accessor8d<U>(data); break; case 9: accessor = new Accessor9d<U>(data); break; default: throw new IllegalArgumentException(""+numD+" dimensions not yet supported in PlaneView"); } } /** * Returns the {@link DimensionedDataSource} that the PlaneView is attached to. */ public DimensionedDataSource<U> getDataSource() { return data; } /** * Returns the 0th dimension of the view. */ public long d0() { return axisNumber0Size; } /** * Returns the 1th dimension of the view. */ public long d1() { return axisNumber1Size; } /** * A view.get() call will pull the value at the view input coordinates * from the data set into val. No index out of bounds checking is done. * * @param i0 0th view input coord * @param i1 1th view input coord * @param val The output where the result is placed */ public void get(long i0, long i1, U val) { accessor.get(i0, i1, val); } /** * A planeView.set() call will push the value at the view input * coordinates into the data set. No index out of bounds checking * is done. * * @param i0 0th view input coord * @param i1 1th view input coord * @param val The input that is stored in the underlying data set */ public void set(long i0, long i1, U val) { accessor.set(i0, i1, val); } /** * A planeView.safeGet() call will do a get() call provided the * passed index coordinate values fit within the view's dimensions. * If not an exception is thrown instead. */ public void safeGet(long i0, long i1, U val) { if (outOfBounds(i0, i1)) { throw new IllegalArgumentException("view index out of bounds"); } else get(i0, i1, val); } /** * A planeView.safeSet() call will do a set() call provided the * passed index coordinate values fit within the view's dimensions. * If not an exception is thrown instead. */ public void safeSet(long i0, long i1, U val) { if (outOfBounds(i0, i1)) { throw new IllegalArgumentException("view index out of bounds"); } else set(i0, i1, val); } /** * Return the column number of 0th index view position * (i.e. which column is "x" in the view). */ public int axisNumber0() { return axisNumber0; } /** * Return the column number of 1th index view position * (i.e. which column is "y" in the view). */ public int axisNumber1() { return axisNumber1; } /** * Return the number of dimensions in the view. */ @Override public int numDimensions() { return 2; } /** * Retrieve each view dimension by index. Throws an exception if * the dimension index number is outside the view dimensions. */ @Override public long dimension(int d) { if (d == 0) return axisNumber0Size; if (d == 1) return axisNumber1Size; throw new IllegalArgumentException("dimension out of bounds"); } /** * Returns the number of dimensions beyond 2 that this PlaneView can manipulate. * @return */ public int getPositionsCount() { return accessor.getPositionsCount(); } /** * Set the position value of one of the dimensions of the PlaneView */ public void setPositionValue(int i, long v) { accessor.setPositionValue(i, v); } /** * Get the position value of one of the dimensions of the PlaneView */ public long getPositionValue(int i) { return accessor.getPositionValue(i); } /** * Translates the dimensions associated with sliders into their own * original coordinate position of the parent data source. That's * kind of confusing. Imagine you have a 5d dataset. Your "x" and "y" * coord positions were set to 1 and 3. The planeView stores the 3 * non-planar dims as 0, 1, and 2. But their original coord positions * in the parent data source were 0, 2, and 4. This method maps 0/1/2 * into 0/2/4 in this one case. * * @param extraDimPos * @return */ public int getDataSourceAxisNumber(int extraDimPos) { int counted = 0; for (int i = 0; i < data.numDimensions(); i++) { if (i == axisNumber0 || i == axisNumber1) continue; if (counted == extraDimPos) return i; counted++; } return -1; } /** * Returns the dimension of extra axis i in the parent data source * * @param extraDimPos * @return */ public long getDataSourceAxisSize(int extraDimPos) { int pos = getDataSourceAxisNumber(extraDimPos); return data.dimension(pos); } /** * Returns the model coords of the point on the model currently * associated with the i0/i1 coords and the current slider * positions. * * @param i0 * @param i1 * @param modelCoords */ public void getModelCoords(long i0, long i1, long[] modelCoords) { for (int i = 0; i < getPositionsCount(); i++) { int pos = getDataSourceAxisNumber(i); long value = getPositionValue(i); modelCoords[pos] = value; } modelCoords[axisNumber0] = i0; modelCoords[axisNumber1] = i1; } /** * Get a snapshot of a whole plane of data using the current axis positions * and "x" and "y" axis designations. So one can easily generate a Y/Z plane * where X == 250, for example. * * @param scratchVar A variable that the routine will use in its calcs. * * @return */ @SuppressWarnings("unchecked") public <V extends Allocatable<V>> DimensionedDataSource<U> copyPlane(U scratchVar) { DimensionedDataSource<U> newDs = (DimensionedDataSource<U>) DimensionedStorage.allocate((V) scratchVar, new long[] {axisNumber0Size,axisNumber1Size}); TwoDView<U> view = new TwoDView<>(newDs); for (long y = 0; y < axisNumber1Size; y++) { for (long x = 0; x < axisNumber0Size; x++) { accessor.get(x, y, scratchVar); view.set(x, y, scratchVar); } } String d0Str = data.getAxisType(axisNumber0) == null ? ("dim "+axisNumber0) : data.getAxisType(axisNumber0); String d1Str = data.getAxisType(axisNumber1) == null ? ("dim "+axisNumber1) : data.getAxisType(axisNumber1); String axes = "["+d0Str+":"+d1Str+"]"; String miniTitle = axes + "slice"; newDs.setName(data.getName() == null ? miniTitle : (miniTitle + " of "+data.getName())); newDs.setAxisType(0, data.getAxisType(axisNumber0)); newDs.setAxisType(1, data.getAxisType(axisNumber1)); newDs.setAxisUnit(0, data.getAxisUnit(axisNumber0)); newDs.setAxisUnit(1, data.getAxisUnit(axisNumber1)); newDs.setValueType(data.getValueType()); newDs.setValueUnit(data.getValueUnit()); CoordinateSpace origSpace = data.getCoordinateSpace(); if (origSpace instanceof LinearNdCoordinateSpace) { LinearNdCoordinateSpace origLinSpace = (LinearNdCoordinateSpace) data.getCoordinateSpace(); BigDecimal[] scales = new BigDecimal[2]; scales[0] = origLinSpace.getScale(axisNumber0); scales[1] = origLinSpace.getScale(axisNumber1); BigDecimal[] offsets = new BigDecimal[2]; offsets[0] = origLinSpace.getOffset(axisNumber0); offsets[1] = origLinSpace.getOffset(axisNumber1); LinearNdCoordinateSpace newLinSpace = new LinearNdCoordinateSpace(scales, offsets); newDs.setCoordinateSpace(newLinSpace); } return newDs; } // ---------------------------------------------------------------------- // PRIVATE DECLARATIONS FOLLOW // ---------------------------------------------------------------------- private boolean outOfBounds(long i0, long i1) { if (i0 < 0 || i0 >= axisNumber0Size) return true; if (i1 < 0 || i1 >= axisNumber1Size) return true; return false; } private interface Accessor<X> { void set(long i0, long i1, X value); void get(long i0, long i1, X value); int getPositionsCount(); void setPositionValue(int i, long v); long getPositionValue(int i); } private abstract class AccessorBase { private long[] extraDimPositions; AccessorBase(int numD) { int size = numD - 2; if (size < 0) size = 0; extraDimPositions = new long[size]; } public int getPositionsCount() { return extraDimPositions.length; } public void setPositionValue(int i, long v) { if (i < 0 || i >= extraDimPositions.length) throw new IllegalArgumentException("illegal extra dim position"); extraDimPositions[i] = v; } public long getPositionValue(int i) { if (i < 0 || i >= extraDimPositions.length) throw new IllegalArgumentException("illegal extra dim position"); return extraDimPositions[i]; } } private class Accessor1d<X> extends AccessorBase implements Accessor<X> { private final OneDView<X> view; Accessor1d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new OneDView<>(data); } @Override public void set(long i0, long i1, X value) { view.set(i0, value); } @Override public void get(long i0, long i1, X value) { view.get(i0, value); } } private class Accessor2d<X> extends AccessorBase implements Accessor<X> { private final TwoDView<X> view; Accessor2d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new TwoDView<>(data); } @Override public void set(long i0, long i1, X value) { view.set(i0, i1, value); } @Override public void get(long i0, long i1, X value) { view.get(i0, i1, value); } } private class Accessor3d<X> extends AccessorBase implements Accessor<X> { private final ThreeDView<X> view; private long u0, u1, u2; Accessor3d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new ThreeDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 3d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, value); } } private class Accessor4d<X> extends AccessorBase implements Accessor<X> { private final FourDView<X> view; private long u0, u1, u2, u3; Accessor4d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new FourDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 4d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, value); } } private class Accessor5d<X> extends AccessorBase implements Accessor<X> { private final FiveDView<X> view; private long u0, u1, u2, u3, u4; Accessor5d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new FiveDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 5d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, value); } } private class Accessor6d<X> extends AccessorBase implements Accessor<X> { private final SixDView<X> view; private long u0, u1, u2, u3, u4, u5; Accessor6d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new SixDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); } else if (axisNumber0 == 0 && axisNumber1 == 5) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); } else if (axisNumber0 == 1 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); } else if (axisNumber0 == 2 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; u5 = getPositionValue(3); } else if (axisNumber0 == 3 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = i1; } else if (axisNumber0 == 4 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 6d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, u5, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, u5, value); } } private class Accessor7d<X> extends AccessorBase implements Accessor<X> { private final SevenDView<X> view; private long u0, u1, u2, u3, u4, u5, u6; Accessor7d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new SevenDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 0 && axisNumber1 == 5) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); } else if (axisNumber0 == 0 && axisNumber1 == 6) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 1 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); } else if (axisNumber0 == 1 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 2 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); } else if (axisNumber0 == 2 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); } else if (axisNumber0 == 3 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); } else if (axisNumber0 == 3 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; } else if (axisNumber0 == 4 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = i1; u6 = getPositionValue(4); } else if (axisNumber0 == 4 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = i1; } else if (axisNumber0 == 5 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 7d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, u5, u6, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, u5, u6, value); } } private class Accessor8d<X> extends AccessorBase implements Accessor<X> { private final EightDView<X> view; private long u0, u1, u2, u3, u4, u5, u6, u7; Accessor8d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new EightDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 5) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 6) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 0 && axisNumber1 == 7) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 1 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 1 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 1 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 2 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 2 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 2 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 3 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 3 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 3 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 4 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); } else if (axisNumber0 == 4 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 4 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 5 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = i1; u7 = getPositionValue(5); } else if (axisNumber0 == 5 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = getPositionValue(5); u7 = i1; } else if (axisNumber0 == 6 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = i0; u7 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, u5, u6, u7, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, u5, u6, u7, value); } } private class Accessor9d<X> extends AccessorBase implements Accessor<X> { private final NineDView<X> view; private long u0, u1, u2, u3, u4, u5, u6, u7, u8; Accessor9d(DimensionedDataSource<X> data) { super(data.numDimensions()); view = new NineDView<>(data); } private void setPos(long i0, long i1) { if (axisNumber0 == 0 && axisNumber1 == 1) { u0 = i0; u1 = i1; u2 = getPositionValue(0); u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 2) { u0 = i0; u1 = getPositionValue(0); u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 3) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 4) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 5) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 6) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 7) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 0 && axisNumber1 == 8) { u0 = i0; u1 = getPositionValue(0); u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 1 && axisNumber1 == 2) { u0 = getPositionValue(0); u1 = i0; u2 = i1; u3 = getPositionValue(1); u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 1 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = i0; u2 = getPositionValue(1); u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 2 && axisNumber1 == 3) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = i1; u4 = getPositionValue(2); u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 2 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 2 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 2 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 2 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 2 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = i0; u3 = getPositionValue(2); u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 3 && axisNumber1 == 4) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = i1; u5 = getPositionValue(3); u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 3 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 3 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 3 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 3 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = i0; u4 = getPositionValue(3); u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 4 && axisNumber1 == 5) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = i1; u6 = getPositionValue(4); u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 4 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 4 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 4 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = i0; u5 = getPositionValue(4); u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 5 && axisNumber1 == 6) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = i1; u7 = getPositionValue(5); u8 = getPositionValue(6); } else if (axisNumber0 == 5 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = getPositionValue(5); u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 5 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = i0; u6 = getPositionValue(5); u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 6 && axisNumber1 == 7) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = i0; u7 = i1; u8 = getPositionValue(6); } else if (axisNumber0 == 6 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = i0; u7 = getPositionValue(6); u8 = i1; } else if (axisNumber0 == 7 && axisNumber1 == 8) { u0 = getPositionValue(0); u1 = getPositionValue(1); u2 = getPositionValue(2); u3 = getPositionValue(3); u4 = getPositionValue(4); u5 = getPositionValue(5); u6 = getPositionValue(6); u7 = i0; u8 = i1; } else throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1); } @Override public void set(long i0, long i1, X value) { setPos(i0, i1); view.set(u0, u1, u2, u3, u4, u5, u6, u7, u8, value); } @Override public void get(long i0, long i1, X value) { setPos(i0, i1); view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, value); } } }
Extend PlaneView to work with 10-d data sources
src/main/java/nom/bdezonia/zorbage/dataview/PlaneView.java
Extend PlaneView to work with 10-d data sources
<ide><path>rc/main/java/nom/bdezonia/zorbage/dataview/PlaneView.java <ide> case 9: <ide> accessor = new Accessor9d<U>(data); <ide> break; <add> case 10: <add> accessor = new Accessor10d<U>(data); <add> break; <ide> default: <ide> throw new IllegalArgumentException(""+numD+" dimensions not yet supported in PlaneView"); <ide> } <ide> view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, value); <ide> } <ide> } <add> <add> private class Accessor10d<X> <add> extends AccessorBase <add> implements Accessor<X> <add> { <add> private final TenDView<X> view; <add> private long u0, u1, u2, u3, u4, u5, u6, u7, u8, u9; <add> <add> Accessor10d(DimensionedDataSource<X> data) { <add> super(data.numDimensions()); <add> view = new TenDView<>(data); <add> } <add> <add> private void setPos(long i0, long i1) { <add> if (axisNumber0 == 0 && axisNumber1 == 1) { <add> u0 = i0; <add> u1 = i1; <add> u2 = getPositionValue(0); <add> u3 = getPositionValue(1); <add> u4 = getPositionValue(2); <add> u5 = getPositionValue(3); <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 0 && axisNumber1 == 2) { <add> u0 = i0; <add> u1 = getPositionValue(0); <add> u2 = i1; <add> u3 = getPositionValue(1); <add> u4 = getPositionValue(2); <add> u5 = getPositionValue(3); <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 0 && axisNumber1 == 3) { <add> u0 = i0; <add> u1 = getPositionValue(0); <add> u2 = getPositionValue(1); <add> u3 = i1; <add> u4 = getPositionValue(2); <add> u5 = getPositionValue(3); <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 0 && axisNumber1 == 4) { <add> u0 = i0; <add> u1 = getPositionValue(0); <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = i1; <add> u5 = getPositionValue(3); <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 0 && axisNumber1 == 5) { <add> u0 = i0; <add> u1 = getPositionValue(0); <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = i1; <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 0 && axisNumber1 == 6) { <add> u0 = i0; <add> u1 = getPositionValue(0); <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = i1; <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 0 && axisNumber1 == 7) { <add> u0 = i0; <add> u1 = getPositionValue(0); <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = i1; <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 0 && axisNumber1 == 8) { <add> u0 = i0; <add> u1 = getPositionValue(0); <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = i1; <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 0 && axisNumber1 == 9) { <add> u0 = i0; <add> u1 = getPositionValue(0); <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = getPositionValue(7); <add> u9 = i1; <add> } <add> else if (axisNumber0 == 1 && axisNumber1 == 2) { <add> u0 = getPositionValue(0); <add> u1 = i0; <add> u2 = i1; <add> u3 = getPositionValue(1); <add> u4 = getPositionValue(2); <add> u5 = getPositionValue(3); <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 1 && axisNumber1 == 3) { <add> u0 = getPositionValue(0); <add> u1 = i0; <add> u2 = getPositionValue(1); <add> u3 = i1; <add> u4 = getPositionValue(2); <add> u5 = getPositionValue(3); <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 1 && axisNumber1 == 4) { <add> u0 = getPositionValue(0); <add> u1 = i0; <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = i1; <add> u5 = getPositionValue(3); <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 1 && axisNumber1 == 5) { <add> u0 = getPositionValue(0); <add> u1 = i0; <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = i1; <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 1 && axisNumber1 == 6) { <add> u0 = getPositionValue(0); <add> u1 = i0; <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = i1; <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 1 && axisNumber1 == 7) { <add> u0 = getPositionValue(0); <add> u1 = i0; <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = i1; <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 1 && axisNumber1 == 8) { <add> u0 = getPositionValue(0); <add> u1 = i0; <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = i1; <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 1 && axisNumber1 == 9) { <add> u0 = getPositionValue(0); <add> u1 = i0; <add> u2 = getPositionValue(1); <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = getPositionValue(7); <add> u9 = i1; <add> } <add> else if (axisNumber0 == 2 && axisNumber1 == 3) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = i0; <add> u3 = i1; <add> u4 = getPositionValue(2); <add> u5 = getPositionValue(3); <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 2 && axisNumber1 == 4) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = i0; <add> u3 = getPositionValue(2); <add> u4 = i1; <add> u5 = getPositionValue(3); <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 2 && axisNumber1 == 5) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = i0; <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = i1; <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 2 && axisNumber1 == 6) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = i0; <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = i1; <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 2 && axisNumber1 == 7) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = i0; <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = i1; <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 2 && axisNumber1 == 8) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = i0; <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = i1; <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 2 && axisNumber1 == 9) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = i0; <add> u3 = getPositionValue(2); <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = getPositionValue(7); <add> u9 = i1; <add> } <add> else if (axisNumber0 == 3 && axisNumber1 == 4) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = i0; <add> u4 = i1; <add> u5 = getPositionValue(3); <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 3 && axisNumber1 == 5) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = i0; <add> u4 = getPositionValue(3); <add> u5 = i1; <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 3 && axisNumber1 == 6) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = i0; <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = i1; <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 3 && axisNumber1 == 7) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = i0; <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = i1; <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 3 && axisNumber1 == 8) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = i0; <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = i1; <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 3 && axisNumber1 == 9) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = i0; <add> u4 = getPositionValue(3); <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = getPositionValue(7); <add> u9 = i1; <add> } <add> else if (axisNumber0 == 4 && axisNumber1 == 5) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = i0; <add> u5 = i1; <add> u6 = getPositionValue(4); <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 4 && axisNumber1 == 6) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = i0; <add> u5 = getPositionValue(4); <add> u6 = i1; <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 4 && axisNumber1 == 7) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = i0; <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = i1; <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 4 && axisNumber1 == 8) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = i0; <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = i1; <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 4 && axisNumber1 == 9) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = i0; <add> u5 = getPositionValue(4); <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = getPositionValue(7); <add> u9 = i1; <add> } <add> else if (axisNumber0 == 5 && axisNumber1 == 6) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = getPositionValue(4); <add> u5 = i0; <add> u6 = i1; <add> u7 = getPositionValue(5); <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 5 && axisNumber1 == 7) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = getPositionValue(4); <add> u5 = i0; <add> u6 = getPositionValue(5); <add> u7 = i1; <add> u8 = getPositionValue(6); <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 5 && axisNumber1 == 8) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = getPositionValue(4); <add> u5 = i0; <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = i1; <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 5 && axisNumber1 == 9) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = getPositionValue(4); <add> u5 = i0; <add> u6 = getPositionValue(5); <add> u7 = getPositionValue(6); <add> u8 = getPositionValue(7); <add> u9 = i1; <add> } <add> else if (axisNumber0 == 6 && axisNumber1 == 7) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = getPositionValue(4); <add> u5 = getPositionValue(5); <add> u6 = i0; <add> u7 = i1; <add> u8 = getPositionValue(6); <add> } <add> else if (axisNumber0 == 6 && axisNumber1 == 8) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = getPositionValue(4); <add> u5 = getPositionValue(5); <add> u6 = i0; <add> u7 = getPositionValue(6); <add> u8 = i1; <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 6 && axisNumber1 == 9) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = getPositionValue(4); <add> u5 = getPositionValue(5); <add> u6 = i0; <add> u7 = getPositionValue(6); <add> u8 = getPositionValue(7); <add> u9 = i1; <add> } <add> else if (axisNumber0 == 7 && axisNumber1 == 8) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = getPositionValue(4); <add> u5 = getPositionValue(5); <add> u6 = getPositionValue(6); <add> u7 = i0; <add> u8 = i1; <add> u9 = getPositionValue(7); <add> } <add> else if (axisNumber0 == 7 && axisNumber1 == 9) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = getPositionValue(4); <add> u5 = getPositionValue(5); <add> u6 = getPositionValue(6); <add> u7 = i0; <add> u8 = getPositionValue(7); <add> u9 = i1; <add> } <add> else if (axisNumber0 == 8 && axisNumber1 == 9) { <add> u0 = getPositionValue(0); <add> u1 = getPositionValue(1); <add> u2 = getPositionValue(2); <add> u3 = getPositionValue(3); <add> u4 = getPositionValue(4); <add> u5 = getPositionValue(5); <add> u6 = getPositionValue(6); <add> u7 = getPositionValue(7); <add> u8 = i0; <add> u9 = i1; <add> } <add> else <add> throw new IllegalArgumentException("missing coordinate combo for 8d "+axisNumber0+" "+axisNumber1); <add> } <add> <add> @Override <add> public void set(long i0, long i1, X value) { <add> setPos(i0, i1); <add> view.set(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, value); <add> } <add> <add> @Override <add> public void get(long i0, long i1, X value) { <add> setPos(i0, i1); <add> view.get(u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, value); <add> } <add> } <ide> }
Java
apache-2.0
7ef46219629079d55cbeeb65a2449b8239a29c8f
0
mathemage/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,mathemage/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,spennihana/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,spennihana/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,h2oai/h2o-dev,spennihana/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,spennihana/h2o-3,mathemage/h2o-3,mathemage/h2o-3,mathemage/h2o-3,spennihana/h2o-3,h2oai/h2o-dev,mathemage/h2o-3,h2oai/h2o-3,spennihana/h2o-3
package ai.h2o.automl; import hex.*; import water.*; import water.api.schemas3.KeyV3; import water.exceptions.H2OIllegalArgumentException; import water.util.Log; import water.util.TwoDimTable; import java.text.SimpleDateFormat; import java.util.*; import static water.DKV.getGet; import static water.Key.make; /** * Utility to track all the models built for a given dataset type. * <p> * Note that if a new Leaderboard is made for the same project it'll * keep using the old model list, which allows us to run AutoML multiple * times and keep adding to the leaderboard. * <p> * The models are returned sorted by either an appropriate default metric * for the model category (auc, mean per class error, or mean residual deviance), * or by a metric that's set via #setMetricAndDirection. * <p> * TODO: make this robust against removal of models from the DKV. */ public class Leaderboard extends Keyed<Leaderboard> { /** * Identifier for models that should be grouped together in the leaderboard * (e.g., "airlines" and "iris"). */ private final String project; /** * List of models for this leaderboard, sorted by metric so that the best is first, * according to the standard metric for the given model type. NOTE: callers should * access this through #models() to make sure they don't get a stale copy. */ private Key<Model>[] models; /** * Sort metrics for the models in this leaderboard, in the same order as the models. */ public double[] sort_metrics; /** * Metric used to sort this leaderboard. */ private String sort_metric; /** * Metric direction used in the sort. */ private boolean sort_decreasing; /** * UserFeedback object used to send, um, feedback to the, ah, user. :-) * Right now this is a "new leader" message. */ private UserFeedback userFeedback; /** HIDEME! */ private Leaderboard() { throw new UnsupportedOperationException("Do not call the default constructor Leaderboard()."); } /** * */ public Leaderboard(String project, UserFeedback userFeedback) { this._key = make(idForProject(project)); this.project = project; this.userFeedback = userFeedback; Leaderboard old = DKV.getGet(this._key); if (null == old) { this.models = new Key[0]; DKV.put(this); } } // satisfy typing for job return type... public static class LeaderboardKeyV3 extends KeyV3<Iced, LeaderboardKeyV3, Leaderboard> { public LeaderboardKeyV3() { } public LeaderboardKeyV3(Key<Leaderboard> key) { super(key); } } public static String idForProject(String project) { return "AutoML_Leaderboard_" + project; } public String getProject() { return project; } public void setMetricAndDirection(String metric, boolean sortDecreasing){ this.sort_metric = metric; this.sort_decreasing = sortDecreasing; } public void setDefaultMetricAndDirection(Model m) { if (m._output.isBinomialClassifier()) setMetricAndDirection("auc", true); else if (m._output.isClassifier()) setMetricAndDirection("mean_per_class_error", false); else if (m._output.isSupervised()) setMetricAndDirection("residual_deviance", false); } /** * Add the given models to the leaderboard. Note that to make this easier to use from * Grid, which returns its models in random order, we allow the caller to add the same * model multiple times and we eliminate the duplicates here. * @param newModels */ final public void addModels(final Key<Model>[] newModels) { if (null == this._key) throw new H2OIllegalArgumentException("Can't add models to a Leaderboard which isn't in the DKV."); if (this.sort_metric == null) { // lazily set to default for this model category setDefaultMetricAndDirection(newModels[0].get()); } final Key<Model> newLeader[] = new Key[1]; // only set if there's a new leader new TAtomic<Leaderboard>() { @Override final public Leaderboard atomic(Leaderboard old) { if (old == null) old = new Leaderboard(); final Key<Model>[] oldModels = old.models; final Key<Model> oldLeader = (oldModels == null || 0 == oldModels.length) ? null : oldModels[0]; // eliminate duplicates Set<Key<Model>> uniques = new HashSet(oldModels.length + newModels.length); uniques.addAll(Arrays.asList(oldModels)); uniques.addAll(Arrays.asList(newModels)); old.models = uniques.toArray(new Key[0]); // Sort by metric. // TODO: If we want to train on different frames and then compare we need to score all the models and sort on the new metrics. try { List<Key<Model>> newModelsSorted = ModelMetrics.sortModelsByMetric(sort_metric, sort_decreasing, Arrays.asList(old.models)); old.models = newModelsSorted.toArray(new Key[0]); } catch (H2OIllegalArgumentException e) { Log.warn("ModelMetrics.sortModelsByMetric failed: " + e); throw e; } Model[] models = new Model[old.models.length]; old.sort_metrics = old.sortMetrics(modelsForModelKeys(old.models, models)); // NOTE: we've now written over old.models // TODO: should take out of the tatomic if (oldLeader == null || ! oldLeader.equals(old.models[0])) newLeader[0] = old.models[0]; return old; } // atomic }.invoke(this._key); // We've updated the DKV but not this instance, so: this.models = this.modelKeys(); this.sort_metrics = sortMetrics(this.models()); // always EckoClient.updateLeaderboard(this); if (null != newLeader[0]) { userFeedback.info(UserFeedbackEvent.Stage.ModelTraining, "New leader: " + newLeader[0]); } } public void addModel(final Key<Model> key) { Key<Model>keys[] = new Key[1]; keys[0] = key; addModels(keys); } public void addModel(final Model model) { Key<Model>keys[] = new Key[1]; keys[0] = model._key; addModels(keys); } private static Model[] modelsForModelKeys(Key<Model>[] modelKeys, Model[] models) { assert models.length >= modelKeys.length; int i = 0; for (Key<Model> modelKey : modelKeys) models[i++] = getGet(modelKey); return models; } /** * @return list of keys of models sorted by the default metric for the model category, fetched from the DKV */ public Key<Model>[] modelKeys() { return ((Leaderboard)DKV.getGet(this._key)).models; } /** * @return list of keys of models sorted by the given metric , fetched from the DKV */ public Key<Model>[] modelKeys(String metric, boolean sortDecreasing) { Key<Model>[] models = modelKeys(); List<Key<Model>> newModelsSorted = ModelMetrics.sortModelsByMetric(metric, sortDecreasing, Arrays.asList(models)); return newModelsSorted.toArray(new Key[0]); } /** * @return list of models sorted by the default metric for the model category */ public Model[] models() { Key<Model>[] modelKeys = modelKeys(); if (modelKeys == null || 0 == modelKeys.length) return new Model[0]; Model[] models = new Model[modelKeys.length]; return modelsForModelKeys(modelKeys, models); } /** * @return list of models sorted by the given metric */ public Model[] models(String metric, boolean sortDecreasing) { Key<Model>[] modelKeys = modelKeys(metric, sortDecreasing); if (modelKeys == null || 0 == modelKeys.length) return new Model[0]; Model[] models = new Model[modelKeys.length]; return modelsForModelKeys(modelKeys, models); } public Model leader() { Key<Model>[] modelKeys = modelKeys(); if (modelKeys == null || 0 == modelKeys.length) return null; return modelKeys[0].get(); } public long[] timestamps(Model[] models) { long[] timestamps = new long[models.length]; int i = 0; for (Model m : models) timestamps[i++] = m._output._end_time; return timestamps; } public double[] sortMetrics(Model[] models) { double[] sort_metrics = new double[models.length]; int i = 0; for (Model m : models) sort_metrics[i++] = defaultMetricForModel(m); return sort_metrics; } /** * Delete everything in the DKV that this points to. We currently need to be able to call this after deleteWithChildren(). */ public void delete() { remove(); } public void deleteWithChildren() { for (Model m : models()) m.delete(); delete(); } public static double defaultMetricForModel(Model m) { ModelMetrics mm = m._output._cross_validation_metrics != null ? m._output._cross_validation_metrics : m._output._validation_metrics != null ? m._output._validation_metrics : m._output._training_metrics; if (m._output.isBinomialClassifier()) { return(((ModelMetricsBinomial)mm).auc()); } else if (m._output.isClassifier()) { return(((ModelMetricsMultinomial)mm).mean_per_class_error()); } else if (m._output.isSupervised()) { return(((ModelMetricsRegression)mm).residual_deviance()); } Log.warn("Failed to find metric for model: " + m); return Double.NaN; } public static String defaultMetricNameForModel(Model m) { if (m._output.isBinomialClassifier()) { return "auc"; } else if (m._output.isClassifier()) { return "mean per-class error"; } else if (m._output.isSupervised()) { return "residual deviance"; } return "unknown"; } public String rankTsv() { String fieldSeparator = "\\t"; String lineSeparator = "\\n"; StringBuffer sb = new StringBuffer(); // sb.append("Rank").append(fieldSeparator).append("Error").append(lineSeparator); sb.append("Error").append(lineSeparator); Model[] models = models(); for (int i = models.length - 1; i >= 0; i--) { // TODO: allow the metric to be passed in. Note that this assumes the validation (or training) frame is the same. Model m = models[i]; sb.append(defaultMetricForModel(m)); sb.append(lineSeparator); } return sb.toString(); } public String timeTsv() { String fieldSeparator = "\\t"; String lineSeparator = "\\n"; StringBuffer sb = new StringBuffer(); sb.append("Time").append(fieldSeparator).append("Error").append(lineSeparator); Model[] models = models(); for (int i = models.length - 1; i >= 0; i--) { // TODO: allow the metric to be passed in. Note that this assumes the validation (or training) frame is the same. Model m = models[i]; sb.append(timestampFormat.format(m._output._end_time)); sb.append(fieldSeparator); sb.append(defaultMetricForModel(m)); sb.append(lineSeparator); } return sb.toString(); } protected static final String[] colHeaders(String metric) { return new String[] {"model ID", "timestamp", metric.toString()}; } protected static final String[] colTypes= { "string", "string", "string" }; protected static final String[] colFormats= { "%s", "%s", "%s" }; public static final TwoDimTable makeTwoDimTable(String tableHeader, String sort_metric, int length) { String[] rowHeaders = new String[length]; for (int i = 0; i < length; i++) rowHeaders[i] = "" + i; return new TwoDimTable(tableHeader, "models sorted in order of " + sort_metric + ", best first", rowHeaders, Leaderboard.colHeaders(sort_metric), Leaderboard.colTypes, Leaderboard.colFormats, "#"); } public void addTwoDimTableRow(TwoDimTable table, int row, String[] modelIDs, long[] timestamps, double[] errors) { int col = 0; table.set(row, col++, modelIDs[row]); table.set(row, col++, timestampFormat.format(new Date(timestamps[row]))); table.set(row, col++, String.format("%.6f", errors[row])); } public TwoDimTable toTwoDimTable() { return toTwoDimTable("Leaderboard for project: " + project, false); } public TwoDimTable toTwoDimTable(String tableHeader, boolean leftJustifyModelIds) { Model[] models = this.models(); long[] timestamps = timestamps(models); String[] modelIDsFormatted = new String[models.length]; TwoDimTable table = makeTwoDimTable(tableHeader, sort_metric, models.length); // %-s doesn't work in TwoDimTable.toString(), so fake it here: int maxModelIdLen = -1; for (Model m : models) maxModelIdLen = Math.max(maxModelIdLen, m._key.toString().length()); for (int i = 0; i < models.length; i++) if (leftJustifyModelIds) { modelIDsFormatted[i] = (models[i]._key.toString() + " ") .substring(0, maxModelIdLen); } else { modelIDsFormatted[i] = models[i]._key.toString(); } for (int i = 0; i < models.length; i++) addTwoDimTableRow(table, i, modelIDsFormatted, timestamps, sort_metrics); return table; } private static final SimpleDateFormat timestampFormat = new SimpleDateFormat("HH:mm:ss.SSS"); public static String toString(String project, Model[] models, String fieldSeparator, String lineSeparator, boolean includeTitle, boolean includeHeader, boolean includeTimestamp) { StringBuilder sb = new StringBuilder(); if (includeTitle) { sb.append("Leaderboard for project \"") .append(project) .append("\": "); if (models.length == 0) { sb.append("<empty>"); return sb.toString(); } sb.append(lineSeparator); } boolean printedHeader = false; for (Model m : models) { // TODO: allow the metric to be passed in. Note that this assumes the validation (or training) frame is the same. if (includeHeader && ! printedHeader) { sb.append("Model_ID"); sb.append(fieldSeparator); sb.append(defaultMetricNameForModel(m)); if (includeTimestamp) { sb.append(fieldSeparator); sb.append("timestamp"); } sb.append(lineSeparator); printedHeader = true; } sb.append(m._key.toString()); sb.append(fieldSeparator); sb.append(defaultMetricForModel(m)); if (includeTimestamp) { sb.append(fieldSeparator); sb.append(timestampFormat.format(m._output._end_time)); } sb.append(lineSeparator); } return sb.toString(); } public String toString(String fieldSeparator, String lineSeparator) { return toString(project, models(), fieldSeparator, lineSeparator, true, true, false); } @Override public String toString() { return toString(" ; ", " | "); } }
h2o-automl/src/main/java/ai/h2o/automl/Leaderboard.java
package ai.h2o.automl; import hex.*; import water.*; import water.api.schemas3.KeyV3; import water.exceptions.H2OIllegalArgumentException; import water.util.Log; import water.util.TwoDimTable; import java.text.SimpleDateFormat; import java.util.*; import static water.DKV.getGet; import static water.Key.make; /** * Utility to track all the models built for a given dataset type. * <p> * Note that if a new Leaderboard is made for the same project it'll * keep using the old model list, which allows us to run AutoML multiple * times and keep adding to the leaderboard. * <p> * The models are returned sorted by either an appropriate default metric * for the model category (auc, mean per class error, or mean residual deviance), * or by a metric that's set via #setMetricAndDirection. * <p> * TODO: make this robust against removal of models from the DKV. */ public class Leaderboard extends Keyed<Leaderboard> { /** * Identifier for models that should be grouped together in the leaderboard * (e.g., "airlines" and "iris"). */ private final String project; /** * List of models for this leaderboard, sorted by metric so that the best is first, * according to the standard metric for the given model type. NOTE: callers should * access this through #models() to make sure they don't get a stale copy. */ private Key<Model>[] models; /** * Sort metrics for the models in this leaderboard, in the same order as the models. */ public double[] sort_metrics; /** * Metric used to sort this leaderboard. */ private String sort_metric; /** * Metric direction used in the sort. */ private boolean sort_decreasing; /** * UserFeedback object used to send, um, feedback to the, ah, user. :-) * Right now this is a "new leader" message. */ private UserFeedback userFeedback; /** HIDEME! */ private Leaderboard() { throw new UnsupportedOperationException("Do not call the default constructor Leaderboard()."); } /** * */ public Leaderboard(String project, UserFeedback userFeedback) { this._key = make(idForProject(project)); this.project = project; this.userFeedback = userFeedback; Leaderboard old = DKV.getGet(this._key); if (null == old) { this.models = new Key[0]; DKV.put(this); } } // satisfy typing for job return type... public static class LeaderboardKeyV3 extends KeyV3<Iced, LeaderboardKeyV3, Leaderboard> { public LeaderboardKeyV3() { } public LeaderboardKeyV3(Key<Leaderboard> key) { super(key); } } public static String idForProject(String project) { return "AutoML_Leaderboard_" + project; } public String getProject() { return project; } public void setMetricAndDirection(String metric, boolean sortDecreasing){ this.sort_metric = metric; this.sort_decreasing = sortDecreasing; } public void setDefaultMetricAndDirection(Model m) { if (m._output.isBinomialClassifier()) setMetricAndDirection("auc", true); else if (m._output.isClassifier()) setMetricAndDirection("mean_per_class_error", false); else if (m._output.isSupervised()) setMetricAndDirection("residual_deviance", false); } /** * Add the given models to the leaderboard. Note that to make this easier to use from * Grid, which returns its models in random order, we allow the caller to add the same * model multiple times and we eliminate the duplicates here. * @param newModels */ final public void addModels(final Key<Model>[] newModels) { if (null == this._key) throw new H2OIllegalArgumentException("Can't add models to a Leaderboard which isn't in the DKV."); if (this.sort_metric == null) { // lazily set to default for this model category setDefaultMetricAndDirection(newModels[0].get()); } final Key<Model> newLeader[] = new Key[1]; // only set if there's a new leader new TAtomic<Leaderboard>() { @Override final public Leaderboard atomic(Leaderboard old) { if (old == null) old = new Leaderboard(); final Key<Model>[] oldModels = old.models; final Key<Model> oldLeader = (oldModels == null || 0 == oldModels.length) ? null : oldModels[0]; // eliminate duplicates Set<Key<Model>> uniques = new HashSet(oldModels.length + newModels.length); uniques.addAll(Arrays.asList(oldModels)); uniques.addAll(Arrays.asList(newModels)); old.models = uniques.toArray(new Key[0]); // Sort by metric. // TODO: If we want to train on different frames and then compare we need to score all the models and sort on the new metrics. try { List<Key<Model>> newModelsSorted = ModelMetrics.sortModelsByMetric(sort_metric, sort_decreasing, Arrays.asList(old.models)); old.models = newModelsSorted.toArray(new Key[0]); } catch (H2OIllegalArgumentException e) { Log.warn("ModelMetrics.sortModelsByMetric failed: " + e); throw e; } Model[] models = new Model[old.models.length]; old.sort_metrics = old.sortMetrics(modelsForModelKeys(old.models, models)); // NOTE: we've now written over old.models // TODO: should take out of the tatomic if (oldLeader == null || ! oldLeader.equals(old.models[0])) newLeader[0] = old.models[0]; return old; } // atomic }.invoke(this._key); // We've updated the DKV but not this instance, so: this.models = this.modelKeys(); this.sort_metrics = sortMetrics(this.models()); // always EckoClient.updateLeaderboard(this); if (null != newLeader[0]) { userFeedback.info(UserFeedbackEvent.Stage.ModelTraining, "New leader: " + newLeader[0]); } } public void addModel(final Key<Model> key) { Key<Model>keys[] = new Key[1]; keys[0] = key; addModels(keys); } public void addModel(final Model model) { Key<Model>keys[] = new Key[1]; keys[0] = model._key; addModels(keys); } private static Model[] modelsForModelKeys(Key<Model>[] modelKeys, Model[] models) { assert models.length >= modelKeys.length; int i = 0; for (Key<Model> modelKey : modelKeys) models[i++] = getGet(modelKey); return models; } /** * @return list of keys of models sorted by the default metric for the model category, fetched from the DKV */ public Key<Model>[] modelKeys() { return ((Leaderboard)DKV.getGet(this._key)).models; } /** * @return list of keys of models sorted by the given metric , fetched from the DKV */ public Key<Model>[] modelKeys(String metric, boolean sortDecreasing) { Key<Model>[] models = modelKeys(); List<Key<Model>> newModelsSorted = ModelMetrics.sortModelsByMetric(metric, sortDecreasing, Arrays.asList(models)); return newModelsSorted.toArray(new Key[0]); } /** * @return list of models sorted by the default metric for the model category */ public Model[] models() { Key<Model>[] modelKeys = modelKeys(); if (modelKeys == null || 0 == modelKeys.length) return new Model[0]; Model[] models = new Model[modelKeys.length]; return modelsForModelKeys(modelKeys, models); } /** * @return list of models sorted by the given metric */ public Model[] models(String metric, boolean sortDecreasing) { Key<Model>[] modelKeys = modelKeys(metric, sortDecreasing); if (modelKeys == null || 0 == modelKeys.length) return new Model[0]; Model[] models = new Model[modelKeys.length]; return modelsForModelKeys(modelKeys, models); } public Model leader() { Key<Model>[] modelKeys = modelKeys(); if (modelKeys == null || 0 == modelKeys.length) return null; return modelKeys[0].get(); } public long[] timestamps(Model[] models) { long[] timestamps = new long[models.length]; int i = 0; for (Model m : models) timestamps[i++] = m._output._end_time; return timestamps; } public double[] sortMetrics(Model[] models) { double[] sort_metrics = new double[models.length]; int i = 0; for (Model m : models) sort_metrics[i++] = defaultMetricForModel(m); return sort_metrics; } /** * Delete everything in the DKV that this points to. We currently need to be able to call this after deleteWithChildren(). */ public void delete() { remove(); } public void deleteWithChildren() { for (Model m : models()) m.delete(); delete(); } public static double defaultMetricForModel(Model m) { ModelMetrics mm = m._output._cross_validation_metrics != null ? m._output._cross_validation_metrics : m._output._validation_metrics != null ? m._output._validation_metrics : m._output._training_metrics; if (m._output.isBinomialClassifier()) { return(((ModelMetricsBinomial)mm).auc()); } else if (m._output.isClassifier()) { return(((ModelMetricsMultinomial)mm).mean_per_class_error()); } else if (m._output.isSupervised()) { return(((ModelMetricsRegression)mm).residual_deviance()); } Log.warn("Failed to find metric for model: " + m); return Double.NaN; } public static String defaultMetricNameForModel(Model m) { if (m._output.isBinomialClassifier()) { return "auc"; } else if (m._output.isClassifier()) { return "mean per-class error"; } else if (m._output.isSupervised()) { return "residual deviance"; } return "unknown"; } public String rankTsv() { String fieldSeparator = "\\t"; String lineSeparator = "\\n"; StringBuffer sb = new StringBuffer(); // sb.append("Rank").append(fieldSeparator).append("Error").append(lineSeparator); sb.append("Error").append(lineSeparator); Model[] models = models(); for (int i = models.length - 1; i >= 0; i--) { // TODO: allow the metric to be passed in. Note that this assumes the validation (or training) frame is the same. Model m = models[i]; sb.append(defaultMetricForModel(m)); sb.append(lineSeparator); } return sb.toString(); } public String timeTsv() { String fieldSeparator = "\\t"; String lineSeparator = "\\n"; StringBuffer sb = new StringBuffer(); sb.append("Time").append(fieldSeparator).append("Error").append(lineSeparator); Model[] models = models(); for (int i = models.length - 1; i >= 0; i--) { // TODO: allow the metric to be passed in. Note that this assumes the validation (or training) frame is the same. Model m = models[i]; sb.append(timestampFormat.format(m._output._end_time)); sb.append(fieldSeparator); sb.append(defaultMetricForModel(m)); sb.append(lineSeparator); } return sb.toString(); } protected static final String[] colHeaders = { "model ID", "timestamp", "metric" }; protected static final String[] colTypes= { "string", "string", "string" }; protected static final String[] colFormats= { "%s", "%s", "%s" }; public static final TwoDimTable makeTwoDimTable(String tableHeader, String sort_metric, int length) { String[] rowHeaders = new String[length]; for (int i = 0; i < length; i++) rowHeaders[i] = "" + i; return new TwoDimTable(tableHeader, "models sorted in order of " + sort_metric + ", best first", rowHeaders, Leaderboard.colHeaders, Leaderboard.colTypes, Leaderboard.colFormats, "#"); } public void addTwoDimTableRow(TwoDimTable table, int row, String[] modelIDs, long[] timestamps, double[] errors) { int col = 0; table.set(row, col++, modelIDs[row]); table.set(row, col++, timestampFormat.format(new Date(timestamps[row]))); table.set(row, col++, String.format("%.6f", errors[row])); } public TwoDimTable toTwoDimTable() { return toTwoDimTable("Leaderboard for project: " + project, false); } public TwoDimTable toTwoDimTable(String tableHeader, boolean leftJustifyModelIds) { Model[] models = this.models(); long[] timestamps = timestamps(models); String[] modelIDsFormatted = new String[models.length]; TwoDimTable table = makeTwoDimTable(tableHeader, sort_metric, models.length); // %-s doesn't work in TwoDimTable.toString(), so fake it here: int maxModelIdLen = -1; for (Model m : models) maxModelIdLen = Math.max(maxModelIdLen, m._key.toString().length()); for (int i = 0; i < models.length; i++) if (leftJustifyModelIds) { modelIDsFormatted[i] = (models[i]._key.toString() + " ") .substring(0, maxModelIdLen); } else { modelIDsFormatted[i] = models[i]._key.toString(); } for (int i = 0; i < models.length; i++) addTwoDimTableRow(table, i, modelIDsFormatted, timestamps, sort_metrics); return table; } private static final SimpleDateFormat timestampFormat = new SimpleDateFormat("HH:mm:ss.SSS"); public static String toString(String project, Model[] models, String fieldSeparator, String lineSeparator, boolean includeTitle, boolean includeHeader, boolean includeTimestamp) { StringBuilder sb = new StringBuilder(); if (includeTitle) { sb.append("Leaderboard for project \"") .append(project) .append("\": "); if (models.length == 0) { sb.append("<empty>"); return sb.toString(); } sb.append(lineSeparator); } boolean printedHeader = false; for (Model m : models) { // TODO: allow the metric to be passed in. Note that this assumes the validation (or training) frame is the same. if (includeHeader && ! printedHeader) { sb.append("Model_ID"); sb.append(fieldSeparator); sb.append(defaultMetricNameForModel(m)); if (includeTimestamp) { sb.append(fieldSeparator); sb.append("timestamp"); } sb.append(lineSeparator); printedHeader = true; } sb.append(m._key.toString()); sb.append(fieldSeparator); sb.append(defaultMetricForModel(m)); if (includeTimestamp) { sb.append(fieldSeparator); sb.append(timestampFormat.format(m._output._end_time)); } sb.append(lineSeparator); } return sb.toString(); } public String toString(String fieldSeparator, String lineSeparator) { return toString(project, models(), fieldSeparator, lineSeparator, true, true, false); } @Override public String toString() { return toString(" ; ", " | "); } }
Print actual metric used in leaderboard
h2o-automl/src/main/java/ai/h2o/automl/Leaderboard.java
Print actual metric used in leaderboard
<ide><path>2o-automl/src/main/java/ai/h2o/automl/Leaderboard.java <ide> return sb.toString(); <ide> } <ide> <del> protected static final String[] colHeaders = { <del> "model ID", <del> "timestamp", <del> "metric" }; <add> protected static final String[] colHeaders(String metric) { <add> return new String[] {"model ID", "timestamp", metric.toString()}; <add> } <ide> <ide> protected static final String[] colTypes= { <ide> "string", <ide> return new TwoDimTable(tableHeader, <ide> "models sorted in order of " + sort_metric + ", best first", <ide> rowHeaders, <del> Leaderboard.colHeaders, <add> Leaderboard.colHeaders(sort_metric), <ide> Leaderboard.colTypes, <ide> Leaderboard.colFormats, <ide> "#");
Java
bsd-2-clause
d8cb93baeb0ac7af46c472c91403e421d868dde3
0
chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio
package com.jme3.app; import java.util.logging.Logger; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.pm.ActivityInfo; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.jme3.app.Application; import com.jme3.input.TouchInput; import com.jme3.input.android.AndroidInput; import com.jme3.input.controls.TouchListener; import com.jme3.input.controls.TouchTrigger; import com.jme3.input.event.TouchEvent; import com.jme3.system.AppSettings; import com.jme3.system.JmeSystem; import com.jme3.system.android.OGLESContext; import com.jme3.system.android.AndroidConfigChooser.ConfigType; /** * <code>AndroidHarness</code> wraps a jme application object and runs it on Android * @author Kirill * @author larynx */ public class AndroidHarness extends Activity implements TouchListener, DialogInterface.OnClickListener { protected final static Logger logger = Logger.getLogger(AndroidHarness.class.getName()); /** * The application class to start */ protected String appClass = "jme3test.android.Test"; /** * The jme3 application object */ protected Application app = null; /** * ConfigType.FASTEST is RGB565, GLSurfaceView default * ConfigType.BEST is RGBA8888 or better if supported by the hardware */ protected ConfigType eglConfigType = ConfigType.FASTEST; /** * If true all valid and not valid egl configs are logged */ protected boolean eglConfigVerboseLogging = false; /** * Title of the exit dialog, default is "Do you want to exit?" */ protected String exitDialogTitle = "Do you want to exit?"; /** * Message of the exit dialog, default is "Use your home key to bring this app into the background or exit to terminate it." */ protected String exitDialogMessage = "Use your home key to bring this app into the background or exit to terminate it."; /** * Set the screen orientation, default is SENSOR * ActivityInfo.SCREEN_ORIENTATION_* constants * package android.content.pm.ActivityInfo * * SCREEN_ORIENTATION_UNSPECIFIED * SCREEN_ORIENTATION_LANDSCAPE * SCREEN_ORIENTATION_PORTRAIT * SCREEN_ORIENTATION_USER * SCREEN_ORIENTATION_BEHIND * SCREEN_ORIENTATION_SENSOR (default) * SCREEN_ORIENTATION_NOSENSOR */ protected int screenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR; protected OGLESContext ctx; protected GLSurfaceView view; protected boolean isGLThreadPaused = true; final private String ESCAPE_EVENT = "TouchEscape"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); JmeSystem.setResources(getResources()); JmeSystem.setActivity(this); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setRequestedOrientation(screenOrientation); AppSettings settings = new AppSettings(true); AndroidInput input = new AndroidInput(this); // Create application instance try { app = null; view = null; @SuppressWarnings("unchecked") Class<? extends Application> clazz = (Class<? extends Application>) Class.forName(appClass); app = clazz.newInstance(); app.setSettings(settings); app.start(); ctx = (OGLESContext) app.getContext(); view = ctx.createView(input, eglConfigType, eglConfigVerboseLogging); setContentView(view); } catch (Exception ex) { handleError("Class " + appClass + " init failed", ex); setContentView(new TextView(this)); } } @Override protected void onRestart() { super.onRestart(); if (app != null) app.restart(); logger.info("onRestart"); } @Override protected void onStart() { super.onStart(); logger.info("onStart"); } @Override protected void onResume() { super.onResume(); if (view != null) view.onResume(); isGLThreadPaused = false; logger.info("onResume"); } @Override protected void onPause() { super.onPause(); if (view != null) view.onPause(); isGLThreadPaused = true; logger.info("onPause"); } @Override protected void onStop() { super.onStop(); logger.info("onStop"); } @Override protected void onDestroy() { if (app != null) app.stop(! isGLThreadPaused); super.onDestroy(); logger.info("onDestroy"); } public Application getJmeApplication() { return app; } /** * Called when an error has occured. This is typically * invoked when an uncought exception is thrown in the render thread. * @param errorMsg The error message, if any, or null. * @param t Throwable object, or null. */ public void handleError(final String errorMsg, final Throwable t) { String s = ""; if (t != null && t.getStackTrace() != null) { for (StackTraceElement ste: t.getStackTrace()) { s += ste.getClassName() + "." + ste.getMethodName() + "(" + + ste.getLineNumber() + ") "; } } final String sTrace = s; logger.severe(t != null ? t.toString() : "OpenGL Exception"); logger.severe((errorMsg != null ? errorMsg + ": " : "") + sTrace); this.runOnUiThread(new Runnable() { @Override public void run() { AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon) .setTitle(t != null ? (t.getMessage() != null ? (t.getMessage() + ": " + t.getClass().getName()) : t.getClass().getName()) : "OpenGL Exception") .setPositiveButton("Kill", AndroidHarness.this) .setMessage((errorMsg != null ? errorMsg + ": " : "") + sTrace) .create(); dialog.show(); } }); } /** * Called by the android alert dialog, terminate the activity and OpenGL rendering * @param dialog * @param whichButton */ public void onClick(DialogInterface dialog, int whichButton) { if (whichButton != -2) { if (app != null) app.stop(true); this.finish(); } } /** * Gets called by the InputManager on all touch/drag/scale events */ @Override public void onTouch(String name, TouchEvent evt, float tpf) { if (name.equals(ESCAPE_EVENT)) { switch(evt.getType()) { case KEY_UP: this.runOnUiThread(new Runnable() { @Override public void run() { AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon) .setTitle(exitDialogTitle) .setPositiveButton("Yes", AndroidHarness.this) .setNegativeButton("No", AndroidHarness.this) .setMessage(exitDialogMessage) .create(); dialog.show(); } }); break; default: break; } } } }
engine/src/android/com/jme3/app/AndroidHarness.java
package com.jme3.app; import java.util.logging.Logger; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.jme3.app.Application; import com.jme3.input.TouchInput; import com.jme3.input.android.AndroidInput; import com.jme3.input.controls.TouchListener; import com.jme3.input.controls.TouchTrigger; import com.jme3.input.event.TouchEvent; import com.jme3.system.AppSettings; import com.jme3.system.JmeSystem; import com.jme3.system.android.OGLESContext; import com.jme3.system.android.AndroidConfigChooser.ConfigType; /** * <code>AndroidHarness</code> wraps a jme application object and runs it on Android * @author Kirill * @author larynx */ public class AndroidHarness extends Activity implements TouchListener, DialogInterface.OnClickListener { protected final static Logger logger = Logger.getLogger(AndroidHarness.class.getName()); /** * The application class to start */ protected String appClass = "jme3test.android.Test"; /** * The jme3 application object */ protected Application app = null; /** * ConfigType.FASTEST is RGB565, GLSurfaceView default * ConfigType.BEST is RGBA8888 or better if supported by the hardware */ protected ConfigType eglConfigType = ConfigType.FASTEST; /** * If true all valid and not valid egl configs are logged */ protected boolean eglConfigVerboseLogging = false; /** * Title of the exit dialog, default is "Do you want to exit?" */ protected String exitDialogTitle = "Do you want to exit?"; /** * Message of the exit dialog, default is "Use your home key to bring this app into the background or exit to terminate it." */ protected String exitDialogMessage = "Use your home key to bring this app into the background or exit to terminate it."; protected OGLESContext ctx; protected GLSurfaceView view; final private String ESCAPE_EVENT = "TouchEscape"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); JmeSystem.setResources(getResources()); JmeSystem.setActivity(this); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); AppSettings settings = new AppSettings(true); AndroidInput input = new AndroidInput(this); // Create application instance try { app = null; view = null; @SuppressWarnings("unchecked") Class<? extends Application> clazz = (Class<? extends Application>) Class.forName(appClass); app = clazz.newInstance(); app.setSettings(settings); app.start(); ctx = (OGLESContext) app.getContext(); view = ctx.createView(input, eglConfigType, eglConfigVerboseLogging); setContentView(view); } catch (Exception ex) { handleError("Class " + appClass + " init failed", ex); setContentView(new TextView(this)); } } @Override protected void onRestart(){ super.onRestart(); if (app != null) app.restart(); logger.info("onRestart"); } @Override protected void onStart(){ super.onStart(); logger.info("onStart"); } @Override protected void onResume() { super.onResume(); if (view != null) view.onResume(); logger.info("onResume"); } @Override protected void onPause() { super.onPause(); if (view != null) view.onPause(); logger.info("onPause"); } @Override protected void onStop(){ super.onStop(); logger.info("onStop"); } @Override protected void onDestroy(){ if (app != null) app.stop(true); super.onDestroy(); logger.info("onDestroy"); } public Application getJmeApplication() { return app; } /** * Called when an error has occured. This is typically * invoked when an uncought exception is thrown in the render thread. * @param errorMsg The error message, if any, or null. * @param t Throwable object, or null. */ public void handleError(final String errorMsg, final Throwable t) { String s = ""; if (t != null && t.getStackTrace() != null) { for (StackTraceElement ste: t.getStackTrace()) { s += ste.getClassName() + "." + ste.getMethodName() + "(" + + ste.getLineNumber() + ") "; } } final String sTrace = s; logger.severe(t != null ? t.toString() : "OpenGL Exception"); logger.severe((errorMsg != null ? errorMsg + ": " : "") + sTrace); this.runOnUiThread(new Runnable() { @Override public void run() { AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon) .setTitle(t != null ? (t.getMessage() != null ? (t.getMessage() + ": " + t.getClass().getName()) : t.getClass().getName()) : "OpenGL Exception") .setPositiveButton("Kill", AndroidHarness.this) .setMessage((errorMsg != null ? errorMsg + ": " : "") + sTrace) .create(); dialog.show(); } }); } /** * Called by the android alert dialog, terminate the activity and OpenGL rendering * @param dialog * @param whichButton */ public void onClick(DialogInterface dialog, int whichButton) { if (whichButton != -2) { if (app != null) app.stop(true); this.finish(); } } /** * Gets called by the InputManager on all touch/drag/scale events */ @Override public void onTouch(String name, TouchEvent evt, float tpf) { if (name.equals(ESCAPE_EVENT)) { switch(evt.getType()) { case KEY_UP: this.runOnUiThread(new Runnable() { @Override public void run() { AlertDialog dialog = new AlertDialog.Builder(AndroidHarness.this) // .setIcon(R.drawable.alert_dialog_icon) .setTitle(exitDialogTitle) .setPositiveButton("Yes", AndroidHarness.this) .setNegativeButton("No", AndroidHarness.this) .setMessage(exitDialogMessage) .create(); dialog.show(); } }); break; default: break; } } } }
Android: Fixed deadlock in AndroidHarness.onDestroy() and added screenOrientation git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@7791 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
engine/src/android/com/jme3/app/AndroidHarness.java
Android: Fixed deadlock in AndroidHarness.onDestroy() and added screenOrientation
<ide><path>ngine/src/android/com/jme3/app/AndroidHarness.java <ide> import android.app.Activity; <ide> import android.app.AlertDialog; <ide> import android.content.DialogInterface; <add>import android.content.pm.ActivityInfo; <ide> import android.opengl.GLSurfaceView; <ide> import android.os.Bundle; <ide> import android.view.SurfaceView; <ide> */ <ide> protected String exitDialogMessage = "Use your home key to bring this app into the background or exit to terminate it."; <ide> <add> /** <add> * Set the screen orientation, default is SENSOR <add> * ActivityInfo.SCREEN_ORIENTATION_* constants <add> * package android.content.pm.ActivityInfo <add> * <add> * SCREEN_ORIENTATION_UNSPECIFIED <add> * SCREEN_ORIENTATION_LANDSCAPE <add> * SCREEN_ORIENTATION_PORTRAIT <add> * SCREEN_ORIENTATION_USER <add> * SCREEN_ORIENTATION_BEHIND <add> * SCREEN_ORIENTATION_SENSOR (default) <add> * SCREEN_ORIENTATION_NOSENSOR <add> */ <add> protected int screenOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR; <ide> <ide> protected OGLESContext ctx; <ide> protected GLSurfaceView view; <del> <add> protected boolean isGLThreadPaused = true; <ide> final private String ESCAPE_EVENT = "TouchEscape"; <ide> <ide> @Override <ide> requestWindowFeature(Window.FEATURE_NO_TITLE); <ide> getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, <ide> WindowManager.LayoutParams.FLAG_FULLSCREEN); <del> <add> <add> setRequestedOrientation(screenOrientation); <add> <ide> AppSettings settings = new AppSettings(true); <ide> AndroidInput input = new AndroidInput(this); <ide> <ide> <ide> <ide> @Override <del> protected void onRestart(){ <add> protected void onRestart() <add> { <ide> super.onRestart(); <ide> if (app != null) <ide> app.restart(); <ide> <ide> <ide> @Override <del> protected void onStart(){ <add> protected void onStart() <add> { <ide> super.onStart(); <ide> logger.info("onStart"); <ide> } <ide> <ide> @Override <del> protected void onResume() { <add> protected void onResume() <add> { <ide> super.onResume(); <ide> if (view != null) <ide> view.onResume(); <add> isGLThreadPaused = false; <ide> logger.info("onResume"); <ide> } <ide> <ide> @Override <del> protected void onPause() { <add> protected void onPause() <add> { <ide> super.onPause(); <ide> if (view != null) <ide> view.onPause(); <add> isGLThreadPaused = true; <ide> logger.info("onPause"); <ide> } <ide> <ide> @Override <del> protected void onStop(){ <add> protected void onStop() <add> { <ide> super.onStop(); <ide> logger.info("onStop"); <ide> } <ide> <ide> @Override <del> protected void onDestroy(){ <add> protected void onDestroy() <add> { <ide> if (app != null) <del> app.stop(true); <add> app.stop(! isGLThreadPaused); <ide> super.onDestroy(); <ide> logger.info("onDestroy"); <ide> }
Java
mit
f1c49f061d21b9324575e62f855a64b61a6b1536
0
nking/curvature-scale-space-corners-and-transformations,nking/curvature-scale-space-corners-and-transformations
package algorithms.imageProcessing; import algorithms.compGeometry.PointPartitioner; import static algorithms.imageProcessing.PointMatcher.minTolerance; import algorithms.imageProcessing.util.MatrixUtil; import algorithms.misc.MiscMath; import algorithms.util.PairFloat; import algorithms.util.PairFloatArray; import algorithms.util.PairInt; import algorithms.util.PairIntArray; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import thirdparty.HungarianAlgorithm; /** * class to match the points extracted from two images. * * the transformation parameters of translation, rotation and scale are * found given the two sets of points. * <pre> Details of determining the transformation from points. After points are matched: Estimating scale: Take 2 pairs of points in both datasets and compute the distance between them and then take the ratio: scale = (distance between pair in set 1) / (distance between pair in set 2) Note: scale is roughly determined from contour matching too in the inflection matcher. Estimating rotation: Take the same 2 pairs and determine the difference in their angles: tan(theta) = delta y / delta x rotation = atan((delta y between pair in set 1) /(delta x between pair in set 1)) - atan((delta y between pair in set 2) /(delta x between pair in set 2)) Estimate translation: Performed on one point in set 1 with its candidate match in set 2: From the full transformation equation, we can rewrite: transX = xt0 - xc*scale - (((x0-xc)*scale*math.cos(theta)) + ((y0-yc)*scale*math.sin(theta))) transY = yt0 - yc*scale - ((-(x0-xc)*scale*math.sin(theta)) + ((y0-yc)*scale*math.cos(theta))) where (xc, yc) is the center of the first image Matching the points: For the contour matching, we were able to choose subsets of the entire sets of contours for better matching characteristics (subsets that had larger sigma values for their peaks could be used). For the points given here, there isn't a clear indicator for a subset that could be used preferably so that all nodes might not need to be visited. The need to use pairs of points in set1 matched against pairs in set 2 means that if one tries every combination of pairs, the runtime complexity is exponential. number of ways to make pairs in set 1 times the number of ways to make pairs in set 2 = n_1! n_2! ------------ X ------------ 2*(n_1 - 2)! 2*(n_2 - 2)! This is not feasible as soon as the sets get larger than a dozen points. Alternately, one could try a search algorithm to visit the space of all possible combinations of parameters instead of all combinations of subsets of pairs. max translation x possible = width of image 2 max translation y possible = height of image 2 max scale is set to some reasonable number like 10? max rotation is 1 degree changes = 360 (or quadrants?) then total number of permutations = maxTransX * maxTransY * maxScale * 360 = 1000 * 500 * 10 * 360 = 1.8 billion for pure grid search over parameter space then trying the parameters on all points puts another factor into there of nPoints set 1 * nPoints set 2. Note, because the cosine and sine terms in the transformation equation due to rotation work against one another and don't proceed in a total combined single direction with theta, we can't use a gradient descent solver. (note, this hasn't been edited for positive Y up yet) positive Y is down positive X is right positive theta starts from Y=0, X>=0 and proceeds CW 270 QIII | QIV | 180--------- 0 +X | QII | QI 90 +Y theta cos(theta) sin(theta) 0 0 1.0 0 ----- 30 0.5236 0.87 0.5 | 45 0.785 0.707 0.707 | QI 60 1.047 0.5 0.866 | 90 1.57 0.0 1.0 ----- 120 2.09 -0.5 0.866 | QII 150 2.618 -0.866 0.5 | 180 3.1416 -1.0 0.0 ----- 210 3.6652 -0.866 -0.5 | QIII 240 | 270 4.7124 0.0 -1.0 ----- 300 5.236 0.5 -0.866 | QIV 330 | ----- So then, it looks like a grid search over rotation and scale intervals followed by fitting for translation to get into the local neighborhood of the transformation solution, followed by the use of the Nelder-Mead Downhill Simplex to refine the transformation is a better solution. runtime complexity of: grid search: nRotationIntervals * nScaleIntervals * nSet1 * nSet2 downhill search: not polynomial nor deterministic. varies by dataset. In the searches, if rotation and scale are fixed, and transX and transY are to be found, one can use either: (1) compare the offsets implied by each combination of points in set 1 and set 2. for brown_lowe_2003 image1 and image2, the number of corners is n1 = 78 n2 = 88 n1 * n2 = 5616 How does one determine the best solution among those translations? One needs an assumed tolerance for the translation, and then to count the number of matches to a point in the 2nd set. The best solution has the highest number of matches with the same rules for an assumed tolerance and the smallest avg difference with predicted positions for matches in set 2. For the tolerance, the reasons that translation might be different as a function of position in the image might be: -- due to rounding to a pixel. these are very small errors. -- due to projection effects for different epipolar geometry (camera nadir perpendicular to different feature, for example). these are potentially very large and are not solved in the transformation with this point matcher though a tolerance is made for a small amount of it. (NOTE however, that once the points are matched, the true epipolar geometry can be calculated with the StereoProjection classes). -- due to errors in the location of the corner. this can be due to the edge detector. these are small errors. -- due to image warping such as distortions from the shape of the lens. one would need a point matcher tailored for the specific geometric projection. -- due to a camera not completely perpendicularly aligned with the optical axis. presumably, this is an extreme case and you'd want better data... For the Brown & Lowe 2003 points, transX=293.1 (stdDev=10.3) transY=14.3 (stdDev=5.9) the large standard deviation appears to be due to projection effects. the skyline is rotated about 13 degrees w.r.t. skyline in second image while the features at the bottom remain horizontal in both. The spread in standard deviation appears to be correlated w/ the image dimensions, as would be expected with projection being the largest reason for a spread in translation. That is, the X axis is twice the size of the Y and so are their respective standard deviations. Could make a generous allowance for projection effects by assuming a maximum present such as that in the Brown & Lowe images, that is image size times an error due to a differential spread over those pixels for a maximum difference in rotation such as 20 degrees or something. For Brown & Lowe images, the tolerance would be number of pixels for dimension times 0.02. If there is no reasonable solution using only scale, rotation, and translation, then a more computationally expensive point matcher that solves for epipolar geometry too or a differential rotation and associated variance in other parameters is needed (and hasn't been implemented here yet). **OR, even better, an approach using contours and an understanding of occlusion (the later possibly requires shape identification) can be made with the contour matcher in this project.** The contour matcher approach is currently not **commonly** possible with this project, because most edges are not closed curves. OR (2) try every possible combination of translation for X and Y which would be width of image 2 in pixels times the height of image 2 in pixels. for brown_lowe_2003 image1 and image2, image2 width = 517, height = 374 w * h = 193358 so this method is 34 times more The best solution among those translations is found in the same way as (1) above. </pre> * @author nichole */ public final class PointMatcher { private final Logger log = Logger.getLogger(this.getClass().getName()); protected static int minTolerance = 5; private boolean costIsNumAndDiff = false; //TODO: this has to be a high number for sets with projection. // the solution is sensitive to this value. private final float generalTolerance = 8; public static float toleranceGridFactor = 4.f; public void setCostToNumMatchedAndDiffFromModel() { costIsNumAndDiff = true; } /** * NOT READY FOR USE * * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @param outputMatchedLeftXY * @param outputMatchedRightXY * @param useLargestToleranceForOutput use the largest tolerance for * applying the transformation to point sets during matching. the largest * tolerance is the class variable generalTolerance. * If useLargestToleranceForOutput is false, the transformation's best * fit is used during matching (which should provide a smaller but more * certain matched output). If this method is used as a precursor to * projection (epipolar) solvers of sets that do have projection components, * one might prefer to set this to true to allow more to be matched. * @return */ public TransformationPointFit performPartitionedMatching( PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height, PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY, boolean useLargestToleranceForOutput) { /* -- perform whole sets matching -- perform vertical partition matching -- perform horizontal partition matching -- if the vert or horiz results are better that whole sets, consider partition into 4 TODO: methods are using a special fitting function specifically for skyline matches, but the function may not be ideal for whole image corner matching, so need to allow the choice of fitness function to be passed as an argument. */ // ====== whole sets match ======= PairIntArray allPointsLeftMatched = new PairIntArray(); PairIntArray allPointsRightMatched = new PairIntArray(); TransformationPointFit allPointsFit = performMatching( unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height, allPointsLeftMatched, allPointsRightMatched, 1.0f); float allPointsNStat = (float)allPointsFit.getNumberOfMatchedPoints()/ (float)allPointsFit.getNMaxMatchable(); log.info("all points set nStat=" + allPointsNStat + " Euclidean fit=" + allPointsFit.toString()); // ====== vertical partitioned matches ======= TransformationPointFit verticalPartitionedFit = performVerticalPartitionedMatching(2, unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height); /* // ====== horizontal partitioned matches ======= TransformationPointFit horizontalPartitionedFit = performHorizontalPartitionedMatching(2, unmatchedLeftXY, unmatchedRightXY, image1CentroidX, image1CentroidY, image2CentroidX, image2CentroidY); */ TransformationPointFit bestFit = allPointsFit; if (fitIsBetter(bestFit, verticalPartitionedFit)) { //fitIsBetterNStat(bestFit, verticalPartitionedFit)) { bestFit = verticalPartitionedFit; } if (bestFit == null) { return null; } // TODO: compare to horizontal fits when implemented Transformer transformer = new Transformer(); int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray transformedLeft = transformer.applyTransformation2( bestFit.getParameters(), unmatchedLeftXY, image1CentroidX, image1CentroidY); float transTolX, transTolY, tolerance; if (useLargestToleranceForOutput) { tolerance = generalTolerance; transTolX = generalTolerance * (float)Math.sqrt(1./2); transTolY = transTolX; } else { transTolX = bestFit.getTranslationXTolerance(); transTolY = bestFit.getTranslationYTolerance(); tolerance = (float)Math.sqrt(transTolX*transTolX + transTolY*transTolY); } float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal( transformedLeft, unmatchedRightXY, transTolX, transTolX); matchPoints(unmatchedLeftXY, unmatchedRightXY, tolerance, matchIndexesAndDiffs, outputMatchedLeftXY, outputMatchedRightXY); return bestFit; } /** * given unmatched point sets unmatchedLeftXY and unmatchedRightXY, * partitions the data in numberOfPartitions vertically, finds the * best match for each combination of vertical partitions as subsets * of their parent sets, then finds the best partition solution * among those, then refines the solution with a more detailed search * using all points. * * @param numberOfPartitions the number of vertical partitions to make. * the maximum value accepted is 3 and minimum is 1. * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @return best fitting transformation between unmatched left and right */ public TransformationPointFit performVerticalPartitionedMatching( final int numberOfPartitions, PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height) { if (numberOfPartitions > 3) { throw new IllegalArgumentException( "numberOfPartitions max value is 3"); } if (numberOfPartitions < 1) { throw new IllegalArgumentException( "numberOfPartitions min value is 1"); } int nXDiv = numberOfPartitions; int nYDiv = 1; float setsFractionOfImage = 1.f/(float)numberOfPartitions; int n = (int)Math.pow(nXDiv * nYDiv, 2); TransformationPointFit[] vertPartitionedFits = new TransformationPointFit[n]; float[] nStat = new float[n]; PointPartitioner partitioner = new PointPartitioner(); PairIntArray[] vertPartitionedLeft = partitioner.partitionVerticalOnly( unmatchedLeftXY, nXDiv); PairIntArray[] vertPartitionedRight = partitioner.partitionVerticalOnly( unmatchedRightXY, nXDiv); int bestFitIdx = -1; int count = 0; for (int p1 = 0; p1 < vertPartitionedLeft.length; p1++) { for (int p2 = 0; p2 < vertPartitionedRight.length; p2++) { // determine fit only with partitioned points PairIntArray part1 = vertPartitionedLeft[p1]; PairIntArray part2 = vertPartitionedRight[p2]; TransformationPointFit fit = calcTransWithRoughGrid( part1, part2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fit == null) { log.fine(Integer.toString(count) + ", p1=" + p1 + " p2=" + p2 + ") NO SOLN " + " n1=" + part1.getN() + " n2=" + part2.getN()); count++; continue; } nStat[count] = (float)fit.getNumberOfMatchedPoints()/ (float)fit.getNMaxMatchable(); log.fine(Integer.toString(count) + ", p1=" + p1 + " p2=" + p2 + ") nStat=" + nStat[count] + " n1=" + part1.getN() + " n2=" + part2.getN() + " Euclidean fit=" + fit.toString()); vertPartitionedFits[count] = fit; if (bestFitIdx == -1) { bestFitIdx = count; } else { // if nStat != inf, best has smallest st dev from mean if (fitIsBetter(vertPartitionedFits[bestFitIdx], vertPartitionedFits[count])) { log.fine("****==> fit=" + vertPartitionedFits[count].toString()); bestFitIdx = count; } } count++; } } if (bestFitIdx == -1) { return null; } /* nDiv=2 0: [0][1] 1: [0][1] [0] [1] 2: [0][1] 3: [0][1] [0] [1] nDiv=3 0: [0][1][2] 1: [0][1][2] 2: [0][1][2] [0] [1] [2] 3: [0][1][2] 4: [0][1][2] 5: [0][1][2] [0] [1] [2] 6: [0][1][2] 7: [0][1][2] 8: [0][1][2] [0] [1] [2] Consistent solutions for nDiv=2 would have similar solutions for comparisons 0: and 3: (which is index 0 and n+1) Consistent solutions for nDiv=3 would have similar solutions for comparisons 0: and 4: and 8: (which is index 0 and (n+1) and 2*(n+1)) OR 3: and 7: (which is index n and (2*n)+1) */ TransformationPointFit bestFit = vertPartitionedFits[bestFitIdx]; float scaleTolerance = 0.1f; float rotInDegreesTolerance = 20; float translationTolerance = 20; int idx2 = -1; int idx3 = -1; if (numberOfPartitions == 2) { if (bestFitIdx == 0) { // is this similar to vertPartitionedFits[3] ? idx2 = 3; } else if (bestFitIdx == 3) { // is this similar to vertPartitionedFits[0] ? idx2 = 0; } } else if (numberOfPartitions == 3) { if (bestFitIdx == 0) { // is this similar to vertPartitionedFits[4] and vertPartitionedFits[8] ? idx2 = 4; idx3 = 8; } else if (bestFitIdx == 4) { // is this similar to vertPartitionedFits[0] and vertPartitionedFits[8] ? idx2 = 0; idx3 = 8; } else if (bestFitIdx == 8) { // is this similar to vertPartitionedFits[0] and vertPartitionedFits[4] ? idx2 = 0; idx3 = 4; } else if (bestFitIdx == 3) { // is this similar to vertPartitionedFits[7] ? idx2 = 7; idx3 = -1; } else if (bestFitIdx == 7) { // is this similar to vertPartitionedFits[3] ? idx2 = 3; idx3 = -1; } if (idx2 > -1) { boolean fitIsSimilar = fitIsSimilar(bestFit, vertPartitionedFits[idx2], scaleTolerance, rotInDegreesTolerance, translationTolerance); if (fitIsSimilar) { log.fine("similar solutions for idx=" + Integer.toString(bestFitIdx) + " and " + Integer.toString(idx2) + ":" + " Euclidean fit" + Integer.toString(bestFitIdx) + "=" + bestFit.toString() + " Euclidean fit" + Integer.toString(idx2) + "=" + vertPartitionedFits[idx2].toString()); //TODO: combine these? } if (idx3 > -1) { fitIsSimilar = fitIsSimilar(bestFit, vertPartitionedFits[idx3], scaleTolerance, rotInDegreesTolerance, translationTolerance); if (fitIsSimilar) { log.fine("similar solutions for idx=" + Integer.toString(bestFitIdx) + " and " + Integer.toString(idx3) + ":" + " Euclidean fit" + Integer.toString(bestFitIdx) + "=" + bestFit.toString() + " Euclidean fit" + Integer.toString(idx3) + "=" + vertPartitionedFits[idx3].toString()); //TODO: combine these? } } } } if (bestFit == null) { return null; } log.info("best fit so far from partitions: " + bestFit.toString()); //TODO: if solutions are combined, this may need to be done above. // use either a finer grid search or a downhill simplex to improve the // solution which was found coursely within about 10 degrees float rot = bestFit.getParameters().getRotationInDegrees(); int rotStart = (int)rot - 10; if (rotStart < 0) { rotStart = 360 + rotStart; } int rotStop = (int)rot + 10; if (rotStop > 359) { rotStop = rotStop - 360; } int rotDelta = 1; int scaleStart = (int)(0.9 * bestFit.getScale()); if (scaleStart < 1) { scaleStart = 1; } int scaleStop = (int)(1.1 * bestFit.getScale()); int scaleDelta = 1; int nTransIntervals = 4; float transX = bestFit.getParameters().getTranslationX(); float transY = bestFit.getParameters().getTranslationY(); //TODO: revision needed here float toleranceX = bestFit.getTranslationXTolerance(); float toleranceY = bestFit.getTranslationYTolerance(); float dx = (image2Width/toleranceGridFactor); float dy = (image2Height/toleranceGridFactor); if (toleranceX < (dx/10.f)) { dx = (dx/10.f); } if (toleranceY < (dy/10.f)) { dy = (dy/10.f); } float tolTransX = 2 * toleranceX; float tolTransY = 2 * toleranceY; int transXStart = (int)(transX - dx); int transXStop = (int)(transX + dx); int transYStart = (int)(transY - dy); int transYStop = (int)(transY + dy); log.fine(String.format( "starting finer grid search with rot=%d to %d and scale=%d to %d", rotStart, rotStop, scaleStart, scaleStop)); TransformationPointFit fit = calculateTransformationWithGridSearch( unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height, rotStart, rotStop, rotDelta, scaleStart, scaleStop, scaleDelta, transXStart, transXStop, transYStart, transYStop, nTransIntervals, tolTransX, tolTransY, setsFractionOfImage); if (bestFit != null && fit != null) { log.fine(" partition compare \n **==> bestFit=" + bestFit.toString() + "\n fit=" + fit.toString()); } TransformationPointFit[] reevalFits = new TransformationPointFit[2]; boolean[] fitIsBetter = new boolean[1]; if ((bestFit != null) && (fit != null) && ( ((bestFit.getTranslationXTolerance()/fit.getTranslationXTolerance()) > 2) && ((bestFit.getTranslationYTolerance()/fit.getTranslationYTolerance()) > 2)) || ( ((bestFit.getTranslationXTolerance()/fit.getTranslationXTolerance()) < 0.5) && ((bestFit.getTranslationYTolerance()/fit.getTranslationYTolerance()) < 0.5)) ) { reevaluateFitsForCommonTolerance(bestFit, fit, unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, reevalFits, fitIsBetter); bestFit = reevalFits[0]; fit = reevalFits[1]; } else { fitIsBetter[0] = fitIsBetter(bestFit, fit); } if (bestFit != null && fit != null) { log.fine(" tol corrected partition compare \n **==> bestFit=" + bestFit.toString() + "\n fit=" + fit.toString()); } if (fitIsBetter[0]) { log.fine(" ***** partition bestFit=" + fit.toString()); } else { log.fine(" ***** partition keeping bestFit=" + bestFit.toString()); } if (fitIsBetter[0]) { bestFit = fit; } if (bestFit.getNMaxMatchable() == 0) { int nMaxMatchable = (unmatchedLeftXY.getN() < unmatchedRightXY.getN()) ? unmatchedLeftXY.getN() : unmatchedRightXY.getN(); bestFit.setMaximumNumberMatchable(nMaxMatchable); } return bestFit; } /** * NOT READY FOR USE * * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param outputMatchedLeftXY * @param image2Width * @param outputMatchedRightXY * @param image2Height * @param useLargestToleranceForOutput use the largest tolerance for * applying the transformation to point sets during matching. the largest * tolerance is the class variable generalTolerance. * If useLargestToleranceForOutput is false, the transformation's best * fit is used during matching (which should provide a smaller but more * certain matched output). If this method is used as a precursor to * projection (epipolar) solvers of sets that do have projection components, * one might prefer to set this to true to allow more to be matched. * @return best fitting transformation between unmatched points sets * left and right */ public TransformationPointFit performMatching0( PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height, PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY, boolean useLargestToleranceForOutput) { if (unmatchedLeftXY == null || unmatchedLeftXY.getN() < 3) { throw new IllegalArgumentException( "unmatchedLeftXY cannot be null and must have at least 3 points."); } if (unmatchedRightXY == null || unmatchedRightXY.getN() < 3) { throw new IllegalArgumentException( "unmatchedRightXY cannot be null and must have at least 3 points."); } TransformationPointFit bestFit = performMatching0( unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height); if (bestFit == null) { return null; } int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; Transformer transformer = new Transformer(); PairFloatArray transformedLeft = transformer.applyTransformation2( bestFit.getParameters(), unmatchedLeftXY, image1CentroidX, image1CentroidY); float transTolX, transTolY, tolerance; if (useLargestToleranceForOutput) { tolerance = generalTolerance; transTolX = generalTolerance * (float)Math.sqrt(1./2); transTolY = transTolX; } else { transTolX = bestFit.getTranslationXTolerance(); transTolY = bestFit.getTranslationYTolerance(); tolerance = (float)Math.sqrt(transTolX*transTolX + transTolY*transTolY); } float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal( transformedLeft, unmatchedRightXY, transTolX, transTolX); matchPoints(unmatchedLeftXY, unmatchedRightXY, tolerance, matchIndexesAndDiffs, outputMatchedLeftXY, outputMatchedRightXY); int nMaxMatchable = (unmatchedLeftXY.getN() < unmatchedRightXY.getN()) ? unmatchedLeftXY.getN() : unmatchedRightXY.getN(); bestFit.setMaximumNumberMatchable(nMaxMatchable); return bestFit; } /** * Given unmatched point sets unmatchedLeftXY and unmatchedRightXY, * finds the best Euclidean transformation, then finds the best partition * solution among those, then refines the solution with a more detailed * search using all points. * * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @return best fitting transformation between unmatched left and right */ public TransformationPointFit performMatching0( PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height) { float setsFractionOfImage = 1.0f; PairIntArray part1 = unmatchedLeftXY; PairIntArray part2 = unmatchedRightXY; TransformationPointFit fit = calcTransWithRoughGrid( part1, part2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fit == null) { return null; } float nStat = (float)fit.getNumberOfMatchedPoints()/ (float)fit.getNMaxMatchable(); log.info("best fit so fars: " + fit.toString()); // use either a finer grid search or a downhill simplex to improve the // solution which was found coursely within about 10 degrees float rot = fit.getParameters().getRotationInDegrees(); int rotStart = (int)rot - 10; if (rotStart < 0) { rotStart = 360 + rotStart; } int rotStop = (int)rot + 10; if (rotStop > 359) { rotStop = rotStop - 360; } int rotDelta = 1; int scaleStart = (int)(0.9 * fit.getScale()); if (scaleStart < 1) { scaleStart = 1; } int scaleStop = (int)(1.1 * fit.getScale()); int scaleDelta = 1; int nTransIntervals = 4; float transX = fit.getParameters().getTranslationX(); float transY = fit.getParameters().getTranslationY(); //TODO: revision needed here float toleranceX = fit.getTranslationXTolerance(); float toleranceY = fit.getTranslationYTolerance(); float dx = (image2Width/toleranceGridFactor); float dy = (image2Height/toleranceGridFactor); if (toleranceX < (dx/10.f)) { dx = (dx/10.f); } if (toleranceY < (dy/10.f)) { dy = (dy/10.f); } float tolTransX = 2 * toleranceX; float tolTransY = 2 * toleranceY; int transXStart = (int)(transX - dx); int transXStop = (int)(transX + dx); int transYStart = (int)(transY - dy); int transYStop = (int)(transY + dy); log.fine(String.format( "starting finer grid search with rot=%d to %d and scale=%d to %d", rotStart, rotStop, scaleStart, scaleStop)); TransformationPointFit fit2 = calculateTransformationWithGridSearch( unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height, rotStart, rotStop, rotDelta, scaleStart, scaleStop, scaleDelta, transXStart, transXStop, transYStart, transYStop, nTransIntervals, tolTransX, tolTransY, setsFractionOfImage); if (fitIsBetter(fit, fit2)) { fit = fit2; } if (fit.getNMaxMatchable() == 0) { int nMaxMatchable = (unmatchedLeftXY.getN() < unmatchedRightXY.getN()) ? unmatchedLeftXY.getN() : unmatchedRightXY.getN(); fit.setMaximumNumberMatchable(nMaxMatchable); } return fit; } /** * NOT READY FOR USE * * @param numberOfPartitions the number of vertical partitions to make. * the maximum value accepted is 3. * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param outputMatchedLeftXY * @param image2Width * @param outputMatchedRightXY * @param image2Height * @param useLargestToleranceForOutput use the largest tolerance for * applying the transformation to point sets during matching. the largest * tolerance is the class variable generalTolerance. * If useLargestToleranceForOutput is false, the transformation's best * fit is used during matching (which should provide a smaller but more * certain matched output). If this method is used as a precursor to * projection (epipolar) solvers of sets that do have projection components, * one might prefer to set this to true to allow more to be matched. * @return best fitting transformation between unmatched points sets * left and right */ public TransformationPointFit performVerticalPartitionedMatching( final int numberOfPartitions, PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height, PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY, boolean useLargestToleranceForOutput) { if (numberOfPartitions > 3) { throw new IllegalArgumentException("numberOfPartitions max value is 3"); } if (numberOfPartitions < 1) { throw new IllegalArgumentException("numberOfPartitions min value is 1"); } TransformationPointFit bestFit = performVerticalPartitionedMatching( numberOfPartitions, unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height); if (bestFit == null) { return null; } int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; Transformer transformer = new Transformer(); PairFloatArray transformedLeft = transformer.applyTransformation2( bestFit.getParameters(), unmatchedLeftXY, image1CentroidX, image1CentroidY); float transTolX, transTolY, tolerance; if (useLargestToleranceForOutput) { tolerance = generalTolerance; transTolX = generalTolerance * (float)Math.sqrt(1./2); transTolY = transTolX; } else { transTolX = bestFit.getTranslationXTolerance(); transTolY = bestFit.getTranslationYTolerance(); tolerance = (float)Math.sqrt(transTolX*transTolX + transTolY*transTolY); } float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal( transformedLeft, unmatchedRightXY, transTolX, transTolX); matchPoints(unmatchedLeftXY, unmatchedRightXY, tolerance, matchIndexesAndDiffs, outputMatchedLeftXY, outputMatchedRightXY); int nMaxMatchable = (unmatchedLeftXY.getN() < unmatchedRightXY.getN()) ? unmatchedLeftXY.getN() : unmatchedRightXY.getN(); bestFit.setMaximumNumberMatchable(nMaxMatchable); return bestFit; } /** * NOT READY FOR USE * * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param outputMatchedLeftXY * @param image2Height * @param image2Width * @param outputMatchedRightXY * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * * @return */ public TransformationPointFit performMatching( PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height, PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY, float setsFractionOfImage) { Transformer transformer = new Transformer(); PairIntArray part1 = unmatchedLeftXY; PairIntArray part2 = unmatchedRightXY; TransformationPointFit transFit = calculateEuclideanTransformation( part1, part2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (transFit == null) { return null; } // -- filter part1 and part2 to keep only intersection region int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; int image2CentroidX = image2Width >> 1; int image2CentroidY = image2Height >> 1; PairIntArray filtered1 = new PairIntArray(); PairIntArray filtered2 = new PairIntArray(); populateIntersectionOfRegions(transFit.getParameters(), part1, part2, image1CentroidX, image1CentroidY, image2CentroidX, image2CentroidY, filtered1, filtered2); int nMaxMatchable = (filtered1.getN() < filtered2.getN()) ? filtered1.getN() : filtered2.getN(); transFit.setMaximumNumberMatchable(nMaxMatchable); if (nMaxMatchable == 0) { return transFit; } // -- transform filtered1 for matching and evaluation PairFloatArray transformedFiltered1 = transformer.applyTransformation2(transFit.getParameters(), filtered1, image1CentroidX, image1CentroidY); //TODO: consider using transFit.getTolerance() here float transTolX = generalTolerance; float tolerance = transTolX * (float)Math.sqrt(1./2); //evaluate the fit and store a statistical var: nmatched/nmaxmatchable float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal( transformedFiltered1, filtered2, transTolX, transTolX); PairFloatArray part1MatchedTransformed = new PairFloatArray(); PairIntArray part2Matched = new PairIntArray(); matchPoints(transformedFiltered1, filtered2, tolerance, matchIndexesAndDiffs, part1MatchedTransformed, part2Matched); PairIntArray part1Matched = new PairIntArray(); part2Matched = new PairIntArray(); matchPoints(filtered1, filtered2, tolerance, matchIndexesAndDiffs, part1Matched, part2Matched); TransformationPointFit fit2 = evaluateFitForMatchedTransformed( transFit.getParameters(), part1MatchedTransformed, part2Matched); fit2.setTranslationXTolerance(transTolX); fit2.setTranslationYTolerance(transTolX); fit2.setMaximumNumberMatchable(nMaxMatchable); float nStat = (nMaxMatchable > 0) ? (float)part1Matched.getN()/(float)nMaxMatchable : 0; log.fine("nStat=" + nStat + " nMaxMatchable=" + nMaxMatchable + " Euclidean fit=" + fit2.toString() + " original fit=" + transFit.toString()); outputMatchedLeftXY.swapContents(part1Matched); outputMatchedRightXY.swapContents(part2Matched); return fit2; } /** * given the scale, rotation and set 1's reference frame centroids, * calculate the translation between set1 and set2 assuming that not all * points will match. transXTol and transYTol allow a tolerance when * matching the predicted position of a point in set2. * * It's expected that the invoker of this method is trying to solve for * translation for sets of points like corners in images. This assumption * means that the number of point pair combinations is always far less * than the pixel combinations of translations over x and y. * * NOTE: scale has be >= 1, so if one image has a smaller scale, it has to * be the first set given in arguments. * * ALSO NOTE: if you know a better solution exists for translation * parameters that matches fewer points, but has a small avg dist from * model and smaller standard deviation from the avg dist from model, * then transXTol and transYTol should be set to a smaller value and passed * to this method. * @param params transformation parameters to apply to matched1 * @param matched1Transformed * @param matched2 set of points from image 2 that are matched to points in * matched1 with same indexes * @return */ public TransformationPointFit evaluateFitForMatchedTransformed( TransformationParameters params, PairFloatArray matched1Transformed, PairIntArray matched2) { if (matched1Transformed == null) { throw new IllegalArgumentException( "matched1Transformed cannot be null"); } if (matched2 == null) { throw new IllegalArgumentException("matched2 cannot be null"); } if (matched1Transformed.getN() != matched2.getN()) { throw new IllegalArgumentException( "the 2 point sets must have the same length"); } double[] diff = new double[matched1Transformed.getN()]; double avg = 0; for (int i = 0; i < matched1Transformed.getN(); i++) { float transformedX = matched1Transformed.getX(i); float transformedY = matched1Transformed.getY(i); int x2 = matched2.getX(i); int y2 = matched2.getY(i); double dx = x2 - transformedX; double dy = y2 - transformedY; diff[i] = Math.sqrt(dx*dx + dy*dy); avg += diff[i]; } avg /= (double)matched2.getN(); double stdDev = 0; for (int i = 0; i < matched2.getN(); i++) { double d = diff[i] - avg; stdDev += (d * d); } stdDev = Math.sqrt(stdDev/((double)matched2.getN() - 1)); TransformationPointFit fit = new TransformationPointFit(params, matched2.getN(), avg, stdDev, Float.MAX_VALUE, Float.MAX_VALUE); return fit; } protected TransformationPointFit evaluateFitForUnMatchedTransformedGreedy( TransformationParameters params, PairFloatArray unmatched1Transformed, PairIntArray unmatched2, float tolTransX, float tolTransY) { if (unmatched1Transformed == null) { throw new IllegalArgumentException( "unmatched1Transformed cannot be null"); } if (unmatched2 == null) { throw new IllegalArgumentException( "unmatched2 cannot be null"); } int n = unmatched1Transformed.getN(); Set<Integer> chosen = new HashSet<Integer>(); double[] diffs = new double[n]; int nMatched = 0; double avg = 0; for (int i = 0; i < n; i++) { float transformedX = unmatched1Transformed.getX(i); float transformedY = unmatched1Transformed.getY(i); double minDiff = Double.MAX_VALUE; int min2Idx = -1; for (int j = 0; j < unmatched2.getN(); j++) { if (chosen.contains(Integer.valueOf(j))) { continue; } float dx = transformedX - unmatched2.getX(j); float dy = transformedY - unmatched2.getY(j); if ((Math.abs(dx) > tolTransX) || (Math.abs(dy) > tolTransY)) { continue; } float diff = (float)Math.sqrt(dx*dx + dy*dy); if (diff < minDiff) { minDiff = diff; min2Idx = j; } } if (minDiff < Double.MAX_VALUE) { diffs[nMatched] = minDiff; nMatched++; chosen.add(Integer.valueOf(min2Idx)); avg += minDiff; } } avg = (nMatched == 0) ? Double.MAX_VALUE : avg / (double)nMatched; double stDev = 0; for (int i = 0; i < nMatched; i++) { double d = diffs[i] - avg; stDev += (d * d); } stDev = (nMatched == 0) ? Double.MAX_VALUE : Math.sqrt(stDev/((double)nMatched - 1.)); TransformationPointFit fit = new TransformationPointFit(params, nMatched, avg, stDev, tolTransX, tolTransY); return fit; } protected TransformationPointFit evaluateFitForUnMatchedTransformedOptimal( TransformationParameters params, PairFloatArray unmatched1Transformed, PairIntArray unmatched2, float tolTransX, float tolTransY) { if (unmatched1Transformed == null) { throw new IllegalArgumentException( "unmatched1Transformed cannot be null"); } if (unmatched2 == null) { throw new IllegalArgumentException( "unmatched2 cannot be null"); } int n = unmatched1Transformed.getN(); float[][] matchedIndexesAndDiffs = calculateMatchUsingOptimal( unmatched1Transformed, unmatched2, tolTransX, tolTransY); int nMatched = matchedIndexesAndDiffs.length; double avg = 0; double stDev = 0; for (int i = 0; i < nMatched; i++) { avg += matchedIndexesAndDiffs[i][2]; } avg = (nMatched == 0) ? Double.MAX_VALUE : (avg / (double)nMatched); for (int i = 0; i < nMatched; i++) { double d = matchedIndexesAndDiffs[i][2] - avg; stDev += (d * d); } stDev = (nMatched == 0) ? Double.MAX_VALUE : (Math.sqrt(stDev/((double)nMatched - 1.))); TransformationPointFit fit = new TransformationPointFit(params, nMatched, avg, stDev, tolTransX, tolTransY); return fit; } private void populateIntersectionOfRegions( TransformationParameters params, PairIntArray set1, PairIntArray set2, int image1CentroidX, int image1CentroidY, int image2CentroidX, int image2CentroidY, PairIntArray filtered1, PairIntArray filtered2) { double tolerance = 20; // determine the bounds of filtered2. any points in set2 that have // x < xy2LL[0] will not be matchable, etc. // TODO: correct this to use "point inside polygon" instead of rectangle Transformer transformer = new Transformer(); double[] xy2LL = transformer.applyTransformation(params, image1CentroidX, image1CentroidY, 0, 0); double[] xy2UR = transformer.applyTransformation(params, image1CentroidX, image1CentroidY, 2*image1CentroidX - 1, 2*image1CentroidY - 1); // to find lower-left and upper-left in image 1 of image // 2 boundaries requires the reverse parameters MatchedPointsTransformationCalculator tc = new MatchedPointsTransformationCalculator(); double[] x1cy1c = tc.applyTransformation(params, image1CentroidX, image1CentroidY, image1CentroidX, image1CentroidY); TransformationParameters revParams = tc.swapReferenceFrames( params, image2CentroidX, image2CentroidY, image1CentroidX, image1CentroidY, x1cy1c[0], x1cy1c[1]); double[] xy1LL = transformer.applyTransformation( revParams, image2CentroidX, image2CentroidY, 0, 0); xy1LL[0] -= tolerance; xy1LL[1] -= tolerance; double[] xy1UR = transformer.applyTransformation( revParams, image2CentroidX, image2CentroidY, 2*image2CentroidX - 1, 2*image2CentroidY - 1); xy1UR[0] += tolerance; xy1UR[1] += tolerance; for (int i = 0; i < set1.getN(); i++) { int x = set1.getX(i); // TODO: replace with an "outside polygon" check if ((x < xy1LL[0]) || (x > xy1UR[0])) { continue; } int y = set1.getY(i); if ((y < xy1LL[1]) || (y > xy1UR[1])) { continue; } filtered1.add(x, y); } for (int i = 0; i < set2.getN(); i++) { int x = set2.getX(i); // TODO: replace with an "outside polygon" check if ((x < xy2LL[0]) || (x > xy2UR[0])) { continue; } int y = set2.getY(i); if ((y < xy2LL[1]) || (y > xy2UR[1])) { continue; } filtered2.add(x, y); } } /** * given the indexes and residuals from optimal matching, populate * outputMatched1 and outputMatched2; * * @param set1 * @param set2 * @param transTolXY * @param matchedIndexesAndDiffs two dimensional array holding the matched * indexes and the distances between the model and the point for that pair. * each row holds {idx1, idx2, diff} * @param outputMatched1 the container to hold the output matching points * for image 1 that are paired with outputMatched2 as a result of running * this method. * @param outputMatched2 the container to hold the output matching points * for image 2 that are paired with outputMatched1 as a result of running * this method. */ public void matchPoints( PairIntArray set1, PairIntArray set2, float transTolXY, float[][] matchedIndexesAndDiffs, PairIntArray outputMatched1, PairIntArray outputMatched2) { if (matchedIndexesAndDiffs == null) { return; } for (int i = 0; i < matchedIndexesAndDiffs.length; i++) { int idx1 = (int)matchedIndexesAndDiffs[i][0]; int idx2 = (int)matchedIndexesAndDiffs[i][1]; float diff = matchedIndexesAndDiffs[i][2]; if (diff < transTolXY) { outputMatched1.add(set1.getX(idx1), set1.getY(idx1)); outputMatched2.add(set2.getX(idx2), set2.getY(idx2)); } } } /** * given the indexes and residuals from optimal matching, populate * outputMatched1 and outputMatched2; * * @param set1 * @param set2 * @param transTolXY * @param matchedIndexesAndDiffs two dimensional array holding the matched * indexes and the distances between the model and the point for that pair. * each row holds {idx1, idx2, diff} * @param outputMatched1 the container to hold the output matching points * for image 1 that are paired with outputMatched2 as a result of running * this method. * @param outputMatched2 the container to hold the output matching points * for image 2 that are paired with outputMatched1 as a result of running * this method. */ public void matchPoints(PairFloatArray set1, PairIntArray set2, float transTolXY, float[][] matchedIndexesAndDiffs, PairFloatArray outputMatched1, PairIntArray outputMatched2) { for (int i = 0; i < matchedIndexesAndDiffs.length; i++) { int idx1 = (int)matchedIndexesAndDiffs[i][0]; int idx2 = (int)matchedIndexesAndDiffs[i][1]; float diff = matchedIndexesAndDiffs[i][2]; if (diff < transTolXY) { outputMatched1.add(set1.getX(idx1), set1.getY(idx1)); outputMatched2.add(set2.getX(idx2), set2.getY(idx2)); } } } /** * calculate for unmatched points and if best match is not good, * reverse the order of sets and try again in order to solve for * possible scale transformation smaller than 1. * * @param scene * @param model * @param image1Width * @param image1Height * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * @param image2Width * @param image2Height * * @return */ public TransformationPointFit calculateEuclideanTransformation( PairIntArray scene, PairIntArray model, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { TransformationPointFit fit = calcTransWithRoughGrid( scene, model, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fit == null) { return null; } int nMaxMatchable = (scene.getN() < model.getN()) ? scene.getN() : model.getN(); float fracMatched = (float)fit.getNumberOfMatchedPoints()/(float)nMaxMatchable; if (fracMatched < 0.3) { // reverse the order to solve for possible scale < 1. TransformationPointFit revFit = calcTransWithRoughGrid( model, scene, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fitIsBetter(fit, revFit)) { TransformationParameters params = revFit.getParameters(); // reverse the parameters. // needs a reference point in both datasets for direct calculation int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; int image2CentroidX = image2Width >> 1; int image2CentroidY = image2Height >> 1; MatchedPointsTransformationCalculator tc = new MatchedPointsTransformationCalculator(); double[] x1y1 = tc.applyTransformation(params, image1CentroidX, image1CentroidY, image2CentroidX, image2CentroidY); TransformationParameters revParams = tc.swapReferenceFrames( params, image1CentroidX, image1CentroidY, image2CentroidX, image2CentroidY, x1y1[0], x1y1[1]); fit = new TransformationPointFit(revParams, revFit.getNumberOfMatchedPoints(), revFit.getMeanDistFromModel(), revFit.getStDevFromMean(), revFit.getTranslationXTolerance(), revFit.getTranslationYTolerance()); } } return fit; } /** * calculate for unmatched points. Note, this method does a grid search * over rotation and scale in intervals of 10 degrees and 1, * respectively and for each translation solution within those, * it has uses O(N^4) algorithm to find the best translation in x and y, * so it is a good idea to use a smaller * set of good matching points here or to use the method * which can limit the search space to known limits. * NOTE: the translation algorithm runtime complexity will be improved soon. * calculateTranslationForUnmatched0 will be used instead soon. * * @param scene * @param model * @param image1Width * @param image1Height * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * @param image2Height * @param image2Width * * @return */ public TransformationPointFit calcTransWithRoughGrid( PairIntArray scene, PairIntArray model, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { if ((scene == null) || (model == null)) { return null; } if ((scene.getN() < 3) || (model.getN() < 3)) { return null; } int rotStart = 0; int rotStop = 359; int rotDelta = 10; int scaleStart = 1; int scaleStop = 5; int scaleDelta = 1; TransformationPointFit fit = calculateTransformationWithGridSearch( scene, model, image1Width, image1Height, image2Width, image2Height, rotStart, rotStop, rotDelta, scaleStart, scaleStop, scaleDelta, setsFractionOfImage); if (fit != null) { log.fine("best from calculateTransformationWithGridSearch: " + fit.toString()); } return fit; } /** * given unordered unmatched points for a transformed set1 and * the model set2 from image1 and image2 * respectively, find the * optimal matching in set2 within tolerance and return the * matched information as a two dimensional array of * {index from set1, index from set2, diff of point in set2 from * model generation by point in set1} * * @param transformed1 * @param set2 * @param toleranceX * @param toleranceY * @return a two dimensional array holding the matched indexes and * the distances between the model and the point for that pair. * each row holds float[]{idx1, idx2, diff} */ public float[][] calculateMatchUsingOptimal( PairFloatArray transformed1, PairIntArray set2, float toleranceX, float toleranceY) { int nPoints1 = transformed1.getN(); int nPoints2 = set2.getN(); float[][] diffsAsCost = new float[nPoints1][nPoints2]; // the algorithm modifies diffsAsCost, so make a copy float[][] diffsAsCostCopy = new float[nPoints1][nPoints2]; // key = indexes i,j; value = diffX, diffY Map<PairInt, PairFloat> diffsXY = new HashMap<PairInt, PairFloat>(); int nWithinTol = 0; for (int i = 0; i < transformed1.getN(); i++) { diffsAsCost[i] = new float[nPoints2]; diffsAsCostCopy[i] = new float[nPoints2]; float x = transformed1.getX(i); float y = transformed1.getY(i); for (int j = 0; j < set2.getN(); j++) { int x2 = set2.getX(j); int y2 = set2.getY(j); float diffX = x - x2; float diffY = y - y2; if ((Math.abs(diffX) > toleranceX) || (Math.abs(diffY) > toleranceY)) { diffsAsCost[i][j] = Float.MAX_VALUE; diffsAsCostCopy[i][j] = Float.MAX_VALUE; } else { double dist = Math.sqrt(diffX*diffX + diffY*diffY); diffsAsCost[i][j] = (float)dist; diffsAsCostCopy[i][j] = (float)dist; diffsXY.put(new PairInt(i, j), new PairFloat(diffX, diffY)); nWithinTol++; } } } if (nWithinTol == 0) { return new float[0][]; } boolean transposed = false; if (nPoints1 > nPoints2) { diffsAsCostCopy = MatrixUtil.transpose(diffsAsCostCopy); transposed = true; } HungarianAlgorithm b = new HungarianAlgorithm(); int[][] match = b.computeAssignments(diffsAsCostCopy); // count the number of matches int count = 0; for (int i = 0; i < match.length; i++) { int idx1 = match[i][0]; int idx2 = match[i][1]; if (idx1 == -1 || idx2 == -1) { continue; } if (idx1 == Float.MAX_VALUE || idx2 == Float.MAX_VALUE) { continue; } if (transposed) { int swap = idx1; idx1 = idx2; idx2 = swap; } PairFloat diffXY = diffsXY.get(new PairInt(idx1, idx2)); if (diffXY == null) { continue; } if ((diffXY.getX() > toleranceX) || (diffXY.getY() > toleranceY)) { continue; } count++; } float[][] output = new float[count][]; if (count == 0) { return output; } count = 0; for (int i = 0; i < match.length; i++) { int idx1 = match[i][0]; int idx2 = match[i][1]; if (idx1 == -1 || idx2 == -1) { continue; } if (transposed) { int swap = idx1; idx1 = idx2; idx2 = swap; } PairFloat diffXY = diffsXY.get(new PairInt(idx1, idx2)); if (diffXY == null) { continue; } if ((diffXY.getX() > toleranceX) || (diffXY.getY() > toleranceY)) { continue; } output[count] = new float[3]; output[count][0] = idx1; output[count][1] = idx2; output[count][2] = diffsAsCost[idx1][idx2]; count++; } return output; } /** * Calculate for unmatched points the Euclidean transformation to transform * set1 into the reference frame of set2. Note, this method does a grid * search over rotation and scale in the given intervals, and for each * translation solution within those, it uses an O(N^2) algorithm to find * the best translation in x and y. * If there are solutions with similar fits and different parameters, they * are retained and compared with finer grid searches to decide among * them so the total runtime complexity is * larger than O(N^2) but smaller than O(N^3). * The constant factors in the runtime are roughly * ((scaleStop - scaleStart)/scaleDelta) * times (number of rotation intervals) * times (number of grid search cells which is 10*10 at best). * * @param set1 * @param set2 * @param image1Width * @param image1Height * @param image2Width * @param rotStart start of rotation search in degrees * @param rotStop stop (exclusive) or rotations search in degrees * @param image2Height * @param rotDelta change in rotation to add to reach next step in rotation * search in degrees * @param scaleStart * @param scaleStop * @param scaleDelta * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * * @return */ public TransformationPointFit calculateTransformationWithGridSearch( PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, int rotStart, int rotStop, int rotDelta, int scaleStart, int scaleStop, int scaleDelta, float setsFractionOfImage) { if (rotStart < 0 || rotStart > 359) { throw new IllegalArgumentException( "rotStart must be between 0 and 359, inclusive"); } if (rotStop < 0 || rotStop > 359) { throw new IllegalArgumentException( "rotStop must be between 0 and 359, inclusive"); } if (rotDelta < 1) { throw new IllegalArgumentException( "rotDelta must be > 0"); } if (!(scaleStart > 0)) { throw new IllegalArgumentException("scaleStart must be > 0"); } if (!(scaleStop > 0)) { throw new IllegalArgumentException("scaleStop must be > 0"); } if (!(scaleDelta > 0)) { throw new IllegalArgumentException("scaleDelta must be > 0"); } float tolTransX = generalTolerance;//4.0f * image1CentroidX * 0.02f; float tolTransY = generalTolerance;//4.0f * image1CentroidY * 0.02f; if (tolTransX < minTolerance) { tolTransX = minTolerance; } if (tolTransY < minTolerance) { tolTransY = minTolerance; } // rewrite the rotation points into array because start is sometimes // higher number than stop in unit circle int[] rotation = MiscMath.writeDegreeIntervals(rotStart, rotStop, rotDelta); int nMaxMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); TransformationPointFit bestFit = null; List<TransformationPointFit> similarToBestFit = new ArrayList<TransformationPointFit>(); TransformationPointFit bestFitForScale = null; for (int scale = scaleStart; scale <= scaleStop; scale += scaleDelta) { for (int rot : rotation) { float rotationInRadians = (float)(rot*Math.PI/180.f); TransformationPointFit fit = calculateTranslationForUnmatched0( set1, set2, image1Width, image1Height, image2Width, image2Height, rotationInRadians, scale, setsFractionOfImage); TransformationPointFit[] reevalFits = new TransformationPointFit[2]; boolean[] fitIsBetter = new boolean[1]; reevaluateFitsForCommonTolerance(bestFit, fit, set1, set2, image1Width, image1Height, reevalFits, fitIsBetter); bestFit = reevalFits[0]; fit = reevalFits[1]; if (bestFit != null && fit != null) { log.fine(" rot compare \n **==> bestFit=" + bestFit.toString() + "\n fit=" + fit.toString()); } int areSimilar = fitsAreSimilarWithDiffParameters(bestFit, fit); //0==same fit; 1==similar fits; -1==different fits if (areSimilar == 0) { //no need to recheck for convergence or change bestFit continue; } else if (areSimilar == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit); } //TODO: temporary debugging: if (!fitIsBetter[0] && (bestFit != null)) { log.fine("**==> rot keeping bestFit=" + bestFit.toString()); } if (fitIsBetter[0]) { log.fine("**==> rot fit=" + fit.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit; int bestNMatches = bestFit.getNumberOfMatchedPoints(); double bestAvg = bestFit.getMeanDistFromModel(); double bestS = bestFit.getStDevFromMean(); float fracMatched = (float)bestNMatches/(float)nMaxMatchable; boolean converged = false; if ((bestAvg < 1) && (bestS < 1)) { if (fracMatched > 0.9) { converged = true; } } else if ((bestAvg < 0.5) && (bestS < 0.5)) { if (nMaxMatchable > 10 && bestNMatches > 10) { converged = true; } } if (converged) { log.fine("** converged"); similarToBestFit.add(0, bestFit); for (TransformationPointFit fit2 : similarToBestFit) { if (fit2.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot2 = fit2.getParameters().getRotationInRadians(); while (rot2 >= 2*Math.PI) { rot2 -= 2*Math.PI; } fit2.getParameters().setRotationInRadians(rot2); } fit2.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBest( similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } log.fine(" bestFit=" + bestFit.toString()); return bestFit; } else { if (bestFit.getNumberOfMatchedPoints() == 0) { continue; } /* TODO: this might be better to perform at the end of the method right before returning the best result */ int nIntervals = 3; TransformationPointFit fit2 = finerGridSearch( nIntervals, bestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage ); //0==same fit; 1==similar fits; -1==different fits int areSimilar2 = fitsAreSimilarWithDiffParameters(bestFit, fit2); if (areSimilar2 == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit2); } boolean fitIsBetter2 = fitIsBetter(bestFit, fit2); if (fitIsBetter2) { log.fine("***==> fit=" + fit2.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit2; } } } } if (fitIsBetter(bestFitForScale, bestFit)) { bestFitForScale = bestFit; } else { log.fine("previous scale solution was better, so end scale iter"); // revert to previous scale bestFit = bestFitForScale; //TODO: revisit this with tests // scale was probably smaller so return best solution break; } } similarToBestFit.add(0, bestFit); for (TransformationPointFit fit : similarToBestFit) { if (fit.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot = fit.getParameters().getRotationInRadians(); while (rot >= 2*Math.PI) { rot -= 2*Math.PI; } fit.getParameters().setRotationInRadians(rot); } fit.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBest(similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } if (bestFit != null) { bestFit.setMaximumNumberMatchable(nMaxMatchable); log.fine(" bestFit=" + bestFit.toString()); } return bestFit; } /** * Calculate for matched points the Euclidean transformation to transform * set1 into the reference frame of set2. * @param set1 * @param set2 * @param image1Width * @param image1Height * @param image2Width * @param rotStart start of rotation search in degrees * @param rotStop stop (exclusive) or rotations search in degrees * @param image2Height * @param rotDelta change in rotation to add to reach next step in rotation * search in degrees * @param scaleStart * @param scaleStop * @param scaleDelta * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * * @return */ public TransformationPointFit calculateTransformationWithGridSearchForMatched( PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, int rotStart, int rotStop, int rotDelta, int scaleStart, int scaleStop, int scaleDelta, float setsFractionOfImage) { if (rotStart < 0 || rotStart > 359) { throw new IllegalArgumentException( "rotStart must be between 0 and 359, inclusive"); } if (rotStop < 0 || rotStop > 359) { throw new IllegalArgumentException( "rotStop must be between 0 and 359, inclusive"); } if (rotDelta < 1) { throw new IllegalArgumentException( "rotDelta must be > 0"); } if (!(scaleStart > 0)) { throw new IllegalArgumentException("scaleStart must be > 0"); } if (!(scaleStop > 0)) { throw new IllegalArgumentException("scaleStop must be > 0"); } if (!(scaleDelta > 0)) { throw new IllegalArgumentException("scaleDelta must be > 0"); } // rewrite the rotation points into array because start is sometimes // higher number than stop in unit circle int[] rotation = MiscMath.writeDegreeIntervals(rotStart, rotStop, rotDelta); Transformer transformer = new Transformer(); int nMaxMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); TransformationPointFit bestFit = null; List<TransformationPointFit> similarToBestFit = new ArrayList<TransformationPointFit>(); TransformationPointFit bestFitForScale = null; for (int scale = scaleStart; scale <= scaleStop; scale += scaleDelta) { for (int rot : rotation) { float rotationInRadians = (float)(rot*Math.PI/180.f); TransformationParameters params = calculateTranslationForMatched(set1, set2, rotationInRadians, scale, image1Width, image1Height, image2Width, image2Height); int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray allPoints1Tr = transformer.applyTransformation( params, image1CentroidX, image1CentroidY, set1); TransformationPointFit fit = evaluateFitForMatchedTransformed( params, allPoints1Tr, set2); //0==same fit; 1==similar fits; -1==different fits int areSimilar = fitsAreSimilarWithDiffParameters(bestFit, fit); if (areSimilar == 0) { //no need to recheck for convergence or change bestFit continue; } else if (areSimilar == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit); } boolean fitIsBetter = fitIsBetter(bestFit, fit); if (fitIsBetter) { log.fine("**==> fit=" + fit.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit; int bestNMatches = bestFit.getNumberOfMatchedPoints(); double bestAvg = bestFit.getMeanDistFromModel(); double bestS = bestFit.getStDevFromMean(); float fracMatched = (float)bestNMatches/(float)nMaxMatchable; boolean converged = false; if ((bestAvg < 1) && (bestS < 1)) { if (fracMatched > 0.9) { converged = true; } } else if ((bestAvg < 0.5) && (bestS < 0.5)) { if (nMaxMatchable > 10 && bestNMatches > 10) { converged = true; } } if (converged) { log.fine("** converged"); similarToBestFit.add(0, bestFit); for (TransformationPointFit fit2 : similarToBestFit) { if (fit2.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot2 = fit2.getParameters().getRotationInRadians(); while (rot2 >= 2*Math.PI) { rot2 -= 2*Math.PI; } fit2.getParameters().setRotationInRadians(rot2); } fit2.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBestForMatched( similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } log.fine(" bestFit=" + bestFit.toString()); return bestFit; } else { if (bestFit.getNumberOfMatchedPoints() == 0) { continue; } /* TODO: this might be better to perform at the end of the method right before returning the best result */ int nIntervals = 3; TransformationPointFit fit2 = finerGridSearchForMatched( nIntervals, bestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage ); //0==same fit; 1==similar fits; -1==different fits int areSimilar2 = fitsAreSimilarWithDiffParameters(bestFit, fit2); if (areSimilar2 == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit2); } boolean fitIsBetter2 = fitIsBetter(bestFit, fit2); if (fitIsBetter2) { log.fine("***==> fit=" + fit2.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit2; } } } } if (fitIsBetter(bestFitForScale, bestFit)) { bestFitForScale = bestFit; } else { log.fine("previous scale solution was better, so end scale iter"); // revert to previous scale bestFit = bestFitForScale; //TODO: revisit this with tests // scale was probably smaller so return best solution break; } } similarToBestFit.add(0, bestFit); for (TransformationPointFit fit : similarToBestFit) { if (fit.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot = fit.getParameters().getRotationInRadians(); while (rot >= 2*Math.PI) { rot -= 2*Math.PI; } fit.getParameters().setRotationInRadians(rot); } fit.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBestForMatched(similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } if (bestFit != null) { bestFit.setMaximumNumberMatchable(nMaxMatchable); log.fine(" bestFit=" + bestFit.toString()); } return bestFit; } /** * Calculate for unmatched points the Euclidean transformation to transform * set1 into the reference frame of set2. Note, this method does a grid * search over rotation and scale in the given intervals, and for each * translation solution within those, it uses an O(N^2) algorithm to find * the best translation in x and y. * If there are solutions with similar fits and different parameters, they * are retained and compared with finer grid searches to decide among * them so the total runtime complexity is * larger than O(N^2) but smaller than O(N^3). * The constant factors in the runtime are roughly * ((scaleStop - scaleStart)/scaleDelta) * times (number of rotation intervals) * times (number of grid search cells which is 10*10 at best). * * @param set1 * @param set2 * @param image1Width * @param image1Height * @param image2Width * @param rotStart start of rotation search in degrees * @param rotStop stop (exclusive) or rotations search in degrees * @param image2Height * @param rotDelta change in rotation to add to reach next step in rotation * search in degrees * @param scaleStart * @param scaleStop * @param scaleDelta * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * * @return */ public TransformationPointFit calculateTransformationWithGridSearch( PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, int rotStart, int rotStop, int rotDelta, int scaleStart, int scaleStop, int scaleDelta, int transXStart, int transXStop, int transYStart, int transYStop, int nTransIntervals, float tolTransX, float tolTransY, float setsFractionOfImage) { if (rotStart < 0 || rotStart > 359) { throw new IllegalArgumentException( "rotStart must be between 0 and 359, inclusive"); } if (rotStop < 0 || rotStop > 359) { throw new IllegalArgumentException( "rotStop must be between 0 and 359, inclusive"); } if (rotDelta < 1) { throw new IllegalArgumentException( "rotDelta must be > 0"); } if (!(scaleStart > 0)) { throw new IllegalArgumentException("scaleStart must be > 0"); } if (!(scaleStop > 0)) { throw new IllegalArgumentException("scaleStop must be > 0"); } if (!(scaleDelta > 0)) { throw new IllegalArgumentException("scaleDelta must be > 0"); } // rewrite the rotation points into array because start is sometimes // higher number than stop in unit circle int[] rotation = MiscMath.writeDegreeIntervals(rotStart, rotStop, rotDelta); boolean setsAreMatched = false; Transformer transformer = new Transformer(); int nMaxMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); TransformationPointFit bestFit = null; List<TransformationPointFit> similarToBestFit = new ArrayList<TransformationPointFit>(); TransformationPointFit bestFitForScale = null; for (int scale = scaleStart; scale <= scaleStop; scale += scaleDelta) { for (int rot : rotation) { float rotationInRadians = (float)(rot*Math.PI/180.f); TransformationPointFit fit = calculateTranslationForUnmatched0( set1, set2, image1Width, image1Height, image2Width, image2Height, rotationInRadians, scale, transXStart, transXStop, transYStart, transYStop, nTransIntervals, tolTransX, tolTransY, setsFractionOfImage); //0==same fit; 1==similar fits; -1==different fits int areSimilar = fitsAreSimilarWithDiffParameters(bestFit, fit); if (areSimilar == 0) { //no need to recheck for convergence or change bestFit continue; } else if (areSimilar == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit); } boolean fitIsBetter = fitIsBetter(bestFit, fit); if (fitIsBetter) { log.fine("**==> fit=" + fit.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit; int bestNMatches = bestFit.getNumberOfMatchedPoints(); double bestAvg = bestFit.getMeanDistFromModel(); double bestS = bestFit.getStDevFromMean(); float fracMatched = (float)bestNMatches/(float)nMaxMatchable; boolean converged = false; if ((bestAvg < 1) && (bestS < 1)) { if (fracMatched > 0.9) { converged = true; } } else if ((bestAvg < 0.5) && (bestS < 0.5)) { if (nMaxMatchable > 10 && bestNMatches > 10) { converged = true; } } if (converged) { log.fine("** converged"); similarToBestFit.add(0, bestFit); for (TransformationPointFit fit2 : similarToBestFit) { if (fit2.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot2 = fit2.getParameters().getRotationInRadians(); while (rot2 >= 2*Math.PI) { rot2 -= 2*Math.PI; } fit2.getParameters().setRotationInRadians(rot2); } fit2.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBest( similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } log.fine(" bestFit=" + bestFit.toString()); return bestFit; } else { if (bestFit.getNumberOfMatchedPoints() == 0) { continue; } /* TODO: this might be better to perform at the end of the method right before returning the best result */ int nIntervals = 3; TransformationPointFit fit2 = finerGridSearch( nIntervals, bestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage ); //0==same fit; 1==similar fits; -1==different fits int areSimilar2 = fitsAreSimilarWithDiffParameters(bestFit, fit2); if (areSimilar2 == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit2); } boolean fitIsBetter2 = fitIsBetter(bestFit, fit2); if (fitIsBetter2) { log.fine("***==> fit=" + fit2.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit2; } } } } if (fitIsBetter(bestFitForScale, bestFit)) { bestFitForScale = bestFit; log.fine(" ==> bestFitForScale=" + bestFitForScale.toString()); } else { log.fine("previous scale solution was better, so end scale iter"); // revert to previous scale bestFit = bestFitForScale; //TODO: revisit this with tests // scale was probably smaller so return best solution break; } } similarToBestFit.add(0, bestFit); for (TransformationPointFit fit : similarToBestFit) { if (fit.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot = fit.getParameters().getRotationInRadians(); while (rot >= 2*Math.PI) { rot -= 2*Math.PI; } fit.getParameters().setRotationInRadians(rot); } fit.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBest(similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } if (bestFit != null) { bestFit.setMaximumNumberMatchable(nMaxMatchable); log.fine(" bestFit=" + bestFit.toString()); } return bestFit; } protected TransformationPointFit[] evaluateTranslationsOverGrid( PairIntArray set1, PairIntArray set2, final int image1Width, final int image1Height, final int image2Width, final int image2Height, final float rotationInRadians, final float scale, int transXStart, int transXStop, int transXDelta, int transYStart, int transYStop, int transYDelta, float tolTransX, float tolTransY, final boolean setsAreMatched, final float setsFractionOfImage, final int numberOfBestToReturn) { /* _____ | | |_____| largest negative or positive translationX of set1 is the width of set2 _____ | | |_____| */ if (transXDelta < 1) { throw new IllegalArgumentException( "transXDelta must be greater than 0"); } if (rotationInRadians < 0 || rotationInRadians > 359) { throw new IllegalArgumentException( "rotation must be between 0 and 359, inclusive"); } if (scale < 1) { // numerical errors in rounding to integer can give wrong solutions //throw new IllegalStateException("scale cannot be smaller than 1"); log.severe("scale cannot be smaller than 1"); return null; } int nMaxMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); if (nMaxMatchable == 0) { return null; } int nTranslations = (((transXStop - transXStart)/transXDelta) + 1) * (((transYStop - transYStart)/transYDelta) + 1); if (nTranslations == 0) { return null; } Transformer transformer = new Transformer(); int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; int count = 0; TransformationPointFit[] fits = new TransformationPointFit[nTranslations]; for (float transX = transXStart; transX <= transXStop; transX += transXDelta) { for (float transY = transYStart; transY <= transYStop; transY += transYDelta) { float tx0 = transX + (transXDelta/2); float ty0 = transY + (transYDelta/2); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationInRadians); params.setScale(scale); params.setTranslationX(tx0); params.setTranslationY(ty0); PairFloatArray allPoints1Tr = transformer.applyTransformation( params, image1CentroidX, image1CentroidY, set1); TransformationPointFit fit; if (setsAreMatched) { fit = evaluateFitForMatchedTransformed(params, allPoints1Tr, set2); } else { // default is to use greedy matching but use optimal for small sets if (nMaxMatchable <= 10) { fit = evaluateFitForUnMatchedTransformedOptimal(params, allPoints1Tr, set2, tolTransX, tolTransY); } else { fit = evaluateFitForUnMatchedTransformedGreedy(params, //fit = evaluateFitForUnMatchedTransformedOptimal(params, allPoints1Tr, set2, tolTransX, tolTransY); } } fits[count] = fit; count++; } } // sort the fits sortByDescendingMatches(fits, 0, (fits.length - 1)); fits = Arrays.copyOf(fits, numberOfBestToReturn); return fits; } /** * given the scale, rotation and set 1's reference frame centroids, * calculate the translation between set1 and set2 assuming that not all * points will match. transXTol and transYTol allow a tolerance when * matching the predicted position of a point in set2. * * It's expected that the invoker of this method is trying to solve for * translation for sets of points like corners in images. This assumption * means that the number of point pair combinations is always far less * than the pixel combinations of translations over x and y. * * NOTE: scale has be >= 1, so if one image has a smaller scale, it has to * be the first set given in arguments. * * This method is in progress... * * @param set1 set of points from image 1 to match to image2. * @param set2 set of points from image 2 to be matched with image 1 * @param rotationInRadians given in radians with value between 0 and 2*pi, * exclusive * @param scale * @param image1Width width of image 1, used to derive range of x * translations in case centroidX1 is ever used as a non-center reference. * @param image1Height height of image 1, used to derive range of y * translations in case centroidY1 is ever used as a non-center reference. * @param image2Width width of image 2, used to derive range of x * translations * @param image2Height height of image 2, used to derive range of y * translations * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * @return */ public TransformationPointFit calculateTranslationForUnmatched0( PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float rotationInRadians, float scale, float setsFractionOfImage) { if (set1 == null) { throw new IllegalArgumentException("set1 cannot be null"); } if (set2 == null) { throw new IllegalArgumentException("set2 cannot be null"); } if (set1.getN() < 2) { return null; } if (set2.getN() < 2) { return null; } if (scale < 1) { // numerical errors in rounding to integer can give wrong solutions //throw new IllegalStateException("scale cannot be smaller than 1"); log.severe("scale cannot be smaller than 1"); return null; } int bestTransXStart = -1*image2Width + 1; int bestTransXStop = image2Width - 1; int bestTransYStart = -1*image2Width + 1; int bestTransYStop = image2Width - 1; // TODO: consider using point density to estimate this int nIntervals = 11; int dx = (bestTransXStop - bestTransXStart)/nIntervals; int dy = (bestTransYStop - bestTransYStart)/nIntervals; /*TODO: The comparisons seem to need same tolerance used when comparing the fits, so no longer decreasing these upon decreased cell size or smaller mean distance from model. If need to change this back to a tolerance that does decrease with grid cell size, then would need to add a step to the comparisons of bestFit and fit where this method is used. An extra step would be needed to re-do the evalation of whichever had a larger tolerance in it's fit using the lower tolerance. Then the comparison would be correct at that level and finer here where needed. */ float tolTransX = (int)(0.5*dx/toleranceGridFactor); float tolTransY = (int)(0.5*dy/toleranceGridFactor); /*when tolerance is too high, mean dist from model becomes more important than the number of matches*/ TransformationPointFit fit = calculateTranslationForUnmatched0( set1, set2, image1Width, image1Height, image2Width, image2Height, rotationInRadians, scale, bestTransXStart, bestTransXStop, bestTransYStart, bestTransYStop, nIntervals, tolTransX, tolTransY, setsFractionOfImage); return fit; } /** * given the scale, rotation and set 1's reference frame centroids, * calculate the translation between set1 and set2 assuming that not all * points will match. transXTol and transYTol allow a tolerance when * matching the predicted position of a point in set2. * * It's expected that the invoker of this method is trying to solve for * translation for sets of points like corners in images. This assumption * means that the number of point pair combinations is always far less * than the pixel combinations of translations over x and y. * * NOTE: scale has be >= 1, so if one image has a smaller scale, it has to * be the first set given in arguments. * * This method is in progress... * * @param set1 set of points from image 1 to match to image2. * @param set2 set of points from image 2 to be matched with image 1 * @param rotationInRadians given in radians with value between 0 and 2*pi, * exclusive * @param scale * @param transXStart * @param transXStop * @param image1Width width of image 1, used to derive range of x * translations in case centroidX1 is ever used as a non-center reference. * @param transYStop * @param transYStart * @param nTransIntervals * @param image1Height height of image 1, used to derive range of y * translations in case centroidY1 is ever used as a non-center reference. * @param image2Width width of image 2, used to derive range of x * translations * @param image2Height height of image 2, used to derive range of y * translations * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * @return */ public TransformationPointFit calculateTranslationForUnmatched0( PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float rotationInRadians, float scale, int transXStart, int transXStop, int transYStart, int transYStop, int nTransIntervals, float tolTransX, float tolTransY, float setsFractionOfImage) { if (set1 == null) { throw new IllegalArgumentException("set1 cannot be null"); } if (set2 == null) { throw new IllegalArgumentException("set2 cannot be null"); } if (set1.getN() < 2) { return null; } if (set2.getN() < 2) { return null; } int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray scaledRotatedSet1 = scaleAndRotate(set1, rotationInRadians, scale, image1CentroidX, image1CentroidY); if (scale < 1) { // numerical errors in rounding to integer can give wrong solutions //throw new IllegalStateException("scale cannot be smaller than 1"); log.severe("scale cannot be smaller than 1"); return null; } int maxNMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); TransformationPointFit bestFit = null; int bestTransXStart = transXStart; int bestTransXStop = transXStop; int bestTransYStart = transYStart; int bestTransYStop = transYStop; int nIntervals = nTransIntervals; int dx = (bestTransXStop - bestTransXStart)/nIntervals; int dy = (bestTransYStop - bestTransYStart)/nIntervals; float cellFactor = 1.25f; int limit = 1; boolean setsAreMatched = false; int nIter = 0; while ((dx > limit) && (dy > limit)) { if (nIter > 0) { tolTransX = dx; tolTransY = dy; } if (bestFit == null) { if (Math.abs(rotationInRadians - 0.34906584) < 0.1) { if (set1.getN()==36 && set2.getN()==34) { int z = 1; } } } TransformationPointFit fit = calculateTranslationFromGridThenDownhillSimplex( scaledRotatedSet1, set1, set2, image1Width, image1Height, image2Width, image2Height, rotationInRadians, scale, bestTransXStart, bestTransXStop, dx, bestTransYStart, bestTransYStop, dy, tolTransX, tolTransY, setsAreMatched, setsFractionOfImage); if (bestFit != null && fit != null) { log.fine(" * compare \n ==> bestFit=" + bestFit.toString() + "\n fit=" + fit.toString()); } boolean fitIsBetter = fitIsBetter(bestFit, fit); if (!fitIsBetter && (bestFit != null)) { log.fine(" * keeping bestFit=" + bestFit.toString()); } if (fitIsBetter) { if (bestFit == null) { log.fine(" *==> new cycle fit=" + fit.toString()); } else { log.fine(" *==> fit=" + fit.toString()); } bestFit = fit; float transX = bestFit.getParameters().getTranslationX(); float transY = bestFit.getParameters().getTranslationY(); log.fine(String.format(" previous X translation range %d:%d", bestTransXStart, bestTransXStop)); log.fine(String.format(" previous Y translation range %d:%d", bestTransYStart, bestTransYStop)); log.fine(String.format(" previous cell size dx=%d dy=%d", dx, dy)); bestTransXStart = (int)(transX - cellFactor*dx); bestTransXStop = (int)(transX + cellFactor*dx); bestTransYStart = (int)(transY - cellFactor*dy); bestTransYStop = (int)(transY + cellFactor*dy); dx = (bestTransXStop - bestTransXStart)/nIntervals; dy = (bestTransYStop - bestTransYStart)/nIntervals; log.fine(String.format(" next X translation range %d:%d", bestTransXStart, bestTransXStop)); log.fine(String.format(" next Y translation range %d:%d", bestTransYStart, bestTransYStop)); log.fine(String.format(" next cell size dx=%d dy=%d", dx, dy)); } else { log.fine(" end scale, rot iteration"); /* TODO: when the nelder-mead didn't produce a better result, we arrive here and may need to do a grid search over the final result using a search range of the final transX and transY plus and minus the last dx,dy (or the half of those if tests pass). */ break; } nIter++; } if (bestFit != null) { bestFit.setMaximumNumberMatchable(maxNMatchable); } if (bestFit != null) { log.fine(" * returning bestFit=" + bestFit.toString()); if (bestFit.getNumberOfMatchedPoints() == 35) { if (Math.abs(bestFit.getMeanDistFromModel() - 3.0) < 0.01) { if (Math.abs(bestFit.getStDevFromMean() - 0.0) < 0.01) { if (Math.abs(bestFit.getParameters().getRotationInDegrees() - 18) < 0.01) { int z = 1; } } } } } return bestFit; } private TransformationPointFit calculateTranslationFromGridThenDownhillSimplex( PairFloatArray scaledRotatedSet1, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float rotationInRadians, float scale, int transXStart, int transXStop, int transXDelta, int transYStart, int transYStop, int transYDelta, float tolTransX, float tolTransY, boolean setsAreMatched, float setsFractionOfImage) { if (scaledRotatedSet1 == null) { throw new IllegalArgumentException("scaledRotatedSet1 cannot be null"); } if (set1 == null) { throw new IllegalArgumentException("set1 cannot be null"); } if (set2 == null) { throw new IllegalArgumentException("set2 cannot be null"); } if (scaledRotatedSet1.getN() != set1.getN()) { throw new IllegalArgumentException( "scaledRotatedSet1 has to be the same length as set1"); } if (tolTransX < 1) { throw new IllegalArgumentException("tolTransX should be > 0"); } if (tolTransY < 1) { throw new IllegalArgumentException("tolTransY should be > 0"); } if (transXDelta == 0) { throw new IllegalArgumentException("transXDelta cannot be 0"); } if (transYDelta == 0) { throw new IllegalArgumentException("transYDelta cannot be 0"); } int numberOfBestToReturn = 10; int dsLimit = (transXStop - transXStart) / transXDelta; int maxNMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); TransformationPointFit[] fits = evaluateTranslationsOverGrid( set1, set2, image1Width, image1Height, image2Width, image2Height, rotationInRadians, scale, transXStart, transXStop, transXDelta, transYStart, transYStop, transYDelta, tolTransX, tolTransY, setsAreMatched, setsFractionOfImage, numberOfBestToReturn); if (fits == null) { return null; } /* if the first 4 or so top fits all have nMatchedPoints=1 or 0, then don't use the downhill simplex. */ boolean tooFewMatches = true; for (int i = 0; i < 4; ++i) { TransformationPointFit fit = fits[i]; if (fit != null && fit.getNumberOfMatchedPoints() > 1) { tooFewMatches = false; break; } } if (tooFewMatches) { return fits[0]; } TransformationPointFit fit; if (transXDelta < dsLimit) { fit = fits[0]; } else { int nMaxIter = 50; if (maxNMatchable > 60) { nMaxIter = 150; } else if (maxNMatchable > 30) { nMaxIter = 100; } // the bounds are to keep the solution within the current // best range /*float boundsXHalf = (transXStop - transXStart) / 2; float boundsYHalf = (transYStop - transYStart) / 2; float boundsXCenter = (transXStart + transXStop) / 2; float boundsYCenter = (transYStart + transYStop) / 2;*/ /* the top fits solution define the region to search within further. */ //{translationXMin, translationXMax, translationYMin, translationYMax} float[] transXYMinMaxes = getTranslationMinAndMaxes(fits); float x0 = transXYMinMaxes[0] - tolTransX; //float x1 = transXYMinMaxes[1] + tolTransX; float y0 = transXYMinMaxes[2] - tolTransY; //float y1 = transXYMinMaxes[3] + tolTransY; float boundsXCenter = (transXYMinMaxes[0] + transXYMinMaxes[1])/2.f; float boundsYCenter = (transXYMinMaxes[2] + transXYMinMaxes[3])/2.f; float boundsXHalf = x0 - boundsXCenter; float boundsYHalf = y0 - boundsYCenter; fit = refineTranslationWithDownhillSimplex( scaledRotatedSet1, set2, fits, boundsXCenter, boundsYCenter, tolTransX, tolTransY, boundsXHalf, boundsYHalf, scale, rotationInRadians, setsAreMatched, nMaxIter); } if (fit != null) { fit.setMaximumNumberMatchable(maxNMatchable); } return fit; } /** * given the scale, rotation and set 1's reference frame centroids, * calculate the translation between set1 and set2 assuming that not all * points will match. transXTol and transYTol allow a tolerance when * matching the predicted position of a point in set2. * Note that the reference point for the rotation is the center of the * image 1 width and height. * * It's expected that the invoker of this method is trying to solve for * translation for sets of points like corners in images. This assumption * means that the number of point pair combinations is always far less * than the pixel combinations of translations over x and y. * * NOTE: scale has be >= 1, so if one image has a smaller scale, it has to * be the first set given in arguments. * * ALSO NOTE: if you know a better solution exists for translation * parameters that matches fewer points, but has a small avg dist from * model and smaller standard deviation from the avg dist from model, * then transXTol and transYTol should be set to a smaller value and passed * to this method. * * @param matched1 set of points from image 1 to match to image2. * @param matched2 set of points from image 2 to be matched with image 1 * @param rotationInRadians given in radians with value between 0 and 2*pi, exclusive * @param scale * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @return */ public TransformationParameters calculateTranslationForMatched( PairIntArray matched1, PairIntArray matched2, float rotationInRadians, float scale, int image1Width, int image1Height, int image2Width, int image2Height) { if (scale < 1) { // numerical errors in rounding to integer can give wrong solutions //throw new IllegalStateException("scale cannot be smaller than 1"); log.severe("scale cannot be smaller than 1"); return null; } int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; double scaleTimesCosine = scale * Math.cos(rotationInRadians); double scaleTimesSine = scale * Math.sin(rotationInRadians); double avgTransX = 0; double avgTransY = 0; for (int i = 0; i < matched1.getN(); i++) { int x = matched1.getX(i); int y = matched1.getY(i); double xr = image1CentroidX*scale + ( ((x - image1CentroidX) * scaleTimesCosine) + ((y - image1CentroidY) * scaleTimesSine)); double yr = image1CentroidY*scale + ( (-(x - image1CentroidX) * scaleTimesSine) + ((y - image1CentroidY) * scaleTimesCosine)); int x2 = matched2.getX(i); int y2 = matched2.getY(i); avgTransX += (int)Math.round(x2 - xr); avgTransY += (int)Math.round(y2 - yr); } avgTransX /= (float)matched1.getN(); avgTransY /= (float)matched1.getN(); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationInRadians); params.setScale(scale); params.setTranslationX((float)avgTransX); params.setTranslationY((float)avgTransY); return params; } protected boolean fitIsSimilar(TransformationPointFit fit1, TransformationPointFit fit2, float scaleTolerance, float rotInDegreesTolerance, float translationTolerance) { if (fit1 == null || fit2 == null) { return false; } TransformationParameters params1 = fit1.getParameters(); TransformationParameters params2 = fit2.getParameters(); float rotA = params1.getRotationInDegrees(); float rotB = params2.getRotationInDegrees(); if (rotA > rotB) { float swap = rotA; rotA = rotB; rotB = swap; } if (((rotB - rotA) > rotInDegreesTolerance) && (((rotA + 360) - rotB) > rotInDegreesTolerance)) { return false; } if ((Math.abs(params1.getScale() - params2.getScale()) <= scaleTolerance) && (Math.abs(params1.getTranslationX() - params2.getTranslationX()) <= translationTolerance) && (Math.abs(params1.getTranslationY() - params2.getTranslationY()) <= translationTolerance) ) { return true; } return false; } /** * given the transformed x y that have already been scaled and rotated, add the * transX and transY, respectively and calculated the average residual * between that and set2 and the standard deviation from the average. * Note that set2 and (scaledRotatedX, scaledRotatedY) are NOT known to be * matched points so the residuals are minimized for each point in * the model to find the matching in set2 before computing the * average and standard deviation. * * @param set2 * @param scaledRotatedSet1 the model xy points scaled and rotated * @param transX the x translation to apply to the model points * @param transY the y translation to apply to the model points * @return */ protected TransformationPointFit evaluateFitForUnMatchedGreedy( PairFloatArray scaledRotatedSet1, float transX, float transY, float tolTransX, float tolTransY, PairIntArray set2, final float scale, final float rotationRadians) { if (set2 == null) { throw new IllegalArgumentException( "set2 cannot be null"); } if (scaledRotatedSet1 == null) { throw new IllegalArgumentException( "scaledRotatedSet1 cannot be null"); } int nMaxMatchable = (scaledRotatedSet1.getN() < set2.getN()) ? scaledRotatedSet1.getN() : set2.getN(); Set<Integer> chosen = new HashSet<Integer>(); double[] diffs = new double[scaledRotatedSet1.getN()]; int nMatched = 0; double avg = 0; for (int i = 0; i < scaledRotatedSet1.getN(); i++) { float transformedX = scaledRotatedSet1.getX(i) + transX; float transformedY = scaledRotatedSet1.getY(i) + transY; double minDiff = Double.MAX_VALUE; int min2Idx = -1; for (int j = 0; j < set2.getN(); j++) { if (chosen.contains(Integer.valueOf(j))) { continue; } float dx = set2.getX(j) - transformedX; float dy = set2.getY(j) - transformedY; if ((Math.abs(dx) > tolTransX) || (Math.abs(dy) > tolTransY)) { continue; } float diff = (float)Math.sqrt(dx*dx + dy*dy); if (diff < minDiff) { minDiff = diff; min2Idx = j; } } if (minDiff < Double.MAX_VALUE) { diffs[nMatched] = minDiff; nMatched++; chosen.add(Integer.valueOf(min2Idx)); avg += minDiff; } } avg = (nMatched == 0) ? Double.MAX_VALUE : avg / (double)nMatched; double stDev = 0; for (int i = 0; i < nMatched; i++) { double d = diffs[i] - avg; stDev += (d * d); } stDev = (nMatched == 0) ? Double.MAX_VALUE : Math.sqrt(stDev/((double)nMatched - 1.)); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationRadians); params.setScale(scale); params.setTranslationX(transX); params.setTranslationY(transY); TransformationPointFit fit = new TransformationPointFit(params, nMatched, avg, stDev, tolTransX, tolTransY); fit.setMaximumNumberMatchable(nMaxMatchable); return fit; } public boolean fitIsBetter(TransformationPointFit bestFit, TransformationPointFit compareFit) { if (costIsNumAndDiff) { return fitIsBetterUseNumAndDiff(bestFit, compareFit); } if (compareFit == null) { return false; } if (bestFit == null) { return true; } int compNMatches = compareFit.getNumberOfMatchedPoints(); int bestNMatches = bestFit.getNumberOfMatchedPoints(); double compAvg = compareFit.getMeanDistFromModel(); double bestAvg = bestFit.getMeanDistFromModel(); double compS = compareFit.getStDevFromMean(); double bestS = bestFit.getStDevFromMean(); double r = bestAvg/compAvg; int diffEps = (int)Math.round(2.*Math.ceil(Math.max(bestNMatches, compNMatches)/10.)); if (diffEps == 0) { diffEps = 1; } //0==same fit; 1==similar fits; -1==different fits int areSimilar = fitsAreSimilarWithDiffParameters(bestFit, compareFit); if ((areSimilar != -1) && (Math.abs(bestNMatches - compNMatches) <= diffEps)) { // if compareFit tolerance is alot larger than bestFit, this would // not be a fair comparison, so check before returning true if ((compareFit.getTranslationXTolerance() < bestFit.getTranslationXTolerance()) &&(compareFit.getTranslationYTolerance() < bestFit.getTranslationYTolerance()) ) { return true; } } if ( (compNMatches >= 3) && (bestNMatches >= 3) && (compNMatches <= 10) && (bestNMatches <= 10) && (Math.abs(bestNMatches - compNMatches) < 2)) { if (r > 1.4) { return true; } else if (r < 0.7) { return false; } } else if ((compNMatches > 5) && (bestNMatches > 5) && (Math.abs(bestNMatches - compNMatches) <= diffEps)) { //TODO: may need to revise this if (r > 2) { return true; } else if (r < 0.5) { return false; } } else if ( (compNMatches >= 3) && (bestNMatches >= 3) && (compNMatches <= 10) && (bestNMatches <= 10) && (Math.abs(bestNMatches - compNMatches) < 3)) { if (r > 10) { return true; } else if (r < 0.1) { return false; } } else if ( (Math.abs(bestNMatches - compNMatches) < 4) && (bestNMatches >= 7) && (bestNMatches <= 15) && (compNMatches >= 7) && (compNMatches <= 15)) { if (r > 10) { return true; } else if (r < 0.1) { return false; } } if (compNMatches > bestNMatches) { return true; } else if (compNMatches == bestNMatches) { if (!Double.isNaN(compareFit.getMeanDistFromModel())) { //TODO: may need to revise this: if (Math.abs(compAvg - bestAvg) < 1.0) { if (compS < bestS) { return true; } else if (compS > bestS) { return false; } } if (compAvg < bestAvg) { return true; } else if (compAvg > bestAvg) { return false; } if (compS < bestS) { return true; } else if (compS > bestS) { return false; } } } /* TODO: altering the above so that close values in number matched, but large differences in mean dist from model will use mean diff from model for example: bestFit: nMatchedPoints=15 nMaxMatchable=15.0 meanDistFromModel=84.14178034464518 stDevFromMean=56.981437125683364 tolerance=288.4995667241114 rotationInRadians=0.05235988 rotationInDegrees=3.0000000834826057 scale=1.0 translationX=-159.04364 translationY=-63.772995 fitCompare: nMatchedPoints=14 nMaxMatchable=0.0 meanDistFromModel=4.542982544217791 stDevFromMean=0.2876419359024278 tolerance=288.4995667241114 rotationInRadians=0.06981317 rotationInDegrees=3.999999969014533 scale=1.0 translationX=-209.35757 translationY=-11.052967 can see that the fitCompare should be preferred */ return false; } /** * compare bestFit to compareFit and return * -1 if bestFit is better * 0 if they are equal * 1 if compareFit is better * @param bestFit * @param compareFit * @return */ public int compare(TransformationPointFit bestFit, TransformationPointFit compareFit) { /* if (costIsNumAndDiff) { return fitIsBetterUseNumAndDiff(bestFit, compareFit); } */ if (compareFit == null && bestFit == null) { return 0; } else if (compareFit == null) { return -1; } else if (bestFit == null) { return 1; } int compNMatches = compareFit.getNumberOfMatchedPoints(); int bestNMatches = bestFit.getNumberOfMatchedPoints(); double compAvg = compareFit.getMeanDistFromModel(); double bestAvg = bestFit.getMeanDistFromModel(); double compS = compareFit.getStDevFromMean(); double bestS = bestFit.getStDevFromMean(); double r = bestAvg/compAvg; int diffEps = (int)Math.round(2.*Math.ceil(Math.max(bestNMatches, compNMatches)/10.)); if (diffEps == 0) { diffEps = 1; } int areSimilar = fitsAreSimilarWithDiffParameters(bestFit, compareFit); if ((areSimilar != -1) && (Math.abs(bestNMatches - compNMatches) <= diffEps)) { // if compareFit tolerance is alot larger than bestFit, this would // not be a fair comparison, so check before returning true if ((compareFit.getTranslationXTolerance() < bestFit.getTranslationXTolerance()) &&(compareFit.getTranslationYTolerance() < bestFit.getTranslationYTolerance()) ) { return 1; } } if ( (compNMatches >= 3) && (bestNMatches >= 3) && (compNMatches <= 10) && (bestNMatches <= 10) && (Math.abs(bestNMatches - compNMatches) < 2)) { if (r > 1.4) { return 1; } else if (r < 0.7) { return -1; } } else if ((compNMatches > 5) && (bestNMatches > 5) && (Math.abs(bestNMatches - compNMatches) <= diffEps)) { //TODO: may need to revise this if (r > 2) { return 1; } else if (r < 0.5) { return -1; } } else if ( (compNMatches >= 3) && (bestNMatches >= 3) && (compNMatches <= 10) && (bestNMatches <= 10) && (Math.abs(bestNMatches - compNMatches) < 3)) { if (r > 10) { return 1; } else if (r < 0.1) { return -1; } } else if ( (Math.abs(bestNMatches - compNMatches) < 4) && (bestNMatches >= 7) && (bestNMatches <= 15) && (compNMatches >= 7) && (compNMatches <= 15)) { if (r > 10) { return 1; } else if (r < 0.1) { return -1; } } if (compNMatches > bestNMatches) { return 1; } else if (compNMatches == bestNMatches) { if (!Double.isNaN(compareFit.getMeanDistFromModel())) { //TODO: may need to revise this: if (Math.abs(compAvg - bestAvg) < 1.0) { if (compS < bestS) { return 1; } else if (compS > bestS) { return -1; } } if (compAvg < bestAvg) { return 1; } else if (compAvg > bestAvg) { return -1; } if (compS < bestS) { return 1; } else if (compS > bestS) { return -1; } else { return 0; } } } return -1; } public boolean fitIsBetterUseNumAndDiff(TransformationPointFit bestFit, TransformationPointFit compareFit) { if (compareFit == null) { return false; } if (bestFit == null) { if (compareFit.getNumberOfMatchedPoints() > 0) { return true; } else { return false; } } float compN = compareFit.getNumberOfMatchedPoints(); float bestN = bestFit.getNumberOfMatchedPoints(); double compAvg = compareFit.getMeanDistFromModel(); double compS = compareFit.getStDevFromMean(); double compAvgS = compAvg + compS; double bestAvg = bestFit.getMeanDistFromModel(); double bestS = bestFit.getStDevFromMean(); double bestAvgS = bestAvg + bestS; float f = 1.5f; if (!Double.isNaN(compAvg)) { if ((compN/bestN) >= f) { return true; } else if ((compN >= bestN) && (compAvg < bestAvg) && (compS < bestS)) { return true; } } return false; } public boolean fitIsBetter(ProjectiveFit bestFit, ProjectiveFit compareFit) { if (compareFit == null) { return false; } if (bestFit == null) { return true; } int nMatches = compareFit.getNumberOfPoints(); if (nMatches > bestFit.getNumberOfPoints()) { return true; } else if (nMatches == bestFit.getNumberOfPoints()) { if (!Double.isNaN(compareFit.getMeanDistFromModel()) && ( compareFit.getMeanDistFromModel() < bestFit.getMeanDistFromModel())) { return true; } else if (compareFit.getMeanDistFromModel() == bestFit.getMeanDistFromModel()) { if (compareFit.getStdDevOfMean() < bestFit.getStdDevOfMean()) { return true; } } } return false; } /** * a fitness function that tries to allow a smaller number of points roughly * fit to be seen in contrast to a larger number of points that * are not a better fit, but have better stats due to matching alot of * scattered points. * if numberOfMatched/maxMatchable is not infinite: * if the mean/10 of the comparison fit is better than the best mean/10, * a true is returned, else * compares the standard * deviation from the mean difference to the model fit and returns true * if compareFit has a smaller value. * @param bestFit * @param compareFit * @return */ protected boolean fitIsBetter2(TransformationPointFit bestFit, TransformationPointFit compareFit) { if (compareFit == null) { return false; } if (bestFit == null) { return true; } float compareNStat = (float)compareFit.getNumberOfMatchedPoints()/ (float)compareFit.getNMaxMatchable(); if (Float.isInfinite(compareNStat)) { return false; } float bestNStat = (float)bestFit.getNumberOfMatchedPoints()/ (float)bestFit.getNMaxMatchable(); if (Float.isInfinite(bestNStat)) { return true; } if ((bestFit.getNumberOfMatchedPoints() == 0) && (compareFit.getNumberOfMatchedPoints() > 0)) { return true; } else if (compareFit.getNumberOfMatchedPoints() == 0) { return false; } double bestMean = bestFit.getMeanDistFromModel(); double compareMean = compareFit.getMeanDistFromModel(); int comp = Double.compare(compareMean, bestMean); if (comp < 0) { return true; } else if (comp > 0) { return false; } double bestStdDevMean = bestFit.getStDevFromMean(); double compareStdDevMean = compareFit.getStDevFromMean(); // a smaller std dev from mean is a better fit if (Double.compare(compareStdDevMean, bestStdDevMean) < 0) { return true; } else if (compareStdDevMean == bestStdDevMean) { return (Double.compare(compareMean, bestMean) < 0); } return false; } // ======= code that needs testing and revision the most /** * refine the transformation params to make a better match of edges1 to * edges2 where the points within edges in both sets are not necessarily * 1 to 1 matches (that is, the input is not expected to be matched * already). * * TODO: improve transformEdges to find translation for all edges * via a search method rather than trying all pairs of points. * * @param edges1 * @param edges2 * @param params * @param centroidX1 * @param centroidY1 * @param centroidX2 * @param centroidY2 * @return */ public TransformationParameters refineTransformation(PairIntArray[] edges1, PairIntArray[] edges2, final TransformationParameters params, final int centroidX1, final int centroidY1, final int centroidX2, final int centroidY2) { if (edges1 == null || edges1.length == 0) { throw new IllegalArgumentException("edges1 cannot be null or empty"); } if (edges2 == null || edges2.length == 0) { throw new IllegalArgumentException("edges2 cannot be null or empty"); } //TODO: set this empirically from tests double convergence = 0; double r = params.getRotationInRadians(); double s = params.getScale(); double rMin = r - (10 * Math.PI/180); double rMax = r + (10 * Math.PI/180); double sMin = s - 1.5; double sMax = s + 1.5; // the positive offsets can be found w/ reflection? // TODO: needs testing for starter points. these are supplying the // "grid search" portion of exploring more than local space double[] drs = new double[] { -5.0 * Math.PI/180., -2.5 * Math.PI/180., -1.0 * Math.PI/180., 1.0 * Math.PI/180., 2.5 * Math.PI/180., 5.0 * Math.PI/180. }; double[] dss = new double[] { -1.0, -0.1, -0.05, 0.05 /*, 0.05, 0.1, 1.0*/ }; if (r == 0) { drs = new double[]{0}; } if (s == 1) { dss = new double[]{0}; sMin = 1; } if (sMin < 1) { sMin = 1; } if (rMin < 0) { rMin = 0; } int n = (1 + dss.length) * (1 + drs.length); TransformationPointFit[] fits = new TransformationPointFit[n]; int count = 0; for (int i = 0; i <= dss.length; i++) { double scale = (i == 0) ? s : s + dss[i - 1]; for (int j = 0; j <= drs.length; j++) { double rotation = (j == 0) ? r : r + drs[j - 1]; fits[count] = calculateTranslationAndTransformEdges( rotation, scale, edges1, edges2, centroidX1, centroidY1); if (fits[count] != null) { count++; } } } if (count < n) { fits = Arrays.copyOf(fits, count); } float alpha = 1; // > 0 float gamma = 2; // > 1 float beta = 0.5f; float tau = 0.5f; boolean go = true; int nMaxIter = 100; int nIter = 0; int bestFitIdx = 0; int worstFitIdx = fits.length - 1; int lastNMatches = Integer.MIN_VALUE; double lastAvgDistModel = Double.MAX_VALUE; int nIterSameMin = 0; while (go && (nIter < nMaxIter)) { if (fits.length == 0) { break; } sortByDescendingMatches(fits, 0, (fits.length - 1)); for (int i = (fits.length - 1); i > -1; --i) { if (fits[i] != null) { worstFitIdx = i; break; } } if (fits[bestFitIdx] == null) { break; } /*if (fits.length > 0) { log.info("best fit: n=" + fits[bestFitIdx].getNumberOfMatchedPoints() + " dm=" + fits[bestFitIdx].getMeanDistFromModel() + " params:\n" + fits[bestFitIdx].getParameters().toString()); }*/ if ((lastNMatches == fits[bestFitIdx].getNumberOfMatchedPoints()) && (Math.abs(lastAvgDistModel - fits[bestFitIdx].getMeanDistFromModel()) < 0.01)) { nIterSameMin++; /*if (nIterSameMin >= 5) { break; }*/ } else { nIterSameMin = 0; } lastNMatches = fits[bestFitIdx].getNumberOfMatchedPoints(); lastAvgDistModel = fits[bestFitIdx].getMeanDistFromModel(); // determine center for all points excepting the worse fit double rSum = 0.0; double sSum = 0.0; int c = 0; for (int i = 0; i < (fits.length - 1); i++) { if (fits[i] != null) { rSum += fits[i].getRotationInRadians(); sSum += fits[i].getScale(); c++; } } r = rSum / (double)c; s = sSum / (double)c; // "Reflection" double rReflect = r + (alpha * (r - fits[worstFitIdx].getRotationInRadians())); double sReflect = s + (alpha * (s - fits[worstFitIdx].getScale())); TransformationPointFit fitReflected = calculateTranslationAndTransformEdges( rReflect, sReflect, edges1, edges2, centroidX1, centroidY1); //TODO: consider putting back in a check for bounds int comp0 = compare(fits[bestFitIdx], fitReflected); int compLast = compare(fits[worstFitIdx], fitReflected); if ((comp0 < 1) && (compLast == 1)) { // replace last with f_refl fits[worstFitIdx] = fitReflected; } else if (comp0 == 1) { // reflected is better than best fit, so "expand" // "Expansion" double rExpansion = r + (gamma * (rReflect - r)); double sExpansion = s + (gamma * (sReflect - s)); TransformationPointFit fitExpansion = calculateTranslationAndTransformEdges( rExpansion, sExpansion, edges1, edges2, centroidX1, centroidY1); int compR = compare(fitReflected, fitExpansion); if (compR == 1) { // expansion fit is better than reflected fit fits[worstFitIdx] = fitExpansion; } else { fits[worstFitIdx] = fitReflected; } } else if (compLast < 1) { // reflected fit is worse than the worst (last) fit, so contract // "Contraction" double rContraction = r + (beta * (fits[worstFitIdx].getRotationInRadians() - r)); double sContraction = s + (beta * (fits[worstFitIdx].getScale() - s)); TransformationPointFit fitContraction = calculateTranslationAndTransformEdges( rContraction, sContraction, edges1, edges2, centroidX1, centroidY1); int compC = compare(fits[worstFitIdx], fitContraction); if (compC > -1) { fits[worstFitIdx] = fitContraction; } else { // "Reduction" for (int i = 1; i < fits.length; ++i) { if (fits[i] == null) { /*TODO: consider setting this fits[i] = new TransformationPointFit( new TransformationParameters(), 0, Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE ); */ continue; } float rReduction = (fits[bestFitIdx].getRotationInRadians() + (tau * (fits[i].getRotationInRadians() - fits[bestFitIdx].getRotationInRadians()))); float sReduction = (fits[bestFitIdx].getScale() + (tau * (fits[i].getScale() - fits[bestFitIdx].getScale()))); //NOTE: there's a possibility of a null fit. // instead of re-writing the fits array, will // assign a fake infinitely bad fit which will // fall to the bottom of the list after the next // sort. TransformationPointFit fit = calculateTranslationAndTransformEdges( rReduction, sReduction, edges1, edges2, centroidX1, centroidY1); fits[i] = fit; } } } log.finest("best fit so far: nMatches=" + fits[bestFitIdx].getNumberOfMatchedPoints() + " diff from model=" + fits[bestFitIdx].getMeanDistFromModel() ); nIter++; if ((fits[bestFitIdx].getNumberOfMatchedPoints() == convergence) && (fits[bestFitIdx].getMeanDistFromModel() == 0)) { go = false; /*} else if ((r > rMax) || (r < rMin)) { go = false;*/ } else if ((s > sMax) || (s < sMin)) { go = false; } } // additional step that's helpful if not enough iterations are used, // is to test the summed transX, transY which represent the center // of the simplex against the best fit TransformationPointFit fitAvg = calculateTranslationAndTransformEdges( r, s, edges1, edges2, centroidX1, centroidY1); int comp = compare(fits[bestFitIdx], fitAvg); if (comp == 1) { fits[bestFitIdx] = fitAvg; } // if rotation > 2PI, subtract 2PI if ((fits[bestFitIdx] != null) && (fits[bestFitIdx].getParameters().getRotationInRadians() > 2.*Math.PI)) { float rot = fits[bestFitIdx].getParameters().getRotationInRadians(); while (rot >= 2*Math.PI) { rot -= 2*Math.PI; } fits[bestFitIdx].getParameters().setRotationInRadians(rot); } return fits[bestFitIdx].getParameters(); } /** * TODO: improve transformEdges to find translation for all edges * via a search method rather than trying all pairs of points. * * Given edges1 and edges2 which we already know are matched edges due to * contour matching or other means, and given the rotation and scale, * determine the translation between the edges and return the fit. * * @param rotInRad * @param scl * @param edges1 * @param edges2 * @param centroidX1 * @param centroidY1 * @return */ private TransformationPointFit calculateTranslationAndTransformEdges( double rotInRad, double scl, PairIntArray[] edges1, PairIntArray[] edges2, int centroidX1, int centroidY1) { if (edges1 == null || edges1.length == 0) { throw new IllegalArgumentException("edges1 cannot be null or empty"); } if (edges2 == null || edges2.length == 0) { throw new IllegalArgumentException("edges2 cannot be null or empty"); } if ((edges1.length != edges2.length)) { throw new IllegalArgumentException( "edges1 and edges2 must be the same length"); } /* edges1 and edges2 are matched edges, but should be considered clouds of points rather than point to point matches within the edges. For each paired edge in edges1 and edges2, determine the implied translation by their centroids. These are combined in weighted average where the weight is the length of the edge. Then a small area surrounding the averaged translation is searched to find the best fit. */ float s = (float)scl; float scaleTimesCosine = (float)(s * Math.cos(rotInRad)); float scaleTimesSine = (float)(s * Math.sin(rotInRad)); //TODO: revisit this: float tolTransX = 2.f * centroidX1 * 0.02f; float tolTransY = 2.f * centroidY1 * 0.02f; if (tolTransX < minTolerance) { tolTransX = minTolerance; } if (tolTransY < minTolerance) { tolTransY = minTolerance; } int nTotal = 0; float[] weights = new float[edges1.length]; for (int i = 0; i < edges1.length; i++) { weights[i] = edges1[i].getN(); nTotal += edges1[i].getN(); } for (int i = 0; i < edges1.length; i++) { weights[i] /= (float)nTotal; } MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper(); float translationX = 0; float translationY = 0; for (int i = 0; i < edges1.length; i++) { PairIntArray edge1 = edges1[i]; PairIntArray edge2 = edges2[i]; double[] xycen1 = curveHelper.calculateXYCentroids(edge1); double[] xycen2 = curveHelper.calculateXYCentroids(edge2); double srX1 = centroidX1*s + ( ((xycen1[0] - centroidX1) * scaleTimesCosine) + ((xycen1[1] - centroidY1) * scaleTimesSine)); double srY1 = centroidY1*s + ( (-(xycen1[0] - centroidX1) * scaleTimesSine) + ((xycen1[1] - centroidY1) * scaleTimesCosine)); double tx = xycen2[0] - srX1; double ty = xycen2[1] - srY1; translationX += weights[i] * tx; translationY += weights[i] * ty; } TransformationPointFit bestFit = refineTranslationWithDownhillSimplex( edges1, edges2, translationX, translationY, tolTransX, tolTransY, 20.f, 20.f, s, (float)rotInRad, centroidX1, centroidY1); return bestFit; } /** * sort the fits by descending number of matches. * @param fits * @param idxLo * @param idxHi, upper index, inclusive */ void sortByDescendingMatches(TransformationPointFit[] fits, int idxLo, int idxHi) { if (idxLo < idxHi) { int idxMid = partition(fits, idxLo, idxHi); sortByDescendingMatches(fits, idxLo, idxMid - 1); sortByDescendingMatches(fits, idxMid + 1, idxHi); } } private int partition(TransformationPointFit[] fits, int idxLo, int idxHi) { TransformationPointFit x = fits[idxHi]; int store = idxLo - 1; for (int i = idxLo; i < idxHi; i++) { if (fitIsBetter(x, fits[i])) { store++; TransformationPointFit swap = fits[store]; fits[store] = fits[i]; fits[i] = swap; } } store++; TransformationPointFit swap = fits[store]; fits[store] = fits[idxHi]; fits[idxHi] = swap; return store; } protected PairFloatArray scaleAndRotate(PairIntArray set1, float rotation, float scale, int centroidX1, int centroidY1) { if (scale < 1) { // numerical errors in rounding to integer can give wrong solutions //throw new IllegalStateException("scale cannot be smaller than 1"); log.severe("scale cannot be smaller than 1"); } if (set1 == null) { throw new IllegalArgumentException("set1 cannot be null"); } PairFloatArray transformed1 = new PairFloatArray(); float s = scale; float scaleTimesCosine = (float)(s * Math.cos(rotation)); float scaleTimesSine = (float)(s * Math.sin(rotation)); //apply scale and rotation to set1 points for (int i = 0; i < set1.getN(); i++) { int x = set1.getX(i); int y = set1.getY(i); float sclRotX = centroidX1*s + ( ((x - centroidX1) * scaleTimesCosine) + ((y - centroidY1) * scaleTimesSine)); float sclRotY = centroidY1*s + ( (-(x - centroidX1) * scaleTimesSine) + ((y - centroidY1) * scaleTimesCosine)); transformed1.add(sclRotX, sclRotY); } return transformed1; } /** * Searches among the given translation range for the best fit to a * Euclidean transformation formed by scale, rotationRadians and the * best fitting translation X and Y given starter points fits. * Note the method is not precise so should be wrapped with a follow-up * method that further searches in the solution's local region. * @param scaledRotatedSet1 * @param set2 * @param fits * @param transX * @param transY * @param tolTransX * @param tolTransY * @param plusMinusTransX * @param plusMinusTransY * @param scale * @param rotationRadians * @param setsAreMatched * @param nMaxIter * @return */ protected TransformationPointFit refineTranslationWithDownhillSimplex( PairFloatArray scaledRotatedSet1, PairIntArray set2, TransformationPointFit[] fits, float transX, float transY, float tolTransX, float tolTransY, float plusMinusTransX, float plusMinusTransY, final float scale, final float rotationRadians, boolean setsAreMatched, int nMaxIter) { int nMaxMatchable = (scaledRotatedSet1.getN() < set2.getN()) ? scaledRotatedSet1.getN() : set2.getN(); if (nMaxMatchable == 0) { return null; } //TODO: revise this: double eps = Math.log(nMaxMatchable)/Math.log(10); float alpha = 1; // > 0 float gamma = 2; // > 1 float beta = 0.5f; float tau = 0.5f; boolean go = true; float txMin = transX - plusMinusTransX; float txMax = transX + plusMinusTransX; float tyMin = transY - plusMinusTransY; float tyMax = transY + plusMinusTransY; int nIter = 0; int bestFitIdx = 0; int worstFitIdx = fits.length - 1; TransformationParameters[] lastParams = extractParameters(fits); while (go && (nIter < nMaxIter)) { if (fits.length == 0) { break; } sortByDescendingMatches(fits, 0, (fits.length - 1)); for (int i = (fits.length - 1); i > -1; --i) { if (fits[i] != null) { worstFitIdx = i; break; } } if (fits[bestFitIdx] == null) { break; } if (nIter > 0) { TransformationParameters[] currentParams = extractParameters(fits); boolean areTheSame = areEqual(lastParams, currentParams); if (areTheSame) { break; } lastParams = currentParams; } // determine center for all points excepting the worse fit float txSum = 0.0f; float tySum = 0.0f; int c = 0; for (int i = 0; i < (fits.length - 1); ++i) { if (fits[i] != null) { txSum += fits[i].getTranslationX(); tySum += fits[i].getTranslationY(); c++; } } transX = txSum / (float)c; transY = tySum / (float)c; // "Reflection" float txReflect = transX + (alpha * (transX - fits[worstFitIdx].getTranslationX())); float tyReflect = transY + (alpha * (transY - fits[worstFitIdx].getTranslationY())); TransformationPointFit fitReflected = evaluateFit( scaledRotatedSet1, txReflect, tyReflect, tolTransX, tolTransY, set2, scale, rotationRadians, setsAreMatched); //TODO: consider putting back in a check for bounds int comp0 = compare(fits[bestFitIdx], fitReflected); int compLast = compare(fits[worstFitIdx], fitReflected); if ((comp0 < 1) && (compLast == 1)) { // replace last with f_refl fits[worstFitIdx] = fitReflected; } else if (comp0 == 1) { // reflected is better than best fit, so "expand" // "Expansion" float txExpansion = transX + (gamma * (txReflect - transX)); float tyExpansion = transY + (gamma * (tyReflect - transY)); TransformationPointFit fitExpansion = evaluateFit(scaledRotatedSet1, txExpansion, tyExpansion, tolTransX, tolTransY, set2, scale, rotationRadians, setsAreMatched); int compR = compare(fitReflected, fitExpansion); if (compR == 1) { // expansion fit is better than reflected fit fits[worstFitIdx] = fitExpansion; } else { fits[worstFitIdx] = fitReflected; } } else if (compLast < 1) { // reflected fit is worse than the worst (last) fit, so contract // "Contraction" float txContraction = transX + (beta * (fits[worstFitIdx].getTranslationX() - transX)); float tyContraction = transY + (beta * (fits[worstFitIdx].getTranslationY() - transY)); TransformationPointFit fitContraction = evaluateFit(scaledRotatedSet1, txContraction, tyContraction, tolTransX, tolTransY, set2, scale, rotationRadians, setsAreMatched); int compC = compare(fits[worstFitIdx], fitContraction); if (compC > -1) { fits[worstFitIdx] = fitContraction; } else { if (true) { // "Reduction" for (int i = 1; i < fits.length; ++i) { if (fits[i] == null) { /*TODO: consider setting this fits[i] = new TransformationPointFit( new TransformationParameters(), 0, Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE ); */ continue; } float txReduction = (fits[bestFitIdx].getTranslationX() + (tau * (fits[i].getTranslationX() - fits[bestFitIdx].getTranslationX()))); float tyReduction = (fits[bestFitIdx].getTranslationY() + (tau * (fits[i].getTranslationY() - fits[bestFitIdx].getTranslationY()))); //NOTE: there's a possibility of a null fit. // instead of re-writing the fits array, will // assign a fake infinitely bad fit which will // fall to the bottom of the list after the next // sort. TransformationPointFit fit = evaluateFit(scaledRotatedSet1, txReduction, tyReduction, tolTransX, tolTransY, set2, scale, rotationRadians, setsAreMatched); fits[i] = fit; } } } } log.finest("best fit so far: nMatches=" + fits[bestFitIdx].getNumberOfMatchedPoints() + " diff from model=" + fits[bestFitIdx].getMeanDistFromModel() ); nIter++; if ((fits[bestFitIdx].getNumberOfMatchedPoints() == nMaxMatchable) && (fits[bestFitIdx].getMeanDistFromModel() < eps)) { go = false; } else if ((transX > txMax) || (transX < txMin)) { go = false; } else if ((transY > tyMax) || (transY < tyMin)) { go = false; } } // additional step that's helpful if not enough iterations are used, // is to test the summed transX, transY which represent the center // of the simplex against the best fit TransformationPointFit fitAvg = evaluateFit(scaledRotatedSet1, transX, transY, tolTransX, tolTransY, set2, scale, rotationRadians, setsAreMatched); int comp = compare(fits[bestFitIdx], fitAvg); if (comp == 1) { fits[bestFitIdx] = fitAvg; } return fits[bestFitIdx]; } private TransformationPointFit refineTranslationWithDownhillSimplex( final PairIntArray[] edges1, final PairIntArray[] edges2, float transX, float transY, float tolTransX, float tolTransY, float plusMinusTransX, float plusMinusTransY, final float scale, final float rotationRadians, int centroidX1, int centroidY1) { int n1 = 0; for (PairIntArray edge : edges1) { n1 += edge.getN(); } int n2 = 0; for (PairIntArray edge : edges2) { n2 += edge.getN(); } int nMaxMatchable = (n1 < n2) ? n1 : n2; if (nMaxMatchable == 0) { return null; } //TODO: revise this: double eps = Math.log(nMaxMatchable)/Math.log(10); float txMin = transX - plusMinusTransX; float txMax = transX + plusMinusTransX; float tyMin = transY - plusMinusTransY; float tyMax = transY + plusMinusTransY; // the positive offsets can be found w/ reflection float[] dtx = new float[]{ -plusMinusTransX, -0.5f*plusMinusTransX, -0.25f*plusMinusTransX, -0.125f*plusMinusTransX, -0.0625f*plusMinusTransX }; float[] dty = new float[]{ -plusMinusTransY, -0.5f*plusMinusTransY, -0.25f*plusMinusTransY, -0.125f*plusMinusTransY, -0.0625f*plusMinusTransY }; int n = (1 + dtx.length) * (1 + dty.length); TransformationPointFit[] fits = new TransformationPointFit[n]; int count = 0; for (int i = 0; i <= dtx.length; i++) { float tx = (i == 0) ? transX : (transX + dtx[i - 1]); for (int j = 0; j <= dty.length; j++) { float ty = (i == 0) ? transY : (transY + dty[i - 1]); fits[count] = evaluateFit(edges1, edges2, tx, ty, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); if (fits[count] != null) { count++; } } } if (count < n) { fits = Arrays.copyOf(fits, count); } float alpha = 1; // > 0 float gamma = 2; // > 1 float beta = 0.5f; float tau = 0.5f; boolean go = true; int nMaxIter = 100; int nIter = 0; int bestFitIdx = 0; int worstFitIdx = fits.length - 1; int lastNMatches = Integer.MIN_VALUE; double lastAvgDistModel = Double.MAX_VALUE; int nIterSameMin = 0; while (go && (nIter < nMaxIter)) { if (fits.length == 0) { break; } sortByDescendingMatches(fits, 0, (fits.length - 1)); for (int i = (fits.length - 1); i > -1; --i) { if (fits[i] != null) { worstFitIdx = i; break; } } if (fits[bestFitIdx] == null) { break; } if ((lastNMatches == fits[bestFitIdx].getNumberOfMatchedPoints()) && (Math.abs(lastAvgDistModel - fits[bestFitIdx].getMeanDistFromModel()) < 0.01)) { nIterSameMin++; /*if (nIterSameMin >= 10) { break; }*/ } else { nIterSameMin = 0; } lastNMatches = fits[bestFitIdx].getNumberOfMatchedPoints(); lastAvgDistModel = fits[bestFitIdx].getMeanDistFromModel(); // determine center for all points excepting the worse fit float txSum = 0.0f; float tySum = 0.0f; int c = 0; for (int i = 0; i < (fits.length - 1); ++i) { if (fits[i] != null) { txSum += fits[i].getTranslationX(); tySum += fits[i].getTranslationY(); ++c; } } transX = txSum / (float)c; transY = tySum / (float)c; // "Reflection" float txReflect = transX + (alpha * (transX - fits[worstFitIdx].getTranslationX())); float tyReflect = transY + (alpha * (transY - fits[worstFitIdx].getTranslationY())); TransformationPointFit fitReflected = evaluateFit( edges1, edges2, txReflect, tyReflect, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); //TODO: consider putting back in a check for bounds int comp0 = compare(fits[bestFitIdx], fitReflected); int compLast = compare(fits[worstFitIdx], fitReflected); if ((comp0 < 1) && (compLast == 1)) { // replace last with f_refl fits[worstFitIdx] = fitReflected; } else if (comp0 == 1) { // reflected is better than best fit, so "expand" // "Expansion" float txExpansion = transX + (gamma * (txReflect - transX)); float tyExpansion = transY + (gamma * (tyReflect - transY)); TransformationPointFit fitExpansion = evaluateFit(edges1, edges2, txExpansion, tyExpansion, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); int compR = compare(fitReflected, fitExpansion); if (compR == 1) { // expansion fit is better than reflected fit fits[worstFitIdx] = fitExpansion; } else { fits[worstFitIdx] = fitReflected; } } else if (compLast < 1) { // reflected fit is worse than the worst (last) fit, so contract // "Contraction" float txContraction = transX + (beta * (fits[worstFitIdx].getTranslationX() - transX)); float tyContraction = transY + (beta * (fits[worstFitIdx].getTranslationY() - transY)); TransformationPointFit fitContraction = evaluateFit(edges1, edges2, txContraction, tyContraction, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); int compC = compare(fits[worstFitIdx], fitContraction); if (compC > -1) { fits[worstFitIdx] = fitContraction; } else { // "Reduction" for (int i = 1; i < fits.length; i++) { if (fits[i] == null) { /* TODO: consider setting this fits[i] = new TransformationPointFit( new TransformationParameters(), 0, Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE ); */ continue; } float txReduction = (fits[bestFitIdx].getTranslationX() + (tau * (fits[i].getTranslationX() - fits[bestFitIdx].getTranslationX()))); float tyReduction = (fits[bestFitIdx].getTranslationY() + (tau * (fits[i].getTranslationY() - fits[bestFitIdx].getTranslationY()))); //NOTE: there's a possibility of a null fit. // instead of re-writing the fits array, will // assign a fake infinitely bad fit which will // fall to the bottom of the list after the next // sort. TransformationPointFit fit = evaluateFit(edges1, edges2, txReduction, tyReduction, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); fits[i] = fit; } } } log.finest("best fit so far: nMatches=" + fits[bestFitIdx].getNumberOfMatchedPoints() + " diff from model=" + fits[bestFitIdx].getMeanDistFromModel() ); nIter++; if ((fits[bestFitIdx].getNumberOfMatchedPoints() == nMaxMatchable) && (fits[bestFitIdx].getMeanDistFromModel() < eps)) { go = false; } /*else if ((transX > txMax) || (transX < txMin)) { go = false; } else if ((transY > tyMax) || (transY < tyMin)) { go = false; }*/ } // additional step that's helpful if not enough iterations are used, // is to test the summed transX, transY which represent the center // of the simplex against the best fit TransformationPointFit fitAvg = evaluateFit(edges1, edges2, transX, transY, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); int comp = compare(fits[bestFitIdx], fitAvg); if (comp == 1) { fits[bestFitIdx] = fitAvg; } return fits[bestFitIdx]; } protected TransformationPointFit evaluateFit( PairFloatArray scaledRotatedSet1, float transX, float transY, float tolTransX, float tolTransY, PairIntArray set2, final float scale, final float rotationRadians, boolean setsAreMatched) { if (set2 == null) { throw new IllegalArgumentException( "set2 cannot be null"); } if (scaledRotatedSet1 == null) { throw new IllegalArgumentException( "scaledTransformedSet1 cannot be null"); } if (setsAreMatched) { return evaluateFitForMatched(scaledRotatedSet1, transX, transY, set2, scale, rotationRadians); } return evaluateFitForUnMatched(scaledRotatedSet1, transX, transY, tolTransX, tolTransY, set2, scale, rotationRadians); } private TransformationPointFit evaluateFit( PairIntArray[] edges1, PairIntArray[] edges2, float translationX, float translationY, float tolTransX, float tolTransY, float scale, float rotationRadians, int centroidX1, int centroidY1) { if (edges1 == null || edges1.length == 0) { throw new IllegalArgumentException("edges1 cannot be null or empty"); } if (edges2 == null || edges2.length == 0) { throw new IllegalArgumentException("edges2 cannot be null or empty"); } int n1 = 0; for (PairIntArray edge : edges1) { n1 += edge.getN(); } int n2 = 0; for (PairIntArray edge : edges2) { n2 += edge.getN(); } int nMaxMatchable = (n1 < n2) ? n1 : n2; if (nMaxMatchable == 0) { return null; } List<Double> residuals = new ArrayList<Double>(); int nTotal = 0; for (int i = 0; i < edges1.length; i++) { PairIntArray edge1 = edges1[i]; PairIntArray edge2 = edges2[i]; nTotal += edge1.getN(); calculateTranslationResidualsForUnmatchedMultiplicity( edge1, edge2, translationX, translationY, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1, residuals); } double avg = 0; for (Double diff : residuals) { avg += diff.doubleValue(); } avg /= (double)residuals.size(); double stdDev = 0; for (Double diff : residuals) { double d = diff.doubleValue() - avg; stdDev += (d * d); } stdDev = Math.sqrt(stdDev/((double)residuals.size() - 1)); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationRadians); params.setScale(scale); params.setTranslationX(translationX); params.setTranslationY(translationY); TransformationPointFit fit = new TransformationPointFit(params, residuals.size(), avg, stdDev, tolTransX, tolTransY); return fit; } /** * calculate the residuals between edge1 points and edge2 points with the * assumption that there may not be one to one point matches, but instead * will be general point matches. For that reason, a greedy search for * nearest neighbor with the possibility of multiple matches to a neighbor * is used. * * @param edge1 * @param edge2 * @param transX * @param transY * @param tolTransX * @param tolTransY * @param scale * @param rotationRadians * @param outputResiduals */ private void calculateTranslationResidualsForUnmatchedMultiplicity( PairIntArray edge1, PairIntArray edge2, float transX, float transY, float tolTransX, float tolTransY, final float scale, final float rotationRadians, int centroidX1, int centroidY1, List<Double> outputResiduals) { if (edge1 == null || edge1.getN() == 0) { throw new IllegalArgumentException( "edge1 cannot be null or empty"); } if (edge2 == null || edge2.getN() == 0) { throw new IllegalArgumentException( "edge2 cannot be null or empty"); } int nMaxMatchable = (edge1.getN() < edge2.getN()) ? edge1.getN() : edge2.getN(); if (nMaxMatchable == 0) { return; } float scaleTimesCosine = (float)(scale * Math.cos(rotationRadians)); float scaleTimesSine = (float)(scale * Math.sin(rotationRadians)); for (int i = 0; i < edge1.getN(); i++) { int x1 = edge1.getX(i); int y1 = edge1.getY(i); float transformedX = (centroidX1*scale + ( ((x1 - centroidX1) * scaleTimesCosine) + ((y1 - centroidY1) * scaleTimesSine))) + transX; float transformedY = (centroidY1*scale + ( (-(x1 - centroidX1) * scaleTimesSine) + ((y1 - centroidY1) * scaleTimesCosine))) + transY; double minDiff = Double.MAX_VALUE; for (int j = 0; j < edge2.getN(); j++) { int x2 = edge2.getX(j); int y2 = edge2.getY(j); float dx = x2 - transformedX; float dy = y2 - transformedY; if ((Math.abs(dx) > tolTransX) || (Math.abs(dy) > tolTransY)) { continue; } float diff = (float)Math.sqrt(dx*dx + dy*dy); if (diff < minDiff) { minDiff = diff; } } if (minDiff < Double.MAX_VALUE) { outputResiduals.add(Double.valueOf(minDiff)); } } } /** * given the model x y that have already been scaled and rotated, add the * transX and transY, respectively and calculated the average residual * between that and set2 and the standard deviation from the average. * Note that set2 and (scaledRotatedX, scaledRotatedY) are known to be * matched points so index 1 in set2 and index1 in scaledRotated represent * matching points. * @param set2 * @param scaledRotatedX the model x points scaled and rotated * @param scaledRotatedY the model y points scaled and rotated * @param transX the x translation to apply to the model points * @param transY the y translation to apply to the model points * @return */ private TransformationPointFit evaluateFitForMatched( PairFloatArray scaledRotatedSet1, float transX, float transY, PairIntArray set2, final float scale, final float rotationRadians) { if (set2 == null || set2.getN() == 0) { throw new IllegalArgumentException( "set2 cannot be null or empty"); } if (scaledRotatedSet1 == null || scaledRotatedSet1.getN() == 0) { throw new IllegalArgumentException( "scaledRotatedSet1 cannot be null or empty"); } if (set2.getN() != scaledRotatedSet1.getN()) { throw new IllegalArgumentException( "for matched sets, set2 must be the same length as scaledRotated" + " X and Y"); } int nMaxMatchable = (scaledRotatedSet1.getN() < set2.getN()) ? scaledRotatedSet1.getN() : set2.getN(); if (nMaxMatchable == 0) { return null; } double sum = 0; double[] diff = new double[set2.getN()]; for (int i = 0; i < set2.getN(); i++) { float transformedX = scaledRotatedSet1.getX(i) + transX; float transformedY = scaledRotatedSet1.getY(i) + transY; double dx = transformedX - set2.getX(i); double dy = transformedY - set2.getY(i); diff[i] = Math.sqrt(dx*dx + dy+dy); sum += diff[i]; } double avgDiff = sum/(double)set2.getN(); sum = 0; for (int i = 0; i < set2.getN(); i++) { sum += (diff[i] * diff[i]); } double stDev = Math.sqrt(sum/((double)set2.getN() - 1)); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationRadians); params.setScale(scale); params.setTranslationX(transX); params.setTranslationY(transY); TransformationPointFit fit = new TransformationPointFit(params, set2.getN(), avgDiff, stDev, Float.MAX_VALUE, Float.MAX_VALUE); fit.setMaximumNumberMatchable(nMaxMatchable); return fit; } /** * given the model x y that have already been scaled and rotated, add the * transX and transY, respectively and calculated the average residual * between that and set2 and the standard deviation from the average. * Note that set2 and (scaledRotatedX, scaledRotatedY) are NOT known to be * matched points so the residuals are minimized for each point in * the model to find the matching in set2 before computing the * average and standard deviation. * * @param set2 * @param scaledRotatedSet1 the model x,y points scaled and rotated * @param transX the x translation to apply to the model points * @param transY the y translation to apply to the model points * @return */ private TransformationPointFit evaluateFitForUnMatched( PairFloatArray scaledRotatedSet1, float transX, float transY, float tolTransX, float tolTransY, PairIntArray set2, final float scale, final float rotationRadians) { //return evaluateFitForUnMatchedOptimal(scaledRotatedX, // scaledRotatedY, transX, transY, tolTransX, tolTransY, // set2, scale, rotationRadians); return evaluateFitForUnMatchedGreedy(scaledRotatedSet1, transX, transY, tolTransX, tolTransY, set2, scale, rotationRadians); } private TransformationParameters[] extractParameters( TransformationPointFit[] fits) { if (fits == null) { return new TransformationParameters[0]; } TransformationParameters[] params = new TransformationParameters[fits.length]; for (int i = 0; i < fits.length; ++i) { if (fits[i] != null) { params[i] = fits[i].getParameters(); } } return params; } private boolean areEqual(TransformationParameters[] lastParams, TransformationParameters[] currentParams) { if (lastParams.length != currentParams.length) { throw new IllegalArgumentException( "lastParams.length must be equal to currentParams.length"); } for (int i = 0; i < lastParams.length; ++i) { TransformationParameters p0 = lastParams[i]; TransformationParameters p1 = currentParams[i]; if ((p0 == null) && (p1 != null)) { return false; } else if ((p0 != null) && (p1 == null)) { return false; } else if (p0 == null && p1 == null) { continue; } else if (!p0.equals(p1)) { return false; } } return true; } /** * compare the fields mean distance from model and standard deviation * from mean to find if they are similar within a tolerance, then * find if the parameters are the same and return * <pre> * 0==same fit; 1==similar fits; -1==different fits * </pre> * @param bestFit * @param fit * @return comparisonResult 0==same fit; 1==similar fits; -1==different fits */ protected int fitsAreSimilarWithDiffParameters( TransformationPointFit bestFit, TransformationPointFit fit) { if (bestFit == null || fit == null) { return -1; } /*if the fit and bestFit is very close, need an infrastructure to return more than one (and to reset it when another fit not similar to bestFit is found) bestFit: fit=nMatchedPoints=63 nMaxMatchable=63.0 meanDistFromModel=37.57523582095192 stDevFromMean=22.616214121394517 tolerance=144.2497833620557 rotationInRadians=0.34906584 rotationInDegrees=19.99999941818584 scale=1.0 translationX=86.61143 translationY=-18.330833 fit: fit=nMatchedPoints=63 nMaxMatchable=63.0 meanDistFromModel=36.79744166041177 <-- mean dist and stdev are similar stDevFromMean=23.167906020816925 tolerance=144.2497833620557 rotationInRadians=0.5235988 rotationInDegrees=30.000000834826057 <--- rot is very different scale=1.0 translationX=91.6094 translationY=-72.9244 <--- transY is very different the correct answer is closer to "bestFit" but is currently then replaced with fit, so need to preserve both. correct answer: rotationInDegrees=18.000000500895634 scale=1.0 translationX=7.0 translationY=33.0 number of vertical partitions=3 ---- in contrast, these 2 sets of meanDistFromModel and stDevFromMean are significantly different: bestFit: meanDistFromModel=0.3658992320831333 stDevFromMean=0.15709856816653883 fit: meanDistFromModel=2.267763360270432 stDevFromMean=1.0703222291650063 ----- so ratios are needed rather than differences similar fits: divMean = 1.02 divStDev = 0.976 different fits: divMean = 0.161 divStDev = 0.147 */ //TODO: this may need to be adjusted and in the 2 fitness // functions which use it... should be it's own method... int nEps = (int)(1.5*Math.ceil(bestFit.getNumberOfMatchedPoints()/10.)); if (nEps == 0) { nEps = 1; } int diffNMatched = Math.abs(bestFit.getNumberOfMatchedPoints() - fit.getNumberOfMatchedPoints()); if (diffNMatched > nEps) { return -1; } double divMean = Math.abs(bestFit.getMeanDistFromModel()/ fit.getMeanDistFromModel()); double divStDev = Math.abs(bestFit.getStDevFromMean()/ fit.getStDevFromMean()); if ((Math.abs(1 - divMean) < 0.05) && (Math.abs(1 - divStDev) < 0.3)) { if (bestFit.getParameters().equals(fit.getParameters())) { return 0; } else { return 1; } } return -1; } /** * for unmatched sets of points, use a finer grid search to find the best * fit among the given parameters in similarToBestFit. * * @param similarToBestFit * @param set1 * @param set2 * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @param setsFractionOfImage * @return */ protected TransformationPointFit finerGridSearchToDistinguishBest( List<TransformationPointFit> similarToBestFit, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { if (similarToBestFit.isEmpty()) { return null; } else if (similarToBestFit.size() == 1) { return similarToBestFit.get(0); } int nIntervals = 3; TransformationPointFit bestFit = null; for (TransformationPointFit sFit : similarToBestFit) { TransformationPointFit fit = finerGridSearch( nIntervals, sFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fitIsBetter(bestFit, fit)) { bestFit = fit; } } return bestFit; } protected TransformationPointFit finerGridSearchToDistinguishBestForMatched( List<TransformationPointFit> similarToBestFit, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { if (similarToBestFit.isEmpty()) { return null; } else if (similarToBestFit.size() == 1) { return similarToBestFit.get(0); } int nIntervals = 3; TransformationPointFit bestFit = null; for (TransformationPointFit sFit : similarToBestFit) { TransformationPointFit fit = finerGridSearchForMatched( nIntervals, sFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fitIsBetter(bestFit, fit)) { bestFit = fit; } } return bestFit; } private TransformationPointFit finerGridSearch( int nIntervals, TransformationPointFit bestFit, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { double halfRange = 3 * bestFit.getMeanDistFromModel(); if (Double.isInfinite(halfRange)) { return null; } int transXStart = (int)(bestFit.getTranslationX() - halfRange); int transXStop = (int)(bestFit.getTranslationX() + halfRange); int transYStart = (int)(bestFit.getTranslationY() - halfRange); int transYStop = (int)(bestFit.getTranslationY() + halfRange); int transXDelta = (transXStop - transXStart)/nIntervals; int transYDelta = (transYStop - transYStart)/nIntervals; if (transXDelta == 0) { transXDelta++; } if (transYDelta == 0) { transYDelta++; } float tolTransX2 = bestFit.getTranslationXTolerance(); float tolTransY2 = bestFit.getTranslationYTolerance(); boolean setsAreMatched = false; int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray scaledRotatedSet1 = scaleAndRotate(set1, bestFit.getRotationInRadians(), bestFit.getScale(), image1CentroidX, image1CentroidY); TransformationPointFit fit2 = calculateTranslationFromGridThenDownhillSimplex( scaledRotatedSet1, set1, set2, image1Width, image1Height, image2Width, image2Height, bestFit.getRotationInRadians(), bestFit.getScale(), transXStart, transXStop, transXDelta, transYStart, transYStop, transYDelta, tolTransX2, tolTransY2, setsAreMatched, setsFractionOfImage); return fit2; } private TransformationPointFit finerGridSearchForMatched( int nIntervals, TransformationPointFit bestFit, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { double halfRange = 3 * bestFit.getMeanDistFromModel(); if (Double.isInfinite(halfRange)) { return null; } int transXStart = (int)(bestFit.getTranslationX() - halfRange); int transXStop = (int)(bestFit.getTranslationX() + halfRange); int transYStart = (int)(bestFit.getTranslationY() - halfRange); int transYStop = (int)(bestFit.getTranslationY() + halfRange); int transXDelta = (transXStop - transXStart)/nIntervals; int transYDelta = (transYStop - transYStart)/nIntervals; if (transXDelta == 0) { transXDelta++; } if (transYDelta == 0) { transYDelta++; } int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray scaledRotatedSet1 = scaleAndRotate(set1, bestFit.getRotationInRadians(), bestFit.getScale(), image1CentroidX, image1CentroidY); float unusedTolerance = Float.MIN_VALUE; boolean setsAreMatched = true; TransformationPointFit fit2 = calculateTranslationFromGridThenDownhillSimplex( scaledRotatedSet1, set1, set2, image1Width, image1Height, image2Width, image2Height, bestFit.getRotationInRadians(), bestFit.getScale(), transXStart, transXStop, transXDelta, transYStart, transYStop, transYDelta, unusedTolerance, unusedTolerance, setsAreMatched, setsFractionOfImage); return fit2; } /** compare the bestFit and fit tolerances and return <pre> -1 : both are not null and bestFit tolerances are smaller 0 : both are not null and tolerances are same. 1 : both are not null and fit tolerances are smaller 2 : both are not null and the x and y fits and smaller and larger in a mix 3 : either bestFit or fit is null </pre> */ private int compareTolerance(TransformationPointFit bestFit, TransformationPointFit fit) { if (bestFit == null || fit == null) { return 3; } float diffTolX = bestFit.getTranslationXTolerance() - fit.getTranslationXTolerance(); float diffTolY = bestFit.getTranslationYTolerance() - fit.getTranslationYTolerance(); if ((Math.abs(diffTolX) < 1) && (Math.abs(diffTolY) < 1)) { return 0; } else if ((diffTolX > 0) && (diffTolY > 0)) { return 1; } else if ((diffTolX < 0) && (diffTolY < 0)) { return -1; } else { return 2; } } /** * Re-evaluate the fit of the enclosed parameters, but use the new tolerance * for translation in x and y. * * @param fit * @param set1 * @param set2 * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @param setsFractionOfImage * @return */ private TransformationPointFit reevaluateForNewTolerance( TransformationPointFit fit, float translationXTolerance, float translationYTolerance, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height) { if (fit == null) { return null; } float rotationInRadians = fit.getRotationInRadians(); float scale = fit.getScale(); int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray scaledRotatedSet1 = scaleAndRotate(set1, rotationInRadians, scale, image1CentroidX, image1CentroidY); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationInRadians); params.setScale(scale); params.setTranslationX(fit.getTranslationX()); params.setTranslationY(fit.getTranslationY()); //TODO: may need to change TransformationPointFit to retain tolerance in X and Y // instead of a single value. TransformationPointFit fit2 = evaluateFitForUnMatchedTransformedGreedy( params, scaledRotatedSet1, set2, translationXTolerance, translationYTolerance); return fit2; } /** * find the minima and maxima of translationX and translationY for the given * fits. * @param fits * @return new float[]{minTX, maxTX, minTY, maxTY} */ protected float[] getTranslationMinAndMaxes(TransformationPointFit[] fits) { if (fits == null || fits.length == 0) { return null; } float minTX = Float.MAX_VALUE; float maxTX = Float.MIN_VALUE; float minTY = Float.MAX_VALUE; float maxTY = Float.MIN_VALUE; for (TransformationPointFit fit : fits) { if (fit == null) { continue; } float tx = fit.getTranslationX(); float ty = fit.getTranslationY(); if (tx < minTX) { minTX = tx; } if (ty < minTY) { minTY = ty; } if (tx > maxTX) { maxTX = tx; } if (ty > maxTY) { maxTY = ty; } } return new float[]{minTX, maxTX, minTY, maxTY}; } /** * re-evaluate bestFit or fit, whichever has the largest translation * tolerance, using the smaller tolerance. Note that there are * exception rules, such as when both bestFit and fit have * same number of points, but fit has a mean dist from model less than one * and bestFit has a much larger mean distance from model. In that case, * even if bestFit has a smaller translation tolerance, fit will not * be re-evaluated because such a mean distance from model means the * answer has converged. * * * @param bestFit * @param fit * @param set1 * @param set2 * @param image1Width * @param image1Height * @param reevalFits * @param fitIsBetter */ protected void reevaluateFitsForCommonTolerance( TransformationPointFit bestFit, TransformationPointFit fit, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, final TransformationPointFit[] reevalFits, final boolean[] fitIsBetter) { /* check for whether fit has converged already for equal number of points matched. */ if (fit != null && bestFit != null) { int bestNMatches = bestFit.getNumberOfMatchedPoints(); int compNMatches = fit.getNumberOfMatchedPoints(); int diffEps = (int)Math.round(2.*Math.ceil(Math.max(bestNMatches, compNMatches)/10.)); if (diffEps == 0) { diffEps = 1; } if ((bestNMatches > 2) && (compNMatches > 2)) { if (Math.abs(bestNMatches - compNMatches) < diffEps) { if ((fit.getMeanDistFromModel() < 1) && (fit.getStDevFromMean() < 1) && (bestFit.getMeanDistFromModel() > 1)) { // fit is the better fit fitIsBetter[0] = true; reevalFits[0] = bestFit; reevalFits[1] = fit; return; } } } /* when tolerances are both already very small, not redoing the fit, just comparing as is */ int limit = 7; if ((bestFit.getTranslationXTolerance() < limit) && (bestFit.getTranslationYTolerance() < limit) && (fit.getTranslationXTolerance() < limit) && (fit.getTranslationYTolerance() < limit)) { fitIsBetter[0] = fitIsBetter(bestFit, fit); reevalFits[0] = bestFit; reevalFits[1] = fit; return; } } /* -1 : both are not null and bestFit tolerances are smaller 0 : both are not null and tolerances are same. 1 : both are not null and fit tolerances are smaller 2 : both are not null and the x and y fits and smaller and larger in a mix 3 : either bestFit or fit is null */ int compTol = compareTolerance(bestFit, fit); TransformationPointFit bestFitT = bestFit; TransformationPointFit fitT = fit; if (compTol == 1) { bestFitT = reevaluateForNewTolerance(bestFit, fit.getTranslationXTolerance(), fit.getTranslationYTolerance(), set1, set2, image1Width, image1Height); /* // do not use the lower tolerance. it may be a false fit if null here if (bestFitT == null) { bestFitT = bestFit; } else if (bestFitT.getNumberOfMatchedPoints() == 0) { if (bestFit.getNumberOfMatchedPoints() > 10) { bestFitT = bestFit; } }*/ } else if (compTol == -1) { fitT = reevaluateForNewTolerance(fit, bestFit.getTranslationXTolerance(), bestFit.getTranslationYTolerance(), set1, set2, image1Width, image1Height); /* // do not use the lower tolerance if resulted in null fit if (fitT == null) { fitT = fit; } else if (fitT.getNumberOfMatchedPoints() == 0) { if (fit.getNumberOfMatchedPoints() > 10) { fitT = fit; } }*/ } else if (compTol == 2) { // TODO: may need to revise this // reduce both to smallest tolerances float tolX = bestFit.getTranslationXTolerance(); if (fit.getTranslationXTolerance() < tolX) { tolX = fit.getTranslationXTolerance(); } float tolY = bestFit.getTranslationYTolerance(); if (fit.getTranslationYTolerance() < tolY) { tolY = fit.getTranslationYTolerance(); } bestFitT = reevaluateForNewTolerance(bestFit, tolX, tolY, set1, set2, image1Width, image1Height); fitT = reevaluateForNewTolerance(fit, tolX, tolY, set1, set2, image1Width, image1Height); /* // do not use the lower tolerance if resulted in null fits if (fitT == null) { fitT = fit; bestFitT = bestFit; } else if (fitT.getNumberOfMatchedPoints() == 0) { if (fit.getNumberOfMatchedPoints() > 10) { fitT = fit; bestFitT = bestFit; } } else if (bestFitT == null) { fitT = fit; bestFitT = bestFit; } else if (bestFitT.getNumberOfMatchedPoints() == 0) { if (bestFitT.getNumberOfMatchedPoints() > 10) { fitT = fit; bestFitT = bestFit; } }*/ } fitIsBetter[0] = fitIsBetter(bestFitT, fitT); reevalFits[0] = bestFit; if (fitIsBetter[0]) { reevalFits[1] = fitT; } if (bestFit != null && fit != null) { if (compTol == 1) { log.fine(" rot re-evaluated bestFit at lower tolerance"); } else if (compTol == 2) { log.fine(" rot re-evaluated bestFit and fit at common tolerance"); } } } }
src/algorithms/imageProcessing/PointMatcher.java
package algorithms.imageProcessing; import algorithms.compGeometry.PointPartitioner; import static algorithms.imageProcessing.PointMatcher.minTolerance; import algorithms.imageProcessing.util.MatrixUtil; import algorithms.misc.MiscMath; import algorithms.util.PairFloat; import algorithms.util.PairFloatArray; import algorithms.util.PairInt; import algorithms.util.PairIntArray; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import thirdparty.HungarianAlgorithm; /** * class to match the points extracted from two images. * * the transformation parameters of translation, rotation and scale are * found given the two sets of points. * <pre> Details of determining the transformation from points. After points are matched: Estimating scale: Take 2 pairs of points in both datasets and compute the distance between them and then take the ratio: scale = (distance between pair in set 1) / (distance between pair in set 2) Note: scale is roughly determined from contour matching too in the inflection matcher. Estimating rotation: Take the same 2 pairs and determine the difference in their angles: tan(theta) = delta y / delta x rotation = atan((delta y between pair in set 1) /(delta x between pair in set 1)) - atan((delta y between pair in set 2) /(delta x between pair in set 2)) Estimate translation: Performed on one point in set 1 with its candidate match in set 2: From the full transformation equation, we can rewrite: transX = xt0 - xc*scale - (((x0-xc)*scale*math.cos(theta)) + ((y0-yc)*scale*math.sin(theta))) transY = yt0 - yc*scale - ((-(x0-xc)*scale*math.sin(theta)) + ((y0-yc)*scale*math.cos(theta))) where (xc, yc) is the center of the first image Matching the points: For the contour matching, we were able to choose subsets of the entire sets of contours for better matching characteristics (subsets that had larger sigma values for their peaks could be used). For the points given here, there isn't a clear indicator for a subset that could be used preferably so that all nodes might not need to be visited. The need to use pairs of points in set1 matched against pairs in set 2 means that if one tries every combination of pairs, the runtime complexity is exponential. number of ways to make pairs in set 1 times the number of ways to make pairs in set 2 = n_1! n_2! ------------ X ------------ 2*(n_1 - 2)! 2*(n_2 - 2)! This is not feasible as soon as the sets get larger than a dozen points. Alternately, one could try a search algorithm to visit the space of all possible combinations of parameters instead of all combinations of subsets of pairs. max translation x possible = width of image 2 max translation y possible = height of image 2 max scale is set to some reasonable number like 10? max rotation is 1 degree changes = 360 (or quadrants?) then total number of permutations = maxTransX * maxTransY * maxScale * 360 = 1000 * 500 * 10 * 360 = 1.8 billion for pure grid search over parameter space then trying the parameters on all points puts another factor into there of nPoints set 1 * nPoints set 2. Note, because the cosine and sine terms in the transformation equation due to rotation work against one another and don't proceed in a total combined single direction with theta, we can't use a gradient descent solver. (note, this hasn't been edited for positive Y up yet) positive Y is down positive X is right positive theta starts from Y=0, X>=0 and proceeds CW 270 QIII | QIV | 180--------- 0 +X | QII | QI 90 +Y theta cos(theta) sin(theta) 0 0 1.0 0 ----- 30 0.5236 0.87 0.5 | 45 0.785 0.707 0.707 | QI 60 1.047 0.5 0.866 | 90 1.57 0.0 1.0 ----- 120 2.09 -0.5 0.866 | QII 150 2.618 -0.866 0.5 | 180 3.1416 -1.0 0.0 ----- 210 3.6652 -0.866 -0.5 | QIII 240 | 270 4.7124 0.0 -1.0 ----- 300 5.236 0.5 -0.866 | QIV 330 | ----- So then, it looks like a grid search over rotation and scale intervals followed by fitting for translation to get into the local neighborhood of the transformation solution, followed by the use of the Nelder-Mead Downhill Simplex to refine the transformation is a better solution. runtime complexity of: grid search: nRotationIntervals * nScaleIntervals * nSet1 * nSet2 downhill search: not polynomial nor deterministic. varies by dataset. In the searches, if rotation and scale are fixed, and transX and transY are to be found, one can use either: (1) compare the offsets implied by each combination of points in set 1 and set 2. for brown_lowe_2003 image1 and image2, the number of corners is n1 = 78 n2 = 88 n1 * n2 = 5616 How does one determine the best solution among those translations? One needs an assumed tolerance for the translation, and then to count the number of matches to a point in the 2nd set. The best solution has the highest number of matches with the same rules for an assumed tolerance and the smallest avg difference with predicted positions for matches in set 2. For the tolerance, the reasons that translation might be different as a function of position in the image might be: -- due to rounding to a pixel. these are very small errors. -- due to projection effects for different epipolar geometry (camera nadir perpendicular to different feature, for example). these are potentially very large and are not solved in the transformation with this point matcher though a tolerance is made for a small amount of it. (NOTE however, that once the points are matched, the true epipolar geometry can be calculated with the StereoProjection classes). -- due to errors in the location of the corner. this can be due to the edge detector. these are small errors. -- due to image warping such as distortions from the shape of the lens. one would need a point matcher tailored for the specific geometric projection. -- due to a camera not completely perpendicularly aligned with the optical axis. presumably, this is an extreme case and you'd want better data... For the Brown & Lowe 2003 points, transX=293.1 (stdDev=10.3) transY=14.3 (stdDev=5.9) the large standard deviation appears to be due to projection effects. the skyline is rotated about 13 degrees w.r.t. skyline in second image while the features at the bottom remain horizontal in both. The spread in standard deviation appears to be correlated w/ the image dimensions, as would be expected with projection being the largest reason for a spread in translation. That is, the X axis is twice the size of the Y and so are their respective standard deviations. Could make a generous allowance for projection effects by assuming a maximum present such as that in the Brown & Lowe images, that is image size times an error due to a differential spread over those pixels for a maximum difference in rotation such as 20 degrees or something. For Brown & Lowe images, the tolerance would be number of pixels for dimension times 0.02. If there is no reasonable solution using only scale, rotation, and translation, then a more computationally expensive point matcher that solves for epipolar geometry too or a differential rotation and associated variance in other parameters is needed (and hasn't been implemented here yet). **OR, even better, an approach using contours and an understanding of occlusion (the later possibly requires shape identification) can be made with the contour matcher in this project.** The contour matcher approach is currently not **commonly** possible with this project, because most edges are not closed curves. OR (2) try every possible combination of translation for X and Y which would be width of image 2 in pixels times the height of image 2 in pixels. for brown_lowe_2003 image1 and image2, image2 width = 517, height = 374 w * h = 193358 so this method is 34 times more The best solution among those translations is found in the same way as (1) above. </pre> * @author nichole */ public final class PointMatcher { private final Logger log = Logger.getLogger(this.getClass().getName()); protected static int minTolerance = 5; private boolean costIsNumAndDiff = false; //TODO: this has to be a high number for sets with projection. // the solution is sensitive to this value. private final float generalTolerance = 8; public static float toleranceGridFactor = 4.f; public void setCostToNumMatchedAndDiffFromModel() { costIsNumAndDiff = true; } /** * NOT READY FOR USE * * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @param outputMatchedLeftXY * @param outputMatchedRightXY * @param useLargestToleranceForOutput use the largest tolerance for * applying the transformation to point sets during matching. the largest * tolerance is the class variable generalTolerance. * If useLargestToleranceForOutput is false, the transformation's best * fit is used during matching (which should provide a smaller but more * certain matched output). If this method is used as a precursor to * projection (epipolar) solvers of sets that do have projection components, * one might prefer to set this to true to allow more to be matched. * @return */ public TransformationPointFit performPartitionedMatching( PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height, PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY, boolean useLargestToleranceForOutput) { /* -- perform whole sets matching -- perform vertical partition matching -- perform horizontal partition matching -- if the vert or horiz results are better that whole sets, consider partition into 4 TODO: methods are using a special fitting function specifically for skyline matches, but the function may not be ideal for whole image corner matching, so need to allow the choice of fitness function to be passed as an argument. */ // ====== whole sets match ======= PairIntArray allPointsLeftMatched = new PairIntArray(); PairIntArray allPointsRightMatched = new PairIntArray(); TransformationPointFit allPointsFit = performMatching( unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height, allPointsLeftMatched, allPointsRightMatched, 1.0f); float allPointsNStat = (float)allPointsFit.getNumberOfMatchedPoints()/ (float)allPointsFit.getNMaxMatchable(); log.info("all points set nStat=" + allPointsNStat + " Euclidean fit=" + allPointsFit.toString()); // ====== vertical partitioned matches ======= TransformationPointFit verticalPartitionedFit = performVerticalPartitionedMatching(2, unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height); /* // ====== horizontal partitioned matches ======= TransformationPointFit horizontalPartitionedFit = performHorizontalPartitionedMatching(2, unmatchedLeftXY, unmatchedRightXY, image1CentroidX, image1CentroidY, image2CentroidX, image2CentroidY); */ TransformationPointFit bestFit = allPointsFit; if (fitIsBetter(bestFit, verticalPartitionedFit)) { //fitIsBetterNStat(bestFit, verticalPartitionedFit)) { bestFit = verticalPartitionedFit; } if (bestFit == null) { return null; } // TODO: compare to horizontal fits when implemented Transformer transformer = new Transformer(); int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray transformedLeft = transformer.applyTransformation2( bestFit.getParameters(), unmatchedLeftXY, image1CentroidX, image1CentroidY); float transTolX, transTolY, tolerance; if (useLargestToleranceForOutput) { tolerance = generalTolerance; transTolX = generalTolerance * (float)Math.sqrt(1./2); transTolY = transTolX; } else { transTolX = bestFit.getTranslationXTolerance(); transTolY = bestFit.getTranslationYTolerance(); tolerance = (float)Math.sqrt(transTolX*transTolX + transTolY*transTolY); } float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal( transformedLeft, unmatchedRightXY, transTolX, transTolX); matchPoints(unmatchedLeftXY, unmatchedRightXY, tolerance, matchIndexesAndDiffs, outputMatchedLeftXY, outputMatchedRightXY); return bestFit; } /** * given unmatched point sets unmatchedLeftXY and unmatchedRightXY, * partitions the data in numberOfPartitions vertically, finds the * best match for each combination of vertical partitions as subsets * of their parent sets, then finds the best partition solution * among those, then refines the solution with a more detailed search * using all points. * * @param numberOfPartitions the number of vertical partitions to make. * the maximum value accepted is 3 and minimum is 1. * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @return best fitting transformation between unmatched left and right */ public TransformationPointFit performVerticalPartitionedMatching( final int numberOfPartitions, PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height) { if (numberOfPartitions > 3) { throw new IllegalArgumentException( "numberOfPartitions max value is 3"); } if (numberOfPartitions < 1) { throw new IllegalArgumentException( "numberOfPartitions min value is 1"); } int nXDiv = numberOfPartitions; int nYDiv = 1; float setsFractionOfImage = 1.f/(float)numberOfPartitions; int n = (int)Math.pow(nXDiv * nYDiv, 2); TransformationPointFit[] vertPartitionedFits = new TransformationPointFit[n]; float[] nStat = new float[n]; PointPartitioner partitioner = new PointPartitioner(); PairIntArray[] vertPartitionedLeft = partitioner.partitionVerticalOnly( unmatchedLeftXY, nXDiv); PairIntArray[] vertPartitionedRight = partitioner.partitionVerticalOnly( unmatchedRightXY, nXDiv); int bestFitIdx = -1; int count = 0; for (int p1 = 0; p1 < vertPartitionedLeft.length; p1++) { for (int p2 = 0; p2 < vertPartitionedRight.length; p2++) { // determine fit only with partitioned points PairIntArray part1 = vertPartitionedLeft[p1]; PairIntArray part2 = vertPartitionedRight[p2]; TransformationPointFit fit = calcTransWithRoughGrid( part1, part2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fit == null) { log.fine(Integer.toString(count) + ", p1=" + p1 + " p2=" + p2 + ") NO SOLN " + " n1=" + part1.getN() + " n2=" + part2.getN()); count++; continue; } nStat[count] = (float)fit.getNumberOfMatchedPoints()/ (float)fit.getNMaxMatchable(); log.fine(Integer.toString(count) + ", p1=" + p1 + " p2=" + p2 + ") nStat=" + nStat[count] + " n1=" + part1.getN() + " n2=" + part2.getN() + " Euclidean fit=" + fit.toString()); vertPartitionedFits[count] = fit; if (bestFitIdx == -1) { bestFitIdx = count; } else { // if nStat != inf, best has smallest st dev from mean if (fitIsBetter(vertPartitionedFits[bestFitIdx], vertPartitionedFits[count])) { log.fine("****==> fit=" + vertPartitionedFits[count].toString()); bestFitIdx = count; } } count++; } } if (bestFitIdx == -1) { return null; } /* nDiv=2 0: [0][1] 1: [0][1] [0] [1] 2: [0][1] 3: [0][1] [0] [1] nDiv=3 0: [0][1][2] 1: [0][1][2] 2: [0][1][2] [0] [1] [2] 3: [0][1][2] 4: [0][1][2] 5: [0][1][2] [0] [1] [2] 6: [0][1][2] 7: [0][1][2] 8: [0][1][2] [0] [1] [2] Consistent solutions for nDiv=2 would have similar solutions for comparisons 0: and 3: (which is index 0 and n+1) Consistent solutions for nDiv=3 would have similar solutions for comparisons 0: and 4: and 8: (which is index 0 and (n+1) and 2*(n+1)) OR 3: and 7: (which is index n and (2*n)+1) */ TransformationPointFit bestFit = vertPartitionedFits[bestFitIdx]; float scaleTolerance = 0.1f; float rotInDegreesTolerance = 20; float translationTolerance = 20; int idx2 = -1; int idx3 = -1; if (numberOfPartitions == 2) { if (bestFitIdx == 0) { // is this similar to vertPartitionedFits[3] ? idx2 = 3; } else if (bestFitIdx == 3) { // is this similar to vertPartitionedFits[0] ? idx2 = 0; } } else if (numberOfPartitions == 3) { if (bestFitIdx == 0) { // is this similar to vertPartitionedFits[4] and vertPartitionedFits[8] ? idx2 = 4; idx3 = 8; } else if (bestFitIdx == 4) { // is this similar to vertPartitionedFits[0] and vertPartitionedFits[8] ? idx2 = 0; idx3 = 8; } else if (bestFitIdx == 8) { // is this similar to vertPartitionedFits[0] and vertPartitionedFits[4] ? idx2 = 0; idx3 = 4; } else if (bestFitIdx == 3) { // is this similar to vertPartitionedFits[7] ? idx2 = 7; idx3 = -1; } else if (bestFitIdx == 7) { // is this similar to vertPartitionedFits[3] ? idx2 = 3; idx3 = -1; } if (idx2 > -1) { boolean fitIsSimilar = fitIsSimilar(bestFit, vertPartitionedFits[idx2], scaleTolerance, rotInDegreesTolerance, translationTolerance); if (fitIsSimilar) { log.fine("similar solutions for idx=" + Integer.toString(bestFitIdx) + " and " + Integer.toString(idx2) + ":" + " Euclidean fit" + Integer.toString(bestFitIdx) + "=" + bestFit.toString() + " Euclidean fit" + Integer.toString(idx2) + "=" + vertPartitionedFits[idx2].toString()); //TODO: combine these? } if (idx3 > -1) { fitIsSimilar = fitIsSimilar(bestFit, vertPartitionedFits[idx3], scaleTolerance, rotInDegreesTolerance, translationTolerance); if (fitIsSimilar) { log.fine("similar solutions for idx=" + Integer.toString(bestFitIdx) + " and " + Integer.toString(idx3) + ":" + " Euclidean fit" + Integer.toString(bestFitIdx) + "=" + bestFit.toString() + " Euclidean fit" + Integer.toString(idx3) + "=" + vertPartitionedFits[idx3].toString()); //TODO: combine these? } } } } if (bestFit == null) { return null; } log.info("best fit so far from partitions: " + bestFit.toString()); //TODO: if solutions are combined, this may need to be done above. // use either a finer grid search or a downhill simplex to improve the // solution which was found coursely within about 10 degrees float rot = bestFit.getParameters().getRotationInDegrees(); int rotStart = (int)rot - 10; if (rotStart < 0) { rotStart = 360 + rotStart; } int rotStop = (int)rot + 10; if (rotStop > 359) { rotStop = rotStop - 360; } int rotDelta = 1; int scaleStart = (int)(0.9 * bestFit.getScale()); if (scaleStart < 1) { scaleStart = 1; } int scaleStop = (int)(1.1 * bestFit.getScale()); int scaleDelta = 1; int nTransIntervals = 4; float transX = bestFit.getParameters().getTranslationX(); float transY = bestFit.getParameters().getTranslationY(); //TODO: revision needed here float toleranceX = bestFit.getTranslationXTolerance(); float toleranceY = bestFit.getTranslationYTolerance(); float dx = (image2Width/toleranceGridFactor); float dy = (image2Height/toleranceGridFactor); if (toleranceX < (dx/10.f)) { dx = (dx/10.f); } if (toleranceY < (dy/10.f)) { dy = (dy/10.f); } float tolTransX = 2 * toleranceX; float tolTransY = 2 * toleranceY; int transXStart = (int)(transX - dx); int transXStop = (int)(transX + dx); int transYStart = (int)(transY - dy); int transYStop = (int)(transY + dy); log.fine(String.format( "starting finer grid search with rot=%d to %d and scale=%d to %d", rotStart, rotStop, scaleStart, scaleStop)); TransformationPointFit fit = calculateTransformationWithGridSearch( unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height, rotStart, rotStop, rotDelta, scaleStart, scaleStop, scaleDelta, transXStart, transXStop, transYStart, transYStop, nTransIntervals, tolTransX, tolTransY, setsFractionOfImage); if (bestFit != null && fit != null) { log.fine(" partition compare \n **==> bestFit=" + bestFit.toString() + "\n fit=" + fit.toString()); } boolean fitIsBetter = fitIsBetter(bestFit, fit); if (fitIsBetter) { log.fine(" partition bestFit=" + fit.toString()); } else { log.fine(" partition keeping bestFit=" + bestFit.toString()); } if (fitIsBetter) { bestFit = fit; } if (bestFit.getNMaxMatchable() == 0) { int nMaxMatchable = (unmatchedLeftXY.getN() < unmatchedRightXY.getN()) ? unmatchedLeftXY.getN() : unmatchedRightXY.getN(); bestFit.setMaximumNumberMatchable(nMaxMatchable); } return bestFit; } /** * NOT READY FOR USE * * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param outputMatchedLeftXY * @param image2Width * @param outputMatchedRightXY * @param image2Height * @param useLargestToleranceForOutput use the largest tolerance for * applying the transformation to point sets during matching. the largest * tolerance is the class variable generalTolerance. * If useLargestToleranceForOutput is false, the transformation's best * fit is used during matching (which should provide a smaller but more * certain matched output). If this method is used as a precursor to * projection (epipolar) solvers of sets that do have projection components, * one might prefer to set this to true to allow more to be matched. * @return best fitting transformation between unmatched points sets * left and right */ public TransformationPointFit performMatching0( PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height, PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY, boolean useLargestToleranceForOutput) { if (unmatchedLeftXY == null || unmatchedLeftXY.getN() < 3) { throw new IllegalArgumentException( "unmatchedLeftXY cannot be null and must have at least 3 points."); } if (unmatchedRightXY == null || unmatchedRightXY.getN() < 3) { throw new IllegalArgumentException( "unmatchedRightXY cannot be null and must have at least 3 points."); } TransformationPointFit bestFit = performMatching0( unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height); if (bestFit == null) { return null; } int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; Transformer transformer = new Transformer(); PairFloatArray transformedLeft = transformer.applyTransformation2( bestFit.getParameters(), unmatchedLeftXY, image1CentroidX, image1CentroidY); float transTolX, transTolY, tolerance; if (useLargestToleranceForOutput) { tolerance = generalTolerance; transTolX = generalTolerance * (float)Math.sqrt(1./2); transTolY = transTolX; } else { transTolX = bestFit.getTranslationXTolerance(); transTolY = bestFit.getTranslationYTolerance(); tolerance = (float)Math.sqrt(transTolX*transTolX + transTolY*transTolY); } float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal( transformedLeft, unmatchedRightXY, transTolX, transTolX); matchPoints(unmatchedLeftXY, unmatchedRightXY, tolerance, matchIndexesAndDiffs, outputMatchedLeftXY, outputMatchedRightXY); int nMaxMatchable = (unmatchedLeftXY.getN() < unmatchedRightXY.getN()) ? unmatchedLeftXY.getN() : unmatchedRightXY.getN(); bestFit.setMaximumNumberMatchable(nMaxMatchable); return bestFit; } /** * Given unmatched point sets unmatchedLeftXY and unmatchedRightXY, * finds the best Euclidean transformation, then finds the best partition * solution among those, then refines the solution with a more detailed * search using all points. * * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @return best fitting transformation between unmatched left and right */ public TransformationPointFit performMatching0( PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height) { float setsFractionOfImage = 1.0f; PairIntArray part1 = unmatchedLeftXY; PairIntArray part2 = unmatchedRightXY; TransformationPointFit fit = calcTransWithRoughGrid( part1, part2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fit == null) { return null; } float nStat = (float)fit.getNumberOfMatchedPoints()/ (float)fit.getNMaxMatchable(); log.info("best fit so fars: " + fit.toString()); // use either a finer grid search or a downhill simplex to improve the // solution which was found coursely within about 10 degrees float rot = fit.getParameters().getRotationInDegrees(); int rotStart = (int)rot - 10; if (rotStart < 0) { rotStart = 360 + rotStart; } int rotStop = (int)rot + 10; if (rotStop > 359) { rotStop = rotStop - 360; } int rotDelta = 1; int scaleStart = (int)(0.9 * fit.getScale()); if (scaleStart < 1) { scaleStart = 1; } int scaleStop = (int)(1.1 * fit.getScale()); int scaleDelta = 1; int nTransIntervals = 4; float transX = fit.getParameters().getTranslationX(); float transY = fit.getParameters().getTranslationY(); //TODO: revision needed here float toleranceX = fit.getTranslationXTolerance(); float toleranceY = fit.getTranslationYTolerance(); float dx = (image2Width/toleranceGridFactor); float dy = (image2Height/toleranceGridFactor); if (toleranceX < (dx/10.f)) { dx = (dx/10.f); } if (toleranceY < (dy/10.f)) { dy = (dy/10.f); } float tolTransX = 2 * toleranceX; float tolTransY = 2 * toleranceY; int transXStart = (int)(transX - dx); int transXStop = (int)(transX + dx); int transYStart = (int)(transY - dy); int transYStop = (int)(transY + dy); log.fine(String.format( "starting finer grid search with rot=%d to %d and scale=%d to %d", rotStart, rotStop, scaleStart, scaleStop)); TransformationPointFit fit2 = calculateTransformationWithGridSearch( unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height, rotStart, rotStop, rotDelta, scaleStart, scaleStop, scaleDelta, transXStart, transXStop, transYStart, transYStop, nTransIntervals, tolTransX, tolTransY, setsFractionOfImage); if (fitIsBetter(fit, fit2)) { fit = fit2; } if (fit.getNMaxMatchable() == 0) { int nMaxMatchable = (unmatchedLeftXY.getN() < unmatchedRightXY.getN()) ? unmatchedLeftXY.getN() : unmatchedRightXY.getN(); fit.setMaximumNumberMatchable(nMaxMatchable); } return fit; } /** * NOT READY FOR USE * * @param numberOfPartitions the number of vertical partitions to make. * the maximum value accepted is 3. * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param outputMatchedLeftXY * @param image2Width * @param outputMatchedRightXY * @param image2Height * @param useLargestToleranceForOutput use the largest tolerance for * applying the transformation to point sets during matching. the largest * tolerance is the class variable generalTolerance. * If useLargestToleranceForOutput is false, the transformation's best * fit is used during matching (which should provide a smaller but more * certain matched output). If this method is used as a precursor to * projection (epipolar) solvers of sets that do have projection components, * one might prefer to set this to true to allow more to be matched. * @return best fitting transformation between unmatched points sets * left and right */ public TransformationPointFit performVerticalPartitionedMatching( final int numberOfPartitions, PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height, PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY, boolean useLargestToleranceForOutput) { if (numberOfPartitions > 3) { throw new IllegalArgumentException("numberOfPartitions max value is 3"); } if (numberOfPartitions < 1) { throw new IllegalArgumentException("numberOfPartitions min value is 1"); } TransformationPointFit bestFit = performVerticalPartitionedMatching( numberOfPartitions, unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, image2Width, image2Height); if (bestFit == null) { return null; } int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; Transformer transformer = new Transformer(); PairFloatArray transformedLeft = transformer.applyTransformation2( bestFit.getParameters(), unmatchedLeftXY, image1CentroidX, image1CentroidY); float transTolX, transTolY, tolerance; if (useLargestToleranceForOutput) { tolerance = generalTolerance; transTolX = generalTolerance * (float)Math.sqrt(1./2); transTolY = transTolX; } else { transTolX = bestFit.getTranslationXTolerance(); transTolY = bestFit.getTranslationYTolerance(); tolerance = (float)Math.sqrt(transTolX*transTolX + transTolY*transTolY); } float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal( transformedLeft, unmatchedRightXY, transTolX, transTolX); matchPoints(unmatchedLeftXY, unmatchedRightXY, tolerance, matchIndexesAndDiffs, outputMatchedLeftXY, outputMatchedRightXY); int nMaxMatchable = (unmatchedLeftXY.getN() < unmatchedRightXY.getN()) ? unmatchedLeftXY.getN() : unmatchedRightXY.getN(); bestFit.setMaximumNumberMatchable(nMaxMatchable); return bestFit; } /** * NOT READY FOR USE * * @param unmatchedLeftXY * @param unmatchedRightXY * @param image1Width * @param image1Height * @param outputMatchedLeftXY * @param image2Height * @param image2Width * @param outputMatchedRightXY * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * * @return */ public TransformationPointFit performMatching( PairIntArray unmatchedLeftXY, PairIntArray unmatchedRightXY, int image1Width, int image1Height, int image2Width, int image2Height, PairIntArray outputMatchedLeftXY, PairIntArray outputMatchedRightXY, float setsFractionOfImage) { Transformer transformer = new Transformer(); PairIntArray part1 = unmatchedLeftXY; PairIntArray part2 = unmatchedRightXY; TransformationPointFit transFit = calculateEuclideanTransformation( part1, part2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (transFit == null) { return null; } // -- filter part1 and part2 to keep only intersection region int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; int image2CentroidX = image2Width >> 1; int image2CentroidY = image2Height >> 1; PairIntArray filtered1 = new PairIntArray(); PairIntArray filtered2 = new PairIntArray(); populateIntersectionOfRegions(transFit.getParameters(), part1, part2, image1CentroidX, image1CentroidY, image2CentroidX, image2CentroidY, filtered1, filtered2); int nMaxMatchable = (filtered1.getN() < filtered2.getN()) ? filtered1.getN() : filtered2.getN(); transFit.setMaximumNumberMatchable(nMaxMatchable); if (nMaxMatchable == 0) { return transFit; } // -- transform filtered1 for matching and evaluation PairFloatArray transformedFiltered1 = transformer.applyTransformation2(transFit.getParameters(), filtered1, image1CentroidX, image1CentroidY); //TODO: consider using transFit.getTolerance() here float transTolX = generalTolerance; float tolerance = transTolX * (float)Math.sqrt(1./2); //evaluate the fit and store a statistical var: nmatched/nmaxmatchable float[][] matchIndexesAndDiffs = calculateMatchUsingOptimal( transformedFiltered1, filtered2, transTolX, transTolX); PairFloatArray part1MatchedTransformed = new PairFloatArray(); PairIntArray part2Matched = new PairIntArray(); matchPoints(transformedFiltered1, filtered2, tolerance, matchIndexesAndDiffs, part1MatchedTransformed, part2Matched); PairIntArray part1Matched = new PairIntArray(); part2Matched = new PairIntArray(); matchPoints(filtered1, filtered2, tolerance, matchIndexesAndDiffs, part1Matched, part2Matched); TransformationPointFit fit2 = evaluateFitForMatchedTransformed( transFit.getParameters(), part1MatchedTransformed, part2Matched); fit2.setTranslationXTolerance(transTolX); fit2.setTranslationYTolerance(transTolX); fit2.setMaximumNumberMatchable(nMaxMatchable); float nStat = (nMaxMatchable > 0) ? (float)part1Matched.getN()/(float)nMaxMatchable : 0; log.fine("nStat=" + nStat + " nMaxMatchable=" + nMaxMatchable + " Euclidean fit=" + fit2.toString() + " original fit=" + transFit.toString()); outputMatchedLeftXY.swapContents(part1Matched); outputMatchedRightXY.swapContents(part2Matched); return fit2; } /** * given the scale, rotation and set 1's reference frame centroids, * calculate the translation between set1 and set2 assuming that not all * points will match. transXTol and transYTol allow a tolerance when * matching the predicted position of a point in set2. * * It's expected that the invoker of this method is trying to solve for * translation for sets of points like corners in images. This assumption * means that the number of point pair combinations is always far less * than the pixel combinations of translations over x and y. * * NOTE: scale has be >= 1, so if one image has a smaller scale, it has to * be the first set given in arguments. * * ALSO NOTE: if you know a better solution exists for translation * parameters that matches fewer points, but has a small avg dist from * model and smaller standard deviation from the avg dist from model, * then transXTol and transYTol should be set to a smaller value and passed * to this method. * @param params transformation parameters to apply to matched1 * @param matched1Transformed * @param matched2 set of points from image 2 that are matched to points in * matched1 with same indexes * @return */ public TransformationPointFit evaluateFitForMatchedTransformed( TransformationParameters params, PairFloatArray matched1Transformed, PairIntArray matched2) { if (matched1Transformed == null) { throw new IllegalArgumentException( "matched1Transformed cannot be null"); } if (matched2 == null) { throw new IllegalArgumentException("matched2 cannot be null"); } if (matched1Transformed.getN() != matched2.getN()) { throw new IllegalArgumentException( "the 2 point sets must have the same length"); } double[] diff = new double[matched1Transformed.getN()]; double avg = 0; for (int i = 0; i < matched1Transformed.getN(); i++) { float transformedX = matched1Transformed.getX(i); float transformedY = matched1Transformed.getY(i); int x2 = matched2.getX(i); int y2 = matched2.getY(i); double dx = x2 - transformedX; double dy = y2 - transformedY; diff[i] = Math.sqrt(dx*dx + dy*dy); avg += diff[i]; } avg /= (double)matched2.getN(); double stdDev = 0; for (int i = 0; i < matched2.getN(); i++) { double d = diff[i] - avg; stdDev += (d * d); } stdDev = Math.sqrt(stdDev/((double)matched2.getN() - 1)); TransformationPointFit fit = new TransformationPointFit(params, matched2.getN(), avg, stdDev, Float.MAX_VALUE, Float.MAX_VALUE); return fit; } protected TransformationPointFit evaluateFitForUnMatchedTransformedGreedy( TransformationParameters params, PairFloatArray unmatched1Transformed, PairIntArray unmatched2, float tolTransX, float tolTransY) { if (unmatched1Transformed == null) { throw new IllegalArgumentException( "unmatched1Transformed cannot be null"); } if (unmatched2 == null) { throw new IllegalArgumentException( "unmatched2 cannot be null"); } int n = unmatched1Transformed.getN(); Set<Integer> chosen = new HashSet<Integer>(); double[] diffs = new double[n]; int nMatched = 0; double avg = 0; for (int i = 0; i < n; i++) { float transformedX = unmatched1Transformed.getX(i); float transformedY = unmatched1Transformed.getY(i); double minDiff = Double.MAX_VALUE; int min2Idx = -1; for (int j = 0; j < unmatched2.getN(); j++) { if (chosen.contains(Integer.valueOf(j))) { continue; } float dx = transformedX - unmatched2.getX(j); float dy = transformedY - unmatched2.getY(j); if ((Math.abs(dx) > tolTransX) || (Math.abs(dy) > tolTransY)) { continue; } float diff = (float)Math.sqrt(dx*dx + dy*dy); if (diff < minDiff) { minDiff = diff; min2Idx = j; } } if (minDiff < Double.MAX_VALUE) { diffs[nMatched] = minDiff; nMatched++; chosen.add(Integer.valueOf(min2Idx)); avg += minDiff; } } avg = (nMatched == 0) ? Double.MAX_VALUE : avg / (double)nMatched; double stDev = 0; for (int i = 0; i < nMatched; i++) { double d = diffs[i] - avg; stDev += (d * d); } stDev = (nMatched == 0) ? Double.MAX_VALUE : Math.sqrt(stDev/((double)nMatched - 1.)); TransformationPointFit fit = new TransformationPointFit(params, nMatched, avg, stDev, tolTransX, tolTransY); return fit; } protected TransformationPointFit evaluateFitForUnMatchedTransformedOptimal( TransformationParameters params, PairFloatArray unmatched1Transformed, PairIntArray unmatched2, float tolTransX, float tolTransY) { if (unmatched1Transformed == null) { throw new IllegalArgumentException( "unmatched1Transformed cannot be null"); } if (unmatched2 == null) { throw new IllegalArgumentException( "unmatched2 cannot be null"); } int n = unmatched1Transformed.getN(); float[][] matchedIndexesAndDiffs = calculateMatchUsingOptimal( unmatched1Transformed, unmatched2, tolTransX, tolTransY); int nMatched = matchedIndexesAndDiffs.length; double avg = 0; double stDev = 0; for (int i = 0; i < nMatched; i++) { avg += matchedIndexesAndDiffs[i][2]; } avg = (nMatched == 0) ? Double.MAX_VALUE : (avg / (double)nMatched); for (int i = 0; i < nMatched; i++) { double d = matchedIndexesAndDiffs[i][2] - avg; stDev += (d * d); } stDev = (nMatched == 0) ? Double.MAX_VALUE : (Math.sqrt(stDev/((double)nMatched - 1.))); TransformationPointFit fit = new TransformationPointFit(params, nMatched, avg, stDev, tolTransX, tolTransY); return fit; } private void populateIntersectionOfRegions( TransformationParameters params, PairIntArray set1, PairIntArray set2, int image1CentroidX, int image1CentroidY, int image2CentroidX, int image2CentroidY, PairIntArray filtered1, PairIntArray filtered2) { double tolerance = 20; // determine the bounds of filtered2. any points in set2 that have // x < xy2LL[0] will not be matchable, etc. // TODO: correct this to use "point inside polygon" instead of rectangle Transformer transformer = new Transformer(); double[] xy2LL = transformer.applyTransformation(params, image1CentroidX, image1CentroidY, 0, 0); double[] xy2UR = transformer.applyTransformation(params, image1CentroidX, image1CentroidY, 2*image1CentroidX - 1, 2*image1CentroidY - 1); // to find lower-left and upper-left in image 1 of image // 2 boundaries requires the reverse parameters MatchedPointsTransformationCalculator tc = new MatchedPointsTransformationCalculator(); double[] x1cy1c = tc.applyTransformation(params, image1CentroidX, image1CentroidY, image1CentroidX, image1CentroidY); TransformationParameters revParams = tc.swapReferenceFrames( params, image2CentroidX, image2CentroidY, image1CentroidX, image1CentroidY, x1cy1c[0], x1cy1c[1]); double[] xy1LL = transformer.applyTransformation( revParams, image2CentroidX, image2CentroidY, 0, 0); xy1LL[0] -= tolerance; xy1LL[1] -= tolerance; double[] xy1UR = transformer.applyTransformation( revParams, image2CentroidX, image2CentroidY, 2*image2CentroidX - 1, 2*image2CentroidY - 1); xy1UR[0] += tolerance; xy1UR[1] += tolerance; for (int i = 0; i < set1.getN(); i++) { int x = set1.getX(i); // TODO: replace with an "outside polygon" check if ((x < xy1LL[0]) || (x > xy1UR[0])) { continue; } int y = set1.getY(i); if ((y < xy1LL[1]) || (y > xy1UR[1])) { continue; } filtered1.add(x, y); } for (int i = 0; i < set2.getN(); i++) { int x = set2.getX(i); // TODO: replace with an "outside polygon" check if ((x < xy2LL[0]) || (x > xy2UR[0])) { continue; } int y = set2.getY(i); if ((y < xy2LL[1]) || (y > xy2UR[1])) { continue; } filtered2.add(x, y); } } /** * given the indexes and residuals from optimal matching, populate * outputMatched1 and outputMatched2; * * @param set1 * @param set2 * @param transTolXY * @param matchedIndexesAndDiffs two dimensional array holding the matched * indexes and the distances between the model and the point for that pair. * each row holds {idx1, idx2, diff} * @param outputMatched1 the container to hold the output matching points * for image 1 that are paired with outputMatched2 as a result of running * this method. * @param outputMatched2 the container to hold the output matching points * for image 2 that are paired with outputMatched1 as a result of running * this method. */ public void matchPoints( PairIntArray set1, PairIntArray set2, float transTolXY, float[][] matchedIndexesAndDiffs, PairIntArray outputMatched1, PairIntArray outputMatched2) { if (matchedIndexesAndDiffs == null) { return; } for (int i = 0; i < matchedIndexesAndDiffs.length; i++) { int idx1 = (int)matchedIndexesAndDiffs[i][0]; int idx2 = (int)matchedIndexesAndDiffs[i][1]; float diff = matchedIndexesAndDiffs[i][2]; if (diff < transTolXY) { outputMatched1.add(set1.getX(idx1), set1.getY(idx1)); outputMatched2.add(set2.getX(idx2), set2.getY(idx2)); } } } /** * given the indexes and residuals from optimal matching, populate * outputMatched1 and outputMatched2; * * @param set1 * @param set2 * @param transTolXY * @param matchedIndexesAndDiffs two dimensional array holding the matched * indexes and the distances between the model and the point for that pair. * each row holds {idx1, idx2, diff} * @param outputMatched1 the container to hold the output matching points * for image 1 that are paired with outputMatched2 as a result of running * this method. * @param outputMatched2 the container to hold the output matching points * for image 2 that are paired with outputMatched1 as a result of running * this method. */ public void matchPoints(PairFloatArray set1, PairIntArray set2, float transTolXY, float[][] matchedIndexesAndDiffs, PairFloatArray outputMatched1, PairIntArray outputMatched2) { for (int i = 0; i < matchedIndexesAndDiffs.length; i++) { int idx1 = (int)matchedIndexesAndDiffs[i][0]; int idx2 = (int)matchedIndexesAndDiffs[i][1]; float diff = matchedIndexesAndDiffs[i][2]; if (diff < transTolXY) { outputMatched1.add(set1.getX(idx1), set1.getY(idx1)); outputMatched2.add(set2.getX(idx2), set2.getY(idx2)); } } } /** * calculate for unmatched points and if best match is not good, * reverse the order of sets and try again in order to solve for * possible scale transformation smaller than 1. * * @param scene * @param model * @param image1Width * @param image1Height * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * @param image2Width * @param image2Height * * @return */ public TransformationPointFit calculateEuclideanTransformation( PairIntArray scene, PairIntArray model, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { TransformationPointFit fit = calcTransWithRoughGrid( scene, model, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fit == null) { return null; } int nMaxMatchable = (scene.getN() < model.getN()) ? scene.getN() : model.getN(); float fracMatched = (float)fit.getNumberOfMatchedPoints()/(float)nMaxMatchable; if (fracMatched < 0.3) { // reverse the order to solve for possible scale < 1. TransformationPointFit revFit = calcTransWithRoughGrid( model, scene, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fitIsBetter(fit, revFit)) { TransformationParameters params = revFit.getParameters(); // reverse the parameters. // needs a reference point in both datasets for direct calculation int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; int image2CentroidX = image2Width >> 1; int image2CentroidY = image2Height >> 1; MatchedPointsTransformationCalculator tc = new MatchedPointsTransformationCalculator(); double[] x1y1 = tc.applyTransformation(params, image1CentroidX, image1CentroidY, image2CentroidX, image2CentroidY); TransformationParameters revParams = tc.swapReferenceFrames( params, image1CentroidX, image1CentroidY, image2CentroidX, image2CentroidY, x1y1[0], x1y1[1]); fit = new TransformationPointFit(revParams, revFit.getNumberOfMatchedPoints(), revFit.getMeanDistFromModel(), revFit.getStDevFromMean(), revFit.getTranslationXTolerance(), revFit.getTranslationYTolerance()); } } return fit; } /** * calculate for unmatched points. Note, this method does a grid search * over rotation and scale in intervals of 10 degrees and 1, * respectively and for each translation solution within those, * it has uses O(N^4) algorithm to find the best translation in x and y, * so it is a good idea to use a smaller * set of good matching points here or to use the method * which can limit the search space to known limits. * NOTE: the translation algorithm runtime complexity will be improved soon. * calculateTranslationForUnmatched0 will be used instead soon. * * @param scene * @param model * @param image1Width * @param image1Height * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * @param image2Height * @param image2Width * * @return */ public TransformationPointFit calcTransWithRoughGrid( PairIntArray scene, PairIntArray model, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { if ((scene == null) || (model == null)) { return null; } if ((scene.getN() < 3) || (model.getN() < 3)) { return null; } int rotStart = 0; int rotStop = 359; int rotDelta = 10; int scaleStart = 1; int scaleStop = 5; int scaleDelta = 1; TransformationPointFit fit = calculateTransformationWithGridSearch( scene, model, image1Width, image1Height, image2Width, image2Height, rotStart, rotStop, rotDelta, scaleStart, scaleStop, scaleDelta, setsFractionOfImage); if (fit != null) { log.fine("best from calculateTransformationWithGridSearch: " + fit.toString()); } return fit; } /** * given unordered unmatched points for a transformed set1 and * the model set2 from image1 and image2 * respectively, find the * optimal matching in set2 within tolerance and return the * matched information as a two dimensional array of * {index from set1, index from set2, diff of point in set2 from * model generation by point in set1} * * @param transformed1 * @param set2 * @param toleranceX * @param toleranceY * @return a two dimensional array holding the matched indexes and * the distances between the model and the point for that pair. * each row holds float[]{idx1, idx2, diff} */ public float[][] calculateMatchUsingOptimal( PairFloatArray transformed1, PairIntArray set2, float toleranceX, float toleranceY) { int nPoints1 = transformed1.getN(); int nPoints2 = set2.getN(); float[][] diffsAsCost = new float[nPoints1][nPoints2]; // the algorithm modifies diffsAsCost, so make a copy float[][] diffsAsCostCopy = new float[nPoints1][nPoints2]; // key = indexes i,j; value = diffX, diffY Map<PairInt, PairFloat> diffsXY = new HashMap<PairInt, PairFloat>(); int nWithinTol = 0; for (int i = 0; i < transformed1.getN(); i++) { diffsAsCost[i] = new float[nPoints2]; diffsAsCostCopy[i] = new float[nPoints2]; float x = transformed1.getX(i); float y = transformed1.getY(i); for (int j = 0; j < set2.getN(); j++) { int x2 = set2.getX(j); int y2 = set2.getY(j); float diffX = x - x2; float diffY = y - y2; if ((Math.abs(diffX) > toleranceX) || (Math.abs(diffY) > toleranceY)) { diffsAsCost[i][j] = Float.MAX_VALUE; diffsAsCostCopy[i][j] = Float.MAX_VALUE; } else { double dist = Math.sqrt(diffX*diffX + diffY*diffY); diffsAsCost[i][j] = (float)dist; diffsAsCostCopy[i][j] = (float)dist; diffsXY.put(new PairInt(i, j), new PairFloat(diffX, diffY)); nWithinTol++; } } } if (nWithinTol == 0) { return new float[0][]; } boolean transposed = false; if (nPoints1 > nPoints2) { diffsAsCostCopy = MatrixUtil.transpose(diffsAsCostCopy); transposed = true; } HungarianAlgorithm b = new HungarianAlgorithm(); int[][] match = b.computeAssignments(diffsAsCostCopy); // count the number of matches int count = 0; for (int i = 0; i < match.length; i++) { int idx1 = match[i][0]; int idx2 = match[i][1]; if (idx1 == -1 || idx2 == -1) { continue; } if (idx1 == Float.MAX_VALUE || idx2 == Float.MAX_VALUE) { continue; } if (transposed) { int swap = idx1; idx1 = idx2; idx2 = swap; } PairFloat diffXY = diffsXY.get(new PairInt(idx1, idx2)); if (diffXY == null) { continue; } if ((diffXY.getX() > toleranceX) || (diffXY.getY() > toleranceY)) { continue; } count++; } float[][] output = new float[count][]; if (count == 0) { return output; } count = 0; for (int i = 0; i < match.length; i++) { int idx1 = match[i][0]; int idx2 = match[i][1]; if (idx1 == -1 || idx2 == -1) { continue; } if (transposed) { int swap = idx1; idx1 = idx2; idx2 = swap; } PairFloat diffXY = diffsXY.get(new PairInt(idx1, idx2)); if (diffXY == null) { continue; } if ((diffXY.getX() > toleranceX) || (diffXY.getY() > toleranceY)) { continue; } output[count] = new float[3]; output[count][0] = idx1; output[count][1] = idx2; output[count][2] = diffsAsCost[idx1][idx2]; count++; } return output; } /** * Calculate for unmatched points the Euclidean transformation to transform * set1 into the reference frame of set2. Note, this method does a grid * search over rotation and scale in the given intervals, and for each * translation solution within those, it uses an O(N^2) algorithm to find * the best translation in x and y. * If there are solutions with similar fits and different parameters, they * are retained and compared with finer grid searches to decide among * them so the total runtime complexity is * larger than O(N^2) but smaller than O(N^3). * The constant factors in the runtime are roughly * ((scaleStop - scaleStart)/scaleDelta) * times (number of rotation intervals) * times (number of grid search cells which is 10*10 at best). * * @param set1 * @param set2 * @param image1Width * @param image1Height * @param image2Width * @param rotStart start of rotation search in degrees * @param rotStop stop (exclusive) or rotations search in degrees * @param image2Height * @param rotDelta change in rotation to add to reach next step in rotation * search in degrees * @param scaleStart * @param scaleStop * @param scaleDelta * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * * @return */ public TransformationPointFit calculateTransformationWithGridSearch( PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, int rotStart, int rotStop, int rotDelta, int scaleStart, int scaleStop, int scaleDelta, float setsFractionOfImage) { if (rotStart < 0 || rotStart > 359) { throw new IllegalArgumentException( "rotStart must be between 0 and 359, inclusive"); } if (rotStop < 0 || rotStop > 359) { throw new IllegalArgumentException( "rotStop must be between 0 and 359, inclusive"); } if (rotDelta < 1) { throw new IllegalArgumentException( "rotDelta must be > 0"); } if (!(scaleStart > 0)) { throw new IllegalArgumentException("scaleStart must be > 0"); } if (!(scaleStop > 0)) { throw new IllegalArgumentException("scaleStop must be > 0"); } if (!(scaleDelta > 0)) { throw new IllegalArgumentException("scaleDelta must be > 0"); } float tolTransX = generalTolerance;//4.0f * image1CentroidX * 0.02f; float tolTransY = generalTolerance;//4.0f * image1CentroidY * 0.02f; if (tolTransX < minTolerance) { tolTransX = minTolerance; } if (tolTransY < minTolerance) { tolTransY = minTolerance; } // rewrite the rotation points into array because start is sometimes // higher number than stop in unit circle int[] rotation = MiscMath.writeDegreeIntervals(rotStart, rotStop, rotDelta); int nMaxMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); TransformationPointFit bestFit = null; List<TransformationPointFit> similarToBestFit = new ArrayList<TransformationPointFit>(); TransformationPointFit bestFitForScale = null; for (int scale = scaleStart; scale <= scaleStop; scale += scaleDelta) { for (int rot : rotation) { float rotationInRadians = (float)(rot*Math.PI/180.f); TransformationPointFit fit = calculateTranslationForUnmatched0( set1, set2, image1Width, image1Height, image2Width, image2Height, rotationInRadians, scale, setsFractionOfImage); TransformationPointFit[] reevalFits = new TransformationPointFit[2]; boolean[] fitIsBetter = new boolean[1]; reevaluateFitsForCommonTolerance(bestFit, fit, set1, set2, image1Width, image1Height, reevalFits, fitIsBetter); bestFit = reevalFits[0]; fit = reevalFits[1]; if (bestFit != null && fit != null) { log.fine(" rot compare \n **==> bestFit=" + bestFit.toString() + "\n fit=" + fit.toString()); } int areSimilar = fitsAreSimilarWithDiffParameters(bestFit, fit); //0==same fit; 1==similar fits; -1==different fits if (areSimilar == 0) { //no need to recheck for convergence or change bestFit continue; } else if (areSimilar == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit); } //TODO: temporary debugging: if (!fitIsBetter[0] && (bestFit != null)) { log.fine("**==> rot keeping bestFit=" + bestFit.toString()); } if (fitIsBetter[0]) { log.fine("**==> rot fit=" + fit.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit; int bestNMatches = bestFit.getNumberOfMatchedPoints(); double bestAvg = bestFit.getMeanDistFromModel(); double bestS = bestFit.getStDevFromMean(); float fracMatched = (float)bestNMatches/(float)nMaxMatchable; boolean converged = false; if ((bestAvg < 1) && (bestS < 1)) { if (fracMatched > 0.9) { converged = true; } } else if ((bestAvg < 0.5) && (bestS < 0.5)) { if (nMaxMatchable > 10 && bestNMatches > 10) { converged = true; } } if (converged) { log.fine("** converged"); similarToBestFit.add(0, bestFit); for (TransformationPointFit fit2 : similarToBestFit) { if (fit2.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot2 = fit2.getParameters().getRotationInRadians(); while (rot2 >= 2*Math.PI) { rot2 -= 2*Math.PI; } fit2.getParameters().setRotationInRadians(rot2); } fit2.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBest( similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } log.fine(" bestFit=" + bestFit.toString()); return bestFit; } else { if (bestFit.getNumberOfMatchedPoints() == 0) { continue; } /* TODO: this might be better to perform at the end of the method right before returning the best result */ int nIntervals = 3; TransformationPointFit fit2 = finerGridSearch( nIntervals, bestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage ); //0==same fit; 1==similar fits; -1==different fits int areSimilar2 = fitsAreSimilarWithDiffParameters(bestFit, fit2); if (areSimilar2 == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit2); } boolean fitIsBetter2 = fitIsBetter(bestFit, fit2); if (fitIsBetter2) { log.fine("***==> fit=" + fit2.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit2; } } } } if (fitIsBetter(bestFitForScale, bestFit)) { bestFitForScale = bestFit; } else { log.fine("previous scale solution was better, so end scale iter"); // revert to previous scale bestFit = bestFitForScale; //TODO: revisit this with tests // scale was probably smaller so return best solution break; } } similarToBestFit.add(0, bestFit); for (TransformationPointFit fit : similarToBestFit) { if (fit.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot = fit.getParameters().getRotationInRadians(); while (rot >= 2*Math.PI) { rot -= 2*Math.PI; } fit.getParameters().setRotationInRadians(rot); } fit.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBest(similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } if (bestFit != null) { bestFit.setMaximumNumberMatchable(nMaxMatchable); log.fine(" bestFit=" + bestFit.toString()); } return bestFit; } /** * Calculate for matched points the Euclidean transformation to transform * set1 into the reference frame of set2. * @param set1 * @param set2 * @param image1Width * @param image1Height * @param image2Width * @param rotStart start of rotation search in degrees * @param rotStop stop (exclusive) or rotations search in degrees * @param image2Height * @param rotDelta change in rotation to add to reach next step in rotation * search in degrees * @param scaleStart * @param scaleStop * @param scaleDelta * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * * @return */ public TransformationPointFit calculateTransformationWithGridSearchForMatched( PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, int rotStart, int rotStop, int rotDelta, int scaleStart, int scaleStop, int scaleDelta, float setsFractionOfImage) { if (rotStart < 0 || rotStart > 359) { throw new IllegalArgumentException( "rotStart must be between 0 and 359, inclusive"); } if (rotStop < 0 || rotStop > 359) { throw new IllegalArgumentException( "rotStop must be between 0 and 359, inclusive"); } if (rotDelta < 1) { throw new IllegalArgumentException( "rotDelta must be > 0"); } if (!(scaleStart > 0)) { throw new IllegalArgumentException("scaleStart must be > 0"); } if (!(scaleStop > 0)) { throw new IllegalArgumentException("scaleStop must be > 0"); } if (!(scaleDelta > 0)) { throw new IllegalArgumentException("scaleDelta must be > 0"); } // rewrite the rotation points into array because start is sometimes // higher number than stop in unit circle int[] rotation = MiscMath.writeDegreeIntervals(rotStart, rotStop, rotDelta); Transformer transformer = new Transformer(); int nMaxMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); TransformationPointFit bestFit = null; List<TransformationPointFit> similarToBestFit = new ArrayList<TransformationPointFit>(); TransformationPointFit bestFitForScale = null; for (int scale = scaleStart; scale <= scaleStop; scale += scaleDelta) { for (int rot : rotation) { float rotationInRadians = (float)(rot*Math.PI/180.f); TransformationParameters params = calculateTranslationForMatched(set1, set2, rotationInRadians, scale, image1Width, image1Height, image2Width, image2Height); int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray allPoints1Tr = transformer.applyTransformation( params, image1CentroidX, image1CentroidY, set1); TransformationPointFit fit = evaluateFitForMatchedTransformed( params, allPoints1Tr, set2); //0==same fit; 1==similar fits; -1==different fits int areSimilar = fitsAreSimilarWithDiffParameters(bestFit, fit); if (areSimilar == 0) { //no need to recheck for convergence or change bestFit continue; } else if (areSimilar == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit); } boolean fitIsBetter = fitIsBetter(bestFit, fit); if (fitIsBetter) { log.fine("**==> fit=" + fit.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit; int bestNMatches = bestFit.getNumberOfMatchedPoints(); double bestAvg = bestFit.getMeanDistFromModel(); double bestS = bestFit.getStDevFromMean(); float fracMatched = (float)bestNMatches/(float)nMaxMatchable; boolean converged = false; if ((bestAvg < 1) && (bestS < 1)) { if (fracMatched > 0.9) { converged = true; } } else if ((bestAvg < 0.5) && (bestS < 0.5)) { if (nMaxMatchable > 10 && bestNMatches > 10) { converged = true; } } if (converged) { log.fine("** converged"); similarToBestFit.add(0, bestFit); for (TransformationPointFit fit2 : similarToBestFit) { if (fit2.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot2 = fit2.getParameters().getRotationInRadians(); while (rot2 >= 2*Math.PI) { rot2 -= 2*Math.PI; } fit2.getParameters().setRotationInRadians(rot2); } fit2.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBestForMatched( similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } log.fine(" bestFit=" + bestFit.toString()); return bestFit; } else { if (bestFit.getNumberOfMatchedPoints() == 0) { continue; } /* TODO: this might be better to perform at the end of the method right before returning the best result */ int nIntervals = 3; TransformationPointFit fit2 = finerGridSearchForMatched( nIntervals, bestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage ); //0==same fit; 1==similar fits; -1==different fits int areSimilar2 = fitsAreSimilarWithDiffParameters(bestFit, fit2); if (areSimilar2 == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit2); } boolean fitIsBetter2 = fitIsBetter(bestFit, fit2); if (fitIsBetter2) { log.fine("***==> fit=" + fit2.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit2; } } } } if (fitIsBetter(bestFitForScale, bestFit)) { bestFitForScale = bestFit; } else { log.fine("previous scale solution was better, so end scale iter"); // revert to previous scale bestFit = bestFitForScale; //TODO: revisit this with tests // scale was probably smaller so return best solution break; } } similarToBestFit.add(0, bestFit); for (TransformationPointFit fit : similarToBestFit) { if (fit.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot = fit.getParameters().getRotationInRadians(); while (rot >= 2*Math.PI) { rot -= 2*Math.PI; } fit.getParameters().setRotationInRadians(rot); } fit.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBestForMatched(similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } if (bestFit != null) { bestFit.setMaximumNumberMatchable(nMaxMatchable); log.fine(" bestFit=" + bestFit.toString()); } return bestFit; } /** * Calculate for unmatched points the Euclidean transformation to transform * set1 into the reference frame of set2. Note, this method does a grid * search over rotation and scale in the given intervals, and for each * translation solution within those, it uses an O(N^2) algorithm to find * the best translation in x and y. * If there are solutions with similar fits and different parameters, they * are retained and compared with finer grid searches to decide among * them so the total runtime complexity is * larger than O(N^2) but smaller than O(N^3). * The constant factors in the runtime are roughly * ((scaleStop - scaleStart)/scaleDelta) * times (number of rotation intervals) * times (number of grid search cells which is 10*10 at best). * * @param set1 * @param set2 * @param image1Width * @param image1Height * @param image2Width * @param rotStart start of rotation search in degrees * @param rotStop stop (exclusive) or rotations search in degrees * @param image2Height * @param rotDelta change in rotation to add to reach next step in rotation * search in degrees * @param scaleStart * @param scaleStop * @param scaleDelta * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * * @return */ public TransformationPointFit calculateTransformationWithGridSearch( PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, int rotStart, int rotStop, int rotDelta, int scaleStart, int scaleStop, int scaleDelta, int transXStart, int transXStop, int transYStart, int transYStop, int nTransIntervals, float tolTransX, float tolTransY, float setsFractionOfImage) { if (rotStart < 0 || rotStart > 359) { throw new IllegalArgumentException( "rotStart must be between 0 and 359, inclusive"); } if (rotStop < 0 || rotStop > 359) { throw new IllegalArgumentException( "rotStop must be between 0 and 359, inclusive"); } if (rotDelta < 1) { throw new IllegalArgumentException( "rotDelta must be > 0"); } if (!(scaleStart > 0)) { throw new IllegalArgumentException("scaleStart must be > 0"); } if (!(scaleStop > 0)) { throw new IllegalArgumentException("scaleStop must be > 0"); } if (!(scaleDelta > 0)) { throw new IllegalArgumentException("scaleDelta must be > 0"); } // rewrite the rotation points into array because start is sometimes // higher number than stop in unit circle int[] rotation = MiscMath.writeDegreeIntervals(rotStart, rotStop, rotDelta); boolean setsAreMatched = false; Transformer transformer = new Transformer(); int nMaxMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); TransformationPointFit bestFit = null; List<TransformationPointFit> similarToBestFit = new ArrayList<TransformationPointFit>(); TransformationPointFit bestFitForScale = null; for (int scale = scaleStart; scale <= scaleStop; scale += scaleDelta) { for (int rot : rotation) { float rotationInRadians = (float)(rot*Math.PI/180.f); TransformationPointFit fit = calculateTranslationForUnmatched0( set1, set2, image1Width, image1Height, image2Width, image2Height, rotationInRadians, scale, transXStart, transXStop, transYStart, transYStop, nTransIntervals, tolTransX, tolTransY, setsFractionOfImage); //0==same fit; 1==similar fits; -1==different fits int areSimilar = fitsAreSimilarWithDiffParameters(bestFit, fit); if (areSimilar == 0) { //no need to recheck for convergence or change bestFit continue; } else if (areSimilar == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit); } boolean fitIsBetter = fitIsBetter(bestFit, fit); if (fitIsBetter) { log.fine("**==> fit=" + fit.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit; int bestNMatches = bestFit.getNumberOfMatchedPoints(); double bestAvg = bestFit.getMeanDistFromModel(); double bestS = bestFit.getStDevFromMean(); float fracMatched = (float)bestNMatches/(float)nMaxMatchable; boolean converged = false; if ((bestAvg < 1) && (bestS < 1)) { if (fracMatched > 0.9) { converged = true; } } else if ((bestAvg < 0.5) && (bestS < 0.5)) { if (nMaxMatchable > 10 && bestNMatches > 10) { converged = true; } } if (converged) { log.fine("** converged"); similarToBestFit.add(0, bestFit); for (TransformationPointFit fit2 : similarToBestFit) { if (fit2.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot2 = fit2.getParameters().getRotationInRadians(); while (rot2 >= 2*Math.PI) { rot2 -= 2*Math.PI; } fit2.getParameters().setRotationInRadians(rot2); } fit2.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBest( similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } log.fine(" bestFit=" + bestFit.toString()); return bestFit; } else { if (bestFit.getNumberOfMatchedPoints() == 0) { continue; } /* TODO: this might be better to perform at the end of the method right before returning the best result */ int nIntervals = 3; TransformationPointFit fit2 = finerGridSearch( nIntervals, bestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage ); //0==same fit; 1==similar fits; -1==different fits int areSimilar2 = fitsAreSimilarWithDiffParameters(bestFit, fit2); if (areSimilar2 == 1) { log.fine("fit was similar to bestFit"); if (similarToBestFit.isEmpty()) { similarToBestFit.add(bestFit); } similarToBestFit.add(fit2); } boolean fitIsBetter2 = fitIsBetter(bestFit, fit2); if (fitIsBetter2) { log.fine("***==> fit=" + fit2.toString()); if (areSimilar == -1) { log.fine("clear similarToBestFit"); similarToBestFit.clear(); } bestFit = fit2; } } } } if (fitIsBetter(bestFitForScale, bestFit)) { bestFitForScale = bestFit; log.fine(" ==> bestFitForScale=" + bestFitForScale.toString()); } else { log.fine("previous scale solution was better, so end scale iter"); // revert to previous scale bestFit = bestFitForScale; //TODO: revisit this with tests // scale was probably smaller so return best solution break; } } similarToBestFit.add(0, bestFit); for (TransformationPointFit fit : similarToBestFit) { if (fit.getParameters().getRotationInRadians() > 2.*Math.PI) { float rot = fit.getParameters().getRotationInRadians(); while (rot >= 2*Math.PI) { rot -= 2*Math.PI; } fit.getParameters().setRotationInRadians(rot); } fit.setMaximumNumberMatchable(nMaxMatchable); } bestFit = finerGridSearchToDistinguishBest(similarToBestFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); log.fine("**==> deciding among " + similarToBestFit.size() + " similar fits:"); for (TransformationPointFit sFit : similarToBestFit) { log.fine(" sFit=" + sFit.toString()); } if (bestFit != null) { bestFit.setMaximumNumberMatchable(nMaxMatchable); log.fine(" bestFit=" + bestFit.toString()); } return bestFit; } protected TransformationPointFit[] evaluateTranslationsOverGrid( PairIntArray set1, PairIntArray set2, final int image1Width, final int image1Height, final int image2Width, final int image2Height, final float rotationInRadians, final float scale, int transXStart, int transXStop, int transXDelta, int transYStart, int transYStop, int transYDelta, float tolTransX, float tolTransY, final boolean setsAreMatched, final float setsFractionOfImage, final int numberOfBestToReturn) { /* _____ | | |_____| largest negative or positive translationX of set1 is the width of set2 _____ | | |_____| */ if (transXDelta < 1) { throw new IllegalArgumentException( "transXDelta must be greater than 0"); } if (rotationInRadians < 0 || rotationInRadians > 359) { throw new IllegalArgumentException( "rotation must be between 0 and 359, inclusive"); } if (scale < 1) { // numerical errors in rounding to integer can give wrong solutions //throw new IllegalStateException("scale cannot be smaller than 1"); log.severe("scale cannot be smaller than 1"); return null; } int nMaxMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); if (nMaxMatchable == 0) { return null; } int nTranslations = (((transXStop - transXStart)/transXDelta) + 1) * (((transYStop - transYStart)/transYDelta) + 1); if (nTranslations == 0) { return null; } Transformer transformer = new Transformer(); int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; int count = 0; TransformationPointFit[] fits = new TransformationPointFit[nTranslations]; for (float transX = transXStart; transX <= transXStop; transX += transXDelta) { for (float transY = transYStart; transY <= transYStop; transY += transYDelta) { float tx0 = transX + (transXDelta/2); float ty0 = transY + (transYDelta/2); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationInRadians); params.setScale(scale); params.setTranslationX(tx0); params.setTranslationY(ty0); PairFloatArray allPoints1Tr = transformer.applyTransformation( params, image1CentroidX, image1CentroidY, set1); TransformationPointFit fit; if (setsAreMatched) { fit = evaluateFitForMatchedTransformed(params, allPoints1Tr, set2); } else { // default is to use greedy matching but use optimal for small sets if (nMaxMatchable <= 10) { fit = evaluateFitForUnMatchedTransformedOptimal(params, allPoints1Tr, set2, tolTransX, tolTransY); } else { fit = evaluateFitForUnMatchedTransformedGreedy(params, //fit = evaluateFitForUnMatchedTransformedOptimal(params, allPoints1Tr, set2, tolTransX, tolTransY); } } fits[count] = fit; count++; } } // sort the fits sortByDescendingMatches(fits, 0, (fits.length - 1)); fits = Arrays.copyOf(fits, numberOfBestToReturn); return fits; } /** * given the scale, rotation and set 1's reference frame centroids, * calculate the translation between set1 and set2 assuming that not all * points will match. transXTol and transYTol allow a tolerance when * matching the predicted position of a point in set2. * * It's expected that the invoker of this method is trying to solve for * translation for sets of points like corners in images. This assumption * means that the number of point pair combinations is always far less * than the pixel combinations of translations over x and y. * * NOTE: scale has be >= 1, so if one image has a smaller scale, it has to * be the first set given in arguments. * * This method is in progress... * * @param set1 set of points from image 1 to match to image2. * @param set2 set of points from image 2 to be matched with image 1 * @param rotationInRadians given in radians with value between 0 and 2*pi, * exclusive * @param scale * @param image1Width width of image 1, used to derive range of x * translations in case centroidX1 is ever used as a non-center reference. * @param image1Height height of image 1, used to derive range of y * translations in case centroidY1 is ever used as a non-center reference. * @param image2Width width of image 2, used to derive range of x * translations * @param image2Height height of image 2, used to derive range of y * translations * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * @return */ public TransformationPointFit calculateTranslationForUnmatched0( PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float rotationInRadians, float scale, float setsFractionOfImage) { if (set1 == null) { throw new IllegalArgumentException("set1 cannot be null"); } if (set2 == null) { throw new IllegalArgumentException("set2 cannot be null"); } if (set1.getN() < 2) { return null; } if (set2.getN() < 2) { return null; } if (scale < 1) { // numerical errors in rounding to integer can give wrong solutions //throw new IllegalStateException("scale cannot be smaller than 1"); log.severe("scale cannot be smaller than 1"); return null; } int bestTransXStart = -1*image2Width + 1; int bestTransXStop = image2Width - 1; int bestTransYStart = -1*image2Width + 1; int bestTransYStop = image2Width - 1; // TODO: consider using point density to estimate this int nIntervals = 11; int dx = (bestTransXStop - bestTransXStart)/nIntervals; int dy = (bestTransYStop - bestTransYStart)/nIntervals; /*TODO: The comparisons seem to need same tolerance used when comparing the fits, so no longer decreasing these upon decreased cell size or smaller mean distance from model. If need to change this back to a tolerance that does decrease with grid cell size, then would need to add a step to the comparisons of bestFit and fit where this method is used. An extra step would be needed to re-do the evalation of whichever had a larger tolerance in it's fit using the lower tolerance. Then the comparison would be correct at that level and finer here where needed. */ float tolTransX = (int)(0.5*dx/toleranceGridFactor); float tolTransY = (int)(0.5*dy/toleranceGridFactor); /*when tolerance is too high, mean dist from model becomes more important than the number of matches*/ TransformationPointFit fit = calculateTranslationForUnmatched0( set1, set2, image1Width, image1Height, image2Width, image2Height, rotationInRadians, scale, bestTransXStart, bestTransXStop, bestTransYStart, bestTransYStop, nIntervals, tolTransX, tolTransY, setsFractionOfImage); return fit; } /** * given the scale, rotation and set 1's reference frame centroids, * calculate the translation between set1 and set2 assuming that not all * points will match. transXTol and transYTol allow a tolerance when * matching the predicted position of a point in set2. * * It's expected that the invoker of this method is trying to solve for * translation for sets of points like corners in images. This assumption * means that the number of point pair combinations is always far less * than the pixel combinations of translations over x and y. * * NOTE: scale has be >= 1, so if one image has a smaller scale, it has to * be the first set given in arguments. * * This method is in progress... * * @param set1 set of points from image 1 to match to image2. * @param set2 set of points from image 2 to be matched with image 1 * @param rotationInRadians given in radians with value between 0 and 2*pi, * exclusive * @param scale * @param transXStart * @param transXStop * @param image1Width width of image 1, used to derive range of x * translations in case centroidX1 is ever used as a non-center reference. * @param transYStop * @param transYStart * @param nTransIntervals * @param image1Height height of image 1, used to derive range of y * translations in case centroidY1 is ever used as a non-center reference. * @param image2Width width of image 2, used to derive range of x * translations * @param image2Height height of image 2, used to derive range of y * translations * @param setsFractionOfImage the fraction of their images that set 1 * and set2 were extracted from. If set1 and set2 were derived from the * images without using a partition method, this is 1.0, else if the * quadrant partitioning was used, this is 0.25. The variable is used * internally in determining histogram bin sizes for translation. * @return */ public TransformationPointFit calculateTranslationForUnmatched0( PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float rotationInRadians, float scale, int transXStart, int transXStop, int transYStart, int transYStop, int nTransIntervals, float tolTransX, float tolTransY, float setsFractionOfImage) { if (set1 == null) { throw new IllegalArgumentException("set1 cannot be null"); } if (set2 == null) { throw new IllegalArgumentException("set2 cannot be null"); } if (set1.getN() < 2) { return null; } if (set2.getN() < 2) { return null; } int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray scaledRotatedSet1 = scaleAndRotate(set1, rotationInRadians, scale, image1CentroidX, image1CentroidY); if (scale < 1) { // numerical errors in rounding to integer can give wrong solutions //throw new IllegalStateException("scale cannot be smaller than 1"); log.severe("scale cannot be smaller than 1"); return null; } int maxNMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); TransformationPointFit bestFit = null; int bestTransXStart = transXStart; int bestTransXStop = transXStop; int bestTransYStart = transYStart; int bestTransYStop = transYStop; int nIntervals = nTransIntervals; int dx = (bestTransXStop - bestTransXStart)/nIntervals; int dy = (bestTransYStop - bestTransYStart)/nIntervals; float cellFactor = 1.25f; int limit = 1; boolean setsAreMatched = false; int nIter = 0; while ((dx > limit) && (dy > limit)) { if (nIter > 0) { tolTransX = dx; tolTransY = dy; } if (bestFit == null) { if (Math.abs(rotationInRadians - 0.34906584) < 0.1) { if (set1.getN()==36 && set2.getN()==34) { int z = 1; } } } TransformationPointFit fit = calculateTranslationFromGridThenDownhillSimplex( scaledRotatedSet1, set1, set2, image1Width, image1Height, image2Width, image2Height, rotationInRadians, scale, bestTransXStart, bestTransXStop, dx, bestTransYStart, bestTransYStop, dy, tolTransX, tolTransY, setsAreMatched, setsFractionOfImage); if (bestFit != null && fit != null) { log.fine(" * compare \n ==> bestFit=" + bestFit.toString() + "\n fit=" + fit.toString()); } boolean fitIsBetter = fitIsBetter(bestFit, fit); if (!fitIsBetter && (bestFit != null)) { log.fine(" * keeping bestFit=" + bestFit.toString()); } if (fitIsBetter) { if (bestFit == null) { log.fine(" *==> new cycle fit=" + fit.toString()); } else { log.fine(" *==> fit=" + fit.toString()); } bestFit = fit; float transX = bestFit.getParameters().getTranslationX(); float transY = bestFit.getParameters().getTranslationY(); log.fine(String.format(" previous X translation range %d:%d", bestTransXStart, bestTransXStop)); log.fine(String.format(" previous Y translation range %d:%d", bestTransYStart, bestTransYStop)); log.fine(String.format(" previous cell size dx=%d dy=%d", dx, dy)); bestTransXStart = (int)(transX - cellFactor*dx); bestTransXStop = (int)(transX + cellFactor*dx); bestTransYStart = (int)(transY - cellFactor*dy); bestTransYStop = (int)(transY + cellFactor*dy); dx = (bestTransXStop - bestTransXStart)/nIntervals; dy = (bestTransYStop - bestTransYStart)/nIntervals; log.fine(String.format(" next X translation range %d:%d", bestTransXStart, bestTransXStop)); log.fine(String.format(" next Y translation range %d:%d", bestTransYStart, bestTransYStop)); log.fine(String.format(" next cell size dx=%d dy=%d", dx, dy)); } else { log.fine(" end scale, rot iteration"); /* TODO: when the nelder-mead didn't produce a better result, we arrive here and may need to do a grid search over the final result using a search range of the final transX and transY plus and minus the last dx,dy (or the half of those if tests pass). */ break; } nIter++; } if (bestFit != null) { bestFit.setMaximumNumberMatchable(maxNMatchable); } if (bestFit != null) { log.fine(" * returning bestFit=" + bestFit.toString()); if (bestFit.getNumberOfMatchedPoints() == 35) { if (Math.abs(bestFit.getMeanDistFromModel() - 3.0) < 0.01) { if (Math.abs(bestFit.getStDevFromMean() - 0.0) < 0.01) { if (Math.abs(bestFit.getParameters().getRotationInDegrees() - 18) < 0.01) { int z = 1; } } } } } return bestFit; } private TransformationPointFit calculateTranslationFromGridThenDownhillSimplex( PairFloatArray scaledRotatedSet1, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float rotationInRadians, float scale, int transXStart, int transXStop, int transXDelta, int transYStart, int transYStop, int transYDelta, float tolTransX, float tolTransY, boolean setsAreMatched, float setsFractionOfImage) { if (scaledRotatedSet1 == null) { throw new IllegalArgumentException("scaledRotatedSet1 cannot be null"); } if (set1 == null) { throw new IllegalArgumentException("set1 cannot be null"); } if (set2 == null) { throw new IllegalArgumentException("set2 cannot be null"); } if (scaledRotatedSet1.getN() != set1.getN()) { throw new IllegalArgumentException( "scaledRotatedSet1 has to be the same length as set1"); } if (tolTransX < 1) { throw new IllegalArgumentException("tolTransX should be > 0"); } if (tolTransY < 1) { throw new IllegalArgumentException("tolTransY should be > 0"); } if (transXDelta == 0) { throw new IllegalArgumentException("transXDelta cannot be 0"); } if (transYDelta == 0) { throw new IllegalArgumentException("transYDelta cannot be 0"); } int numberOfBestToReturn = 10; int dsLimit = (transXStop - transXStart) / transXDelta; int maxNMatchable = (set1.getN() < set2.getN()) ? set1.getN() : set2.getN(); TransformationPointFit[] fits = evaluateTranslationsOverGrid( set1, set2, image1Width, image1Height, image2Width, image2Height, rotationInRadians, scale, transXStart, transXStop, transXDelta, transYStart, transYStop, transYDelta, tolTransX, tolTransY, setsAreMatched, setsFractionOfImage, numberOfBestToReturn); if (fits == null) { return null; } /* if the first 4 or so top fits all have nMatchedPoints=1 or 0, then don't use the downhill simplex. */ boolean tooFewMatches = true; for (int i = 0; i < 4; ++i) { TransformationPointFit fit = fits[i]; if (fit != null && fit.getNumberOfMatchedPoints() > 1) { tooFewMatches = false; break; } } if (tooFewMatches) { return fits[0]; } TransformationPointFit fit; if (transXDelta < dsLimit) { fit = fits[0]; } else { int nMaxIter = 50; if (maxNMatchable > 60) { nMaxIter = 150; } else if (maxNMatchable > 30) { nMaxIter = 100; } // the bounds are to keep the solution within the current // best range /*float boundsXHalf = (transXStop - transXStart) / 2; float boundsYHalf = (transYStop - transYStart) / 2; float boundsXCenter = (transXStart + transXStop) / 2; float boundsYCenter = (transYStart + transYStop) / 2;*/ /* the top fits solution define the region to search within further. */ //{translationXMin, translationXMax, translationYMin, translationYMax} float[] transXYMinMaxes = getTranslationMinAndMaxes(fits); float x0 = transXYMinMaxes[0] - tolTransX; //float x1 = transXYMinMaxes[1] + tolTransX; float y0 = transXYMinMaxes[2] - tolTransY; //float y1 = transXYMinMaxes[3] + tolTransY; float boundsXCenter = (transXYMinMaxes[0] + transXYMinMaxes[1])/2.f; float boundsYCenter = (transXYMinMaxes[2] + transXYMinMaxes[3])/2.f; float boundsXHalf = x0 - boundsXCenter; float boundsYHalf = y0 - boundsYCenter; fit = refineTranslationWithDownhillSimplex( scaledRotatedSet1, set2, fits, boundsXCenter, boundsYCenter, tolTransX, tolTransY, boundsXHalf, boundsYHalf, scale, rotationInRadians, setsAreMatched, nMaxIter); } if (fit != null) { fit.setMaximumNumberMatchable(maxNMatchable); } return fit; } /** * given the scale, rotation and set 1's reference frame centroids, * calculate the translation between set1 and set2 assuming that not all * points will match. transXTol and transYTol allow a tolerance when * matching the predicted position of a point in set2. * Note that the reference point for the rotation is the center of the * image 1 width and height. * * It's expected that the invoker of this method is trying to solve for * translation for sets of points like corners in images. This assumption * means that the number of point pair combinations is always far less * than the pixel combinations of translations over x and y. * * NOTE: scale has be >= 1, so if one image has a smaller scale, it has to * be the first set given in arguments. * * ALSO NOTE: if you know a better solution exists for translation * parameters that matches fewer points, but has a small avg dist from * model and smaller standard deviation from the avg dist from model, * then transXTol and transYTol should be set to a smaller value and passed * to this method. * * @param matched1 set of points from image 1 to match to image2. * @param matched2 set of points from image 2 to be matched with image 1 * @param rotationInRadians given in radians with value between 0 and 2*pi, exclusive * @param scale * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @return */ public TransformationParameters calculateTranslationForMatched( PairIntArray matched1, PairIntArray matched2, float rotationInRadians, float scale, int image1Width, int image1Height, int image2Width, int image2Height) { if (scale < 1) { // numerical errors in rounding to integer can give wrong solutions //throw new IllegalStateException("scale cannot be smaller than 1"); log.severe("scale cannot be smaller than 1"); return null; } int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; double scaleTimesCosine = scale * Math.cos(rotationInRadians); double scaleTimesSine = scale * Math.sin(rotationInRadians); double avgTransX = 0; double avgTransY = 0; for (int i = 0; i < matched1.getN(); i++) { int x = matched1.getX(i); int y = matched1.getY(i); double xr = image1CentroidX*scale + ( ((x - image1CentroidX) * scaleTimesCosine) + ((y - image1CentroidY) * scaleTimesSine)); double yr = image1CentroidY*scale + ( (-(x - image1CentroidX) * scaleTimesSine) + ((y - image1CentroidY) * scaleTimesCosine)); int x2 = matched2.getX(i); int y2 = matched2.getY(i); avgTransX += (int)Math.round(x2 - xr); avgTransY += (int)Math.round(y2 - yr); } avgTransX /= (float)matched1.getN(); avgTransY /= (float)matched1.getN(); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationInRadians); params.setScale(scale); params.setTranslationX((float)avgTransX); params.setTranslationY((float)avgTransY); return params; } protected boolean fitIsSimilar(TransformationPointFit fit1, TransformationPointFit fit2, float scaleTolerance, float rotInDegreesTolerance, float translationTolerance) { if (fit1 == null || fit2 == null) { return false; } TransformationParameters params1 = fit1.getParameters(); TransformationParameters params2 = fit2.getParameters(); float rotA = params1.getRotationInDegrees(); float rotB = params2.getRotationInDegrees(); if (rotA > rotB) { float swap = rotA; rotA = rotB; rotB = swap; } if (((rotB - rotA) > rotInDegreesTolerance) && (((rotA + 360) - rotB) > rotInDegreesTolerance)) { return false; } if ((Math.abs(params1.getScale() - params2.getScale()) <= scaleTolerance) && (Math.abs(params1.getTranslationX() - params2.getTranslationX()) <= translationTolerance) && (Math.abs(params1.getTranslationY() - params2.getTranslationY()) <= translationTolerance) ) { return true; } return false; } /** * given the transformed x y that have already been scaled and rotated, add the * transX and transY, respectively and calculated the average residual * between that and set2 and the standard deviation from the average. * Note that set2 and (scaledRotatedX, scaledRotatedY) are NOT known to be * matched points so the residuals are minimized for each point in * the model to find the matching in set2 before computing the * average and standard deviation. * * @param set2 * @param scaledRotatedSet1 the model xy points scaled and rotated * @param transX the x translation to apply to the model points * @param transY the y translation to apply to the model points * @return */ protected TransformationPointFit evaluateFitForUnMatchedGreedy( PairFloatArray scaledRotatedSet1, float transX, float transY, float tolTransX, float tolTransY, PairIntArray set2, final float scale, final float rotationRadians) { if (set2 == null) { throw new IllegalArgumentException( "set2 cannot be null"); } if (scaledRotatedSet1 == null) { throw new IllegalArgumentException( "scaledRotatedSet1 cannot be null"); } int nMaxMatchable = (scaledRotatedSet1.getN() < set2.getN()) ? scaledRotatedSet1.getN() : set2.getN(); Set<Integer> chosen = new HashSet<Integer>(); double[] diffs = new double[scaledRotatedSet1.getN()]; int nMatched = 0; double avg = 0; for (int i = 0; i < scaledRotatedSet1.getN(); i++) { float transformedX = scaledRotatedSet1.getX(i) + transX; float transformedY = scaledRotatedSet1.getY(i) + transY; double minDiff = Double.MAX_VALUE; int min2Idx = -1; for (int j = 0; j < set2.getN(); j++) { if (chosen.contains(Integer.valueOf(j))) { continue; } float dx = set2.getX(j) - transformedX; float dy = set2.getY(j) - transformedY; if ((Math.abs(dx) > tolTransX) || (Math.abs(dy) > tolTransY)) { continue; } float diff = (float)Math.sqrt(dx*dx + dy*dy); if (diff < minDiff) { minDiff = diff; min2Idx = j; } } if (minDiff < Double.MAX_VALUE) { diffs[nMatched] = minDiff; nMatched++; chosen.add(Integer.valueOf(min2Idx)); avg += minDiff; } } avg = (nMatched == 0) ? Double.MAX_VALUE : avg / (double)nMatched; double stDev = 0; for (int i = 0; i < nMatched; i++) { double d = diffs[i] - avg; stDev += (d * d); } stDev = (nMatched == 0) ? Double.MAX_VALUE : Math.sqrt(stDev/((double)nMatched - 1.)); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationRadians); params.setScale(scale); params.setTranslationX(transX); params.setTranslationY(transY); TransformationPointFit fit = new TransformationPointFit(params, nMatched, avg, stDev, tolTransX, tolTransY); fit.setMaximumNumberMatchable(nMaxMatchable); return fit; } public boolean fitIsBetter(TransformationPointFit bestFit, TransformationPointFit compareFit) { if (costIsNumAndDiff) { return fitIsBetterUseNumAndDiff(bestFit, compareFit); } if (compareFit == null) { return false; } if (bestFit == null) { return true; } int compNMatches = compareFit.getNumberOfMatchedPoints(); int bestNMatches = bestFit.getNumberOfMatchedPoints(); double compAvg = compareFit.getMeanDistFromModel(); double bestAvg = bestFit.getMeanDistFromModel(); double compS = compareFit.getStDevFromMean(); double bestS = bestFit.getStDevFromMean(); double r = bestAvg/compAvg; int diffEps = (int)Math.round(2.*Math.ceil(Math.max(bestNMatches, compNMatches)/10.)); if (diffEps == 0) { diffEps = 1; } //0==same fit; 1==similar fits; -1==different fits int areSimilar = fitsAreSimilarWithDiffParameters(bestFit, compareFit); if ((areSimilar != -1) && (Math.abs(bestNMatches - compNMatches) <= diffEps)) { // if compareFit tolerance is alot larger than bestFit, this would // not be a fair comparison, so check before returning true if ((compareFit.getTranslationXTolerance() < bestFit.getTranslationXTolerance()) &&(compareFit.getTranslationYTolerance() < bestFit.getTranslationYTolerance()) ) { return true; } } if ( (compNMatches >= 3) && (bestNMatches >= 3) && (compNMatches <= 10) && (bestNMatches <= 10) && (Math.abs(bestNMatches - compNMatches) < 2)) { if (r > 1.4) { return true; } else if (r < 0.7) { return false; } } else if ((compNMatches > 5) && (bestNMatches > 5) && (Math.abs(bestNMatches - compNMatches) <= diffEps)) { //TODO: may need to revise this if (r > 2) { return true; } else if (r < 0.5) { return false; } } else if ( (compNMatches >= 3) && (bestNMatches >= 3) && (compNMatches <= 10) && (bestNMatches <= 10) && (Math.abs(bestNMatches - compNMatches) < 3)) { if (r > 10) { return true; } else if (r < 0.1) { return false; } } else if ( (Math.abs(bestNMatches - compNMatches) < 4) && (bestNMatches >= 7) && (bestNMatches <= 15) && (compNMatches >= 7) && (compNMatches <= 15)) { if (r > 10) { return true; } else if (r < 0.1) { return false; } } if (compNMatches > bestNMatches) { return true; } else if (compNMatches == bestNMatches) { if (!Double.isNaN(compareFit.getMeanDistFromModel())) { //TODO: may need to revise this: if (Math.abs(compAvg - bestAvg) < 1.0) { if (compS < bestS) { return true; } else if (compS > bestS) { return false; } } if (compAvg < bestAvg) { return true; } else if (compAvg > bestAvg) { return false; } if (compS < bestS) { return true; } else if (compS > bestS) { return false; } } } /* TODO: altering the above so that close values in number matched, but large differences in mean dist from model will use mean diff from model for example: bestFit: nMatchedPoints=15 nMaxMatchable=15.0 meanDistFromModel=84.14178034464518 stDevFromMean=56.981437125683364 tolerance=288.4995667241114 rotationInRadians=0.05235988 rotationInDegrees=3.0000000834826057 scale=1.0 translationX=-159.04364 translationY=-63.772995 fitCompare: nMatchedPoints=14 nMaxMatchable=0.0 meanDistFromModel=4.542982544217791 stDevFromMean=0.2876419359024278 tolerance=288.4995667241114 rotationInRadians=0.06981317 rotationInDegrees=3.999999969014533 scale=1.0 translationX=-209.35757 translationY=-11.052967 can see that the fitCompare should be preferred */ return false; } /** * compare bestFit to compareFit and return * -1 if bestFit is better * 0 if they are equal * 1 if compareFit is better * @param bestFit * @param compareFit * @return */ public int compare(TransformationPointFit bestFit, TransformationPointFit compareFit) { /* if (costIsNumAndDiff) { return fitIsBetterUseNumAndDiff(bestFit, compareFit); } */ if (compareFit == null && bestFit == null) { return 0; } else if (compareFit == null) { return -1; } else if (bestFit == null) { return 1; } int compNMatches = compareFit.getNumberOfMatchedPoints(); int bestNMatches = bestFit.getNumberOfMatchedPoints(); double compAvg = compareFit.getMeanDistFromModel(); double bestAvg = bestFit.getMeanDistFromModel(); double compS = compareFit.getStDevFromMean(); double bestS = bestFit.getStDevFromMean(); double r = bestAvg/compAvg; int diffEps = (int)Math.round(2.*Math.ceil(Math.max(bestNMatches, compNMatches)/10.)); if (diffEps == 0) { diffEps = 1; } int areSimilar = fitsAreSimilarWithDiffParameters(bestFit, compareFit); if ((areSimilar != -1) && (Math.abs(bestNMatches - compNMatches) <= diffEps)) { // if compareFit tolerance is alot larger than bestFit, this would // not be a fair comparison, so check before returning true if ((compareFit.getTranslationXTolerance() < bestFit.getTranslationXTolerance()) &&(compareFit.getTranslationYTolerance() < bestFit.getTranslationYTolerance()) ) { return 1; } } if ( (compNMatches >= 3) && (bestNMatches >= 3) && (compNMatches <= 10) && (bestNMatches <= 10) && (Math.abs(bestNMatches - compNMatches) < 2)) { if (r > 1.4) { return 1; } else if (r < 0.7) { return -1; } } else if ((compNMatches > 5) && (bestNMatches > 5) && (Math.abs(bestNMatches - compNMatches) <= diffEps)) { //TODO: may need to revise this if (r > 2) { return 1; } else if (r < 0.5) { return -1; } } else if ( (compNMatches >= 3) && (bestNMatches >= 3) && (compNMatches <= 10) && (bestNMatches <= 10) && (Math.abs(bestNMatches - compNMatches) < 3)) { if (r > 10) { return 1; } else if (r < 0.1) { return -1; } } else if ( (Math.abs(bestNMatches - compNMatches) < 4) && (bestNMatches >= 7) && (bestNMatches <= 15) && (compNMatches >= 7) && (compNMatches <= 15)) { if (r > 10) { return 1; } else if (r < 0.1) { return -1; } } if (compNMatches > bestNMatches) { return 1; } else if (compNMatches == bestNMatches) { if (!Double.isNaN(compareFit.getMeanDistFromModel())) { //TODO: may need to revise this: if (Math.abs(compAvg - bestAvg) < 1.0) { if (compS < bestS) { return 1; } else if (compS > bestS) { return -1; } } if (compAvg < bestAvg) { return 1; } else if (compAvg > bestAvg) { return -1; } if (compS < bestS) { return 1; } else if (compS > bestS) { return -1; } else { return 0; } } } return -1; } public boolean fitIsBetterUseNumAndDiff(TransformationPointFit bestFit, TransformationPointFit compareFit) { if (compareFit == null) { return false; } if (bestFit == null) { if (compareFit.getNumberOfMatchedPoints() > 0) { return true; } else { return false; } } float compN = compareFit.getNumberOfMatchedPoints(); float bestN = bestFit.getNumberOfMatchedPoints(); double compAvg = compareFit.getMeanDistFromModel(); double compS = compareFit.getStDevFromMean(); double compAvgS = compAvg + compS; double bestAvg = bestFit.getMeanDistFromModel(); double bestS = bestFit.getStDevFromMean(); double bestAvgS = bestAvg + bestS; float f = 1.5f; if (!Double.isNaN(compAvg)) { if ((compN/bestN) >= f) { return true; } else if ((compN >= bestN) && (compAvg < bestAvg) && (compS < bestS)) { return true; } } return false; } public boolean fitIsBetter(ProjectiveFit bestFit, ProjectiveFit compareFit) { if (compareFit == null) { return false; } if (bestFit == null) { return true; } int nMatches = compareFit.getNumberOfPoints(); if (nMatches > bestFit.getNumberOfPoints()) { return true; } else if (nMatches == bestFit.getNumberOfPoints()) { if (!Double.isNaN(compareFit.getMeanDistFromModel()) && ( compareFit.getMeanDistFromModel() < bestFit.getMeanDistFromModel())) { return true; } else if (compareFit.getMeanDistFromModel() == bestFit.getMeanDistFromModel()) { if (compareFit.getStdDevOfMean() < bestFit.getStdDevOfMean()) { return true; } } } return false; } /** * a fitness function that tries to allow a smaller number of points roughly * fit to be seen in contrast to a larger number of points that * are not a better fit, but have better stats due to matching alot of * scattered points. * if numberOfMatched/maxMatchable is not infinite: * if the mean/10 of the comparison fit is better than the best mean/10, * a true is returned, else * compares the standard * deviation from the mean difference to the model fit and returns true * if compareFit has a smaller value. * @param bestFit * @param compareFit * @return */ protected boolean fitIsBetter2(TransformationPointFit bestFit, TransformationPointFit compareFit) { if (compareFit == null) { return false; } if (bestFit == null) { return true; } float compareNStat = (float)compareFit.getNumberOfMatchedPoints()/ (float)compareFit.getNMaxMatchable(); if (Float.isInfinite(compareNStat)) { return false; } float bestNStat = (float)bestFit.getNumberOfMatchedPoints()/ (float)bestFit.getNMaxMatchable(); if (Float.isInfinite(bestNStat)) { return true; } if ((bestFit.getNumberOfMatchedPoints() == 0) && (compareFit.getNumberOfMatchedPoints() > 0)) { return true; } else if (compareFit.getNumberOfMatchedPoints() == 0) { return false; } double bestMean = bestFit.getMeanDistFromModel(); double compareMean = compareFit.getMeanDistFromModel(); int comp = Double.compare(compareMean, bestMean); if (comp < 0) { return true; } else if (comp > 0) { return false; } double bestStdDevMean = bestFit.getStDevFromMean(); double compareStdDevMean = compareFit.getStDevFromMean(); // a smaller std dev from mean is a better fit if (Double.compare(compareStdDevMean, bestStdDevMean) < 0) { return true; } else if (compareStdDevMean == bestStdDevMean) { return (Double.compare(compareMean, bestMean) < 0); } return false; } // ======= code that needs testing and revision the most /** * refine the transformation params to make a better match of edges1 to * edges2 where the points within edges in both sets are not necessarily * 1 to 1 matches (that is, the input is not expected to be matched * already). * * TODO: improve transformEdges to find translation for all edges * via a search method rather than trying all pairs of points. * * @param edges1 * @param edges2 * @param params * @param centroidX1 * @param centroidY1 * @param centroidX2 * @param centroidY2 * @return */ public TransformationParameters refineTransformation(PairIntArray[] edges1, PairIntArray[] edges2, final TransformationParameters params, final int centroidX1, final int centroidY1, final int centroidX2, final int centroidY2) { if (edges1 == null || edges1.length == 0) { throw new IllegalArgumentException("edges1 cannot be null or empty"); } if (edges2 == null || edges2.length == 0) { throw new IllegalArgumentException("edges2 cannot be null or empty"); } //TODO: set this empirically from tests double convergence = 0; double r = params.getRotationInRadians(); double s = params.getScale(); double rMin = r - (10 * Math.PI/180); double rMax = r + (10 * Math.PI/180); double sMin = s - 1.5; double sMax = s + 1.5; // the positive offsets can be found w/ reflection? // TODO: needs testing for starter points. these are supplying the // "grid search" portion of exploring more than local space double[] drs = new double[] { -5.0 * Math.PI/180., -2.5 * Math.PI/180., -1.0 * Math.PI/180., 1.0 * Math.PI/180., 2.5 * Math.PI/180., 5.0 * Math.PI/180. }; double[] dss = new double[] { -1.0, -0.1, -0.05, 0.05 /*, 0.05, 0.1, 1.0*/ }; if (r == 0) { drs = new double[]{0}; } if (s == 1) { dss = new double[]{0}; sMin = 1; } if (sMin < 1) { sMin = 1; } if (rMin < 0) { rMin = 0; } int n = (1 + dss.length) * (1 + drs.length); TransformationPointFit[] fits = new TransformationPointFit[n]; int count = 0; for (int i = 0; i <= dss.length; i++) { double scale = (i == 0) ? s : s + dss[i - 1]; for (int j = 0; j <= drs.length; j++) { double rotation = (j == 0) ? r : r + drs[j - 1]; fits[count] = calculateTranslationAndTransformEdges( rotation, scale, edges1, edges2, centroidX1, centroidY1); if (fits[count] != null) { count++; } } } if (count < n) { fits = Arrays.copyOf(fits, count); } float alpha = 1; // > 0 float gamma = 2; // > 1 float beta = 0.5f; float tau = 0.5f; boolean go = true; int nMaxIter = 100; int nIter = 0; int bestFitIdx = 0; int worstFitIdx = fits.length - 1; int lastNMatches = Integer.MIN_VALUE; double lastAvgDistModel = Double.MAX_VALUE; int nIterSameMin = 0; while (go && (nIter < nMaxIter)) { if (fits.length == 0) { break; } sortByDescendingMatches(fits, 0, (fits.length - 1)); for (int i = (fits.length - 1); i > -1; --i) { if (fits[i] != null) { worstFitIdx = i; break; } } if (fits[bestFitIdx] == null) { break; } /*if (fits.length > 0) { log.info("best fit: n=" + fits[bestFitIdx].getNumberOfMatchedPoints() + " dm=" + fits[bestFitIdx].getMeanDistFromModel() + " params:\n" + fits[bestFitIdx].getParameters().toString()); }*/ if ((lastNMatches == fits[bestFitIdx].getNumberOfMatchedPoints()) && (Math.abs(lastAvgDistModel - fits[bestFitIdx].getMeanDistFromModel()) < 0.01)) { nIterSameMin++; /*if (nIterSameMin >= 5) { break; }*/ } else { nIterSameMin = 0; } lastNMatches = fits[bestFitIdx].getNumberOfMatchedPoints(); lastAvgDistModel = fits[bestFitIdx].getMeanDistFromModel(); // determine center for all points excepting the worse fit double rSum = 0.0; double sSum = 0.0; int c = 0; for (int i = 0; i < (fits.length - 1); i++) { if (fits[i] != null) { rSum += fits[i].getRotationInRadians(); sSum += fits[i].getScale(); c++; } } r = rSum / (double)c; s = sSum / (double)c; // "Reflection" double rReflect = r + (alpha * (r - fits[worstFitIdx].getRotationInRadians())); double sReflect = s + (alpha * (s - fits[worstFitIdx].getScale())); TransformationPointFit fitReflected = calculateTranslationAndTransformEdges( rReflect, sReflect, edges1, edges2, centroidX1, centroidY1); //TODO: consider putting back in a check for bounds int comp0 = compare(fits[bestFitIdx], fitReflected); int compLast = compare(fits[worstFitIdx], fitReflected); if ((comp0 < 1) && (compLast == 1)) { // replace last with f_refl fits[worstFitIdx] = fitReflected; } else if (comp0 == 1) { // reflected is better than best fit, so "expand" // "Expansion" double rExpansion = r + (gamma * (rReflect - r)); double sExpansion = s + (gamma * (sReflect - s)); TransformationPointFit fitExpansion = calculateTranslationAndTransformEdges( rExpansion, sExpansion, edges1, edges2, centroidX1, centroidY1); int compR = compare(fitReflected, fitExpansion); if (compR == 1) { // expansion fit is better than reflected fit fits[worstFitIdx] = fitExpansion; } else { fits[worstFitIdx] = fitReflected; } } else if (compLast < 1) { // reflected fit is worse than the worst (last) fit, so contract // "Contraction" double rContraction = r + (beta * (fits[worstFitIdx].getRotationInRadians() - r)); double sContraction = s + (beta * (fits[worstFitIdx].getScale() - s)); TransformationPointFit fitContraction = calculateTranslationAndTransformEdges( rContraction, sContraction, edges1, edges2, centroidX1, centroidY1); int compC = compare(fits[worstFitIdx], fitContraction); if (compC > -1) { fits[worstFitIdx] = fitContraction; } else { // "Reduction" for (int i = 1; i < fits.length; ++i) { if (fits[i] == null) { /*TODO: consider setting this fits[i] = new TransformationPointFit( new TransformationParameters(), 0, Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE ); */ continue; } float rReduction = (fits[bestFitIdx].getRotationInRadians() + (tau * (fits[i].getRotationInRadians() - fits[bestFitIdx].getRotationInRadians()))); float sReduction = (fits[bestFitIdx].getScale() + (tau * (fits[i].getScale() - fits[bestFitIdx].getScale()))); //NOTE: there's a possibility of a null fit. // instead of re-writing the fits array, will // assign a fake infinitely bad fit which will // fall to the bottom of the list after the next // sort. TransformationPointFit fit = calculateTranslationAndTransformEdges( rReduction, sReduction, edges1, edges2, centroidX1, centroidY1); fits[i] = fit; } } } log.finest("best fit so far: nMatches=" + fits[bestFitIdx].getNumberOfMatchedPoints() + " diff from model=" + fits[bestFitIdx].getMeanDistFromModel() ); nIter++; if ((fits[bestFitIdx].getNumberOfMatchedPoints() == convergence) && (fits[bestFitIdx].getMeanDistFromModel() == 0)) { go = false; /*} else if ((r > rMax) || (r < rMin)) { go = false;*/ } else if ((s > sMax) || (s < sMin)) { go = false; } } // additional step that's helpful if not enough iterations are used, // is to test the summed transX, transY which represent the center // of the simplex against the best fit TransformationPointFit fitAvg = calculateTranslationAndTransformEdges( r, s, edges1, edges2, centroidX1, centroidY1); int comp = compare(fits[bestFitIdx], fitAvg); if (comp == 1) { fits[bestFitIdx] = fitAvg; } // if rotation > 2PI, subtract 2PI if ((fits[bestFitIdx] != null) && (fits[bestFitIdx].getParameters().getRotationInRadians() > 2.*Math.PI)) { float rot = fits[bestFitIdx].getParameters().getRotationInRadians(); while (rot >= 2*Math.PI) { rot -= 2*Math.PI; } fits[bestFitIdx].getParameters().setRotationInRadians(rot); } return fits[bestFitIdx].getParameters(); } /** * TODO: improve transformEdges to find translation for all edges * via a search method rather than trying all pairs of points. * * Given edges1 and edges2 which we already know are matched edges due to * contour matching or other means, and given the rotation and scale, * determine the translation between the edges and return the fit. * * @param rotInRad * @param scl * @param edges1 * @param edges2 * @param centroidX1 * @param centroidY1 * @return */ private TransformationPointFit calculateTranslationAndTransformEdges( double rotInRad, double scl, PairIntArray[] edges1, PairIntArray[] edges2, int centroidX1, int centroidY1) { if (edges1 == null || edges1.length == 0) { throw new IllegalArgumentException("edges1 cannot be null or empty"); } if (edges2 == null || edges2.length == 0) { throw new IllegalArgumentException("edges2 cannot be null or empty"); } if ((edges1.length != edges2.length)) { throw new IllegalArgumentException( "edges1 and edges2 must be the same length"); } /* edges1 and edges2 are matched edges, but should be considered clouds of points rather than point to point matches within the edges. For each paired edge in edges1 and edges2, determine the implied translation by their centroids. These are combined in weighted average where the weight is the length of the edge. Then a small area surrounding the averaged translation is searched to find the best fit. */ float s = (float)scl; float scaleTimesCosine = (float)(s * Math.cos(rotInRad)); float scaleTimesSine = (float)(s * Math.sin(rotInRad)); //TODO: revisit this: float tolTransX = 2.f * centroidX1 * 0.02f; float tolTransY = 2.f * centroidY1 * 0.02f; if (tolTransX < minTolerance) { tolTransX = minTolerance; } if (tolTransY < minTolerance) { tolTransY = minTolerance; } int nTotal = 0; float[] weights = new float[edges1.length]; for (int i = 0; i < edges1.length; i++) { weights[i] = edges1[i].getN(); nTotal += edges1[i].getN(); } for (int i = 0; i < edges1.length; i++) { weights[i] /= (float)nTotal; } MiscellaneousCurveHelper curveHelper = new MiscellaneousCurveHelper(); float translationX = 0; float translationY = 0; for (int i = 0; i < edges1.length; i++) { PairIntArray edge1 = edges1[i]; PairIntArray edge2 = edges2[i]; double[] xycen1 = curveHelper.calculateXYCentroids(edge1); double[] xycen2 = curveHelper.calculateXYCentroids(edge2); double srX1 = centroidX1*s + ( ((xycen1[0] - centroidX1) * scaleTimesCosine) + ((xycen1[1] - centroidY1) * scaleTimesSine)); double srY1 = centroidY1*s + ( (-(xycen1[0] - centroidX1) * scaleTimesSine) + ((xycen1[1] - centroidY1) * scaleTimesCosine)); double tx = xycen2[0] - srX1; double ty = xycen2[1] - srY1; translationX += weights[i] * tx; translationY += weights[i] * ty; } TransformationPointFit bestFit = refineTranslationWithDownhillSimplex( edges1, edges2, translationX, translationY, tolTransX, tolTransY, 20.f, 20.f, s, (float)rotInRad, centroidX1, centroidY1); return bestFit; } /** * sort the fits by descending number of matches. * @param fits * @param idxLo * @param idxHi, upper index, inclusive */ void sortByDescendingMatches(TransformationPointFit[] fits, int idxLo, int idxHi) { if (idxLo < idxHi) { int idxMid = partition(fits, idxLo, idxHi); sortByDescendingMatches(fits, idxLo, idxMid - 1); sortByDescendingMatches(fits, idxMid + 1, idxHi); } } private int partition(TransformationPointFit[] fits, int idxLo, int idxHi) { TransformationPointFit x = fits[idxHi]; int store = idxLo - 1; for (int i = idxLo; i < idxHi; i++) { if (fitIsBetter(x, fits[i])) { store++; TransformationPointFit swap = fits[store]; fits[store] = fits[i]; fits[i] = swap; } } store++; TransformationPointFit swap = fits[store]; fits[store] = fits[idxHi]; fits[idxHi] = swap; return store; } protected PairFloatArray scaleAndRotate(PairIntArray set1, float rotation, float scale, int centroidX1, int centroidY1) { if (scale < 1) { // numerical errors in rounding to integer can give wrong solutions //throw new IllegalStateException("scale cannot be smaller than 1"); log.severe("scale cannot be smaller than 1"); } if (set1 == null) { throw new IllegalArgumentException("set1 cannot be null"); } PairFloatArray transformed1 = new PairFloatArray(); float s = scale; float scaleTimesCosine = (float)(s * Math.cos(rotation)); float scaleTimesSine = (float)(s * Math.sin(rotation)); //apply scale and rotation to set1 points for (int i = 0; i < set1.getN(); i++) { int x = set1.getX(i); int y = set1.getY(i); float sclRotX = centroidX1*s + ( ((x - centroidX1) * scaleTimesCosine) + ((y - centroidY1) * scaleTimesSine)); float sclRotY = centroidY1*s + ( (-(x - centroidX1) * scaleTimesSine) + ((y - centroidY1) * scaleTimesCosine)); transformed1.add(sclRotX, sclRotY); } return transformed1; } /** * Searches among the given translation range for the best fit to a * Euclidean transformation formed by scale, rotationRadians and the * best fitting translation X and Y given starter points fits. * Note the method is not precise so should be wrapped with a follow-up * method that further searches in the solution's local region. * @param scaledRotatedSet1 * @param set2 * @param fits * @param transX * @param transY * @param tolTransX * @param tolTransY * @param plusMinusTransX * @param plusMinusTransY * @param scale * @param rotationRadians * @param setsAreMatched * @param nMaxIter * @return */ protected TransformationPointFit refineTranslationWithDownhillSimplex( PairFloatArray scaledRotatedSet1, PairIntArray set2, TransformationPointFit[] fits, float transX, float transY, float tolTransX, float tolTransY, float plusMinusTransX, float plusMinusTransY, final float scale, final float rotationRadians, boolean setsAreMatched, int nMaxIter) { int nMaxMatchable = (scaledRotatedSet1.getN() < set2.getN()) ? scaledRotatedSet1.getN() : set2.getN(); if (nMaxMatchable == 0) { return null; } //TODO: revise this: double eps = Math.log(nMaxMatchable)/Math.log(10); float alpha = 1; // > 0 float gamma = 2; // > 1 float beta = 0.5f; float tau = 0.5f; boolean go = true; float txMin = transX - plusMinusTransX; float txMax = transX + plusMinusTransX; float tyMin = transY - plusMinusTransY; float tyMax = transY + plusMinusTransY; int nIter = 0; int bestFitIdx = 0; int worstFitIdx = fits.length - 1; TransformationParameters[] lastParams = extractParameters(fits); while (go && (nIter < nMaxIter)) { if (fits.length == 0) { break; } sortByDescendingMatches(fits, 0, (fits.length - 1)); for (int i = (fits.length - 1); i > -1; --i) { if (fits[i] != null) { worstFitIdx = i; break; } } if (fits[bestFitIdx] == null) { break; } if (nIter > 0) { TransformationParameters[] currentParams = extractParameters(fits); boolean areTheSame = areEqual(lastParams, currentParams); if (areTheSame) { break; } lastParams = currentParams; } // determine center for all points excepting the worse fit float txSum = 0.0f; float tySum = 0.0f; int c = 0; for (int i = 0; i < (fits.length - 1); ++i) { if (fits[i] != null) { txSum += fits[i].getTranslationX(); tySum += fits[i].getTranslationY(); c++; } } transX = txSum / (float)c; transY = tySum / (float)c; // "Reflection" float txReflect = transX + (alpha * (transX - fits[worstFitIdx].getTranslationX())); float tyReflect = transY + (alpha * (transY - fits[worstFitIdx].getTranslationY())); TransformationPointFit fitReflected = evaluateFit( scaledRotatedSet1, txReflect, tyReflect, tolTransX, tolTransY, set2, scale, rotationRadians, setsAreMatched); //TODO: consider putting back in a check for bounds int comp0 = compare(fits[bestFitIdx], fitReflected); int compLast = compare(fits[worstFitIdx], fitReflected); if ((comp0 < 1) && (compLast == 1)) { // replace last with f_refl fits[worstFitIdx] = fitReflected; } else if (comp0 == 1) { // reflected is better than best fit, so "expand" // "Expansion" float txExpansion = transX + (gamma * (txReflect - transX)); float tyExpansion = transY + (gamma * (tyReflect - transY)); TransformationPointFit fitExpansion = evaluateFit(scaledRotatedSet1, txExpansion, tyExpansion, tolTransX, tolTransY, set2, scale, rotationRadians, setsAreMatched); int compR = compare(fitReflected, fitExpansion); if (compR == 1) { // expansion fit is better than reflected fit fits[worstFitIdx] = fitExpansion; } else { fits[worstFitIdx] = fitReflected; } } else if (compLast < 1) { // reflected fit is worse than the worst (last) fit, so contract // "Contraction" float txContraction = transX + (beta * (fits[worstFitIdx].getTranslationX() - transX)); float tyContraction = transY + (beta * (fits[worstFitIdx].getTranslationY() - transY)); TransformationPointFit fitContraction = evaluateFit(scaledRotatedSet1, txContraction, tyContraction, tolTransX, tolTransY, set2, scale, rotationRadians, setsAreMatched); int compC = compare(fits[worstFitIdx], fitContraction); if (compC > -1) { fits[worstFitIdx] = fitContraction; } else { if (true) { // "Reduction" for (int i = 1; i < fits.length; ++i) { if (fits[i] == null) { /*TODO: consider setting this fits[i] = new TransformationPointFit( new TransformationParameters(), 0, Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE ); */ continue; } float txReduction = (fits[bestFitIdx].getTranslationX() + (tau * (fits[i].getTranslationX() - fits[bestFitIdx].getTranslationX()))); float tyReduction = (fits[bestFitIdx].getTranslationY() + (tau * (fits[i].getTranslationY() - fits[bestFitIdx].getTranslationY()))); //NOTE: there's a possibility of a null fit. // instead of re-writing the fits array, will // assign a fake infinitely bad fit which will // fall to the bottom of the list after the next // sort. TransformationPointFit fit = evaluateFit(scaledRotatedSet1, txReduction, tyReduction, tolTransX, tolTransY, set2, scale, rotationRadians, setsAreMatched); fits[i] = fit; } } } } log.finest("best fit so far: nMatches=" + fits[bestFitIdx].getNumberOfMatchedPoints() + " diff from model=" + fits[bestFitIdx].getMeanDistFromModel() ); nIter++; if ((fits[bestFitIdx].getNumberOfMatchedPoints() == nMaxMatchable) && (fits[bestFitIdx].getMeanDistFromModel() < eps)) { go = false; } else if ((transX > txMax) || (transX < txMin)) { go = false; } else if ((transY > tyMax) || (transY < tyMin)) { go = false; } } // additional step that's helpful if not enough iterations are used, // is to test the summed transX, transY which represent the center // of the simplex against the best fit TransformationPointFit fitAvg = evaluateFit(scaledRotatedSet1, transX, transY, tolTransX, tolTransY, set2, scale, rotationRadians, setsAreMatched); int comp = compare(fits[bestFitIdx], fitAvg); if (comp == 1) { fits[bestFitIdx] = fitAvg; } return fits[bestFitIdx]; } private TransformationPointFit refineTranslationWithDownhillSimplex( final PairIntArray[] edges1, final PairIntArray[] edges2, float transX, float transY, float tolTransX, float tolTransY, float plusMinusTransX, float plusMinusTransY, final float scale, final float rotationRadians, int centroidX1, int centroidY1) { int n1 = 0; for (PairIntArray edge : edges1) { n1 += edge.getN(); } int n2 = 0; for (PairIntArray edge : edges2) { n2 += edge.getN(); } int nMaxMatchable = (n1 < n2) ? n1 : n2; if (nMaxMatchable == 0) { return null; } //TODO: revise this: double eps = Math.log(nMaxMatchable)/Math.log(10); float txMin = transX - plusMinusTransX; float txMax = transX + plusMinusTransX; float tyMin = transY - plusMinusTransY; float tyMax = transY + plusMinusTransY; // the positive offsets can be found w/ reflection float[] dtx = new float[]{ -plusMinusTransX, -0.5f*plusMinusTransX, -0.25f*plusMinusTransX, -0.125f*plusMinusTransX, -0.0625f*plusMinusTransX }; float[] dty = new float[]{ -plusMinusTransY, -0.5f*plusMinusTransY, -0.25f*plusMinusTransY, -0.125f*plusMinusTransY, -0.0625f*plusMinusTransY }; int n = (1 + dtx.length) * (1 + dty.length); TransformationPointFit[] fits = new TransformationPointFit[n]; int count = 0; for (int i = 0; i <= dtx.length; i++) { float tx = (i == 0) ? transX : (transX + dtx[i - 1]); for (int j = 0; j <= dty.length; j++) { float ty = (i == 0) ? transY : (transY + dty[i - 1]); fits[count] = evaluateFit(edges1, edges2, tx, ty, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); if (fits[count] != null) { count++; } } } if (count < n) { fits = Arrays.copyOf(fits, count); } float alpha = 1; // > 0 float gamma = 2; // > 1 float beta = 0.5f; float tau = 0.5f; boolean go = true; int nMaxIter = 100; int nIter = 0; int bestFitIdx = 0; int worstFitIdx = fits.length - 1; int lastNMatches = Integer.MIN_VALUE; double lastAvgDistModel = Double.MAX_VALUE; int nIterSameMin = 0; while (go && (nIter < nMaxIter)) { if (fits.length == 0) { break; } sortByDescendingMatches(fits, 0, (fits.length - 1)); for (int i = (fits.length - 1); i > -1; --i) { if (fits[i] != null) { worstFitIdx = i; break; } } if (fits[bestFitIdx] == null) { break; } if ((lastNMatches == fits[bestFitIdx].getNumberOfMatchedPoints()) && (Math.abs(lastAvgDistModel - fits[bestFitIdx].getMeanDistFromModel()) < 0.01)) { nIterSameMin++; /*if (nIterSameMin >= 10) { break; }*/ } else { nIterSameMin = 0; } lastNMatches = fits[bestFitIdx].getNumberOfMatchedPoints(); lastAvgDistModel = fits[bestFitIdx].getMeanDistFromModel(); // determine center for all points excepting the worse fit float txSum = 0.0f; float tySum = 0.0f; int c = 0; for (int i = 0; i < (fits.length - 1); ++i) { if (fits[i] != null) { txSum += fits[i].getTranslationX(); tySum += fits[i].getTranslationY(); ++c; } } transX = txSum / (float)c; transY = tySum / (float)c; // "Reflection" float txReflect = transX + (alpha * (transX - fits[worstFitIdx].getTranslationX())); float tyReflect = transY + (alpha * (transY - fits[worstFitIdx].getTranslationY())); TransformationPointFit fitReflected = evaluateFit( edges1, edges2, txReflect, tyReflect, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); //TODO: consider putting back in a check for bounds int comp0 = compare(fits[bestFitIdx], fitReflected); int compLast = compare(fits[worstFitIdx], fitReflected); if ((comp0 < 1) && (compLast == 1)) { // replace last with f_refl fits[worstFitIdx] = fitReflected; } else if (comp0 == 1) { // reflected is better than best fit, so "expand" // "Expansion" float txExpansion = transX + (gamma * (txReflect - transX)); float tyExpansion = transY + (gamma * (tyReflect - transY)); TransformationPointFit fitExpansion = evaluateFit(edges1, edges2, txExpansion, tyExpansion, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); int compR = compare(fitReflected, fitExpansion); if (compR == 1) { // expansion fit is better than reflected fit fits[worstFitIdx] = fitExpansion; } else { fits[worstFitIdx] = fitReflected; } } else if (compLast < 1) { // reflected fit is worse than the worst (last) fit, so contract // "Contraction" float txContraction = transX + (beta * (fits[worstFitIdx].getTranslationX() - transX)); float tyContraction = transY + (beta * (fits[worstFitIdx].getTranslationY() - transY)); TransformationPointFit fitContraction = evaluateFit(edges1, edges2, txContraction, tyContraction, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); int compC = compare(fits[worstFitIdx], fitContraction); if (compC > -1) { fits[worstFitIdx] = fitContraction; } else { // "Reduction" for (int i = 1; i < fits.length; i++) { if (fits[i] == null) { /* TODO: consider setting this fits[i] = new TransformationPointFit( new TransformationParameters(), 0, Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE ); */ continue; } float txReduction = (fits[bestFitIdx].getTranslationX() + (tau * (fits[i].getTranslationX() - fits[bestFitIdx].getTranslationX()))); float tyReduction = (fits[bestFitIdx].getTranslationY() + (tau * (fits[i].getTranslationY() - fits[bestFitIdx].getTranslationY()))); //NOTE: there's a possibility of a null fit. // instead of re-writing the fits array, will // assign a fake infinitely bad fit which will // fall to the bottom of the list after the next // sort. TransformationPointFit fit = evaluateFit(edges1, edges2, txReduction, tyReduction, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); fits[i] = fit; } } } log.finest("best fit so far: nMatches=" + fits[bestFitIdx].getNumberOfMatchedPoints() + " diff from model=" + fits[bestFitIdx].getMeanDistFromModel() ); nIter++; if ((fits[bestFitIdx].getNumberOfMatchedPoints() == nMaxMatchable) && (fits[bestFitIdx].getMeanDistFromModel() < eps)) { go = false; } /*else if ((transX > txMax) || (transX < txMin)) { go = false; } else if ((transY > tyMax) || (transY < tyMin)) { go = false; }*/ } // additional step that's helpful if not enough iterations are used, // is to test the summed transX, transY which represent the center // of the simplex against the best fit TransformationPointFit fitAvg = evaluateFit(edges1, edges2, transX, transY, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1); int comp = compare(fits[bestFitIdx], fitAvg); if (comp == 1) { fits[bestFitIdx] = fitAvg; } return fits[bestFitIdx]; } protected TransformationPointFit evaluateFit( PairFloatArray scaledRotatedSet1, float transX, float transY, float tolTransX, float tolTransY, PairIntArray set2, final float scale, final float rotationRadians, boolean setsAreMatched) { if (set2 == null) { throw new IllegalArgumentException( "set2 cannot be null"); } if (scaledRotatedSet1 == null) { throw new IllegalArgumentException( "scaledTransformedSet1 cannot be null"); } if (setsAreMatched) { return evaluateFitForMatched(scaledRotatedSet1, transX, transY, set2, scale, rotationRadians); } return evaluateFitForUnMatched(scaledRotatedSet1, transX, transY, tolTransX, tolTransY, set2, scale, rotationRadians); } private TransformationPointFit evaluateFit( PairIntArray[] edges1, PairIntArray[] edges2, float translationX, float translationY, float tolTransX, float tolTransY, float scale, float rotationRadians, int centroidX1, int centroidY1) { if (edges1 == null || edges1.length == 0) { throw new IllegalArgumentException("edges1 cannot be null or empty"); } if (edges2 == null || edges2.length == 0) { throw new IllegalArgumentException("edges2 cannot be null or empty"); } int n1 = 0; for (PairIntArray edge : edges1) { n1 += edge.getN(); } int n2 = 0; for (PairIntArray edge : edges2) { n2 += edge.getN(); } int nMaxMatchable = (n1 < n2) ? n1 : n2; if (nMaxMatchable == 0) { return null; } List<Double> residuals = new ArrayList<Double>(); int nTotal = 0; for (int i = 0; i < edges1.length; i++) { PairIntArray edge1 = edges1[i]; PairIntArray edge2 = edges2[i]; nTotal += edge1.getN(); calculateTranslationResidualsForUnmatchedMultiplicity( edge1, edge2, translationX, translationY, tolTransX, tolTransY, scale, rotationRadians, centroidX1, centroidY1, residuals); } double avg = 0; for (Double diff : residuals) { avg += diff.doubleValue(); } avg /= (double)residuals.size(); double stdDev = 0; for (Double diff : residuals) { double d = diff.doubleValue() - avg; stdDev += (d * d); } stdDev = Math.sqrt(stdDev/((double)residuals.size() - 1)); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationRadians); params.setScale(scale); params.setTranslationX(translationX); params.setTranslationY(translationY); TransformationPointFit fit = new TransformationPointFit(params, residuals.size(), avg, stdDev, tolTransX, tolTransY); return fit; } /** * calculate the residuals between edge1 points and edge2 points with the * assumption that there may not be one to one point matches, but instead * will be general point matches. For that reason, a greedy search for * nearest neighbor with the possibility of multiple matches to a neighbor * is used. * * @param edge1 * @param edge2 * @param transX * @param transY * @param tolTransX * @param tolTransY * @param scale * @param rotationRadians * @param outputResiduals */ private void calculateTranslationResidualsForUnmatchedMultiplicity( PairIntArray edge1, PairIntArray edge2, float transX, float transY, float tolTransX, float tolTransY, final float scale, final float rotationRadians, int centroidX1, int centroidY1, List<Double> outputResiduals) { if (edge1 == null || edge1.getN() == 0) { throw new IllegalArgumentException( "edge1 cannot be null or empty"); } if (edge2 == null || edge2.getN() == 0) { throw new IllegalArgumentException( "edge2 cannot be null or empty"); } int nMaxMatchable = (edge1.getN() < edge2.getN()) ? edge1.getN() : edge2.getN(); if (nMaxMatchable == 0) { return; } float scaleTimesCosine = (float)(scale * Math.cos(rotationRadians)); float scaleTimesSine = (float)(scale * Math.sin(rotationRadians)); for (int i = 0; i < edge1.getN(); i++) { int x1 = edge1.getX(i); int y1 = edge1.getY(i); float transformedX = (centroidX1*scale + ( ((x1 - centroidX1) * scaleTimesCosine) + ((y1 - centroidY1) * scaleTimesSine))) + transX; float transformedY = (centroidY1*scale + ( (-(x1 - centroidX1) * scaleTimesSine) + ((y1 - centroidY1) * scaleTimesCosine))) + transY; double minDiff = Double.MAX_VALUE; for (int j = 0; j < edge2.getN(); j++) { int x2 = edge2.getX(j); int y2 = edge2.getY(j); float dx = x2 - transformedX; float dy = y2 - transformedY; if ((Math.abs(dx) > tolTransX) || (Math.abs(dy) > tolTransY)) { continue; } float diff = (float)Math.sqrt(dx*dx + dy*dy); if (diff < minDiff) { minDiff = diff; } } if (minDiff < Double.MAX_VALUE) { outputResiduals.add(Double.valueOf(minDiff)); } } } /** * given the model x y that have already been scaled and rotated, add the * transX and transY, respectively and calculated the average residual * between that and set2 and the standard deviation from the average. * Note that set2 and (scaledRotatedX, scaledRotatedY) are known to be * matched points so index 1 in set2 and index1 in scaledRotated represent * matching points. * @param set2 * @param scaledRotatedX the model x points scaled and rotated * @param scaledRotatedY the model y points scaled and rotated * @param transX the x translation to apply to the model points * @param transY the y translation to apply to the model points * @return */ private TransformationPointFit evaluateFitForMatched( PairFloatArray scaledRotatedSet1, float transX, float transY, PairIntArray set2, final float scale, final float rotationRadians) { if (set2 == null || set2.getN() == 0) { throw new IllegalArgumentException( "set2 cannot be null or empty"); } if (scaledRotatedSet1 == null || scaledRotatedSet1.getN() == 0) { throw new IllegalArgumentException( "scaledRotatedSet1 cannot be null or empty"); } if (set2.getN() != scaledRotatedSet1.getN()) { throw new IllegalArgumentException( "for matched sets, set2 must be the same length as scaledRotated" + " X and Y"); } int nMaxMatchable = (scaledRotatedSet1.getN() < set2.getN()) ? scaledRotatedSet1.getN() : set2.getN(); if (nMaxMatchable == 0) { return null; } double sum = 0; double[] diff = new double[set2.getN()]; for (int i = 0; i < set2.getN(); i++) { float transformedX = scaledRotatedSet1.getX(i) + transX; float transformedY = scaledRotatedSet1.getY(i) + transY; double dx = transformedX - set2.getX(i); double dy = transformedY - set2.getY(i); diff[i] = Math.sqrt(dx*dx + dy+dy); sum += diff[i]; } double avgDiff = sum/(double)set2.getN(); sum = 0; for (int i = 0; i < set2.getN(); i++) { sum += (diff[i] * diff[i]); } double stDev = Math.sqrt(sum/((double)set2.getN() - 1)); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationRadians); params.setScale(scale); params.setTranslationX(transX); params.setTranslationY(transY); TransformationPointFit fit = new TransformationPointFit(params, set2.getN(), avgDiff, stDev, Float.MAX_VALUE, Float.MAX_VALUE); fit.setMaximumNumberMatchable(nMaxMatchable); return fit; } /** * given the model x y that have already been scaled and rotated, add the * transX and transY, respectively and calculated the average residual * between that and set2 and the standard deviation from the average. * Note that set2 and (scaledRotatedX, scaledRotatedY) are NOT known to be * matched points so the residuals are minimized for each point in * the model to find the matching in set2 before computing the * average and standard deviation. * * @param set2 * @param scaledRotatedSet1 the model x,y points scaled and rotated * @param transX the x translation to apply to the model points * @param transY the y translation to apply to the model points * @return */ private TransformationPointFit evaluateFitForUnMatched( PairFloatArray scaledRotatedSet1, float transX, float transY, float tolTransX, float tolTransY, PairIntArray set2, final float scale, final float rotationRadians) { //return evaluateFitForUnMatchedOptimal(scaledRotatedX, // scaledRotatedY, transX, transY, tolTransX, tolTransY, // set2, scale, rotationRadians); return evaluateFitForUnMatchedGreedy(scaledRotatedSet1, transX, transY, tolTransX, tolTransY, set2, scale, rotationRadians); } private TransformationParameters[] extractParameters( TransformationPointFit[] fits) { if (fits == null) { return new TransformationParameters[0]; } TransformationParameters[] params = new TransformationParameters[fits.length]; for (int i = 0; i < fits.length; ++i) { if (fits[i] != null) { params[i] = fits[i].getParameters(); } } return params; } private boolean areEqual(TransformationParameters[] lastParams, TransformationParameters[] currentParams) { if (lastParams.length != currentParams.length) { throw new IllegalArgumentException( "lastParams.length must be equal to currentParams.length"); } for (int i = 0; i < lastParams.length; ++i) { TransformationParameters p0 = lastParams[i]; TransformationParameters p1 = currentParams[i]; if ((p0 == null) && (p1 != null)) { return false; } else if ((p0 != null) && (p1 == null)) { return false; } else if (p0 == null && p1 == null) { continue; } else if (!p0.equals(p1)) { return false; } } return true; } /** * compare the fields mean distance from model and standard deviation * from mean to find if they are similar within a tolerance, then * find if the parameters are the same and return * <pre> * 0==same fit; 1==similar fits; -1==different fits * </pre> * @param bestFit * @param fit * @return comparisonResult 0==same fit; 1==similar fits; -1==different fits */ protected int fitsAreSimilarWithDiffParameters( TransformationPointFit bestFit, TransformationPointFit fit) { if (bestFit == null || fit == null) { return -1; } /*if the fit and bestFit is very close, need an infrastructure to return more than one (and to reset it when another fit not similar to bestFit is found) bestFit: fit=nMatchedPoints=63 nMaxMatchable=63.0 meanDistFromModel=37.57523582095192 stDevFromMean=22.616214121394517 tolerance=144.2497833620557 rotationInRadians=0.34906584 rotationInDegrees=19.99999941818584 scale=1.0 translationX=86.61143 translationY=-18.330833 fit: fit=nMatchedPoints=63 nMaxMatchable=63.0 meanDistFromModel=36.79744166041177 <-- mean dist and stdev are similar stDevFromMean=23.167906020816925 tolerance=144.2497833620557 rotationInRadians=0.5235988 rotationInDegrees=30.000000834826057 <--- rot is very different scale=1.0 translationX=91.6094 translationY=-72.9244 <--- transY is very different the correct answer is closer to "bestFit" but is currently then replaced with fit, so need to preserve both. correct answer: rotationInDegrees=18.000000500895634 scale=1.0 translationX=7.0 translationY=33.0 number of vertical partitions=3 ---- in contrast, these 2 sets of meanDistFromModel and stDevFromMean are significantly different: bestFit: meanDistFromModel=0.3658992320831333 stDevFromMean=0.15709856816653883 fit: meanDistFromModel=2.267763360270432 stDevFromMean=1.0703222291650063 ----- so ratios are needed rather than differences similar fits: divMean = 1.02 divStDev = 0.976 different fits: divMean = 0.161 divStDev = 0.147 */ //TODO: this may need to be adjusted and in the 2 fitness // functions which use it... should be it's own method... int nEps = (int)(1.5*Math.ceil(bestFit.getNumberOfMatchedPoints()/10.)); if (nEps == 0) { nEps = 1; } int diffNMatched = Math.abs(bestFit.getNumberOfMatchedPoints() - fit.getNumberOfMatchedPoints()); if (diffNMatched > nEps) { return -1; } double divMean = Math.abs(bestFit.getMeanDistFromModel()/ fit.getMeanDistFromModel()); double divStDev = Math.abs(bestFit.getStDevFromMean()/ fit.getStDevFromMean()); if ((Math.abs(1 - divMean) < 0.05) && (Math.abs(1 - divStDev) < 0.3)) { if (bestFit.getParameters().equals(fit.getParameters())) { return 0; } else { return 1; } } return -1; } /** * for unmatched sets of points, use a finer grid search to find the best * fit among the given parameters in similarToBestFit. * * @param similarToBestFit * @param set1 * @param set2 * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @param setsFractionOfImage * @return */ protected TransformationPointFit finerGridSearchToDistinguishBest( List<TransformationPointFit> similarToBestFit, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { if (similarToBestFit.isEmpty()) { return null; } else if (similarToBestFit.size() == 1) { return similarToBestFit.get(0); } int nIntervals = 3; TransformationPointFit bestFit = null; for (TransformationPointFit sFit : similarToBestFit) { TransformationPointFit fit = finerGridSearch( nIntervals, sFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fitIsBetter(bestFit, fit)) { bestFit = fit; } } return bestFit; } protected TransformationPointFit finerGridSearchToDistinguishBestForMatched( List<TransformationPointFit> similarToBestFit, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { if (similarToBestFit.isEmpty()) { return null; } else if (similarToBestFit.size() == 1) { return similarToBestFit.get(0); } int nIntervals = 3; TransformationPointFit bestFit = null; for (TransformationPointFit sFit : similarToBestFit) { TransformationPointFit fit = finerGridSearchForMatched( nIntervals, sFit, set1, set2, image1Width, image1Height, image2Width, image2Height, setsFractionOfImage); if (fitIsBetter(bestFit, fit)) { bestFit = fit; } } return bestFit; } private TransformationPointFit finerGridSearch( int nIntervals, TransformationPointFit bestFit, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { double halfRange = 3 * bestFit.getMeanDistFromModel(); if (Double.isInfinite(halfRange)) { return null; } int transXStart = (int)(bestFit.getTranslationX() - halfRange); int transXStop = (int)(bestFit.getTranslationX() + halfRange); int transYStart = (int)(bestFit.getTranslationY() - halfRange); int transYStop = (int)(bestFit.getTranslationY() + halfRange); int transXDelta = (transXStop - transXStart)/nIntervals; int transYDelta = (transYStop - transYStart)/nIntervals; if (transXDelta == 0) { transXDelta++; } if (transYDelta == 0) { transYDelta++; } float tolTransX2 = bestFit.getTranslationXTolerance(); float tolTransY2 = bestFit.getTranslationYTolerance(); boolean setsAreMatched = false; int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray scaledRotatedSet1 = scaleAndRotate(set1, bestFit.getRotationInRadians(), bestFit.getScale(), image1CentroidX, image1CentroidY); TransformationPointFit fit2 = calculateTranslationFromGridThenDownhillSimplex( scaledRotatedSet1, set1, set2, image1Width, image1Height, image2Width, image2Height, bestFit.getRotationInRadians(), bestFit.getScale(), transXStart, transXStop, transXDelta, transYStart, transYStop, transYDelta, tolTransX2, tolTransY2, setsAreMatched, setsFractionOfImage); return fit2; } private TransformationPointFit finerGridSearchForMatched( int nIntervals, TransformationPointFit bestFit, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, int image2Width, int image2Height, float setsFractionOfImage) { double halfRange = 3 * bestFit.getMeanDistFromModel(); if (Double.isInfinite(halfRange)) { return null; } int transXStart = (int)(bestFit.getTranslationX() - halfRange); int transXStop = (int)(bestFit.getTranslationX() + halfRange); int transYStart = (int)(bestFit.getTranslationY() - halfRange); int transYStop = (int)(bestFit.getTranslationY() + halfRange); int transXDelta = (transXStop - transXStart)/nIntervals; int transYDelta = (transYStop - transYStart)/nIntervals; if (transXDelta == 0) { transXDelta++; } if (transYDelta == 0) { transYDelta++; } int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray scaledRotatedSet1 = scaleAndRotate(set1, bestFit.getRotationInRadians(), bestFit.getScale(), image1CentroidX, image1CentroidY); float unusedTolerance = Float.MIN_VALUE; boolean setsAreMatched = true; TransformationPointFit fit2 = calculateTranslationFromGridThenDownhillSimplex( scaledRotatedSet1, set1, set2, image1Width, image1Height, image2Width, image2Height, bestFit.getRotationInRadians(), bestFit.getScale(), transXStart, transXStop, transXDelta, transYStart, transYStop, transYDelta, unusedTolerance, unusedTolerance, setsAreMatched, setsFractionOfImage); return fit2; } /** compare the bestFit and fit tolerances and return <pre> -1 : both are not null and bestFit tolerances are smaller 0 : both are not null and tolerances are same. 1 : both are not null and fit tolerances are smaller 2 : both are not null and the x and y fits and smaller and larger in a mix 3 : either bestFit or fit is null </pre> */ private int compareTolerance(TransformationPointFit bestFit, TransformationPointFit fit) { if (bestFit == null || fit == null) { return 3; } float diffTolX = bestFit.getTranslationXTolerance() - fit.getTranslationXTolerance(); float diffTolY = bestFit.getTranslationYTolerance() - fit.getTranslationYTolerance(); if ((Math.abs(diffTolX) < 1) && (Math.abs(diffTolY) < 1)) { return 0; } else if ((diffTolX > 0) && (diffTolY > 0)) { return 1; } else if ((diffTolX < 0) && (diffTolY < 0)) { return -1; } else { return 2; } } /** * Re-evaluate the fit of the enclosed parameters, but use the new tolerance * for translation in x and y. * * @param fit * @param set1 * @param set2 * @param image1Width * @param image1Height * @param image2Width * @param image2Height * @param setsFractionOfImage * @return */ private TransformationPointFit reevaluateForNewTolerance( TransformationPointFit fit, float translationXTolerance, float translationYTolerance, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height) { if (fit == null) { return null; } float rotationInRadians = fit.getRotationInRadians(); float scale = fit.getScale(); int image1CentroidX = image1Width >> 1; int image1CentroidY = image1Height >> 1; PairFloatArray scaledRotatedSet1 = scaleAndRotate(set1, rotationInRadians, scale, image1CentroidX, image1CentroidY); TransformationParameters params = new TransformationParameters(); params.setRotationInRadians(rotationInRadians); params.setScale(scale); params.setTranslationX(fit.getTranslationX()); params.setTranslationY(fit.getTranslationY()); //TODO: may need to change TransformationPointFit to retain tolerance in X and Y // instead of a single value. TransformationPointFit fit2 = evaluateFitForUnMatchedTransformedGreedy( params, scaledRotatedSet1, set2, translationXTolerance, translationYTolerance); return fit2; } /** * find the minima and maxima of translationX and translationY for the given * fits. * @param fits * @return new float[]{minTX, maxTX, minTY, maxTY} */ protected float[] getTranslationMinAndMaxes(TransformationPointFit[] fits) { if (fits == null || fits.length == 0) { return null; } float minTX = Float.MAX_VALUE; float maxTX = Float.MIN_VALUE; float minTY = Float.MAX_VALUE; float maxTY = Float.MIN_VALUE; for (TransformationPointFit fit : fits) { if (fit == null) { continue; } float tx = fit.getTranslationX(); float ty = fit.getTranslationY(); if (tx < minTX) { minTX = tx; } if (ty < minTY) { minTY = ty; } if (tx > maxTX) { maxTX = tx; } if (ty > maxTY) { maxTY = ty; } } return new float[]{minTX, maxTX, minTY, maxTY}; } protected void reevaluateFitsForCommonTolerance( TransformationPointFit bestFit, TransformationPointFit fit, PairIntArray set1, PairIntArray set2, int image1Width, int image1Height, final TransformationPointFit[] reevalFits, final boolean[] fitIsBetter) { /* -1 : both are not null and bestFit tolerances are smaller 0 : both are not null and tolerances are same. 1 : both are not null and fit tolerances are smaller 2 : both are not null and the x and y fits and smaller and larger in a mix 3 : either bestFit or fit is null */ int compTol = compareTolerance(bestFit, fit); TransformationPointFit bestFitT = bestFit; TransformationPointFit fitT = fit; if (compTol == 1) { bestFitT = reevaluateForNewTolerance(bestFit, fit.getTranslationXTolerance(), fit.getTranslationYTolerance(), set1, set2, image1Width, image1Height); } else if (compTol == -1) { fitT = reevaluateForNewTolerance(fit, bestFit.getTranslationXTolerance(), bestFit.getTranslationYTolerance(), set1, set2, image1Width, image1Height); } else if (compTol == 2) { // TODO: may need to revise this // reduce both to smallest tolerances float tolX = bestFit.getTranslationXTolerance(); if (fit.getTranslationXTolerance() < tolX) { tolX = fit.getTranslationXTolerance(); } float tolY = bestFit.getTranslationYTolerance(); if (fit.getTranslationYTolerance() < tolY) { tolY = fit.getTranslationYTolerance(); } bestFitT = reevaluateForNewTolerance(bestFit, tolX, tolY, set1, set2, image1Width, image1Height); fitT = reevaluateForNewTolerance(fit, tolX, tolY, set1, set2, image1Width, image1Height); } fitIsBetter[0] = fitIsBetter(bestFitT, fitT); reevalFits[0] = bestFit; if (fitIsBetter[0]) { reevalFits[1] = fitT; } if (bestFit != null && fit != null) { if (compTol == 1) { log.fine(" rot re-evaluated bestFit at lower tolerance"); } else if (compTol == 2) { log.fine(" rot re-evaluated bestFit and fit at common tolerance"); } } } }
more improvements in PointMatcher
src/algorithms/imageProcessing/PointMatcher.java
more improvements in PointMatcher
<ide><path>rc/algorithms/imageProcessing/PointMatcher.java <ide> log.fine(" partition compare \n **==> bestFit=" + bestFit.toString() + "\n fit=" + fit.toString()); <ide> } <ide> <del> boolean fitIsBetter = fitIsBetter(bestFit, fit); <del> <del>if (fitIsBetter) { <del>log.fine(" partition bestFit=" + fit.toString()); <add> TransformationPointFit[] reevalFits = new TransformationPointFit[2]; <add> boolean[] fitIsBetter = new boolean[1]; <add> if ((bestFit != null) && (fit != null) && <add> ( <add> ((bestFit.getTranslationXTolerance()/fit.getTranslationXTolerance()) > 2) <add> && <add> ((bestFit.getTranslationYTolerance()/fit.getTranslationYTolerance()) > 2)) <add> || <add> ( <add> ((bestFit.getTranslationXTolerance()/fit.getTranslationXTolerance()) < 0.5) <add> && <add> ((bestFit.getTranslationYTolerance()/fit.getTranslationYTolerance()) < 0.5)) <add> ) { <add> <add> reevaluateFitsForCommonTolerance(bestFit, fit, <add> unmatchedLeftXY, unmatchedRightXY, image1Width, image1Height, <add> reevalFits, fitIsBetter); <add> <add> bestFit = reevalFits[0]; <add> fit = reevalFits[1]; <add> <add> } else { <add> fitIsBetter[0] = fitIsBetter(bestFit, fit); <add> } <add> <add>if (bestFit != null && fit != null) { <add>log.fine(" tol corrected partition compare \n **==> bestFit=" + bestFit.toString() + "\n fit=" + fit.toString()); <add>} <add> <add>if (fitIsBetter[0]) { <add>log.fine(" ***** partition bestFit=" + fit.toString()); <ide> } else { <del>log.fine(" partition keeping bestFit=" + bestFit.toString()); <add>log.fine(" ***** partition keeping bestFit=" + bestFit.toString()); <ide> } <ide> <del> if (fitIsBetter) { <add> if (fitIsBetter[0]) { <ide> bestFit = fit; <ide> } <ide> <ide> return new float[]{minTX, maxTX, minTY, maxTY}; <ide> } <ide> <add> /** <add> * re-evaluate bestFit or fit, whichever has the largest translation <add> * tolerance, using the smaller tolerance. Note that there are <add> * exception rules, such as when both bestFit and fit have <add> * same number of points, but fit has a mean dist from model less than one <add> * and bestFit has a much larger mean distance from model. In that case, <add> * even if bestFit has a smaller translation tolerance, fit will not <add> * be re-evaluated because such a mean distance from model means the <add> * answer has converged. <add> * <add> * <add> * @param bestFit <add> * @param fit <add> * @param set1 <add> * @param set2 <add> * @param image1Width <add> * @param image1Height <add> * @param reevalFits <add> * @param fitIsBetter <add> */ <ide> protected void reevaluateFitsForCommonTolerance( <ide> TransformationPointFit bestFit, TransformationPointFit fit, <ide> PairIntArray set1, PairIntArray set2, <ide> int image1Width, int image1Height, <ide> final TransformationPointFit[] reevalFits, final boolean[] fitIsBetter) { <add> <add> /* <add> check for whether fit has converged already for equal number of points <add> matched. <add> */ <add> if (fit != null && bestFit != null) { <add> int bestNMatches = bestFit.getNumberOfMatchedPoints(); <add> int compNMatches = fit.getNumberOfMatchedPoints(); <add> int diffEps = (int)Math.round(2.*Math.ceil(Math.max(bestNMatches, <add> compNMatches)/10.)); <add> if (diffEps == 0) { <add> diffEps = 1; <add> } <add> if ((bestNMatches > 2) && (compNMatches > 2)) { <add> if (Math.abs(bestNMatches - compNMatches) < diffEps) { <add> if ((fit.getMeanDistFromModel() < 1) <add> && (fit.getStDevFromMean() < 1) <add> && (bestFit.getMeanDistFromModel() > 1)) { <add> <add> // fit is the better fit <add> fitIsBetter[0] = true; <add> reevalFits[0] = bestFit; <add> reevalFits[1] = fit; <add> return; <add> } <add> } <add> } <add> <add> /* <add> when tolerances are both already very small, not redoing the fit, <add> just comparing as is <add> */ <add> int limit = 7; <add> if ((bestFit.getTranslationXTolerance() < limit) && <add> (bestFit.getTranslationYTolerance() < limit) && <add> (fit.getTranslationXTolerance() < limit) && <add> (fit.getTranslationYTolerance() < limit)) { <add> <add> fitIsBetter[0] = fitIsBetter(bestFit, fit); <add> reevalFits[0] = bestFit; <add> reevalFits[1] = fit; <add> return; <add> } <add> <add> } <ide> <ide> /* <ide> -1 : both are not null and bestFit tolerances are smaller <ide> fit.getTranslationYTolerance(), <ide> set1, set2, <ide> image1Width, image1Height); <del> <add> /* <add> // do not use the lower tolerance. it may be a false fit if null here <add> if (bestFitT == null) { <add> bestFitT = bestFit; <add> } else if (bestFitT.getNumberOfMatchedPoints() == 0) { <add> if (bestFit.getNumberOfMatchedPoints() > 10) { <add> bestFitT = bestFit; <add> } <add> }*/ <add> <ide> } else if (compTol == -1) { <ide> <ide> fitT = reevaluateForNewTolerance(fit, <ide> set1, set2, <ide> image1Width, image1Height); <ide> <add> /* <add> // do not use the lower tolerance if resulted in null fit <add> if (fitT == null) { <add> fitT = fit; <add> } else if (fitT.getNumberOfMatchedPoints() == 0) { <add> if (fit.getNumberOfMatchedPoints() > 10) { <add> fitT = fit; <add> } <add> }*/ <add> <ide> } else if (compTol == 2) { <ide> <ide> // TODO: may need to revise this <ide> <ide> fitT = reevaluateForNewTolerance(fit, <ide> tolX, tolY, set1, set2, image1Width, image1Height); <add> <add> /* <add> // do not use the lower tolerance if resulted in null fits <add> if (fitT == null) { <add> fitT = fit; <add> bestFitT = bestFit; <add> } else if (fitT.getNumberOfMatchedPoints() == 0) { <add> if (fit.getNumberOfMatchedPoints() > 10) { <add> fitT = fit; <add> bestFitT = bestFit; <add> } <add> } else if (bestFitT == null) { <add> fitT = fit; <add> bestFitT = bestFit; <add> } else if (bestFitT.getNumberOfMatchedPoints() == 0) { <add> if (bestFitT.getNumberOfMatchedPoints() > 10) { <add> fitT = fit; <add> bestFitT = bestFit; <add> } <add> }*/ <ide> } <ide> <ide> fitIsBetter[0] = fitIsBetter(bestFitT, fitT);
Java
mit
4bb07b1a5d26c37b6e5bb6543c23141be0b57ecb
0
sarahtattersall/PIPE,sjdayday/PIPE,frig-neutron/PIPE
package pipe.views; import static org.junit.Assert.*; import java.awt.Color; import java.util.Observable; import java.util.Observer; import org.junit.Before; import org.junit.Test; import pipe.models.PipeObservable; import pipe.models.component.token.Token; public class MarkingViewTest implements Observer { private MarkingView markingView; private TokenView tokenView; private boolean called; private boolean newMarkingViewShouldBeNull; @Before public void setUp() throws Exception { tokenView = new TokenView(true, "Fred", Color.black); } @Test public void verifyTokenViewCanBeReplacedWithNewInstance() throws Exception { Token model = tokenView.getModel(); markingView = new MarkingView(tokenView, 3); assertEquals("Fred", markingView.getToken().getID()); TokenView newTokenView = new TokenView(true, "Mary", Color.green); newTokenView.updateModelFromPrevious(tokenView); assertEquals(newTokenView, markingView.getToken()); assertEquals("Mary", markingView.getToken().getID()); assertEquals(Color.green, markingView.getToken().getColor()); assertEquals(model, markingView.getToken().getModel()); } @Test public void verifyTokenViewThatIsLaterDisabledGeneratesNullUpdate() throws Exception { markingView = new MarkingView(tokenView, 3); assertEquals(tokenView, markingView.getToken()); tokenView.disableAndNotifyObservers(); assertNull(markingView.getToken()); } @Override public void update(Observable oldObject, Object newObject) { called = true; MarkingView view=null; if (oldObject instanceof PipeObservable) { view = (MarkingView) ((PipeObservable) oldObject).getObservable(); } assertEquals(view , markingView); if (newMarkingViewShouldBeNull) assertNull(newObject); } }
pipe-gui/src/test/java/pipe/views/MarkingViewTest.java
package pipe.views; import static org.junit.Assert.*; import java.awt.Color; import java.util.Observable; import java.util.Observer; import org.junit.Before; import org.junit.Test; import pipe.models.PipeObservable; import pipe.models.component.token.Token; public class MarkingViewTest implements Observer { private MarkingView markingView; private TokenView tokenView; private boolean called; private boolean newMarkingViewShouldBeNull; @Before public void setUp() throws Exception { tokenView = new TokenView(true, "Fred", Color.black); } @Test public void verifyTokenViewCanBeReplacedWithNewInstance() throws Exception { Token model = tokenView.getModel(); markingView = new MarkingView(tokenView, 3); assertEquals("Fred", markingView.getToken().getID()); TokenView newTokenView = new TokenView(true, "Mary", Color.green); newTokenView.updateModelFromPrevious(tokenView); assertEquals(newTokenView, markingView.getToken()); assertEquals("Mary", markingView.getToken().getID()); assertEquals(Color.green, markingView.getToken().getColor()); assertEquals(model, markingView.getToken().getModel()); } @Test public void verifyTokenViewThatIsLaterDisabledGeneratesNullUpdate() throws Exception { markingView = new MarkingView(tokenView, 3); assertEquals(tokenView, markingView.getToken()); tokenView.disableAndNotifyObservers(); assertNull(markingView.getToken()); } @Test public void verifyMarkingViewTellsObserversToDeleteSelfIfItsTokenViewIsSetDisabled() throws Exception { markingView = new MarkingView(tokenView, 3); markingView.addObserver(this); newMarkingViewShouldBeNull = true; markingView.setChanged(); markingView.notifyObservers(null); while (!called) { Thread.sleep(10); } } @Override public void update(Observable oldObject, Object newObject) { called = true; MarkingView view=null; if (oldObject instanceof PipeObservable) { view = (MarkingView) ((PipeObservable) oldObject).getObservable(); } assertEquals(view , markingView); if (newMarkingViewShouldBeNull) assertNull(newObject); } }
Remove buggy unit test
pipe-gui/src/test/java/pipe/views/MarkingViewTest.java
Remove buggy unit test
<ide><path>ipe-gui/src/test/java/pipe/views/MarkingViewTest.java <ide> tokenView.disableAndNotifyObservers(); <ide> assertNull(markingView.getToken()); <ide> } <del> @Test <del> public void verifyMarkingViewTellsObserversToDeleteSelfIfItsTokenViewIsSetDisabled() throws Exception <del> { <del> markingView = new MarkingView(tokenView, 3); <del> markingView.addObserver(this); <del> newMarkingViewShouldBeNull = true; <del> markingView.setChanged(); <del> markingView.notifyObservers(null); <del> while (!called) <del> { <del> Thread.sleep(10); <del> } <del> } <ide> @Override <ide> public void update(Observable oldObject, Object newObject) <ide> {
Java
apache-2.0
error: pathspec 'teaapps/src/main/java/org/teatrove/teaapps/contexts/JMXContext.java' did not match any file(s) known to git
69965dfb0b0f4b45b8aa57f902a0c31534694264
1
teatrove/teatrove,teatrove/teatrove
package org.teatrove.teaapps.contexts; import java.lang.management.ClassLoadingMXBean; import java.lang.management.CompilationMXBean; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryManagerMXBean; import java.lang.management.MemoryPoolMXBean; import java.lang.management.OperatingSystemMXBean; import java.lang.management.RuntimeMXBean; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.util.List; import javax.management.MBeanServer; public class JMXContext { public ClassLoadingMXBean getClassLoadingMXBean() { return ManagementFactory.getClassLoadingMXBean(); } public void setClassLoadingMXBeanVerbose(boolean value) { ManagementFactory.getClassLoadingMXBean().setVerbose(value); } public CompilationMXBean getCompilationMXBean() { return ManagementFactory.getCompilationMXBean(); } public List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() { return ManagementFactory.getGarbageCollectorMXBeans(); } public List<MemoryManagerMXBean> getMemoryManagerMXBeans() { return ManagementFactory.getMemoryManagerMXBeans(); } public MemoryMXBean getMemoryMXBean() { return ManagementFactory.getMemoryMXBean(); } public void setMemoryMXBeanVerbose(boolean value) { ManagementFactory.getMemoryMXBean().setVerbose(value); } public List<MemoryPoolMXBean> getMemoryPoolMXBeans() { return ManagementFactory.getMemoryPoolMXBeans(); } public void resetPeakUsage(MemoryPoolMXBean bean) { bean.resetPeakUsage(); } public void setCollectionUsageThreshold(MemoryPoolMXBean bean, long threshold) { bean.setCollectionUsageThreshold(threshold); } public void setUsageThreshold(MemoryPoolMXBean bean, long threshold) { bean.setUsageThreshold(threshold); } public OperatingSystemMXBean getOperatingSystemMXBean() { return ManagementFactory.getOperatingSystemMXBean(); } public MBeanServer getPlatformMBeanServer() { return ManagementFactory.getPlatformMBeanServer(); } // TODO add methods for platform server public RuntimeMXBean getRuntimeMXBean() { return ManagementFactory.getRuntimeMXBean(); } public ThreadMXBean getThreadMXBean() { return ManagementFactory.getThreadMXBean(); } public ThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers) { return ManagementFactory.getThreadMXBean().dumpAllThreads(lockedMonitors, lockedSynchronizers); } public long[] findDeadlockedThreads() { return ManagementFactory.getThreadMXBean().findDeadlockedThreads(); } public long[] findMonitorDeadlockedThreads() { return ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads(); } public void setThreadContentionMonitoringEnabled(boolean enable) { ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(enable); } public void setThreadCpuTimeEnabled(boolean enable) { ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(enable); } }
teaapps/src/main/java/org/teatrove/teaapps/contexts/JMXContext.java
- adding JMXContext to build
teaapps/src/main/java/org/teatrove/teaapps/contexts/JMXContext.java
- adding JMXContext to build
<ide><path>eaapps/src/main/java/org/teatrove/teaapps/contexts/JMXContext.java <add>package org.teatrove.teaapps.contexts; <add> <add>import java.lang.management.ClassLoadingMXBean; <add>import java.lang.management.CompilationMXBean; <add>import java.lang.management.GarbageCollectorMXBean; <add>import java.lang.management.ManagementFactory; <add>import java.lang.management.MemoryMXBean; <add>import java.lang.management.MemoryManagerMXBean; <add>import java.lang.management.MemoryPoolMXBean; <add>import java.lang.management.OperatingSystemMXBean; <add>import java.lang.management.RuntimeMXBean; <add>import java.lang.management.ThreadInfo; <add>import java.lang.management.ThreadMXBean; <add>import java.util.List; <add> <add>import javax.management.MBeanServer; <add> <add>public class JMXContext { <add> <add> public ClassLoadingMXBean getClassLoadingMXBean() { <add> return ManagementFactory.getClassLoadingMXBean(); <add> } <add> <add> public void setClassLoadingMXBeanVerbose(boolean value) { <add> ManagementFactory.getClassLoadingMXBean().setVerbose(value); <add> } <add> <add> public CompilationMXBean getCompilationMXBean() { <add> return ManagementFactory.getCompilationMXBean(); <add> } <add> <add> public List<GarbageCollectorMXBean> getGarbageCollectorMXBeans() { <add> return ManagementFactory.getGarbageCollectorMXBeans(); <add> } <add> <add> public List<MemoryManagerMXBean> getMemoryManagerMXBeans() { <add> return ManagementFactory.getMemoryManagerMXBeans(); <add> } <add> <add> public MemoryMXBean getMemoryMXBean() { <add> return ManagementFactory.getMemoryMXBean(); <add> } <add> <add> public void setMemoryMXBeanVerbose(boolean value) { <add> ManagementFactory.getMemoryMXBean().setVerbose(value); <add> } <add> <add> public List<MemoryPoolMXBean> getMemoryPoolMXBeans() { <add> return ManagementFactory.getMemoryPoolMXBeans(); <add> } <add> <add> public void resetPeakUsage(MemoryPoolMXBean bean) { <add> bean.resetPeakUsage(); <add> } <add> <add> public void setCollectionUsageThreshold(MemoryPoolMXBean bean, long threshold) { <add> bean.setCollectionUsageThreshold(threshold); <add> } <add> <add> public void setUsageThreshold(MemoryPoolMXBean bean, long threshold) { <add> bean.setUsageThreshold(threshold); <add> } <add> <add> public OperatingSystemMXBean getOperatingSystemMXBean() { <add> return ManagementFactory.getOperatingSystemMXBean(); <add> } <add> <add> public MBeanServer getPlatformMBeanServer() { <add> return ManagementFactory.getPlatformMBeanServer(); <add> } <add> <add> // TODO add methods for platform server <add> <add> public RuntimeMXBean getRuntimeMXBean() { <add> return ManagementFactory.getRuntimeMXBean(); <add> } <add> <add> public ThreadMXBean getThreadMXBean() { <add> return ManagementFactory.getThreadMXBean(); <add> } <add> <add> public ThreadInfo[] dumpAllThreads(boolean lockedMonitors, boolean lockedSynchronizers) { <add> return ManagementFactory.getThreadMXBean().dumpAllThreads(lockedMonitors, lockedSynchronizers); <add> } <add> <add> public long[] findDeadlockedThreads() { <add> return ManagementFactory.getThreadMXBean().findDeadlockedThreads(); <add> } <add> <add> public long[] findMonitorDeadlockedThreads() { <add> return ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads(); <add> } <add> <add> public void setThreadContentionMonitoringEnabled(boolean enable) { <add> ManagementFactory.getThreadMXBean().setThreadContentionMonitoringEnabled(enable); <add> } <add> <add> public void setThreadCpuTimeEnabled(boolean enable) { <add> ManagementFactory.getThreadMXBean().setThreadCpuTimeEnabled(enable); <add> } <add>}
Java
bsd-2-clause
61094aebb570232632f8584ac8fd470819c5b37b
0
bogovicj/bigdataviewer-core,bigdataviewer/bigdataviewer-core,bogovicj/bigdataviewer-core,bigdataviewer/bigdataviewer-core
/* * #%L * BigDataViewer core classes with minimal dependencies. * %% * Copyright (C) 2012 - 2020 BigDataViewer developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package bdv.img.n5; import bdv.AbstractViewerSetupImgLoader; import bdv.ViewerImgLoader; import bdv.cache.CacheControl; import bdv.img.cache.SimpleCacheArrayLoader; import bdv.img.cache.VolatileGlobalCellCache; import bdv.util.ConstantRandomAccessible; import bdv.util.MipmapTransforms; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.function.Function; import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription; import mpicbg.spim.data.generic.sequence.BasicViewSetup; import mpicbg.spim.data.generic.sequence.ImgLoaderHint; import mpicbg.spim.data.sequence.MultiResolutionImgLoader; import mpicbg.spim.data.sequence.MultiResolutionSetupImgLoader; import mpicbg.spim.data.sequence.VoxelDimensions; import net.imglib2.Dimensions; import net.imglib2.FinalDimensions; import net.imglib2.FinalInterval; import net.imglib2.RandomAccessibleInterval; import net.imglib2.Volatile; import net.imglib2.cache.queue.BlockingFetchQueues; import net.imglib2.cache.queue.FetcherThreads; import net.imglib2.cache.volatiles.CacheHints; import net.imglib2.cache.volatiles.LoadingStrategy; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileByteArray; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileDoubleArray; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileFloatArray; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileIntArray; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileLongArray; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileShortArray; import net.imglib2.img.cell.CellGrid; import net.imglib2.img.cell.CellImg; import net.imglib2.realtransform.AffineTransform3D; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.integer.ByteType; import net.imglib2.type.numeric.integer.IntType; import net.imglib2.type.numeric.integer.LongType; import net.imglib2.type.numeric.integer.ShortType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.type.numeric.integer.UnsignedIntType; import net.imglib2.type.numeric.integer.UnsignedLongType; import net.imglib2.type.numeric.integer.UnsignedShortType; import net.imglib2.type.numeric.real.DoubleType; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.type.volatiles.VolatileByteType; import net.imglib2.type.volatiles.VolatileDoubleType; import net.imglib2.type.volatiles.VolatileFloatType; import net.imglib2.type.volatiles.VolatileIntType; import net.imglib2.type.volatiles.VolatileLongType; import net.imglib2.type.volatiles.VolatileShortType; import net.imglib2.type.volatiles.VolatileUnsignedByteType; import net.imglib2.type.volatiles.VolatileUnsignedIntType; import net.imglib2.type.volatiles.VolatileUnsignedLongType; import net.imglib2.type.volatiles.VolatileUnsignedShortType; import net.imglib2.util.Cast; import net.imglib2.view.Views; import org.janelia.saalfeldlab.n5.*; import static bdv.img.n5.BdvN5Format.DATA_TYPE_KEY; import static bdv.img.n5.BdvN5Format.DOWNSAMPLING_FACTORS_KEY; import static bdv.img.n5.BdvN5Format.getPathName; public class N5ImageLoader implements ViewerImgLoader, MultiResolutionImgLoader { private final File n5File; // TODO: it would be good if this would not be needed // find available setups from the n5 private final AbstractSequenceDescription< ?, ?, ? > seq; /** * Maps setup id to {@link SetupImgLoader}. */ private final Map< Integer, SetupImgLoader > setupImgLoaders = new HashMap<>(); public N5ImageLoader( final File n5File, final AbstractSequenceDescription< ?, ?, ? > sequenceDescription ) { this.n5File = n5File; this.seq = sequenceDescription; } public File getN5File() { return n5File; } private volatile boolean isOpen = false; private FetcherThreads fetchers; private VolatileGlobalCellCache cache; private N5Reader n5; private void open() { if ( !isOpen ) { synchronized ( this ) { if ( isOpen ) return; try { this.n5 = new N5FSReader( n5File.getAbsolutePath() ); int maxNumLevels = 0; final List< ? extends BasicViewSetup > setups = seq.getViewSetupsOrdered(); for ( final BasicViewSetup setup : setups ) { final int setupId = setup.getId(); final SetupImgLoader setupImgLoader = createSetupImgLoader( setupId ); setupImgLoaders.put( setupId, setupImgLoader ); maxNumLevels = Math.max( maxNumLevels, setupImgLoader.numMipmapLevels() ); } final int numFetcherThreads = Math.max( 1, Runtime.getRuntime().availableProcessors() ); final BlockingFetchQueues< Callable< ? > > queue = new BlockingFetchQueues<>( maxNumLevels, numFetcherThreads ); fetchers = new FetcherThreads( queue, numFetcherThreads ); cache = new VolatileGlobalCellCache( queue ); } catch ( IOException e ) { throw new RuntimeException( e ); } isOpen = true; } } } /** * Clear the cache. Images that were obtained from * this loader before {@link #close()} will stop working. Requesting images * after {@link #close()} will cause the n5 to be reopened (with a * new cache). */ public void close() { if ( isOpen ) { synchronized ( this ) { if ( !isOpen ) return; fetchers.shutdown(); cache.clearCache(); isOpen = false; } } } @Override public SetupImgLoader getSetupImgLoader( final int setupId ) { open(); return setupImgLoaders.get( setupId ); } private < T extends NativeType< T >, V extends Volatile< T > & NativeType< V > > SetupImgLoader< T, V > createSetupImgLoader( final int setupId ) throws IOException { final String pathName = getPathName( setupId ); final DataType dataType = n5.getAttribute( pathName, DATA_TYPE_KEY, DataType.class ); switch ( dataType ) { case UINT8: return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedByteType(), new VolatileUnsignedByteType() ) ); case UINT16: return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedShortType(), new VolatileUnsignedShortType() ) ); case UINT32: return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedIntType(), new VolatileUnsignedIntType() ) ); case UINT64: return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedLongType(), new VolatileUnsignedLongType() ) ); case INT8: return Cast.unchecked( new SetupImgLoader<>( setupId, new ByteType(), new VolatileByteType() ) ); case INT16: return Cast.unchecked( new SetupImgLoader<>( setupId, new ShortType(), new VolatileShortType() ) ); case INT32: return Cast.unchecked( new SetupImgLoader<>( setupId, new IntType(), new VolatileIntType() ) ); case INT64: return Cast.unchecked( new SetupImgLoader<>( setupId, new LongType(), new VolatileLongType() ) ); case FLOAT32: return Cast.unchecked( new SetupImgLoader<>( setupId, new FloatType(), new VolatileFloatType() ) ); case FLOAT64: return Cast.unchecked( new SetupImgLoader<>( setupId, new DoubleType(), new VolatileDoubleType() ) ); } return null; } @Override public CacheControl getCacheControl() { open(); return cache; } public class SetupImgLoader< T extends NativeType< T >, V extends Volatile< T > & NativeType< V > > extends AbstractViewerSetupImgLoader< T, V > implements MultiResolutionSetupImgLoader< T > { private final int setupId; private final double[][] mipmapResolutions; private final AffineTransform3D[] mipmapTransforms; public SetupImgLoader( final int setupId, final T type, final V volatileType ) throws IOException { super( type, volatileType ); this.setupId = setupId; final String pathName = getPathName( setupId ); mipmapResolutions = n5.getAttribute( pathName, DOWNSAMPLING_FACTORS_KEY, double[][].class ); mipmapTransforms = new AffineTransform3D[ mipmapResolutions.length ]; for ( int level = 0; level < mipmapResolutions.length; level++ ) mipmapTransforms[ level ] = MipmapTransforms.getMipmapTransformDefault( mipmapResolutions[ level ] ); } @Override public RandomAccessibleInterval< V > getVolatileImage( final int timepointId, final int level, final ImgLoaderHint... hints ) { return prepareCachedImage( timepointId, level, LoadingStrategy.BUDGETED, volatileType ); } @Override public RandomAccessibleInterval< T > getImage( final int timepointId, final int level, final ImgLoaderHint... hints ) { return prepareCachedImage( timepointId, level, LoadingStrategy.BLOCKING, type ); } @Override public Dimensions getImageSize( final int timepointId, final int level ) { try { final String pathName = getPathName( setupId, timepointId, level ); final DatasetAttributes attributes = n5.getDatasetAttributes( pathName ); return new FinalDimensions( attributes.getDimensions() ); } catch( Exception e ) { return null; } } @Override public double[][] getMipmapResolutions() { return mipmapResolutions; } @Override public AffineTransform3D[] getMipmapTransforms() { return mipmapTransforms; } @Override public int numMipmapLevels() { return mipmapResolutions.length; } @Override public VoxelDimensions getVoxelSize( final int timepointId ) { return null; } /** * Create a {@link CellImg} backed by the cache. */ private < T extends NativeType< T > > RandomAccessibleInterval< T > prepareCachedImage( final int timepointId, final int level, final LoadingStrategy loadingStrategy, final T type ) { try { final String pathName = getPathName( setupId, timepointId, level ); final DatasetAttributes attributes = n5.getDatasetAttributes( pathName ); final long[] dimensions = attributes.getDimensions(); final int[] cellDimensions = attributes.getBlockSize(); final CellGrid grid = new CellGrid( dimensions, cellDimensions ); final int priority = numMipmapLevels() - 1 - level; final CacheHints cacheHints = new CacheHints( loadingStrategy, priority, false ); final SimpleCacheArrayLoader< ? > loader = createCacheArrayLoader( n5, pathName ); return cache.createImg( grid, timepointId, setupId, level, cacheHints, loader, type ); } catch ( IOException e ) { System.err.println( String.format( "image data for timepoint %d setup %d level %d could not be found.", timepointId, setupId, level ) ); return Views.interval( new ConstantRandomAccessible<>( type.createVariable(), 3 ), new FinalInterval( 1, 1, 1 ) ); } } } private static class N5CacheArrayLoader< A > implements SimpleCacheArrayLoader< A > { private final N5Reader n5; private final String pathName; private final DatasetAttributes attributes; private final Function< DataBlock< ? >, A > createArray; N5CacheArrayLoader( final N5Reader n5, final String pathName, final DatasetAttributes attributes, final Function< DataBlock< ? >, A > createArray ) { this.n5 = n5; this.pathName = pathName; this.attributes = attributes; this.createArray = createArray; } @Override public A loadArray( final long[] gridPosition ) throws IOException { final DataBlock< ? > dataBlock = n5.readBlock( pathName, attributes, gridPosition ); if ( dataBlock == null ) return createEmptyArray( gridPosition ); else return createArray.apply( dataBlock ); } private A createEmptyArray( long[] gridPosition ) { final int[] blockSize = attributes.getBlockSize(); final int n = blockSize[ 0 ] * blockSize[ 1 ] * blockSize[ 2 ]; switch ( attributes.getDataType() ) { case UINT8: case INT8: return createArray.apply( new ByteArrayDataBlock( blockSize, gridPosition, new byte[ n ] ) ); case UINT16: case INT16: return createArray.apply( new ShortArrayDataBlock( blockSize, gridPosition, new short[ n ] ) ); case UINT32: case INT32: return createArray.apply( new IntArrayDataBlock( blockSize, gridPosition, new int[ n ] ) ); case UINT64: case INT64: return createArray.apply( new LongArrayDataBlock( blockSize, gridPosition, new long[ n ] ) ); case FLOAT32: return createArray.apply( new FloatArrayDataBlock( blockSize, gridPosition, new float[ n ] ) ); case FLOAT64: return createArray.apply( new DoubleArrayDataBlock( blockSize, gridPosition, new double[ n ] ) ); default: throw new UnsupportedOperationException("Data type not supported: " + attributes.getDataType()); } } } public static SimpleCacheArrayLoader< ? > createCacheArrayLoader( final N5Reader n5, final String pathName ) throws IOException { final DatasetAttributes attributes = n5.getDatasetAttributes( pathName ); switch ( attributes.getDataType() ) { case UINT8: case INT8: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileByteArray( Cast.unchecked( dataBlock.getData() ), true ) ); case UINT16: case INT16: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileShortArray( Cast.unchecked( dataBlock.getData() ), true ) ); case UINT32: case INT32: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileIntArray( Cast.unchecked( dataBlock.getData() ), true ) ); case UINT64: case INT64: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileLongArray( Cast.unchecked( dataBlock.getData() ), true ) ); case FLOAT32: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileFloatArray( Cast.unchecked( dataBlock.getData() ), true ) ); case FLOAT64: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileDoubleArray( Cast.unchecked( dataBlock.getData() ), true ) ); default: throw new IllegalArgumentException(); } } }
src/main/java/bdv/img/n5/N5ImageLoader.java
/* * #%L * BigDataViewer core classes with minimal dependencies. * %% * Copyright (C) 2012 - 2020 BigDataViewer developers. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package bdv.img.n5; import bdv.AbstractViewerSetupImgLoader; import bdv.ViewerImgLoader; import bdv.cache.CacheControl; import bdv.img.cache.SimpleCacheArrayLoader; import bdv.img.cache.VolatileGlobalCellCache; import bdv.util.ConstantRandomAccessible; import bdv.util.MipmapTransforms; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.function.Function; import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription; import mpicbg.spim.data.generic.sequence.BasicViewSetup; import mpicbg.spim.data.generic.sequence.ImgLoaderHint; import mpicbg.spim.data.sequence.MultiResolutionImgLoader; import mpicbg.spim.data.sequence.MultiResolutionSetupImgLoader; import mpicbg.spim.data.sequence.VoxelDimensions; import net.imglib2.Dimensions; import net.imglib2.FinalDimensions; import net.imglib2.FinalInterval; import net.imglib2.RandomAccessibleInterval; import net.imglib2.Volatile; import net.imglib2.cache.queue.BlockingFetchQueues; import net.imglib2.cache.queue.FetcherThreads; import net.imglib2.cache.volatiles.CacheHints; import net.imglib2.cache.volatiles.LoadingStrategy; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileByteArray; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileDoubleArray; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileFloatArray; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileIntArray; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileLongArray; import net.imglib2.img.basictypeaccess.volatiles.array.VolatileShortArray; import net.imglib2.img.cell.CellGrid; import net.imglib2.img.cell.CellImg; import net.imglib2.realtransform.AffineTransform3D; import net.imglib2.type.NativeType; import net.imglib2.type.numeric.integer.ByteType; import net.imglib2.type.numeric.integer.IntType; import net.imglib2.type.numeric.integer.LongType; import net.imglib2.type.numeric.integer.ShortType; import net.imglib2.type.numeric.integer.UnsignedByteType; import net.imglib2.type.numeric.integer.UnsignedIntType; import net.imglib2.type.numeric.integer.UnsignedLongType; import net.imglib2.type.numeric.integer.UnsignedShortType; import net.imglib2.type.numeric.real.DoubleType; import net.imglib2.type.numeric.real.FloatType; import net.imglib2.type.volatiles.VolatileByteType; import net.imglib2.type.volatiles.VolatileDoubleType; import net.imglib2.type.volatiles.VolatileFloatType; import net.imglib2.type.volatiles.VolatileIntType; import net.imglib2.type.volatiles.VolatileLongType; import net.imglib2.type.volatiles.VolatileShortType; import net.imglib2.type.volatiles.VolatileUnsignedByteType; import net.imglib2.type.volatiles.VolatileUnsignedIntType; import net.imglib2.type.volatiles.VolatileUnsignedLongType; import net.imglib2.type.volatiles.VolatileUnsignedShortType; import net.imglib2.util.Cast; import net.imglib2.view.Views; import org.janelia.saalfeldlab.n5.DataBlock; import org.janelia.saalfeldlab.n5.DataType; import org.janelia.saalfeldlab.n5.DatasetAttributes; import org.janelia.saalfeldlab.n5.N5FSReader; import org.janelia.saalfeldlab.n5.N5Reader; import static bdv.img.n5.BdvN5Format.DATA_TYPE_KEY; import static bdv.img.n5.BdvN5Format.DOWNSAMPLING_FACTORS_KEY; import static bdv.img.n5.BdvN5Format.getPathName; public class N5ImageLoader implements ViewerImgLoader, MultiResolutionImgLoader { private final File n5File; // TODO: it would be good if this would not be needed // find available setups from the n5 private final AbstractSequenceDescription< ?, ?, ? > seq; /** * Maps setup id to {@link SetupImgLoader}. */ private final Map< Integer, SetupImgLoader > setupImgLoaders = new HashMap<>(); public N5ImageLoader( final File n5File, final AbstractSequenceDescription< ?, ?, ? > sequenceDescription ) { this.n5File = n5File; this.seq = sequenceDescription; } public File getN5File() { return n5File; } private volatile boolean isOpen = false; private FetcherThreads fetchers; private VolatileGlobalCellCache cache; private N5Reader n5; private void open() { if ( !isOpen ) { synchronized ( this ) { if ( isOpen ) return; try { this.n5 = new N5FSReader( n5File.getAbsolutePath() ); int maxNumLevels = 0; final List< ? extends BasicViewSetup > setups = seq.getViewSetupsOrdered(); for ( final BasicViewSetup setup : setups ) { final int setupId = setup.getId(); final SetupImgLoader setupImgLoader = createSetupImgLoader( setupId ); setupImgLoaders.put( setupId, setupImgLoader ); maxNumLevels = Math.max( maxNumLevels, setupImgLoader.numMipmapLevels() ); } final int numFetcherThreads = Math.max( 1, Runtime.getRuntime().availableProcessors() ); final BlockingFetchQueues< Callable< ? > > queue = new BlockingFetchQueues<>( maxNumLevels, numFetcherThreads ); fetchers = new FetcherThreads( queue, numFetcherThreads ); cache = new VolatileGlobalCellCache( queue ); } catch ( IOException e ) { throw new RuntimeException( e ); } isOpen = true; } } } /** * Clear the cache. Images that were obtained from * this loader before {@link #close()} will stop working. Requesting images * after {@link #close()} will cause the n5 to be reopened (with a * new cache). */ public void close() { if ( isOpen ) { synchronized ( this ) { if ( !isOpen ) return; fetchers.shutdown(); cache.clearCache(); isOpen = false; } } } @Override public SetupImgLoader getSetupImgLoader( final int setupId ) { open(); return setupImgLoaders.get( setupId ); } private < T extends NativeType< T >, V extends Volatile< T > & NativeType< V > > SetupImgLoader< T, V > createSetupImgLoader( final int setupId ) throws IOException { final String pathName = getPathName( setupId ); final DataType dataType = n5.getAttribute( pathName, DATA_TYPE_KEY, DataType.class ); switch ( dataType ) { case UINT8: return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedByteType(), new VolatileUnsignedByteType() ) ); case UINT16: return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedShortType(), new VolatileUnsignedShortType() ) ); case UINT32: return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedIntType(), new VolatileUnsignedIntType() ) ); case UINT64: return Cast.unchecked( new SetupImgLoader<>( setupId, new UnsignedLongType(), new VolatileUnsignedLongType() ) ); case INT8: return Cast.unchecked( new SetupImgLoader<>( setupId, new ByteType(), new VolatileByteType() ) ); case INT16: return Cast.unchecked( new SetupImgLoader<>( setupId, new ShortType(), new VolatileShortType() ) ); case INT32: return Cast.unchecked( new SetupImgLoader<>( setupId, new IntType(), new VolatileIntType() ) ); case INT64: return Cast.unchecked( new SetupImgLoader<>( setupId, new LongType(), new VolatileLongType() ) ); case FLOAT32: return Cast.unchecked( new SetupImgLoader<>( setupId, new FloatType(), new VolatileFloatType() ) ); case FLOAT64: return Cast.unchecked( new SetupImgLoader<>( setupId, new DoubleType(), new VolatileDoubleType() ) ); } return null; } @Override public CacheControl getCacheControl() { open(); return cache; } public class SetupImgLoader< T extends NativeType< T >, V extends Volatile< T > & NativeType< V > > extends AbstractViewerSetupImgLoader< T, V > implements MultiResolutionSetupImgLoader< T > { private final int setupId; private final double[][] mipmapResolutions; private final AffineTransform3D[] mipmapTransforms; public SetupImgLoader( final int setupId, final T type, final V volatileType ) throws IOException { super( type, volatileType ); this.setupId = setupId; final String pathName = getPathName( setupId ); mipmapResolutions = n5.getAttribute( pathName, DOWNSAMPLING_FACTORS_KEY, double[][].class ); mipmapTransforms = new AffineTransform3D[ mipmapResolutions.length ]; for ( int level = 0; level < mipmapResolutions.length; level++ ) mipmapTransforms[ level ] = MipmapTransforms.getMipmapTransformDefault( mipmapResolutions[ level ] ); } @Override public RandomAccessibleInterval< V > getVolatileImage( final int timepointId, final int level, final ImgLoaderHint... hints ) { return prepareCachedImage( timepointId, level, LoadingStrategy.BUDGETED, volatileType ); } @Override public RandomAccessibleInterval< T > getImage( final int timepointId, final int level, final ImgLoaderHint... hints ) { return prepareCachedImage( timepointId, level, LoadingStrategy.BLOCKING, type ); } @Override public Dimensions getImageSize( final int timepointId, final int level ) { try { final String pathName = getPathName( setupId, timepointId, level ); final DatasetAttributes attributes = n5.getDatasetAttributes( pathName ); return new FinalDimensions( attributes.getDimensions() ); } catch( Exception e ) { return null; } } @Override public double[][] getMipmapResolutions() { return mipmapResolutions; } @Override public AffineTransform3D[] getMipmapTransforms() { return mipmapTransforms; } @Override public int numMipmapLevels() { return mipmapResolutions.length; } @Override public VoxelDimensions getVoxelSize( final int timepointId ) { return null; } /** * Create a {@link CellImg} backed by the cache. */ private < T extends NativeType< T > > RandomAccessibleInterval< T > prepareCachedImage( final int timepointId, final int level, final LoadingStrategy loadingStrategy, final T type ) { try { final String pathName = getPathName( setupId, timepointId, level ); final DatasetAttributes attributes = n5.getDatasetAttributes( pathName ); final long[] dimensions = attributes.getDimensions(); final int[] cellDimensions = attributes.getBlockSize(); final CellGrid grid = new CellGrid( dimensions, cellDimensions ); final int priority = numMipmapLevels() - 1 - level; final CacheHints cacheHints = new CacheHints( loadingStrategy, priority, false ); final SimpleCacheArrayLoader< ? > loader = createCacheArrayLoader( n5, pathName ); return cache.createImg( grid, timepointId, setupId, level, cacheHints, loader, type ); } catch ( IOException e ) { System.err.println( String.format( "image data for timepoint %d setup %d level %d could not be found.", timepointId, setupId, level ) ); return Views.interval( new ConstantRandomAccessible<>( type.createVariable(), 3 ), new FinalInterval( 1, 1, 1 ) ); } } } private static class N5CacheArrayLoader< A > implements SimpleCacheArrayLoader< A > { private final N5Reader n5; private final String pathName; private final DatasetAttributes attributes; private final Function< DataBlock< ? >, A > createArray; N5CacheArrayLoader( final N5Reader n5, final String pathName, final DatasetAttributes attributes, final Function< DataBlock< ? >, A > createArray ) { this.n5 = n5; this.pathName = pathName; this.attributes = attributes; this.createArray = createArray; } @Override public A loadArray( final long[] gridPosition ) throws IOException { return createArray.apply( n5.readBlock( pathName, attributes, gridPosition ) ); } } public static SimpleCacheArrayLoader< ? > createCacheArrayLoader( final N5Reader n5, final String pathName ) throws IOException { final DatasetAttributes attributes = n5.getDatasetAttributes( pathName ); switch ( attributes.getDataType() ) { case UINT8: case INT8: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileByteArray( Cast.unchecked( dataBlock.getData() ), true ) ); case UINT16: case INT16: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileShortArray( Cast.unchecked( dataBlock.getData() ), true ) ); case UINT32: case INT32: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileIntArray( Cast.unchecked( dataBlock.getData() ), true ) ); case UINT64: case INT64: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileLongArray( Cast.unchecked( dataBlock.getData() ), true ) ); case FLOAT32: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileFloatArray( Cast.unchecked( dataBlock.getData() ), true ) ); case FLOAT64: return new N5CacheArrayLoader<>( n5, pathName, attributes, dataBlock -> new VolatileDoubleArray( Cast.unchecked( dataBlock.getData() ), true ) ); default: throw new IllegalArgumentException(); } } }
Handle missing n5 blocks (#104) handle missing n5 blocks by creating empty arrays TODO consider handling this in the CachedCellImg or possibly re-using arrays to reduce RAM consumption/ better utilize cache Co-authored-by: Christian Tischer <[email protected]>
src/main/java/bdv/img/n5/N5ImageLoader.java
Handle missing n5 blocks (#104)
<ide><path>rc/main/java/bdv/img/n5/N5ImageLoader.java <ide> import net.imglib2.type.volatiles.VolatileUnsignedShortType; <ide> import net.imglib2.util.Cast; <ide> import net.imglib2.view.Views; <del>import org.janelia.saalfeldlab.n5.DataBlock; <del>import org.janelia.saalfeldlab.n5.DataType; <del>import org.janelia.saalfeldlab.n5.DatasetAttributes; <del>import org.janelia.saalfeldlab.n5.N5FSReader; <del>import org.janelia.saalfeldlab.n5.N5Reader; <add>import org.janelia.saalfeldlab.n5.*; <ide> <ide> import static bdv.img.n5.BdvN5Format.DATA_TYPE_KEY; <ide> import static bdv.img.n5.BdvN5Format.DOWNSAMPLING_FACTORS_KEY; <ide> @Override <ide> public A loadArray( final long[] gridPosition ) throws IOException <ide> { <del> return createArray.apply( n5.readBlock( pathName, attributes, gridPosition ) ); <add> final DataBlock< ? > dataBlock = n5.readBlock( pathName, attributes, gridPosition ); <add> <add> if ( dataBlock == null ) <add> return createEmptyArray( gridPosition ); <add> else <add> return createArray.apply( dataBlock ); <add> } <add> <add> private A createEmptyArray( long[] gridPosition ) <add> { <add> final int[] blockSize = attributes.getBlockSize(); <add> final int n = blockSize[ 0 ] * blockSize[ 1 ] * blockSize[ 2 ]; <add> switch ( attributes.getDataType() ) <add> { <add> case UINT8: <add> case INT8: <add> return createArray.apply( new ByteArrayDataBlock( blockSize, gridPosition, new byte[ n ] ) ); <add> case UINT16: <add> case INT16: <add> return createArray.apply( new ShortArrayDataBlock( blockSize, gridPosition, new short[ n ] ) ); <add> case UINT32: <add> case INT32: <add> return createArray.apply( new IntArrayDataBlock( blockSize, gridPosition, new int[ n ] ) ); <add> case UINT64: <add> case INT64: <add> return createArray.apply( new LongArrayDataBlock( blockSize, gridPosition, new long[ n ] ) ); <add> case FLOAT32: <add> return createArray.apply( new FloatArrayDataBlock( blockSize, gridPosition, new float[ n ] ) ); <add> case FLOAT64: <add> return createArray.apply( new DoubleArrayDataBlock( blockSize, gridPosition, new double[ n ] ) ); <add> default: <add> throw new UnsupportedOperationException("Data type not supported: " + attributes.getDataType()); <add> } <ide> } <ide> } <ide>
Java
apache-2.0
c7e6e4e004be97744d24bbf3f235119e1fb22f97
0
btmura/rbb
/* * Copyright (C) 2012 Brian Muramatsu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmura.android.reddit.activity; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentManager.OnBackStackChangedListener; import android.app.FragmentTransaction; import android.app.LoaderManager.LoaderCallbacks; import android.content.Intent; import android.content.Loader; import android.content.SharedPreferences; import android.os.Bundle; import android.os.StrictMode; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.MenuItem; import android.view.View; import com.btmura.android.reddit.Debug; import com.btmura.android.reddit.LoaderIds; import com.btmura.android.reddit.R; import com.btmura.android.reddit.content.AccountLoader; import com.btmura.android.reddit.content.AccountLoader.AccountResult; import com.btmura.android.reddit.entity.Subreddit; import com.btmura.android.reddit.entity.Thing; import com.btmura.android.reddit.fragment.ControlFragment; import com.btmura.android.reddit.fragment.GlobalMenuFragment; import com.btmura.android.reddit.fragment.SubredditListFragment; import com.btmura.android.reddit.fragment.SubredditListFragment.OnSubredditSelectedListener; import com.btmura.android.reddit.fragment.SubredditNameHolder; import com.btmura.android.reddit.fragment.ThingListFragment; import com.btmura.android.reddit.fragment.ThingListFragment.OnThingSelectedListener; import com.btmura.android.reddit.fragment.ThingMenuFragment; import com.btmura.android.reddit.fragment.ThingMenuFragment.ThingPagerHolder; import com.btmura.android.reddit.widget.AccountSpinnerAdapter; import com.btmura.android.reddit.widget.ThingPagerAdapter; public class LoginBrowserActivity extends Activity implements LoaderCallbacks<AccountResult>, OnNavigationListener, OnSubredditSelectedListener, OnThingSelectedListener, OnBackStackChangedListener, SubredditNameHolder, ThingPagerHolder { public static final String TAG = "LoginBrowserActivity"; private ActionBar bar; private AccountSpinnerAdapter adapter; private boolean isSinglePane; private ViewPager thingPager; private SharedPreferences prefs; @Override protected void onCreate(Bundle savedInstanceState) { if (Debug.DEBUG_STRICT_MODE) { StrictMode.enableDefaults(); } super.onCreate(savedInstanceState); setContentView(R.layout.browser); setInitialFragments(savedInstanceState); setActionBar(); setViews(); getLoaderManager().initLoader(LoaderIds.ACCOUNTS, null, this); } private void setInitialFragments(Bundle savedInstanceState) { if (savedInstanceState == null) { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(GlobalMenuFragment.newInstance(GlobalMenuFragment.FLAG_SHOW_MANAGE_ACCOUNTS), GlobalMenuFragment.TAG); ft.commit(); } } private void setActionBar() { bar = getActionBar(); bar.setDisplayShowTitleEnabled(false); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); adapter = new AccountSpinnerAdapter(this); bar.setListNavigationCallbacks(adapter, this); } private void setViews() { isSinglePane = findViewById(R.id.thing_list_container) == null; if (!isSinglePane) { thingPager = (ViewPager) findViewById(R.id.thing_pager); getFragmentManager().addOnBackStackChangedListener(this); } } public Loader<AccountResult> onCreateLoader(int id, Bundle args) { return new AccountLoader(this); } public void onLoadFinished(Loader<AccountResult> loader, AccountResult result) { adapter.setAccountNames(result.accountNames); prefs = result.prefs; int index = AccountLoader.getLastAccountIndex(prefs, result.accountNames); bar.setSelectedNavigationItem(index); } public void onLoaderReset(Loader<AccountResult> loader) { adapter.setAccountNames(null); } public boolean onNavigationItemSelected(int itemPosition, long itemId) { if (Debug.DEBUG_ACTIVITY) { Log.d(TAG, "onNavigationItemSelected itemPosition:" + itemPosition); } String accountName = adapter.getItem(itemPosition); AccountLoader.setLastAccount(prefs, accountName); SubredditListFragment f = getSubredditListFragment(); if (f == null || !f.getAccountName().equals(accountName)) { f = SubredditListFragment.newInstance(accountName, null, 0); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.subreddit_list_container, f, SubredditListFragment.TAG); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.commit(); } return true; } public void onSubredditLoaded(Subreddit subreddit) { if (!isSinglePane) { loadSubredditMultiPane(subreddit); } } protected void loadSubredditMultiPane(Subreddit subreddit) { ThingListFragment tf = getThingListFragment(); if (tf == null) { ControlFragment cf = ControlFragment.newInstance(subreddit, null, -1, 0); tf = ThingListFragment.newInstance(getAccountName(), subreddit, 0, 0); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(cf, ControlFragment.TAG); ft.replace(R.id.thing_list_container, tf, ThingListFragment.TAG); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.commit(); } } public void onSubredditSelected(Subreddit subreddit) { if (isSinglePane) { selectSubredditSinglePane(subreddit); } else { selectSubredditMultiPane(subreddit); } } protected void selectSubredditSinglePane(Subreddit subreddit) { Intent intent = new Intent(this, ThingListActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.putExtra(ThingListActivity.EXTRA_SUBREDDIT, subreddit); intent.putExtra(ThingListActivity.EXTRA_FLAGS, 0); startActivity(intent); } protected void selectSubredditMultiPane(Subreddit subreddit) { safePopBackStackImmediate(); ControlFragment cf = ControlFragment.newInstance(subreddit, null, -1, 0); ThingListFragment tf = ThingListFragment.newInstance(getAccountName(), subreddit, 0, 0); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(cf, ControlFragment.TAG); ft.replace(R.id.thing_list_container, tf, ThingListFragment.TAG); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.commit(); } public void onThingSelected(Thing thing, int position) { if (isSinglePane) { selectThingSinglePane(thing); } else { selectThingMultiPane(thing, position); } } protected void selectThingSinglePane(Thing thing) { Intent intent = new Intent(this, ThingActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.putExtra(ThingActivity.EXTRA_THING, thing); intent.putExtra(ThingActivity.EXTRA_FLAGS, 0); startActivity(intent); } protected void selectThingMultiPane(Thing thing, int thingPosition) { safePopBackStackImmediate(); ControlFragment cf = getControlFragment(); cf = ControlFragment.newInstance(cf.getSubreddit(), thing, thingPosition, 0); ThingMenuFragment tf = ThingMenuFragment.newInstance(thing); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(cf, ControlFragment.TAG); ft.add(tf, ThingMenuFragment.TAG); ft.addToBackStack(null); ft.commit(); ThingPagerAdapter adapter = new ThingPagerAdapter(getFragmentManager(), thing); thingPager.setAdapter(adapter); } public int getThingBodyWidth() { return 0; } public void onBackStackChanged() { boolean hasThing = getThingMenuFragment() != null; bar.setDisplayHomeAsUpEnabled(hasThing); thingPager.setVisibility(hasThing ? View.VISIBLE : View.GONE); } public CharSequence getSubredditName() { return null; } public ViewPager getPager() { return thingPager; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: getFragmentManager().popBackStack(); return true; default: return super.onOptionsItemSelected(item); } } private String getAccountName() { return adapter.getAccountName(bar.getSelectedNavigationIndex()); } private void safePopBackStackImmediate() { FragmentManager fm = getFragmentManager(); if (fm.getBackStackEntryCount() > 0) { fm.removeOnBackStackChangedListener(this); fm.popBackStackImmediate(); fm.addOnBackStackChangedListener(this); } } private ControlFragment getControlFragment() { return (ControlFragment) getFragmentManager().findFragmentByTag(ControlFragment.TAG); } private SubredditListFragment getSubredditListFragment() { return (SubredditListFragment) getFragmentManager().findFragmentByTag(SubredditListFragment.TAG); } private ThingListFragment getThingListFragment() { return (ThingListFragment) getFragmentManager().findFragmentByTag(ThingListFragment.TAG); } private ThingMenuFragment getThingMenuFragment() { return (ThingMenuFragment) getFragmentManager().findFragmentByTag(ThingMenuFragment.TAG); } }
src/com/btmura/android/reddit/activity/LoginBrowserActivity.java
/* * Copyright (C) 2012 Brian Muramatsu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmura.android.reddit.activity; import android.app.ActionBar; import android.app.FragmentManager; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.FragmentManager.OnBackStackChangedListener; import android.app.FragmentTransaction; import android.app.LoaderManager.LoaderCallbacks; import android.content.Intent; import android.content.Loader; import android.content.SharedPreferences; import android.os.Bundle; import android.os.StrictMode; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.View; import com.btmura.android.reddit.Debug; import com.btmura.android.reddit.LoaderIds; import com.btmura.android.reddit.R; import com.btmura.android.reddit.content.AccountLoader; import com.btmura.android.reddit.content.AccountLoader.AccountResult; import com.btmura.android.reddit.entity.Subreddit; import com.btmura.android.reddit.entity.Thing; import com.btmura.android.reddit.fragment.ControlFragment; import com.btmura.android.reddit.fragment.GlobalMenuFragment; import com.btmura.android.reddit.fragment.SubredditListFragment; import com.btmura.android.reddit.fragment.SubredditListFragment.OnSubredditSelectedListener; import com.btmura.android.reddit.fragment.SubredditNameHolder; import com.btmura.android.reddit.fragment.ThingListFragment; import com.btmura.android.reddit.fragment.ThingListFragment.OnThingSelectedListener; import com.btmura.android.reddit.fragment.ThingMenuFragment; import com.btmura.android.reddit.fragment.ThingMenuFragment.ThingPagerHolder; import com.btmura.android.reddit.widget.AccountSpinnerAdapter; import com.btmura.android.reddit.widget.ThingPagerAdapter; public class LoginBrowserActivity extends Activity implements LoaderCallbacks<AccountResult>, OnNavigationListener, OnSubredditSelectedListener, OnThingSelectedListener, OnBackStackChangedListener, SubredditNameHolder, ThingPagerHolder { public static final String TAG = "LoginBrowserActivity"; private ActionBar bar; private AccountSpinnerAdapter adapter; private boolean isSinglePane; private ViewPager thingPager; private SharedPreferences prefs; @Override protected void onCreate(Bundle savedInstanceState) { if (Debug.DEBUG_STRICT_MODE) { StrictMode.enableDefaults(); } super.onCreate(savedInstanceState); setContentView(R.layout.browser); setInitialFragments(savedInstanceState); setActionBar(); setViews(); getLoaderManager().initLoader(LoaderIds.ACCOUNTS, null, this); } private void setInitialFragments(Bundle savedInstanceState) { if (savedInstanceState == null) { FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(GlobalMenuFragment.newInstance(GlobalMenuFragment.FLAG_SHOW_MANAGE_ACCOUNTS), GlobalMenuFragment.TAG); ft.commit(); } } private void setActionBar() { bar = getActionBar(); bar.setDisplayShowTitleEnabled(false); bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); adapter = new AccountSpinnerAdapter(this); bar.setListNavigationCallbacks(adapter, this); } private void setViews() { isSinglePane = findViewById(R.id.thing_list_container) == null; if (!isSinglePane) { thingPager = (ViewPager) findViewById(R.id.thing_pager); getFragmentManager().addOnBackStackChangedListener(this); } } public Loader<AccountResult> onCreateLoader(int id, Bundle args) { return new AccountLoader(this); } public void onLoadFinished(Loader<AccountResult> loader, AccountResult result) { adapter.setAccountNames(result.accountNames); prefs = result.prefs; int index = AccountLoader.getLastAccountIndex(prefs, result.accountNames); bar.setSelectedNavigationItem(index); } public void onLoaderReset(Loader<AccountResult> loader) { adapter.setAccountNames(null); } public boolean onNavigationItemSelected(int itemPosition, long itemId) { if (Debug.DEBUG_ACTIVITY) { Log.d(TAG, "onNavigationItemSelected itemPosition:" + itemPosition); } String accountName = adapter.getItem(itemPosition); AccountLoader.setLastAccount(prefs, accountName); SubredditListFragment f = getSubredditListFragment(); if (f == null || !f.getAccountName().equals(accountName)) { f = SubredditListFragment.newInstance(accountName, null, 0); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.replace(R.id.subreddit_list_container, f, SubredditListFragment.TAG); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.commit(); } return true; } public void onSubredditLoaded(Subreddit subreddit) { if (!isSinglePane) { loadSubredditMultiPane(subreddit); } } protected void loadSubredditMultiPane(Subreddit subreddit) { ThingListFragment tf = getThingListFragment(); if (tf == null) { ControlFragment cf = ControlFragment.newInstance(subreddit, null, -1, 0); tf = ThingListFragment.newInstance(getAccountName(), subreddit, 0, 0); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(cf, ControlFragment.TAG); ft.replace(R.id.thing_list_container, tf, ThingListFragment.TAG); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.commit(); } } public void onSubredditSelected(Subreddit subreddit) { if (isSinglePane) { selectSubredditSinglePane(subreddit); } else { selectSubredditMultiPane(subreddit); } } protected void selectSubredditSinglePane(Subreddit subreddit) { Intent intent = new Intent(this, ThingListActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.putExtra(ThingListActivity.EXTRA_SUBREDDIT, subreddit); intent.putExtra(ThingListActivity.EXTRA_FLAGS, 0); startActivity(intent); } protected void selectSubredditMultiPane(Subreddit subreddit) { safePopBackStackImmediate(); ControlFragment cf = ControlFragment.newInstance(subreddit, null, -1, 0); ThingListFragment tf = ThingListFragment.newInstance(getAccountName(), subreddit, 0, 0); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(cf, ControlFragment.TAG); ft.replace(R.id.thing_list_container, tf, ThingListFragment.TAG); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.commit(); } public void onThingSelected(Thing thing, int position) { if (isSinglePane) { selectThingSinglePane(thing); } else { selectThingMultiPane(thing, position); } } protected void selectThingSinglePane(Thing thing) { Intent intent = new Intent(this, ThingActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.putExtra(ThingActivity.EXTRA_THING, thing); intent.putExtra(ThingActivity.EXTRA_FLAGS, 0); startActivity(intent); } protected void selectThingMultiPane(Thing thing, int thingPosition) { safePopBackStackImmediate(); ControlFragment cf = getControlFragment(); cf = ControlFragment.newInstance(cf.getSubreddit(), thing, thingPosition, 0); ThingMenuFragment tf = ThingMenuFragment.newInstance(thing); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.add(cf, ControlFragment.TAG); ft.add(tf, ThingMenuFragment.TAG); ft.addToBackStack(null); ft.commit(); ThingPagerAdapter adapter = new ThingPagerAdapter(getFragmentManager(), thing); thingPager.setAdapter(adapter); } public int getThingBodyWidth() { return 0; } public void onBackStackChanged() { if (getThingMenuFragment() != null) { thingPager.setVisibility(View.VISIBLE); } else { thingPager.setVisibility(View.GONE); } } public CharSequence getSubredditName() { return null; } public ViewPager getPager() { return thingPager; } private String getAccountName() { return adapter.getAccountName(bar.getSelectedNavigationIndex()); } private void safePopBackStackImmediate() { FragmentManager fm = getFragmentManager(); if (fm.getBackStackEntryCount() > 0) { fm.removeOnBackStackChangedListener(this); fm.popBackStackImmediate(); fm.addOnBackStackChangedListener(this); } } private ControlFragment getControlFragment() { return (ControlFragment) getFragmentManager().findFragmentByTag(ControlFragment.TAG); } private SubredditListFragment getSubredditListFragment() { return (SubredditListFragment) getFragmentManager().findFragmentByTag(SubredditListFragment.TAG); } private ThingListFragment getThingListFragment() { return (ThingListFragment) getFragmentManager().findFragmentByTag(ThingListFragment.TAG); } private ThingMenuFragment getThingMenuFragment() { return (ThingMenuFragment) getFragmentManager().findFragmentByTag(ThingMenuFragment.TAG); } }
Add back home up button support
src/com/btmura/android/reddit/activity/LoginBrowserActivity.java
Add back home up button support
<ide><path>rc/com/btmura/android/reddit/activity/LoginBrowserActivity.java <ide> package com.btmura.android.reddit.activity; <ide> <ide> import android.app.ActionBar; <del>import android.app.FragmentManager; <ide> import android.app.ActionBar.OnNavigationListener; <ide> import android.app.Activity; <add>import android.app.FragmentManager; <ide> import android.app.FragmentManager.OnBackStackChangedListener; <ide> import android.app.FragmentTransaction; <ide> import android.app.LoaderManager.LoaderCallbacks; <ide> import android.os.StrictMode; <ide> import android.support.v4.view.ViewPager; <ide> import android.util.Log; <add>import android.view.MenuItem; <ide> import android.view.View; <ide> <ide> import com.btmura.android.reddit.Debug; <ide> } <ide> <ide> public void onBackStackChanged() { <del> if (getThingMenuFragment() != null) { <del> thingPager.setVisibility(View.VISIBLE); <del> } else { <del> thingPager.setVisibility(View.GONE); <del> } <add> boolean hasThing = getThingMenuFragment() != null; <add> bar.setDisplayHomeAsUpEnabled(hasThing); <add> thingPager.setVisibility(hasThing ? View.VISIBLE : View.GONE); <ide> } <ide> <ide> public CharSequence getSubredditName() { <ide> <ide> public ViewPager getPager() { <ide> return thingPager; <add> } <add> <add> @Override <add> public boolean onOptionsItemSelected(MenuItem item) { <add> switch (item.getItemId()) { <add> case android.R.id.home: <add> getFragmentManager().popBackStack(); <add> return true; <add> <add> default: <add> return super.onOptionsItemSelected(item); <add> } <ide> } <ide> <ide> private String getAccountName() {
Java
lgpl-2.1
71f45f765962b76c1a15e8764e9d724e72f28b88
0
spotbugs/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,sewe/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,sewe/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2004-2006 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.detect; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.LineNumberTable; import edu.umd.cs.findbugs.BugAccumulator; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.LocalVariableAnnotation; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.SignatureParser; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; public class FindSelfComparison extends OpcodeStackDetector { final BugAccumulator bugAccumulator; public FindSelfComparison(BugReporter bugReporter) { this.bugAccumulator = new BugAccumulator(bugReporter); } String f; String className; int state; int putFieldRegister; int putFieldPC = Integer.MIN_VALUE; OpcodeStack.Item putFieldObj; OpcodeStack.Item putFieldValue; XField putFieldXField; @Override public void visit(Code obj) { // System.out.println(getFullyQualifiedMethodName()); whichRegister = -1; registerLoadCount = 0; state = 0; resetDoubleAssignmentState(); super.visit(obj); resetDoubleAssignmentState(); bugAccumulator.reportAccumulatedBugs(); } /** * */ private void resetDoubleAssignmentState() { putFieldPC = Integer.MIN_VALUE; putFieldXField = null; putFieldValue = null; putFieldObj = null; } @Override public void sawBranchTo(int target) { resetDoubleAssignmentState(); } @Override public void sawOpcode(int seen) { // System.out.println(getPC() + " " + OPCODE_NAMES[seen] + " " + whichRegister + " " + registerLoadCount); checkPUTFIELD: if (seen == PUTFIELD) { OpcodeStack.Item obj = stack.getStackItem(1); OpcodeStack.Item value = stack.getStackItem(0); XField f = getXFieldOperand(); if (putFieldPC + 10 > getPC() && f.equals(putFieldXField) && obj.equals(putFieldObj)) { LineNumberTable table = getCode().getLineNumberTable(); if (table != null) { int first = table.getSourceLine(putFieldPC); int second = table.getSourceLine(getPC()); if (first+1 < second) break checkPUTFIELD; } else if (putFieldPC + 4 < getPC()) break checkPUTFIELD; int priority = value.equals(putFieldValue) ? NORMAL_PRIORITY : HIGH_PRIORITY; bugAccumulator.accumulateBug(new BugInstance(this, "SA_FIELD_DOUBLE_ASSIGNMENT", priority) .addClassAndMethod(this) .addReferencedField(this), this); } putFieldPC = getPC(); putFieldXField = f; putFieldObj = obj; putFieldValue = value; } else if (isReturn(seen)) resetDoubleAssignmentState(); if (false) switch (state) { case 0: if (seen == DUP_X1) state = 4; break; case 4: if (seen == PUTFIELD) { f = getRefConstantOperand(); className = getClassConstantOperand(); OpcodeStack.Item item1 = stack.getStackItem(1); putFieldRegister = item1.getRegisterNumber(); if (putFieldRegister >= 0) state = 5; else state = 0; } else state = 0; break; case 5: if (seen == PUTFIELD && getRefConstantOperand().equals(f) && getClassConstantOperand().equals(className)) { OpcodeStack.Item item1 = stack.getStackItem(1); if (putFieldRegister == item1.getRegisterNumber()) bugAccumulator.accumulateBug(new BugInstance(this, "SA_FIELD_DOUBLE_ASSIGNMENT", NORMAL_PRIORITY) .addClassAndMethod(this) .addReferencedField(this), this); } state = 0; break; } switch (seen) { case INVOKEVIRTUAL: case INVOKEINTERFACE: if (getClassName().toLowerCase().indexOf("test") >= 0) break; if (getMethodName().toLowerCase().indexOf("test") >= 0) break; if (getSuperclassName().toLowerCase().indexOf("test") >= 0) break; if (getNextOpcode() == POP) break; String name = getNameConstantOperand(); if (name.equals("equals") || name.equals("compareTo")) { String sig = getSigConstantOperand(); SignatureParser parser = new SignatureParser(sig); if (parser.getNumParameters() == 1 && (name.equals("equals") && sig.endsWith(";)Z") || name.equals("compareTo") && sig.endsWith(";)I"))) checkForSelfOperation(seen, "COMPARISON"); } break; case LOR: case LAND: case LXOR: case LSUB: case IOR: case IAND: case IXOR: case ISUB: checkForSelfOperation(seen, "COMPUTATION"); break; case FCMPG: case DCMPG: case DCMPL: case FCMPL: break; case LCMP: case IF_ACMPEQ: case IF_ACMPNE: case IF_ICMPNE: case IF_ICMPEQ: case IF_ICMPGT: case IF_ICMPLE: case IF_ICMPLT: case IF_ICMPGE: checkForSelfOperation(seen, "COMPARISON"); } if (isRegisterLoad() && seen != IINC) { if (getRegisterOperand() == whichRegister) registerLoadCount++; else { whichRegister = getRegisterOperand(); registerLoadCount = 1; } } else { whichRegister = -1; registerLoadCount = 0; } } int whichRegister; int registerLoadCount; private void checkForSelfOperation(int opCode, String op) { { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); if (item0.getSignature().equals("D") || item0.getSignature().equals("F")) return; if (item1.getSignature().equals("D") || item1.getSignature().equals("F")) return; XField field0 = item0.getXField(); XField field1 = item1.getXField(); int fr0 = item0.getFieldLoadedFromRegister(); int fr1 = item1.getFieldLoadedFromRegister(); if (field0 != null && field0.equals(field1) && fr0 != -1 && fr0 == fr1) bugAccumulator.accumulateBug(new BugInstance(this, "SA_FIELD_SELF_" + op, NORMAL_PRIORITY) .addClassAndMethod(this).addField(field0), this); else if (opCode == IXOR && item0.equals(item1)) { LocalVariableAnnotation localVariableAnnotation = LocalVariableAnnotation .getLocalVariableAnnotation(this, item0); if (localVariableAnnotation != null) bugAccumulator.accumulateBug(new BugInstance(this, "SA_LOCAL_SELF_" + op, HIGH_PRIORITY) .addClassAndMethod(this).add( localVariableAnnotation),this); } else if (opCode == ISUB && registerLoadCount >= 2) { // let FindSelfComparison2 report this; more accurate bugAccumulator.accumulateBug(new BugInstance(this, "SA_LOCAL_SELF_" + op, (opCode == ISUB || opCode == LSUB || opCode == INVOKEINTERFACE || opCode == INVOKEVIRTUAL) ? NORMAL_PRIORITY : HIGH_PRIORITY) .addClassAndMethod(this).add( LocalVariableAnnotation .getLocalVariableAnnotation( getMethod(), whichRegister, getPC(), getPC() - 1)),this); } } } }
findbugs/src/java/edu/umd/cs/findbugs/detect/FindSelfComparison.java
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2004-2006 University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.detect; import org.apache.bcel.classfile.Code; import edu.umd.cs.findbugs.BugAccumulator; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.LocalVariableAnnotation; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ba.SignatureParser; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; public class FindSelfComparison extends OpcodeStackDetector { final BugAccumulator bugAccumulator; public FindSelfComparison(BugReporter bugReporter) { this.bugAccumulator = new BugAccumulator(bugReporter); } String f; String className; int state; int putFieldRegister; int putFieldPC = Integer.MIN_VALUE; OpcodeStack.Item putFieldObj; OpcodeStack.Item putFieldValue; XField putFieldXField; @Override public void visit(Code obj) { whichRegister = -1; registerLoadCount = 0; state = 0; resetDoubleAssignmentState(); super.visit(obj); resetDoubleAssignmentState(); bugAccumulator.reportAccumulatedBugs(); } /** * */ private void resetDoubleAssignmentState() { putFieldPC = Integer.MIN_VALUE; putFieldXField = null; putFieldValue = null; putFieldObj = null; } @Override public void sawBranchTo(int target) { resetDoubleAssignmentState(); } @Override public void sawOpcode(int seen) { // System.out.println(getPC() + " " + OPCODE_NAMES[seen] + " " + whichRegister + " " + registerLoadCount); if (seen == PUTFIELD) { OpcodeStack.Item obj = stack.getStackItem(1); OpcodeStack.Item value = stack.getStackItem(0); XField f = getXFieldOperand(); if (putFieldPC + 10 > getPC() && f.equals(putFieldXField) && obj.equals(putFieldObj)) { int priority = value.equals(putFieldValue) ? NORMAL_PRIORITY : HIGH_PRIORITY; bugAccumulator.accumulateBug(new BugInstance(this, "SA_FIELD_DOUBLE_ASSIGNMENT", priority) .addClassAndMethod(this) .addReferencedField(this), this); } putFieldPC = getPC(); putFieldXField = f; putFieldObj = obj; putFieldValue = value; } else if (isReturn(seen)) resetDoubleAssignmentState(); if (false) switch (state) { case 0: if (seen == DUP_X1) state = 4; break; case 4: if (seen == PUTFIELD) { f = getRefConstantOperand(); className = getClassConstantOperand(); OpcodeStack.Item item1 = stack.getStackItem(1); putFieldRegister = item1.getRegisterNumber(); if (putFieldRegister >= 0) state = 5; else state = 0; } else state = 0; break; case 5: if (seen == PUTFIELD && getRefConstantOperand().equals(f) && getClassConstantOperand().equals(className)) { OpcodeStack.Item item1 = stack.getStackItem(1); if (putFieldRegister == item1.getRegisterNumber()) bugAccumulator.accumulateBug(new BugInstance(this, "SA_FIELD_DOUBLE_ASSIGNMENT", NORMAL_PRIORITY) .addClassAndMethod(this) .addReferencedField(this), this); } state = 0; break; } switch (seen) { case INVOKEVIRTUAL: case INVOKEINTERFACE: if (getClassName().toLowerCase().indexOf("test") >= 0) break; if (getMethodName().toLowerCase().indexOf("test") >= 0) break; if (getSuperclassName().toLowerCase().indexOf("test") >= 0) break; if (getNextOpcode() == POP) break; String name = getNameConstantOperand(); if (name.equals("equals") || name.equals("compareTo")) { String sig = getSigConstantOperand(); SignatureParser parser = new SignatureParser(sig); if (parser.getNumParameters() == 1 && (name.equals("equals") && sig.endsWith(";)Z") || name.equals("compareTo") && sig.endsWith(";)I"))) checkForSelfOperation(seen, "COMPARISON"); } break; case LOR: case LAND: case LXOR: case LSUB: case IOR: case IAND: case IXOR: case ISUB: checkForSelfOperation(seen, "COMPUTATION"); break; case FCMPG: case DCMPG: case DCMPL: case FCMPL: break; case LCMP: case IF_ACMPEQ: case IF_ACMPNE: case IF_ICMPNE: case IF_ICMPEQ: case IF_ICMPGT: case IF_ICMPLE: case IF_ICMPLT: case IF_ICMPGE: checkForSelfOperation(seen, "COMPARISON"); } if (isRegisterLoad() && seen != IINC) { if (getRegisterOperand() == whichRegister) registerLoadCount++; else { whichRegister = getRegisterOperand(); registerLoadCount = 1; } } else { whichRegister = -1; registerLoadCount = 0; } } int whichRegister; int registerLoadCount; private void checkForSelfOperation(int opCode, String op) { { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); if (item0.getSignature().equals("D") || item0.getSignature().equals("F")) return; if (item1.getSignature().equals("D") || item1.getSignature().equals("F")) return; XField field0 = item0.getXField(); XField field1 = item1.getXField(); int fr0 = item0.getFieldLoadedFromRegister(); int fr1 = item1.getFieldLoadedFromRegister(); if (field0 != null && field0.equals(field1) && fr0 != -1 && fr0 == fr1) bugAccumulator.accumulateBug(new BugInstance(this, "SA_FIELD_SELF_" + op, NORMAL_PRIORITY) .addClassAndMethod(this).addField(field0), this); else if (opCode == IXOR && item0.equals(item1)) { LocalVariableAnnotation localVariableAnnotation = LocalVariableAnnotation .getLocalVariableAnnotation(this, item0); if (localVariableAnnotation != null) bugAccumulator.accumulateBug(new BugInstance(this, "SA_LOCAL_SELF_" + op, HIGH_PRIORITY) .addClassAndMethod(this).add( localVariableAnnotation),this); } else if (opCode == ISUB && registerLoadCount >= 2) { // let FindSelfComparison2 report this; more accurate bugAccumulator.accumulateBug(new BugInstance(this, "SA_LOCAL_SELF_" + op, (opCode == ISUB || opCode == LSUB || opCode == INVOKEINTERFACE || opCode == INVOKEVIRTUAL) ? NORMAL_PRIORITY : HIGH_PRIORITY) .addClassAndMethod(this).add( LocalVariableAnnotation .getLocalVariableAnnotation( getMethod(), whichRegister, getPC(), getPC() - 1)),this); } } } }
Fix for the false positives? git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@11339 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/detect/FindSelfComparison.java
Fix for the false positives?
<ide><path>indbugs/src/java/edu/umd/cs/findbugs/detect/FindSelfComparison.java <ide> package edu.umd.cs.findbugs.detect; <ide> <ide> import org.apache.bcel.classfile.Code; <add>import org.apache.bcel.classfile.LineNumberTable; <ide> <ide> import edu.umd.cs.findbugs.BugAccumulator; <ide> import edu.umd.cs.findbugs.BugInstance; <ide> <ide> @Override <ide> public void visit(Code obj) { <add> // System.out.println(getFullyQualifiedMethodName()); <ide> whichRegister = -1; <ide> registerLoadCount = 0; <ide> state = 0; <ide> public void sawOpcode(int seen) { <ide> // System.out.println(getPC() + " " + OPCODE_NAMES[seen] + " " + whichRegister + " " + registerLoadCount); <ide> <del> if (seen == PUTFIELD) { <add> checkPUTFIELD: if (seen == PUTFIELD) { <ide> OpcodeStack.Item obj = stack.getStackItem(1); <ide> OpcodeStack.Item value = stack.getStackItem(0); <ide> XField f = getXFieldOperand(); <ide> if (putFieldPC + 10 > getPC() <ide> && f.equals(putFieldXField) <ide> && obj.equals(putFieldObj)) { <add> LineNumberTable table = getCode().getLineNumberTable(); <add> if (table != null) { <add> int first = table.getSourceLine(putFieldPC); <add> int second = table.getSourceLine(getPC()); <add> if (first+1 < second) <add> break checkPUTFIELD; <add> } else if (putFieldPC + 4 < getPC()) <add> break checkPUTFIELD; <ide> int priority = value.equals(putFieldValue) ? NORMAL_PRIORITY : HIGH_PRIORITY; <ide> bugAccumulator.accumulateBug(new BugInstance(this, "SA_FIELD_DOUBLE_ASSIGNMENT", priority) <ide> .addClassAndMethod(this)
Java
bsd-3-clause
29083ff2c7800a2f54a568838a6c580573e6d8ff
0
Pesegato/MonkeySheet
package com.pesegato.collision; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Spatial; import com.pesegato.collision.hitbox.HBRect; import org.dyn4j.collision.CategoryFilter; import org.dyn4j.collision.broadphase.BroadphaseDetector; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.BodyFixture; import org.dyn4j.dynamics.World; import org.dyn4j.geometry.Convex; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Transform; import org.dyn4j.geometry.Vector2; public class Dyn4JShapeControl extends IDyn4JControl { protected Body body; BodyFixture fixture; //private World world; BroadphaseDetector broadphase; HBRect hbRect; public Dyn4JShapeControl(Convex shape, MassType massType, HBRect hbRect ) { this.hbRect=hbRect; body = new Body(); fixture = new BodyFixture(shape); body.addFixture(fixture); body.setMass(massType); body.setAutoSleepingEnabled(false); fixture.setUserData(hbRect.id); } public void setFilter(CategoryFilter cf){ fixture.setFilter(cf); } public Dyn4JShapeControl(Body body, MassType massType, long id ) { this.body = body; for (BodyFixture bf:body.getFixtures()) bf.setUserData(id); body.setMass(massType); body.setAutoSleepingEnabled(true); } Dyn4JShapeControl(Convex shape, MassType massType, Double weight, //in kg/m Double friction, // low = more slippery Double restitution// more = more bouncy ) { body = new Body(); fixture = new BodyFixture(shape); fixture.setFriction(friction); fixture.setRestitution(restitution); fixture.setDensity(weight); body.addFixture(fixture); body.setMass(massType); body.setAutoSleepingEnabled(true); } public void addToWorld(BroadphaseDetector broadphase) { this.broadphase = broadphase; broadphase.add(body); } public void removeFromWorld() { this.broadphase.remove(body); } /* @Override void addToWorld(World world) { this.world = world; world.addBody(body); } @Override public void removeFromWorld() { if (world==null) return; boolean removed=this.world.removeBody(body); System.out.println("removed "+removed); BroadphaseDetector bp = world.getBroadphaseDetector(); boolean stillThere = bp.contains(body); for (BodyFixture fixture : body.getFixtures()) { stillThere |= bp.contains(body, fixture); } if (stillThere) { // I would need to see more code around the way the body is being removed System.out.println("still there"); } this.world=null; } */ // more = more bouncy void setRestitution(Double restitution) { fixture.setRestitution(restitution); } // more = in kg/m void setDensity(Double kg) { fixture.setDensity(kg); } // low = more slippery void setFriction(Double friction) { fixture.setFriction(friction); } @Override public void setSpatial(Spatial spatial) { this.spatial = spatial; body.translate(new Double(spatial.getLocalTranslation().x), new Double(spatial.getLocalTranslation().y)); //TODO: set initial rotation of the dyn4j-Body } @Override protected void controlUpdate(float tpf) { //Dyn4JAppState handles everything } @Override protected void controlRender(RenderManager rm, ViewPort vp) { } public Body getBody(){ return body; } private Double lastAngle=-1d; private Transform lastTransform = new Transform(); private final static Float negligibleAngleRotation = 0.001f; void updatePhysics(BroadphaseDetector bp, float tpf){ if (bp.contains(body)) bp.update(body); } void updateDraw(float tpf) { Vector2 vector2 = body.getTransform().getTranslation(); this.spatial.setLocalTranslation( new Float(vector2.x), new Float(vector2.y), 0f); Transform transform = body.getTransform(); if (transform.getTranslation().x == lastTransform.getTranslation().x && transform.getTranslation().y == lastTransform.getTranslation().y) { this.spatial.setLocalTranslation( new Vector3f( new Float(transform.getTranslation().x), new Float(transform.getTranslation().y), 0f)); lastTransform=transform; } Double angle = body.getTransform().getRotation(); if (angle != lastAngle) { Quaternion roll = new Quaternion(); roll.fromAngleAxis( new Float(angle) , Vector3f.UNIT_Z); this.spatial.setLocalRotation(roll); lastAngle = angle; } } }
src/main/java/com/pesegato/collision/Dyn4JShapeControl.java
package com.pesegato.collision; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Spatial; import com.pesegato.collision.hitbox.HBRect; import org.dyn4j.collision.broadphase.BroadphaseDetector; import org.dyn4j.dynamics.Body; import org.dyn4j.dynamics.BodyFixture; import org.dyn4j.dynamics.World; import org.dyn4j.geometry.Convex; import org.dyn4j.geometry.MassType; import org.dyn4j.geometry.Transform; import org.dyn4j.geometry.Vector2; public class Dyn4JShapeControl extends IDyn4JControl { protected Body body; BodyFixture fixture; //private World world; BroadphaseDetector broadphase; HBRect hbRect; public Dyn4JShapeControl(Convex shape, MassType massType, HBRect hbRect ) { this.hbRect=hbRect; body = new Body(); fixture = new BodyFixture(shape); body.addFixture(fixture); body.setMass(massType); body.setAutoSleepingEnabled(false); fixture.setUserData(hbRect.id); } public Dyn4JShapeControl(Body body, MassType massType, long id ) { this.body = body; for (BodyFixture bf:body.getFixtures()) bf.setUserData(id); body.setMass(massType); body.setAutoSleepingEnabled(true); } Dyn4JShapeControl(Convex shape, MassType massType, Double weight, //in kg/m Double friction, // low = more slippery Double restitution// more = more bouncy ) { body = new Body(); fixture = new BodyFixture(shape); fixture.setFriction(friction); fixture.setRestitution(restitution); fixture.setDensity(weight); body.addFixture(fixture); body.setMass(massType); body.setAutoSleepingEnabled(true); } public void addToWorld(BroadphaseDetector broadphase) { this.broadphase = broadphase; broadphase.add(body); } public void removeFromWorld() { this.broadphase.remove(body); boolean stillThere = broadphase.contains(body); for (BodyFixture fixture : body.getFixtures()) { stillThere |= broadphase.contains(body, fixture); } if (stillThere) { // I would need to see more code around the way the body is being removed System.out.println("still there"); } } /* @Override void addToWorld(World world) { this.world = world; world.addBody(body); } @Override public void removeFromWorld() { if (world==null) return; boolean removed=this.world.removeBody(body); System.out.println("removed "+removed); BroadphaseDetector bp = world.getBroadphaseDetector(); boolean stillThere = bp.contains(body); for (BodyFixture fixture : body.getFixtures()) { stillThere |= bp.contains(body, fixture); } if (stillThere) { // I would need to see more code around the way the body is being removed System.out.println("still there"); } this.world=null; } */ // more = more bouncy void setRestitution(Double restitution) { fixture.setRestitution(restitution); } // more = in kg/m void setDensity(Double kg) { fixture.setDensity(kg); } // low = more slippery void setFriction(Double friction) { fixture.setFriction(friction); } @Override public void setSpatial(Spatial spatial) { this.spatial = spatial; body.translate(new Double(spatial.getLocalTranslation().x), new Double(spatial.getLocalTranslation().y)); //TODO: set initial rotation of the dyn4j-Body } @Override protected void controlUpdate(float tpf) { //Dyn4JAppState handles everything } @Override protected void controlRender(RenderManager rm, ViewPort vp) { } public Body getBody(){ return body; } private Double lastAngle=-1d; private Transform lastTransform = new Transform(); private final static Float negligibleAngleRotation = 0.001f; void updatePhysics(BroadphaseDetector bp, float tpf){ if (bp.contains(body)) bp.update(body); } void updateDraw(float tpf) { Vector2 vector2 = body.getTransform().getTranslation(); this.spatial.setLocalTranslation( new Float(vector2.x), new Float(vector2.y), 0f); Transform transform = body.getTransform(); if (transform.getTranslation().x == lastTransform.getTranslation().x && transform.getTranslation().y == lastTransform.getTranslation().y) { this.spatial.setLocalTranslation( new Vector3f( new Float(transform.getTranslation().x), new Float(transform.getTranslation().y), 0f)); lastTransform=transform; } Double angle = body.getTransform().getRotation(); if (angle != lastAngle) { Quaternion roll = new Quaternion(); roll.fromAngleAxis( new Float(angle) , Vector3f.UNIT_Z); this.spatial.setLocalRotation(roll); lastAngle = angle; } } }
Added categoryfilter, removed old code
src/main/java/com/pesegato/collision/Dyn4JShapeControl.java
Added categoryfilter, removed old code
<ide><path>rc/main/java/com/pesegato/collision/Dyn4JShapeControl.java <ide> import com.jme3.renderer.ViewPort; <ide> import com.jme3.scene.Spatial; <ide> import com.pesegato.collision.hitbox.HBRect; <add>import org.dyn4j.collision.CategoryFilter; <ide> import org.dyn4j.collision.broadphase.BroadphaseDetector; <ide> import org.dyn4j.dynamics.Body; <ide> import org.dyn4j.dynamics.BodyFixture; <ide> body.setMass(massType); <ide> body.setAutoSleepingEnabled(false); <ide> fixture.setUserData(hbRect.id); <add> } <add> <add> public void setFilter(CategoryFilter cf){ <add> fixture.setFilter(cf); <ide> } <ide> <ide> public Dyn4JShapeControl(Body body, <ide> <ide> public void removeFromWorld() { <ide> this.broadphase.remove(body); <del> boolean stillThere = broadphase.contains(body); <del> for (BodyFixture fixture : body.getFixtures()) { <del> stillThere |= broadphase.contains(body, fixture); <del> } <del> if (stillThere) { <del> // I would need to see more code around the way the body is being removed <del> System.out.println("still there"); <del> } <ide> } <ide> /* <ide> @Override
Java
mit
bbce8d2dfff43404347f5971c98f59bd2347ca24
0
uber/jaeger-client-java,uber/jaeger-client-java
/* * Copyright (c) 2016, Uber Technologies, Inc * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.uber.jaeger.reporters.protocols; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import com.uber.jaeger.Tracer; import com.uber.jaeger.reporters.InMemoryReporter; import com.uber.jaeger.samplers.ConstSampler; import com.uber.jaeger.thriftjava.Log; import com.uber.jaeger.thriftjava.Tag; import com.uber.jaeger.thriftjava.TagType; import io.opentracing.Span; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(DataProviderRunner.class) public class JaegerThriftSpanConverterTest { Tracer tracer; @Before public void setUp() { tracer = new Tracer.Builder("test-service-name", new InMemoryReporter(), new ConstSampler(true)) .build(); } @DataProvider public static Object[][] dataProviderBuildTag() { return new Object[][] { { "value", TagType.STRING, "value" }, { (long) 1, TagType.LONG, (long) 1 }, { 1, TagType.LONG, (long) 1 }, { (short) 1, TagType.LONG, (long) 1 }, { (double) 1, TagType.DOUBLE, (double) 1 }, { (float) 1, TagType.DOUBLE, (double) 1 }, { (byte) 1, TagType.STRING, "1" }, { true, TagType.BOOL, true }, { new ArrayList<String>() { { add("hello"); } }, TagType.STRING, "[hello]" } }; } @Test @UseDataProvider("dataProviderBuildTag") public void testBuildTag(Object tagValue, TagType tagType, Object expected) { Tag tag = JaegerThriftSpanConverter.buildTag("key", tagValue); assertEquals(tagType, tag.getVType()); assertEquals("key", tag.getKey()); switch (tagType) { case STRING: default: assertEquals(expected, tag.getVStr()); break; case BOOL: assertEquals(expected, tag.isVBool()); break; case LONG: assertEquals(expected, tag.getVLong()); break; case DOUBLE: assertEquals(expected, tag.getVDouble()); break; case BINARY: break; } } @Test public void testBuildTags() { Map<String, Object> tags = new HashMap<String, Object>(); tags.put("key", "value"); List<Tag> thriftTags = JaegerThriftSpanConverter.buildTags(tags); assertNotNull(thriftTags); assertEquals(1, thriftTags.size()); assertEquals("key", thriftTags.get(0).getKey()); assertEquals("value", thriftTags.get(0).getVStr()); assertEquals(TagType.STRING, thriftTags.get(0).getVType()); } @Test public void testConvertSpan() { Map<String, Object> fields = new HashMap<String, Object>(); fields.put("k", "v"); Span span = tracer.buildSpan("operation-name").start(); span = span.log(1, "key", "value"); span = span.log(1, fields); com.uber.jaeger.thriftjava.Span thriftSpan = JaegerThriftSpanConverter.convertSpan((com.uber.jaeger.Span) span); assertEquals("operation-name", thriftSpan.getOperationName()); assertEquals(2, thriftSpan.getLogs().size()); Log thriftLog = thriftSpan.getLogs().get(0); assertEquals(1, thriftLog.getTimestamp()); assertEquals(2, thriftLog.getFields().size()); Tag thriftTag = thriftLog.getFields().get(0); assertEquals("event", thriftTag.getKey()); assertEquals("key", thriftTag.getVStr()); thriftTag = thriftLog.getFields().get(1); assertEquals("payload", thriftTag.getKey()); assertEquals("value", thriftTag.getVStr()); thriftLog = thriftSpan.getLogs().get(1); assertEquals(1, thriftLog.getTimestamp()); assertEquals(1, thriftLog.getFields().size()); thriftTag = thriftLog.getFields().get(0); assertEquals("k", thriftTag.getKey()); assertEquals("v", thriftTag.getVStr()); } @Test public void testTruncateString() { String testString = "k9bHT50f9JNpPUggw3Qz\n" + "Q1MUhMobIMPA5ItaB3KD\n" + "vNUoBPRjOpJw2C46vgn3\n" + "UisXI5KIIH8Wd8uqJ8Wn\n" + "Z8NVmrcpIBwxc2Qje5d6\n" + "1mJdQnPMc3VmX1v75As8\n" + "pUyoicWVPeGEidRuhHpt\n" + "R1sIR1YNjwtBIy9Swwdq\n" + "LUIZXdLcPmCvQVPB3cYw\n" + "VGAtFXG7D8ksLsKw94eY\n" + "c7PNm74nEV3jIIvlJ217\n" + "SLBfUBHW6SEjrHcz553i\n" + "VSjpBvJYXR6CsoEMGce0\n" + "LqSypCXJHDAzb0DL1w8B\n" + "kS9g0wCgregSAlq63OIf"; assertEquals(256, JaegerThriftSpanConverter.truncateString(testString).length()); } }
jaeger-core/src/test/java/com/uber/jaeger/reporters/protocols/JaegerThriftSpanConverterTest.java
/* * Copyright (c) 2016, Uber Technologies, Inc * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.uber.jaeger.reporters.protocols; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import com.uber.jaeger.Tracer; import com.uber.jaeger.reporters.InMemoryReporter; import com.uber.jaeger.samplers.ConstSampler; import com.uber.jaeger.thriftjava.Log; import com.uber.jaeger.thriftjava.Tag; import com.uber.jaeger.thriftjava.TagType; import io.opentracing.Span; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(DataProviderRunner.class) public class JaegerThriftSpanConverterTest { Tracer tracer; @Before public void setUp() { tracer = new Tracer.Builder("test-service-name", new InMemoryReporter(), new ConstSampler(true)) .build(); } @DataProvider public static Object[][] dataProviderBuildTag() { // @formatter:off return new Object[][] { { "value", TagType.STRING, "value" }, { (long) 1, TagType.LONG, (long) 1 }, { 1, TagType.LONG, (long) 1 }, { (short) 1, TagType.LONG, (long) 1 }, { (double) 1, TagType.DOUBLE, (double) 1 }, { (float) 1, TagType.DOUBLE, (double) 1 }, { (byte) 1, TagType.STRING, "1" }, { true, TagType.BOOL, true }, { new ArrayList<String>() { { add("hello"); } }, TagType.STRING, "[hello]" } }; // @formatter:on } @Test @UseDataProvider("dataProviderBuildTag") public void testBuildTag(Object tagValue, TagType tagType, Object expected) { Tag tag = JaegerThriftSpanConverter.buildTag("key", tagValue); assertEquals(tagType, tag.getVType()); assertEquals("key", tag.getKey()); switch (tagType) { case STRING: default: assertEquals(expected, tag.getVStr()); break; case BOOL: assertEquals(expected, tag.isVBool()); break; case LONG: assertEquals(expected, tag.getVLong()); break; case DOUBLE: assertEquals(expected, tag.getVDouble()); break; case BINARY: break; } } @Test public void testBuildTags() { Map<String, Object> tags = new HashMap<String, Object>(); tags.put("key", "value"); List<Tag> thriftTags = JaegerThriftSpanConverter.buildTags(tags); assertNotNull(thriftTags); assertEquals(1, thriftTags.size()); assertEquals("key", thriftTags.get(0).getKey()); assertEquals("value", thriftTags.get(0).getVStr()); assertEquals(TagType.STRING, thriftTags.get(0).getVType()); } @Test public void testConvertSpan() { Map<String, Object> fields = new HashMap<String, Object>(); fields.put("k", "v"); Span span = tracer.buildSpan("operation-name").start(); span = span.log(1, "key", "value"); span = span.log(1, fields); com.uber.jaeger.thriftjava.Span thriftSpan = JaegerThriftSpanConverter.convertSpan((com.uber.jaeger.Span) span); assertEquals("operation-name", thriftSpan.getOperationName()); assertEquals(2, thriftSpan.getLogs().size()); Log thriftLog = thriftSpan.getLogs().get(0); assertEquals(1, thriftLog.getTimestamp()); assertEquals(2, thriftLog.getFields().size()); Tag thriftTag = thriftLog.getFields().get(0); assertEquals("event", thriftTag.getKey()); assertEquals("key", thriftTag.getVStr()); thriftTag = thriftLog.getFields().get(1); assertEquals("payload", thriftTag.getKey()); assertEquals("value", thriftTag.getVStr()); thriftLog = thriftSpan.getLogs().get(1); assertEquals(1, thriftLog.getTimestamp()); assertEquals(1, thriftLog.getFields().size()); thriftTag = thriftLog.getFields().get(0); assertEquals("k", thriftTag.getKey()); assertEquals("v", thriftTag.getVStr()); } @Test public void testTruncateString() { String testString = "k9bHT50f9JNpPUggw3Qz\n" + "Q1MUhMobIMPA5ItaB3KD\n" + "vNUoBPRjOpJw2C46vgn3\n" + "UisXI5KIIH8Wd8uqJ8Wn\n" + "Z8NVmrcpIBwxc2Qje5d6\n" + "1mJdQnPMc3VmX1v75As8\n" + "pUyoicWVPeGEidRuhHpt\n" + "R1sIR1YNjwtBIy9Swwdq\n" + "LUIZXdLcPmCvQVPB3cYw\n" + "VGAtFXG7D8ksLsKw94eY\n" + "c7PNm74nEV3jIIvlJ217\n" + "SLBfUBHW6SEjrHcz553i\n" + "VSjpBvJYXR6CsoEMGce0\n" + "LqSypCXJHDAzb0DL1w8B\n" + "kS9g0wCgregSAlq63OIf"; assertEquals(256, JaegerThriftSpanConverter.truncateString(testString).length()); } }
remove formatter comments (#167)
jaeger-core/src/test/java/com/uber/jaeger/reporters/protocols/JaegerThriftSpanConverterTest.java
remove formatter comments (#167)
<ide><path>aeger-core/src/test/java/com/uber/jaeger/reporters/protocols/JaegerThriftSpanConverterTest.java <ide> <ide> @DataProvider <ide> public static Object[][] dataProviderBuildTag() { <del> // @formatter:off <ide> return new Object[][] { <ide> { "value", TagType.STRING, "value" }, <ide> { (long) 1, TagType.LONG, (long) 1 }, <ide> } <ide> }, TagType.STRING, "[hello]" } <ide> }; <del> // @formatter:on <ide> } <ide> <ide> @Test
Java
mit
f751c403d475dc9e92c009f3432df81bc1001f5e
0
lemmy/tlaplus,lemmy/tlaplus,lemmy/tlaplus,lemmy/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus,tlaplus/tlaplus
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Wed 4 Jul 2007 at 17:46:34 PST by lamport // modified on Fri Jan 18 11:33:51 PST 2002 by yuanyu package tlc2.tool; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; import tla2sany.modanalyzer.SpecObj; import tla2sany.semantic.ExprNode; import tlc2.TLCGlobals; import tlc2.output.EC; import tlc2.output.MP; import tlc2.tool.fp.FPSet; import tlc2.tool.fp.FPSetConfiguration; import tlc2.tool.fp.FPSetFactory; import tlc2.tool.liveness.LiveCheck; import tlc2.tool.queue.DiskStateQueue; import tlc2.tool.queue.IStateQueue; import tlc2.util.IdThread; import tlc2.util.LongVec; import tlc2.util.ObjLongTable; import tlc2.util.statistics.BucketStatistics; import tlc2.value.Value; import util.DebugPrinter; import util.FileUtil; import util.FilenameToStream; import util.UniqueString; /** * A TLA+ Model checker */ // SZ Feb 20, 2009: major refactoring of this class introduced due to the changes // in the type hierarchy. multiple methods has been pulled up to the super class. // unused constructors has been removed // the class now contains only the parts, which are different from the DFIDModelChecker // the name resolver and support for the external specification object has been added public class ModelChecker extends AbstractChecker { /** * If the state/ dir should be cleaned up after a successful model run */ private static final boolean VETO_CLEANUP = Boolean.getBoolean(ModelChecker.class.getName() + ".vetoCleanup"); public FPSet theFPSet; // the set of reachable states (SZ: note the type) public IStateQueue theStateQueue; // the state queue public TLCTrace trace; // the trace file protected Worker[] workers; // the workers // used to calculate the spm metric public long distinctStatesPerMinute, statesPerMinute = 0L; protected long oldNumOfGenStates, oldFPSetSize = 0L; /* Constructors */ /** * The only used constructor of the TLA+ model checker * SZ Feb 20, 2009 * @param resolver name resolver to be able to load files (specs and configs) from managed environments * @param specObj external SpecObj added to enable to work on existing specification * Modified on 6 Apr 2010 by Yuan Yu to add fpMemSize parameter. */ public ModelChecker(String specFile, String configFile, String dumpFile, boolean deadlock, String fromChkpt, FilenameToStream resolver, SpecObj specObj, final FPSetConfiguration fpSetConfig) throws EvalException, IOException { // call the abstract constructor super(specFile, configFile, dumpFile, deadlock, fromChkpt, true, resolver, specObj); // SZ Feb 20, 2009: this is a selected alternative this.theStateQueue = new DiskStateQueue(this.metadir); // this.theStateQueue = new MemStateQueue(this.metadir); //TODO why used to div by 20? this.theFPSet = FPSetFactory.getFPSet(fpSetConfig); // initialize the set this.theFPSet.init(TLCGlobals.getNumWorkers(), this.metadir, specFile); // Finally, initialize the trace file: this.trace = new TLCTrace(this.metadir, specFile, this.tool); // Initialize all the workers: this.workers = new Worker[TLCGlobals.getNumWorkers()]; for (int i = 0; i < this.workers.length; i++) { this.workers[i] = new Worker(i, this); } } /** * This method does model checking on a TLA+ spec. All the visited * states are stored in the variable theFPSet. All the states whose * next states have not been explored are stored in the variable * theStateQueue. */ public void modelCheck() throws Exception { report("entering modelCheck()"); // needed to calculate state/minute in final progress report final long startTime = System.currentTimeMillis(); boolean recovered = this.recover(); if (!recovered) { // We start from scratch. Initialize the state queue and the // state set to contain all the initial states. if (!this.checkAssumptions()) return; try { report("doInit(false)"); MP.printMessage(EC.TLC_COMPUTING_INIT); // SZ Feb 23, 2009: do not ignore cancel on creation of the init states if (!this.doInit(false)) { report("exiting, because init failed"); return; } } catch (Throwable e) { report("exception in init"); report(e); // Initial state computation fails with an exception: String msg = e.getMessage(); /** * The following code replaced code equivalent to setting msg = e.getMessage(). * getMessage() for a StackOverflowError returned null, producing a useless * error message. Changed by LL on 12 Mar 2010 */ if (e instanceof StackOverflowError) { msg = "This was a Java StackOverflowError. It was probably the result\n" + "of an incorrect recursive function definition that caused TLC to enter\n" + "an infinite loop when trying to compute the function or its application\n" + "to an element in its putative domain." ; } if (msg == null) { msg = e.toString(); } if (this.errState != null) { MP.printError(EC.TLC_INITIAL_STATE, new String[] { msg, this.errState.toString() }); } else { MP.printError(EC.GENERAL, msg); } // Replay the error with the error stack recorded: this.tool.setCallStack(); try { this.numOfGenStates = new AtomicLong(0); // SZ Feb 23, 2009: ignore cancel on error reporting this.doInit(true); } catch (Throwable e1) { // Assert.printStack(e); MP.printError(EC.TLC_NESTED_EXPRESSION, this.tool.getCallStack().toString()); } this.printSummary(false, startTime); this.cleanup(false); report("exiting, because init failed with exception"); return; } if (this.numOfGenStates.get() == this.theFPSet.size()) { String plural = (this.numOfGenStates.get() == 1) ? "" : "s"; MP.printMessage(EC.TLC_INIT_GENERATED1, new String[] { String.valueOf(this.numOfGenStates), plural }); } else { MP.printMessage(EC.TLC_INIT_GENERATED1, new String[] { String.valueOf(this.numOfGenStates), String.valueOf(this.theFPSet.size()) }); } } report("init processed"); // Finished if there is no next state predicate: if (this.actions.length == 0) { reportSuccess(this.theFPSet, this.numOfGenStates.get()); this.printSummary(true, startTime); this.cleanup(true); report("exiting with actions.length == 0"); return; } boolean success = false; try { report("running TLC"); success = this.runTLC(Integer.MAX_VALUE); if (!success) { report("TLC terminated with error"); return; } if (this.errState == null) { // Always check liveness properties at the end: if (this.checkLiveness) { report("checking liveness"); success = liveCheck.finalCheck(); report("liveness check complete"); if (!success) { report("exiting error status on liveness check"); return; } } // We get here because the checking has been completed. success = true; reportSuccess(this.theFPSet, this.numOfGenStates.get()); } else if (this.keepCallStack) { // Replay the error with the error stack recorded: this.tool.setCallStack(); try { this.doNext(this.predErrState, new ObjLongTable(10)); } catch (Throwable e) { // Assert.printStack(e); MP.printError(EC.TLC_NESTED_EXPRESSION, this.tool.getCallStack().toString()); } } } catch (Exception e) { report("TLC terminated with error"); // Assert.printStack(e); success = false; MP.printError(EC.GENERAL, e); // LL changed call 7 April 2012 } finally { this.printSummary(success, startTime); if (this.checkLiveness) { if (LIVENESS_STATS) { // Reclaim memory for in-degree calculation System.gc(); MP.printStats(liveCheck .calculateInDegreeDiskGraphs(new BucketStatistics("Histogram vertex in-degree", LiveCheck.class.getPackage().getName(), "DiskGraphsInDegree")), liveCheck.getOutDegreeStatistics()); } } this.cleanup(success); } report("exiting modelCheck()"); } /** * Check the assumptions. */ public boolean checkAssumptions() { ExprNode[] assumps = this.tool.getAssumptions(); boolean[] isAxiom = this.tool.getAssumptionIsAxiom(); for (int i = 0; i < assumps.length; i++) { try { if ((!isAxiom[i]) && !this.tool.isValid(assumps[i])) { MP.printError(EC.TLC_ASSUMPTION_FALSE, assumps[i].toString()); return false; } } catch (Exception e) { // Assert.printStack(e); MP.printError(EC.TLC_ASSUMPTION_EVALUATION_ERROR, new String[] { assumps[i].toString(), e.getMessage() }); return false; } } return true; } /** * Initialize the model checker * @return status, if false, the processing should be stopped * @throws Throwable */ public final boolean doInit(boolean ignoreCancel) throws Throwable { // SZ Feb 23, 2009: cancel flag set, quit if (!ignoreCancel && this.cancellationFlag) { return false; } // Generate the initial states. // // The functor is passed to getInitStates() to - instead of adding all // init states into an intermediate StateVec to check and add each state // in a subsequent loop - directly check each state one-by-one and add // it to the queue, fingerprint set and trace file. This avoids // allocating memory for StateVec (which depending on the number of init // states can grow to be GBs) and the subsequent loop over StateVec. final DoInitFunctor functor = new DoInitFunctor(); this.tool.getInitStates(functor); // Iff one of the init states' checks violates any properties, the // functor will record it. if (functor.errState != null) { this.errState = functor.errState; throw functor.e; } // Return whatever the functor has recorded. return functor.returnValue; } /** * Compute the set of the next states. For each next state, check that * it is a valid state, check that the invariants are satisfied, check * that it satisfies the constraints, and enqueue it in the state queue. * Return true if the model checking should stop. * * This method is called from the workers on every step */ public final boolean doNext(TLCState curState, ObjLongTable counts) throws Throwable { // SZ Feb 23, 2009: cancel the calculation if (this.cancellationFlag) { return false; } boolean deadLocked = true; TLCState succState = null; StateVec liveNextStates = null; LongVec liveNextFPs = null; if (this.checkLiveness) { liveNextStates = new StateVec(2); liveNextFPs = new LongVec(2); } try { int k = 0; // <-- // <-- for (int i = 0; i < this.actions.length; i++) { // SZ Feb 23, 2009: cancel the calculation if (this.cancellationFlag) { return false; } //TODO Implement IStateFunctor pattern for getNextStates() too // to reduce memory and runtime overhead of allocating and // looping StateVec. However - contrary to doInit() - doNext() // is incompatible to the functor when liveness checking is // turned on. Liveness checking does not support adding // nextStates one-by-one but expects to be given the whole set // of nextStates in a single invocation // (LiveCheck#addNextState(..). If this limitation is ever // removed, the functor pattern could be applied to doNext too. StateVec nextStates = this.tool.getNextStates(this.actions[i], curState); int sz = nextStates.size(); this.incNumOfGenStates(sz); deadLocked = deadLocked && (sz == 0); SUCCESSORS: for (int j = 0; j < sz; j++) { succState = nextStates.elementAt(j); // Check if succState is a legal state. if (!this.tool.isGoodState(succState)) { if (this.setErrState(curState, succState, false)) { MP.printError(EC.TLC_STATE_NOT_COMPLETELY_SPECIFIED_NEXT); this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); synchronized (this) { this.notify(); } } return true; } if (TLCGlobals.coverageInterval >= 0) { ((TLCStateMutSource) succState).addCounts(counts); } final boolean inModel = (this.tool.isInModel(succState) && this.tool.isInActions(curState, succState)); boolean seen = false; if (inModel) { long fp = succState.fingerPrint(); seen = this.theFPSet.put(fp); if (!seen) { // Write out succState when needed: if (this.allStateWriter != null) { this.allStateWriter.writeState(succState); } // Write succState to trace only if it satisfies the // model constraints. Do not enqueue it yet, but wait // for implied actions and invariants to be checked. // Those checks - if violated - will cause model checking // to terminate. Thus we cannot let concurrent workers start // exploring this new state. Conversely, the state has to // be in the trace in case either invariant or implied action // checks want to print the trace. long loc = this.trace.writeState(curState, fp); succState.uid = loc; } // For liveness checking: if (this.checkLiveness) { liveNextStates.addElement(succState); liveNextFPs.addElement(fp); } } // Check if succState violates any invariant: if (!seen) { try { int len = this.invariants.length; INVARIANTS: for (k = 0; k < len; k++) { // SZ Feb 23, 2009: cancel the calculation if (this.cancellationFlag) { return false; } if (!tool.isValid(this.invariants[k], succState)) { // We get here because of invariant violation: synchronized (this) { if (TLCGlobals.continuation) { MP.printError(EC.TLC_INVARIANT_VIOLATED_BEHAVIOR, this.tool.getInvNames()[k]); this.trace.printTrace(curState, succState); break INVARIANTS; } else { if (this.setErrState(curState, succState, false)) { MP.printError(EC.TLC_INVARIANT_VIOLATED_BEHAVIOR, this.tool .getInvNames()[k]); this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); this.notify(); } return true; } } } } if (k < len) { if (inModel && !seen) { // Even though the state violates an // invariant, add it to the queue. After // all, the user selected to continue model // checking even if an invariant is // violated. this.theStateQueue.sEnqueue(succState); } // Continue with next successor iff an // invariant is violated and // TLCGlobals.continuation is true. continue SUCCESSORS; } } catch (Exception e) { if (this.setErrState(curState, succState, true)) { MP.printError(EC.TLC_INVARIANT_EVALUATION_FAILED, new String[] { this.tool.getInvNames()[k], (e.getMessage() == null) ? e.toString() : e.getMessage() }); this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); this.notify(); } throw e; } } // Check if the state violates any implied action. We need to do it // even if succState is not new. try { int len = this.impliedActions.length; IMPLIED: for (k = 0; k < len; k++) { // SZ Feb 23, 2009: cancel the calculation if (this.cancellationFlag) { return false; } if (!tool.isValid(this.impliedActions[k], curState, succState)) { // We get here because of implied-action violation: synchronized (this) { if (TLCGlobals.continuation) { MP.printError(EC.TLC_ACTION_PROPERTY_VIOLATED_BEHAVIOR, this.tool .getImpliedActNames()[k]); this.trace.printTrace(curState, succState); break IMPLIED; } else { if (this.setErrState(curState, succState, false)) { MP.printError(EC.TLC_ACTION_PROPERTY_VIOLATED_BEHAVIOR, this.tool .getImpliedActNames()[k]); this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); this.notify(); } return true; } } } } if (k < len) { if (inModel && !seen) { // Even though the state violates an // invariant, add it to the queue. After // all, the user selected to continue model // checking even if an implied action is // violated. this.theStateQueue.sEnqueue(succState); } // Continue with next successor iff an // implied action is violated and // TLCGlobals.continuation is true. continue SUCCESSORS; } } catch (Exception e) { if (this.setErrState(curState, succState, true)) { MP.printError(EC.TLC_ACTION_PROPERTY_EVALUATION_FAILED, new String[] { this.tool.getImpliedActNames()[k], (e.getMessage() == null) ? e.toString() : e.getMessage() }); this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); this.notify(); } throw e; } if (inModel && !seen) { // The state is inModel, unseen and neither invariants // nor implied actions are violated. It is thus eligible // for further processing by other workers. this.theStateQueue.sEnqueue(succState); } } // Must set state to null!!! succState = null; } // Check for deadlock: if (deadLocked && this.checkDeadlock) { synchronized (this) { if (this.setErrState(curState, null, false)) { MP.printError(EC.TLC_DEADLOCK_REACHED); this.trace.printTrace(curState, null); this.theStateQueue.finishAll(); this.notify(); } } return true; } // Finally, add curState into the behavior graph for liveness checking: if (this.checkLiveness) { // Add the stuttering step: long curStateFP = curState.fingerPrint(); liveNextStates.addElement(curState); liveNextFPs.addElement(curStateFP); liveCheck.addNextState(curState, curStateFP, liveNextStates, liveNextFPs); } return false; } catch (Throwable e) { // Assert.printStack(e); boolean keep = ((e instanceof StackOverflowError) || (e instanceof OutOfMemoryError) || (e instanceof AssertionError)); synchronized (this) { if (this.setErrState(curState, succState, !keep)) { if (e instanceof StackOverflowError) { MP.printError(EC.SYSTEM_STACK_OVERFLOW, e); } else if (e instanceof OutOfMemoryError) { MP.printError(EC.SYSTEM_OUT_OF_MEMORY, e); } else if (e instanceof AssertionError) { MP.printError(EC.TLC_BUG, e); } else if (e.getMessage() != null) { MP.printError(EC.GENERAL, e); // LL changed call 7 April 2012 } this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); this.notify(); } } throw e; } } /** * Things need to be done here: * Check liveness: check liveness properties on the partial state graph. * Create checkpoint: checkpoint three data structures: the state set, * the state queue, and the state trace. */ public final boolean doPeriodicWork() throws Exception { if ((!this.checkLiveness || !liveCheck.doLiveCheck()) && !TLCGlobals.doCheckPoint()) { // Do not suspend the state queue if neither check-pointing nor // liveness-checking is going to happen. Suspending is expensive. // It stops all workers. return true; } if (this.theStateQueue.suspendAll()) { // Run liveness checking, if needed: if (this.checkLiveness) { if (!liveCheck.check(false)) return false; } if (TLCGlobals.doCheckPoint()) { // Checkpoint: MP.printMessage(EC.TLC_CHECKPOINT_START, this.metadir); // start checkpointing: this.theStateQueue.beginChkpt(); this.trace.beginChkpt(); this.theFPSet.beginChkpt(); this.theStateQueue.resumeAll(); UniqueString.internTbl.beginChkpt(this.metadir); if (this.checkLiveness) { liveCheck.beginChkpt(); } // commit checkpoint: this.theStateQueue.commitChkpt(); this.trace.commitChkpt(); this.theFPSet.commitChkpt(); UniqueString.internTbl.commitChkpt(this.metadir); if (this.checkLiveness) { liveCheck.commitChkpt(); } MP.printMessage(EC.TLC_CHECKPOINT_END); } else { // Just resume worker threads when checkpointing is skipped this.theStateQueue.resumeAll(); } } return true; } public final boolean recover() throws IOException { boolean recovered = false; if (this.fromChkpt != null) { // We recover from previous checkpoint. MP.printMessage(EC.TLC_CHECKPOINT_RECOVER_START, this.fromChkpt); this.trace.recover(); this.theStateQueue.recover(); this.theFPSet.recover(); if (this.checkLiveness) { liveCheck.recover(); } MP.printMessage(EC.TLC_CHECKPOINT_RECOVER_END, new String[] { String.valueOf(this.theFPSet.size()), String.valueOf(this.theStateQueue.size()) }); recovered = true; this.numOfGenStates.set(this.theFPSet.size()); } return recovered; } private final void cleanup(boolean success) throws IOException { this.theFPSet.close(); this.trace.close(); if (this.checkLiveness) liveCheck.close(); if (this.allStateWriter != null) this.allStateWriter.close(); if (!VETO_CLEANUP) { FileUtil.deleteDir(this.metadir, success); } } public final void printSummary(boolean success, final long startTime) throws IOException { super.reportCoverage(this.workers); /* * This allows the toolbox to easily display the last set * of state space statistics by putting them in the same * form as all other progress statistics. */ if (TLCGlobals.tool) { printProgresStats(startTime); } MP.printMessage(EC.TLC_STATS, new String[] { String.valueOf(this.numOfGenStates), String.valueOf(this.theFPSet.size()), String.valueOf(this.theStateQueue.size()) }); if (success) { MP.printMessage(EC.TLC_SEARCH_DEPTH, String.valueOf(this.trace.getLevelForReporting())); } } private final void printProgresStats(final long startTime) throws IOException { final long fpSetSize = this.theFPSet.size(); // print progress showing states per minute metric (spm) final double factor; if (startTime < 0) { factor = TLCGlobals.progressInterval / 60000d; } else { // This is final statistics oldNumOfGenStates = 0; oldFPSetSize = 0; factor = (System.currentTimeMillis() - startTime) / 60000d; } long l = numOfGenStates.get(); statesPerMinute = (long) ((l - oldNumOfGenStates) / factor); oldNumOfGenStates = l; distinctStatesPerMinute = (long) ((fpSetSize - oldFPSetSize) / factor); oldFPSetSize = fpSetSize; MP.printMessage(EC.TLC_PROGRESS_STATS, new String[] { String.valueOf(this.trace.getLevelForReporting()), String.valueOf(this.numOfGenStates), String.valueOf(fpSetSize), String.valueOf(this.theStateQueue.size()), String.valueOf(statesPerMinute), String.valueOf(distinctStatesPerMinute) }); } public static final void reportSuccess(final FPSet anFpSet, final long numOfGenStates) throws IOException { final long fpSetSize = anFpSet.size(); final double actualProb = anFpSet.checkFPs(); reportSuccess(fpSetSize, actualProb, numOfGenStates); } public static final void reportSuccess(final long numOfDistinctStates, final double actualProb, final long numOfGenStates) throws IOException { // shown as 'calculated' in Toolbox final double optimisticProb = numOfDistinctStates * ((numOfGenStates - numOfDistinctStates) / Math.pow(2, 64)); /* The following code added by LL on 3 Aug 2009 to print probabilities * to only one decimal point. Removed by LL on 17 April 2012 because it * seemed to report probabilities > 10-4 as probability 0. */ // final PrintfFormat fmt = new PrintfFormat("val = %.1G"); // final String optimisticProbStr = fmt.sprintf(optimisticProb); // final String actualProbStr = fmt.sprintf(actualProb); // Following two lines added by LL on 17 April 2012 final String optimisticProbStr = "val = " + ProbabilityToString(optimisticProb, 2); // shown as 'observed' in Toolbox final String actualProbStr = "val = " + ProbabilityToString(actualProb, 2); MP.printMessage(EC.TLC_SUCCESS, new String[] { optimisticProbStr, actualProbStr }); } /** * This method added by LL on 17 April 2012 to replace the use of the PrintfFormat * method in reportSuccess. * * Returns a string representing the decimal representation of a probability to * a given number of significant digits. If the input is not a probability, or if * some error is found, then it returns the result of applying Double.toString(long) * to the value. * * Warning: the code makes the following assumption: * - Double.toString(v) returns a decimal representation of v of the * form [d]* ["." [d]+ ["E" [+ | -] [d]+] where d is a decimal digit and * [x] = 0 or 1 instance of x * [x]* = any number of instances of x * [x]+ = any non-zero number of instances of x * x | y = an x or a y * * @param val - the probability represented as a long; must satisfy 0 <= val <= 1. * @param significantDigits - the number of significant digits to include; must be > 0. * @return */ private static final String ProbabilityToString(double val, int significantDigits) { /* * If val = 0 (which shouldn't happen), return "0.0" */ if (val == 0) { return "0.0"; } String valString = Double.toString(val) ; int valStringLen = valString.length(); String result = ""; int next = 0; // pointer to the next character in valString to examine. int significantDigitsFound = 0; /* * Skip past leading zeros. */ while ((next < valStringLen) && (valString.charAt(next) == '0')) { next++ ; } /* * Append all the following digits to result, incrementing * significantDigits for each one. */ while ( (next < valStringLen) && Character.isDigit(valString.charAt(next))) { result = result + valString.charAt(next); significantDigitsFound++; next++ ; } /* * IF next character is not "." * THEN IF at end THEN return result * ELSE return valString. */ if (next == valStringLen) { return result; } else if (valString.charAt(next) != '.') { return valString; } /* * IF significantDigitsFound >= significantDigits, * THEN skip over "." and the following digits. * (this should not happen) * ELSE append "." to result ; * IF significantDigitsFound = 0 * THEN copy each of the following "0"s of valString to result; * copy up to significantDigits - significantDigitsFound * following digits of valString to result; * IF next char of valString a digit >= "5" * THEN propagate a carry backwards over the digits of result * -- e.g., changing ".019" to ".020"; * Skip over remaining digits of valString; */ if (significantDigitsFound >= significantDigits) { next++ ; while ( (next < valStringLen) && Character.isDigit(valString.charAt(next))) { next++ ; } } else { next++; result = result + "."; if (significantDigitsFound == 0) { while ((next < valStringLen) && (valString.charAt(next) == '0')) { next++ ; result = result + "0"; } } while ((next < valStringLen) && Character.isDigit(valString.charAt(next)) && significantDigitsFound < significantDigits ) { result = result + valString.charAt(next); next++; significantDigitsFound++; } if ((next < valStringLen) && Character.isDigit(valString.charAt(next)) && Character.digit(valString.charAt(next), 10) >= 5) { int prev = result.length()-1; // the next digit of result to increment boolean done = false; while (!done) { if (prev < 0) { result = "1" + result; done = true; } else { char prevChar = result.charAt(prev); String front = result.substring(0, prev); String back = result.substring(prev+1); if (Character.isDigit(prevChar)) { if (prevChar == '9') { result = front + '0' + back; } else { result = front + Character.forDigit(Character.digit(prevChar, 10)+1, 10) + back; done = true; } } else { // prevChar must be '.', so just continue } } prev--; } } while ((next < valStringLen) && Character.isDigit(valString.charAt(next))) { next++; } } /* * IF next at end of valString or at "E" * THEN copy remaining chars of valString to result; * return result * ELSE return valString */ if (next >= valStringLen) { return result; } if (valString.charAt(next)=='E') { next++; result = result + "E"; while (next < valStringLen) { result = result + valString.charAt(next); next++; } return result; } return valString; } // The following method used for testing ProbabilityToString // // public static void main(String[] args) { // double[] test = new double[] {.5, .0995, .00000001, 001.000, .0022341, // .0022351, 3.14159E-12, // 00.999, .002351111, 22.8E-14, 0.000E-12, // 37, 0033D, 04.85, -35.3}; // int i = 0; // while (i < test.length) { // System.out.println("" + i + ": " + Double.toString(test[i]) + " -> " + ProbabilityToString(test[i],2)); // i++; // } // } public final void setAllValues(int idx, Value val) { for (int i = 0; i < this.workers.length; i++) { workers[i].setLocalValue(idx, val); } } public final Value getValue(int i, int idx) { return workers[i].getLocalValue(idx); } /** * Spawn the worker threads */ protected IdThread[] startWorkers(AbstractChecker checker, int checkIndex) { for (int i = 0; i < this.workers.length; i++) { this.workers[i].start(); } return this.workers; } /** * Work to be done prior entering to the worker loop */ protected void runTLCPreLoop() { // nothing to do in this implementation } /** * Process calculation. * * Comments added 9 April 2012 by LL. The above was Simon's extensive commenting. I presume * he really mean "ProGRess calculation", since this seems to be where the coverage * and progress information is written. The method writes the progress information, * prints the coverage only if count = 0, and then waits until it's time to print * the next progress report before exiting. (The next progress report is printed * the next time the method is called.) * * It looks like this is where the depth-first model checker exits when it has * finished checking the required depth, but I'm not sure. * * @param count * @param depth * @throws Exception */ protected void runTLCContinueDoing(final int count, final int depth) throws Exception { final int level = this.trace.getLevel(); printProgresStats(-1); if (level > depth) { this.theStateQueue.finishAll(); this.done = true; } else { // The following modification sof count are obviously bogus and // resulted from Simon's modification of Yuan's original code. // Yuan's original code assumes coverageInterval >= progressInterval, // and this should eventually be changed. But for now, // the caller of this method is responsible for updating // count. LL 9 Oct 2009 if (count == 0) { super.reportCoverage(this.workers); // count = TLCGlobals.coverageInterval / TLCGlobals.progressInterval; } // else // { // count--; // } this.wait(TLCGlobals.progressInterval); } } /** * Debugging support * @param e */ private void report(Throwable e) { DebugPrinter.print(e); } public long getStatesGenerated() { return numOfGenStates.get(); } /** * An implementation of {@link IStateFunctor} for * {@link ModelChecker#doInit(boolean)}. */ private class DoInitFunctor implements IStateFunctor { /** * Non-Null iff a violation occurred. */ private TLCState errState; private Throwable e; /** * The return values of addElement are meaningless, but doInit wants to * know the actual outcome when all init states have been processed. * This outcome is stored as returnValue. */ private boolean returnValue = true; /* (non-Javadoc) * @see tlc2.tool.IStateFunctor#addElement(tlc2.tool.TLCState) */ public Object addElement(final TLCState curState) { incNumOfGenStates(1); // getInitStates() does not support aborting init state generation // once a violation has been found (that is why the return values of // addElement are meaningless). It continues until all init // states have been generated. Thus, the functor simply ignores // subsequent states once a violation has been recorded. if (errState != null) { returnValue = false; return returnValue; } try { // Check if the state is a legal state if (!tool.isGoodState(curState)) { MP.printError(EC.TLC_INITIAL_STATE, curState.toString()); return returnValue; } boolean inModel = tool.isInModel(curState); boolean seen = false; if (inModel) { long fp = curState.fingerPrint(); seen = theFPSet.put(fp); if (!seen) { if (allStateWriter != null) { allStateWriter.writeState(curState); } curState.uid = trace.writeState(fp); theStateQueue.enqueue(curState); // build behavior graph for liveness checking if (checkLiveness) { liveCheck.addInitState(curState, fp); } } } // Check properties of the state: if (!seen) { for (int j = 0; j < invariants.length; j++) { if (!tool.isValid(invariants[j], curState)) { // We get here because of invariant violation: MP.printError(EC.TLC_INVARIANT_VIOLATED_INITIAL, new String[] { tool.getInvNames()[j].toString(), curState.toString() }); if (!TLCGlobals.continuation) { returnValue = false; return returnValue; } } } for (int j = 0; j < impliedInits.length; j++) { if (!tool.isValid(impliedInits[j], curState)) { // We get here because of implied-inits violation: MP.printError(EC.TLC_PROPERTY_VIOLATED_INITIAL, new String[] { tool.getImpliedInitNames()[j], curState.toString() }); returnValue = false; return returnValue; } } } } catch (Throwable e) { // Assert.printStack(e); if (e instanceof OutOfMemoryError) { MP.printError(EC.SYSTEM_OUT_OF_MEMORY_TOO_MANY_INIT); returnValue = false; return returnValue; } this.errState = curState; this.e = e; } return returnValue; } } }
tlatools/src/tlc2/tool/ModelChecker.java
// Copyright (c) 2003 Compaq Corporation. All rights reserved. // Portions Copyright (c) 2003 Microsoft Corporation. All rights reserved. // Last modified on Wed 4 Jul 2007 at 17:46:34 PST by lamport // modified on Fri Jan 18 11:33:51 PST 2002 by yuanyu package tlc2.tool; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; import tla2sany.modanalyzer.SpecObj; import tla2sany.semantic.ExprNode; import tlc2.TLCGlobals; import tlc2.output.EC; import tlc2.output.MP; import tlc2.tool.fp.FPSet; import tlc2.tool.fp.FPSetConfiguration; import tlc2.tool.fp.FPSetFactory; import tlc2.tool.liveness.LiveCheck; import tlc2.tool.queue.DiskStateQueue; import tlc2.tool.queue.IStateQueue; import tlc2.util.IdThread; import tlc2.util.LongVec; import tlc2.util.ObjLongTable; import tlc2.util.statistics.BucketStatistics; import tlc2.value.Value; import util.DebugPrinter; import util.FileUtil; import util.FilenameToStream; import util.UniqueString; /** * A TLA+ Model checker */ // SZ Feb 20, 2009: major refactoring of this class introduced due to the changes // in the type hierarchy. multiple methods has been pulled up to the super class. // unused constructors has been removed // the class now contains only the parts, which are different from the DFIDModelChecker // the name resolver and support for the external specification object has been added public class ModelChecker extends AbstractChecker { /** * If the state/ dir should be cleaned up after a successful model run */ private static final boolean VETO_CLEANUP = Boolean.getBoolean(ModelChecker.class.getName() + ".vetoCleanup"); public FPSet theFPSet; // the set of reachable states (SZ: note the type) public IStateQueue theStateQueue; // the state queue public TLCTrace trace; // the trace file protected Worker[] workers; // the workers // used to calculate the spm metric public long distinctStatesPerMinute, statesPerMinute = 0L; protected long oldNumOfGenStates, oldFPSetSize = 0L; /* Constructors */ /** * The only used constructor of the TLA+ model checker * SZ Feb 20, 2009 * @param resolver name resolver to be able to load files (specs and configs) from managed environments * @param specObj external SpecObj added to enable to work on existing specification * Modified on 6 Apr 2010 by Yuan Yu to add fpMemSize parameter. */ public ModelChecker(String specFile, String configFile, String dumpFile, boolean deadlock, String fromChkpt, FilenameToStream resolver, SpecObj specObj, final FPSetConfiguration fpSetConfig) throws EvalException, IOException { // call the abstract constructor super(specFile, configFile, dumpFile, deadlock, fromChkpt, true, resolver, specObj); // SZ Feb 20, 2009: this is a selected alternative this.theStateQueue = new DiskStateQueue(this.metadir); // this.theStateQueue = new MemStateQueue(this.metadir); //TODO why used to div by 20? this.theFPSet = FPSetFactory.getFPSet(fpSetConfig); // initialize the set this.theFPSet.init(TLCGlobals.getNumWorkers(), this.metadir, specFile); // Finally, initialize the trace file: this.trace = new TLCTrace(this.metadir, specFile, this.tool); // Initialize all the workers: this.workers = new Worker[TLCGlobals.getNumWorkers()]; for (int i = 0; i < this.workers.length; i++) { this.workers[i] = new Worker(i, this); } } /** * This method does model checking on a TLA+ spec. All the visited * states are stored in the variable theFPSet. All the states whose * next states have not been explored are stored in the variable * theStateQueue. */ public void modelCheck() throws Exception { report("entering modelCheck()"); // needed to calculate state/minute in final progress report final long startTime = System.currentTimeMillis(); boolean recovered = this.recover(); if (!recovered) { // We start from scratch. Initialize the state queue and the // state set to contain all the initial states. if (!this.checkAssumptions()) return; try { report("doInit(false)"); MP.printMessage(EC.TLC_COMPUTING_INIT); // SZ Feb 23, 2009: do not ignore cancel on creation of the init states if (!this.doInit(false)) { report("exiting, because init failed"); return; } } catch (Throwable e) { report("exception in init"); report(e); // Initial state computation fails with an exception: String msg = e.getMessage(); /** * The following code replaced code equivalent to setting msg = e.getMessage(). * getMessage() for a StackOverflowError returned null, producing a useless * error message. Changed by LL on 12 Mar 2010 */ if (e instanceof StackOverflowError) { msg = "This was a Java StackOverflowError. It was probably the result\n" + "of an incorrect recursive function definition that caused TLC to enter\n" + "an infinite loop when trying to compute the function or its application\n" + "to an element in its putative domain." ; } if (msg == null) { msg = e.toString(); } if (this.errState != null) { MP.printError(EC.TLC_INITIAL_STATE, new String[] { msg, this.errState.toString() }); } else { MP.printError(EC.GENERAL, msg); } // Replay the error with the error stack recorded: this.tool.setCallStack(); try { this.numOfGenStates = new AtomicLong(0); // SZ Feb 23, 2009: ignore cancel on error reporting this.doInit(true); } catch (Throwable e1) { // Assert.printStack(e); MP.printError(EC.TLC_NESTED_EXPRESSION, this.tool.getCallStack().toString()); } this.printSummary(false, startTime); this.cleanup(false); report("exiting, because init failed with exception"); return; } if (this.numOfGenStates.get() == this.theFPSet.size()) { String plural = (this.numOfGenStates.get() == 1) ? "" : "s"; MP.printMessage(EC.TLC_INIT_GENERATED1, new String[] { String.valueOf(this.numOfGenStates), plural }); } else { MP.printMessage(EC.TLC_INIT_GENERATED1, new String[] { String.valueOf(this.numOfGenStates), String.valueOf(this.theFPSet.size()) }); } } report("init processed"); // Finished if there is no next state predicate: if (this.actions.length == 0) { reportSuccess(this.theFPSet, this.numOfGenStates.get()); this.printSummary(true, startTime); this.cleanup(true); report("exiting with actions.length == 0"); return; } boolean success = false; try { report("running TLC"); success = this.runTLC(Integer.MAX_VALUE); if (!success) { report("TLC terminated with error"); return; } if (this.errState == null) { // Always check liveness properties at the end: if (this.checkLiveness) { report("checking liveness"); success = liveCheck.finalCheck(); report("liveness check complete"); if (!success) { report("exiting error status on liveness check"); return; } } // We get here because the checking has been completed. success = true; reportSuccess(this.theFPSet, this.numOfGenStates.get()); } else if (this.keepCallStack) { // Replay the error with the error stack recorded: this.tool.setCallStack(); try { this.doNext(this.predErrState, new ObjLongTable(10)); } catch (Throwable e) { // Assert.printStack(e); MP.printError(EC.TLC_NESTED_EXPRESSION, this.tool.getCallStack().toString()); } } } catch (Exception e) { report("TLC terminated with error"); // Assert.printStack(e); success = false; MP.printError(EC.GENERAL, e); // LL changed call 7 April 2012 } finally { this.printSummary(success, startTime); if (this.checkLiveness) { if (LIVENESS_STATS) { // Reclaim memory for in-degree calculation System.gc(); MP.printStats(liveCheck .calculateInDegreeDiskGraphs(new BucketStatistics("Histogram vertex in-degree", LiveCheck.class.getPackage().getName(), "DiskGraphsInDegree")), liveCheck.getOutDegreeStatistics()); } } this.cleanup(success); } report("exiting modelCheck()"); } /** * Check the assumptions. */ public boolean checkAssumptions() { ExprNode[] assumps = this.tool.getAssumptions(); boolean[] isAxiom = this.tool.getAssumptionIsAxiom(); for (int i = 0; i < assumps.length; i++) { try { if ((!isAxiom[i]) && !this.tool.isValid(assumps[i])) { MP.printError(EC.TLC_ASSUMPTION_FALSE, assumps[i].toString()); return false; } } catch (Exception e) { // Assert.printStack(e); MP.printError(EC.TLC_ASSUMPTION_EVALUATION_ERROR, new String[] { assumps[i].toString(), e.getMessage() }); return false; } } return true; } /** * Initialize the model checker * @return status, if false, the processing should be stopped * @throws Throwable */ public final boolean doInit(boolean ignoreCancel) throws Throwable { // SZ Feb 23, 2009: cancel flag set, quit if (!ignoreCancel && this.cancellationFlag) { return false; } // Generate the initial states. // // The functor is passed to getInitStates() to - instead of adding all // init states into an intermediate StateVec to check and add each state // in a subsequent loop - directly check each state one-by-one and add // it to the queue, fingerprint set and trace file. This avoids // allocating memory for StateVec (which depending on the number of init // states can grow to be GBs) and the subsequent loop over StateVec. final DoInitFunctor functor = new DoInitFunctor(); this.tool.getInitStates(functor); // Iff one of the init states' checks violates any properties, the // functor will record it. if (functor.errState != null) { this.errState = functor.errState; throw functor.e; } // Return whatever the functor has recorded. return functor.returnValue; } /** * Compute the set of the next states. For each next state, check that * it is a valid state, check that the invariants are satisfied, check * that it satisfies the constraints, and enqueue it in the state queue. * Return true if the model checking should stop. * * This method is called from the workers on every step */ public final boolean doNext(TLCState curState, ObjLongTable counts) throws Throwable { // SZ Feb 23, 2009: cancel the calculation if (this.cancellationFlag) { return false; } boolean deadLocked = true; TLCState succState = null; StateVec liveNextStates = null; LongVec liveNextFPs = null; if (this.checkLiveness) { liveNextStates = new StateVec(2); liveNextFPs = new LongVec(2); } try { int k = 0; // <-- // <-- for (int i = 0; i < this.actions.length; i++) { // SZ Feb 23, 2009: cancel the calculation if (this.cancellationFlag) { return false; } //TODO Implement IStateFunctor pattern for getNextStates() too // to reduce memory and runtime overhead of allocating and // looping StateVec. However - contrary to doInit() - doNext() // is incompatible to the functor when liveness checking is // turned on. Liveness checking does not support adding // nextStates one-by-one but expects to be given the whole set // of nextStates in a single invocation // (LiveCheck#addNextState(..). If this limitation is ever // removed, the functor pattern could be applied to doNext too. StateVec nextStates = this.tool.getNextStates(this.actions[i], curState); int sz = nextStates.size(); this.incNumOfGenStates(sz); deadLocked = deadLocked && (sz == 0); SUCCESSORS: for (int j = 0; j < sz; j++) { succState = nextStates.elementAt(j); // Check if succState is a legal state. if (!this.tool.isGoodState(succState)) { if (this.setErrState(curState, succState, false)) { MP.printError(EC.TLC_STATE_NOT_COMPLETELY_SPECIFIED_NEXT); this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); synchronized (this) { this.notify(); } } return true; } if (TLCGlobals.coverageInterval >= 0) { ((TLCStateMutSource) succState).addCounts(counts); } final boolean inModel = (this.tool.isInModel(succState) && this.tool.isInActions(curState, succState)); boolean seen = false; if (inModel) { long fp = succState.fingerPrint(); seen = this.theFPSet.put(fp); if (!seen) { // Write out succState when needed: if (this.allStateWriter != null) { this.allStateWriter.writeState(succState); } // Write succState to trace only if it satisfies the // model constraints. Do not enqueue it yet, but wait // for implied actions and invariants to be checked. // Those checks - if violated - will cause model checking // to terminate. Thus we cannot let concurrent workers start // exploring this new state. Conversely, the state has to // be in the trace in case either invariant or implied action // checks want to print the trace. long loc = this.trace.writeState(curState, fp); succState.uid = loc; } // For liveness checking: if (this.checkLiveness) { liveNextStates.addElement(succState); liveNextFPs.addElement(fp); } } // Check if succState violates any invariant: if (!seen) { try { int len = this.invariants.length; INVARIANTS: for (k = 0; k < len; k++) { // SZ Feb 23, 2009: cancel the calculation if (this.cancellationFlag) { return false; } if (!tool.isValid(this.invariants[k], succState)) { // We get here because of invariant violation: synchronized (this) { if (TLCGlobals.continuation) { MP.printError(EC.TLC_INVARIANT_VIOLATED_BEHAVIOR, this.tool.getInvNames()[k]); this.trace.printTrace(curState, succState); break INVARIANTS; } else { if (this.setErrState(curState, succState, false)) { MP.printError(EC.TLC_INVARIANT_VIOLATED_BEHAVIOR, this.tool .getInvNames()[k]); this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); this.notify(); } return true; } } } } if (k < len) { if (inModel && !seen) { // Even though the state violates an // invariant, add it to the queue. After // all, the user selected to continue model // checking even if an invariant is // violated. this.theStateQueue.sEnqueue(succState); } // Continue with next successor iff an // invariant is violated and // TLCGlobals.continuation is true. continue SUCCESSORS; } } catch (Exception e) { if (this.setErrState(curState, succState, true)) { MP.printError(EC.TLC_INVARIANT_EVALUATION_FAILED, new String[] { this.tool.getInvNames()[k], (e.getMessage() == null) ? e.toString() : e.getMessage() }); this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); this.notify(); } throw e; } } // Check if the state violates any implied action. We need to do it // even if succState is not new. try { int len = this.impliedActions.length; IMPLIED: for (k = 0; k < len; k++) { // SZ Feb 23, 2009: cancel the calculation if (this.cancellationFlag) { return false; } if (!tool.isValid(this.impliedActions[k], curState, succState)) { // We get here because of implied-action violation: synchronized (this) { if (TLCGlobals.continuation) { MP.printError(EC.TLC_ACTION_PROPERTY_VIOLATED_BEHAVIOR, this.tool .getImpliedActNames()[k]); this.trace.printTrace(curState, succState); break IMPLIED; } else { if (this.setErrState(curState, succState, false)) { MP.printError(EC.TLC_ACTION_PROPERTY_VIOLATED_BEHAVIOR, this.tool .getImpliedActNames()[k]); this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); this.notify(); } return true; } } } } if (k < len) { if (inModel && !seen) { // Even though the state violates an // invariant, add it to the queue. After // all, the user selected to continue model // checking even if an implied action is // violated. this.theStateQueue.sEnqueue(succState); } // Continue with next successor iff an // implied action is violated and // TLCGlobals.continuation is true. continue SUCCESSORS; } } catch (Exception e) { if (this.setErrState(curState, succState, true)) { MP.printError(EC.TLC_ACTION_PROPERTY_EVALUATION_FAILED, new String[] { this.tool.getImpliedActNames()[k], (e.getMessage() == null) ? e.toString() : e.getMessage() }); this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); this.notify(); } throw e; } if (inModel && !seen) { // The state is inModel, unseen and neither invariants // nor implied actions are violated. It is thus eligible // for further processing by other workers. this.theStateQueue.sEnqueue(succState); } } // Must set state to null!!! succState = null; } // Check for deadlock: if (deadLocked && this.checkDeadlock) { synchronized (this) { if (this.setErrState(curState, null, false)) { MP.printError(EC.TLC_DEADLOCK_REACHED); this.trace.printTrace(curState, null); this.theStateQueue.finishAll(); this.notify(); } } return true; } // Finally, add curState into the behavior graph for liveness checking: if (this.checkLiveness) { // Add the stuttering step: long curStateFP = curState.fingerPrint(); liveNextStates.addElement(curState); liveNextFPs.addElement(curStateFP); liveCheck.addNextState(curState, curStateFP, liveNextStates, liveNextFPs); } return false; } catch (Throwable e) { // Assert.printStack(e); boolean keep = ((e instanceof StackOverflowError) || (e instanceof OutOfMemoryError) || (e instanceof AssertionError)); synchronized (this) { if (this.setErrState(curState, succState, !keep)) { if (e instanceof StackOverflowError) { MP.printError(EC.SYSTEM_STACK_OVERFLOW, e); } else if (e instanceof OutOfMemoryError) { MP.printError(EC.SYSTEM_OUT_OF_MEMORY, e); } else if (e instanceof AssertionError) { MP.printError(EC.TLC_BUG, e); } else if (e.getMessage() != null) { MP.printError(EC.GENERAL, e); // LL changed call 7 April 2012 } this.trace.printTrace(curState, succState); this.theStateQueue.finishAll(); this.notify(); } } throw e; } } /** * Things need to be done here: * Check liveness: check liveness properties on the partial state graph. * Create checkpoint: checkpoint three data structures: the state set, * the state queue, and the state trace. */ public final boolean doPeriodicWork() throws Exception { if ((!this.checkLiveness || !liveCheck.doLiveCheck()) && !TLCGlobals.doCheckPoint()) { // Do not suspend the state queue if neither check-pointing nor // liveness-checking is going to happen. Suspending is expensive. // It stops all workers. System.err.println("§§grlksejglkfdjglsk§"); return true; } if (this.theStateQueue.suspendAll()) { // Run liveness checking, if needed: if (this.checkLiveness) { if (!liveCheck.check(false)) return false; } if (TLCGlobals.doCheckPoint()) { // Checkpoint: MP.printMessage(EC.TLC_CHECKPOINT_START, this.metadir); // start checkpointing: this.theStateQueue.beginChkpt(); this.trace.beginChkpt(); this.theFPSet.beginChkpt(); this.theStateQueue.resumeAll(); UniqueString.internTbl.beginChkpt(this.metadir); if (this.checkLiveness) { liveCheck.beginChkpt(); } // commit checkpoint: this.theStateQueue.commitChkpt(); this.trace.commitChkpt(); this.theFPSet.commitChkpt(); UniqueString.internTbl.commitChkpt(this.metadir); if (this.checkLiveness) { liveCheck.commitChkpt(); } MP.printMessage(EC.TLC_CHECKPOINT_END); } else { // Just resume worker threads when checkpointing is skipped this.theStateQueue.resumeAll(); } } return true; } public final boolean recover() throws IOException { boolean recovered = false; if (this.fromChkpt != null) { // We recover from previous checkpoint. MP.printMessage(EC.TLC_CHECKPOINT_RECOVER_START, this.fromChkpt); this.trace.recover(); this.theStateQueue.recover(); this.theFPSet.recover(); if (this.checkLiveness) { liveCheck.recover(); } MP.printMessage(EC.TLC_CHECKPOINT_RECOVER_END, new String[] { String.valueOf(this.theFPSet.size()), String.valueOf(this.theStateQueue.size()) }); recovered = true; this.numOfGenStates.set(this.theFPSet.size()); } return recovered; } private final void cleanup(boolean success) throws IOException { this.theFPSet.close(); this.trace.close(); if (this.checkLiveness) liveCheck.close(); if (this.allStateWriter != null) this.allStateWriter.close(); if (!VETO_CLEANUP) { FileUtil.deleteDir(this.metadir, success); } } public final void printSummary(boolean success, final long startTime) throws IOException { super.reportCoverage(this.workers); /* * This allows the toolbox to easily display the last set * of state space statistics by putting them in the same * form as all other progress statistics. */ if (TLCGlobals.tool) { printProgresStats(startTime); } MP.printMessage(EC.TLC_STATS, new String[] { String.valueOf(this.numOfGenStates), String.valueOf(this.theFPSet.size()), String.valueOf(this.theStateQueue.size()) }); if (success) { MP.printMessage(EC.TLC_SEARCH_DEPTH, String.valueOf(this.trace.getLevelForReporting())); } } private final void printProgresStats(final long startTime) throws IOException { final long fpSetSize = this.theFPSet.size(); // print progress showing states per minute metric (spm) final double factor; if (startTime < 0) { factor = TLCGlobals.progressInterval / 60000d; } else { // This is final statistics oldNumOfGenStates = 0; oldFPSetSize = 0; factor = (System.currentTimeMillis() - startTime) / 60000d; } long l = numOfGenStates.get(); statesPerMinute = (long) ((l - oldNumOfGenStates) / factor); oldNumOfGenStates = l; distinctStatesPerMinute = (long) ((fpSetSize - oldFPSetSize) / factor); oldFPSetSize = fpSetSize; MP.printMessage(EC.TLC_PROGRESS_STATS, new String[] { String.valueOf(this.trace.getLevelForReporting()), String.valueOf(this.numOfGenStates), String.valueOf(fpSetSize), String.valueOf(this.theStateQueue.size()), String.valueOf(statesPerMinute), String.valueOf(distinctStatesPerMinute) }); } public static final void reportSuccess(final FPSet anFpSet, final long numOfGenStates) throws IOException { final long fpSetSize = anFpSet.size(); final double actualProb = anFpSet.checkFPs(); reportSuccess(fpSetSize, actualProb, numOfGenStates); } public static final void reportSuccess(final long numOfDistinctStates, final double actualProb, final long numOfGenStates) throws IOException { // shown as 'calculated' in Toolbox final double optimisticProb = numOfDistinctStates * ((numOfGenStates - numOfDistinctStates) / Math.pow(2, 64)); /* The following code added by LL on 3 Aug 2009 to print probabilities * to only one decimal point. Removed by LL on 17 April 2012 because it * seemed to report probabilities > 10-4 as probability 0. */ // final PrintfFormat fmt = new PrintfFormat("val = %.1G"); // final String optimisticProbStr = fmt.sprintf(optimisticProb); // final String actualProbStr = fmt.sprintf(actualProb); // Following two lines added by LL on 17 April 2012 final String optimisticProbStr = "val = " + ProbabilityToString(optimisticProb, 2); // shown as 'observed' in Toolbox final String actualProbStr = "val = " + ProbabilityToString(actualProb, 2); MP.printMessage(EC.TLC_SUCCESS, new String[] { optimisticProbStr, actualProbStr }); } /** * This method added by LL on 17 April 2012 to replace the use of the PrintfFormat * method in reportSuccess. * * Returns a string representing the decimal representation of a probability to * a given number of significant digits. If the input is not a probability, or if * some error is found, then it returns the result of applying Double.toString(long) * to the value. * * Warning: the code makes the following assumption: * - Double.toString(v) returns a decimal representation of v of the * form [d]* ["." [d]+ ["E" [+ | -] [d]+] where d is a decimal digit and * [x] = 0 or 1 instance of x * [x]* = any number of instances of x * [x]+ = any non-zero number of instances of x * x | y = an x or a y * * @param val - the probability represented as a long; must satisfy 0 <= val <= 1. * @param significantDigits - the number of significant digits to include; must be > 0. * @return */ private static final String ProbabilityToString(double val, int significantDigits) { /* * If val = 0 (which shouldn't happen), return "0.0" */ if (val == 0) { return "0.0"; } String valString = Double.toString(val) ; int valStringLen = valString.length(); String result = ""; int next = 0; // pointer to the next character in valString to examine. int significantDigitsFound = 0; /* * Skip past leading zeros. */ while ((next < valStringLen) && (valString.charAt(next) == '0')) { next++ ; } /* * Append all the following digits to result, incrementing * significantDigits for each one. */ while ( (next < valStringLen) && Character.isDigit(valString.charAt(next))) { result = result + valString.charAt(next); significantDigitsFound++; next++ ; } /* * IF next character is not "." * THEN IF at end THEN return result * ELSE return valString. */ if (next == valStringLen) { return result; } else if (valString.charAt(next) != '.') { return valString; } /* * IF significantDigitsFound >= significantDigits, * THEN skip over "." and the following digits. * (this should not happen) * ELSE append "." to result ; * IF significantDigitsFound = 0 * THEN copy each of the following "0"s of valString to result; * copy up to significantDigits - significantDigitsFound * following digits of valString to result; * IF next char of valString a digit >= "5" * THEN propagate a carry backwards over the digits of result * -- e.g., changing ".019" to ".020"; * Skip over remaining digits of valString; */ if (significantDigitsFound >= significantDigits) { next++ ; while ( (next < valStringLen) && Character.isDigit(valString.charAt(next))) { next++ ; } } else { next++; result = result + "."; if (significantDigitsFound == 0) { while ((next < valStringLen) && (valString.charAt(next) == '0')) { next++ ; result = result + "0"; } } while ((next < valStringLen) && Character.isDigit(valString.charAt(next)) && significantDigitsFound < significantDigits ) { result = result + valString.charAt(next); next++; significantDigitsFound++; } if ((next < valStringLen) && Character.isDigit(valString.charAt(next)) && Character.digit(valString.charAt(next), 10) >= 5) { int prev = result.length()-1; // the next digit of result to increment boolean done = false; while (!done) { if (prev < 0) { result = "1" + result; done = true; } else { char prevChar = result.charAt(prev); String front = result.substring(0, prev); String back = result.substring(prev+1); if (Character.isDigit(prevChar)) { if (prevChar == '9') { result = front + '0' + back; } else { result = front + Character.forDigit(Character.digit(prevChar, 10)+1, 10) + back; done = true; } } else { // prevChar must be '.', so just continue } } prev--; } } while ((next < valStringLen) && Character.isDigit(valString.charAt(next))) { next++; } } /* * IF next at end of valString or at "E" * THEN copy remaining chars of valString to result; * return result * ELSE return valString */ if (next >= valStringLen) { return result; } if (valString.charAt(next)=='E') { next++; result = result + "E"; while (next < valStringLen) { result = result + valString.charAt(next); next++; } return result; } return valString; } // The following method used for testing ProbabilityToString // // public static void main(String[] args) { // double[] test = new double[] {.5, .0995, .00000001, 001.000, .0022341, // .0022351, 3.14159E-12, // 00.999, .002351111, 22.8E-14, 0.000E-12, // 37, 0033D, 04.85, -35.3}; // int i = 0; // while (i < test.length) { // System.out.println("" + i + ": " + Double.toString(test[i]) + " -> " + ProbabilityToString(test[i],2)); // i++; // } // } public final void setAllValues(int idx, Value val) { for (int i = 0; i < this.workers.length; i++) { workers[i].setLocalValue(idx, val); } } public final Value getValue(int i, int idx) { return workers[i].getLocalValue(idx); } /** * Spawn the worker threads */ protected IdThread[] startWorkers(AbstractChecker checker, int checkIndex) { for (int i = 0; i < this.workers.length; i++) { this.workers[i].start(); } return this.workers; } /** * Work to be done prior entering to the worker loop */ protected void runTLCPreLoop() { // nothing to do in this implementation } /** * Process calculation. * * Comments added 9 April 2012 by LL. The above was Simon's extensive commenting. I presume * he really mean "ProGRess calculation", since this seems to be where the coverage * and progress information is written. The method writes the progress information, * prints the coverage only if count = 0, and then waits until it's time to print * the next progress report before exiting. (The next progress report is printed * the next time the method is called.) * * It looks like this is where the depth-first model checker exits when it has * finished checking the required depth, but I'm not sure. * * @param count * @param depth * @throws Exception */ protected void runTLCContinueDoing(final int count, final int depth) throws Exception { final int level = this.trace.getLevel(); printProgresStats(-1); if (level > depth) { this.theStateQueue.finishAll(); this.done = true; } else { // The following modification sof count are obviously bogus and // resulted from Simon's modification of Yuan's original code. // Yuan's original code assumes coverageInterval >= progressInterval, // and this should eventually be changed. But for now, // the caller of this method is responsible for updating // count. LL 9 Oct 2009 if (count == 0) { super.reportCoverage(this.workers); // count = TLCGlobals.coverageInterval / TLCGlobals.progressInterval; } // else // { // count--; // } this.wait(TLCGlobals.progressInterval); } } /** * Debugging support * @param e */ private void report(Throwable e) { DebugPrinter.print(e); } public long getStatesGenerated() { return numOfGenStates.get(); } /** * An implementation of {@link IStateFunctor} for * {@link ModelChecker#doInit(boolean)}. */ private class DoInitFunctor implements IStateFunctor { /** * Non-Null iff a violation occurred. */ private TLCState errState; private Throwable e; /** * The return values of addElement are meaningless, but doInit wants to * know the actual outcome when all init states have been processed. * This outcome is stored as returnValue. */ private boolean returnValue = true; /* (non-Javadoc) * @see tlc2.tool.IStateFunctor#addElement(tlc2.tool.TLCState) */ public Object addElement(final TLCState curState) { incNumOfGenStates(1); // getInitStates() does not support aborting init state generation // once a violation has been found (that is why the return values of // addElement are meaningless). It continues until all init // states have been generated. Thus, the functor simply ignores // subsequent states once a violation has been recorded. if (errState != null) { returnValue = false; return returnValue; } try { // Check if the state is a legal state if (!tool.isGoodState(curState)) { MP.printError(EC.TLC_INITIAL_STATE, curState.toString()); return returnValue; } boolean inModel = tool.isInModel(curState); boolean seen = false; if (inModel) { long fp = curState.fingerPrint(); seen = theFPSet.put(fp); if (!seen) { if (allStateWriter != null) { allStateWriter.writeState(curState); } curState.uid = trace.writeState(fp); theStateQueue.enqueue(curState); // build behavior graph for liveness checking if (checkLiveness) { liveCheck.addInitState(curState, fp); } } } // Check properties of the state: if (!seen) { for (int j = 0; j < invariants.length; j++) { if (!tool.isValid(invariants[j], curState)) { // We get here because of invariant violation: MP.printError(EC.TLC_INVARIANT_VIOLATED_INITIAL, new String[] { tool.getInvNames()[j].toString(), curState.toString() }); if (!TLCGlobals.continuation) { returnValue = false; return returnValue; } } } for (int j = 0; j < impliedInits.length; j++) { if (!tool.isValid(impliedInits[j], curState)) { // We get here because of implied-inits violation: MP.printError(EC.TLC_PROPERTY_VIOLATED_INITIAL, new String[] { tool.getImpliedInitNames()[j], curState.toString() }); returnValue = false; return returnValue; } } } } catch (Throwable e) { // Assert.printStack(e); if (e instanceof OutOfMemoryError) { MP.printError(EC.SYSTEM_OUT_OF_MEMORY_TOO_MANY_INIT); returnValue = false; return returnValue; } this.errState = curState; this.e = e; } return returnValue; } } }
Remove left over debug syserr statement.
tlatools/src/tlc2/tool/ModelChecker.java
Remove left over debug syserr statement.
<ide><path>latools/src/tlc2/tool/ModelChecker.java <ide> // Do not suspend the state queue if neither check-pointing nor <ide> // liveness-checking is going to happen. Suspending is expensive. <ide> // It stops all workers. <del> System.err.println("§§grlksejglkfdjglsk§"); <ide> return true; <ide> } <ide>
Java
apache-2.0
b60e8f6890daa8ad4eed26f7bea43bbf38bf307d
0
zqian/sakai,tl-its-umich-edu/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,clhedrick/sakai,ktakacs/sakai,kingmook/sakai,bkirschn/sakai,hackbuteer59/sakai,introp-software/sakai,udayg/sakai,rodriguezdevera/sakai,kingmook/sakai,buckett/sakai-gitflow,hackbuteer59/sakai,pushyamig/sakai,surya-janani/sakai,clhedrick/sakai,joserabal/sakai,liubo404/sakai,Fudan-University/sakai,zqian/sakai,surya-janani/sakai,colczr/sakai,puramshetty/sakai,pushyamig/sakai,lorenamgUMU/sakai,bzhouduke123/sakai,wfuedu/sakai,frasese/sakai,conder/sakai,udayg/sakai,willkara/sakai,joserabal/sakai,willkara/sakai,ouit0408/sakai,pushyamig/sakai,wfuedu/sakai,wfuedu/sakai,tl-its-umich-edu/sakai,clhedrick/sakai,conder/sakai,introp-software/sakai,hackbuteer59/sakai,ouit0408/sakai,frasese/sakai,clhedrick/sakai,kwedoff1/sakai,whumph/sakai,kwedoff1/sakai,willkara/sakai,udayg/sakai,rodriguezdevera/sakai,kingmook/sakai,udayg/sakai,bzhouduke123/sakai,zqian/sakai,willkara/sakai,joserabal/sakai,ktakacs/sakai,ouit0408/sakai,ouit0408/sakai,colczr/sakai,lorenamgUMU/sakai,rodriguezdevera/sakai,buckett/sakai-gitflow,bzhouduke123/sakai,kwedoff1/sakai,liubo404/sakai,zqian/sakai,OpenCollabZA/sakai,surya-janani/sakai,liubo404/sakai,conder/sakai,wfuedu/sakai,introp-software/sakai,colczr/sakai,frasese/sakai,kingmook/sakai,surya-janani/sakai,kingmook/sakai,willkara/sakai,OpenCollabZA/sakai,bkirschn/sakai,buckett/sakai-gitflow,clhedrick/sakai,Fudan-University/sakai,bkirschn/sakai,tl-its-umich-edu/sakai,frasese/sakai,introp-software/sakai,frasese/sakai,ktakacs/sakai,pushyamig/sakai,colczr/sakai,whumph/sakai,colczr/sakai,OpenCollabZA/sakai,zqian/sakai,pushyamig/sakai,Fudan-University/sakai,colczr/sakai,puramshetty/sakai,kingmook/sakai,rodriguezdevera/sakai,lorenamgUMU/sakai,joserabal/sakai,liubo404/sakai,conder/sakai,kingmook/sakai,OpenCollabZA/sakai,bkirschn/sakai,OpenCollabZA/sakai,ouit0408/sakai,puramshetty/sakai,noondaysun/sakai,OpenCollabZA/sakai,bkirschn/sakai,noondaysun/sakai,lorenamgUMU/sakai,colczr/sakai,frasese/sakai,Fudan-University/sakai,kwedoff1/sakai,introp-software/sakai,willkara/sakai,pushyamig/sakai,OpenCollabZA/sakai,joserabal/sakai,clhedrick/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,ktakacs/sakai,ktakacs/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,hackbuteer59/sakai,joserabal/sakai,liubo404/sakai,kwedoff1/sakai,introp-software/sakai,puramshetty/sakai,wfuedu/sakai,Fudan-University/sakai,tl-its-umich-edu/sakai,duke-compsci290-spring2016/sakai,whumph/sakai,ouit0408/sakai,Fudan-University/sakai,udayg/sakai,bzhouduke123/sakai,kwedoff1/sakai,frasese/sakai,tl-its-umich-edu/sakai,conder/sakai,rodriguezdevera/sakai,frasese/sakai,liubo404/sakai,duke-compsci290-spring2016/sakai,joserabal/sakai,rodriguezdevera/sakai,zqian/sakai,kwedoff1/sakai,bkirschn/sakai,bzhouduke123/sakai,hackbuteer59/sakai,kwedoff1/sakai,kingmook/sakai,lorenamgUMU/sakai,whumph/sakai,udayg/sakai,conder/sakai,Fudan-University/sakai,puramshetty/sakai,whumph/sakai,noondaysun/sakai,introp-software/sakai,noondaysun/sakai,bzhouduke123/sakai,noondaysun/sakai,buckett/sakai-gitflow,zqian/sakai,noondaysun/sakai,conder/sakai,pushyamig/sakai,OpenCollabZA/sakai,surya-janani/sakai,udayg/sakai,colczr/sakai,buckett/sakai-gitflow,ouit0408/sakai,lorenamgUMU/sakai,whumph/sakai,bzhouduke123/sakai,noondaysun/sakai,joserabal/sakai,bkirschn/sakai,duke-compsci290-spring2016/sakai,clhedrick/sakai,surya-janani/sakai,tl-its-umich-edu/sakai,hackbuteer59/sakai,noondaysun/sakai,ouit0408/sakai,buckett/sakai-gitflow,duke-compsci290-spring2016/sakai,ktakacs/sakai,tl-its-umich-edu/sakai,wfuedu/sakai,rodriguezdevera/sakai,surya-janani/sakai,surya-janani/sakai,hackbuteer59/sakai,clhedrick/sakai,whumph/sakai,duke-compsci290-spring2016/sakai,introp-software/sakai,udayg/sakai,zqian/sakai,willkara/sakai,tl-its-umich-edu/sakai,duke-compsci290-spring2016/sakai,puramshetty/sakai,ktakacs/sakai,whumph/sakai,puramshetty/sakai,ktakacs/sakai,bkirschn/sakai,lorenamgUMU/sakai,wfuedu/sakai,wfuedu/sakai,Fudan-University/sakai,pushyamig/sakai,lorenamgUMU/sakai,hackbuteer59/sakai,liubo404/sakai,willkara/sakai,conder/sakai,liubo404/sakai,bzhouduke123/sakai
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the"License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.tool.assessment.ui.bean.author; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.faces.context.FacesContext; import javax.faces.context.ExternalContext; import javax.faces.event.ValueChangeEvent; import javax.faces.model.SelectItem; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.tool.assessment.data.ifc.assessment.AttachmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemAttachmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.facade.AssessmentFacade; import org.sakaiproject.tool.assessment.facade.ItemFacade; import org.sakaiproject.tool.assessment.facade.QuestionPoolFacade; import org.sakaiproject.tool.assessment.facade.SectionFacade; import org.sakaiproject.tool.assessment.services.ItemService; import org.sakaiproject.tool.assessment.services.QuestionPoolService; import org.sakaiproject.tool.assessment.services.assessment.AssessmentService; import org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean; import org.sakaiproject.tool.assessment.ui.bean.questionpool.QuestionPoolBean; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.entity.impl.ReferenceComponent; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.exception.TypeException; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.FilePickerHelper; import org.sakaiproject.content.cover.ContentHostingService; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.util.ResourceLoader; //import org.osid.shared.*; /** * Backing bean for Item Authoring, uses ItemBean for UI * $Id$ */ public class ItemAuthorBean implements Serializable { private static Log log = LogFactory.getLog(ItemAuthorBean.class); /** Use serialVersionUID for interoperability. */ private final static long serialVersionUID = 8266438770394956874L; public final static String FROM_QUESTIONPOOL= "questionpool"; public final static String FROM_ASSESSMENT= "assessment"; private String assessTitle; private String sectionIdent; private ArrayList assessmentSectionIdents; private String insertPosition; private String insertToSection; private String insertType; private String assessmentID; private String currentSection; private String itemId; private String itemNo; private String itemType; private String itemTypeString; // used for inserting a question private String showMetadata; private String showOverallFeedback; private String showQuestionLevelFeedback; private String showSelectionLevelFeedback; private String showFeedbackAuthoring; private ArrayList trueFalseAnswerSelectList; private ItemDataIfc item; private ItemBean currentItem; private ItemFacade itemToDelete; private ItemFacade itemToPreview; private List attachmentList; // for questionpool private String qpoolId; private String target; private ArrayList poolListSelectItems; // for item editing private boolean[] choiceCorrectArray; private String maxRecordingTime; private String maxNumberRecordings; private String scaleName; private String[] matches; private String[] matchAnswers; private String[] matchFeedbackList; private String[] answerFeedbackList; // for navigation private String outcome; /** * Creates a new ItemAuthorBean object. */ public ItemAuthorBean() { } public void setItem(ItemDataIfc item) { this.item=item; this.attachmentList = item.getItemAttachmentList(); } public ItemDataIfc getItem() { return item; } public void setCurrentItem(ItemBean item) { this.currentItem=item; } public ItemBean getCurrentItem() { return currentItem; } /** * @return */ public String getAssessTitle() { return assessTitle; } /** * @param string */ public void setAssessTitle(String string) { assessTitle = string; } /** * @return */ public String getSectionIdent() { return sectionIdent; } /** * @param string */ public void setSectionIdent(String string) { sectionIdent = string; } /** * @return */ public ArrayList getAssessmentSectionIdents() { return assessmentSectionIdents; } /** * @param list */ public void setAssessmentSectionIdents(ArrayList list) { assessmentSectionIdents = list; } /** * @return */ public String getInsertPosition() { return insertPosition; } /** * @param string */ public void setInsertPosition(String string) { insertPosition = string; } /** * @return */ public String getInsertToSection() { return insertToSection; } /** * @param string */ public void setInsertToSection(String string) { insertToSection= string; } /** * @return */ public String getInsertType() { return insertType; } /** * @param string */ public void setInsertType(String string) { insertType= string; } /** * @return */ public String getAssessmentID() { return assessmentID; } /** * @param string */ public void setAssessmentID(String string) { assessmentID = string; } /** * @return */ public String getCurrentSection() { return currentSection; } /** * @param string */ public void setCurrentSection(String string) { currentSection = string; } /** * @return */ public String getItemNo() { return itemNo; } /** * @param string */ public void setItemNo(String string) { itemNo = string; } public String getItemId() { return itemId; } public void setItemId(String string) { itemId= string; } /** * @return */ public String getItemType() { return itemType; } /** * @param string */ public void setItemType(String string) { itemType = string; } /** * @return */ public String getItemTypeString() { return itemTypeString; } /** * @param string */ public void setItemTypeString(String string) { itemTypeString = string; } /** * @return */ public String getShowMetadata() { return showMetadata; } /** * @param string */ public void setShowMetadata(String string) { showMetadata = string; } /** * @return */ public String getShowOverallFeedback() { return showOverallFeedback; } /** * @return */ public String getShowQuestionLevelFeedback() { return showQuestionLevelFeedback; } /** * @return */ public String getShowSelectionLevelFeedback() { return showSelectionLevelFeedback; } /** * @param string */ public void setShowOverallFeedback(String string) { showOverallFeedback = string; } /** * @param string */ public void setShowQuestionLevelFeedback(String string) { showQuestionLevelFeedback = string; } /** * @param string */ public void setShowSelectionLevelFeedback(String string) { showSelectionLevelFeedback = string; } /** * @param string */ public void setQpoolId(String string) { qpoolId= string; } /** * @return */ public String getQpoolId() { return qpoolId; } /** * @param string */ public void setItemToDelete(ItemFacade param) { itemToDelete= param; } /** * @return */ public ItemFacade getItemToDelete() { return itemToDelete; } /** * @param string */ public void setItemToPreview(ItemFacade param) { itemToPreview= param; } /** * @return */ public ItemFacade getItemToPreview() { return itemToPreview; } /** * @param string */ public void setTarget(String string) { target= string; } /** * @return */ public String getTarget() { return target; } /** * This is an array of correct/not correct flags * @return the array of correct/not correct flags */ public boolean[] getChoiceCorrectArray() { return choiceCorrectArray; } /** * set array of correct/not correct flags * @param choiceCorrectArray of correct/not correct flags */ public void setChoiceCorrectArray(boolean[] choiceCorrectArray) { this.choiceCorrectArray = choiceCorrectArray; } /** * is the nth choice correct? * @param n * @return */ public boolean isCorrectChoice(int n) { return choiceCorrectArray[n]; } /** * set the nth choice correct? * @param n * @param correctChoice true if it is */ public void setCorrectChoice(int n, boolean correctChoice) { this.choiceCorrectArray[n] = correctChoice; } /** * for audio recording * @return maximum time for recording */ public String getMaxRecordingTime() { return maxRecordingTime; } /** * for audio recording * @param maxRecordingTime maximum time for recording */ public void setMaxRecordingTime(String maxRecordingTime) { this.maxRecordingTime = maxRecordingTime; } /** * for audio recording * @return maximum attempts */ public String getMaxNumberRecordings() { return maxNumberRecordings; } /** * set audio recording maximum attempts * @param maxNumberRecordings */ public void setMaxNumberRecordings(String maxNumberRecordings) { this.maxNumberRecordings = maxNumberRecordings; } /** * for survey * @return the scale */ public String getScaleName() { return scaleName; } /** * set the survey scale * @param scaleName */ public void setScaleName(String scaleName) { this.scaleName = scaleName; } public String getOutcome() { return outcome; } /** * set the survey scale * @param param */ public void setOutcome(String param) { this.outcome= param; } /** * Maching only. * Get an array of match Strings. * @return array of match Strings. */ public String[] getMatches() { return matches; } /** * Maching only. * Set array of match Strings. * @param matches array of match Strings. */ public void setMatches(String[] matches) { this.matches = matches; } /** * Maching only. * Get the nth match String. * @param n * @return the nth match String */ public String getMatch(int n) { return matches[n]; } /** * Maching only. * Set the nth match String. * @param n * @param match */ public void setMatch(int n, String match) { matches[n] = match; } /** * get 1, 2, 3... for each match * @param n * @return */ public int[] getMatchCounter() { int n = matches.length; int count[] = new int[n]; for (int i = 0; i < n; i++) { count[i] = i; } return count; } /** * Derived property. * @return ArrayList of model SelectItems */ public ArrayList getTrueFalseAnswerSelectList() { ArrayList list = new ArrayList(); String trueprop= ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.AuthorMessages","true_msg"); String falseprop= ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.AuthorMessages","false_msg"); String[] answerValues = {"true", "false"}; // not to be displayed in the UI String[] answerLabelText= {trueprop, falseprop}; currentItem.setAnswers(answerValues); currentItem.setAnswerLabels(answerLabelText); for (int i = 0; i < answerValues.length; i++) { SelectItem selection = new SelectItem(); selection.setLabel(answerLabelText[i]); selection.setValue(answerValues[i]); list.add(selection); } return list; } /* Derived property. * @return ArrayList of model SelectItems */ // TODO use sectionBean.getsectionNumberList when its ready public ArrayList getSectionSelectList() { ArrayList list = new ArrayList(); ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.AuthorMessages"); AssessmentBean assessbean = (AssessmentBean) ContextUtil.lookupBean("assessmentBean"); ArrayList sectionSet = assessbean.getSections(); Iterator iter = sectionSet.iterator(); int i =0; while (iter.hasNext()){ i = i + 1; SectionContentsBean part = (SectionContentsBean) iter.next(); SelectItem selection = new SelectItem(); // need to filter out all the random draw parts if (part.getSectionAuthorType().equals(SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL)) { // skip random draw parts, cannot add items to this part manually } else { if ("".equals(part.getTitle())) { selection.setLabel(rb.getString("p")+" "+ i ); } else { selection.setLabel(rb.getString("p")+" " + i + " - " + part.getTitle()); } selection.setValue(part.getSectionId()); list.add(selection); } } Collections.reverse(list); // create a new part if there are no non-randomDraw parts available if (list.size() <1) { i = i + 1; SelectItem temppart = new SelectItem(); temppart.setLabel(rb.getString("p")+" "+ i ); temppart.setValue("-1"); // use -1 to indicate this is a temporary part. if the user decides to cancel the operation, this part will not be created list.add(temppart); } return list; } /** * Derived property. * @return ArrayList of model SelectItems */ public ArrayList getPoolSelectList() { poolListSelectItems = new ArrayList(); QuestionPoolService delegate = new QuestionPoolService(); ArrayList qplist = delegate.getBasicInfoOfAllPools(AgentFacade.getAgentString()); Iterator iter = qplist.iterator(); try { while(iter.hasNext()) { QuestionPoolFacade pool = (QuestionPoolFacade) iter.next(); poolListSelectItems.add(new SelectItem((pool.getQuestionPoolId().toString()), pool.getDisplayName() ) ); } } catch (Exception e){ throw new RuntimeException(e); } Collections.sort(poolListSelectItems, new itemComparator()); return poolListSelectItems; } class itemComparator implements Comparator { public int compare(Object o1, Object o2) { SelectItem i1 = (SelectItem) o1; SelectItem i2 = (SelectItem) o2; return i1.getLabel().compareToIgnoreCase(i2.getLabel()); } } /** * Corresponding answer number list ordered for match * @return answer number */ public String[] getMatchAnswers() { return matchAnswers; } /** * Corresponding answer number list ordered for match * @param matchAnswers answer number list ordered for match */ public void setMatchAnswers(String[] matchAnswers) { this.matchAnswers = matchAnswers; } /** * Corresponding answer number for nth match * @param n * @return */ public String getMatchAnswer(int n) { return matchAnswers[n]; } /** * set answer number for nth match * @param n * @param matchAnswer */ public void setMatchAnswer(int n, String matchAnswer) { matchAnswers[n] = matchAnswer; } /** * feedback for nth match * @param n * @return feedback for nth match */ public String getMatchFeedback(int n) { return matchFeedbackList[n]; } /** * set feedback for nth match * @param n * @param matchFeedback feedback for match */ public void setMatchFeedback(int n, String matchFeedback) { this.matchFeedbackList[n] = matchFeedback; } /** * array of matching feeback * @return array of matching feeback */ public String[] getMatchFeedbackList() { return matchFeedbackList; } /** * set array of matching feeback * @param matchFeedbackList array of matching feeback */ public void setMatchFeedbackList(String[] matchFeedbackList) { this.matchFeedbackList = matchFeedbackList; } /////////////////////////////////////////////////////////////////////////// // ACTION METHODS /////////////////////////////////////////////////////////////////////////// public String[] getAnswerFeedbackList() { return answerFeedbackList; } public void setAnswerFeedbackList(String[] answerFeedbackList) { this.answerFeedbackList = answerFeedbackList; } public String doit() { // navigation for ItemModifyListener return outcome; } /** * delete specified Item */ public String deleteItem() { ItemService delegate = new ItemService(); Long deleteId= this.getItemToDelete().getItemId(); ItemFacade itemf = delegate.getItem(deleteId, AgentFacade.getAgentString()); // save the currSection before itemf.setSection(null), used to reorder question sequences SectionFacade currSection = (SectionFacade) itemf.getSection(); Integer currSeq = itemf.getSequence(); QuestionPoolService qpdelegate = new QuestionPoolService(); if ((qpdelegate.getPoolIdsByItem(deleteId.toString()) == null) || (qpdelegate.getPoolIdsByItem(deleteId.toString()).isEmpty() )){ // if no reference to this item at all, ie, this item is created in // assessment but not assigned to any pool delegate.deleteItem(deleteId, AgentFacade.getAgentString()); } else { if (currSection == null) { // if this item is created from question pool QuestionPoolBean qpoolbean= (QuestionPoolBean) ContextUtil.lookupBean("questionpool"); ItemFacade itemfacade= delegate.getItem(deleteId, AgentFacade.getAgentString()); ArrayList items = new ArrayList(); items.add(itemfacade); qpoolbean.setItemsToDelete(items); qpoolbean.removeQuestionsFromPool(); return "editPool"; } else { // // if some pools still reference to this item, ie, this item is // created in assessment but also assigned a a pool // then just set section = null itemf.setSection(null); delegate.saveItem(itemf); } } AssessmentService assessdelegate = new AssessmentService(); // reorder item numbers SectionFacade sectfacade = assessdelegate.getSection(currSection.getSectionId().toString()); Set itemset = sectfacade.getItemFacadeSet(); // should be size-1 now. Iterator iter = itemset.iterator(); while (iter.hasNext()) { ItemFacade itemfacade = (ItemFacade) iter.next(); Integer itemfacadeseq = itemfacade.getSequence(); if (itemfacadeseq.compareTo(currSeq) > 0 ){ itemfacade.setSequence(new Integer(itemfacadeseq.intValue()-1) ); delegate.saveItem(itemfacade); } } // go to editAssessment.jsp, need to first reset assessmentBean AssessmentBean assessmentBean = (AssessmentBean) ContextUtil.lookupBean( "assessmentBean"); AssessmentFacade assessment = assessdelegate.getAssessment(assessmentBean.getAssessmentId()); assessmentBean.setAssessment(assessment); assessdelegate.updateAssessmentLastModifiedInfo(assessment); return "editAssessment"; } public String confirmDeleteItem(){ ItemService delegate = new ItemService(); String itemId= ContextUtil.lookupParam("itemid"); ItemFacade itemf = delegate.getItem(new Long(itemId), AgentFacade.getAgentString()); setItemToDelete(itemf); return "removeQuestion"; } public void selectItemType(ValueChangeEvent event) { //FacesContext context = FacesContext.getCurrentInstance(); String type = (String) event.getNewValue(); setItemType(type); } /** * @return */ public String getShowFeedbackAuthoring() { return showFeedbackAuthoring; } /** * @param string */ public void setShowFeedbackAuthoring(String string) { showFeedbackAuthoring= string; } public List getAttachmentList() { return attachmentList; } /** * @param list */ public void setAttachmentList(List attachmentList) { this.attachmentList = attachmentList; } public boolean getHasAttachment(){ if (attachmentList != null && attachmentList.size() >0) return true; else return false; } public String addAttachmentsRedirect() { // 1. load resources into session for resources mgmt page // then redirect to resources mgmt page try { List filePickerList = prepareReferenceList(attachmentList); ToolSession currentToolSession = SessionManager.getCurrentToolSession(); currentToolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, filePickerList); ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); context.redirect("sakai.filepicker.helper/tool"); } catch(Exception e){ log.error("fail to redirect to attachment page: " + e.getMessage()); } return getOutcome(); } /* called by SamigoJsfTool.java on exit from file picker */ public void setItemAttachment(){ ItemService service = new ItemService(); ItemDataIfc itemData = null; // itemId == null => new questiion if (this.itemId!=null){ try{ itemData = service.getItem(this.itemId); } catch(Exception e){ log.warn(e.getMessage()); } } // list returns contains modified list of attachments, i.e. new // and old attachments. This list will be // persisted to DB if user hit Save on the Item Modifying page. List list = prepareItemAttachment(itemData); setAttachmentList(list); } private List prepareReferenceList(List attachmentList){ List list = new ArrayList(); if (attachmentList == null){ return list; } for (int i=0; i<attachmentList.size(); i++){ ContentResource cr = null; AttachmentIfc attach = (AttachmentIfc) attachmentList.get(i); try{ log.debug("*** resourceId="+attach.getResourceId()); cr = ContentHostingService.getResource(attach.getResourceId()); } catch (PermissionException e) { log.warn("ContentHostingService.getResource() throws PermissionException="+e.getMessage()); } catch (IdUnusedException e) { log.warn("ContentHostingService.getResource() throws IdUnusedException="+e.getMessage()); // <-- bad sign, some left over association of question and resource, // use case: user remove resource in file picker, then exit modification without // proper cancellation by clicking at the left nav instead of "cancel". // Also in this use case, any added resource would be left orphan. AssessmentService assessmentService = new AssessmentService(); assessmentService.removeItemAttachment(attach.getAttachmentId().toString()); } catch (TypeException e) { log.warn("ContentHostingService.getResource() throws TypeException="+e.getMessage()); } if (cr!=null){ ReferenceComponent ref = new ReferenceComponent(cr.getReference()); log.debug("*** ref="+ref); if (ref !=null ) list.add(ref); } } return list; } private List prepareItemAttachment(ItemDataIfc item){ ToolSession session = SessionManager.getCurrentToolSession(); if (session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) { Set attachmentSet = new HashSet(); if (item != null){ attachmentSet = item.getItemAttachmentSet(); } HashMap map = getResourceIdHash(attachmentSet); ArrayList newAttachmentList = new ArrayList(); AssessmentService assessmentService = new AssessmentService(); String protocol = ContextUtil.getProtocol(); List refs = (List)session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); if (refs!=null && refs.size() > 0){ Reference ref; for(int i=0; i<refs.size(); i++) { ref = (Reference) refs.get(i); String resourceId = ref.getId(); if (map.get(resourceId) == null){ // new attachment, add log.debug("**** ref.Id="+ref.getId()); log.debug("**** ref.name="+ref.getProperties().getProperty( ref.getProperties().getNamePropDisplayName())); ItemAttachmentIfc newAttach = assessmentService.createItemAttachment( item, ref.getId(), ref.getProperties().getProperty( ref.getProperties().getNamePropDisplayName()), protocol); newAttachmentList.add(newAttach); } else{ // attachment already exist, let's add it to new list and // check it off from map newAttachmentList.add((ItemAttachmentIfc)map.get(resourceId)); map.remove(resourceId); } } } session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL); return newAttachmentList; } else return item.getItemAttachmentList(); } private HashMap getResourceIdHash(Set attachmentSet){ HashMap map = new HashMap(); if (attachmentSet !=null ){ Iterator iter = attachmentSet.iterator(); while (iter.hasNext()){ ItemAttachmentIfc attach = (ItemAttachmentIfc) iter.next(); map.put(attach.getResourceId(), attach); } } return map; } private HashMap resourceHash = new HashMap(); public HashMap getResourceHash() { return resourceHash; } public void setResourceHash(HashMap resourceHash) { this.resourceHash = resourceHash; } }
samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/bean/author/ItemAuthorBean.java
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the"License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.tool.assessment.ui.bean.author; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.faces.context.FacesContext; import javax.faces.context.ExternalContext; import javax.faces.event.ValueChangeEvent; import javax.faces.model.SelectItem; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.tool.assessment.data.ifc.assessment.AttachmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemAttachmentIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc; import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.facade.AssessmentFacade; import org.sakaiproject.tool.assessment.facade.ItemFacade; import org.sakaiproject.tool.assessment.facade.QuestionPoolFacade; import org.sakaiproject.tool.assessment.facade.SectionFacade; import org.sakaiproject.tool.assessment.services.ItemService; import org.sakaiproject.tool.assessment.services.QuestionPoolService; import org.sakaiproject.tool.assessment.services.assessment.AssessmentService; import org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean; import org.sakaiproject.tool.assessment.ui.bean.questionpool.QuestionPoolBean; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.entity.impl.ReferenceComponent; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.exception.TypeException; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.FilePickerHelper; import org.sakaiproject.content.cover.ContentHostingService; import org.sakaiproject.tool.cover.SessionManager; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.util.ResourceLoader; //import org.osid.shared.*; /** * Backing bean for Item Authoring, uses ItemBean for UI * $Id$ */ public class ItemAuthorBean implements Serializable { private static Log log = LogFactory.getLog(ItemAuthorBean.class); /** Use serialVersionUID for interoperability. */ private final static long serialVersionUID = 8266438770394956874L; public final static String FROM_QUESTIONPOOL= "questionpool"; public final static String FROM_ASSESSMENT= "assessment"; private String assessTitle; private String sectionIdent; private ArrayList assessmentSectionIdents; private String insertPosition; private String insertToSection; private String insertType; private String assessmentID; private String currentSection; private String itemId; private String itemNo; private String itemType; private String itemTypeString; // used for inserting a question private String showMetadata; private String showOverallFeedback; private String showQuestionLevelFeedback; private String showSelectionLevelFeedback; private String showFeedbackAuthoring; private ArrayList trueFalseAnswerSelectList; private ItemDataIfc item; private ItemBean currentItem; private ItemFacade itemToDelete; private ItemFacade itemToPreview; private List attachmentList; // for questionpool private String qpoolId; private String target; private ArrayList poolListSelectItems; // for item editing private boolean[] choiceCorrectArray; private String maxRecordingTime; private String maxNumberRecordings; private String scaleName; private String[] matches; private String[] matchAnswers; private String[] matchFeedbackList; private String[] answerFeedbackList; // for navigation private String outcome; /** * Creates a new ItemAuthorBean object. */ public ItemAuthorBean() { } public void setItem(ItemDataIfc item) { this.item=item; this.attachmentList = item.getItemAttachmentList(); } public ItemDataIfc getItem() { return item; } public void setCurrentItem(ItemBean item) { this.currentItem=item; } public ItemBean getCurrentItem() { return currentItem; } /** * @return */ public String getAssessTitle() { return assessTitle; } /** * @param string */ public void setAssessTitle(String string) { assessTitle = string; } /** * @return */ public String getSectionIdent() { return sectionIdent; } /** * @param string */ public void setSectionIdent(String string) { sectionIdent = string; } /** * @return */ public ArrayList getAssessmentSectionIdents() { return assessmentSectionIdents; } /** * @param list */ public void setAssessmentSectionIdents(ArrayList list) { assessmentSectionIdents = list; } /** * @return */ public String getInsertPosition() { return insertPosition; } /** * @param string */ public void setInsertPosition(String string) { insertPosition = string; } /** * @return */ public String getInsertToSection() { return insertToSection; } /** * @param string */ public void setInsertToSection(String string) { insertToSection= string; } /** * @return */ public String getInsertType() { return insertType; } /** * @param string */ public void setInsertType(String string) { insertType= string; } /** * @return */ public String getAssessmentID() { return assessmentID; } /** * @param string */ public void setAssessmentID(String string) { assessmentID = string; } /** * @return */ public String getCurrentSection() { return currentSection; } /** * @param string */ public void setCurrentSection(String string) { currentSection = string; } /** * @return */ public String getItemNo() { return itemNo; } /** * @param string */ public void setItemNo(String string) { itemNo = string; } public String getItemId() { return itemId; } public void setItemId(String string) { itemId= string; } /** * @return */ public String getItemType() { return itemType; } /** * @param string */ public void setItemType(String string) { itemType = string; } /** * @return */ public String getItemTypeString() { return itemTypeString; } /** * @param string */ public void setItemTypeString(String string) { itemTypeString = string; } /** * @return */ public String getShowMetadata() { return showMetadata; } /** * @param string */ public void setShowMetadata(String string) { showMetadata = string; } /** * @return */ public String getShowOverallFeedback() { return showOverallFeedback; } /** * @return */ public String getShowQuestionLevelFeedback() { return showQuestionLevelFeedback; } /** * @return */ public String getShowSelectionLevelFeedback() { return showSelectionLevelFeedback; } /** * @param string */ public void setShowOverallFeedback(String string) { showOverallFeedback = string; } /** * @param string */ public void setShowQuestionLevelFeedback(String string) { showQuestionLevelFeedback = string; } /** * @param string */ public void setShowSelectionLevelFeedback(String string) { showSelectionLevelFeedback = string; } /** * @param string */ public void setQpoolId(String string) { qpoolId= string; } /** * @return */ public String getQpoolId() { return qpoolId; } /** * @param string */ public void setItemToDelete(ItemFacade param) { itemToDelete= param; } /** * @return */ public ItemFacade getItemToDelete() { return itemToDelete; } /** * @param string */ public void setItemToPreview(ItemFacade param) { itemToPreview= param; } /** * @return */ public ItemFacade getItemToPreview() { return itemToPreview; } /** * @param string */ public void setTarget(String string) { target= string; } /** * @return */ public String getTarget() { return target; } /** * This is an array of correct/not correct flags * @return the array of correct/not correct flags */ public boolean[] getChoiceCorrectArray() { return choiceCorrectArray; } /** * set array of correct/not correct flags * @param choiceCorrectArray of correct/not correct flags */ public void setChoiceCorrectArray(boolean[] choiceCorrectArray) { this.choiceCorrectArray = choiceCorrectArray; } /** * is the nth choice correct? * @param n * @return */ public boolean isCorrectChoice(int n) { return choiceCorrectArray[n]; } /** * set the nth choice correct? * @param n * @param correctChoice true if it is */ public void setCorrectChoice(int n, boolean correctChoice) { this.choiceCorrectArray[n] = correctChoice; } /** * for audio recording * @return maximum time for recording */ public String getMaxRecordingTime() { return maxRecordingTime; } /** * for audio recording * @param maxRecordingTime maximum time for recording */ public void setMaxRecordingTime(String maxRecordingTime) { this.maxRecordingTime = maxRecordingTime; } /** * for audio recording * @return maximum attempts */ public String getMaxNumberRecordings() { return maxNumberRecordings; } /** * set audio recording maximum attempts * @param maxNumberRecordings */ public void setMaxNumberRecordings(String maxNumberRecordings) { this.maxNumberRecordings = maxNumberRecordings; } /** * for survey * @return the scale */ public String getScaleName() { return scaleName; } /** * set the survey scale * @param scaleName */ public void setScaleName(String scaleName) { this.scaleName = scaleName; } public String getOutcome() { return outcome; } /** * set the survey scale * @param param */ public void setOutcome(String param) { this.outcome= param; } /** * Maching only. * Get an array of match Strings. * @return array of match Strings. */ public String[] getMatches() { return matches; } /** * Maching only. * Set array of match Strings. * @param matches array of match Strings. */ public void setMatches(String[] matches) { this.matches = matches; } /** * Maching only. * Get the nth match String. * @param n * @return the nth match String */ public String getMatch(int n) { return matches[n]; } /** * Maching only. * Set the nth match String. * @param n * @param match */ public void setMatch(int n, String match) { matches[n] = match; } /** * get 1, 2, 3... for each match * @param n * @return */ public int[] getMatchCounter() { int n = matches.length; int count[] = new int[n]; for (int i = 0; i < n; i++) { count[i] = i; } return count; } /** * Derived property. * @return ArrayList of model SelectItems */ public ArrayList getTrueFalseAnswerSelectList() { ArrayList list = new ArrayList(); String trueprop= ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.AuthorMessages","true_msg"); String falseprop= ContextUtil.getLocalizedString("org.sakaiproject.tool.assessment.bundle.AuthorMessages","false_msg"); String[] answerValues = {"true", "false"}; // not to be displayed in the UI String[] answerLabelText= {trueprop, falseprop}; currentItem.setAnswers(answerValues); currentItem.setAnswerLabels(answerLabelText); for (int i = 0; i < answerValues.length; i++) { SelectItem selection = new SelectItem(); selection.setLabel(answerLabelText[i]); selection.setValue(answerValues[i]); list.add(selection); } return list; } /* Derived property. * @return ArrayList of model SelectItems */ // TODO use sectionBean.getsectionNumberList when its ready public ArrayList getSectionSelectList() { ArrayList list = new ArrayList(); ResourceLoader rb = new ResourceLoader("org.sakaiproject.tool.assessment.bundle.AuthorMessages"); AssessmentBean assessbean = (AssessmentBean) ContextUtil.lookupBean("assessmentBean"); ArrayList sectionSet = assessbean.getSections(); Iterator iter = sectionSet.iterator(); int i =0; while (iter.hasNext()){ i = i + 1; SectionContentsBean part = (SectionContentsBean) iter.next(); SelectItem selection = new SelectItem(); // need to filter out all the random draw parts if (part.getSectionAuthorType().equals(SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL)) { // skip random draw parts, cannot add items to this part manually } else { if ("".equals(part.getTitle())) { selection.setLabel(rb.getString("p")+" "+ i ); } else { selection.setLabel(rb.getString("p")+" " + i + " - " + part.getTitle()); } selection.setValue(part.getSectionId()); list.add(selection); } } Collections.reverse(list); // create a new part if there are no non-randomDraw parts available if (list.size() <1) { i = i + 1; SelectItem temppart = new SelectItem(); temppart.setLabel(rb.getString("p")+" "+ i ); temppart.setValue("-1"); // use -1 to indicate this is a temporary part. if the user decides to cancel the operation, this part will not be created list.add(temppart); } return list; } /** * Derived property. * @return ArrayList of model SelectItems */ public ArrayList getPoolSelectList() { poolListSelectItems = new ArrayList(); QuestionPoolService delegate = new QuestionPoolService(); ArrayList qplist = delegate.getBasicInfoOfAllPools(AgentFacade.getAgentString()); Iterator iter = qplist.iterator(); try { while(iter.hasNext()) { QuestionPoolFacade pool = (QuestionPoolFacade) iter.next(); poolListSelectItems.add(new SelectItem((pool.getQuestionPoolId().toString()), pool.getDisplayName() ) ); } } catch (Exception e){ throw new RuntimeException(e); } return poolListSelectItems; } /** * Corresponding answer number list ordered for match * @return answer number */ public String[] getMatchAnswers() { return matchAnswers; } /** * Corresponding answer number list ordered for match * @param matchAnswers answer number list ordered for match */ public void setMatchAnswers(String[] matchAnswers) { this.matchAnswers = matchAnswers; } /** * Corresponding answer number for nth match * @param n * @return */ public String getMatchAnswer(int n) { return matchAnswers[n]; } /** * set answer number for nth match * @param n * @param matchAnswer */ public void setMatchAnswer(int n, String matchAnswer) { matchAnswers[n] = matchAnswer; } /** * feedback for nth match * @param n * @return feedback for nth match */ public String getMatchFeedback(int n) { return matchFeedbackList[n]; } /** * set feedback for nth match * @param n * @param matchFeedback feedback for match */ public void setMatchFeedback(int n, String matchFeedback) { this.matchFeedbackList[n] = matchFeedback; } /** * array of matching feeback * @return array of matching feeback */ public String[] getMatchFeedbackList() { return matchFeedbackList; } /** * set array of matching feeback * @param matchFeedbackList array of matching feeback */ public void setMatchFeedbackList(String[] matchFeedbackList) { this.matchFeedbackList = matchFeedbackList; } /////////////////////////////////////////////////////////////////////////// // ACTION METHODS /////////////////////////////////////////////////////////////////////////// public String[] getAnswerFeedbackList() { return answerFeedbackList; } public void setAnswerFeedbackList(String[] answerFeedbackList) { this.answerFeedbackList = answerFeedbackList; } public String doit() { // navigation for ItemModifyListener return outcome; } /** * delete specified Item */ public String deleteItem() { ItemService delegate = new ItemService(); Long deleteId= this.getItemToDelete().getItemId(); ItemFacade itemf = delegate.getItem(deleteId, AgentFacade.getAgentString()); // save the currSection before itemf.setSection(null), used to reorder question sequences SectionFacade currSection = (SectionFacade) itemf.getSection(); Integer currSeq = itemf.getSequence(); QuestionPoolService qpdelegate = new QuestionPoolService(); if ((qpdelegate.getPoolIdsByItem(deleteId.toString()) == null) || (qpdelegate.getPoolIdsByItem(deleteId.toString()).isEmpty() )){ // if no reference to this item at all, ie, this item is created in // assessment but not assigned to any pool delegate.deleteItem(deleteId, AgentFacade.getAgentString()); } else { if (currSection == null) { // if this item is created from question pool QuestionPoolBean qpoolbean= (QuestionPoolBean) ContextUtil.lookupBean("questionpool"); ItemFacade itemfacade= delegate.getItem(deleteId, AgentFacade.getAgentString()); ArrayList items = new ArrayList(); items.add(itemfacade); qpoolbean.setItemsToDelete(items); qpoolbean.removeQuestionsFromPool(); return "editPool"; } else { // // if some pools still reference to this item, ie, this item is // created in assessment but also assigned a a pool // then just set section = null itemf.setSection(null); delegate.saveItem(itemf); } } AssessmentService assessdelegate = new AssessmentService(); // reorder item numbers SectionFacade sectfacade = assessdelegate.getSection(currSection.getSectionId().toString()); Set itemset = sectfacade.getItemFacadeSet(); // should be size-1 now. Iterator iter = itemset.iterator(); while (iter.hasNext()) { ItemFacade itemfacade = (ItemFacade) iter.next(); Integer itemfacadeseq = itemfacade.getSequence(); if (itemfacadeseq.compareTo(currSeq) > 0 ){ itemfacade.setSequence(new Integer(itemfacadeseq.intValue()-1) ); delegate.saveItem(itemfacade); } } // go to editAssessment.jsp, need to first reset assessmentBean AssessmentBean assessmentBean = (AssessmentBean) ContextUtil.lookupBean( "assessmentBean"); AssessmentFacade assessment = assessdelegate.getAssessment(assessmentBean.getAssessmentId()); assessmentBean.setAssessment(assessment); assessdelegate.updateAssessmentLastModifiedInfo(assessment); return "editAssessment"; } public String confirmDeleteItem(){ ItemService delegate = new ItemService(); String itemId= ContextUtil.lookupParam("itemid"); ItemFacade itemf = delegate.getItem(new Long(itemId), AgentFacade.getAgentString()); setItemToDelete(itemf); return "removeQuestion"; } public void selectItemType(ValueChangeEvent event) { //FacesContext context = FacesContext.getCurrentInstance(); String type = (String) event.getNewValue(); setItemType(type); } /** * @return */ public String getShowFeedbackAuthoring() { return showFeedbackAuthoring; } /** * @param string */ public void setShowFeedbackAuthoring(String string) { showFeedbackAuthoring= string; } public List getAttachmentList() { return attachmentList; } /** * @param list */ public void setAttachmentList(List attachmentList) { this.attachmentList = attachmentList; } public boolean getHasAttachment(){ if (attachmentList != null && attachmentList.size() >0) return true; else return false; } public String addAttachmentsRedirect() { // 1. load resources into session for resources mgmt page // then redirect to resources mgmt page try { List filePickerList = prepareReferenceList(attachmentList); ToolSession currentToolSession = SessionManager.getCurrentToolSession(); currentToolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, filePickerList); ExternalContext context = FacesContext.getCurrentInstance().getExternalContext(); context.redirect("sakai.filepicker.helper/tool"); } catch(Exception e){ log.error("fail to redirect to attachment page: " + e.getMessage()); } return getOutcome(); } /* called by SamigoJsfTool.java on exit from file picker */ public void setItemAttachment(){ ItemService service = new ItemService(); ItemDataIfc itemData = null; // itemId == null => new questiion if (this.itemId!=null){ try{ itemData = service.getItem(this.itemId); } catch(Exception e){ log.warn(e.getMessage()); } } // list returns contains modified list of attachments, i.e. new // and old attachments. This list will be // persisted to DB if user hit Save on the Item Modifying page. List list = prepareItemAttachment(itemData); setAttachmentList(list); } private List prepareReferenceList(List attachmentList){ List list = new ArrayList(); if (attachmentList == null){ return list; } for (int i=0; i<attachmentList.size(); i++){ ContentResource cr = null; AttachmentIfc attach = (AttachmentIfc) attachmentList.get(i); try{ log.debug("*** resourceId="+attach.getResourceId()); cr = ContentHostingService.getResource(attach.getResourceId()); } catch (PermissionException e) { log.warn("ContentHostingService.getResource() throws PermissionException="+e.getMessage()); } catch (IdUnusedException e) { log.warn("ContentHostingService.getResource() throws IdUnusedException="+e.getMessage()); // <-- bad sign, some left over association of question and resource, // use case: user remove resource in file picker, then exit modification without // proper cancellation by clicking at the left nav instead of "cancel". // Also in this use case, any added resource would be left orphan. AssessmentService assessmentService = new AssessmentService(); assessmentService.removeItemAttachment(attach.getAttachmentId().toString()); } catch (TypeException e) { log.warn("ContentHostingService.getResource() throws TypeException="+e.getMessage()); } if (cr!=null){ ReferenceComponent ref = new ReferenceComponent(cr.getReference()); log.debug("*** ref="+ref); if (ref !=null ) list.add(ref); } } return list; } private List prepareItemAttachment(ItemDataIfc item){ ToolSession session = SessionManager.getCurrentToolSession(); if (session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) { Set attachmentSet = new HashSet(); if (item != null){ attachmentSet = item.getItemAttachmentSet(); } HashMap map = getResourceIdHash(attachmentSet); ArrayList newAttachmentList = new ArrayList(); AssessmentService assessmentService = new AssessmentService(); String protocol = ContextUtil.getProtocol(); List refs = (List)session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); if (refs!=null && refs.size() > 0){ Reference ref; for(int i=0; i<refs.size(); i++) { ref = (Reference) refs.get(i); String resourceId = ref.getId(); if (map.get(resourceId) == null){ // new attachment, add log.debug("**** ref.Id="+ref.getId()); log.debug("**** ref.name="+ref.getProperties().getProperty( ref.getProperties().getNamePropDisplayName())); ItemAttachmentIfc newAttach = assessmentService.createItemAttachment( item, ref.getId(), ref.getProperties().getProperty( ref.getProperties().getNamePropDisplayName()), protocol); newAttachmentList.add(newAttach); } else{ // attachment already exist, let's add it to new list and // check it off from map newAttachmentList.add((ItemAttachmentIfc)map.get(resourceId)); map.remove(resourceId); } } } session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL); return newAttachmentList; } else return item.getItemAttachmentList(); } private HashMap getResourceIdHash(Set attachmentSet){ HashMap map = new HashMap(); if (attachmentSet !=null ){ Iterator iter = attachmentSet.iterator(); while (iter.hasNext()){ ItemAttachmentIfc attach = (ItemAttachmentIfc) iter.next(); map.put(attach.getResourceId(), attach); } } return map; } private HashMap resourceHash = new HashMap(); public HashMap getResourceHash() { return resourceHash; } public void setResourceHash(HashMap resourceHash) { this.resourceHash = resourceHash; } }
SAK-11253 git-svn-id: 574bb14f304dbe16c01253ed6697ea749724087f@34308 66ffb92e-73f9-0310-93c1-f5514f145a0a
samigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/bean/author/ItemAuthorBean.java
SAK-11253
<ide><path>amigo/samigo-app/src/java/org/sakaiproject/tool/assessment/ui/bean/author/ItemAuthorBean.java <ide> import java.io.Serializable; <ide> import java.util.ArrayList; <ide> import java.util.Collections; <add>import java.util.Comparator; <ide> import java.util.HashMap; <ide> import java.util.HashSet; <ide> import java.util.Iterator; <ide> catch (Exception e){ <ide> throw new RuntimeException(e); <ide> } <del> <add> Collections.sort(poolListSelectItems, new itemComparator()); <ide> return poolListSelectItems; <ide> } <ide> <add> class itemComparator implements Comparator { <add> public int compare(Object o1, Object o2) { <add> SelectItem i1 = (SelectItem) o1; <add> SelectItem i2 = (SelectItem) o2; <add> return i1.getLabel().compareToIgnoreCase(i2.getLabel()); <add> } <add> } <add> <ide> /** <ide> * Corresponding answer number list ordered for match <ide> * @return answer number
JavaScript
mit
af1573725f4c4b5ac816b009666d3baddf187419
0
ngzax/urbit,jfranklin9000/urbit,jfranklin9000/urbit,urbit/urbit,ngzax/urbit,jfranklin9000/urbit,jfranklin9000/urbit,urbit/urbit,urbit/urbit,ngzax/urbit,urbit/urbit,ngzax/urbit,urbit/urbit,urbit/urbit,jfranklin9000/urbit,ngzax/urbit,jfranklin9000/urbit,ngzax/urbit,ngzax/urbit,urbit/urbit,jfranklin9000/urbit
import React, { Component } from 'react' import classnames from 'classnames'; import { Route, Link } from 'react-router-dom'; import urbitOb from 'urbit-ob'; //TODO textarea + join button to make an api call export class JoinScreen extends Component { constructor(props) { super(props); this.state = { book: '/', error: false }; this.bookChange = this.bookChange.bind(this); } notebooksInclude(text, notebookObj) { let verdict = false; let keyPair = []; // validate that it's a worthwhile thing to check // certainly a unit would be nice here if (text.indexOf('/') === -1) { return verdict; } else { keyPair = text.split('/'); }; // check both levels of object if (keyPair[0] in notebookObj) { if (keyPair[1] in notebookObj[keyPair[0]]) { verdict = true; } } return verdict; } onClickJoin() { const { props, state } = this; let text = state.book; // an error condition to prevent double joins? if (this.notebooksInclude(state.book,props.notebooks) || text.length === 0) { props.history.push('/~publish'); } let book = text.split('/'); let ship = book[0]; book.splice(0, 1); book = '/' + book.join('/'); if (book.length < 2 || !urbitOb.isValidPatp(ship)) { this.setState({ error: true, }); return; } let actionData = { subscribe: { who: ship.replace('~',''), book: /\/?(.*)/.exec(book)[1] } } console.log('actionData', actionData); // TODO: askHistory setting window.api.action("publish","publish-action", actionData); } bookChange(event) { this.setState({ book: event.target.value }); } render() { const { props } = this; let joinClasses = "db f9 green2 ba pa2 b--green2 bg-gray0-d pointer"; if ((!this.state.book) || (this.state.book === "/")) { joinClasses = 'db f9 gray2 ba pa2 b--gray3 bg-gray0-d pointer'; } let errElem = (<span />); if (this.state.error) { errElem = ( <span className="f9 inter red2 db"> Notebook must have a valid name. </span> ); } return ( <div className={`h-100 w-100 pa3 pt2 overflow-x-hidden flex flex-column bg-gray0-d white-d`}> <div className="w-100 dn-m dn-l dn-xl inter pt1 pb6 f8"> <Link to="/~chat/">{"⟵ All Notebooks"}</Link> </div> <h2 className="mb3 f8">Subscribe to an Existing Notebook</h2> <div className="w-100"> <p className="f8 lh-copy mt3 db">Enter a <span className="mono">~ship/notebook-name</span></p> <p className="f9 gray2 mb4">Notebook names use lowercase, hyphens, and slashes.</p> <textarea ref={ e => { this.textarea = e; } } className="f7 mono ba b--gray3 b--gray2-d bg-gray0-d white-d pa3 mb2 db" placeholder="~zod/dream-journal" spellCheck="false" rows={1} onKeyPress={e => { if (e.key === "Enter") { e.preventDefault(); this.onClickJoin(); } }} style={{ resize: 'none', }} onChange={this.bookChange} /> {errElem} <br /> <button onClick={this.onClickJoin.bind(this)} className={joinClasses} >Join Chat</button> </div> </div> ); } } export default JoinScreen
pkg/interface/publish/src/js/components/lib/join.js
import React, { Component } from 'react' import classnames from 'classnames'; import { Route, Link } from 'react-router-dom'; import urbitOb from 'urbit-ob'; //TODO textarea + join button to make an api call export class JoinScreen extends Component { constructor(props) { super(props); this.state = { book: '/', error: false }; this.bookChange = this.bookChange.bind(this); } notebooksInclude(text, notebookObj) { let verdict = false; let keyPair = []; // validate that it's a worthwhile thing to check // certainly a unit would be nice here if (text.indexOf('/') === -1) { return verdict; } else { keyPair = text.split('/'); }; // check both levels of object if (keyPair[0] in notebookObj) { if (keyPair[1] in notebookObj[keyPair[0]]) { verdict = true; } } return verdict; } onClickJoin() { const { props, state } = this; let text = state.book; // an error condition to prevent double joins? if (this.notebooksInclude(state.book,props.notebooks) || text.length === 0) { props.history.push('/~publish'); } let book = text.split('/'); let ship = book[0]; book.splice(0, 1); book = '/' + book.join('/'); if (book.length < 2 || !urbitOb.isValidPatp(ship)) { this.setState({ error: true, }); return; } let actionData = { subscribe: { who: ship.replace('~',''), book: /\/?(.*)/.exec(book)[1] } } console.log('actionData', actionData); // TODO: askHistory setting window.api.action("publish","publish-action", actionData); } bookChange(event) { this.setState({ book: event.target.value }); } render() { const { props } = this; let joinClasses = "db f9 green2 ba pa2 b--green2 bg-gray0-d pointer"; if ((!this.state.book) || (this.state.book === "/")) { joinClasses = 'db f9 gray2 ba pa2 b--gray3 bg-gray0-d pointer'; } let errElem = (<span />); if (this.state.error) { errElem = ( <span className="f9 inter red2 db"> Notebook must have a valid name. </span> ); } return ( <div className={`h-100 w-100 pa3 pt2 overflow-x-hidden flex flex-column bg-gray0-d white-d`}> <div className="w-100 dn-m dn-l dn-xl inter pt1 pb6 f8"> <Link to="/~chat/">{"⟵ All Notebooks"}</Link> </div> <h2 className="mb3 f8">Subscribe to an Existing Notebook</h2> <div className="w-100"> <p className="f8 lh-copy mt3 db">Enter a <span className="mono">~ship/notebook-name</span></p> <p className="f9 gray2 mb4">Notebook names use lowercase, hyphens, and slashes.</p> <textarea ref={ e => { this.textarea = e; } } className="f7 mono ba b--gray3 b--gray2-d bg-gray0-d white-d pa3 mb2 db" placeholder="~zod/dream-journal" spellCheck="false" rows={1} onKeyPress={e => { if (e.key === "Enter") { this.onClickJoin(); } }} style={{ resize: 'none', }} onChange={this.bookChange} /> {errElem} <br /> <button onClick={this.onClickJoin.bind(this)} className={joinClasses} >Join Chat</button> </div> </div> ); } } export default JoinScreen
don't allow spurious newline in input
pkg/interface/publish/src/js/components/lib/join.js
don't allow spurious newline in input
<ide><path>kg/interface/publish/src/js/components/lib/join.js <ide> rows={1} <ide> onKeyPress={e => { <ide> if (e.key === "Enter") { <add> e.preventDefault(); <ide> this.onClickJoin(); <ide> } <ide> }}
JavaScript
mit
b92a22a6d6d4835208798e75ce1d9818cfe0da79
0
OpenCollective/frontend
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { graphql, compose } from 'react-apollo'; import gql from 'graphql-tag'; import { get, omit, pick } from 'lodash'; import { Box, Flex } from '@rebass/grid'; import styled from 'styled-components'; import { Router } from '../server/pages'; import { H2, P, Span } from '../components/Text'; import Logo from '../components/Logo'; import ErrorPage from '../components/ErrorPage'; import Page from '../components/Page'; import Link from '../components/Link'; import SignIn from '../components/SignIn'; import CreateProfile from '../components/CreateProfile'; import ContributeAs from '../components/ContributeAs'; import StyledInputField from '../components/StyledInputField'; import { addCreateCollectiveMutation, addCreateOrderMutation, createUserQuery } from '../graphql/mutations'; import * as api from '../lib/api'; import withIntl from '../lib/withIntl'; import { withUser } from '../components/UserProvider'; import ContributePayment from '../components/ContributePayment'; import ContributeDetails from '../components/ContributeDetails'; import Loading from '../components/Loading'; import StyledButton from '../components/StyledButton'; import StepsProgress from '../components/StepsProgress'; import { formatCurrency } from '../lib/utils'; const STEPS = ['contributeAs', 'details', 'payment']; const StepLabel = styled(Span)` text-transform: uppercase; `; StepLabel.defaultProps = { color: 'black.400', fontSize: 'Tiny', mt: 1 }; const PrevNextButton = styled(StyledButton)``; PrevNextButton.defaultProps = { buttonSize: 'large', fontWeight: 'bold', mx: 2 }; class CreateOrderPage extends React.Component { static getInitialProps({ query: { collectiveSlug, eventSlug, TierId, amount, quantity, totalAmount, interval, description, verb, step, redeem, redirect, }, }) { return { slug: eventSlug || collectiveSlug, TierId, quantity, totalAmount: totalAmount || amount * 100, interval, description, verb, step, redeem, redirect, }; } static propTypes = { slug: PropTypes.string, // for addData TierId: PropTypes.string, quantity: PropTypes.number, totalAmount: PropTypes.number, interval: PropTypes.string, description: PropTypes.string, verb: PropTypes.string, step: PropTypes.string, redirect: PropTypes.string, redeem: PropTypes.bool, createOrder: PropTypes.func.isRequired, // from addCreateOrderMutation data: PropTypes.object.isRequired, // from withData intl: PropTypes.object.isRequired, // from withIntl }; constructor(props) { super(props); const tier = this.getTier(); const interval = (props.interval || '').toLowerCase().replace(/ly$/, ''); const amountOptions = (tier && tier.presets) || [500, 1000, 2000, 5000]; const defaultAmount = amountOptions[Math.floor(amountOptions.length / 2)]; const initialDetails = { quantity: parseInt(props.quantity, 10) || 1, interval: ['month', 'year'].includes(interval) ? interval : null, totalAmount: parseInt(props.totalAmount, 10) || defaultAmount, }; this.state = { loading: false, submitting: false, result: {}, unknownEmail: false, signIn: true, stepProfile: this.getLoggedInUserDefaultContibuteProfile(), stepDetails: initialDetails, stepPayment: null, }; } componentDidUpdate(prevProps) { if (!prevProps.LoggedInUser && this.props.LoggedInUser && !this.state.stepProfile) { this.setState({ stepProfile: this.getLoggedInUserDefaultContibuteProfile() }); } } signIn = email => { if (this.state.submitting) { return false; } this.setState({ submitting: true }); return api .checkUserExistence(email) .then(exists => { if (exists) { return api.signin({ email }, Router.asPath).then(() => { Router.pushRoute('signinLinkSent', { email }); }); } else { this.setState({ unknownEmail: true, submitting: false }); } }) .catch(e => { this.setState({ error: e.message, submitting: false }); }); }; createProfile = data => { if (this.state.submitting) { return false; } const redirect = window.location.pathname; const user = pick(data, ['email', 'firstName', 'lastName']); const organizationData = pick(data, ['orgName', 'githubHandle', 'twitterHandle', 'website']); const organization = Object.keys(organizationData).length > 0 ? organizationData : null; if (organization) { organization.name = organization.orgName; delete organization.orgName; } this.setState({ submitting: true }); this.props .createUser({ user, organization, redirect }) .then(() => { Router.pushRoute('signinLinkSent', { email: user.email }); }) .catch(error => { this.setState({ result: { error: error.message }, submitting: false }); }); }; getLoggedInUserDefaultContibuteProfile() { if (get(this.state, 'stepProfile')) { return this.state.stepProfile; } const { LoggedInUser } = this.props; return !LoggedInUser ? null : { email: LoggedInUser.email, image: LoggedInUser.image, ...LoggedInUser.collective }; } getLoggedInUserDefaultPaymentMethodId() { const pm = get(this.props.LoggedInUser, 'collective.paymentMethods', [])[0]; return pm && pm.id; } /** Returns an array like [personnalProfile, otherProfiles] */ getProfiles() { const { LoggedInUser } = this.props; return !LoggedInUser ? [{}, {}] : [ { email: LoggedInUser.email, image: LoggedInUser.image, ...LoggedInUser.collective }, LoggedInUser.memberOf .filter(m => m.role === 'ADMIN' && m.collective.id !== this.props.data.Collective.id) .map(({ collective }) => collective), ]; } /** Return the currently selected tier, or a falsy value if none selected */ getTier() { const { data, TierId } = this.props; return TierId && get(data, 'Collective.tiers', []).find(t => t.id == TierId); } getContributorTypeName() { const tier = this.getTier(); if (tier) { return tier.name; } else if (this.props.verb === 'pay') { return <FormattedMessage id="member.title" defaultMessage="member" />; } else { return <FormattedMessage id="backer.title" defaultMessage="backer" />; } } renderPrevStepButton(step) { const prevStepIdx = STEPS.indexOf(step) - 1; if (prevStepIdx < 0) { return null; } return ( <PrevNextButton onClick={() => this.changeStep(STEPS[prevStepIdx])} buttonStyle="standard" disabled={this.state.submitting} > &larr; <FormattedMessage id="contribute.prevStep" defaultMessage="Previous step" /> </PrevNextButton> ); } /** Return the index of the last step user can switch to */ getMaxStepIdx() { if (!this.state.stepProfile) return 0; if (!this.state.stepDetails || !this.state.stepDetails.totalAmount) return 1; if (!this.state.stepPayment) return 2; return STEPS.length; } renderNextStepButton(step) { const stepIdx = STEPS.indexOf(step); if (stepIdx === -1) { return null; } const isLast = stepIdx + 1 >= STEPS.length; return ( <PrevNextButton buttonStyle="primary" onClick={() => (isLast ? this.submitOrder() : this.changeStep(STEPS[stepIdx + 1]))} disabled={this.state.submitting || stepIdx + 1 > this.getMaxStepIdx()} > {isLast ? ( <FormattedMessage id="contribute.submit" defaultMessage="Submit" /> ) : ( <FormattedMessage id="contribute.nextStep" defaultMessage="Next step" /> )}{' '} &rarr; </PrevNextButton> ); } renderStep(step) { const { data, LoggedInUser, TierId } = this.props; const [personal, profiles] = this.getProfiles(); const tier = this.getTier(); const amountOptions = (tier && tier.presets) || [500, 1000, 2000, 5000]; if (step === 'contributeAs') { return ( <StyledInputField htmlFor="contributeAs" label="Contribute as:"> {fieldProps => ( <ContributeAs {...fieldProps} onChange={profile => this.setState({ stepProfile: profile, stepPayment: null })} profiles={profiles} personal={personal} defaultSelectedProfile={this.getLoggedInUserDefaultContibuteProfile()} /> )} </StyledInputField> ); } else if (step === 'details') { return ( <ContributeDetails amountOptions={amountOptions} currency={(tier && tier.currency) || data.Collective.currency} onChange={data => this.setState({ stepDetails: data })} showFrequency={Boolean(TierId) || undefined} interval={get(this.state, 'stepDetails.interval')} totalAmount={get(this.state, 'stepDetails.totalAmount')} /> ); } else if (step === 'payment') { return ( <ContributePayment onChange={stepPayment => this.setState({ stepPayment })} paymentMethods={get(LoggedInUser, 'collective.paymentMethods', [])} collective={this.state.stepProfile} /> ); } else if (step === 'submit') { return ( <Flex justifyContent="center" alignItems="center" flexDirection="column"> <Loading /> <P color="red.700">__DEBUG__</P> <P color="red.700">Profile:</P> <textarea>{JSON.stringify(this.state.stepProfile)}</textarea> <P color="red.700">Details:</P> <textarea>{JSON.stringify(this.state.stepDetails)}</textarea> <P color="red.700">PaymentMethod:</P> <textarea>{JSON.stringify(this.state.stepPayment)}</textarea> </Flex> ); } return null; } changeStep = async step => { if (this.props.loadingLoggedInUser || this.state.loading || this.state.submitting) { return false; } const { createCollective, verb, data, refetchLoggedInUser } = this.props; const { stepProfile, step: currentStep } = this.state; const params = { collectiveSlug: data.Collective.slug, step: step === 'contributeAs' ? undefined : step, }; // check if we're creating a new organization if (!currentStep && stepProfile.orgName) { const { data: result } = await createCollective({ name: stepProfile.orgName, ...omit(stepProfile, ['orgName']), }); if (result && result.createCollective) { await refetchLoggedInUser(); this.setState({ stepProfile: result.createCollective }); } } if (verb) { Router.pushRoute('donate', { ...params, verb }); } else { Router.pushRoute('orderCollectiveTier', { ...params, TierId: this.props.TierId }); } }; renderStepsProgress(currentStep) { const { stepProfile, stepDetails, stepPayment } = this.state; const loading = this.props.loadingLoggedInUser || this.state.loading || this.state.submitting; return ( <StepsProgress steps={STEPS} focus={currentStep} allCompleted={currentStep === 'submit'} onStepSelect={this.changeStep} loadingStep={loading ? currentStep : undefined} disabledSteps={loading ? STEPS : STEPS.slice(this.getMaxStepIdx() + 1, STEPS.length)} > {({ step }) => { let label = null; let details = null; if (step === 'contributeAs') { label = <FormattedMessage id="contribute.step.contributeAs" defaultMessage="Contribute as" />; details = get(stepProfile, 'name', null); } else if (step === 'details') { label = <FormattedMessage id="contribute.step.details" defaultMessage="Details" />; if (stepDetails && stepDetails.totalAmount) { const amount = formatCurrency(stepDetails.totalAmount, get(this.props, 'data.Collective.currency')); details = !stepDetails.interval ? ( amount ) : ( <Span> {amount}{' '} <FormattedMessage id="tier.interval" defaultMessage="per {interval, select, month {month} year {year} other {}}" values={{ interval: stepDetails.interval }} /> </Span> ); } } else if (step === 'payment') { label = <FormattedMessage id="contribute.step.payment" defaultMessage="Payment" />; details = get(stepPayment, 'title', null); } return ( <Flex flexDirection="column" alignItems="center"> <StepLabel>{label}</StepLabel> <Span fontSize="Caption" textAlign="center"> {details} </Span> </Flex> ); }} </StepsProgress> ); } renderContent() { const { LoggedInUser } = this.props; const { loading, submitting, unknownEmail } = this.state; if (!LoggedInUser) { return this.state.signIn ? ( <Flex justifyContent="center"> <SignIn onSubmit={this.signIn} onSecondaryAction={() => this.setState({ signIn: false })} loading={loading || submitting} unknownEmail={unknownEmail} /> </Flex> ) : ( <Flex justifyContent="center"> <CreateProfile onPersonalSubmit={this.createProfile} onOrgSubmit={this.createProfile} onSecondaryAction={() => this.setState({ signIn: true })} submitting={submitting} /> </Flex> ); } const step = this.props.step || 'contributeAs'; return ( <Flex flexDirection="column" alignItems="center" mx={3}> <Box>{this.renderStep(step)}</Box> <Flex mt={5}> {this.renderPrevStepButton(step)} {this.renderNextStepButton(step)} </Flex> </Flex> ); } render() { const { data, loadingLoggedInUser } = this.props; if (!data.Collective) { return <ErrorPage data={data} />; } const collective = data.Collective; const logo = collective.image || get(collective.parentCollective, 'image'); const tierName = this.getContributorTypeName(); return ( <Page title={`Contribute - ${collective.name}`} description={collective.description} twitterHandle={collective.twitterHandle} image={collective.image || collective.backgroundImage} > <Flex alignItems="center" flexDirection="column" mx="auto" width={300} pt={4} mb={4}> <Link route="collective" params={{ slug: collective.slug }} className="goBack"> <Logo src={logo} className="logo" type={collective.type} website={collective.website} height="10rem" key={logo} /> </Link> <Link route="collective" params={{ slug: collective.slug }} className="goBack"> <H2 as="h1" color="black.900"> {collective.name} </H2> </Link> <P fontSize="LeadParagraph" fontWeight="LeadParagraph" color="black.600" mt={3}> <FormattedMessage id="contribute.contributorType" defaultMessage="Become a {name}" values={{ name: tierName }} /> </P> </Flex> <Flex id="content" flexDirection="column" alignItems="center" mb={6}> <Box mb={3} width={0.8} css={{ maxWidth: 365, minHeight: 95 }}> {this.renderStepsProgress(this.props.step || 'contributeAs')} </Box> {loadingLoggedInUser || data.loading ? <Loading /> : this.renderContent()} </Flex> {/* TODO Errors below should be displayed somewhere else */} <div className="row result"> <div className="col-sm-2" /> <div className="col-sm-10"> <div className="success">{this.state.result.success}</div> {this.state.result.error && <div className="error">{this.state.result.error}</div>} </div> </div> </Page> ); } } const addData = graphql(gql` query Collective($slug: String) { Collective(slug: $slug) { id slug name description twitterHandle type website image backgroundImage currency parentCollective { image } tiers { id type name slug description amount currency interval presets } } } `); const addCreateUserMutation = graphql(createUserQuery, { props: ({ mutate }) => ({ createUser: variables => mutate({ variables }), }), }); const addGraphQL = compose( addData, addCreateCollectiveMutation, addCreateOrderMutation, addCreateUserMutation, ); export default withIntl(addGraphQL(withUser(CreateOrderPage)));
src/pages/createOrderNewFlow.js
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import { graphql, compose } from 'react-apollo'; import gql from 'graphql-tag'; import { get, omit, pick } from 'lodash'; import { Box, Flex } from '@rebass/grid'; import styled from 'styled-components'; import { Router } from '../server/pages'; import { H2, P, Span } from '../components/Text'; import Logo from '../components/Logo'; import ErrorPage from '../components/ErrorPage'; import Page from '../components/Page'; import Link from '../components/Link'; import SignIn from '../components/SignIn'; import CreateProfile from '../components/CreateProfile'; import ContributeAs from '../components/ContributeAs'; import StyledInputField from '../components/StyledInputField'; import { addCreateCollectiveMutation, addCreateOrderMutation, createUserQuery } from '../graphql/mutations'; import * as api from '../lib/api'; import withIntl from '../lib/withIntl'; import { withUser } from '../components/UserProvider'; import ContributePayment from '../components/ContributePayment'; import ContributeDetails from '../components/ContributeDetails'; import Loading from '../components/Loading'; import StyledButton from '../components/StyledButton'; import StepsProgress from '../components/StepsProgress'; import { formatCurrency } from '../lib/utils'; const STEPS = ['contributeAs', 'details', 'payment']; const StepLabel = styled(Span)` text-transform: uppercase; `; StepLabel.defaultProps = { color: 'black.400', fontSize: 'Tiny', mt: 1 }; const PrevNextButton = styled(StyledButton)``; PrevNextButton.defaultProps = { buttonSize: 'large', fontWeight: 'bold', mx: 2 }; class CreateOrderPage extends React.Component { static getInitialProps({ query: { collectiveSlug, eventSlug, TierId, amount, quantity, totalAmount, interval, description, verb, step, redeem, redirect, }, }) { return { slug: eventSlug || collectiveSlug, TierId, quantity, totalAmount: totalAmount || amount * 100, interval, description, verb, step, redeem, redirect, }; } static propTypes = { slug: PropTypes.string, // for addData TierId: PropTypes.string, quantity: PropTypes.number, totalAmount: PropTypes.number, interval: PropTypes.string, description: PropTypes.string, verb: PropTypes.string, step: PropTypes.string, redirect: PropTypes.string, redeem: PropTypes.bool, createOrder: PropTypes.func.isRequired, // from addCreateOrderMutation data: PropTypes.object.isRequired, // from withData intl: PropTypes.object.isRequired, // from withIntl }; constructor(props) { super(props); const interval = (props.interval || '').toLowerCase().replace(/ly$/, ''); const initialDetails = { quantity: parseInt(props.quantity, 10) || 1, interval: ['month', 'year'].includes(interval) ? interval : null, totalAmount: parseInt(props.totalAmount, 10) || null, }; this.state = { loading: false, submitting: false, result: {}, unknownEmail: false, signIn: true, stepProfile: this.getLoggedInUserDefaultContibuteProfile(), stepDetails: initialDetails, stepPayment: null, }; } componentDidUpdate(prevProps) { if (!prevProps.LoggedInUser && this.props.LoggedInUser && !this.state.stepProfile) { this.setState({ stepProfile: this.getLoggedInUserDefaultContibuteProfile() }); } } signIn = email => { if (this.state.submitting) { return false; } this.setState({ submitting: true }); return api .checkUserExistence(email) .then(exists => { if (exists) { return api.signin({ email }, Router.asPath).then(() => { Router.pushRoute('signinLinkSent', { email }); }); } else { this.setState({ unknownEmail: true, submitting: false }); } }) .catch(e => { this.setState({ error: e.message, submitting: false }); }); }; createProfile = data => { if (this.state.submitting) { return false; } const redirect = window.location.pathname; const user = pick(data, ['email', 'firstName', 'lastName']); const organizationData = pick(data, ['orgName', 'githubHandle', 'twitterHandle', 'website']); const organization = Object.keys(organizationData).length > 0 ? organizationData : null; if (organization) { organization.name = organization.orgName; delete organization.orgName; } this.setState({ submitting: true }); this.props .createUser({ user, organization, redirect }) .then(() => { Router.pushRoute('signinLinkSent', { email: user.email }); }) .catch(error => { this.setState({ result: { error: error.message }, submitting: false }); }); }; getLoggedInUserDefaultContibuteProfile() { if (get(this.state, 'stepProfile')) { return this.state.stepProfile; } const { LoggedInUser } = this.props; return !LoggedInUser ? null : { email: LoggedInUser.email, image: LoggedInUser.image, ...LoggedInUser.collective }; } getLoggedInUserDefaultPaymentMethodId() { const pm = get(this.props.LoggedInUser, 'collective.paymentMethods', [])[0]; return pm && pm.id; } /** Returns an array like [personnalProfile, otherProfiles] */ getProfiles() { const { LoggedInUser } = this.props; return !LoggedInUser ? [{}, {}] : [ { email: LoggedInUser.email, image: LoggedInUser.image, ...LoggedInUser.collective }, LoggedInUser.memberOf .filter(m => m.role === 'ADMIN' && m.collective.id !== this.props.data.Collective.id) .map(({ collective }) => collective), ]; } /** Return the currently selected tier, or a falsy value if none selected */ getTier() { const { data, TierId } = this.props; return TierId && get(data, 'Collective.tiers', []).find(t => t.id == TierId); } getContributorTypeName() { const tier = this.getTier(); if (tier) { return tier.name; } else if (this.props.verb === 'pay') { return <FormattedMessage id="member.title" defaultMessage="member" />; } else { return <FormattedMessage id="backer.title" defaultMessage="backer" />; } } renderPrevStepButton(step) { const prevStepIdx = STEPS.indexOf(step) - 1; if (prevStepIdx < 0) { return null; } return ( <PrevNextButton onClick={() => this.changeStep(STEPS[prevStepIdx])} buttonStyle="standard" disabled={this.state.submitting} > &larr; <FormattedMessage id="contribute.prevStep" defaultMessage="Previous step" /> </PrevNextButton> ); } /** Return the index of the last step user can switch to */ getMaxStepIdx() { if (!this.state.stepProfile) return 0; if (!this.state.stepDetails || !this.state.stepDetails.totalAmount) return 1; if (!this.state.stepPayment) return 2; return STEPS.length; } renderNextStepButton(step) { const stepIdx = STEPS.indexOf(step); if (stepIdx === -1) { return null; } const isLast = stepIdx + 1 >= STEPS.length; return ( <PrevNextButton buttonStyle="primary" onClick={() => (isLast ? this.submitOrder() : this.changeStep(STEPS[stepIdx + 1]))} disabled={this.state.submitting || stepIdx + 1 > this.getMaxStepIdx()} > {isLast ? ( <FormattedMessage id="contribute.submit" defaultMessage="Submit" /> ) : ( <FormattedMessage id="contribute.nextStep" defaultMessage="Next step" /> )}{' '} &rarr; </PrevNextButton> ); } renderStep(step) { const { data, LoggedInUser, TierId } = this.props; const [personal, profiles] = this.getProfiles(); const tier = this.getTier(); if (step === 'contributeAs') { return ( <StyledInputField htmlFor="contributeAs" label="Contribute as:"> {fieldProps => ( <ContributeAs {...fieldProps} onChange={profile => this.setState({ stepProfile: profile, stepPayment: null })} profiles={profiles} personal={personal} defaultSelectedProfile={this.getLoggedInUserDefaultContibuteProfile()} /> )} </StyledInputField> ); } else if (step === 'details') { return ( <ContributeDetails amountOptions={(tier && tier.presets) || [500, 1000, 2000, 5000]} currency={(tier && tier.currency) || data.Collective.currency} onChange={data => this.setState({ stepDetails: data })} showFrequency={Boolean(TierId)} interval={get(this.state, 'stepDetails.interval')} totalAmount={get(this.state, 'stepDetails.totalAmount')} /> ); } else if (step === 'payment') { return ( <ContributePayment onChange={stepPayment => this.setState({ stepPayment })} paymentMethods={get(LoggedInUser, 'collective.paymentMethods', [])} collective={this.state.stepProfile} /> ); } else if (step === 'submit') { return ( <Flex justifyContent="center" alignItems="center" flexDirection="column"> <Loading /> <P color="red.700">__DEBUG__</P> <P color="red.700">Profile:</P> <textarea>{JSON.stringify(this.state.stepProfile)}</textarea> <P color="red.700">Details:</P> <textarea>{JSON.stringify(this.state.stepDetails)}</textarea> <P color="red.700">PaymentMethod:</P> <textarea>{JSON.stringify(this.state.stepPayment)}</textarea> </Flex> ); } return null; } changeStep = async step => { if (this.props.loadingLoggedInUser || this.state.loading || this.state.submitting) { return false; } const { createCollective, verb, data, refetchLoggedInUser } = this.props; const { stepProfile, step: currentStep } = this.state; const params = { collectiveSlug: data.Collective.slug, step: step === 'contributeAs' ? undefined : step, }; // check if we're creating a new organization if (!currentStep && stepProfile.orgName) { const { data: result } = await createCollective({ name: stepProfile.orgName, ...omit(stepProfile, ['orgName']), }); if (result && result.createCollective) { await refetchLoggedInUser(); this.setState({ stepProfile: result.createCollective }); } } if (verb) { Router.pushRoute('donate', { ...params, verb }); } else { Router.pushRoute('orderCollectiveTier', { ...params, TierId: this.props.TierId }); } }; renderStepsProgress(currentStep) { const { stepProfile, stepDetails, stepPayment } = this.state; const loading = this.props.loadingLoggedInUser || this.state.loading || this.state.submitting; return ( <StepsProgress steps={STEPS} focus={currentStep} allCompleted={currentStep === 'submit'} onStepSelect={this.changeStep} loadingStep={loading ? currentStep : undefined} disabledSteps={loading ? STEPS : STEPS.slice(this.getMaxStepIdx() + 1, STEPS.length)} > {({ step }) => { let label = null; let details = null; if (step === 'contributeAs') { label = <FormattedMessage id="contribute.step.contributeAs" defaultMessage="Contribute as" />; details = get(stepProfile, 'name', null); } else if (step === 'details') { label = <FormattedMessage id="contribute.step.details" defaultMessage="Details" />; if (stepDetails && stepDetails.totalAmount) { const amount = formatCurrency(stepDetails.totalAmount, get(this.props, 'data.Collective.currency')); details = !stepDetails.interval ? ( amount ) : ( <Span> {amount}{' '} <FormattedMessage id="tier.interval" defaultMessage="per {interval, select, month {month} year {year} other {}}" values={{ interval: stepDetails.interval }} /> </Span> ); } } else if (step === 'payment') { label = <FormattedMessage id="contribute.step.payment" defaultMessage="Payment" />; details = get(stepPayment, 'title', null); } return ( <Flex flexDirection="column" alignItems="center"> <StepLabel>{label}</StepLabel> <Span fontSize="Caption" textAlign="center"> {details} </Span> </Flex> ); }} </StepsProgress> ); } renderContent() { const { LoggedInUser } = this.props; const { loading, submitting, unknownEmail } = this.state; if (!LoggedInUser) { return this.state.signIn ? ( <Flex justifyContent="center"> <SignIn onSubmit={this.signIn} onSecondaryAction={() => this.setState({ signIn: false })} loading={loading || submitting} unknownEmail={unknownEmail} /> </Flex> ) : ( <Flex justifyContent="center"> <CreateProfile onPersonalSubmit={this.createProfile} onOrgSubmit={this.createProfile} onSecondaryAction={() => this.setState({ signIn: true })} submitting={submitting} /> </Flex> ); } const step = this.props.step || 'contributeAs'; return ( <Flex flexDirection="column" alignItems="center"> <Box>{this.renderStep(step)}</Box> <Flex mt={5}> {this.renderPrevStepButton(step)} {this.renderNextStepButton(step)} </Flex> </Flex> ); } render() { const { data, loadingLoggedInUser } = this.props; if (!data.Collective) { return <ErrorPage data={data} />; } const collective = data.Collective; const logo = collective.image || get(collective.parentCollective, 'image'); const tierName = this.getContributorTypeName(); return ( <Page title={`Contribute - ${collective.name}`} description={collective.description} twitterHandle={collective.twitterHandle} image={collective.image || collective.backgroundImage} > <Flex alignItems="center" flexDirection="column" mx="auto" width={300} pt={4} mb={4}> <Link route="collective" params={{ slug: collective.slug }} className="goBack"> <Logo src={logo} className="logo" type={collective.type} website={collective.website} height="10rem" key={logo} /> </Link> <Link route="collective" params={{ slug: collective.slug }} className="goBack"> <H2 as="h1" color="black.900"> {collective.name} </H2> </Link> <P fontSize="LeadParagraph" fontWeight="LeadParagraph" color="black.600" mt={3}> <FormattedMessage id="contribute.contributorType" defaultMessage="Become a {name}" values={{ name: tierName }} /> </P> </Flex> <Flex id="content" flexDirection="column" alignItems="center" mb={6}> <Box mb={3} width={0.8} css={{ maxWidth: 365, minHeight: 95 }}> {this.renderStepsProgress(this.props.step || 'contributeAs')} </Box> {loadingLoggedInUser || data.loading ? <Loading /> : this.renderContent()} </Flex> {/* TODO Errors below should be displayed somewhere else */} <div className="row result"> <div className="col-sm-2" /> <div className="col-sm-10"> <div className="success">{this.state.result.success}</div> {this.state.result.error && <div className="error">{this.state.result.error}</div>} </div> </div> </Page> ); } } const addData = graphql(gql` query Collective($slug: String) { Collective(slug: $slug) { id slug name description twitterHandle type website image backgroundImage currency parentCollective { image } tiers { id type name slug description amount currency interval presets } } } `); const addCreateUserMutation = graphql(createUserQuery, { props: ({ mutate }) => ({ createUser: variables => mutate({ variables }), }), }); const addGraphQL = compose( addData, addCreateCollectiveMutation, addCreateOrderMutation, addCreateUserMutation, ); export default withIntl(addGraphQL(withUser(CreateOrderPage)));
feat(pages/createOrderNewFlow): set default amount for tiers Signed-off-by: François Hodierne <[email protected]>
src/pages/createOrderNewFlow.js
feat(pages/createOrderNewFlow): set default amount for tiers
<ide><path>rc/pages/createOrderNewFlow.js <ide> <ide> constructor(props) { <ide> super(props); <add> <add> const tier = this.getTier(); <ide> const interval = (props.interval || '').toLowerCase().replace(/ly$/, ''); <add> const amountOptions = (tier && tier.presets) || [500, 1000, 2000, 5000]; <add> const defaultAmount = amountOptions[Math.floor(amountOptions.length / 2)]; <ide> const initialDetails = { <ide> quantity: parseInt(props.quantity, 10) || 1, <ide> interval: ['month', 'year'].includes(interval) ? interval : null, <del> totalAmount: parseInt(props.totalAmount, 10) || null, <add> totalAmount: parseInt(props.totalAmount, 10) || defaultAmount, <ide> }; <ide> <ide> this.state = { <ide> const { data, LoggedInUser, TierId } = this.props; <ide> const [personal, profiles] = this.getProfiles(); <ide> const tier = this.getTier(); <add> const amountOptions = (tier && tier.presets) || [500, 1000, 2000, 5000]; <ide> <ide> if (step === 'contributeAs') { <ide> return ( <ide> } else if (step === 'details') { <ide> return ( <ide> <ContributeDetails <del> amountOptions={(tier && tier.presets) || [500, 1000, 2000, 5000]} <add> amountOptions={amountOptions} <ide> currency={(tier && tier.currency) || data.Collective.currency} <ide> onChange={data => this.setState({ stepDetails: data })} <del> showFrequency={Boolean(TierId)} <add> showFrequency={Boolean(TierId) || undefined} <ide> interval={get(this.state, 'stepDetails.interval')} <ide> totalAmount={get(this.state, 'stepDetails.totalAmount')} <ide> /> <ide> <ide> const step = this.props.step || 'contributeAs'; <ide> return ( <del> <Flex flexDirection="column" alignItems="center"> <add> <Flex flexDirection="column" alignItems="center" mx={3}> <ide> <Box>{this.renderStep(step)}</Box> <ide> <Flex mt={5}> <ide> {this.renderPrevStepButton(step)}
Java
apache-2.0
6b20f23ce548ebacd953507ca59bbebfbdef148a
0
osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi
/* * Copyright (c) OSGi Alliance (2013). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.service.zigbee.data; import org.osgi.service.zigbee.ZigBeeNode; /** * This interface represents an entry of the RoutingTableList (see Table 2.126 * NeighborTableList Record Format in ZIGBEE SPECIFICATION: * 1_053474r17ZB_TSC-ZigBee-Specification.pdf) * * @version 1.0 * * @author see RFC 192 authors: Andre Bottaro, Arnaud Rinquin, Jean-Pierre * Poutcheu, Fabrice Blache, Christophe Demottie, Antonin Chazalet, * Evgeni Grigorov, Nicola Portinaro, Stefano Lenzi. */ public interface LinkQuality { /** * @return the Service.PID refering to the {@link ZigBeeNode} representing * neighbour */ public String getNeighbour(); /** * See the LQI field of the (NeighborTableList Record Format). * * @return the Link Quality Indicator estimated by {@link ZigBeeNode} * returning this for communicating with {@link ZigBeeNode} * identified by the {@link #getNeighbour()} */ public int getLQI(); /** * See the Depth field of the (NeighborTableList Record Format). * * @return the tree-depth of device */ public int getDepth(); /** * See the Relationship field of the (NeighborTableList Record Format). * * @return the relationship between {@link ZigBeeNode} returning this and * the {@link ZigBeeNode} identified by the {@link #getNeighbour()} */ public int getRelationship(); }
org.osgi.service.zigbee/src/org/osgi/service/zigbee/data/LinkQuality.java
/* * Copyright (c) OSGi Alliance (2013). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.service.zigbee.data; import org.osgi.service.zigbee.ZigBeeNode; /** * This interface represents an entry of the RoutingTableList (see Table 2.126 * NeighborTableList Record Format in ZIGBEE SPECIFICATION: * 1_053474r17ZB_TSC-ZigBee-Specification.pdf) * * @version 1.0 * * @author see RFC 192 authors: Andre Bottaro, Arnaud Rinquin, Jean-Pierre * Poutcheu, Fabrice Blache, Christophe Demottie, Antonin Chazalet, * Evgeni Grigorov, Nicola Portinaro, Stefano Lenzi. */ public interface LinkQuality { /** * @return the Service.PID refering to the {@link ZigBeeNode} representing * neighbour */ public String getNeighbour(); /** * See the LQI field of the (NeighborTableList Record Format). * * @return the Link Quality Indicator estimated by {@link ZigBeeNode} * returning this for communicating with {@link ZigBeeNode} * identified by the {@link #getNeighbour()} */ public int getLQI(); /** * See the Depth field of the (NeighborTableList Record Format). * * @return the tree-depth of device */ public int getDepth(); /** * See the Relationship field of the (NeighborTableList Record Format). * * @return the relationship between {@link ZigBeeNode} returning this and * the {@link ZigBeeNode} identified by the {@link #getNeighbour()} */ public int getRelathionship(); }
RFC192: fix a typo in a method name.
org.osgi.service.zigbee/src/org/osgi/service/zigbee/data/LinkQuality.java
RFC192: fix a typo in a method name.
<ide><path>rg.osgi.service.zigbee/src/org/osgi/service/zigbee/data/LinkQuality.java <ide> * @return the relationship between {@link ZigBeeNode} returning this and <ide> * the {@link ZigBeeNode} identified by the {@link #getNeighbour()} <ide> */ <del> public int getRelathionship(); <add> public int getRelationship(); <ide> <ide> }
Java
apache-2.0
38b322d3bc13b1752c65616c2cf66f5c14c369b9
0
mjanicek/rembulan,kroepke/luna
package net.sandius.rembulan.compiler.gen.block; import net.sandius.rembulan.compiler.gen.Slots; import net.sandius.rembulan.util.Check; import net.sandius.rembulan.util.IntContainer; import net.sandius.rembulan.util.IntSet; public class Capture extends Linear implements LocalVariableEffect { public final IntSet indices; public Capture(IntContainer indices) { Check.notNull(indices); this.indices = IntSet.empty().plus(indices); } @Override public String toString() { return "Capture(" + indices.toString(",") + ")"; } @Override protected Slots effect(Slots in) { Slots s = in; for (int i = 0; i < indices.length(); i++) { s = s.capture(indices.get(i)); } return s; } }
rembulan-compiler/src/main/java/net/sandius/rembulan/compiler/gen/block/Capture.java
package net.sandius.rembulan.compiler.gen.block; import net.sandius.rembulan.compiler.gen.Slots; import net.sandius.rembulan.util.Check; import net.sandius.rembulan.util.IntVector; public class Capture extends Linear implements LocalVariableEffect { public final IntVector indices; public Capture(IntVector indices) { Check.notNull(indices); this.indices = indices; } @Override public String toString() { return "Capture(" + indices.toString(",") + ")"; } @Override protected Slots effect(Slots in) { Slots s = in; for (int i = 0; i < indices.length(); i++) { s = s.capture(indices.get(i)); } return s; } }
Using integer sets in capture nodes.
rembulan-compiler/src/main/java/net/sandius/rembulan/compiler/gen/block/Capture.java
Using integer sets in capture nodes.
<ide><path>embulan-compiler/src/main/java/net/sandius/rembulan/compiler/gen/block/Capture.java <ide> <ide> import net.sandius.rembulan.compiler.gen.Slots; <ide> import net.sandius.rembulan.util.Check; <del>import net.sandius.rembulan.util.IntVector; <add>import net.sandius.rembulan.util.IntContainer; <add>import net.sandius.rembulan.util.IntSet; <ide> <ide> public class Capture extends Linear implements LocalVariableEffect { <ide> <del> public final IntVector indices; <add> public final IntSet indices; <ide> <del> public Capture(IntVector indices) { <add> public Capture(IntContainer indices) { <ide> Check.notNull(indices); <del> this.indices = indices; <add> this.indices = IntSet.empty().plus(indices); <ide> } <ide> <ide> @Override
JavaScript
mit
fe7c52f0c457c43c3d405e1482621d09b006ac0f
0
geowa4/pajamas
!(function (factory) { if (typeof module !== 'undefined' && module.exports) module.exports = factory(require('q')) else if (typeof define === 'function' && define.amd) define(['q'], factory) else this['qjax'] = factory(this['Q']) } (function (Q) { var win = window , readyState = 'readyState' , xmlHttpRequest = 'XMLHttpRequest' , xhr = win[xmlHttpRequest] ? function () { return new win[xmlHttpRequest]() } : function () { return new win.ActiveXObject('Microsoft.XMLHTTP') } , responseText = 'responseText' , contentType = 'Content-Type' , requestedWith = 'X-Requested-With' , defaultHeaders = { contentType: 'application/x-www-form-urlencoded' , Accept: { '*' : 'text/javascript, text/html, application/xml,' + ' text/xml, */*' , xml : 'application/xml, text/xml' , html : 'text/html' , text : 'text/plain' , json : 'application/json, text/javascript' , js : 'application/javascript, text/javascript' } , requestedWith: xmlHttpRequest } , toString = Object.prototype.toString , isArray = Array.isArray || function (obj) { return obj instanceof Array } // TODO: evaluate use of `result` , result = function (obj, prop) { var val if (obj == null) return null val = obj[prop] return (typeof val === 'function') ? val.call(obj) : val } , urlAppend = function (url, dataString) { return url + (url.indexOf('?') !== -1 ? '&' : '?') + dataString } , setHeaders = function (http, options) { var headers = options.headers || {} , accept = 'Accept' , h headers[accept] = headers[accept] || defaultHeaders[accept][options.dataType] || defaultHeaders[accept]['*'] if (!options.crossOrigin && !headers[requestedWith]) headers[requestedWith] = defaultHeaders.requestedWith if (!headers[contentType]) headers[contentType] = options.contentType || defaultHeaders.contentType for (h in headers) if (headers.hasOwnProperty(h)) http.setRequestHeader(h, headers[h]) } , toQueryString = function (data) { var queryString = '' , enc = encodeURIComponent , push = function (k, v) { queryString += enc(k) + '=' + enc(v) + '&' } , i , val , prop if (isArray(data)) { for (i = 0; data && i < data.length; i++) push(data[i].name, data[i].value) } else { for (prop in data) { if (data.hasOwnProperty(prop)) { val = data[prop] if (isArray(val)) for (i = 0; i < val.length; i++) push(prop, val[i]) else push(prop, data[prop]) } } } return queryString.replace(/&$/, '').replace(/%20/g,'+') } , responseParsers = { json : function (deferred) { var r = this[responseText] try { r = win.JSON ? win.JSON.parse(r) : eval('(' + r + ')') deferred.resolve(r) } catch (err) { deferred.reject(new Error('Could not parse JSON in response.')) } } , js : function (deferred) { try { deferred.resolve(eval(this[responseText])) } catch (err) { deferred.reject(err) } } , text : function (deferred) { deferred.resolve(this[responseText]) } , html : function (deferred) { responseParsers.text.call(this, deferred) } , xml : function (deferred) { var r = this.responseXML // Chrome makes `responseXML` null; // IE makes `documentElement` null; // FF makes up an element; // this is my attempt at standardization if (r === null || r.documentElement === null || r.documentElement.nodeName === 'parsererror') deferred.resolve(null) else deferred.resolve(this.responseXML) } } return function (options) { var deferred = Q.defer() , promise = deferred.promise // TODO: handle timeouts , timeout , o = options == null ? {} : options , method = (o.method || 'GET').toUpperCase() , url = o.url || '' , data = (o.data && o.processData && typeof o.data !== 'string') ? toQueryString(o.data) : (o.data || null) , dataType = o.dataType || 'json' , http = xhr(); if (data && method === 'GET') { url = urlAppend(url, data) data = null } http.open(method, url, true) setHeaders(http, o) http.onreadystatechange = function () { var status if (http && http[readyState] === 4) { status = http.status if (status >= 200 && status < 300 || status === 304 || status === 0 && http[responseText] !== '') { if (http[responseText]) responseParsers[dataType].call(http, deferred) else deferred.resolve(null) } else deferred.reject( new Error(method + ' ' + url + ': ' + http.status + ' ' + http.statusText)) } } try { http.send(data) } catch (err) { deferred.reject(err) } return promise; } }))
src/qjax.js
!(function (factory) { if (typeof module !== 'undefined' && module.exports) module.exports = factory(require('q')) else if (typeof define === 'function' && define.amd) define(['q'], factory) else this['qjax'] = factory(this['Q']) } (function (Q) { var win = window , readyState = 'readyState' , xmlHttpRequest = 'XMLHttpRequest' , xhr = win[xmlHttpRequest] ? function () { return new win[xmlHttpRequest]() } : function () { return new win.ActiveXObject('Microsoft.XMLHTTP') } , responseText = 'responseText' , contentType = 'Content-Type' , requestedWith = 'X-Requested-With' , defaultHeaders = { contentType: 'application/x-www-form-urlencoded' , Accept: { '*' : 'text/javascript, text/html, application/xml,' + ' text/xml, */*' , xml : 'application/xml, text/xml' , html : 'text/html' , text : 'text/plain' , json : 'application/json, text/javascript' , js : 'application/javascript, text/javascript' } , requestedWith: xmlHttpRequest } , toString = Object.prototype.toString , isArray = Array.isArray || function (obj) { return obj instanceof Array } // TODO: evaluate use of `result` , result = function (obj, prop) { var val if (obj == null) return null val = obj[prop] return (typeof val === 'function') ? val.call(obj) : val } , urlAppend = function (url, dataString) { return url + (url.indexOf('?') !== -1 ? '&' : '?') + dataString } , setHeaders = function (http, options) { var headers = options.headers || {} , accept = 'Accept' , h headers[accept] = headers[accept] || defaultHeaders[accept][options.dataType] || defaultHeaders[accept]['*'] if (!options.crossOrigin && !headers[requestedWith]) headers[requestedWith] = defaultHeaders.requestedWith if (!headers[contentType]) headers[contentType] = options.contentType || defaultHeaders.contentType for (h in headers) if (headers.hasOwnProperty(h)) http.setRequestHeader(h, headers[h]) } , toQueryString = function (data) { var queryString = '' , enc = encodeURIComponent , push = function (k, v) { queryString += enc(k) + '=' + enc(v) + '&' } , i , val , prop if (isArray(data)) { for (i = 0; data && i < data.length; i++) push(data[i].name, data[i].value) } else { for (prop in data) { if (data.hasOwnProperty(prop)) { val = data[prop] if (isArray(val)) for (i = 0; i < val.length; i++) push(prop, val[i]) else push(prop, data[prop]) } } } return queryString.replace(/&$/, '').replace(/%20/g,'+') } , responseParsers = { json : function (deferred) { var r = this[responseText] try { r = win.JSON ? win.JSON.parse(r) : eval('(' + r + ')') deferred.resolve(r) } catch (err) { deferred.reject(new Error('Could not parse JSON in response.')) } } , js : function (deferred) { try { deferred.resolve(eval(this[responseText])) } catch (err) { deferred.reject(err) } } , text : function (deferred) { deferred.resolve(this[responseText]) } , html : function (deferred) { responseParsers.text.call(this, deferred) } , xml : function (deferred) { var r = this.responseXML // Chrome makes `responseXML` null; // IE makes `documentElement` null; // FF makes up an element; // this is my attempt at standardization if (r === null || r.documentElement === null || r.documentElement.nodeName === 'parsererror') deferred.resolve(null) else deferred.resolve(this.responseXML) } } return function (options) { var deferred = Q.defer() , promise = deferred.promise // TODO: handle timeouts , timeout , o = options == null ? {} : options , method = (o.method || 'GET').toUpperCase() , url = o.url || '' , data = (o.processData !== false && o.data) ? toQueryString(o.data) : (o.data || null) , dataType = o.dataType || 'json' , http = xhr(); if (data && method === 'GET') { url = urlAppend(url, data) data = null } http.open(method, url, true) setHeaders(http, o) http.onreadystatechange = function () { var status if (http && http[readyState] === 4) { status = http.status if (status >= 200 && status < 300 || status === 304 || status === 0 && http[responseText] !== '') { if (http[responseText]) responseParsers[dataType].call(http, deferred) else deferred.resolve(null) } else deferred.reject( new Error(method + ' ' + url + ': ' + http.status + ' ' + http.statusText)) } } try { http.send(data) } catch (err) { deferred.reject(err) } return promise; } }))
process data like jquery does
src/qjax.js
process data like jquery does
<ide><path>rc/qjax.js <ide> , o = options == null ? {} : options <ide> , method = (o.method || 'GET').toUpperCase() <ide> , url = o.url || '' <del> , data = (o.processData !== false && o.data) ? <add> , data = (o.data && o.processData && typeof o.data !== 'string') ? <ide> toQueryString(o.data) : <ide> (o.data || null) <ide> , dataType = o.dataType || 'json'
Java
mit
637de1fe288bece8452eaa5e595df2b3ef0fecfe
0
CMPUT301W17T10/psychic-engine
app/src/main/java/com/psychic_engine/cmput301w17t10/feelsappman/EditMoodController.java
package com.psychic_engine.cmput301w17t10.feelsappman; import android.location.Location; import com.psychic_engine.cmput301w17t10.feelsappman.Enums.MoodState; import com.psychic_engine.cmput301w17t10.feelsappman.Enums.SocialSetting; import com.psychic_engine.cmput301w17t10.feelsappman.Models.Mood; import com.psychic_engine.cmput301w17t10.feelsappman.Models.MoodEvent; import com.psychic_engine.cmput301w17t10.feelsappman.Models.ParticipantSingleton; import com.psychic_engine.cmput301w17t10.feelsappman.Models.Photograph; import java.util.Date; /** * Created by Jen on 3/8/2017. */ /* public class EditMoodController { static boolean updateMoodEventList(int moodEventPosition, String moodString, String socialSettingString, String trigger, Photograph photo, String location) { try { Mood mood = null; SocialSetting socialSetting; switch (moodString) { // TODO refactor this - inside MoodState enum class? case "Sad": mood = new Mood(MoodState.SAD); break; case "Happy": mood = new Mood(MoodState.HAPPY); break; case "Shame": mood = new Mood(MoodState.SHAME); break; case "Fear": mood = new Mood(MoodState.FEAR); break; case "Anger": mood = new Mood(MoodState.ANGER); break; case "Surprised": mood = new Mood(MoodState.SURPRISED); break; case "Disgust": mood = new Mood(MoodState.DISGUST); break; case "Confused": mood = new Mood(MoodState.CONFUSED); break; } switch (socialSettingString) { case "Alone": socialSetting = SocialSetting.ALONE; break; case "One Other": socialSetting = SocialSetting.ONEOTHER; break; case "Two To Several": socialSetting = SocialSetting.TWOTOSEVERAL; break; case "Crowd": socialSetting = SocialSetting.CROWD; break; default: socialSetting = null; } MoodEvent moodEvent = new MoodEvent(mood, socialSetting, trigger, photo, location); // replace old moodEvent with new one ParticipantSingleton.getInstance().getSelfParticipant().setMoodEvent(moodEventPosition, moodEvent); return true; } catch (Exception e) { return false; } } } */
Delete EditMoodController.java
app/src/main/java/com/psychic_engine/cmput301w17t10/feelsappman/EditMoodController.java
Delete EditMoodController.java
<ide><path>pp/src/main/java/com/psychic_engine/cmput301w17t10/feelsappman/EditMoodController.java <del>package com.psychic_engine.cmput301w17t10.feelsappman; <del> <del>import android.location.Location; <del> <del>import com.psychic_engine.cmput301w17t10.feelsappman.Enums.MoodState; <del>import com.psychic_engine.cmput301w17t10.feelsappman.Enums.SocialSetting; <del>import com.psychic_engine.cmput301w17t10.feelsappman.Models.Mood; <del>import com.psychic_engine.cmput301w17t10.feelsappman.Models.MoodEvent; <del>import com.psychic_engine.cmput301w17t10.feelsappman.Models.ParticipantSingleton; <del>import com.psychic_engine.cmput301w17t10.feelsappman.Models.Photograph; <del> <del>import java.util.Date; <del> <del>/** <del> * Created by Jen on 3/8/2017. <del> */ <del>/* <del>public class EditMoodController { <del> <del> static boolean updateMoodEventList(int moodEventPosition, String moodString, String socialSettingString, String trigger, Photograph photo, String location) { <del> try { <del> Mood mood = null; <del> SocialSetting socialSetting; <del> <del> switch (moodString) { // TODO refactor this - inside MoodState enum class? <del> case "Sad": <del> mood = new Mood(MoodState.SAD); <del> break; <del> case "Happy": <del> mood = new Mood(MoodState.HAPPY); <del> break; <del> case "Shame": <del> mood = new Mood(MoodState.SHAME); <del> break; <del> case "Fear": <del> mood = new Mood(MoodState.FEAR); <del> break; <del> case "Anger": <del> mood = new Mood(MoodState.ANGER); <del> break; <del> case "Surprised": <del> mood = new Mood(MoodState.SURPRISED); <del> break; <del> case "Disgust": <del> mood = new Mood(MoodState.DISGUST); <del> break; <del> case "Confused": <del> mood = new Mood(MoodState.CONFUSED); <del> break; <del> } <del> <del> <del> switch (socialSettingString) { <del> case "Alone": <del> socialSetting = SocialSetting.ALONE; <del> break; <del> case "One Other": <del> socialSetting = SocialSetting.ONEOTHER; <del> break; <del> case "Two To Several": <del> socialSetting = SocialSetting.TWOTOSEVERAL; <del> break; <del> case "Crowd": <del> socialSetting = SocialSetting.CROWD; <del> break; <del> default: <del> socialSetting = null; <del> } <del> <del> MoodEvent moodEvent = new MoodEvent(mood, socialSetting, trigger, photo, location); <del> <del> // replace old moodEvent with new one <del> ParticipantSingleton.getInstance().getSelfParticipant().setMoodEvent(moodEventPosition, moodEvent); <del> return true; <del> } catch (Exception e) { <del> return false; <del> } <del> } <del>} <del>*/
Java
apache-2.0
6d0141aa982b26cac7ccb2304b6864388771cf0d
0
abarisain/dmix,jcnoir/dmix,hurzl/dmix,abarisain/dmix,hurzl/dmix,0359xiaodong/dmix,0359xiaodong/dmix,jcnoir/dmix,joansmith/dmix,joansmith/dmix
package org.a0z.mpd; import org.a0z.mpd.exception.MPDClientException; import org.a0z.mpd.exception.MPDConnectionException; import org.a0z.mpd.exception.MPDServerException; import android.content.Context; import android.util.Log; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * MPD Server controller. * * @version $Id: MPD.java 2716 2004-11-20 17:37:20Z galmeida $ */ public class MPD { private final static String TAG = "org.a0z.mpd.MPD"; protected MPDConnection mpdConnection; protected MPDConnection mpdIdleConnection; protected MPDConnection mpdStatusConnection; protected MPDStatus mpdStatus; protected MPDPlaylist playlist; protected Directory rootDirectory; static protected boolean sortByTrackNumber = true; static protected boolean sortAlbumsByYear = false; static protected boolean showArtistAlbumCount = false; static protected boolean showAlbumTrackCount = true; static protected Context applicationContext = null; static public Context getApplicationContext() { return applicationContext; } static public void setApplicationContext(Context context) { applicationContext = context; } static public void setShowAlbumTrackCount(boolean v) { showAlbumTrackCount = v; } static public void setShowArtistAlbumCount(boolean v) { showArtistAlbumCount = v; } static public void setSortAlbumsByYear(boolean v) { sortAlbumsByYear = v; } static public void setSortByTrackNumber(boolean v) { sortByTrackNumber = v; } static public boolean showAlbumTrackCount() { return showAlbumTrackCount; } static public boolean showArtistAlbumCount() { return showArtistAlbumCount; } static public boolean sortAlbumsByYear() { return sortAlbumsByYear; } static public boolean sortByTrackNumber() { return sortByTrackNumber; } /** * Constructs a new MPD server controller without connection. */ public MPD() { this.playlist = new MPDPlaylist(this); this.mpdStatus = new MPDStatus(); this.rootDirectory = Directory.makeRootDirectory(this); } /** * Constructs a new MPD server controller. * * @param server server address or host name * @param port server port * @throws MPDServerException if an error occur while contacting server */ public MPD(InetAddress server, int port, String password) throws MPDServerException { this(); connect(server, port, password); } /** * Constructs a new MPD server controller. * * @param server server address or host name * @param port server port * @throws MPDServerException if an error occur while contacting server * @throws UnknownHostException */ public MPD(String server, int port, String password) throws MPDServerException, UnknownHostException { this(); connect(server, port, password); } public void add(Album album) throws MPDServerException { add(album, false, false); } public void add(final Album album, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { final ArrayList<Music> songs = new ArrayList<Music>(getSongs(album)); getPlaylist().addAll(songs); } catch (MPDServerException e) { e.printStackTrace(); } } }; add(r, replace, play); } public void add(Artist artist) throws MPDServerException { add(artist, false, false); } public void add(final Artist artist, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { final ArrayList<Music> songs = new ArrayList<Music>(getSongs(artist)); getPlaylist().addAll(songs); } catch (MPDServerException e) { e.printStackTrace(); } } }; add(r, replace, play); } public void add(final Directory directory, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { getPlaylist().add(directory); } catch (MPDServerException e) { e.printStackTrace(); } } }; add(r, replace, play); } public void add(final FilesystemTreeEntry music, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { if (music instanceof Music) { getPlaylist().add(music); } else if (music instanceof PlaylistFile) { getPlaylist().load(music.getFullpath()); } } catch (MPDServerException e) { e.printStackTrace(); } } }; add(r, replace, play); } public void add(Music music) throws MPDServerException { add(music, false, false); } /** * Adds songs to the queue. It is possible to request a clear of the current * one, and to start the playback once done. * * @param runnable The runnable that will be responsible of inserting the * songs into the queue * @param replace If true, replaces the entire playlist queue with the added files * @param play If true, starts playing once added */ public void add(Runnable runnable, boolean replace, boolean play) throws MPDServerException { int playPos = 0; final boolean isPlaying = MPDStatus.MPD_STATE_PLAYING.equals(getStatus().getState()); if (replace) { if (isPlaying) { playPos = 1; getPlaylist().crop(); } else { getPlaylist().clear(); } } else if (play) { playPos = getPlaylist().size(); } runnable.run(); if (play || (replace && isPlaying)) { skipToPosition(playPos); } /** Finally, clean up the last playing song. */ if (replace && isPlaying) { try { getPlaylist().removeByIndex(0); } catch (MPDServerException e) { Log.d(TAG, "Remove by index failed.", e); } } } public void add(String playlist) throws MPDServerException { add(playlist, false, false); } public void add(final String playlist, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { getPlaylist().load(playlist); } catch (MPDServerException e) { e.printStackTrace(); } } }; add(r, replace, play); } public void add(final URL stream, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { getPlaylist().add(stream); } catch (MPDServerException | MPDClientException e) { e.printStackTrace(); } } }; add(r, replace, play); } protected void addAlbumPaths(List<Album> albums) { if (albums == null || albums.size() == 0) { return; } for (Album a : albums) { try { List<Music> songs = getFirstTrack(a); if (songs.size() > 0) { a.setPath(songs.get(0).getPath()); } } catch (MPDServerException e) { } } } // Returns a pattern where all punctuation characters are escaped. public void addToPlaylist(String playlistName, Album album) throws MPDServerException { addToPlaylist(playlistName, new ArrayList<Music>(getSongs(album))); } public void addToPlaylist(String playlistName, Artist artist) throws MPDServerException { addToPlaylist(playlistName, new ArrayList<Music>(getSongs(artist))); } public void addToPlaylist(String playlistName, Collection<Music> c) throws MPDServerException { if (null == c || c.size() < 1) { return; } for (Music m : c) { getMpdConnection().queueCommand(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlistName, m.getFullpath()); } getMpdConnection().sendCommandQueue(); } public void addToPlaylist(String playlistName, FilesystemTreeEntry entry) throws MPDServerException { getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlistName, entry.getFullpath()); } public void addToPlaylist(String playlistName, Music music) throws MPDServerException { final ArrayList<Music> songs = new ArrayList<Music>(); songs.add(music); addToPlaylist(playlistName, songs); } /** * Increases or decreases volume by <code>modifier</code> amount. * * @param modifier volume adjustment * @throws MPDServerException if an error occur while contacting server */ public void adjustVolume(int modifier) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); // calculate final volume (clip value with [0, 100]) int vol = getVolume() + modifier; vol = Math.max(MPDCommand.MIN_VOLUME, Math.min(MPDCommand.MAX_VOLUME, vol)); mpdConnection.sendCommand(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol)); } /* * test whether given album is in given genre */ public boolean albumInGenre(Album album, Genre genre) throws MPDServerException { List<String> response; Artist artist = album.getArtist(); response = mpdConnection.sendCommand (new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM, MPDCommand.MPD_TAG_ALBUM, album.getName(), album.hasAlbumArtist() ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_TAG_ARTIST, (artist == null ? "" : artist.getName()), MPDCommand.MPD_TAG_GENRE, genre.getName())); return (response.size() > 0); } /** * Clears error message. * * @throws MPDServerException if an error occur while contacting server. */ public void clearError() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_CLEARERROR); } /** * Connects to a MPD server. * * @param server server address or host name * @param port server port */ public synchronized final void connect(InetAddress server, int port, String password) throws MPDServerException { if (!isConnected()) { this.mpdConnection = new MPDConnectionMultiSocket(server, port, 3, password, 5000); this.mpdIdleConnection = new MPDConnectionMonoSocket(server, port, password, 0); this.mpdStatusConnection = new MPDConnectionMonoSocket(server, port, password, 5000); } } /** * Connects to a MPD server. * * @param server server address or host name * @param port server port * @throws MPDServerException if an error occur while contacting server * @throws UnknownHostException */ public final void connect(String server, int port, String password) throws MPDServerException, UnknownHostException { InetAddress address = InetAddress.getByName(server); connect(address, port, password); } /** * Connects to a MPD server. * * @param server server address or host name and port (server:port) * @throws MPDServerException if an error occur while contacting server * @throws UnknownHostException */ public final void connect(String server, String password) throws MPDServerException, UnknownHostException { int port = MPDCommand.DEFAULT_MPD_PORT; String host; if (server.indexOf(':') != -1) { host = server.substring(0, server.lastIndexOf(':')); port = Integer.parseInt(server.substring(server.lastIndexOf(':') + 1)); } else { host = server; } connect(host, port, password); } public void disableOutput(int id) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTDISABLE, Integer.toString(id)); } /** * Disconnects from server. * * @throws MPDServerException if an error occur while closing connection */ public synchronized void disconnect() throws MPDServerException { MPDServerException ex = null; if (mpdConnection != null && mpdConnection.isConnected()) { try { mpdConnection.sendCommand(MPDCommand.MPD_CMD_CLOSE); } catch (MPDServerException e) { ex = e; } } if (mpdConnection != null && mpdConnection.isConnected()) { try { mpdConnection.disconnect(); } catch (MPDServerException e) { ex = (ex != null) ? ex : e;// Always keep first non null // exception } } if (mpdIdleConnection != null && mpdIdleConnection.isConnected()) { try { mpdIdleConnection.disconnect(); } catch (MPDServerException e) { ex = (ex != null) ? ex : e;// Always keep non null first // exception } } if (mpdStatusConnection != null && mpdStatusConnection.isConnected()) { try { mpdStatusConnection.disconnect(); } catch (MPDServerException e) { ex = (ex != null) ? ex : e;// Always keep non null first // exception } } // TODO: Throw ex } public void enableOutput(int id) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTENABLE, Integer.toString(id)); } /** * Similar to <code>search</code>,<code>find</code> looks for exact matches * in the MPD database. * * @param type type of search. Should be one of the following constants: * MPD_FIND_ARTIST, MPD_FIND_ALBUM * @param string case-insensitive locator string. Anything that exactly * matches <code>string</code> will be returned in the results. * @return a Collection of <code>Music</code> * @throws MPDServerException if an error occur while contacting server * @see org.a0z.mpd.Music */ public List<Music> find(String type, String string) throws MPDServerException { return genericSearch(MPDCommand.MPD_CMD_FIND, type, string); } public List<Music> find(String[] args) throws MPDServerException { return genericSearch(MPDCommand.MPD_CMD_FIND, args, true); } /* * For all given albums, look for albumartists and create as many albums as * there are albumartists, including "" The server call can be slow for long * album lists */ protected void fixAlbumArtists(List<Album> albums) { if (albums == null || albums.size() == 0) { return; } List<String[]> albumartists = null; try { albumartists = listAlbumArtists(albums); } catch (MPDServerException e) { } if (albumartists == null || albumartists.size() != albums.size()) { return; } List<Album> splitalbums = new ArrayList<Album>(); int i = 0; for (Album a : albums) { String[] aartists = albumartists.get(i); if (aartists.length > 0) { Arrays.sort(aartists); // make sure "" is the first one if (!"".equals(aartists[0])) { // one albumartist, fix this // album a.setArtist(new Artist(aartists[0])); a.setHasAlbumArtist(true); } // do nothing if albumartist is "" if (aartists.length > 1) { // it's more than one album, insert for (int n = 1; n < aartists.length; n++) { Album newalbum = new Album(a.getName(), new Artist(aartists[n]), true); splitalbums.add(newalbum); } } } i++; } albums.addAll(splitalbums); } protected List<Music> genericSearch(String searchCommand, String args[], boolean sort) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); return Music.getMusicFromList(mpdConnection.sendCommand(searchCommand, args), sort); } protected List<Music> genericSearch(String searchCommand, String type, String strToFind) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(searchCommand, type, strToFind); return Music.getMusicFromList(response, true); } public int getAlbumCount(Artist artist, boolean useAlbumArtistTag) throws MPDServerException { return listAlbums(artist.getName(), useAlbumArtistTag).size(); } public int getAlbumCount(String artist, boolean useAlbumArtistTag) throws MPDServerException { if (mpdConnection == null) { throw new MPDServerException("MPD Connection is not established"); } return listAlbums(artist, useAlbumArtistTag).size(); } protected void getAlbumDetails(List<Album> albums, boolean findYear) throws MPDServerException { for (Album a : albums) { mpdConnection.queueCommand(getAlbumDetailsCommand(a)); } List<String[]> response = mpdConnection.sendCommandQueueSeparated(); if (response.size() != albums.size()) { // Log.d("MPD AlbumDetails", "non matching results "+ // response.size()+" != "+ albums.size()); return; } for (int i = 0; i < response.size(); i++) { String[] list = response.get(i); Album a = albums.get(i); for (String line : list) { if (line.startsWith("songs: ")) { a.setSongCount(Long.parseLong(line.substring("songs: ".length()))); } else if (line.startsWith("playtime: ")) { a.setDuration(Long.parseLong(line.substring("playtime: ".length()))); } } if (findYear) { List<Music> songs = getFirstTrack(a); if (null != songs && !songs.isEmpty()) { a.setYear(songs.get(0).getDate()); a.setPath(songs.get(0).getPath()); } } } } protected MPDCommand getAlbumDetailsCommand(Album album) throws MPDServerException { if (album.hasAlbumArtist()) { return new MPDCommand(MPDCommand.MPD_CMD_COUNT, MPDCommand.MPD_TAG_ALBUM, album.getName(), MPDCommand.MPD_TAG_ALBUM_ARTIST, album.getArtist().getName()); } else { // only get albums without albumartist return new MPDCommand(MPDCommand.MPD_CMD_COUNT, MPDCommand.MPD_TAG_ALBUM, album.getName(), MPDCommand.MPD_TAG_ARTIST, album.getArtist().getName(), MPDCommand.MPD_TAG_ALBUM_ARTIST, ""); } } public List<Album> getAlbums(Artist artist, boolean trackCountNeeded) throws MPDServerException { List<Album> a_albums = getAlbums(artist, trackCountNeeded, false); // 1. the null artist list already contains all albums // 2. the "unknown artist" should not list unknown albumartists if (artist != null && !artist.isUnknown()) { return Item.merged(a_albums, getAlbums(artist, trackCountNeeded, true)); } return a_albums; } public List<Album> getAlbums(Artist artist, boolean trackCountNeeded, boolean useAlbumArtist) throws MPDServerException { if (artist == null) { return getAllAlbums(trackCountNeeded); } List<String> albumNames = listAlbums(artist.getName(), useAlbumArtist); List<Album> albums = new ArrayList<Album>(); if (null == albumNames || albumNames.isEmpty()) { return albums; } for (String album : albumNames) { albums.add(new Album(album, artist, useAlbumArtist)); } if (!useAlbumArtist) { fixAlbumArtists(albums); } // after fixing albumartists if (((MPD.showAlbumTrackCount() && trackCountNeeded) || MPD.sortAlbumsByYear())) { getAlbumDetails(albums, MPD.sortAlbumsByYear()); } if (!MPD.sortAlbumsByYear()) { addAlbumPaths(albums); } Collections.sort(albums); return albums; } /** * @return all Albums */ public List<Album> getAllAlbums(boolean trackCountNeeded) throws MPDServerException { List<String> albumNames = listAlbums(); List<Album> albums = new ArrayList<Album>(); if (null == albumNames || albumNames.isEmpty()) { return albums; // empty list } for (String album : albumNames) { albums.add(new Album(album, null)); } Collections.sort(albums); return albums; } public List<Artist> getArtists() throws MPDServerException { return Item.merged(getArtists(true), getArtists(false)); } public List<Artist> getArtists(boolean useAlbumArtist) throws MPDServerException { List<String> artistNames = useAlbumArtist ? listAlbumArtists() : listArtists(true); List<Artist> artists = new ArrayList<Artist>(); if (null != artistNames && !artistNames.isEmpty()) { for (String artist : artistNames) { artists.add(new Artist(artist, MPD.showArtistAlbumCount() ? getAlbumCount(artist, useAlbumArtist) : 0)); } } Collections.sort(artists); return artists; } public List<Artist> getArtists(Genre genre) throws MPDServerException { return Item.merged(getArtists(genre, false), getArtists(genre, true)); } public List<Artist> getArtists(Genre genre, boolean useAlbumArtist) throws MPDServerException { List<String> artistNames = useAlbumArtist ? listAlbumArtists(genre) : listArtists( genre.getName(), true); List<Artist> artists = new ArrayList<Artist>(); if (null != artistNames && !artistNames.isEmpty()) { for (String artist : artistNames) { artists.add(new Artist(artist, MPD.showArtistAlbumCount() ? getAlbumCount(artist, useAlbumArtist) : 0)); } } Collections.sort(artists); return artists; } /** * Retrieves a database directory listing of the base of the database * directory path. * * @return a <code>Collection</code> of <code>Music</code> and * <code>Directory</code> representing directory entries. * @throws MPDServerException if an error occur while contacting server. * @see Music * @see Directory */ public List<FilesystemTreeEntry> getDir() throws MPDServerException { return getDir(null); } /** * Retrieves a database directory listing of <code>path</code> directory. * * @param path Directory to be listed. * @return a <code>Collection</code> of <code>Music</code> and * <code>Directory</code> representing directory entries. * @throws MPDServerException if an error occur while contacting server. * @see Music * @see Directory */ public List<FilesystemTreeEntry> getDir(String path) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LSDIR, path); LinkedList<String> lineCache = new LinkedList<String>(); LinkedList<FilesystemTreeEntry> result = new LinkedList<FilesystemTreeEntry>(); for (String line : response) { // If we detect a new file element and the line cache isn't empty // dump the linecache into a music item if (line.startsWith("file: ") && lineCache.size() > 0) { result.add(new Music(lineCache)); lineCache.clear(); } if (line.startsWith("playlist: ")) { lineCache.clear(); line = line.substring("playlist: ".length()); result.add(new PlaylistFile(line)); } else if (line.startsWith("directory: ")) { lineCache.clear(); line = line.substring("directory: ".length()); result.add(rootDirectory.makeDirectory(line)); } else { lineCache.add(line); } } if (lineCache.size() > 0) { // Don't create a music object if the line cache does not contain any // It can happen for playlist and directory items with supplementary information for (String line : lineCache) { if (line.startsWith("file: ")) { result.add(new Music(lineCache)); break; } } } return result; } protected List<Music> getFirstTrack(Album album) throws MPDServerException { Artist artist = album.getArtist(); String[] args = new String[6]; args[0] = (artist == null ? "" : album.hasAlbumArtist() ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_TAG_ARTIST); args[1] = (artist == null ? "" : artist.getName()); args[2] = MPDCommand.MPD_TAG_ALBUM; args[3] = album.getName(); args[4] = "track"; args[5] = "1"; List<Music> songs = find(args); if (null == songs || songs.isEmpty()) { args[5] = "01"; songs = find(args); } if (null == songs || songs.isEmpty()) { args[5] = "1"; songs = search(args); } if (null == songs || songs.isEmpty()) { String[] args2 = Arrays.copyOf(args, 4); // find all tracks songs = find(args2); } return songs; } public List<Genre> getGenres() throws MPDServerException { List<String> genreNames = listGenres(); List<Genre> genres = null; if (null != genreNames && !genreNames.isEmpty()) { genres = new ArrayList<Genre>(); for (String genre : genreNames) { genres.add(new Genre(genre)); } } if (null != genres) { Collections.sort(genres); } return genres; } /** * Retrieves <code>MPDConnection</code>. * * @return <code>MPDConnection</code>. */ public MPDConnection getMpdConnection() { return this.mpdConnection; } MPDConnection getMpdIdleConnection() { return this.mpdIdleConnection; } /** * Returns MPD server version. * * @return MPD Server version. */ public String getMpdVersion() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); int[] version = mpdIdleConnection.getMpdVersion(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < version.length; i++) { sb.append(version[i]); if (i < (version.length - 1)) sb.append("."); } return sb.toString(); } /** * Returns the available outputs * * @return List of available outputs */ public List<MPDOutput> getOutputs() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<MPDOutput> result = new LinkedList<MPDOutput>(); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTS); LinkedList<String> lineCache = new LinkedList<String>(); for (String line : response) { if (line.startsWith("outputid: ")) { if (lineCache.size() != 0) { result.add(new MPDOutput(lineCache)); lineCache.clear(); } } lineCache.add(line); } if (lineCache.size() != 0) { result.add(new MPDOutput(lineCache)); } return result; } /** * Retrieves <code>playlist</code>. * * @return playlist. */ public MPDPlaylist getPlaylist() { return this.playlist; } /** * Returns a list of all available playlists */ public List<Item> getPlaylists() throws MPDServerException { return getPlaylists(false); } /** * Returns a list of all available playlists * * @param sort whether the return list should be sorted */ public List<Item> getPlaylists(boolean sort) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<Item> result = new ArrayList<Item>(); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LISTPLAYLISTS); for (String line : response) { if (line.startsWith("playlist")) result.add(new Playlist(line.substring("playlist: ".length()))); } if (sort) Collections.sort(result); return result; } public List<Music> getPlaylistSongs(String playlistName) throws MPDServerException { String args[] = new String[1]; args[0] = playlistName; List<Music> music = genericSearch(MPDCommand.MPD_CMD_PLAYLIST_INFO, args, false); for (int i = 0; i < music.size(); ++i) { music.get(i).setSongId(i); } return music; } /** * Retrieves root directory. * * @return root directory. */ public Directory getRootDirectory() { return rootDirectory; } public List<Music> getSongs(Album album) throws MPDServerException { List<Music> songs = Music.getMusicFromList (getMpdConnection().sendCommand(getSongsCommand(album)), true); if (album.hasAlbumArtist()) { // remove songs that don't have this albumartist // (mpd >=0.18 puts them in) String artistname = album.getArtist().getName(); for (int i = songs.size() - 1; i >= 0; i--) { if (!(artistname.equals(songs.get(i).getAlbumArtist()))) { songs.remove(i); } } } if (null != songs) { Collections.sort(songs); } return songs; } public List<Music> getSongs(Artist artist) throws MPDServerException { List<Album> albums = getAlbums(artist, false); List<Music> songs = new ArrayList<Music>(); for (Album a : albums) { songs.addAll(getSongs(a)); } return songs; } public MPDCommand getSongsCommand(Album album) { String albumname = album.getName(); Artist artist = album.getArtist(); if (null == artist) { // get songs for ANY artist return new MPDCommand(MPDCommand.MPD_CMD_FIND, MPDCommand.MPD_TAG_ALBUM, albumname); } String artistname = artist.getName(); if (album.hasAlbumArtist()) { return new MPDCommand(MPDCommand.MPD_CMD_FIND, MPDCommand.MPD_TAG_ALBUM, albumname, MPDCommand.MPD_TAG_ALBUM_ARTIST, artistname); } else { return new MPDCommand(MPDCommand.MPD_CMD_FIND, MPDCommand.MPD_TAG_ALBUM, albumname, MPDCommand.MPD_TAG_ARTIST, artistname, MPDCommand.MPD_TAG_ALBUM_ARTIST, ""); } } /** * Retrieves statistics for the connected server. * * @return statistics for the connected server. * @throws MPDServerException if an error occur while contacting server. */ public MPDStatistics getStatistics() throws MPDServerException { List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_STATISTICS); return new MPDStatistics(response); } /** * Retrieves status of the connected server. * * @return status of the connected server. * @throws MPDServerException if an error occur while contacting server. */ public MPDStatus getStatus() throws MPDServerException { return getStatus(false); } /** * Retrieves status of the connected server. * * @return status of the connected server. * @throws MPDServerException if an error occur while contacting server. */ public MPDStatus getStatus(boolean forceRefresh) throws MPDServerException { if (forceRefresh || mpdStatus == null || mpdStatus.getState() == null) { if (!isConnected()) { throw new MPDConnectionException("MPD Connection is not established"); } List<String> response = mpdStatusConnection.sendCommand(MPDCommand.MPD_CMD_STATUS); if(response == null) { Log.w(TAG, "No status response from the MPD server."); } else { mpdStatus.updateStatus(response); } } return mpdStatus; } /** * Retrieves current volume. * * @return current volume. * @throws MPDServerException if an error occur while contacting server. */ public int getVolume() throws MPDServerException { return this.getStatus().getVolume(); } /** * Returns true when connected and false when not connected. * * @return true when connected and false when not connected */ public boolean isConnected() { return mpdIdleConnection != null && mpdStatusConnection != null && mpdConnection != null && mpdIdleConnection.isConnected(); } public boolean isMpdConnectionNull() { return (this.mpdConnection == null); } public List<String> listAlbumArtists() throws MPDServerException { return listAlbumArtists(true); } /** * List all album artist names from database. * * @return album artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbumArtists(boolean sortInsensitive) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST); ArrayList<String> result = new ArrayList<String>(); for (String s : response) { String name = s.substring("albumartist: ".length()); result.add(name); } if (sortInsensitive) Collections.sort(result, String.CASE_INSENSITIVE_ORDER); else Collections.sort(result); return result; } public List<String> listAlbumArtists(Genre genre) throws MPDServerException { return listAlbumArtists(genre, true); } /** * List all album artist names from database. * * @return album artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbumArtists(Genre genre, boolean sortInsensitive) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST, MPDCommand.MPD_TAG_GENRE, genre.getName()); ArrayList<String> result = new ArrayList<String>(); for (String s : response) { String name = s.substring("albumartist: ".length()); result.add(name); } if (sortInsensitive) Collections.sort(result, String.CASE_INSENSITIVE_ORDER); else Collections.sort(result); return result; } public List<String[]> listAlbumArtists(List<Album> albums) throws MPDServerException { for (Album a : albums) { mpdConnection.queueCommand(new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST, MPDCommand.MPD_TAG_ARTIST, a.getArtist().getName(), MPDCommand.MPD_TAG_ALBUM, a.getName())); } List<String[]> response = mpdConnection.sendCommandQueueSeparated(); if (response.size() != albums.size()) { Log.d("MPD listAlbumArtists", "ERROR"); return null; } for (int i = 0; i < response.size(); i++) { for (int j = 0; j < response.get(i).length; j++) { response.get(i)[j] = response.get(i)[j].substring("AlbumArtist: ".length()); } } return response; } /** * List all albums from database. * * @return <code>Collection</code> with all album names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbums() throws MPDServerException { return listAlbums(null, false, true); } /** * List all albums from database. * * @param useAlbumArtist use AlbumArtist instead of Artist * @return <code>Collection</code> with all album names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbums(boolean useAlbumArtist) throws MPDServerException { return listAlbums(null, useAlbumArtist, true); } /** * List all albums from a given artist, including an entry for songs with no * album tag. * * @param artist artist to list albums * @param useAlbumArtist use AlbumArtist instead of Artist * @return <code>Collection</code> with all album names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbums(String artist, boolean useAlbumArtist) throws MPDServerException { return listAlbums(artist, useAlbumArtist, true); } /** * List all albums from a given artist. * * @param artist artist to list albums * @param useAlbumArtist use AlbumArtist instead of Artist * @param includeUnknownAlbum include an entry for songs with no album tag * @return <code>Collection</code> with all album names from the given * artist present in database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbums(String artist, boolean useAlbumArtist, boolean includeUnknownAlbum) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); boolean foundSongWithoutAlbum = false; List<String> response = mpdConnection.sendCommand (listAlbumsCommand(artist, useAlbumArtist)); ArrayList<String> result = new ArrayList<String>(); for (String line : response) { String name = line.substring("Album: ".length()); if (name.length() > 0) { result.add(name); } else { foundSongWithoutAlbum = true; } } // add a single blank entry to host all songs without an album set if (includeUnknownAlbum && foundSongWithoutAlbum) { result.add(""); } Collections.sort(result); return result; } /* * get raw command String for listAlbums */ public MPDCommand listAlbumsCommand(String artist, boolean useAlbumArtist) { if (useAlbumArtist) { return new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM, MPDCommand.MPD_TAG_ALBUM_ARTIST, artist); } else { return new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM, artist); } } /** * List all artist names from database. * * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listArtists() throws MPDServerException { return listArtists(true); } /** * List all artist names from database. * * @param sortInsensitive boolean for insensitive sort when true * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listArtists(boolean sortInsensitive) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ARTIST); ArrayList<String> result = new ArrayList<String>(); for (String s : response) { result.add(s.substring("Artist: ".length())); } if (sortInsensitive) Collections.sort(result, String.CASE_INSENSITIVE_ORDER); else Collections.sort(result); return result; } /* * List all albumartist or artist names of all given albums from database. * @return list of array of artist names for each album. * @throws MPDServerException if an error occurs while contacting server. */ public List<String[]> listArtists(List<Album> albums, boolean albumArtist) throws MPDServerException { if (!isConnected()) { throw new MPDServerException("MPD Connection is not established"); } ArrayList<String[]> result = new ArrayList<String[]>(); if (albums == null) { return result; } for (Album a : albums) { // When adding album artist to existing artist check that the artist // matches if (albumArtist && a.getArtist() != null && !a.getArtist().isUnknown()) { mpdConnection.queueCommand (new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST, MPDCommand.MPD_TAG_ALBUM, a.getName(), MPDCommand.MPD_TAG_ARTIST, a.getArtist().getName())); } else { mpdConnection.queueCommand (new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, (albumArtist ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_TAG_ARTIST), MPDCommand.MPD_TAG_ALBUM, a .getName())); } } List<String[]> responses = mpdConnection.sendCommandQueueSeparated(); for (String[] r : responses) { ArrayList<String> albumresult = new ArrayList<String>(); for (String s : r) { String name = s.substring((albumArtist ? "AlbumArtist: " : "Artist: ").length()); albumresult.add(name); } result.add(albumresult.toArray(new String[albumresult.size()])); } return result; } /** * List all artist names from database. * * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listArtists(String genre) throws MPDServerException { return listArtists(genre, true); } /** * List all artist names from database. * * @param sortInsensitive boolean for insensitive sort when true * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listArtists(String genre, boolean sortInsensitive) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ARTIST, MPDCommand.MPD_TAG_GENRE, genre); ArrayList<String> result = new ArrayList<String>(); for (String s : response) { String name = s.substring("Artist: ".length()); result.add(name); } if (sortInsensitive) Collections.sort(result, String.CASE_INSENSITIVE_ORDER); else Collections.sort(result); return result; } /** * List all genre names from database. * * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listGenres() throws MPDServerException { return listGenres(true); } /** * List all genre names from database. * * @param sortInsensitive boolean for insensitive sort when true * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listGenres(boolean sortInsensitive) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_GENRE); ArrayList<String> result = new ArrayList<String>(); for (String s : response) { String name = s.substring("Genre: ".length()); result.add(name); } if (sortInsensitive) Collections.sort(result, String.CASE_INSENSITIVE_ORDER); else Collections.sort(result); return result; } public void movePlaylistSong(String playlistName, int from, int to) throws MPDServerException { getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_MOVE, playlistName, Integer.toString(from), Integer.toString(to)); } /** * Jumps to next playlist track. * * @throws MPDServerException if an error occur while contacting server. */ public void next() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_NEXT); } /** * Pauses/Resumes music playing. * * @throws MPDServerException if an error occur while contacting server. */ public void pause() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_PAUSE); } /** * Starts playing music. * * @throws MPDServerException if an error occur while contacting server. */ public void play() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY); } /** * Plays previous playlist music. * * @throws MPDServerException if an error occur while contacting server.. */ public void previous() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_PREV); } /** * Tells server to refresh database. * * @throws MPDServerException if an error occur while contacting server. */ public void refreshDatabase() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_REFRESH); } /** * Tells server to refresh database. * * @throws MPDServerException if an error occur while contacting server. */ public void refreshDatabase(String folder) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_REFRESH, folder); } public void removeFromPlaylist(String playlistName, Integer pos) throws MPDServerException { getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_DEL, playlistName, Integer.toString(pos)); } /** * Similar to <code>find</code>,<code>search</code> looks for partial * matches in the MPD database. * * @param type type of search. Should be one of the following constants: * MPD_SEARCH_ARTIST, MPD_SEARCH_TITLE, MPD_SEARCH_ALBUM, * MPD_SEARCH_FILENAME * @param string case-insensitive locator string. Anything that contains * <code>string</code> will be returned in the results. * @return a Collection of <code>Music</code>. * @throws MPDServerException if an error occur while contacting server. * @see org.a0z.mpd.Music */ public Collection<Music> search(String type, String string) throws MPDServerException { return genericSearch(MPDCommand.MPD_CMD_SEARCH, type, string); } public List<Music> search(String[] args) throws MPDServerException { return genericSearch(MPDCommand.MPD_CMD_SEARCH, args, true); } /** * Seeks current music to the position. * * @param position song position in seconds * @throws MPDServerException if an error occur while contacting server. */ public void seek(long position) throws MPDServerException { seekById(this.getStatus().getSongId(), position); } /** * Seeks music to the position. * * @param songId music id in playlist. * @param position song position in seconds. * @throws MPDServerException if an error occur while contacting server. */ public void seekById(int songId, long position) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_SEEK_ID, Integer.toString(songId), Long.toString(position)); } /** * Seeks music to the position. * * @param index music position in playlist. * @param position song position in seconds. * @throws MPDServerException if an error occur while contacting server. */ public void seekByIndex(int index, long position) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_SEEK, Integer.toString(index), Long.toString(position)); } /** * Enabled or disable consuming. * * @param consume if true song consuming will be enabled, if false song * consuming will be disabled. * @throws MPDServerException if an error occur while contacting server. */ public void setConsume(boolean consume) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_CONSUME, consume ? "1" : "0"); } /** * Sets cross-fade. * * @param time cross-fade time in seconds. 0 to disable cross-fade. * @throws MPDServerException if an error occur while contacting server. */ public void setCrossfade(int time) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection .sendCommand(MPDCommand.MPD_CMD_CROSSFADE, Integer.toString(Math.max(0, time))); } /** * Enabled or disable random. * * @param random if true random will be enabled, if false random will be * disabled. * @throws MPDServerException if an error occur while contacting server. */ public void setRandom(boolean random) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_RANDOM, random ? "1" : "0"); } /** * Enabled or disable repeating. * * @param repeat if true repeating will be enabled, if false repeating will * be disabled. * @throws MPDServerException if an error occur while contacting server. */ public void setRepeat(boolean repeat) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_REPEAT, repeat ? "1" : "0"); } /** * Enabled or disable single mode. * * @param single if true single mode will be enabled, if false single mode * will be disabled. * @throws MPDServerException if an error occur while contacting server. */ public void setSingle(boolean single) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_SINGLE, single ? "1" : "0"); } /** * Sets volume to <code>volume</code>. * * @param volume new volume value, must be in 0-100 range. * @throws MPDServerException if an error occur while contacting server. */ public void setVolume(int volume) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); int vol = Math.max(MPDCommand.MIN_VOLUME, Math.min(MPDCommand.MAX_VOLUME, volume)); mpdConnection.sendCommand(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol)); } /** * Kills server. * * @throws MPDServerException if an error occur while contacting server. */ public void shutdown() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_KILL); } /** * Skip to song with specified <code>id</code>. * * @param id song id. * @throws MPDServerException if an error occur while contacting server. */ public void skipToId(int id) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY_ID, Integer.toString(id)); } /** * Jumps to track <code>position</code> from playlist. * * @param position track number. * @throws MPDServerException if an error occur while contacting server. * @see #skipToId(int) */ public void skipToPosition(int position) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY, Integer.toString(position)); } /** * Stops music playing. * * @throws MPDServerException if an error occur while contacting server. */ public void stop() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_STOP); } /** * Wait for server changes using "idle" command on the dedicated connection. * * @return Data read from the server. * @throws MPDServerException if an error occur while contacting server */ public List<String> waitForChanges() throws MPDServerException { while (mpdIdleConnection != null && mpdIdleConnection.isConnected()) { List<String> data = mpdIdleConnection .sendAsyncCommand(MPDCommand.MPD_CMD_IDLE); if (data.isEmpty()) { continue; } return data; } throw new MPDConnectionException("IDLE connection lost"); } }
JMPDComm/src/org/a0z/mpd/MPD.java
package org.a0z.mpd; import android.content.Context; import android.util.Log; import org.a0z.mpd.exception.MPDClientException; import org.a0z.mpd.exception.MPDConnectionException; import org.a0z.mpd.exception.MPDServerException; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * MPD Server controller. * * @version $Id: MPD.java 2716 2004-11-20 17:37:20Z galmeida $ */ public class MPD { private final static String TAG = "org.a0z.mpd.MPD"; protected MPDConnection mpdConnection; protected MPDConnection mpdIdleConnection; protected MPDConnection mpdStatusConnection; protected MPDStatus mpdStatus; protected MPDPlaylist playlist; protected Directory rootDirectory; static protected boolean sortByTrackNumber = true; static protected boolean sortAlbumsByYear = false; static protected boolean showArtistAlbumCount = false; static protected boolean showAlbumTrackCount = true; static protected Context applicationContext = null; static public Context getApplicationContext() { return applicationContext; } static public void setApplicationContext(Context context) { applicationContext = context; } static public void setShowAlbumTrackCount(boolean v) { showAlbumTrackCount = v; } static public void setShowArtistAlbumCount(boolean v) { showArtistAlbumCount = v; } static public void setSortAlbumsByYear(boolean v) { sortAlbumsByYear = v; } static public void setSortByTrackNumber(boolean v) { sortByTrackNumber = v; } static public boolean showAlbumTrackCount() { return showAlbumTrackCount; } static public boolean showArtistAlbumCount() { return showArtistAlbumCount; } static public boolean sortAlbumsByYear() { return sortAlbumsByYear; } static public boolean sortByTrackNumber() { return sortByTrackNumber; } /** * Constructs a new MPD server controller without connection. */ public MPD() { this.playlist = new MPDPlaylist(this); this.mpdStatus = new MPDStatus(); this.rootDirectory = Directory.makeRootDirectory(this); } /** * Constructs a new MPD server controller. * * @param server server address or host name * @param port server port * @throws MPDServerException if an error occur while contacting server */ public MPD(InetAddress server, int port, String password) throws MPDServerException { this(); connect(server, port, password); } /** * Constructs a new MPD server controller. * * @param server server address or host name * @param port server port * @throws MPDServerException if an error occur while contacting server * @throws UnknownHostException */ public MPD(String server, int port, String password) throws MPDServerException, UnknownHostException { this(); connect(server, port, password); } public void add(Album album) throws MPDServerException { add(album, false, false); } public void add(final Album album, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { final ArrayList<Music> songs = new ArrayList<Music>(getSongs(album)); getPlaylist().addAll(songs); } catch (MPDServerException e) { e.printStackTrace(); } } }; add(r, replace, play); } public void add(Artist artist) throws MPDServerException { add(artist, false, false); } public void add(final Artist artist, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { final ArrayList<Music> songs = new ArrayList<Music>(getSongs(artist)); getPlaylist().addAll(songs); } catch (MPDServerException e) { e.printStackTrace(); } } }; add(r, replace, play); } public void add(final Directory directory, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { getPlaylist().add(directory); } catch (MPDServerException e) { e.printStackTrace(); } } }; add(r, replace, play); } public void add(final FilesystemTreeEntry music, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { if (music instanceof Music) { getPlaylist().add(music); } else if (music instanceof PlaylistFile) { getPlaylist().load(music.getFullpath()); } } catch (MPDServerException e) { e.printStackTrace(); } } }; add(r, replace, play); } public void add(Music music) throws MPDServerException { add(music, false, false); } /** * Adds songs to the queue. It is possible to request a clear of the current * one, and to start the playback once done. * * @param runnable The runnable that will be responsible of inserting the * songs into the queue * @param replace If true, clears the queue before inserting * @param play If true, starts playing once added * @throws MPDServerException */ public void add(Runnable runnable, boolean replace, boolean play) throws MPDServerException { int oldSize = 0; String status = null; if (replace) { status = getStatus().getState(); stop(); getPlaylist().clear(); } else if (play) { oldSize = getPlaylist().size(); } runnable.run(); if (replace) { if (play || MPDStatus.MPD_STATE_PLAYING.equals(status)) { play(); } } else if (play) { try { int id = getPlaylist().getByIndex(oldSize).getSongId(); skipToId(id); play(); } catch (NullPointerException e) { // If song adding fails, don't crash ! } } } public void add(String playlist) throws MPDServerException { add(playlist, false, false); } public void add(final String playlist, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { getPlaylist().load(playlist); } catch (MPDServerException e) { e.printStackTrace(); } } }; add(r, replace, play); } public void add(final URL stream, boolean replace, boolean play) throws MPDServerException { final Runnable r = new Runnable() { @Override public void run() { try { getPlaylist().add(stream); } catch (MPDServerException | MPDClientException e) { e.printStackTrace(); } } }; add(r, replace, play); } protected void addAlbumPaths(List<Album> albums) { if (albums == null || albums.size() == 0) { return; } for (Album a : albums) { try { List<Music> songs = getFirstTrack(a); if (songs.size() > 0) { a.setPath(songs.get(0).getPath()); } } catch (MPDServerException e) { } } } // Returns a pattern where all punctuation characters are escaped. public void addToPlaylist(String playlistName, Album album) throws MPDServerException { addToPlaylist(playlistName, new ArrayList<Music>(getSongs(album))); } public void addToPlaylist(String playlistName, Artist artist) throws MPDServerException { addToPlaylist(playlistName, new ArrayList<Music>(getSongs(artist))); } public void addToPlaylist(String playlistName, Collection<Music> c) throws MPDServerException { if (null == c || c.size() < 1) { return; } for (Music m : c) { getMpdConnection().queueCommand(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlistName, m.getFullpath()); } getMpdConnection().sendCommandQueue(); } public void addToPlaylist(String playlistName, FilesystemTreeEntry entry) throws MPDServerException { getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlistName, entry.getFullpath()); } public void addToPlaylist(String playlistName, Music music) throws MPDServerException { final ArrayList<Music> songs = new ArrayList<Music>(); songs.add(music); addToPlaylist(playlistName, songs); } /** * Increases or decreases volume by <code>modifier</code> amount. * * @param modifier volume adjustment * @throws MPDServerException if an error occur while contacting server */ public void adjustVolume(int modifier) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); // calculate final volume (clip value with [0, 100]) int vol = getVolume() + modifier; vol = Math.max(MPDCommand.MIN_VOLUME, Math.min(MPDCommand.MAX_VOLUME, vol)); mpdConnection.sendCommand(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol)); } /* * test whether given album is in given genre */ public boolean albumInGenre(Album album, Genre genre) throws MPDServerException { List<String> response; Artist artist = album.getArtist(); response = mpdConnection.sendCommand (new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM, MPDCommand.MPD_TAG_ALBUM, album.getName(), album.hasAlbumArtist() ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_TAG_ARTIST, (artist == null ? "" : artist.getName()), MPDCommand.MPD_TAG_GENRE, genre.getName())); return (response.size() > 0); } /** * Clears error message. * * @throws MPDServerException if an error occur while contacting server. */ public void clearError() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_CLEARERROR); } /** * Connects to a MPD server. * * @param server server address or host name * @param port server port */ public synchronized final void connect(InetAddress server, int port, String password) throws MPDServerException { if (!isConnected()) { this.mpdConnection = new MPDConnectionMultiSocket(server, port, 3, password, 5000); this.mpdIdleConnection = new MPDConnectionMonoSocket(server, port, password, 0); this.mpdStatusConnection = new MPDConnectionMonoSocket(server, port, password, 5000); } } /** * Connects to a MPD server. * * @param server server address or host name * @param port server port * @throws MPDServerException if an error occur while contacting server * @throws UnknownHostException */ public final void connect(String server, int port, String password) throws MPDServerException, UnknownHostException { InetAddress address = InetAddress.getByName(server); connect(address, port, password); } /** * Connects to a MPD server. * * @param server server address or host name and port (server:port) * @throws MPDServerException if an error occur while contacting server * @throws UnknownHostException */ public final void connect(String server, String password) throws MPDServerException, UnknownHostException { int port = MPDCommand.DEFAULT_MPD_PORT; String host; if (server.indexOf(':') != -1) { host = server.substring(0, server.lastIndexOf(':')); port = Integer.parseInt(server.substring(server.lastIndexOf(':') + 1)); } else { host = server; } connect(host, port, password); } public void disableOutput(int id) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTDISABLE, Integer.toString(id)); } /** * Disconnects from server. * * @throws MPDServerException if an error occur while closing connection */ public synchronized void disconnect() throws MPDServerException { MPDServerException ex = null; if (mpdConnection != null && mpdConnection.isConnected()) { try { mpdConnection.sendCommand(MPDCommand.MPD_CMD_CLOSE); } catch (MPDServerException e) { ex = e; } } if (mpdConnection != null && mpdConnection.isConnected()) { try { mpdConnection.disconnect(); } catch (MPDServerException e) { ex = (ex != null) ? ex : e;// Always keep first non null // exception } } if (mpdIdleConnection != null && mpdIdleConnection.isConnected()) { try { mpdIdleConnection.disconnect(); } catch (MPDServerException e) { ex = (ex != null) ? ex : e;// Always keep non null first // exception } } if (mpdStatusConnection != null && mpdStatusConnection.isConnected()) { try { mpdStatusConnection.disconnect(); } catch (MPDServerException e) { ex = (ex != null) ? ex : e;// Always keep non null first // exception } } // TODO: Throw ex } public void enableOutput(int id) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTENABLE, Integer.toString(id)); } /** * Similar to <code>search</code>,<code>find</code> looks for exact matches * in the MPD database. * * @param type type of search. Should be one of the following constants: * MPD_FIND_ARTIST, MPD_FIND_ALBUM * @param string case-insensitive locator string. Anything that exactly * matches <code>string</code> will be returned in the results. * @return a Collection of <code>Music</code> * @throws MPDServerException if an error occur while contacting server * @see org.a0z.mpd.Music */ public List<Music> find(String type, String string) throws MPDServerException { return genericSearch(MPDCommand.MPD_CMD_FIND, type, string); } public List<Music> find(String[] args) throws MPDServerException { return genericSearch(MPDCommand.MPD_CMD_FIND, args, true); } /* * For all given albums, look for albumartists and create as many albums as * there are albumartists, including "" The server call can be slow for long * album lists */ protected void fixAlbumArtists(List<Album> albums) { if (albums == null || albums.size() == 0) { return; } List<String[]> albumartists = null; try { albumartists = listAlbumArtists(albums); } catch (MPDServerException e) { } if (albumartists == null || albumartists.size() != albums.size()) { return; } List<Album> splitalbums = new ArrayList<Album>(); int i = 0; for (Album a : albums) { String[] aartists = albumartists.get(i); if (aartists.length > 0) { Arrays.sort(aartists); // make sure "" is the first one if (!"".equals(aartists[0])) { // one albumartist, fix this // album a.setArtist(new Artist(aartists[0])); a.setHasAlbumArtist(true); } // do nothing if albumartist is "" if (aartists.length > 1) { // it's more than one album, insert for (int n = 1; n < aartists.length; n++) { Album newalbum = new Album(a.getName(), new Artist(aartists[n]), true); splitalbums.add(newalbum); } } } i++; } albums.addAll(splitalbums); } protected List<Music> genericSearch(String searchCommand, String args[], boolean sort) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); return Music.getMusicFromList(mpdConnection.sendCommand(searchCommand, args), sort); } protected List<Music> genericSearch(String searchCommand, String type, String strToFind) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(searchCommand, type, strToFind); return Music.getMusicFromList(response, true); } public int getAlbumCount(Artist artist, boolean useAlbumArtistTag) throws MPDServerException { return listAlbums(artist.getName(), useAlbumArtistTag).size(); } public int getAlbumCount(String artist, boolean useAlbumArtistTag) throws MPDServerException { if (mpdConnection == null) { throw new MPDServerException("MPD Connection is not established"); } return listAlbums(artist, useAlbumArtistTag).size(); } protected void getAlbumDetails(List<Album> albums, boolean findYear) throws MPDServerException { for (Album a : albums) { mpdConnection.queueCommand(getAlbumDetailsCommand(a)); } List<String[]> response = mpdConnection.sendCommandQueueSeparated(); if (response.size() != albums.size()) { // Log.d("MPD AlbumDetails", "non matching results "+ // response.size()+" != "+ albums.size()); return; } for (int i = 0; i < response.size(); i++) { String[] list = response.get(i); Album a = albums.get(i); for (String line : list) { if (line.startsWith("songs: ")) { a.setSongCount(Long.parseLong(line.substring("songs: ".length()))); } else if (line.startsWith("playtime: ")) { a.setDuration(Long.parseLong(line.substring("playtime: ".length()))); } } if (findYear) { List<Music> songs = getFirstTrack(a); if (null != songs && !songs.isEmpty()) { a.setYear(songs.get(0).getDate()); a.setPath(songs.get(0).getPath()); } } } } protected MPDCommand getAlbumDetailsCommand(Album album) throws MPDServerException { if (album.hasAlbumArtist()) { return new MPDCommand(MPDCommand.MPD_CMD_COUNT, MPDCommand.MPD_TAG_ALBUM, album.getName(), MPDCommand.MPD_TAG_ALBUM_ARTIST, album.getArtist().getName()); } else { // only get albums without albumartist return new MPDCommand(MPDCommand.MPD_CMD_COUNT, MPDCommand.MPD_TAG_ALBUM, album.getName(), MPDCommand.MPD_TAG_ARTIST, album.getArtist().getName(), MPDCommand.MPD_TAG_ALBUM_ARTIST, ""); } } public List<Album> getAlbums(Artist artist, boolean trackCountNeeded) throws MPDServerException { List<Album> a_albums = getAlbums(artist, trackCountNeeded, false); // 1. the null artist list already contains all albums // 2. the "unknown artist" should not list unknown albumartists if (artist != null && !artist.isUnknown()) { return Item.merged(a_albums, getAlbums(artist, trackCountNeeded, true)); } return a_albums; } public List<Album> getAlbums(Artist artist, boolean trackCountNeeded, boolean useAlbumArtist) throws MPDServerException { if (artist == null) { return getAllAlbums(trackCountNeeded); } List<String> albumNames = listAlbums(artist.getName(), useAlbumArtist); List<Album> albums = new ArrayList<Album>(); if (null == albumNames || albumNames.isEmpty()) { return albums; } for (String album : albumNames) { albums.add(new Album(album, artist, useAlbumArtist)); } if (!useAlbumArtist) { fixAlbumArtists(albums); } // after fixing albumartists if (((MPD.showAlbumTrackCount() && trackCountNeeded) || MPD.sortAlbumsByYear())) { getAlbumDetails(albums, MPD.sortAlbumsByYear()); } if (!MPD.sortAlbumsByYear()) { addAlbumPaths(albums); } Collections.sort(albums); return albums; } /** * @return all Albums */ public List<Album> getAllAlbums(boolean trackCountNeeded) throws MPDServerException { List<String> albumNames = listAlbums(); List<Album> albums = new ArrayList<Album>(); if (null == albumNames || albumNames.isEmpty()) { return albums; // empty list } for (String album : albumNames) { albums.add(new Album(album, null)); } Collections.sort(albums); return albums; } public List<Artist> getArtists() throws MPDServerException { return Item.merged(getArtists(true), getArtists(false)); } public List<Artist> getArtists(boolean useAlbumArtist) throws MPDServerException { List<String> artistNames = useAlbumArtist ? listAlbumArtists() : listArtists(true); List<Artist> artists = new ArrayList<Artist>(); if (null != artistNames && !artistNames.isEmpty()) { for (String artist : artistNames) { artists.add(new Artist(artist, MPD.showArtistAlbumCount() ? getAlbumCount(artist, useAlbumArtist) : 0)); } } Collections.sort(artists); return artists; } public List<Artist> getArtists(Genre genre) throws MPDServerException { return Item.merged(getArtists(genre, false), getArtists(genre, true)); } public List<Artist> getArtists(Genre genre, boolean useAlbumArtist) throws MPDServerException { List<String> artistNames = useAlbumArtist ? listAlbumArtists(genre) : listArtists( genre.getName(), true); List<Artist> artists = new ArrayList<Artist>(); if (null != artistNames && !artistNames.isEmpty()) { for (String artist : artistNames) { artists.add(new Artist(artist, MPD.showArtistAlbumCount() ? getAlbumCount(artist, useAlbumArtist) : 0)); } } Collections.sort(artists); return artists; } /** * Retrieves a database directory listing of the base of the database * directory path. * * @return a <code>Collection</code> of <code>Music</code> and * <code>Directory</code> representing directory entries. * @throws MPDServerException if an error occur while contacting server. * @see Music * @see Directory */ public List<FilesystemTreeEntry> getDir() throws MPDServerException { return getDir(null); } /** * Retrieves a database directory listing of <code>path</code> directory. * * @param path Directory to be listed. * @return a <code>Collection</code> of <code>Music</code> and * <code>Directory</code> representing directory entries. * @throws MPDServerException if an error occur while contacting server. * @see Music * @see Directory */ public List<FilesystemTreeEntry> getDir(String path) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LSDIR, path); LinkedList<String> lineCache = new LinkedList<String>(); LinkedList<FilesystemTreeEntry> result = new LinkedList<FilesystemTreeEntry>(); for (String line : response) { // If we detect a new file element and the line cache isn't empty // dump the linecache into a music item if (line.startsWith("file: ") && lineCache.size() > 0) { result.add(new Music(lineCache)); lineCache.clear(); } if (line.startsWith("playlist: ")) { lineCache.clear(); line = line.substring("playlist: ".length()); result.add(new PlaylistFile(line)); } else if (line.startsWith("directory: ")) { lineCache.clear(); line = line.substring("directory: ".length()); result.add(rootDirectory.makeDirectory(line)); } else { lineCache.add(line); } } if (lineCache.size() > 0) { // Don't create a music object if the line cache does not contain any // It can happen for playlist and directory items with supplementary information for (String line : lineCache) { if (line.startsWith("file: ")) { result.add(new Music(lineCache)); break; } } } return result; } protected List<Music> getFirstTrack(Album album) throws MPDServerException { Artist artist = album.getArtist(); String[] args = new String[6]; args[0] = (artist == null ? "" : album.hasAlbumArtist() ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_TAG_ARTIST); args[1] = (artist == null ? "" : artist.getName()); args[2] = MPDCommand.MPD_TAG_ALBUM; args[3] = album.getName(); args[4] = "track"; args[5] = "1"; List<Music> songs = find(args); if (null == songs || songs.isEmpty()) { args[5] = "01"; songs = find(args); } if (null == songs || songs.isEmpty()) { args[5] = "1"; songs = search(args); } if (null == songs || songs.isEmpty()) { String[] args2 = Arrays.copyOf(args, 4); // find all tracks songs = find(args2); } return songs; } public List<Genre> getGenres() throws MPDServerException { List<String> genreNames = listGenres(); List<Genre> genres = null; if (null != genreNames && !genreNames.isEmpty()) { genres = new ArrayList<Genre>(); for (String genre : genreNames) { genres.add(new Genre(genre)); } } if (null != genres) { Collections.sort(genres); } return genres; } /** * Retrieves <code>MPDConnection</code>. * * @return <code>MPDConnection</code>. */ public MPDConnection getMpdConnection() { return this.mpdConnection; } MPDConnection getMpdIdleConnection() { return this.mpdIdleConnection; } /** * Returns MPD server version. * * @return MPD Server version. */ public String getMpdVersion() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); int[] version = mpdIdleConnection.getMpdVersion(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < version.length; i++) { sb.append(version[i]); if (i < (version.length - 1)) sb.append("."); } return sb.toString(); } /** * Returns the available outputs * * @return List of available outputs */ public List<MPDOutput> getOutputs() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<MPDOutput> result = new LinkedList<MPDOutput>(); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_OUTPUTS); LinkedList<String> lineCache = new LinkedList<String>(); for (String line : response) { if (line.startsWith("outputid: ")) { if (lineCache.size() != 0) { result.add(new MPDOutput(lineCache)); lineCache.clear(); } } lineCache.add(line); } if (lineCache.size() != 0) { result.add(new MPDOutput(lineCache)); } return result; } /** * Retrieves <code>playlist</code>. * * @return playlist. */ public MPDPlaylist getPlaylist() { return this.playlist; } /** * Returns a list of all available playlists */ public List<Item> getPlaylists() throws MPDServerException { return getPlaylists(false); } /** * Returns a list of all available playlists * * @param sort whether the return list should be sorted */ public List<Item> getPlaylists(boolean sort) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<Item> result = new ArrayList<Item>(); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LISTPLAYLISTS); for (String line : response) { if (line.startsWith("playlist")) result.add(new Playlist(line.substring("playlist: ".length()))); } if (sort) Collections.sort(result); return result; } public List<Music> getPlaylistSongs(String playlistName) throws MPDServerException { String args[] = new String[1]; args[0] = playlistName; List<Music> music = genericSearch(MPDCommand.MPD_CMD_PLAYLIST_INFO, args, false); for (int i = 0; i < music.size(); ++i) { music.get(i).setSongId(i); } return music; } /** * Retrieves root directory. * * @return root directory. */ public Directory getRootDirectory() { return rootDirectory; } public List<Music> getSongs(Album album) throws MPDServerException { List<Music> songs = Music.getMusicFromList (getMpdConnection().sendCommand(getSongsCommand(album)), true); if (album.hasAlbumArtist()) { // remove songs that don't have this albumartist // (mpd >=0.18 puts them in) String artistname = album.getArtist().getName(); for (int i = songs.size() - 1; i >= 0; i--) { if (!(artistname.equals(songs.get(i).getAlbumArtist()))) { songs.remove(i); } } } if (null != songs) { Collections.sort(songs); } return songs; } public List<Music> getSongs(Artist artist) throws MPDServerException { List<Album> albums = getAlbums(artist, false); List<Music> songs = new ArrayList<Music>(); for (Album a : albums) { songs.addAll(getSongs(a)); } return songs; } public MPDCommand getSongsCommand(Album album) { String albumname = album.getName(); Artist artist = album.getArtist(); if (null == artist) { // get songs for ANY artist return new MPDCommand(MPDCommand.MPD_CMD_FIND, MPDCommand.MPD_TAG_ALBUM, albumname); } String artistname = artist.getName(); if (album.hasAlbumArtist()) { return new MPDCommand(MPDCommand.MPD_CMD_FIND, MPDCommand.MPD_TAG_ALBUM, albumname, MPDCommand.MPD_TAG_ALBUM_ARTIST, artistname); } else { return new MPDCommand(MPDCommand.MPD_CMD_FIND, MPDCommand.MPD_TAG_ALBUM, albumname, MPDCommand.MPD_TAG_ARTIST, artistname, MPDCommand.MPD_TAG_ALBUM_ARTIST, ""); } } /** * Retrieves statistics for the connected server. * * @return statistics for the connected server. * @throws MPDServerException if an error occur while contacting server. */ public MPDStatistics getStatistics() throws MPDServerException { List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_STATISTICS); return new MPDStatistics(response); } /** * Retrieves status of the connected server. * * @return status of the connected server. * @throws MPDServerException if an error occur while contacting server. */ public MPDStatus getStatus() throws MPDServerException { return getStatus(false); } /** * Retrieves status of the connected server. * * @return status of the connected server. * @throws MPDServerException if an error occur while contacting server. */ public MPDStatus getStatus(boolean forceRefresh) throws MPDServerException { if (forceRefresh || mpdStatus == null || mpdStatus.getState() == null) { if (!isConnected()) { throw new MPDConnectionException("MPD Connection is not established"); } List<String> response = mpdStatusConnection.sendCommand(MPDCommand.MPD_CMD_STATUS); if(response == null) { Log.w(TAG, "No status response from the MPD server."); } else { mpdStatus.updateStatus(response); } } return mpdStatus; } /** * Retrieves current volume. * * @return current volume. * @throws MPDServerException if an error occur while contacting server. */ public int getVolume() throws MPDServerException { return this.getStatus().getVolume(); } /** * Returns true when connected and false when not connected. * * @return true when connected and false when not connected */ public boolean isConnected() { return mpdIdleConnection != null && mpdStatusConnection != null && mpdConnection != null && mpdIdleConnection.isConnected(); } public boolean isMpdConnectionNull() { return (this.mpdConnection == null); } public List<String> listAlbumArtists() throws MPDServerException { return listAlbumArtists(true); } /** * List all album artist names from database. * * @return album artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbumArtists(boolean sortInsensitive) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST); ArrayList<String> result = new ArrayList<String>(); for (String s : response) { String name = s.substring("albumartist: ".length()); result.add(name); } if (sortInsensitive) Collections.sort(result, String.CASE_INSENSITIVE_ORDER); else Collections.sort(result); return result; } public List<String> listAlbumArtists(Genre genre) throws MPDServerException { return listAlbumArtists(genre, true); } /** * List all album artist names from database. * * @return album artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbumArtists(Genre genre, boolean sortInsensitive) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST, MPDCommand.MPD_TAG_GENRE, genre.getName()); ArrayList<String> result = new ArrayList<String>(); for (String s : response) { String name = s.substring("albumartist: ".length()); result.add(name); } if (sortInsensitive) Collections.sort(result, String.CASE_INSENSITIVE_ORDER); else Collections.sort(result); return result; } public List<String[]> listAlbumArtists(List<Album> albums) throws MPDServerException { for (Album a : albums) { mpdConnection.queueCommand(new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST, MPDCommand.MPD_TAG_ARTIST, a.getArtist().getName(), MPDCommand.MPD_TAG_ALBUM, a.getName())); } List<String[]> response = mpdConnection.sendCommandQueueSeparated(); if (response.size() != albums.size()) { Log.d("MPD listAlbumArtists", "ERROR"); return null; } for (int i = 0; i < response.size(); i++) { for (int j = 0; j < response.get(i).length; j++) { response.get(i)[j] = response.get(i)[j].substring("AlbumArtist: ".length()); } } return response; } /** * List all albums from database. * * @return <code>Collection</code> with all album names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbums() throws MPDServerException { return listAlbums(null, false, true); } /** * List all albums from database. * * @param useAlbumArtist use AlbumArtist instead of Artist * @return <code>Collection</code> with all album names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbums(boolean useAlbumArtist) throws MPDServerException { return listAlbums(null, useAlbumArtist, true); } /** * List all albums from a given artist, including an entry for songs with no * album tag. * * @param artist artist to list albums * @param useAlbumArtist use AlbumArtist instead of Artist * @return <code>Collection</code> with all album names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbums(String artist, boolean useAlbumArtist) throws MPDServerException { return listAlbums(artist, useAlbumArtist, true); } /** * List all albums from a given artist. * * @param artist artist to list albums * @param useAlbumArtist use AlbumArtist instead of Artist * @param includeUnknownAlbum include an entry for songs with no album tag * @return <code>Collection</code> with all album names from the given * artist present in database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listAlbums(String artist, boolean useAlbumArtist, boolean includeUnknownAlbum) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); boolean foundSongWithoutAlbum = false; List<String> response = mpdConnection.sendCommand (listAlbumsCommand(artist, useAlbumArtist)); ArrayList<String> result = new ArrayList<String>(); for (String line : response) { String name = line.substring("Album: ".length()); if (name.length() > 0) { result.add(name); } else { foundSongWithoutAlbum = true; } } // add a single blank entry to host all songs without an album set if (includeUnknownAlbum && foundSongWithoutAlbum) { result.add(""); } Collections.sort(result); return result; } /* * get raw command String for listAlbums */ public MPDCommand listAlbumsCommand(String artist, boolean useAlbumArtist) { if (useAlbumArtist) { return new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM, MPDCommand.MPD_TAG_ALBUM_ARTIST, artist); } else { return new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM, artist); } } /** * List all artist names from database. * * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listArtists() throws MPDServerException { return listArtists(true); } /** * List all artist names from database. * * @param sortInsensitive boolean for insensitive sort when true * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listArtists(boolean sortInsensitive) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ARTIST); ArrayList<String> result = new ArrayList<String>(); for (String s : response) { result.add(s.substring("Artist: ".length())); } if (sortInsensitive) Collections.sort(result, String.CASE_INSENSITIVE_ORDER); else Collections.sort(result); return result; } /* * List all albumartist or artist names of all given albums from database. * @return list of array of artist names for each album. * @throws MPDServerException if an error occurs while contacting server. */ public List<String[]> listArtists(List<Album> albums, boolean albumArtist) throws MPDServerException { if (!isConnected()) { throw new MPDServerException("MPD Connection is not established"); } ArrayList<String[]> result = new ArrayList<String[]>(); if (albums == null) { return result; } for (Album a : albums) { // When adding album artist to existing artist check that the artist // matches if (albumArtist && a.getArtist() != null && !a.getArtist().isUnknown()) { mpdConnection.queueCommand (new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ALBUM_ARTIST, MPDCommand.MPD_TAG_ALBUM, a.getName(), MPDCommand.MPD_TAG_ARTIST, a.getArtist().getName())); } else { mpdConnection.queueCommand (new MPDCommand(MPDCommand.MPD_CMD_LIST_TAG, (albumArtist ? MPDCommand.MPD_TAG_ALBUM_ARTIST : MPDCommand.MPD_TAG_ARTIST), MPDCommand.MPD_TAG_ALBUM, a .getName())); } } List<String[]> responses = mpdConnection.sendCommandQueueSeparated(); for (String[] r : responses) { ArrayList<String> albumresult = new ArrayList<String>(); for (String s : r) { String name = s.substring((albumArtist ? "AlbumArtist: " : "Artist: ").length()); albumresult.add(name); } result.add(albumresult.toArray(new String[albumresult.size()])); } return result; } /** * List all artist names from database. * * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listArtists(String genre) throws MPDServerException { return listArtists(genre, true); } /** * List all artist names from database. * * @param sortInsensitive boolean for insensitive sort when true * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listArtists(String genre, boolean sortInsensitive) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_ARTIST, MPDCommand.MPD_TAG_GENRE, genre); ArrayList<String> result = new ArrayList<String>(); for (String s : response) { String name = s.substring("Artist: ".length()); result.add(name); } if (sortInsensitive) Collections.sort(result, String.CASE_INSENSITIVE_ORDER); else Collections.sort(result); return result; } /** * List all genre names from database. * * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listGenres() throws MPDServerException { return listGenres(true); } /** * List all genre names from database. * * @param sortInsensitive boolean for insensitive sort when true * @return artist names from database. * @throws MPDServerException if an error occur while contacting server. */ public List<String> listGenres(boolean sortInsensitive) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); List<String> response = mpdConnection.sendCommand(MPDCommand.MPD_CMD_LIST_TAG, MPDCommand.MPD_TAG_GENRE); ArrayList<String> result = new ArrayList<String>(); for (String s : response) { String name = s.substring("Genre: ".length()); result.add(name); } if (sortInsensitive) Collections.sort(result, String.CASE_INSENSITIVE_ORDER); else Collections.sort(result); return result; } public void movePlaylistSong(String playlistName, int from, int to) throws MPDServerException { getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_MOVE, playlistName, Integer.toString(from), Integer.toString(to)); } /** * Jumps to next playlist track. * * @throws MPDServerException if an error occur while contacting server. */ public void next() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_NEXT); } /** * Pauses/Resumes music playing. * * @throws MPDServerException if an error occur while contacting server. */ public void pause() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_PAUSE); } /** * Starts playing music. * * @throws MPDServerException if an error occur while contacting server. */ public void play() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY); } /** * Plays previous playlist music. * * @throws MPDServerException if an error occur while contacting server.. */ public void previous() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_PREV); } /** * Tells server to refresh database. * * @throws MPDServerException if an error occur while contacting server. */ public void refreshDatabase() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_REFRESH); } /** * Tells server to refresh database. * * @throws MPDServerException if an error occur while contacting server. */ public void refreshDatabase(String folder) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_REFRESH, folder); } public void removeFromPlaylist(String playlistName, Integer pos) throws MPDServerException { getMpdConnection().sendCommand(MPDCommand.MPD_CMD_PLAYLIST_DEL, playlistName, Integer.toString(pos)); } /** * Similar to <code>find</code>,<code>search</code> looks for partial * matches in the MPD database. * * @param type type of search. Should be one of the following constants: * MPD_SEARCH_ARTIST, MPD_SEARCH_TITLE, MPD_SEARCH_ALBUM, * MPD_SEARCH_FILENAME * @param string case-insensitive locator string. Anything that contains * <code>string</code> will be returned in the results. * @return a Collection of <code>Music</code>. * @throws MPDServerException if an error occur while contacting server. * @see org.a0z.mpd.Music */ public Collection<Music> search(String type, String string) throws MPDServerException { return genericSearch(MPDCommand.MPD_CMD_SEARCH, type, string); } public List<Music> search(String[] args) throws MPDServerException { return genericSearch(MPDCommand.MPD_CMD_SEARCH, args, true); } /** * Seeks current music to the position. * * @param position song position in seconds * @throws MPDServerException if an error occur while contacting server. */ public void seek(long position) throws MPDServerException { seekById(this.getStatus().getSongId(), position); } /** * Seeks music to the position. * * @param songId music id in playlist. * @param position song position in seconds. * @throws MPDServerException if an error occur while contacting server. */ public void seekById(int songId, long position) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_SEEK_ID, Integer.toString(songId), Long.toString(position)); } /** * Seeks music to the position. * * @param index music position in playlist. * @param position song position in seconds. * @throws MPDServerException if an error occur while contacting server. */ public void seekByIndex(int index, long position) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_SEEK, Integer.toString(index), Long.toString(position)); } /** * Enabled or disable consuming. * * @param consume if true song consuming will be enabled, if false song * consuming will be disabled. * @throws MPDServerException if an error occur while contacting server. */ public void setConsume(boolean consume) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_CONSUME, consume ? "1" : "0"); } /** * Sets cross-fade. * * @param time cross-fade time in seconds. 0 to disable cross-fade. * @throws MPDServerException if an error occur while contacting server. */ public void setCrossfade(int time) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection .sendCommand(MPDCommand.MPD_CMD_CROSSFADE, Integer.toString(Math.max(0, time))); } /** * Enabled or disable random. * * @param random if true random will be enabled, if false random will be * disabled. * @throws MPDServerException if an error occur while contacting server. */ public void setRandom(boolean random) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_RANDOM, random ? "1" : "0"); } /** * Enabled or disable repeating. * * @param repeat if true repeating will be enabled, if false repeating will * be disabled. * @throws MPDServerException if an error occur while contacting server. */ public void setRepeat(boolean repeat) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_REPEAT, repeat ? "1" : "0"); } /** * Enabled or disable single mode. * * @param single if true single mode will be enabled, if false single mode * will be disabled. * @throws MPDServerException if an error occur while contacting server. */ public void setSingle(boolean single) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_SINGLE, single ? "1" : "0"); } /** * Sets volume to <code>volume</code>. * * @param volume new volume value, must be in 0-100 range. * @throws MPDServerException if an error occur while contacting server. */ public void setVolume(int volume) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); int vol = Math.max(MPDCommand.MIN_VOLUME, Math.min(MPDCommand.MAX_VOLUME, volume)); mpdConnection.sendCommand(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol)); } /** * Kills server. * * @throws MPDServerException if an error occur while contacting server. */ public void shutdown() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_KILL); } /** * Skip to song with specified <code>id</code>. * * @param id song id. * @throws MPDServerException if an error occur while contacting server. */ public void skipToId(int id) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY_ID, Integer.toString(id)); } /** * Jumps to track <code>position</code> from playlist. * * @param position track number. * @throws MPDServerException if an error occur while contacting server. * @see #skipToId(int) */ public void skipToPosition(int position) throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_PLAY, Integer.toString(position)); } /** * Stops music playing. * * @throws MPDServerException if an error occur while contacting server. */ public void stop() throws MPDServerException { if (!isConnected()) throw new MPDServerException("MPD Connection is not established"); mpdConnection.sendCommand(MPDCommand.MPD_CMD_STOP); } /** * Wait for server changes using "idle" command on the dedicated connection. * * @return Data read from the server. * @throws MPDServerException if an error occur while contacting server */ public List<String> waitForChanges() throws MPDServerException { while (mpdIdleConnection != null && mpdIdleConnection.isConnected()) { List<String> data = mpdIdleConnection .sendAsyncCommand(MPDCommand.MPD_CMD_IDLE); if (data.isEmpty()) { continue; } return data; } throw new MPDConnectionException("IDLE connection lost"); } }
MPD.java: Don't change MPD state when replacing on the playlist. While playing if 'Add, Replace and Play' or 'Add and replace' are selected, don't stop, clear, add and play. Rather than invoke a MPD state change, move the current playing playlist queue item to queue postition 0, then remove the remaining playlist items, add the replacement playlist queue items, select the next playlist item, then remove song 0. It occurs in the same amount of time and the play interruption is minimized. This behaviour causes a track change listener emit rather than state change.
JMPDComm/src/org/a0z/mpd/MPD.java
MPD.java: Don't change MPD state when replacing on the playlist.
<ide><path>MPDComm/src/org/a0z/mpd/MPD.java <ide> <ide> package org.a0z.mpd; <del> <del>import android.content.Context; <del>import android.util.Log; <ide> <ide> import org.a0z.mpd.exception.MPDClientException; <ide> import org.a0z.mpd.exception.MPDConnectionException; <ide> import org.a0z.mpd.exception.MPDServerException; <add> <add>import android.content.Context; <add>import android.util.Log; <ide> <ide> import java.net.InetAddress; <ide> import java.net.URL; <ide> /** <ide> * Adds songs to the queue. It is possible to request a clear of the current <ide> * one, and to start the playback once done. <del> * <add> * <ide> * @param runnable The runnable that will be responsible of inserting the <del> * songs into the queue <del> * @param replace If true, clears the queue before inserting <del> * @param play If true, starts playing once added <del> * @throws MPDServerException <add> * songs into the queue <add> * @param replace If true, replaces the entire playlist queue with the added files <add> * @param play If true, starts playing once added <ide> */ <ide> public void add(Runnable runnable, boolean replace, boolean play) throws MPDServerException { <del> int oldSize = 0; <del> String status = null; <add> int playPos = 0; <add> final boolean isPlaying = MPDStatus.MPD_STATE_PLAYING.equals(getStatus().getState()); <add> <ide> if (replace) { <del> status = getStatus().getState(); <del> stop(); <del> getPlaylist().clear(); <add> if (isPlaying) { <add> playPos = 1; <add> getPlaylist().crop(); <add> } else { <add> getPlaylist().clear(); <add> } <ide> } else if (play) { <del> oldSize = getPlaylist().size(); <add> playPos = getPlaylist().size(); <ide> } <ide> <ide> runnable.run(); <ide> <del> if (replace) { <del> if (play || MPDStatus.MPD_STATE_PLAYING.equals(status)) { <del> play(); <del> } <del> } else if (play) { <add> if (play || (replace && isPlaying)) { <add> skipToPosition(playPos); <add> } <add> <add> /** Finally, clean up the last playing song. */ <add> if (replace && isPlaying) { <ide> try { <del> int id = getPlaylist().getByIndex(oldSize).getSongId(); <del> skipToId(id); <del> play(); <del> } catch (NullPointerException e) { <del> // If song adding fails, don't crash ! <add> getPlaylist().removeByIndex(0); <add> } catch (MPDServerException e) { <add> Log.d(TAG, "Remove by index failed.", e); <ide> } <ide> } <ide> }
Java
apache-2.0
0924ed1241ec67282082fd3b977f127d7f229b74
0
apache/commons-validator,apache/commons-validator,apache/commons-validator
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import static org.junit.Assert.*; import org.apache.commons.validator.ResultPair; import org.junit.Before; import org.junit.Test; /** * Performs Validation Test for url validations. * * @version $Revision$ */ public class UrlValidatorTest { private final boolean printStatus = false; private final boolean printIndex = false;//print index that indicates current scheme,host,port,path, query test were using. @Before public void setUp() { for (int index = 0; index < testPartsIndex.length - 1; index++) { testPartsIndex[index] = 0; } } @Test public void testIsValid() { testIsValid(testUrlParts, UrlValidator.ALLOW_ALL_SCHEMES); setUp(); long options = UrlValidator.ALLOW_2_SLASHES + UrlValidator.ALLOW_ALL_SCHEMES + UrlValidator.NO_FRAGMENTS; testIsValid(testUrlPartsOptions, options); } @Test public void testIsValidScheme() { if (printStatus) { System.out.print("\n testIsValidScheme() "); } //UrlValidator urlVal = new UrlValidator(schemes,false,false,false); UrlValidator urlVal = new UrlValidator(schemes, 0); for (int sIndex = 0; sIndex < testScheme.length; sIndex++) { ResultPair testPair = testScheme[sIndex]; boolean result = urlVal.isValidScheme(testPair.item); assertEquals(testPair.item, testPair.valid, result); if (printStatus) { if (result == testPair.valid) { System.out.print('.'); } else { System.out.print('X'); } } } if (printStatus) { System.out.println(); } } /** * Create set of tests by taking the testUrlXXX arrays and * running through all possible permutations of their combinations. * * @param testObjects Used to create a url. */ public void testIsValid(Object[] testObjects, long options) { UrlValidator urlVal = new UrlValidator(null, null, options); assertTrue(urlVal.isValid("http://www.google.com")); assertTrue(urlVal.isValid("http://www.google.com/")); int statusPerLine = 60; int printed = 0; if (printIndex) { statusPerLine = 6; } do { StringBuilder testBuffer = new StringBuilder(); boolean expected = true; for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) { int index = testPartsIndex[testPartsIndexIndex]; ResultPair[] part = (ResultPair[]) testObjects[testPartsIndexIndex]; testBuffer.append(part[index].item); expected &= part[index].valid; } String url = testBuffer.toString(); boolean result = urlVal.isValid(url); assertEquals(url, expected, result); if (printStatus) { if (printIndex) { System.out.print(testPartsIndextoString()); } else { if (result == expected) { System.out.print('.'); } else { System.out.print('X'); } } printed++; if (printed == statusPerLine) { System.out.println(); printed = 0; } } } while (incrementTestPartsIndex(testPartsIndex, testObjects)); if (printStatus) { System.out.println(); } } @Test public void testValidator202() { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); assertTrue(urlValidator.isValid("http://l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.org")); } @Test public void testValidator204() { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("http://tech.yahoo.com/rc/desktops/102;_ylt=Ao8yevQHlZ4On0O3ZJGXLEQFLZA5")); } @Test public void testValidator218() { UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); assertTrue("parentheses should be valid in URLs", validator.isValid("http://somewhere.com/pathxyz/file(1).html")); } @Test public void testValidator235() { String version = System.getProperty("java.version"); if (version.compareTo("1.6") < 0) { System.out.println("Cannot run Unicode IDN tests"); return; // Cannot run the test } UrlValidator validator = new UrlValidator(); assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("http://xn--d1abbgf6aiiy.xn--p1ai")); assertTrue("президент.рф should validate", validator.isValid("http://президент.рф")); assertTrue("www.b\u00fccher.ch should validate", validator.isValid("http://www.b\u00fccher.ch")); assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("http://www.\uFFFD.ch")); assertTrue("www.b\u00fccher.ch should validate", validator.isValid("ftp://www.b\u00fccher.ch")); assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("ftp://www.\uFFFD.ch")); } @Test public void testValidator248() { RegexValidator regex = new RegexValidator(new String[] {"localhost", ".*\\.my-testing"}); UrlValidator validator = new UrlValidator(regex, 0); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); assertTrue("first.my-testing should validate", validator.isValid("http://first.my-testing/test/index.html")); assertTrue("sup3r.my-testing should validate", validator.isValid("http://sup3r.my-testing/test/index.html")); assertFalse("broke.my-test should not validate", validator.isValid("http://broke.my-test/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); // Now check using options validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); assertTrue("machinename URL should validate", validator.isValid("http://machinename/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); } @Test public void testValidator288() { UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("hostname should validate", validator.isValid("http://hostname")); assertTrue("hostname with path should validate", validator.isValid("http://hostname/test/index.html")); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); assertFalse("first.my-testing should not validate", validator.isValid("http://first.my-testing/test/index.html")); assertFalse("broke.hostname should not validate", validator.isValid("http://broke.hostname/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); // Turn it off, and check validator = new UrlValidator(0); assertFalse("hostname should no longer validate", validator.isValid("http://hostname")); assertFalse("localhost URL should no longer validate", validator.isValid("http://localhost/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); } @Test public void testValidator276() { // file:// isn't allowed by default UrlValidator validator = new UrlValidator(); assertTrue("http://apache.org/ should be allowed by default", validator.isValid("http://www.apache.org/test/index.html")); assertFalse("file:///c:/ shouldn't be allowed by default", validator.isValid("file:///C:/some.file")); assertFalse("file:///c:\\ shouldn't be allowed by default", validator.isValid("file:///C:\\some.file")); assertFalse("file:///etc/ shouldn't be allowed by default", validator.isValid("file:///etc/hosts")); assertFalse("file://localhost/etc/ shouldn't be allowed by default", validator.isValid("file://localhost/etc/hosts")); assertFalse("file://localhost/c:/ shouldn't be allowed by default", validator.isValid("file://localhost/c:/some.file")); // Turn it on, and check // Note - we need to enable local urls when working with file: validator = new UrlValidator(new String[] {"http","file"}, UrlValidator.ALLOW_LOCAL_URLS); assertTrue("http://apache.org/ should be allowed by default", validator.isValid("http://www.apache.org/test/index.html")); assertTrue("file:///c:/ should now be allowed", validator.isValid("file:///C:/some.file")); assertFalse("file:///c:\\ should not be allowed", // Only allow forward slashes validator.isValid("file:///C:\\some.file")); assertTrue("file:///etc/ should now be allowed", validator.isValid("file:///etc/hosts")); assertTrue("file://localhost/etc/ should now be allowed", validator.isValid("file://localhost/etc/hosts")); assertTrue("file://localhost/c:/ should now be allowed", validator.isValid("file://localhost/c:/some.file")); // These are never valid assertFalse("file://c:/ shouldn't ever be allowed, needs file:///c:/", validator.isValid("file://C:/some.file")); assertFalse("file://c:\\ shouldn't ever be allowed, needs file:///c:/", validator.isValid("file://C:\\some.file")); } @Test public void testValidator391OK() { String[] schemes = {"file"}; UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("file:///C:/path/to/dir/")); } @Test public void testValidator391FAILS() { String[] schemes = {"file"}; UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("file:/C:/path/to/dir/")); } @Test public void testValidator309() { UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://sample.ondemand.com/")); assertTrue(urlValidator.isValid("hTtP://sample.ondemand.CoM/")); assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/")); urlValidator = new UrlValidator(new String[] {"HTTP","HTTPS"}); assertTrue(urlValidator.isValid("http://sample.ondemand.com/")); assertTrue(urlValidator.isValid("hTtP://sample.ondemand.CoM/")); assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/")); } @Test public void testValidator339(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://www.cnn.com/WORLD/?hpt=sitenav")); // without assertTrue(urlValidator.isValid("http://www.cnn.com./WORLD/?hpt=sitenav")); // with assertFalse(urlValidator.isValid("http://www.cnn.com../")); // doubly dotty assertFalse(urlValidator.isValid("http://www.cnn.invalid/")); assertFalse(urlValidator.isValid("http://www.cnn.invalid./")); // check . does not affect invalid domains } @Test public void testValidator339IDN(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://президент.рф/WORLD/?hpt=sitenav")); // without assertTrue(urlValidator.isValid("http://президент.рф./WORLD/?hpt=sitenav")); // with assertFalse(urlValidator.isValid("http://президент.рф..../")); // very dotty assertFalse(urlValidator.isValid("http://президент.рф.../")); // triply dotty assertFalse(urlValidator.isValid("http://президент.рф../")); // doubly dotty } @Test public void testValidator342(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://example.rocks/")); assertTrue(urlValidator.isValid("http://example.rocks")); } @Test public void testValidator411(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://example.rocks:/")); assertTrue(urlValidator.isValid("http://example.rocks:0/")); assertTrue(urlValidator.isValid("http://example.rocks:65535/")); assertFalse(urlValidator.isValid("http://example.rocks:65536/")); assertFalse(urlValidator.isValid("http://example.rocks:100000/")); } @Test public void testValidator464() { String[] schemes = {"file"}; UrlValidator urlValidator = new UrlValidator(schemes); String fileNAK = "file://bad ^ domain.com/label/test"; assertFalse(fileNAK, urlValidator.isValid(fileNAK)); } @Test public void testValidator452(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://[::FFFF:129.144.52.38]:80/index.html")); } static boolean incrementTestPartsIndex(int[] testPartsIndex, Object[] testParts) { boolean carry = true; //add 1 to lowest order part. boolean maxIndex = true; for (int testPartsIndexIndex = testPartsIndex.length - 1; testPartsIndexIndex >= 0; --testPartsIndexIndex) { int index = testPartsIndex[testPartsIndexIndex]; ResultPair[] part = (ResultPair[]) testParts[testPartsIndexIndex]; maxIndex &= (index == (part.length - 1)); if (carry) { if (index < part.length - 1) { index++; testPartsIndex[testPartsIndexIndex] = index; carry = false; } else { testPartsIndex[testPartsIndexIndex] = 0; carry = true; } } } return (!maxIndex); } private String testPartsIndextoString() { StringBuilder carryMsg = new StringBuilder("{"); for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) { carryMsg.append(testPartsIndex[testPartsIndexIndex]); if (testPartsIndexIndex < testPartsIndex.length - 1) { carryMsg.append(','); } else { carryMsg.append('}'); } } return carryMsg.toString(); } @Test public void testValidateUrl() { assertTrue(true); } @Test public void testValidator290() { UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://xn--h1acbxfam.idn.icann.org/")); // assertTrue(validator.isValid("http://xn--e1afmkfd.xn--80akhbyknj4f")); // Internationalized country code top-level domains assertTrue(validator.isValid("http://test.xn--lgbbat1ad8j")); //Algeria assertTrue(validator.isValid("http://test.xn--fiqs8s")); // China assertTrue(validator.isValid("http://test.xn--fiqz9s")); // China assertTrue(validator.isValid("http://test.xn--wgbh1c")); // Egypt assertTrue(validator.isValid("http://test.xn--j6w193g")); // Hong Kong assertTrue(validator.isValid("http://test.xn--h2brj9c")); // India assertTrue(validator.isValid("http://test.xn--mgbbh1a71e")); // India assertTrue(validator.isValid("http://test.xn--fpcrj9c3d")); // India assertTrue(validator.isValid("http://test.xn--gecrj9c")); // India assertTrue(validator.isValid("http://test.xn--s9brj9c")); // India assertTrue(validator.isValid("http://test.xn--xkc2dl3a5ee0h")); // India assertTrue(validator.isValid("http://test.xn--45brj9c")); // India assertTrue(validator.isValid("http://test.xn--mgba3a4f16a")); // Iran assertTrue(validator.isValid("http://test.xn--mgbayh7gpa")); // Jordan assertTrue(validator.isValid("http://test.xn--mgbc0a9azcg")); // Morocco assertTrue(validator.isValid("http://test.xn--ygbi2ammx")); // Palestinian Territory assertTrue(validator.isValid("http://test.xn--wgbl6a")); // Qatar assertTrue(validator.isValid("http://test.xn--p1ai")); // Russia assertTrue(validator.isValid("http://test.xn--mgberp4a5d4ar")); // Saudi Arabia assertTrue(validator.isValid("http://test.xn--90a3ac")); // Serbia assertTrue(validator.isValid("http://test.xn--yfro4i67o")); // Singapore assertTrue(validator.isValid("http://test.xn--clchc0ea0b2g2a9gcd")); // Singapore assertTrue(validator.isValid("http://test.xn--3e0b707e")); // South Korea assertTrue(validator.isValid("http://test.xn--fzc2c9e2c")); // Sri Lanka assertTrue(validator.isValid("http://test.xn--xkc2al3hye2a")); // Sri Lanka assertTrue(validator.isValid("http://test.xn--ogbpf8fl")); // Syria assertTrue(validator.isValid("http://test.xn--kprw13d")); // Taiwan assertTrue(validator.isValid("http://test.xn--kpry57d")); // Taiwan assertTrue(validator.isValid("http://test.xn--o3cw4h")); // Thailand assertTrue(validator.isValid("http://test.xn--pgbs0dh")); // Tunisia assertTrue(validator.isValid("http://test.xn--mgbaam7a8h")); // United Arab Emirates // Proposed internationalized ccTLDs // assertTrue(validator.isValid("http://test.xn--54b7fta0cc")); // Bangladesh // assertTrue(validator.isValid("http://test.xn--90ae")); // Bulgaria // assertTrue(validator.isValid("http://test.xn--node")); // Georgia // assertTrue(validator.isValid("http://test.xn--4dbrk0ce")); // Israel // assertTrue(validator.isValid("http://test.xn--mgb9awbf")); // Oman // assertTrue(validator.isValid("http://test.xn--j1amh")); // Ukraine // assertTrue(validator.isValid("http://test.xn--mgb2ddes")); // Yemen // Test TLDs // assertTrue(validator.isValid("http://test.xn--kgbechtv")); // Arabic // assertTrue(validator.isValid("http://test.xn--hgbk6aj7f53bba")); // Persian // assertTrue(validator.isValid("http://test.xn--0zwm56d")); // Chinese // assertTrue(validator.isValid("http://test.xn--g6w251d")); // Chinese // assertTrue(validator.isValid("http://test.xn--80akhbyknj4f")); // Russian // assertTrue(validator.isValid("http://test.xn--11b5bs3a9aj6g")); // Hindi // assertTrue(validator.isValid("http://test.xn--jxalpdlp")); // Greek // assertTrue(validator.isValid("http://test.xn--9t4b11yi5a")); // Korean // assertTrue(validator.isValid("http://test.xn--deba0ad")); // Yiddish // assertTrue(validator.isValid("http://test.xn--zckzah")); // Japanese // assertTrue(validator.isValid("http://test.xn--hlcj6aya9esc7a")); // Tamil } @Test public void testValidator361() { UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://hello.tokyo/")); } @Test public void testValidator363(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://www.example.org/a/b/hello..world")); assertTrue(urlValidator.isValid("http://www.example.org/a/hello..world")); assertTrue(urlValidator.isValid("http://www.example.org/hello.world/")); assertTrue(urlValidator.isValid("http://www.example.org/hello..world/")); assertTrue(urlValidator.isValid("http://www.example.org/hello.world")); assertTrue(urlValidator.isValid("http://www.example.org/hello..world")); assertTrue(urlValidator.isValid("http://www.example.org/..world")); assertTrue(urlValidator.isValid("http://www.example.org/.../world")); assertFalse(urlValidator.isValid("http://www.example.org/../world")); assertFalse(urlValidator.isValid("http://www.example.org/..")); assertFalse(urlValidator.isValid("http://www.example.org/../")); assertFalse(urlValidator.isValid("http://www.example.org/./..")); assertFalse(urlValidator.isValid("http://www.example.org/././..")); assertTrue(urlValidator.isValid("http://www.example.org/...")); assertTrue(urlValidator.isValid("http://www.example.org/.../")); assertTrue(urlValidator.isValid("http://www.example.org/.../..")); } @Test public void testValidator375() { UrlValidator validator = new UrlValidator(); String url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"; assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url)); url = "http://[::1]:80/index.html"; assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url)); url = "http://FEDC:BA98:7654:3210:FEDC:BA98:7654:3210:80/index.html"; assertFalse("IPv6 address without [] should not validate: " + url, validator.isValid(url)); } @Test public void testValidator353() { // userinfo UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://www.apache.org:80/path")); assertTrue(validator.isValid("http://user:[email protected]:80/path")); assertTrue(validator.isValid("http://user:@www.apache.org:80/path")); assertTrue(validator.isValid("http://[email protected]:80/path")); assertTrue(validator.isValid("http://us%00er:-._~!$&'()*+,;[email protected]:80/path")); assertFalse(validator.isValid("http://:[email protected]:80/path")); assertFalse(validator.isValid("http://:@www.apache.org:80/path")); assertFalse(validator.isValid("http://user:pa:[email protected]/path")); assertFalse(validator.isValid("http://user:pa@[email protected]/path")); } @Test public void testValidator382() { UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("ftp://username:[email protected]:8042/over/there/index.dtb?type=animal&name=narwhal#nose")); } @Test public void testValidator380() { UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://www.apache.org:80/path")); assertTrue(validator.isValid("http://www.apache.org:8/path")); assertTrue(validator.isValid("http://www.apache.org:/path")); } @Test public void testValidator420() { UrlValidator validator = new UrlValidator(); assertFalse(validator.isValid("http://example.com/serach?address=Main Avenue")); assertTrue(validator.isValid("http://example.com/serach?address=Main%20Avenue")); assertTrue(validator.isValid("http://example.com/serach?address=Main+Avenue")); } @Test public void testValidator467() { UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); assertTrue(validator.isValid("https://example.com/some_path/path/")); assertTrue(validator.isValid("https://example.com//somepath/path/")); assertTrue(validator.isValid("https://example.com//some_path/path/")); assertTrue(validator.isValid("http://example.com//_test")); // VALIDATOR-429 } @Test public void testValidator283() { UrlValidator validator = new UrlValidator(); assertFalse(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%fr")); assertTrue(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%22")); } @Test public void testFragments() { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); assertFalse(urlValidator.isValid("http://apache.org/a/b/c#frag")); urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("http://apache.org/a/b/c#frag")); } //-------------------- Test data for creating a composite URL /** * The data given below approximates the 4 parts of a URL * <scheme>://<authority><path>?<query> except that the port number * is broken out of authority to increase the number of permutations. * A complete URL is composed of a scheme+authority+port+path+query, * all of which must be individually valid for the entire URL to be considered * valid. */ ResultPair[] testUrlScheme = {new ResultPair("http://", true), new ResultPair("ftp://", true), new ResultPair("h3t://", true), new ResultPair("3ht://", false), new ResultPair("http:/", false), new ResultPair("http:", false), new ResultPair("http/", false), new ResultPair("://", false)}; ResultPair[] testUrlAuthority = {new ResultPair("www.google.com", true), new ResultPair("www.google.com.", true), new ResultPair("go.com", true), new ResultPair("go.au", true), new ResultPair("0.0.0.0", true), new ResultPair("255.255.255.255", true), new ResultPair("256.256.256.256", false), new ResultPair("255.com", true), new ResultPair("1.2.3.4.5", false), new ResultPair("1.2.3.4.", false), new ResultPair("1.2.3", false), new ResultPair(".1.2.3.4", false), new ResultPair("go.a", false), new ResultPair("go.a1a", false), new ResultPair("go.cc", true), new ResultPair("go.1aa", false), new ResultPair("aaa.", false), new ResultPair(".aaa", false), new ResultPair("aaa", false), new ResultPair("", false) }; ResultPair[] testUrlPort = {new ResultPair(":80", true), new ResultPair(":65535", true), // max possible new ResultPair(":65536", false), // max possible +1 new ResultPair(":0", true), new ResultPair("", true), new ResultPair(":-1", false), new ResultPair(":65636", false), new ResultPair(":999999999999999999", false), new ResultPair(":65a", false) }; ResultPair[] testPath = {new ResultPair("/test1", true), new ResultPair("/t123", true), new ResultPair("/$23", true), new ResultPair("/..", false), new ResultPair("/../", false), new ResultPair("/test1/", true), new ResultPair("", true), new ResultPair("/test1/file", true), new ResultPair("/..//file", false), new ResultPair("/test1//file", false) }; //Test allow2slash, noFragment ResultPair[] testUrlPathOptions = {new ResultPair("/test1", true), new ResultPair("/t123", true), new ResultPair("/$23", true), new ResultPair("/..", false), new ResultPair("/../", false), new ResultPair("/test1/", true), new ResultPair("/#", false), new ResultPair("", true), new ResultPair("/test1/file", true), new ResultPair("/t123/file", true), new ResultPair("/$23/file", true), new ResultPair("/../file", false), new ResultPair("/..//file", false), new ResultPair("/test1//file", true), new ResultPair("/#/file", false) }; ResultPair[] testUrlQuery = {new ResultPair("?action=view", true), new ResultPair("?action=edit&mode=up", true), new ResultPair("", true) }; Object[] testUrlParts = {testUrlScheme, testUrlAuthority, testUrlPort, testPath, testUrlQuery}; Object[] testUrlPartsOptions = {testUrlScheme, testUrlAuthority, testUrlPort, testUrlPathOptions, testUrlQuery}; int[] testPartsIndex = {0, 0, 0, 0, 0}; //---------------- Test data for individual url parts ---------------- private final String[] schemes = {"http", "gopher", "g0-To+.", "not_valid" // TODO this will need to be dropped if the ctor validates schemes }; ResultPair[] testScheme = {new ResultPair("http", true), new ResultPair("ftp", false), new ResultPair("httpd", false), new ResultPair("gopher", true), new ResultPair("g0-to+.", true), new ResultPair("not_valid", false), // underscore not allowed new ResultPair("HtTp", true), new ResultPair("telnet", false)}; }
src/test/java/org/apache/commons/validator/routines/UrlValidatorTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import org.apache.commons.validator.ResultPair; import junit.framework.TestCase; /** * Performs Validation Test for url validations. * * @version $Revision$ */ public class UrlValidatorTest extends TestCase { private final boolean printStatus = false; private final boolean printIndex = false;//print index that indicates current scheme,host,port,path, query test were using. public UrlValidatorTest(String testName) { super(testName); } @Override protected void setUp() { for (int index = 0; index < testPartsIndex.length - 1; index++) { testPartsIndex[index] = 0; } } public void testIsValid() { testIsValid(testUrlParts, UrlValidator.ALLOW_ALL_SCHEMES); setUp(); long options = UrlValidator.ALLOW_2_SLASHES + UrlValidator.ALLOW_ALL_SCHEMES + UrlValidator.NO_FRAGMENTS; testIsValid(testUrlPartsOptions, options); } public void testIsValidScheme() { if (printStatus) { System.out.print("\n testIsValidScheme() "); } //UrlValidator urlVal = new UrlValidator(schemes,false,false,false); UrlValidator urlVal = new UrlValidator(schemes, 0); for (int sIndex = 0; sIndex < testScheme.length; sIndex++) { ResultPair testPair = testScheme[sIndex]; boolean result = urlVal.isValidScheme(testPair.item); assertEquals(testPair.item, testPair.valid, result); if (printStatus) { if (result == testPair.valid) { System.out.print('.'); } else { System.out.print('X'); } } } if (printStatus) { System.out.println(); } } /** * Create set of tests by taking the testUrlXXX arrays and * running through all possible permutations of their combinations. * * @param testObjects Used to create a url. */ public void testIsValid(Object[] testObjects, long options) { UrlValidator urlVal = new UrlValidator(null, null, options); assertTrue(urlVal.isValid("http://www.google.com")); assertTrue(urlVal.isValid("http://www.google.com/")); int statusPerLine = 60; int printed = 0; if (printIndex) { statusPerLine = 6; } do { StringBuilder testBuffer = new StringBuilder(); boolean expected = true; for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) { int index = testPartsIndex[testPartsIndexIndex]; ResultPair[] part = (ResultPair[]) testObjects[testPartsIndexIndex]; testBuffer.append(part[index].item); expected &= part[index].valid; } String url = testBuffer.toString(); boolean result = urlVal.isValid(url); assertEquals(url, expected, result); if (printStatus) { if (printIndex) { System.out.print(testPartsIndextoString()); } else { if (result == expected) { System.out.print('.'); } else { System.out.print('X'); } } printed++; if (printed == statusPerLine) { System.out.println(); printed = 0; } } } while (incrementTestPartsIndex(testPartsIndex, testObjects)); if (printStatus) { System.out.println(); } } public void testValidator202() { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); assertTrue(urlValidator.isValid("http://l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.org")); } public void testValidator204() { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("http://tech.yahoo.com/rc/desktops/102;_ylt=Ao8yevQHlZ4On0O3ZJGXLEQFLZA5")); } public void testValidator218() { UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); assertTrue("parentheses should be valid in URLs", validator.isValid("http://somewhere.com/pathxyz/file(1).html")); } public void testValidator235() { String version = System.getProperty("java.version"); if (version.compareTo("1.6") < 0) { System.out.println("Cannot run Unicode IDN tests"); return; // Cannot run the test } UrlValidator validator = new UrlValidator(); assertTrue("xn--d1abbgf6aiiy.xn--p1ai should validate", validator.isValid("http://xn--d1abbgf6aiiy.xn--p1ai")); assertTrue("президент.рф should validate", validator.isValid("http://президент.рф")); assertTrue("www.b\u00fccher.ch should validate", validator.isValid("http://www.b\u00fccher.ch")); assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("http://www.\uFFFD.ch")); assertTrue("www.b\u00fccher.ch should validate", validator.isValid("ftp://www.b\u00fccher.ch")); assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("ftp://www.\uFFFD.ch")); } public void testValidator248() { RegexValidator regex = new RegexValidator(new String[] {"localhost", ".*\\.my-testing"}); UrlValidator validator = new UrlValidator(regex, 0); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); assertTrue("first.my-testing should validate", validator.isValid("http://first.my-testing/test/index.html")); assertTrue("sup3r.my-testing should validate", validator.isValid("http://sup3r.my-testing/test/index.html")); assertFalse("broke.my-test should not validate", validator.isValid("http://broke.my-test/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); // Now check using options validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); assertTrue("machinename URL should validate", validator.isValid("http://machinename/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); } public void testValidator288() { UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("hostname should validate", validator.isValid("http://hostname")); assertTrue("hostname with path should validate", validator.isValid("http://hostname/test/index.html")); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); assertFalse("first.my-testing should not validate", validator.isValid("http://first.my-testing/test/index.html")); assertFalse("broke.hostname should not validate", validator.isValid("http://broke.hostname/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); // Turn it off, and check validator = new UrlValidator(0); assertFalse("hostname should no longer validate", validator.isValid("http://hostname")); assertFalse("localhost URL should no longer validate", validator.isValid("http://localhost/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); } public void testValidator276() { // file:// isn't allowed by default UrlValidator validator = new UrlValidator(); assertTrue("http://apache.org/ should be allowed by default", validator.isValid("http://www.apache.org/test/index.html")); assertFalse("file:///c:/ shouldn't be allowed by default", validator.isValid("file:///C:/some.file")); assertFalse("file:///c:\\ shouldn't be allowed by default", validator.isValid("file:///C:\\some.file")); assertFalse("file:///etc/ shouldn't be allowed by default", validator.isValid("file:///etc/hosts")); assertFalse("file://localhost/etc/ shouldn't be allowed by default", validator.isValid("file://localhost/etc/hosts")); assertFalse("file://localhost/c:/ shouldn't be allowed by default", validator.isValid("file://localhost/c:/some.file")); // Turn it on, and check // Note - we need to enable local urls when working with file: validator = new UrlValidator(new String[] {"http","file"}, UrlValidator.ALLOW_LOCAL_URLS); assertTrue("http://apache.org/ should be allowed by default", validator.isValid("http://www.apache.org/test/index.html")); assertTrue("file:///c:/ should now be allowed", validator.isValid("file:///C:/some.file")); assertFalse("file:///c:\\ should not be allowed", // Only allow forward slashes validator.isValid("file:///C:\\some.file")); assertTrue("file:///etc/ should now be allowed", validator.isValid("file:///etc/hosts")); assertTrue("file://localhost/etc/ should now be allowed", validator.isValid("file://localhost/etc/hosts")); assertTrue("file://localhost/c:/ should now be allowed", validator.isValid("file://localhost/c:/some.file")); // These are never valid assertFalse("file://c:/ shouldn't ever be allowed, needs file:///c:/", validator.isValid("file://C:/some.file")); assertFalse("file://c:\\ shouldn't ever be allowed, needs file:///c:/", validator.isValid("file://C:\\some.file")); } public void testValidator391OK() { String[] schemes = {"file"}; UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("file:///C:/path/to/dir/")); } public void testValidator391FAILS() { String[] schemes = {"file"}; UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("file:/C:/path/to/dir/")); } public void testValidator309() { UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://sample.ondemand.com/")); assertTrue(urlValidator.isValid("hTtP://sample.ondemand.CoM/")); assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/")); urlValidator = new UrlValidator(new String[] {"HTTP","HTTPS"}); assertTrue(urlValidator.isValid("http://sample.ondemand.com/")); assertTrue(urlValidator.isValid("hTtP://sample.ondemand.CoM/")); assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/")); } public void testValidator339(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://www.cnn.com/WORLD/?hpt=sitenav")); // without assertTrue(urlValidator.isValid("http://www.cnn.com./WORLD/?hpt=sitenav")); // with assertFalse(urlValidator.isValid("http://www.cnn.com../")); // doubly dotty assertFalse(urlValidator.isValid("http://www.cnn.invalid/")); assertFalse(urlValidator.isValid("http://www.cnn.invalid./")); // check . does not affect invalid domains } public void testValidator339IDN(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://президент.рф/WORLD/?hpt=sitenav")); // without assertTrue(urlValidator.isValid("http://президент.рф./WORLD/?hpt=sitenav")); // with assertFalse(urlValidator.isValid("http://президент.рф..../")); // very dotty assertFalse(urlValidator.isValid("http://президент.рф.../")); // triply dotty assertFalse(urlValidator.isValid("http://президент.рф../")); // doubly dotty } public void testValidator342(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://example.rocks/")); assertTrue(urlValidator.isValid("http://example.rocks")); } public void testValidator411(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://example.rocks:/")); assertTrue(urlValidator.isValid("http://example.rocks:0/")); assertTrue(urlValidator.isValid("http://example.rocks:65535/")); assertFalse(urlValidator.isValid("http://example.rocks:65536/")); assertFalse(urlValidator.isValid("http://example.rocks:100000/")); } public void testValidator464() { String[] schemes = {"file"}; UrlValidator urlValidator = new UrlValidator(schemes); String fileNAK = "file://bad ^ domain.com/label/test"; assertFalse(fileNAK, urlValidator.isValid(fileNAK)); } public void testValidator452(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://[::FFFF:129.144.52.38]:80/index.html")); } static boolean incrementTestPartsIndex(int[] testPartsIndex, Object[] testParts) { boolean carry = true; //add 1 to lowest order part. boolean maxIndex = true; for (int testPartsIndexIndex = testPartsIndex.length - 1; testPartsIndexIndex >= 0; --testPartsIndexIndex) { int index = testPartsIndex[testPartsIndexIndex]; ResultPair[] part = (ResultPair[]) testParts[testPartsIndexIndex]; maxIndex &= (index == (part.length - 1)); if (carry) { if (index < part.length - 1) { index++; testPartsIndex[testPartsIndexIndex] = index; carry = false; } else { testPartsIndex[testPartsIndexIndex] = 0; carry = true; } } } return (!maxIndex); } private String testPartsIndextoString() { StringBuilder carryMsg = new StringBuilder("{"); for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) { carryMsg.append(testPartsIndex[testPartsIndexIndex]); if (testPartsIndexIndex < testPartsIndex.length - 1) { carryMsg.append(','); } else { carryMsg.append('}'); } } return carryMsg.toString(); } public void testValidateUrl() { assertTrue(true); } public void testValidator290() { UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://xn--h1acbxfam.idn.icann.org/")); // assertTrue(validator.isValid("http://xn--e1afmkfd.xn--80akhbyknj4f")); // Internationalized country code top-level domains assertTrue(validator.isValid("http://test.xn--lgbbat1ad8j")); //Algeria assertTrue(validator.isValid("http://test.xn--fiqs8s")); // China assertTrue(validator.isValid("http://test.xn--fiqz9s")); // China assertTrue(validator.isValid("http://test.xn--wgbh1c")); // Egypt assertTrue(validator.isValid("http://test.xn--j6w193g")); // Hong Kong assertTrue(validator.isValid("http://test.xn--h2brj9c")); // India assertTrue(validator.isValid("http://test.xn--mgbbh1a71e")); // India assertTrue(validator.isValid("http://test.xn--fpcrj9c3d")); // India assertTrue(validator.isValid("http://test.xn--gecrj9c")); // India assertTrue(validator.isValid("http://test.xn--s9brj9c")); // India assertTrue(validator.isValid("http://test.xn--xkc2dl3a5ee0h")); // India assertTrue(validator.isValid("http://test.xn--45brj9c")); // India assertTrue(validator.isValid("http://test.xn--mgba3a4f16a")); // Iran assertTrue(validator.isValid("http://test.xn--mgbayh7gpa")); // Jordan assertTrue(validator.isValid("http://test.xn--mgbc0a9azcg")); // Morocco assertTrue(validator.isValid("http://test.xn--ygbi2ammx")); // Palestinian Territory assertTrue(validator.isValid("http://test.xn--wgbl6a")); // Qatar assertTrue(validator.isValid("http://test.xn--p1ai")); // Russia assertTrue(validator.isValid("http://test.xn--mgberp4a5d4ar")); // Saudi Arabia assertTrue(validator.isValid("http://test.xn--90a3ac")); // Serbia assertTrue(validator.isValid("http://test.xn--yfro4i67o")); // Singapore assertTrue(validator.isValid("http://test.xn--clchc0ea0b2g2a9gcd")); // Singapore assertTrue(validator.isValid("http://test.xn--3e0b707e")); // South Korea assertTrue(validator.isValid("http://test.xn--fzc2c9e2c")); // Sri Lanka assertTrue(validator.isValid("http://test.xn--xkc2al3hye2a")); // Sri Lanka assertTrue(validator.isValid("http://test.xn--ogbpf8fl")); // Syria assertTrue(validator.isValid("http://test.xn--kprw13d")); // Taiwan assertTrue(validator.isValid("http://test.xn--kpry57d")); // Taiwan assertTrue(validator.isValid("http://test.xn--o3cw4h")); // Thailand assertTrue(validator.isValid("http://test.xn--pgbs0dh")); // Tunisia assertTrue(validator.isValid("http://test.xn--mgbaam7a8h")); // United Arab Emirates // Proposed internationalized ccTLDs // assertTrue(validator.isValid("http://test.xn--54b7fta0cc")); // Bangladesh // assertTrue(validator.isValid("http://test.xn--90ae")); // Bulgaria // assertTrue(validator.isValid("http://test.xn--node")); // Georgia // assertTrue(validator.isValid("http://test.xn--4dbrk0ce")); // Israel // assertTrue(validator.isValid("http://test.xn--mgb9awbf")); // Oman // assertTrue(validator.isValid("http://test.xn--j1amh")); // Ukraine // assertTrue(validator.isValid("http://test.xn--mgb2ddes")); // Yemen // Test TLDs // assertTrue(validator.isValid("http://test.xn--kgbechtv")); // Arabic // assertTrue(validator.isValid("http://test.xn--hgbk6aj7f53bba")); // Persian // assertTrue(validator.isValid("http://test.xn--0zwm56d")); // Chinese // assertTrue(validator.isValid("http://test.xn--g6w251d")); // Chinese // assertTrue(validator.isValid("http://test.xn--80akhbyknj4f")); // Russian // assertTrue(validator.isValid("http://test.xn--11b5bs3a9aj6g")); // Hindi // assertTrue(validator.isValid("http://test.xn--jxalpdlp")); // Greek // assertTrue(validator.isValid("http://test.xn--9t4b11yi5a")); // Korean // assertTrue(validator.isValid("http://test.xn--deba0ad")); // Yiddish // assertTrue(validator.isValid("http://test.xn--zckzah")); // Japanese // assertTrue(validator.isValid("http://test.xn--hlcj6aya9esc7a")); // Tamil } public void testValidator361() { UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://hello.tokyo/")); } public void testValidator363(){ UrlValidator urlValidator = new UrlValidator(); assertTrue(urlValidator.isValid("http://www.example.org/a/b/hello..world")); assertTrue(urlValidator.isValid("http://www.example.org/a/hello..world")); assertTrue(urlValidator.isValid("http://www.example.org/hello.world/")); assertTrue(urlValidator.isValid("http://www.example.org/hello..world/")); assertTrue(urlValidator.isValid("http://www.example.org/hello.world")); assertTrue(urlValidator.isValid("http://www.example.org/hello..world")); assertTrue(urlValidator.isValid("http://www.example.org/..world")); assertTrue(urlValidator.isValid("http://www.example.org/.../world")); assertFalse(urlValidator.isValid("http://www.example.org/../world")); assertFalse(urlValidator.isValid("http://www.example.org/..")); assertFalse(urlValidator.isValid("http://www.example.org/../")); assertFalse(urlValidator.isValid("http://www.example.org/./..")); assertFalse(urlValidator.isValid("http://www.example.org/././..")); assertTrue(urlValidator.isValid("http://www.example.org/...")); assertTrue(urlValidator.isValid("http://www.example.org/.../")); assertTrue(urlValidator.isValid("http://www.example.org/.../..")); } public void testValidator375() { UrlValidator validator = new UrlValidator(); String url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"; assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url)); url = "http://[::1]:80/index.html"; assertTrue("IPv6 address URL should validate: " + url, validator.isValid(url)); url = "http://FEDC:BA98:7654:3210:FEDC:BA98:7654:3210:80/index.html"; assertFalse("IPv6 address without [] should not validate: " + url, validator.isValid(url)); } public void testValidator353() { // userinfo UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://www.apache.org:80/path")); assertTrue(validator.isValid("http://user:[email protected]:80/path")); assertTrue(validator.isValid("http://user:@www.apache.org:80/path")); assertTrue(validator.isValid("http://[email protected]:80/path")); assertTrue(validator.isValid("http://us%00er:-._~!$&'()*+,;[email protected]:80/path")); assertFalse(validator.isValid("http://:[email protected]:80/path")); assertFalse(validator.isValid("http://:@www.apache.org:80/path")); assertFalse(validator.isValid("http://user:pa:[email protected]/path")); assertFalse(validator.isValid("http://user:pa@[email protected]/path")); } public void testValidator382() { UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("ftp://username:[email protected]:8042/over/there/index.dtb?type=animal&name=narwhal#nose")); } public void testValidator380() { UrlValidator validator = new UrlValidator(); assertTrue(validator.isValid("http://www.apache.org:80/path")); assertTrue(validator.isValid("http://www.apache.org:8/path")); assertTrue(validator.isValid("http://www.apache.org:/path")); } public void testValidator420() { UrlValidator validator = new UrlValidator(); assertFalse(validator.isValid("http://example.com/serach?address=Main Avenue")); assertTrue(validator.isValid("http://example.com/serach?address=Main%20Avenue")); assertTrue(validator.isValid("http://example.com/serach?address=Main+Avenue")); } public void testValidator467() { UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); assertTrue(validator.isValid("https://example.com/some_path/path/")); assertTrue(validator.isValid("https://example.com//somepath/path/")); assertTrue(validator.isValid("https://example.com//some_path/path/")); assertTrue(validator.isValid("http://example.com//_test")); // VALIDATOR-429 } public void testValidator283() { UrlValidator validator = new UrlValidator(); assertFalse(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%fr")); assertTrue(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%22")); } public void testFragments() { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); assertFalse(urlValidator.isValid("http://apache.org/a/b/c#frag")); urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("http://apache.org/a/b/c#frag")); } //-------------------- Test data for creating a composite URL /** * The data given below approximates the 4 parts of a URL * <scheme>://<authority><path>?<query> except that the port number * is broken out of authority to increase the number of permutations. * A complete URL is composed of a scheme+authority+port+path+query, * all of which must be individually valid for the entire URL to be considered * valid. */ ResultPair[] testUrlScheme = {new ResultPair("http://", true), new ResultPair("ftp://", true), new ResultPair("h3t://", true), new ResultPair("3ht://", false), new ResultPair("http:/", false), new ResultPair("http:", false), new ResultPair("http/", false), new ResultPair("://", false)}; ResultPair[] testUrlAuthority = {new ResultPair("www.google.com", true), new ResultPair("www.google.com.", true), new ResultPair("go.com", true), new ResultPair("go.au", true), new ResultPair("0.0.0.0", true), new ResultPair("255.255.255.255", true), new ResultPair("256.256.256.256", false), new ResultPair("255.com", true), new ResultPair("1.2.3.4.5", false), new ResultPair("1.2.3.4.", false), new ResultPair("1.2.3", false), new ResultPair(".1.2.3.4", false), new ResultPair("go.a", false), new ResultPair("go.a1a", false), new ResultPair("go.cc", true), new ResultPair("go.1aa", false), new ResultPair("aaa.", false), new ResultPair(".aaa", false), new ResultPair("aaa", false), new ResultPair("", false) }; ResultPair[] testUrlPort = {new ResultPair(":80", true), new ResultPair(":65535", true), // max possible new ResultPair(":65536", false), // max possible +1 new ResultPair(":0", true), new ResultPair("", true), new ResultPair(":-1", false), new ResultPair(":65636", false), new ResultPair(":999999999999999999", false), new ResultPair(":65a", false) }; ResultPair[] testPath = {new ResultPair("/test1", true), new ResultPair("/t123", true), new ResultPair("/$23", true), new ResultPair("/..", false), new ResultPair("/../", false), new ResultPair("/test1/", true), new ResultPair("", true), new ResultPair("/test1/file", true), new ResultPair("/..//file", false), new ResultPair("/test1//file", false) }; //Test allow2slash, noFragment ResultPair[] testUrlPathOptions = {new ResultPair("/test1", true), new ResultPair("/t123", true), new ResultPair("/$23", true), new ResultPair("/..", false), new ResultPair("/../", false), new ResultPair("/test1/", true), new ResultPair("/#", false), new ResultPair("", true), new ResultPair("/test1/file", true), new ResultPair("/t123/file", true), new ResultPair("/$23/file", true), new ResultPair("/../file", false), new ResultPair("/..//file", false), new ResultPair("/test1//file", true), new ResultPair("/#/file", false) }; ResultPair[] testUrlQuery = {new ResultPair("?action=view", true), new ResultPair("?action=edit&mode=up", true), new ResultPair("", true) }; Object[] testUrlParts = {testUrlScheme, testUrlAuthority, testUrlPort, testPath, testUrlQuery}; Object[] testUrlPartsOptions = {testUrlScheme, testUrlAuthority, testUrlPort, testUrlPathOptions, testUrlQuery}; int[] testPartsIndex = {0, 0, 0, 0, 0}; //---------------- Test data for individual url parts ---------------- private final String[] schemes = {"http", "gopher", "g0-To+.", "not_valid" // TODO this will need to be dropped if the ctor validates schemes }; ResultPair[] testScheme = {new ResultPair("http", true), new ResultPair("ftp", false), new ResultPair("httpd", false), new ResultPair("gopher", true), new ResultPair("g0-to+.", true), new ResultPair("not_valid", false), // underscore not allowed new ResultPair("HtTp", true), new ResultPair("telnet", false)}; }
=> JUnit4
src/test/java/org/apache/commons/validator/routines/UrlValidatorTest.java
=> JUnit4
<ide><path>rc/test/java/org/apache/commons/validator/routines/UrlValidatorTest.java <ide> */ <ide> package org.apache.commons.validator.routines; <ide> <add>import static org.junit.Assert.*; <add> <ide> import org.apache.commons.validator.ResultPair; <del> <del>import junit.framework.TestCase; <add>import org.junit.Before; <add>import org.junit.Test; <ide> <ide> /** <ide> * Performs Validation Test for url validations. <ide> * <ide> * @version $Revision$ <ide> */ <del>public class UrlValidatorTest extends TestCase { <add>public class UrlValidatorTest { <ide> <ide> private final boolean printStatus = false; <ide> private final boolean printIndex = false;//print index that indicates current scheme,host,port,path, query test were using. <ide> <del> public UrlValidatorTest(String testName) { <del> super(testName); <del> } <del> <del> @Override <del> protected void setUp() { <add> @Before <add> public void setUp() { <ide> for (int index = 0; index < testPartsIndex.length - 1; index++) { <ide> testPartsIndex[index] = 0; <ide> } <ide> } <ide> <add> @Test <ide> public void testIsValid() { <ide> testIsValid(testUrlParts, UrlValidator.ALLOW_ALL_SCHEMES); <ide> setUp(); <ide> testIsValid(testUrlPartsOptions, options); <ide> } <ide> <add> @Test <ide> public void testIsValidScheme() { <ide> if (printStatus) { <ide> System.out.print("\n testIsValidScheme() "); <ide> } <ide> } <ide> <add> @Test <ide> public void testValidator202() { <ide> String[] schemes = {"http","https"}; <ide> UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); <ide> assertTrue(urlValidator.isValid("http://l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.l.org")); <ide> } <ide> <add> @Test <ide> public void testValidator204() { <ide> String[] schemes = {"http","https"}; <ide> UrlValidator urlValidator = new UrlValidator(schemes); <ide> assertTrue(urlValidator.isValid("http://tech.yahoo.com/rc/desktops/102;_ylt=Ao8yevQHlZ4On0O3ZJGXLEQFLZA5")); <ide> } <ide> <add> @Test <ide> public void testValidator218() { <ide> UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); <ide> assertTrue("parentheses should be valid in URLs", <ide> validator.isValid("http://somewhere.com/pathxyz/file(1).html")); <ide> } <ide> <add> @Test <ide> public void testValidator235() { <ide> String version = System.getProperty("java.version"); <ide> if (version.compareTo("1.6") < 0) { <ide> assertFalse("www.\uFFFD.ch FFFD should fail", validator.isValid("ftp://www.\uFFFD.ch")); <ide> } <ide> <add> @Test <ide> public void testValidator248() { <ide> RegexValidator regex = new RegexValidator(new String[] {"localhost", ".*\\.my-testing"}); <ide> UrlValidator validator = new UrlValidator(regex, 0); <ide> validator.isValid("http://www.apache.org/test/index.html")); <ide> } <ide> <add> @Test <ide> public void testValidator288() { <ide> UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); <ide> <ide> validator.isValid("http://www.apache.org/test/index.html")); <ide> } <ide> <add> @Test <ide> public void testValidator276() { <ide> // file:// isn't allowed by default <ide> UrlValidator validator = new UrlValidator(); <ide> validator.isValid("file://C:\\some.file")); <ide> } <ide> <add> @Test <ide> public void testValidator391OK() { <ide> String[] schemes = {"file"}; <ide> UrlValidator urlValidator = new UrlValidator(schemes); <ide> assertTrue(urlValidator.isValid("file:///C:/path/to/dir/")); <ide> } <ide> <add> @Test <ide> public void testValidator391FAILS() { <ide> String[] schemes = {"file"}; <ide> UrlValidator urlValidator = new UrlValidator(schemes); <ide> assertTrue(urlValidator.isValid("file:/C:/path/to/dir/")); <ide> } <ide> <add> @Test <ide> public void testValidator309() { <ide> UrlValidator urlValidator = new UrlValidator(); <ide> assertTrue(urlValidator.isValid("http://sample.ondemand.com/")); <ide> assertTrue(urlValidator.isValid("httpS://SAMPLE.ONEMAND.COM/")); <ide> } <ide> <add> @Test <ide> public void testValidator339(){ <ide> UrlValidator urlValidator = new UrlValidator(); <ide> assertTrue(urlValidator.isValid("http://www.cnn.com/WORLD/?hpt=sitenav")); // without <ide> assertFalse(urlValidator.isValid("http://www.cnn.invalid./")); // check . does not affect invalid domains <ide> } <ide> <add> @Test <ide> public void testValidator339IDN(){ <ide> UrlValidator urlValidator = new UrlValidator(); <ide> assertTrue(urlValidator.isValid("http://президент.рф/WORLD/?hpt=sitenav")); // without <ide> assertFalse(urlValidator.isValid("http://президент.рф../")); // doubly dotty <ide> } <ide> <add> @Test <ide> public void testValidator342(){ <ide> UrlValidator urlValidator = new UrlValidator(); <ide> assertTrue(urlValidator.isValid("http://example.rocks/")); <ide> assertTrue(urlValidator.isValid("http://example.rocks")); <ide> } <ide> <add> @Test <ide> public void testValidator411(){ <ide> UrlValidator urlValidator = new UrlValidator(); <ide> assertTrue(urlValidator.isValid("http://example.rocks:/")); <ide> assertFalse(urlValidator.isValid("http://example.rocks:100000/")); <ide> } <ide> <add> @Test <ide> public void testValidator464() { <ide> String[] schemes = {"file"}; <ide> UrlValidator urlValidator = new UrlValidator(schemes); <ide> assertFalse(fileNAK, urlValidator.isValid(fileNAK)); <ide> } <ide> <add> @Test <ide> public void testValidator452(){ <ide> UrlValidator urlValidator = new UrlValidator(); <ide> assertTrue(urlValidator.isValid("http://[::FFFF:129.144.52.38]:80/index.html")); <ide> <ide> } <ide> <add> @Test <ide> public void testValidateUrl() { <ide> assertTrue(true); <ide> } <ide> <add> @Test <ide> public void testValidator290() { <ide> UrlValidator validator = new UrlValidator(); <ide> assertTrue(validator.isValid("http://xn--h1acbxfam.idn.icann.org/")); <ide> // assertTrue(validator.isValid("http://test.xn--hlcj6aya9esc7a")); // Tamil <ide> } <ide> <add> @Test <ide> public void testValidator361() { <ide> UrlValidator validator = new UrlValidator(); <ide> assertTrue(validator.isValid("http://hello.tokyo/")); <ide> } <ide> <add> @Test <ide> public void testValidator363(){ <ide> UrlValidator urlValidator = new UrlValidator(); <ide> assertTrue(urlValidator.isValid("http://www.example.org/a/b/hello..world")); <ide> assertTrue(urlValidator.isValid("http://www.example.org/.../..")); <ide> } <ide> <add> @Test <ide> public void testValidator375() { <ide> UrlValidator validator = new UrlValidator(); <ide> String url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"; <ide> } <ide> <ide> <add> @Test <ide> public void testValidator353() { // userinfo <ide> UrlValidator validator = new UrlValidator(); <ide> assertTrue(validator.isValid("http://www.apache.org:80/path")); <ide> assertFalse(validator.isValid("http://user:pa@[email protected]/path")); <ide> } <ide> <add> @Test <ide> public void testValidator382() { <ide> UrlValidator validator = new UrlValidator(); <ide> assertTrue(validator.isValid("ftp://username:[email protected]:8042/over/there/index.dtb?type=animal&name=narwhal#nose")); <ide> } <ide> <add> @Test <ide> public void testValidator380() { <ide> UrlValidator validator = new UrlValidator(); <ide> assertTrue(validator.isValid("http://www.apache.org:80/path")); <ide> assertTrue(validator.isValid("http://www.apache.org:/path")); <ide> } <ide> <add> @Test <ide> public void testValidator420() { <ide> UrlValidator validator = new UrlValidator(); <ide> assertFalse(validator.isValid("http://example.com/serach?address=Main Avenue")); <ide> assertTrue(validator.isValid("http://example.com/serach?address=Main+Avenue")); <ide> } <ide> <add> @Test <ide> public void testValidator467() { <ide> UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); <ide> assertTrue(validator.isValid("https://example.com/some_path/path/")); <ide> assertTrue(validator.isValid("http://example.com//_test")); // VALIDATOR-429 <ide> } <ide> <add> @Test <ide> public void testValidator283() { <ide> UrlValidator validator = new UrlValidator(); <ide> assertFalse(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%fr")); <ide> assertTrue(validator.isValid("http://finance.yahoo.com/news/Owners-54B-NY-housing-apf-2493139299.html?x=0&ap=%22")); <ide> } <ide> <add> @Test <ide> public void testFragments() { <ide> String[] schemes = {"http","https"}; <ide> UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS);
Java
apache-2.0
45444ed2b9e27997ef8b3927a82291bfba098325
0
apache/groovy,paulk-asert/groovy,paulk-asert/incubator-groovy,apache/groovy,apache/incubator-groovy,apache/incubator-groovy,paulk-asert/incubator-groovy,shils/groovy,paulk-asert/groovy,shils/groovy,armsargis/groovy,apache/groovy,paulk-asert/incubator-groovy,armsargis/groovy,shils/incubator-groovy,paulk-asert/groovy,shils/incubator-groovy,shils/groovy,armsargis/groovy,apache/groovy,shils/incubator-groovy,apache/incubator-groovy,shils/groovy,apache/incubator-groovy,paulk-asert/incubator-groovy,paulk-asert/incubator-groovy,armsargis/groovy,shils/incubator-groovy,paulk-asert/groovy
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.groovy.ast.decompiled; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.MixinNode; import org.codehaus.groovy.classgen.Verifier; import org.objectweb.asm.Opcodes; import java.lang.reflect.Modifier; import java.util.List; import java.util.function.Supplier; /** * A {@link ClassNode} kind representing the classes coming from *.class files decompiled using ASM. * * @see AsmDecompiler */ public class DecompiledClassNode extends ClassNode { private final ClassStub classData; private final AsmReferenceResolver resolver; private volatile boolean supersInitialized; private volatile boolean membersInitialized; public DecompiledClassNode(ClassStub data, AsmReferenceResolver resolver) { super(data.className, getFullModifiers(data), null, null, MixinNode.EMPTY_ARRAY); classData = data; this.resolver = resolver; isPrimaryNode = false; } /** * Handle the case of inner classes returning the correct modifiers from * the INNERCLASS reference since the top-level modifiers for inner classes * wont include static or private/protected. */ private static int getFullModifiers(ClassStub data) { return (data.innerClassModifiers == -1) ? data.accessModifiers : data.innerClassModifiers; } public long getCompilationTimeStamp() { if (classData.fields != null) { for (FieldStub field : classData.fields) { if (Modifier.isStatic(field.accessModifiers)) { Long timestamp = Verifier.getTimestampFromFieldName(field.fieldName); if (timestamp != null) { return timestamp; } } } } return Long.MAX_VALUE; } @Override public GenericsType[] getGenericsTypes() { lazyInitSupers(); return super.getGenericsTypes(); } @Override public boolean isUsingGenerics() { lazyInitSupers(); return super.isUsingGenerics(); } @Override public List<FieldNode> getFields() { lazyInitMembers(); return super.getFields(); } @Override public ClassNode[] getInterfaces() { lazyInitSupers(); return super.getInterfaces(); } @Override public List<MethodNode> getMethods() { lazyInitMembers(); return super.getMethods(); } @Override public List<ConstructorNode> getDeclaredConstructors() { lazyInitMembers(); return super.getDeclaredConstructors(); } @Override public FieldNode getDeclaredField(String name) { lazyInitMembers(); return super.getDeclaredField(name); } @Override public List<MethodNode> getDeclaredMethods(String name) { lazyInitMembers(); return super.getDeclaredMethods(name); } @Override public ClassNode getUnresolvedSuperClass(boolean useRedirect) { lazyInitSupers(); return super.getUnresolvedSuperClass(useRedirect); } @Override public ClassNode[] getUnresolvedInterfaces(boolean useRedirect) { lazyInitSupers(); return super.getUnresolvedInterfaces(useRedirect); } @Override public List<AnnotationNode> getAnnotations() { lazyInitSupers(); return super.getAnnotations(); } @Override public List<AnnotationNode> getAnnotations(ClassNode type) { lazyInitSupers(); return super.getAnnotations(type); } @Override public void setRedirect(ClassNode cn) { throw new UnsupportedOperationException(); } @Override public void setGenericsPlaceHolder(boolean b) { throw new UnsupportedOperationException(); } @Override public void setUsingGenerics(boolean b) { throw new UnsupportedOperationException(); } @Override public String setName(String name) { throw new UnsupportedOperationException(); } @Override public boolean isResolved() { return true; } @Override public Class getTypeClass() { return resolver.resolveJvmClass(getName()); } private void lazyInitSupers() { if (supersInitialized) return; synchronized (lazyInitLock) { if (!supersInitialized) { ClassSignatureParser.configureClass(this, this.classData, this.resolver); addAnnotations(classData, this); supersInitialized = true; } } } private void lazyInitMembers() { if (membersInitialized) return; synchronized (lazyInitLock) { if (!membersInitialized) { if (classData.methods != null) { for (MethodStub method : classData.methods) { if (isConstructor(method)) { addConstructor(createConstructor(method)); } else { addMethod(createMethodNode(method)); } } } if (classData.fields != null) { for (FieldStub field : classData.fields) { addField(createFieldNode(field)); } } membersInitialized = true; } } } private FieldNode createFieldNode(final FieldStub field) { Supplier<FieldNode> fieldNodeSupplier = () -> addAnnotations(field, MemberSignatureParser.createFieldNode(field, resolver, this)); if ((field.accessModifiers & Opcodes.ACC_PRIVATE) != 0) { return new LazyFieldNode(fieldNodeSupplier, field.fieldName); } return fieldNodeSupplier.get(); } private MethodNode createMethodNode(final MethodStub method) { Supplier<MethodNode> methodNodeSupplier = () -> addAnnotations(method, MemberSignatureParser.createMethodNode(resolver, method)); if ((method.accessModifiers & Opcodes.ACC_PRIVATE) != 0) { return new LazyMethodNode(methodNodeSupplier, method.methodName); } return methodNodeSupplier.get(); } private ConstructorNode createConstructor(final MethodStub method) { Supplier<ConstructorNode> constructorNodeSupplier = () -> (ConstructorNode) addAnnotations(method, MemberSignatureParser.createMethodNode(resolver, method)); if ((method.accessModifiers & Opcodes.ACC_PRIVATE) != 0) { return new LazyConstructorNode(constructorNodeSupplier); } return constructorNodeSupplier.get(); } private boolean isConstructor(MethodStub method) { return "<init>".equals(method.methodName); } private <T extends AnnotatedNode> T addAnnotations(MemberStub stub, T node) { List<AnnotationStub> annotations = stub.annotations; if (annotations != null) { for (AnnotationStub annotation : annotations) { AnnotationNode annotationNode = Annotations.createAnnotationNode(annotation, resolver); if (annotationNode != null) { node.addAnnotation(annotationNode); } } } return node; } }
src/main/java/org/codehaus/groovy/ast/decompiled/DecompiledClassNode.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.codehaus.groovy.ast.decompiled; import org.codehaus.groovy.ast.AnnotatedNode; import org.codehaus.groovy.ast.AnnotationNode; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.ConstructorNode; import org.codehaus.groovy.ast.FieldNode; import org.codehaus.groovy.ast.GenericsType; import org.codehaus.groovy.ast.MethodNode; import org.codehaus.groovy.ast.MixinNode; import org.codehaus.groovy.classgen.Verifier; import org.objectweb.asm.Opcodes; import java.lang.reflect.Modifier; import java.util.List; import java.util.function.Supplier; /** * A {@link ClassNode} kind representing the classes coming from *.class files decompiled using ASM. * * @see AsmDecompiler */ public class DecompiledClassNode extends ClassNode { private final ClassStub classData; private final AsmReferenceResolver resolver; private boolean supersInitialized = false; private boolean membersInitialized = false; public DecompiledClassNode(ClassStub data, AsmReferenceResolver resolver) { super(data.className, getFullModifiers(data), null, null, MixinNode.EMPTY_ARRAY); classData = data; this.resolver = resolver; isPrimaryNode = false; } /** * Handle the case of inner classes returning the correct modifiers from * the INNERCLASS reference since the top-level modifiers for inner classes * wont include static or private/protected. */ private static int getFullModifiers(ClassStub data) { return (data.innerClassModifiers == -1) ? data.accessModifiers : data.innerClassModifiers; } public long getCompilationTimeStamp() { if (classData.fields != null) { for (FieldStub field : classData.fields) { if (Modifier.isStatic(field.accessModifiers)) { Long timestamp = Verifier.getTimestampFromFieldName(field.fieldName); if (timestamp != null) { return timestamp; } } } } return Long.MAX_VALUE; } @Override public GenericsType[] getGenericsTypes() { lazyInitSupers(); return super.getGenericsTypes(); } @Override public boolean isUsingGenerics() { lazyInitSupers(); return super.isUsingGenerics(); } @Override public List<FieldNode> getFields() { lazyInitMembers(); return super.getFields(); } @Override public ClassNode[] getInterfaces() { lazyInitSupers(); return super.getInterfaces(); } @Override public List<MethodNode> getMethods() { lazyInitMembers(); return super.getMethods(); } @Override public List<ConstructorNode> getDeclaredConstructors() { lazyInitMembers(); return super.getDeclaredConstructors(); } @Override public FieldNode getDeclaredField(String name) { lazyInitMembers(); return super.getDeclaredField(name); } @Override public List<MethodNode> getDeclaredMethods(String name) { lazyInitMembers(); return super.getDeclaredMethods(name); } @Override public ClassNode getUnresolvedSuperClass(boolean useRedirect) { lazyInitSupers(); return super.getUnresolvedSuperClass(useRedirect); } @Override public ClassNode[] getUnresolvedInterfaces(boolean useRedirect) { lazyInitSupers(); return super.getUnresolvedInterfaces(useRedirect); } @Override public List<AnnotationNode> getAnnotations() { lazyInitSupers(); return super.getAnnotations(); } @Override public List<AnnotationNode> getAnnotations(ClassNode type) { lazyInitSupers(); return super.getAnnotations(type); } @Override public void setRedirect(ClassNode cn) { throw new UnsupportedOperationException(); } @Override public void setGenericsPlaceHolder(boolean b) { throw new UnsupportedOperationException(); } @Override public void setUsingGenerics(boolean b) { throw new UnsupportedOperationException(); } @Override public String setName(String name) { throw new UnsupportedOperationException(); } @Override public boolean isResolved() { return true; } @Override public Class getTypeClass() { return resolver.resolveJvmClass(getName()); } private void lazyInitSupers() { synchronized (lazyInitLock) { if (!supersInitialized) { ClassSignatureParser.configureClass(this, this.classData, this.resolver); addAnnotations(classData, this); supersInitialized = true; } } } private void lazyInitMembers() { synchronized (lazyInitLock) { if (!membersInitialized) { if (classData.methods != null) { for (MethodStub method : classData.methods) { if (isConstructor(method)) { addConstructor(createConstructor(method)); } else { addMethod(createMethodNode(method)); } } } if (classData.fields != null) { for (FieldStub field : classData.fields) { addField(createFieldNode(field)); } } membersInitialized = true; } } } private FieldNode createFieldNode(final FieldStub field) { Supplier<FieldNode> fieldNodeSupplier = () -> addAnnotations(field, MemberSignatureParser.createFieldNode(field, resolver, this)); if ((field.accessModifiers & Opcodes.ACC_PRIVATE) != 0) { return new LazyFieldNode(fieldNodeSupplier, field.fieldName); } return fieldNodeSupplier.get(); } private MethodNode createMethodNode(final MethodStub method) { Supplier<MethodNode> methodNodeSupplier = () -> addAnnotations(method, MemberSignatureParser.createMethodNode(resolver, method)); if ((method.accessModifiers & Opcodes.ACC_PRIVATE) != 0) { return new LazyMethodNode(methodNodeSupplier, method.methodName); } return methodNodeSupplier.get(); } private ConstructorNode createConstructor(final MethodStub method) { Supplier<ConstructorNode> constructorNodeSupplier = () -> (ConstructorNode) addAnnotations(method, MemberSignatureParser.createMethodNode(resolver, method)); if ((method.accessModifiers & Opcodes.ACC_PRIVATE) != 0) { return new LazyConstructorNode(constructorNodeSupplier); } return constructorNodeSupplier.get(); } private boolean isConstructor(MethodStub method) { return "<init>".equals(method.methodName); } private <T extends AnnotatedNode> T addAnnotations(MemberStub stub, T node) { List<AnnotationStub> annotations = stub.annotations; if (annotations != null) { for (AnnotationStub annotation : annotations) { AnnotationNode annotationNode = Annotations.createAnnotationNode(annotation, resolver); if (annotationNode != null) { node.addAnnotation(annotationNode); } } } return node; } }
Tweak lazy logic with double-checked locking
src/main/java/org/codehaus/groovy/ast/decompiled/DecompiledClassNode.java
Tweak lazy logic with double-checked locking
<ide><path>rc/main/java/org/codehaus/groovy/ast/decompiled/DecompiledClassNode.java <ide> public class DecompiledClassNode extends ClassNode { <ide> private final ClassStub classData; <ide> private final AsmReferenceResolver resolver; <del> private boolean supersInitialized = false; <del> private boolean membersInitialized = false; <add> private volatile boolean supersInitialized; <add> private volatile boolean membersInitialized; <ide> <ide> public DecompiledClassNode(ClassStub data, AsmReferenceResolver resolver) { <ide> super(data.className, getFullModifiers(data), null, null, MixinNode.EMPTY_ARRAY); <ide> } <ide> <ide> private void lazyInitSupers() { <add> if (supersInitialized) return; <add> <ide> synchronized (lazyInitLock) { <ide> if (!supersInitialized) { <ide> ClassSignatureParser.configureClass(this, this.classData, this.resolver); <ide> } <ide> <ide> private void lazyInitMembers() { <add> if (membersInitialized) return; <add> <ide> synchronized (lazyInitLock) { <ide> if (!membersInitialized) { <ide> if (classData.methods != null) {