answer
stringlengths
17
10.2M
package com.haxademic.core.audio.analysis.input; import beads.AudioContext; import beads.Bead; import beads.FFT; import beads.Gain; import beads.PeakDetector; import beads.PowerSpectrum; import beads.ShortFrameSegmenter; import beads.SpectralDifference; import processing.core.PGraphics; public class AudioInputBeads implements IAudioInput { protected AudioContext ac; protected Gain gain; protected float[] freqs; protected PowerSpectrum ps; protected PeakDetector od; protected AudioStreamData audioStreamData = new AudioStreamData(); public AudioInputBeads() { ac = new AudioContext(); ShortFrameSegmenter sfs = new ShortFrameSegmenter(ac); FFT fft = new FFT(); gain = new Gain(ac, 2); ps = new PowerSpectrum(); sfs.setChunkSize(2048); sfs.setHopSize(441); sfs.addInput(gain); // sfs.addInput(ac.out); sfs.addListener(fft); fft.addListener(ps); // beat detection SpectralDifference sd = new SpectralDifference(ac.getSampleRate()); ps.addListener(sd); od = new PeakDetector(); sd.addListener(od); /* * These parameters will need to be adjusted based on the * type of music. This demo uses the mouse position to adjust * them dynamically. * mouse.x controls Threshold, mouse.y controls Alpha */ od.setThreshold(0.2f); od.setAlpha(.9f); od.addMessageListener( new Bead(){ protected void messageReceived(Bead b) { audioStreamData.setBeat(); } } ); // common setup and stream init ac.out.addDependent(sfs); gain.addInput(ac.getAudioInput()); ac.start(); } public AudioStreamData audioData() { return audioStreamData; } public void update(PGraphics pg) { // get FFT spectrum from Beads if(ps == null) return; float[] features = ps.getFeatures(); // update audio data object if(features != null) { // make a lower-amplitude copy if(freqs == null) freqs = new float[features.length]; for (int i = 0; i < features.length; i++) { freqs[i] = features[i] * 0.1f; } audioStreamData.setFFTFrequencies(freqs); audioStreamData.calcFreqsDampened(); } audioStreamData.setWaveformOffsets(ac.out.getOutBuffer(0)); // audioStreamData.setAmp(od.getLastOnsetValue()); audioStreamData.calcAmpAverage(); audioStreamData.update(); // debug draw if(pg != null) audioStreamData.drawDebug(pg); } }
package controllers; import java.util.List; import controllers.routes; import models.Account; import models.DnsEntry; import models.Domain; import fileauth.actions.BasicAuth; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import views.html.Admin.*; @BasicAuth public class AdminDynDNS extends Application { public static Result index() { Account account = Account.geAccountOrCreate(request().username()); if(!account.isAdmin()) { return forbidden(); } List<DnsEntry> entries = DnsEntry.find.all(); List<Account> accounts = Account.find.all(); return ok(index.render(entries, accounts)); } public static Result update(Long id) { Account account = Account.geAccountOrCreate(request().username()); if(!account.isAdmin()) { return forbidden(); } Form<DnsEntry> entryForm = Form.form(DnsEntry.class).bindFromRequest(); DnsEntry entry = entryForm.get(); DnsEntry oldEntry = DnsEntry.find.byId(id); entry.updated = null; // FIXME work around for resetting APIKey Bug.... entry.apiKey = oldEntry.apiKey; entry.update(id); return redirect(routes.AdminDynDNS.index()); } public static Result delete(Long id) { Account account = Account.geAccountOrCreate(request().username()); if(!account.isAdmin()) { return forbidden(); } DnsEntry entry = DnsEntry.find.byId(id); if (entry != null) { Domain domain = Domain.find.byId(entry.domain.id); entry.delete(); domain.forceUpdate = true; domain.save(); } return redirect(routes.AdminDynDNS.index()); } public static Result resetApiKey(Long id) { Account account = Account.geAccountOrCreate(request().username()); if(!account.isAdmin()) { return forbidden(); } DnsEntry entry = DnsEntry.find.byId(id); if (entry != null) { entry.apiKey = DnsEntry.generateApiKey(); entry.update(); } return redirect(routes.AdminDynDNS.index()); } }
package com.haxademic.demo.draw.particle; import java.util.ArrayList; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.app.config.AppSettings; import com.haxademic.core.app.config.Config; import com.haxademic.core.debug.DebugView; import com.haxademic.core.draw.color.ImageGradient; import com.haxademic.core.draw.filters.pshader.BloomFilter; import com.haxademic.core.draw.filters.pshader.BrightnessStepFilter; import com.haxademic.core.draw.filters.pshader.FXAAFilter; import com.haxademic.core.draw.filters.pshader.GrainFilter; import com.haxademic.core.draw.filters.pshader.VignetteFilter; import com.haxademic.core.draw.image.ImageUtil; import com.haxademic.core.file.FileUtil; import com.haxademic.core.math.MathUtil; import com.haxademic.core.render.Renderer; import com.haxademic.core.system.AppRestart; import com.haxademic.core.system.SystemUtil; import com.haxademic.core.ui.UI; import processing.core.PVector; public class Demo_ParticleBranchers extends PAppletHax { public static void main(String args[]) { arguments = args; PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } protected String STROKE_SIZE = "STROKE_SIZE"; protected String NUM_DRAWS_PER_FRAME = "NUM_DRAWS_PER_FRAME"; protected ArrayList<BranchingParticle> particles; protected ArrayList<BranchingParticle> deadParticles; protected boolean resetQueued = false; protected float maxLifespan = 200; protected float maxBranchAge = 100; protected int numInitialParticles = 2; protected float maxDescendants = 10; protected boolean evenInitialSpread = false; protected boolean childrenBranchFaster = false; protected float curveAmp = 0.01f; protected final int TURN_MODE_NONE = 0; protected final int TURN_MODE_ON = 1; protected final int TURN_MODE_MIXED = 2; protected final int TURN_MODE_NOISE = 3; protected int[] turnModes = new int[] {TURN_MODE_NONE, TURN_MODE_ON, TURN_MODE_MIXED, TURN_MODE_NOISE}; protected int turnMode = TURN_MODE_NONE; protected final int COLOR_MODE_ALL_COLORS = 0; protected final int COLOR_MODE_COLORS_ON_WHITE = 1; protected final int COLOR_MODE_COLORS_ON_BLACK = 2; protected final int COLOR_MODE_WHITE_ON_BLACK = 3; protected final int COLOR_MODE_WHITE_ON_BLACK_FADE = 4; protected final int COLOR_MODE_BLACK_ON_WHITE = 5; protected final int COLOR_MODE_TRIG = 6; protected int[] colorModes = new int[] {COLOR_MODE_ALL_COLORS, COLOR_MODE_COLORS_ON_WHITE, COLOR_MODE_COLORS_ON_BLACK, COLOR_MODE_WHITE_ON_BLACK, COLOR_MODE_WHITE_ON_BLACK_FADE, COLOR_MODE_BLACK_ON_WHITE, COLOR_MODE_TRIG}; protected int colorMode = COLOR_MODE_ALL_COLORS; protected int bgColor; protected ImageGradient imageGradient; protected int endFrame = -1; protected boolean renderImages = false; protected boolean renderSingleMovie = false; protected void config() { Config.setProperty( AppSettings.WIDTH, 960 ); Config.setProperty( AppSettings.HEIGHT, 540 ); Config.setProperty( AppSettings.FULLSCREEN, false ); Config.setProperty( AppSettings.ALWAYS_ON_TOP, false ); Config.setProperty( AppSettings.RENDERING_MOVIE, false ); if(renderSingleMovie) Config.setProperty( AppSettings.RENDERING_MOVIE, true ); Config.setProperty( AppSettings.RENDERING_MOVIE_START_FRAME, 1 ); Config.setProperty( AppSettings.RENDERING_MOVIE_STOP_FRAME, 1 + 60 * 60 ); } protected void firstFrame() { UI.addTitle("BRANCHERS CONTROLS"); UI.addSlider(STROKE_SIZE, 2, 0, 10, 0.1f, false); UI.addSlider(NUM_DRAWS_PER_FRAME, 4, 1, 15, 1f, false); // load palette imageGradient = new ImageGradient(ImageGradient.PASTELS()); imageGradient.addTexturesFromPath(ImageGradient.COOLORS_PATH); imageGradient.randomGradientTexture(); // build particles arrays for recycling / object pool particles = new ArrayList<BranchingParticle>(); deadParticles = new ArrayList<BranchingParticle>(); // start with a clear canvas bgColor = p.color(0); pg.beginDraw(); pg.background(bgColor); pg.endDraw(); // new props to start reset(); } protected void reset() { // new parameters maxLifespan = MathUtil.randRange(100, 500); maxBranchAge = maxLifespan * MathUtil.randRangeDecimal(0.1f, 0.9f); numInitialParticles = MathUtil.randRange(2, 10); maxDescendants = MathUtil.randRange(3, 30); evenInitialSpread = MathUtil.randBoolean(); childrenBranchFaster = MathUtil.randBoolean(); turnMode = turnModes[MathUtil.randRange(0, turnModes.length - 1)]; colorMode = colorModes[MathUtil.randRange(0, colorModes.length - 1)]; curveAmp = MathUtil.randRangeDecimal(0.001f, 0.03f); // override for rendering colorMode = COLOR_MODE_ALL_COLORS; // new color palette imageGradient.randomGradientTexture(); switch (colorMode) { case COLOR_MODE_ALL_COLORS: bgColor = imageGradient.getColorAtProgress(0); break; case COLOR_MODE_COLORS_ON_WHITE: case COLOR_MODE_BLACK_ON_WHITE: bgColor = p.color(255); break; case COLOR_MODE_COLORS_ON_BLACK: case COLOR_MODE_WHITE_ON_BLACK: case COLOR_MODE_WHITE_ON_BLACK_FADE: case COLOR_MODE_TRIG: bgColor = p.color(0); break; default: break; } // slay all particles for (int i = 0; i < particles.size(); i++) particles.get(i).die(); resetQueued = true; } public void keyPressed() { super.keyPressed(); if(p.key == ' ') reset(); } protected void drawApp() { // clear app background background(0); // draw to main canvas. make canvas pixels accessible pg.beginDraw(); pg.strokeWeight(UI.value(STROKE_SIZE)); // clear background if queued checkClearCanvas(); // update particles pg.loadPixels(); for (int j = 0; j < UI.valueInt(NUM_DRAWS_PER_FRAME); j++) { for (int i = 0; i < particles.size(); i++) particles.get(i).update(); for (int i = 0; i < particles.size(); i++) particles.get(i).update(); // post-processing for special fade mode if(colorMode == COLOR_MODE_WHITE_ON_BLACK_FADE) { BrightnessStepFilter.instance(p).setBrightnessStep(-1f/255f * 1.0f); BrightnessStepFilter.instance(p).applyTo(pg); } } // close offscreen buffer pg.endDraw(); // draw to screen & postprocess p.image(pg, 0, 0); postProcess(); // auto reset particles DebugView.setValue("particles", particles.size()); if(particles.size() == 0 && endFrame == -1) { endFrame = p.frameCount; } if(endFrame != -1 && p.frameCount > endFrame + 60) { if(renderSingleMovie) { Renderer.instance().videoRenderer.stop(); AppRestart.restart(p); } else { if(renderImages) saveFrame(FileUtil.haxademicOutputPath() + "branchers" + FileUtil.SEPARATOR + SystemUtil.getTimestampFine() + ".png"); reset(); endFrame = -1; } } } protected void checkClearCanvas() { if(resetQueued) { pg.background(bgColor); regenerateParticles(); resetQueued = false; } } protected void postProcess() { FXAAFilter.instance(p).applyTo(p.g); BloomFilter.instance(p).setStrength(0.1f); BloomFilter.instance(p).setBlurIterations(2); BloomFilter.instance(p).setBlendMode(BloomFilter.BLEND_DARKEST); // BloomFilter.instance(p).applyTo(p.g); // BloomFilter.instance(p).applyTo(pg); VignetteFilter.instance(p).setDarkness(0.4f); VignetteFilter.instance(p).applyTo(p.g); GrainFilter.instance(p).setTime(p.frameCount * 0.01f); GrainFilter.instance(p).setCrossfade(0.08f); GrainFilter.instance(p).applyTo(p.g); } protected void regenerateParticles() { for (int i = 0; i < numInitialParticles; i++) { // set direction float dir = p.random(P.TWO_PI); if(evenInitialSpread) dir = P.TWO_PI/numInitialParticles * i; // launch particle BranchingParticle newParticle = getParticle(); newParticle.reset(pg.width/2, pg.height/2, dir, 0); particles.add(newParticle); } } public BranchingParticle getParticle() { if(deadParticles.size() > 0) return deadParticles.remove(deadParticles.size() - 1); else return new BranchingParticle(); } // Particle class public class BranchingParticle { protected PVector position = new PVector(); protected float direction = 0; protected float speed = 1; protected int age = 0; protected int branchAge = 0; protected int lifeSpan = 0; protected int gen = 0; protected int curColor = 0; protected float colorSample = 0; protected float turnAmp = 0; public BranchingParticle() {} public void reset(float x, float y, float dir, int generation) { // reset position.set(x, y); direction = dir; gen = generation + 1; age = 0; // new random lifespan & branch time values lifeSpan = MathUtil.randRange(maxLifespan/2f, maxLifespan); branchAge = MathUtil.randRange(maxBranchAge/2f, maxBranchAge); if(childrenBranchFaster) branchAge /= this.gen / 4f; // branch faster with child depth // pick new color newLineColor(); while(curColor == bgColor) newLineColor(); // pick a turn mode if(turnMode == TURN_MODE_NONE || turnMode == TURN_MODE_NOISE) { turnAmp = 0; } else if(turnMode == TURN_MODE_ON || turnMode == TURN_MODE_MIXED) { // turnAmp = (gen % 2 == 0) ? 0.01f * gen : -0.01f * gen; // turn based on generation turnAmp = curveAmp * gen; if(MathUtil.randBoolean()) turnAmp *= -1f; } if(turnMode == TURN_MODE_MIXED) { if(MathUtil.randBoolean()) turnAmp = 0; } } protected void newLineColor() { switch (colorMode) { case COLOR_MODE_ALL_COLORS: case COLOR_MODE_COLORS_ON_WHITE: case COLOR_MODE_COLORS_ON_BLACK: colorSample += MathUtil.randRangeDecimal(0.01f, 0.5f); colorSample = colorSample % 1f; curColor = imageGradient.getColorAtProgress(colorSample); break; case COLOR_MODE_BLACK_ON_WHITE: curColor = p.color(0); break; case COLOR_MODE_WHITE_ON_BLACK: case COLOR_MODE_WHITE_ON_BLACK_FADE: case COLOR_MODE_TRIG: curColor = p.color(255); break; default: break; } } public void die() { if(particles.contains(this)) { particles.remove(this); deadParticles.add(this); } } public void update() { // turn? if(turnMode == TURN_MODE_NOISE) { float noiseAdd = -0.5f + p.noise(p.frameCount * lifeSpan * 0.01f, gen); turnAmp += noiseAdd * 0.005f; DebugView.setValue("turnAmp", turnAmp); } direction = direction + turnAmp; // move/age float lastX = position.x; float lastY = position.y; position.add(P.cos(direction) * speed, P.sin(direction) * speed); age++; // branch if(age == branchAge) { newBranch(); } // hit test on existing lines float nextX = position.x + P.cos(direction) * speed * 2f; float nextY = position.y + P.sin(direction) * speed * 2f; int canvasColor = ImageUtil.getPixelColor(pg, (int) nextX, (int) nextY); // draw if(colorMode == COLOR_MODE_TRIG) updateColorTrig(); pg.stroke(curColor); boolean startedLine = false; // if(canvasColor == bgColor) { pg.line(lastX, lastY, position.x, position.y); startedLine = true; // check for EOL if (age == lifeSpan) { newBranch(); die(); } else { if(canvasColor != bgColor && age > UI.value(STROKE_SIZE) * 1.75f) { // make sure pixel detection is far enough from starting location before hit test kills pg.line(position.x, position.y, nextX, nextY); die(); } else if (position.x < 0 || position.x > pg.width || position.y < 0 || position.y > pg.height) { die(); } else if(canvasColor != bgColor && gen > 1 && age > UI.value(STROKE_SIZE) * 1.015f) { // further generations don't need the same initial distance check for collisions. Let's not let them go past each other die(); } } } protected void newBranch() { // limit branch numbers if(gen > maxDescendants) return; // calculate a new direction for child branch float dirAdd = MathUtil.randRangeDecimal(0.2f, 0.99f); if(gen > 3) dirAdd = MathUtil.randRangeDecimal(0.9f, P.HALF_PI * 0.8f ); float angleOptions = 6; // if(MathUtil.randBoolean()) angleOptions = numInitialParticles; dirAdd = P.PI/angleOptions * MathUtil.randRange(1, angleOptions - 1); // keep within 0-PI, but exclude 0 and PI // dirAdd = P.PI/angleOptions * MathUtil.randRange(1, P.floor(angleOptions/2)); // optionally, don't allow acute angles backward if(MathUtil.randBoolean()) dirAdd *= -1f; // randomly reverse // if(MathUtil.randBoolean()) dirAdd = 0; // keep same direction // branch off a new particle with new properties BranchingParticle newParticle = getParticle(); newParticle.reset(position.x, position.y, direction + dirAdd, gen); particles.add(newParticle); // debug text // pg.fill(0); // pg.text(gen+"-", position.x + 10, position.y + 0); // set another random time for the next branch branchAge = age + MathUtil.randRange(30, 70); } protected void updateColorTrig() { curColor = p.color( P.sin(age * 0.02f) * 100f + 155f, P.sin(age * 0.025f) * 100f + 155f, P.sin(age * 0.03f) * 100f + 155f ); } } }
package api.web.gw2.mapping.v2.wvw.objectives; import api.web.gw2.mapping.core.EnumValue; import api.web.gw2.mapping.core.IdValue; import api.web.gw2.mapping.core.LocalizedResource; import api.web.gw2.mapping.core.OptionalValue; import api.web.gw2.mapping.core.Point2D; import api.web.gw2.mapping.core.Point3D; import api.web.gw2.mapping.core.URLValue; import api.web.gw2.mapping.v2.wvw.MapType; import java.net.URL; import java.util.Optional; public final class JsonpObjective implements Objective { @IdValue(flavor = IdValue.Flavor.STRING) private String id = ""; @LocalizedResource private String name = ""; @IdValue private int sectorId = -1; @EnumValue private ObjectiveType type = ObjectiveType.UNKNOWN; @EnumValue private MapType mapType = MapType.UNKNOWN; @IdValue private int mapId = -1; private Point3D<Double> coord = new Point3D<>(0d, 0d, 0d); private Point2D<Double> labelCoord = new Point2D<>(0d, 0d); @URLValue @OptionalValue private Optional<URL> marker = Optional.empty(); /** * Creates a new empty instance. */ public JsonpObjective() { } @Override public String getId() { return id; } @Override public String getName() { return name; } @Override public int getSectorId() { return sectorId; } @Override public ObjectiveType getType() { return type; } @Override public MapType getMapType() { return mapType; } @Override public int getMapId() { return mapId; } @Override public Point3D<Double> getCoord() { return coord; } @Override public Optional<URL> getMarker() { return marker; } @Override public Point2D<Double> getLabelCoord() { return labelCoord; } }
package controllers; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; import javax.xml.xquery.XQException; import org.brackit.xquery.atomic.Int; import models.BackendHandlerInterface; import models.GitHandler; import models.SirixHandler; import models.User; import models.UserHandler; import models.XChroniclerHandler; import models.XQueryUsage; import play.libs.Json; //import play.mvc.BodyParser.Json; import play.mvc.Controller; import play.mvc.Result; import utils.JSONConstants; import com.fasterxml.jackson.databind.node.ObjectNode; public class Application extends Controller { public static Result index() { return ok("this is just the index, you should be looking somewhere else"); } private static BackendHandlerInterface getBackend(String backendName) { if (backendName.equals(BackendHandlerInterface.GIT)) { return GitHandler.getInstance(); } else if (backendName.equals(BackendHandlerInterface.XCHRONICLER)) { return XChroniclerHandler.getInstance(); } else if (backendName.equals(BackendHandlerInterface.SIRIX)) { return SirixHandler.getInstance(); } else { throw new UnsupportedOperationException(); } } /** * Used for testing, allows to initialize a repository with HTTP/GET * * @param backendName * @return */ public static Result initRepositoryWithGET(String backendName) { BackendHandlerInterface backend = getBackend(backendName); if (backend.init()) { return ok("Success initializing repository"); } else { return ok("Failure to initialize repository"); } } /** * Initializes the repositories, should clean existing ones if they exist * Uses HTTP/POST * * @return */ public static Result initRepository() { final Map<String, String[]> postInput = getPOSTData(); String backendName = postInput.get(utils.JSONConstants.BACKEND)[0]; BackendHandlerInterface backend = getBackend(backendName); ObjectNode returnJson = Json.newObject(); if (backend.init()) { returnJson.put(JSONConstants.ANSWER, JSONConstants.SUCCESS); } else { returnJson.put(JSONConstants.ANSWER, JSONConstants.FAIL); } response().setHeader("Access-Control-Allow-Origin", "*"); return ok(returnJson); } /** * Collects the data submitted on a HTTP/POST request * * @return */ private static Map<String, String[]> getPOSTData() { return request().body().asFormUrlEncoded(); } /** * Uses HTTP/POST * * @return */ public static Result getHEAD() { final Map<String, String[]> postInput = getPOSTData(); BackendHandlerInterface backend = getBackend(postInput .get(JSONConstants.BACKEND)[0]); response().setHeader("Access-Control-Allow-Origin", "*"); return ok(backend.getRepositoryHEAD().toJSON()); } /** * Uses HTTP/POST * * @return */ public static Result getRevision() { final Map<String, String[]> postInput = getPOSTData(); BackendHandlerInterface backend = getBackend(postInput .get(JSONConstants.BACKEND)[0]); String revision = postInput.get(JSONConstants.REVISION_ID)[0]; response().setHeader("Access-Control-Allow-Origin", "*"); return ok(backend.checkout(revision).toJSON()); } /** * Uses HTTP/POST * * @return */ public static Result getLog() { final Map<String, String[]> postInput = getPOSTData(); BackendHandlerInterface backend = getBackend(postInput .get(JSONConstants.BACKEND)[0]); response().setHeader("Access-Control-Allow-Origin", "*"); System.out.println(backend.getLog()); return ok(Json.toJson(backend.getLog())); } /** * Uses HTTP/GET * * @return */ public static Result getHEADWithGET(String backendName) { BackendHandlerInterface backend = getBackend(backendName); return ok(backend.getRepositoryHEAD().toJSON()); } public static Result removeRepository(String backendName) { BackendHandlerInterface backend = getBackend(backendName); if (backend.removeExistingRepository()) return ok(JSONConstants.SUCCESS); return ok(JSONConstants.FAIL); } public static Result commit() { /** * Fetch content */ final Map<String, String[]> postInput = getPOSTData(); String url = postInput.get(JSONConstants.URL)[0]; String content = ""; if (postInput.get(JSONConstants.CONTENT) != null) { content = postInput.get(JSONConstants.CONTENT)[0]; } String message = postInput.get(JSONConstants.MESSAGE)[0]; String userId = postInput.get(JSONConstants.USER)[0]; String backendName = postInput.get(JSONConstants.BACKEND)[0]; String relativeVersion =null; if(postInput.get(JSONConstants.RELATIVE_VERSION)!=null){ relativeVersion = postInput.get(JSONConstants.RELATIVE_VERSION)[0]; } if (postInput.get(JSONConstants.COMMIT_FILE_URL) != null) { String fileurl = postInput.get(JSONConstants.COMMIT_FILE_URL)[0]; if (fileurl != null) { String pathToTest = "../XMLTestFramework/public/userStories/"; System.out.println("try to get " + pathToTest + fileurl); File file = new File(pathToTest + fileurl); System.out.println(file.getAbsolutePath()); try { List<String> lines = Files.readAllLines( Paths.get(pathToTest + fileurl), Charset.defaultCharset()); content = ""; for (String string : lines) { content += string; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * Pre-processes the POST contents */ BackendHandlerInterface backend = getBackend(backendName); User user = UserHandler.getUser(Integer.parseInt(userId)); /** * Tries to perform the Commit */ String answer = ""; long elapsedTime = Long.MAX_VALUE; long start = System.nanoTime(); int relativeVersionInt=0; System.out.println("relativeVersion: "+relativeVersion); if(relativeVersion!=null){ relativeVersionInt= Integer.parseInt(relativeVersion); } if(relativeVersion==null || relativeVersionInt==0){ if (backend.commit(url, content, message, user)) { answer = JSONConstants.SUCCESS; elapsedTime = System.nanoTime() - start; } else { answer = JSONConstants.FAIL; } }else{ if (backend.commit(url, content, message, user,relativeVersionInt)) { answer = JSONConstants.SUCCESS; elapsedTime = System.nanoTime() - start; } else { answer = JSONConstants.FAIL; } } /** * Creates the response */ // return new ActionWrapper(super.onRequest(request, actionMethod)); response().setHeader("Access-Control-Allow-Origin", "*"); ObjectNode returnJson = Json.newObject(); returnJson.put(JSONConstants.TIME, elapsedTime); returnJson.put(JSONConstants.ANSWER, answer); return ok(returnJson); } public static Result testVfile() { XChroniclerHandler backend = (XChroniclerHandler) XChroniclerHandler .getInstance(); return ok(backend.generateVFileSimpleTest()); } public static Result testXGetHEAD(String fileURL) { try { String result = XChroniclerHandler.getHeadFile(fileURL); if (result.isEmpty()) throw new Exception("Result was empty"); return ok(result); } catch (XQException e) { e.printStackTrace(); return internalServerError("The URL you sent was malformed perhaps\n Exception information: " + e.toString()); } catch (Exception e) { e.printStackTrace(); return internalServerError("Apparently the file doesn't exist.\n Exception result: " + e.getMessage()); } } public static Result testXCheckoutRevision(String revision, String fileUrl) { try { String result = XChroniclerHandler.checkout(revision, fileUrl); if (result.isEmpty()) throw new Exception("Result was empty"); return ok(result); } catch (XQException e) { e.printStackTrace(); return internalServerError("The URL you sent was malformed perhaps\n Exception information: " + e.toString()); } catch (Exception e) { e.printStackTrace(); return internalServerError("Apparently the file doesn't exist.\n Exception result: " + e.getMessage()); } } public static Result checkPreFlight() { // Need to add the correct domain in here!! response().setHeader("Access-Control-Allow-Origin", "*"); // Only allow POST response().setHeader("Access-Control-Allow-Methods", "POST"); // Cache response for 5 minutes response().setHeader("Access-Control-Max-Age", "300"); // Ensure this header is also allowed! response().setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); return ok(); } public static Result revert(){ final Map<String, String[]> postInput = getPOSTData(); BackendHandlerInterface backend = getBackend(postInput .get(JSONConstants.BACKEND)[0]); int relativeVersion=Integer.parseInt(postInput .get(JSONConstants.RELATIVE_VERSION)[0]); backend.revert(relativeVersion); return ok(); } public static Result getDiff(){ final Map<String, String[]> postInput = getPOSTData(); BackendHandlerInterface backend = getBackend(postInput .get(JSONConstants.BACKEND)[0]); int relativeVersion=Integer.parseInt(postInput .get(JSONConstants.RELATIVE_VERSION)[0]); backend.getDiff(relativeVersion); return ok(); } public static Result testSirix() { SirixHandler.databaseSirix(); //loadDocumentAndQueryTemporal(); //SirixHandler.printAllVersions(); /* * try { * * //XQueryUsage.loadDocumentAndQuery(); //System.out.println(); // * XQueryUsage.loadDocumentAndUpdate(); //System.out.println(); // * XQueryUsage.loadCollectionAndQuery(); // System.out.println(); // * XQueryUsage.loadDocumentAndQueryTemporal(); } catch (QueryException * e) { // TODO Auto-generated catch block e.printStackTrace(); } catch * (IOException e) { // TODO Auto-generated catch block * e.printStackTrace(); } */ return ok(); } }
package org.lightmare.jpa.jta; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import javax.ejb.EJBException; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import org.lightmare.cache.MetaData; import org.lightmare.cache.TransactionHolder; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Class to manage {@link javax.transaction.UserTransaction} for * {@link javax.ejb.Stateless} bean {@link java.lang.reflect.Proxy} calls * * @author levan * */ public class BeanTransactions { // Error messages for inappropriate use of user transactions private static final String MANDATORY_ERROR = "TransactionAttributeType.MANDATORY must always be called within transaction"; private static final String NEVER_ERROR = "TransactionAttributeType.NEVER is called within transaction"; private static final String SUPPORTS_ERROR = "TransactionAttributeType.SUPPORTS can not be initiator of bean transaction"; /** * Inner class to cache {@link EntityTransaction}s and {@link EntityManager} * s in one {@link Collection} for {@link UserTransaction} implementation * * @author levan * */ protected static class TransactionData { EntityManager em; EntityTransaction entityTransaction; } /** * Creates new {@link TransactionData} object with passed * {@link EntityTransaction} and {@link EntityManager} instances * * @param entityTransaction * @param em * @return {@link TransactionData} */ private static TransactionData createTransactionData( EntityTransaction entityTransaction, EntityManager em) { TransactionData transactionData = new TransactionData(); transactionData.em = em; transactionData.entityTransaction = entityTransaction; return transactionData; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction( EntityTransaction... entityTransactions) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(entityTransactions); TransactionHolder.setTransaction(transaction); } else { // If entityTransactions array is available then adds it to // UserTransaction object UserTransactionFactory.join(transaction, entityTransactions); } return transaction; } /** * Gets existing transaction from cache * * @param entityTransactions * @return {@link UserTransaction} */ public static UserTransaction getTransaction(Collection<EntityManager> ems) { UserTransaction transaction = TransactionHolder.getTransaction(); if (transaction == null) { transaction = UserTransactionFactory.get(); TransactionHolder.setTransaction(transaction); } Collection<TransactionData> entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); return transaction; } /** * Gets appropriated {@link TransactionAttributeType} for instant * {@link Method} of {@link javax.ejb.Stateless} bean * * @param metaData * @param method * @return {@link TransactionAttributeType} */ public static TransactionAttributeType getTransactionType( MetaData metaData, Method method) { TransactionAttributeType type; if (method == null) { type = null; } else { TransactionAttributeType attrType = metaData .getTransactionAttrType(); TransactionManagementType manType = metaData .getTransactionManType(); TransactionAttribute attr = method .getAnnotation(TransactionAttribute.class); if (manType.equals(TransactionManagementType.CONTAINER)) { if (attr == null) { type = attrType; } else { type = attr.value(); } } else { type = null; } } return type; } /** * Gets status of passed transaction by {@link UserTransaction#getStatus()} * method call * * @param transaction * @return <code>int</code> * @throws IOException */ private static int getStatus(UserTransaction transaction) throws IOException { int status; try { status = transaction.getStatus(); } catch (SystemException ex) { throw new IOException(ex); } return status; } /** * Checks if transaction is active and if it is not begins transaction * * @param entityTransaction */ private static void beginEntityTransaction( EntityTransaction entityTransaction) { if (ObjectUtils.notTrue(entityTransaction.isActive())) { entityTransaction.begin(); } } /** * Gets {@link EntityTransaction} from passed {@link EntityManager} and * begins it * * @param em * @return {@link EntityTransaction} */ private static EntityTransaction getEntityTransaction(EntityManager em) { EntityTransaction entityTransaction; if (em == null) { entityTransaction = null; } else { entityTransaction = em.getTransaction(); beginEntityTransaction(entityTransaction); } return entityTransaction; } /** * Gets {@link EntityTransaction} for each {@link EntityManager} and begins * it * * @param ems * @return {@link Collection}<EntityTransaction> */ private static Collection<TransactionData> getEntityTransactions( Collection<EntityManager> ems) { Collection<TransactionData> entityTransactions; if (CollectionUtils.valid(ems)) { entityTransactions = new ArrayList<TransactionData>(); for (EntityManager em : ems) { EntityTransaction entityTransaction = getEntityTransaction(em); TransactionData transactionData = createTransactionData( entityTransaction, em); entityTransactions.add(transactionData); } } else { entityTransactions = null; } return entityTransactions; } /** * Decides whether create or join {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param type * @param transaction * @param em * @throws IOException */ private static void addTransaction(BeanHandler handler, TransactionAttributeType type, UserTransaction transaction, Collection<EntityManager> ems) throws IOException { Collection<TransactionData> entityTransactions; TransactionManager.addCaller(transaction, handler); if (type.equals(TransactionAttributeType.NOT_SUPPORTED)) { TransactionManager.addFreeEntityManagers(transaction, ems); } else if (type.equals(TransactionAttributeType.REQUIRED)) { entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { entityTransactions = getEntityTransactions(ems); TransactionManager.addReqNewTransactions(transaction, entityTransactions); } else if (type.equals(TransactionAttributeType.MANDATORY)) { int status = getStatus(transaction); if (status == UserTransactionFactory.INACTIVE_TRANSACTION_STATE) { TransactionManager.addEntityManagers(transaction, ems); throw new EJBException(MANDATORY_ERROR); } else { entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); } } else if (type.equals(TransactionAttributeType.NEVER)) { try { int status = getStatus(transaction); if (status > UserTransactionFactory.INACTIVE_TRANSACTION_STATE) { throw new EJBException(NEVER_ERROR); } } finally { TransactionManager.addFreeEntityManagers(transaction, ems); } } else if (type.equals(TransactionAttributeType.SUPPORTS)) { entityTransactions = getEntityTransactions(ems); TransactionManager.addEntityTransactions(transaction, entityTransactions); } } /** * Defines which {@link TransactionAttribute} is used on bean {@link Class} * and decides whether create or join {@link UserTransaction} by this * annotation * * @param handler * @param method * @param entityTransaction * @throws IOException */ public static TransactionAttributeType addTransaction(BeanHandler handler, Method method, Collection<EntityManager> ems) throws IOException { TransactionAttributeType type; MetaData metaData = handler.getMetaData(); type = getTransactionType(metaData, method); UserTransaction transaction = getTransaction(); if (ObjectUtils.notNull(type)) { addTransaction(handler, type, transaction, ems); } else { TransactionManager.addEntityManagers(transaction, ems); } return type; } /** * Rollbacks passed {@link UserTransaction} by * {@link TransactionAttributeType} distinguishes only * {@link TransactionAttributeType#REQUIRES_NEW} case or uses standard * rollback for all other * * @param type * @param handler * @throws IOException */ private static void rollbackTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransaction transaction = getTransaction(); if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { TransactionManager.rollbackReqNew(transaction); } else if (TransactionManager.isFreeType(type)) { TransactionManager.closeFreeEntityManagers(transaction); } else { TransactionManager.rollback(transaction); } } /** * Decides which rollback method to call of {@link UserTransaction} * implementation by {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void rollbackTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { rollbackTransaction(type, handler); } else { closeEntityManagers(); } } /** * Commits transactions which should be in scope * * @param type * @param transaction * @throws IOException */ private static void commitScoped(TransactionAttributeType type, UserTransaction transaction) throws IOException { if (type.equals(TransactionAttributeType.REQUIRED)) { TransactionManager.commit(transaction); } else if (type.equals(TransactionAttributeType.SUPPORTS)) { int status = getStatus(transaction); if (status == UserTransactionFactory.INACTIVE_TRANSACTION_STATE) { TransactionManager.remove(transaction); } else { TransactionManager.remove(transaction); throw new EJBException(SUPPORTS_ERROR); } } else if (type.equals(TransactionAttributeType.MANDATORY)) { TransactionManager.remove(transaction); throw new EJBException(MANDATORY_ERROR); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param type * @param handler * @throws IOException */ private static void commitTransaction(TransactionAttributeType type, BeanHandler handler) throws IOException { UserTransaction transaction = getTransaction(); if (TransactionManager.isTransactionalType(type)) { boolean check = TransactionManager .checkCaller(transaction, handler); if (check) { commitScoped(type, transaction); } } else if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { TransactionManager.commitReqNew(transaction); } else if (TransactionManager.isFreeType(type)) { TransactionManager.closeFreeEntityManagers(transaction); } else { TransactionManager.closeEntityManagers(transaction); } } /** * Decides whether commit or not {@link UserTransaction} by * {@link TransactionAttribute} annotation * * @param handler * @param method * @throws IOException */ public static void commitTransaction(BeanHandler handler, Method method) throws IOException { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { commitTransaction(type, handler); } else { closeEntityManagers(); } } /** * Closes cached {@link EntityManager}s after method call */ public static void closeEntityManagers() { UserTransaction transaction = TransactionHolder.getTransaction(); if (ObjectUtils.notNull(transaction)) { TransactionManager.close(transaction); } } /** * Removes {@link UserTransaction} attribute from cache if passed * {@link BeanHandler} is first in EJB injection method chain * * @param handler * @param type */ private static void remove(BeanHandler handler, TransactionAttributeType type) { UserTransaction transaction = TransactionHolder.getTransaction(); if (ObjectUtils.notNull(transaction)) { if (type.equals(TransactionAttributeType.REQUIRES_NEW)) { TransactionManager.closeReqNewEntityManagers(transaction); } else if (TransactionManager.isFreeType(type)) { TransactionManager.closeFreeEntityManagers(transaction); } boolean check = TransactionManager .checkCaller(transaction, handler); if (check) { TransactionManager.remove(transaction); } } else { TransactionHolder.removeTransaction(); } } /** * Removes {@link UserTransaction} attribute from cache if * {@link TransactionAttributeType} is null or if passed {@link BeanHandler} * is first in EJB injection method chain * * @param handler * @param method */ public static void remove(BeanHandler handler, Method method) { TransactionAttributeType type = getTransactionType( handler.getMetaData(), method); if (ObjectUtils.notNull(type)) { remove(handler, type); } else { UserTransaction transaction = TransactionHolder.getTransaction(); if (ObjectUtils.notNull(transaction)) { TransactionManager.remove(transaction); } else { TransactionHolder.removeTransaction(); } } } }
package org.ligoj.app.plugin.prov; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.stream.Stream; import javax.cache.annotation.CacheKey; import javax.cache.annotation.CacheResult; import javax.persistence.EntityNotFoundException; import javax.transaction.Transactional; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.ligoj.app.iam.IamProvider; import org.ligoj.app.iam.UserOrg; import org.ligoj.app.model.Configurable; import org.ligoj.app.model.Node; import org.ligoj.app.model.Subscription; import org.ligoj.app.plugin.prov.dao.ProvBudgetRepository; import org.ligoj.app.plugin.prov.dao.ProvContainerTypeRepository; import org.ligoj.app.plugin.prov.dao.ProvCurrencyRepository; import org.ligoj.app.plugin.prov.dao.ProvDatabaseTypeRepository; import org.ligoj.app.plugin.prov.dao.ProvInstanceTypeRepository; import org.ligoj.app.plugin.prov.dao.ProvLocationRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteContainerRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteDatabaseRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteInstanceRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteStorageRepository; import org.ligoj.app.plugin.prov.dao.ProvQuoteSupportRepository; import org.ligoj.app.plugin.prov.dao.ProvUsageRepository; import org.ligoj.app.plugin.prov.model.AbstractQuote; import org.ligoj.app.plugin.prov.model.ProvLocation; import org.ligoj.app.plugin.prov.model.ProvQuote; import org.ligoj.app.plugin.prov.model.ReservationMode; import org.ligoj.app.plugin.prov.model.ResourceType; import org.ligoj.app.plugin.prov.quote.container.ProvQuoteContainerResource; import org.ligoj.app.plugin.prov.quote.database.ProvQuoteDatabaseResource; import org.ligoj.app.plugin.prov.quote.instance.ProvQuoteInstanceResource; import org.ligoj.app.plugin.prov.quote.storage.ProvQuoteStorageResource; import org.ligoj.app.plugin.prov.quote.support.ProvQuoteSupportResource; import org.ligoj.app.plugin.prov.terraform.TerraformRunnerResource; import org.ligoj.app.resource.ServicePluginLocator; import org.ligoj.app.resource.plugin.AbstractConfiguredServicePlugin; import org.ligoj.app.resource.subscription.SubscriptionResource; import org.ligoj.bootstrap.core.DescribedBean; import org.ligoj.bootstrap.core.dao.RestRepository; import org.ligoj.bootstrap.core.resource.BusinessException; import org.ligoj.bootstrap.model.system.SystemConfiguration; import org.ligoj.bootstrap.resource.system.configuration.ConfigurationResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * The provisioning service. There is complete quote configuration along the subscription. */ @Service @Path(ProvResource.SERVICE_URL) @Produces(MediaType.APPLICATION_JSON) @Transactional @Slf4j public class ProvResource extends AbstractConfiguredServicePlugin<ProvQuote> implements QuoteRelated<ProvQuote> { /** * Plug-in key. */ public static final String SERVICE_URL = BASE_URL + "/prov"; /** * Plug-in key. */ public static final String SERVICE_KEY = SERVICE_URL.replace('/', ':').substring(1); /** * Parameter used for attached currency. */ public static final String PARAMETER_CURRENCY_NAME = SERVICE_KEY + ":currency"; /** * Ordered/mapped columns. */ public static final Map<String, String> ORM_COLUMNS = new HashMap<>(); /** * Parallel configuration. When value is <code>1</code>, parallel stream will be used as often as possible. * Otherwise, sequential will be used. */ public static final String USE_PARALLEL = SERVICE_KEY + ":use-parallel"; @Autowired @Getter protected SubscriptionResource subscriptionResource; @Autowired protected ServicePluginLocator locator; @Autowired @Getter private ProvQuoteRepository repository; @Autowired private ProvCurrencyRepository currencyRepository; @Autowired private ConfigurationResource configuration; @Autowired private ProvLocationRepository locationRepository; @Autowired private ProvTagResource tagResource; @Autowired private ProvNetworkResource networkResource; @Autowired private IamProvider[] iamProvider; // Resources block @Autowired private ProvQuoteInstanceResource qiResource; @Autowired private ProvQuoteDatabaseResource qbResource; @Autowired private ProvQuoteContainerResource qcResource; @Autowired private ProvQuoteSupportResource qspResource; @Autowired private ProvQuoteStorageResource qsResource; // Types block @Autowired private ProvInstanceTypeRepository itRepository; @Autowired private ProvDatabaseTypeRepository btRepository; @Autowired private ProvContainerTypeRepository ctRepository; // Quote block @Autowired private ProvQuoteInstanceRepository qiRepository; @Autowired private ProvQuoteStorageRepository qsRepository; @Autowired private ProvQuoteDatabaseRepository qbRepository; @Autowired private ProvQuoteContainerRepository qcRepository; @Autowired private ProvQuoteSupportRepository qs2Repository; // Billing part @Autowired private ProvUsageRepository usageRepository; @Autowired private ProvBudgetRepository budgetRepository; @Autowired private ProvBudgetResource budgetResource; @Autowired private TerraformRunnerResource runner; @Autowired private ProvResource self; static { ORM_COLUMNS.put("name", "name"); ORM_COLUMNS.put("description", "description"); } @Override public String getKey() { return SERVICE_KEY; } /** * Transform a {@link String} to {@link UserOrg} */ private Function<String, ? extends UserOrg> toUser() { return iamProvider[0].getConfiguration().getUserRepository()::toUser; } /** * Return all available locations for a subscription. * * @param subscription The subscription identifier, will be used to filter the locations from the associated * provider. * @return The all available locations for the given subscription. */ @GET @Path("{subscription:\\d+}/location") @Consumes(MediaType.APPLICATION_JSON) public List<ProvLocation> findLocations(@PathParam("subscription") final int subscription) { final var node = subscriptionResource.checkVisible(subscription).getNode().getId(); return locationRepository.findAll(node); } /** * Return the available processors for a subscription. * * @param node The node identifier, will be used to filter the processors from the associated provider. * @return The available processors for the given subscription. */ @CacheResult(cacheName = "prov-processor") protected Map<String, List<String>> findProcessors(@CacheKey final String node) { final var listC = new HashMap<String, List<String>>(); listC.put("instance", itRepository.findProcessors(node)); listC.put("database", btRepository.findProcessors(node)); listC.put("container", ctRepository.findProcessors(node)); return listC; } /** * Check and return the expected location within the given subscription. The subscription is used to determinate the * related node (provider). Return <code>null</code> when the given name is <code>null</code> or empty. In other * cases, the the name must be found. * * @param node The provider node. * @param name The location name. Case is insensitive. * @return The visible location for the related subscription or <code>null</code>. */ public ProvLocation findLocation(final String node, final String name) { if (StringUtils.isEmpty(name)) { // No check return null; } // Find the scoped location return assertFound(locationRepository.findByName(node, name), name); } @GET @Path("{subscription:\\d+}") @Override public QuoteVo getConfiguration(@PathParam("subscription") final int subscription) { // Check the visibility return getConfiguration(subscriptionResource.checkVisible(subscription)); } /** * Return the quote configuration from a validated subscription. The subscription's visibility must have been * previously checked. * * @param subscription A visible subscription for the current principal. * @return The configuration with computed data. */ public QuoteVo getConfiguration(final Subscription subscription) { final var vo = new QuoteVo(); final var quote = repository.getCompute(subscription.getId()); DescribedBean.copy(quote, vo); vo.copyAuditData(quote, toUser()); vo.setLocation(quote.getLocation()); vo.setInstances(quote.getInstances()); vo.setDatabases(qbRepository.findAll(quote)); vo.setContainers(qcRepository.findAll(quote)); vo.setStorages(qsRepository.findAll(quote)); vo.setUsage(quote.getUsage()); vo.setBudget(quote.getBudget()); vo.setLicense(quote.getLicense()); vo.setRamAdjustedRate(ObjectUtils.defaultIfNull(quote.getRamAdjustedRate(), 100)); vo.setReservationMode(quote.getReservationMode()); vo.setProcessor(quote.getProcessor()); vo.setPhysical(quote.getPhysical()); vo.setTerraformStatus(runner.getTaskInternal(subscription)); vo.setSupports(qs2Repository.findAll(quote)); vo.setLocations(locationRepository.findAll(subscription.getNode().getId())); vo.setTags(tagResource.findAll(quote)); vo.setNetworks(networkResource.findAll(subscription.getId())); vo.setUsages(usageRepository.findAll(quote)); vo.setBudgets(budgetRepository.findAll(quote)); vo.setProcessors(self.findProcessors(subscription.getNode().getTool().getId())); // Also copy the costs final var unbound = quote.isUnboundCost(); vo.setCostNoSupport(new FloatingCost(quote.getCostNoSupport(), quote.getMaxCostNoSupport(), quote.getInitialCost(), quote.getMaxInitialCost(), unbound)); vo.setCostSupport(new FloatingCost(quote.getCostSupport(), quote.getMaxCostSupport(), 0, 0, unbound)); vo.setCost(quote.toFloatingCost()); vo.setCurrency(quote.getCurrency()); return vo; } /** * Return the quote status linked to given subscription. * * @param subscription The parent subscription identifier. * @return The quote status (summary only) linked to given subscription. */ public QuoteLightVo getSubscriptionStatus(final int subscription) { final var vo = new QuoteLightVo(); final var compute = repository.getComputeSummary(subscription).get(0); final var database = repository.getDatabaseSummary(subscription).get(0); final var container = repository.getContainerSummary(subscription).get(0); final var storage = repository.getStorageSummary(subscription).get(0); final var entity = (ProvQuote) compute[0]; DescribedBean.copy(entity, vo); vo.setCost(entity.toFloatingCost()); vo.setLocation(entity.getLocation()); vo.setCurrency(entity.getCurrency()); // Count resources types vo.setNbInstances(((Long) compute[1]).intValue()); vo.setNbDatabases(((Long) database[1]).intValue()); vo.setNbContainers(((Long) container[1]).intValue()); vo.setNbStorages(((Long) storage[1]).intValue()); // Sum up resources vo.setTotalCpu(Stream.of(compute, database, container).mapToDouble(r -> ((Double) r[2])).sum()); vo.setTotalRam(Stream.of(compute, database, container).mapToInt(r -> ((Long) r[3]).intValue()).sum()); vo.setNbPublicAccess(Stream.of(compute, database, container).mapToInt(r -> ((Long) r[4]).intValue()).sum()); vo.setTotalStorage(((Long) storage[2]).intValue()); return vo; } /** * Update the configuration details. The costs and the related resources are refreshed with lookup. * * @param subscription The subscription to update * @param vo The new quote. * @return The new updated cost. */ @PUT @Path("{subscription:\\d+}") @Consumes(MediaType.APPLICATION_JSON) public FloatingCost update(@PathParam("subscription") final int subscription, final QuoteEditionVo vo) { final var entity = getQuoteFromSubscription(subscription); entity.setName(vo.getName()); entity.setDescription(vo.getDescription()); var oldLicense = entity.getLicense(); var oldLocation = entity.getLocation(); var oldUsage = entity.getUsage(); var oldBudget = entity.getBudget(); var oldRamAdjusted = ObjectUtils.defaultIfNull(entity.getRamAdjustedRate(), 100); var oldReservationMode = ObjectUtils.defaultIfNull(entity.getReservationMode(), ReservationMode.RESERVED); var oldProcessor = StringUtils.trimToNull(entity.getProcessor()); var oldPhysical = entity.getPhysical(); entity.setLocation(findLocation(entity.getSubscription().getNode().getId(), vo.getLocation())); entity.setUsage(Optional.ofNullable(vo.getUsage()) .map(u -> findConfiguredByName(usageRepository, u, subscription)).orElse(null)); entity.setBudget(Optional.ofNullable(vo.getBudget()) .map(u -> findConfiguredByName(budgetRepository, u, subscription)).orElse(null)); entity.setLicense(vo.getLicense()); entity.setRamAdjustedRate(ObjectUtils.defaultIfNull(vo.getRamAdjustedRate(), 100)); entity.setReservationMode(vo.getReservationMode()); entity.setProcessor(StringUtils.trimToNull(vo.getProcessor())); entity.setPhysical(vo.getPhysical()); if (vo.isRefresh() || !oldLocation.equals(entity.getLocation()) || !Objects.equals(oldUsage, entity.getUsage()) || !Objects.equals(oldBudget, entity.getBudget()) || !oldRamAdjusted.equals(entity.getRamAdjustedRate()) || oldReservationMode != entity.getReservationMode() || !Objects.equals(oldLicense, entity.getLicense()) || !Objects.equals(oldProcessor, entity.getProcessor()) || !Objects.equals(oldPhysical, entity.getPhysical())) { return refresh(entity); } // No refresh needed return entity.toFloatingCost(); } /** * Compute the total cost and save it into the related quote. All separated compute and storage costs are also * updated. * * @param subscription The subscription to compute * @return The updated computed cost. */ @PUT @Path("{subscription:\\d+}/refresh-cost") @Consumes(MediaType.APPLICATION_JSON) public FloatingCost updateCost(@PathParam("subscription") final int subscription) { // Get the quote (and fetch internal resources) to refresh final var quote = repository.getCompute(subscription); return processCost(quote, BooleanUtils.isTrue(quote.getLeanOnChange())).getTotal(); } /** * Return a parallel stream if allowed. * * @param <T> The stream item type. * @param collection The collection to stream. * @return The parallel or sequential stream. * @see #USE_PARALLEL */ public <T> Stream<T> newStream(final Collection<T> collection) { if (configuration.get(USE_PARALLEL, 1) == 1) { return collection.parallelStream(); } return collection.stream(); } /** * For each resources, execute the given cost function. */ private UpdatedCost processCost(final ProvQuote entity, boolean lean) { final var relatedCosts = Collections .synchronizedMap(new EnumMap<ResourceType, Map<Integer, FloatingCost>>(ResourceType.class)); return processCost(entity, lean, relatedCosts); } /** * For each resources, execute the given cost function. */ private UpdatedCost processCost(final ProvQuote entity, final boolean lean, Map<ResourceType, Map<Integer, FloatingCost>> relatedCosts) { if (lean) { budgetResource.lean(entity, relatedCosts); return processCost(entity, false, relatedCosts); } log.info("Refresh cost started for subscription {}", entity.getSubscription().getId()); // Reset the costs to 0, will be updated further in this process entity.setCostNoSupport(0d); entity.setMaxCostNoSupport(0d); entity.setCost(0d); entity.setMaxCost(0d); entity.setInitialCost(0d); entity.setMaxInitialCost(0d); // Fetch the usages and budgets of this quotes (parallel) entity.getUsages().size(); entity.getBudgets().size(); // Add the compute cost, and update the unbound cost log.info("Refresh cost started for subscription {} / instances ... ", entity.getSubscription().getId()); entity.setUnboundCostCounter((int) newStream(qiRepository.findAll(entity)).map(qiResource::updateCost) .map(fc -> addCost(entity, fc)).filter(FloatingCost::isUnbound).count()); // Add the database cost log.info("Refresh cost started for subscription {} / databases ... ", entity.getSubscription().getId()); newStream(qbRepository.findAll(entity)).map(qbResource::updateCost).forEach(fc -> addCost(entity, fc)); // Add the database cost log.info("Refresh cost started for subscription {} / containers ... ", entity.getSubscription().getId()); newStream(qcRepository.findAll(entity)).map(qcResource::updateCost).forEach(fc -> addCost(entity, fc)); // Add the storage cost log.info("Refresh cost started for subscription {} / storages ... ", entity.getSubscription().getId()); newStream(qsRepository.findAll(entity)).map(qsResource::updateCost).forEach(fc -> addCost(entity, fc)); // Return the rounded computation log.info("Refresh cost started for subscription {} / support ... ", entity.getSubscription().getId()); final var cost = new UpdatedCost(entity.getId()); log.info("Refresh cost finished for subscription {}", entity.getSubscription().getId()); cost.setRelated(relatedCosts); return refreshSupportCost(cost, entity); } private FloatingCost refreshSupportCost(final ProvQuote entity) { final var support = qs2Repository.findAll(entity).stream().map(qspResource::refresh) .reduce(new FloatingCost(0, 0, 0, 0, entity.isUnboundCost()), FloatingCost::add); entity.setCostSupport(round(support.getMin())); entity.setMaxCostSupport(round(support.getMax())); entity.setCost(round(entity.getCostSupport() + entity.getCostNoSupport())); entity.setMaxCost(round(entity.getMaxCostSupport() + entity.getMaxCostNoSupport())); return entity.toFloatingCost(); } /** * Refresh the cost of the support for the whole whole quote. * * @param cost The target cost object to update. * @param quote The source quote. * @return The same target cost parameter. */ public UpdatedCost refreshSupportCost(final UpdatedCost cost, final ProvQuote quote) { cost.setTotal(refreshSupportCost(quote).round()); quote.getSupports().forEach(s -> cost.getRelated().computeIfAbsent(ResourceType.SUPPORT, k -> new HashMap<>()) .put(s.getId(), s.toFloatingCost())); return cost; } /** * Refresh the cost of the support for the whole whole quote related to a resource. * * @param cost The target cost object to update. * @param entity A recently updated resource. * @param <Q> The entity type to refresh. * @return The same target cost parameter. */ public <Q extends AbstractQuote<?>> UpdatedCost refreshSupportCost(final UpdatedCost cost, final Q entity) { return refreshSupportCost(cost, entity.getConfiguration()); } /** * Execute the lookup for each resource and compute the total cost. * * @param subscription The subscription to compute * @return The updated computed cost. */ @PUT @Path("{subscription:\\d+}/refresh") @Consumes(MediaType.APPLICATION_JSON) public FloatingCost refresh(@PathParam("subscription") final int subscription) { return refresh(getQuoteFromSubscription(subscription)); } @Override public FloatingCost refresh(final ProvQuote entity) { updateCurrency(entity); return processCost(entity, true).getTotal(); } /** * Update the currency from the parameter. */ private void updateCurrency(final ProvQuote entity) { entity.setCurrency(Optional.ofNullable( subscriptionResource.getParameters(entity.getSubscription().getId()).get(PARAMETER_CURRENCY_NAME)) .map(currencyRepository::findByName).orElse(null)); } @Override public void create(final int subscription) { // Add an empty quote final var quote = new ProvQuote(); quote.setSubscription(subscriptionRepository.findOne(subscription)); // Associate a default name and description quote.setName(quote.getSubscription().getProject().getName()); final var provider = quote.getSubscription().getNode().getRefined(); final var locations = locationRepository.findAllBy("node.id", provider.getId()); if (locations.isEmpty()) { // No available location, need a catalog to continue throw new BusinessException(SERVICE_KEY + "-no-catalog", provider.getId(), provider.getName()); } quote.setLocation(locations.get(0)); quote.setDescription(quote.getSubscription().getProject().getPkey() + "-> " + provider.getName()); updateCurrency(quote); repository.saveAndFlush(quote); } /** * Check the visibility of a configured entity and check the ownership by the given subscription. * * @param repository The repository managing the entity to find. * @param id The requested configured identifier. * @param subscription The required subscription owner. * @param <K> The {@link Configurable} identifier type. * @param <T> The {@link Configurable} type. * @return The entity where the related subscription if visible. */ public <K extends Serializable, T extends Configurable<ProvQuote, K>> T findConfigured( final RestRepository<T, K> repository, final K id, final int subscription) { // Simple proxy call but with public visibility final var entity = findConfigured(repository, id); if (entity.getConfiguration().getSubscription().getId() != subscription) { // Associated project is not visible, reject the configuration access throw new EntityNotFoundException(id.toString()); } return entity; } @Override public void delete(final int subscription, final boolean remoteData) { // Delete the configuration if available Optional.ofNullable(repository.findBy("subscription.id", subscription)).ifPresent(c -> repository.delete(c)); } @Override public List<Class<?>> getInstalledEntities() { return Arrays.asList(Node.class, SystemConfiguration.class); } }
package com.vikaa.lubbi.core; import com.baidu.frontia.FrontiaApplication; public class BaseApplication extends FrontiaApplication { public final static boolean debug = false; @Override public void onCreate() { super.onCreate(); CrashHandler crashHandler = CrashHandler.getInstance(); crashHandler.init(getApplicationContext()); } }
package org.liquidengine.legui.demo; import org.joml.Vector2f; import org.joml.Vector4f; import org.liquidengine.legui.animation.Animation; import org.liquidengine.legui.component.*; import org.liquidengine.legui.component.event.component.ChangeSizeEvent; import org.liquidengine.legui.component.event.label.LabelContentChangeEvent; import org.liquidengine.legui.component.event.selectbox.SelectBoxChangeSelectionEventListener; import org.liquidengine.legui.component.event.slider.SliderChangeValueEvent; import org.liquidengine.legui.component.event.slider.SliderChangeValueEventListener; import org.liquidengine.legui.component.misc.listener.label.UpdateLabelStyleWidthListener; import org.liquidengine.legui.component.misc.listener.label.UpdateLabelWidthListener; import org.liquidengine.legui.component.optional.Orientation; import org.liquidengine.legui.component.optional.align.HorizontalAlign; import org.liquidengine.legui.component.optional.align.VerticalAlign; import org.liquidengine.legui.event.*; import org.liquidengine.legui.icon.Icon; import org.liquidengine.legui.icon.ImageIcon; import org.liquidengine.legui.image.BufferedImage; import org.liquidengine.legui.listener.CursorEnterEventListener; import org.liquidengine.legui.listener.FocusEventListener; import org.liquidengine.legui.listener.KeyEventListener; import org.liquidengine.legui.listener.MouseClickEventListener; import org.liquidengine.legui.style.Style; import org.liquidengine.legui.style.Style.DisplayType; import org.liquidengine.legui.style.Style.PositionType; import org.liquidengine.legui.style.border.SimpleLineBorder; import org.liquidengine.legui.style.color.ColorConstants; import org.liquidengine.legui.style.font.FontRegistry; import org.liquidengine.legui.style.font.TextDirection; import org.liquidengine.legui.style.shadow.Shadow; import org.liquidengine.legui.theme.Theme; import org.liquidengine.legui.theme.Themes; import org.liquidengine.legui.util.TextUtil; import org.lwjgl.glfw.GLFW; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import static org.liquidengine.legui.component.optional.align.HorizontalAlign.*; import static org.liquidengine.legui.component.optional.align.VerticalAlign.*; import static org.liquidengine.legui.event.MouseClickEvent.MouseClickAction.*; import static org.liquidengine.legui.input.Mouse.MouseButton.MOUSE_BUTTON_LEFT; public class ExampleGui extends Panel { private final Label mouseTargetLabel; private final Label mouseLabel; private final Label upsLabel; private final Label focusedGuiLabel; private final TextArea textArea; private final TextInput textInput; private final Label debugLabel; private ImageView imageView; private CheckBox generateEventsByLayoutManager; public ExampleGui() { this(800, 600); } public ExampleGui(int width, int height) { super(0, 0, width, height); //@formatter:off Panel p1 = new Panel(1 * 20, 10, 10, 10); this.add(p1); p1.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println); Panel p2 = new Panel(2 * 20, 10, 10, 10); this.add(p2); p2.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println); Panel p3 = new Panel(3 * 20, 10, 10, 10); this.add(p3); p3.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println); Panel p4 = new Panel(4 * 20, 10, 10, 10); this.add(p4); p4.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println); Panel p5 = new Panel(5 * 20, 10, 10, 10); this.add(p5); p5.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println); Panel p6 = new Panel(6 * 20, 10, 10, 10); this.add(p6); p6.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println); Panel p7 = new Panel(7 * 20, 10, 10, 10); this.add(p7); p7.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println); Panel p8 = new Panel(8 * 20, 10, 10, 10); this.add(p8); p8.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println); Panel p9 = new Panel(9 * 20, 10, 10, 10); this.add(p9); p9.getListenerMap().addListener(FocusEvent.class, (FocusEventListener) System.out::println); this.add(mouseTargetLabel = new Label("Hello Label 1", 10, height - 30, width - 20, 20)); focusedGuiLabel = new Label("Hello Label 2", 10, height - 50, width - 20, 20); focusedGuiLabel.getStyle().setBorder(new SimpleLineBorder(ColorConstants.red(), 1)); focusedGuiLabel.getListenerMap().addListener(LabelContentChangeEvent.class,new UpdateLabelStyleWidthListener()); this.add(focusedGuiLabel); this.add(debugLabel = new Label("Debug Label", 10, height - 75, width - 20, 20)); this.add(mouseLabel = new Label("Hello Label 3", 130, 30, 100, 20)); this.add(upsLabel = new Label("Hello Label 4", 130, 60, 100, 20)); Label verticalLabel = new Label("VERTICAL LABEL", 500, 500, 50, 50); verticalLabel.getStyle().setBorder(new SimpleLineBorder(ColorConstants.red(), 2)); verticalLabel.setTextDirection(TextDirection.VERTICAL_TOP_DOWN); //@formatter:on verticalLabel.getListenerMap().addListener(KeyEvent.class, (e) -> { if (e.getKey() == GLFW.GLFW_KEY_LEFT) verticalLabel.getPosition().x -= 5; if (e.getKey() == GLFW.GLFW_KEY_RIGHT) verticalLabel.getPosition().x += 5; if (e.getKey() == GLFW.GLFW_KEY_UP) verticalLabel.getPosition().y -= 5; if (e.getKey() == GLFW.GLFW_KEY_DOWN) verticalLabel.getPosition().y += 5; if (e.getKey() == GLFW.GLFW_KEY_KP_1) verticalLabel.setTextDirection(TextDirection.HORIZONTAL); if (e.getKey() == GLFW.GLFW_KEY_KP_2) verticalLabel.setTextDirection(TextDirection.VERTICAL_TOP_DOWN); if (e.getKey() == GLFW.GLFW_KEY_KP_3) verticalLabel.setTextDirection(TextDirection.VERTICAL_DOWN_TOP); }); //@formatter:off this.add(verticalLabel); this.add(createImageWrapperWidgetWithImage()); this.add(createButtonWithTooltip()); generateEventsByLayoutManager = new CheckBox("Generate events by layout manager", 20, 200, 200, 20); this.add(generateEventsByLayoutManager); this.add(createCheckboxWithAnimation(generateEventsByLayoutManager)); ProgressBar progressBar = new ProgressBar(250, 10, 100, 10); progressBar.setValue(50); this.add(progressBar); { RadioButtonGroup radioButtonGroup = new RadioButtonGroup(); RadioButton radioButton1 = new RadioButton(250, 30, 100, 20); RadioButton radioButton2 = new RadioButton(250, 60, 100, 20); radioButton1.setChecked(true); radioButton2.setChecked(false); radioButton1.setRadioButtonGroup(radioButtonGroup); radioButton2.setRadioButtonGroup(radioButtonGroup); this.add(radioButton1); this.add(radioButton2); } Slider slider1 = new Slider(250, 90, 100, 20); slider1.setMinValue(-1f); slider1.setMaxValue(1f); slider1.setStepSize(.1f); slider1.setValue(0f); final Tooltip slider1Tooltip = new Tooltip(); slider1Tooltip.setSize(100, 20); slider1Tooltip.setPosition(slider1.getSize().x + 2, 0); slider1Tooltip.getTextState().setText("Value: " + String.format("%.2f", slider1.getValue())); slider1.addSliderChangeValueEventListener((SliderChangeValueEventListener) event -> { slider1Tooltip.getTextState().setText(String.format("Value: %.2f", event.getNewValue())); slider1Tooltip.setSize(100, 20); }); slider1.setTooltip(slider1Tooltip); this.add(slider1); Slider slider2 = new Slider(220, 90, 20, 100, 50f); slider2.setOrientation(Orientation.VERTICAL); this.add(slider2); textInput = new TextInput(250, 130, 100, 30); textInput.getStyle().setHorizontalAlign(RIGHT); textInput.getListenerMap().addListener(KeyEvent.class, (KeyEventListener) event -> { if (event.getKey() == GLFW.GLFW_KEY_F1 && event.getAction() == GLFW.GLFW_RELEASE) { textInput.getStyle().setHorizontalAlign(LEFT); } else if (event.getKey() == GLFW.GLFW_KEY_F2 && event.getAction() == GLFW.GLFW_RELEASE) { textInput.getStyle().setHorizontalAlign(CENTER); } else if (event.getKey() == GLFW.GLFW_KEY_F3 && event.getAction() == GLFW.GLFW_RELEASE) { textInput.getStyle().setHorizontalAlign(RIGHT); } }); this.add(textInput); Widget widget = new Widget("Hello widget", 250, 170, 100, 100); widget.setTitleHeight(20); widget.getTitleContainer().getStyle().getBackground().setColor(ColorConstants.lightGreen()); widget.getStyle().setTextColor(ColorConstants.black()); String innerText = "Inner Widget; Resize events: "; Widget inner = new Widget(innerText + 0); inner.setResizable(false); inner.getStyle().setPosition(PositionType.RELATIVE); inner.getStyle().getFlexStyle().setFlexGrow(1); inner.getStyle().setMargin(10f); inner.getContainer().getStyle().getBackground().setColor(ColorConstants.lightGreen()); widget.getContainer().getStyle().setDisplay(DisplayType.FLEX); widget.getContainer().add(inner); AtomicInteger counter = new AtomicInteger(); inner.getListenerMap().addListener(ChangeSizeEvent.class, e -> { counter.getAndIncrement(); inner.getTitle().getTextState().setText(innerText + "; Resize events: " + counter.get()); }); this.add(widget); Button turnWidVisible = new Button("", 360, 280, 20, 20); turnWidVisible.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> { if (CLICK == (event.getAction())) { widget.show(); } }); Icon bgIm = new ImageIcon(new BufferedImage("org/liquidengine/legui/demo/1.png")); bgIm.setSize(new Vector2f(20, 20)); turnWidVisible.getStyle().getBackground().setIcon(bgIm); Icon hbgIm = new ImageIcon(new BufferedImage("org/liquidengine/legui/demo/2.png")); hbgIm.setSize(new Vector2f(20, 20)); // turnWidVisible.setHoveredBackgroundIcon(hbgIm); Icon pbIm = new ImageIcon(new BufferedImage("org/liquidengine/legui/demo/3.png")); pbIm.setSize(new Vector2f(20, 20)); // turnWidVisible.setPressedBackgroundIcon(pbIm); this.add(turnWidVisible); Widget widget2 = new Widget("Hello 2 widget", 250, 310, 100, 100); widget2.setTitleHeight(20); widget2.setCloseButtonColor(ColorConstants.white()); widget2.getCloseButton().getStyle().getBackground().setColor(ColorConstants.black()); widget2.getTitleContainer().getStyle().getBackground().setColor(ColorConstants.lightGreen()); widget2.getStyle().setTextColor(ColorConstants.black()); widget2.setDraggable(false); widget2.setMinimizable(true); Button turnDraggable = new Button("Draggable", 10, 10, 80, 20); turnDraggable.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> { if (event.getAction() == CLICK) { Dialog dialog = new Dialog("Question:", 300, 100); Label questionLabel = new Label("Are you sure want to turn " + (widget2.isDraggable() ? "off" : "on") + "this widget draggable?", 10, 10, 200, 20); Button yesButton = new Button("Yes", 10, 50, 50, 20); Button noButton = new Button("No", 70, 50, 50, 20); yesButton.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) e -> { if (CLICK == e.getAction()) { widget2.setDraggable(!widget2.isDraggable()); dialog.close(); } }); noButton.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) e -> { if (CLICK == e.getAction()) { dialog.close(); } }); dialog.getContainer().add(questionLabel); dialog.getContainer().add(yesButton); dialog.getContainer().add(noButton); dialog.show(event.getFrame()); } }); widget2.getContainer().add(turnDraggable); this.add(widget2); Button turnWidVisible2 = new Button("", 360, 310, 20, 20); turnWidVisible2.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> { if (CLICK == event.getAction()) { widget2.show(); } }); this.add(turnWidVisible2); Widget widget3 = new Widget("Hello 2 widget", 250, 420, 100, 100); widget3.setTitleHeight(20); widget3.setTitleEnabled(false); widget3.getTitleContainer().getStyle().getBackground().setColor(ColorConstants.lightGreen()); widget3.setCloseable(false); widget3.setMinimizable(true); widget3.getStyle().setTextColor(ColorConstants.black()); this.add(widget3); Button turnWidVisible3 = new Button("", 360, 340, 20, 20); turnWidVisible3.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> { if (CLICK == event.getAction()) { widget3.show(); } }); this.add(turnWidVisible3); widget3.getContainer().add(new Panel(5, 5, 20, 20)); widget3.getContainer().add(new Panel(30, 5, 20, 20)); widget3.getContainer().add(new Panel(30, 30, 20, 20)); widget3.getContainer().add(new Panel(5, 30, 20, 20)); Button b = new Button(55, 5, 40, 20); b.getStyle().setFont(FontRegistry.MATERIAL_ICONS_REGULAR); b.getStyle().setVerticalAlign(MIDDLE); b.getStyle().setHorizontalAlign(CENTER); b.getStyle().setFontSize(20f); String up = TextUtil.cpToStr(0xE5D8); String down = TextUtil.cpToStr(0xE5DB); b.getTextState().setText(down); b.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> { if (event.getAction() == CLICK) { widget3.setTitleEnabled(!widget3.isTitleEnabled()); b.getTextState().setText(widget3.isTitleEnabled() ? up : down); // widget3.setResizable(!widget3.isResizable()); } }); widget3.getContainer().add(b); Button b2 = new Button(55, 30, 40, 20); b2.getStyle().setVerticalAlign(MIDDLE); b2.getStyle().setHorizontalAlign(CENTER); b2.getStyle().setFontSize(20f); String up2 = "-"; String down2 = "+"; b2.getTextState().setText(down2); b2.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> { if (event.getAction() == CLICK) { widget3.setCloseable(!widget3.isCloseable()); b2.getTextState().setText(widget3.isCloseable() ? up2 : down2); } }); widget3.getContainer().add(b2); widget3.getStyle().setMinWidth(100f); widget3.getStyle().setMinHeight(50f); widget3.getStyle().setMaxWidth(400f); widget3.getStyle().setMaxHeight(150f); ScrollBar scrollBar1 = new ScrollBar(360, 170, 20, 100, 20); scrollBar1.setOrientation(Orientation.VERTICAL); scrollBar1.setVisibleAmount(20); scrollBar1.setArrowsEnabled(true); scrollBar1.getStyle().getBackground().setColor(ColorConstants.white()); scrollBar1.setScrollColor(ColorConstants.darkGray()); scrollBar1.setArrowColor(ColorConstants.darkGray()); scrollBar1.getStyle().setBorder(new SimpleLineBorder(ColorConstants.red(), 1)); this.add(scrollBar1); ScrollBar scrollBar11 = new ScrollBar(385, 170, 7, 100, 20); scrollBar11.setOrientation(Orientation.VERTICAL); scrollBar11.setVisibleAmount(20); scrollBar11.setArrowsEnabled(false); scrollBar11.getStyle().getBackground().setColor(ColorConstants.white()); scrollBar11.setScrollColor(ColorConstants.darkGray()); scrollBar11.getStyle().setBorder(new SimpleLineBorder(ColorConstants.darkGray(), 1)); scrollBar11.getStyle().setBorderRadius(null); this.add(scrollBar11); ScrollBar scrollBar2 = new ScrollBar(250, 280, 100, 20, 20); scrollBar2.setOrientation(Orientation.HORIZONTAL); scrollBar2.setVisibleAmount(20); scrollBar2.setArrowsEnabled(true); scrollBar2.getStyle().setBorder(new SimpleLineBorder(ColorConstants.black(), 1)); scrollBar2.getStyle().getBackground().setColor(ColorConstants.darkGray()); scrollBar2.setScrollColor(ColorConstants.white()); scrollBar2.setArrowColor(ColorConstants.white()); this.add(scrollBar2); Panel panel1 = new Panel(420, 170, 100, 100); panel1.getStyle().getBackground().setColor(ColorConstants.blue()); this.add(panel1); Panel panel2 = new Panel(470, 170, 100, 100); panel2.getStyle().getBackground().setColor(ColorConstants.green()); this.add(panel2); createButtonWithTooltip().getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> { MouseClickEvent.MouseClickAction action = event.getAction(); if (CLICK == action) { mouseTargetLabel.getStyle().setDisplay(mouseTargetLabel.isVisible() ? Style.DisplayType.NONE : Style.DisplayType.MANUAL); } if (RELEASE == action) { System.out.println("RELEASE"); } if (PRESS == action) { System.out.println("PRESS"); } }); ScrollablePanel scrollablePanel = new ScrollablePanel(420, 10, 250, 150); scrollablePanel.getStyle().getBackground().setColor(1, 1, 1, 1); scrollablePanel.getContainer().setSize(300, 200); ScrollablePanel scp = new ScrollablePanel(10, 10, 150, 100); scp.getContainer().setSize(300, 300); scp.getContainer().add(new TextInput("Hello Scrollable", 10, 10, 150, 20)); scrollablePanel.getContainer().add(scp); this.add(scrollablePanel); slider2.getListenerMap().addListener(SliderChangeValueEvent.class, (SliderChangeValueEventListener) event -> scrollablePanel .setHorizontalScrollBarHeight(event.getNewValue() / 2f + 10) ); slider1.getListenerMap().addListener(SliderChangeValueEvent.class, (SliderChangeValueEventListener) event -> scrollablePanel.getHorizontalScrollBar() .setArrowSize(event.getNewValue() / 4f + 10) ); textArea = new TextArea(420, 280, 150, 100); textArea.getTextState().setText("ABC DEF GH\r\nI JKL MNO PQR\nSTU VWXYZ"); textArea.setCaretPosition(12); textArea.getTextAreaField().getStyle().setHorizontalAlign(CENTER); textArea.getTextAreaField().getStyle().setVerticalAlign(BOTTOM); this.add(textArea); textArea.getTextAreaField().getListenerMap().addListener(KeyEvent.class, (KeyEventListener) event -> { if (event.getKey() == GLFW.GLFW_KEY_F1 && event.getAction() == GLFW.GLFW_RELEASE) { textArea.getTextAreaField().getStyle().setHorizontalAlign(LEFT); } else if (event.getKey() == GLFW.GLFW_KEY_F2 && event.getAction() == GLFW.GLFW_RELEASE) { textArea.getTextAreaField().getStyle().setHorizontalAlign(CENTER); } else if (event.getKey() == GLFW.GLFW_KEY_F3 && event.getAction() == GLFW.GLFW_RELEASE) { textArea.getTextAreaField().getStyle().setHorizontalAlign(RIGHT); } else if (event.getKey() == GLFW.GLFW_KEY_F5 && event.getAction() == GLFW.GLFW_RELEASE) { textArea.getTextAreaField().getStyle().setVerticalAlign(TOP); } else if (event.getKey() == GLFW.GLFW_KEY_F6 && event.getAction() == GLFW.GLFW_RELEASE) { textArea.getTextAreaField().getStyle().setVerticalAlign(MIDDLE); } else if (event.getKey() == GLFW.GLFW_KEY_F7 && event.getAction() == GLFW.GLFW_RELEASE) { textArea.getTextAreaField().getStyle().setVerticalAlign(BOTTOM); } else if (event.getKey() == GLFW.GLFW_KEY_F8 && event.getAction() == GLFW.GLFW_RELEASE) { textArea.getTextAreaField().getStyle().setVerticalAlign(BASELINE); } }); textArea.getTextAreaField().getListenerMap().addListener(DropEvent.class, e->{ String text = textArea.getTextAreaField().getTextState().getText(); StringBuilder t = new StringBuilder(text); List<String> files = e.getFiles(); for (String file : files) { t.append(file).append("\n"); } textArea.getTextAreaField().getTextState().setText(t.toString()); textArea.getTextAreaField().getTextState().setCaretPosition(t.length()-1); }); Label passLabel = new Label("Password:", 420, 390, 150, 15); this.add(passLabel); PasswordInput caretp = new PasswordInput(420, 405, 150, 20); caretp.getStyle().setHorizontalAlign(CENTER); this.add(caretp); TextInput inpur = new TextInput(420, 430, 50, 35); inpur.getTextState().setText("00"); inpur.getStyle().setFontSize(35f); inpur.getStyle().setHorizontalAlign(CENTER); inpur.getStyle().setVerticalAlign(MIDDLE); inpur.getStyle().getBackground().setColor(ColorConstants.white()); this.add(inpur); SelectBox<Object> selectBox = new SelectBox<>(20, 260, 100, 20); selectBox.addElement(0.25f); selectBox.addElement(0.5d); selectBox.addElement(1); selectBox.addElement("MyText"); selectBox.addElement(new Long(2L)); selectBox.setVisibleCount(7); selectBox.setElementHeight(20); selectBox.addSelectBoxChangeSelectionEventListener((SelectBoxChangeSelectionEventListener<Object>) event -> { Dialog dialog = new Dialog("SelectBox clicked", 300, 100); Label valueLabel = new Label("Value: " + event.getNewValue().toString(), 10, 10, 300, 20); dialog.getContainer().add(valueLabel); Label classLabel = new Label("Class: " + event.getNewValue().getClass().getName(), 10, 30, 300, 20); dialog.getContainer().add(classLabel); dialog.show(event.getFrame()); }); this.add(selectBox); Button sbb = new Button("Add element", 130, 260, 70, 20); sbb.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> { if (event.getAction() == CLICK) { selectBox.addElement("Dynamic#" + selectBox.getElements().size()); } }); this.add(sbb); this.add(createToggleButtonWithLongTooltip()); //@formatter:on this.add(createSwitchThemeButton()); this.add(createShadowWidget()); } public CheckBox getGenerateEventsByLayoutManager() { return generateEventsByLayoutManager; } private Widget createImageWrapperWidgetWithImage() { Widget imageWrapper = new Widget(20, 30, 100, 100); imageWrapper.setAscendible(true); imageWrapper.setTitleEnabled(true); imageView = new ImageView(new BufferedImage("org/liquidengine/legui/demo/1.jpg")); imageView.setPosition(15, 5); imageView.setSize(70, 70); imageView.getStyle().setBorderRadius(10f); imageWrapper.getTitle().getTextState().setText("Ascendible widget"); imageWrapper.getContainer().add(imageView); imageWrapper.setCloseable(false); return imageWrapper; } private Button createButtonWithTooltip() { Button button = new Button(20, 170, 50, 20); /*button.getStyle().getBackground().setColor(new Vector4f(1));*/ button.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) System.out::println); button.setTooltip(new Tooltip("Just button")); button.getTooltip().setPosition(0, 25); button.getTooltip().getSize().set(50, 60); button.getTooltip().getStyle().setPadding(4f); int[] idv = {0}; button.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) (MouseClickEvent event) -> { if (event.getAction().equals(CLICK)) { idv[0]++; HorizontalAlign h; VerticalAlign v; int hh = idv[0] % 3; int vv = (idv[0] / 3) % 3; switch (hh) { case 0: h = LEFT; break; case 1: h = CENTER; break; case 2: default: h = RIGHT; break; } switch (vv) { case 0: v = TOP; break; case 1: v = MIDDLE; break; case 2: default: v = BOTTOM; break; } System.out.println(h + " " + v); button.getTooltip().getStyle().setHorizontalAlign(h); button.getTooltip().getStyle().setVerticalAlign(v); } }); return button; } private CheckBox createCheckboxWithAnimation(CheckBox checkBox1) { CheckBox checkBox2 = new CheckBox(20, 230, 100, 20); checkBox2.getStyle().getBackground().setColor(new Vector4f(1, 0, 0, 1)); checkBox2.getStyle().setPadding(5f, 10f, 5f, 20f); checkBox2.setChecked(true); checkBox2.getListenerMap().addListener(CursorEnterEvent.class, (CursorEnterEventListener) event -> { boolean entered = event.isEntered(); Vector4f newColor = ColorConstants.green(); if (entered) { createColorAnimationOnHover(event.getTargetComponent(), newColor, checkBox2).startAnimation(); } }); checkBox2.getListenerMap().addListener(CursorEnterEvent.class, (CursorEnterEventListener) event -> { boolean entered = event.isEntered(); Vector4f newColor = ColorConstants.red(); if (entered) { createColorAnimationOnHover(event.getTargetComponent(), newColor, checkBox1).startAnimation(); } }); return checkBox2; } private ToggleButton createToggleButtonWithLongTooltip() { ToggleButton toggleButton = new ToggleButton("", 100, 170, 40, 20); Icon bgImageNormal = new ImageIcon(new BufferedImage("org/liquidengine/legui/demo/toggle.png")); toggleButton.getListenerMap().addListener(CursorEnterEvent.class, (CursorEnterEventListener) System.out::println); toggleButton.setTooltip(new Tooltip("Just toggle button with long tooltipText text")); toggleButton.getListenerMap().addListener(CursorEnterEvent.class, (CursorEnterEventListener) event -> { if (event.isEntered()) { getColorAnimation(toggleButton, ColorConstants.blue()).startAnimation(); } else { getColorAnimation(toggleButton, ColorConstants.red()).startAnimation(); } }); toggleButton.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> getSlideImageOnClick(toggleButton, bgImageNormal).startAnimation()); toggleButton.getTooltip().setPosition(45, 0); toggleButton.getTooltip().getSize().set(140, 40); toggleButton.getTooltip().getStyle().getBackground().setColor(ColorConstants.darkGray()); toggleButton.getTooltip().getStyle().setTextColor(ColorConstants.white()); toggleButton.getTooltip().getStyle().setPadding(4f); int[] id = {0}; toggleButton.getListenerMap().addListener(MouseClickEvent.class, (MouseClickEventListener) event -> { if (event.getAction().equals(CLICK)) { id[0]++; HorizontalAlign h = LEFT; VerticalAlign v = TOP; int hh = id[0] % 3; int vv = (id[0] / 3) % 3; switch (hh) { case 0: h = LEFT; break; case 1: h = CENTER; break; case 2: h = RIGHT; break; } switch (vv) { case 0: v = TOP; break; case 1: v = MIDDLE; break; case 2: v = BOTTOM; break; } System.out.println(h + " " + v); toggleButton.getTooltip().getStyle().setHorizontalAlign(h); toggleButton.getTooltip().getStyle().setVerticalAlign(v); } }); bgImageNormal.setSize(new Vector2f(100 * 40 / 60, 20)); bgImageNormal.setPosition(new Vector2f(40 - 100 * 40 / 60, 0)); toggleButton.getStyle().getBackground().setIcon(bgImageNormal); return toggleButton; } private Button createSwitchThemeButton() { final Theme[] current = {Themes.getDefaultTheme()}; final Theme[] list = {Themes.FLAT_DARK, Themes.FLAT_PETERRIVER, Themes.FLAT_PETERRIVER_DARK, Themes.FLAT_WHITE}; final int[] themeIndex = {0}; String text = "Switch theme "; Button switchTheme = new Button(text, 600, 400, 120, 30); switchTheme.getListenerMap().addListener(MouseClickEvent.class, switchThemeClickListener(current, list, themeIndex, switchTheme)); return switchTheme; } private Widget createShadowWidget() { Widget shadowWidget = new Widget(20, 310, 200, 120); shadowWidget.getTitleTextState().setText("Shadow test widget"); shadowWidget.setCloseable(false); shadowWidget.setResizable(false); shadowWidget.setAscendible(true); shadowWidget.getStyle().setShadow(new Shadow()); shadowWidget.getStyle().getShadow().setColor(ColorConstants.red()); Slider hOffsetSlider = new Slider(110, 5 + 20 * 0, 80, 10); shadowWidget.getContainer().add(hOffsetSlider); hOffsetSlider.setValue(50f); hOffsetSlider.addSliderChangeValueEventListener((e) -> shadowWidget.getStyle().getShadow().sethOffset(hOffsetSlider.getValue() - 50f) ); Label hOffsetLabel = new Label(10, 5 + 20 * 0, 90, 10); hOffsetLabel.getStyle().setFontSize(18f); hOffsetLabel.getHoveredStyle().setFontSize(20f); hOffsetLabel.getTextState().setText("HOffset: "); shadowWidget.getContainer().add(hOffsetLabel); Slider vOffsetSlider = new Slider(110, 5 + 20 * 1, 80, 10); shadowWidget.getContainer().add(vOffsetSlider); vOffsetSlider.setValue(50f); vOffsetSlider.addSliderChangeValueEventListener((e) -> shadowWidget.getStyle().getShadow().setvOffset(vOffsetSlider.getValue() - 50f) ); Label vOffsetLabel = new Label(10, 5 + 20 * 1, 90, 10); vOffsetLabel.getTextState().setText("VOffset: "); shadowWidget.getContainer().add(vOffsetLabel); Slider blurSlider = new Slider(110, 5 + 20 * 2, 80, 10); shadowWidget.getContainer().add(blurSlider); blurSlider.addSliderChangeValueEventListener((e) -> shadowWidget.getStyle().getShadow().setBlur(blurSlider.getValue()) ); Label blurLabel = new Label(10, 5 + 20 * 2, 90, 10); blurLabel.getTextState().setText("Blur: "); shadowWidget.getContainer().add(blurLabel); Slider spreadSlider = new Slider(110, 5 + 20 * 3, 80, 10); shadowWidget.getContainer().add(spreadSlider); spreadSlider.setValue(50f); spreadSlider.addSliderChangeValueEventListener((e) -> shadowWidget.getStyle().getShadow().setSpread(spreadSlider.getValue() - 50f) ); Label spreadLabel = new Label(10, 5 + 20 * 3, 90, 10); spreadLabel.getTextState().setText("Spread: "); shadowWidget.getContainer().add(spreadLabel); Slider transparencySlider = new Slider(110, 5 + 20 * 4, 80, 10); shadowWidget.getContainer().add(transparencySlider); transparencySlider.addSliderChangeValueEventListener((e) -> { shadowWidget.getStyle().getBackground().getColor().w = 1 - transparencySlider.getValue() / 100f; shadowWidget.getContainer().getStyle().getBackground().getColor().w = 1 - transparencySlider.getValue() / 100f; }); Label transparencyLabel = new Label(10, 5 + 20 * 4, 90, 10); transparencyLabel.getTextState().setText("W Transparency: "); shadowWidget.getContainer().add(transparencyLabel); return shadowWidget; } private Animation createColorAnimationOnHover(Component component, Vector4f newColor, Component targetComponent) { return new Animation() { private Vector4f initialColor; private Vector4f colorRange; private double time; @Override protected void beforeAnimation() { initialColor = new Vector4f(targetComponent.getStyle().getBackground().getColor()); colorRange = newColor.sub(initialColor); } @Override protected boolean animate(double delta) { time += delta; targetComponent.getStyle().getBackground().getColor().set(new Vector4f(initialColor) .add(new Vector4f(colorRange) .mul((float) Math.abs(Math.sin(time * 2))))); return !component.isHovered(); } @Override protected void afterAnimation() { targetComponent.getStyle().getBackground().getColor().set(initialColor); } }; } private MouseClickEventListener switchThemeClickListener(Theme[] current, Theme[] list, int[] index, Button switchTheme) { return event -> { if (event.getAction().equals(CLICK) && event.getButton().equals(MOUSE_BUTTON_LEFT)) { Theme curr = current[0]; if (index[0] < list.length && index[0] > -1) { curr = list[index[0]]; index[0] = (index[0] + 1) % list.length; } else { index[0] = 0; curr = list[0]; } Themes.setDefaultTheme(curr); Themes.getDefaultTheme().applyAll(event.getFrame()); } }; } private Animation getSlideImageOnClick(ToggleButton toggleButton, Icon bgImageNormal) { return new Animation() { private float initialPosition; private double time; private double spentTime; private float endPosition; @Override protected void beforeAnimation() { time = 0.5d; spentTime = 0; initialPosition = bgImageNormal.getPosition().x; if (toggleButton.isToggled()) { endPosition = 0; } else { endPosition = toggleButton.getSize().x - bgImageNormal.getSize().x; } } @Override protected boolean animate(double delta) { spentTime += delta; float percentage = (float) (spentTime / time); bgImageNormal.getPosition().x = initialPosition + (endPosition - initialPosition) * percentage; return spentTime >= time; } @Override protected void afterAnimation() { bgImageNormal.getPosition().x = endPosition; } }; } private Animation getColorAnimation(ToggleButton toggleButton, Vector4f targetColor) { return new Animation() { private Vector4f baseColor; private Vector4f endColor; private Vector4f colorVector; private double time; private double spentTime; @Override protected void beforeAnimation() { time = 1.5d; spentTime = 0; baseColor = new Vector4f(toggleButton.getStyle().getBackground().getColor()); endColor = targetColor; colorVector = new Vector4f(endColor).sub(baseColor); } @Override protected boolean animate(double delta) { spentTime += delta; float percentage = (float) (spentTime / time); Vector4f newColor = new Vector4f(baseColor).add(new Vector4f(colorVector).mul(percentage)); toggleButton.getStyle().getBackground().setColor(newColor); return spentTime >= time; } @Override protected void afterAnimation() { toggleButton.getStyle().getBackground().setColor(endColor); } }; } public TextArea getTextArea() { return textArea; } public ImageView getImageView() { return imageView; } public void setImageView(ImageView imageView) { this.imageView = imageView; } public Label getMouseTargetLabel() { return mouseTargetLabel; } public Label getMouseLabel() { return mouseLabel; } public Label getUpsLabel() { return upsLabel; } public Label getFocusedGuiLabel() { return focusedGuiLabel; } public TextInput getTextInput() { return textInput; } public Label getDebugLabel() { return debugLabel; } }
package sandbox.benchmark; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.app.GameSettings; import com.almasb.fxgl.entity.*; import com.almasb.fxgl.entity.level.tiled.TMXLevelLoader; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TextField; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Text; import kotlin.Unit; import kotlin.system.TimingKt; import java.util.List; import static com.almasb.fxgl.dsl.FXGL.*; /** * This is a sample for testing the performance of tiled map loading * * @author Adam Bocco (adam.bocco) (adam.bocco@gmail.com) */ public class TiledBenchmarkSample extends GameApplication { private static String currentMapSelection = ""; private static Text status; @Override protected void initSettings(GameSettings settings) { settings.setWidth(600); settings.setHeight(500); settings.setTitle("TiledBenchmarkSample"); settings.setVersion("0.1"); } @Override protected void initUI() { List<String> mapURLsList = List.of("tmx/zeph/test_map.tmx", "tmx/benchmarking/csv_1layer_noflip_500x500.tmx", "tmx/benchmarking/gzip_5layers_noflip_500x500.tmx", "tmx/benchmarking/gzip_10layers_noflip_500x500.tmx", "tmx/benchmarking/csv_1layer_verticalflip_500x500.tmx", "tmx/benchmarking/csv_1layer_horizontalflip_500x500.tmx", "tmx/benchmarking/csv_1objectlayer_noflip_100x100.tmx", "tmx/benchmarking/csv_1objectlayer_verticalflip_100x100.tmx", "tmx/benchmarking/csv_1objectlayer_horizontalflip_100x100.tmx"); ObservableList<String> mapURLs = FXCollections.observableList(mapURLsList); Text mapChoicesLabel = getUIFactoryService().newText("Map Choices: ", Color.BLACK, 14); ChoiceBox<String> mapChoices = getUIFactoryService().newChoiceBox(mapURLs); mapChoices.setPrefWidth(400); mapChoices.setOnAction(actionEvent -> currentMapSelection = mapChoices.getValue()); mapChoices.getSelectionModel().selectFirst(); Text iterationsLabel = getUIFactoryService().newText("Iterations: ", Color.BLACK, 14); TextField iterationsInput = new TextField(); iterationsInput.setText("1"); Button startTestButton = new Button("Start"); startTestButton.setOnAction(actionEvent -> { int iterations; try { iterations = Integer.parseInt(iterationsInput.getText()); } catch (NumberFormatException e) { System.out.println("Enter a number of iterations"); status.setText("Enter a number of iterations"); return; } if (currentMapSelection.equals("")) { System.out.println("Choose a map to test"); status.setText("Choose a map to test"); } else { status.setText("Running test..."); runMap(currentMapSelection, iterations); } }); Text statusLabel = getUIFactoryService().newText("Status: ", Color.BLACK, 14); status = getUIFactoryService().newText("Choose a test map", Color.BLACK, 14); addUINode(new VBox(5, mapChoicesLabel, mapChoices, iterationsLabel, iterationsInput, startTestButton, statusLabel, status ), 10, 20); } @Override protected void initGame() { getGameWorld().addEntityFactory(new TiledBenchmarkFactory()); } public static void main(String[] args) { launch(args); } public static void runMap(String mapURL, int iterations) { getExecutor().startAsync(() -> { long totalTime = 0L; for (int i = 0; i < iterations; i++) { var time = TimingKt.measureNanoTime(() -> { var level = getAssetLoader().loadLevel(mapURL, new TMXLevelLoader()); return Unit.INSTANCE; }); totalTime += time; System.out.printf("Iteration " + (i+1) + " : %.2f seconds\n", time / 1_000_000_000.0); } String results = "Map: " + currentMapSelection + "\nIterations: " + iterations + "\nAverage: " + (totalTime/iterations) / 1_000_000_000.0; status.setText(results); System.out.println(results); }); } public static class TiledBenchmarkFactory implements EntityFactory { @Spawns("nav,portal,") public Entity spawnTiledObject(SpawnData data) { return entityBuilder(data).build(); } } }
package com.loca.addressbook.userinterface.commands; import com.loca.addressbook.exceptions.InvalidCommandParameterException; import com.loca.addressbook.userinterface.ConsolePrinter; import java.util.List; public class HelpCommand implements Command { private static final String NEW_LINE = "\n"; private static final String TAB = "\t"; private CommandType commandType = CommandType.HELP; private List<String> parameters; private ConsolePrinter consolePrinter; public HelpCommand (ConsolePrinter consolePrinter, List<String> parameters) { this.parameters = parameters; this.consolePrinter = consolePrinter; } @Override public String getName() { return commandType.getCommandName(); } @Override public String getDescription() { return commandType.getDescription(); } @Override public void execute() throws InvalidCommandParameterException { if (parameters.size() != commandType.getArgumentCount()) { throw new InvalidCommandParameterException(); } String helpText = makeHelpText(); showHelpText(helpText); } private String makeHelpText() { StringBuilder helpText = new StringBuilder(100); for (CommandType commandType: CommandType.values()) { helpText.append(commandType.getCommandName()); helpText.append(TAB); helpText.append(commandType.getDescription()); helpText.append(NEW_LINE); } return helpText.toString(); } private void showHelpText(String helpText) { consolePrinter.print(helpText); } }
package org.noear.weed.wrap; import org.noear.weed.DbContext; import org.noear.weed.SQLBuilder; /** * BETWEEN AND :: >= + <= * */ public class DbOracleAdapter implements DbAdapter{ @Override public boolean excludeFormat(String str) { return str.startsWith("\""); } @Override public String schemaFormat(String sc) { return "\"" + sc + "\""; } @Override public String tableFormat(String tb) { String[] ss = tb.split("\\."); if(ss.length > 1){ return "\"" + ss[0] + "\".\"" + ss[1].toUpperCase() + "\""; }else{ return "\"" + ss[0].toUpperCase() + "\""; } } @Override public String columnFormat(String col) { String[] ss = col.split("\\."); if(ss.length > 1){ return "\"" + ss[0] + "\".\"" + ss[0] + "\""; }else{ return "\"" + ss[0] + "\""; } } @Override public void selectPage(DbContext ctx, String table1, SQLBuilder sqlB, StringBuilder orderBy, int start, int size) { StringBuilder sb = new StringBuilder(); if (orderBy == null) { String tb = table1.split(" ")[0].replace("$.","").trim(); String pk = ctx.getTablePk1(tb); if(pk == null){ throw new RuntimeException("Please add orderBy"); } sb.append("SELECT ROW_NUMBER() OVER(ORDER BY ").append(columnFormat(pk)).append(") AS _ROW_NUM, "); } else { sb.append("SELECT ROW_NUMBER() OVER(").append(orderBy).append(") AS _ROW_NUM, "); } sqlB.insert(0, sb); //_ROW_NUM,1 StringBuilder sb2 = new StringBuilder(); sb2.append("SELECT _x.* FROM (").append(sqlB.builder).append(") _x "); sb2.append(" WHERE _x._ROW_NUM BETWEEN ") .append(start + 1).append(" AND ") .append(start + size); sqlB.builder = sb2; } @Override public void selectTop(DbContext ctx, String table1, SQLBuilder sqlB, StringBuilder orderBy, int size) { sqlB.insert(0,"SELECT "); if(sqlB.indexOf(" WHERE ") > 0){ sqlB.append(" AND"); }else{ sqlB.append(" WHERE"); } sqlB.append(" ROWNUM <= ") .append(size); if(orderBy!=null){ sqlB.append(orderBy); } } }
package com.redhat.ceylon.compiler.typechecker.model; import java.util.List; public class ClassAlias extends Class { @Override public ProducedType getProducedType(ProducedType outerType, List<ProducedType> typeArguments) { return aliasType(outerType, typeArguments); } @Override public boolean isAlias() { return true; } @Override public boolean isAbstract() { Class etd = getExtendedTypeDeclaration(); return etd!=null && etd!=this && etd.isAbstract(); } }
package org.malaguna.cmdit.bbeans; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.el.ELContext; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.component.UIData; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.Flash; import javax.faces.model.SelectItem; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.malaguna.cmdit.model.AbstractObject; import org.malaguna.cmdit.model.usrmgt.Center; import org.malaguna.cmdit.model.usrmgt.User; import org.malaguna.cmdit.service.BeanNames; import org.malaguna.cmdit.service.CommandRunner; import org.malaguna.cmdit.service.ServiceDelegate; import org.malaguna.cmdit.service.commands.Command; import org.malaguna.cmdit.service.commands.CommandException; import org.malaguna.cmdit.service.commands.ResultCommand; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; public class AbstractBean extends CommandRunner{ private final static String AUTH_USER_KEY = "authuser"; private final static String AUTH_CENTER_KEY = "authcenter"; private Flash flash = null; /** * Resuelve el locale del cliente */ public Locale getLocale(){ return getFacesContext().getViewRoot().getLocale(); } public AbstractBean (){ WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); super.setService((ServiceDelegate)wac.getBean(BeanNames.SERVICE)); } /** * * @return El contexto de Faces */ protected FacesContext getFacesContext(){ return FacesContext.getCurrentInstance(); } /** * * @return El contexto del contenedor de Faces */ protected ExternalContext getExternalContext(){ return getFacesContext().getExternalContext(); } protected ServletContext getServletContext(){ ServletContext sc = null; try{ sc = (ServletContext)getExternalContext().getContext(); }catch(Exception e){ logError("err.abb.noServletContext", e, (Object[])null); } return sc; } /** * Devuelve un back bean dado su nombre * * @param backBean */ public Object getBackBeanReference(String backBean){ ELContext context = getFacesContext().getELContext(); return context.getELResolver().getValue(context, null, backBean); } /** * Devuelve un Bean de Spring dado su nombre * * @param name * @return */ public Object getSpringBean(String name){ Object result = null; if(getBeanFactory() != null) result = getBeanFactory().getBean(name); else{ String className = this.getClass().getName(); String mensaje = String.format("El MBean %s no ha sido inicializado convenientemente, no dispone de acceso al BeanFactory!", className); setErrorMessage("Error de inicialización", mensaje); } return result; } protected void setInfoMessage(String summary, String msg) { getFacesContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, summary, msg)); } protected void setInfoMessage(UIComponent component, String summary, String msg) { getFacesContext().addMessage(component.getClientId(getFacesContext()), new FacesMessage(FacesMessage.SEVERITY_INFO, summary, msg)); } /** * Introduce un mensaje de tipo WARM en la cola de mensajes de Faces * @param summary Mensaje de Advertencia */ protected void setWarmMessage(String summary, String msg) { getFacesContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, summary, msg)); } /** * Introduce un mensaje de tipo WARM en la cola de mensajes de Faces asociado a un componente de la vista * @param component El componente al que se le asocia el mensaje * @param summary Mensaje de Advertencia */ protected void setWarmMessage(UIComponent component, String summary, String msg) { getFacesContext().addMessage(component.getClientId(getFacesContext()), new FacesMessage(FacesMessage.SEVERITY_WARN, summary, msg)); } /** * Introduce un mensaje de tipo ERROR en la cola de mensajes de Faces * @param summary Mensaje de error */ protected void setErrorMessage(String summary, String msg) { getFacesContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, msg)); } /** * Introduce un mensaje de tipo ERROR en la cola de mensajes de Faces asociado a un componente de la vista * @param component El componente al que se le asocia el mensaje * @param summary Mensaje de error */ protected void setErrorMessage(UIComponent component, String summary, String msg) { getFacesContext().addMessage(component.getClientId(getFacesContext()), new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, msg)); } /** * Introduce un mensaje de tipo FATAL en la cola de mensajes de Faces * @param summary Mensaje de error fatal */ protected void setFatalMessage(String summary, String msg) { getFacesContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, summary, msg)); } /** * Introduce un mensaje de tipo FATAL en la cola de mensajes de Faces asociado a un componente de la vista * @param component El componente al que se le asocia el mensaje * @param summary Mensaje de error fatal */ protected void setFatalMessage(UIComponent component, String summary, String msg) { getFacesContext().addMessage(component.getClientId(getFacesContext()), new FacesMessage(FacesMessage.SEVERITY_FATAL, summary, msg)); } /** * It runs a command safely and catching all error info. If commands fail, * it won't do anything. * * @param cmd * @return * @throws CommandException */ protected Command runCommandWE(Command cmd) throws CommandException{ cmd.setLocale(getLocale()); cmd.setUser(getAuthUserFromSession()); return super.runCommand(cmd); } /** * It runs a command safely and catching all error info. If commands fail, * it will show error info standard way. * * @param cmd * @return */ @Override protected Command runCommand(Command cmd){ cmd.setLocale(getLocale()); cmd.setUser(getAuthUserFromSession()); cmd.setCenter(getCenterFromSession()); try{ cmd = super.runCommand(cmd); if( (cmd != null) && (cmd.getUserComment() != null) ){ setInfoMessage("Command Info:", cmd.getUserComment()); } }catch(Exception e){ Throwable ce = (e.getCause() != null)?e.getCause():e; String aux = getMessage(ce.getClass().getName(), getLocale()); String errMsg = null; if(aux != null) errMsg = String.format("%s: %s", aux, ce.getLocalizedMessage()); else errMsg = ce.getLocalizedMessage(); setErrorMessage("Command Error:", errMsg); cmd = null; } return cmd; } /** * This is for bussines logic outside a request, in this case there is no possible user * to retrieve from context. For example an HL7 message, a WebService without credentials, * etc. * * @param cmd * @return * @throws CommandException */ protected Command runCommandOffSession(Command cmd) throws CommandException{ cmd.setLocale(getLocale()); return super.runCommand(cmd); } /** * Method that obtains the selected row from a UIComponent. It does not check super classes * * @param anEvent */ protected Object selectRowFromEvent(UIComponent tmpComponent, Class<?> clazz) { return selectRowFromEvent(tmpComponent, clazz, false); } /** * Method that obtains the selected row from a UIComponent. It can check super class * * @param anEvent */ protected Object selectRowFromEvent(UIComponent tmpComponent, Class<?> clazz, boolean checkSuper) { Object tmpRowData = null; if(tmpComponent != null){ while (null != tmpComponent && !(tmpComponent instanceof UIData)) tmpComponent = tmpComponent.getParent(); if (tmpComponent != null && (tmpComponent instanceof UIData)) { tmpRowData = ((UIData)tmpComponent).getRowData(); boolean checked = clazz.isAssignableFrom(tmpRowData.getClass()); if(!checked && checkSuper){ checked = clazz.isInstance(tmpRowData); } if(!checked){ setErrorMessage("Casting from event error:", "Error de casting para el objeto fila: se esperaba [" + clazz.toString() + "] y es [" + tmpRowData.getClass().toString() + "]"); tmpRowData = null; } } } return tmpRowData; } protected void sendFileThroughHttpResponse(File file, String fileName, String contentType) throws Exception { if(file != null && file.exists()){ if(contentType != null){ HttpServletResponse response = (HttpServletResponse) getFacesContext().getExternalContext().getResponse(); response.setHeader("pragma", "no-cache"); response.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); response.setHeader("Expires", "01 Apr 1995 01:10:10 GMT"); StringBuffer contentDisposition = new StringBuffer(); contentDisposition.append("attachment;"); contentDisposition.append("filename=\""); contentDisposition.append(fileName!=null?fileName:file.getName()); contentDisposition.append("\""); response.setHeader ("Content-Disposition", contentDisposition.toString()); response.setContentType(contentType); try { FileUtils.copyFile(file, response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); } getFacesContext().responseComplete(); }else{ setErrorMessage("Sendind file error:", "No se ha indicado tipo de contenido del fichero a enviar por HTTP"); } }else{ setErrorMessage("Sendind file error:", "No se ha indicado fichero para enviar por HTTP"); } } /** * It puts into session an user. Only a SessionAbstractBean can do this. * * @param user */ protected void putAuthUserIntoSession(User user){ if(this instanceof SessionAbstractBean){ ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); ec.getSessionMap().put(AUTH_USER_KEY, user); } } /** * It retrieves from session an user */ private User getAuthUserFromSession(){ ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); return (User)ec.getSessionMap().get(AUTH_USER_KEY); } private Center getCenterFromSession(){ ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); return (Center)ec.getSessionMap().get(AUTH_CENTER_KEY); } protected void putFlash(String key, Object value){ if (flash == null){ flash = FacesContext.getCurrentInstance().getExternalContext().getFlash(); } flash.put(key, value); } protected Object getFlash(String key){ if (flash == null){ flash = FacesContext.getCurrentInstance().getExternalContext().getFlash(); } return flash.get(key); } @SuppressWarnings("unchecked") protected List<SelectItem> loadAllObjectsAsSelectItems(Class<? extends ResultCommand<? extends List<? extends AbstractObject<? extends Serializable>>>> clazz, String action){ List<SelectItem> result = null; ResultCommand<? extends List<? extends AbstractObject<? extends Serializable>>> cmd = null; cmd = (ResultCommand<? extends List<? extends AbstractObject<? extends Serializable>>>) createCommand(clazz); cmd.setAction(action); cmd = (ResultCommand<? extends List<? extends AbstractObject<? extends Serializable>>>) runCommand(cmd); if( (cmd != null) && (cmd.getResult() != null) && !(cmd.getResult().isEmpty()) ){ result = new ArrayList<SelectItem>(); for(AbstractObject<?> aux : cmd.getResult()) result.add(new SelectItem(aux.getPid(), aux.toString())); } return result; } }
package tk.wurst_client.utils; import java.util.ArrayDeque; import java.util.Arrays; import java.util.HashSet; import com.google.common.collect.AbstractIterator; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.network.play.client.CPacketAnimation; import net.minecraft.network.play.client.CPacketPlayerDigging; import net.minecraft.network.play.client.CPacketPlayerDigging.Action; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import tk.wurst_client.WurstClient; public final class BlockUtils { private static final Minecraft mc = Minecraft.getMinecraft(); public static IBlockState getState(BlockPos pos) { return mc.world.getBlockState(pos); } public static Block getBlock(BlockPos pos) { return getState(pos).getBlock(); } public static int getId(BlockPos pos) { return Block.getIdFromBlock(getBlock(pos)); } public static Material getMaterial(BlockPos pos) { return getState(pos).getMaterial(); } public static AxisAlignedBB getBoundingBox(BlockPos pos) { return getState(pos).getBoundingBox(mc.world, pos).offset(pos); } public static boolean canBeClicked(BlockPos pos) { return getBlock(pos).canCollideCheck(getState(pos), false); } public static float getHardness(BlockPos pos) { return getState(pos).getPlayerRelativeBlockHardness(mc.player, mc.world, pos); } private static void processRightClickBlock(BlockPos pos, EnumFacing side, Vec3d hitVec) { mc.playerController.processRightClickBlock(mc.player, mc.world, pos, side, hitVec, EnumHand.MAIN_HAND); } private static void swingArmClient() { mc.player.swingArm(EnumHand.MAIN_HAND); } private static void swingArmPacket() { mc.player.connection .sendPacket(new CPacketAnimation(EnumHand.MAIN_HAND)); } public static boolean placeBlockLegit(BlockPos pos) { Vec3d eyesPos = RotationUtils.getEyesPos(); Vec3d posVec = new Vec3d(pos).addVector(0.5, 0.5, 0.5); double distanceSqPosVec = eyesPos.squareDistanceTo(posVec); for(EnumFacing side : EnumFacing.values()) { BlockPos neighbor = pos.offset(side); // check if neighbor can be right clicked if(!canBeClicked(neighbor)) continue; Vec3d hitVec = posVec.add(new Vec3d(side.getDirectionVec()).scale(0.5)); double distanceSqHitVec = eyesPos.squareDistanceTo(hitVec); // check if hitVec is within range (4.25 blocks) if(distanceSqHitVec > 18.0625) continue; // check if side is visible (facing away from player) if(distanceSqHitVec <= distanceSqPosVec) continue; // check line of sight if(mc.world.rayTraceBlocks(eyesPos, hitVec, false, true, false) != null) continue; // face block if(!RotationUtils.faceVectorPacket(hitVec)) return true; // place block processRightClickBlock(neighbor, side.getOpposite(), hitVec); swingArmClient(); mc.rightClickDelayTimer = 4; return true; } return false; } public static boolean placeBlockSimple(BlockPos pos) { Vec3d eyesPos = RotationUtils.getEyesPos(); Vec3d posVec = new Vec3d(pos).addVector(0.5, 0.5, 0.5); for(EnumFacing side : EnumFacing.values()) { BlockPos neighbor = pos.offset(side); // check if neighbor can be right clicked if(!canBeClicked(neighbor)) continue; Vec3d hitVec = posVec.add(new Vec3d(side.getDirectionVec()).scale(0.5)); // check if hitVec is within range (6 blocks) if(eyesPos.squareDistanceTo(hitVec) > 36) continue; // place block processRightClickBlock(neighbor, side.getOpposite(), hitVec); return true; } return false; } public static boolean breakBlockLegit(BlockPos pos) { Vec3d eyesPos = RotationUtils.getEyesPos(); Vec3d posVec = new Vec3d(pos).addVector(0.5, 0.5, 0.5); double distanceSqPosVec = eyesPos.squareDistanceTo(posVec); for(EnumFacing side : EnumFacing.values()) { Vec3d hitVec = posVec.add(new Vec3d(side.getDirectionVec()).scale(0.5)); double distanceSqHitVec = eyesPos.squareDistanceTo(hitVec); // check if hitVec is within range (4.25 blocks) if(distanceSqHitVec > 18.0625) continue; // check if side is facing towards player if(distanceSqHitVec >= distanceSqPosVec) continue; // check line of sight if(mc.world.rayTraceBlocks(eyesPos, hitVec, false, true, false) != null) continue; // AutoTool WurstClient.INSTANCE.mods.autoToolMod.setSlot(pos); // face block if(!RotationUtils.faceVectorPacket(hitVec)) return true; // damage block if(!mc.playerController.onPlayerDamageBlock(pos, side)) return false; // swing arm swingArmPacket(); return true; } return false; } public static boolean breakBlockExtraLegit(BlockPos pos) { Vec3d eyesPos = RotationUtils.getEyesPos(); Vec3d posVec = new Vec3d(pos).addVector(0.5, 0.5, 0.5); double distanceSqPosVec = eyesPos.squareDistanceTo(posVec); for(EnumFacing side : EnumFacing.values()) { Vec3d hitVec = posVec.add(new Vec3d(side.getDirectionVec()).scale(0.5)); double distanceSqHitVec = eyesPos.squareDistanceTo(hitVec); // check if hitVec is within range (4.25 blocks) if(distanceSqHitVec > 18.0625) continue; // check if side is facing towards player if(distanceSqHitVec >= distanceSqPosVec) continue; // check line of sight if(mc.world.rayTraceBlocks(eyesPos, hitVec, false, true, false) != null) continue; // AutoTool WurstClient.INSTANCE.mods.autoToolMod.setSlot(pos); // face block if(!RotationUtils.faceVectorClient(hitVec)) return true; // if attack key is down but nothing happens, release it for one // tick if(mc.gameSettings.keyBindAttack.pressed && !mc.playerController.getIsHittingBlock()) { mc.gameSettings.keyBindAttack.pressed = false; return true; } // damage block mc.gameSettings.keyBindAttack.pressed = true; return true; } return false; } public static boolean breakBlockSimple(BlockPos pos) { Vec3d eyesPos = RotationUtils.getEyesPos(); Vec3d posVec = new Vec3d(pos).addVector(0.5, 0.5, 0.5); double distanceSqPosVec = eyesPos.squareDistanceTo(posVec); for(EnumFacing side : EnumFacing.values()) { Vec3d hitVec = posVec.add(new Vec3d(side.getDirectionVec()).scale(0.5)); double distanceSqHitVec = eyesPos.squareDistanceTo(hitVec); // check if hitVec is within range (6 blocks) if(distanceSqHitVec > 36) continue; // check if side is facing towards player if(distanceSqHitVec >= distanceSqPosVec) continue; // AutoTool WurstClient.INSTANCE.mods.autoToolMod.setSlot(pos); // face block RotationUtils.faceVectorPacket(hitVec); // damage block if(!mc.playerController.onPlayerDamageBlock(pos, side)) return false; // swing arm swingArmPacket(); return true; } return false; } public static void breakBlockPacketSpam(BlockPos pos) { Vec3d eyesPos = RotationUtils.getEyesPos(); Vec3d posVec = new Vec3d(pos).addVector(0.5, 0.5, 0.5); double distanceSqPosVec = eyesPos.squareDistanceTo(posVec); for(EnumFacing side : EnumFacing.values()) { Vec3d hitVec = posVec.add(new Vec3d(side.getDirectionVec()).scale(0.5)); // check if side is facing towards player if(eyesPos.squareDistanceTo(hitVec) >= distanceSqPosVec) continue; // break block mc.player.connection.sendPacket(new CPacketPlayerDigging( Action.START_DESTROY_BLOCK, pos, side)); mc.player.connection.sendPacket( new CPacketPlayerDigging(Action.STOP_DESTROY_BLOCK, pos, side)); return; } } public static boolean rightClickBlockLegit(BlockPos pos) { Vec3d eyesPos = RotationUtils.getEyesPos(); Vec3d posVec = new Vec3d(pos).addVector(0.5, 0.5, 0.5); double distanceSqPosVec = eyesPos.squareDistanceTo(posVec); for(EnumFacing side : EnumFacing.values()) { Vec3d hitVec = posVec.add(new Vec3d(side.getDirectionVec()).scale(0.5)); double distanceSqHitVec = eyesPos.squareDistanceTo(hitVec); // check if hitVec is within range (4.25 blocks) if(distanceSqHitVec > 18.0625) continue; // check if side is facing towards player if(distanceSqHitVec >= distanceSqPosVec) continue; // check line of sight if(mc.world.rayTraceBlocks(eyesPos, hitVec, false, true, false) != null) continue; // face block if(!RotationUtils.faceVectorPacket(hitVec)) return true; // place block processRightClickBlock(pos, side, hitVec); swingArmClient(); mc.rightClickDelayTimer = 4; return true; } return false; } public static boolean rightClickBlockSimple(BlockPos pos) { Vec3d eyesPos = RotationUtils.getEyesPos(); Vec3d posVec = new Vec3d(pos).addVector(0.5, 0.5, 0.5); double distanceSqPosVec = eyesPos.squareDistanceTo(posVec); for(EnumFacing side : EnumFacing.values()) { Vec3d hitVec = posVec.add(new Vec3d(side.getDirectionVec()).scale(0.5)); double distanceSqHitVec = eyesPos.squareDistanceTo(hitVec); // check if hitVec is within range (6 blocks) if(distanceSqHitVec > 36) continue; // check if side is facing towards player if(distanceSqHitVec >= distanceSqPosVec) continue; // place block processRightClickBlock(pos, side, hitVec); return true; } return false; } public static Iterable<BlockPos> getValidBlocksByDistance(double range, boolean ignoreVisibility, BlockValidator validator) { // prepare range check Vec3d eyesPos = RotationUtils.getEyesPos().subtract(0.5, 0.5, 0.5); double rangeSq = Math.pow(range + 0.5, 2); // set start pos BlockPos startPos = new BlockPos(RotationUtils.getEyesPos()); return () -> new AbstractIterator<BlockPos>() { // initialize queue private ArrayDeque<BlockPos> queue = new ArrayDeque<>(Arrays.asList(startPos)); private HashSet<BlockPos> visited = new HashSet<>(); @Override protected BlockPos computeNext() { // find block using breadth first search while(!queue.isEmpty()) { BlockPos current = queue.pop(); // check range if(eyesPos.squareDistanceTo(new Vec3d(current)) > rangeSq) continue; boolean canBeClicked = canBeClicked(current); if(ignoreVisibility || !canBeClicked) { // add neighbors for(EnumFacing facing : EnumFacing.values()) { BlockPos next = current.offset(facing); if(visited.contains(next)) continue; queue.add(next); visited.add(next); } } // check if block is valid if(canBeClicked && validator.isValid(current)) return current; } return endOfData(); } }; } public static Iterable<BlockPos> getValidBlocksByDistanceReversed( double range, boolean ignoreVisibility, BlockValidator validator) { ArrayDeque<BlockPos> validBlocks = new ArrayDeque<>(); BlockUtils.getValidBlocksByDistance(range, ignoreVisibility, validator) .forEach((p) -> validBlocks.push(p)); return validBlocks; } public static Iterable<BlockPos> getValidBlocks(double range, BlockValidator validator) { // prepare range check Vec3d eyesPos = RotationUtils.getEyesPos().subtract(0.5, 0.5, 0.5); double rangeSq = Math.pow(range + 0.5, 2); return getValidBlocks((int)Math.ceil(range), (pos) -> { // check range if(eyesPos.squareDistanceTo(new Vec3d(pos)) > rangeSq) return false; // check if block is valid return validator.isValid(pos); }); } public static Iterable<BlockPos> getValidBlocks(int blockRange, BlockValidator validator) { BlockPos playerPos = new BlockPos(RotationUtils.getEyesPos()); BlockPos min = playerPos.add(-blockRange, -blockRange, -blockRange); BlockPos max = playerPos.add(blockRange, blockRange, blockRange); return () -> new AbstractIterator<BlockPos>() { private BlockPos last; private BlockPos computeNextUnchecked() { if(last == null) { last = min; return last; } int x = last.getX(); int y = last.getY(); int z = last.getZ(); if(z < max.getZ()) z++; else if(x < max.getX()) { z = min.getZ(); x++; }else if(y < max.getY()) { z = min.getZ(); x = min.getX(); y++; }else return null; last = new BlockPos(x, y, z); return last; } @Override protected BlockPos computeNext() { BlockPos pos; while((pos = computeNextUnchecked()) != null) { // skip air blocks if(getMaterial(pos) == Material.AIR) continue; // check if block is valid if(!validator.isValid(pos)) continue; return pos; } return endOfData(); } }; } public static interface BlockValidator { public boolean isValid(BlockPos pos); } }
package org.reasm.m68k.assembly.internal; import java.util.ArrayList; import org.reasm.Architecture; import org.reasm.m68k.Identifier; import org.reasm.source.MacroInstantiation; import org.reasm.source.SourceLocation; import ca.fragag.text.DocumentReader; import ca.fragag.text.RangedCharSequenceReader; final class Macro { private static final class Substitution { static final int ATTRIBUTE = -1; static final int LABEL = -2; static final int NARG = -3; final int offset; final int length; final int operandIndex; Substitution(int offset, int length, int operandIndex) { this.offset = offset; this.length = length; this.operandIndex = operandIndex; } } private static void findNamedSubstitution(String[] operands, String name, int startPosition, int endPosition, ArrayList<Substitution> substitutions) { if ("NARG".equalsIgnoreCase(name)) { substitutions.add(new Substitution(startPosition, endPosition - startPosition, Substitution.NARG)); return; } for (int i = 0; i < operands.length; i++) { if (operands[i].equalsIgnoreCase(name)) { substitutions.add(new Substitution(startPosition, endPosition - startPosition, i)); break; } } } private static ArrayList<Substitution> identifySubstitutions(String[] operands, SourceLocation body) { // There are a few patterns that will get substituted in macros. // The following patterns are matched anywhere in the macro body: // - \{xyz} if xyz is an integer, gets substituted to the nth operand (\0 is the attribute); otherwise, if xyz matches the // name of an operand, gets substituted with the corresponding operand in a macro invocation // - \* gets substituted with the last label on the macro invocation line // The following patterns are matched outside of string literals only: // - xyz if xyz is an identifier that matches the name of an operand, gets substituted with the corresponding operand // in a macro invocation // - \xyz if xyz is an integer, gets substituted to the nth operand (\0 is the attribute) final ArrayList<Substitution> substitutions = new ArrayList<>(); final RangedCharSequenceReader reader = new RangedCharSequenceReader(new DocumentReader(body.getFile().getText()), body.getTextPosition(), body.getTextPosition() + body.getSourceNode().getLength()); int inString = -1; while (!reader.atEnd()) { final int startPosition = reader.getCurrentPosition(); int codePoint = reader.getCurrentCodePoint(); if (codePoint == '\\') { reader.advance(); codePoint = reader.getCurrentCodePoint(); if (codePoint == '{') { // Read until we find a '}'. do { reader.advance(); codePoint = reader.getCurrentCodePoint(); } while (codePoint != -1 && codePoint != '}'); if (codePoint == '}') { reader.advance(); final int endPosition = reader.getCurrentPosition(); // Read the name starting after "\{" and ending before "}". // Trim it because operands are always trimmed. reader.setCurrentPosition(startPosition + 2); final String name = reader.readSubstring(endPosition - startPosition - 3).trim(); Integer i = tryParseInt(name); if (i != null) { // NOTE: i - 1 is ATTRIBUTE when i == 0 substitutions.add(new Substitution(startPosition, endPosition - startPosition, i - 1)); } else { // Check if the text between the braces matches the name of an operand. findNamedSubstitution(operands, name, startPosition, endPosition, substitutions); } } continue; } if (codePoint == '*') { reader.advance(); substitutions.add(new Substitution(startPosition, reader.getCurrentPosition() - startPosition, Substitution.LABEL)); continue; } if (inString == -1) { if (Identifier.isDigit(codePoint)) { // Read until we find a non-digit. do { reader.advance(); } while (Identifier.isDigit(reader.getCurrentCodePoint())); final int endPosition = reader.getCurrentPosition(); reader.setCurrentPosition(startPosition + 1); final String name = reader.readSubstring(endPosition - startPosition - 1).trim(); final Integer i = tryParseInt(name); if (i != null) { // NOTE: i - 1 is ATTRIBUTE when i == 0 substitutions.add(new Substitution(startPosition, endPosition - startPosition, i - 1)); } continue; } } else { // Skip the next code point. This allows single and double quotes, in particular, to be escaped. reader.advance(); } } else { if (inString == -1) { if (codePoint == '\'' || codePoint == '"') { inString = codePoint; } else if (Identifier.isValidIdentifierCodePoint(codePoint)) { boolean startsWithDigit = Identifier.isDigit(codePoint); // Read an identifier. do { reader.advance(); } while (Identifier.isValidIdentifierCodePoint(reader.getCurrentCodePoint())); if (!startsWithDigit) { final int endPosition = reader.getCurrentPosition(); reader.setCurrentPosition(startPosition); final String identifier = reader.readSubstring(endPosition - startPosition); // Check if the identifier matches the name of an operand. findNamedSubstitution(operands, identifier, startPosition, endPosition, substitutions); } continue; } } else if (inString == codePoint) { inString = -1; } } reader.advance(); } return substitutions; } private static Integer tryParseInt(String name) { final int length = name.length(); if (length == 0) { return null; } long result = 0; for (int i = 0; i < length; i++) { final char ch = name.charAt(i); if (!Identifier.isDigit(ch)) { return null; } result = result * 10 + (ch - '0'); // Overflow? if (result > Integer.MAX_VALUE) { return null; } } return (int) result; } private final SourceLocation body; private final ArrayList<Substitution> substitutions; private final boolean hasLabelSubstitutions; Macro(String[] operands, SourceLocation body) { this.body = body; this.substitutions = identifySubstitutions(operands, body); boolean hasLabelSubstitutions = false; for (Substitution substitution : this.substitutions) { if (substitution.operandIndex == Substitution.LABEL) { hasLabelSubstitutions = true; break; } } this.hasLabelSubstitutions = hasLabelSubstitutions; } final Architecture getArchitecture() { return this.body.getArchitecture(); } final boolean hasLabelSubstitutions() { return this.hasLabelSubstitutions; } final MacroInstantiation substituteMacroOperands(M68KAssemblyContext context) { MacroInstantiation result = new MacroInstantiation(this.body); int correction = 0; for (Substitution substitution : this.substitutions) { String substitutedText = ""; switch (substitution.operandIndex) { case Substitution.NARG: substitutedText = Integer.toString(context.numberOfOperands); break; case Substitution.LABEL: if (context.numberOfLabels > 0) { substitutedText = context.getLabelText(context.numberOfLabels - 1); } break; case Substitution.ATTRIBUTE: if (context.attribute != null) { substitutedText = context.attribute; } break; default: if (substitution.operandIndex < context.numberOfOperands) { substitutedText = context.getOperandText(substitution.operandIndex); } break; } result = result.replaceText(substitution.offset + correction, substitution.length, substitutedText); correction += substitutedText.length() - substitution.length; } return result; } }
package com.vinsol.sms_scheduler.activities; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.app.Activity; import android.app.AlarmManager; import android.app.Dialog; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.database.Cursor; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.ContactsContract.Groups; import android.speech.RecognizerIntent; import android.telephony.SmsManager; import android.text.Editable; import android.text.SpannableStringBuilder; import android.text.TextPaint; import android.text.TextWatcher; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.DatePicker.OnDateChangedListener; import android.widget.EditText; import android.widget.Filter; import android.widget.Filterable; import android.widget.GridView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TimePicker; import android.widget.TimePicker.OnTimeChangedListener; import android.widget.Toast; import com.vinsol.sms_scheduler.Constants; import com.vinsol.sms_scheduler.DBAdapter; import com.vinsol.sms_scheduler.R; import com.vinsol.sms_scheduler.models.GroupStructure; import com.vinsol.sms_scheduler.models.MyContact; import com.vinsol.sms_scheduler.models.SpannedEntity; import com.vinsol.sms_scheduler.receivers.SMSHandleReceiver; public class NewScheduleActivity extends Activity { AutoCompleteTextView numbersText; ImageButton addFromContactsImgButton; Button dateButton; TextView characterCountText; EditText messageText; ImageButton templateImageButton; ImageButton speechImageButton; ImageButton addTemplateImageButton; Button scheduleButton; Button cancelButton; GridView smileysGrid; static ArrayList<ArrayList<HashMap<String, Object>>> nativeChildData = new ArrayList<ArrayList<HashMap<String, Object>>>(); static ArrayList<HashMap<String, Object>> nativeGroupData = new ArrayList<HashMap<String, Object>>(); static ArrayList<ArrayList<HashMap<String, Object>>> privateChildData = new ArrayList<ArrayList<HashMap<String, Object>>>(); static ArrayList<HashMap<String, Object>> privateGroupData = new ArrayList<HashMap<String, Object>>(); //boolean empty; SmsManager smsManager = SmsManager.getDefault(); ArrayList<String> parts = new ArrayList<String>(); ArrayList<String> templatesArray = new ArrayList<String>(); static ArrayList<SpannedEntity> Spans = new ArrayList<SpannedEntity>(); private SpannableStringBuilder ssb = new SpannableStringBuilder(); private int spanStartPosition = 0; private ArrayList<ClickableSpan> clickableSpanArrayList = new ArrayList<ClickableSpan>(); private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234; DBAdapter mdba = new DBAdapter(NewScheduleActivity.this); AutoCompleteAdapter myAutoCompleteAdapter; Dialog dateSelectDialog; Dialog templateDialog; boolean suggestionsBoolean = true; Pattern p = Pattern.compile(""); Date refDate = new Date(); Calendar refCal = new GregorianCalendar(); Date processDate = new Date(); ArrayList<MyContact> shortlist = new ArrayList<MyContact>(); boolean smileyVisible = false; int positionTrack; ArrayList<Long> ids = new ArrayList<Long>(); ArrayList<String> idsString = new ArrayList<String>(); SimpleDateFormat sdf = new SimpleDateFormat("EEE hh:mm aa, dd MMM yyyy"); int [] images = { R.drawable.emoticon_01, R.drawable.emoticon_02, R.drawable.emoticon_03, R.drawable.emoticon_04, R.drawable.emoticon_05, R.drawable.emoticon_06, R.drawable.emoticon_07, R.drawable.emoticon_08, R.drawable.emoticon_09, R.drawable.emoticon_10, R.drawable.emoticon_11, R.drawable.emoticon_12, }; String [] smileys = { ":-)", ":-D", "B-D", ":-P", ";-)", "o:-)", "$-)", ":-(", ":'-(", ":-\\", ":-O", ":-X" }; int toOpen = 0; Dialog dataLoadWaitDialog; IntentFilter dataloadIntentFilter; private BroadcastReceiver mDataLoadedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent2) { if(dataLoadWaitDialog.isShowing()) { dataLoadWaitDialog.cancel(); if(toOpen == 1){ Intent intent = new Intent(NewScheduleActivity.this, ContactsTabsActivity.class); intent.putExtra("IDSARRAY", idsString); intent.putExtra("ORIGIN", "new"); toOpen = 0; startActivityForResult(intent, 2); } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.new_schedule_layout); dataLoadWaitDialog = new Dialog(NewScheduleActivity.this); dataLoadWaitDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); numbersText = (AutoCompleteTextView) findViewById(R.id.new_numbers_text); addFromContactsImgButton = (ImageButton) findViewById(R.id.new_add_from_contact_imgbutton); dateButton = (Button) findViewById(R.id.new_date_button); characterCountText = (TextView) findViewById(R.id.new_char_count_text); messageText = (EditText) findViewById(R.id.new_message_space); templateImageButton = (ImageButton) findViewById(R.id.template_imgbutton); speechImageButton = (ImageButton) findViewById(R.id.speech_imgbutton); addTemplateImageButton = (ImageButton) findViewById(R.id.add_template_imgbutton); scheduleButton = (Button) findViewById(R.id.new_schedule_button); cancelButton = (Button) findViewById(R.id.new_cancel_button); smileysGrid = (GridView) findViewById(R.id.smileysGrid); Spans.clear(); numbersText.setThreshold(1); // Check to see if a recognition activity is present PackageManager pm = getPackageManager(); List<ResolveInfo> activities = pm.queryIntentActivities( new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0); if (activities.size() != 0) { speechImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startVoiceRecognitionActivity(); } }); } else { speechImageButton.setEnabled(false); } dataloadIntentFilter = new IntentFilter(); dataloadIntentFilter.addAction(SmsApplicationLevelData.DIALOG_CONTROL_ACTION); setFunctionalities(); loadGroupsData(); myAutoCompleteAdapter = new AutoCompleteAdapter(this); numbersText.setAdapter(myAutoCompleteAdapter); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); registerReceiver(mDataLoadedReceiver, dataloadIntentFilter); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); unregisterReceiver(mDataLoadedReceiver); } public void setFunctionalities(){ addFromContactsImgButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //Log.i("MSG", "isDataLoaded : " + SmsApplicationLevelData.isDataLoaded); if(SmsApplicationLevelData.isDataLoaded){ Log.i("MSG", "entering into if and isDataLoaded : " + SmsApplicationLevelData.isDataLoaded); Intent intent = new Intent(NewScheduleActivity.this, ContactsTabsActivity.class); intent.putExtra("IDSARRAY", idsString); intent.putExtra("ORIGIN", "new"); startActivityForResult(intent, 2); }else{ toOpen = 1; dataLoadWaitDialog.setContentView(R.layout.wait_dialog); // dataLoadWaitDialog.setOnCancelListener(new OnCancelListener() { // @Override // public void onCancel(DialogInterface dialog) { // // TODO Auto-generated method stub // Log.i("MSG", "2"); // toOpen = 0; // dataLoadWaitDialog.cancel(); dataLoadWaitDialog.show(); } } }); numbersText.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(SmsApplicationLevelData.isDataLoaded){ if(spanStartPosition > 0){ numbersText.setSelection(spanStartPosition); }else if (Spans.size() > 0){ numbersText.setSelection(numbersText.getText().toString().length()); } }else{ dataLoadWaitDialog.setContentView(R.layout.wait_dialog); dataLoadWaitDialog.setCancelable(false); // dataLoadWaitDialog.setOnCancelListener(new OnCancelListener() { // @Override // public void onCancel(DialogInterface dialog) { // // TODO Auto-generated method stub // Log.i("MSG", "2"); // toOpen = 0; // dataLoadWaitDialog.cancel(); dataLoadWaitDialog.show(); } } }); numbersText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { Log.v("cccc", "" + keyCode + " " + KeyEvent.KEYCODE_COMMA); if(keyCode == KeyEvent.KEYCODE_DEL){ int pos = numbersText.getSelectionStart(); int len = 0; for(int i = 0; i< Spans.size(); i++){ len = len + Spans.get(i).displayName.length(); if(i!=0){ len = len + 2; } if(pos<=len){ int position = pos - (Spans.get(i).displayName.length()); if (position > 0) numbersText.setSelection(position); for(int j = 0; j< nativeGroupData.size(); j++){ for(int k = 0; k< nativeChildData.get(j).size(); k++){ if((Long.parseLong((String)nativeChildData.get(j).get(k).get(Constants.CHILD_CONTACT_ID))) == Spans.get(i).entityId && (Boolean)nativeChildData.get(j).get(k).get(Constants.CHILD_CHECK)){ nativeChildData.get(j).get(k).put(Constants.CHILD_CHECK, false); } } } for(int j = 0; j< privateGroupData.size(); j++){ for(int k = 0; k< privateChildData.get(j).size(); k++){ if((Long.parseLong((String)privateChildData.get(j).get(k).get(Constants.CHILD_CONTACT_ID))) == Spans.get(i).entityId && (Boolean)privateChildData.get(j).get(k).get(Constants.CHILD_CHECK)){ privateChildData.get(j).get(k).put(Constants.CHILD_CHECK, false); } } } Spans.remove(i); refreshSpannableString(); myAutoCompleteAdapter.notifyDataSetInvalidated(); myAutoCompleteAdapter.notifyDataSetChanged(); break; } } } return false; } }); numbersText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { int pos = numbersText.getSelectionStart(); Log.i("MSG", pos + ""); if(pos>1){ if(numbersText.getText().toString().charAt(numbersText.getSelectionStart()-1) == ' '){ if(numbersText.getText().toString().charAt(pos-2)== '0' || numbersText.getText().toString().charAt(pos-2)== '1' || numbersText.getText().toString().charAt(pos-2)== '2' || numbersText.getText().toString().charAt(pos-2)== '3' || numbersText.getText().toString().charAt(pos-2)== '4' || numbersText.getText().toString().charAt(pos-2)== '5' || numbersText.getText().toString().charAt(pos-2)== '6' || numbersText.getText().toString().charAt(pos-2)== '7' || numbersText.getText().toString().charAt(pos-2)== '8' || numbersText.getText().toString().charAt(pos-2)== '9'){ numbersText.setText(numbersText.getText().toString().substring(0, pos-1));// + numbersText.getText().toString().substring(pos, numbersText.getText().toString().length()-1)); int start = 0; for(int i= 0; i < pos-1 ; i++){ if(numbersText.getText().toString().charAt(i) == ' '){ start = i+1; } } boolean isPresent = false; for(int i = 0; i< Spans.size(); i++){ if(Spans.get(i).displayName.equals(numbersText.getText().toString().substring(start, pos-1))){ isPresent = true; break; } } if(!isPresent){ SpannedEntity span = new SpannedEntity(-1, 1, numbersText.getText().toString().substring(start, pos-1), -1, -1); Spans.add(span); } refreshSpannableString(); } } } } }); numbersText.setLongClickable(false); numbersText.setMovementMethod(LinkMovementMethod.getInstance()); numbersText.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { boolean isPresent = false; for(int i = 0; i< Spans.size(); i++){ if(Spans.get(i).entityId == Long.parseLong(shortlist.get(position).content_uri_id)){ isPresent = true; break; } } if(!isPresent){ final SpannedEntity span = new SpannedEntity(-1, 2, shortlist.get(position).name, Long.parseLong(shortlist.get(position).content_uri_id), -1); Spans.add(span); } refreshSpannableString(); } }); Date currentDate = new Date(); final SimpleDateFormat sdf = new SimpleDateFormat("EEE hh:mm aa, dd MMM yyyy"); dateButton.setText(sdf.format(currentDate)); processDate = currentDate; dateButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dateSelectDialog = new Dialog(NewScheduleActivity.this); dateSelectDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dateSelectDialog.setContentView(R.layout.date_input_dialog); final DatePicker datePicker = (DatePicker) dateSelectDialog.findViewById(R.id.new_date_picker); final TimePicker timePicker = (TimePicker) dateSelectDialog.findViewById(R.id.new_time_picker); final View dateLabel = dateSelectDialog.findViewById(R.id.new_date_label); Button okDateButton = (Button) dateSelectDialog.findViewById(R.id.new_date_dialog_ok_button); Button cancelDateButton = (Button) dateSelectDialog.findViewById(R.id.new_date_dialog_cancel_button); timePicker.setCurrentHour(processDate.getHours()); timePicker.setCurrentMinute(processDate.getMinutes()); final int mYear = processDate.getYear() + 1900; final int mMonth = processDate.getMonth(); final int mDay = processDate.getDate(); datePicker.init(mYear, mMonth, mDay, new OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { //String temp = sdf.format(new Date(year-1900, monthOfYear, dayOfMonth, timePicker.getCurrentHour(), timePicker.getCurrentMinute())); //dateLabel.setText(temp); if(checkDateValidity(new Date(year-1900, monthOfYear, dayOfMonth, timePicker.getCurrentHour(), timePicker.getCurrentMinute()))){ dateLabel.setVisibility(View.INVISIBLE); }else{ dateLabel.setVisibility(View.VISIBLE); } } }); refCal = new GregorianCalendar(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), timePicker.getCurrentHour(), timePicker.getCurrentMinute()); refDate = refCal.getTime(); if(checkDateValidity(refDate)){ dateLabel.setVisibility(View.INVISIBLE); }else{ dateLabel.setVisibility(View.VISIBLE); } okDateButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { refCal = new GregorianCalendar(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), timePicker.getCurrentHour(), timePicker.getCurrentMinute()); refDate = refCal.getTime(); if(checkDateValidity(refDate)){ processDate = refDate; dateSelectDialog.cancel(); String temp = sdf.format(new Date(processDate.getYear(), processDate.getMonth(), processDate.getDate(), processDate.getHours(), processDate.getMinutes())); dateButton.setText(temp); }else{ processDate = refDate; dateSelectDialog.cancel(); String temp = sdf.format(new Date(processDate.getYear(), processDate.getMonth(), processDate.getDate(), processDate.getHours(), processDate.getMinutes())); dateButton.setText(temp); } } }); cancelDateButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dateSelectDialog.cancel(); } }); timePicker.setOnTimeChangedListener(new OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { String temp = sdf.format(new Date(datePicker.getYear()-1900, datePicker.getMonth(), datePicker.getDayOfMonth(), hourOfDay, minute)); if(checkDateValidity(new Date(datePicker.getYear()-1900, datePicker.getMonth(), datePicker.getDayOfMonth(), hourOfDay, minute))){ dateLabel.setVisibility(View.INVISIBLE); } else { dateLabel.setVisibility(View.VISIBLE); } } }); dateSelectDialog.show(); } }); messageText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { int length = s.length(); parts = smsManager.divideMessage(s.toString()); characterCountText.setText(String.valueOf(length)); } }); smileysGrid.setAdapter(new SmileysAdapter(this)); smileysGrid.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { int cursorPos = messageText.getSelectionStart(); String beforeString = messageText.getText().toString().substring(0, cursorPos); String afterString = messageText.getText().toString().substring(cursorPos, messageText.length()); if(cursorPos!=0){ if(messageText.getText().toString().charAt(cursorPos-1) == ' '){ if(messageText.getText().length()>0){ messageText.setText(beforeString + smileys[position] + " " + afterString); messageText.setSelection(cursorPos + smileys[position].length() + 1); }else{ messageText.setText(beforeString + smileys[position]); messageText.setSelection(cursorPos + smileys[position].length()); } }else{ if(afterString.length()>0){ messageText.setText((beforeString.length()>0 ? beforeString + " " : "") + smileys[position] + " " + afterString); messageText.setSelection(cursorPos + smileys[position].length() + 2); }else{ messageText.setText(beforeString + " " + smileys[position]); messageText.setSelection(cursorPos + smileys[position].length() + 1); } } }else if(messageText.getText().length()==0){ messageText.setText(smileys[position]); messageText.setSelection(cursorPos + smileys[position].length()); }else{ messageText.setText(smileys[position] + " " + afterString); messageText.setSelection(cursorPos + smileys[position].length() + 1); } } }); // dspeechImageButton.setOnClickListener(new OnClickListener() { // @Override // public void onClick(View v) { templateImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { loadTemplates(); if(templatesArray.size()>0){ TemplateAdapter templateAdapter = new TemplateAdapter(); templateDialog = new Dialog(NewScheduleActivity.this); templateDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); templateDialog.setContentView(R.layout.templates_dialog); ListView templateList = (ListView) templateDialog.findViewById(R.id.dialog_template_list); templateList.setAdapter(templateAdapter); templateDialog.show(); }else{ Toast.makeText(NewScheduleActivity.this, "No templates, please add some", Toast.LENGTH_SHORT).show(); } } }); addTemplateImageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(messageText.getText().toString().matches("(''|[' ']*)")){ Toast.makeText(NewScheduleActivity.this, "Text is blank. Couldn't add it as Template", Toast.LENGTH_SHORT).show(); }else{ mdba.open(); Cursor cur = mdba.fetchAllTemplates(); boolean z = true; if(cur.moveToFirst()){ do{ if(cur.getString(cur.getColumnIndex(DBAdapter.KEY_TEMP_CONTENT)).equals(messageText.getText().toString())){ z = false; break; } }while(cur.moveToNext()); } if(z){ if(mdba.addTemplate(messageText.getText().toString()) > 0){ Toast.makeText(NewScheduleActivity.this, "Template added", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(NewScheduleActivity.this, "Template couldn't be added", Toast.LENGTH_SHORT).show(); } mdba.close(); }else{ Toast.makeText(NewScheduleActivity.this, "Template already exists", Toast.LENGTH_SHORT).show(); } } } }); scheduleButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // if(numbersText.getText().toString().matches("(''|[' ']*)")){ //// Toast.makeText(NewScheduleActivity.this, "Invalid Number", Toast.LENGTH_SHORT).show(); //// numbersText.requestFocus(); // doSmsScheduling(); // }else{ // if(!checkDateValidity(processDate)){ // Toast.makeText(NewScheduleActivity.this, "Date is in Past, message will be sent immediately", Toast.LENGTH_SHORT).show(); if(Spans.size()==0 && messageText.getText().toString().matches("(''|[' ']*)")){ //Toast.makeText(NewScheduleActivity.this, "Mention Recipients and Message to proceed", Toast.LENGTH_SHORT).show(); //NewScheduleActivity.this.finish(); final Dialog d = new Dialog(NewScheduleActivity.this); d.requestWindowFeature(Window.FEATURE_NO_TITLE); d.setContentView(R.layout.confirmation_dialog_layout); TextView questionText = (TextView) d.findViewById(R.id.confirmation_dialog_text); Button yesButton = (Button) d.findViewById(R.id.confirmation_dialog_yes_button); Button noButton = (Button) d.findViewById(R.id.confirmation_dialog_no_button); questionText.setText("Nothing to schedule"); yesButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.schedule_dialog_states)); noButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.discard_dialog_states)); yesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { d.cancel(); //NewScheduleActivity.this.finish(); numbersText.requestFocus(); } }); noButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { d.cancel(); NewScheduleActivity.this.finish(); } }); d.show(); }else if(Spans.size()==0){ final Dialog d = new Dialog(NewScheduleActivity.this); d.requestWindowFeature(Window.FEATURE_NO_TITLE); d.setContentView(R.layout.confirmation_dialog_layout); TextView questionText = (TextView) d.findViewById(R.id.confirmation_dialog_text); Button yesButton = (Button) d.findViewById(R.id.confirmation_dialog_yes_button); Button noButton = (Button) d.findViewById(R.id.confirmation_dialog_no_button); questionText.setText("No recipients added!"); yesButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.save_as_draft_dialog_states)); noButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.add_recipients_dialog_states)); yesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doSmsScheduling(); d.cancel(); NewScheduleActivity.this.finish(); } }); noButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { d.cancel(); numbersText.requestFocus(); } }); d.show(); }else if(messageText.getText().toString().matches("(''|[' ']*)")){ final Dialog d = new Dialog(NewScheduleActivity.this); d.requestWindowFeature(Window.FEATURE_NO_TITLE); d.setContentView(R.layout.confirmation_dialog_layout); TextView questionText = (TextView) d.findViewById(R.id.confirmation_dialog_text); Button yesButton = (Button) d.findViewById(R.id.confirmation_dialog_yes_button); Button noButton = (Button) d.findViewById(R.id.confirmation_dialog_no_button); questionText.setText("Message is blank!"); yesButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.save_as_draft_dialog_states)); noButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.write_message_dialog_states)); yesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doSmsScheduling(); d.cancel(); NewScheduleActivity.this.finish(); } }); noButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { messageText.requestFocus(); d.cancel(); } }); d.show(); }else{ doSmsScheduling(); NewScheduleActivity.this.finish(); } } }); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(!messageText.getText().toString().matches("(''|[' ']*)") || !numbersText.getText().toString().matches("(''|[' ']*)")){ final Dialog d = new Dialog(NewScheduleActivity.this); d.requestWindowFeature(Window.FEATURE_NO_TITLE); d.setContentView(R.layout.confirmation_dialog_layout); TextView questionText = (TextView) d.findViewById(R.id.confirmation_dialog_text); Button yesButton = (Button) d.findViewById(R.id.confirmation_dialog_yes_button); Button noButton = (Button) d.findViewById(R.id.confirmation_dialog_no_button); questionText.setText("Discard this message?"); yesButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.ok_dialog_states)); noButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.cancel_dialog_states)); yesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { d.cancel(); NewScheduleActivity.this.finish(); } }); noButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { d.cancel(); } }); d.show(); }else{ NewScheduleActivity.this.finish(); } } }); } class TemplateAdapter extends ArrayAdapter{ TemplateAdapter(){ super(NewScheduleActivity.this, R.layout.template_list_row, templatesArray); } @Override public View getView(int position, View convertView, ViewGroup parent) { final int _position = position; LayoutInflater inflater = getLayoutInflater(); View row = inflater.inflate(R.layout.template_list_row, parent, false); TextView templateText = (TextView) row.findViewById(R.id.template_content_space); templateText.setText(templatesArray.get(position)); row.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(messageText.getText().toString().equals("")){ messageText.setText(templatesArray.get(_position)); }else{ messageText.setText(messageText.getText().toString() + "\n" + templatesArray.get(_position)); } messageText.setSelection(messageText.getText().toString().length()); templateDialog.cancel(); } }); return row; } } public class SmileysAdapter extends BaseAdapter { private Context mContext; public SmileysAdapter(Context c) { mContext = c; } public int getCount() { return images.length; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { //pos = position; ImageView imageView; if(convertView==null){ imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(50, 50)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(8, 8, 8, 8); }else{ imageView = (ImageView) convertView; } imageView.setImageResource(images[position]); return imageView; } } // ...End of ImageAdapter... public void loadTemplates(){ mdba.open(); Cursor cur = mdba.fetchAllTemplates(); mdba.close(); templatesArray.clear(); if(cur.moveToFirst()){ do{ templatesArray.add(cur.getString(cur.getColumnIndex(DBAdapter.KEY_TEMP_CONTENT))); }while(cur.moveToNext()); } } boolean checkDateValidity(Date date){ Calendar cal = new GregorianCalendar(date.getYear() + 1900, date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()); if((cal.getTimeInMillis()-System.currentTimeMillis()) <= 0){ return false; }else{ return true; } } public void doSmsScheduling(){ Calendar cal = new GregorianCalendar(processDate.getYear() + 1900, processDate.getMonth(), processDate.getDate(), processDate.getHours(), processDate.getMinutes()); final SimpleDateFormat sdf = new SimpleDateFormat("EEE hh:mm aa, dd MMM yyyy"); String dateString = sdf.format(cal.getTime()); mdba.open(); long groupId = mdba.getNextGroupId(); //String[] numbers = numbersText.getText().toString().split(",(' ')*"); ArrayList<String> numbers = new ArrayList<String>(); Log.i("MSG", Spans.size()+""); if(Spans.size()==0){ SpannedEntity span = new SpannedEntity(-1, 1, " ", -1, -1); // for adding as a fake span to create a draft Spans.add(span); } for(int i = 0; i< Spans.size(); i++){ if(Spans.get(i).type == 2){ for(int j = 0; j< SmsApplicationLevelData.contactsList.size(); j++){ if(Spans.get(i).entityId == Long.parseLong(SmsApplicationLevelData.contactsList.get(j).content_uri_id)){ numbers.add(SmsApplicationLevelData.contactsList.get(j).number); long received_id = mdba.scheduleSms(SmsApplicationLevelData.contactsList.get(j).number, messageText.getText().toString(), dateString, parts.size(), groupId, cal.getTimeInMillis()); if(!Spans.get(i).displayName.equals(" ")){ Log.i("MESSAGE", "entered to add to recents"); mdba.addRecentContact(Spans.get(i).entityId, ""); } Log.i("MSG", "before if else"); if(messageText.getText().toString().length() == 0){ Log.i("MSG", "inside messageText if else"); mdba.setAsDraft(received_id); }else{ if(!(Spans.size()==0) && !(messageText.getText().toString().matches("(''|[' ']*)"))){ if(mdba.getCurrentPiFiretime() == -1){ handlePiUpdate(SmsApplicationLevelData.contactsList.get(j).number, groupId, received_id, cal.getTimeInMillis()); }else if(cal.getTimeInMillis() < mdba.getCurrentPiFiretime()){ handlePiUpdate(SmsApplicationLevelData.contactsList.get(j).number, groupId, received_id, cal.getTimeInMillis()); } } } Log.i("MSG", "after if else"); Spans.get(i).smsId = received_id; Spans.get(i).spanId = mdba.createSpan(Spans.get(i).displayName, Spans.get(i).entityId, Spans.get(i).type, Spans.get(i).smsId); for(int k = 0; k< Spans.get(i).groupIds.size(); k++){ mdba.addSpanGroupRel(Spans.get(i).spanId, Spans.get(i).groupIds.get(k), 0); } } } }else if(Spans.get(i).type == 1){ long received_id = mdba.scheduleSms(Spans.get(i).displayName, messageText.getText().toString(), dateString, parts.size(), groupId, cal.getTimeInMillis()); if(Spans.size()==0 || messageText.toString().matches("(''|[' ']*)") || Spans.get(i).displayName.equals(" ")){ mdba.setAsDraft(received_id); }else{ mdba.addRecentContact(-1, Spans.get(i).displayName); if(mdba.getCurrentPiFiretime() == -1){ handlePiUpdate(Spans.get(i).displayName, groupId, received_id, cal.getTimeInMillis()); }else if(cal.getTimeInMillis() < mdba.getCurrentPiFiretime()){ handlePiUpdate(Spans.get(i).displayName, groupId, received_id, cal.getTimeInMillis()); } } Spans.get(i).smsId = received_id; Spans.get(i).spanId = mdba.createSpan(Spans.get(i).displayName, Spans.get(i).entityId, Spans.get(i).type, Spans.get(i).smsId); } } mdba.close(); // if(!(messageText.getText().toString().matches("(''|(' ')+)"))){ // for(int i = 0; i< numbers.length; i++){ // if(mdba.getCurrentPiFiretime() == -1){ // handlePiUpdate(numbers[i], groupId, received_id, cal.getTimeInMillis()); // }else if(cal.getTimeInMillis() < mdba.getCurrentPiFiretime()){ // handlePiUpdate(numbers[i], groupId, received_id, cal.getTimeInMillis()); } public void handlePiUpdate(String number, long groupId, long id, long time){ Cursor cur = mdba.getPiDetails(); cur.moveToFirst(); Intent intent = new Intent(NewScheduleActivity.this, SMSHandleReceiver.class); intent.setAction(DBAdapter.PRIVATE_SMS_ACTION); PendingIntent pi; if(cur.getLong(cur.getColumnIndex(DBAdapter.KEY_TIME))>0){ intent.putExtra("ID", cur.getLong(cur.getColumnIndex(DBAdapter.KEY_SMS_ID))); intent.putExtra("NUMBER", " "); intent.putExtra("MESSAGE", " "); pi = PendingIntent.getBroadcast(NewScheduleActivity.this, (int)cur.getLong(cur.getColumnIndex(DBAdapter.KEY_PI_NUMBER)), intent, PendingIntent.FLAG_CANCEL_CURRENT); pi.cancel(); } intent.putExtra("ID", id); intent.putExtra("NUMBER", number); intent.putExtra("MESSAGE", messageText.getText().toString()); Random rand = new Random(); int piNumber = rand.nextInt(); pi = PendingIntent.getBroadcast(NewScheduleActivity.this, piNumber, intent, PendingIntent.FLAG_UPDATE_CURRENT); mdba.updatePi(piNumber, id, time); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, time, pi); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) { // Fill the list view with the strings the recognizer thought it could have heard final ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); final Dialog d = new Dialog(NewScheduleActivity.this); d.requestWindowFeature(Window.FEATURE_NO_TITLE); d.setContentView(R.layout.voice_matches_dialog); ListView matchesList = (ListView) d.findViewById(R.id.matches_list); matchesList.setAdapter(new ArrayAdapter<String>(this, R.layout.simple_list_item, matches)); matchesList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { if(messageText.getText().toString().length()==0) { messageText.setText(matches.get(position)); } else { messageText.setText(messageText.getText().toString() + "\n" + matches.get(position)); } d.cancel(); } }); d.show(); } else if(resultCode == 2){ idsString.clear(); refreshSpannableString(); } super.onActivityResult(requestCode, resultCode, data); } public ArrayList<MyContact> shortlistContacts(CharSequence constraint){ String text2 = (String) constraint; if(text2.length()>0){ Pattern p = Pattern.compile(text2, Pattern.CASE_INSENSITIVE); for(int i = 0; i < SmsApplicationLevelData.contactsList.size(); i++){ SmsApplicationLevelData.contactsList.get(i).number = refineNumber(SmsApplicationLevelData.contactsList.get(i).number); Matcher m = p.matcher(SmsApplicationLevelData.contactsList.get(i).name); if(m.find()){ shortlist.add(SmsApplicationLevelData.contactsList.get(i)); } else { m = p.matcher(SmsApplicationLevelData.contactsList.get(i).number); if(m.find()){ shortlist.add(SmsApplicationLevelData.contactsList.get(i)); } } } } return shortlist; } class AutoCompleteAdapter extends ArrayAdapter<MyContact> implements Filterable{ private ArrayList<MyContact> mData; public AutoCompleteAdapter(Context context) { super(context, android.R.layout.simple_dropdown_item_1line); mData = new ArrayList<MyContact>(); } @Override public int getCount() { return mData.size(); } @Override public MyContact getItem(int position) { return mData.get(position); } @Override public Filter getFilter() { Filter myFilter = new Filter(){ @Override protected FilterResults performFiltering(CharSequence constraint) { mData.clear(); FilterResults filterResults = new FilterResults(); String text; try{ text = (String) constraint; text.length(); }catch(NullPointerException npe){ text = " "; } // if(constraint.length()>0){ // text = (String) constraint; // }else{ // text = ""; shortlist.clear(); Log.i("MESSAGE", "f : " + text); positionTrack = 0; if(text.length()>0 && !((text.charAt(text.length()-1)==' ' && text.charAt(text.length()-2) == ','))){ for(int i = 0; i< text.length(); i++){ if(i<text.length()-2 && text.charAt(i) == ',' && text.charAt(i+1) == ' '){ positionTrack = i+2; } } String text2 = text.substring(positionTrack, text.length()); try{ String p = text2; }catch(NullPointerException npe){ text2 = " "; } mData = shortlistContacts(text2); filterResults.values = mData; filterResults.count = mData.size(); } return filterResults; } @Override protected void publishResults(CharSequence constraints, FilterResults results) { if(results != null && results.count > 0) { notifyDataSetChanged(); }else { notifyDataSetInvalidated(); } } }; return myFilter; } public View getView(int position, View convertView, ViewGroup parent){ LayoutInflater inflater = getLayoutInflater(); View row = inflater.inflate(R.layout.dropdown_row_layout, parent, false); TextView nameLabel = (TextView) row.findViewById(R.id.row_name_label); TextView numberLabel = (TextView) row.findViewById(R.id.row_number_label); nameLabel.setText(shortlist.get(position).name); numberLabel.setText(shortlist.get(position).number); return row; } } public String refineNumber(String number){ if(number.matches("[0-9]+")){ return number; } ArrayList<Character> chars = new ArrayList<Character>(); for(int i = 0; i< number.length(); i++){ chars.add(number.charAt(i)); } for(int i = 0; i< chars.size(); i++){ if(!(chars.get(i)=='0' || chars.get(i)=='1' || chars.get(i)=='2' || chars.get(i)=='3' || chars.get(i)=='4' || chars.get(i)=='5' || chars.get(i)=='6' || chars.get(i)=='7' || chars.get(i)=='8' || chars.get(i)=='9'|| chars.get(i)=='+')){ chars.remove(i); i } } //if(number.matches("[0-9]{10}")){ number = new String(); for(int i = 0; i< chars.size(); i++){ number = number + chars.get(i); } return number; } public void refreshSpannableString(){ ssb.clear(); clickableSpanArrayList.clear(); // clickableSpanArrayList = new ArrayList<ClickableSpan>(); spanStartPosition = 0; numbersText.setText(""); for(int i = 0; i< Spans.size(); i++){ final int _i = i; clickableSpanArrayList.add(new ClickableSpan() { @Override public void onClick(View widget) { Log.i("MSG", _i + ""); for(int j = 0; j< nativeGroupData.size(); j++){ for(int k = 0; k< nativeChildData.get(j).size(); k++){ if((Long.parseLong((String)nativeChildData.get(j).get(k).get(Constants.CHILD_CONTACT_ID))) == Spans.get(_i).entityId && (Boolean)nativeChildData.get(j).get(k).get(Constants.CHILD_CHECK)){ nativeChildData.get(j).get(k).put(Constants.CHILD_CHECK, false); } } } Spans.remove(_i); refreshSpannableString(); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); //ds.bgColor = 0Xffb2d6d7; ds.setUnderlineText(false); } }); try{ ssb.append(Spans.get(i).displayName + ", "); ssb.setSpan(clickableSpanArrayList.get(clickableSpanArrayList.size() - 1), spanStartPosition, (spanStartPosition + (Spans.get(i).displayName.length())), SpannableStringBuilder.SPAN_INCLUSIVE_EXCLUSIVE); spanStartPosition += Spans.get(i).displayName.length() + 2; numbersText.setText(ssb); numbersText.setSelection(spanStartPosition); }catch(IndexOutOfBoundsException iob){ } } } @Override public void onBackPressed() { //super.onBackPressed(); if(!(Spans.size()==0) && !(messageText.getText().toString().matches("(''|[' ']*)"))){ final Dialog d = new Dialog(NewScheduleActivity.this); d.requestWindowFeature(Window.FEATURE_NO_TITLE); d.setContentView(R.layout.confirmation_dialog_layout); TextView questionText = (TextView) d.findViewById(R.id.confirmation_dialog_text); Button yesButton = (Button) d.findViewById(R.id.confirmation_dialog_yes_button); Button noButton = (Button) d.findViewById(R.id.confirmation_dialog_no_button); questionText.setText("Schedule Message?"); yesButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.yes_dialog_states)); noButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.no_dialog_states)); yesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doSmsScheduling(); Toast.makeText(NewScheduleActivity.this, "Message Scheduled", Toast.LENGTH_SHORT).show(); if(!checkDateValidity(processDate)){ Toast.makeText(NewScheduleActivity.this, "Date is in Past, message will be sent immediately", Toast.LENGTH_SHORT).show(); } d.cancel(); NewScheduleActivity.this.finish(); } }); noButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { d.cancel(); NewScheduleActivity.this.finish(); } }); d.show(); }else if(!(Spans.size()==0) || !(messageText.getText().toString().matches("(''|[' ']*)"))){ final Dialog d = new Dialog(NewScheduleActivity.this); d.requestWindowFeature(Window.FEATURE_NO_TITLE); d.setContentView(R.layout.confirmation_dialog_layout); TextView questionText = (TextView) d.findViewById(R.id.confirmation_dialog_text); Button yesButton = (Button) d.findViewById(R.id.confirmation_dialog_yes_button); Button noButton = (Button) d.findViewById(R.id.confirmation_dialog_no_button); questionText.setText("Save as Draft?"); yesButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.yes_dialog_states)); noButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.no_dialog_states)); yesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doSmsScheduling(); Toast.makeText(NewScheduleActivity.this, "Message saved as draft", Toast.LENGTH_SHORT).show(); d.cancel(); NewScheduleActivity.this.finish(); } }); noButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { d.cancel(); NewScheduleActivity.this.finish(); } }); d.show(); }else{ NewScheduleActivity.this.finish(); } } public void loadGroupsData(){ nativeGroupData.clear(); nativeChildData.clear(); privateGroupData.clear(); privateChildData.clear(); String[] projection = new String[] { Groups._ID, Groups.TITLE, Groups.SYSTEM_ID, Groups.NOTES, }; Uri groupsUri = ContactsContract.Groups.CONTENT_URI; int count = 0; Cursor groupCursor = managedQuery(groupsUri, projection, null, null, null); if(groupCursor.moveToFirst()){ do{ HashMap<String, Object> group = new HashMap<String, Object>(); group.put(Constants.GROUP_NAME, groupCursor.getString(groupCursor.getColumnIndex(Groups.TITLE))); group.put(Constants.GROUP_IMAGE, new BitmapFactory().decodeResource(getResources(), R.drawable.expander_ic_maximized)); group.put(Constants.GROUP_CHECK, false); group.put(Constants.GROUP_TYPE, 1); group.put(Constants.GROUP_ID, groupCursor.getLong(groupCursor.getColumnIndex(Groups._ID))); ArrayList<HashMap<String, Object>> child = new ArrayList<HashMap<String, Object>>(); nativeGroupData.add(group); for(int i = 0; i < SmsApplicationLevelData.contactsList.size(); i++){ for(int j = 0; j< SmsApplicationLevelData.contactsList.get(i).groupRowId.size(); j++){ if(groupCursor.getLong(groupCursor.getColumnIndex(Groups._ID)) == SmsApplicationLevelData.contactsList.get(i).groupRowId.get(j)){ HashMap<String, Object> childParameters = new HashMap<String, Object>(); childParameters.put(Constants.CHILD_NAME, SmsApplicationLevelData.contactsList.get(i).name); childParameters.put(Constants.CHILD_NUMBER, SmsApplicationLevelData.contactsList.get(i).number); childParameters.put(Constants.CHILD_IMAGE, SmsApplicationLevelData.contactsList.get(i).image); childParameters.put(Constants.CHILD_CHECK, false); childParameters.put(Constants.CHILD_CONTACT_ID, SmsApplicationLevelData.contactsList.get(i).content_uri_id); child.add(childParameters); } } } nativeChildData.add(child); count++; }while(groupCursor.moveToNext()); } mdba.open(); Cursor groupsCursor = mdba.fetchAllGroups(); if(groupsCursor.moveToFirst()){ do{ HashMap<String, Object> group = new HashMap<String, Object>(); group.put(Constants.GROUP_NAME, groupsCursor.getString(groupsCursor.getColumnIndex(DBAdapter.KEY_GROUP_NAME))); group.put(Constants.GROUP_IMAGE, new BitmapFactory().decodeResource(getResources(), R.drawable.expander_ic_maximized)); group.put(Constants.GROUP_CHECK, false); group.put(Constants.GROUP_TYPE, 2); group.put(Constants.GROUP_ID, groupsCursor.getString(groupsCursor.getColumnIndex(DBAdapter.KEY_GROUP_ID))); privateGroupData.add(group); GroupStructure groupStructure; ArrayList<HashMap<String, Object>> child = new ArrayList<HashMap<String, Object>>(); ArrayList<Long> contactIds = mdba.fetchIdsForGroups(groupsCursor.getLong(groupsCursor.getColumnIndex(DBAdapter.KEY_GROUP_ID))); for(int i = 0; i< contactIds.size(); i++){ for(int j = 0; j< SmsApplicationLevelData.contactsList.size(); j++){ if(contactIds.get(i)==Long.parseLong(SmsApplicationLevelData.contactsList.get(j).content_uri_id)){ HashMap<String, Object> childParameters = new HashMap<String, Object>(); childParameters.put(Constants.CHILD_NAME, SmsApplicationLevelData.contactsList.get(j).name); childParameters.put(Constants.CHILD_NUMBER, SmsApplicationLevelData.contactsList.get(j).number); childParameters.put(Constants.CHILD_CONTACT_ID, SmsApplicationLevelData.contactsList.get(j).content_uri_id); childParameters.put(Constants.CHILD_IMAGE, SmsApplicationLevelData.contactsList.get(j).image); childParameters.put(Constants.CHILD_CHECK, false); child.add(childParameters); } } } privateChildData.add(child); count++; }while(groupsCursor.moveToNext()); } mdba.close(); } private void startVoiceRecognitionActivity() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo"); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5); startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE); } }
package ch.idsia.benchmark.mario.engine.level; import ch.idsia.benchmark.mario.engine.sprites.Sprite; import ch.idsia.tools.MarioAIOptions; import ch.idsia.tools.RandomCreatureGenerator; import ch.idsia.utils.ErrorCodes; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.Random; /** * This class is simple to use. Just call <b>createLevel</b> method with params: * <ul> * MarioAIOptions args, that contains: ... TODO:TASK:[M] * <p/> * <li>length -- length of the level in cells. One cell is 16 pixels long</li> * <li>height -- height of the level in cells. One cell is 16 pixels long </li> * <li>seed -- use this param to make a globalRandom level. * On different machines with the same seed param there will be one level</li> * <li>levelDifficulty -- use this param to change difficult of the level. * On different machines with the same seed param there will be one level</li> * <li>levelType -- levelType of the level. One of Overground, Underground, Castle.</li> * </ul> * * @see #TYPE_OVERGROUND * @see #TYPE_UNDERGROUND * @see #TYPE_CASTLE */ public class LevelGenerator { public static final int TYPE_OVERGROUND = 0; public static final int TYPE_UNDERGROUND = 1; public static final int TYPE_CASTLE = 2; public static final int DEFAULT_FLOOR = -1; public static final int LevelLengthMinThreshold = 50; // minimal length of the level. used in ToolsConfigurator private static boolean isFlatLevel; private static int length; private static int height; private static Level level; private static Random globalRandom = new Random(0); private static Random ceilingRandom = new Random(0); private static RandomCreatureGenerator creaturesRandom = new RandomCreatureGenerator(0, "", 0); public static Random dxRnd = new Random(0); //used in addEnemy to compute dx private static final int ODDS_STRAIGHT = 0; private static final int ODDS_HILL_STRAIGHT = 1; private static final int ODDS_TUBES = 2; private static final int ODDS_GAPS = 3; private static final int ODDS_CANNONS = 4; private static final int ODDS_DEAD_ENDS = 5; private static int[] odds = new int[6]; private static int totalOdds; private static int levelDifficulty; private static int levelType; private static int levelSeed; private static final int ANY_HEIGHT = -1; private static final int INFINITE_FLOOR_HEIGHT = Integer.MAX_VALUE; //Level customization counters static Level.objCounters counters = new Level.objCounters(); private LevelGenerator() {} private static void loadLevel(String filePath) { try { if (filePath.equals("")) //This must never happen { System.err.println("[MarioAI ERROR] : level file path is empty; exiting..."); System.exit(ErrorCodes.FILE_NAME_OR_LOAD_PROBLEM); } level = Level.load(new ObjectInputStream(new FileInputStream(filePath))); } catch (IOException e) { System.err.println("[MarioAI EXCEPTION] : failed while trying to load " + filePath); System.exit(ErrorCodes.FILE_NAME_OR_LOAD_PROBLEM); } catch (ClassNotFoundException e) { System.err.println("[MarioAI EXCEPTION] : class not found in " + filePath); System.exit(ErrorCodes.FILE_NAME_OR_LOAD_PROBLEM); } } public static Level createLevel(MarioAIOptions args) { // -ls option can also load level from file if filename instead of a number provided levelType = args.getLevelType(); try { levelSeed = args.getLevelRandSeed() + levelType; } catch (Exception e) { loadLevel(args.getParameterValue("-ls")); return level; } length = args.getLevelLength(); height = args.getLevelHeight(); if (height < 15) { System.err.println("[Mario AI WARNING] : Level height changed to minimal allowed value 15"); height = 15; } isFlatLevel = args.isFlatLevel(); if (isFlatLevel) { args.setBlocksCount(false); args.setCoinsCount(false); args.setTubesCount(false); args.setGapsCount(false); args.setDeadEndsCount(false); args.setCannonsCount(false); args.setEnemies("off"); } counters.reset(args); levelDifficulty = args.getLevelDifficulty(); odds[ODDS_STRAIGHT] = 20; odds[ODDS_HILL_STRAIGHT] = 1; odds[ODDS_TUBES] = 2 + 1 * levelDifficulty; odds[ODDS_GAPS] = 3 * levelDifficulty; odds[ODDS_CANNONS] = -10 + 5 * levelDifficulty; odds[ODDS_DEAD_ENDS] = 2 + 2 * levelDifficulty; if (levelType != LevelGenerator.TYPE_OVERGROUND) odds[ODDS_HILL_STRAIGHT] = 0; //no hill straight in TYPE_OVERGROUND level totalOdds = 0; for (int i = 0; i < odds.length; i++) { if (odds[i] < 0) odds[i] = 0; totalOdds += odds[i]; odds[i] = totalOdds - odds[i]; } level = new Level(length, height); // levelSeed = args.getLevelRandSeed();// + levelType; // TODO:TASK:[M] ensure the difference of underground, castle globalRandom.setSeed(levelSeed); creaturesRandom.setSeed(levelSeed, args.getEnemies(), levelDifficulty); ceilingRandom.setSeed(levelSeed); dxRnd.setSeed(levelSeed); int currentLength = 0; //total level currentLength so far //by default mario supposed to start on a straight surface int floor = DEFAULT_FLOOR; if (isFlatLevel) floor = height - 1 - globalRandom.nextInt(4); currentLength += buildStraight(0, level.length, true, floor, INFINITE_FLOOR_HEIGHT); while (currentLength < level.length - 10) { // System.out.println("level.currentLength - currentLength = " + (level.currentLength - currentLength)); currentLength += buildZone(currentLength, level.length - currentLength, ANY_HEIGHT, floor, INFINITE_FLOOR_HEIGHT); } if (!isFlatLevel) //NOT flat level floor = height - 1 - globalRandom.nextInt(4); //floor of the exit line //coordinates of the exit level.xExit = level.length; level.yExit = floor; level.randomSeed = levelSeed; level.type = levelType; level.difficulty = levelDifficulty; //level zone where exit is located for (int x = currentLength; x < level.length; x++) { for (int y = 0; y < height; y++) { if (y >= floor) { level.setBlock(x, y, (byte) (1 + 9 * 16)); } } } // //if underground or castle then build ceiling // if (levelType == LevelGenerator.TYPE_CASTLE || levelType == LevelGenerator.TYPE_UNDERGROUND) // int ceiling = 0; // int run = 0; // for (int x = 0; x < level.length; x++) // if (run-- <= 0 && x > 4) // ceiling = globalRandom.nextInt(4); // run = globalRandom.nextInt(4) + 4; // for (int y = 0; y < level.height; y++) // if ((x > 4 && y <= ceiling) || x < 1) // level.setBlock(x, 0, (byte) (1 + 9 * 16)); fixWalls(); level.counters = counters; return level; } private static int buildZone(int x, int maxLength, int maxHeight, int floor, int floorHeight) { // System.out.println("buildZone maxLength = " + maxLength); int t = globalRandom.nextInt(totalOdds); int type = 0; //calculate what will be built for (int i = 0; i < odds.length; i++) { if (odds[i] <= t) { type = i; } } int length = 0; switch (type) { case ODDS_STRAIGHT: length = buildStraight(x, maxLength, false, floor, floorHeight); break; case ODDS_HILL_STRAIGHT: if (floor == DEFAULT_FLOOR && counters.hillStraightCount < counters.totalHillStraight) { counters.hillStraightCount++; // length = buildHillStraight(x, maxLength, floor, false); length = buildHill(x, true, maxLength, floor, false); } else length = 0; break; case ODDS_TUBES: if (counters.tubesCount < counters.totalTubes) length = buildTubes(x, maxLength, maxHeight, floor, floorHeight); else length = 0; break; case ODDS_GAPS: if ((floor > 2 || floor == ANY_HEIGHT) && (counters.gapsCount < counters.totalGaps)) { counters.gapsCount++; length = buildGap(x, maxLength, maxHeight, floor, floorHeight); } else length = 0; break; case ODDS_CANNONS: if (counters.cannonsCount < counters.totalCannons) length = buildCannons(x, maxLength, maxHeight, floor, floorHeight); else length = 0; break; case ODDS_DEAD_ENDS: { if (floor == DEFAULT_FLOOR && counters.deadEndsCount < counters.totalDeadEnds) //if method was not called from buildDeadEnds { counters.deadEndsCount++; length = buildDeadEnds(x, maxLength); } } } int crCount = 0; // for (int y = level.height - 3; y > levelDifficulty + 1; --y) // addEnemy(x, y); // ++crCount; for (int yy = level.height; yy > 0; yy if (level.getBlock(x, yy) == 0 && creaturesRandom.nextInt(levelDifficulty + 1) + 1 > (levelDifficulty + 1) / 2 && crCount < levelDifficulty + 1 && level.getSpriteTemplate(x, yy) == null) { addEnemy(x, yy); ++crCount; } if (levelType > 0) buildCeiling(x, length); return length; } private static void buildCeiling(int x0, int length) { int maxCeilingHeight = 3; int ceilingLength = length; if (ceilingLength < 2) return; // len: // for (int i = x0; i < x1; i++) // for (int j = 0; j < height; j++) // if (level.getBlock(i, j) != 0) // maxCeilingHeight = j; // break len; int len = 0; while (len < ceilingLength) { int sectionLength = ceilingRandom.nextInt(2) + 2; if (sectionLength > ceilingLength) sectionLength = ceilingLength; // if (maxCeilingHeight > 0) // maxCeilingHeight--; // if (maxCeilingHeight == 0) // maxCeilingHeight = 1; // if (maxCeilingHeight > 5) // maxCeilingHeight = 5; int height = ceilingRandom.nextInt(maxCeilingHeight) + 1; for (int i = 0; i < sectionLength; i++) { for (int j = 0; j < height; j++) level.setBlock(x0 + len + i, j, (byte) (1 + 9 * 16)); } len += sectionLength; } } private static void addEnemy(int x, int y) { if (!creaturesRandom.canAdd()) return; int dx = (int) dxRnd.nextGaussian(); int creatureKind = creaturesRandom.nextCreature(); if (creatureKind != Sprite.KIND_UNDEF) { if (level.setSpriteTemplate(x + dx, y, new SpriteTemplate(creatureKind))) ++counters.creatures; else creaturesRandom.increaseLastCreature(); } } //x0 - first block to start from //maxLength - maximal length of the zone private static int buildDeadEnds(int x0, int maxLength) { //first of all build pre dead end zone int floor = height - 2 - globalRandom.nextInt(2); //floor of pre dead end zone int length = 0; // total zone length int preDeadEndLength = 7 + globalRandom.nextInt(10); int rHeight = floor - 1; //rest height length += buildStraight(x0, preDeadEndLength, true, floor, INFINITE_FLOOR_HEIGHT);//buildZone( x0, x0+preDeadEndLength, floor ); //build pre dead end zone buildBlocks(x0, x0 + preDeadEndLength, floor, true, 0, 0, true, true); //correct direction //true - top, false = bottom globalRandom.nextInt(); int k = globalRandom.nextInt(5);//(globalRandom.nextInt() % (this.levelDifficulty+1)); boolean direction = globalRandom.nextInt(k + 1) != 1; int separatorY = 3 + globalRandom.nextInt(rHeight - 7); //Y coordinate of the top line of the separator //Y coordinate of the bottom line of the separator is determined as separatorY + separatorHeight int separatorHeight = 2 + globalRandom.nextInt(2); int nx = x0 + length; int depth = globalRandom.nextInt(levelDifficulty + 1) + 2 * (1 + levelDifficulty); if (depth + length > maxLength) { // depth = maxLength while (depth + length > maxLength - 1) { depth } } int tLength = 0; int bSpace = floor - (separatorY + separatorHeight); if (bSpace < 4) { while (bSpace < 4) { separatorY -= 1; bSpace = floor - (separatorY + separatorHeight); } } int wallWidth = 2 + globalRandom.nextInt(3); while (tLength < depth) //top part { tLength += buildZone(nx + tLength, depth - tLength, separatorY - 1, separatorY, separatorHeight); } tLength = 0; while (tLength < depth) //bottom part { tLength += buildZone(nx + tLength, depth - tLength, bSpace, floor, INFINITE_FLOOR_HEIGHT); } for (int x = nx; x < nx + depth; x++) { for (int y = 0; y < height; y++) { if (x - nx >= depth - wallWidth) { if (direction == true) //wall on the top { if (y <= separatorY)// + separatorHeight ) { level.setBlock(x, y, (byte) (1 + 9 * 16)); } } else { if (y >= separatorY) { level.setBlock(x, y, (byte) (1 + 9 * 16)); } } } } } return length + tLength; } private static int buildGap(int xo, int maxLength, int maxHeight, int vfloor, int floorHeight) { int gs = globalRandom.nextInt(5) + 2; //GapStairs int gl = globalRandom.nextInt(levelDifficulty) + levelDifficulty > 7 ? 10 : 3;//globalRandom.nextInt(2) + 2; //GapLength int length = gs * 2 + gl; if (length > maxLength) length = maxLength; boolean hasStairs = globalRandom.nextInt(3) == 0; if (isFlatLevel || (maxHeight <= 5 && maxHeight != ANY_HEIGHT)) { hasStairs = false; } int floor = vfloor; if (vfloor == DEFAULT_FLOOR && !isFlatLevel) { floor = height - 1 - globalRandom.nextInt(4); } else //code in this block is a magic. don't change it { floor++; // globalRandom.nextInt(); if (floor > 1) { floor -= 1; } } if (floorHeight == INFINITE_FLOOR_HEIGHT) { floorHeight = height - floor; } // if (gs > 3 && creaturesRandom.nextInt(35) > levelDifficulty + 1 && !hasStairs) //// addEnemiesLine(xo, xo + gs - 1, floor - 1); //// addEnemiesLine(xo + length - gs, xo + length - 1, floor - 1); for (int x = xo; x < xo + length; x++) { if (x < xo + gs || x > xo + length - gs - 1) { for (int y = 0; y < height; y++) { if (y >= floor && y <= floor + floorHeight) level.setBlock(x, y, (byte) (1 + 9 * 16)); else if (hasStairs) { if (x < xo + gs) { if (y >= floor - (x - xo) + 1 && y <= floor + floorHeight) level.setBlock(x, y, (byte) (9 + 0 * 16)); } else if (y >= floor - ((xo + length) - x) + 2 && y <= floor + floorHeight) level.setBlock(x, y, (byte) (9 + 0 * 16)); } } } } if (gl > 8) { buildHill(xo + gs + globalRandom.nextInt(Math.abs((gl - 4)) / 2 + 1), false, 3, floor, true); } return length; } private static int buildCannons(int xo, int maxLength, int maxHeight, int vfloor, int floorHeight) { int maxCannonHeight = 0; int length = globalRandom.nextInt(10) + 2; if (length > maxLength) length = maxLength; int floor = vfloor; if (vfloor == DEFAULT_FLOOR) { floor = height - 1 - globalRandom.nextInt(4); } else { globalRandom.nextInt(); } if (floorHeight == INFINITE_FLOOR_HEIGHT) { floorHeight = height - floor; } int oldXCannon = -1; int xCannon = xo + 1 + globalRandom.nextInt(4); for (int x = xo; x < xo + length; x++) { if (x > xCannon) { xCannon += 2 + globalRandom.nextInt(4); counters.cannonsCount++; } if (xCannon == xo + length - 1) { xCannon += 10; } int cannonHeight = floor - globalRandom.nextInt(3) - 1; //cannon height is a Y coordinate of top part of the cannon if (maxHeight != ANY_HEIGHT) { //maxHeight -= 2; if (floor - cannonHeight >= maxHeight) { if (maxHeight > 4) { maxHeight = 4; } while (floor - cannonHeight > maxHeight) { cannonHeight++; } } if (cannonHeight > maxCannonHeight) maxCannonHeight = cannonHeight; } for (int y = 0; y < height; y++) { if (y >= floor && y <= floor + floorHeight) { level.setBlock(x, y, (byte) (1 + 9 * 16)); } else if (counters.cannonsCount <= counters.totalCannons) { if (x == xCannon && y >= cannonHeight && y <= floor)// + floorHeight) { if (y == cannonHeight) { if (oldXCannon != -1 && creaturesRandom.nextInt(35) > levelDifficulty + 1) { // addEnemiesLine(oldXCannon + 1, xCannon - 1, floor - 1); } oldXCannon = x; level.setBlock(x, y, (byte) (14 + 0 * 16)); // cannon barrel } else if (y == cannonHeight + 1) { level.setBlock(x, y, (byte) (14 + 1 * 16)); // base for cannon barrel } else { level.setBlock(x, y, (byte) (14 + 2 * 16)); // cannon pole } } } } } if (globalRandom.nextBoolean()) buildBlocks(xo, xo + length, floor - maxCannonHeight - 2, false, 0, 0, false, false); return length; } private static int buildHill(int x0, boolean withStraight, int maxLength, int vfloor, boolean isInGap) { int length = globalRandom.nextInt(10) + 10; if (length > maxLength) { length = maxLength; } int floor = vfloor; if (vfloor == DEFAULT_FLOOR) { floor = height - 1 - globalRandom.nextInt(4); } if (withStraight) { for (int x = x0; x < x0 + length; x++) { for (int y = 0; y < height; y++) { if (y >= floor) { level.setBlock(x, y, (byte) (1 + 9 * 16)); } } } } boolean canBuild = true; int top = floor; if (isInGap) floor = level.height; while (canBuild) { top -= isFlatLevel ? 0 : (globalRandom.nextInt(2) + 2); if (top < 0) canBuild = false; else { int l = globalRandom.nextInt(length / 2) + 1; int xx0 = globalRandom.nextInt(l + 1) + x0; if (globalRandom.nextInt(4) == 0) { decorate(xx0 - 1, xx0 + l + 1, top); canBuild = false; } for (int x = xx0; x < xx0 + l; x++) { for (int y = top; y < floor; y++) { int xx = 5; if (x == xx0) xx = 4; if (x == xx0 + l - 1) xx = 6; int yy = 9; if (y == top) yy = 8; if (level.getBlock(x, y) == 0) { level.setBlock(x, y, (byte) (xx + yy * 16)); } else { if (level.getBlock(x, y) == (byte) (4 + 8 * 16)) level.setBlock(x, y, (byte) (4 + 11 * 16)); if (level.getBlock(x, y) == (byte) (6 + 8 * 16)) level.setBlock(x, y, (byte) (6 + 11 * 16)); } } } addEnemy(xx0, top - 1); } } return length; } private static int buildTubes(int xo, int maxLength, int maxHeight, int vfloor, int floorHeight) { int maxTubeHeight = 0; int length = globalRandom.nextInt(10) + 5; if (length > maxLength) length = maxLength; int floor = vfloor; if (vfloor == DEFAULT_FLOOR) { floor = height - 1 - globalRandom.nextInt(4); } else { globalRandom.nextInt(); } int xTube = xo + 1 + globalRandom.nextInt(4); int tubeHeight = floor - globalRandom.nextInt(3) - 1; if (maxHeight != ANY_HEIGHT) { //maxHeight -= 2; if (floor - tubeHeight > maxHeight) { if (maxHeight > 4) { maxHeight = 4; } while (floor - tubeHeight > maxHeight) { tubeHeight++; } } } if (floorHeight == INFINITE_FLOOR_HEIGHT) { floorHeight = height - floor; } int oldXTube = -1; for (int x = xo; x < xo + length; x++) { if (x > xTube + 1) { xTube += 3 + globalRandom.nextInt(4); tubeHeight = floor - globalRandom.nextInt(2) - 2; if (maxHeight != ANY_HEIGHT) { while (floor - tubeHeight > maxHeight - 1) { tubeHeight++; } } if (tubeHeight > maxTubeHeight) maxTubeHeight = tubeHeight; } if (xTube >= xo + length - 2) { xTube += 10; } if (x == xTube && globalRandom.nextInt(11) < levelDifficulty + 1 && creaturesRandom.isCreatureEnabled("f")) { level.setSpriteTemplate(x, tubeHeight, new SpriteTemplate(Sprite.KIND_ENEMY_FLOWER)); ++counters.creatures; } for (int y = 0; y < floor + floorHeight; y++) { if (y >= floor && y <= floor + floorHeight) level.setBlock(x, y, (byte) (1 + 9 * 16)); else { if ((x == xTube || x == xTube + 1) && y >= tubeHeight) { int xPic = 10 + x - xTube; if (y == tubeHeight) { level.setBlock(x, y, (byte) (xPic + 0 * 16)); if (x == xTube) { if (oldXTube != -1 && creaturesRandom.nextInt(35) > levelDifficulty + 1) { // addEnemiesLine(oldXTube + 2, xTube - 1, floor - 1); } oldXTube = x; counters.tubesCount++; } } else { level.setBlock(x, y, (byte) (xPic + 1 * 16)); } } } } } if (globalRandom.nextBoolean()) buildBlocks(xo, xo + length, floor - maxTubeHeight - 2, false, 0, 0, false, false); return length; } // parameter safe should be set to true iff length of the Straight > 10. // minimal length = 2 //floorHeight - height of the floor. used for building of the top part of the dead end separator private static int buildStraight(int xo, int maxLength, boolean safe, int vfloor, int floorHeight) { int length; if (floorHeight != INFINITE_FLOOR_HEIGHT) { length = maxLength; } else { length = globalRandom.nextInt(8) + 2;//globalRandom.nextInt(50)+1) + 2; if (safe) length = 10 + globalRandom.nextInt(5); if (length > maxLength) length = maxLength; } int floor = vfloor; if (vfloor == DEFAULT_FLOOR) { floor = height - 1 - globalRandom.nextInt(4); } else { globalRandom.nextInt(); } int y1 = height; if (floorHeight != INFINITE_FLOOR_HEIGHT) { y1 = floor + floorHeight; } for (int x = xo; x < xo + length; x++) for (int y = floor; y < y1; y++) if (y >= floor) level.setBlock(x, y, (byte) (1 + 9 * 16)); if (!safe) { if (length > 5) { decorate(xo, xo + length, floor); } } return length; } private static boolean canBuildBlocks(int x0, int floor, boolean isHB) { if ((counters.blocksCount >= counters.totalBlocks && !isHB)) { return false; } boolean res = true; // if (floor < 1) // return false; // for (int y = 0; y < 1; y++) // if (level.getBlock(x0, floor - y) != 0) // res = false; // break; return res; } private static void buildBlocks(int x0, int x1, int floor, boolean pHB, int pS, int pE, boolean onlyHB, boolean isDistance) { if (counters.blocksCount > counters.totalBlocks) { return; } int s = pS; //Start int e = pE; //End boolean hb = pHB; if (onlyHB) hb = onlyHB; --floor; while (floor > 0) //minimal distance between the bricks line and floor is 4 { if ((x1 - 1 - e) - (x0 + 1 + s) > 0) //minimal number of bricks in the line is positive value { for (int x = x0 + s; x < x1 - e; x++) { if (hb && counters.totalHiddenBlocks != 0) //if hidden blocks to be built { boolean isBlock = globalRandom.nextInt(2) == 1; if (isBlock && canBuildBlocks(x, floor - 4, true)) { level.setBlock(x, floor - 4, (byte) (1)); //a hidden block with a coin counters.hiddenBlocksCount++; ++counters.coinsCount; } } else { boolean canDeco = false; //can add enemy line and coins //decorate( x0, x1, floor, true ); if (x != x0 + 1 && x != x1 - 2 && globalRandom.nextInt(3) == 0) { if (canBuildBlocks(x, floor - 4, false)) { counters.blocksCount++; if ((globalRandom.nextInt(4) == 0)) { if (level.getBlock(x, floor) == 0) level.setBlock(x, floor, (byte) (4 + 2 + 1 * 16)); //a brick with animated question symbol with power up. when broken becomes a rock } else { if (level.getBlock(x, floor) == 0) { level.setBlock(x, floor, (byte) (4 + 1 + 1 * 16)); //a brick with animated question symbol with coin. when broken becomes a rock ++counters.coinsCount; } } canDeco = true; } } else if (globalRandom.nextInt(4) == 0) { if (canBuildBlocks(x, floor - 4, false)) { counters.blocksCount++; if (globalRandom.nextInt(4) == 0) { if (level.getBlock(x, floor) == 0) level.setBlock(x, floor, (byte) (2 + 1 * 16)); //a brick with a power up. when broken becomes a rock } else { if (level.getBlock(x, floor) == 0) { level.setBlock(x, floor, (byte) (1 + 1 * 16)); //a brick with a coin. when broken becomes a rock ++counters.coinsCount; } } canDeco = true; } } else if (globalRandom.nextInt(2) == 1 && canBuildBlocks(x, floor - 4, false)) { if (level.getBlock(x, floor) == 0) { counters.blocksCount++; //TODO:TASK:!H! move it in to the Level.setBlock level.setBlock(x, floor, (byte) (0 + 1 * 16)); //a break brick canDeco = true; } } if (canDeco) { //if (creaturesRandom.nextInt(35) > levelDifficulty + 1) addEnemiesLine(x0 + 1, x1 - 1, floor - 1); buildCoins(x0, x1, floor, s, e); } } } if (onlyHB) { hb = true; } else { hb = globalRandom.nextInt(4) == 0;//globalRandom.nextInt(3) == globalRandom.nextInt(3); } } // if (creaturesRandom.nextInt(35) > levelDifficulty + 1) // addEnemiesLine(x0 + 1, x1 - 1, floor - 1); floor -= isDistance ? 4 : globalRandom.nextInt(6) + 3; s = globalRandom.nextInt(4); e = globalRandom.nextInt(4); } globalRandom.nextBoolean(); } private static void buildCoins(int x0, int x1, int floor, int s, int e) { if (floor - 2 < 0) return; //if (!isFlatLevel) if ((x1 - 1 - e) - (x0 + 1 + s) > 1) { for (int x = x0 + 1 + s; x < x1 - 1 - e; x++) { if (counters.coinsCount >= counters.totalCoins) { break; } if (level.getBlock(x, floor - 2) == 0) //if cell (x, floor-2) is empty { counters.coinsCount++; level.setBlock(x, floor - 2, (byte) (2 + 2 * 16)); //coin } } } } private static void decorate(int x0, int x1, int floor) { if (floor < 1) return; int s = globalRandom.nextInt(4); int e = globalRandom.nextInt(4); boolean hb = ((globalRandom.nextInt(levelDifficulty + 1) % (levelDifficulty + 1))) > 0.5; // if (!hb) // addEnemiesLine(x0 + 1, x1 - 1, floor - 1); if (floor - 2 > 0 && !hb) { buildCoins(x0, x1, floor, s, e); } buildBlocks(x0, x1, floor, hb, s, e, false, false); } private static void fixWalls() { boolean[][] blockMap = new boolean[length + 1][height + 1]; for (int x = 0; x < length + 1; x++) { for (int y = 0; y < height + 1; y++) { int blocks = 0; for (int xx = x - 1; xx < x + 1; xx++) { for (int yy = y - 1; yy < y + 1; yy++) { if (level.getBlockCapped(xx, yy) == (byte) (1 + 9 * 16)) blocks++; } } blockMap[x][y] = blocks == 4; } } blockify(level, blockMap, length + 1, height + 1); } private static void blockify(Level level, boolean[][] blocks, int width, int height) { int to = 0; if (levelType == LevelGenerator.TYPE_CASTLE) to = 4 * 2; else if (levelType == LevelGenerator.TYPE_UNDERGROUND) to = 4 * 3; boolean[][] b = new boolean[2][2]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { for (int xx = x; xx <= x + 1; xx++) { for (int yy = y; yy <= y + 1; yy++) { int _xx = xx; int _yy = yy; if (_xx < 0) _xx = 0; if (_yy < 0) _yy = 0; if (_xx > width - 1) _xx = width - 1; if (_yy > height - 1) _yy = height - 1; b[xx - x][yy - y] = blocks[_xx][_yy]; } } if (b[0][0] == b[1][0] && b[0][1] == b[1][1]) { if (b[0][0] == b[0][1]) { if (b[0][0]) { level.setBlock(x, y, (byte) (1 + 9 * 16 + to)); } else { // KEEP OLD BLOCK! } } else { if (b[0][0]) { level.setBlock(x, y, (byte) (1 + 10 * 16 + to)); } else { level.setBlock(x, y, (byte) (1 + 8 * 16 + to)); } } } else if (b[0][0] == b[0][1] && b[1][0] == b[1][1]) { if (b[0][0]) { level.setBlock(x, y, (byte) (2 + 9 * 16 + to)); } else { level.setBlock(x, y, (byte) (0 + 9 * 16 + to)); } } else if (b[0][0] == b[1][1] && b[0][1] == b[1][0]) { level.setBlock(x, y, (byte) (1 + 9 * 16 + to)); } else if (b[0][0] == b[1][0]) { if (b[0][0]) { if (b[0][1]) { level.setBlock(x, y, (byte) (3 + 10 * 16 + to)); } else { level.setBlock(x, y, (byte) (3 + 11 * 16 + to)); } } else { if (b[0][1]) { level.setBlock(x, y, (byte) (2 + 8 * 16 + to)); } else { level.setBlock(x, y, (byte) (0 + 8 * 16 + to)); } } } else if (b[0][1] == b[1][1]) { if (b[0][1]) { if (b[0][0]) { level.setBlock(x, y, (byte) (3 + 9 * 16 + to)); } else { level.setBlock(x, y, (byte) (3 + 8 * 16 + to)); } } else { if (b[0][0]) { level.setBlock(x, y, (byte) (2 + 10 * 16 + to)); } else { level.setBlock(x, y, (byte) (0 + 10 * 16 + to)); } } } else { level.setBlock(x, y, (byte) (0 + 1 * 16 + to)); } } } } //private static int buildHillStraight(int xo, int maxLength, int vfloor, final boolean isInGap) //// System.out.println("xo = " + xo); // int length = globalRandom.nextInt(10) + 10; // if (length > maxLength) // length = maxLength; //*/ /* first component of sum : position on Y axis second component of sum : position on X axis starting at 0 *16 because size of the picture is 16x16 pixels 0+9*16 -- left side of the ground 1+9*16 -- upper side of ground; common block telling "it's smth (ground) here". Is processed further. 2+9*16 -- right side of the earth 3+9*16 -- peice of the earth 9+0*16 -- block of a ladder 14+0*16 -- cannon barrel 14+1*16 -- base for cannon barrel 14+2*16 -- cannon pole 4+8*16 -- left piece of a hill of ground 4+11*16 -- left piece of a hill of ground as well 6+8*16 -- right upper peice of a hill 6+11*16 -- right upper peice of a hill on earth 2+2*16 -- animated coin 4+2+1*16 -- a rock with animated question symbol with power up 4+1+1*16 -- a rock with animated question symbol with coin 2+1*16 -- brick with power up. when broken becomes a rock 1+1*16 -- brick with power coin. when broken becomes a rock 0+1*16 -- break brick 1+10*16 -- earth, bottom piece 1+8*16 -- earth, upper piece 3+10*16 -- piece of earth 3+11*16 -- piece of earth 2+8*16 -- right part of earth 0+8*16 -- left upper part of earth 3+8*16 -- piece of earth 2+10*16 -- right bottomp iece of earth 0+10*16 -- left bottom piece of earth */
package org.smoothbuild.util.collect; import static org.smoothbuild.util.collect.Lists.toCommaSeparatedString; import static org.smoothbuild.util.collect.Named.named; import java.util.Objects; import java.util.function.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; public class NamedList<T> { private final ImmutableList<Named<T>> list; private final ImmutableMap<String, T> map; private final ImmutableMap<String, Integer> indexMap; public static <E> NamedList<E> namedList(ImmutableList<Named<E>> list) { return new NamedList<>(list); } private NamedList(ImmutableList<Named<T>> list) { this.list = list; this.map = calculateMap(list); this.indexMap = calculateIndexMap(list); } public ImmutableList<Named<T>> list() { return list; } public ImmutableList<T> objects() { return Lists.map(list, Named::object); } public ImmutableMap<String, T> map() { return map; } public boolean contains(String name) { return map.containsKey(name); } public T getObject(int index) { return list.get(index).object(); } public int size() { return list.size(); } public ImmutableMap<String, Integer> indexMap() { return indexMap; } public <R> NamedList<R> mapObjects(Function<T, R> mapper) { return new NamedList<>(Lists.map(list, n -> named(n.name(), mapper.apply(n.object())))); } private static <E> ImmutableMap<String, Integer> calculateIndexMap( ImmutableList<Named<E>> nameds) { Builder<String, Integer> builder = ImmutableMap.builder(); for (int i = 0; i < nameds.size(); i++) { int index = i; nameds.get(i).name().ifPresent(n -> builder.put(n, index)); } return builder.build(); } private static <E> ImmutableMap<String, E> calculateMap(ImmutableList<Named<E>> nameds) { Builder<String, E> builder = ImmutableMap.builder(); for (Named<E> named : nameds) { named.name().ifPresent(n -> builder.put(n, named.object())); } return builder.build(); } @Override public boolean equals(Object object) { if (this == object) { return true; } return object instanceof NamedList<?> that && list.equals(that.list); } @Override public int hashCode() { return Objects.hash(list); } @Override public String toString() { return "NamedList(" + valuesToString() + ")"; } public String valuesToString() { return toCommaSeparatedString(list); } }
package nallar.patched.world.tracking; import java.util.ArrayList; import nallar.collections.ConcurrentLinkedQueueList; import nallar.tickthreading.Log; import nallar.tickthreading.patcher.Declare; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.PlayerInstance; import net.minecraft.server.management.PlayerManager; import net.minecraft.world.WorldServer; public abstract class PatchPlayerManager extends PlayerManager { public Object chunkWatcherLock; private ConcurrentLinkedQueueList<PlayerInstance> chunkWatcherWithPlayersQ; public void construct() { chunkWatcherLock = new Object(); try { chunkWatcherWithPlayers = chunkWatcherWithPlayersQ = new ConcurrentLinkedQueueList<PlayerInstance>(); } catch (NoSuchFieldError e) { // MCPC+. } } @Override @Declare public net.minecraft.util.LongHashMap getChunkWatchers() { return this.playerInstances; } @Override public void updatePlayerInstances() { int currentTick = MinecraftServer.currentTick; ArrayList<PlayerInstance> postponed = new ArrayList<PlayerInstance>(); PlayerInstance playerInstance; while ((playerInstance = chunkWatcherWithPlayersQ.poll()) != null) { try { if (playerInstance.shouldPostPone(currentTick++ % 800 == 0, currentTick)) { postponed.add(playerInstance); } else { playerInstance.sendChunkUpdate(); } } catch (Exception e) { Log.severe("Failed to send " + playerInstance, e); playerInstance.clearTileCount(); } } chunkWatcherWithPlayersQ.addAll(postponed); if (currentTick % 300 == 0 && this.players.isEmpty()) { this.theWorldServer.theChunkProviderServer.unloadAllChunks(); } } @Override public PlayerInstance getOrCreateChunkWatcher(int par1, int par2, boolean par3) { long var4 = (long) par1 + 2147483647L | (long) par2 + 2147483647L << 32; PlayerInstance var6 = (PlayerInstance) this.playerInstances.getValueByKey(var4); if (var6 == null && par3) { synchronized (chunkWatcherLock) { var6 = (PlayerInstance) this.playerInstances.getValueByKey(var4); if (var6 == null) { var6 = new PlayerInstance(this, par1, par2); this.playerInstances.add(var4, var6); } } } return var6; } public PatchPlayerManager(WorldServer par1WorldServer, int par2) { super(par1WorldServer, par2); } @Override @Declare public java.util.Queue<PlayerInstance> getChunkWatcherWithPlayers() { return this.chunkWatcherWithPlayersQ; } }
package com.emc.mongoose.generator; import com.emc.mongoose.common.concurrent.DaemonBase; import com.emc.mongoose.common.concurrent.Throttle; import com.emc.mongoose.model.api.io.Output; import com.emc.mongoose.model.impl.item.CsvFileItemInput; import com.emc.mongoose.model.util.ItemNamingType; import com.emc.mongoose.model.util.LoadType; import com.emc.mongoose.common.exception.UserShootHisFootException; import static com.emc.mongoose.ui.config.Config.ItemConfig.NamingConfig; import static com.emc.mongoose.ui.config.Config.ItemConfig; import static com.emc.mongoose.ui.config.Config.LoadConfig; import static com.emc.mongoose.ui.config.Config.LoadConfig.LimitConfig; import com.emc.mongoose.ui.log.LogUtil; import com.emc.mongoose.ui.log.Markers; import com.emc.mongoose.model.api.io.Input; import com.emc.mongoose.model.api.io.task.IoTask; import com.emc.mongoose.model.api.io.task.IoTaskFactory; import com.emc.mongoose.model.api.item.Item; import com.emc.mongoose.model.api.item.ItemFactory; import com.emc.mongoose.model.api.load.Driver; import com.emc.mongoose.model.api.load.Generator; import com.emc.mongoose.model.api.load.Monitor; import com.emc.mongoose.model.impl.io.RangePatternDefinedInput; import com.emc.mongoose.model.impl.item.BasicMutableDataItemFactory; import com.emc.mongoose.model.impl.item.BasicItemNameInput; import com.emc.mongoose.model.impl.item.NewDataItemInput; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.EOFException; import java.io.IOException; import java.nio.channels.ClosedByInterruptException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; public class BasicGenerator<I extends Item, O extends IoTask<I>> extends DaemonBase implements Generator<I, O>, Output<I> { private final static Logger LOG = LogManager.getLogger(); private final static int BATCH_SIZE = 0x1000; private final List<Driver<I, O>> drivers; private final AtomicReference<Monitor<I, O>> monitorRef = new AtomicReference<>(null); private final LoadType ioType; private final Input<I> itemInput; private final Thread worker; private final long countLimit; private final int maxItemQueueSize; private final boolean isShuffling = false; private final boolean isCircular; private final Throttle<I> rateThrottle; private final IoTaskFactory<I, O> ioTaskFactory; private final String dstContainer; private final String runId; private long producedItemsCount = 0; @Override public final void put(final I item) throws IOException { final O nextIoTask = ioTaskFactory.getInstance(ioType, item, dstContainer); final Driver<I, O> nextDriver = getNextDriver(); nextDriver.put(nextIoTask); } @Override public final int put(final List<I> buffer, final int from, final int to) throws IOException { if(to > from) { final List<O> ioTasks = new ArrayList<>(to - from); for(int i = from; i < to; i ++) { ioTasks.add(ioTaskFactory.getInstance(ioType, buffer.get(i), dstContainer)); } final Driver<I, O> nextDriver = getNextDriver(); nextDriver.put(ioTasks, 0, ioTasks.size()); } return to - from; } @Override public final int put(final List<I> buffer) throws IOException { final int n = buffer.size(); final List<O> ioTasks = new ArrayList<>(n); for(final I nextItem : buffer) { ioTasks.add(ioTaskFactory.getInstance(ioType, nextItem, dstContainer)); } final Driver<I, O> nextDriver = getNextDriver(); nextDriver.put(ioTasks, 0, n); return n; } @Override public final Input<I> getInput() throws IOException { return itemInput; } private final class GeneratorTask implements Runnable { private final Random rnd = new Random(); @Override public final void run() { if(itemInput == null) { LOG.debug(Markers.MSG, "No item source for the producing, exiting"); return; } int n = 0, m = 0; long remaining; try { List<I> buff; while(!isInterrupted()) { remaining = countLimit - producedItemsCount; if(remaining <= 0) { break; } try { buff = new ArrayList<>(BATCH_SIZE); n = itemInput.get(buff, BATCH_SIZE); if(n > remaining) { n = (int) remaining; } if(isShuffling) { Collections.shuffle(buff, rnd); } if(isInterrupted()) { break; } if(n > 0 && rateThrottle.requestContinueFor(null, n)) { for(m = 0; m < n && !isInterrupted(); ) { m += put(buff, m, n); } producedItemsCount += n; } else { if(isInterrupted()) { break; } } // CIRCULARITY FEATURE: // produce only <maxItemQueueSize> items in order to make it possible to // enqueue them infinitely if(isCircular && producedItemsCount >= maxItemQueueSize) { break; } } catch( final EOFException | InterruptedException | ClosedByInterruptException | IllegalStateException e ) { break; } catch(final IOException e) { LogUtil.exception( LOG, Level.DEBUG, e, "Failed to transfer the data items, count = {}, " + "batch size = {}, batch offset = {}", producedItemsCount, n, m ); } } } finally { LOG.debug( Markers.MSG, "{}: produced {} items from \"{}\" for the \"{}\"", Thread.currentThread().getName(), producedItemsCount, itemInput.toString(), this ); try { itemInput.close(); } catch(final IOException e) { LogUtil.exception( LOG, Level.WARN, e, "Failed to close the item source \"{}\"", itemInput.toString() ); } shutdown(); } } } public BasicGenerator( final String runId, final List<Driver<I, O>> drivers, final ItemFactory<I> itemFactory, final IoTaskFactory<I, O> ioTaskFactory, final ItemConfig itemConfig, final LoadConfig loadConfig ) throws UserShootHisFootException { this.runId = runId; this.drivers = drivers; final LimitConfig limitConfig = loadConfig.getLimitConfig(); try { final long l = limitConfig.getCount(); this.countLimit = l > 0 ? l : Long.MAX_VALUE; this.maxItemQueueSize = loadConfig.getQueueConfig().getSize(); this.isCircular = loadConfig.getCircular(); this.rateThrottle = new RateThrottle<>(limitConfig.getRate()); final String t = itemConfig.getOutputConfig().getContainer(); if(t == null || t.isEmpty()) { dstContainer = runId; } else { dstContainer = t; } final Input<String> pathInput = new RangePatternDefinedInput(dstContainer); final NamingConfig namingConfig = itemConfig.getNamingConfig(); final ItemNamingType namingType = ItemNamingType.valueOf(namingConfig.getType().toUpperCase()); final String namingPrefix = namingConfig.getPrefix(); final int namingLength = namingConfig.getLength(); final int namingRadix = namingConfig.getRadix(); final long namingOffset = namingConfig.getOffset(); final BasicItemNameInput namingInput = new BasicItemNameInput( namingType, namingPrefix, namingLength, namingRadix, namingOffset ); this.ioType = LoadType.valueOf(loadConfig.getType().toUpperCase()); switch(ioType) { case CREATE: // TODO copy mode if(itemFactory instanceof BasicMutableDataItemFactory) { this.itemInput = new NewDataItemInput( itemFactory, pathInput, namingInput, itemConfig.getDataConfig().getSize() ); } else { this.itemInput = null; // TODO } break; case READ: case UPDATE: case DELETE: final String itemInputFile = itemConfig.getInputConfig().getFile(); if(itemInputFile != null && !itemInputFile.isEmpty()) { this.itemInput = new CsvFileItemInput<>( Paths.get(itemInputFile), itemFactory ); } else { // TODO use container input this.itemInput = null; } break; default: throw new UserShootHisFootException(); } } catch(final Exception e) { throw new UserShootHisFootException(e); } this.ioTaskFactory = ioTaskFactory; worker = new Thread(new GeneratorTask(), "generator"); worker.setDaemon(true); } @Override public final void register(final Monitor<I, O> monitor) throws IllegalStateException { if(monitorRef.compareAndSet(null, monitor)) { for(final Driver<I, O> driver : drivers) { driver.register(monitor); } } else { throw new IllegalStateException("Generator is already used by another monitor"); } } private final AtomicLong rrc = new AtomicLong(0); protected Driver<I, O> getNextDriver() { return drivers.get((int) (rrc.incrementAndGet() % drivers.size())); } @Override protected void doStart() throws IllegalStateException { worker.start(); } @Override protected void doShutdown() { doInterrupt(); } @Override protected void doInterrupt() { worker.interrupt(); } @Override public boolean await(final long timeout, final TimeUnit timeUnit) throws InterruptedException { timeUnit.timedJoin(worker, timeout); return true; } @Override protected void doClose() throws IOException { if(itemInput != null) { itemInput.close(); } } }
package permafrost.tundra.data; import com.wm.data.IData; import com.wm.data.IDataCursor; import com.wm.data.IDataFactory; import com.wm.data.IDataUtil; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.representer.Represent; import permafrost.tundra.io.StreamHelper; import permafrost.tundra.lang.BytesHelper; import permafrost.tundra.lang.StringHelper; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.List; import java.util.Map; /** * Deserializes and serializes IData objects from and to YAML. */ public class IDataYAMLParser extends IDataTextParser { /** * Initialization on demand holder idiom. */ private static class Holder { /** * The singleton instance of the class. */ private static final IDataYAMLParser INSTANCE = new IDataYAMLParser(); } /** * Disallow instantiation of this class. */ private IDataYAMLParser() {} /** * Returns the singleton instance of this class. * @return The singleton instance of this class. */ public static IDataYAMLParser getInstance() { return Holder.INSTANCE; } /** * Serializes the given IData document as YAML to the given output stream. * * @param outputStream The stream to write the encoded IData to. * @param document The IData document to be encoded. * @param charset The character set to use. * @throws IOException If there is a problem writing to the stream. */ public void encode(OutputStream outputStream, IData document, Charset charset) throws IOException { StreamHelper.copy(StreamHelper.normalize(encodeToString(document), charset), outputStream); } /** * Returns an IData representation of the YAML data read from the given input stream. * * @param inputStream The input stream to be decoded. * @param charset The character set to use. * @return An IData representation of the given input stream data. * @throws IOException If there is a problem reading from the stream. */ public IData decode(InputStream inputStream, Charset charset) throws IOException { return decodeFromString(StringHelper.normalize(inputStream, charset)); } /** * The MIME media type for YAML. * * @return YAML MIME media type. */ public String getContentType() { return "application/yaml"; } /** * Returns an IData representation of the YAML data. * * @param string The String to be decoded. * @return An IData representation of the given data. * @throws IOException If an I/O problem occurs. */ @Override public IData decodeFromString(String string) throws IOException { Yaml yaml = new Yaml(); Object object = yaml.load(string); IData output = null; if (object instanceof Map) { output = IDataHelper.toIData((Map)object); } else if (object instanceof List) { IData[] array = IDataHelper.toIDataArray((List)object); output = IDataFactory.create(); IDataCursor cursor = output.getCursor(); IDataUtil.put(cursor, "recordWithNoID", array); cursor.destroy(); } return output; } /** * Returns a YAML representation of the given IData object. * * @param input The IData to convert to YAML. * @return The YAML representation of the IData. */ @Override public String encodeToString(IData input) throws IOException { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); Yaml yaml = new Yaml(new Representer(), options); IDataCursor cursor = input.getCursor(); IData[] array = IDataUtil.getIDataArray(cursor, "recordWithNoID"); cursor.destroy(); Object object = null; if (array != null) { object = IDataHelper.toList(array); } else { object = IDataHelper.toMap(input); } return yaml.dump(object); } /** * Tundra implementation of YAML Representer which supports InputStreams and * Objects with no public members. */ protected class Representer extends org.yaml.snakeyaml.representer.Representer { /** * Default constructor. */ public Representer() { this.multiRepresenters.put(ByteArrayInputStream.class, new RepresentInputStream()); this.representers.put(null, new RepresentObject()); } /** * Expose RepresentString implementation to this class by subclassing it. */ private class RepresentString extends org.yaml.snakeyaml.representer.Representer.RepresentString {} /** * Represent any Object as a YAML node, even those without public members. */ protected class RepresentObject extends RepresentJavaBean { /** * The Represent object used when encoding an Object with no public members. */ protected Represent defaultRepresent; /** * Default constructor. */ public RepresentObject() { defaultRepresent = new RepresentString(); } /** * Returns a YAML node representation of the given Object: if the Object * has public members, these are encoded to YAML, otherwise Object.toString() * is encoded to YAML. * @param data The Object to be converted to a YAML node. */ public Node representData(Object data) { Node node = null; try { node = super.representData(data); } catch(YAMLException ex) { node = defaultRepresent.representData(data); } return node; } } /** * Represent an InputStream as a YAML node. */ protected class RepresentInputStream extends RepresentByteArray { /** * Returns a YAML node representation of the given InputStream object. * @param data The InputStream to be converted to a YAML node. */ @SuppressWarnings("unchecked") public Node representData(Object data) { try { return super.representData(BytesHelper.normalize((InputStream) data)); } catch(IOException ex) { throw new YAMLException(ex); } } } } }
package ru.yandex.opentsdb.flume; import com.google.common.base.Throwables; import com.stumbleupon.async.Callback; import com.stumbleupon.async.Deferred; import com.yammer.metrics.core.Meter; import net.opentsdb.core.TSDB; import net.opentsdb.core.Tags; import net.opentsdb.core.WritableDataPoints; import org.apache.flume.Channel; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.EventDeliveryException; import org.apache.flume.Transaction; import org.apache.flume.conf.Configurable; import org.apache.flume.instrumentation.ChannelCounter; import org.apache.flume.instrumentation.SinkCounter; import org.apache.flume.sink.AbstractSink; import org.hbase.async.HBaseClient; import org.hbase.async.HBaseRpc; import org.hbase.async.PleaseThrottleException; import org.hbase.async.PutRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * Sink, capable to do writes into opentsdb. * This version expects full command in event body. * * @author Andrey Stepachev */ public class OpenTSDBSink2 extends AbstractSink implements Configurable { private final Logger logger = LoggerFactory.getLogger(OpenTSDBSink2.class); public static final Charset UTF8 = Charset.forName("UTF-8"); private SinkCounter sinkCounter; private ChannelCounter channelCounter; private int batchSize; private Semaphore statesPermitted; private TSDB tsdb; private HBaseClient hbaseClient; private String zkquorum; private String zkpath; private String seriesTable; private String uidsTable; private Meter pointsCounter; /** * State object holds result of asynchronous operations. * Implements throttle, when hbase can't handle incoming * rate of data points. * This object should be added as callback to handle throttles. */ private class State implements Callback<Object, Object> { volatile boolean throttle = false; volatile Exception failure; private long stime = System.currentTimeMillis(); private AtomicInteger inFlight = new AtomicInteger(0); private Semaphore signal = new Semaphore(0); private final Callback<Void, State> callback; private final int count; private State(List<EventData> data) throws Exception { this(data, null); } private State(List<EventData> data, Callback<Void, State> callback) throws Exception { this.callback = callback; this.count = data.size(); writeDataPoints(data); } public Object call(final Object arg) throws Exception { if (arg instanceof PleaseThrottleException) { final PleaseThrottleException e = (PleaseThrottleException) arg; logger.warn("Need to throttle, HBase isn't keeping up.", e); throttle = true; final HBaseRpc rpc = e.getFailedRpc(); if (rpc instanceof PutRequest) { hbaseClient.put((PutRequest) rpc); // Don't lose edits. } return null; } else if (arg instanceof Exception) { int now = inFlight.decrementAndGet(); logger.error("Failed event", arg); if (callback != null && now == 0) callback.call(this); failure = (Exception) arg; } else { pointsCounter.mark(); int now = inFlight.decrementAndGet(); if (callback != null && now == 0) callback.call(this); } return arg; } /** * Main entry method for adding points * * @param data points list */ private void writeDataPoints(List<EventData> data) throws Exception { if (data.size() < 1) return; inFlight.incrementAndGet(); // hack for not complete before we push all points try { for (EventData eventData : data) { } Set<String> failures = new HashSet<String>(); long prevTs = data.get(0).timestamp; for (EventData eventData : data) { try { if (eventData.timestamp == prevTs) continue; sinkCounter.incrementEventDrainAttemptCount(); prevTs = eventData.timestamp; final Deferred<Object> d = eventData.writePoint(tsdb); d.addBoth(this); if (throttle) throttle(d); inFlight.incrementAndGet(); sinkCounter.incrementEventDrainSuccessCount(); } catch (IllegalArgumentException ie) { failures.add(ie.getMessage()); } } if (failures.size() > 0) { logger.error("Points imported with " + failures.toString() + " IllegalArgumentExceptions"); } } finally { int total = inFlight.decrementAndGet(); if (total == 0 && callback != null) callback.call(this); } } /** * Helper method, implements throttle. * Sleeps, until throttle will be switch off * by successful operation. * * @param deferred */ private void throttle(Deferred deferred) { logger.info("Throttling..."); long throttle_time = System.nanoTime(); try { deferred.join(); } catch (Exception e) { throw new RuntimeException("Should never happen", e); } throttle_time = System.nanoTime() - throttle_time; if (throttle_time < 1000000000L) { logger.info("Got throttled for only " + throttle_time + "ns, sleeping a bit now"); try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException("interrupted", e); } } logger.info("Done throttling..."); throttle = false; } public int count() { return count; } } /** * Parsed event. */ private static class EventData { final String seriesKey; final String metric; final long timestamp; final String value; final HashMap<String, String> tags; public EventData(String seriesKey, String metric, long timestamp, String value, HashMap<String, String> tags) { this.seriesKey = seriesKey; this.metric = metric.replace('@', '_'); // FIXME: Workaround for opentsdb regarding the '@' symbol as invalid this.timestamp = timestamp; this.value = value; this.tags = tags; } public Deferred<Object> writePoint(TSDB tsdb) { Deferred<Object> d; if (Tags.looksLikeInteger(value)) { d = tsdb.addPoint(metric, timestamp, Tags.parseLong(value), tags); } else { // floating point value d = tsdb.addPoint(metric, timestamp, Float.parseFloat(value), tags); } return d; } public Deferred<Object> makeDeferred(WritableDataPoints dp) { Deferred<Object> d; if (Tags.looksLikeInteger(value)) { d = dp.addPoint(timestamp, Tags.parseLong(value)); } else { // floating point value d = dp.addPoint(timestamp, Float.parseFloat(value)); } return d; } static Comparator<EventData> orderBySeriesAndTimestamp() { return new Comparator<EventData>() { public int compare(EventData o1, EventData o2) { int c = o1.seriesKey.compareTo(o2.seriesKey); if (c == 0) return (o1.timestamp < o2.timestamp) ? -1 : (o1.timestamp == o2.timestamp ? 0 : 1); else return c; } }; } static Comparator<EventData> orderByTimestamp() { return new Comparator<EventData>() { public int compare(EventData o1, EventData o2) { return (o1.timestamp < o2.timestamp) ? -1 : (o1.timestamp == o2.timestamp ? 0 : 1); } }; } @Override public String toString() { return "EventData{" + "seriesKey='" + seriesKey + '\'' + ", metric='" + metric + '\'' + ", timestamp=" + timestamp + ", value='" + value + '\'' + ", tags=" + tags + '}'; } } /** * EventData 'constructor' * * @param event what to parse * @return constructed EventData */ private EventData parseEvent(final byte[] body) { final int idx = eventBodyStart(body); if (idx == -1) { logger.error("empty event"); return null; } final String[] words = Tags.splitString( new String(body, idx, body.length - idx, UTF8), ' '); final String metric = words[0]; if (metric.length() <= 0) { logger.error("invalid metric: " + metric); return null; } final long timestamp = Tags.parseLong(words[1]); if (timestamp <= 0) { logger.error("invalid metric: " + metric); return null; } final String value = words[2]; if (value.length() <= 0) { logger.error("invalid value: " + value); return null; } final String[] tagWords = Arrays.copyOfRange(words, 3, words.length); // keep them sorted, helps to identify tags in different order, but // same set of them Arrays.sort(tagWords); final HashMap<String, String> tags = new HashMap<String, String>(); StringBuilder seriesKey = new StringBuilder(metric); for (String tagWord : tagWords) { if (!tagWord.isEmpty()) { Tags.parse(tags, tagWord); seriesKey.append(' ').append(tagWord); } } return new EventData(seriesKey.toString(), metric, timestamp, value, tags); } /** * Process event, spawns up to 'parallel' number of executors, * and concurrently take transactions and send * to hbase. * * @return Status * @throws org.apache.flume.EventDeliveryException */ @Override public Status process() throws EventDeliveryException { final Channel channel = getChannel(); ArrayList<EventData> datas = new ArrayList<EventData>(batchSize); Transaction transaction = channel.getTransaction(); Event event; try { transaction.begin(); long stime = System.currentTimeMillis(); while ((event = channel.take()) != null && datas.size() < batchSize) { try { BatchEvent be = new BatchEvent(event.getBody()); for (byte[] body : be) { final EventData eventData = parseEvent(body); if (eventData == null) continue; datas.add(eventData); } } catch (Exception e) { continue; } } final int size = datas.size(); channelCounter.addToEventTakeSuccessCount(size); if (size == 1) { statesPermitted.acquire(); new State(datas, returnPermitCb()); } else if (size > 0) { stime = System.currentTimeMillis(); // sort incoming datapoints, tsdb doesn't like unordered Collections.sort(datas, EventData.orderBySeriesAndTimestamp()); // int start = 0; // String seriesKey = datas.get(0).seriesKey; // for (int end = 1; end < size; end++) { // if (!seriesKey.equals(datas.get(end).seriesKey)) { // statesPermitted.acquire(); // new State(datas.subList(start, end), returnPermitCb()); // start = end; statesPermitted.acquire(); new State(datas, returnPermitCb()); } if (size > 0) { sinkCounter.incrementBatchCompleteCount(); channelCounter.addToEventPutSuccessCount(size); } transaction.commit(); } catch (Throwable t) { logger.error("Batch failed: number of events " + datas.size(), t); transaction.rollback(); throw Throwables.propagate(t); } finally { transaction.close(); } return Status.READY; } private Callback<Void, State> returnPermitCb() { return new Callback<Void, State>() { @Override public Void call(State state) throws Exception { statesPermitted.release(); logger.info("Batch finished with " + state.count() + " events in " + (System.currentTimeMillis() - state.stime) + "ms"); return null; } }; } private byte[] PUT = {'p', 'u', 't'}; public int eventBodyStart(final byte[] body) { int idx = 0; for (byte b : PUT) { if (body[idx++] != b) return -1; } while (idx < body.length) { if (body[idx] != ' ') { return idx; } idx++; } return -1; } @Override public void configure(Context context) { sinkCounter = new SinkCounter(getName()); channelCounter = new ChannelCounter(getName()); batchSize = context.getInteger("batchSize", 100); zkquorum = context.getString("zkquorum"); zkpath = context.getString("zkpath", "/hbase"); seriesTable = context.getString("table.main", "tsdb"); uidsTable = context.getString("table.uids", "tsdb-uid"); statesPermitted = new Semaphore(context.getInteger("states", 50)); pointsCounter = Metrics.registry.newMeter(this.getClass(), "write", "points", TimeUnit.SECONDS); } @Override public synchronized void start() { logger.info(String.format("Starting: %s:%s series:%s uids:%s batchSize:%d", zkquorum, zkpath, seriesTable, uidsTable, batchSize)); hbaseClient = new HBaseClient(zkquorum, zkpath); tsdb = new TSDB(hbaseClient, seriesTable, uidsTable); channelCounter.start(); sinkCounter.start(); super.start(); } @Override public synchronized void stop() { if (tsdb != null) try { tsdb.shutdown().joinUninterruptibly(); tsdb = null; hbaseClient = null; } catch (Exception e) { logger.error("Can't shutdown tsdb", e); throw Throwables.propagate(e); } channelCounter.stop(); sinkCounter.stop(); super.stop(); } }
package seedu.tache.logic.commands; import seedu.tache.logic.commands.exceptions.CommandException; public class UndoCommand extends Command { public static final String COMMAND_WORD = "undo"; public static final String MESSAGE_USAGE = COMMAND_WORD + ":\n" + "Undoes the last change to the address book.\n\t" + "Example: " + COMMAND_WORD; public static final String MESSAGE_SUCCESS = "Undone: %s"; public static final String MESSAGE_EMPTY_HISTORY = "Nothing to undo!"; public static final String MESSAGE_FAILURE = "Failed to undo: %s"; @Override public CommandResult execute() { // TODO Auto-generated method stub if (undoHistory.isEmpty()) { return new CommandResult(MESSAGE_EMPTY_HISTORY); } else { Undoable lastCommand = undoHistory.pop(); assert lastCommand.isUndoable() : "The popped command can't be undone!"; try { String undoResult = lastCommand.undo(); return new CommandResult(String.format(MESSAGE_SUCCESS, undoResult)); } catch (CommandException e) { return new CommandResult(String.format(MESSAGE_FAILURE, e.getMessage())); } } } }
package com.cmput301.cs.project.activities; import android.app.ActionBar; import android.app.DialogFragment; import android.app.FragmentTransaction; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.cmput301.cs.project.App; import com.cmput301.cs.project.R; import com.cmput301.cs.project.adapters.ClaimsApproverAdapter; import com.cmput301.cs.project.adapters.ClaimsClaimantAdapter; import com.cmput301.cs.project.controllers.ClaimListController; import com.cmput301.cs.project.controllers.TagsChangedListener; import com.cmput301.cs.project.controllers.TagsManager; import com.cmput301.cs.project.dialogs.TagSelectorDialogFragment; import com.cmput301.cs.project.listeners.TagSelectorListener; import com.cmput301.cs.project.models.Claim; import com.cmput301.cs.project.models.ClaimsList; import com.cmput301.cs.project.models.Tag; import com.cmput301.cs.project.models.User; import java.util.ArrayList; /** * Is the activity that launches at start of app. <p> * An activity that shows a list of {@link com.cmput301.cs.project.models.Claim Claims}. <p> * Redirects to {@link com.cmput301.cs.project.activities.LoginActivity LoginActivity} if no user is found. * Has menu buttons that allow the creation of new claims via {@link com.cmput301.cs.project.activities.EditClaimActivity EditClaimActivity} * and for the {@link com.cmput301.cs.project.activities.TagManagerActivity TagManagerActivity}. <p> * If a claim item is clicked {@link com.cmput301.cs.project.activities.ClaimViewActivity ClaimViewActivity} is called for that claim. <p> * Finally there are tabs at the top of the activity that allow the user to switch between approver and claimant. Claimant shows only claims * for the current user and Approver shows a list of the claims for every user EXCEPT the current user. * <p/> * If a tag is renamed or deleted the onTagRename and onTagResume methods, respectively, will reload the list of claims. * * @author rozsa * @author jbenson */ public class ClaimListActivity extends ListActivity implements TagsChangedListener, TagSelectorListener { private static final int POSITION_CLAIMANT = 0; private static final int POSITION_APPROVER = 1; private static final int NEW_CLAIM = 0; private static final int VIEW_CLAIM = 1; private ArrayList<Tag> mWantedTags; private ClaimListController mClaimListController; private ClaimsApproverAdapter mApproverAdapter; private ClaimsClaimantAdapter mClaimantAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.claim_list_activity); User user = App.get(this).getUser(); if (user == null) { startActivity(new Intent(this, LoginActivity.class)); finish(); } mWantedTags = new ArrayList<Tag>(); mClaimListController = new ClaimListController(user, ClaimsList.getInstance(this)); setupListView(); setupActionBar(); TagsManager.get(this).addTagChangedListener(mClaimListController); } @Override public void onResume() { super.onResume(); setupListView(); } @Override protected void onDestroy() { super.onDestroy(); TagsManager.get(this).removeTagChangedListener(mClaimListController); } private void setupListView() { mApproverAdapter = new ClaimsApproverAdapter(this, mClaimListController.getApprovableClaims()); mClaimantAdapter = new ClaimsClaimantAdapter(this, mClaimListController.getClaimantClaims()); mClaimantAdapter.updateFilter(mWantedTags); mClaimantAdapter.sort(Claim.START_ASCENDING); mApproverAdapter.sort(Claim.START_DESCENDING); if (showClaimantList()) { setListAdapter(mClaimantAdapter); } else { setListAdapter(mApproverAdapter); } } private boolean showClaimantList() { final ActionBar actionBar = getActionBar(); return actionBar == null || actionBar.getSelectedTab() == null || actionBar.getSelectedTab().getPosition() == POSITION_CLAIMANT; } @Override public void onListItemClick(ListView lv, View v, int position, long id) { ArrayAdapter<Claim> adapter = (ArrayAdapter<Claim>) getListAdapter(); Intent i = new Intent(this, ClaimViewActivity.class); i.putExtra(App.KEY_CLAIM, adapter.getItem(position)); startActivityForResult(i, VIEW_CLAIM); } private void setupActionBar() { final ActionBar actionBar = getActionBar(); if (actionBar != null) { final ActionBar.TabListener listener = new ActionBar.TabListener() { @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { final int position = tab.getPosition(); switch (position) { case POSITION_CLAIMANT: setListAdapter(mClaimantAdapter); break; case POSITION_APPROVER: setListAdapter(mApproverAdapter); break; default: throw new AssertionError("unexpected position: " + position); } } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { // do nothing } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { // do nothing } }; actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.addTab(actionBar.newTab() .setText(R.string.claimant) .setTabListener(listener)); actionBar.addTab(actionBar.newTab() .setText(R.string.approver) .setTabListener(listener)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.claim_list_activity, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.tagManager: startActivity(new Intent(this, TagManagerActivity.class)); return true; case R.id.add: startActivityForResult(new Intent(this, EditClaimActivity.class), NEW_CLAIM); return true; case R.id.filter: startTagSelector(); return true; case R.id.action_settings: startActivity(new Intent(this, SettingsActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } private void startTagSelector() { ArrayList<Tag> allTags = new ArrayList<Tag>(TagsManager.get(this).peekTags()); if (allTags.size() > 0) { DialogFragment fragment = TagSelectorDialogFragment.newInstance(allTags, mWantedTags); fragment.show(getFragmentManager(), "dialog"); } else { Toast.makeText(this, "There are no tags to filter", Toast.LENGTH_LONG).show(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == NEW_CLAIM) { if (resultCode == RESULT_OK) { Claim claim = data.getExtras().getParcelable(App.KEY_CLAIM); mClaimListController.addClaim(claim); mClaimantAdapter = new ClaimsClaimantAdapter(this, mClaimListController.getClaimantClaims()); setListAdapter(mClaimantAdapter); } } else if (requestCode == VIEW_CLAIM) { mClaimantAdapter = new ClaimsClaimantAdapter(this, mClaimListController.getClaimantClaims()); setListAdapter(mClaimantAdapter); } } @Override public void onTagRenamed(Tag tag, Tag oldName) { setupListView(); if (mWantedTags.contains(oldName)) { mWantedTags.remove(tag); mWantedTags.add(tag); mClaimantAdapter.updateFilter(mWantedTags); } } @Override public void onTagDeleted(Tag tag) { setupListView(); if (mWantedTags.contains(tag)) { mWantedTags.remove(tag); mClaimantAdapter.updateFilter(mWantedTags); } } @Override public void onTagCreated(Tag tag) { // do nothing } @Override public void wantedTagsChanged(ArrayList<Tag> newWantedTags) { mWantedTags = newWantedTags; mClaimantAdapter.updateFilter(mWantedTags); } }
package com.jwetherell.algorithms.data_structures; public class SuffixTrie<C extends CharSequence> extends Trie<C> { @SuppressWarnings("unchecked") public SuffixTrie(String string) { root = new Node<C>(null); int length = string.length(); for (int i=0; i<length; i++) { CharSequence seq = string.substring(i, length); super.add((C)seq); } } @Override public boolean add(C key) { //Ignore public calls to add. The class should be immutable. return false; } }
package uk.co.jemos.podam.api; import net.jcip.annotations.Immutable; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.jemos.podam.common.*; import uk.co.jemos.podam.exceptions.PodamMockeryException; import java.lang.annotation.Annotation; import java.lang.reflect.*; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import javax.validation.Constraint; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.ws.Holder; /** * The PODAM factory implementation * * @author mtedone * * @since 1.0.0 * */ @ThreadSafe @Immutable public class PodamFactoryImpl implements PodamFactory { private static final String RESOLVING_COLLECTION_EXCEPTION_STR = "An exception occurred while resolving the collection"; private static final String MAP_CREATION_EXCEPTION_STR = "An exception occurred while creating a Map object"; private static final String UNCHECKED_STR = "unchecked"; private static final String THE_ANNOTATION_VALUE_STR = "The annotation value: "; private static final Type[] NO_TYPES = new Type[0]; private static final Object[] NO_ARGS = new Object[0]; private static final Object OBJECT = new Object(); /** Application logger */ private static final Logger LOG = LoggerFactory .getLogger(PodamFactoryImpl.class.getName()); /** * External factory to delegate production this factory cannot handle * <p> * The default is {@link NullExternalFactory}. * </p> */ private PodamFactory externalFactory = NullExternalFactory.getInstance(); /** * The strategy to use to fill data. * <p> * The default is {@link RandomDataProviderStrategy}. * </p> */ private DataProviderStrategy strategy = RandomDataProviderStrategy.getInstance(); /** * The strategy to use to introspect data. * <p> * The default is {@link DefaultClassInfoStrategy}. * </p> */ private ClassInfoStrategy classInfoStrategy = DefaultClassInfoStrategy.getInstance(); /** * Default constructor. */ public PodamFactoryImpl() { this(NullExternalFactory.getInstance(), RandomDataProviderStrategy.getInstance()); } /** * Constructor with non-default strategy * * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(DataProviderStrategy strategy) { this(NullExternalFactory.getInstance(), strategy); } /** * Constructor with non-default external factory * * @param externalFactory * External factory to delegate production this factory cannot * handle */ public PodamFactoryImpl(PodamFactory externalFactory) { this(externalFactory, RandomDataProviderStrategy.getInstance()); } /** * Full constructor. * * @param externalFactory * External factory to delegate production this factory cannot * handle * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(PodamFactory externalFactory, DataProviderStrategy strategy) { this.externalFactory = externalFactory; this.strategy = strategy; } /** * {@inheritDoc} */ @Override public <T> T manufacturePojoWithFullData(Class<T> pojoClass, Type... genericTypeArgs) { ConstructorAdaptiveComparator constructorComparator = findConstructorComparator(); constructorComparator.addHeavyClass(pojoClass); T retValue = this.manufacturePojo(pojoClass, genericTypeArgs); constructorComparator.removeHeavyClass(pojoClass); return retValue; } /** * {@inheritDoc} */ @Override public <T> T manufacturePojo(Class<T> pojoClass, Type... genericTypeArgs) { Map<Class<?>, Integer> pojos = new HashMap<Class<?>, Integer>(); pojos.put(pojoClass, 0); try { Class<?> declaringClass = null; AttributeMetadata pojoMetadata = new AttributeMetadata(pojoClass, genericTypeArgs, declaringClass); return this.manufacturePojoInternal(pojoClass, pojoMetadata, pojos, genericTypeArgs); } catch (InstantiationException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (InvocationTargetException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(e.getMessage(), e); } } /** * {@inheritDoc} */ @Override public <T> T populatePojo(T pojo, Type... genericTypeArgs) { Map<Class<?>, Integer> pojos = new HashMap<Class<?>, Integer>(); pojos.put(pojo.getClass(), 0); try { return this.populatePojoInternal(pojo, pojos, genericTypeArgs); } catch (InstantiationException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (InvocationTargetException e) { throw new PodamMockeryException(e.getMessage(), e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(e.getMessage(), e); } } /** * {@inheritDoc} */ @Override public DataProviderStrategy getStrategy() { return strategy; } /** * {@inheritDoc} */ @Override public PodamFactory setStrategy(DataProviderStrategy strategy) { this.strategy = strategy; return this; } /** * {@inheritDoc} */ @Override public ClassInfoStrategy getClassStrategy() { return classInfoStrategy; } /** * {@inheritDoc} */ @Override public PodamFactory setClassStrategy(ClassInfoStrategy classInfoStrategy) { this.classInfoStrategy = classInfoStrategy; return this; } /** * {@inheritDoc} */ @Override public PodamFactory getExternalFactory() { return externalFactory; } /** * {@inheritDoc} */ @Override public PodamFactory setExternalFactory(PodamFactory externalFactory) { this.externalFactory = externalFactory; return this; } private Type[] fillTypeArgMap(final Map<String, Type> typeArgsMap, final Class<?> pojoClass, final Type[] genericTypeArgs) { TypeVariable<?>[] array = pojoClass.getTypeParameters(); List<TypeVariable<?>> typeParameters = new ArrayList<TypeVariable<?>>(Arrays.asList(array)); Iterator<TypeVariable<?>> iterator = typeParameters.iterator(); /* Removing types, which are already in typeArgsMap */ while (iterator.hasNext()) { if (typeArgsMap.containsKey(iterator.next().getName())) { iterator.remove(); } } if (typeParameters.size() > genericTypeArgs.length) { String msg = pojoClass.getCanonicalName() + " is missing generic type arguments, expected " + typeParameters + " found " + Arrays.toString(genericTypeArgs); throw new IllegalStateException(msg); } int i; for (i = 0; i < typeParameters.size(); i++) { typeArgsMap.put(typeParameters.get(i).getName(), genericTypeArgs[i]); } Type[] genericTypeArgsExtra; if (typeParameters.size() < genericTypeArgs.length) { genericTypeArgsExtra = Arrays.copyOfRange(genericTypeArgs, i, genericTypeArgs.length); } else { genericTypeArgsExtra = null; } /* Adding types, which were specified during inheritance */ Class<?> clazz = pojoClass; while (clazz != null) { Type superType = clazz.getGenericSuperclass(); clazz = clazz.getSuperclass(); if (superType instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) superType; Type[] actualParamTypes = paramType.getActualTypeArguments(); TypeVariable<?>[] paramTypes = clazz.getTypeParameters(); for (i = 0; i < actualParamTypes.length && i < paramTypes.length; i++) { if (actualParamTypes[i] instanceof Class) { typeArgsMap.put(paramTypes[i].getName(), actualParamTypes[i]); } } } } return genericTypeArgsExtra; } private Object instantiatePojoWithoutConstructors( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); // If no publicly accessible constructors are available, // the best we can do is to find a constructor (e.g. // getInstance()) Method[] declaredMethods = pojoClass.getDeclaredMethods(); strategy.sort(declaredMethods); // A candidate factory method is a method which returns the // Class type // The parameters to pass to the method invocation Object[] parameterValues = null; for (Method candidateConstructor : declaredMethods) { if (!Modifier.isStatic(candidateConstructor.getModifiers()) || !candidateConstructor.getReturnType().equals(pojoClass) || retValue != null) { continue; } Class<?>[] parameterTypes = candidateConstructor.getParameterTypes(); if (parameterTypes.length == 0) { parameterValues = NO_ARGS; } else { // This is a factory method with arguments parameterValues = new Object[candidateConstructor .getParameterTypes().length]; Annotation[][] parameterAnnotations = candidateConstructor .getParameterAnnotations(); int idx = 0; for (Class<?> parameterType : parameterTypes) { List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); Type genericType = candidateConstructor.getGenericParameterTypes()[idx]; parameterValues[idx] = manufactureParameterValue(parameterType, genericType, annotations, typeArgsMap, pojos, genericTypeArgsExtra == null ? NO_TYPES : genericTypeArgsExtra); idx++; } } try { retValue = candidateConstructor.invoke(pojoClass, parameterValues); LOG.debug("Could create an instance using " + candidateConstructor); } catch (Exception t) { LOG.debug( "PODAM could not create an instance for constructor: " + candidateConstructor + ". Will try another one...", t); } } if (retValue == null) { LOG.debug("For class {} PODAM could not possibly create" + " a value statically. Will try other means.", pojoClass); } return retValue; } /** * It resolves generic parameter type * * * @param paramType * The generic parameter type * @param typeArgsMap * A map of resolved types * @param methodGenericTypeArgs * Return value posible generic types of the generic parameter * type * @return value for class representing the generic parameter type */ private Class<?> resolveGenericParameter(Type paramType, Map<String, Type> typeArgsMap, AtomicReference<Type[]> methodGenericTypeArgs) { Class<?> parameterType = null; methodGenericTypeArgs.set(NO_TYPES); if (paramType instanceof TypeVariable<?>) { final TypeVariable<?> typeVariable = (TypeVariable<?>) paramType; final Type type = typeArgsMap.get(typeVariable.getName()); if (type != null) { parameterType = resolveGenericParameter(type, typeArgsMap, methodGenericTypeArgs); } } else if (paramType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) paramType; parameterType = (Class<?>) pType.getRawType(); methodGenericTypeArgs.set(pType.getActualTypeArguments()); } else if (paramType instanceof WildcardType) { WildcardType wType = (WildcardType) paramType; Type[] bounds = wType.getLowerBounds(); String msg; if (bounds != null && bounds.length > 0) { msg = "Lower bounds:"; } else { bounds = wType.getUpperBounds(); msg = "Upper bounds:"; } if (bounds != null && bounds.length > 0) { LOG.debug(msg + Arrays.toString(bounds)); parameterType = resolveGenericParameter(bounds[0], typeArgsMap, methodGenericTypeArgs); } } else if (paramType instanceof Class) { parameterType = (Class<?>) paramType; } if (parameterType == null) { LOG.warn("Unrecognized type {}. Will use Object instead", paramType); parameterType = Object.class; } return parameterType; } /** * It returns the boolean value indicated in the annotation. * * @param annotations * The collection of annotations for the annotated attribute * @param attributeMetadata * The attribute's metadata, if any, used for customisation * @return The boolean value indicated in the annotation */ private Boolean getBooleanValueForAnnotation(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Boolean retValue = null; for (Annotation annotation : annotations) { if (PodamBooleanValue.class.isAssignableFrom(annotation.getClass())) { PodamBooleanValue localStrategy = (PodamBooleanValue) annotation; retValue = localStrategy.boolValue(); break; } } if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } return retValue; } private Byte getByteValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Byte retValue = null; for (Annotation annotation : annotations) { if (PodamByteValue.class.isAssignableFrom(annotation.getClass())) { PodamByteValue intStrategy = (PodamByteValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Byte.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a byte type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { byte minValue = intStrategy.minValue(); byte maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getByteInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } return retValue; } private Short getShortValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Short retValue = null; for (Annotation annotation : annotations) { if (PodamShortValue.class.isAssignableFrom(annotation.getClass())) { PodamShortValue shortStrategy = (PodamShortValue) annotation; String numValueStr = shortStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Short.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a short type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { short minValue = shortStrategy.minValue(); short maxValue = shortStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getShortInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } return retValue; } /** * It creates and returns a random {@link Character} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * @return A random {@link Character} value */ private Character getCharacterValueWithinRange( List<Annotation> annotations, AttributeMetadata attributeMetadata) { Character retValue = null; for (Annotation annotation : annotations) { if (PodamCharValue.class.isAssignableFrom(annotation.getClass())) { PodamCharValue annotationStrategy = (PodamCharValue) annotation; char charValue = annotationStrategy.charValue(); if (charValue != ' ') { retValue = charValue; } else { char minValue = annotationStrategy.minValue(); char maxValue = annotationStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getCharacterInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } return retValue; } private Integer getIntegerValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Integer retValue = null; for (Annotation annotation : annotations) { if (PodamIntValue.class.isAssignableFrom(annotation.getClass())) { PodamIntValue intStrategy = (PodamIntValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Integer.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to an Integer. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { int minValue = intStrategy.minValue(); int maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getIntegerInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } return retValue; } private Float getFloatValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Float retValue = null; for (Annotation annotation : annotations) { if (PodamFloatValue.class.isAssignableFrom(annotation.getClass())) { PodamFloatValue floatStrategy = (PodamFloatValue) annotation; String numValueStr = floatStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Float.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Float. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { float minValue = floatStrategy.minValue(); float maxValue = floatStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getFloatInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } return retValue; } /** * It creates and returns a random {@link Double} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * * @return a random {@link Double} value */ private Double getDoubleValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Double retValue = null; for (Annotation annotation : annotations) { if (PodamDoubleValue.class.isAssignableFrom(annotation.getClass())) { PodamDoubleValue doubleStrategy = (PodamDoubleValue) annotation; String numValueStr = doubleStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Double.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Double. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { double minValue = doubleStrategy.minValue(); double maxValue = doubleStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getDoubleInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } return retValue; } private Long getLongValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Long retValue = null; for (Annotation annotation : annotations) { if (PodamLongValue.class.isAssignableFrom(annotation.getClass())) { PodamLongValue longStrategy = (PodamLongValue) annotation; String numValueStr = longStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Long.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Long. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { long minValue = longStrategy.minValue(); long maxValue = longStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getLongInRange(minValue, maxValue, attributeMetadata); } break; } } if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } return retValue; } /** * It attempts to resolve the given class as a wrapper class and if this is * the case it assigns a random value * * * @param boxedType * The class which might be a wrapper class * @param annotations * The attribute's annotations, if any, used for customisation * @param attributeMetadata * The attribute's metadata, if any, used for customisation * @return {@code null} if this is not a wrapper class, otherwise an Object * with the value for the wrapper class */ private Object resolveBoxedValue(Class<?> boxedType, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (boxedType.equals(Integer.class) || boxedType.equals(int.class)) { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Long.class) || boxedType.equals(long.class)) { retValue = getLongValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Float.class) || boxedType.equals(float.class)) { retValue = getFloatValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Double.class) || boxedType.equals(double.class)) { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Boolean.class) || boxedType.equals(boolean.class)) { retValue = getBooleanValueForAnnotation(annotations, attributeMetadata); } else if (boxedType.equals(Byte.class) || boxedType.equals(byte.class)) { retValue = getByteValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Short.class) || boxedType.equals(short.class)) { retValue = getShortValueWithinRange(annotations, attributeMetadata); } else if (boxedType.equals(Character.class) || boxedType.equals(char.class)) { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); } else { throw new IllegalArgumentException( String.format("%s is unsupported wrapper type", boxedType)); } return retValue; } /** * It creates and returns an instance of the given class if at least one of * its constructors has been annotated with {@link PodamConstructor} * * @param <T> * The type of the instance to return * * @param pojoClass * The class of which an instance is required * @param pojos * How many instances of the same class have been created so far * @param genericTypeArgs * The generic type arguments for the current generic class * instance * @return an instance of the given class if at least one of its * constructors has been annotated with {@link PodamConstructor} * @throws SecurityException * If an security was violated */ @SuppressWarnings({ UNCHECKED_STR }) private <T> T instantiatePojo(Class<T> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws SecurityException { T retValue = null; Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors.length == 0 || Modifier.isAbstract(pojoClass.getModifiers())) { /* No public constructors, we will try static factory methods */ try { retValue = (T) instantiatePojoWithoutConstructors( pojoClass, pojos, genericTypeArgs); } catch (Exception e) { LOG.debug("We couldn't create an instance for pojo: " + pojoClass + " with factory methods, will " + " try non-public constructors.", e); } /* Then non-public constructors */ if (retValue == null) { constructors = pojoClass.getDeclaredConstructors(); } } if (retValue == null && constructors.length > 0) { /* We want constructor with minumum number of parameters * to speed up the creation */ strategy.sort(constructors); for (Constructor<?> constructor : constructors) { try { Object[] parameterValues = getParameterValuesForConstructor( constructor, pojoClass, pojos, genericTypeArgs); // Being a generic method we cannot be sure on the identity of // T, therefore the mismatch between the newInstance() return // value (Object) and T is acceptable, thus the SuppressWarning // annotation // Security hack if (!constructor.isAccessible()) { constructor.setAccessible(true); } retValue = (T) constructor.newInstance(parameterValues); if (retValue != null) { LOG.debug("We could create an instance with constructor: " + constructor); break; } } catch (Exception e) { LOG.debug("We couldn't create an instance for pojo: {} with" + " constructor: {}. Will try with another one.", pojoClass, constructor, e); } } } if (retValue == null) { LOG.debug("For class {} PODAM could not possibly create" + " a value. Will try other means.", pojoClass); } return retValue; } @SuppressWarnings(UNCHECKED_STR) private <T> T manufacturePojoInternal(Class<T> pojoClass, AttributeMetadata pojoMetadata, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { LOG.debug("Manufacturing {} with parameters {}", pojoClass, Arrays.toString(genericTypeArgs)); T retValue = null; // reuse object from memoization table T objectToReuse = (T) strategy.getMemoizedObject(pojoMetadata); if (objectToReuse != null) { LOG.debug("Fetched memoized object for {}", pojoClass); return objectToReuse; } if (pojoClass.isEnum()) { int enumConstantsLength = pojoClass.getEnumConstants().length; if (enumConstantsLength > 0) { int enumIndex = strategy.getIntegerInRange(0, enumConstantsLength - 1, new AttributeMetadata(pojoClass, genericTypeArgs, pojoClass)); return pojoClass.getEnumConstants()[enumIndex]; } } if (pojoClass.isPrimitive()) { // For JDK POJOs we can't retrieve attribute name return (T) resolveBoxedValue(pojoClass, Collections.<Annotation>emptyList(), new AttributeMetadata(pojoClass, genericTypeArgs, pojoClass)); } if (pojoClass.isInterface()) { Class<T> specificClass = (Class<T>) strategy .getSpecificClass(pojoClass); if (!specificClass.equals(pojoClass)) { return this.manufacturePojoInternal(specificClass, pojoMetadata, pojos, genericTypeArgs); } else { return resortToExternalFactory( "{} is an interface. Resorting to {} external factory", pojoClass, genericTypeArgs); } } try { retValue = instantiatePojo(pojoClass, pojos, genericTypeArgs); } catch (SecurityException e) { throw new PodamMockeryException( "Security exception while applying introspection.", e); } if (retValue == null) { if (Modifier.isAbstract(pojoClass.getModifiers())) { Class<T> specificClass = (Class<T>) strategy .getSpecificClass(pojoClass); if (!specificClass.equals(pojoClass)) { return this.manufacturePojoInternal(specificClass, pojoMetadata, pojos, genericTypeArgs); } } return resortToExternalFactory( "Failed to manufacture {}. Resorting to {} external factory", pojoClass, genericTypeArgs); } // update memoization cache with new object // the reference is stored before properties are set so that recursive // properties can use it strategy.cacheMemoizedObject(pojoMetadata, retValue); if (retValue != null) { populatePojoInternal(retValue, pojos, genericTypeArgs); } return retValue; } @SuppressWarnings(UNCHECKED_STR) private <T> T populatePojoInternal(T pojo, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> pojoClass = pojo.getClass(); if (pojo instanceof Collection && ((Collection<?>)pojo).size() == 0) { fillCollection((Collection<? super Object>)pojo, pojos, genericTypeArgs); } else if (pojo instanceof Map && ((Map<?,?>)pojo).size() == 0) { fillMap((Map<? super Object,? super Object>)pojo, pojos, genericTypeArgs); } Class<?>[] parameterTypes = null; Class<?> attributeType = null; ClassInfo classInfo = classInfoStrategy.getClassInfo(pojo.getClass()); final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Set<ClassAttribute> classAttributes = classInfo.getClassAttributes(); // According to JavaBeans standards, setters should have only // one argument Object setterArg = null; Iterator<ClassAttribute> iter = classAttributes.iterator(); while (iter.hasNext()) { ClassAttribute attribute = iter.next(); Set<Method> setters = attribute.getSetters(); if (setters.isEmpty()) { if (attribute.getGetters().isEmpty()) { iter.remove(); } continue; } else { iter.remove(); } /* We want to find setter defined the latest */ Method setter = null; for (Method current : setters) { if (setter == null || setter.getDeclaringClass().isAssignableFrom(current.getDeclaringClass())) { setter = current; } } parameterTypes = setter.getParameterTypes(); if (parameterTypes.length != 1) { LOG.warn("Skipping setter with non-single arguments {}", setter); continue; } // A class which has got an attribute to itself (e.g. // recursive hierarchies) attributeType = parameterTypes[0]; // If an attribute has been annotated with // PodamAttributeStrategy, it takes the precedence over any // other strategy. Additionally we don't pass the attribute // metadata for value customisation; if user went to the extent // of specifying a PodamAttributeStrategy annotation for an // attribute they are already customising the value assigned to // that attribute. String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); List<Annotation> pojoAttributeAnnotations = PodamUtils.getAttributeAnnotations( attribute.getAttribute(), setter); AttributeStrategy<?> attributeStrategy = findAttributeStrategy(pojoAttributeAnnotations, attributeType); if (null != attributeStrategy) { LOG.debug("The attribute: " + attributeName + " will be filled using the following strategy: " + attributeStrategy); setterArg = returnAttributeDataStrategyValue(attributeType, attributeStrategy); } else { if (typeArgsMap.isEmpty()) { Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } } Type[] typeArguments = NO_TYPES; // If the parameter is a generic parameterized type resolve // the actual type arguments if (setter.getGenericParameterTypes()[0] instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) setter .getGenericParameterTypes()[0]; typeArguments = attributeParameterizedType .getActualTypeArguments(); } else if (setter.getGenericParameterTypes()[0] instanceof TypeVariable) { final TypeVariable<?> typeVariable = (TypeVariable<?>) setter .getGenericParameterTypes()[0]; Type type = typeArgsMap.get(typeVariable.getName()); if (type instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) type; typeArguments = attributeParameterizedType .getActualTypeArguments(); attributeType = (Class<?>) attributeParameterizedType .getRawType(); } else { attributeType = (Class<?>) type; } } AtomicReference<Type[]> typeGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); for (int i = 0; i < typeArguments.length; i++) { if (typeArguments[i] instanceof TypeVariable) { Class<?> resolvedType = resolveGenericParameter(typeArguments[i], typeArgsMap, typeGenericTypeArgs); if (!Collection.class.isAssignableFrom(resolvedType) && !Map.class.isAssignableFrom(resolvedType)) { typeArguments[i] = resolvedType; } } } setterArg = manufactureAttributeValue(pojo, pojos, attributeType, setter.getGenericParameterTypes()[0], pojoAttributeAnnotations, attributeName, typeArgsMap, typeArguments); } try { setter.invoke(pojo, setterArg); } catch(IllegalAccessException e) { LOG.warn("{} is not accessible. Setting it to accessible." + " However this is a security hack and your code" + " should really adhere to JavaBeans standards.", setter.toString()); setter.setAccessible(true); setter.invoke(pojo, setterArg); } } for (ClassAttribute readOnlyAttribute : classAttributes) { Method getter = readOnlyAttribute.getGetters().iterator().next(); if (getter != null && !getter.getReturnType().isPrimitive()) { if (getter.getGenericParameterTypes().length == 0) { Object fieldValue = null; try { fieldValue = getter.invoke(pojo, NO_ARGS); } catch(Exception e) { LOG.debug("Cannot access {}, skipping", getter); } if (fieldValue != null) { LOG.debug("Populating read-only field {}", getter); Type[] genericTypeArgsAll; if (getter.getGenericReturnType() instanceof ParameterizedType) { if (typeArgsMap.isEmpty()) { Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } } ParameterizedType paramType = (ParameterizedType) getter.getGenericReturnType(); Type[] actualTypes = paramType.getActualTypeArguments(); genericTypeArgsAll = mergeActualAndSuppliedGenericTypes( actualTypes, genericTypeArgs, typeArgsMap); } else { genericTypeArgsAll = genericTypeArgs; } if (getter.getReturnType().getTypeParameters().length > genericTypeArgsAll.length) { Type[] missing = new Type[ getter.getReturnType().getTypeParameters().length - genericTypeArgsAll.length]; for (int i = 0; i < missing.length; i++) { missing[i] = Object.class; } LOG.warn("Missing type parameters, appended {}", Arrays.toString(missing)); genericTypeArgsAll = mergeTypeArrays(genericTypeArgsAll, missing); } Class<?> fieldClass = fieldValue.getClass(); Integer depth = pojos.get(fieldClass); if (depth == null) { depth = -1; } if (depth <= strategy.getMaxDepth(fieldClass)) { pojos.put(fieldClass, depth + 1); populatePojoInternal(fieldValue, pojos, genericTypeArgsAll); pojos.put(fieldClass, depth); } else { LOG.warn("Loop in filling read-only field {} detected.", getter); } } } else { LOG.warn("Skipping invalid getter {}", getter); } } } // It executes any extra methods Collection<Method> extraMethods = classInfoStrategy.getExtraMethods(pojoClass); if (null != extraMethods) { for (Method extraMethod : extraMethods) { Class<?>[] argTypes = extraMethod.getParameterTypes(); Type[] genericTypes = extraMethod.getGenericParameterTypes(); Annotation[][] annotations = extraMethod.getParameterAnnotations(); Object[] args = new Object[argTypes.length]; for (int i = 0; i < argTypes.length; i++) { List<Annotation> paramAnnotations = Arrays.asList(annotations[i]); args[i] = manufactureParameterValue(pojos, argTypes[i], genericTypes[i], paramAnnotations, typeArgsMap, genericTypeArgs); } extraMethod.invoke(pojo, args); } } return pojo; } private Object manufactureParameterValue(Map<Class<?>, Integer> pojos, Class<?> parameterType, Type genericType, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { String attributeName = null; return manufactureAttributeValue(OBJECT, pojos, parameterType, genericType, annotations, attributeName, typeArgsMap, genericTypeArgs); } private Object manufactureAttributeValue(Object pojo, Map<Class<?>, Integer> pojos, Class<?> attributeType, Type genericAttributeType, List<Annotation> annotations, String attributeName, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object attributeValue = null; Class<?> realAttributeType; if (Object.class.equals(attributeType) && attributeType != genericAttributeType) { AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); realAttributeType = resolveGenericParameter(genericAttributeType, typeArgsMap, elementGenericTypeArgs); } else { realAttributeType = attributeType; } AttributeMetadata attributeMetadata = new AttributeMetadata( attributeName, realAttributeType, genericTypeArgs, annotations, pojo.getClass()); // Primitive type if (realAttributeType.isPrimitive() || isWrapper(realAttributeType)) { attributeValue = resolveBoxedValue(realAttributeType, annotations, attributeMetadata); // String type } else if (realAttributeType.equals(String.class)) { attributeValue = resolveStringValue(annotations, attributeMetadata); } else if (realAttributeType.isArray()) { // Array type attributeValue = resolveArrayElementValue(realAttributeType, genericAttributeType, attributeName, pojos, annotations, pojo, typeArgsMap); // Otherwise it's a different type of Object (including // the Object class) } else if (Collection.class.isAssignableFrom(realAttributeType)) { attributeValue = resolveCollectionValueWhenCollectionIsPojoAttribute( pojo, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } else if (Map.class.isAssignableFrom(realAttributeType)) { attributeValue = resolveMapValueWhenMapIsPojoAttribute(pojo, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } else if (realAttributeType.isEnum()) { // Enum type int enumConstantsLength = realAttributeType.getEnumConstants().length; if (enumConstantsLength > 0) { int enumIndex = strategy.getIntegerInRange(0, enumConstantsLength, attributeMetadata) % enumConstantsLength; attributeValue = realAttributeType.getEnumConstants()[enumIndex]; } } else if (Type.class.isAssignableFrom(realAttributeType)) { Type paremeterType = null; if (genericAttributeType instanceof ParameterizedType) { ParameterizedType parametrized = (ParameterizedType) genericAttributeType; Type[] arguments = parametrized.getActualTypeArguments(); if (arguments.length > 0) { paremeterType = arguments[0]; } } else if (realAttributeType.getTypeParameters().length > 0) { paremeterType = realAttributeType.getTypeParameters()[0]; } if (paremeterType != null) { AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); attributeValue = resolveGenericParameter(paremeterType, typeArgsMap, elementGenericTypeArgs); } else { LOG.error("{} is missing generic type argument, supplied {} {}", genericAttributeType, typeArgsMap, Arrays.toString(genericTypeArgs)); } } // For any other type, we use the PODAM strategy if (attributeValue == null) { TypeVariable<?>[] typeParams = attributeType.getTypeParameters(); Type[] genericTypeArgsAll = mergeActualAndSuppliedGenericTypes( typeParams, genericTypeArgs, typeArgsMap); Integer depth = pojos.get(realAttributeType); if (depth == null) { depth = -1; } if (depth <= strategy.getMaxDepth(pojo.getClass())) { pojos.put(realAttributeType, depth + 1); attributeValue = this.manufacturePojoInternal( realAttributeType, attributeMetadata, pojos, genericTypeArgsAll); pojos.put(realAttributeType, depth); } else { attributeValue = resortToExternalFactory( "Loop in {} production detected. Resorting to {} external factory", realAttributeType, genericTypeArgsAll); } } return attributeValue; } /** * Finds constructor comparator from current strategy. * * @return {@link ConstructorAdaptiveComparator} of the current strategy */ private ConstructorAdaptiveComparator findConstructorComparator() { AbstractRandomDataProviderStrategy sortingStrategy; if (getStrategy() instanceof AbstractRandomDataProviderStrategy) { sortingStrategy = (AbstractRandomDataProviderStrategy) getStrategy(); } else { throw new IllegalStateException("manufacturePojoWithFullData can" + " only be used with strategies derived from" + " AbstractRandomDataProviderStrategy"); } if (sortingStrategy.getConstructorComparator() instanceof ConstructorAdaptiveComparator) { return (ConstructorAdaptiveComparator) sortingStrategy.getConstructorComparator(); } else { throw new IllegalStateException("manufacturePojoWithFullData can" + " only be used with constructor comparators derived from" + " ConstructorAdaptiveComparator"); } } /** * Delegates POJO manufacturing to an external factory * * @param <T> * The type of the instance to return * @param msg * Message to log, must contain two parameters * @param pojoClass * The class of which an instance is required * @param genericTypeArgs * The generic type arguments for the current generic class * instance * @return instance of POJO produced by external factory or null */ private <T> T resortToExternalFactory(String msg, Class<T> pojoClass, Type... genericTypeArgs) { LOG.warn(msg, pojoClass, externalFactory.getClass().getName()); ConstructorAdaptiveComparator constuctorComparator = findConstructorComparator(); if (constuctorComparator.isHeavyClass(pojoClass)) { return externalFactory.<T>manufacturePojoWithFullData(pojoClass, genericTypeArgs); } else { return externalFactory.<T>manufacturePojo(pojoClass, genericTypeArgs); } } /** * Utility to merge actual types with supplied array of generic type * substitutions * * @param actualTypes * an array of types used for field or POJO declaration * @param suppliedTypes * an array of supplied types for generic type substitution * @param typeArgsMap * a map relating the generic class arguments ("&lt;T, V&gt;" for * example) with their actual types * @return An array of merged actual and supplied types with generic types * resolved */ private Type[] mergeActualAndSuppliedGenericTypes( Type[] actualTypes, Type[] suppliedTypes, Map<String, Type> typeArgsMap) { List<Type> resolvedTypes = new ArrayList<Type>(); List<Type> substitutionTypes = new ArrayList<Type>(Arrays.asList(suppliedTypes)); for (int i = 0; i < actualTypes.length; i++) { Type type = null; if (actualTypes[i] instanceof TypeVariable) { type = typeArgsMap.get(((TypeVariable<?>)actualTypes[i]).getName()); } else if (actualTypes[i] instanceof Class) { type = actualTypes[i]; } else if (actualTypes[i] instanceof WildcardType) { AtomicReference<Type[]> methodGenericTypeArgs = new AtomicReference<Type[]>(NO_TYPES); type = resolveGenericParameter(actualTypes[i], typeArgsMap, methodGenericTypeArgs); } if (type != null) { resolvedTypes.add(type); if (!substitutionTypes.isEmpty() && substitutionTypes.get(0).equals(type)) { substitutionTypes.remove(0); } } } Type[] resolved = resolvedTypes.toArray(new Type[resolvedTypes.size()]); Type[] supplied = substitutionTypes.toArray(new Type[substitutionTypes.size()]); return mergeTypeArrays(resolved, supplied); } private String resolveStringValue(List<Annotation> annotations, AttributeMetadata attributeMetadata) throws InstantiationException, IllegalAccessException { String retValue = null; if (annotations == null || annotations.isEmpty()) { retValue = strategy.getStringValue(attributeMetadata); } else { for (Annotation annotation : annotations) { if (!PodamStringValue.class.isAssignableFrom(annotation .getClass())) { continue; } // A specific value takes precedence over the length PodamStringValue podamAnnotation = (PodamStringValue) annotation; if (podamAnnotation.strValue() != null && podamAnnotation.strValue().length() > 0) { retValue = podamAnnotation.strValue(); } else { retValue = strategy.getStringOfLength( podamAnnotation.length(), attributeMetadata); } } if (retValue == null) { retValue = strategy.getStringValue(attributeMetadata); } } return retValue; } private AttributeStrategy<?> findAttributeStrategy( List<Annotation> annotations, Class<?> attributeType) throws InstantiationException, IllegalAccessException { List<Annotation> localAnnotations = new ArrayList<Annotation>(annotations); Iterator<Annotation> iter = localAnnotations.iterator(); while (iter.hasNext()) { Annotation annotation = iter.next(); if (annotation instanceof PodamStrategyValue) { PodamStrategyValue strategyAnnotation = (PodamStrategyValue) annotation; return strategyAnnotation.value().newInstance(); } /* Find real class out of proxy */ Class<? extends Annotation> annotationClass = annotation.getClass(); if (Proxy.isProxyClass(annotationClass)) { Class<?>[] interfaces = annotationClass.getInterfaces(); if (interfaces.length == 1) { @SuppressWarnings("unchecked") Class<? extends Annotation> tmp = (Class<? extends Annotation>) interfaces[0]; annotationClass = tmp; } } Class<AttributeStrategy<?>> attrStrategyClass; if ((attrStrategyClass = strategy.getStrategyForAnnotation(annotationClass)) != null) { return attrStrategyClass.newInstance(); } if (annotation.annotationType().getAnnotation(Constraint.class) != null) { if (annotation instanceof NotNull) { /* We don't need to do anything for NotNull constraint */ iter.remove(); } else if (!NotNull.class.getPackage().equals(annotationClass.getPackage())) { LOG.warn("Please, registrer AttributeStratergy for custom " + "constraint {}, in DataProviderStrategy! Value " + "will be left to null", annotation); } } else { iter.remove(); } } AttributeStrategy<?> retValue = null; if (!localAnnotations.isEmpty() && !Collection.class.isAssignableFrom(attributeType) && !Map.class.isAssignableFrom(attributeType) && !attributeType.isArray()) { retValue = new BeanValidationStrategy(localAnnotations, attributeType); } return retValue; } /** * It returns {@code true} if this class is a wrapper class, {@code false} * otherwise * * @param candidateWrapperClass * The class to check * @return {@code true} if this class is a wrapper class, {@code false} * otherwise */ private boolean isWrapper(Class<?> candidateWrapperClass) { return candidateWrapperClass.equals(Byte.class) ? true : candidateWrapperClass.equals(Boolean.class) ? true : candidateWrapperClass.equals(Character.class) ? true : candidateWrapperClass.equals(Short.class) ? true : candidateWrapperClass .equals(Integer.class) ? true : candidateWrapperClass .equals(Long.class) ? true : candidateWrapperClass .equals(Float.class) ? true : candidateWrapperClass .equals(Double.class) ? true : false; } private Collection<? super Object> resolveCollectionValueWhenCollectionIsPojoAttribute( Object pojo, Map<Class<?>, Integer> pojos, Class<?> collectionType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { // This needs to be generic because collections can be of any type Collection<? super Object> retValue = null; if (null != pojo && null != attributeName) { retValue = PodamUtils.getFieldValue(pojo, attributeName); } retValue = resolveCollectionType(collectionType, retValue); if (null == retValue) { return null; } try { Class<?> typeClass = null; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("The collection attribute: " + attributeName + " does not have a type. We will assume Object for you"); // Support for non-generified collections typeClass = Object.class; } else { Type actualTypeArgument = genericTypeArgs[0]; typeClass = resolveGenericParameter(actualTypeArgument, typeArgsMap, elementGenericTypeArgs); } fillCollection(pojos, annotations, attributeName, retValue, typeClass, elementGenericTypeArgs.get()); } catch (SecurityException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalArgumentException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InstantiationException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } return retValue; } private void fillCollection(Collection<? super Object> collection, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Class<?> pojoClass = collection.getClass(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); Annotation[] annotations = collection.getClass().getAnnotations(); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); Class<?> collectionClass = pojoClass; Type[] typeParams = collectionClass.getTypeParameters(); main : while (typeParams.length < 1) { for (Type genericIface : collectionClass.getGenericInterfaces()) { Class<?> clazz = resolveGenericParameter(genericIface, typeArgsMap, elementGenericTypeArgs); if (Collection.class.isAssignableFrom(clazz)) { collectionClass = clazz; typeParams = elementGenericTypeArgs.get(); continue main; } } Type type = collectionClass.getGenericSuperclass(); if (type != null) { Class<?> clazz = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); if (Collection.class.isAssignableFrom(clazz)) { collectionClass = clazz; typeParams = elementGenericTypeArgs.get(); continue main; } } if (Collection.class.equals(collectionClass)) { LOG.warn("Collection {} doesn't have generic types," + "will use Object instead", pojoClass); typeParams = new Type[] { Object.class }; } } Class<?> elementTypeClass = resolveGenericParameter(typeParams[0], typeArgsMap, elementGenericTypeArgs); Type[] elementGenericArgs = mergeTypeArrays(elementGenericTypeArgs.get(), genericTypeArgsExtra); String attributeName = null; fillCollection(pojos, Arrays.asList(annotations), attributeName, collection, elementTypeClass, elementGenericArgs); } private void fillCollection(Map<Class<?>, Integer> pojos, List<Annotation> annotations, String attributeName, Collection<? super Object> collection, Class<?> collectionElementType, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it Holder<AttributeStrategy<?>> elementStrategyHolder = new Holder<AttributeStrategy<?>>(); Holder<AttributeStrategy<?>> keyStrategyHolder = null; Integer nbrElements = findCollectionSize(annotations, collectionElementType, elementStrategyHolder, keyStrategyHolder); AttributeStrategy<?> elementStrategy = elementStrategyHolder.value; try { if (collection.size() > nbrElements) { collection.clear(); } for (int i = collection.size(); i < nbrElements; i++) { // The default Object element; if (null != elementStrategy && (elementStrategy instanceof ObjectStrategy) && Object.class.equals(collectionElementType)) { LOG.debug("Element strategy is ObjectStrategy and collection element is of type Object: using the ObjectStrategy strategy"); element = elementStrategy.getValue(); } else if (null != elementStrategy && !(elementStrategy instanceof ObjectStrategy)) { LOG.debug("Collection elements will be filled using the following strategy: " + elementStrategy); element = returnAttributeDataStrategyValue( collectionElementType, elementStrategy); } else { Map<String, Type> nullTypeArgsMap = new HashMap<String, Type>(); element = manufactureAttributeValue(collection, pojos, collectionElementType, collectionElementType, annotations, attributeName, nullTypeArgsMap, genericTypeArgs); } collection.add(element); } } catch (UnsupportedOperationException e) { LOG.warn("Cannot fill immutable collection {}", collection.getClass()); } } private Map<? super Object, ? super Object> resolveMapValueWhenMapIsPojoAttribute( Object pojo, Map<Class<?>, Integer> pojos, Class<?> attributeType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { Map<? super Object, ? super Object> retValue = null; if (null != pojo && null != attributeName) { retValue = PodamUtils.getFieldValue(pojo, attributeName); } retValue = resolveMapType(attributeType, retValue); if (null == retValue) { return null; } try { Class<?> keyClass = null; Class<?> elementClass = null; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("Map attribute: " + attributeName + " is non-generic. We will assume a Map<Object, Object> for you."); keyClass = Object.class; elementClass = Object.class; } else { // Expected only key, value type if (genericTypeArgs.length != 2) { throw new IllegalStateException( "In a Map only key value generic type are expected."); } Type[] actualTypeArguments = genericTypeArgs; keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter(actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } MapArguments mapArguments = new MapArguments(); mapArguments.setAttributeName(attributeName); mapArguments.setPojos(pojos); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(retValue); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments .setElementGenericTypeArgs(elementGenericTypeArgs.get()); fillMap(mapArguments); } catch (InstantiationException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (SecurityException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } return retValue; } private void fillMap(Map<? super Object, ? super Object> map, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Class<?> pojoClass = map.getClass(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); Class<?> mapClass = pojoClass; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); Type[] typeParams = mapClass.getTypeParameters(); main : while (typeParams.length < 2) { for (Type genericIface : mapClass.getGenericInterfaces()) { Class<?> clazz = resolveGenericParameter(genericIface, typeArgsMap, elementGenericTypeArgs); if (Map.class.isAssignableFrom(clazz)) { typeParams = elementGenericTypeArgs.get(); mapClass = clazz; continue main; } } Type type = mapClass.getGenericSuperclass(); if (type != null) { Class<?> clazz = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); if (Map.class.isAssignableFrom(clazz)) { typeParams = elementGenericTypeArgs.get(); mapClass = clazz; continue main; } } if (Map.class.equals(mapClass)) { LOG.warn("Map {} doesn't have generic types," + "will use Object, Object instead", pojoClass); typeParams = new Type[] { Object.class, Object.class }; } } AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); Class<?> keyClass = resolveGenericParameter(typeParams[0], typeArgsMap, keyGenericTypeArgs); Class<?> elementClass = resolveGenericParameter(typeParams[1], typeArgsMap, elementGenericTypeArgs); Type[] keyGenericArgs = mergeTypeArrays(keyGenericTypeArgs.get(), genericTypeArgsExtra); Type[] elementGenericArgs = mergeTypeArrays(elementGenericTypeArgs.get(), genericTypeArgsExtra); MapArguments mapArguments = new MapArguments(); mapArguments.setPojos(pojos); mapArguments.setAnnotations(Arrays.asList(pojoClass.getAnnotations())); mapArguments.setMapToBeFilled(map); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericArgs); mapArguments.setElementGenericTypeArgs(elementGenericArgs); fillMap(mapArguments); } private void fillMap(MapArguments mapArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it Holder<AttributeStrategy<?>> elementStrategyHolder = new Holder<AttributeStrategy<?>>(); Holder<AttributeStrategy<?>> keyStrategyHolder = new Holder<AttributeStrategy<?>>(); Integer nbrElements = findCollectionSize(mapArguments.getAnnotations(), mapArguments.getElementClass(), elementStrategyHolder, keyStrategyHolder); AttributeStrategy<?> keyStrategy = keyStrategyHolder.value; AttributeStrategy<?> elementStrategy = elementStrategyHolder.value; Map<? super Object, ? super Object> map = mapArguments.getMapToBeFilled(); try { if (map.size() > nbrElements) { map.clear(); } for (int i = map.size(); i < nbrElements; i++) { Object keyValue = null; Object elementValue = null; MapKeyOrElementsArguments valueArguments = new MapKeyOrElementsArguments(); valueArguments.setAttributeName(mapArguments.getAttributeName()); valueArguments.setMapToBeFilled(mapArguments.getMapToBeFilled()); valueArguments.setPojos(mapArguments.getPojos()); valueArguments.setAnnotations(mapArguments.getAnnotations()); valueArguments.setKeyOrValueType(mapArguments.getKeyClass()); valueArguments.setElementStrategy(keyStrategy); valueArguments.setGenericTypeArgs(mapArguments .getKeyGenericTypeArgs()); keyValue = getMapKeyOrElementValue(valueArguments); valueArguments.setKeyOrValueType(mapArguments.getElementClass()); valueArguments.setElementStrategy(elementStrategy); valueArguments.setGenericTypeArgs(mapArguments .getElementGenericTypeArgs()); elementValue = getMapKeyOrElementValue(valueArguments); /* ConcurrentHashMap doesn't allow null values */ if (elementValue != null || !(map instanceof ConcurrentHashMap)) { map.put(keyValue, elementValue); } } } catch (UnsupportedOperationException e) { LOG.warn("Cannot fill immutable map {}", map.getClass()); } } private Object getMapKeyOrElementValue( MapKeyOrElementsArguments keyOrElementsArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; if (null != keyOrElementsArguments.getElementStrategy() && ObjectStrategy.class.isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass()) && Object.class.equals(keyOrElementsArguments .getKeyOrValueType())) { LOG.debug("Element strategy is ObjectStrategy and Map key or value type is of type Object: using the ObjectStrategy strategy"); retValue = keyOrElementsArguments.getElementStrategy().getValue(); } else if (null != keyOrElementsArguments.getElementStrategy() && !ObjectStrategy.class .isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass())) { LOG.debug("Map key or value will be filled using the following strategy: " + keyOrElementsArguments.getElementStrategy()); retValue = returnAttributeDataStrategyValue( keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getElementStrategy()); } else { Map<String, Type> nullTypeArgsMap = new HashMap<String, Type>(); retValue = manufactureAttributeValue( keyOrElementsArguments.getMapToBeFilled(), keyOrElementsArguments.getPojos(), keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getAnnotations(), keyOrElementsArguments.getAttributeName(), nullTypeArgsMap, keyOrElementsArguments.getGenericTypeArgs()); } return retValue; } private Object resolveArrayElementValue(Class<?> attributeType, Type genericType, String attributeName, Map<Class<?>, Integer> pojos, List<Annotation> annotations, Object pojo, Map<String, Type> typeArgsMap) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> componentType = null; Type genericComponentType = null; AtomicReference<Type[]> genericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericType instanceof GenericArrayType) { genericComponentType = ((GenericArrayType) genericType).getGenericComponentType(); if (genericComponentType instanceof TypeVariable) { TypeVariable<?> componentTypeVariable = (TypeVariable<?>) genericComponentType; final Type resolvedType = typeArgsMap.get(componentTypeVariable.getName()); componentType = resolveGenericParameter(resolvedType, typeArgsMap, genericTypeArgs); } } else if (genericType instanceof Class) { Class<?> arrayClass = (Class<?>) genericType; genericComponentType = arrayClass.getComponentType(); } else { genericComponentType = attributeType.getComponentType(); } if (componentType == null) { componentType = attributeType.getComponentType(); } // If the user defined a strategy to fill the collection elements, // we use it Holder<AttributeStrategy<?>> elementStrategyHolder = new Holder<AttributeStrategy<?>>(); Holder<AttributeStrategy<?>> keyStrategyHolder = null; Integer nbrElements = findCollectionSize(annotations, attributeType, elementStrategyHolder, keyStrategyHolder); AttributeStrategy<?> elementStrategy = elementStrategyHolder.value; Object arrayElement = null; Object array = Array.newInstance(componentType, nbrElements); for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && (elementStrategy instanceof ObjectStrategy) && Object.class.equals(componentType)) { LOG.debug("Element strategy is ObjectStrategy and array element is of type Object: using the ObjectStrategy strategy"); arrayElement = elementStrategy.getValue(); } else if (null != elementStrategy && !(elementStrategy instanceof ObjectStrategy)) { LOG.debug("Array elements will be filled using the following strategy: " + elementStrategy); arrayElement = returnAttributeDataStrategyValue(componentType, elementStrategy); } else { arrayElement = manufactureAttributeValue(array, pojos, componentType, genericComponentType, annotations, attributeName, typeArgsMap, genericTypeArgs.get()); } Array.set(array, i, arrayElement); } return array; } private Integer findCollectionSize(List<Annotation> annotations, Class<?> collectionElementType, Holder<AttributeStrategy<?>> elementStrategyHolder, Holder<AttributeStrategy<?>> keyStrategyHolder) throws InstantiationException, IllegalAccessException { // If the user defined a strategy to fill the collection elements, // we use it Size size = null; for (Annotation annotation : annotations) { if (annotation instanceof PodamCollection) { PodamCollection collectionAnnotation = (PodamCollection) annotation; if (null != elementStrategyHolder) { Class<? extends AttributeStrategy<?>> strategy = collectionAnnotation.collectionElementStrategy(); if (null == strategy || ObjectStrategy.class.isAssignableFrom(strategy)) { strategy = collectionAnnotation.mapElementStrategy(); } if (null != strategy) { elementStrategyHolder.value = strategy.newInstance(); } } if (null != keyStrategyHolder) { Class<? extends AttributeStrategy<?>> strategy = collectionAnnotation.mapKeyStrategy(); if (null != strategy) { keyStrategyHolder.value = strategy.newInstance(); } } return collectionAnnotation.nbrElements(); } else if (annotation instanceof Size) { size = (Size) annotation; } } Integer nbrElements = strategy .getNumberOfCollectionElements(collectionElementType); if (null != size) { if (nbrElements > size.max()) { nbrElements = size.max(); } if (nbrElements < size.min()) { nbrElements = size.min(); } } return nbrElements; } /** * Given a collection type it returns an instance * * <ul> * <li>The default type for a {@link List} is an {@link ArrayList}</li> * <li>The default type for a {@link Queue} is a {@link LinkedList}</li> * <li>The default type for a {@link Set} is a {@link HashSet}</li> * </ul> * * @param collectionType * The collection type * * @param defaultValue * Default value for the collection, can be null * @return an instance of the collection type or null */ private Collection<? super Object> resolveCollectionType( Class<?> collectionType, Collection<? super Object> defaultValue) { Collection<? super Object> retValue = null; // Default list and set are ArrayList and HashSet. If users // wants a particular collection flavour they have to initialise // the collection if (null != defaultValue && (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) { /* Default collection, which is not immutable */ retValue = defaultValue; } else { if (Queue.class.isAssignableFrom(collectionType)) { if (collectionType.isAssignableFrom(LinkedList.class)) { retValue = new LinkedList<Object>(); } } else if (Set.class.isAssignableFrom(collectionType)) { if (collectionType.isAssignableFrom(HashSet.class)) { retValue = new HashSet<Object>(); } } else { if (collectionType.isAssignableFrom(ArrayList.class)) { retValue = new ArrayList<Object>(); } } if (null != retValue && null != defaultValue) { retValue.addAll(defaultValue); } } return retValue; } /** * It manufactures and returns a default instance for each map type * * <p> * The default implementation for a {@link ConcurrentMap} is * {@link ConcurrentHashMap} * </p> * * <p> * The default implementation for a {@link SortedMap} is a {@link TreeMap} * </p> * * <p> * The default Map is none of the above was recognised is a {@link HashMap} * </p> * * @param mapType * The attribute type implementing Map * @param defaultValue * Default value for map * @return A default instance for each map type or null * */ private Map<? super Object, ? super Object> resolveMapType( Class<?> mapType, Map<? super Object, ? super Object> defaultValue) { Map<? super Object, ? super Object> retValue = null; if (null != defaultValue && (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) { /* Default map, which is not immutable */ retValue = defaultValue; } else { if (SortedMap.class.isAssignableFrom(mapType)) { if (mapType.isAssignableFrom(TreeMap.class)) { retValue = new TreeMap<Object, Object>(); } } else if (ConcurrentMap.class.isAssignableFrom(mapType)) { if (mapType.isAssignableFrom(ConcurrentHashMap.class)) { retValue = new ConcurrentHashMap<Object, Object>(); } } else { if (mapType.isAssignableFrom(HashMap.class)) { retValue = new HashMap<Object, Object>(); } } } return retValue; } private Object[] getParameterValuesForConstructor( Constructor<?> constructor, Class<?> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); final Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); Annotation[][] parameterAnnotations = constructor .getParameterAnnotations(); Class<?>[] parameterTypes = constructor.getParameterTypes(); Type[] genericTypes = constructor.getGenericParameterTypes(); Object[] parameterValues = new Object[parameterTypes.length]; for (int idx = 0; idx < parameterTypes.length; idx++) { List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); Type genericType = (idx < genericTypes.length) ? genericTypes[idx] : parameterTypes[idx]; parameterValues[idx] = manufactureParameterValue(parameterTypes[idx], genericType, annotations, typeArgsMap, pojos, genericTypeArgsExtra == null ? NO_TYPES : genericTypeArgsExtra); } return parameterValues; } private Object manufactureParameterValue(Class<?> parameterType, Type genericType, List<Annotation> annotations, final Map<String, Type> typeArgsMap, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object parameterValue = null; AttributeStrategy<?> attributeStrategy = findAttributeStrategy(annotations, parameterType); if (null != attributeStrategy) { LOG.debug("The parameter: " + genericType + " will be filled using the following strategy: " + attributeStrategy); return returnAttributeDataStrategyValue(parameterType, attributeStrategy); } if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> defaultValue = null; Collection<? super Object> collection = resolveCollectionType( parameterType, defaultValue); if (collection != null) { Class<?> collectionElementType; AtomicReference<Type[]> collectionGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) genericType; Type actualTypeArgument = pType.getActualTypeArguments()[0]; collectionElementType = resolveGenericParameter( actualTypeArgument, typeArgsMap, collectionGenericTypeArgs); } else { LOG.warn("Collection parameter {} type is non-generic." + "We will assume a Collection<Object> for you.", genericType); collectionElementType = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( collectionGenericTypeArgs.get(), genericTypeArgs); String attributeName = null; fillCollection(pojos, annotations, attributeName, collection, collectionElementType, genericTypeArgsAll); parameterValue = collection; } } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> defaultValue = null; Map<? super Object, ? super Object> map = resolveMapType(parameterType, defaultValue); if (map != null) { Class<?> keyClass; Class<?> elementClass; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( NO_TYPES); if (genericType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) genericType; Type[] actualTypeArguments = pType.getActualTypeArguments(); keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter( actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } else { LOG.warn("Map parameter {} type is non-generic." + "We will assume a Map<Object,Object> for you.", genericType); keyClass = Object.class; elementClass = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( elementGenericTypeArgs.get(), genericTypeArgs); MapArguments mapArguments = new MapArguments(); mapArguments.setPojos(pojos); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(map); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments.setElementGenericTypeArgs(genericTypeArgsAll); fillMap(mapArguments); parameterValue = map; } } if (parameterValue == null) { Map<String, Type> typeArgsMapForParam; if (genericType instanceof ParameterizedType) { typeArgsMapForParam = new HashMap<String, Type>(typeArgsMap); ParameterizedType parametrizedType = (ParameterizedType) genericType; TypeVariable<?>[] argumentTypes = parameterType.getTypeParameters(); Type[] argumentGenericTypes = parametrizedType.getActualTypeArguments(); for (int k = 0; k < argumentTypes.length; k++) { if (argumentGenericTypes[k] instanceof Class) { Class<?> genericParam = (Class<?>) argumentGenericTypes[k]; typeArgsMapForParam.put(argumentTypes[k].getName(), genericParam); } } } else { typeArgsMapForParam = typeArgsMap; } parameterValue = manufactureParameterValue(pojos, parameterType, genericType, annotations, typeArgsMapForParam, genericTypeArgs); } return parameterValue; } /** * Utility method to merge two arrays * * @param original * The main array * @param extra * The additional array, optionally may be null * @return A merged array of original and extra arrays */ private Type[] mergeTypeArrays(Type[] original, Type[] extra) { Type[] merged; if (extra != null) { merged = new Type[original.length + extra.length]; System.arraycopy(original, 0, merged, 0, original.length); System.arraycopy(extra, 0, merged, original.length, extra.length); } else { merged = original; } return merged; } private Object returnAttributeDataStrategyValue(Class<?> attributeType, AttributeStrategy<?> attributeStrategy) throws IllegalArgumentException { Object retValue = attributeStrategy.getValue(); if (retValue != null) { Class<?> desiredType = attributeType.isPrimitive() ? PodamUtils.primitiveToBoxedType(attributeType) : attributeType; if (!desiredType.isAssignableFrom(retValue.getClass())) { String errMsg = "The type of the Podam Attribute Strategy is not " + attributeType.getName() + " but " + retValue.getClass().getName() + ". An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } } return retValue; } }
package com.rexsl.page.inset; import com.jcabi.aspects.Loggable; import com.rexsl.page.BasePage; import com.rexsl.page.CookieBuilder; import com.rexsl.page.Inset; import com.rexsl.page.JaxbBundle; import com.rexsl.page.Resource; import java.net.HttpURLConnection; import java.net.URI; import java.util.logging.Level; import javax.validation.constraints.NotNull; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.Validate; @ToString @EqualsAndHashCode(of = "resource") @Loggable(Loggable.DEBUG) @SuppressWarnings("PMD.TooManyMethods") public final class FlashInset implements Inset { /** * Header name. */ private static final String HEADER = "X-Rexsl-Flash"; /** * Cookie name. */ private static final String COOKIE = "Rexsl-Flash"; /** * The resource. */ private final transient Resource resource; /** * Public ctor. * @param res The resource */ public FlashInset(@NotNull final Resource res) { this.resource = res; } /** * {@inheritDoc} */ @Override public void render(@NotNull final BasePage<?, ?> page, @NotNull final Response.ResponseBuilder builder) { if (this.resource.httpHeaders().getCookies() .containsKey(FlashInset.COOKIE)) { final FlashInset.Flash cookie = new FlashInset.Flash( this.resource.httpHeaders().getCookies().get(FlashInset.COOKIE) ); page.append( FlashInset.bundle( cookie.level(), cookie.message(), cookie.msec() ) ); builder.cookie( new CookieBuilder(this.resource.uriInfo().getBaseUri()) .name(FlashInset.COOKIE) .build() ); } } /** * Make a bundle. * @param level Logging level * @param msg Message * @param msec Time spent * @return JaxbBundle injectable into the page */ public static JaxbBundle bundle(@NotNull final Level level, @NotNull final String msg, final long msec) { return new JaxbBundle("flash") .add("message", msg).up() .add("level", level.toString()).up() .add("msec", Long.toString(msec)).up(); } /** * Make a bundle. * @param level Logging level * @param msg Message * @return JaxbBundle injectable into the page * @since 0.4.16 */ public static JaxbBundle bundle(final Level level, final String msg) { return FlashInset.bundle(level, msg, 0L); } /** * Create an exception that will redirect to the page with an error message. * * <p>The difference between this method and a static * {@link #forward(URI,String,Level)} is in its awareness of a resource, * which is forwarding. Key benefit is that a non-static method adds extra * value to the cookie, which is time consumed by the resource until the * redirect happened. * * @param uri The URI to forward to * @param message The message to show as error * @param level Message level * @return The exception to throw */ public WebApplicationException redirect(@NotNull final URI uri, @NotNull final String message, @NotNull final Level level) { return new FlashException( Response.status(HttpURLConnection.HTTP_SEE_OTHER) .location(uri) .cookie( new FlashInset.Flash( uri, message, level, System.currentTimeMillis() - this.resource.started()) ) .header(FlashInset.HEADER, message) .entity(message) .build(), message, level ); } /** * Create an exception that will redirect to the page with an error message. * * <p>The difference between this method and a static * {@link #forward(URI,Exception)} is in its awareness of a resource, * which is forwarding. Key benefit is that a non-static method adds extra * value to the cookie, which is time consumed by the resource until the * redirect happened. * * @param uri The URI to forward to * @param cause The cause of this problem * @return The exception to throw */ public WebApplicationException redirect(@NotNull final URI uri, @NotNull final Exception cause) { return this.redirect(uri, cause.getMessage(), Level.SEVERE); } /** * Create an exception that will forward to the page with an error message. * @param uri The URI to forward to * @param message The message to show as error * @param level Message level * @return The exception to throw */ public static WebApplicationException forward(@NotNull final URI uri, @NotNull final String message, @NotNull final Level level) { return new FlashException( Response.status(HttpURLConnection.HTTP_SEE_OTHER) .location(uri) .cookie(new FlashInset.Flash(uri, message, level)) .header(FlashInset.HEADER, message) .entity(message) .build(), message, level ); } /** * Throw an exception that will forward to the page with an error message. * @param uri The URI to forward to * @param cause The cause of this problem * @return The exception to throw */ public static WebApplicationException forward(@NotNull final URI uri, @NotNull final Exception cause) { return FlashInset.forward(uri, cause.getMessage(), Level.SEVERE); } /** * The cookie. */ public static final class Flash extends NewCookie { /** * Total elements expected in a cookie text. */ private static final int TOTAL = 3; /** * The message. */ private final transient String msg; /** * Level of message. */ private final transient Level lvl; /** * Milliseconds consumed (or -1). */ private final transient long millis; /** * Public ctor, from a cookie encoded text. * @param cookie The cookie */ public Flash(@NotNull final Cookie cookie) { super(FlashInset.COOKIE, cookie.getValue()); Validate.notBlank(cookie.getValue(), "cookie value is blank"); final String decoded = FlashInset.Flash.decode(this.getValue()); final String[] parts = decoded.split(":", FlashInset.Flash.TOTAL); Validate.isTrue( parts.length == FlashInset.Flash.TOTAL, // @checkstyle LineLength (1 line) "can't decode cookie '%s' (decoded='%s'), %d parts expected but %d found", this.getValue(), decoded, FlashInset.Flash.TOTAL, parts.length ); Validate.isTrue( parts[0].matches("INFO|WARNING|SEVERE"), "can't detect level of cookie '%s' (decoded='%s')", this.getValue(), decoded ); this.lvl = Level.parse(parts[0]); Validate.isTrue( parts[1].matches("-1|\\d+"), "can't parse milliseconds in cookie '%s' (decoded='%s')", this.getValue(), decoded ); this.millis = Long.parseLong(parts[1]); Validate.notBlank( parts[2], "empty message in cookie '%s' (decoded='%s')", this.getValue(), decoded ); this.msg = parts[2]; } /** * Public ctor, from exact values. * @param base Base URI where we're using it * @param message The message * @param level The level */ public Flash(@NotNull final URI base, @NotNull final String message, @NotNull final Level level) { this(base, message, level, -1); } /** * Public ctor, from exact values. * @param base Base URI where we're using it * @param message The message * @param level The level * @param msec Milliseconds consumed * @checkstyle ParameterNumber (5 lines) */ public Flash(@NotNull final URI base, @NotNull final String message, @NotNull final Level level, final long msec) { super( new CookieBuilder(base) .name(FlashInset.COOKIE) .value(FlashInset.Flash.encode(message, level, msec)) .temporary() .build() ); Validate.notBlank(message, "flash message can't be empty"); this.msg = message; this.lvl = level; Validate.isTrue( msec > 0 || msec == -1, "milliseconds can either be positive or equal to -1" ); this.millis = msec; } /** * Get message. * @return The message */ public String message() { return this.msg; } /** * Get color of it. * @return The color */ public Level level() { return this.lvl; } /** * Milliseconds consumed. * @return The amount of them */ public long msec() { return this.millis; } /** * {@inheritDoc} */ @Override public String getPath() { return "/"; } /** * Encode message and color. * @param message The message * @param level The level * @param msec Milliseconds consumed * @return Encoded cookie value */ private static String encode(final String message, final Level level, final long msec) { try { return Base64.encodeBase64URLSafeString( String.format("%s:%d:%s", level, msec, message) .getBytes(CharEncoding.UTF_8) ); } catch (java.io.UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } } /** * Decode text. * @param text The text to decode (cookie value) * @return Decoded value */ private static String decode(final String text) { try { return new String( Base64.decodeBase64(text), CharEncoding.UTF_8 ); } catch (java.io.UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } } } }
package uk.co.jemos.podam.api; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicReference; import net.jcip.annotations.Immutable; import net.jcip.annotations.ThreadSafe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.jemos.podam.common.AttributeStrategy; import uk.co.jemos.podam.common.PodamBooleanValue; import uk.co.jemos.podam.common.PodamByteValue; import uk.co.jemos.podam.common.PodamCharValue; import uk.co.jemos.podam.common.PodamCollection; import uk.co.jemos.podam.common.PodamConstants; import uk.co.jemos.podam.common.PodamConstructor; import uk.co.jemos.podam.common.PodamDoubleValue; import uk.co.jemos.podam.common.PodamFloatValue; import uk.co.jemos.podam.common.PodamIntValue; import uk.co.jemos.podam.common.PodamLongValue; import uk.co.jemos.podam.common.PodamShortValue; import uk.co.jemos.podam.common.PodamStrategyValue; import uk.co.jemos.podam.common.PodamStringValue; import uk.co.jemos.podam.exceptions.PodamMockeryException; /** * The PODAM factory implementation * * @author mtedone * * @since 1.0.0 * */ @ThreadSafe @Immutable public class PodamFactoryImpl implements PodamFactory { private static final String RESOLVING_COLLECTION_EXCEPTION_STR = "An exception occurred while resolving the collection"; private static final String MAP_CREATION_EXCEPTION_STR = "An exception occurred while creating a Map object"; private static final String RAWTYPES_STR = "rawtypes"; private static final String UNCHECKED_STR = "unchecked"; private static final String THE_ANNOTATION_VALUE_STR = "The annotation value: "; private static final Type[] NO_TYPES = new Type[0]; /** Application logger */ private static final Logger LOG = LoggerFactory .getLogger(PodamFactoryImpl.class.getName()); /** * External factory to delegate production this factory cannot handle * <p> * The default is {@link LoggingExternalFactory}. * </p> */ private final PodamFactory externalFactory; /** * The strategy to use to fill data. * <p> * The default is {@link RandomDataProviderStrategy}. * </p> */ private final DataProviderStrategy strategy; /** * A map to keep one object for each class. If memoization is enabled, the * factory will use this table to avoid creating objects of the same class * multiple times. */ private Map<Class<?>, Object> memoizationTable = new HashMap<Class<?>, Object>(); /** * Default constructor. */ public PodamFactoryImpl() { this(LoggingExternalFactory.getInstance(), RandomDataProviderStrategy.getInstance()); } /** * Constructor with non-default strategy * * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(DataProviderStrategy strategy) { this(LoggingExternalFactory.getInstance(), strategy); } /** * Constructor with non-default external factory * * @param externalFactory * External factory to delegate production this factory cannot * handle */ public PodamFactoryImpl(PodamFactory externalFactory) { this(externalFactory, RandomDataProviderStrategy.getInstance()); } /** * Full constructor. * * @param externalFactory * External factory to delegate production this factory cannot * handle * @param strategy * The strategy to use to fill data */ public PodamFactoryImpl(PodamFactory externalFactory, DataProviderStrategy strategy) { this.externalFactory = externalFactory; this.strategy = strategy; } /** * {@inheritDoc} */ @Override public <T> T manufacturePojo(Class<T> pojoClass) { return this.manufacturePojo(pojoClass, NO_TYPES); } /** * {@inheritDoc} */ @Override public <T> T manufacturePojo(Class<T> pojoClass, Type... genericTypeArgs) { Map<Class<?>, Integer> pojos = new HashMap<Class<?>, Integer>(); pojos.put(pojoClass, 0); try { return this.manufacturePojoInternal(pojoClass, pojos, genericTypeArgs); } catch (InstantiationException e) { throw new PodamMockeryException("", e); } catch (IllegalAccessException e) { throw new PodamMockeryException("", e); } catch (InvocationTargetException e) { throw new PodamMockeryException("", e); } catch (ClassNotFoundException e) { throw new PodamMockeryException("", e); } } /** * {@inheritDoc} */ @Override public DataProviderStrategy getStrategy() { return strategy; } private Type[] fillTypeArgMap(final Map<String, Type> typeArgsMap, final Class<?> pojoClass, final Type[] genericTypeArgs) { final TypeVariable<?>[] typeParameters = pojoClass.getTypeParameters(); if (typeParameters.length > genericTypeArgs.length) { String msg = pojoClass.getCanonicalName() + " is missing generic type arguments, expected " + typeParameters.length + " found " + Arrays.toString(genericTypeArgs); throw new IllegalStateException(msg); } int i; for (i = 0; i < typeParameters.length; i++) { typeArgsMap.put(typeParameters[i].getName(), genericTypeArgs[i]); } Type[] genericTypeArgsExtra; if (typeParameters.length < genericTypeArgs.length) { genericTypeArgsExtra = Arrays.copyOfRange(genericTypeArgs, i, genericTypeArgs.length); } else { genericTypeArgsExtra = null; } /* Adding types, which were specified during inheritance */ Class<?> clazz = pojoClass; while (clazz != null) { Type superType = clazz.getGenericSuperclass(); clazz = clazz.getSuperclass(); if (superType instanceof ParameterizedType) { ParameterizedType paramType = (ParameterizedType) superType; Type[] actualParamTypes = paramType.getActualTypeArguments(); TypeVariable<?>[] paramTypes = clazz.getTypeParameters(); for (i = 0; i < actualParamTypes.length && i < paramTypes.length; i++) { if (actualParamTypes[i] instanceof Class) { typeArgsMap.put(paramTypes[i].getName(), actualParamTypes[i]); } } } } return genericTypeArgsExtra; } private Object createNewInstanceForClassWithoutConstructors( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> clazz, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; Constructor<?>[] constructors = clazz.getConstructors(); if (constructors.length == 0 || Modifier.isAbstract(clazz.getModifiers())) { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); try { Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } } catch (IllegalStateException e) { LOG.error( "An error occurred while filling the type argument in the map", e); return null; } // If no publicly accessible constructors are available, // the best we can do is to find a constructor (e.g. // getInstance()) Method[] declaredMethods = clazz.getDeclaredMethods(); // A candidate factory method is a method which returns the // Class type // The parameters to pass to the method invocation Object[] parameterValues = null; Object[] noParams = new Object[] {}; for (Method candidateConstructor : declaredMethods) { if (!Modifier.isStatic(candidateConstructor.getModifiers()) || !candidateConstructor.getReturnType().equals(clazz) || retValue != null) { continue; } parameterValues = new Object[candidateConstructor .getParameterTypes().length]; Type[] parameterTypes = candidateConstructor .getGenericParameterTypes(); if (parameterTypes.length == 0) { parameterValues = noParams; } else { // This is a factory method with arguments Annotation[][] parameterAnnotations = candidateConstructor .getParameterAnnotations(); int idx = 0; for (Type paramType : parameterTypes) { AtomicReference<Type[]> methodGenericTypeArgs = new AtomicReference<Type[]>(); Class<?> parameterType = resolveGenericParameter( paramType, typeArgsMap, methodGenericTypeArgs); List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); String attributeName = null; // It's a Collection type if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> listType = resolveCollectionType(parameterType); Class<?> elementType; if (paramType instanceof ParameterizedType) { elementType = (Class<?>) methodGenericTypeArgs .get()[0]; } else { LOG.warn("Collection parameter {} type is non-generic." + "We will assume a Collection<Object> for you.", paramType); elementType = Object.class; } int nbrElements = strategy .getNumberOfCollectionElements(elementType); for (Annotation annotation : annotations) { if (annotation.annotationType().equals( PodamCollection.class)) { PodamCollection ann = (PodamCollection) annotation; nbrElements = ann.nbrElements(); } } for (int i = 0; i < nbrElements; i++) { Object attributeValue = manufactureAttributeValue( clazz, pojos, elementType, annotations, attributeName); listType.add(attributeValue); } parameterValues[idx] = listType; // It's a Map } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> mapType = resolveMapType(parameterType); Class<?> keyClass; Class<?> valueClass; if (paramType instanceof ParameterizedType) { keyClass = (Class<?>) methodGenericTypeArgs .get()[0]; valueClass = (Class<?>) methodGenericTypeArgs .get()[1]; } else { LOG.warn("Map parameter {} type is non-generic." + "We will assume a Map<Object,Object> for you.", paramType); keyClass = Object.class; valueClass = Object.class; } int nbrElements = strategy .getNumberOfCollectionElements(valueClass); for (Annotation annotation : annotations) { if (annotation.annotationType().equals( PodamCollection.class)) { PodamCollection ann = (PodamCollection) annotation; nbrElements = ann.nbrElements(); } } for (int i = 0; i < nbrElements; i++) { Object keyValue = manufactureAttributeValue( clazz, pojos, keyClass, annotations, attributeName); Object elementValue = manufactureAttributeValue( clazz, pojos, valueClass, annotations, attributeName); mapType.put(keyValue, elementValue); } parameterValues[idx] = mapType; } else { // It's any other object parameterValues[idx] = manufactureAttributeValue( clazz, pojos, parameterType, annotations, attributeName, typeArgsMap, genericTypeArgs); } idx++; } } try { retValue = candidateConstructor.invoke(clazz, parameterValues); LOG.info("Could create an instance using " + candidateConstructor); } catch (Exception t) { LOG.info( "PODAM could not create an instance for constructor: " + candidateConstructor + ". Will try another one...", t); } } } else { // There are public constructors. We want constructor with minumum // number of parameters to speed up the creation strategy.sort(constructors); for (Constructor<?> constructor : constructors) { try { Object[] constructorArgs = getParameterValuesForConstructor( constructor, pojoClass, pojos, genericTypeArgs); retValue = constructor.newInstance(constructorArgs); LOG.info("For class: " + clazz.getName() + " a valid constructor: " + constructor + " was found. PODAM will use it to create an instance."); break; } catch (Exception t) { LOG.info( "Couldn't create attribute with constructor: " + constructor + ". Will check if other constructors are available", t); } } } if (retValue == null) { retValue = externalFactory.manufacturePojo(clazz, genericTypeArgs); } if (retValue == null) { LOG.warn("For attribute {}[{}] PODAM could not possibly create" + " a value. It will be returned as null.", pojoClass, clazz); } return retValue; } /** * It resolves generic parameter type * * * @param paramType * The generic parameter type * @param typeArgsMap * A map of resolved types * @param methodGenericTypeArgs * Return value posible generic types of the generic parameter * type * @return value for class representing the generic parameter type */ private Class<?> resolveGenericParameter(Type paramType, Map<String, Type> typeArgsMap, AtomicReference<Type[]> methodGenericTypeArgs) { Class<?> parameterType = null; methodGenericTypeArgs.set(new Type[] {}); if (paramType instanceof TypeVariable<?>) { final TypeVariable<?> typeVariable = (TypeVariable<?>) paramType; final Type type = typeArgsMap.get(typeVariable.getName()); if (type != null) { parameterType = resolveGenericParameter(type, typeArgsMap, methodGenericTypeArgs); } } else if (paramType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) paramType; parameterType = (Class<?>) pType.getRawType(); methodGenericTypeArgs.set(pType.getActualTypeArguments()); } else if (paramType instanceof WildcardType) { WildcardType wType = (WildcardType) paramType; Type[] bounds = wType.getLowerBounds(); String msg; if (bounds != null && bounds.length > 0) { msg = "Lower bounds:"; } else { bounds = wType.getUpperBounds(); msg = "Upper bounds:"; } if (bounds != null && bounds.length > 0) { LOG.debug(msg + Arrays.toString(bounds)); parameterType = resolveGenericParameter(bounds[0], typeArgsMap, methodGenericTypeArgs); } } else if (paramType instanceof Class) { parameterType = (Class<?>) paramType; } if (parameterType == null) { LOG.warn("Unrecognized type {}. Will use Object instead", paramType); parameterType = Object.class; } return parameterType; } private Object resolvePrimitiveValue(Class<?> primitiveClass, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (primitiveClass.equals(int.class)) { if (!annotations.isEmpty()) { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } } else if (primitiveClass.equals(long.class)) { if (!annotations.isEmpty()) { retValue = getLongValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } } else if (primitiveClass.equals(float.class)) { if (!annotations.isEmpty()) { retValue = getFloatValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } } else if (primitiveClass.equals(double.class)) { if (!annotations.isEmpty()) { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } } else if (primitiveClass.equals(boolean.class)) { if (!annotations.isEmpty()) { retValue = getBooleanValueForAnnotation(annotations); } if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } } else if (primitiveClass.equals(byte.class)) { if (!annotations.isEmpty()) { retValue = getByteValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } } else if (primitiveClass.equals(short.class)) { if (!annotations.isEmpty()) { retValue = getShortValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } } else if (primitiveClass.equals(char.class)) { if (!annotations.isEmpty()) { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } } return retValue; } /** * It returns the boolean value indicated in the annotation. * * @param annotations * The collection of annotations for the annotated attribute * @return The boolean value indicated in the annotation */ private Boolean getBooleanValueForAnnotation(List<Annotation> annotations) { Boolean retValue = null; for (Annotation annotation : annotations) { if (PodamBooleanValue.class.isAssignableFrom(annotation.getClass())) { PodamBooleanValue localStrategy = (PodamBooleanValue) annotation; retValue = localStrategy.boolValue(); break; } } return retValue; } private Byte getByteValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Byte retValue = null; for (Annotation annotation : annotations) { if (PodamByteValue.class.isAssignableFrom(annotation.getClass())) { PodamByteValue intStrategy = (PodamByteValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Byte.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a byte type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { byte minValue = intStrategy.minValue(); byte maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getByteInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Short getShortValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Short retValue = null; for (Annotation annotation : annotations) { if (PodamShortValue.class.isAssignableFrom(annotation.getClass())) { PodamShortValue shortStrategy = (PodamShortValue) annotation; String numValueStr = shortStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Short.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = "The precise value: " + numValueStr + " cannot be converted to a short type. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { short minValue = shortStrategy.minValue(); short maxValue = shortStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getShortInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It creates and returns a random {@link Character} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * @return A random {@link Character} value */ private Character getCharacterValueWithinRange( List<Annotation> annotations, AttributeMetadata attributeMetadata) { Character retValue = null; for (Annotation annotation : annotations) { if (PodamCharValue.class.isAssignableFrom(annotation.getClass())) { PodamCharValue annotationStrategy = (PodamCharValue) annotation; char charValue = annotationStrategy.charValue(); if (charValue != ' ') { retValue = charValue; } else { char minValue = annotationStrategy.minValue(); char maxValue = annotationStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getCharacterInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Integer getIntegerValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Integer retValue = null; for (Annotation annotation : annotations) { if (PodamIntValue.class.isAssignableFrom(annotation.getClass())) { PodamIntValue intStrategy = (PodamIntValue) annotation; String numValueStr = intStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Integer.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to an Integer. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { int minValue = intStrategy.minValue(); int maxValue = intStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getIntegerInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Float getFloatValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Float retValue = null; for (Annotation annotation : annotations) { if (PodamFloatValue.class.isAssignableFrom(annotation.getClass())) { PodamFloatValue floatStrategy = (PodamFloatValue) annotation; String numValueStr = floatStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Float.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Float. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { float minValue = floatStrategy.minValue(); float maxValue = floatStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getFloatInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It creates and returns a random {@link Double} value * * @param annotations * The list of annotations which might customise the return value * * @param attributeMetadata * The attribute's metadata, if any, used for customisation * * * @return a random {@link Double} value */ private Double getDoubleValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Double retValue = null; for (Annotation annotation : annotations) { if (PodamDoubleValue.class.isAssignableFrom(annotation.getClass())) { PodamDoubleValue doubleStrategy = (PodamDoubleValue) annotation; String numValueStr = doubleStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Double.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Double. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { double minValue = doubleStrategy.minValue(); double maxValue = doubleStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getDoubleInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } private Long getLongValueWithinRange(List<Annotation> annotations, AttributeMetadata attributeMetadata) { Long retValue = null; for (Annotation annotation : annotations) { if (PodamLongValue.class.isAssignableFrom(annotation.getClass())) { PodamLongValue longStrategy = (PodamLongValue) annotation; String numValueStr = longStrategy.numValue(); if (null != numValueStr && !"".equals(numValueStr)) { try { retValue = Long.valueOf(numValueStr); } catch (NumberFormatException nfe) { String errMsg = THE_ANNOTATION_VALUE_STR + numValueStr + " could not be converted to a Long. An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg, nfe); } } else { long minValue = longStrategy.minValue(); long maxValue = longStrategy.maxValue(); // Sanity check if (minValue > maxValue) { maxValue = minValue; } retValue = strategy.getLongInRange(minValue, maxValue, attributeMetadata); } break; } } return retValue; } /** * It attempts to resolve the given class as a wrapper class and if this is * the case it assigns a random value * * * @param candidateWrapperClass * The class which might be a wrapper class * @param attributeMetadata * The attribute's metadata, if any, used for customisation * @return {@code null} if this is not a wrapper class, otherwise an Object * with the value for the wrapper class */ private Object resolveWrapperValue(Class<?> candidateWrapperClass, List<Annotation> annotations, AttributeMetadata attributeMetadata) { Object retValue = null; if (candidateWrapperClass.equals(Integer.class)) { if (!annotations.isEmpty()) { retValue = getIntegerValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getInteger(attributeMetadata); } } else if (candidateWrapperClass.equals(Long.class)) { if (!annotations.isEmpty()) { retValue = getLongValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getLong(attributeMetadata); } } else if (candidateWrapperClass.equals(Float.class)) { if (!annotations.isEmpty()) { retValue = getFloatValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getFloat(attributeMetadata); } } else if (candidateWrapperClass.equals(Double.class)) { if (!annotations.isEmpty()) { retValue = getDoubleValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getDouble(attributeMetadata); } } else if (candidateWrapperClass.equals(Boolean.class)) { if (!annotations.isEmpty()) { retValue = getBooleanValueForAnnotation(annotations); } if (retValue == null) { retValue = strategy.getBoolean(attributeMetadata); } } else if (candidateWrapperClass.equals(Byte.class)) { if (!annotations.isEmpty()) { retValue = getByteValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getByte(attributeMetadata); } } else if (candidateWrapperClass.equals(Short.class)) { if (!annotations.isEmpty()) { retValue = getShortValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getShort(attributeMetadata); } } else if (candidateWrapperClass.equals(Character.class)) { if (!annotations.isEmpty()) { retValue = getCharacterValueWithinRange(annotations, attributeMetadata); } if (retValue == null) { retValue = strategy.getCharacter(attributeMetadata); } } return retValue; } @SuppressWarnings({ UNCHECKED_STR, RAWTYPES_STR }) private <T> T resolvePojoWithoutSetters(Class<T> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { T retValue = null; Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors.length == 0) { retValue = (T) createNewInstanceForClassWithoutConstructors( pojoClass, pojos, pojoClass, genericTypeArgs); } else { // There are public constructors. We want constructor with minumum // number of parameters to speed up the creation strategy.sort(constructors); for (Constructor<?> constructor : constructors) { Object[] parameterValues = getParameterValuesForConstructor( constructor, pojoClass, pojos, genericTypeArgs); // Being a generic method we cannot be sure on the identity of // T, therefore the mismatch between the newInstance() return // value (Object) and T is acceptable, thus the SuppressWarning // annotation try { if (!constructor.isAccessible()) { constructor.setAccessible(true); } retValue = (T) constructor.newInstance(parameterValues); if (retValue instanceof Collection && ((Collection) retValue).isEmpty()) { LOG.info("We could create an instance with constructor: " + constructor + ", but collection is empty" + ". Will try with another one."); } else if (retValue instanceof Map && ((Map) retValue).isEmpty()) { LOG.info("We could create an instance with constructor: " + constructor + ", but map is empty" + ". Will try with another one."); } else { LOG.info("We could create an instance with constructor: " + constructor); break; } } catch (Exception t) { LOG.info("We couldn't create an instance for pojo: " + pojoClass + " for constructor: " + constructor + ". Will try with another one.", t); } } if (retValue == null) { retValue = externalFactory.manufacturePojo(pojoClass, genericTypeArgs); } } return retValue; } @SuppressWarnings(UNCHECKED_STR) private <T> T manufacturePojoInternal(Class<T> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { T retValue = null; // reuse object from memoization table if (strategy.isMemoizationEnabled()) { T objectToReuse = (T) memoizationTable.get(pojoClass); if (objectToReuse != null) { return objectToReuse; } } if (pojoClass.isPrimitive()) { // For JDK POJOs we can't retrieve attribute name List<Annotation> annotations = new ArrayList<Annotation>(); String noName = null; return (T) resolvePrimitiveValue(pojoClass, annotations, new AttributeMetadata(noName, pojoClass, annotations, pojoClass)); } if (pojoClass.isInterface() || Modifier.isAbstract(pojoClass.getModifiers())) { Class<T> specificClass = (Class<T>) strategy .getSpecificClass(pojoClass); if (!specificClass.equals(pojoClass)) { return this.manufacturePojoInternal(specificClass, pojos, genericTypeArgs); } else { if (Modifier.isAbstract(pojoClass.getModifiers())) { return (T) createNewInstanceForClassWithoutConstructors( pojoClass, pojos, pojoClass, genericTypeArgs); } else { return externalFactory.manufacturePojo(pojoClass, genericTypeArgs); } } } // If a public no-arg constructor can be found we use it, // otherwise we try to find a non-public one and we use that. If the // class does not have a no-arg constructor we search for a suitable // constructor. try { Constructor<?>[] constructors = pojoClass.getConstructors(); if (constructors == null || constructors.length == 0) { LOG.warn("No public constructors were found for {}. " + "We'll look for a default, non-public constructor.", pojoClass); Constructor<T> defaultConstructor = pojoClass .getDeclaredConstructor(new Class[] {}); LOG.info("Will use: " + defaultConstructor); // Security hack defaultConstructor.setAccessible(true); retValue = defaultConstructor.newInstance(); } else { retValue = resolvePojoWithoutSetters(pojoClass, pojos, genericTypeArgs); } } catch (SecurityException e) { throw new PodamMockeryException( "Security exception while applying introspection.", e); } catch (NoSuchMethodException e1) { LOG.info( "No default (public or non-public) constructors were found. " + "Also no other public constructors were found. " + "Your last hope is that we find a non-public, non-default constructor.", e1); Constructor<?>[] constructors = pojoClass.getDeclaredConstructors(); if (constructors == null || constructors.length == 0) { throw new IllegalStateException( "The POJO " + pojoClass + " appears without constructors. How is this possible? "); } LOG.info("Will use: " + constructors[0]); // It uses the first public constructor found Object[] parameterValuesForConstructor = getParameterValuesForConstructor( constructors[0], pojoClass, pojos, genericTypeArgs); constructors[0].setAccessible(true); retValue = (T) constructors[0] .newInstance(parameterValuesForConstructor); } // update memoization table with new object // the reference is stored before properties are set so that recursive // properties can use it if (strategy.isMemoizationEnabled()) { memoizationTable.put(pojoClass, retValue); } /* Construction failed, no point to continue */ if (retValue == null) { return null; } if (retValue instanceof Collection && ((Collection<?>)retValue).size() == 0) { fillCollection((Collection<? super Object>)retValue, pojos, genericTypeArgs); } else if (retValue instanceof Map && ((Map<?,?>)retValue).size() == 0) { fillMap((Map<? super Object,? super Object>)retValue, pojos, genericTypeArgs); } Class<?>[] parameterTypes = null; Class<?> attributeType = null; ClassInfo classInfo = PodamUtils.getClassInfo(pojoClass, strategy.getExcludedAnnotations()); // According to JavaBeans standards, setters should have only // one argument Object setterArg = null; for (Method setter : classInfo.getClassSetters()) { List<Annotation> pojoAttributeAnnotations = retrieveFieldAnnotations( pojoClass, setter); String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); parameterTypes = setter.getParameterTypes(); if (parameterTypes.length != 1) { throw new IllegalStateException("A " + pojoClass.getSimpleName() + "." + setter.getName() + "() should have only one argument"); } // A class which has got an attribute to itself (e.g. // recursive hierarchies) attributeType = parameterTypes[0]; // If an attribute has been annotated with // PodamAttributeStrategy, it takes the precedence over any // other strategy. Additionally we don't pass the attribute // metadata for value customisation; if user went to the extent // of specifying a PodamAttributeStrategy annotation for an // attribute they are already customising the value assigned to // that attribute. PodamStrategyValue attributeStrategyAnnotation = containsAttributeStrategyAnnotation(pojoAttributeAnnotations); if (null != attributeStrategyAnnotation) { AttributeStrategy<?> attributeStrategy = attributeStrategyAnnotation .value().newInstance(); if (LOG.isDebugEnabled()) { LOG.debug("The attribute: " + attributeName + " will be filled using the following strategy: " + attributeStrategy); } setterArg = returnAttributeDataStrategyValue(attributeType, attributeStrategy); } else { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } Type[] typeArguments = new Type[] {}; // If the parameter is a generic parameterized type resolve // the actual type arguments if (setter.getGenericParameterTypes()[0] instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) setter .getGenericParameterTypes()[0]; typeArguments = attributeParameterizedType .getActualTypeArguments(); } else if (setter.getGenericParameterTypes()[0] instanceof TypeVariable) { final TypeVariable<?> typeVariable = (TypeVariable<?>) setter .getGenericParameterTypes()[0]; Type type = typeArgsMap.get(typeVariable.getName()); if (type instanceof ParameterizedType) { final ParameterizedType attributeParameterizedType = (ParameterizedType) type; typeArguments = attributeParameterizedType .getActualTypeArguments(); attributeType = (Class<?>) attributeParameterizedType .getRawType(); } else { attributeType = (Class<?>) type; } } AtomicReference<Type[]> typeGenericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); for (int i = 0; i < typeArguments.length; i++) { if (typeArguments[i] instanceof TypeVariable) { Class<?> resolvedType = resolveGenericParameter(typeArguments[i], typeArgsMap, typeGenericTypeArgs); if (!Collection.class.isAssignableFrom(resolvedType) && !Map.class.isAssignableFrom(resolvedType)) { typeArguments[i] = resolvedType; } } } setterArg = manufactureAttributeValue(pojoClass, pojos, attributeType, pojoAttributeAnnotations, attributeName, typeArgsMap, typeArguments); if (null == setterArg) { setterArg = externalFactory.manufacturePojo(attributeType); } } if (setterArg != null) { try { setter.invoke(retValue, setterArg); } catch(IllegalAccessException e) { LOG.warn("{} is not accessible. Setting it to accessible." + " However this is a security hack and your code" + " should really adhere to JavaBeans standards.", setter.toString()); setter.setAccessible(true); setter.invoke(retValue, setterArg); } } else { LOG.warn("Couldn't find a suitable value for attribute {}[{}]" + ". It will be left to null.", pojoClass, attributeType); } } return retValue; } private Object manufactureAttributeValue(Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> attributeType, List<Annotation> annotations, String attributeName, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Map<String, Type> nullTypeArgsMap = new HashMap<String, Type>(); return manufactureAttributeValue(pojoClass, pojos, attributeType, annotations, attributeName, nullTypeArgsMap, genericTypeArgs); } @SuppressWarnings(RAWTYPES_STR) private Object manufactureAttributeValue(Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> attributeType, List<Annotation> annotations, String attributeName, Map<String, Type> typeArgsMap, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object attributeValue = null; Class<?> realAttributeType; if (genericTypeArgs.length > 0 && genericTypeArgs[0] instanceof Class && attributeType.isAssignableFrom((Class) genericTypeArgs[0])) { realAttributeType = (Class) genericTypeArgs[0]; } else { realAttributeType = attributeType; } AttributeMetadata attributeMetadata = new AttributeMetadata( attributeName, realAttributeType, annotations, pojoClass); // Primitive type if (realAttributeType.isPrimitive()) { attributeValue = resolvePrimitiveValue(realAttributeType, annotations, attributeMetadata); // Wrapper type } else if (isWrapper(realAttributeType)) { attributeValue = resolveWrapperValue(realAttributeType, annotations, attributeMetadata); // String type } else if (realAttributeType.equals(String.class)) { attributeValue = resolveStringValue(annotations, attributeMetadata); } else if (realAttributeType.getName().startsWith("[")) { // Array type attributeValue = resolveArrayElementValue(realAttributeType, pojos, annotations, pojoClass, attributeName, typeArgsMap); // Otherwise it's a different type of Object (including // the Object class) } else if (Collection.class.isAssignableFrom(realAttributeType)) { // Collection type try { attributeValue = resolveCollectionValueWhenCollectionIsPojoAttribute( pojoClass, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } catch(IllegalArgumentException e) { LOG.info("Cannot manufacture list {}, will try strategy", realAttributeType); } } else if (Map.class.isAssignableFrom(realAttributeType)) { // Map type try { attributeValue = resolveMapValueWhenMapIsPojoAttribute(pojoClass, pojos, realAttributeType, attributeName, annotations, typeArgsMap, genericTypeArgs); } catch(IllegalArgumentException e) { LOG.info("Cannot manufacture map {}, will try strategy", realAttributeType); } } else if (realAttributeType.isEnum()) { // Enum type int enumConstantsLength = realAttributeType.getEnumConstants().length; if (enumConstantsLength > 0) { int enumIndex = strategy.getIntegerInRange(0, enumConstantsLength, attributeMetadata) % enumConstantsLength; attributeValue = realAttributeType.getEnumConstants()[enumIndex]; } } else if (Type.class.isAssignableFrom(realAttributeType)) { if (genericTypeArgs.length > 0 && genericTypeArgs[0] != null) { AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>(new Type[] {}); attributeValue = resolveGenericParameter(genericTypeArgs[0], typeArgsMap, elementGenericTypeArgs); } else { LOG.error("{} is missing generic type argument", realAttributeType); } } // For any other type, we use the PODAM strategy if (attributeValue == null) { Integer depth = pojos.get(realAttributeType); if (depth == null) { depth = -1; } if (depth <= strategy.getMaxDepth(pojoClass)) { pojos.put(realAttributeType, depth + 1); attributeValue = this.manufacturePojoInternal( realAttributeType, pojos, genericTypeArgs); pojos.put(realAttributeType, depth); } else { LOG.warn("Loop in {} production detected.", realAttributeType); attributeValue = externalFactory.manufacturePojo( realAttributeType, genericTypeArgs); } } return attributeValue; } private String resolveStringValue(List<Annotation> annotations, AttributeMetadata attributeMetadata) throws InstantiationException, IllegalAccessException { String retValue = null; if (annotations == null || annotations.isEmpty()) { retValue = strategy.getStringValue(attributeMetadata); } else { for (Annotation annotation : annotations) { if (!PodamStringValue.class.isAssignableFrom(annotation .getClass())) { continue; } // A specific value takes precedence over the length PodamStringValue podamAnnotation = (PodamStringValue) annotation; if (podamAnnotation.strValue() != null && podamAnnotation.strValue().length() > 0) { retValue = podamAnnotation.strValue(); } else { retValue = strategy.getStringOfLength( podamAnnotation.length(), attributeMetadata); } } if (retValue == null) { retValue = strategy.getStringValue(attributeMetadata); } } return retValue; } /** * It returns an default value for a {@link Field} matching the attribute * name or null if a field was not found. * * @param pojoClass * The class supposed to contain the field * @param attributeName * The field name * * @return an instance of {@link Field} matching the attribute name or * null if a field was not found. */ private <T> T getDefaultFieldValue(Class<?> pojoClass, String attributeName) { T retValue = null; try { Field field = getField(pojoClass, attributeName); if (field == null) { throw new NoSuchFieldException( "It was not possible to retrieve field: " + attributeName); } // It allows to invoke Field.get on private fields field.setAccessible(true); // TODO: we probably already have instantiated the pojoClass, // it will be better to pass pojoInstance instead of pojoClass Object newInstance = pojoClass.newInstance(); retValue = (T) field.get(newInstance); } catch (Exception e) { LOG.info( "The field didn't exist or we couldn't call an empty constructor.", e); } return retValue; } /** * It returns a {@link Field} matching the attribute name or null if a field * was not found. * * @param pojoClass * The class supposed to contain the field * @param attributeName * The field name * * @return a {@link Field} matching the attribute name or null if a field * was not found. */ private Field getField(Class<?> pojoClass, String attributeName) { Field field = null; Class<?> clazz = pojoClass; while (clazz != null) { try { field = clazz.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { LOG.info("A field could not be found for attribute name: " + attributeName, e); clazz = clazz.getSuperclass(); } } return field; } /** * It returns a {@link PodamStrategyValue} if one was specified, or * {@code null} otherwise. * * @param annotations * The list of annotations * @return {@code true} if the list of annotations contains at least one * {@link PodamStrategyValue} annotation. */ private PodamStrategyValue containsAttributeStrategyAnnotation( List<Annotation> annotations) { PodamStrategyValue retValue = null; for (Annotation annotation : annotations) { if (PodamStrategyValue.class .isAssignableFrom(annotation.getClass())) { retValue = (PodamStrategyValue) annotation; break; } } return retValue; } /** * It returns {@code true} if this class is a wrapper class, {@code false} * otherwise * * @param candidateWrapperClass * The class to check * @return {@code true} if this class is a wrapper class, {@code false} * otherwise */ private boolean isWrapper(Class<?> candidateWrapperClass) { return candidateWrapperClass.equals(Byte.class) ? true : candidateWrapperClass.equals(Boolean.class) ? true : candidateWrapperClass.equals(Character.class) ? true : candidateWrapperClass.equals(Short.class) ? true : candidateWrapperClass .equals(Integer.class) ? true : candidateWrapperClass .equals(Long.class) ? true : candidateWrapperClass .equals(Float.class) ? true : candidateWrapperClass .equals(Double.class) ? true : false; } /** * Given the original class and the setter method, it returns all * annotations for the field or an empty collection if no custom annotations * were found on the field * * @param clazz * The class containing the annotated attribute * @param setter * The setter method * @return all annotations for the field * @throws NoSuchFieldException * If the field could not be found * @throws SecurityException * if a security exception occurred */ private List<Annotation> retrieveFieldAnnotations(Class<?> clazz, Method setter) { Class<?> workClass = clazz; List<Annotation> retValue = new ArrayList<Annotation>(); // Checks if the field has got any custom annotations String attributeName = PodamUtils .extractFieldNameFromSetterMethod(setter); Field setterField = null; while (workClass != null) { try { setterField = workClass.getDeclaredField(attributeName); break; } catch (NoSuchFieldException e) { LOG.info( "A field for " + attributeName + " could not be found", e); workClass = workClass.getSuperclass(); } } if (setterField != null) { Annotation[] annotations = setterField.getAnnotations(); if (annotations != null && annotations.length != 0) { retValue = Arrays.asList(annotations); } } return retValue; } private Collection<? super Object> resolveCollectionValueWhenCollectionIsPojoAttribute( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> collectionType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { // This needs to be generic because collections can be of any type Collection<? super Object> retValue = getDefaultFieldValue(pojoClass, attributeName); if (null == retValue) { retValue = resolveCollectionType(collectionType); } try { Class<?> typeClass = null; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("The collection attribute: " + attributeName + " does not have a type. We will assume Object for you"); // Support for non-generified collections typeClass = Object.class; } else { Type actualTypeArgument = genericTypeArgs[0]; typeClass = resolveGenericParameter(actualTypeArgument, typeArgsMap, elementGenericTypeArgs); } fillCollection(pojoClass, pojos, attributeName, annotations, retValue, typeClass, elementGenericTypeArgs.get()); } catch (SecurityException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalArgumentException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InstantiationException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, e); } return retValue; } private void fillCollection(Collection<? super Object> collection, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Class<?> pojoClass = collection.getClass(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null && genericTypeArgsExtra.length > 0) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } String attributeName = null; Annotation[] annotations = collection.getClass().getAnnotations(); Class<?> collectionClass = pojoClass; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); Type[] typeParams = collectionClass.getTypeParameters(); while (typeParams.length < 1) { Type type = collectionClass.getGenericSuperclass(); collectionClass = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); typeParams = elementGenericTypeArgs.get(); } Class<?> elementTypeClass = resolveGenericParameter(typeParams[0], typeArgsMap, elementGenericTypeArgs); fillCollection(pojoClass, pojos, attributeName, Arrays.asList(annotations), collection, elementTypeClass, elementGenericTypeArgs.get()); } private void fillCollection(Class<?> pojoClass, Map<Class<?>, Integer> pojos, String attributeName, List<Annotation> annotations, Collection<? super Object> collection, Class<?> collectionElementType, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements = strategy .getNumberOfCollectionElements(collectionElementType); if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); elementStrategy = collectionAnnotation.collectionElementStrategy() .newInstance(); } for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass()) && Object.class.equals(collectionElementType)) { LOG.debug("Element strategy is ObjectStrategy and collection element is of type Object: using the ObjectStrategy strategy"); collection.add(elementStrategy.getValue()); } else if (null != elementStrategy && !ObjectStrategy.class.isAssignableFrom(elementStrategy .getClass())) { LOG.debug("Collection elements will be filled using the following strategy: " + elementStrategy); Object strategyValue = returnAttributeDataStrategyValue( collectionElementType, elementStrategy); collection.add(strategyValue); } else { collection.add(manufactureAttributeValue(pojoClass, pojos, collectionElementType, annotations, attributeName, genericTypeArgs)); } } } private Map<? super Object, ? super Object> resolveMapValueWhenMapIsPojoAttribute( Class<?> pojoClass, Map<Class<?>, Integer> pojos, Class<?> attributeType, String attributeName, List<Annotation> annotations, Map<String, Type> typeArgsMap, Type... genericTypeArgs) { Map<? super Object, ? super Object> retValue = getDefaultFieldValue(pojoClass, attributeName); if (null == retValue) { retValue = resolveMapType(attributeType); } try { Class<?> keyClass = null; Class<?> elementClass = null; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (genericTypeArgs == null || genericTypeArgs.length == 0) { LOG.warn("Map attribute: " + attributeName + " is non-generic. We will assume a Map<Object, Object> for you."); keyClass = Object.class; elementClass = Object.class; } else { // Expected only key, value type if (genericTypeArgs.length != 2) { throw new IllegalStateException( "In a Map only key value generic type are expected."); } Type[] actualTypeArguments = genericTypeArgs; keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter(actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } MapArguments mapArguments = new MapArguments(); mapArguments.setPojoClass(pojoClass); mapArguments.setPojos(pojos); mapArguments.setAttributeName(attributeName); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(retValue); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments .setElementGenericTypeArgs(elementGenericTypeArgs.get()); fillMap(mapArguments); } catch (InstantiationException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (IllegalAccessException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (SecurityException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (ClassNotFoundException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } catch (InvocationTargetException e) { throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); } return retValue; } private void fillMap(Map<? super Object, ? super Object> map, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Class<?> pojoClass = map.getClass(); Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); if (genericTypeArgsExtra != null && genericTypeArgsExtra.length > 0) { LOG.warn("Lost generic type arguments {}", Arrays.toString(genericTypeArgsExtra)); } Annotation[] annotations = pojoClass.getAnnotations(); String attributeName = null; Class<?> mapClass = pojoClass; AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); Type[] typeParams = mapClass.getTypeParameters(); while (typeParams.length < 2) { Type type = mapClass.getGenericSuperclass(); mapClass = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); typeParams = elementGenericTypeArgs.get(); } AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); Class<?> keyClass = resolveGenericParameter(typeParams[0], typeArgsMap, keyGenericTypeArgs); Class<?> elementClass = resolveGenericParameter(typeParams[1], typeArgsMap, elementGenericTypeArgs); MapArguments mapArguments = new MapArguments(); mapArguments.setPojoClass(pojoClass); mapArguments.setPojos(pojos); mapArguments.setAttributeName(attributeName); mapArguments.setAnnotations(Arrays.asList(annotations)); mapArguments.setMapToBeFilled(map); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments .setElementGenericTypeArgs(elementGenericTypeArgs.get()); fillMap(mapArguments); } private void fillMap(MapArguments mapArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> keyStrategy = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : mapArguments.getAnnotations()) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements = strategy.getNumberOfCollectionElements(mapArguments .getElementClass()); if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); keyStrategy = collectionAnnotation.mapKeyStrategy().newInstance(); elementStrategy = collectionAnnotation.mapElementStrategy() .newInstance(); } for (int i = 0; i < nbrElements; i++) { Object keyValue = null; Object elementValue = null; MapKeyOrElementsArguments valueArguments = new MapKeyOrElementsArguments(); valueArguments.setPojoClass(mapArguments.getPojoClass()); valueArguments.setPojos(mapArguments.getPojos()); valueArguments.setAttributeName(mapArguments.getAttributeName()); valueArguments.setAnnotations(mapArguments.getAnnotations()); valueArguments.setKeyOrValueType(mapArguments.getKeyClass()); valueArguments.setElementStrategy(keyStrategy); valueArguments.setGenericTypeArgs(mapArguments .getKeyGenericTypeArgs()); keyValue = getMapKeyOrElementValue(valueArguments); valueArguments = new MapKeyOrElementsArguments(); valueArguments.setPojoClass(mapArguments.getPojoClass()); valueArguments.setPojos(mapArguments.getPojos()); valueArguments.setAttributeName(mapArguments.getAttributeName()); valueArguments.setAnnotations(mapArguments.getAnnotations()); valueArguments.setKeyOrValueType(mapArguments.getElementClass()); valueArguments.setElementStrategy(elementStrategy); valueArguments.setGenericTypeArgs(mapArguments .getElementGenericTypeArgs()); elementValue = getMapKeyOrElementValue(valueArguments); Map<? super Object, ? super Object> map = mapArguments.getMapToBeFilled(); /* ConcurrentHashMap doesn't allow null values */ if (elementValue != null || !(map instanceof ConcurrentHashMap)) { map.put(keyValue, elementValue); } } } private Object getMapKeyOrElementValue( MapKeyOrElementsArguments keyOrElementsArguments) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Object retValue = null; if (null != keyOrElementsArguments.getElementStrategy() && ObjectStrategy.class.isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass()) && Object.class.equals(keyOrElementsArguments .getKeyOrValueType())) { LOG.debug("Element strategy is ObjectStrategy and Map key or value type is of type Object: using the ObjectStrategy strategy"); retValue = keyOrElementsArguments.getElementStrategy().getValue(); } else if (null != keyOrElementsArguments.getElementStrategy() && !ObjectStrategy.class .isAssignableFrom(keyOrElementsArguments .getElementStrategy().getClass())) { LOG.debug("Map key or value will be filled using the following strategy: " + keyOrElementsArguments.getElementStrategy()); retValue = returnAttributeDataStrategyValue( keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getElementStrategy()); } else { retValue = manufactureAttributeValue( keyOrElementsArguments.getPojoClass(), keyOrElementsArguments.getPojos(), keyOrElementsArguments.getKeyOrValueType(), keyOrElementsArguments.getAnnotations(), keyOrElementsArguments.getAttributeName(), keyOrElementsArguments.getGenericTypeArgs()); } return retValue; } private Object resolveArrayElementValue(Class<?> attributeType, Map<Class<?>, Integer> pojos, List<Annotation> annotations, Class<?> pojoClass, String attributeName, Map<String, Type> typeArgsMap) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { Class<?> componentType = attributeType.getComponentType(); AtomicReference<Type[]> genericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (null != attributeName) { try { final Type genericType = pojoClass.getDeclaredField( attributeName).getGenericType(); if (genericType instanceof GenericArrayType) { final Type type = ((GenericArrayType) genericType) .getGenericComponentType(); if (type instanceof TypeVariable<?>) { final Type typeVarType = typeArgsMap .get(((TypeVariable<?>) type).getName()); componentType = resolveGenericParameter(typeVarType, typeArgsMap, genericTypeArgs); } } } catch (NoSuchFieldException e) { LOG.info("Cannot get the declared field type for field " + attributeName + " of class " + pojoClass.getName(), e); } } // If the user defined a strategy to fill the collection elements, // we use it PodamCollection collectionAnnotation = null; AttributeStrategy<?> elementStrategy = null; for (Annotation annotation : annotations) { if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { collectionAnnotation = (PodamCollection) annotation; break; } } int nbrElements; if (null != collectionAnnotation) { nbrElements = collectionAnnotation.nbrElements(); elementStrategy = collectionAnnotation.collectionElementStrategy() .newInstance(); } else { nbrElements = strategy.getNumberOfCollectionElements(attributeType); } Object arrayElement = null; Object array = Array.newInstance(componentType, nbrElements); for (int i = 0; i < nbrElements; i++) { // The default if (null != elementStrategy && ObjectStrategy.class .isAssignableFrom(collectionAnnotation .collectionElementStrategy()) && Object.class.equals(componentType)) { LOG.debug("Element strategy is ObjectStrategy and array element is of type Object: using the ObjectStrategy strategy"); arrayElement = elementStrategy.getValue(); } else if (null != elementStrategy && !ObjectStrategy.class .isAssignableFrom(collectionAnnotation .collectionElementStrategy())) { LOG.debug("Array elements will be filled using the following strategy: " + elementStrategy); arrayElement = returnAttributeDataStrategyValue(componentType, elementStrategy); } else { arrayElement = manufactureAttributeValue(pojoClass, pojos, componentType, annotations, attributeName, typeArgsMap, genericTypeArgs.get()); } Array.set(array, i, arrayElement); } return array; } /** * Given a collection type it returns an instance * <p> * <ul> * <li>The default type for a {@link List} is an {@link ArrayList}</li> * <li>The default type for a {@link Queue} is a {@link LinkedList}</li> * <li>The default type for a {@link Set} is a {@link HashSet}</li> * </ul> * * </p> * * @param collectionType * The collection type * * @return an instance of the collection type */ @SuppressWarnings({ RAWTYPES_STR, UNCHECKED_STR }) private Collection<? super Object> resolveCollectionType( Class<?> collectionType) { Collection<? super Object> retValue = null; // Default list and set are ArrayList and HashSet. If users // wants a particular collection flavour they have to initialise // the collection if (Queue.class.isAssignableFrom(collectionType)) { if (collectionType.isAssignableFrom(LinkedList.class)) { retValue = new LinkedList(); } } else if (Set.class.isAssignableFrom(collectionType)) { if (collectionType.isAssignableFrom(HashSet.class)) { retValue = new HashSet(); } } else { if (collectionType.isAssignableFrom(ArrayList.class)) { retValue = new ArrayList(); } } if (null == retValue) { throw new IllegalArgumentException("Collection type: " + collectionType + " not supported"); } return retValue; } /** * It manufactures and returns a default instance for each map type * * <p> * The default implementation for a {@link ConcurrentMap} is * {@link ConcurrentHashMap} * </p> * * <p> * The default implementation for a {@link SortedMap} is a {@link TreeMap} * </p> * * <p> * The default Map is none of the above was recognised is a {@link HashMap} * </p> * * @param mapType * The attribute type implementing Map * @return A default instance for each map type * */ @SuppressWarnings({ UNCHECKED_STR, RAWTYPES_STR }) private Map<? super Object, ? super Object> resolveMapType( Class<?> mapType) { Map<? super Object, ? super Object> retValue = null; if (SortedMap.class.isAssignableFrom(mapType)) { if (mapType.isAssignableFrom(TreeMap.class)) { retValue = new TreeMap(); } } else if (ConcurrentMap.class.isAssignableFrom(mapType)) { if (mapType.isAssignableFrom(ConcurrentHashMap.class)) { retValue = new ConcurrentHashMap(); } } else { if (mapType.isAssignableFrom(HashMap.class)) { retValue = new HashMap(); } } if (null == retValue) { throw new IllegalArgumentException("Map type: " + mapType + " not supported"); } return retValue; } private Object[] getParameterValuesForConstructor( Constructor<?> constructor, Class<?> pojoClass, Map<Class<?>, Integer> pojos, Type... genericTypeArgs) throws InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException { final Map<String, Type> typeArgsMap = new HashMap<String, Type>(); Type[] genericTypeArgsExtra = null; genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, genericTypeArgs); Annotation[][] parameterAnnotations = constructor .getParameterAnnotations(); Object[] parameterValues = new Object[constructor.getParameterTypes().length]; // Found a constructor with @PodamConstructor annotation Class<?>[] parameterTypes = constructor.getParameterTypes(); int idx = 0; for (Class<?> parameterType : parameterTypes) { List<Annotation> annotations = Arrays .asList(parameterAnnotations[idx]); String attributeName = null; if (Collection.class.isAssignableFrom(parameterType)) { Collection<? super Object> collection = resolveCollectionType(parameterType); Type type = constructor.getGenericParameterTypes()[idx]; Class<?> collectionElementType; AtomicReference<Type[]> collectionGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type actualTypeArgument = pType.getActualTypeArguments()[0]; collectionElementType = resolveGenericParameter( actualTypeArgument, typeArgsMap, collectionGenericTypeArgs); } else { LOG.warn("Collection parameter {} type is non-generic." + "We will assume a Collection<Object> for you.", type); collectionElementType = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( collectionGenericTypeArgs.get(), genericTypeArgsExtra); fillCollection(pojoClass, pojos, attributeName, annotations, collection, collectionElementType, genericTypeArgsAll); parameterValues[idx] = collection; } else if (Map.class.isAssignableFrom(parameterType)) { Map<? super Object, ? super Object> mapType = resolveMapType(parameterType); Type type = constructor.getGenericParameterTypes()[idx]; Class<?> keyClass; Class<?> elementClass; AtomicReference<Type[]> keyGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); AtomicReference<Type[]> elementGenericTypeArgs = new AtomicReference<Type[]>( new Type[] {}); if (type instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) type; Type[] actualTypeArguments = pType.getActualTypeArguments(); keyClass = resolveGenericParameter(actualTypeArguments[0], typeArgsMap, keyGenericTypeArgs); elementClass = resolveGenericParameter( actualTypeArguments[1], typeArgsMap, elementGenericTypeArgs); } else { LOG.warn("Map parameter {} type is non-generic." + "We will assume a Map<Object,Object> for you.", type); keyClass = Object.class; elementClass = Object.class; } Type[] genericTypeArgsAll = mergeTypeArrays( elementGenericTypeArgs.get(), genericTypeArgsExtra); MapArguments mapArguments = new MapArguments(); mapArguments.setPojoClass(pojoClass); mapArguments.setPojos(pojos); mapArguments.setAttributeName(attributeName); mapArguments.setAnnotations(annotations); mapArguments.setMapToBeFilled(mapType); mapArguments.setKeyClass(keyClass); mapArguments.setElementClass(elementClass); mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); mapArguments.setElementGenericTypeArgs(genericTypeArgsAll); fillMap(mapArguments); parameterValues[idx] = mapType; } else { parameterValues[idx] = manufactureAttributeValue(pojoClass, pojos, parameterType, annotations, attributeName, typeArgsMap, genericTypeArgs); } idx++; } return parameterValues; } /** * Utility method to merge two arrays * * @param original * The main array * @param extra * The additional array, optionally may be null * @return A merged array of original and extra arrays */ private Type[] mergeTypeArrays(Type[] original, Type[] extra) { Type[] merged; if (extra != null) { merged = new Type[original.length + extra.length]; System.arraycopy(original, 0, merged, 0, original.length); System.arraycopy(extra, 0, merged, original.length, extra.length); } else { merged = original; } return merged; } private Object returnAttributeDataStrategyValue(Class<?> attributeType, AttributeStrategy<?> attributeStrategy) throws InstantiationException, IllegalAccessException { Object retValue = null; Method attributeStrategyMethod = null; try { attributeStrategyMethod = attributeStrategy.getClass().getMethod( PodamConstants.PODAM_ATTRIBUTE_STRATEGY_METHOD_NAME, new Class<?>[] {}); if (!attributeType.isAssignableFrom(attributeStrategyMethod .getReturnType())) { String errMsg = "The type of the Podam Attribute Strategy is not " + attributeType.getName() + " but " + attributeStrategyMethod.getReturnType().getName() + ". An exception will be thrown."; LOG.error(errMsg); throw new IllegalArgumentException(errMsg); } retValue = attributeStrategy.getValue(); } catch (SecurityException e) { throw new IllegalStateException( "A security issue occurred while retrieving the Podam Attribute Strategy details", e); } catch (NoSuchMethodException e) { throw new IllegalStateException( "It seems the Podam Attribute Annotation is of the wrong type", e); } return retValue; } }
package com.syncleus.dann.visualization; import com.sun.j3d.utils.behaviors.mouse.MouseWheelZoom; import com.sun.j3d.utils.behaviors.vp.OrbitBehavior; import com.sun.j3d.utils.universe.SimpleUniverse; import com.syncleus.dann.associativemap.AssociativeMap; import java.awt.GraphicsConfiguration; import javax.media.j3d.*; import javax.vecmath.*; public class AssociativeMapCanvas extends Canvas3D { private static final long serialVersionUID = 1L; private AssociativeMapVisualization mapVisual; public AssociativeMapCanvas(AssociativeMap map) { this(map, SimpleUniverse.getPreferredConfiguration()); } public AssociativeMap getAssociativeMap() { return this.mapVisual.getMap(); } public AssociativeMapCanvas(AssociativeMap map, GraphicsConfiguration configuration) { super(configuration); BranchGroup root = createRoot(); this.mapVisual = new AssociativeMapVisualization(map); this.mapVisual.refresh(); root.addChild(mapVisual); SimpleUniverse universe = new SimpleUniverse(this); universe.addBranchGraph(root); // Set the initial view position TransformGroup viewTransformGroup = universe.getViewingPlatform().getViewPlatformTransform(); Transform3D viewTransform = new Transform3D(); viewTransform.set(1f, new Vector3f(0f, 0f, 10f)); viewTransformGroup.setTransform(viewTransform); // add an orbital mouse control to the scene OrbitBehavior mouseOrbital = new OrbitBehavior(this); mouseOrbital.setRotationCenter(new Point3d(0f, 0f, -2f)); mouseOrbital.setReverseRotate(true); mouseOrbital.setSchedulingBounds(new BoundingSphere(new Point3d(0.0, 0.0, 0.0), Double.POSITIVE_INFINITY)); universe.getViewingPlatform().setViewPlatformBehavior(mouseOrbital); } public void refresh() { this.mapVisual.refresh(); } private static BranchGroup createRoot() { // Create the branch group BranchGroup branchGroup = new BranchGroup(); // Create the bounding leaf node BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 1000.0); BoundingLeaf boundingLeaf = new BoundingLeaf(bounds); branchGroup.addChild(boundingLeaf); // Create the background Background bg = new Background(new Color3f(0.05f, 0.05f, 0.2f)); bg.setApplicationBounds(bounds); branchGroup.addChild(bg); // Create the ambient light AmbientLight ambLight = new AmbientLight(new Color3f(1.0f, 1.0f, 1.0f)); ambLight.setInfluencingBounds(bounds); branchGroup.addChild(ambLight); // Create the directional light Vector3f dir = new Vector3f(-1f, -1f, -1f); DirectionalLight dirLight = new DirectionalLight(new Color3f(1.0f, 1.0f, 1.0f), dir); dirLight.setInfluencingBounds(bounds); branchGroup.addChild(dirLight); return branchGroup; } }
package yokohama.unit.translator; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import lombok.NonNull; import lombok.SneakyThrows; import org.apache.commons.collections4.ListUtils; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import yokohama.unit.ast.Assertion; import yokohama.unit.ast.Definition; import yokohama.unit.ast.EqualToMatcher; import yokohama.unit.ast.Execution; import yokohama.unit.ast.FourPhaseTest; import yokohama.unit.ast.Group; import yokohama.unit.ast.Ident; import yokohama.unit.ast.InstanceOfMatcher; import yokohama.unit.ast.InstanceSuchThatMatcher; import yokohama.unit.ast.IsNotPredicate; import yokohama.unit.ast.IsPredicate; import yokohama.unit.ast.LetBindings; import yokohama.unit.ast.Matcher; import yokohama.unit.ast.MatcherVisitor; import yokohama.unit.ast.NullValueMatcher; import yokohama.unit.ast.Phase; import yokohama.unit.ast.Position; import yokohama.unit.ast.Predicate; import yokohama.unit.ast.PredicateVisitor; import yokohama.unit.ast.Proposition; import yokohama.unit.ast.Row; import yokohama.unit.ast.Table; import yokohama.unit.ast.TableExtractVisitor; import yokohama.unit.ast.TableRef; import yokohama.unit.ast.Test; import yokohama.unit.ast.ThrowsPredicate; import yokohama.unit.ast_junit.CatchClause; import yokohama.unit.ast_junit.ClassDecl; import yokohama.unit.ast_junit.ClassType; import yokohama.unit.ast_junit.CompilationUnit; import yokohama.unit.ast_junit.ConjunctionMatcherExpr; import yokohama.unit.ast_junit.EqualToMatcherExpr; import yokohama.unit.ast_junit.InstanceOfMatcherExpr; import yokohama.unit.ast_junit.InvokeStaticExpr; import yokohama.unit.ast_junit.IsStatement; import yokohama.unit.ast_junit.NonArrayType; import yokohama.unit.ast_junit.NullExpr; import yokohama.unit.ast_junit.NullValueMatcherExpr; import yokohama.unit.ast_junit.PrimitiveType; import yokohama.unit.ast_junit.ReturnIsNotStatement; import yokohama.unit.ast_junit.ReturnIsStatement; import yokohama.unit.ast_junit.Span; import yokohama.unit.ast_junit.TestMethod; import yokohama.unit.ast_junit.Statement; import yokohama.unit.ast_junit.SuchThatMatcherExpr; import yokohama.unit.ast_junit.TryStatement; import yokohama.unit.ast_junit.Type; import yokohama.unit.ast_junit.VarInitStatement; import yokohama.unit.ast_junit.Var; import yokohama.unit.ast_junit.VarExpr; import yokohama.unit.util.GenSym; import yokohama.unit.util.Pair; import yokohama.unit.util.SUtils; public class AstToJUnitAst { private final Optional<Path> docyPath; private final String className; private final String packageName; ExpressionStrategy expressionStrategy; MockStrategy mockStrategy; AstToJUnitAst( Optional<Path> docyPath, String className, String packageName, ExpressionStrategy expressionStrategy, MockStrategy mockStrategy) { this.docyPath = docyPath; this.className = className; this.packageName = packageName; this.expressionStrategy = expressionStrategy; this.mockStrategy = mockStrategy; } TableExtractVisitor tableExtractVisitor = new TableExtractVisitor(); Span spanOf(yokohama.unit.ast.Span span) { return new Span(docyPath, span.getStart(), span.getEnd()); } public CompilationUnit translate(String name, Group group, @NonNull String packageName) { List<Definition> definitions = group.getDefinitions(); final List<Table> tables = tableExtractVisitor.extractTables(group); List<TestMethod> methods = definitions.stream() .flatMap(definition -> definition.accept( test -> translateTest(test, tables).stream(), fourPhaseTest -> translateFourPhaseTest(fourPhaseTest, tables, new GenSym()).stream(), table -> Stream.empty())) .collect(Collectors.toList()); ClassDecl classDecl = new ClassDecl(name, methods); return new CompilationUnit(packageName, classDecl); } List<TestMethod> translateTest(Test test, final List<Table> tables) { final String name = test.getName(); List<Assertion> assertions = test.getAssertions(); List<TestMethod> testMethods = IntStream.range(0, assertions.size()) .mapToObj(Integer::new) .flatMap(i -> translateAssertion(assertions.get(i), i + 1, name, tables).stream()) .collect(Collectors.toList()); return testMethods; } List<TestMethod> translateAssertion(Assertion assertion, int index, String testName, List<Table> tables) { String methodName = SUtils.toIdent(testName) + "_" + index; List<Proposition> propositions = assertion.getPropositions(); return assertion.getFixture().accept( () -> { GenSym genSym = new GenSym(); String env = genSym.generate("env"); return Arrays.asList( new TestMethod( methodName, ListUtils.union( expressionStrategy.env(env), propositions.stream() .flatMap(proposition -> translateProposition( proposition, genSym, env)) .collect(Collectors.toList())))); }, tableRef -> { GenSym genSym = new GenSym(); String env = genSym.generate("env"); List<List<Statement>> table = translateTableRef(tableRef, tables, genSym, env); return IntStream.range(0, table.size()) .mapToObj(Integer::new) .map(i -> { return new TestMethod( methodName + "_" + (i + 1), ListUtils.union( expressionStrategy.env(env), ListUtils.union( table.get(i), propositions .stream() .flatMap(proposition -> translateProposition( proposition, genSym, env)) .collect(Collectors.toList())))); }) .collect(Collectors.toList()); }, bindings -> { GenSym genSym = new GenSym(); String env = genSym.generate("env"); return Arrays.asList( new TestMethod( methodName, ListUtils.union( expressionStrategy.env(env), Stream.concat( bindings.getBindings() .stream() .flatMap(binding -> translateBinding( binding, genSym, env)), propositions.stream() .flatMap(proposition -> translateProposition( proposition, genSym, env))) .collect(Collectors.toList())))); }); } Stream<Statement> translateProposition(Proposition proposition, GenSym genSym, String envVarName) { String actual = genSym.generate("actual"); String expected = genSym.generate("expected"); Predicate predicate = proposition.getPredicate(); Stream<Statement> subjectAndPredicate = predicate.<Stream<Statement>>accept( isPredicate -> { return Stream.concat( expressionStrategy.eval( actual, envVarName, proposition.getSubject(), genSym, docyPath, className, packageName).stream(), translateMatcher(isPredicate.getComplement(), expected, genSym, envVarName)); }, isNotPredicate -> { // inhibit `is not instance e of Exception such that...` isNotPredicate.getComplement().accept( equalTo -> null, instanceOf -> null, instanceSuchThat -> { throw new TranslationException( spanOf(instanceSuchThat.getSpan()).toString() + ": " + "`instance _ of _ such that` cannot follow `is not`"); }, nullValue -> null); String unexpected = genSym.generate("unexpected"); return Stream.concat( expressionStrategy.eval( actual, envVarName, proposition.getSubject(), genSym, docyPath, className, packageName).stream(), Stream.concat( translateMatcher(isNotPredicate.getComplement(), unexpected, genSym, envVarName), Stream.of(new VarInitStatement( Type.MATCHER, expected, new InvokeStaticExpr( new ClassType("org.hamcrest.CoreMatchers", Span.dummySpan()), Arrays.asList(), "not", Arrays.asList(Type.MATCHER), Arrays.asList(new Var(unexpected)), Type.MATCHER), spanOf(predicate.getSpan()))))); }, throwsPredicate -> { String __ = genSym.generate("tmp"); return Stream.concat( bindThrown( actual, expressionStrategy.eval( __, envVarName, proposition.getSubject(), genSym, docyPath, className, packageName), genSym, envVarName), translateMatcher(throwsPredicate.getThrowee(), expected, genSym, envVarName)); } ); return Stream.concat( subjectAndPredicate, Stream.of(new IsStatement(new Var(actual), new Var(expected), spanOf(predicate.getSpan())))); } Stream<Statement> bindThrown(String actual, List<Statement> statements, GenSym genSym, String envVarName) { String e = genSym.generate("ex"); /* Throwable actual; try { // statements actual = null; } catch (XXXXException e) { // extract the cause if wrapped: inserted by the strategy actual = e.get...; } catch (Throwable e) { actual = e; } */ return Stream.of( new TryStatement( ListUtils.union( statements, Arrays.asList(new VarInitStatement( Type.THROWABLE, actual, new NullExpr(), Span.dummySpan()))), Arrays.asList(expressionStrategy.catchAndAssignCause(actual, genSym), new CatchClause( new ClassType("java.lang.Throwable", Span.dummySpan()), new Var(e), Arrays.asList(new VarInitStatement( Type.THROWABLE, actual, new VarExpr(e), Span.dummySpan())))), Arrays.asList())); } Stream<Statement> translateMatcher(Matcher matcher, String varName, GenSym genSym, String envVarName) { return matcher.accept(new MatcherVisitor<Stream<Statement>>() { @Override public Stream<Statement> visitEqualTo(EqualToMatcher equalTo) { Var objVar = new Var(genSym.generate("obj")); return Stream.concat( expressionStrategy.eval( objVar.getName(), envVarName, equalTo.getExpr(), genSym, docyPath, className, packageName).stream(), Stream.of(new VarInitStatement( Type.MATCHER, varName, new EqualToMatcherExpr(objVar), Span.dummySpan()))); } @Override public Stream<Statement> visitInstanceOf(InstanceOfMatcher instanceOf) { return Stream.of(new VarInitStatement( Type.MATCHER, varName, new InstanceOfMatcherExpr(instanceOf.getClazz().getName()), spanOf(instanceOf.getSpan()))); } @Override public Stream<Statement> visitInstanceSuchThat(InstanceSuchThatMatcher instanceSuchThat) { String bindVarName = instanceSuchThat.getVar().getName(); String instanceOfVarName = genSym.generate("instanceOfMatcher"); VarInitStatement instanceOfStatement = new VarInitStatement( Type.MATCHER, instanceOfVarName, new InstanceOfMatcherExpr(instanceSuchThat.getClazz().getName()), spanOf(instanceSuchThat.getSpan())); List<Pair<Var, Stream<Statement>>> suchThats = instanceSuchThat.getPropositions().stream().map(proposition -> { Var suchThatVar = new Var(genSym.generate("suchThat")); Var predVar = new Var(genSym.generate("pred")); yokohama.unit.ast.QuotedExpr subject = proposition.getSubject(); Predicate pred = proposition.getPredicate(); return pred.accept(new PredicateVisitor<Pair<Var, Stream<Statement>>>() { @Override public Pair<Var, Stream<Statement>> visitIsPredicate(IsPredicate isPredicate) { Var matchesArg = new Var(genSym.generate("arg")); Stream<Statement> predStatements = translateMatcher(isPredicate.getComplement(), predVar.getName(), genSym, envVarName); Stream<Statement> s = Stream.of(new VarInitStatement( Type.MATCHER, suchThatVar.getName(), new SuchThatMatcherExpr( new ArrayList<Statement>() {{ addAll(expressionStrategy.bind(envVarName, bindVarName, matchesArg, genSym)); addAll(predStatements.collect(Collectors.toList())); addAll(expressionStrategy.eval( "actual", envVarName, subject, genSym, docyPath, className, packageName)); add(new ReturnIsStatement(new Var("actual"), predVar)); }}, proposition.getDescription(), matchesArg), spanOf(isPredicate.getSpan()))); return new Pair<>(suchThatVar, s); } @Override public Pair<Var, Stream<Statement>> visitIsNotPredicate(IsNotPredicate isNotPredicate) { Var matchesArg = new Var(genSym.generate("arg")); Stream<Statement> predStatements = translateMatcher(isNotPredicate.getComplement(), predVar.getName(), genSym, envVarName); Stream<Statement> s = Stream.of(new VarInitStatement( Type.MATCHER, suchThatVar.getName(), new SuchThatMatcherExpr( new ArrayList<Statement>() {{ addAll(expressionStrategy.bind(envVarName, bindVarName, matchesArg, genSym)); addAll(predStatements.collect(Collectors.toList())); addAll(expressionStrategy.eval( "actual", envVarName, subject, genSym, docyPath, className, packageName)); add(new ReturnIsNotStatement(new Var("actual"), predVar)); }}, proposition.getDescription(), matchesArg), spanOf(isNotPredicate.getSpan()))); return new Pair<>(suchThatVar, s); } @Override public Pair<Var, Stream<Statement>> visitThrowsPredicate(ThrowsPredicate throwsPredicate) { Var matchesArg = new Var(genSym.generate("arg")); Stream<Statement> predStatements = translateMatcher(throwsPredicate.getThrowee(), predVar.getName(), genSym, envVarName); Stream<Statement> s = Stream.of(new VarInitStatement( Type.MATCHER, suchThatVar.getName(), new SuchThatMatcherExpr( new ArrayList<Statement>() {{ addAll(expressionStrategy.bind(envVarName, bindVarName, matchesArg, genSym)); addAll(predStatements.collect(Collectors.toList())); addAll(bindThrown( "actual", expressionStrategy.eval( "__", envVarName, subject, genSym, docyPath, className, packageName), genSym, envVarName) .collect(Collectors.toList())); add(new ReturnIsStatement(new Var("actual"), predVar)); }}, proposition.getDescription(), matchesArg), spanOf(throwsPredicate.getSpan()))); return new Pair<>(suchThatVar, s); } }); }).collect(Collectors.toList()); Stream<Var> suchThatVars = suchThats.stream().map(Pair::getFirst); Stream<Statement> suchThatStatements = suchThats.stream().flatMap(Pair::getSecond); VarInitStatement allOfStatement = new VarInitStatement( Type.MATCHER, varName, new ConjunctionMatcherExpr( Stream.concat( Stream.of(new Var(instanceOfVarName)), suchThatVars ).collect(Collectors.toList())), Span.dummySpan()); return Stream.concat( Stream.of(instanceOfStatement), Stream.concat( suchThatStatements, Stream.of(allOfStatement))); } @Override public Stream<Statement> visitNullValue(NullValueMatcher nullValue) { return Stream.of( new VarInitStatement( Type.MATCHER, varName, new NullValueMatcherExpr(), spanOf(nullValue.getSpan()))); } }); } Stream<Statement> translateBinding(yokohama.unit.ast.Binding binding, GenSym genSym, String envVarName) { String name = binding.getName().getName(); String varName = genSym.generate(name); return Stream.concat( translateExpr(binding.getValue(), varName, genSym, envVarName), expressionStrategy.bind(envVarName, name, new Var(varName), genSym).stream()); } Stream<Statement> translateExpr(yokohama.unit.ast.Expr expr, String varName, GenSym genSym, String envVarName) { return expr.accept( quotedExpr -> expressionStrategy.eval( varName, envVarName, quotedExpr, genSym, docyPath, className, packageName) .stream(), stubExpr -> { return mockStrategy.stub( varName, stubExpr.getClassToStub(), stubExpr.getBehavior(), expressionStrategy, envVarName, genSym, docyPath, className, packageName); }); } Type translateType(yokohama.unit.ast.Type type) { return new Type( translateNonArrayType(type.getNonArrayType()), type.getDims()); } NonArrayType translateNonArrayType(yokohama.unit.ast.NonArrayType nonArrayType) { return nonArrayType.accept( primitiveType -> new PrimitiveType(primitiveType.getKind()), classType -> new ClassType( classType.getName(), new Span( docyPath, classType.getSpan().getStart(), classType.getSpan().getEnd())) ); } List<List<Statement>> translateTableRef(TableRef tableRef, List<Table> tables, GenSym genSym, String envVarName) { String name = tableRef.getName(); List<String> idents = tableRef.getIdents() .stream() .map(Ident::getName) .collect(Collectors.toList()); switch(tableRef.getType()) { case INLINE: return translateTable( tables.stream() .filter(table -> table.getName().equals(name)) .findFirst() .get(), idents, genSym, envVarName); case CSV: return parseCSV(name, CSVFormat.DEFAULT.withHeader(), idents, genSym, envVarName); case TSV: return parseCSV(name, CSVFormat.TDF.withHeader(), idents, genSym, envVarName); case EXCEL: return parseExcel(name, idents, genSym, envVarName); } throw new IllegalArgumentException("'" + Objects.toString(tableRef) + "' is not a table reference."); } List<List<Statement>> translateTable(Table table, List<String> idents, GenSym genSym, String envVarName) { return table.getRows() .stream() .map(row -> translateRow( row, table.getHeader() .stream() .map(Ident::getName) .collect(Collectors.toList()), idents, genSym, envVarName)) .collect(Collectors.toList()); } List<Statement> translateRow(Row row, List<String> header, List<String> idents, GenSym genSym, String envVarName) { return IntStream.range(0, header.size()) .filter(i -> idents.contains(header.get(i))) .mapToObj(Integer::new) .flatMap(i -> { String varName = genSym.generate(header.get(i)); return Stream.concat( translateExpr(row.getExprs().get(i), varName, genSym, envVarName), expressionStrategy.bind(envVarName, header.get(i), new Var(varName), genSym).stream()); }) .collect(Collectors.toList()); } @SneakyThrows(IOException.class) List<List<Statement>> parseCSV(String fileName, CSVFormat format, List<String> idents, GenSym genSym, String envVarName) { try ( final InputStream in = getClass().getResourceAsStream(fileName); final Reader reader = new InputStreamReader(in, "UTF-8"); final CSVParser parser = new CSVParser(reader, format)) { return StreamSupport.stream(parser.spliterator(), false) .map(record -> parser.getHeaderMap().keySet() .stream() .filter(key -> idents.contains(key)) .flatMap(name -> { String varName = genSym.generate(name); return Stream.concat( expressionStrategy.eval( varName, envVarName, new yokohama.unit.ast.QuotedExpr( record.get(name), new yokohama.unit.ast.Span( new Position((int)parser.getCurrentLineNumber(), -1), new Position(-1, -1))), genSym, Optional.of(Paths.get(fileName)), className, packageName).stream(), expressionStrategy.bind(envVarName, name, new Var(varName), genSym).stream()); }) .collect(Collectors.toList())) .collect(Collectors.toList()); } } List<List<Statement>> parseExcel(String fileName, List<String> idents, GenSym genSym, String envVarName) { try (InputStream in = getClass().getResourceAsStream(fileName)) { final Workbook book = WorkbookFactory.create(in); final Sheet sheet = book.getSheetAt(0); final int top = sheet.getFirstRowNum(); final int left = sheet.getRow(top).getFirstCellNum(); List<String> names = StreamSupport.stream(sheet.getRow(top).spliterator(), false) .map(cell -> cell.getStringCellValue()) .collect(Collectors.toList()); return StreamSupport.stream(sheet.spliterator(), false) .skip(1) .map(row -> IntStream.range(0, names.size()) .filter(i -> idents.contains(names.get(i))) .mapToObj(Integer::new) .flatMap(i -> { String varName = genSym.generate(names.get(i)); return Stream.concat( expressionStrategy.eval( varName, envVarName, new yokohama.unit.ast.QuotedExpr( row.getCell(left + i).getStringCellValue(), new yokohama.unit.ast.Span( new Position(row.getRowNum() + 1, left + i + 1), new Position(-1, -1))), genSym, Optional.of(Paths.get(fileName)), className, packageName).stream(), expressionStrategy.bind(envVarName, names.get(i), new Var(varName), genSym).stream()); }) .collect(Collectors.toList())) .collect(Collectors.toList()); } catch (InvalidFormatException | IOException e) { throw new TranslationException(e); } } List<TestMethod> translateFourPhaseTest(FourPhaseTest fourPhaseTest, List<Table> tables, GenSym genSym) { String env = genSym.generate("env"); String testName = SUtils.toIdent(fourPhaseTest.getName()); Stream<Statement> bindings; if (fourPhaseTest.getSetup().isPresent()) { Phase setup = fourPhaseTest.getSetup().get(); if (setup.getLetBindings().isPresent()) { LetBindings letBindings = setup.getLetBindings().get(); bindings = letBindings.getBindings() .stream() .flatMap(binding -> { String varName = genSym.generate(binding.getName()); return Stream.concat( translateExpr(binding.getValue(), varName, genSym, env), expressionStrategy.bind(env, binding.getName(), new Var(varName), genSym).stream()); }); } else { bindings = Stream.empty(); } } else { bindings = Stream.empty(); } Optional<Stream<Statement>> setupActions = fourPhaseTest.getSetup() .map(Phase::getExecutions) .map(execition -> translateExecutions(execition, genSym, env)); Optional<Stream<Statement>> exerciseActions = fourPhaseTest.getExercise() .map(Phase::getExecutions) .map(execution -> translateExecutions(execution, genSym, env)); Stream<Statement> testStatements = fourPhaseTest.getVerify().getAssertions() .stream() .flatMap(assertion -> assertion.getPropositions() .stream() .flatMap(proposition -> translateProposition(proposition, genSym, env)) ); List<Statement> statements = Stream.concat( bindings, Stream.concat( Stream.concat( setupActions.isPresent() ? setupActions.get() : Stream.empty(), exerciseActions.isPresent() ? exerciseActions.get() : Stream.empty()), testStatements) ).collect(Collectors.toList()); List<Statement> actionsAfter; if (fourPhaseTest.getTeardown().isPresent()) { Phase teardown = fourPhaseTest.getTeardown().get(); actionsAfter = translateExecutions(teardown.getExecutions(), genSym, env).collect(Collectors.toList()); } else { actionsAfter = Arrays.asList(); } return Arrays.asList( new TestMethod( testName, ListUtils.union( expressionStrategy.env(env), actionsAfter.size() > 0 ? Arrays.asList( new TryStatement( statements, Arrays.asList(), actionsAfter)) : statements))); } Stream<Statement> translateExecutions(List<Execution> executions, GenSym genSym, String envVarName) { String __ = genSym.generate("__"); return executions.stream() .flatMap(execution -> execution.getExpressions() .stream() .flatMap(expression -> expressionStrategy.eval( __, envVarName, expression, genSym, docyPath, className, packageName).stream())); } }
package org.jboss.marshalling.river; public final class Protocol { public static final int MAX_VERSION = 2; public static final int ID_NULL_OBJECT = 0x01; public static final int ID_REPEAT_OBJECT_FAR = 0x02; public static final int ID_PREDEFINED_OBJECT = 0x03; public static final int ID_NEW_OBJECT = 0x04; public static final int ID_NEW_OBJECT_UNSHARED = 0x05; public static final int ID_REPEAT_CLASS_FAR = 0x06; public static final int ID_PLAIN_CLASS = 0x07; public static final int ID_PROXY_CLASS = 0x08; // Proxy.isProxy(?) == true public static final int ID_SERIALIZABLE_CLASS = 0x09; // ? extends Serializable.class public static final int ID_EXTERNALIZABLE_CLASS = 0x0a; // ? extends Externalizable.class public static final int ID_EXTERNALIZER_CLASS = 0x0b; public static final int ID_ENUM_TYPE_CLASS = 0x0c; // ? extends Enum.class public static final int ID_OBJECT_ARRAY_TYPE_CLASS = 0x0d; // ? extends Object[].class public static final int ID_PREDEFINED_PLAIN_CLASS = 0x0e; public static final int ID_PREDEFINED_PROXY_CLASS = 0x0f; public static final int ID_PREDEFINED_SERIALIZABLE_CLASS = 0x10; public static final int ID_PREDEFINED_EXTERNALIZABLE_CLASS = 0x11; public static final int ID_PREDEFINED_EXTERNALIZER_CLASS = 0x12; public static final int ID_PREDEFINED_ENUM_TYPE_CLASS = 0x13; // the following are never cached public static final int ID_STRING_CLASS = 0x14; // String.class public static final int ID_CLASS_CLASS = 0x15; // Class.class public static final int ID_OBJECT_CLASS = 0x16; // Object.class public static final int ID_ENUM_CLASS = 0x17; // Enum.class public static final int ID_BOOLEAN_ARRAY_CLASS = 0x18; // boolean[].class public static final int ID_BYTE_ARRAY_CLASS = 0x19; // ..etc.. public static final int ID_SHORT_ARRAY_CLASS = 0x1a; public static final int ID_INT_ARRAY_CLASS = 0x1b; public static final int ID_LONG_ARRAY_CLASS = 0x1c; public static final int ID_CHAR_ARRAY_CLASS = 0x1d; public static final int ID_FLOAT_ARRAY_CLASS = 0x1e; public static final int ID_DOUBLE_ARRAY_CLASS = 0x1f; public static final int ID_PRIM_BOOLEAN = 0x20; // boolean.class public static final int ID_PRIM_BYTE = 0x21; // ..etc.. public static final int ID_PRIM_SHORT = 0x22; public static final int ID_PRIM_INT = 0x23; public static final int ID_PRIM_LONG = 0x24; public static final int ID_PRIM_CHAR = 0x25; public static final int ID_PRIM_FLOAT = 0x26; public static final int ID_PRIM_DOUBLE = 0x27; public static final int ID_VOID = 0x28; // void.class public static final int ID_BOOLEAN_CLASS = 0x29; // Boolean.class public static final int ID_BYTE_CLASS = 0x2a; // ..etc.. public static final int ID_SHORT_CLASS = 0x2b; public static final int ID_INTEGER_CLASS = 0x2c; public static final int ID_LONG_CLASS = 0x2d; public static final int ID_CHARACTER_CLASS = 0x2e; public static final int ID_FLOAT_CLASS = 0x2f; public static final int ID_DOUBLE_CLASS = 0x30; public static final int ID_VOID_CLASS = 0x31; // Void.class // protocol version >= 1 public static final int ID_START_BLOCK_SMALL = 0x32; // 8 bit size public static final int ID_START_BLOCK_MEDIUM = 0x33; // 16 bit size public static final int ID_START_BLOCK_LARGE = 0x34; // 32 bit size public static final int ID_END_BLOCK_DATA = 0x35; public static final int ID_CLEAR_CLASS_CACHE = 0x36; // implies CLEAR_INSTANCE_CACHE public static final int ID_CLEAR_INSTANCE_CACHE = 0x37; public static final int ID_WRITE_OBJECT_CLASS = 0x38; // ? extends Serializable.class, plus writeObject method // protocol version >= 2 public static final int ID_REPEAT_OBJECT_NEAR = 0x39; // 8-bit unsigned negative int relative public static final int ID_REPEAT_OBJECT_NEARISH = 0x3a; // 16-bit unsigned negative int relative public static final int ID_REPEAT_CLASS_NEAR = 0x3b; // 8-bit unsigned negative int relative public static final int ID_REPEAT_CLASS_NEARISH = 0x3c; // 16-bit unsigned negative int relative public static final int ID_STRING_EMPTY = 0x3d; // ""; not cached // these three are cached public static final int ID_STRING_SMALL = 0x3e; // <0x100 chars public static final int ID_STRING_MEDIUM = 0x3f; // <0x10000 chars public static final int ID_STRING_LARGE = 0x40; // <0x80000000 chars private Protocol() { } }
package net.runelite.api; import lombok.AllArgsConstructor; import lombok.Getter; /** * An enumeration of string local variables. */ @AllArgsConstructor @Getter public enum VarClientStr { CHATBOX_TYPED_TEXT(335), INPUT_TEXT(359), PRIVATE_MESSAGE_TARGET(360), RECENT_CLAN_CHAT(362); private final int index; }
// G l y p h S l u r I n f o // // <editor-fold defaultstate="collapsed" desc="hdr"> // This program is free software: you can redistribute it and/or modify it under the terms of the // </editor-fold> package org.audiveris.omr.sheet.curve; import ij.process.ByteProcessor; import org.audiveris.omr.glyph.Glyph; import org.audiveris.omr.math.CubicUtil; import org.audiveris.omr.math.LineUtil; import org.audiveris.omr.math.PointUtil; import org.audiveris.omr.run.Orientation; import org.audiveris.omr.run.Run; import org.audiveris.omr.run.RunTable; import java.awt.Point; import java.awt.geom.CubicCurve2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.audiveris.omr.run.RunTableFactory; public class GlyphSlurInfo extends SlurInfo { private GlyphSlurInfo (Glyph glyph, List<Point> keyPoints) { super(0, null, null, keyPoints, null, Collections.emptyList(), 0); this.glyph = glyph; } // getCurve // @Override public CubicCurve2D getCurve () { return curve; } // getMidPoint // /** * Report the middle point of the slur. * * @return middle point */ @Override public Point2D getMidPoint () { return CubicUtil.getMidPoint(curve); } /** * Create proper GlyphSlurInfo for a slur defined by its glyph. * The bezier curve is directly computed from the glyph. * * @param glyph the defining glyph * @return the corresponding slur info */ public static GlyphSlurInfo create (Glyph glyph) { final List<Point> points = new KeyPointsBuilder(glyph).retrieveKeyPoints(); final GlyphSlurInfo info = new GlyphSlurInfo(glyph, points); // Curve points final Point s0 = points.get(0); final Point s1 = points.get(1); final Point s2 = points.get(2); final Point s3 = points.get(3); info.curve = CubicUtil.createCurve(s0, s1, s2, s3); // Above or below? info.above = CubicUtil.above(info.curve); return info; } // KeyPointsBuilder // /** * Class {@code KeyPointsBuilder} builds a slur from a provided glyph. * <p> * This class is meant for manual slur built on a selected glyph, by using exactly 4 key points * evenly spaced along the glyph abscissa axis. */ private static class KeyPointsBuilder { private final Glyph glyph; private final RunTable rt; /** * Creates a new {@code KeyPointsBuilder} object. * * @param glyph the underlying glyph */ KeyPointsBuilder (Glyph glyph) { this.glyph = glyph; RunTable table = glyph.getRunTable(); if (table.getOrientation() != Orientation.VERTICAL) { ByteProcessor buf = table.getBuffer(); table = new RunTableFactory(Orientation.VERTICAL).createTable(buf); } rt = table; } public List<Point> retrieveKeyPoints () { // Retrieve the 4 points WRT glyph bounds final int width = glyph.getWidth(); final List<Point> points = new ArrayList<>(4); points.add(vectorAtX(0)); points.add(vectorAtX((int) Math.rint(width / 3.0))); points.add(vectorAtX((int) Math.rint((2 * width) / 3.0))); points.add(vectorAtX(width - 1)); // Use sheet coordinates rather than glyph-based coordinates final int dx = glyph.getLeft(); final int dy = glyph.getTop(); for (Point point : points) { point.translate(dx, dy); } return points; } private Point lookLeft (int x0) { for (int x = x0 - 1; x >= 0; x int y = yAtX(x); if (y != -1) { return new Point(x, y); } } return null; } private Point lookRight (int x0) { int size = rt.getSize(); for (int x = x0 + 1; x < size; x++) { int y = yAtX(x); if (y != -1) { return new Point(x, y); } } return null; } /** * Report the best offset for a given x offset. * <p> * If no run is found at x offset, columns on left and on right are searched, and y offset * is then interpolated. * * @param x abscissa offset since glyph left side * @return vector offset since glyph top left corner */ private Point vectorAtX (int x) { int y = yAtX(x); if (y != -1) { return new Point(x, y); } Point left = lookLeft(x); Point right = lookRight(x); return PointUtil.rounded(LineUtil.intersectionAtX(new Line2D.Double(left, right), x)); } /** * Read the y offset for a given x offset. * * @param x given x offset * @return -1 if there is no run at x, otherwise the middle of run */ private int yAtX (int x) { if (rt.isSequenceEmpty(x)) { return -1; } int yMin = Integer.MAX_VALUE; int yMax = Integer.MIN_VALUE; for (Iterator<Run> it = rt.iterator(x); it.hasNext();) { Run run = it.next(); yMin = Math.min(yMin, run.getStart()); yMax = Math.max(yMax, run.getStop()); } return yMin + ((yMax - yMin) / 2); } } }
package ru.stqa.pft.sandbox; public class MyFirstProgram { public static void main(String[] args) { hello("world"); hello("user"); hello("test"); double l = 5; System.out.println("площать квадрата со стороной " + l + " = " + area(l)); double a = 5; double b =6; System.out.println("площать прямоугольника со сторонами " + a + " и " + b + " = " + area(a, b)); } public static void hello(String somebody){ System.out.println("Hello, " + somebody + "!"); } public static double area(double len) { return len * len; } public static double area(double a, double b) { return a * b; } }
package com.smartdevicelink.trace; // Borrowed from Dave Boll's infamous SdlLinkRelay.java public class Mime { private static final String BASE_64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** * @param str A String to encode into base64 String. * @return Base64 encoded String or a null String if input is null. */ public static String base64Encode(String str) { if(str == null){ return null; } String b64String = ""; try { byte[] strBytes = str.getBytes("US-ASCII"); b64String = base64Encode(strBytes); } catch (Exception ex) { // Don't care? } return b64String; } /** * @param bytesToEncode A byte array to encode into base64 String. * @return Base64 encoded String or a null String if input array is null. */ public static String base64Encode(byte bytesToEncode[]) { if(bytesToEncode != null){ return base64Encode(bytesToEncode, 0, bytesToEncode.length); } return null; } /** * @param bytesToEncode A byte array to encode into base64 String. * @param offset Offset to begin at * @param length Length to read * @return Base64 encoded String or a null String if input array is null or the input range is out of bounds. */ public static String base64Encode(byte bytesToEncode[], int offset, int length) { if (bytesToEncode == null || bytesToEncode.length < length || bytesToEncode.length < offset + length) { return null; } StringBuilder sb = new StringBuilder(); int idxin = 0; int b64idx = 0; for (idxin = offset; idxin < offset + length; idxin++) { switch ((idxin - offset) % 3) { case 0: b64idx = (bytesToEncode[idxin] >> 2) & 0x3f; break; case 1: b64idx = (bytesToEncode[idxin] >> 4) & 0x0f; b64idx |= ((bytesToEncode[idxin - 1] << 4) & 0x30); break; case 2: b64idx = (bytesToEncode[idxin] >> 6) & 0x03; b64idx |= ((bytesToEncode[idxin - 1] << 2) & 0x3c); sb.append(getBase64Char(b64idx)); b64idx = bytesToEncode[idxin] & 0x3f; break; } sb.append(getBase64Char(b64idx)); } switch ((idxin - offset) % 3) { case 0: break; case 1: b64idx = (bytesToEncode[idxin - 1] << 4) & 0x30; sb.append(getBase64Char(b64idx)); sb.append("=="); break; case 2: b64idx = ((bytesToEncode[idxin - 1] << 2) & 0x3c); sb.append(getBase64Char(b64idx)); sb.append('='); break; } return sb.toString(); } private static char getBase64Char(int b64idx){ if(b64idx >= 0 && b64idx < BASE_64_CHARS.length()) { return BASE_64_CHARS.charAt(b64idx); }else{ return 0x20; } } }
package japsadev.bio.hts.clustering; import java.util.ArrayList; import java.io.*; import japsa.seq.SequenceOutputStream; import japsadev.bio.hts.clustering.PairDistance; import japsadev.bio.hts.clustering.GettingTreadsFromFasta; /** * @author buvan.suji * */ public class KmeanClustering { public static void Clustering() throws Exception{ FileInputStream file1 = new FileInputStream("TRfile.fasta"); BufferedReader br = new BufferedReader(new InputStreamReader(file1)); String line = null; while((line = br.readLine())!=null){ ArrayList<String> descript = new ArrayList<String>(); ArrayList<String> reads = new ArrayList<String>(); //ArrayList<Integer> MaxReadLn = new ArrayList<Integer>(); int MaxReadLn = 0; int Nreads; String FileName; int NumberElements; int ClustElements; int n; int d[]; int k[][]; final int p =2;//number of clusters int tempk[][]; int m[]; int Nclusters = 0; double max = 0; double temp1 = 0; int index1=0; int index2=0; int count1=0,count2=0; long startTime = System.nanoTime(); GettingTreadsFromFasta.DestReads(line); //GettingTreadsFromFasta.DestReads(); descript = GettingTreadsFromFasta.GetRname(); reads = GettingTreadsFromFasta.GetTReads(); Nreads = GettingTreadsFromFasta.NumberReads(); FileName = GettingTreadsFromFasta.GetFileName(); NumberElements = GettingTreadsFromFasta.SeqLength(); ClustElements = GettingTreadsFromFasta.NelementsClustering(); double[][] table = new double[Nreads][Nreads]; for (int i=0; i<Nreads; ++i){ for(int j=0;j<Nreads;++j){ table[i][j]=0; } } for (int i = 0; i < reads.size(); i++) { int temp = 0; for (int j = i + 1; j < reads.size(); j++) { String x = reads.get(i); String y = reads.get(j); PairDistance.EditDistanceResult result = PairDistance.compute(x, y); double normdist = ((double) result.getDistance()) / Math.max(x.length(), y.length()); table[i][j]=normdist; temp = x.length(); } MaxReadLn = Math.max(MaxReadLn, temp); } n=Nreads; d=new int[n]; //name of the reads for(int i=0;i<n;++i){ d[i]=i; } //Initialising arrays k=new int[p][n]; tempk=new int[p][n]; m=new int [p]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { temp1 = table[i][j]; if(max < temp1){ max = temp1; index1=i; index2=j; } } } //Initializing m m[0] = index1; m[1] = index2; int temp=0; int flag=0; do{ for(int i=0;i<p;++i){ for(int j=0;j<n;++j){ k[i][j]=-1; } } for(int i=0;i<n;++i){ temp=NewCluster(d[i], table, m); if(temp==0){ k[temp][count1++]=d[i]; } else if(temp==1){ k[temp][count2++]=d[i]; } } NewMean(table, m, n, k); // call to method which will calculate mean at this step. flag = VerifyEqual(n, k, tempk); // check if terminating condition is satisfied. if(flag!=1){ /*Take backup of k in tempk so that you can check for equivalence in next step*/ for(int i=0;i<p;++i){ for(int j=0;j<n;++j){ tempk[i][j]=k[i][j]; } } } System.out.println("\nClusters Results:"); for(int i=0;i<p;++i){ System.out.print("C"+(i+1)+"{ "); for(int j=0;k[i][j]!=-1 && j<n-1;++j) System.out.print(k[i][j]+" "); System.out.println("}"); } //end of for loop System.out.println("\nCentroid of the clusters are: "); for(int i=0;i<p;++i){ System.out.print("m"+(i+1)+"="+m[i]+" "); } count1=0;count2=0; Nclusters += 1; } while(flag==0); long t = System.nanoTime()-startTime; double estimateTime = (double)t/1000000000.0; File file = new File("ClusterResult_"+FileName); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write("Number of Reads: "+ Nreads); bw.newLine(); bw.write("Maximum Read Length: "+ MaxReadLn); bw.newLine(); bw.write("Number of Iterations: "+ Nclusters); bw.newLine(); bw.write("Estimated Time: "+estimateTime+" ms"); bw.newLine(); bw.write("Two clusters elements are: "); bw.newLine(); for(int i=0;i<p;++i){ String s = "C"+(i+1)+"{ "; bw.write(s); for(int j=0;k[i][j]!=-1 && j<n-1;++j){ bw.write(descript.get(k[i][j])); bw.newLine(); } bw.write("}"); bw.newLine(); } bw.close(); } br.close(); } public static int NewCluster(int a, double list[][], int m[] ){ double diff[] = new double[2]; for(int i=0;i<2;++i){ if(a<m[i]){ diff[i] = list[a][m[i]]; } else if(a>m[i]){ diff[i] = list[m[i]][a]; } else{ diff[i]=0; } } int val=0; double temp=diff[0]; for(int i=0;i<2;++i){ if(diff[i]<temp){ temp=diff[i]; val=i; } }//end of for loop return val; } static void NewMean(double list [][], int m[], int n, int k[][]){ ArrayList<Integer> t = new ArrayList<Integer>() ; for(int i=0;i<2;++i){ m[i]=0; // initializing means to 0 } //int cnt=0; for(int i=0;i<2;++i){ for(int j=0;j<n-1;++j){ if(k[i][j]!=-1){ t.add(k[i][j]); } } ArrayList<Double> s = new ArrayList<Double>(); for(int x1 = 0; x1<t.size();++x1){ double sum = 0; for(int x2=0;x2<t.size();++x2){ if(t.get(x1)<t.get(x2)){ sum = sum+(list[t.get(x1)][t.get(x2)]*list[t.get(x1)][t.get(x2)]); } else if(t.get(x1)>t.get(x2)){ sum = sum+(list[t.get(x2)][t.get(x1)]*list[t.get(x2)][t.get(x1)]); } else{ sum = sum+0; } } //System.out.println(sum); s.add(sum/t.size()); } //System.out.println(s.size()); double min=s.get(0); int d2 = 0; for(int x3=1;x3<s.size();++x3){ if(min>s.get(x3)){ min = s.get(x3); d2 = x3; } } m[i]=t.get(d2); s.clear(); t.clear(); } } //This checks if previous k ie. tempk and current k are same.Used as terminating case. static int VerifyEqual(int n, int k[][], int tempk[][]){ for(int i=0;i<2;++i){ for(int j=0;j<n;++j){ if(tempk[i][j]!=k[i][j]){ return 0; } } } return 1; } public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Clustering(); // C:\Users\buvan.suji\workspace\Distance\SampleData\results\TR_Fasta\OutputReads\chr11119005_1121390.fasta // C:\Users\buvan.suji\workspace\Distance\SampleData\results\TR_Fasta\OutputReads\chr1842862036_42864557.fasta //C:/Users/Subashchandran/Marseclipse/workspace/Data/TrResults/Finished Cluster/chr11119005_1121390.fasta //C:/Users/Subashchandran/Marseclipse/workspace/Data/TrResults/chr2440992_444078.fasta //C:/Users/Subashchandran/Marseclipse/workspace/Data/TrResults/chr68826819_8829365.fasta //C:/Users/Subashchandran/Marseclipse/workspace/Data/TrResults/FinishedCluster/chr11119005_1121390.fasta //C:\Users\Subashchandran\Marseclipse\workspace\OldData\TrResults\Finished Cluster\chr11119005_1121390.fasta } }
package dr.app.beagle.evomodel.branchmodel; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import org.apache.commons.math.random.MersenneTwister; import dr.app.beagle.evomodel.substmodel.FrequencyModel; import dr.app.beagle.evomodel.substmodel.GY94CodonModel; import dr.app.beagle.evomodel.substmodel.SubstitutionModel; import dr.app.bss.Utils; import dr.evolution.datatype.Codons; import dr.evolution.datatype.DataType; import dr.evolution.tree.NodeRef; import dr.evomodel.tree.TreeModel; import dr.inference.model.AbstractModel; import dr.inference.model.Model; import dr.inference.model.Parameter; import dr.inference.model.Parameter.Default; import dr.inference.model.Variable; import dr.inference.model.Variable.ChangeType; import dr.math.MathUtils; /** * @author Filip Bielejec * @version $Id$ * */ @SuppressWarnings("serial") public class RandomBranchModel extends AbstractModel implements BranchModel { public static final String RANDOM_BRANCH_MODEL = "randomBranchModel"; private final TreeModel treeModel; private GY94CodonModel baseSubstitutionModel; private LinkedList<SubstitutionModel> substitutionModels; // private int[] order; private LinkedHashMap<NodeRef, Integer> branchAssignmentMap; private static MersenneTwister random = new MersenneTwister( MathUtils.nextLong()); public RandomBranchModel(TreeModel treeModel, GY94CodonModel baseSubstitutionModel) { super(RANDOM_BRANCH_MODEL); this.treeModel = treeModel; this.baseSubstitutionModel = baseSubstitutionModel; setup(); }// END: Constructor private void setup() { // TODO: parse double stdev = 1.0; double mean = 0.0; DataType dataType = baseSubstitutionModel.getDataType(); FrequencyModel freqModel = baseSubstitutionModel.getFrequencyModel(); Parameter kappaParameter = new Parameter.Default("kappa", 1, baseSubstitutionModel.getKappa()); substitutionModels = new LinkedList<SubstitutionModel>(); branchAssignmentMap = new LinkedHashMap<NodeRef, Integer>(); int branchClass = 0; for (NodeRef node : treeModel.getNodes()) { if (!treeModel.isRoot(node)) { double nodeHeight = treeModel.getNodeHeight(node); double parentHeight = treeModel.getNodeHeight(treeModel .getParent(node)); System.out.println("upper: " + parentHeight + ", lower: " + nodeHeight); double time = 0.5 * (parentHeight - nodeHeight); double baseOmega = baseSubstitutionModel.getOmega(); double epsilon = (random.nextGaussian() * stdev + mean); double value = baseOmega * time + epsilon; Parameter omegaParameter = new Parameter.Default("omega", 1, value); GY94CodonModel gy94 = new GY94CodonModel((Codons) dataType, omegaParameter, kappaParameter, freqModel); substitutionModels.add(gy94); branchAssignmentMap.put(node, branchClass); branchClass++; } }// END: nodes loop }// END: setup @Override public Mapping getBranchModelMapping(NodeRef branch) { final int branchClass = branchAssignmentMap.get(branch); return new Mapping() { public int[] getOrder() { return new int[] { branchClass }; } public double[] getWeights() { return new double[] { 1.0 }; } }; } @Override public List<SubstitutionModel> getSubstitutionModels() { return substitutionModels; } @Override public SubstitutionModel getRootSubstitutionModel() { // int rootClass = branchAssignmentMap.get(treeModel.getRoot()); // return substitutionModels.get(rootClass); throw new RuntimeException("Not implemented!"); } @Override public FrequencyModel getRootFrequencyModel() { return getRootSubstitutionModel().getFrequencyModel(); } @Override public boolean requiresMatrixConvolution() { return false; } @Override protected void handleModelChangedEvent(Model model, Object object, int index) { fireModelChanged(); } @Override protected void handleVariableChangedEvent(Variable variable, int index, ChangeType type) { } @Override protected void storeState() { } @Override protected void restoreState() { } @Override protected void acceptState() { } }// END: class
package dr.app.beauti.components.dnds; import dr.app.beauti.generator.BaseComponentGenerator; import dr.app.beauti.options.BeautiOptions; import dr.app.beauti.options.PartitionSubstitutionModel; import dr.app.beauti.util.XMLWriter; import dr.util.Attribute; /** * @author Filip Bielejec * @version $Id$ */ public class DnDsComponentGenerator extends BaseComponentGenerator { protected DnDsComponentGenerator(BeautiOptions options) { super(options); } public boolean usesInsertionPoint(InsertionPoint point) { DnDsComponentOptions component = (DnDsComponentOptions) options .getComponentOptions(DnDsComponentOptions.class); if (component.getPartitionList().size() == 0) { // Empty, so do nothing return false; } switch (point) { case IN_OPERATORS: case IN_FILE_LOG_PARAMETERS: case IN_TREES_LOG: case AFTER_TREES_LOG: return true; default: return false; } } protected void generate(InsertionPoint point, Object item, XMLWriter writer) { DnDsComponentOptions component = (DnDsComponentOptions) options .getComponentOptions(DnDsComponentOptions.class); switch (point) { case IN_OPERATORS: writeCodonPartitionedRobustCounting(writer, component); break; case IN_FILE_LOG_PARAMETERS: writeLogs(writer, component); break; case IN_TREES_LOG: writeTreeLogs(writer, component); break; case AFTER_TREES_LOG: writeDNdSLogger(writer, component); writeDNdSReport(writer, component); break; default: throw new IllegalArgumentException( "This insertion point is not implemented for " + this.getClass().getName()); } } protected String getCommentLabel() { return "Codon partitioned robust counting"; } private void writeCodonPartitionedRobustCounting(XMLWriter writer, DnDsComponentOptions component) { for (PartitionSubstitutionModel model : component.getPartitionList()) { writeCodonPartitionedRobustCounting(writer, model); } } // Called for each model that requires robust counting (can be more than // one) private void writeCodonPartitionedRobustCounting(XMLWriter writer, PartitionSubstitutionModel model) { System.err.println("DEBUG: Writing RB for " + model.getName()); writer.writeComment("Robust counting for: " + model.getName()); // TODO: Hand coding is so 90s // S operator writer.writeOpenTag("codonPartitionedRobustCounting", new Attribute[] { new Attribute.Default<String>("id", "robustCounting1"), new Attribute.Default<String>("labeling", "S"), new Attribute.Default<String>("useUniformization", "true"), new Attribute.Default<String>("unconditionedPerBranch", "true") }); writer.writeIDref("idref", "treeModel"); writer.writeOpenTag("firstPosition"); writer.writeIDref("ancestralTreeLikelihood", "CP1.treeLikelihood"); writer.writeCloseTag("firstPosition"); writer.writeOpenTag("secondPosition"); writer.writeIDref("ancestralTreeLikelihood", "CP2.treeLikelihood"); writer.writeCloseTag("secondPosition"); writer.writeOpenTag("thirdPosition"); writer.writeIDref("ancestralTreeLikelihood", "CP3.treeLikelihood"); writer.writeCloseTag("thirdPosition"); writer.writeCloseTag("codonPartitionedRobustCounting"); writer.writeBlankLine(); // N operator: writer.writeOpenTag("codonPartitionedRobustCounting", new Attribute[] { new Attribute.Default<String>("id", "robustCounting2"), new Attribute.Default<String>("labeling", "N"), new Attribute.Default<String>("useUniformization", "true"), new Attribute.Default<String>("unconditionedPerBranch", "true") }); writer.writeIDref("idref", "treeModel"); writer.writeOpenTag("firstPosition"); writer.writeIDref("ancestralTreeLikelihood", "CP1.treeLikelihood"); writer.writeCloseTag("firstPosition"); writer.writeOpenTag("secondPosition"); writer.writeIDref("ancestralTreeLikelihood", "CP2.treeLikelihood"); writer.writeCloseTag("secondPosition"); writer.writeOpenTag("thirdPosition"); writer.writeIDref("ancestralTreeLikelihood", "CP3.treeLikelihood"); writer.writeCloseTag("thirdPosition"); writer.writeCloseTag("codonPartitionedRobustCounting"); }// END: writeCodonPartitionedRobustCounting() private void writeLogs(XMLWriter writer, DnDsComponentOptions component) { for (PartitionSubstitutionModel model : component.getPartitionList()) { writeLogs(writer, model); } } private void writeLogs(XMLWriter writer, PartitionSubstitutionModel model) { writer.writeComment("Robust counting for: " + model.getName()); writer.writeIDref("codonPartitionedRobustCounting", "robustCounting1"); writer.writeIDref("codonPartitionedRobustCounting", "robustCounting2"); }// END: writeLogs() private void writeTreeLogs(XMLWriter writer, DnDsComponentOptions component) { for (PartitionSubstitutionModel model : component.getPartitionList()) { // We re-use the same method writeLogs(writer, model); } } private void writeDNdSLogger(XMLWriter writer, DnDsComponentOptions component) { for (PartitionSubstitutionModel model : component.getPartitionList()) { writeDNdSLogger(writer, model); } } private void writeDNdSLogger(XMLWriter writer, PartitionSubstitutionModel model) { writer.writeComment("Robust counting for: " + model.getName()); writer.writeOpenTag("log", new Attribute[] { new Attribute.Default<String>("id", "fileLog_dNdS"), new Attribute.Default<String>("logEvery", "10000"), new Attribute.Default<String>("fileName", model.getName() + ".log") }); writer .writeOpenTag("dNdSLogger", new Attribute[] { new Attribute.Default<String>("id", "dNdS") }); writer.writeIDref("idref", "treeModel"); writer.writeIDref("codonPartitionedRobustCounting", "robustCounting1"); writer.writeIDref("codonPartitionedRobustCounting", "robustCounting2"); writer.writeCloseTag("dNdSLogger"); writer.writeCloseTag("log"); }// END: writeLogs() private void writeDNdSReport(XMLWriter writer, DnDsComponentOptions component) { for (PartitionSubstitutionModel model : component.getPartitionList()) { writeDNdSReport(writer, model); } } private void writeDNdSReport(XMLWriter writer, PartitionSubstitutionModel model) { writer.writeComment("Robust counting for: " + model.getName()); writer.writeOpenTag("report"); writer.write("<dNdSPerSiteAnalysis fileName=" + '\"' + model.getName() + ".log\"/>"); writer.writeCloseTag("report"); }// END: writeDNdSReport() }// END: class
package dr.evomodel.speciation; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.Taxon; import dr.inference.model.Parameter; import dr.inference.model.Variable; import java.util.Set; /** * Beginning of tree prior for birth-death + serial sampling + extant sample proportion. More Tanja magic... * * @author Alexei Drummond */ public class BirthDeathSerialSamplingModel extends MaskableSpeciationModel { // birth rate Variable<Double> lambda; // death rate Variable<Double> mu; // serial sampling rate Variable<Double> psi; // extant sampling proportion Variable<Double> p; //boolean death rate is relative? boolean relativeDeath = false; // boolean stating whether sampled individuals remain infectious, or become non-infectious // boolean sampledIndividualsRemainInfectious = false; // replaced by r // the additional parameter 0 <= r <= 1 has to be estimated. // for r=1, this is sampledRemainInfectiousProb=0 // for r=0, this is sampledRemainInfectiousProb=1 Variable<Double> r; //Variable<Double> finalTimeInterval; boolean hasFinalSample = false; // the origin of the infection, x0 > tree.getRoot(); Variable<Double> origin; public BirthDeathSerialSamplingModel( Variable<Double> lambda, Variable<Double> mu, Variable<Double> psi, Variable<Double> p, boolean relativeDeath, Variable<Double> r, boolean hasFinalSample, Variable<Double> origin, Type units) { this("birthDeathSerialSamplingModel", lambda, mu, psi, p, relativeDeath, r, hasFinalSample, origin, units); } public BirthDeathSerialSamplingModel( String modelName, Variable<Double> lambda, Variable<Double> mu, Variable<Double> psi, Variable<Double> p, boolean relativeDeath, Variable<Double> r, boolean hasFinalSample, Variable<Double> origin, Type units) { super(modelName, units); this.relativeDeath = relativeDeath; this.lambda = lambda; addVariable(lambda); lambda.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); this.mu = mu; addVariable(mu); mu.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); this.psi = psi; addVariable(psi); psi.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); this.p = p; addVariable(p); p.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); this.hasFinalSample = hasFinalSample; this.r = r; addVariable(r); r.addBounds(new Parameter.DefaultBounds(1.0, 0.0, 1)); this.origin = origin; if (origin != null) { addVariable(origin); origin.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1)); } } /** * @param b birth rate * @param d death rate * @param p proportion sampled at final time point * @param psi rate of sampling per lineage per unit time * @param t time * @return the probability of no sampled descendants after time, t */ public static double p0(double b, double d, double p, double psi, double t) { double c1 = c1(b, d, psi); double c2 = c2(b, d, p, psi); double expc1trc2 = Math.exp(-c1 * t) * (1.0 - c2); return (b + d + psi + c1 * ((expc1trc2 - (1.0 + c2)) / (expc1trc2 + (1.0 + c2)))) / (2.0 * b); } public static double q(double b, double d, double p, double psi, double t) { double c1 = c1(b, d, psi); double c2 = c2(b, d, p, psi); double res = 2.0 * (1.0 - c2 * c2) + Math.exp(-c1 * t) * (1.0 - c2) * (1.0 - c2) + Math.exp(c1 * t) * (1.0 + c2) * (1.0 + c2); return res; } private static double c1(double b, double d, double psi) { return Math.abs(Math.sqrt(Math.pow(b - d - psi, 2.0) + 4.0 * b * psi)); } private static double c2(double b, double d, double p, double psi) { return -(b - d - 2.0 * b * p - psi) / c1(b, d, psi); } public double p0(double t) { return p0(birth(), death(), p(), psi(), t); } public double q(double t) { return q(birth(), death(), p(), psi(), t); } private double c1() { return c1(birth(), death(), psi()); } private double c2() { return c2(birth(), death(), p(), psi()); } public double birth() { if (mask != null) return mask.birth(); return lambda.getValue(0); } public double death() { if (mask != null) return mask.death(); return relativeDeath ? mu.getValue(0) * birth() : mu.getValue(0); } public double psi() { if (mask != null) return mask.psi(); return psi.getValue(0); } /** * @return the proportion of population sampled at final sample, or zero if there is no final sample */ public double p() { if (mask != null) return mask.p.getValue(0); return hasFinalSample ? p.getValue(0) : 0; } public double r() { if (mask != null) return mask.r(); return r.getValue(0); } // The mask does not affect the following three methods public boolean isSamplingOrigin() { return origin != null; } public double x0() { return origin.getValue(0); } /** * Generic likelihood calculation * * @param tree the tree to calculate likelihood of * @return log-likelihood of density */ public final double calculateTreeLogLikelihood(Tree tree) { if (isSamplingOrigin() && x0() < tree.getNodeHeight(tree.getRoot())) { return Double.NEGATIVE_INFINITY; // throw new RuntimeException("Orign value (" + x0() + ") cannot < tree root height (" + tree.getNodeHeight(tree.getRoot()) + ")"); } //System.out.println("calculating tree log likelihood"); //double time = finalTimeInterval(); // extant leaves int n = 0; // extinct leaves int m = 0; for (int i = 0; i < tree.getExternalNodeCount(); i++) { NodeRef node = tree.getExternalNode(i); if (tree.getNodeHeight(node) == 0.0) { n += 1; } else { m += 1; } } if (!hasFinalSample && n != 1) { throw new RuntimeException( "For sampling-through-time model there must be exactly one tip at time zero."); } double x1 = tree.getNodeHeight(tree.getRoot()); double c1 = c1(); double c2 = c2(); double b = birth(); double p = p(); double logL; if (isSamplingOrigin()) { logL = Math.log(1.0 / q(x0())); //System.out.println("originLogL=" + logL + " x0"); } else { throw new RuntimeException( "The origin must be sampled, as integrating it out is not implemented!"); // integrating out the time between the origin and the root of the tree //double bottom = c1 * (c2 + 1) * (1 - c2 + (1 + c2) * Math.exp(c1 * x1)); //logL = Math.log(1 / bottom); } if (hasFinalSample) { logL += n * Math.log(4.0 * p); } for (int i = 0; i < tree.getInternalNodeCount(); i++) { double x = tree.getNodeHeight(tree.getInternalNode(i)); logL += Math.log(b / q(x)); //System.out.println("internalNodeLogL=" + Math.log(b / q(x))); } for (int i = 0; i < tree.getExternalNodeCount(); i++) { double y = tree.getNodeHeight(tree.getExternalNode(i)); if (y > 0.0) { logL += Math.log(psi() * (r() + (1.0 - r()) * p0(y)) * q(y)); //System.out.println("externalNodeLogL=" + Math.log(psi() * (r() + (1.0 - r()) * p0(y)) * q(y))); } else if (!hasFinalSample) { //handle condition ending on final tip in sampling-through-time-only situation logL += Math.log(psi() * q(y)); // System.out.println("externalNodeLogL=" + Math.log(psi() * q(y))); } } return logL; } public double calculateTreeLogLikelihood(Tree tree, Set<Taxon> exclude) { if (exclude.size() == 0) return calculateTreeLogLikelihood(tree); throw new RuntimeException("Not implemented!"); } public void mask(SpeciationModel mask) { if (mask instanceof BirthDeathSerialSamplingModel) { this.mask = (BirthDeathSerialSamplingModel) mask; } else { throw new IllegalArgumentException(); } } public void unmask() { mask = null; } // if a mask exists then use the mask's parameters instead (except for origin and finalTimeInterval) BirthDeathSerialSamplingModel mask = null; }
package dr.evomodelxml.branchratemodel; import dr.evolution.tree.TreeUtils; import dr.evolution.util.Taxa; import dr.evolution.util.TaxonList; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.branchratemodel.LocalClockModel; import dr.evomodel.tree.TreeModel; import dr.inference.model.Parameter; import dr.xml.*; import java.util.logging.Logger; public class LocalClockModelParser extends AbstractXMLObjectParser { public static final String LOCAL_CLOCK_MODEL = "localClockModel"; public static final String RATE = BranchRateModel.RATE; public static final String RELATIVE = "relative"; public static final String CLADE = "clade"; public static final String INCLUDE_STEM = "includeStem"; public static final String STEM_PROPORTION = "stemProportion"; public static final String EXCLUDE_CLADE = "excludeClade"; public static final String EXTERNAL_BRANCHES = "externalBranches"; public static final String TRUNK = "trunk"; public static final String INDEX = "index"; public String getParserName() { return LOCAL_CLOCK_MODEL; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); LocalClockModel localClockModel; if (xo.getElementFirstChild(RATE) instanceof BranchRateModel) { BranchRateModel globalBranchRates = (BranchRateModel) xo.getElementFirstChild(RATE); localClockModel = new LocalClockModel(tree, globalBranchRates); } else { Parameter globalRateParameter = (Parameter) xo.getElementFirstChild(RATE); localClockModel = new LocalClockModel(tree, globalRateParameter); } for (int i = 0; i < xo.getChildCount(); i++) { if (xo.getChild(i) instanceof XMLObject) { XMLObject xoc = (XMLObject) xo.getChild(i); Parameter rateParameter = null; BranchRateModel branchRates = (BranchRateModel) xoc.getChild(BranchRateModel.class); if (branchRates == null) { rateParameter = (Parameter) xoc.getChild(Parameter.class); } if (xoc.getName().equals(CLADE)) { boolean relative = xoc.getAttribute(RELATIVE, false); TaxonList taxonList = (TaxonList) xoc.getChild(TaxonList.class); if (taxonList.getTaxonCount() == 1) { throw new XMLParseException("A local clock for a clade must be defined by at least two taxa"); } boolean excludeClade = false; double stemProportion = 0.0; if (xoc.hasAttribute(INCLUDE_STEM)) { // if includeStem=true then assume it is the whole stem stemProportion = xoc.getBooleanAttribute(INCLUDE_STEM) ? 1.0 : 0.0; } if (xoc.hasAttribute(STEM_PROPORTION)) { stemProportion = xoc.getDoubleAttribute(STEM_PROPORTION); if (stemProportion < 0.0 || stemProportion > 1.0) { throw new XMLParseException("A stem proportion should be between 0, 1"); } } if (xoc.hasAttribute(EXCLUDE_CLADE)) { excludeClade = xoc.getBooleanAttribute(EXCLUDE_CLADE); } try { if (branchRates != null) { localClockModel.addCladeClock(taxonList, branchRates, relative, stemProportion, excludeClade); } else { localClockModel.addCladeClock(taxonList, rateParameter, relative, stemProportion, excludeClade); } } catch (TreeUtils.MissingTaxonException mte) { throw new XMLParseException("Taxon, " + mte + ", in " + getParserName() + " was not found in the tree."); } } else if (xoc.getName().equals(EXTERNAL_BRANCHES)) { boolean relative = xoc.getAttribute(RELATIVE, false); TaxonList taxonList = (TaxonList) xoc.getChild(TaxonList.class); try { if (branchRates != null) { localClockModel.addExternalBranchClock(taxonList, branchRates, relative); } else { localClockModel.addExternalBranchClock(taxonList, rateParameter, relative); } } catch (TreeUtils.MissingTaxonException mte) { throw new XMLParseException("Taxon, " + mte + ", in " + getParserName() + " was not found in the tree."); } } else if (xoc.getName().equals(TRUNK)) { boolean relative = xoc.getAttribute(RELATIVE, false); Parameter indexParameter = null; if (xoc.hasChildNamed(INDEX)) { indexParameter = (Parameter) xoc.getElementFirstChild(INDEX); } TaxonList taxonList = (TaxonList) xoc.getChild(TaxonList.class); try { if (branchRates != null) { localClockModel.addTrunkClock(taxonList, branchRates, indexParameter, relative); } else { localClockModel.addTrunkClock(taxonList, rateParameter, indexParameter, relative); } } catch (TreeUtils.MissingTaxonException mte) { throw new XMLParseException("Taxon, " + mte + ", in " + getParserName() + " was not found in the tree."); } } } } Logger.getLogger("dr.evomodel").info("\nUsing local clock branch rate model."); return localClockModel; }
package edu.iu.grid.oim.model.db; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import javax.security.auth.x500.X500Principal; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.pkcs.Attribute; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x500.RDN; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.asn1.x509.Extensions; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.cms.CMSException; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.crypto.util.PublicKeyFactory; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.util.encoders.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import edu.iu.grid.oim.lib.Authorization; import edu.iu.grid.oim.lib.Footprints; import edu.iu.grid.oim.lib.StaticConfig; import edu.iu.grid.oim.lib.Footprints.FPTicket; import edu.iu.grid.oim.lib.StringArray; import edu.iu.grid.oim.model.CertificateRequestStatus; import edu.iu.grid.oim.model.UserContext; import edu.iu.grid.oim.model.cert.CertificateManager; import edu.iu.grid.oim.model.cert.ICertificateSigner.CertificateBase; import edu.iu.grid.oim.model.cert.ICertificateSigner.CertificateProviderException; import edu.iu.grid.oim.model.cert.ICertificateSigner.IHostCertificatesCallBack; import edu.iu.grid.oim.model.db.record.CertificateRequestHostRecord; import edu.iu.grid.oim.model.db.record.ContactRecord; import edu.iu.grid.oim.model.db.record.DNRecord; import edu.iu.grid.oim.model.db.record.GridAdminRecord; import edu.iu.grid.oim.model.db.record.VORecord; import edu.iu.grid.oim.model.exceptions.CertificateRequestException; import edu.iu.grid.oim.view.divrep.form.validator.CNValidator; public class CertificateRequestHostModel extends CertificateRequestModelBase<CertificateRequestHostRecord> { static Logger log = Logger.getLogger(CertificateRequestHostModel.class); public CertificateRequestHostModel(UserContext _context) { super(_context, "certificate_request_host"); } //NO-AC public CertificateRequestHostRecord get(int id) throws SQLException { CertificateRequestHostRecord rec = null; ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); if (stmt.execute("SELECT * FROM "+table_name+ " WHERE id = " + id)) { rs = stmt.getResultSet(); if(rs.next()) { rec = new CertificateRequestHostRecord(rs); } } stmt.close(); conn.close(); return rec; } //return requests that I have submitted public ArrayList<CertificateRequestHostRecord> getISubmitted(Integer id) throws SQLException { ArrayList<CertificateRequestHostRecord> ret = new ArrayList<CertificateRequestHostRecord>(); ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); stmt.execute("SELECT * FROM "+table_name + " WHERE requester_contact_id = " + id); rs = stmt.getResultSet(); while(rs.next()) { ret.add(new CertificateRequestHostRecord(rs)); } stmt.close(); conn.close(); return ret; } //return requests that I am GA public ArrayList<CertificateRequestHostRecord> getIApprove(Integer id) throws SQLException { ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>(); //list all domains that user is gridadmin of StringBuffer cond = new StringBuffer(); HashSet<Integer> vos = new HashSet<Integer>(); GridAdminModel model = new GridAdminModel(context); try { for(GridAdminRecord grec : model.getGridAdminsByContactID(id)) { if(cond.length() != 0) { cond.append(" OR "); } cond.append("cns LIKE '%"+StringEscapeUtils.escapeSql(grec.domain)+"</String>%'"); vos.add(grec.vo_id); } } catch (SQLException e1) { log.error("Failed to lookup GridAdmin domains", e1); } String vos_list = ""; for(Integer vo : vos) { if(vos_list.length() != 0) { vos_list += ","; } vos_list += vo; } if(cond.length() != 0) { ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); System.out.println("Searching SQL: SELECT * FROM "+table_name + " WHERE ("+cond.toString() + ") AND approver_vo_id in ("+vos_list+") AND status in ('REQUESTED','RENEW_REQUESTED','REVOKE_REQUESTED')"); stmt.execute("SELECT * FROM "+table_name + " WHERE ("+cond.toString() + ") AND approver_vo_id in ("+vos_list+") AND status in ('REQUESTED','RENEW_REQUESTED','REVOKE_REQUESTED')"); rs = stmt.getResultSet(); while(rs.next()) { recs.add(new CertificateRequestHostRecord(rs)); } stmt.close(); conn.close(); } return recs; } //NO-AC //issue all requested certs and store it back to DB //you can monitor request status by checking returned Certificate[] public void startissue(final CertificateRequestHostRecord rec) throws CertificateRequestException { // mark the request as "issuing.." try { rec.status = CertificateRequestStatus.ISSUING; context.setComment("Starting to issue certificates."); super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to update certificate request status for request:" + rec.id); throw new CertificateRequestException("Failed to update certificate request status"); }; //reconstruct cert array from db final StringArray csrs = new StringArray(rec.csrs); final StringArray serial_ids = new StringArray(rec.cert_serial_ids); final StringArray pkcs7s = new StringArray(rec.cert_pkcs7); final StringArray certificates = new StringArray(rec.cert_certificate); final StringArray intermediates = new StringArray(rec.cert_intermediate); final StringArray statuses = new StringArray(rec.cert_statuses); final CertificateBase[] certs = new CertificateBase[csrs.length()]; for(int c = 0; c < csrs.length(); ++c) { certs[c] = new CertificateBase(); certs[c].csr = csrs.get(c); certs[c].serial = serial_ids.get(c); certs[c].certificate = certificates.get(c); certs[c].intermediate = intermediates.get(c); certs[c].pkcs7 = pkcs7s.get(c); } new Thread(new Runnable() { public void failed(String message, Throwable e) { log.error(message, e); rec.status = CertificateRequestStatus.FAILED; rec.status_note = message + " :: " + e.getMessage(); try { context.setComment(message + " :: " + e.getMessage()); CertificateRequestHostModel.super.update(get(rec.id), rec); } catch (SQLException e1) { log.error("Failed to update request status while processing failed condition :" + message, e1); } //update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.description = "Failed to issue certificate.\n\n"; ticket.description += message+"\n\n"; ticket.description += e.getMessage()+"\n\n"; ticket.description += "The alert has been sent to GOC alert for further actions on this issue."; ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.fail.assignee")); ticket.nextaction = "GOC developer to investigate"; fp.update(ticket, rec.goc_ticket_id); } //should we use Quartz instead? public void run() { final CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id); try { //lookup requester contact information String requester_email = rec.requester_email; //for guest request if(rec.requester_contact_id != null) { //for user request ContactModel cmodel = new ContactModel(context); ContactRecord requester = cmodel.get(rec.requester_contact_id); requester_email = requester.primary_email; } log.debug("Starting signing process"); cm.signHostCertificates(certs, new IHostCertificatesCallBack() { //called once all certificates are requested (and approved) - but not yet issued @Override public void certificateRequested() { log.debug("certificateRequested called"); //update certs db contents try { for(int c = 0; c < certs.length; ++c) { CertificateBase cert = certs[c]; serial_ids.set(c, cert.serial); //really just order ID (until the certificate is issued) statuses.set(c, CertificateRequestStatus.ISSUING); } rec.cert_serial_ids = serial_ids.toXML(); rec.cert_statuses = statuses.toXML(); context.setComment("All certificate requests have been sent."); CertificateRequestHostModel.super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to update certificate update while monitoring issue progress:" + rec.id); } } //called for each certificate issued @Override public void certificateSigned(CertificateBase cert, int idx) { log.info("host cert issued by digicert: serial_id:" + cert.serial); log.info("pkcs7:" + cert.pkcs7); //pull some information from the cert for validation purpose try { ArrayList<Certificate> chain = CertificateManager.parsePKCS7(cert.pkcs7); X509Certificate c0 = CertificateManager.getIssuedX509Cert(chain); cert.notafter = c0.getNotAfter(); cert.notbefore = c0.getNotBefore(); //do a bit of validation Calendar today = Calendar.getInstance(); if(Math.abs(today.getTimeInMillis() - cert.notbefore.getTime()) > 1000*3600*24) { log.warn("Host certificate issued for request "+rec.id+"(idx:"+idx+") has cert_notbefore set too distance from current timestamp"); } long dayrange = (cert.notafter.getTime() - cert.notbefore.getTime()) / (1000*3600*24); if(dayrange < 350 || dayrange > 450) { log.warn("Host certificate issued for request "+rec.id+ "(idx:"+idx+") has invalid range of "+dayrange+" days (too far from 395 days)"); } //make sure dn starts with correct base X500Principal dn = c0.getSubjectX500Principal(); String apache_dn = CertificateManager.X500Principal_to_ApacheDN(dn); if(!apache_dn.startsWith(cm.getHostDNBase())) { log.error("Host certificate issued for request " + rec.id + "(idx:"+idx+") has DN:"+apache_dn+" which doesn't have an expected DN base: "+cm.getHostDNBase()); } } catch (CertificateException e1) { log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1); } catch (CMSException e1) { log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1); } catch (IOException e1) { log.error("Failed to validate host certificate (pkcs7) issued. ID:" + rec.id+"(idx:"+idx+")", e1); } //update status note try { statuses.set(idx, CertificateRequestStatus.ISSUED); rec.cert_statuses = statuses.toXML(); rec.status_note = "Certificate idx:"+idx+" has been issued. Serial Number: " + cert.serial; context.setComment(rec.status_note); CertificateRequestHostModel.super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to update certificate update while monitoring issue progress:" + rec.id); } } }, requester_email); log.debug("Finishing up issue process"); //update records int idx = 0; StringArray cert_certificates = new StringArray(rec.cert_certificate); StringArray cert_intermediates = new StringArray(rec.cert_intermediate); StringArray cert_pkcs7s = new StringArray(rec.cert_pkcs7); StringArray cert_serial_ids = new StringArray(rec.cert_serial_ids); for(CertificateBase cert : certs) { cert_certificates.set(idx, cert.certificate); rec.cert_certificate = cert_certificates.toXML(); cert_intermediates.set(idx, cert.intermediate); rec.cert_intermediate = cert_intermediates.toXML(); cert_pkcs7s.set(idx, cert.pkcs7); rec.cert_pkcs7 = cert_pkcs7s.toXML(); cert_serial_ids.set(idx, cert.serial); rec.cert_serial_ids = cert_serial_ids.toXML(); ++idx; } //set cert expiriation dates using the first certificate issued (out of many *requests*) CertificateBase cert = certs[0]; rec.cert_notafter = cert.notafter; rec.cert_notbefore = cert.notbefore; //log.debug("Updating status"); //update status try { rec.status = CertificateRequestStatus.ISSUED; context.setComment("All ceritificates has been issued."); CertificateRequestHostModel.super.update(get(rec.id), rec); } catch (SQLException e) { throw new CertificateRequestException("Failed to update status for certificate request: " + rec.id); } log.debug("Updating ticket"); //update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has issued certificate. Resolving this ticket."; } else { ticket.description = "Someone with IP address: " + context.getRemoteAddr() + " has issued certificate. Resolving this ticket."; } ticket.status = "Resolved"; //suppressing notification if submitter is GA ArrayList<ContactRecord> gas = findGridAdmin(rec); boolean submitter_is_ga = false; for(ContactRecord ga : gas) { if(ga.id.equals(rec.requester_contact_id)) { submitter_is_ga = true; break; } } if(submitter_is_ga) { ticket.mail_suppression_assignees = true; ticket.mail_suppression_submitter = true; ticket.mail_suppression_ccs = true; } fp.update(ticket, rec.goc_ticket_id); } catch (CertificateProviderException e) { failed("Failed to sign certificate -- CertificateProviderException ", e); } catch (SQLException e) { failed("Failed to sign certificate -- most likely couldn't lookup requester contact info", e); } catch(Exception e) { failed("Failed to sign certificate -- unhandled", e); } } }).start(); } //NO-AC //return true if success public void approve(CertificateRequestHostRecord rec) throws CertificateRequestException { //get number of certificate requested for this request String [] cns = rec.getCNs(); int count = cns.length; //check quota CertificateQuotaModel quota = new CertificateQuotaModel(context); if(!quota.canApproveHostCert(count)) { throw new CertificateRequestException("You will exceed your host certificate quota."); } rec.status = CertificateRequestStatus.APPROVED; try { //context.setComment("Certificate Approved"); super.update(get(rec.id), rec); quota.incrementHostCertApproval(count); } catch (SQLException e) { log.error("Failed to approve host certificate request: " + rec.id); throw new CertificateRequestException("Failed to update certificate request record"); } //find if requester is ga ArrayList<ContactRecord> gas = findGridAdmin(rec); boolean submitter_is_ga = false; for(ContactRecord ga : gas) { if(ga.id.equals(rec.requester_contact_id)) { submitter_is_ga = true; break; } } //update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); if(submitter_is_ga) { ticket.description = rec.requester_name + " has approved this host certificate request.\n\n"; ticket.mail_suppression_assignees = false; //Per Von/Alain's request, we will send notification to Alain when request is approved ticket.mail_suppression_ccs = true; ticket.mail_suppression_submitter = true; } else { ticket.description = "Dear " + rec.requester_name + ",\n\n"; ticket.description += "Your host certificate request has been approved. \n\n"; } ticket.description += "To retrieve the certificate please visit " + getTicketUrl(rec.id) + " and click on Issue Certificate button.\n\n"; if(StaticConfig.isDebug()) { ticket.description += "Or if you are using the command-line: osg-cert-retrieve -T -i "+rec.id+"\n\n"; } else { ticket.description += "Or if you are using the command-line: osg-cert-retrieve -i "+rec.id+"\n\n"; } ticket.nextaction = "Requester to download certificate"; Calendar nad = Calendar.getInstance(); nad.add(Calendar.DATE, 7); ticket.nad = nad.getTime(); fp.update(ticket, rec.goc_ticket_id); } //NO-AC (for authenticated user) //return request record if successful, otherwise null public CertificateRequestHostRecord requestAsUser( ArrayList<String> csrs, ContactRecord requester, String request_comment, String[] request_ccs, Integer approver_vo_id) throws CertificateRequestException { CertificateRequestHostRecord rec = new CertificateRequestHostRecord(); //Date current = new Date(); rec.requester_contact_id = requester.id; rec.requester_name = requester.name; rec.approver_vo_id = approver_vo_id; rec.requester_email = requester.primary_email; //rec.requester_phone = requester.primary_phone; Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.name = requester.name; ticket.email = requester.primary_email; ticket.phone = requester.primary_phone; ticket.title = "Host Certificate Request by " + requester.name + "(OIM user)"; ticket.metadata.put("SUBMITTER_NAME", requester.name); if(request_ccs != null) { for(String cc : request_ccs) { ticket.ccs.add(cc); } } log.debug("submitting request as user"); return request(csrs, rec, ticket, request_comment); } //NO-AC (for guest user) //return request record if successful, otherwise null public CertificateRequestHostRecord requestAsGuest( ArrayList<String> csrs, String requester_name, String requester_email, String requester_phone, String request_comment, String[] request_ccs, Integer approver_vo_id) throws CertificateRequestException { CertificateRequestHostRecord rec = new CertificateRequestHostRecord(); //Date current = new Date(); rec.approver_vo_id = approver_vo_id; rec.requester_name = requester_name; rec.requester_email = requester_email; Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.name = requester_name; ticket.email = requester_email; ticket.phone = requester_phone; ticket.title = "Host Certificate Request by " + requester_name + "(Guest)"; ticket.metadata.put("SUBMITTER_NAME", requester_name); if(request_ccs != null) { for(String cc : request_ccs) { ticket.ccs.add(cc); } } return request(csrs, rec, ticket, request_comment); } private String getTicketUrl(Integer request_id) { String base; //this is not an exactly correct assumption, but it should be good enough if(StaticConfig.isDebug()) { base = "https://oim-itb.grid.iu.edu/oim/"; } else { base = "https://oim.grid.iu.edu/oim/"; } return base + "certificatehost?id=" + request_id; } //NO-AC //return request record if successful, otherwise null (guest interface) private CertificateRequestHostRecord request( ArrayList<String> csrs, CertificateRequestHostRecord rec, FPTicket ticket, String request_comment) throws CertificateRequestException { //log.debug("request"); Date current = new Date(); rec.request_time = new Timestamp(current.getTime()); rec.status = CertificateRequestStatus.REQUESTED; //set all host cert status to REQUESTED StringArray statuses = new StringArray(csrs.size()); for(int c = 0; c < csrs.size(); ++c) { statuses.set(c, CertificateRequestStatus.REQUESTED); } rec.cert_statuses = statuses.toXML(); if(request_comment != null) { rec.status_note = request_comment; context.setComment(request_comment); } //store CSRs / CNs to record StringArray csrs_sa = new StringArray(csrs.size()); StringArray cns_sa = new StringArray(csrs.size()); int idx = 0; CNValidator cnv = new CNValidator(CNValidator.Type.HOST); for(String csr_string : csrs) { log.debug("processing csr: " + csr_string); String cn; ArrayList<String> sans; try { PKCS10CertificationRequest csr = CertificateManager.parseCSR(csr_string); cn = CertificateManager.pullCNFromCSR(csr); sans = CertificateManager.pullSANFromCSR(csr); //validate CN //if(!cn.matches("^([-0-9a-zA-Z\\.]*/)?[-0-9a-zA-Z\\.]*$")) { //OSGPKI-255 // throw new CertificateRequestException("CN structure is invalid, or contains invalid characters."); if(!cnv.isValid(cn)) { throw new CertificateRequestException("CN specified is invalid: " + cn + " .. " + cnv.getErrorMessage()); } for(String san : sans) { if(!cnv.isValid(san)) { throw new CertificateRequestException("SAN specified is invalid: " + san + " .. " + cnv.getErrorMessage()); } } //check private key strength SubjectPublicKeyInfo pkinfo = csr.getSubjectPublicKeyInfo(); RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkinfo); int keysize = rsa.getModulus().bitLength(); if(keysize < 2048) { throw new CertificateRequestException("Please use RSA keysize greater than or equal to 2048 bits."); } cns_sa.set(idx, cn); } catch (IOException e) { log.error("Failed to base64 decode CSR", e); throw new CertificateRequestException("Failed to base64 decode CSR:"+csr_string, e); } catch (NullPointerException e) { log.error("(probably) couldn't find CN inside the CSR:"+csr_string, e); throw new CertificateRequestException("Failed to base64 decode CSR", e); } csrs_sa.set(idx++, csr_string); } rec.csrs = csrs_sa.toXML(); rec.cns = cns_sa.toXML(); StringArray empty = new StringArray(csrs.size()); String empty_xml = empty.toXML(); rec.cert_certificate = empty_xml; rec.cert_intermediate = empty_xml; rec.cert_pkcs7 = empty_xml; rec.cert_serial_ids = empty_xml; try { ArrayList<ContactRecord> gas = findGridAdmin(rec); //find if submitter is ga boolean submitter_is_ga = false; for(ContactRecord ga : gas) { if(ga.id.equals(rec.requester_contact_id)) { submitter_is_ga = true; break; } } //now submit - after this, we are commited. Integer request_id = super.insert(rec); if(submitter_is_ga) { ticket.description = "Host certificate request has been submitted by a GridAdmin.\n\n"; ticket.mail_suppression_assignees = true; ticket.mail_suppression_submitter = true; ticket.mail_suppression_ccs = true; } else { ticket.description = "Dear GridAdmin; "; for(ContactRecord ga : gas) { ticket.description += ga.name + ", "; ticket.ccs.add(ga.primary_email); } ticket.description += "\n\n"; ticket.description += "Host certificate request has been submitted. "; ticket.description += "Please determine this request's authenticity, and approve / disapprove at " + getTicketUrl(request_id) + "\n\n"; } ticket.description += "CNs requested:\n"; for(String cn : cns_sa.getAll()) { ticket.description += "/CN=" + cn + "\n"; } Authorization auth = context.getAuthorization(); ticket.description += "Requester IP:" + context.getRemoteAddr() + "\n"; if(auth.isUser()) { ContactRecord user = auth.getContact(); ticket.description += "Submitter is OIM authenticated with DN:" + auth.getUserDN() + "\n"; } if(request_comment != null) { ticket.description += "Requester Comment: "+request_comment; } ticket.assignees.add(StaticConfig.conf.getProperty("certrequest.host.assignee")); ticket.nextaction = "GridAdmin to verify requester"; Calendar nad = Calendar.getInstance(); nad.add(Calendar.DATE, 7); ticket.nad = nad.getTime(); //set metadata ticket.metadata.put("SUBMITTED_VIA", "OIM/CertManager(host)"); if(auth.isUser()) { ticket.metadata.put("SUBMITTER_DN", auth.getUserDN()); } //all ready to submit request Footprints fp = new Footprints(context); log.debug("opening footprints ticket"); String ticket_id = fp.open(ticket); log.debug("update request record with goc ticket id"); rec.goc_ticket_id = ticket_id; context.setComment("Opened GOC Ticket " + ticket_id); super.update(get(request_id), rec); log.debug("request updated"); } catch (SQLException e) { throw new CertificateRequestException("Failed to insert host certificate request record", e); } log.debug("returnign rec"); return rec; } //find gridadmin who should process the request - identify domain from csrs //if there are more than 1 vos group, then user must specify approver_vo_id // * it could be null for gridadmin with only 1 vo group, and approver_vo_id will be reset to the correct VO ID public ArrayList<ContactRecord> findGridAdmin(CertificateRequestHostRecord rec) throws CertificateRequestException { GridAdminModel gamodel = new GridAdminModel(context); String gridadmin_domain = null; int idx = 0; ArrayList<String> domains = new ArrayList<String>(); String[] csrs = rec.getCSRs(); if(csrs.length == 0) { throw new CertificateRequestException("No CSR"); } for(String csr_string : csrs) { //parse CSR and pull CN String cn; ArrayList<String> sans; try { PKCS10CertificationRequest csr = CertificateManager.parseCSR(csr_string); cn = CertificateManager.pullCNFromCSR(csr); sans = CertificateManager.pullSANFromCSR(csr); } catch (IOException e) { log.error("Failed to base64 decode CSR", e); throw new CertificateRequestException("Failed to base64 decode CSR:"+csr_string, e); } catch (NullPointerException e) { log.error("(probably) couldn't find CN inside the CSR:"+csr_string, e); throw new CertificateRequestException("Failed to base64 decode CSR", e); } catch(Exception e) { throw new CertificateRequestException("Failed to decode CSR", e); } //lookup registered gridadmin domain String domain = null; try { domain = gamodel.getDomainByFQDN(cn); } catch (SQLException e) { throw new CertificateRequestException("Failed to lookup GridAdmin to approve host:" + cn, e); } if(domain == null) { throw new CertificateRequestException("The hostname you have provided in the CSR/CN=" + cn + " does not match any domain OIM is currently configured to issue certificates for.\n\nPlease double check the CN you have specified. If you'd like to be a GridAdmin for this domain, please open GOC Ticket at https://ticket.grid.iu.edu "); } //make sure same set of gridadmin approves all host if(gridadmin_domain == null) { gridadmin_domain = domain; log.debug("first domain is " + gridadmin_domain); } else { if(!gridadmin_domain.equals(domain)) { //throw new CertificateRequestException("All host certificates must be approved by the same set of gridadmins. Different for " + cn); domains.add(domain); log.debug("Next domain is " + domain); } } //make sure SANs are also approved by the same domain or share a common GridAdmin for(String san : sans) { try { String san_domain = gamodel.getDomainByFQDN(san); if(!gridadmin_domain.equals(san_domain)) { //throw new CertificateRequestException("All SAN must be approved by the same set of gridadmins. Different for " + san); domains.add(san_domain); log.debug("san domain is " + san_domain); } } catch (SQLException e) { throw new CertificateRequestException("Failed to lookup GridAdmin for SAN:" + san, e); } } } try { //for first domain in the list, add the grid admins. For each additional domain remove all non-matching grid-admins ArrayList<ContactRecord> gas = new ArrayList<ContactRecord> (); HashMap<VORecord, ArrayList<GridAdminRecord>> groups = gamodel.getByDomainGroupedByVO(gridadmin_domain); if(groups.size() == 0) { throw new CertificateRequestException("No gridadmin exists for domain: " + gridadmin_domain); } if(groups.size() == 1 && rec.approver_vo_id == null) { //set approver_vo_id to the one and only one vogroup's vo id Iterator<VORecord> it = groups.keySet().iterator(); VORecord vorec = it.next(); rec.approver_vo_id = vorec.id; } String vonames = ""; for(VORecord vo : groups.keySet()) { vonames += vo.name + ", "; //just in case we might need to report error message later if(vo.id.equals(rec.approver_vo_id)) { log.debug("found a match.. return the list " + vo.name); gas.addAll(GAsToContacts(groups.get(vo))); } } for (String domain : domains) { //HashMap<VORecord, ArrayList<GridAdminRecord>> groups = gamodel.getByDomainGroupedByVO(gridadmin_domain); log.debug("looking up approvers for domain " + domain); groups = gamodel.getByDomainGroupedByVO(domain); if(groups.size() == 0) { throw new CertificateRequestException("No gridadmin exists for domain: " + domain); } if(groups.size() == 1 && rec.approver_vo_id == null) { Iterator<VORecord> it = groups.keySet().iterator(); VORecord vorec = it.next(); rec.approver_vo_id = vorec.id; log.debug("set approver_vo_id to the one and only one vogroup's vo id " + rec.approver_vo_id); } vonames = ""; log.debug("For each vo record for " + domain); int match_id = 0; for(VORecord vo : groups.keySet()) { log.debug(vo.name); vonames += vo.name + ", "; //just in case we might need to report error message later if(vo.id.equals(rec.approver_vo_id)) { match_id = vo.id; log.debug("found an exact match.. return the list " + vo.name); ArrayList<ContactRecord> newgas = GAsToContacts(groups.get(vo)); if (newgas.isEmpty()) { log.debug("no contacts for " + vo.name); } ArrayList<ContactRecord> sharedgas = new ArrayList<ContactRecord>(); for(ContactRecord contact: newgas) { log.debug("checking contact name " + contact.name); if (gas.contains(contact)) { sharedgas.add(contact); log.debug("adding " + contact.name); } } gas = sharedgas; //return GAsToContacts(gas); } } if (match_id == 0) { for(VORecord vo : groups.keySet()) { log.debug(vo.name); vonames += vo.name + ", "; //just in case we might need to report error message later //if(vo.id.equals(rec.approver_vo_id)) { log.debug("matching using the list " + vo.name); ArrayList<ContactRecord> newgas = GAsToContacts(groups.get(vo)); if (newgas.isEmpty()) { log.debug("no contacts for " + vo.name); } ArrayList<ContactRecord> sharedgas = new ArrayList<ContactRecord>(); for(ContactRecord contact: newgas) { log.debug("checking contact name " + contact.name); if (gas.contains(contact)) { sharedgas.add(contact); log.debug("adding " + contact.name); } } gas = sharedgas; //return GAsToContacts(gas); } } } if (!gas.isEmpty()) { return gas; } else { //oops.. didn't find specified vo.. throw new CertificateRequestException("Couldn't find GridAdmin group under specified VO."); } } catch (SQLException e) { throw new CertificateRequestException("Failed to lookup gridadmin contacts for domain:" + gridadmin_domain, e); } } public ArrayList<ContactRecord> GAsToContacts(ArrayList<GridAdminRecord> gas) throws SQLException { //convert contact_id to contact record ArrayList<ContactRecord> contacts = new ArrayList<ContactRecord>(); ContactModel cmodel = new ContactModel(context); for(GridAdminRecord ga : gas) { log.debug("adding contact id " + ga.contact_id); contacts.add(cmodel.get(ga.contact_id)); } return contacts; } //NO-AC public void requestRevoke(CertificateRequestHostRecord rec) throws CertificateRequestException { rec.status = CertificateRequestStatus.REVOCATION_REQUESTED; try { super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to request revocation of host certificate: " + rec.id); throw new CertificateRequestException("Failed to update request status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has requested revocation of this certificate request."; } else { ticket.description = "Guest user with IP:" + context.getRemoteAddr() + " has requested revocation of this certificate request."; } ticket.description += "\n\nPlease approve / disapprove this request at " + getTicketUrl(rec.id); ticket.nextaction = "Grid Admin to process request."; //nad will be set to 7 days from today by default ticket.status = "Engineering"; //I need to reopen resolved ticket. fp.update(ticket, rec.goc_ticket_id); } //NO-AC //return true if success public void cancel(CertificateRequestHostRecord rec) throws CertificateRequestException { try { if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) || rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { rec.status = CertificateRequestStatus.ISSUED; } else { rec.status = CertificateRequestStatus.CANCELED; } super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to cancel host certificate request:" + rec.id); throw new CertificateRequestException("Failed to cancel request status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has canceled this request.\n\n"; } else { //Guest can still cancel by providing the password used to submit the request. } ticket.description += "\n\n> " + context.getComment(); ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } public void reject(CertificateRequestHostRecord rec) throws CertificateRequestException { if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED)|| rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { rec.status = CertificateRequestStatus.ISSUED; } else { //all others rec.status = CertificateRequestStatus.REJECTED; } try { //context.setComment("Certificate Approved"); super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to reject host certificate request:" + rec.id); throw new CertificateRequestException("Failed to reject request status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has rejected this certificate request.\n\n"; } else { throw new CertificateRequestException("Guest shouldn't be rejecting request"); } ticket.description += "> " + context.getComment(); ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } //NO-AC public void revoke(CertificateRequestHostRecord rec) throws CertificateRequestException { //revoke //CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id); String issuer_dn = ""; //by default ArrayList<Certificate> chain = null; try { if (rec.getPKCS7s()[0] != null) { chain = CertificateManager.parsePKCS7(rec.getPKCS7s()[0]); X509Certificate c0 = CertificateManager.getIssuedX509Cert(chain); X500Principal issuer = c0.getIssuerX500Principal(); issuer_dn = CertificateManager.X500Principal_to_ApacheDN(issuer); } } catch (CertificateException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (CMSException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (IOException e2) { // TODO Auto-generated catch block //e2.printStackTrace(); -this will error for cilogon } CertificateManager cm = CertificateManager.Factory(issuer_dn); try { String[] cert_serial_ids = rec.getSerialIDs(); StringArray statuses = new StringArray(rec.cert_statuses); for(int i = 0;i < cert_serial_ids.length; ++i) { //for(String cert_serial_id : cert_serial_ids) { //only revoke ones that are not yet revoked if(statuses.get(i).equals(CertificateRequestStatus.ISSUED)) { String cert_serial_id = cert_serial_ids[i]; log.info("Revoking certificate with serial ID: " + cert_serial_id); cm.revokeHostCertificate(cert_serial_id); statuses.set(i, CertificateRequestStatus.REVOKED); //TODO - how do I know the revocation succeeded or not? } } rec.cert_statuses = statuses.toXML(); } catch (CertificateProviderException e1) { log.error("Failed to revoke host certificate", e1); throw new CertificateRequestException("Failed to revoke host certificate", e1); } rec.status = CertificateRequestStatus.REVOKED; try { //context.setComment("Certificate Approved"); super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to update host certificate status: " + rec.id); throw new CertificateRequestException("Failed to update host certificate status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has revoked this certificate.\n\n"; } else { throw new CertificateRequestException("Guest shouldn't be revoking certificate"); } ticket.description += "> " + context.getComment(); ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } //NO-AC public void revoke(CertificateRequestHostRecord rec, int idx) throws CertificateRequestException { //make sure we have valid idx String[] cert_serial_ids = rec.getSerialIDs(); String cert_serial_id = cert_serial_ids[idx]; StringArray statuses = new StringArray(rec.cert_statuses); if(idx >= cert_serial_ids.length) { throw new CertificateRequestException("Invalid certififcate index:"+idx); } //revoke one CertificateManager cm = CertificateManager.Factory(context, rec.approver_vo_id); try { log.info("Revoking certificate with serial ID: " + cert_serial_id); cm.revokeHostCertificate(cert_serial_id); statuses.set(idx, CertificateRequestStatus.REVOKED); //TODO - how do I know the revocation succeeded or not? rec.cert_statuses = statuses.toXML(); } catch (CertificateProviderException e1) { log.error("Failed to revoke host certificate", e1); throw new CertificateRequestException("Failed to revoke host certificate", e1); } //set rec.status to REVOKED if all certificates are revoked boolean allrevoked = true; for(int i = 0;i < cert_serial_ids.length; ++i) { if(!statuses.get(i).equals(CertificateRequestStatus.REVOKED)) { allrevoked = false; break; } } if(allrevoked) { rec.status = CertificateRequestStatus.REVOKED; } try { //context.setComment("Revoked certificate with serial ID:"+cert_serial_id); super.update(get(rec.id), rec); } catch (SQLException e) { log.error("Failed to update host certificate status: " + rec.id); throw new CertificateRequestException("Failed to update host certificate status", e); } Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); Authorization auth = context.getAuthorization(); if(auth.isUser()) { ContactRecord contact = auth.getContact(); ticket.description = contact.name + " has revoked a certificate with serial ID:"+cert_serial_id+".\n\n"; } else { throw new CertificateRequestException("Guest shouldn't be revoking certificate!"); } ticket.description += "> " + context.getComment(); //ticket.status = "Resolved"; fp.update(ticket, rec.goc_ticket_id); } //determines if user should be able to view request details, logs, and download certificate (pkcs12 is session specific) public boolean canView(CertificateRequestHostRecord rec) { return true; } //true if user can approve request public boolean canApprove(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if( //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) || rec.status.equals(CertificateRequestStatus.REQUESTED)) { //^RA doesn't *approve* REVOKE_REQUESTED - RA just click on REVOKE button if(auth.isUser()) { //grid admin can appove it ContactRecord user = auth.getContact(); try { ArrayList<ContactRecord> gas = findGridAdmin(rec); for(ContactRecord ga : gas) { if(ga.id.equals(user.id)) { return true; } } } catch (CertificateRequestException e) { log.error("Failed to lookup gridadmin for " + rec.id + " while processing canApprove()", e); } } } return false; } public LogDetail getLastApproveLog(ArrayList<LogDetail> logs) { for(LogDetail log : logs) { if(log.status.equals("APPROVED")) { return log; } } return null; } public boolean canReject(CertificateRequestHostRecord rec) { return canApprove(rec); //same rule as approval } public boolean canCancel(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.REQUESTED) || rec.status.equals(CertificateRequestStatus.APPROVED) || //if renew_requesterd > approved cert is canceled, it should really go back to "issued", but currently it doesn't. //rec.status.equals(CertificateRequestStatus.RENEW_REQUESTED) || rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { if(auth.isUser()) { if(auth.allows("admin_gridadmin")) return true; //if user has admin_gridadmin priv (probably pki staff), then he/she can cancel it //requester can cancel one's own request if(rec.requester_contact_id != null) {//could be null if guest submitted it ContactRecord contact = auth.getContact(); if(rec.requester_contact_id.equals(contact.id)) return true; } //grid admin can cancel it ContactRecord user = auth.getContact(); try { ArrayList<ContactRecord> gas = findGridAdmin(rec); for(ContactRecord ga : gas) { if(ga.id.equals(user.id)) { return true; } } } catch (CertificateRequestException e) { log.error("Failed to lookup gridadmin for " + rec.id + " while processing canCancel()", e); } } } return false; } //why can't we just issue certificate after it's been approved? because we might have to create pkcs12 public boolean canIssue(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.APPROVED)) { if(rec.requester_contact_id == null) { //anyone can issue guest request return true; } else { if(auth.isUser()) { ContactRecord contact = auth.getContact(); //requester can issue if(rec.requester_contact_id.equals(contact.id)) return true; } } } return false; } public boolean canRequestRevoke(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if(rec.status.equals(CertificateRequestStatus.ISSUED)) { if(auth.isUser() && canRevoke(rec)) { //if user can directly revoke it, no need to request it return false; } //all else, allow return true; } return false; } public boolean canRevoke(CertificateRequestHostRecord rec) { if(!canView(rec)) return false; if( rec.status.equals(CertificateRequestStatus.ISSUED) || rec.status.equals(CertificateRequestStatus.REVOCATION_REQUESTED)) { if(auth.isUser()) { if(auth.allows("admin_gridadmin")) return true; //if user has admin_gridadmin priv (probably pki staff), then he/she can revoke it //requester oneself can revoke it if(rec.requester_contact_id != null) {//could be null if guest submitted it ContactRecord contact = auth.getContact(); if(rec.requester_contact_id.equals(contact.id)) return true; } //grid admin can revoke it ContactRecord user = auth.getContact(); try { ArrayList<ContactRecord> gas = findGridAdmin(rec); for(ContactRecord ga : gas) { if(ga.id.equals(user.id)) { return true; } } } catch (CertificateRequestException e) { log.error("Failed to lookup gridadmin for " + rec.id + " while processing canRevoke()", e); } } } return false; } //canRevokeOne public boolean canRevoke(CertificateRequestHostRecord rec, int idx) { if(!canRevoke(rec)) return false; StringArray statuses = new StringArray(rec.cert_statuses); return statuses.get(idx).equals(CertificateRequestStatus.ISSUED); } //NO AC public CertificateRequestHostRecord getBySerialID(String serial_id) throws SQLException { serial_id = normalizeSerialID(serial_id); CertificateRequestHostRecord rec = null; ResultSet rs = null; Connection conn = connectOIM(); PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM "+table_name+ " WHERE cert_serial_ids like ?"); pstmt.setString(1, "%>"+serial_id+"<%"); if (pstmt.executeQuery() != null) { rs = pstmt.getResultSet(); if(rs.next()) { rec = new CertificateRequestHostRecord(rs); } } pstmt.close(); conn.close(); return rec; } //pass null to not filter public ArrayList<CertificateRequestHostRecord> search(String cns_contains, String status, Date request_after, Date request_before, Integer signer) throws SQLException { ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>(); ResultSet rs = null; Connection conn = connectOIM(); String sql = "SELECT * FROM "+table_name+" WHERE 1 = 1"; if(cns_contains != null) { sql += " AND cns like \"%"+StringEscapeUtils.escapeSql(cns_contains)+"%\""; } if(status != null) { sql += " AND status = \""+StringEscapeUtils.escapeSql(status)+"\""; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(request_after != null) { sql += " AND request_time >= \""+sdf.format(request_after) + "\""; } if(request_before != null) { sql += " AND request_time <= \""+sdf.format(request_before) + "\""; } PreparedStatement stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); while(rs.next()) { CertificateRequestHostRecord cr = new CertificateRequestHostRecord(rs); if (signer != null) { log.debug("cr signer " + cr.getSigner()); if ((signer == 0 && cr.getSigner().matches("(.*)CILogon(.*)")) || (signer == 1 && cr.getSigner().matches("(.*)Digicert(.*)"))) { recs.add(cr); } } else { recs.add(cr); } } stmt.close(); conn.close(); return recs; } //prevent low level access - please use model specific actions @Override public Integer insert(CertificateRequestHostRecord rec) throws SQLException { throw new UnsupportedOperationException("Please use model specific actions instead (request, approve, reject, etc..)"); } @Override public void update(CertificateRequestHostRecord oldrec, CertificateRequestHostRecord newrec) throws SQLException { throw new UnsupportedOperationException("Please use model specific actions instead (request, approve, reject, etc..)"); } @Override public void remove(CertificateRequestHostRecord rec) throws SQLException { throw new UnsupportedOperationException("disallowing remove cert request.."); } @Override CertificateRequestHostRecord createRecord() throws SQLException { // TODO Auto-generated method stub return null; } public void notifyExpiringIn(Integer days_less_than) throws SQLException { final SimpleDateFormat dformat = new SimpleDateFormat(); dformat.setTimeZone(auth.getTimeZone()); ContactModel cmodel = new ContactModel(context); //process host certificate requests log.debug("Looking for host certificate expiring in " + days_less_than + " days"); for(CertificateRequestHostRecord rec : findExpiringIn(days_less_than)) { log.debug("host cert: " + rec.id + " expires on " + dformat.format(rec.cert_notafter)); Date expiration_date = rec.cert_notafter; //user can't renew host certificate, so instead of keep notifying, let's just notify only once by limiting the time window //when notification can be sent out Calendar today = Calendar.getInstance(); if((rec.cert_notafter.getTime() - today.getTimeInMillis()) < 1000*3600*24*23) { log.info("Aborting expiration notification for host certificate " + rec.id + " - it's expiring in less than 23 days"); continue; } //send notification Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.description = "Dear " + rec.requester_name + ",\n\n"; ticket.description += "Your host certificates will expire on "+dformat.format(expiration_date)+"\n\n"; //list CNs - per Horst's request. for(String cn : rec.getCNs()) { ticket.description += cn+"\n"; } ticket.description+= "\n"; ticket.description += "Please request for new host certificate(s) for replacements.\n\n"; ticket.description += "Please visit "+getTicketUrl(rec.id)+" for more details.\n\n"; //don't send to CCs ticket.mail_suppression_ccs = true; if(StaticConfig.isDebug()) { log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expiring host certificate"); log.debug(ticket.description); log.debug(ticket.status); } else { fp.update(ticket, rec.goc_ticket_id); log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expiring host certificate"); } } } public ArrayList<CertificateRequestHostRecord> findExpiringIn(Integer days) throws SQLException { ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>(); ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); stmt.execute("SELECT * FROM "+table_name + " WHERE status = '"+CertificateRequestStatus.ISSUED+"' AND CURDATE() > DATE_SUB( cert_notafter, INTERVAL "+days+" DAY )"); rs = stmt.getResultSet(); while(rs.next()) { recs.add(new CertificateRequestHostRecord(rs)); } stmt.close(); conn.close(); return recs; } public void processCertificateExpired() throws SQLException { //search for expired certificates ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.ISSUED+"' AND cert_notafter < CURDATE()")) { rs = stmt.getResultSet(); while(rs.next()) { CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs); StringArray statuses = new StringArray(rec.csrs.length()); for(int c = 0; c < rec.csrs.length(); ++c) { statuses.set(c, CertificateRequestStatus.EXPIRED); } rec.cert_statuses = statuses.toXML(); rec.status = CertificateRequestStatus.EXPIRED; context.setComment("Certificate is no longer valid."); super.update(get(rec.id), rec); // update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ticket.description = "Certificate(s) has been expired."; if(StaticConfig.isDebug()) { log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expired host certificate"); log.debug(ticket.description); log.debug(ticket.status); } else { fp.update(ticket, rec.goc_ticket_id); log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expired host certificate"); } log.info("sent expiration notification for user certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")"); } } stmt.close(); conn.close(); } //search for approved request that is too old (call this every day) public void processStatusExpired() throws SQLException { ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); //approved in exactly 15 days ago if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.APPROVED+"' AND DATEDIFF(NOW() ,update_time) = 15")) { rs = stmt.getResultSet(); while(rs.next()) { CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs); // update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ContactModel cmodel = new ContactModel(context); //send notification ticket.description = "Dear " + rec.requester_name + ",\n\n"; ticket.description += "Your host certificate (id: "+rec.id+") was approved 15 days ago. The request is scheduled to be automatically canceled within another 15 days. Please take this opportunity to download your approved certificate at your earliest convenience. If you are experiencing any trouble with the issuance of your certificate, please feel free to contact the GOC for further assistance. Please visit "+getTicketUrl(rec.id)+" to issue your host certificate.\n\n"; if(StaticConfig.isDebug()) { log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expiring status for host certificate"); log.debug(ticket.description); log.debug(ticket.status); } else { fp.update(ticket, rec.goc_ticket_id); log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expiring status for host certificate"); } log.info("sent approval expiration warning notification for host certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")"); } } //approved 30 days ago if (stmt.execute("SELECT * FROM "+table_name+ " WHERE status = '"+CertificateRequestStatus.APPROVED+"' AND DATEDIFF(NOW() ,update_time) = 30")) { rs = stmt.getResultSet(); while(rs.next()) { CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs); rec.status = CertificateRequestStatus.CANCELED; context.setComment("Certificate was not issued within 30 days after approval."); super.update(get(rec.id), rec); // update ticket Footprints fp = new Footprints(context); FPTicket ticket = fp.new FPTicket(); ContactModel cmodel = new ContactModel(context); //send notification ticket.description = "Dear " + rec.requester_name + ",\n\n"; ticket.description += "You did not issue your host certificate (id: "+rec.id+") within 30 days from the approval. In compliance with OSG PKI policy, the request is being canceled. You are welcome to re-request if necessary at "+getTicketUrl(rec.id)+".\n\n"; ticket.status = "Resolved"; if(StaticConfig.isDebug()) { log.debug("skipping (this is debug) ticket update on ticket : " + rec.goc_ticket_id + " to notify expired status for host certificate"); log.debug(ticket.description); log.debug(ticket.status); } else { fp.update(ticket, rec.goc_ticket_id); log.info("updated goc ticket : " + rec.goc_ticket_id + " to notify expired status for host certificate"); } log.info("sent approval calelation notification for host certificate request: " + rec.id + " (ticket id:"+rec.goc_ticket_id+")"); } } stmt.close(); conn.close(); } //used by RestServlet only once to reset approver_vo_id public ArrayList<CertificateRequestHostRecord> findNullVO() throws SQLException { ArrayList<CertificateRequestHostRecord> recs = new ArrayList<CertificateRequestHostRecord>(); ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); stmt.execute("SELECT * FROM "+table_name + " WHERE approver_vo_id is NULL order by id"); rs = stmt.getResultSet(); while(rs.next()) { recs.add(new CertificateRequestHostRecord(rs)); } stmt.close(); conn.close(); return recs; } //one time function to reset cert_statuses field for all records public void resetStatuses(PrintWriter out) throws SQLException { out.write("CertificateRequestHostModel::resetStatuses\n"); ResultSet rs = null; Connection conn = connectOIM(); Statement stmt = conn.createStatement(); stmt.execute("SELECT * FROM "+table_name + " WHERE cert_statuses is NULL"); rs = stmt.getResultSet(); while(rs.next()) { CertificateRequestHostRecord rec = new CertificateRequestHostRecord(rs); System.out.println("resetting statuses for rec id:"+rec.id); out.write("rec id:"+rec.id+"\n"); out.write("\t certcounts:"+rec.getCNs().length+"\n"); StringArray statuses = new StringArray(rec.getCNs().length); for(int i = 0;i<rec.getCNs().length;++i) { statuses.set(i, rec.status); } rec.cert_statuses = statuses.toXML(); super.update(get(rec.id), rec); } stmt.close(); conn.close(); } }
package org.fcrepo.metrics; import com.yammer.metrics.AbstractPollingReporter; import com.yammer.metrics.Clock; import com.yammer.metrics.MetricFilter; import com.yammer.metrics.graphite.Graphite; import com.yammer.metrics.graphite.GraphiteReporter; import java.util.concurrent.TimeUnit; public class ReporterFactory { public AbstractPollingReporter registerGraphiteReporter(Graphite g, String prefix) { GraphiteReporter r = new GraphiteReporter(RegistryService.getMetrics(), g, Clock.defaultClock(), prefix, TimeUnit.SECONDS, TimeUnit.MILLISECONDS, MetricFilter.ALL); r.start(1, TimeUnit.MINUTES); return r; } public static ReporterFactory buildDefaultReporterFactory() { return new ReporterFactory(); } }
package edu.umd.cs.findbugs.detect; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.FieldAnnotation; import edu.umd.cs.findbugs.LocalVariableAnnotation; import edu.umd.cs.findbugs.OpcodeStack; public class FindSelfComparison extends BytecodeScanningDetector { BugReporter bugReporter; OpcodeStack stack = new OpcodeStack(); public FindSelfComparison(BugReporter bugReporter) { this.bugReporter = bugReporter; } @Override public void visit(JavaClass obj) { } @Override public void visit(Method obj) { } @Override public void visit(Code obj) { whichRegister = -1; registerLoadCount = 0; stack.resetForMethodEntry(this); super.visit(obj); } @Override public void sawOpcode(int seen) { // System.out.println(getPC() + " " + OPCODE_NAMES[seen] + " " + whichRegister + " " + registerLoadCount); stack.mergeJumps(this); switch (seen) { 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: { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); if (item0.getSignature().equals("D") || item0.getSignature().equals("F")) break; if (item1.getSignature().equals("D") || item1.getSignature().equals("F")) break; FieldAnnotation field0 = item0.getField(); FieldAnnotation field1 = item1.getField(); int fr0 = item0.getFieldLoadedFromRegister(); int fr1 = item1.getFieldLoadedFromRegister(); if (field0 != null && field0.equals(field1) && fr0 != -1 && fr0 == fr1) bugReporter.reportBug(new BugInstance(this, "SA_FIELD_SELF_COMPARISON", NORMAL_PRIORITY) .addClassAndMethod(this).add(field0) .addSourceLine(this)); else if (registerLoadCount >= 2) { bugReporter.reportBug(new BugInstance(this, "SA_LOCAL_SELF_COMPARISON", NORMAL_PRIORITY) .addClassAndMethod(this).add( LocalVariableAnnotation .getLocalVariableAnnotation( getMethod(), whichRegister, getPC(), getPC() - 1)) .addSourceLine(this)); } } } stack.sawOpcode(this, seen); if (isRegisterLoad() && seen != IINC) { if (getRegisterOperand() == whichRegister) registerLoadCount++; else { whichRegister = getRegisterOperand(); registerLoadCount = 1; } } else { whichRegister = -1; registerLoadCount = 0; } } int whichRegister; int registerLoadCount; }
package org.zkoss.ganttz; import org.zkoss.ganttz.util.script.ScriptsRequiredDeclaration; @ScriptsRequiredDeclaration(dependsOn = YUIMin.class) public class ScriptsRequiredByPlanner { public static final String SELECTOR = "/zkau/web/js/yui/2.7.0/selector/selector-min.js"; public static final String YAHOO_DOM_EVENT = "/zkau/web/js/yui/2.7.0/yahoo-dom-event/yahoo-dom-event.js"; public static final String DRAGDROPMIN = "/zkau/web/js/yui/2.7.0/dragdrop/dragdrop-min.js"; public static final String ELEMENT_MIN = "/zkau/web/js/yui/2.7.0/element/element-min.js"; public static final String RESIZE_MIN = "/zkau/web/js/yui/2.7.0/resize/resize-min.js"; public static final String LOGGER_MIN = "/zkau/web/js/yui/2.7.0/logger/logger-min.js"; }
package com.maxifier.cliche; import jline.console.completer.Completer; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.List; /** * Annotation for commands. Allows to specify the name of a command, otherwise method's name is used. * * @author ASG */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Command { /** * Allows to override default command name, which is derived from method's name * * @return "" or null if default name is used, user-specified name otherwise. */ String name() default ""; // if "" then Null is assumed. /** * Specify the description of the command. Default description (if this * property is not set) says "methodName(Arg1Type, Arg2Type,...) : ReturnType". * * @return command's description or "" if not set. */ String description() default ""; String abbrev() default ""; /** * Specify the string to output before command's output, i.e. some explanations. * * @return command's header or "" if not set. */ String header() default ""; /** * Specify the Class which will implement auto-complete logic. The class should return list of possible options by terms. * * @return command's header or "" if not set. */ Class<? extends Completer> completer() default DEFAULT_COMPLETER.class; static final class DEFAULT_COMPLETER implements Completer { @Override public int complete(String buffer, int cursor, List<CharSequence> candidates) { return 0; } } }
package com.commonliabray.jpush; import java.util.Iterator; import java.util.List; import org.json.JSONException; import org.json.JSONObject; import com.commonliabray.activity.demo.MainActivity; import com.commonliabray.asynchttp.activity.LoginActivity; import com.commonliabray.asynchttp.manager.UserManager; import com.commonliabray.model.PushMessage; import com.loopj.android.http.commonhttp.ResponseEntityToModule; import android.app.ActivityManager; import android.app.ActivityManager.RunningTaskInfo; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import cn.jpush.android.api.JPushInterface; /** * @author vision * @function */ public class JPushReceiver extends BroadcastReceiver { private static final String TAG = "JPush"; @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Log.d(TAG, "[JPushReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle)); if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) { int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID); Log.d(TAG, "[JPushReceiver] ID: " + notifactionId); } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) { PushMessage pushMessage = (PushMessage) ResponseEntityToModule .parseJsonToModule(bundle.getString(JPushInterface.EXTRA_EXTRA), PushMessage.class); if (getCurrentTask(context)) { Intent pushIntent = new Intent(); pushIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); pushIntent.putExtra("pushMessage", pushMessage); if (pushMessage.messageType != null && pushMessage.messageType.equals("2") && !UserManager.getInstance().hasLogined()) { pushIntent.setClass(context, LoginActivity.class); pushIntent.putExtra("fromPush", true); } else { /** * Case */ if (UserManager.getInstance().getUser() != null) { Log.e("has logined:", UserManager.getInstance().getUser().data.name + " "); } pushIntent.setClass(context, JPushTestActivity.class); } context.startActivity(pushIntent); } else { /** * switch--case */ Intent mainIntent = new Intent(context, MainActivity.class); mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (pushMessage.messageType != null && pushMessage.messageType.equals("2")) { Intent loginIntent = new Intent(); loginIntent.setClass(context, LoginActivity.class); loginIntent.putExtra("fromPush", true); loginIntent.putExtra("pushMessage", pushMessage); context.startActivities(new Intent[] { mainIntent, loginIntent }); } else { Intent pushIntent = new Intent(context, JPushTestActivity.class); pushIntent.putExtra("pushMessage", pushMessage); context.startActivities(new Intent[] { mainIntent, pushIntent }); } } } } // intent extra private static String printBundle(Bundle bundle) { StringBuilder sb = new StringBuilder(); for (String key : bundle.keySet()) { if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) { sb.append("\nkey:" + key + ", value:" + bundle.getInt(key)); } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) { sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key)); } else if (key.equals(JPushInterface.EXTRA_EXTRA)) { if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) { Log.i(TAG, "This message has no Extra data"); continue; } try { /** * JSON */ JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA)); Iterator<String> it = json.keys(); while (it.hasNext()) { String myKey = it.next().toString(); sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json.optString(myKey) + "]"); } } catch (JSONException e) { Log.e(TAG, "Get message extra JSON error!"); } } else { sb.append("\nkey:" + key + ", value:" + bundle.getString(key)); } } return sb.toString(); } /** * () * * @return */ @SuppressWarnings("deprecation") private boolean getCurrentTask(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> appProcessInfos = activityManager.getRunningTasks(50); for (RunningTaskInfo process : appProcessInfos) { if (process.baseActivity.getPackageName().equals(context.getPackageName()) || process.topActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; } }
package ca.ualberta.cs.views; import java.util.ArrayList; import java.util.List; import ca.ualberta.cs.controllers.BrowseController; import ca.ualberta.cs.controllers.ForumEntryController; import ca.ualberta.cs.f14t07_application.R; import ca.ualberta.cs.f14t07_application.R.layout; import ca.ualberta.cs.intent_singletons.BrowseRequestSingleton; import ca.ualberta.cs.intent_singletons.ForumEntrySingleton; import ca.ualberta.cs.models.Entry; import ca.ualberta.cs.models.ForumEntry; import ca.ualberta.cs.models.ForumEntryList; import ca.ualberta.cs.views.BrowseActivity.SearchThread; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; /** * This activity displays a ForumEntry to the user. It displays the question, its answers, and their replies. * It also allows the user to create an answer to the question * @author bbruner * */ public class QuestionActivity extends Activity implements Observer<ForumEntryList> { /* * TODO: Allow user to save the question as favourite * TODO: Display an upvote count for question and answers * TODO: Display a place to show/hide comments * TODO: User can sort answer by upvotes * TODO: Home screen button * TODO: Display Author's name by the Entry * TODO: Back button takes you somewhere definitive (ask Brendan what this means) */ private ForumEntryController forumEntryController; private ArrayAdapter<Entry> answerListAdapter; private List<Entry> answerList; private ListView answerListView; private ImageView showPicture; /** * Called when this activity is first created. Instantiate class variables here and * create on click listeners here. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_question); this.answerList = new ArrayList<Entry>(); this.forumEntryController = new ForumEntryController(this); this.answerListAdapter = new ArrayAdapter<Entry>(QuestionActivity.this, R.layout.list_item, this.answerList); this.answerListView = (ListView) findViewById(R.id.QuestionAnswerList); this.answerListView.setAdapter(this.answerListAdapter); showPicture = (ImageView)findViewById(R.id.picture); /* * On click listener for when the save button is pushed. */ Button save = (Button) findViewById(R.id.QuestionSaveButton); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveButton(); } }); /* * On click listener for answer button. */ Button answerButton = (Button) findViewById(R.id.AddButton); answerButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { answerQuestion(); } }); } /** * This function is called everytime this activity starts. */ @Override public void onStart() { super.onStart(); /* * Get the instance of the ForumEntrySingleton. Then, see what ForumEntry is being focused * on and use the controller to set that in the view. */ ForumEntrySingleton fes = ForumEntrySingleton.getInstance(); this.forumEntryController.setView(fes.getForumEntry()); } /** * Creates a menu when the ... is clicked in the view. */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.question, menu); return true; } /** * Handles selection of items in the options menu. */ @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(); Intent intent; intent = new Intent(this, BrowseActivity.class); BrowseRequestSingleton.getInstance().setSearchToken(BrowseRequestSingleton.SEARCH_EVERYTHING); switch (id) { case R.id.switchToMyQuestions: /* * Set the search and view tokens in the BrowseRequestSingleton, this way, the browse activity * knows what to search for and what view to present when starting up. */ BrowseRequestSingleton.getInstance().setViewToken(BrowseRequestSingleton.MY_AUTHORED_VIEW); startActivity(intent); return true; case R.id.switchToReadLaters: /* * Set the search and view tokens in the BrowseRequestSingleton, this way, the browse activity * knows what to search for and what view to present when starting up. */ BrowseRequestSingleton.getInstance().setViewToken(BrowseRequestSingleton.READ_LATER_VIEW); startActivity(intent); return true; case R.id.switchToFavourites: /* * Set the search and view tokens in the BrowseRequestSingleton, this way, the browse activity * knows what to search for and what view to present when starting up. */ BrowseRequestSingleton.getInstance().setViewToken(BrowseRequestSingleton.FAVOURITES_VIEW); startActivity(intent); return true; case R.id.switchToHome: Intent homeIntent = new Intent(this, MainScreenActivity.class); startActivity(homeIntent); return true; default: return super.onOptionsItemSelected(item); } } public Dialog onCreateDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Select a save method"); builder.setCancelable(true); builder.setPositiveButton(R.string.savefave, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { forumEntryController.saveFavouritesCopy(); } }); builder.setNegativeButton(R.string.savereadlater, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { forumEntryController.saveReadLaterCopy(); } }); // Create the AlertDialog AlertDialog dialog = builder.create(); dialog.show(); return dialog; } /** * This function will add the ForumEntry being viewed to a favourites cache. */ private void saveButton() { /* * TODO: prompts user if they want to save as favourite, or other thing and uses controller * to do so. */ //Toast.makeText(this, "Save not implemented", Toast.LENGTH_SHORT).show(); onCreateDialog(); } /** * This function will start the AskActivity so that the user can answer the * question (ie, append an Answer to the ForumEntry). */ private void answerQuestion() { /* * Start the AskActivity to enter an answer to the forum entry. * Note that the ForumEntrySingleton does not have to be set, because there is no way * it could have been changed by another activity. */ Intent intent = new Intent(this, AskActivity.class); startActivity(intent); } /** * This function is called by the model. The view should be updated in this function. */ @Override public void update(ForumEntryList model) { ForumEntry focus = model.getView().get(ForumEntryList.FIRST_FORUM_ENTRY); /* * Set the answer list first. * Cannot use assignment (ie answerList = model.getView()) because then * we would have to make a new adapter and then set that new adapter (due * to java being call by value). */ this.answerList.clear(); this.answerList.addAll(focus.getAnswers()); this.answerListAdapter.notifyDataSetChanged(); /* if(focus.getQuestion().getPicture()!=null){ showPicture.setImageBitmap(focus.getQuestion().getPicture()); }*/ /* * Set the questions subject in the view. */ TextView questionSubject = (TextView) findViewById(R.id.QuestionSubject); questionSubject.setText(focus.getQuestion().getSubject()); /* * Set the questions main body of text in the view. */ TextView questionText = (TextView) findViewById(R.id.QuestionText); questionText.setText(focus.getQuestion().getPost()); } }
package com.psddev.dari.db; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.RepeatingTask; import com.psddev.dari.util.Stats; import com.psddev.dari.util.StringUtils; /** * Periodically updates indexes annotated with {@code \@Recalculate}. */ public class RecalculationTask extends RepeatingTask { private static final int UPDATE_LATEST_EVERY_SECONDS = 60; private static final int QUERY_ITERABLE_SIZE = 200; private static final Logger LOGGER = LoggerFactory.getLogger(RecalculationTask.class); private static final Stats STATS = new Stats("Recalculation Task"); private long recordsProcessed = 0L; private long recordsTotal = 0L; @Override protected DateTime calculateRunTime(DateTime currentTime) { return everyMinute(currentTime); } @Override protected void doRepeatingTask(DateTime runTime) throws Exception { recordsProcessed = 0L; recordsTotal = 0L; for (RecalculationContext context : getIndexableMethods()) { Stats.Timer timer = STATS.startTimer(); long recalculated = recalculateIfNecessary(context); if (recalculated > 0L) { timer.stop("Recalculate " + context.getKey(), recalculated); } } } /** * Checks the LastRecalculation and DistributedLock and executes recalculate if it should. */ private long recalculateIfNecessary(RecalculationContext context) { String updateKey = context.getKey(); long recalculated = 0; boolean shouldExecute = false; boolean canExecute = false; LastRecalculation last = Query.from(LastRecalculation.class).master().noCache().where("key = ?", updateKey).first(); if (last == null) { last = new LastRecalculation(); last.setKey(updateKey); shouldExecute = true; context.setReindexAll(true); } else { if (last.getLastExecutedDate() == null && last.getCurrentRunningDate() == null) { // this has never been executed, and it's not currently executing. shouldExecute = true; context.setReindexAll(true); } else if (last.getLastExecutedDate() != null && context.delay.isUpdateDue(new DateTime(), last.getLastExecutedDate())) { // this has been executed before and an update is due. shouldExecute = true; } if (last.getCurrentRunningDate() != null) { // this is currently executing shouldExecute = false; if (context.delay.isUpdateDue(new DateTime(), last.getCurrentRunningDate())) { // the task is running, but another update is already due. // It probably died. Clear it out and pick it up next // time if it hasn't updated, but don't run this time. last.setCurrentRunningDate(null); last.saveImmediately(); } } } if (shouldExecute) { // Check to see if any other processes are currently running on other hosts. if (Query.from(LastRecalculation.class).where("currentRunningDate > ?", new DateTime().minusSeconds(UPDATE_LATEST_EVERY_SECONDS * 5)).hasMoreThan(0)) { shouldExecute = false; } } if (shouldExecute) { boolean locked = false; DistributedLock lock = new DistributedLock(Database.Static.getDefault(), updateKey); try { if (lock.tryLock()) { locked = true; last.setCurrentRunningDate(new DateTime()); last.saveImmediately(); canExecute = true; } } finally { if (locked) { lock.unlock(); } } if (canExecute) { try { recalculated = recalculate(context, last); } finally { last.setLastExecutedDate(new DateTime()); last.setCurrentRunningDate(null); last.saveImmediately(); } } } return recalculated; } /** * Actually does the work of iterating through the records and updating indexes. */ private long recalculate(RecalculationContext context, LastRecalculation last) { long recalculated = 0L; // Still testing this out. boolean useMetricQuery = false; try { Query<?> query = Query.fromAll().noCache().resolveToReferenceOnly(); query.getOptions().put(SqlDatabase.USE_JDBC_FETCH_SIZE_QUERY_OPTION, false); if (!context.isReindexAll()) { for (ObjectMethod method : context.methods) { query.or(method.getUniqueName() + " != missing"); } } ObjectField metricField = context.getMetric(); DateTime processedLastRunDate = last.getLastExecutedDate(); if (metricField != null) { if (last.getLastExecutedDate() != null) { MetricInterval interval = metricField.as(MetricAccess.FieldData.class).getEventDateProcessor(); if (interval != null) { processedLastRunDate = new DateTime(interval.process(processedLastRunDate)); if (useMetricQuery) { query.and(metricField.getUniqueName() + "#date >= ?", processedLastRunDate); query.and(metricField.getUniqueName() + " != 0"); } } } } for (Object obj : query.iterable(QUERY_ITERABLE_SIZE)) { try { if (!shouldContinue()) { break; } setProgressIndex(++ recordsTotal); State objState = State.getInstance(obj); if (objState == null) { continue; } if (!useMetricQuery) { if (last.getLastExecutedDate() != null) { if (metricField != null) { Metric metric = new Metric(objState, metricField); DateTime lastMetricUpdate = metric.getLastUpdate(); if (lastMetricUpdate == null) { // there's no metric data, so just pass. continue; } if (!context.isReindexAll() && lastMetricUpdate.isBefore(processedLastRunDate.minusSeconds(1))) { // metric data is older than the last run date, so skip it. continue; } } } } objState.setResolveToReferenceOnly(false); for (ObjectMethod method : context.methods) { LOGGER.debug("Updating Index: " + method.getInternalName() + " for " + objState.getId()); method.recalculate(objState); recalculated ++; } recordsProcessed ++; } finally { if (last.getCurrentRunningDate().plusSeconds(UPDATE_LATEST_EVERY_SECONDS).isBeforeNow()) { last.setCurrentRunningDate(new DateTime()); last.saveImmediately(); } } } } finally { last.setCurrentRunningDate(new DateTime()); last.saveImmediately(); } return recalculated; } @Override public String getProgress() { return new StringBuilder("Recalculated ").append(recordsProcessed).append(", checked ").append(recordsTotal).toString(); } /** * Saves the last time the index update was executed for each context. */ public static class LastRecalculation extends Record { // null if it's not running @Indexed private Long currentRunningDate; private Long lastExecutedDate; @Indexed(unique = true) private String key; public DateTime getCurrentRunningDate() { return (currentRunningDate == null ? null : new DateTime(currentRunningDate)); } public void setCurrentRunningDate(DateTime currentRunningDate) { this.currentRunningDate = (currentRunningDate == null ? null : currentRunningDate.getMillis()); } public DateTime getLastExecutedDate() { return (lastExecutedDate == null ? null : new DateTime(lastExecutedDate)); } public void setLastExecutedDate(DateTime lastExecutedDate) { this.lastExecutedDate = (lastExecutedDate == null ? null : lastExecutedDate.getMillis()); } public String getKey() { return key; } public void setKey(String key) { this.key = key; } } private static Collection<RecalculationContext> getIndexableMethods() { Map<String, RecalculationContext> contextsByGroupsAndDelayAndMetric = new HashMap<String, RecalculationContext>(); for (ObjectType type : Database.Static.getDefault().getEnvironment().getTypes()) { for (ObjectMethod method : type.getMethods()) { if (method.getJavaDeclaringClassName().equals(type.getObjectClassName()) && !method.as(RecalculationFieldData.class).isImmediate() && method.as(RecalculationFieldData.class).getRecalculationDelay() != null) { TreeSet<String> groups = new TreeSet<String>(); if (Modification.class.isAssignableFrom(type.getObjectClass())) { @SuppressWarnings("unchecked") Class<? extends Modification<?>> modClass = ((Class<? extends Modification<?>>) type.getObjectClass()); for (Class<?> modifiedClass : Modification.Static.getModifiedClasses(modClass)) { ObjectType modifiedType = ObjectType.getInstance(modifiedClass); if (modifiedType != null) { groups.add(modifiedType.getInternalName()); } else { groups.add(modifiedClass.getName()); } } } else { groups.add(type.getInternalName()); } RecalculationContext context = new RecalculationContext(type, groups, method.as(RecalculationFieldData.class).getRecalculationDelay()); context.methods.add(method); String key = context.getKey(); if (!contextsByGroupsAndDelayAndMetric.containsKey(key)) { contextsByGroupsAndDelayAndMetric.put(key, context); } contextsByGroupsAndDelayAndMetric.get(key).methods.add(method); } } } return contextsByGroupsAndDelayAndMetric.values(); } private static final class RecalculationContext { public final ObjectType type; public final RecalculationDelay delay; public final TreeSet<String> groups; public final Set<ObjectMethod> methods = new HashSet<ObjectMethod>(); public boolean reindexAll = false; public RecalculationContext(ObjectType type, TreeSet<String> groups, RecalculationDelay delay) { this.type = type; this.groups = groups; this.delay = delay; } public ObjectField getMetric() { boolean first = true; ObjectField metricField = null; ObjectField useMetricField = null; for (ObjectMethod method : methods) { String methodMetricFieldName = method.as(MetricAccess.FieldData.class).getRecalculableFieldName(); ObjectField methodMetricField = null; if (methodMetricFieldName != null) { methodMetricField = type.getState().getDatabase().getEnvironment().getField(methodMetricFieldName); if (methodMetricField == null) { methodMetricField = type.getField(methodMetricFieldName); } if (methodMetricField == null) { LOGGER.warn("Invalid metric field: " + methodMetricFieldName); } } if (first) { metricField = methodMetricField; useMetricField = metricField; } else { if (!ObjectUtils.equals(metricField, methodMetricField)) { useMetricField = null; } } first = false; } return useMetricField; } public String getKey() { if (methods.isEmpty()) { throw new IllegalStateException("Add a method before you get the key!"); } ObjectField metricField = getMetric(); return type.getInternalName() + " " + StringUtils.join(groups.toArray(new String[0]), ",") + " " + delay.getClass().getName() + (metricField != null ? " " + metricField.getUniqueName() : ""); } public boolean isReindexAll() { return reindexAll; } public void setReindexAll(boolean reindexAll) { this.reindexAll = reindexAll; } } }
package org.jetel.data.parser; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.CloverDataRecordSerializer; import org.jetel.data.DataRecord; import org.jetel.data.DataRecordFactory; import org.jetel.data.DataRecordSerializer; import org.jetel.data.Defaults; import org.jetel.data.formatter.CloverDataFormatter; import org.jetel.data.formatter.CloverDataFormatter.DataCompressAlgorithm; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.IParserExceptionHandler; import org.jetel.exception.JetelException; import org.jetel.exception.PolicyType; import org.jetel.graph.ContextProvider; import org.jetel.metadata.DataRecordMetadata; import org.jetel.metadata.DataRecordMetadataXMLReaderWriter; import org.jetel.util.bytes.ByteBufferUtils; import org.jetel.util.bytes.CloverBuffer; import org.jetel.util.file.FileUtils; import org.jetel.util.primitive.BitArray; import org.jetel.util.stream.CloverDataStream; import org.jetel.util.stream.StreamUtils; public class CloverDataParser extends AbstractParser implements ICloverDataParser { public static class FileConfig { public byte majorVersion; public byte minorVersion; public byte revisionVersion; public int compressionAlgorithm; public CloverDataFormatter.DataFormatVersion formatVersion; public DataRecordMetadata metadata; public boolean raw; } private final static Log logger = LogFactory.getLog(CloverDataParser.class); private DataRecordMetadata metadata; private ReadableByteChannel recordFile; private CloverDataStream.Input input; private CloverBuffer recordBuffer; private InputStream inStream; private URL projectURL; private DataRecordSerializer serializer; private CloverDataFormatter.DataCompressAlgorithm compress; /** Clover version which has been used to create the input data file. */ private FileConfig version; private boolean useParsingFromJobflow_3_4 = false; /** * True, if the current transformation is jobflow. */ private boolean isJobflow; private final static int LONG_SIZE_BYTES = 8; private final static int LEN_SIZE_SPECIFIER = 4; public CloverDataParser(DataRecordMetadata metadata){ this.metadata = metadata; this.compress = DataCompressAlgorithm.NONE; } public FileConfig getVersion() { return version; } public InputStream getInStream() { return inStream; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#getNext() */ @Override public DataRecord getNext() throws JetelException { DataRecord record = DataRecordFactory.newRecord(metadata); record.init(); return getNext(record); } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#skip(int) */ @Override public int skip(int nRec) throws JetelException { if (nRec == 0) { return 0; } if (isDirectReadingSupported()) { CloverBuffer buffer = CloverBuffer.allocate(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE); for (int skipped = 0; skipped < nRec; skipped++) { if (!getNextDirect(buffer)) { return skipped; } } } else { DataRecord record = DataRecordFactory.newRecord(metadata); record.init(); for (int skipped = 0; skipped < nRec; skipped++) { if (getNext(record) == null) { return skipped; } } } return nRec; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#init(org.jetel.metadata.DataRecordMetadata) */ @Override public void init() throws ComponentNotReadyException { if (metadata == null) { throw new ComponentNotReadyException("Metadata are null"); } recordBuffer = CloverBuffer.allocateDirect(Defaults.Record.RECORD_INITIAL_SIZE, Defaults.Record.RECORD_LIMIT_SIZE); recordBuffer.order(CloverDataFormatter.BUFFER_BYTE_ORDER); serializer=new CloverDataRecordSerializer(); } private void doReleaseDataSource() throws IOException { if (inStream != null) { inStream.close(); inStream = null; // setDataSource() tests inStream for null } } @Override protected void releaseDataSource() { try { doReleaseDataSource(); } catch (IOException ioe) { logger.warn("Failed to release data source", ioe); } } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#setDataSource(java.lang.Object) * * parameter: data fiele name or {data file name, index file name} */ @Override public void setDataSource(Object in) throws ComponentNotReadyException { String inData=null; if (releaseDataSource) { releaseDataSource(); } if (in instanceof InputStream) { inStream = (InputStream) in; }else if (in instanceof ReadableByteChannel){ inStream = Channels.newInputStream((ReadableByteChannel)in); }else if (in instanceof File){ try { inStream = new FileInputStream((File)in); } catch (IOException e) { throw new ComponentNotReadyException(e); } }else if (in instanceof String[]) { inData = ((String[])in)[0]; }else if (in instanceof String){ inData = (String)in; }else{ throw new ComponentNotReadyException("Unsupported Data Source type: "+in.getClass().getName()); } if (inStream==null) { // doReleaseDataSource() should set the previous stream to null try{ String fileName = new File(FileUtils.getFile(projectURL, inData)).getName(); if (fileName.toLowerCase().endsWith(".zip")) { fileName = fileName.substring(0,fileName.lastIndexOf('.')); } inStream = FileUtils.getInputStream(projectURL, !inData.startsWith("zip:") ? inData : inData + "#" + CloverDataFormatter.DATA_DIRECTORY + fileName); } catch (IOException ex) { throw new ComponentNotReadyException(ex); } } //read and check header of clover binary data format to check out the compatibility issues version = checkCompatibilityHeader(inStream, metadata); if(version.formatVersion!=CloverDataFormatter.CURRENT_FORMAT_VERSION){ return; } this.compress=DataCompressAlgorithm.getAlgorithm(version.compressionAlgorithm); //is the current transformation jobflow? isJobflow = ContextProvider.getRuntimeContext() != null && ContextProvider.getRuntimeContext().getJobType().isJobflow(); //special de-serialisation needs to be used, see CLO-1382 if (version.majorVersion == 3 && (version.minorVersion == 3 || version.minorVersion == 4) && isJobflow) { useParsingFromJobflow_3_4 = true; } switch(compress){ case NONE: this.input= new CloverDataStream.Input(inStream); break; case LZ4: this.input= new CloverDataStream.Input(inStream, new CloverDataStream.DecompressorLZ4()); break; case GZIP: this.input= new CloverDataStream.Input(inStream, new CloverDataStream.DecompressorGZIP()); break; default: throw new RuntimeException("Unsupported compression algorithm: "+compress); } } public static FileConfig checkCompatibilityHeader(ReadableByteChannel recordFile, DataRecordMetadata metadata) throws ComponentNotReadyException { return checkCompatibilityHeader(Channels.newInputStream(recordFile),metadata); } public static FileConfig checkCompatibilityHeader(InputStream recordFile, DataRecordMetadata metadata) throws ComponentNotReadyException { byte[] extraBytes; CloverBuffer buffer = CloverBuffer.wrap(new byte[CloverDataFormatter.CLOVER_DATA_HEADER_LENGTH]); try { int count = StreamUtils.readBlocking(recordFile, buffer.array()); if (count != buffer.capacity()) { throw new IOException("Failed to read file header"); } } catch (IOException e) { throw new ComponentNotReadyException(e); } //read clover binary data header and check backward compatibility //better header description is at CloverDataFormatter.setDataTarget() method long cloverHash=buffer.getLong(); if (CloverDataFormatter.CLOVER_DATA_HEADER != cloverHash) { //clover binary data format is definitely incompatible with current version - header is not present throw new ComponentNotReadyException("Source clover data file is obsolete. Data cannot be read."); } long cloverDataCompatibilityHash = buffer.getLong(); FileConfig version = new FileConfig(); version.majorVersion = buffer.get(); version.minorVersion = buffer.get(); version.revisionVersion = buffer.get(); if (cloverDataCompatibilityHash == CloverDataFormatter.CLOVER_DATA_COMPATIBILITY_HASH_2_9){ version.formatVersion=CloverDataFormatter.DataFormatVersion.VERSION_29; }else if (cloverDataCompatibilityHash == CloverDataFormatter.CLOVER_DATA_COMPATIBILITY_HASH_3_5){ version.formatVersion=CloverDataFormatter.DataFormatVersion.VERSION_35; }else if (cloverDataCompatibilityHash == CloverDataFormatter.CLOVER_DATA_COMPATIBILITY_HASH_4_0){ version.formatVersion=CloverDataFormatter.DataFormatVersion.VERSION_40; }else{ throw new ComponentNotReadyException("Invallid Clover Data Compatibility Hash: "+cloverDataCompatibilityHash); } switch(version.formatVersion){ case VERSION_29: case VERSION_35: extraBytes = new byte[CloverDataFormatter.HEADER_OPTIONS_ARRAY_SIZE_3_5]; try { int count = StreamUtils.readBlocking(recordFile, extraBytes); if (count != extraBytes.length) { throw new IOException("Failed to read file header"); } } catch (IOException e) { throw new ComponentNotReadyException(e); } if (BitArray.isSet(extraBytes, 0) ^ Defaults.Record.USE_FIELDS_NULL_INDICATORS) { throw new ComponentNotReadyException("Source file with binary data format is not compatible. Engine producer has different setup of Defaults.Record.USE_FIELDS_NULL_INDICATORS (see documentation). Data cannot be read."); } // what's left is metadata serialized, will let this to "other" parser break; case VERSION_40: extraBytes = new byte[CloverDataFormatter.HEADER_OPTIONS_ARRAY_SIZE]; try { int count = StreamUtils.readBlocking(recordFile, extraBytes); if (count != extraBytes.length) { throw new IOException("Failed to read file header"); } } catch (IOException e) { throw new ComponentNotReadyException(e); } if (BitArray.isSet(extraBytes, 0) ^ Defaults.Record.USE_FIELDS_NULL_INDICATORS) { throw new ComponentNotReadyException("Source file with binary data format is not compatible. Engine producer has different setup of Defaults.Record.USE_FIELDS_NULL_INDICATORS (see documentation). Data cannot be read."); } version.compressionAlgorithm=BitArray.extractNumber(extraBytes, CloverDataFormatter.OPTION_MASK_COMPRESSED_DATA); version.raw = BitArray.extractNumber(extraBytes, CloverDataFormatter.OPTION_MASK_RAW_DATA) == 1; //check metadata (just read,do not control now) int metasize; try { metasize=ByteBufferUtils.decodeLength(recordFile); byte[] metadef=new byte[metasize]; if (StreamUtils.readBlocking(recordFile, metadef) != metasize){ throw new IOException("Not enough data in file."); } version.metadata=DataRecordMetadataXMLReaderWriter.readMetadata(new ByteArrayInputStream(metadef)); } catch (IOException e) { throw new ComponentNotReadyException("Unable to read metadata definition from CloverData file", e); } break; default: throw new ComponentNotReadyException("Source clover data file is not supported (version " + version.majorVersion + "." + version.minorVersion + "." + version.revisionVersion + "). Data cannot be read."); } return version; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#close() */ @Override public void close() { releaseDataSource(); } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#getNext(org.jetel.data.DataRecord) */ @Override public DataRecord getNext(DataRecord record) throws JetelException { if (!getNextDirect(recordBuffer)) { return null; //end of file reached } if (!useParsingFromJobflow_3_4) { record.deserializeUnitary(recordBuffer,serializer); } else { record.deserialize(recordBuffer,serializer); } return record; } /** * Reads the next serialized record into the provided buffer. * The target buffer is cleared first. * <p> * The position of the target buffer will be set to 0 * and the limit will be set to the end of the serialized record. * </p><p> * Returns the provided buffer or <code>null</code> * if there is no record available. * </p> * * @param targetBuffer the target buffer * @return <code>targetBuffer</code> or <code>null</code> if no data available * @throws JetelException */ @Override public boolean getNextDirect(CloverBuffer targetBuffer) throws JetelException { final int size; try { size=ByteBufferUtils.decodeLength(input); if (size<0) return false; //end of file reached targetBuffer.clear(); targetBuffer.limit(size); if (input.read(targetBuffer)==-1){ throw new JetelException("Insufficient data in datastream."); } targetBuffer.flip(); } catch(IOException ex){ throw new JetelException(ex); } return true; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#setExceptionHandler(org.jetel.exception.IParserExceptionHandler) */ @Override public void setExceptionHandler(IParserExceptionHandler handler) { } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#getExceptionHandler() */ @Override public IParserExceptionHandler getExceptionHandler() { return null; } /* (non-Javadoc) * @see org.jetel.data.parser.Parser#getPolicyType() */ @Override public PolicyType getPolicyType() { return null; } @Override public void reset() { close(); } @Override public Object getPosition() { return null; } @Override public void movePosition(Object position) { } public URL getProjectURL() { return projectURL; } public void setProjectURL(URL projectURL) { this.projectURL = projectURL; } @Override public void preExecute() throws ComponentNotReadyException { reset(); } @Override public void postExecute() throws ComponentNotReadyException { if (releaseDataSource) { releaseDataSource(); } } @Override public void free() { close(); } @Override public boolean nextL3Source() { return false; } @Override public boolean isDirectReadingSupported() { return getVersion().raw; } }
package cubrikproject.tud.likelines.service.impl; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import cubrikproject.tud.likelines.service.activator.Activator; import cubrikproject.tud.likelines.util.YouTubeComment; import cubrikproject.tud.likelines.util.YouTubeComment.TimePoint; import cubrikproject.tud.likelines.util.YouTubeDL; import cubrikproject.tud.likelines.util.YouTubeDL.YouTubeStream; import cubrikproject.tud.likelines.webservice.LikeLinesWebService; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.smila.utils.config.ConfigUtils; /** * The service responsible for launching indexing processes in the background. * * @author R. Vliegendhart */ public class LLIndexer implements cubrikproject.tud.likelines.service.interfaces.LLIndexer { private final static Log _log = LogFactory.getLog(LLIndexer.class); private final String propertiesFile = getClass().getSimpleName() + ".properties"; private final Properties props; private final String ffmpegPath; private final String motionActivityPath; private final String indexStoragePath; private final String DEFAULT_FFMPEG = "ffmpeg"; private final String DEFAULT_MOTIONACTIVITY = "motionActivity"; final Map<String, String> secretKeys; Transcoder transcoder; MotionActivityAnalyzer motionActivityAnalyzer; private final Set<String> indexedVideos = new HashSet<String>(); public LLIndexer() { System.out.println(">>> LLIndexer: Reading (configuration/)" + Activator.BUNDLE_NAME + "/" + propertiesFile); props = loadProperties(); String ffmpegPathFromProps = nullIfMissing( getProperty("ffmpegPath") ); String motionActivityPathFromProps = nullIfMissing( getProperty("motionActivityPath") ); ffmpegPath = (ffmpegPathFromProps == null) ? findOnPath(DEFAULT_FFMPEG) : ffmpegPathFromProps; motionActivityPath = (motionActivityPathFromProps == null) ? findOnPath(DEFAULT_MOTIONACTIVITY) : motionActivityPathFromProps; secretKeys = getSecretKeys(); testSecretKeys(secretKeys); transcoder = (ffmpegPath == null) ? null : new Transcoder(ffmpegPath); motionActivityAnalyzer = (motionActivityPath == null) ? null : new MotionActivityAnalyzer(motionActivityPath); indexStoragePath = prepareIndexStorage(); if (_log.isInfoEnabled()) { _log.info("LLIndexer created using following setting"); _log.info(" -ffmpegPath=" + ffmpegPath); _log.info(" -motionActivityPath=" + motionActivityPath); } } private String prepareIndexStorage() { final String configuredIndexStoragePath = getProperty("indexStoragePath"); final File indexStoragePathFile = (configuredIndexStoragePath == null) ? new File(System.getProperty("java.io.tmpdir"), "SMILA_LL_IndexStorage") : new File(configuredIndexStoragePath); if (!indexStoragePathFile.exists()) indexStoragePathFile.mkdirs(); return indexStoragePathFile.getPath(); } @Override synchronized public void scheduleMCA(String videoId, LikeLinesWebService llServer, boolean contentAnalysisRequired) { if (indexedVideos.contains(videoId)) { System.err.println("scheduleMCA: Ignoring videoId " + videoId + " since it's being indexed or has been."); return; } // For now, simplistic mechanism to prevent duplicate work: indexedVideos.add(videoId); Thread thread = new Thread(new MCATask(videoId, llServer, contentAnalysisRequired)); thread.start(); } public class MCATask implements Runnable { private final String videoId; private final LikeLinesWebService llServer; private final String serverUrl; private final boolean contentAnalysisRequired; public MCATask(String videoId, LikeLinesWebService llServer, boolean contentAnalysisRequired) { this.videoId = videoId; this.llServer = llServer; this.serverUrl = llServer.serverUrl; this.contentAnalysisRequired = contentAnalysisRequired; } @Override public void run() { System.err.println("MCATask: Starting: " + videoId); String secretKey = secretKeys.get(serverUrl); if (!videoId.startsWith("YouTube:")) { System.err.println("MCATask only supports YouTube:<id>!"); return; } // future implementation should introduce branches for different URL schemes final String youtubeId = videoId.substring("YouTube:".length()); try { final Map<String, String> videoInfo = YouTubeDL.getVideoInfo(youtubeId); final boolean ageGate = YouTubeDL.isAgeRestrictedVideo(youtubeId); YouTubeStream firstStream = null; for (YouTubeStream stream : YouTubeDL.getDownloadStreams(videoInfo, ageGate)) { firstStream = stream; break; } if (firstStream == null) { System.err.println("ERR: No stream found!"); return; } final String downloadPath = new File(indexStoragePath, "mca-" + youtubeId + firstStream.getExtension()).getPath(); firstStream.downloadTo(downloadPath); final String convertPath = new File(indexStoragePath, "mca-" + youtubeId + "-conv.mpg").getPath(); boolean transcodeSuccess = transcoder.transcodeAndWait(downloadPath, convertPath) == 0; System.err.println("MCATask: Done converting, now starting motion analysis"); final double[] motionScores = motionActivityAnalyzer.analyze(convertPath); System.err.println("MCATask: Now downloading comments"); List<Integer> deeplinksList = new ArrayList<Integer>(); for (YouTubeComment cmnt : YouTubeComment.retrieveDeepLinkComments(youtubeId)) for (TimePoint deeplink : cmnt.deeplinks) deeplinksList.add(deeplink.inSeconds); final double[] deeplinks = new double[deeplinksList.size()]; for (int i = 0; i < deeplinks.length; i++) deeplinks[i] = deeplinksList.get(i); System.err.println("MCATask: Submitting MCA results to server: " + serverUrl); llServer.postMCA(videoId, "motionActivity", llServer.MCA_TYPE_CURVE, motionScores, secretKey); llServer.postMCA(videoId, "deeplinks", llServer.MCA_TYPE_POINT, deeplinks, secretKey); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (InterruptedException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (RuntimeException e) { e.printStackTrace(); throw e; } System.err.println("MCATask: Done: " + videoId); } } /** * Loads the property file * * @return The Properties or null if it does not exist */ private Properties loadProperties() { Properties res = null; try { res = ConfigUtils.getConfigProperties(Activator.BUNDLE_NAME, propertiesFile); } catch (Exception e) { _log.warn(e); } return res; } /** * Gets a property or null if the properties file or the property don't exist * * @return The Properties or null if it does not exist */ private String getProperty(String propertyName) { return props == null ? null : props.getProperty(propertyName); } /** * Find an executable on the PATH * * @param executable Name of the executable to search for * @return A path if found, otherwise null */ private String findOnPath(String executable) { final boolean w32 = System.getProperty("os.name").startsWith("Windows"); final String exeSuffix = w32 ? ".exe" : ""; executable += exeSuffix; for (String path: System.getenv("PATH").split(File.pathSeparator)) { File f = new File(path, executable); if (f.exists()) return f.getAbsolutePath(); } return null; } /** * Maps a path to null if it does not exist. * * @param path The path to check as a String * @return The path if it exists, otherwise null */ private String nullIfMissing(String path) { return (path != null && new File(path).exists()) ? path : null; } /** * Loads the secret keys from the properties file and stores it in a map * * @return A mapping from LikeLines server URLs to their secret keys. */ private Map<String,String> getSecretKeys() { final HashMap<String, String> res = new HashMap<String,String>(); final String secretKeysProperty = getProperty("secretKeys"); final String[] secretKeysAndServers = (secretKeysProperty==null) ? new String[0] : secretKeysProperty.split("\\s+"); if (secretKeysAndServers.length % 2 != 0) { _log.warn("LLIndexer: secretKeys property should contain an even number of items after splitting!"); return res; } for (int i = 0; i < secretKeysAndServers.length; i += 2) { final String secretKey = secretKeysAndServers[i]; final String server = LikeLinesWebService.ensureTrailingSlash(secretKeysAndServers[i + 1]); res.put(server, secretKey); } return res; } /** * Tests and removes secret keys that are invalid. * * @param secretKeys */ private static void testSecretKeys(Map<String,String> secretKeys) { final List<String> failedServers = new ArrayList<String>(); for (final Entry<String, String> kv : secretKeys.entrySet()) { final String server = kv.getKey(); final String key = kv.getValue(); LikeLinesWebService llserver = null; try { llserver = new LikeLinesWebService(server); } catch (MalformedURLException e) { _log.warn("LLIndexer: testSecretKeys: malformed URL in server: " + server); failedServers.add(server); e.printStackTrace(); continue; } try { if (!llserver.testKey(key)) { _log.warn("LLIndexer: testSecretKeys: incorrect key for server: " + server); failedServers.add(server); continue; } } catch (IOException e) { _log.warn("LLIndexer: testSecretKeys: I/O error, server down? " + server); failedServers.add(server); e.printStackTrace(); continue; } } for (final String server : failedServers) secretKeys.remove(server); } }
package nl.mpi.kinnate.data; import java.net.URI; import java.util.ArrayList; import java.util.Vector; import javax.swing.ImageIcon; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.data.ArbilNode; import nl.mpi.arbil.util.BugCatcher; import nl.mpi.arbil.util.MessageDialogHandler; import nl.mpi.kinnate.entityindexer.EntityCollection; import nl.mpi.kinnate.entityindexer.IndexerParameters; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.svg.SymbolGraphic; public class KinTreeNode extends ArbilNode implements Comparable { public EntityData entityData; private IndexerParameters indexerParameters; DataTypes.RelationType subnodeFilter; ArbilNode[] childNodes = null; static private SymbolGraphic symbolGraphic; private EntityCollection entityCollection; private MessageDialogHandler dialogHandler; private BugCatcher bugCatcher; private ArbilDataNodeLoader dataNodeLoader; public KinTreeNode(EntityData entityData, IndexerParameters indexerParameters, MessageDialogHandler dialogHandler, BugCatcher bugCatcher, EntityCollection entityCollection, ArbilDataNodeLoader dataNodeLoader) { super(); this.indexerParameters = indexerParameters; this.entityData = entityData; this.subnodeFilter = null; this.entityCollection = entityCollection; this.dialogHandler = dialogHandler; this.bugCatcher = bugCatcher; this.dataNodeLoader = dataNodeLoader; symbolGraphic = new SymbolGraphic(dialogHandler, bugCatcher); } // todo: create new constructor that takes a unique identifer and loads from the database public KinTreeNode(EntityData entityData, DataTypes.RelationType subnodeFilter, IndexerParameters indexerParameters, MessageDialogHandler dialogHandler, BugCatcher bugCatcher, EntityCollection entityCollection, ArbilDataNodeLoader dataNodeLoader) { super(); this.indexerParameters = indexerParameters; this.entityData = entityData; this.subnodeFilter = subnodeFilter; // subnode filter should be null unless the child nodes are to be filtered this.entityCollection = entityCollection; this.dialogHandler = dialogHandler; this.bugCatcher = bugCatcher; this.dataNodeLoader = dataNodeLoader; symbolGraphic = new SymbolGraphic(dialogHandler, bugCatcher); } @Override public String toString() { StringBuilder labelBuilder = new StringBuilder(); if (entityData == null) { labelBuilder.append("(entity not loaded)"); } else { final String[] labelArray = entityData.getLabel(); if (labelArray != null && labelArray.length > 0) { for (String labelString : labelArray) { labelBuilder.append(labelString); labelBuilder.append(" "); } } else { labelBuilder.append("(unnamed entity)"); } } return labelBuilder.toString(); } @Override public ArbilDataNode[] getAllChildren() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void getAllChildren(Vector<ArbilDataNode> allChildren) { throw new UnsupportedOperationException("Not supported yet."); } @Override public ArbilNode[] getChildArray() { // if (childNodes != null) { // return childNodes; // } else if (entityData != null) { ArrayList<ArbilNode> relationList = new ArrayList<ArbilNode>(); // todo: add metanodes and ui option to hide show relation types for (EntityRelation entityRelation : entityData.getAllRelations()) { final boolean showFiltered = subnodeFilter == DataTypes.RelationType.ancestor || subnodeFilter == DataTypes.RelationType.descendant; // todo: remove limitation of sanguine relations "isSanguinLine" and find the caues of the error when non sanguine relations are shown if (DataTypes.isSanguinLine(entityRelation.getRelationType()) && (subnodeFilter == null || (subnodeFilter == entityRelation.getRelationType() && showFiltered))) { EntityData alterEntity = entityRelation.getAlterNode(); if (alterEntity == null) { // todo: should these enties be cached? or will the entire tree be discarded on redraw? alterEntity = entityCollection.getEntity(entityRelation.alterUniqueIdentifier, indexerParameters); entityRelation.setAlterNode(alterEntity); } relationList.add(new KinTreeNode(alterEntity, entityRelation.getRelationType(), indexerParameters, dialogHandler, bugCatcher, entityCollection, dataNodeLoader)); } } if (entityData.archiveLinkArray != null) { for (URI archiveLink : entityData.archiveLinkArray) { ArbilDataNode linkedArbilDataNode = dataNodeLoader.getArbilDataNode(null, archiveLink); relationList.add(linkedArbilDataNode); } } childNodes = relationList.toArray(new ArbilNode[]{}); return childNodes; // } else { // return new ArbilNode[]{}; // todo: inthe case of metadata nodes load them via the arbil data loader // try { // String entityPath = entityData.getEntityPath(); // if (entityPath != null) { //// ArbilDataNode arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, new URI(entityPath)); // if (entityData.isEgo || egoIdentifiers.contains(entityData.getUniqueIdentifier())) { // egoNodeArray.add(arbilDataNode); // } else if (requiredEntityIdentifiers.contains(entityData.getUniqueIdentifier())) { // requiredNodeArray.add(arbilDataNode); // } else { // remainingNodeArray.add(arbilDataNode); // } catch (URISyntaxException exception) { // System.err.println(exception.getMessage()); } @Override public int getChildCount() { throw new UnsupportedOperationException("Not supported yet."); } @Override public ImageIcon getIcon() { if (entityData != null) { return symbolGraphic.getSymbolGraphic(entityData.getSymbolType(), entityData.isEgo); } return null; } @Override public boolean hasCatalogue() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasHistory() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasLocalResource() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean hasResource() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isArchivableFile() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCatalogue() { return false; } @Override public boolean isChildNode() { return false; } @Override public boolean isCmdiMetaDataNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isCorpus() { return false; } @Override public boolean isDataLoaded() { return true; } @Override public boolean isDirectory() { return false; } @Override public boolean isEditable() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isEmptyMetaNode() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isFavorite() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isLoading() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isLocal() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isMetaDataNode() { return false; } @Override public boolean isResourceSet() { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isSession() { return false; } public int compareTo(Object o) { if (o instanceof KinTreeNode) { int compResult = this.toString().compareTo(o.toString()); if (compResult == 0) { // todo: compare by age if the labels match // compResult = entityData } return compResult; } else { // put kin nodes in front of other nodes return 1; } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final KinTreeNode other = (KinTreeNode) obj; if (entityData == null || other.entityData == null) { // todo: it would be good for this to never be null, or at least to aways have the UniqueIdentifier to compare return false; } if (this.entityData.getUniqueIdentifier() != other.entityData.getUniqueIdentifier() && (this.entityData.getUniqueIdentifier() == null || !this.entityData.getUniqueIdentifier().equals(other.entityData.getUniqueIdentifier()))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 37 * hash + (this.entityData.getUniqueIdentifier() != null ? this.entityData.getUniqueIdentifier().hashCode() : 0); return hash; } }
package com.intellij.codeInsight; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.lookup.LookupValueWithPsiElement; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.xml.XmlAttribute; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class TargetElementUtil { public static final int REFERENCED_ELEMENT_ACCEPTED = 0x01; public static final int ELEMENT_NAME_ACCEPTED = 0x02; public static final int NEW_AS_CONSTRUCTOR = 0x04; public static final int LOOKUP_ITEM_ACCEPTED = 0x08; public static final int THIS_ACCEPTED = 0x10; public static final int SUPER_ACCEPTED = 0x20; private TargetElementUtil() {} public static PsiElement findTargetElement(Editor editor, int flags) { int offset = editor.getCaretModel().getOffset(); return findTargetElement(editor, flags, offset); } public static PsiReference findReference(Editor editor) { return findReference(editor, editor.getCaretModel().getOffset()); } @Nullable public static PsiReferenceExpression findReferenceExpression(Editor editor) { final PsiReference ref = findReference(editor); return ref instanceof PsiReferenceExpression ? (PsiReferenceExpression)ref : null; } public static PsiReference findReference(Editor editor, int offset) { ApplicationManager.getApplication().assertIsDispatchThread(); Project project = editor.getProject(); if (project == null) return null; Document document = editor.getDocument(); PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); if (file == null) return null; PsiDocumentManager.getInstance(project).commitAllDocuments(); offset = adjustOffset(document, offset); if (file instanceof PsiCompiledElement) { return ((PsiCompiledElement)file).getMirror().findReferenceAt(offset); } return file.findReferenceAt(offset); } public static PsiElement findTargetElement(Editor editor, int flags, int offset) { ApplicationManager.getApplication().assertIsDispatchThread(); Project project = editor.getProject(); if (project == null) return null; Lookup activeLookup = LookupManager.getInstance(project).getActiveLookup(); if (activeLookup != null && (flags & LOOKUP_ITEM_ACCEPTED) != 0) { final PsiElement lookupItem = getLookupItem(activeLookup); return lookupItem != null && lookupItem.isValid() ? lookupItem : null; } Document document = editor.getDocument(); PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document); if (file == null) return null; offset = adjustOffset(document, offset); PsiElement element = file.findElementAt(offset); if ((flags & REFERENCED_ELEMENT_ACCEPTED) != 0) { final PsiElement referenceOrReferencedElement = getReferenceOrReferencedElement(file, editor, flags, offset); //if (referenceOrReferencedElement == null) { // return getReferenceOrReferencedElement(file, editor, flags, offset); if (referenceOrReferencedElement != null && referenceOrReferencedElement.isValid() && !isEnumConstantReference(element, referenceOrReferencedElement)) { return referenceOrReferencedElement; } } if (element == null) return null; if ((flags & ELEMENT_NAME_ACCEPTED) != 0) { if (element instanceof PsiNamedElement) return element; PsiElement parent = element.getParent(); if (element instanceof PsiIdentifier) { if (parent instanceof PsiClass && element.equals(((PsiClass)parent).getNameIdentifier())) { return parent; } else if (parent instanceof PsiVariable && element.equals(((PsiVariable)parent).getNameIdentifier())) { return parent; } else if (parent instanceof PsiMethod && element.equals(((PsiMethod)parent).getNameIdentifier())) { return parent; } else if (parent instanceof PsiLabeledStatement && element.equals(((PsiLabeledStatement)parent).getLabelIdentifier())) { return parent; } } else if (parent instanceof PsiNamedElement) { // A bit hacky depends on navigation offset correctly overridden if (parent.getTextOffset() == element.getTextRange().getStartOffset() && !(parent instanceof XmlAttribute)) { return parent; } } } if (element instanceof PsiKeyword) { if (element.getParent() instanceof PsiThisExpression) { if ((flags & THIS_ACCEPTED) == 0) return null; PsiType type = ((PsiThisExpression)element.getParent()).getType(); if (!(type instanceof PsiClassType)) return null; return ((PsiClassType)type).resolve(); } if (element.getParent() instanceof PsiSuperExpression) { if ((flags & SUPER_ACCEPTED) == 0) return null; PsiType type = ((PsiSuperExpression)element.getParent()).getType(); if (!(type instanceof PsiClassType)) return null; return ((PsiClassType)type).resolve(); } } return null; } private static boolean isEnumConstantReference(final PsiElement element, final PsiElement referenceOrReferencedElement) { return element != null && element.getParent() instanceof PsiEnumConstant && referenceOrReferencedElement instanceof PsiMethod && ((PsiMethod)referenceOrReferencedElement).isConstructor(); } public static int adjustOffset(Document document, final int offset) { CharSequence text = document.getCharsSequence(); int correctedOffset = offset; int textLength = document.getTextLength(); if (offset >= textLength) { correctedOffset = textLength - 1; } else { if (!Character.isJavaIdentifierPart(text.charAt(offset))) { correctedOffset } } if (correctedOffset < 0 || !Character.isJavaIdentifierPart(text.charAt(correctedOffset))) return offset; return correctedOffset; } private static PsiElement getReferenceOrReferencedElement(PsiFile file, Editor editor, int flags, int offset) { PsiReference ref = findReference(editor, offset); if (ref == null) return null; PsiManager manager = file.getManager(); final PsiElement referenceElement = ref.getElement(); PsiElement refElement; if (ref instanceof PsiJavaReference) { refElement = ((PsiJavaReference)ref).advancedResolve(true).getElement(); } else { refElement = ref.resolve(); } if (refElement == null) { DaemonCodeAnalyzer.getInstance(manager.getProject()).updateVisibleHighlighters(editor); return null; } else { if ((flags & NEW_AS_CONSTRUCTOR) != 0) { PsiElement parent = referenceElement.getParent(); if (parent instanceof PsiAnonymousClass) { parent = parent.getParent(); } if (parent instanceof PsiNewExpression) { PsiMethod constructor = ((PsiNewExpression)parent).resolveConstructor(); if (constructor != null) { refElement = constructor; } } } if (refElement instanceof PsiClass && refElement.getContainingFile().getVirtualFile() == null) { // in mirror file of compiled class String qualifiedName = ((PsiClass)refElement).getQualifiedName(); if (qualifiedName == null) return null; return JavaPsiFacade.getInstance(manager.getProject()).findClass(qualifiedName, refElement.getResolveScope()); } return refElement; } } private static PsiElement getLookupItem(Lookup activeLookup) { LookupItem item = activeLookup.getCurrentItem(); if (item == null) return null; Object o = item.getObject(); if (o instanceof PsiElement) { PsiElement element = (PsiElement)o; if (!(element instanceof PsiPackage)) { if (!isValidElement(element)) return null; } return element; } else if (o instanceof LookupValueWithPsiElement) { final PsiElement element = ((LookupValueWithPsiElement)o).getElement(); if (element != null && isValidElement(element)) return element; } return null; } private static boolean isValidElement(@NotNull PsiElement element) { PsiFile file = element.getContainingFile(); if (file == null) return false; if (file.getOriginalFile() != null) file = file.getOriginalFile(); return file != null && file.getVirtualFile() != null; } }
package io.quarkus.maven; import static java.util.stream.Collectors.joining; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.Socket; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Dependency; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; 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.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.collection.CollectRequest; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.repository.WorkspaceReader; import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.resolution.DependencyRequest; import org.eclipse.aether.resolution.DependencyResolutionException; import org.eclipse.aether.resolution.DependencyResult; import org.eclipse.aether.util.artifact.JavaScopes; import org.twdata.maven.mojoexecutor.MojoExecutor; import io.quarkus.bootstrap.resolver.maven.workspace.LocalProject; import io.quarkus.dev.DevModeContext; import io.quarkus.dev.DevModeMain; import io.quarkus.maven.components.MavenVersionEnforcer; import io.quarkus.maven.utilities.MojoUtils; import io.quarkus.utilities.JavaBinFinder; /** * The dev mojo, that runs a quarkus app in a forked process. A background compilation process is launched and any changes are * automatically reflected in your running application. * <p> * You can use this dev mode in a remote container environment with {@code remote-dev}. */ @Mojo(name = "dev", defaultPhase = LifecyclePhase.PREPARE_PACKAGE, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) public class DevMojo extends AbstractMojo { /** * running any one of these phases means the compile phase will have been run, if these have * not been run we manually run compile */ private static final Set<String> POST_COMPILE_PHASES = new HashSet<>(Arrays.asList( "compile", "process-classes", "generate-test-sources", "process-test-sources", "generate-test-resources", "process-test-resources", "test-compile", "process-test-classes", "test", "prepare-package", "package", "pre-integration-test", "integration-test", "post-integration-test", "verify", "install", "deploy")); private static final String ORG_APACHE_MAVEN_PLUGINS = "org.apache.maven.plugins"; private static final String MAVEN_COMPILER_PLUGIN = "maven-compiler-plugin"; private static final String ORG_JETBRAINS_KOTLIN = "org.jetbrains.kotlin"; private static final String KOTLIN_MAVEN_PLUGIN = "kotlin-maven-plugin"; /** * The directory for compiled classes. */ @Parameter(readonly = true, required = true, defaultValue = "${project.build.outputDirectory}") private File outputDirectory; @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; /** * If this server should be started in debug mode. The default is to start in debug mode and listen on * port 5005. Whether or not the JVM is suspended waiting for a debugger to be attached, * depends on the value of {@link #suspend}. {@code debug} supports the following options: * <table> * <tr> * <td><b>Value</b></td> * <td>Effect</td> * </tr> * <tr> * <td><b>false</b></td> * <td>The JVM is not started in debug mode</td> * </tr> * <tr> * <td><b>true</b></td> * <td>The JVM is started in debug mode and will be listening on port 5005</td> * </tr> * <tr> * <td><b>client</b></td> * <td>The JVM is started in client mode, and attempts to connect to localhost:5005</td> * </tr> * <tr> * <td><b>{port}</b></td> * <td>The JVM is started in debug mode and will be listening on {port}</td> * </tr> * </table> */ @Parameter(defaultValue = "${debug}") private String debug; /** * Whether or not the JVM launch, in debug mode, should be suspended. This parameter is only * relevant when the JVM is launched in {@link #debug debug mode}. This parameter supports the * following values (all the allowed values are case insensitive): * <table> * <th> * <td>Value</td> * <td>Effect</td> * </th> * <tr> * <td>y or true</td> * <td>The debug mode JVM launch is suspended</td> * </tr> * <tr> * <td>n or false</td> * <td>The debug mode JVM is started without suspending</td> * </tr> * </table> */ @Parameter(defaultValue = "${suspend}") private String suspend; @Parameter(defaultValue = "${project.build.directory}") private File buildDir; @Parameter(defaultValue = "${project.build.sourceDirectory}") private File sourceDir; @Parameter(defaultValue = "${project.build.directory}") private File workingDir; @Parameter(defaultValue = "${jvm.args}") private String jvmArgs; @Parameter(defaultValue = "${session}") private MavenSession session; @Parameter(defaultValue = "TRUE") private boolean deleteDevJar; @Component private MavenVersionEnforcer mavenVersionEnforcer; @Component private RepositorySystem repoSystem; @Parameter(defaultValue = "${repositorySystemSession}", readonly = true) private RepositorySystemSession repoSession; @Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true, required = true) private List<RemoteRepository> repos; /** * This value is intended to be set to true when some generated bytecode * is erroneous causing the JVM to crash when the verify:none option is set (which is on by default) */ @Parameter(defaultValue = "${preventnoverify}") private boolean preventnoverify = false; /** * Whether changes in the projects that appear to be dependencies of the project containing the application to be launched * should trigger hot-reload. By default they do. */ @Parameter(defaultValue = "${noDeps}") private boolean noDeps = false; /** * Additional parameters to pass to javac when recompiling changed * source files. */ @Parameter private List<String> compilerArgs; /** * The -source argument to javac. */ @Parameter(defaultValue = "${maven.compiler.source}") private String source; /** * The -target argument to javac. */ @Parameter(defaultValue = "${maven.compiler.target}") private String target; @Component private WorkspaceReader wsReader; @Component private BuildPluginManager pluginManager; @Override public void execute() throws MojoFailureException, MojoExecutionException { mavenVersionEnforcer.ensureMavenVersion(getLog(), session); //we always want to compile if needed, so if it is run from the parent it will compile dependent projects handleAutoCompile(); Plugin pluginDef = MojoUtils.checkProjectForMavenBuildPlugin(project); if (pluginDef == null) { getLog().warn("The quarkus-maven-plugin build goal was not configured for this project, " + "skipping quarkus:dev as this is assumed to be a support library. If you want to run quarkus dev" + " on this project make sure the quarkus-maven-plugin is configured with a build goal."); return; } if (!sourceDir.isDirectory()) { getLog().warn("The project's sources directory does not exist " + sourceDir); } try { List<String> args = new ArrayList<>(); String javaTool = JavaBinFinder.findBin(); getLog().debug("Using javaTool: " + javaTool); args.add(javaTool); if (this.suspend != null) { switch (this.suspend.toLowerCase(Locale.ENGLISH)) { case "n": case "false": { suspend = "n"; break; } case "y": case "true": { suspend = "y"; break; } default: { getLog().warn( "Ignoring invalid value \"" + suspend + "\" for \"suspend\" param and defaulting to \"n\""); suspend = "n"; break; } } } else { suspend = "n"; } if (jvmArgs != null) { args.addAll(Arrays.asList(jvmArgs.split(" "))); } // the following flags reduce startup time and are acceptable only for dev purposes args.add("-XX:TieredStopAtLevel=1"); if (!preventnoverify) { args.add("-Xverify:none"); } DevModeRunner runner = new DevModeRunner(args); runner.prepare(); runner.run(); long nextCheck = System.currentTimeMillis() + 100; Map<Path, Long> pomFiles = readPomFileTimestamps(runner); for (;;) { //we never suspend after the first run suspend = "n"; long sleep = Math.max(0, nextCheck - System.currentTimeMillis()) + 1; Thread.sleep(sleep); if (System.currentTimeMillis() > nextCheck) { nextCheck = System.currentTimeMillis() + 100; if (!runner.process.isAlive()) { return; } boolean changed = false; for (Map.Entry<Path, Long> e : pomFiles.entrySet()) { long t = Files.getLastModifiedTime(e.getKey()).toMillis(); if (t > e.getValue()) { changed = true; pomFiles.put(e.getKey(), t); } } if (changed) { DevModeRunner newRunner = new DevModeRunner(args); try { newRunner.prepare(); } catch (Exception e) { getLog().info("Could not load changed pom.xml file, changes not applied", e); continue; } runner.stop(); newRunner.run(); runner = newRunner; } } } } catch (Exception e) { throw new MojoFailureException("Failed to run", e); } } private void handleAutoCompile() throws MojoExecutionException { //we check to see if there was a compile (or later) goal before this plugin boolean compileNeeded = true; for (String goal : session.getGoals()) { if (POST_COMPILE_PHASES.contains(goal)) { compileNeeded = false; break; } if (goal.endsWith("quarkus:dev")) { break; } } //if the user did not compile we run it for them if (compileNeeded) { // compile the Kotlin sources if needed final String kotlinMavenPluginKey = ORG_JETBRAINS_KOTLIN + ":" + KOTLIN_MAVEN_PLUGIN; final Plugin kotlinMavenPlugin = project.getPlugin(kotlinMavenPluginKey); if (kotlinMavenPlugin != null) { executeCompileGoal(kotlinMavenPlugin, ORG_JETBRAINS_KOTLIN, KOTLIN_MAVEN_PLUGIN); } // Compile the Java sources if needed final String compilerPluginKey = ORG_APACHE_MAVEN_PLUGINS + ":" + MAVEN_COMPILER_PLUGIN; final Plugin compilerPlugin = project.getPlugin(compilerPluginKey); if (compilerPlugin != null) { executeCompileGoal(compilerPlugin, ORG_APACHE_MAVEN_PLUGINS, MAVEN_COMPILER_PLUGIN); } } } private void executeCompileGoal(Plugin plugin, String groupId, String artifactId) throws MojoExecutionException { Xpp3Dom configuration = MojoExecutor.configuration(); Xpp3Dom pluginConfiguration = (Xpp3Dom) plugin.getConfiguration(); if (pluginConfiguration != null) { //Filter out `test*` configurations for (Xpp3Dom child : pluginConfiguration.getChildren()) { if (!child.getName().startsWith("test")) { configuration.addChild(child); } } } MojoExecutor.executeMojo( MojoExecutor.plugin( MojoExecutor.groupId(groupId), MojoExecutor.artifactId(artifactId), MojoExecutor.version(plugin.getVersion()), plugin.getDependencies()), MojoExecutor.goal("compile"), configuration, MojoExecutor.executionEnvironment( project, session, pluginManager)); } private Map<Path, Long> readPomFileTimestamps(DevModeRunner runner) throws IOException { Map<Path, Long> ret = new HashMap<>(); for (Path i : runner.getPomFiles()) { ret.put(i, Files.getLastModifiedTime(i).toMillis()); } return ret; } private String getSourceEncoding() { Object sourceEncodingProperty = project.getProperties().get("project.build.sourceEncoding"); if (sourceEncodingProperty != null) { return (String) sourceEncodingProperty; } return null; } private void addProject(DevModeContext devModeContext, LocalProject localProject) { String projectDirectory = null; Set<String> sourcePaths = null; String classesPath = null; String resourcePath = null; final MavenProject mavenProject = session.getProjectMap().get( String.format("%s:%s:%s", localProject.getGroupId(), localProject.getArtifactId(), localProject.getVersion())); if (mavenProject == null) { projectDirectory = localProject.getDir().toAbsolutePath().toString(); Path sourcePath = localProject.getSourcesSourcesDir().toAbsolutePath(); if (Files.isDirectory(sourcePath)) { sourcePaths = Collections.singleton( sourcePath.toString()); } else { sourcePaths = Collections.emptySet(); } } else { projectDirectory = mavenProject.getBasedir().getPath(); sourcePaths = mavenProject.getCompileSourceRoots().stream() .map(Paths::get) .filter(Files::isDirectory) .map(src -> src.toAbsolutePath().toString()) .collect(Collectors.toSet()); } Path classesDir = localProject.getClassesDir(); if (Files.isDirectory(classesDir)) { classesPath = classesDir.toAbsolutePath().toString(); } Path resourcesSourcesDir = localProject.getResourcesSourcesDir(); if (Files.isDirectory(resourcesSourcesDir)) { resourcePath = resourcesSourcesDir.toAbsolutePath().toString(); } DevModeContext.ModuleInfo moduleInfo = new DevModeContext.ModuleInfo( localProject.getArtifactId(), projectDirectory, sourcePaths, classesPath, resourcePath); devModeContext.getModules().add(moduleInfo); } private void addToClassPaths(StringBuilder classPathManifest, DevModeContext classPath, File file) { final URI uri = file.toPath().toAbsolutePath().toUri(); try { classPath.getClassPath().add(uri.toURL()); } catch (MalformedURLException e) { throw new RuntimeException(e); } classPathManifest.append(uri).append(" "); } class DevModeRunner { private static final String KOTLIN_MAVEN_PLUGIN_GA = "org.jetbrains.kotlin:kotlin-maven-plugin"; private final List<String> args; private Process process; private Set<Path> pomFiles = new HashSet<>(); DevModeRunner(List<String> args) { this.args = new ArrayList<>(args); } /** * Attempts to prepare the dev mode runner. */ void prepare() throws Exception { if (debug == null) { boolean useDebugMode = true; // debug mode not specified // make sure 5005 is not used, we don't want to just fail if something else is using it try (Socket socket = new Socket(InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), 5005)) { getLog().error("Port 5005 in use, not starting in debug mode"); useDebugMode = false; } catch (IOException e) { } if (useDebugMode) { args.add("-Xdebug"); args.add("-Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=" + suspend); } } else if (debug.toLowerCase().equals("client")) { args.add("-Xdebug"); args.add("-Xrunjdwp:transport=dt_socket,address=localhost:5005,server=n,suspend=" + suspend); } else if (debug.toLowerCase().equals("true")) { args.add("-Xdebug"); args.add("-Xrunjdwp:transport=dt_socket,address=localhost:5005,server=y,suspend=" + suspend); } else if (!debug.toLowerCase().equals("false")) { try { int port = Integer.parseInt(debug); if (port <= 0) { throw new MojoFailureException("The specified debug port must be greater than 0"); } args.add("-Xdebug"); args.add("-Xrunjdwp:transport=dt_socket,address=" + port + ",server=y,suspend=" + suspend); } catch (NumberFormatException e) { throw new MojoFailureException( "Invalid value for debug parameter: " + debug + " must be true|false|client|{port}"); } } //build a class-path string for the base platform //this stuff does not change // Do not include URIs in the manifest, because some JVMs do not like that StringBuilder classPathManifest = new StringBuilder(); final DevModeContext devModeContext = new DevModeContext(); for (Map.Entry<Object, Object> e : System.getProperties().entrySet()) { devModeContext.getSystemProperties().put(e.getKey().toString(), (String) e.getValue()); } devModeContext.setProjectDir(project.getFile().getParentFile()); devModeContext.getBuildSystemProperties().putAll((Map) project.getProperties()); // this is a minor hack to allow ApplicationConfig to be populated with defaults devModeContext.getBuildSystemProperties().putIfAbsent("quarkus.application.name", project.getArtifactId()); devModeContext.getBuildSystemProperties().putIfAbsent("quarkus.application.version", project.getVersion()); devModeContext.setSourceEncoding(getSourceEncoding()); devModeContext.setSourceJavaVersion(source); devModeContext.setTargetJvmVersion(target); // Set compilation flags. Try the explicitly given configuration first. Otherwise, // refer to the configuration of the Maven Compiler Plugin. if (compilerArgs != null) { devModeContext.setCompilerOptions(compilerArgs); } else { for (Plugin plugin : project.getBuildPlugins()) { if (!plugin.getKey().equals("org.apache.maven.plugins:maven-compiler-plugin")) { continue; } Xpp3Dom compilerPluginConfiguration = (Xpp3Dom) plugin.getConfiguration(); if (compilerPluginConfiguration == null) { continue; } Xpp3Dom compilerPluginArgsConfiguration = compilerPluginConfiguration.getChild("compilerArgs"); if (compilerPluginArgsConfiguration == null) { continue; } List<String> compilerPluginArgs = new ArrayList<>(); for (Xpp3Dom argConfiguration : compilerPluginArgsConfiguration.getChildren()) { compilerPluginArgs.add(argConfiguration.getValue()); } devModeContext.setCompilerOptions(compilerPluginArgs); break; } } setKotlinSpecificFlags(devModeContext); final LocalProject localProject; if (noDeps) { localProject = LocalProject.load(outputDirectory.toPath()); addProject(devModeContext, localProject); pomFiles.add(localProject.getDir().resolve("pom.xml")); } else { localProject = LocalProject.loadWorkspace(outputDirectory.toPath()); for (LocalProject project : localProject.getSelfWithLocalDeps()) { if (project.getClassesDir() != null && //if this project also contains Quarkus extensions we do no want to include these in the discovery //a bit of an edge case, but if you try and include a sample project with your extension you will //run into problems without this (Files.exists(project.getClassesDir().resolve("META-INF/quarkus-extension.properties")) || Files.exists(project.getClassesDir().resolve("META-INF/quarkus-build-steps.list")))) { continue; } addProject(devModeContext, project); pomFiles.add(project.getDir().resolve("pom.xml")); } } addQuarkusDevModeDeps(classPathManifest, devModeContext); args.add("-Djava.util.logging.manager=org.jboss.logmanager.LogManager"); //wiring devmode is used for CDI beans that are not part of the user application (i.e. beans in 3rd party jars) //we need this because these beans cannot be loaded by the runtime class loader, they must be loaded by the platform //class loader File wiringClassesDirectory = new File(buildDir, "wiring-devmode"); wiringClassesDirectory.mkdirs(); addToClassPaths(classPathManifest, devModeContext, wiringClassesDirectory); //in most cases these are not used, however they need to be present for some //parent-first cases such as logging for (Artifact appDep : project.getArtifacts()) { addToClassPaths(classPathManifest, devModeContext, appDep.getFile()); } //now we need to build a temporary jar to actually run File tempFile = new File(buildDir, project.getArtifactId() + "-dev.jar"); tempFile.delete(); // Only delete the -dev.jar on exit if requested if (deleteDevJar) { tempFile.deleteOnExit(); } getLog().debug("Executable jar: " + tempFile.getAbsolutePath()); devModeContext.getClassesRoots().add(outputDirectory.getAbsoluteFile()); devModeContext.setFrameworkClassesDir(wiringClassesDirectory.getAbsoluteFile()); devModeContext.setCacheDir(new File(buildDir, "transformer-cache").getAbsoluteFile()); // this is the jar file we will use to launch the dev mode main class devModeContext.setDevModeRunnerJarFile(tempFile); try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tempFile))) { out.putNextEntry(new ZipEntry("META-INF/")); Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, classPathManifest.toString()); manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, DevModeMain.class.getName()); out.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); manifest.write(out); out.putNextEntry(new ZipEntry(DevModeMain.DEV_MODE_CONTEXT)); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); ObjectOutputStream obj = new ObjectOutputStream(new DataOutputStream(bytes)); obj.writeObject(devModeContext); obj.close(); out.write(bytes.toByteArray()); } outputDirectory.mkdirs(); args.add("-jar"); args.add(tempFile.getAbsolutePath()); } private void addQuarkusDevModeDeps(StringBuilder classPathManifest, final DevModeContext devModeContext) throws MojoExecutionException, DependencyResolutionException { final String pomPropsPath = "META-INF/maven/io.quarkus/quarkus-development-mode/pom.properties"; final InputStream devModePomPropsIs = DevModeMain.class.getClassLoader().getResourceAsStream(pomPropsPath); if (devModePomPropsIs == null) { throw new MojoExecutionException("Failed to locate " + pomPropsPath + " on the classpath"); } final Properties devModeProps = new Properties(); try (InputStream is = devModePomPropsIs) { devModeProps.load(is); } catch (IOException e) { throw new MojoExecutionException("Failed to load " + pomPropsPath + " from the classpath", e); } final String devModeGroupId = devModeProps.getProperty("groupId"); if (devModeGroupId == null) { throw new MojoExecutionException("Classpath resource " + pomPropsPath + " is missing groupId"); } final String devModeArtifactId = devModeProps.getProperty("artifactId"); if (devModeArtifactId == null) { throw new MojoExecutionException("Classpath resource " + pomPropsPath + " is missing artifactId"); } final String devModeVersion = devModeProps.getProperty("version"); if (devModeVersion == null) { throw new MojoExecutionException("Classpath resource " + pomPropsPath + " is missing version"); } final DefaultArtifact devModeJar = new DefaultArtifact(devModeGroupId, devModeArtifactId, "jar", devModeVersion); final DependencyResult cpRes = repoSystem.resolveDependencies(repoSession, new DependencyRequest() .setCollectRequest( new CollectRequest() .setRoot(new org.eclipse.aether.graph.Dependency(devModeJar, JavaScopes.RUNTIME)) .setRepositories(repos))); for (ArtifactResult appDep : cpRes.getArtifactResults()) { File file = appDep.getArtifact().getFile(); addToClassPaths(classPathManifest, devModeContext, file); } } private void setKotlinSpecificFlags(DevModeContext devModeContext) { Plugin kotlinMavenPlugin = null; for (Plugin plugin : project.getBuildPlugins()) { if (plugin.getKey().equals(KOTLIN_MAVEN_PLUGIN_GA)) { kotlinMavenPlugin = plugin; break; } } if (kotlinMavenPlugin == null) { return; } getLog().debug("Kotlin Maven plugin detected"); List<String> compilerPluginArtifacts = new ArrayList<>(); List<Dependency> dependencies = kotlinMavenPlugin.getDependencies(); for (Dependency dependency : dependencies) { try { ArtifactResult resolvedArtifact = repoSystem.resolveArtifact(repoSession, new ArtifactRequest() .setArtifact(new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(), dependency.getType(), dependency.getVersion())) .setRepositories(repos)); compilerPluginArtifacts.add(resolvedArtifact.getArtifact().getFile().toPath().toAbsolutePath().toString()); } catch (ArtifactResolutionException e) { getLog().warn("Unable to properly setup dev-mode for Kotlin", e); return; } } devModeContext.setCompilerPluginArtifacts(compilerPluginArtifacts); List<String> options = new ArrayList<>(); Xpp3Dom compilerPluginConfiguration = (Xpp3Dom) kotlinMavenPlugin.getConfiguration(); if (compilerPluginConfiguration != null) { Xpp3Dom compilerPluginArgsConfiguration = compilerPluginConfiguration.getChild("pluginOptions"); if (compilerPluginArgsConfiguration != null) { for (Xpp3Dom argConfiguration : compilerPluginArgsConfiguration.getChildren()) { options.add(argConfiguration.getValue()); } } } devModeContext.setCompilerPluginsOptions(options); } public Set<Path> getPomFiles() { return pomFiles; } public void run() throws Exception { // Display the launch command line in dev mode if (getLog().isDebugEnabled()) { getLog().debug("Launching JVM with command line: " + args.stream().collect(joining(" "))); } process = new ProcessBuilder(args) .inheritIO() .directory(workingDir) .start(); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { process.destroy(); } }, "Development Mode Shutdown Hook")); } public void stop() throws InterruptedException { process.destroy(); process.waitFor(); } } }
package com.shuimin.pond.codec.restful; import com.shuimin.common.S; import com.shuimin.common.f.Function; import com.shuimin.common.f.Holder; import com.shuimin.pond.core.db.Record; import com.shuimin.pond.codec.mvc.Controller; import com.shuimin.pond.core.Global; import com.shuimin.pond.core.Middleware; import com.shuimin.pond.core.Pond; import com.shuimin.pond.core.Request; import com.shuimin.pond.core.http.HttpMethod; import com.shuimin.pond.core.mw.Action; import java.io.File; import java.util.Arrays; import static com.shuimin.common.S._for; import static com.shuimin.common.f.Tuple.T3; import static com.shuimin.common.f.Tuple.t3; import static com.shuimin.pond.core.Interrupt.render; import static com.shuimin.pond.core.Pond.debug; import static com.shuimin.pond.core.Renderable.view; import static com.shuimin.pond.core.http.HttpMethod.mask; public class Resource extends Controller { /** * GET ${bo}/?[query] -- list as query text/html index.view || application/json */ public static final Function<T3<Integer, String, Middleware>, Resource> INDEX = res -> t3(mask(HttpMethod.GET), "", Action.simple((req, resp) -> { ResourceService service = res.service.val; String mime = getAcceptHeader(req).trim().toLowerCase(); if (mime.startsWith("text/html")) render(view(res.resourcePath("index.view"), service.query(req))); else render(service.render(mime, service.query((req)))); })); /** * POST ${bo}/?[params] -- create */ public static final Function<T3<Integer, String, Middleware>, Resource> CREATE = res -> t3(mask(HttpMethod.POST), "", Action.simple((req, resp) -> res.service.val.create(req))); /** * GET ${bo}/${id} -- get by id text/html detail.view || application/json */ public final static Function<T3<Integer, String, Middleware>, Resource> GET = res -> t3(mask(HttpMethod.GET), "/${_id}" , Action.simple((req, resp) -> { String id = req.param("_id"); String mime = getAcceptHeader(req).trim().toLowerCase(); if (mime.startsWith("text/html")) render(view(res.resourcePath("detail.view"), res.service.val.get(id))); else render(res.service.val.render(mime, res.service.val.get(id))); })); /** * DELETE ${bo}/${id} --delete */ public final static Function<T3<Integer, String, Middleware>, Resource> DELETE = res -> t3(mask(HttpMethod.DELETE), "/${_id}", Action.simple((req, resp) -> { String id = req.param("_id"); res.service.val.delete(id); }) ); /** * PUT ${bo}/${id} --update */ public final static Function<T3<Integer, String, Middleware>, Resource> UPDATE = res -> t3(mask(HttpMethod.PUT), "/${_id}", Action.simple((req, resp) -> { ResourceService service = res.service.val; String id = req.param("_id"); service.update(id, req); }) ); /** * GET ${bo}/new -- new view ONLY ACCEPT text/html new.view */ public final Function<T3<Integer, String, Middleware>, Resource> VIEW_NEW = res -> t3(mask(HttpMethod.GET), "/new", Action.fly(() -> render(view(resourcePath("new.view")))) ); /** * GET ${bo}/${id}/edit -- edit view ACCEPT text/html edit.view */ public final Function<T3<Integer, String, Middleware>, Resource> VIEW_EDIT = res -> t3(mask(HttpMethod.GET), "/${_id}/edit", Action.simple((req, resp) -> { String id = req.param("_id"); Object o = res.service.val.get(id); render(view(resourcePath("edit.view"), o)); }) ); protected final Holder<ResourceService> service = new Holder<>(); private Resource(ResourceService service) { this.service.val = service; } static String getAcceptHeader(Request req) { String accept = _for(req.header("Accept")).first(); debug("Accept:" + accept); return S.str.notBlank(accept) ? accept : "text/html"; } public static Resource build(Record proto, Function<T3<Integer, String, Middleware>, Resource>... actions) { Resource ret = new Resource(new ResourceService() { @Override Record prototype() { return proto; } }); if (actions == null || actions.length == 0) return ret.initByDefault(); else ret.actions.addAll(Arrays.asList(_for(actions).map(a -> a.apply(ret)).join())); return ret; } public static Resource build(Function.F0<Record> func, Function<T3<Integer, String, Middleware>, Resource>... actions) { return build(func.apply(),actions); } public ResourceService service() { return service.val; } String templatePath() { return Pond.attribute(Global.TEMPLATE_PATH); } private Resource initByDefault() { this.actions.add(INDEX.apply(this)); this.actions.add(GET.apply(this)); this.actions.add(UPDATE.apply(this)); this.actions.add(CREATE.apply(this)); this.actions.add(VIEW_NEW.apply(this)); this.actions.add(VIEW_EDIT.apply(this)); this.actions.add(DELETE.apply(this)); return this; } String resourcePath(String name) { return templatePath() + File.separator + nameSupplier.apply(this) + File.separator + name; } }
package com.almende.dialog; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.jongo.Aggregate; import org.jongo.Jongo; import org.jongo.MongoCollection; import org.jongo.marshall.jackson.JacksonMapper; import com.almende.dialog.accounts.AdapterConfig; import com.almende.dialog.model.Session; import com.almende.dialog.util.ServerUtils; import com.almende.eve.rpc.jsonrpc.jackson.JOM; import com.almende.util.ParallelInit; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.datatype.joda.JodaModule; import com.mongodb.DB; public class Logger { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(Logger.class.getName()); private static final int adapter_chunk_size = 20; public Logger() { } public void severe(String adapterID, String message, String ddrRecordId, String sessionKey) { severe(adapterID, null, message, ddrRecordId, sessionKey); } public void severe(String adapterID, String adapterType, String message, String ddrRecordId, String sessionKey) { this.log(LogLevel.SEVERE, adapterID, adapterType, message, ddrRecordId, sessionKey); } public void severe(AdapterConfig adapter, String message, Session session) { this.log(LogLevel.SEVERE, adapter, message, session); } public void severe(AdapterConfig adapter, String message, String ddrRecordId, String sessionKey) { this.log(LogLevel.SEVERE, adapter, message, ddrRecordId, sessionKey); } public void warning(String adapterID, String message, String ddrRecordId, String sessionKey) { warning(adapterID, null, message, ddrRecordId, sessionKey); } public void warning(String adapterID, String adapterType, String message, String ddrRecordId, String sessionKey) { this.log(LogLevel.WARNING, adapterID, adapterType, message, ddrRecordId, sessionKey); } public void warning(AdapterConfig adapter, String message, String ddrRecordId, String sessionKey) { this.log(LogLevel.WARNING, adapter, message, ddrRecordId, sessionKey); } public void warning(AdapterConfig adapter, String message, Session session) { this.log(LogLevel.WARNING, adapter, message, session); } public void info(String adapterID, String message, String ddrRecordId, String sessionKey) { info(adapterID, null, message, ddrRecordId, sessionKey); } public void info(String adapterID, String adapterType, String message, String ddrRecordId, String sessionKey) { this.log(LogLevel.INFO, adapterID, adapterType, message, ddrRecordId, sessionKey); } public void info(AdapterConfig adapter, String message, String ddrRecordId, String sessionKey) { this.log(LogLevel.INFO, adapter, message, ddrRecordId, sessionKey); } public void info(AdapterConfig adapter, String message, Session session) { this.log(LogLevel.INFO, adapter, message, session); } public void debug(String adapterID, String message, String ddrRecordId, String sessionKey) { debug(adapterID, null, message, ddrRecordId, sessionKey); } public void debug(String adapterID, String adapterType, String message, String ddrRecordId, String sessionKey) { this.log(LogLevel.DEBUG, adapterID, adapterType, message, ddrRecordId, sessionKey); } public void debug(AdapterConfig adapter, String message, String ddrRecordId, String sessionKey) { this.log(LogLevel.DEBUG, adapter, message, ddrRecordId, sessionKey); } public void debug(AdapterConfig adapter, String message, Session session) { this.log(LogLevel.DEBUG, adapter, message, session); } public void ddr(AdapterConfig adapter, String message, String ddrRecordId, String sessionKey) { this.log(LogLevel.DDR, adapter, message, ddrRecordId, sessionKey); } public void log(LogLevel level, String adapterId, String adapterType, String message, String ddrRecordId, String sessionKey) { MongoCollection collection = getCollection(); collection.insert(new Log(level, adapterId, adapterType, message, ddrRecordId, sessionKey)); } public void log(LogLevel level, AdapterConfig adapter, String message, String ddrRecordId, String sessionKey) { MongoCollection collection = getCollection(); collection.insert(new Log(level, adapter, message, ddrRecordId, sessionKey)); } public void log(LogLevel level, AdapterConfig adapter, String message, Session session) { MongoCollection collection = getCollection(); collection.insert(new Log(level, adapter, message, session)); } public List<Log> find(Collection<String> adapters, Collection<LogLevel> levels, String adapterType, Long endTime, Integer offset, Integer limit) { List<Log> resultLogs = new ArrayList<Log>(); try { if (adapters != null) { log.info(String.format("Initial adapters size %s", adapters.size())); int startingIndex = 0; int endIndex = adapters.size() <= adapter_chunk_size ? adapters.size() : adapter_chunk_size; for (int chunkCount = 0; chunkCount <= (adapters.size() / adapter_chunk_size); chunkCount++) { log.info(String.format("chunkCount %s startIndex: %s endIndex %s", chunkCount, startingIndex, endIndex)); List<String> chunkedAdapters = new ArrayList<String>(adapters).subList(startingIndex, endIndex); List<Log> logsWithLimit = getLogsWithLimit(chunkedAdapters, levels, adapterType, endTime, offset, limit); if (logsWithLimit != null && !logsWithLimit.isEmpty()) { resultLogs.addAll(logsWithLimit); } //update indexes startingIndex = startingIndex + adapter_chunk_size; endIndex = adapters.size() >= endIndex + adapter_chunk_size ? endIndex + adapter_chunk_size : adapters.size(); } } else { resultLogs = getLogsWithLimit(adapters, levels, adapterType, endTime, offset, limit); } } catch (Exception e) { log.severe("Exception seen while trying to fetch logs. Message: " + e.getMessage()); } return resultLogs; } /** * fetches the logs based on the initial {@link Logger#adapter_chunk_size} adapters. <br> * creates a jongo aggregate query similar to: <br> * ( [ { $match: { adapterID: {$in: ["f9a398e0-ba5d-11e3-a019-08edb99eaa2d"]}, timestamp: {$lte: 1396449705737} } }, { $group: { _id: {level: "$level", id:"$logId", adapterId: "$adapterID", adapterType: "$adapterType", message:"$message", timestamp: "$timestamp"} } }, { $sort : {timestamp: -1} }, { $skip: 0 }, { $limit: 4 } ] ) * * * @return * @throws Exception */ private List<Log> getLogsWithLimit(Collection<String> adapters, Collection<LogLevel> levels, String adapterType, Long endTime, Integer offset, Integer limit) throws Exception { MongoCollection collection = getCollection(); //initially collect all the match queries String matchQuery = null; if (adapters != null) { int endIndex = adapters.size() <= adapter_chunk_size - 1 ? adapters.size() : adapter_chunk_size; List<String> subAdapterList = new ArrayList<String>(adapters).subList(0, endIndex); if (!subAdapterList.isEmpty()) { matchQuery = "adapterID: {$in:" + ServerUtils.serialize(subAdapterList) + "}"; } } if (adapterType != null){ matchQuery = matchQuery != null ? ( matchQuery + "," ) : ""; matchQuery += "adapterType:\"" + adapterType + "\""; } if (endTime != null) { matchQuery = matchQuery != null ? ( matchQuery + "," ) : ""; matchQuery += "timestamp:{$lte:" + endTime + "}"; } if(levels != null) { matchQuery = matchQuery != null ? ( matchQuery + "," ) : ""; matchQuery += "level:{$in:" + ServerUtils.serialize(levels) + "}"; } Aggregate aggregate = null; //create an aggregate query with the matchQuery first if(matchQuery != null) { aggregate = collection.aggregate(String.format("{$match: {%s}}", matchQuery)); } //update the aggregate query with groupQuery next. This includes all the fields to fetch String groupQuery = "{$group:{_id: {trackingToken:\"$trackingToken\",logId:\"$logId\", level: \"$level\", " + "adapterID: \"$adapterID\", adapterType: \"$adapterType\", message:\"$message\", " + "timestamp: \"$timestamp\", ddrRecordId: \"$ddrRecordId\", sessionKey: \"$sessionKey\"}}}"; if(aggregate != null) { aggregate = aggregate.and(groupQuery); } else { aggregate = collection.aggregate(groupQuery); } if (offset == null) { offset = 0; } if (limit == null) { limit = 50; } //update the aggregate query with sort (on timestamp), offset and limit aggregate = aggregate.and("{$sort : {timestamp: -1}}").and(String.format("{$skip :%s}", offset)) .and(String.format("{$limit :%s}", limit)); List<ObjectNode> resultLogMap = aggregate.as(ObjectNode.class); ArrayList<Log> resultLogs = new ArrayList<Log>(); for (ObjectNode resultLog : resultLogMap) { JsonNode jsonNode = resultLog.get("_id"); Log convertValue = JOM.getInstance().convertValue(jsonNode, Log.class); resultLogs.add(convertValue); } return resultLogs; } private static MongoCollection getCollection() { DB db = ParallelInit.getDatastore(); Jongo jongo = new Jongo(db, new JacksonMapper.Builder().registerModule(new JodaModule()) .enable(MapperFeature.AUTO_DETECT_GETTERS).withView(Log.class).build()); return jongo.getCollection(Log.class.getCanonicalName().toLowerCase() + "s"); } }
package com.notlob.jgrid.renderer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import com.notlob.jgrid.Grid; import com.notlob.jgrid.model.Column; import com.notlob.jgrid.model.Row; import com.notlob.jgrid.model.SortDirection; import com.notlob.jgrid.styles.AlignmentStyle; import com.notlob.jgrid.styles.CellStyle; import com.notlob.jgrid.styles.ContentStyle; import com.notlob.jgrid.styles.LineStyle; /** * Responsible for rendering individual cells. * * @author Stef */ public class CellRenderer<T> extends Renderer<T> { // Used when painting a cell throws an exception. protected Image errorImage; // The references below are recycled objects - to avoid GC churn. // Used to render the inner border (example: anchor) of a cell and also used to layout the content // of a cell. protected final Rectangle innerBounds; // Used to align an image and/or text within the innerBounds. protected final Point contentLocation; public CellRenderer(final Grid<T> grid) { super(grid); errorImage = getImage("cell_error.gif"); contentLocation = new Point(0, 0); innerBounds = new Rectangle(0, 0, 0, 0); } /** * Paint the background, borders and content for the specified cell (column and row). * * The cell's background, content and (any) inner borders are painted within the specified cell bounds. * * The cell's outer border can be renderer around the outside of these bounds. */ public void paintCell(final RenderContext rc, final Rectangle bounds, final Column column, final Row<T> row, final CellStyle cellStyle) { try { CellStyle currentStyle = cellStyle; // If the cell has the anchor, use a composite style. if (!rc.isPaintingPinned() && grid.isFocusControl() && grid.isHighlightAnchorCellBorder() && doesColumnHaveAnchor(column) && doesRowHaveAnchor(row)) { styleRegistry.getStyleCollector().addFirst(styleRegistry.getAnchorStyle()); currentStyle = styleRegistry.getStyleCollector().getCellStyle(); } if (rc.getRenderPass() == RenderPass.BACKGROUND) { // Paint the cell background. paintCellBackground(rc, bounds, currentStyle, row); } else if (rc.getRenderPass() == RenderPass.FOREGROUND) { // Paint cell content. paintCellContent(rc, bounds, column, row, currentStyle); paintCellBorders(rc, bounds, currentStyle); } } catch (final Throwable t) { if (!rc.isErrorLogged()) { // Print the error to the std err and ensure we only do this once to avoid log fillage. System.err.println(String.format("Failed to paint: %s", t.getMessage())); t.printStackTrace(System.err); rc.setErrorLogged(true); } // Render a failure. final RGB background = (rc.isAlternate() && (cellStyle.getBackgroundAlternate() != null)) ? cellStyle.getBackgroundAlternate() : cellStyle.getBackground(); final GC gc = rc.getGC(); gc.setForeground(getColour(cellStyle.getForeground())); gc.setBackground(getColour(background)); gc.drawImage(errorImage, bounds.x + 2, bounds.y + 2); gc.drawText("ERROR", bounds.x + 2 + errorImage.getBounds().width, bounds.y + 2); } } /** * Fill the cell background. Expand the area of the fill to include any cell spacing, otherwise strips are left * in the background colour of the grid. */ protected void paintCellBackground(final RenderContext rc, final Rectangle bounds, final CellStyle cellStyle, final Row<T> row) throws Exception { final GC gc = rc.getGC(); gc.setAlpha(cellStyle.getBackgroundOpacity()); final RGB background = (rc.isAlternate() && (cellStyle.getBackgroundAlternate() != null)) ? cellStyle.getBackgroundAlternate() : cellStyle.getBackground(); final RGB backgroundGradient1 = (rc.isAlternate() && (cellStyle.getBackgroundAlternateGradient1() != null)) ? cellStyle.getBackgroundAlternateGradient1() : cellStyle.getBackgroundGradient1(); final RGB backgroundGradient2 = (rc.isAlternate() && (cellStyle.getBackgroundAlternateGradient2() != null)) ? cellStyle.getBackgroundAlternateGradient2() : cellStyle.getBackgroundGradient2(); // Get the background colour (or colours if there's a gradient). if (backgroundGradient1 == null || backgroundGradient2 == null) { // Fill with no Gradient gc.setBackground(getColour(background)); if ((row != null) && (row.getAnimation() != null)) { row.getAnimation().pulseBackground(rc, row); } gc.fillRectangle(bounds.x, bounds.y, bounds.width, bounds.height); } else { // Fill with Gradient (upper, lower). final int halfHeight = bounds.height / 2; gc.setForeground(getColour(backgroundGradient1)); gc.setBackground(getColour(background)); gc.fillGradientRectangle(bounds.x, bounds.y, bounds.width, halfHeight, true); gc.setForeground(getColour(background)); gc.setBackground(getColour(backgroundGradient2)); gc.fillGradientRectangle(bounds.x, bounds.y + halfHeight, bounds.width, 1 + halfHeight, true); } } /** * Paint the outer then inner borders of the cell. */ protected void paintCellBorders(final RenderContext rc, final Rectangle bounds, final CellStyle cellStyle) throws Exception { final GC gc = rc.getGC(); gc.setAlpha(cellStyle.getForegroundOpacity()); // Render outer border. setCorners(bounds, topLeft, topRight, bottomRight, bottomLeft); paintBorderLine(gc, cellStyle.getBorderOuterTop(), topLeft, topRight); paintBorderLine(gc, cellStyle.getBorderOuterBottom(), bottomLeft, bottomRight); paintBorderLine(gc, cellStyle.getBorderOuterLeft(), topLeft, bottomLeft); // Avoid rendering a grip on certain cells (corner and last header for example). if (!(rc.isDontPaintGrip() && (cellStyle.getBorderOuterRight() != null) && (cellStyle.getBorderOuterRight().getLineStyle() == LineStyle.GRIP))) { paintBorderLine(gc, cellStyle.getBorderOuterRight(), topRight, bottomRight); } // Calculate where the inner border should be. shrinkRectangle(bounds, innerBounds, cellStyle.getPaddingInnerBorder()); // Render inner border. setCorners(innerBounds, topLeft, topRight, bottomRight, bottomLeft); paintBorderLine(gc, cellStyle.getBorderInnerTop(), topLeft, topRight); paintBorderLine(gc, cellStyle.getBorderInnerBottom(), bottomLeft, bottomRight); paintBorderLine(gc, cellStyle.getBorderInnerLeft(), topLeft, bottomLeft); paintBorderLine(gc, cellStyle.getBorderInnerRight(), topRight, bottomRight); } /** * Paint cell's image and text within the bounds specified using the style specified. */ protected void paintCellContent(final RenderContext rc, final Rectangle bounds, final Column column, final Row<T> row, final CellStyle cellStyle) throws Exception { // The corner cell has no content. if (column == gridModel.getRowNumberColumn() && row == gridModel.getColumnHeaderRow()) { return; } final GC gc = rc.getGC(); gc.setAlpha(cellStyle.getForegroundOpacity()); gc.setFont(getFont(cellStyle.getFontData())); // We'll use inner bounds to indicate where the next piece of content will be allowed. Initially, it's the full // cell bounds (adjusted for cell padding), then, after the first image or text is drawn, the inner bounds will // shrink/move to ensure the next image/text content can't overwrite it. // Note: This should only be used if content overlap is off. final int outerBorderLeftWidth = (cellStyle.getBorderOuterLeft() == null ? 0 :cellStyle.getBorderOuterLeft().getWidth()); final int outerBorderTopWidth = (cellStyle.getBorderOuterTop() == null ? 0 : cellStyle.getBorderOuterTop().getWidth()); innerBounds.x = bounds.x + cellStyle.getPaddingLeft() + outerBorderLeftWidth; innerBounds.y = bounds.y + cellStyle.getPaddingTop() + outerBorderTopWidth; innerBounds.width = bounds.width - cellStyle.getPaddingLeft() - cellStyle.getPaddingRight() - outerBorderLeftWidth; innerBounds.height = bounds.height - cellStyle.getPaddingTop() - cellStyle.getPaddingBottom() - outerBorderTopWidth; // Render cell image BEFORE text.. if ((row != null) && (cellStyle.getContentStyle() == ContentStyle.IMAGE || cellStyle.getContentStyle() == ContentStyle.IMAGE_THEN_TEXT)) { paintCellImage(rc, column, row, cellStyle); } // Render cell text. if (cellStyle.getContentStyle() != ContentStyle.IMAGE) { final Rectangle oldClipping = gc.getClipping(); gc.setClipping(innerBounds); paintCellText(rc, column, row, cellStyle); gc.setClipping(oldClipping); } // Render cell image AFTER text.. if ((row != null) && (cellStyle.getContentStyle() == ContentStyle.TEXT_THEN_IMAGE)) { paintCellImage(rc, column, row, cellStyle); } } /** * Paints the image for the cell (if there is one) regardless of whether we're painting it before (to the left of) * or after (to the right of) the cell's text (if any). */ protected void paintCellImage(final RenderContext rc, final Column column, final Row<T> row, final CellStyle cellStyle) throws Exception { final Image image = getCellImage(column, row); if (image != null) { // Get the image alignment. final AlignmentStyle imageAlignment = (cellStyle.getImageAlignment() != null) ? cellStyle.getImageAlignment() : (column.getImageAlignment() != null ? column.getImageAlignment() : AlignmentStyle.LEFT_CENTER); // Align/position and render the image. align(image.getBounds().width, image.getBounds().height, innerBounds, contentLocation, imageAlignment); rc.getGC().drawImage(image, contentLocation.x, contentLocation.y); if (!cellStyle.isAllowContentOverlap()) { innerBounds.x += (image.getBounds().width + cellStyle.getPaddingImageText()); innerBounds.width -= (image.getBounds().width + cellStyle.getPaddingImageText()); } } } /** * Paints the cell text (and animates if required). */ protected void paintCellText(final RenderContext rc, final Column column, final Row<T> row, final CellStyle cellStyle) throws Exception { final String text = getCellText(column, row); if (text != null && !text.isEmpty()) { final GC gc = rc.getGC(); // Ensure any image in the header row that follows text, doesn't have text running through it. int widthCap = 0; if (row == gridModel.getColumnHeaderRow() && (cellStyle.getContentStyle() == ContentStyle.TEXT_THEN_IMAGE)) { final Image image = getCellImage(column, row); if (image != null) { widthCap = image.getBounds().width + cellStyle.getPaddingImageText(); innerBounds.width -= widthCap; gc.setClipping(innerBounds); } } final Point textExtent = getTextExtent(text, rc, cellStyle.getFontData()); final int width = Math.min(textExtent.x, (innerBounds.width - widthCap)); final int height = Math.min(textExtent.y, innerBounds.height); final AlignmentStyle textAlignment = (cellStyle.getTextAlignment() == null) ? (column.getTextAlignment() == null ? AlignmentStyle.LEFT_CENTER : column.getTextAlignment()) : cellStyle.getTextAlignment(); align(width, height, innerBounds, contentLocation, textAlignment); // Perform an animation on the row - if required. This can cause the text to bounce into view. if ((row != null) && (row != gridModel.getColumnHeaderRow()) && (row.getAnimation() != null)) { row.getAnimation().animateText(rc, this, row); } final boolean highlightFilterMatch = doesCellHaveStyleableFilterMatch(row, column); if (highlightFilterMatch) { // Use text highlighting if there's a FilterMatchRange in this column (and it's trackable). gc.setBackground(getColour(styleRegistry.getFilterMatchBackground())); gc.setForeground(getColour(styleRegistry.getFilterMatchForeground())); gc.drawText(text, contentLocation.x, contentLocation.y); } else { // Use normal colours if we're not highlighting a filter result. gc.setForeground(getColour(cellStyle.getForeground())); gc.drawText(text, contentLocation.x, contentLocation.y, SWT.DRAW_TRANSPARENT); } if (widthCap > 0) { innerBounds.width += widthCap; gc.setClipping(innerBounds); } if (!cellStyle.isAllowContentOverlap()) { innerBounds.x += (width + cellStyle.getPaddingImageText()); innerBounds.width -= (height + cellStyle.getPaddingImageText()); } } } /** * Gets the text for the cell from the label provider if required. */ public String getCellText(final Column column, final Row<T> row) { if (column == gridModel.getRowNumberColumn()) { return String.valueOf(row.getRowIndex() + 1); } else if (column == gridModel.getGroupSelectorColumn()) { return ""; } else if (row == gridModel.getColumnHeaderRow()) { return column.getCaption(); } else { return grid.getLabelProvider().getText(column, row.getElement()); } } /** * Return the image for the given cell. */ protected Image getCellImage(final Column column, final Row<T> row) { if (row == gridModel.getColumnHeaderRow()) { // Get any image from the provider final Image image = grid.getLabelProvider().getHeaderImage(column); if (image != null) { return image; } // Return a sorted image if sorted. if (column.getSortDirection() != SortDirection.NONE) { if (column.getSortDirection() == SortDirection.ASC){ return getImage("sort_ascending.png"); } else if (column.getSortDirection() == SortDirection.DESC){ return getImage("sort_descending.png"); } } } else if ((column == gridModel.getRowNumberColumn()) || (column == gridModel.getGroupSelectorColumn())) { return null; } else { // Get any image from the provider return grid.getLabelProvider().getImage(column, row.getElement()); } return null; } public Point getContentLocation() { return contentLocation; } public Rectangle getInnerBounds() { return innerBounds; } }
package com.serenegiant.glutils; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; public class TextureWrapper implements Parcelable { public final int texUnit; public final int texId; public final int width; public final int height; public TextureWrapper(final int texUnit, final int texId, final int width, final int height) { this.texUnit = texUnit; this.texId = texId; this.width = width; this.height = height; } protected TextureWrapper(@NonNull final Parcel in) { texUnit = in.readInt(); texId = in.readInt(); width = in.readInt(); height = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel dest, final int flags) { dest.writeInt(texUnit); dest.writeInt(texId); dest.writeInt(width); dest.writeInt(height); } public static final Creator<TextureWrapper> CREATOR = new Creator<TextureWrapper>() { @Override public TextureWrapper createFromParcel(Parcel in) { return new TextureWrapper(in); } @Override public TextureWrapper[] newArray(int size) { return new TextureWrapper[size]; } }; }
package edu.umd.cs.findbugs; import java.io.IOException; import java.io.Serializable; import java.math.BigInteger; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.StringTokenizer; import org.apache.bcel.Constants; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.classfile.Field; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InvokeInstruction; import org.apache.bcel.generic.MethodGen; import org.objectweb.asm.tree.ClassNode; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.JavaClassAndMethod; import edu.umd.cs.findbugs.ba.Location; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.ba.bcp.FieldVariable; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.FieldDescriptor; import edu.umd.cs.findbugs.classfile.MethodDescriptor; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.visitclass.DismantleBytecode; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; import edu.umd.cs.findbugs.xml.XMLAttributeList; import edu.umd.cs.findbugs.xml.XMLOutput; /** * An instance of a bug pattern. * A BugInstance consists of several parts: * <p/> * <ul> * <li> the type, which is a string indicating what kind of bug it is; * used as a key for the FindBugsMessages resource bundle * <li> the priority; how likely this instance is to actually be a bug * <li> a list of <em>annotations</em> * </ul> * <p/> * The annotations describe classes, methods, fields, source locations, * and other relevant context information about the bug instance. * Every BugInstance must have at least one ClassAnnotation, which * describes the class in which the instance was found. This is the * "primary class annotation". * <p/> * <p> BugInstance objects are built up by calling a string of <code>add</code> * methods. (These methods all "return this", so they can be chained). * Some of the add methods are specialized to get information automatically from * a BetterVisitor or DismantleBytecode object. * * @author David Hovemeyer * @see BugAnnotation */ public class BugInstance implements Comparable<BugInstance>, XMLWriteableWithMessages, Serializable, Cloneable { private static final long serialVersionUID = 1L; private String type; private int priority; private ArrayList<BugAnnotation> annotationList; private int cachedHashCode; private @CheckForNull BugDesignation userDesignation; private BugProperty propertyListHead, propertyListTail; private String uniqueId; private String oldInstanceHash; private String instanceHash; private int instanceOccurrenceNum; private int instanceOccurrenceMax; /* * The following fields are used for tracking Bug instances across multiple versions of software. * They are meaningless in a BugCollection for just one version of software. */ private long firstVersion = 0; private long lastVersion = -1; private boolean introducedByChangeOfExistingClass; private boolean removedByChangeOfPersistingClass; /** * This value is used to indicate that the cached hashcode * is invalid, and should be recomputed. */ private static final int INVALID_HASH_CODE = 0; /** * This value is used to indicate whether BugInstances should be reprioritized very low, * when the BugPattern is marked as experimental */ private static boolean adjustExperimental = false; private static Set<String> bugTypes = Collections.synchronizedSet(new HashSet<String>()); /** * Constructor. * * @param type the bug type * @param priority the bug priority */ public BugInstance(String type, int priority) { this.type = type; this.priority = priority; annotationList = new ArrayList<BugAnnotation>(4); cachedHashCode = INVALID_HASH_CODE; if (bugTypes.add(type)) { BugPattern p = I18N.instance().lookupBugPattern(type); if (p == null) { String msg = "Can't find definition of bug type " + type; AnalysisContext.logError(msg, new IllegalArgumentException(msg)); } } if (adjustExperimental && isExperimental()) this.priority = Detector.EXP_PRIORITY; boundPriority(); } private void boundPriority() { priority = boundedPriority(priority); } @Override public Object clone() { BugInstance dup; try { dup = (BugInstance) super.clone(); // Do deep copying of mutable objects for (int i = 0; i < dup.annotationList.size(); ++i) { dup.annotationList.set(i, (BugAnnotation) dup.annotationList.get(i).clone()); } dup.propertyListHead = dup.propertyListTail = null; for (Iterator<BugProperty> i = propertyIterator(); i.hasNext(); ) { dup.addProperty((BugProperty) i.next().clone()); } return dup; } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } /** * Create a new BugInstance. * This is the constructor that should be used by Detectors. * * @param detector the Detector that is reporting the BugInstance * @param type the bug type * @param priority the bug priority */ public BugInstance(Detector detector, String type, int priority) { this(type, priority); if (detector != null) { // Adjust priority if required DetectorFactory factory = DetectorFactoryCollection.instance().getFactoryByClassName(detector.getClass().getName()); if (factory != null) { this.priority += factory.getPriorityAdjustment(); boundPriority(); } } } /** * Create a new BugInstance. * This is the constructor that should be used by Detectors. * * @param detector the Detector2 that is reporting the BugInstance * @param type the bug type * @param priority the bug priority */ public BugInstance(Detector2 detector, String type, int priority) { this(type, priority); if (detector != null) { // Adjust priority if required DetectorFactory factory = DetectorFactoryCollection.instance().getFactoryByClassName(detector.getDetectorClassName()); if (factory != null) { this.priority += factory.getPriorityAdjustment(); boundPriority(); } } } public static void setAdjustExperimental(boolean adjust) { adjustExperimental = adjust; } /** * Get the bug type. */ public String getType() { return type; } /** * Get the BugPattern. */ public BugPattern getBugPattern() { return I18N.instance().lookupBugPattern(getType()); } /** * Get the bug priority. */ public int getPriority() { return priority; } /** * Get a string describing the bug priority and type. * e.g. "High Priority Correctness" * @return a string describing the bug priority and type */ public String getPriorityTypeString() { String priorityString = getPriorityString(); //then get the category and put everything together String categoryString = I18N.instance().getBugCategoryDescription(this.getBugPattern().getCategory()); return priorityString + " Priority " + categoryString; //TODO: internationalize the word "Priority" } public String getPriorityTypeAbbreviation() { String priorityString = getPriorityAbbreviation(); return priorityString + " " + getCategoryAbbrev(); } public String getCategoryAbbrev() { BugPattern bugPattern = getBugPattern(); if (bugPattern == null) return "?"; return bugPattern.getCategoryAbbrev(); } public String getPriorityString() { //first, get the priority int value = this.getPriority(); String priorityString; if (value == Detector.HIGH_PRIORITY) priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_high", "High"); else if (value == Detector.NORMAL_PRIORITY) priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_normal", "Medium"); else if (value == Detector.LOW_PRIORITY) priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_low", "Low"); else if (value == Detector.EXP_PRIORITY) priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_experimental", "Experimental"); else priorityString = edu.umd.cs.findbugs.L10N.getLocalString("sort.priority_ignore", "Ignore"); // This probably shouldn't ever happen, but what the hell, let's be complete return priorityString; } public String getPriorityAbbreviation() { return getPriorityString().substring(0,1); } /** * Set the bug priority. */ public void setPriority(int p) { priority = boundedPriority(p); } private int boundedPriority(int p) { return Math.max(Detector.HIGH_PRIORITY, Math.min(Detector.IGNORE_PRIORITY, p)); } public void raisePriority() { priority = boundedPriority(priority-1); } public void lowerPriority() { priority = boundedPriority(priority+1); } public void lowerPriorityALot() { priority = boundedPriority(priority+2); } /** * Is this bug instance the result of an experimental detector? */ public boolean isExperimental() { BugPattern pattern = I18N.instance().lookupBugPattern(type); return (pattern != null) && pattern.isExperimental(); } /** * Get the primary class annotation, which indicates where the bug occurs. */ public ClassAnnotation getPrimaryClass() { return (ClassAnnotation) findAnnotationOfType(ClassAnnotation.class); } /** * Get the primary method annotation, which indicates where the bug occurs. */ public MethodAnnotation getPrimaryMethod() { return (MethodAnnotation) findAnnotationOfType(MethodAnnotation.class); } /** * Get the primary method annotation, which indicates where the bug occurs. */ public FieldAnnotation getPrimaryField() { return (FieldAnnotation) findAnnotationOfType(FieldAnnotation.class); } public BugInstance lowerPriorityIfDeprecated() { MethodAnnotation m = getPrimaryMethod(); if (m != null && AnalysisContext.currentXFactory().getDeprecated().contains(XFactory.createXMethod(m))) lowerPriority(); FieldAnnotation f = getPrimaryField(); if (f != null && AnalysisContext.currentXFactory().getDeprecated().contains(XFactory.createXField(f))) lowerPriority(); return this; } /** * Find the first BugAnnotation in the list of annotations * that is the same type or a subtype as the given Class parameter. * * @param cls the Class parameter * @return the first matching BugAnnotation of the given type, * or null if there is no such BugAnnotation */ private BugAnnotation findAnnotationOfType(Class<? extends BugAnnotation> cls) { for (Iterator<BugAnnotation> i = annotationIterator(); i.hasNext();) { BugAnnotation annotation = i.next(); if (cls.isAssignableFrom(annotation.getClass())) return annotation; } return null; } public LocalVariableAnnotation getPrimaryLocalVariableAnnotation() { for (BugAnnotation annotation : annotationList) if (annotation instanceof LocalVariableAnnotation) return (LocalVariableAnnotation) annotation; return null; } /** * Get the primary source line annotation. * There is guaranteed to be one (unless some Detector constructed * an invalid BugInstance). * * @return the source line annotation */ public SourceLineAnnotation getPrimarySourceLineAnnotation() { // Highest priority: return the first top level source line annotation for (BugAnnotation annotation : annotationList) { if (annotation instanceof SourceLineAnnotation) return (SourceLineAnnotation) annotation; } // Next: Try primary method, primary field, primary class SourceLineAnnotation srcLine; if ((srcLine = inspectPackageMemberSourceLines(getPrimaryMethod())) != null) return srcLine; if ((srcLine = inspectPackageMemberSourceLines(getPrimaryField())) != null) return srcLine; if ((srcLine = inspectPackageMemberSourceLines(getPrimaryClass())) != null) return srcLine; // Last resort: throw exception throw new IllegalStateException("BugInstance must contain at least one class, method, or field annotation"); } public String getInstanceKey() { StringBuffer buf = new StringBuffer(type); for (BugAnnotation annotation : annotationList) { if (annotation instanceof SourceLineAnnotation || annotation instanceof MethodAnnotation && !annotation.isSignificant()) { // do nothing } else { buf.append(":"); buf.append(annotation.format("hash", null)); } } return buf.toString(); } /** * If given PackageMemberAnnotation is non-null, return its * SourceLineAnnotation. * * @param packageMember * a PackageMemberAnnotation * @return the PackageMemberAnnotation's SourceLineAnnotation, or null if * there is no SourceLineAnnotation */ private SourceLineAnnotation inspectPackageMemberSourceLines(PackageMemberAnnotation packageMember) { return (packageMember != null) ? packageMember.getSourceLines() : null; } /** * Get an Iterator over all bug annotations. */ public Iterator<BugAnnotation> annotationIterator() { return annotationList.iterator(); } /** * Get the abbreviation of this bug instance's BugPattern. * This is the same abbreviation used by the BugCode which * the BugPattern is a particular species of. */ public String getAbbrev() { BugPattern pattern = I18N.instance().lookupBugPattern(getType()); return pattern != null ? pattern.getAbbrev() : "<unknown bug pattern>"; } /** set the user designation object. This will clobber any * existing annotationText (or any other BugDesignation field). */ public void setUserDesignation(BugDesignation bd) { userDesignation = bd; } /** return the user designation object, which may be null. * * A previous calls to getSafeUserDesignation(), setAnnotationText(), * or setUserDesignation() will ensure it will be non-null * [barring an intervening setUserDesignation(null)]. * @see #getNonnullUserDesignation() */ @Nullable public BugDesignation getUserDesignation() { return userDesignation; } /** return the user designation object, creating one if * necessary. So calling * <code>getSafeUserDesignation().setDesignation("HARMLESS")</code> * will always work without the possibility of a NullPointerException. * @see #getUserDesignation() */ @NonNull public BugDesignation getNonnullUserDesignation() { if (userDesignation == null) userDesignation = new BugDesignation(); return userDesignation; } /** Get the user designation key. * E.g., "MOSTLY_HARMLESS", "CRITICAL", "NOT_A_BUG", etc. * * If the user designation object is null,returns UNCLASSIFIED. * * To set the user designation key, call * <code>getSafeUserDesignation().setDesignation("HARMLESS")</code>. * * @see I18N#getUserDesignation(String key) * @return the user designation key */ @NonNull public String getUserDesignationKey() { BugDesignation userDesignation = this.userDesignation; if (userDesignation == null) return BugDesignation.UNCLASSIFIED; return userDesignation.getDesignationKey(); } /** * Set the user annotation text. * * @param annotationText the user annotation text */ public void setAnnotationText(String annotationText) { getNonnullUserDesignation().setAnnotationText(annotationText); } /** * Get the user annotation text. * * @return the user annotation text */ @NonNull public String getAnnotationText() { BugDesignation userDesignation = this.userDesignation; if (userDesignation == null) return ""; String s = userDesignation.getAnnotationText(); if (s == null) return ""; return s; } /** * Determine whether or not the annotation text contains * the given word. * * @param word the word * @return true if the annotation text contains the word, false otherwise */ public boolean annotationTextContainsWord(String word) { return getTextAnnotationWords().contains(word); } /** * Get set of words in the text annotation. */ public Set<String> getTextAnnotationWords() { HashSet<String> result = new HashSet<String>(); StringTokenizer tok = new StringTokenizer(getAnnotationText(), " \t\r\n\f.,:;-"); while (tok.hasMoreTokens()) { result.add(tok.nextToken()); } return result; } /** * Get the BugInstance's unique id. * * @return the unique id, or null if no unique id has been assigned * * Deprecated, since it isn't persistent */ @Deprecated public String getUniqueId() { return uniqueId; } /** * Set the unique id of the BugInstance. * * @param uniqueId the unique id * * * Deprecated, since it isn't persistent */ @Deprecated void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } private class BugPropertyIterator implements Iterator<BugProperty> { private BugProperty prev, cur; private boolean removed; /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return findNext() != null; } /* (non-Javadoc) * @see java.util.Iterator#next() */ public BugProperty next() { BugProperty next = findNext(); if (next == null) throw new NoSuchElementException(); prev = cur; cur = next; removed = false; return cur; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { if (cur == null || removed) throw new IllegalStateException(); if (prev == null) { propertyListHead = cur.getNext(); } else { prev.setNext(cur.getNext()); } if (cur == propertyListTail) { propertyListTail = prev; } removed = true; } private BugProperty findNext() { return cur == null ? propertyListHead : cur.getNext(); } } /** * Get value of given property. * * @param name name of the property to get * @return the value of the named property, or null if * the property has not been set */ public String getProperty(String name) { BugProperty prop = lookupProperty(name); return prop != null ? prop.getValue() : null; } /** * Get value of given property, returning given default * value if the property has not been set. * * @param name name of the property to get * @param defaultValue default value to return if propery is not set * @return the value of the named property, or the default * value if the property has not been set */ public String getProperty(String name, String defaultValue) { String value = getProperty(name); return value != null ? value : defaultValue; } /** * Get an Iterator over the properties defined in this BugInstance. * * @return Iterator over properties */ public Iterator<BugProperty> propertyIterator() { return new BugPropertyIterator(); } /** * Set value of given property. * * @param name name of the property to set * @param value the value of the property * @return this object, so calls can be chained */ public BugInstance setProperty(String name, String value) { BugProperty prop = lookupProperty(name); if (prop != null) { prop.setValue(value); } else { prop = new BugProperty(name, value); addProperty(prop); } return this; } /** * Look up a property by name. * * @param name name of the property to look for * @return the BugProperty with the given name, * or null if the property has not been set */ public BugProperty lookupProperty(String name) { BugProperty prop = propertyListHead; while (prop != null) { if (prop.getName().equals(name)) break; prop = prop.getNext(); } return prop; } /** * Delete property with given name. * * @param name name of the property to delete * @return true if a property with that name was deleted, * or false if there is no such property */ public boolean deleteProperty(String name) { BugProperty prev = null; BugProperty prop = propertyListHead; while (prop != null) { if (prop.getName().equals(name)) break; prev = prop; prop = prop.getNext(); } if (prop != null) { if (prev != null) { // Deleted node in interior or at tail of list prev.setNext(prop.getNext()); } else { // Deleted node at head of list propertyListHead = prop.getNext(); } if (prop.getNext() == null) { // Deleted node at end of list propertyListTail = prev; } return true; } else { // No such property return false; } } private void addProperty(BugProperty prop) { if (propertyListTail != null) { propertyListTail.setNext(prop); propertyListTail = prop; } else { propertyListHead = propertyListTail = prop; } prop.setNext(null); } /** * Add a Collection of BugAnnotations. * * @param annotationCollection Collection of BugAnnotations */ public BugInstance addAnnotations(Collection<? extends BugAnnotation> annotationCollection) { for (BugAnnotation annotation : annotationCollection) { add(annotation); } return this; } public BugInstance addClassAndMethod(MethodDescriptor methodDescriptor) { addClass(methodDescriptor.getClassName()); add(MethodAnnotation.fromMethodDescriptor(methodDescriptor)); return this; } /** * Add a class annotation and a method annotation for the class and method * which the given visitor is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addClassAndMethod(PreorderVisitor visitor) { addClass(visitor); addMethod(visitor); return this; } /** * Add class and method annotations for given method. * * @param methodAnnotation the method * @return this object */ public BugInstance addClassAndMethod(MethodAnnotation methodAnnotation) { addClass(methodAnnotation.getClassName()); addMethod(methodAnnotation); return this; } /** * Add class and method annotations for given method. * * @param methodGen the method * @param sourceFile source file the method is defined in * @return this object */ public BugInstance addClassAndMethod(MethodGen methodGen, String sourceFile) { addClass(methodGen.getClassName()); addMethod(methodGen, sourceFile); return this; } /** * Add class and method annotations for given class and method. * * @param javaClass the class * @param method the method * @return this object */ public BugInstance addClassAndMethod(JavaClass javaClass, Method method) { addClass(javaClass.getClassName()); addMethod(javaClass, method); return this; } /** * Add a class annotation. If this is the first class annotation added, * it becomes the primary class annotation. * * @param className the name of the class * @param sourceFileName the source file of the class * @return this object * @deprecated use addClass(String) instead */ public BugInstance addClass(String className, String sourceFileName) { ClassAnnotation classAnnotation = new ClassAnnotation(className); add(classAnnotation); return this; } /** * Add a class annotation. If this is the first class annotation added, * it becomes the primary class annotation. * * @param className the name of the class * @return this object */ public BugInstance addClass(String className) { className = ClassName.toDottedClassName(className); ClassAnnotation classAnnotation = new ClassAnnotation(className); add(classAnnotation); return this; } /** * Add a class annotation for the classNode. * * @param classNode the ASM visitor * @return this object */ public BugInstance addClass(ClassNode classNode) { ClassAnnotation classAnnotation = new ClassAnnotation(classNode.name); add(classAnnotation); return this; } /** * Add a class annotation. If this is the first class annotation added, * it becomes the primary class annotation. * * @param classDescriptor the class to add * @return this object */ public BugInstance addClass(ClassDescriptor classDescriptor) { add(ClassAnnotation.fromClassDescriptor(classDescriptor)); return this; } /** * Add a class annotation. If this is the first class annotation added, * it becomes the primary class annotation. * * @param jclass the JavaClass object for the class * @return this object */ public BugInstance addClass(JavaClass jclass) { addClass(jclass.getClassName()); return this; } /** * Add a class annotation for the class that the visitor is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addClass(PreorderVisitor visitor) { String className = visitor.getDottedClassName(); addClass(className); return this; } /** * Add a class annotation for the superclass of the class the visitor * is currently visiting. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addSuperclass(PreorderVisitor visitor) { String className = visitor.getSuperclassName(); addClass(className); return this; } public BugInstance addType(String typeDescriptor) { TypeAnnotation typeAnnotation = new TypeAnnotation(typeDescriptor); add(typeAnnotation); return this; } public BugInstance addFoundAndExpectedType(String foundType, String expectedType) { add( new TypeAnnotation(foundType)).describe(TypeAnnotation.FOUND_ROLE); add( new TypeAnnotation(expectedType)).describe(TypeAnnotation.EXPECTED_ROLE); return this; } public BugInstance addTypeOfNamedClass(String typeName) { TypeAnnotation typeAnnotation = new TypeAnnotation("L" + typeName.replace('.','/')+";"); add(typeAnnotation); return this; } /** * Add a field annotation. * * @param className name of the class containing the field * @param fieldName the name of the field * @param fieldSig type signature of the field * @param isStatic whether or not the field is static * @return this object */ public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) { addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic)); return this; } /** * Add a field annotation. * * @param className name of the class containing the field * @param fieldName the name of the field * @param fieldSig type signature of the field * @param isStatic whether or not the field is static * @return this object */ public BugInstance addField(String className, String fieldName, String fieldSig, int accessFlags) { addField(new FieldAnnotation(className, fieldName, fieldSig, accessFlags)); return this; } public BugInstance addField(PreorderVisitor visitor) { FieldAnnotation fieldAnnotation = FieldAnnotation.fromVisitedField(visitor); return addField(fieldAnnotation); } /** * Add a field annotation * * @param fieldAnnotation the field annotation * @return this object */ public BugInstance addField(FieldAnnotation fieldAnnotation) { add(fieldAnnotation); return this; } /** * Add a field annotation for a FieldVariable matched in a ByteCodePattern. * * @param field the FieldVariable * @return this object */ public BugInstance addField(FieldVariable field) { return addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic()); } /** * Add a field annotation for an XField. * * @param xfield the XField * @return this object */ public BugInstance addOptionalField(@CheckForNull XField xfield) { if (xfield == null) return this; return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic()); } /** * Add a field annotation for an XField. * * @param xfield the XField * @return this object */ public BugInstance addField(XField xfield) { return addField(xfield.getClassName(), xfield.getName(), xfield.getSignature(), xfield.isStatic()); } /** * Add a field annotation for a FieldDescriptor. * * @param fieldDescriptor the FieldDescriptor * @return this object */ public BugInstance addField(FieldDescriptor fieldDescriptor) { FieldAnnotation fieldAnnotation = FieldAnnotation.fromFieldDescriptor(fieldDescriptor); add(fieldAnnotation); return this; } /** * Add a field annotation for the field which has just been accessed * by the method currently being visited by given visitor. * Assumes that a getfield/putfield or getstatic/putstatic * has just been seen. * * @param visitor the DismantleBytecode object * @return this object */ public BugInstance addReferencedField(DismantleBytecode visitor) { FieldAnnotation f = FieldAnnotation.fromReferencedField(visitor); addField(f); return this; } /** * Add a field annotation for the field referenced by the FieldAnnotation parameter */ public BugInstance addReferencedField(FieldAnnotation fa) { addField(fa); return this; } /** * Add a field annotation for the field which is being visited by * given visitor. * * @param visitor the visitor * @return this object */ public BugInstance addVisitedField(PreorderVisitor visitor) { FieldAnnotation f = FieldAnnotation.fromVisitedField(visitor); addField(f); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * * @param className name of the class containing the method * @param methodName name of the method * @param methodSig type signature of the method * @param isStatic true if the method is static, false otherwise * @return this object */ public BugInstance addMethod(String className, String methodName, String methodSig, boolean isStatic) { addMethod(MethodAnnotation.fromForeignMethod(className, methodName, methodSig, isStatic)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * * @param className name of the class containing the method * @param methodName name of the method * @param methodSig type signature of the method * @param accessFlags accessFlags for the method * @return this object */ public BugInstance addMethod(String className, String methodName, String methodSig, int accessFlags) { addMethod(MethodAnnotation.fromForeignMethod(className, methodName, methodSig, accessFlags)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param methodGen the MethodGen object for the method * @param sourceFile source file method is defined in * @return this object */ public BugInstance addMethod(MethodGen methodGen, String sourceFile) { String className = methodGen.getClassName(); MethodAnnotation methodAnnotation = new MethodAnnotation(className, methodGen.getName(), methodGen.getSignature(), methodGen.isStatic()); addMethod(methodAnnotation); addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(methodGen, sourceFile)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param javaClass the class the method is defined in * @param method the method * @return this object */ public BugInstance addMethod(JavaClass javaClass, Method method) { MethodAnnotation methodAnnotation = new MethodAnnotation(javaClass.getClassName(), method.getName(), method.getSignature(), method.isStatic()); SourceLineAnnotation methodSourceLines = SourceLineAnnotation.forEntireMethod( javaClass, method); methodAnnotation.setSourceLines(methodSourceLines); addMethod(methodAnnotation); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param classAndMethod JavaClassAndMethod identifying the method to add * @return this object */ public BugInstance addMethod(JavaClassAndMethod classAndMethod) { return addMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod()); } /** * Add a method annotation for the method which the given visitor is currently visiting. * If the method has source line information, then a SourceLineAnnotation * is added to the method. * * @param visitor the BetterVisitor * @return this object */ public BugInstance addMethod(PreorderVisitor visitor) { MethodAnnotation methodAnnotation = MethodAnnotation.fromVisitedMethod(visitor); addMethod(methodAnnotation); addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(visitor)); return this; } /** * Add a method annotation for the method which has been called * by the method currently being visited by given visitor. * Assumes that the visitor has just looked at an invoke instruction * of some kind. * * @param visitor the DismantleBytecode object * @return this object */ public BugInstance addCalledMethod(DismantleBytecode visitor) { return addMethod(MethodAnnotation.fromCalledMethod(visitor)).describe("METHOD_CALLED"); } /** * Add a method annotation. * * @param className name of class containing called method * @param methodName name of called method * @param methodSig signature of called method * @param isStatic true if called method is static, false if not * @return this object */ public BugInstance addCalledMethod(String className, String methodName, String methodSig, boolean isStatic) { return addMethod(MethodAnnotation.fromCalledMethod(className, methodName, methodSig, isStatic)).describe("METHOD_CALLED"); } /** * Add a method annotation for the method which is called by given * instruction. * * @param methodGen the method containing the call * @param inv the InvokeInstruction * @return this object */ public BugInstance addCalledMethod(MethodGen methodGen, InvokeInstruction inv) { ConstantPoolGen cpg = methodGen.getConstantPool(); String className = inv.getClassName(cpg); String methodName = inv.getMethodName(cpg); String methodSig = inv.getSignature(cpg); addMethod(className, methodName, methodSig, inv.getOpcode() == Constants.INVOKESTATIC); describe("METHOD_CALLED"); return this; } /** * Add a MethodAnnotation from an XMethod. * * @param xmethod the XMethod * @return this object */ public BugInstance addMethod(XMethod xmethod) { addMethod(MethodAnnotation.fromXMethod(xmethod)); return this; } /** * Add a method annotation. If this is the first method annotation added, * it becomes the primary method annotation. * * @param methodAnnotation the method annotation * @return this object */ public BugInstance addMethod(MethodAnnotation methodAnnotation) { add(methodAnnotation); return this; } /** * Add an integer annotation. * * @param value the integer value * @return this object */ public BugInstance addInt(int value) { add(new IntAnnotation(value)); return this; } /** * Add a String annotation. * * @param value the String value * @return this object */ public BugInstance addString(String value) { add(new StringAnnotation(value)); return this; } /** * Add a source line annotation. * * @param sourceLine the source line annotation * @return this object */ public BugInstance addSourceLine(SourceLineAnnotation sourceLine) { add(sourceLine); return this; } /** * Add a source line annotation for instruction whose PC is given * in the method that the given visitor is currently visiting. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param visitor a BytecodeScanningDetector that is currently visiting the method * @param pc bytecode offset of the instruction * @return this object */ public BugInstance addSourceLine(BytecodeScanningDetector visitor, int pc) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor.getClassContext(), visitor, pc); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for instruction whose PC is given * in the method that the given visitor is currently visiting. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param visitor a PreorderVisitor that is currently visiting the method * @param pc bytecode offset of the instruction * @return this object */ public BugInstance addSourceLine(ClassContext classContext, PreorderVisitor visitor, int pc) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, visitor, pc); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for the given instruction in the given method. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param methodGen the method being visited * @param sourceFile source file the method is defined in * @param handle the InstructionHandle containing the visited instruction * @return this object */ public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, @NonNull InstructionHandle handle) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, methodGen, sourceFile, handle); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing a range of instructions. * * @param classContext the ClassContext * @param methodGen the method * @param sourceFile source file the method is defined in * @param start the start instruction in the range * @param end the end instruction in the range (inclusive) * @return this object */ public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start, InstructionHandle end) { // Make sure start and end are really in the right order. if (start.getPosition() > end.getPosition()) { InstructionHandle tmp = start; start = end; end = tmp; } SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen, sourceFile, start, end); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add source line annotation for given Location in a method. * * @param classContext the ClassContext * @param method the Method * @param location the Location in the method * @return this BugInstance */ public BugInstance addSourceLine(ClassContext classContext, Method method, Location location) { return addSourceLine(classContext, method, location.getHandle()); } /** * Add source line annotation for given Location in a method. * * @param classContext the ClassContext * @param method the Method * @param location the Location in the method * @return this BugInstance */ public BugInstance addSourceLine(ClassContext classContext, Method method, InstructionHandle handle) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(classContext, method, handle.getPosition()); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return this object */ public BugInstance addSourceLineRange(BytecodeScanningDetector visitor, int startPC, int endPC) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(visitor.getClassContext(), visitor, startPC, endPC); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation describing the * source line numbers for a range of instructions in the method being * visited by the given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param classContext the ClassContext * @param visitor a BetterVisitor which is visiting the method * @param startPC the bytecode offset of the start instruction in the range * @param endPC the bytecode offset of the end instruction in the range * @return this object */ public BugInstance addSourceLineRange(ClassContext classContext, PreorderVisitor visitor, int startPC, int endPC) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, visitor, startPC, endPC); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a source line annotation for instruction currently being visited * by given visitor. * Note that if the method does not have line number information, then * no source line annotation will be added. * * @param visitor a BytecodeScanningDetector visitor that is currently visiting the instruction * @return this object */ public BugInstance addSourceLine(BytecodeScanningDetector visitor) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(visitor); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Add a non-specific source line annotation. * This will result in the entire source file being displayed. * * @param className the class name * @param sourceFile the source file name * @return this object */ public BugInstance addUnknownSourceLine(String className, String sourceFile) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.createUnknown(className, sourceFile); if (sourceLineAnnotation != null) add(sourceLineAnnotation); return this; } /** * Format a string describing this bug instance. * * @return the description */ public String getMessageWithoutPrefix() { BugPattern bugPattern = I18N.instance().lookupBugPattern(type); String pattern, shortPattern; if (bugPattern == null) shortPattern = pattern = "Error: missing bug pattern for key " + type; else { pattern = bugPattern.getLongDescription(); shortPattern = bugPattern.getShortDescription(); } try { FindBugsMessageFormat format = new FindBugsMessageFormat(pattern); return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass()); } catch (RuntimeException e) { AnalysisContext.logError("Error generating bug msg ", e); return shortPattern + " [Error generating customized description]"; } } public String getAbridgedMessage() { BugPattern bugPattern = I18N.instance().lookupBugPattern(type); String pattern, shortPattern; if (bugPattern == null) shortPattern = pattern = "Error: missing bug pattern for key " + type; else { pattern = bugPattern.getLongDescription().replaceAll(" in \\{1\\}", ""); shortPattern = bugPattern.getShortDescription(); } try { FindBugsMessageFormat format = new FindBugsMessageFormat(pattern); return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass()); } catch (RuntimeException e) { AnalysisContext.logError("Error generating bug msg ", e); return shortPattern + " [Error generating customized description]"; } } /** * Format a string describing this bug instance. * * @return the description */ public String getMessage() { String pattern = I18N.instance().getMessage(type); FindBugsMessageFormat format = new FindBugsMessageFormat(pattern); try { return format.format(annotationList.toArray(new BugAnnotation[annotationList.size()]), getPrimaryClass()); } catch (RuntimeException e) { AnalysisContext.logError("Error generating bug msg ", e); BugPattern bugPattern = I18N.instance().lookupBugPattern(type); if (bugPattern == null) return "Error: missing bug pattern for key " + type; return bugPattern.getShortDescription() + " [Error generating customized description]"; } } /** * Format a string describing this bug pattern, with the priority and type at the beginning. * e.g. "(High Priority Correctness) Guaranteed null pointer dereference..." */ public String getMessageWithPriorityType() { return "(" + this.getPriorityTypeString() + ") " + this.getMessage(); } public String getMessageWithPriorityTypeAbbreviation() { return this.getPriorityTypeAbbreviation() + " "+ this.getMessage(); } /** * Add a description to the most recently added bug annotation. * * @param description the description to add * @return this object */ public BugInstance describe(String description) { annotationList.get(annotationList.size() - 1).setDescription(description); return this; } /** * Convert to String. * This method returns the "short" message describing the bug, * as opposed to the longer format returned by getMessage(). * The short format is appropriate for the tree view in a GUI, * where the annotations are listed separately as part of the overall * bug instance. */ @Override public String toString() { return I18N.instance().getShortMessage(type); } public void writeXML(XMLOutput xmlOutput) throws IOException { writeXML(xmlOutput, false); } public void writeXML(XMLOutput xmlOutput, boolean addMessages) throws IOException { XMLAttributeList attributeList = new XMLAttributeList() .addAttribute("type", type) .addAttribute("priority", String.valueOf(priority)); BugPattern pattern = getBugPattern(); if (pattern != null) { // The bug abbreviation and pattern category are // emitted into the XML for informational purposes only. // (The information is redundant, but might be useful // for processing tools that want to make sense of // bug instances without looking at the plugin descriptor.) attributeList.addAttribute("abbrev", pattern.getAbbrev()); attributeList.addAttribute("category", pattern.getCategory()); } if (addMessages) { // Add a uid attribute, if we have a unique id. if (getUniqueId() != null) { attributeList.addAttribute("uid", getUniqueId()); } attributeList.addAttribute("instanceHash", getInstanceHash()); attributeList.addAttribute("instanceOccurrenceNum", Integer.toString(getInstanceOccurrenceNum())); attributeList.addAttribute("instanceOccurrenceMax", Integer.toString(getInstanceOccurrenceMax())); } if (firstVersion > 0) attributeList.addAttribute("first", Long.toString(firstVersion)); if (lastVersion >= 0) attributeList.addAttribute("last", Long.toString(lastVersion)); if (introducedByChangeOfExistingClass) attributeList.addAttribute("introducedByChange", "true"); if (removedByChangeOfPersistingClass) attributeList.addAttribute("removedByChange", "true"); xmlOutput.openTag(ELEMENT_NAME, attributeList); if (userDesignation != null) { userDesignation.writeXML(xmlOutput); } if (addMessages) { BugPattern bugPattern = getBugPattern(); xmlOutput.openTag("ShortMessage"); xmlOutput.writeText(bugPattern != null ? bugPattern.getShortDescription() : this.toString()); xmlOutput.closeTag("ShortMessage"); xmlOutput.openTag("LongMessage"); if (FindBugsDisplayFeatures.isAbridgedMessages()) xmlOutput.writeText(this.getAbridgedMessage()); else xmlOutput.writeText(this.getMessageWithoutPrefix()); xmlOutput.closeTag("LongMessage"); } boolean foundSourceAnnotation = false; for (BugAnnotation annotation : annotationList) { if (annotation instanceof SourceLineAnnotation) foundSourceAnnotation = true; annotation.writeXML(xmlOutput, addMessages); } if (!foundSourceAnnotation && addMessages) { SourceLineAnnotation synth = getPrimarySourceLineAnnotation(); if (synth != null) { synth.setSynthetic(true); synth.writeXML(xmlOutput, addMessages); } } if (propertyListHead != null) { BugProperty prop = propertyListHead; while (prop != null) { prop.writeXML(xmlOutput); prop = prop.getNext(); } } xmlOutput.closeTag(ELEMENT_NAME); } private static final String ELEMENT_NAME = "BugInstance"; private static final String USER_ANNOTATION_ELEMENT_NAME = "UserAnnotation"; public BugInstance addOptionalAnnotation(@CheckForNull BugAnnotation annotation) { if (annotation == null) return this; return add(annotation); } public BugInstance add(BugAnnotation annotation) { if (annotation == null) throw new IllegalStateException("Missing BugAnnotation!"); // Add to list annotationList.add(annotation); // This object is being modified, so the cached hashcode // must be invalidated cachedHashCode = INVALID_HASH_CODE; return this; } private void addSourceLinesForMethod(MethodAnnotation methodAnnotation, SourceLineAnnotation sourceLineAnnotation) { if (sourceLineAnnotation != null) { // Note: we don't add the source line annotation directly to // the bug instance. Instead, we stash it in the MethodAnnotation. // It is much more useful there, and it would just be distracting // if it were displayed in the UI, since it would compete for attention // with the actual bug location source line annotation (which is much // more important and interesting). methodAnnotation.setSourceLines(sourceLineAnnotation); } } @Override public int hashCode() { if (cachedHashCode == INVALID_HASH_CODE) { int hashcode = type.hashCode() + priority; Iterator<BugAnnotation> i = annotationIterator(); while (i.hasNext()) hashcode += i.next().hashCode(); if (hashcode == INVALID_HASH_CODE) hashcode = INVALID_HASH_CODE+1; cachedHashCode = hashcode; } return cachedHashCode; } @Override public boolean equals(Object o) { if (!(o instanceof BugInstance)) return false; BugInstance other = (BugInstance) o; if (!type.equals(other.type) || priority != other.priority) return false; if (annotationList.size() != other.annotationList.size()) return false; int numAnnotations = annotationList.size(); for (int i = 0; i < numAnnotations; ++i) { BugAnnotation lhs = annotationList.get(i); BugAnnotation rhs = other.annotationList.get(i); if (!lhs.equals(rhs)) return false; } return true; } public int compareTo(BugInstance other) { int cmp; cmp = type.compareTo(other.type); if (cmp != 0) return cmp; cmp = priority - other.priority; if (cmp != 0) return cmp; // Compare BugAnnotations lexicographically int pfxLen = Math.min(annotationList.size(), other.annotationList.size()); for (int i = 0; i < pfxLen; ++i) { BugAnnotation lhs = annotationList.get(i); BugAnnotation rhs = other.annotationList.get(i); cmp = lhs.compareTo(rhs); if (cmp != 0) return cmp; } // All elements in prefix were the same, // so use number of elements to decide return annotationList.size() - other.annotationList.size(); } /** * @param firstVersion The firstVersion to set. */ public void setFirstVersion(long firstVersion) { this.firstVersion = firstVersion; if (lastVersion >= 0 && firstVersion > lastVersion) throw new IllegalArgumentException( firstVersion + ".." + lastVersion); } /** * @return Returns the firstVersion. */ public long getFirstVersion() { return firstVersion; } /** * @param lastVersion The lastVersion to set. */ public void setLastVersion(long lastVersion) { if (lastVersion >= 0 && firstVersion > lastVersion) throw new IllegalArgumentException( firstVersion + ".." + lastVersion); this.lastVersion = lastVersion; } /** * @return Returns the lastVersion. */ public long getLastVersion() { return lastVersion; } /** * @param introducedByChangeOfExistingClass The introducedByChangeOfExistingClass to set. */ public void setIntroducedByChangeOfExistingClass(boolean introducedByChangeOfExistingClass) { this.introducedByChangeOfExistingClass = introducedByChangeOfExistingClass; } /** * @return Returns the introducedByChangeOfExistingClass. */ public boolean isIntroducedByChangeOfExistingClass() { return introducedByChangeOfExistingClass; } /** * @param removedByChangeOfPersistingClass The removedByChangeOfPersistingClass to set. */ public void setRemovedByChangeOfPersistingClass(boolean removedByChangeOfPersistingClass) { this.removedByChangeOfPersistingClass = removedByChangeOfPersistingClass; } /** * @return Returns the removedByChangeOfPersistingClass. */ public boolean isRemovedByChangeOfPersistingClass() { return removedByChangeOfPersistingClass; } /** * @param instanceHash The instanceHash to set. */ public void setInstanceHash(String instanceHash) { this.instanceHash = instanceHash; } /** * @param oldInstanceHash The oldInstanceHash to set. */ public void setOldInstanceHash(String oldInstanceHash) { this.oldInstanceHash = oldInstanceHash; } private static final boolean DONT_HASH = SystemProperties.getBoolean("findbugs.dontHash"); /** * @return Returns the instanceHash. */ public String getInstanceHash() { if (instanceHash != null) return instanceHash; MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); } catch (Exception e2) { // OK, we won't digest } instanceHash = getInstanceKey(); if (digest != null && !DONT_HASH) { byte [] data = digest.digest(instanceHash.getBytes()); String tmp = new BigInteger(1,data).toString(16); instanceHash = tmp; } return instanceHash; } public boolean isInstanceHashConsistent() { return oldInstanceHash == null || instanceHash.equals(oldInstanceHash); } /** * @param instanceOccurrenceNum The instanceOccurrenceNum to set. */ public void setInstanceOccurrenceNum(int instanceOccurrenceNum) { this.instanceOccurrenceNum = instanceOccurrenceNum; } /** * @return Returns the instanceOccurrenceNum. */ public int getInstanceOccurrenceNum() { return instanceOccurrenceNum; } /** * @param instanceOccurrenceMax The instanceOccurrenceMax to set. */ public void setInstanceOccurrenceMax(int instanceOccurrenceMax) { this.instanceOccurrenceMax = instanceOccurrenceMax; } /** * @return Returns the instanceOccurrenceMax. */ public int getInstanceOccurrenceMax() { return instanceOccurrenceMax; } } // vim:ts=4
package org.xdi.oxauth.model.common; import java.util.Arrays; import java.util.List; import org.gluu.site.ldap.persistence.annotation.LdapEntry; import org.gluu.site.ldap.persistence.annotation.LdapObjectClass; @LdapEntry @LdapObjectClass(values = { "top", "gluuPerson" }) public class User extends SimpleUser { private static final long serialVersionUID = 6634191420188575733L; public void setAttribute(String attributeName, String attributeValue) { CustomAttribute attribute = new CustomAttribute(attributeName, attributeValue); getCustomAttributes().remove(attribute); getCustomAttributes().add(attribute); } public void setAttribute(String attributeName, String[] attributeValues) { CustomAttribute attribute = new CustomAttribute(attributeName, Arrays.asList(attributeValues)); getCustomAttributes().remove(attribute); getCustomAttributes().add(attribute); } public void setAttribute(String attributeName, List<String> attributeValues) { CustomAttribute attribute = new CustomAttribute(attributeName, attributeValues); getCustomAttributes().remove(attribute); getCustomAttributes().add(attribute); } }
// of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. import java.io.DataInput; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Writable; import org.apache.hadoop.mapred.FileAlreadyExistsException; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import hadooptrunk.InputSampler; import hadooptrunk.MultipleOutputs; import hadooptrunk.TotalOrderPartitioner; import fi.tkk.ics.hadoop.bam.BAMInputFormat; import fi.tkk.ics.hadoop.bam.BAMRecordReader; import fi.tkk.ics.hadoop.bam.custom.samtools.BlockCompressedOutputStream; import fi.tkk.ics.hadoop.bam.custom.samtools.SAMRecord; public final class Summarize extends Configured implements Tool { public static void main(String[] args) throws Exception { System.exit(ToolRunner.run(new Configuration(), new Summarize(), args)); } private final List<Job> jobs = new ArrayList<Job>(); @Override public int run(String[] args) throws ClassNotFoundException, IOException, InterruptedException { if (args.length < 3) { System.err.println( "Usage: Summarize <output directory> <levels> "+ "file [file...]\n\n"+ "Levels should be a comma-separated list of positive integers. "+ "For each level,\noutputs a summary file describing the average "+ "number of alignments at various\npositions in the file. The "+ "level is the number of alignments that are\nsummarized into "+ "one."); return 2; } FileSystem fs = FileSystem.get(getConf()); Path outputDir = new Path(args[0]); if (fs.exists(outputDir) && !fs.getFileStatus(outputDir).isDir()) { System.err.printf( "ERROR: specified output directory '%s' is not a directory!\n", outputDir); return 2; } String[] levels = args[1].split(","); for (String l : levels) { try { int lvl = Integer.parseInt(l); if (lvl > 0) continue; System.err.printf( "ERROR: specified summary level '%d' is not positive!\n", lvl); } catch (NumberFormatException e) { System.err.printf( "ERROR: specified summary level '%s' is not an integer!\n", l); } return 2; } List<Path> files = new ArrayList<Path>(args.length - 2); for (String file : Arrays.asList(args).subList(2, args.length)) files.add(new Path(file)); if (new HashSet<Path>(files).size() < files.size()) { System.err.println("ERROR: duplicate file names specified!"); return 2; } for (Path file : files) if (!fs.isFile(file)) { System.err.printf("ERROR: file '%s' is not a file!\n", file); return 2; } for (Path file : files) submitJob(file, outputDir, levels); int ret = 0; for (Job job : jobs) if (!job.waitForCompletion(true)) ret = 1; return ret; } private void submitJob( Path inputFile, Path outputDir, String[] summaryLvls) throws ClassNotFoundException, IOException, InterruptedException { Configuration conf = new Configuration(getConf()); // Used by SummarizeOutputFormat to construct the output filename conf.set(SummarizeOutputFormat.INPUT_FILENAME_PROP, inputFile.getName()); conf.setStrings(SummarizeReducer.SUMMARY_LEVELS_PROP, summaryLvls); setSamplingConf(inputFile, conf); // As far as I can tell there's no non-deprecated way of getting this // info. int maxReduceTasks = new JobClient(new JobConf(conf)).getClusterStatus() .getMaxReduceTasks(); conf.setInt("mapred.reduce.tasks", Math.max(1, maxReduceTasks * 9 / 10)); Job job = new Job(conf); job.setJarByClass (Summarize.class); job.setMapperClass (Mapper.class); job.setReducerClass(SummarizeReducer.class); job.setMapOutputKeyClass (LongWritable.class); job.setMapOutputValueClass(Range.class); job.setOutputKeyClass (NullWritable.class); job.setOutputValueClass (RangeCount.class); job.setInputFormatClass (SummarizeInputFormat.class); job.setOutputFormatClass(SummarizeOutputFormat.class); FileInputFormat .setInputPaths(job, inputFile); FileOutputFormat.setOutputPath(job, outputDir); job.setPartitionerClass(TotalOrderPartitioner.class); sample(inputFile, job); for (String s : summaryLvls) MultipleOutputs.addNamedOutput( job, "summary" + s, SummarizeOutputFormat.class, NullWritable.class, Range.class); job.submit(); jobs.add(job); } private void setSamplingConf(Path inputFile, Configuration conf) throws IOException { Path inputDir = inputFile.getParent(); inputDir = inputDir.makeQualified(inputDir.getFileSystem(conf)); String name = inputFile.getName(); Path partition = new Path(inputDir, "_partitioning" + name); TotalOrderPartitioner.setPartitionFile(conf, partition); try { URI partitionURI = new URI( partition.toString() + "#_partitioning" + name); DistributedCache.addCacheFile(partitionURI, conf); DistributedCache.createSymlink(conf); } catch (URISyntaxException e) { assert false; } } private void sample(Path inputFile, Job job) throws ClassNotFoundException, IOException, InterruptedException { InputSampler.Sampler<LongWritable,Range> sampler = new InputSampler.IntervalSampler<LongWritable,Range>(0.01, 100); InputSampler.<LongWritable,Range>writePartitionFile(job, sampler); } } final class SummarizeReducer extends Reducer<LongWritable,Range, NullWritable,RangeCount> { public static final String SUMMARY_LEVELS_PROP = "summarize.summary.levels"; private MultipleOutputs<NullWritable,RangeCount> mos; // Each list is paired with the number of ranges it uses to compute a single // summary output. private final List<Triple<Integer, String, List<Range>>> summaryLists = new ArrayList<Triple<Integer, String, List<Range>>>(); // This is a safe initial choice: it doesn't matter whether the first actual // reference ID we get matches this or not, since all summaryLists are empty // anyway. private int currentReferenceID = 0; @Override public void setup( Reducer<LongWritable,Range, NullWritable,RangeCount>.Context ctx) { mos = new MultipleOutputs<NullWritable,RangeCount>(ctx); for (String s : ctx.getConfiguration().getStrings(SUMMARY_LEVELS_PROP)) { int level = Integer.parseInt(s); summaryLists.add( new Triple<Integer, String, List<Range>>( level, "summary" + level, new ArrayList<Range>())); } } @Override protected void reduce( LongWritable key, Iterable<Range> ranges, Reducer<LongWritable,Range, NullWritable,RangeCount>.Context context) throws IOException, InterruptedException { final int referenceID = (int)(key.get() >>> 32); // When the reference sequence changes we have to flush out everything // we've got and start from scratch again. if (referenceID != currentReferenceID) { currentReferenceID = referenceID; doAllSummaries(); } for (Range range : ranges) for (Triple<Integer, String, List<Range>> tuple : summaryLists) { int level = tuple.fst; String outName = tuple.snd; List<Range> rangeList = tuple.thd; rangeList.add(range); if (rangeList.size() == level) doSummary(rangeList, outName); } } @Override protected void cleanup( Reducer<LongWritable,Range, NullWritable,RangeCount>.Context context) throws IOException, InterruptedException { // Don't lose any remaining ones at the end. doAllSummaries(); mos.close(); } private void doAllSummaries() throws IOException, InterruptedException { for (Triple<Integer, String, List<Range>> tuple : summaryLists) if (!tuple.thd.isEmpty()) doSummary(tuple.thd, tuple.snd); } private void doSummary(Collection<Range> group, String outName) throws IOException, InterruptedException { RangeCount summary = computeSummary(group); group.clear(); mos.write(NullWritable.get(), summary, outName); } private RangeCount computeSummary(Collection<Range> group) { RangeCount rc = new RangeCount(currentReferenceID); // Calculate mean centre of mass and length. Use long to avoid overflow. long com = 0; long len = 0; for (Range r : group) { com += r.getCentreOfMass(); len += r.getLength(); } com /= group.size(); len /= group.size(); int beg = (int)com - (int)len/2; int end = (int)com + (int)len/2; rc.range.beg.set(beg); rc.range.end.set(end); rc.count. set(group.size()); return rc; } } final class Range implements Writable { public final IntWritable beg = new IntWritable(); public final IntWritable end = new IntWritable(); public void setFrom(SAMRecord record) { beg.set(record.getAlignmentStart()); end.set(record.getAlignmentEnd()); } public int getCentreOfMass() { return (beg.get() + end.get()) / 2; } public int getLength() { return end.get() - beg.get(); } @Override public void write(DataOutput out) throws IOException { beg.write(out); end.write(out); } @Override public void readFields(DataInput in) throws IOException { beg.readFields(in); end.readFields(in); } } final class RangeCount implements Comparable<RangeCount>, Writable { public final Range range = new Range(); public final IntWritable count = new IntWritable(); private final IntWritable rid; public RangeCount(int id) { rid = new IntWritable(id); } // This is what the TextOutputFormat will write. The format is // It might not be sorted by range.beg though! With the centre of mass // approach, it most likely won't be. @Override public String toString() { return rid + "\t" + range.beg + "\t" + range.end + "\t" + count; } // Comparisons only take into account the leftmost position. @Override public int compareTo(RangeCount o) { return Integer.valueOf(range.beg.get()).compareTo(o.range.beg.get()); } @Override public void write(DataOutput out) throws IOException { range.write(out); count.write(out); rid .write(out); } @Override public void readFields(DataInput in) throws IOException { range.readFields(in); count.readFields(in); rid .readFields(in); } } // We want the centre of mass to be used as (the low order bits of) the key // already at this point, because we want a total order so that we can // meaningfully look at consecutive ranges in the reducers. If we were to set // the final key in the mapper, the partitioner wouldn't use it. // And since getting the centre of mass requires calculating the Range as well, // we might as well get that here as well. final class SummarizeInputFormat extends FileInputFormat<LongWritable,Range> { private final BAMInputFormat bamIF = new BAMInputFormat(); @Override protected boolean isSplitable(JobContext job, Path path) { return bamIF.isSplitable(job, path); } @Override public List<InputSplit> getSplits(JobContext job) throws IOException { return bamIF.getSplits(job); } @Override public RecordReader<LongWritable,Range> createRecordReader(InputSplit split, TaskAttemptContext ctx) throws InterruptedException, IOException { final RecordReader<LongWritable,Range> rr = new SummarizeRecordReader(); rr.initialize(split, ctx); return rr; } } final class SummarizeRecordReader extends RecordReader<LongWritable,Range> { private final BAMRecordReader bamRR = new BAMRecordReader(); private final LongWritable key = new LongWritable(); private final Range range = new Range(); @Override public void initialize(InputSplit spl, TaskAttemptContext ctx) throws IOException { bamRR.initialize(spl, ctx); } @Override public void close() throws IOException { bamRR.close(); } @Override public float getProgress() { return bamRR.getProgress(); } @Override public LongWritable getCurrentKey () { return key; } @Override public Range getCurrentValue() { return range; } @Override public boolean nextKeyValue() { if (!bamRR.nextKeyValue()) return false; final SAMRecord rec = bamRR.getCurrentValue().get(); range.setFrom(rec); key.set((long)rec.getReferenceIndex() << 32 | range.getCentreOfMass()); return true; } } final class SummarizeOutputFormat extends TextOutputFormat<NullWritable,RangeCount> { public static final String INPUT_FILENAME_PROP = "summarize.input.filename"; @Override public RecordWriter<NullWritable,RangeCount> getRecordWriter( TaskAttemptContext ctx) throws IOException { Path path = getDefaultWorkFile(ctx, ""); FileSystem fs = path.getFileSystem(ctx.getConfiguration()); return new TextOutputFormat.LineRecordWriter<NullWritable,RangeCount>( new DataOutputStream( new BlockCompressedOutputStream(fs.create(path)))); } @Override public Path getDefaultWorkFile( TaskAttemptContext context, String ext) throws IOException { Configuration conf = context.getConfiguration(); // From MultipleOutputs. If we had a later version of FileOutputFormat as // well, we'd use getOutputName(). String summaryName = conf.get("mapreduce.output.basename"); // A RecordWriter is created as soon as a reduce task is started, even // though MultipleOutputs eventually overrides it with its own. // To avoid creating a file called "inputfilename-null" when that // RecordWriter is initialized, make it a hidden file instead, like this. // We can't use a filename we'd use later, because TextOutputFormat would // throw later on, as the file would already exist. String inputName = summaryName == null ? ".unused_" : ""; inputName += conf.get(INPUT_FILENAME_PROP); String extension = ext.isEmpty() ? ext : "." + ext; int part = context.getTaskAttemptID().getTaskID().getId(); return new Path(super.getDefaultWorkFile(context, ext).getParent(), inputName + "-" + summaryName + "-" + String.format("%06d", part) + extension); } // Allow the output directory to exist, so that we can make multiple jobs // that write into it. @Override public void checkOutputSpecs(JobContext job) throws FileAlreadyExistsException, IOException {} } final class Triple<A,B,C> { public A fst; public B snd; public C thd; public Triple(A a, B b, C c) { fst = a; snd = b; thd = c; } }
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.net.Socket; import java.util.Date; import java.net.Inet4Address; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TCPClient implements Runnable { private static final int SIZE_OF_POOL = 10; private static final int NUMBER_OF_CLIENTS = 100; private static final int NUMBER_OF_REQUESTS_PER_CLIENTS = 5; private static String IP; private static String Port; private int counter; public TCPClient(int count) { this.counter = count; } @Override public void run() { for (int i=0;i<NUMBER_OF_REQUESTS_PER_CLIENTS;i++) { try { Socket socket = new Socket(IP, Integer.parseInt(Port)); String message, response; DataOutputStream output = new DataOutputStream(socket.getOutputStream()); BufferedReader server = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); String clientMessage = "HELLO "+ Inet4Address.getLocalHost().getHostAddress() + " " + socket.getLocalPort() + " " + this.counter + System.lineSeparator(); Reader clientMessageReader = new StringReader(clientMessage); BufferedReader messageFromClient = new BufferedReader(clientMessageReader); message = messageFromClient.readLine() + System.lineSeparator(); output.writeBytes(message); response = server.readLine(); System.out.println("[" + new Date() + "] Received: " + response); try { Thread.sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) { } socket.close(); } catch (IOException e) { e.printStackTrace(); } } } public static ExecutorService TCP_WORKER_SERVICE = Executors.newFixedThreadPool(SIZE_OF_POOL); public static void main(String args[]) throws IOException { IP = args[0]; Port = args[1]; int cntr = 0; while (cntr < NUMBER_OF_CLIENTS) { TCPClient tcpClient = new TCPClient(cntr); TCP_WORKER_SERVICE.submit(tcpClient); cntr ++; } } }
package us.kbase.auth2.service.api; import static us.kbase.auth2.service.api.APIUtils.relativize; import static us.kbase.auth2.service.api.APIUtils.getLoginCookie; import static us.kbase.auth2.service.api.APIUtils.getMaxCookieAge; import static us.kbase.auth2.service.api.APIUtils.upperCase; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.NoSuchProviderException; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.Map.Entry; import javax.inject.Inject; import javax.ws.rs.CookieParam; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Cookie; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.UriInfo; import org.glassfish.jersey.server.mvc.Template; import org.glassfish.jersey.server.mvc.Viewable; import us.kbase.auth2.lib.AuthUser; import us.kbase.auth2.lib.Authentication; import us.kbase.auth2.lib.LoginToken; import us.kbase.auth2.lib.UserName; import us.kbase.auth2.lib.exceptions.AuthenticationException; import us.kbase.auth2.lib.exceptions.ErrorType; import us.kbase.auth2.lib.exceptions.ExternalConfigMappingException; import us.kbase.auth2.lib.exceptions.IllegalParameterException; import us.kbase.auth2.lib.exceptions.InvalidTokenException; import us.kbase.auth2.lib.exceptions.MissingParameterException; import us.kbase.auth2.lib.exceptions.NoSuchIdentityProviderException; import us.kbase.auth2.lib.exceptions.NoTokenProvidedException; import us.kbase.auth2.lib.exceptions.UnauthorizedException; import us.kbase.auth2.lib.exceptions.UserExistsException; import us.kbase.auth2.lib.identity.RemoteIdentityWithID; import us.kbase.auth2.lib.storage.exceptions.AuthStorageException; import us.kbase.auth2.lib.token.IncomingToken; import us.kbase.auth2.lib.token.NewToken; import us.kbase.auth2.lib.token.TemporaryToken; import us.kbase.auth2.service.AuthExternalConfig; import us.kbase.auth2.service.AuthExternalConfig.AuthExternalConfigMapper; @Path("/login") public class Login { //TODO TEST //TODO JAVADOC @Inject private Authentication auth; @GET public Response loginStart( @QueryParam("provider") final String provider, @QueryParam("redirect") final String redirect, @Context UriInfo uriInfo) throws NoSuchIdentityProviderException, AuthStorageException, IllegalParameterException { //TODO CONFIG REDIRECT check redirect url matches allowed config & is valid URL //TODO CONFIG allow enable & disable of id providers. checkRedirectURL(redirect); if (provider != null && !provider.trim().isEmpty()) { final String state = auth.getBareToken(); final URI target = toURI( auth.getIdentityProviderURL(provider, state, false)); final ResponseBuilder r = Response.seeOther(target) .cookie(getStateCookie(state)); if (redirect != null && !redirect.trim().isEmpty()) { r.cookie(getRedirectCookie(redirect)); } return r.build(); } else { final Map<String, Object> ret = new HashMap<>(); final List<Map<String, String>> provs = new LinkedList<>(); ret.put("providers", provs); for (final String prov: auth.getIdentityProviders()) { final Map<String, String> rep = new HashMap<>(); rep.put("name", prov); final URI i = auth.getIdentityProviderImageURI(prov); if (i.isAbsolute()) { rep.put("img", i.toString()); } else { rep.put("img", relativize(uriInfo, i)); } provs.add(rep); } ret.put("hasprov", !provs.isEmpty()); ret.put("urlpre", "?provider="); if (redirect != null && !redirect.trim().isEmpty()) { ret.put("redirect", redirect); } return Response.ok().entity(new Viewable("/loginstart", ret)) .build(); } } private void checkRedirectURL(final String redirect) throws AuthStorageException, IllegalParameterException { if (redirect != null && !redirect.trim().isEmpty()) { final AuthExternalConfig ext; try { ext = auth.getExternalConfig(new AuthExternalConfigMapper()); } catch (ExternalConfigMappingException e) { throw new RuntimeException("Dude, like, what just happened?", e); } try { new URL(redirect); } catch (MalformedURLException e) { throw new IllegalParameterException("Illegal redirect URL: " + redirect); } if (ext.getAllowedRedirectPrefix() != null) { if (!redirect.startsWith( ext.getAllowedRedirectPrefix().toString())) { throw new IllegalParameterException( "Illegal redirect url: " + redirect); } } } } private NewCookie getRedirectCookie(final String redirect) { return new NewCookie(new Cookie( "redirect", redirect == null ? "no redirect" : redirect, "/login", null), "redirect url", redirect == null ? 0 : 30 * 60, APIConstants.SECURE_COOKIES); } private NewCookie getStateCookie(final String state) { return new NewCookie(new Cookie( "statevar", state == null ? "no state" : state, "/login/complete", null), "loginstate", state == null ? 0 : 30 * 60, APIConstants.SECURE_COOKIES); } @GET @Path("/complete/{provider}") public Response login( @PathParam("provider") String provider, @CookieParam("statevar") final String state, @CookieParam("redirect") final String redirect, @Context final UriInfo uriInfo) throws MissingParameterException, AuthenticationException, NoSuchProviderException, AuthStorageException, UnauthorizedException { //TODO INPUT handle error in params (provider, state) provider = upperCase(provider); final MultivaluedMap<String, String> qps = uriInfo.getQueryParameters(); //TODO ERRHANDLE handle returned OAuth error code in queryparams final String authcode = qps.getFirst("code"); //may need to be configurable final String retstate = qps.getFirst("state"); //may need to be configurable if (state == null || state.trim().isEmpty()) { throw new MissingParameterException( "Couldn't retrieve state value from cookie"); } if (!state.equals(retstate)) { throw new AuthenticationException(ErrorType.AUTHENTICATION_FAILED, "State values do not match, this may be a CXRF attack"); } final LoginToken lr = auth.login(provider, authcode); final Response r; // always redirect so the authcode doesn't remain in the title bar // note nginx will rewrite the redirect appropriately so absolute // redirects are ok if (lr.isLoggedIn()) { r = Response.seeOther(getRedirectURI(redirect, "/me")) //TODO LOGIN get keep me logged in from cookie set at start of login .cookie(getLoginCookie(lr.getToken(), true)) .cookie(getStateCookie(null)) .cookie(getRedirectCookie(null)).build(); } else { r = Response.seeOther(toURI("/login/complete")).cookie( getLoginInProcessCookie(lr.getTemporaryToken())) .cookie(getStateCookie(null)) .build(); } return r; } private URI getRedirectURI(final String redirect, final String deflt) { //TODO REDIRECT check redirect url matches allowed config & is valid URL if (redirect != null && !redirect.trim().isEmpty()) { return toURI(redirect); } return toURI(deflt); } private NewCookie getLoginInProcessCookie(final TemporaryToken token) { return new NewCookie(new Cookie("in-process-login-token", token == null ? "no token" : token.getToken(), "/login", null), "logintoken", token == null ? 0 : getMaxCookieAge(token, false), APIConstants.SECURE_COOKIES); } @GET @Path("/complete") @Template(name = "/loginchoice") public Map<String, Object> loginComplete( @CookieParam("in-process-login-token") final String token, @Context final UriInfo uriInfo) throws NoTokenProvidedException, AuthStorageException, InvalidTokenException { if (token == null || token.trim().isEmpty()) { throw new NoTokenProvidedException( "Missing in-process-login-token"); } final Map<RemoteIdentityWithID, AuthUser> ids = auth.getLoginState( new IncomingToken(token.trim())); final Map<String, Object> ret = new HashMap<>(); ret.put("createurl", relativize(uriInfo, "/login/create")); ret.put("pickurl", relativize(uriInfo, "/login/pick")); ret.put("provider", ids.keySet().iterator().next().getRemoteID() .getProvider()); final List<Map<String, String>> create = new LinkedList<>(); final List<Map<String, String>> login = new LinkedList<>(); ret.put("create", create); ret.put("login", login); for (final Entry<RemoteIdentityWithID, AuthUser> e: ids.entrySet()) { final RemoteIdentityWithID id = e.getKey(); if (e.getValue() == null) { final Map<String, String> c = new HashMap<>(); c.put("id", id.getID().toString()); //TODO UI get safe username from db. Splitting on @ is not necessarily safe, only do it if it's there c.put("usernamesugg", id.getDetails().getUsername() .split("@")[0]); c.put("prov_username", id.getDetails().getUsername()); c.put("prov_fullname", id.getDetails().getFullname()); c.put("prov_email", id.getDetails().getEmail()); create.add(c); } else { final Map<String, String> l = new HashMap<>(); l.put("id", id.getID().toString()); l.put("prov_username", id.getDetails().getUsername()); l.put("username", e.getValue().getUserName().getName()); login.add(l); } } return ret; } @POST @Path("/pick") public Response pickAccount( @CookieParam("in-process-login-token") final String token, @CookieParam("redirect") final String redirect, @FormParam("id") final UUID identityID) throws NoTokenProvidedException, AuthenticationException, AuthStorageException, UnauthorizedException { if (token == null || token.trim().isEmpty()) { throw new NoTokenProvidedException( "Missing in-process-login-token"); } final NewToken newtoken = auth.login( new IncomingToken(token), identityID); return Response.seeOther(getRedirectURI(redirect, "/me")) //TODO LOGIN get keep me logged in from cookie set at start of login .cookie(getLoginCookie(newtoken, true)) .cookie(getLoginInProcessCookie(null)) .cookie(getRedirectCookie(null)).build(); } @POST @Path("/create") public Response createUser( @CookieParam("in-process-login-token") final String token, @CookieParam("redirect") final String redirect, @FormParam("id") final UUID identityID, @FormParam("user") final String userName, @FormParam("full") final String fullName, @FormParam("email") final String email, @FormParam("stayLoggedIn") final String stayLoggedIn, @FormParam("private") final String nameAndEmailPrivate) throws AuthenticationException, AuthStorageException, UserExistsException, NoTokenProvidedException, MissingParameterException, IllegalParameterException, UnauthorizedException { if (token == null || token.trim().isEmpty()) { throw new NoTokenProvidedException( "Missing in-process-login-token"); } //TODO INPUT sanity check inputs final boolean sessionLogin = stayLoggedIn == null || stayLoggedIn.isEmpty(); final boolean priv = nameAndEmailPrivate != null && nameAndEmailPrivate.isEmpty(); // might want to enapsulate the user data in a NewUser class final NewToken newtoken = auth.createUser(new IncomingToken(token), identityID, new UserName(userName), fullName, email, sessionLogin, priv); return Response.seeOther(getRedirectURI(redirect, "/me")) //TODO LOGIN get keep me logged in from cookie set at start of login .cookie(getLoginCookie(newtoken, true)) .cookie(getLoginInProcessCookie(null)) .cookie(getRedirectCookie(null)).build(); } //Assumes valid URI in URL form private URI toURI(final URL loginURL) { try { return loginURL.toURI(); } catch (URISyntaxException e) { throw new RuntimeException("This should be impossible", e); } } //Assumes valid URI in String form private URI toURI(final String uri) { try { return new URI(uri); } catch (URISyntaxException e) { throw new RuntimeException("This should be impossible", e); } } }
// DispatchTimer.java // xal package xal.tools.dispatch; import java.util.Date; /** DispatchTimer */ public class DispatchTimer { /** possible dispatch modes */ public enum DispatchTimerMode { FIXED_RATE, COALESCING } /** possible run states of the dispatch timer */ private enum DispatchTimerRunState { PROCESSING, SUSPENDED, DISPOSED } /** queue to which to dispatch events */ final private DispatchQueue EVENT_QUEUE; /** internal queue used to schedule the timer events */ final private DispatchQueue SCHEDULE_QUEUE; /** event to execute when this timer fires */ private Runnable _eventHandler; /** event to execute when this timer is canceled */ private Runnable _cancelHandler; /** indicates whether this timer is canceled */ private volatile boolean _isCanceled; /** run state of this timer */ private volatile DispatchTimerRunState _runState; /** milliseconds of the interval between when the timer fires */ private volatile long _milliInterval; /** nanoseconds of the interval between when the timer fires */ private volatile int _nanoInterval; /** next scheduled event */ private ScheduledEvent _nextScheduledEvent; /** delegate for handling the specified dispatch mode */ final private DispatchTimerModeDelegate DISPATCH_MODE_DELEGATE; /** Primary Constructor */ public DispatchTimer( final DispatchTimerMode dispatchMode, final DispatchQueue eventQueue, final Runnable eventHandler ) { DISPATCH_MODE_DELEGATE = getDispatchModeDelegate( dispatchMode ); EVENT_QUEUE = eventQueue; _eventHandler = eventHandler; SCHEDULE_QUEUE = DispatchQueue.createSerialQueue( "Dispatch Timer Scheduling Queue" ); _runState = DispatchTimerRunState.PROCESSING; _isCanceled = false; _nextScheduledEvent = null; } /** Constructor */ public DispatchTimer( final DispatchQueue eventQueue, final Runnable eventHandler ) { this ( DispatchTimerMode.FIXED_RATE, eventQueue, eventHandler ); } /** Create a new fixed rate timer */ static public DispatchTimer getFixedRateInstance( final DispatchQueue eventQueue, final Runnable eventHandler ) { return new DispatchTimer( DispatchTimerMode.FIXED_RATE, eventQueue, eventHandler ); } /** Create a new coalescing timer */ static public DispatchTimer getCoalescingInstance( final DispatchQueue eventQueue, final Runnable eventHandler ) { return new DispatchTimer( DispatchTimerMode.COALESCING, eventQueue, eventHandler ); } /** Get the dispatch mode delegate for the corresponding mode enum */ private DispatchTimerModeDelegate getDispatchModeDelegate( final DispatchTimerMode dispatchMode ) { switch( dispatchMode ) { case FIXED_RATE: return new DispatchTimerFixedRateDispatch(); case COALESCING: return new DispatchTimerCoalescingDispatch(); default: return new DispatchTimerFixedRateDispatch(); } } /** release resources held by this timer */ protected void finalize() throws Throwable { dispose(); } /** Set the event handler which is dispatched to the queue when the timer fires */ public void setEventHandler( final Runnable eventHandler ) { _eventHandler = eventHandler; } /** Set the cancel handler which is dipsatched to the queue when the timer is canceled */ public void setCancelHandler( final Runnable cancelHandler ) { _cancelHandler = cancelHandler; } /** * Start the timer now and set the interval between when the timer fires. * @param milliInterval milliseconds of the interval between when the timer fires * @param nanoInterval nanoseconds of the interval between when the timer fires */ public void startNowWithInterval( final long milliInterval, final int nanoInterval ) { setStartTimeAndInterval( new Date(), milliInterval, nanoInterval ); } /** * Set the time at which this timer starts and the interval between when the timer fires. * @param milliInterval milliseconds of the interval between when the timer fires * @param nanoInterval nanoseconds of the interval between when the timer fires */ public void setStartTimeAndInterval( final Date startTime, final long milliInterval, final int nanoInterval ) { cancelNextScheduledEvent(); // Since the start time is changing, we need to immediately cancel the next pending event here plus later on the schedule queue (see code below). SCHEDULE_QUEUE.dispatchAsync( new Runnable() { public void run() { cancelNextScheduledEvent(); // Cancel any currently scheduled event on the schedule queue in addition to immediately (see code above) _milliInterval = milliInterval; _nanoInterval = nanoInterval; final ScheduledEvent nextScheduledEvent = new ScheduledEvent( startTime ); // schedule an event that will execute immediately upon dispatch _nextScheduledEvent = nextScheduledEvent; SCHEDULE_QUEUE.dispatchAfter( startTime, nextScheduledEvent ); // dispatch after the start time } }); } /** Schedule the next event */ private void scheduleNextEvent( final ScheduledEvent nextScheduledEvent ) { SCHEDULE_QUEUE.dispatchAsync( new Runnable() { public void run() { _nextScheduledEvent = nextScheduledEvent; SCHEDULE_QUEUE.dispatchAsync( nextScheduledEvent ); } }); } /** Cancel this timer */ public void cancel() { _isCanceled = true; cancelNextScheduledEvent(); final Runnable cancelHandler = _cancelHandler; if ( cancelHandler != null ) { EVENT_QUEUE.dispatchAsync( cancelHandler ); } } /** Cancel the next scheduled event if any */ private void cancelNextScheduledEvent() { final ScheduledEvent nextScheduledEvent = _nextScheduledEvent; if ( nextScheduledEvent != null ) { nextScheduledEvent.cancel(); } _nextScheduledEvent = null; } /** Determines whether this queue is suspended (disposed implies suspended) */ public boolean isSuspended() { return _runState != DispatchTimerRunState.PROCESSING; // disposed states are also suspended } /** suspend this timer if it is processing (do nothing if disposed or already suspended) */ public void suspend() { switch( _runState ) { case PROCESSING: _runState = DispatchTimerRunState.SUSPENDED; break; default: break; } } /** resume this timer */ public void resume() { switch( _runState ) { case SUSPENDED: _runState = DispatchTimerRunState.PROCESSING; resumeScheduling(); break; case DISPOSED: throw new RuntimeException( "Cannot resume the disposed dispatch timer." ); default: break; } } /** resume scheduling events */ private void resumeScheduling() { final ScheduledEvent nextScheduledEvent = _nextScheduledEvent; if ( nextScheduledEvent != null ) { nextScheduledEvent.resume(); } } /** dispose of this timer's resources */ public void dispose() { _runState = DispatchTimerRunState.DISPOSED; SCHEDULE_QUEUE.dispose(); } /** determine whether this timer has been disposed */ public boolean isDisposed() { return _runState == DispatchTimerRunState.DISPOSED; } /** Event scheduled for execution */ private class ScheduledEvent implements Runnable { /** indicates whether the event would have fired if it had not been suspended */ private boolean _isPastDue; /** indicates whether this event is canceled */ private volatile boolean _isCanceled; /** time at which the event should fire */ private final long TARGET_TIME; /** additional nanosecond time */ private final int NANO_OFFSET; /** Primary Constructor */ public ScheduledEvent( final long targetTime, final int nanoOffset ) { TARGET_TIME = targetTime; NANO_OFFSET = nanoOffset; _isCanceled = false; _isPastDue = false; } /** Constructor */ public ScheduledEvent( final Date targetDate, final int nanoOffset ) { this( targetDate.getTime(), nanoOffset ); } /** Constructor */ public ScheduledEvent( final long targetTime ) { this( targetTime, 0 ); } /** Constructor */ public ScheduledEvent( final Date targetDate ) { this( targetDate.getTime() ); } /** Constructor with event scheduled immediately */ public ScheduledEvent() { this( new Date() ); } /** Get the target time */ public long getTargetTime() { return TARGET_TIME; } /** Get the next scheduled event relative to this one using the timer's millisecond and nanosecond intervals */ public ScheduledEvent nextScheduledEvent() { return nextScheduledEvent( _milliInterval, _nanoInterval ); } /** Get the next scheduled event relative to this one using the specified delays */ public ScheduledEvent nextScheduledEvent( final long milliDelay, final int nanoDelay ) { // Calculate the new target time and nano offset. If nanos accumulate more than a millisecond, shift that amount to the milliseconds. final int nanoShift = NANO_OFFSET + nanoDelay; final long targetTime = TARGET_TIME + milliDelay + nanoShift / 1000000; final int nanoOffset = nanoShift % 1000000; return new ScheduledEvent( targetTime, nanoOffset ); } /** Cancel this timer */ public void cancel() { _isCanceled = true; synchronized( SCHEDULE_QUEUE ) { try { SCHEDULE_QUEUE.notifyAll(); } catch( Exception exception ) {} } } /** Resume the timer and fire the event if it is past due */ public void resume() { if ( _isPastDue ) { dispatchEventIfEnabled(); } } /** dispatch the event if timer is active */ private void dispatchEventIfEnabled() { if ( !_isCanceled ) { switch ( _runState ) { case PROCESSING: DISPATCH_MODE_DELEGATE.processTimerEvent( _eventHandler ); break; default: _isPastDue = true; break; } } } /** Executes the event */ public void run() { synchronized( SCHEDULE_QUEUE ) { if ( !_isCanceled ) { try { while ( !_isCanceled ) { final long milliTimeout = TARGET_TIME - new Date().getTime(); // milliseconds left to wait final int nanoTimeout = NANO_OFFSET; if ( milliTimeout > 0 ) { SCHEDULE_QUEUE.wait( milliTimeout, 0 ); // wait the remaining millisecond timeout } else if ( milliTimeout == 0 && nanoTimeout > 0 ) { SCHEDULE_QUEUE.wait( 0, nanoTimeout ); // wait the remaining nano interval break; // assume the nano timeout was successful as we have no way to verify otherwise } else { break; } } } catch ( Exception exception ) { exception.printStackTrace(); } finally { dispatchEventIfEnabled(); } } } } } /** Make the next scheduled event */ private ScheduledEvent makeNextScheduledEvent() { return _nextScheduledEvent.nextScheduledEvent(); } /** Delegate interface for handling the various dispatch modes */ interface DispatchTimerModeDelegate { /** process the current timer event */ public void processTimerEvent( final Runnable eventHandler ); } /** Dispatches events at a fixed rate */ private class DispatchTimerFixedRateDispatch implements DispatchTimerModeDelegate { /** process the current timer event */ public void processTimerEvent( final Runnable eventHandler ) { final ScheduledEvent nextEvent = makeNextScheduledEvent(); if ( eventHandler != null ) { EVENT_QUEUE.dispatchAsync( eventHandler ); } if ( !_isCanceled ) scheduleNextEvent( nextEvent ); } } /** Dispatches events at a fixed rate but coalesces events that are concurrent thus preventing events from backing up in the queue */ private class DispatchTimerCoalescingDispatch implements DispatchTimerModeDelegate { /** process the current timer event */ public void processTimerEvent( final Runnable eventHandler ) { final ScheduledEvent nextEvent = makeNextScheduledEvent(); try { if ( eventHandler != null ) { EVENT_QUEUE.dispatchSync( eventHandler ); } } finally { if ( !_isCanceled ) scheduleNextEvent( nextEvent ); } } } }
package cluedo.view; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import cluedo.model.cards.CharacterCard; import cluedo.model.gameObjects.CluedoCharacter; import cluedo.model.gameObjects.CluedoCharacter.Suspect; /** * Shows the player info on the right side of the main frame * * @author Cameron Bryers and Hannah Craighead * */ public class PlayerInfoPanel extends JPanel { // Image of the player's character private JLabel playerIcon, playerLabel; // Buttons that the player can choose private JButton[] commandButtons; private ButtonGroup buttonGroup; private final String commands[] = new String[] { "Show Cards", "Show Checklist" }; // Current player info private BufferedImage playerImage; private String playerName; public PlayerInfoPanel() { playerIcon = new JLabel(); playerIcon.setHorizontalAlignment(JLabel.CENTER); playerLabel = new JLabel(); playerLabel.setHorizontalAlignment(JLabel.CENTER); commandButtons = new JButton[commands.length]; buttonGroup = new ButtonGroup(); // this.setSize(new Dimension(20,526)); this.setMaximumSize(new Dimension(100, 526)); init(); } private void init() { setLayout(new GridLayout(6, 1)); add(new JLabel()); add(playerIcon); add(playerLabel); // Set up buttons for (int i = 0; i < commandButtons.length; i++) { commandButtons[i] = new JButton(commands[i]); buttonGroup.add(commandButtons[i]); add(commandButtons[i]); } // TODO setup button listeners add(new JLabel("<html>Cameron Bryers and<br>Hannah Craighead MMXV</html>", JLabel.CENTER)); setVisible(true); } /** * Change the current player * * @param playerImage * @param playerName */ public void setPlayer(BufferedImage playerImage, String playerName) { this.playerImage = playerImage; this.playerName = playerName; if(playerImage != null){ // Resize image BufferedImage resized = CluedoMainFrame.resizeImage(playerImage, 100, 200); playerIcon.setIcon(new ImageIcon(resized)); } playerLabel.setText(playerName); } /** * Testing * @param args * @throws IOException */ public static void main(String args[]) throws IOException { JFrame frame = new JFrame(); // BufferedImage image = new CharacterCard(new CluedoCharacter(Suspect.MRS_PEACOCK)).getImage(); BufferedImage image = ImageIO.read(new File("blue_player_token.png")); // BufferedImage img = (BufferedImage) image.getScaledInstance(200, 200, Image.SCALE_SMOOTH); PlayerInfoPanel panel = new PlayerInfoPanel(); panel.setPlayer(image, "David"); frame.add(panel); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); } }
package org.bonej.plugins; import java.awt.AWTEvent; import java.awt.Checkbox; import java.awt.Choice; import java.awt.Color; import java.awt.TextField; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.stream.Stream; import org.bonej.geometry.FitEllipsoid; import org.bonej.menuWrappers.LocalThickness; import org.bonej.util.DialogModifier; import org.bonej.util.ImageCheck; import org.scijava.vecmath.Color3f; import org.scijava.vecmath.Point3f; import Jama.EigenvalueDecomposition; import Jama.Matrix; import customnode.CustomPointMesh; import customnode.CustomTriangleMesh; import ij.IJ; import ij.ImagePlus; import ij.ImageStack; import ij.gui.DialogListener; import ij.gui.GenericDialog; import ij.measure.Calibration; import ij.measure.ResultsTable; import ij.plugin.PlugIn; import ij.process.ImageProcessor; import ij3d.Image3DUniverse; import marchingcubes.MCTriangulator; public class ParticleCounter implements PlugIn, DialogListener { /** Foreground value */ static final int FORE = -1; /** Background value */ static final int BACK = 0; /** Surface colour style */ private static final int GRADIENT = 0; private static final int SPLIT = 1; private static final int ORIENTATION = 2; private String sPhase = ""; private String chunkString = ""; private JOINING labelMethod = JOINING.MAPPED; @Override public boolean dialogItemChanged(final GenericDialog gd, final AWTEvent e) { if (DialogModifier.hasInvalidNumber(gd.getNumericFields())) return false; final List<?> choices = gd.getChoices(); final List<?> checkboxes = gd.getCheckboxes(); final List<?> numbers = gd.getNumericFields(); // link algorithm choice to chunk size field final Choice choice = (Choice) choices.get(1); final TextField num = (TextField) numbers.get(5); num.setEnabled(choice.getSelectedItem().contentEquals("Multithreaded")); // link moments and ellipsoid choice to unit vector choice final Checkbox momBox = (Checkbox) checkboxes.get(4); final Checkbox elBox = (Checkbox) checkboxes.get(8); final Checkbox vvvBox = (Checkbox) checkboxes.get(9); vvvBox.setEnabled(elBox.getState() || momBox.getState()); // link show stack 3d to volume resampling final Checkbox box = (Checkbox) checkboxes.get(17); final TextField numb = (TextField) numbers.get(4); numb.setEnabled(box.getState()); // link show surfaces, gradient choice and split value final Checkbox surfbox = (Checkbox) checkboxes.get(13); final Choice col = (Choice) choices.get(0); final TextField split = (TextField) numbers.get(3); col.setEnabled(surfbox.getState()); split.setEnabled(surfbox.getState() && col.getSelectedIndex() == 1); DialogModifier.registerMacroValues(gd, gd.getComponents()); return true; } @Override public void run(final String arg) { final ImagePlus imp = IJ.getImage(); if (null == imp) { IJ.noImage(); return; } if (!ImageCheck.isBinary(imp)) { IJ.error("Binary image required"); return; } final Calibration cal = imp.getCalibration(); final String units = cal.getUnits(); final GenericDialog gd = new GenericDialog("Setup"); final String[] headers = { "Measurement Options", " " }; final String[] labels = new String[10]; final boolean[] defaultValues = new boolean[10]; labels[0] = "Exclude on sides"; defaultValues[0] = false; labels[1] = "Surface_area"; defaultValues[1] = true; labels[2] = "Feret diameter"; defaultValues[2] = false; labels[3] = "Enclosed_volume"; defaultValues[3] = true; labels[4] = "Moments of inertia"; defaultValues[4] = true; labels[5] = "Euler characteristic"; defaultValues[5] = true; labels[6] = "Thickness"; defaultValues[6] = true; labels[7] = "Mask thickness map"; defaultValues[7] = false; labels[8] = "Ellipsoids"; defaultValues[8] = true; labels[9] = "Record unit vectors"; defaultValues[9] = false; gd.addCheckboxGroup(5, 2, labels, defaultValues, headers); gd.addNumericField("Min Volume", 0, 3, 7, units + "³"); gd.addNumericField("Max Volume", Double.POSITIVE_INFINITY, 3, 7, units + "³"); gd.addNumericField("Surface_resampling", 2, 0); final String[] headers2 = { "Graphical Results", " " }; final String[] labels2 = new String[8]; final boolean[] defaultValues2 = new boolean[8]; labels2[0] = "Show_particle stack"; defaultValues2[0] = true; labels2[1] = "Show_size stack"; defaultValues2[1] = false; labels2[2] = "Show_thickness stack"; defaultValues2[2] = false; labels2[3] = "Show_surfaces (3D)"; defaultValues2[3] = true; labels2[4] = "Show_centroids (3D)"; defaultValues2[4] = true; labels2[5] = "Show_axes (3D)"; defaultValues2[5] = true; labels2[6] = "Show_ellipsoids (3D)"; defaultValues2[6] = true; labels2[7] = "Show_stack (3D)"; defaultValues2[7] = true; gd.addCheckboxGroup(4, 2, labels2, defaultValues2, headers2); final String[] items = { "Gradient", "Split", "Orientation"}; gd.addChoice("Surface colours", items, items[0]); gd.addNumericField("Split value", 0, 3, 7, units + "³"); gd.addNumericField("Volume_resampling", 2, 0); final String[] items2 = { "Multithreaded", "Linear", "Mapped" }; gd.addChoice("Labelling algorithm", items2, items2[2]); gd.addNumericField("Slices per chunk", 2, 0); gd.addDialogListener(this); gd.showDialog(); if (gd.wasCanceled()) { return; } final double minVol = gd.getNextNumber(); final double maxVol = gd.getNextNumber(); final boolean doExclude = gd.getNextBoolean(); final boolean doSurfaceArea = gd.getNextBoolean(); final boolean doFeret = gd.getNextBoolean(); final boolean doSurfaceVolume = gd.getNextBoolean(); final int resampling = (int) Math.floor(gd.getNextNumber()); final boolean doMoments = gd.getNextBoolean(); final boolean doEulerCharacters = gd.getNextBoolean(); final boolean doThickness = gd.getNextBoolean(); final boolean doMask = gd.getNextBoolean(); final boolean doEllipsoids = gd.getNextBoolean(); final boolean doVerboseUnitVectors = gd.getNextBoolean(); final boolean doParticleImage = gd.getNextBoolean(); final boolean doParticleSizeImage = gd.getNextBoolean(); final boolean doThickImage = gd.getNextBoolean(); final boolean doSurfaceImage = gd.getNextBoolean(); final int colourMode = gd.getNextChoiceIndex(); final double splitValue = gd.getNextNumber(); final boolean doCentroidImage = gd.getNextBoolean(); final boolean doAxesImage = gd.getNextBoolean(); final boolean doEllipsoidImage = gd.getNextBoolean(); final boolean do3DOriginal = gd.getNextBoolean(); final int origResampling = (int) Math.floor(gd.getNextNumber()); final String choice = gd.getNextChoice(); if (choice.equals(items2[0])) labelMethod = JOINING.MULTI; else if (choice.equals(items2[1])) labelMethod = JOINING.LINEAR; else labelMethod = JOINING.MAPPED; final int slicesPerChunk = (int) Math.floor(gd.getNextNumber()); // get the particles and do the analysis final long start = System.nanoTime(); final Object[] result = getParticles(imp, slicesPerChunk, minVol, maxVol, FORE, doExclude); // calculate particle labelling time in ms final long time = (System.nanoTime() - start) / 1000000; IJ.log("Particle labelling finished in " + time + " ms"); final int[][] particleLabels = (int[][]) result[1]; final long[] particleSizes = getParticleSizes(particleLabels); final int nParticles = particleSizes.length; final double[] volumes = getVolumes(imp, particleSizes); final double[][] centroids = getCentroids(imp, particleLabels, particleSizes); final int[][] limits = getParticleLimits(imp, particleLabels, nParticles); // set up resources for analysis ArrayList<List<Point3f>> surfacePoints = new ArrayList<>(); if (doSurfaceArea || doSurfaceVolume || doSurfaceImage || doEllipsoids || doFeret) { surfacePoints = getSurfacePoints(imp, particleLabels, limits, resampling, nParticles); } EigenvalueDecomposition[] eigens = new EigenvalueDecomposition[nParticles]; if (doMoments || doAxesImage || colourMode == ORIENTATION) { eigens = getEigens(imp, particleLabels, centroids); } // calculate dimensions double[] surfaceAreas = new double[nParticles]; if (doSurfaceArea) { surfaceAreas = getSurfaceAreas(surfacePoints); } double[] ferets = new double[nParticles]; if (doFeret) { ferets = getFerets(surfacePoints); } double[] surfaceVolumes = new double[nParticles]; if (doSurfaceVolume) { surfaceVolumes = getSurfaceVolume(surfacePoints); } double[][] eulerCharacters = new double[nParticles][3]; if (doEulerCharacters) { eulerCharacters = getEulerCharacter(imp, particleLabels, limits, nParticles); } double[][] thick = new double[nParticles][2]; if (doThickness) { final LocalThickness th = new LocalThickness(); final ImagePlus thickImp = th.getLocalThickness(imp, false, doMask); thick = getMeanStdDev(thickImp, particleLabels, particleSizes); if (doThickImage) { double max = 0; for (int i = 1; i < nParticles; i++) { max = Math.max(max, thick[i][2]); } thickImp.getProcessor().setMinAndMax(0, max); thickImp.setTitle(imp.getShortTitle() + "_thickness"); thickImp.show(); thickImp.setSlice(1); IJ.run("Fire"); } } Object[][] ellipsoids = new Object[nParticles][10]; if (doEllipsoids || doEllipsoidImage) { ellipsoids = getEllipsoids(surfacePoints); } // Show numerical results final ResultsTable rt = new ResultsTable(); for (int i = 1; i < volumes.length; i++) { if (volumes[i] > 0) { rt.incrementCounter(); rt.addLabel(imp.getTitle()); rt.addValue("ID", i); rt.addValue("Vol. (" + units + "³)", volumes[i]); rt.addValue("x Cent (" + units + ")", centroids[i][0]); rt.addValue("y Cent (" + units + ")", centroids[i][1]); rt.addValue("z Cent (" + units + ")", centroids[i][2]); if (doSurfaceArea) { rt.addValue("SA (" + units + "²)", surfaceAreas[i]); } if (doFeret) { rt.addValue("Feret (" + units + ")", ferets[i]); } if (doSurfaceVolume) { rt.addValue("Encl. Vol. (" + units + "³)", surfaceVolumes[i]); } if (doMoments) { final EigenvalueDecomposition E = eigens[i]; rt.addValue("I1", E.getD().get(2, 2)); rt.addValue("I2", E.getD().get(1, 1)); rt.addValue("I3", E.getD().get(0, 0)); rt.addValue("vX", E.getV().get(0, 0)); rt.addValue("vY", E.getV().get(1, 0)); rt.addValue("vZ", E.getV().get(2, 0)); if (doVerboseUnitVectors) { rt.addValue("vX1", E.getV().get(0, 1)); rt.addValue("vY1", E.getV().get(1, 1)); rt.addValue("vZ1", E.getV().get(2, 1)); rt.addValue("vX2", E.getV().get(0, 2)); rt.addValue("vY2", E.getV().get(1, 2)); rt.addValue("vZ2", E.getV().get(2, 2)); } } if (doEulerCharacters) { rt.addValue("Euler (χ)", eulerCharacters[i][0]); rt.addValue("Holes (β1)", eulerCharacters[i][1]); rt.addValue("Cavities (β2)", eulerCharacters[i][2]); } if (doThickness) { rt.addValue("Thickness (" + units + ")", thick[i][0]); rt.addValue("SD Thickness (" + units + ")", thick[i][1]); rt.addValue("Max Thickness (" + units + ")", thick[i][2]); } if (doEllipsoids) { final double[] rad; final double[][] unitV; if (ellipsoids[i] == null) { rad = new double[] { Double.NaN, Double.NaN, Double.NaN }; unitV = new double[][] { { Double.NaN, Double.NaN, Double.NaN }, { Double.NaN, Double.NaN, Double.NaN }, { Double.NaN, Double.NaN, Double.NaN } }; } else { final Object[] el = ellipsoids[i]; rad = (double[]) el[1]; unitV = (double[][]) el[2]; } rt.addValue("Major radius (" + units + ")", rad[0]); rt.addValue("Int. radius (" + units + ")", rad[1]); rt.addValue("Minor radius (" + units + ")", rad[2]); if (doVerboseUnitVectors) { rt.addValue("V00", unitV[0][0]); rt.addValue("V01", unitV[0][1]); rt.addValue("V02", unitV[0][2]); rt.addValue("V10", unitV[1][0]); rt.addValue("V11", unitV[1][1]); rt.addValue("V12", unitV[1][2]); rt.addValue("V20", unitV[2][0]); rt.addValue("V21", unitV[2][1]); rt.addValue("V22", unitV[2][2]); } } rt.updateResults(); } } rt.show("Results"); // Show resulting image stacks if (doParticleImage) { displayParticleLabels(particleLabels, imp).show(); IJ.run("Fire"); } if (doParticleSizeImage) { displayParticleValues(imp, particleLabels, volumes).show(); IJ.run("Fire"); } // show 3D renderings if (doSurfaceImage || doCentroidImage || doAxesImage || do3DOriginal || doEllipsoidImage) { final Image3DUniverse univ = new Image3DUniverse(); if (doSurfaceImage) { displayParticleSurfaces(univ, surfacePoints, colourMode, volumes, splitValue, eigens); } if (doCentroidImage) { displayCentroids(centroids, univ); } if (doAxesImage) { displayPrincipalAxes(univ, eigens, centroids, particleSizes); } if (doEllipsoidImage) { displayEllipsoids(ellipsoids, univ); } if (do3DOriginal) { display3DOriginal(imp, origResampling, univ); } univ.show(); } IJ.showProgress(1.0); IJ.showStatus("Particle Analysis Complete"); UsageReporter.reportEvent(this).send(); } /** * Add all the neighbouring labels of a pixel to the map, except 0 * (background) and the pixel's own label, which is already in the map. The * LUT gets updated with the minimum neighbour found, but this is only within * the first neighbours and not the minimum label in the pixel's neighbour * network * * @param map a map of LUT values. * @param nbh a neighbourhood in the image. * @param centre current pixel's label */ private static void addNeighboursToMap(final List<HashSet<Integer>> map, final int[] nbh, final int centre) { final HashSet<Integer> set = map.get(centre); Arrays.stream(nbh).filter(n -> n > 0).forEach(set::add); } private static void applyLUT(final int[][] particleLabels, final int[] lut, final int w, final int h, final int d) { for (int z = 0; z < d; z++) { IJ.showStatus("Applying LUT..."); IJ.showProgress(z, d - 1); final int[] slice = particleLabels[z]; for (int y = 0; y < h; y++) { final int yw = y * w; for (int x = 0; x < w; x++) { final int i = yw + x; final int label = slice[i]; if (label == 0) continue; slice[i] = lut[label]; } } } } private static boolean checkConsistence(final int[] lut, final List<HashSet<Integer>> map) { final int l = lut.length; for (int i = 1; i < l; i++) { if (!map.get(lut[i]).contains(i)) return false; } return true; } /** * Connect structures = minimisation of IDs * * @param imp an image. * @param workArray work array. * @param particleLabels particles in the image. * @param phase foreground or background * @param scanRanges int[][] listgetPixel(particleLabels, x, y, z, w, h, * d);ing ranges to run connectStructures on */ private void connectStructures(final ImagePlus imp, final byte[][] workArray, final int[][] particleLabels, final int phase, final int[][] scanRanges) { IJ.showStatus("Connecting " + sPhase + " structures" + chunkString); final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); for (int c = 0; c < scanRanges[0].length; c++) { final int sR0 = scanRanges[0][c]; final int sR1 = scanRanges[1][c]; final int sR2 = scanRanges[2][c]; final int sR3 = scanRanges[3][c]; for (int z = sR0; z < sR1; z++) { for (int y = 0; y < h; y++) { final int rowIndex = y * w; for (int x = 0; x < w; x++) { final int arrayIndex = rowIndex + x; final List<int[]> coordinates; if (workArray[z][arrayIndex] == BACK) { coordinates = get26NeighbourhoodCoordinates(x, y, z, w, h, d); } else if (workArray[z][arrayIndex] == FORE && particleLabels[z][arrayIndex] > 1) { coordinates = get6NeighbourhoodCoordinates(x, y, z, w, h, d); } else { continue; } replaceLabelsWithMinimum(coordinates, workArray, particleLabels, w, phase, sR2, sR3); } } if (phase == FORE) { IJ.showStatus("Connecting foreground structures" + chunkString); IJ.showProgress(z, d); } else { IJ.showStatus("Connecting background structures" + chunkString); IJ.showProgress(z, d + 1); } } } } /** * Find duplicated values and update the LUT * * @param counter counts of LUT values. * @param map map of LUT values. * @param lut a look-up table. * @return total number of duplicate values found. */ private static int countDuplicates(int[] counter, final ArrayList<HashSet<Integer>> map, final int[] lut) { //reset to 0 the counter array final int l = counter.length; counter = new int[l]; HashSet<Integer> set = null; for (int i = 1; i < map.size(); i++) { set = map.get(i); for (final Integer val : set) { final int v = val.intValue(); // every time a value is seen, log it counter[v]++; // update its LUT value if value was // found in a set with lower than current // lut value if (lut[v] > i) lut[v] = i; } } minimiseLutArray(lut); // all values should be seen only once, // count how many >1s there are. int count = 0; for (int i = 1; i < l; i++) { if (counter[i] > 1) count++; } return count; } /** * Calculate the cross product of 3 Point3f's, which describe two vectors * joined at the tails. Can be used to find the plane / surface normal of a * triangle. Half of its magnitude is the area of the triangle. * * @param point0 both vectors' tails * @param point1 vector 1's head * @param point2 vector 2's head * @return cross product vector */ private static Point3f crossProduct(final Point3f point0, final Point3f point1, final Point3f point2) { final double x1 = point1.x - point0.x; final double y1 = point1.y - point0.y; final double z1 = point1.z - point0.z; final double x2 = point2.x - point0.x; final double y2 = point2.y - point0.y; final double z2 = point2.z - point0.z; final Point3f crossVector = new Point3f(); crossVector.x = (float) (y1 * z2 - z1 * y2); crossVector.y = (float) (z1 * x2 - x1 * z2); crossVector.z = (float) (x1 * y2 - y1 * x2); return crossVector; } private static void display3DOriginal(final ImagePlus imp, final int resampling, final Image3DUniverse univ) { final Color3f colour = new Color3f(1.0f, 1.0f, 1.0f); final boolean[] channels = { true, true, true }; try { univ.addVoltex(imp, colour, imp.getTitle(), 0, channels, resampling) .setLocked(true); } catch (final NullPointerException npe) { IJ.log("3D Viewer was closed before rendering completed."); } } /** * Draws 3 orthogonal axes defined by the centroid, unitvector and axis * length. * * @param univ the universe where axes are drawn. * @param centroid centroid of a particle. * @param unitVector orientation of the particle. * @param lengths lengths of the axes. * @param green green component of the axes' color. * @param title text shown by the axes. */ private static void displayAxes(final Image3DUniverse univ, final double[] centroid, final double[][] unitVector, final double[] lengths, final float green, final String title) { final double cX = centroid[0]; final double cY = centroid[1]; final double cZ = centroid[2]; final double eVec1x = unitVector[0][0]; final double eVec1y = unitVector[1][0]; final double eVec1z = unitVector[2][0]; final double eVec2x = unitVector[0][1]; final double eVec2y = unitVector[1][1]; final double eVec2z = unitVector[2][1]; final double eVec3x = unitVector[0][2]; final double eVec3y = unitVector[1][2]; final double eVec3z = unitVector[2][2]; final double l1 = lengths[0]; final double l2 = lengths[1]; final double l3 = lengths[2]; final List<Point3f> mesh = new ArrayList<>(); final Point3f start1 = new Point3f(); start1.x = (float) (cX - eVec1x * l1); start1.y = (float) (cY - eVec1y * l1); start1.z = (float) (cZ - eVec1z * l1); mesh.add(start1); final Point3f end1 = new Point3f(); end1.x = (float) (cX + eVec1x * l1); end1.y = (float) (cY + eVec1y * l1); end1.z = (float) (cZ + eVec1z * l1); mesh.add(end1); final Point3f start2 = new Point3f(); start2.x = (float) (cX - eVec2x * l2); start2.y = (float) (cY - eVec2y * l2); start2.z = (float) (cZ - eVec2z * l2); mesh.add(start2); final Point3f end2 = new Point3f(); end2.x = (float) (cX + eVec2x * l2); end2.y = (float) (cY + eVec2y * l2); end2.z = (float) (cZ + eVec2z * l2); mesh.add(end2); final Point3f start3 = new Point3f(); start3.x = (float) (cX - eVec3x * l3); start3.y = (float) (cY - eVec3y * l3); start3.z = (float) (cZ - eVec3z * l3); mesh.add(start3); final Point3f end3 = new Point3f(); end3.x = (float) (cX + eVec3x * l3); end3.y = (float) (cY + eVec3y * l3); end3.z = (float) (cZ + eVec3z * l3); mesh.add(end3); final Color3f aColour = new Color3f(1.0f, green, 0.0f); try { univ.addLineMesh(mesh, aColour, title, false).setLocked(true); } catch (final NullPointerException npe) { IJ.log("3D Viewer was closed before rendering completed."); } } /** * Draw the particle centroids in a 3D viewer * * @param centroids [n][3] centroids of particles. * @param univ universe where the centroids are displayed. */ private static void displayCentroids(final double[][] centroids, final Image3DUniverse univ) { final int nCentroids = centroids.length; for (int p = 1; p < nCentroids; p++) { IJ.showStatus("Rendering centroids..."); IJ.showProgress(p, nCentroids); final Point3f centroid = new Point3f(); centroid.x = (float) centroids[p][0]; centroid.y = (float) centroids[p][1]; centroid.z = (float) centroids[p][2]; final List<Point3f> point = new ArrayList<>(); point.add(centroid); final CustomPointMesh mesh = new CustomPointMesh(point); mesh.setPointSize(5.0f); final float red = 0.0f; final float green = 0.5f * p / nCentroids; final float blue = 1.0f; final Color3f cColour = new Color3f(red, green, blue); mesh.setColor(cColour); try { univ.addCustomMesh(mesh, "Centroid " + p).setLocked(true); } catch (final NullPointerException npe) { IJ.log("3D Viewer was closed before rendering completed."); return; } } } private static void displayEllipsoids(final Object[][] ellipsoids, final Image3DUniverse univ) { final int nEllipsoids = ellipsoids.length; for (int el = 1; el < nEllipsoids; el++) { IJ.showStatus("Rendering ellipsoids..."); IJ.showProgress(el, nEllipsoids); if (ellipsoids[el] == null) { continue; } final double[] radii = (double[]) ellipsoids[el][1]; if (!isRadiiValid(radii)) { continue; } final double[] centre = (double[]) ellipsoids[el][0]; final double[][] eV = (double[][]) ellipsoids[el][2]; final double a = radii[0]; // longest final double b = radii[1]; // middle final double c = radii[2]; // shortest if (a < b || b < c || a < c) { IJ.log("Error: Bad ellipsoid radius ordering! Surface: " + el); } final double[][] ellipsoid = FitEllipsoid.testEllipsoid(a, b, c, 0, 0, 0, 0, 0, 1000, false); final int nPoints = ellipsoid.length; // rotate points by eigenvector matrix // and add transformation for centre for (int p = 0; p < nPoints; p++) { final double x = ellipsoid[p][0]; final double y = ellipsoid[p][1]; final double z = ellipsoid[p][2]; ellipsoid[p][0] = x * eV[0][0] + y * eV[0][1] + z * eV[0][2] + centre[0]; ellipsoid[p][1] = x * eV[1][0] + y * eV[1][1] + z * eV[1][2] + centre[1]; ellipsoid[p][2] = x * eV[2][0] + y * eV[2][1] + z * eV[2][2] + centre[2]; } final List<Point3f> points = new ArrayList<>(); for (final double[] anEllipsoid : ellipsoid) { final Point3f e = new Point3f(); e.x = (float) anEllipsoid[0]; e.y = (float) anEllipsoid[1]; e.z = (float) anEllipsoid[2]; points.add(e); } final CustomPointMesh mesh = new CustomPointMesh(points); mesh.setPointSize(1.0f); final float red = 0.0f; final float green = 0.5f; final float blue = 1.0f; final Color3f cColour = new Color3f(red, green, blue); mesh.setColor(cColour); try { univ.addCustomMesh(mesh, "Ellipsoid " + el).setLocked(true); } catch (final NullPointerException npe) { IJ.log("3D Viewer was closed before rendering completed."); return; } // Add some axes displayAxes(univ, centre, eV, radii, 1.0f, "Ellipsoid Axes " + el); } } /** * Display the particle labels as an ImagePlus * * @param particleLabels particles labelled in the original image. * @param imp original image, used for image dimensions, calibration and * titles * @return an image of the particles. */ private static ImagePlus displayParticleLabels(final int[][] particleLabels, final ImagePlus imp) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int wh = w * h; final ImageStack stack = new ImageStack(w, h); double max = 0; for (int z = 0; z < d; z++) { final float[] slicePixels = new float[wh]; for (int i = 0; i < wh; i++) { slicePixels[i] = particleLabels[z][i]; max = Math.max(max, slicePixels[i]); } stack.addSlice(imp.getImageStack().getSliceLabel(z + 1), slicePixels); } final ImagePlus impParticles = new ImagePlus(imp.getShortTitle() + "_parts", stack); impParticles.setCalibration(imp.getCalibration()); impParticles.getProcessor().setMinAndMax(0, max); if (max > Math.pow(2, 24)) IJ.error("Warning", "More than 16777216 (2^24) particles./n/n" + "Particle image labels are inaccurate above this number."); return impParticles; } /** * Draw the particle surfaces in a 3D viewer * * @param univ universe where the centroids are displayed. * @param surfacePoints points of each particle. */ private static void displayParticleSurfaces(final Image3DUniverse univ, final Collection<List<Point3f>> surfacePoints, final int colourMode, final double[] volumes, final double splitValue, final EigenvalueDecomposition[] eigens) { int p = 0; final int nParticles = surfacePoints.size(); for (final List<Point3f> surfacePoint : surfacePoints) { IJ.showStatus("Rendering surfaces..."); IJ.showProgress(p, nParticles); if (p > 0 && !surfacePoint.isEmpty()) { Color3f pColour = new Color3f(0, 0, 0); if (colourMode == GRADIENT) { final float red = 1.0f - p / (float) nParticles; final float green = 1.0f - red; final float blue = p / (2.0f * nParticles); pColour = new Color3f(red, green, blue); } else if (colourMode == SPLIT) { if (volumes[p] > splitValue) { // red if over pColour = new Color3f(1.0f, 0.0f, 0.0f); } else { // yellow if under pColour = new Color3f(1.0f, 1.0f, 0.0f); } } else if (colourMode == ORIENTATION) { pColour = colourFromEigenVector(eigens[p]); } // Add the mesh try { univ.addTriangleMesh(surfacePoint, pColour, "Surface " + p).setLocked( true); } catch (final NullPointerException npe) { IJ.log("3D Viewer was closed before rendering completed."); return; } } p++; } } /** * Generate a colour based on the inertia tensor's eigenvector * * Colour is from the HSB colour wheel scaled by 0.5 to fit * into pi radians (rather than the 2 pi it normally occupies), * so that red is at 0, pi and 2pi radians. * * Colour is mapped to the axis-angle representation of the tensor * so hue varies as a function of second axis rotation around the * first. * * @param eigen Eigenvalue decomposition of the particle * @return Colour scaling in red for axis and green for angle */ private static Color3f colourFromEigenVector(EigenvalueDecomposition eigen) { final Matrix rotation = eigen.getV(); //convert the rotation matrix into axis-angle representation //calculate the axis final double u0 = rotation.get(2, 1) - rotation.get(1, 2); final double u1 = rotation.get(0, 2) - rotation.get(2, 0); final double u2 = rotation.get(1, 0) - rotation.get(0, 1); final double magnitudeU = Math.sqrt(u0 * u0 + u1 * u1 + u2 * u2); //axis ranges from -pi/2 to +pi/2 final double axis = Math.asin(magnitudeU / 2); //axis normed ranges from 0 to 1 final double axisNormed = ((axis + Math.PI/2) / 2)/(Math.PI/2); //calculate the angle from the trace (sum of diagonals) double trace = rotation.trace(); //if trace is out of range if (trace > 3 || trace < -1) { Matrix turn = new Matrix(3, 3); turn.set(0, 0, -1); turn.set(1, 1, -1); turn.set(1, 1, 1); trace = rotation.times(turn).trace(); } if (trace > 3 || trace < -1) IJ.log("The rotation didn't fix the out of bounds trace :-("); double angle = Math.acos((trace - 1.0)/2.0); final float hue = (float)(angle / Math.PI); final float saturation = (float) axisNormed; final float brightness = (float) axisNormed; final int rgb = Color.HSBtoRGB(hue, saturation, brightness); final Color color = new Color(rgb); float red = (float)(color.getRed()/255d); float green = (float)(color.getGreen()/255d); float blue = (float)(color.getBlue()/255d); return new Color3f(red, green, blue); } /** * Create an image showing some particle measurement * * @param imp an image. * @param particleLabels the particles in the image. * @param values list of values whose array indices correspond to * particlelabels * @return ImagePlus with particle labels substituted with some value */ private static ImagePlus displayParticleValues(final ImagePlus imp, final int[][] particleLabels, final double[] values) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int wh = w * h; final float[][] pL = new float[d][wh]; values[0] = 0; // don't colour the background final ImageStack stack = new ImageStack(w, h); for (int z = 0; z < d; z++) { for (int i = 0; i < wh; i++) { final int p = particleLabels[z][i]; pL[z][i] = (float) values[p]; } stack.addSlice(imp.getImageStack().getSliceLabel(z + 1), pL[z]); } final double max = Arrays.stream(values).max().orElse(0.0); final ImagePlus impOut = new ImagePlus(imp.getShortTitle() + "_" + "volume", stack); impOut.setCalibration(imp.getCalibration()); impOut.getProcessor().setMinAndMax(0, max); return impOut; } private static void displayPrincipalAxes(final Image3DUniverse univ, final EigenvalueDecomposition[] eigens, final double[][] centroids, long[] particleSizes) { final int nEigens = eigens.length; for (int p = 1; p < nEigens; p++) { IJ.showStatus("Rendering principal axes..."); IJ.showProgress(p, nEigens); final long size = particleSizes[p]; final Matrix eVec = eigens[p].getV(); final Matrix eVal = eigens[p].getD(); double[] lengths = new double[3]; for (int i = 0; i < 3; i++) { lengths[i] = 2 * Math.sqrt(eVal.get(2 - i, 2 - i) / size); } displayAxes(univ, centroids[p], eVec.getArray(), lengths, 0.0f, "Principal Axes " + p); } } /** * Scans edge voxels and set all touching particles to background * * @param imp an image. * @param particleLabels particles in the image. */ private void excludeOnEdges(final ImagePlus imp, final int[][] particleLabels, final byte[][] workArray) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final long[] particleSizes = getParticleSizes(particleLabels); final int nLabels = particleSizes.length; final int[] newLabel = new int[nLabels]; for (int i = 0; i < nLabels; i++) newLabel[i] = i; // scan faces // top and bottom faces for (int y = 0; y < h; y++) { final int index = y * w; for (int x = 0; x < w; x++) { final int pt = particleLabels[0][index + x]; if (pt > 0) newLabel[pt] = 0; final int pb = particleLabels[d - 1][index + x]; if (pb > 0) newLabel[pb] = 0; } } // west and east faces for (int z = 0; z < d; z++) { for (int y = 0; y < h; y++) { final int pw = particleLabels[z][y * w]; final int pe = particleLabels[z][y * w + w - 1]; if (pw > 0) newLabel[pw] = 0; if (pe > 0) newLabel[pe] = 0; } } // north and south faces final int lastRow = w * (h - 1); for (int z = 0; z < d; z++) { for (int x = 0; x < w; x++) { final int pn = particleLabels[z][x]; final int ps = particleLabels[z][lastRow + x]; if (pn > 0) newLabel[pn] = 0; if (ps > 0) newLabel[ps] = 0; } } // replace labels final int wh = w * h; for (int z = 0; z < d; z++) { for (int i = 0; i < wh; i++) { final int p = particleLabels[z][i]; final int nL = newLabel[p]; if (nL == 0) { particleLabels[z][i] = 0; workArray[z][i] = 0; } } } } /** * Remove particles outside user-specified volume thresholds * * @param imp ImagePlus, used for calibration * @param workArray binary foreground and background information * @param particleLabels Packed 3D array of particle labels * @param minVol minimum (inclusive) particle volume * @param maxVol maximum (inclusive) particle volume * @param phase phase we are interested in */ private void filterParticles(final ImagePlus imp, final byte[][] workArray, final int[][] particleLabels, final double minVol, final double maxVol, final int phase) { if (minVol == 0 && maxVol == Double.POSITIVE_INFINITY) return; final int d = imp.getImageStackSize(); final int wh = workArray[0].length; final long[] particleSizes = getParticleSizes(particleLabels); final double[] particleVolumes = getVolumes(imp, particleSizes); final byte flip; if (phase == FORE) { flip = 0; } else { flip = (byte) 255; } for (int z = 0; z < d; z++) { for (int i = 0; i < wh; i++) { final int p = particleLabels[z][i]; final double v = particleVolumes[p]; if (v < minVol || v > maxVol) { workArray[z][i] = flip; particleLabels[z][i] = 0; } } } } private static boolean findFirstAppearance(final int[] lut, final List<HashSet<Integer>> map) { final int l = map.size(); boolean changed = false; for (int i = 0; i < l; i++) { final HashSet<Integer> set = map.get(i); for (final Integer val : set) { // if the current lut value is greater // than the current position // update lut with current position if (lut[val] > i) { lut[val] = i; changed = true; } } } return changed; } private static int findMinimumLabel(final Iterable<int[]> coordinates, final byte[][] workArray, final int[][] particleLabels, final int w, final int phase, final int minStart) { int minLabel = minStart; for (final int[] coordinate : coordinates) { final int z = coordinate[2]; final int index = getOffset(coordinate[0], coordinate[1], w); if (workArray[z][index] == phase) { final int label = particleLabels[z][index]; if (label != 0 && label < minLabel) { minLabel = label; } } } return minLabel; } /** * Go through all pixels and assign initial particle label * * @param imp an image. * @param workArray byte[] array containing pixel values * @param phase FORE or BACK for foreground of background respectively * @return particleLabels int[] array containing label associating every pixel * with a particle */ private int[][] firstIDAttribution(final ImagePlus imp, final byte[][] workArray, final int phase) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int[] bounds = { w, h, d }; final int wh = w * h; IJ.showStatus("Finding " + sPhase + " structures"); final int[][] particleLabels = new int[d][wh]; int ID = 1; final BiFunction<int[], int[], List<int[]>> neighbourhoodFinder; if (phase == BACK) { neighbourhoodFinder = ParticleCounter::get6NeighbourhoodCoordinates; } else { neighbourhoodFinder = ParticleCounter::get26NeighbourhoodCoordinates; } for (int z = 0; z < d; z++) { for (int y = 0; y < h; y++) { final int rowIndex = y * w; for (int x = 0; x < w; x++) { final int arrayIndex = rowIndex + x; if (workArray[z][arrayIndex] != phase) { continue; } particleLabels[z][arrayIndex] = ID; final List<int[]> coordinates = neighbourhoodFinder.apply(new int[] { x, y, z }, bounds); coordinates.add(new int[] { x, y, z }); final int minTag = findMinimumLabel(coordinates, workArray, particleLabels, w, phase, ID); particleLabels[z][arrayIndex] = minTag; if (minTag == ID) { ID++; } } } IJ.showProgress(z, d); } return particleLabels; } /** * Get neighborhood of a pixel in a 3D image (0 border conditions) * Longhand, hard-coded for speed * * @param neighborhood a neighbourhood in the image. * @param image 3D image (int[][]) * @param x0 x- coordinate * @param y0 y- coordinate * @param z0 z- coordinate (in image stacks the indexes start at 1) * @param w width of the image. * @param h height of the image. * @param d depth of the image. */ private static void get26Neighborhood(final int[] neighborhood, final int[][] image, final int x, final int y, final int z, final int w, final int h, final int d) { final int xm1 = x - 1; final int xp1 = x + 1; final int ym1 = y - 1; final int yp1 = y + 1; final int zm1 = z - 1; final int zp1 = z + 1; neighborhood[0] = getPixel(image, xm1, ym1, zm1, w, h, d); neighborhood[1] = getPixel(image, x, ym1, zm1, w, h, d); neighborhood[2] = getPixel(image, xp1, ym1, zm1, w, h, d); neighborhood[3] = getPixel(image, xm1, y, zm1, w, h, d); neighborhood[4] = getPixel(image, x, y, zm1, w, h, d); neighborhood[5] = getPixel(image, xp1, y, zm1, w, h, d); neighborhood[6] = getPixel(image, xm1, yp1, zm1, w, h, d); neighborhood[7] = getPixel(image, x, yp1, zm1, w, h, d); neighborhood[8] = getPixel(image, xp1, yp1, zm1, w, h, d); neighborhood[9] = getPixel(image, xm1, ym1, z, w, h, d); neighborhood[10] = getPixel(image, x, ym1, z, w, h, d); neighborhood[11] = getPixel(image, xp1, ym1, z, w, h, d); neighborhood[12] = getPixel(image, xm1, y, z, w, h, d); neighborhood[13] = getPixel(image, xp1, y, z, w, h, d); neighborhood[14] = getPixel(image, xm1, yp1, z, w, h, d); neighborhood[15] = getPixel(image, x, yp1, z, w, h, d); neighborhood[16] = getPixel(image, xp1, yp1, z, w, h, d); neighborhood[17] = getPixel(image, xm1, ym1, zp1, w, h, d); neighborhood[18] = getPixel(image, x, ym1, zp1, w, h, d); neighborhood[19] = getPixel(image, xp1, ym1, zp1, w, h, d); neighborhood[20] = getPixel(image, xm1, y, zp1, w, h, d); neighborhood[21] = getPixel(image, x, y, zp1, w, h, d); neighborhood[22] = getPixel(image, xp1, y, zp1, w, h, d); neighborhood[23] = getPixel(image, xm1, yp1, zp1, w, h, d); neighborhood[24] = getPixel(image, x, yp1, zp1, w, h, d); neighborhood[25] = getPixel(image, xp1, yp1, zp1, w, h, d); } private static List<int[]> get26NeighbourhoodCoordinates(final int[] voxel, final int[] bounds) { return get26NeighbourhoodCoordinates(voxel[0], voxel[1], voxel[2], bounds[0], bounds[1], bounds[2]); } private static List<int[]> get26NeighbourhoodCoordinates(final int x0, final int y0, final int z0, final int w, final int h, final int d) { final List<int[]> coordinates = new ArrayList<>(); for (int z = z0 - 1; z <= z0 + 1; z++) { for (int y = y0 - 1; y <= y0 + 1; y++) { for (int x = x0 - 1; x <= x0 + 1; x++) { if (z == z0 && y == y0 && x == x0) { continue; } if (withinBounds(x, y, z, w, h, d)) { coordinates.add(new int[] { x, y, z }); } } } } return coordinates; } private static void get6Neighborhood(final int[] neighborhood, final int[][] image, final int x, final int y, final int z, final int w, final int h, final int d) { neighborhood[0] = getPixel(image, x - 1, y, z, w, h, d); neighborhood[1] = getPixel(image, x, y - 1, z, w, h, d); neighborhood[2] = getPixel(image, x, y, z - 1, w, h, d); neighborhood[3] = getPixel(image, x + 1, y, z, w, h, d); neighborhood[4] = getPixel(image, x, y + 1, z, w, h, d); neighborhood[5] = getPixel(image, x, y, z + 1, w, h, d); } private static List<int[]> get6NeighbourhoodCoordinates(final int[] voxel, final int[] bounds) { return get26NeighbourhoodCoordinates(voxel[0], voxel[1], voxel[2], bounds[0], bounds[1], bounds[2]); } private static List<int[]> get6NeighbourhoodCoordinates(final int x0, final int y0, final int z0, final int w, final int h, final int d) { return Stream.of(new int[] { x0 - 1, y0, z0 }, new int[] { x0 + 1, y0, z0 }, new int[] { x0, y0 - 1, z0 }, new int[] { x0, y0 + 1, z0 }, new int[] { x0, y0, z0 - 1 }, new int[] { x0, y0, z0 + 1 }).filter( a -> withinBounds(a[0], a[1], a[2], w, h, d)).collect(Collectors .toList()); } /** * create a binary ImagePlus containing a single particle and which 'just * fits' the particle * * @param p The particle ID to get * @param imp original image, used for calibration * @param particleLabels work array of particle labels * @param limits x,y and z limits of each particle * @param padding amount of empty space to pad around each particle * @return a cropped single particle image. */ private static ImagePlus getBinaryParticle(final int p, final ImagePlus imp, final int[][] particleLabels, final int[][] limits, final int padding) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int xMin = Math.max(0, limits[p][0] - padding); final int xMax = Math.min(w - 1, limits[p][1] + padding); final int yMin = Math.max(0, limits[p][2] - padding); final int yMax = Math.min(h - 1, limits[p][3] + padding); final int zMin = Math.max(0, limits[p][4] - padding); final int zMax = Math.min(d - 1, limits[p][5] + padding); final int stackWidth = xMax - xMin + 1; final int stackHeight = yMax - yMin + 1; final int stackSize = stackWidth * stackHeight; final ImageStack stack = new ImageStack(stackWidth, stackHeight); for (int z = zMin; z <= zMax; z++) { final byte[] slice = new byte[stackSize]; int i = 0; for (int y = yMin; y <= yMax; y++) { final int sourceIndex = y * w; for (int x = xMin; x <= xMax; x++) { if (particleLabels[z][sourceIndex + x] == p) { slice[i] = (byte) 0xFF; } i++; } } stack.addSlice(imp.getStack().getSliceLabel(z + 1), slice); } final ImagePlus binaryImp = new ImagePlus("Particle_" + p, stack); final Calibration cal = imp.getCalibration(); binaryImp.setCalibration(cal); return binaryImp; } /** * Get the centroids of all the particles in real units * * @param imp an image. * @param particleLabels particles in the image. * @param particleSizes sizes of the particles * @return double[][] containing all the particles' centroids */ private static double[][] getCentroids(final ImagePlus imp, final int[][] particleLabels, final long[] particleSizes) { final int nParticles = particleSizes.length; final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final double[][] sums = new double[nParticles][3]; for (int z = 0; z < d; z++) { for (int y = 0; y < h; y++) { final int index = y * w; for (int x = 0; x < w; x++) { final int particle = particleLabels[z][index + x]; sums[particle][0] += x; sums[particle][1] += y; sums[particle][2] += z; } } } final Calibration cal = imp.getCalibration(); final double[][] centroids = new double[nParticles][3]; for (int p = 0; p < nParticles; p++) { centroids[p][0] = cal.pixelWidth * sums[p][0] / particleSizes[p]; centroids[p][1] = cal.pixelHeight * sums[p][1] / particleSizes[p]; centroids[p][2] = cal.pixelDepth * sums[p][2] / particleSizes[p]; } return centroids; } private static EigenvalueDecomposition[] getEigens(final ImagePlus imp, final int[][] particleLabels, final double[][] centroids) { final Calibration cal = imp.getCalibration(); final double vW = cal.pixelWidth; final double vH = cal.pixelHeight; final double vD = cal.pixelDepth; final double voxVhVd = (vH * vH + vD * vD) / 12; final double voxVwVd = (vW * vW + vD * vD) / 12; final double voxVhVw = (vH * vH + vW * vW) / 12; final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int nParticles = centroids.length; final EigenvalueDecomposition[] eigens = new EigenvalueDecomposition[nParticles]; final double[][] momentTensors = new double[nParticles][6]; for (int z = 0; z < d; z++) { IJ.showStatus("Calculating particle moments..."); IJ.showProgress(z, d); final double zVd = z * vD; for (int y = 0; y < h; y++) { final double yVh = y * vH; final int index = y * w; for (int x = 0; x < w; x++) { final int p = particleLabels[z][index + x]; if (p > 0) { final double xVw = x * vW; final double dx = xVw - centroids[p][0]; final double dy = yVh - centroids[p][1]; final double dz = zVd - centroids[p][2]; momentTensors[p][0] += dy * dy + dz * dz + voxVhVd; // Ixx momentTensors[p][1] += dx * dx + dz * dz + voxVwVd; // Iyy momentTensors[p][2] += dy * dy + dx * dx + voxVhVw; // Izz momentTensors[p][3] += dx * dy; // Ixy momentTensors[p][4] += dx * dz; // Ixz momentTensors[p][5] += dy * dz; // Iyz } } } for (int p = 1; p < nParticles; p++) { final double[][] inertiaTensor = new double[3][3]; inertiaTensor[0][0] = momentTensors[p][0]; inertiaTensor[1][1] = momentTensors[p][1]; inertiaTensor[2][2] = momentTensors[p][2]; inertiaTensor[0][1] = -momentTensors[p][3]; inertiaTensor[0][2] = -momentTensors[p][4]; inertiaTensor[1][0] = -momentTensors[p][3]; inertiaTensor[1][2] = -momentTensors[p][5]; inertiaTensor[2][0] = -momentTensors[p][4]; inertiaTensor[2][1] = -momentTensors[p][5]; final Matrix inertiaTensorMatrix = new Matrix(inertiaTensor); final EigenvalueDecomposition E = new EigenvalueDecomposition( inertiaTensorMatrix); eigens[p] = E; } } return eigens; } private static Object[][] getEllipsoids( final Collection<List<Point3f>> surfacePoints) { final Object[][] ellipsoids = new Object[surfacePoints.size()][]; int p = 0; for (final List<Point3f> points : surfacePoints) { if (points == null) { p++; continue; } final Iterator<Point3f> pointIter = points.iterator(); final double[][] coOrdinates = new double[points.size()][3]; int i = 0; while (pointIter.hasNext()) { final Point3f point = pointIter.next(); coOrdinates[i][0] = point.x; coOrdinates[i][1] = point.y; coOrdinates[i][2] = point.z; i++; } try { ellipsoids[p] = FitEllipsoid.yuryPetrov(coOrdinates); } catch (final RuntimeException re) { IJ.log("Could not fit ellipsoid to surface " + p); } p++; } return ellipsoids; } /** * Get the Euler characteristic of each particle * * @param imp an image. * @param particleLabels particles of the image. * @param limits limits of the particles. * @param nParticles number particles. * @return euler characteristic of each image. */ private double[][] getEulerCharacter(final ImagePlus imp, final int[][] particleLabels, final int[][] limits, final int nParticles) { final Connectivity con = new Connectivity(); final double[][] eulerCharacters = new double[nParticles][3]; for (int p = 1; p < nParticles; p++) { final ImagePlus particleImp = getBinaryParticle(p, imp, particleLabels, limits, 1); final double euler = con.getSumEuler(particleImp); final double cavities = getNCavities(particleImp); // Calculate number of holes and cavities using // Euler = particles - holes + cavities // where particles = 1 final double holes = cavities - euler + 1; final double[] bettis = { euler, holes, cavities }; eulerCharacters[p] = bettis; } return eulerCharacters; } /** * Get the Feret diameter of a surface. Uses an inefficient brute-force * algorithm. * * @param particleSurfaces points of all the particles. * @return Feret diameters of the surfaces. */ private static double[] getFerets( final List<List<Point3f>> particleSurfaces) { final int nParticles = particleSurfaces.size(); final double[] ferets = new double[nParticles]; final ListIterator<List<Point3f>> it = particleSurfaces.listIterator(); int i = 0; Point3f a; Point3f b; List<Point3f> surface; ListIterator<Point3f> ita; ListIterator<Point3f> itb; while (it.hasNext()) { IJ.showStatus("Finding Feret diameter..."); IJ.showProgress(it.nextIndex(), nParticles); surface = it.next(); if (surface == null) { ferets[i] = Double.NaN; i++; continue; } ita = surface.listIterator(); while (ita.hasNext()) { a = ita.next(); itb = surface.listIterator(ita.nextIndex()); while (itb.hasNext()) { b = itb.next(); ferets[i] = Math.max(ferets[i], a.distance(b)); } } i++; } return ferets; } /** * Get the mean and standard deviation of pixel values &gt;0 for each particle * in a particle label work array * * @param imp Input image containing pixel values * @param particleLabels workArray containing particle labels * @param particleSizes array of particle sizes as pixel counts * @return array containing mean, std dev and max pixel values for each * particle */ private static double[][] getMeanStdDev(final ImagePlus imp, final int[][] particleLabels, final long[] particleSizes) { final int nParticles = particleSizes.length; final int d = imp.getImageStackSize(); final int wh = imp.getWidth() * imp.getHeight(); final ImageStack stack = imp.getImageStack(); final double[] sums = new double[nParticles]; for (int z = 0; z < d; z++) { final float[] pixels = (float[]) stack.getPixels(z + 1); final int[] labelPixels = particleLabels[z]; for (int i = 0; i < wh; i++) { final double value = pixels[i]; if (value > 0) { sums[labelPixels[i]] += value; } } } final double[][] meanStdDev = new double[nParticles][3]; for (int p = 1; p < nParticles; p++) { meanStdDev[p][0] = sums[p] / particleSizes[p]; } final double[] sumSquares = new double[nParticles]; for (int z = 0; z < d; z++) { final float[] pixels = (float[]) stack.getPixels(z + 1); final int[] labelPixels = particleLabels[z]; for (int i = 0; i < wh; i++) { final double value = pixels[i]; if (value > 0) { final int p = labelPixels[i]; final double residual = value - meanStdDev[p][0]; sumSquares[p] += residual * residual; meanStdDev[p][2] = Math.max(meanStdDev[p][2], value); } } } for (int p = 1; p < nParticles; p++) { meanStdDev[p][1] = Math.sqrt(sumSquares[p] / particleSizes[p]); } return meanStdDev; } private int getNCavities(final ImagePlus imp) { final Object[] result = getParticles(imp, BACK); final long[] particleSizes = (long[]) result[2]; final int nParticles = particleSizes.length; return nParticles - 2; } /** * Find the offset within a 1D array given 2 (x, y) offset values * * @param m x difference * @param n y difference * @param w width of the stack. * @return Integer offset for looking up pixel in work array */ private static int getOffset(final int m, final int n, final int w) { return m + n * w; } /** * Get the minimum and maximum x, y and z coordinates of each particle * * @param imp ImagePlus (used for stack size) * @param particleLabels work array containing labelled particles * @param nParticles number of particles in the stack * @return int[][] containing x, y and z minima and maxima. */ private static int[][] getParticleLimits(final ImagePlus imp, final int[][] particleLabels, final int nParticles) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int[][] limits = new int[nParticles][6]; for (int i = 0; i < nParticles; i++) { limits[i][0] = Integer.MAX_VALUE; // x min limits[i][1] = 0; // x max limits[i][2] = Integer.MAX_VALUE; // y min limits[i][3] = 0; // y max limits[i][4] = Integer.MAX_VALUE; // z min limits[i][5] = 0; // z max } for (int z = 0; z < d; z++) { for (int y = 0; y < h; y++) { final int index = y * w; for (int x = 0; x < w; x++) { final int i = particleLabels[z][index + x]; limits[i][0] = Math.min(limits[i][0], x); limits[i][1] = Math.max(limits[i][1], x); limits[i][2] = Math.min(limits[i][2], y); limits[i][3] = Math.max(limits[i][3], y); limits[i][4] = Math.min(limits[i][4], z); limits[i][5] = Math.max(limits[i][5], z); } } } return limits; } private ArrayList<ArrayList<short[]>> getParticleLists( final int[][] particleLabels, final int nBlobs, final int w, final int h, final int d) { final ArrayList<ArrayList<short[]>> pL = new ArrayList<>(nBlobs); pL.add(new ArrayList<>()); final long[] particleSizes = getParticleSizes(particleLabels); for (int b = 1; b < nBlobs; b++) { pL.add(new ArrayList<>((int) particleSizes[b])); } // add all the particle coordinates to the appropriate list for (short z = 0; z < d; z++) { IJ.showStatus("Listing substructures..."); IJ.showProgress(z, d); final int[] sliceLabels = particleLabels[z]; for (short y = 0; y < h; y++) { final int i = y * w; for (short x = 0; x < w; x++) { final int p = sliceLabels[i + x]; if (p > 0) { // ignore background final short[] voxel = { x, y, z }; pL.get(p).add(voxel); } } } } return pL; } /** * Get particles, particle labels and particle sizes from a 3D ImagePlus * * @param imp Binary input image * @param slicesPerChunk number of slices per chunk. 2 is generally good. * @param minVol minimum volume particle to include * @param maxVol maximum volume particle to include * @param phase foreground or background (FORE or BACK) * @param doExclude if true, remove particles touching sides of the stack * @return Object[] {byte[][], int[][]} containing a binary workArray and * particle labels. */ private Object[] getParticles(final ImagePlus imp, final int slicesPerChunk, final double minVol, final double maxVol, final int phase, final boolean doExclude) { final byte[][] workArray = makeWorkArray(imp); return getParticles(imp, workArray, slicesPerChunk, minVol, maxVol, phase, doExclude); } private Object[] getParticles(final ImagePlus imp, final int phase) { final byte[][] workArray = makeWorkArray(imp); final double minVol = 0; final double maxVol = Double.POSITIVE_INFINITY; return getParticles(imp, workArray, 4, minVol, maxVol, phase, false); } /** * Get particles, particle labels and sizes from a workArray using an * ImagePlus for scale information * * @param imp input binary image * @param workArray work array * @param slicesPerChunk number of slices to use for each chunk * @param minVol minimum volume particle to include * @param maxVol maximum volume particle to include * @param phase FORE or BACK for foreground or background respectively * @param doExclude exclude particles touching the edges. * @return Object[] array containing a binary workArray, particle labels and * particle sizes */ private Object[] getParticles(final ImagePlus imp, final byte[][] workArray, final int slicesPerChunk, final double minVol, final double maxVol, final int phase, final boolean doExclude) { if (phase == FORE) { sPhase = "foreground"; } else if (phase == BACK) { sPhase = "background"; } else { throw new IllegalArgumentException(); } if (slicesPerChunk < 1) { throw new IllegalArgumentException(); } // Set up the chunks final int[][] particleLabels = firstIDAttribution(imp, workArray, phase); if (labelMethod == JOINING.MULTI) { // connect particles within chunks final int nChunks = getNChunks(imp, slicesPerChunk); final int nThreads = Runtime.getRuntime().availableProcessors(); final ConnectStructuresThread[] cptf = new ConnectStructuresThread[nThreads]; final int[][] chunkRanges = getChunkRanges(imp, nChunks, slicesPerChunk); for (int thread = 0; thread < nThreads; thread++) { cptf[thread] = new ConnectStructuresThread(thread, nThreads, imp, workArray, particleLabels, phase, nChunks, chunkRanges); cptf[thread].start(); } try { for (int thread = 0; thread < nThreads; thread++) { cptf[thread].join(); } } catch (final InterruptedException ie) { IJ.error("A thread was interrupted."); } // connect particles between chunks if (nChunks > 1) { chunkString = ": stitching..."; final int[][] stitchRanges = getStitchRanges(imp, nChunks, slicesPerChunk); connectStructures(imp, workArray, particleLabels, phase, stitchRanges); } } else if (labelMethod == JOINING.LINEAR) { joinStructures(imp, particleLabels, phase); } else if (labelMethod == JOINING.MAPPED) { final int nParticles = getParticleSizes(particleLabels).length; joinMappedStructures(imp, particleLabels, nParticles, phase); } filterParticles(imp, workArray, particleLabels, minVol, maxVol, phase); if (doExclude) excludeOnEdges(imp, particleLabels, workArray); minimiseLabels(particleLabels); final long[] particleSizes = getParticleSizes(particleLabels); return new Object[] { workArray, particleLabels, particleSizes }; } /** * Get pixel in 3D image (0 border conditions) * * @param image 3D image * @param x x- coordinate * @param y y- coordinate * @param z z- coordinate (in image stacks the indexes start at 1) * @param w width of the image. * @param h height of the image. * @param d depth of the image. * @return corresponding pixel (0 if out of image) */ private static int getPixel(final int[][] image, final int x, final int y, final int z, final int w, final int h, final int d) { if (withinBounds(x, y, z, w, h, d)) return image[z][x + y * w]; return 0; } /** * Return scan ranges for stitching. The first 2 values for each chunk are the * first slice of the next chunk and the last 2 values are the range through * which to replaceLabels() Running replace labels over incrementally * increasing volumes as chunks are added is OK (for 1st interface connect * chunks 0 & 1, for 2nd connect chunks 0, 1, 2, etc.) * * @param imp an image. * @param nC number of chunks * @param slicesPerChunk number of slices chunks process. * @return scanRanges list of scan limits for connectStructures() to stitch * chunks back together */ private static int[][] getStitchRanges(final ImagePlus imp, final int nC, final int slicesPerChunk) { final int nSlices = imp.getImageStackSize(); if (nC < 2) { return null; } final int[][] scanRanges = new int[4][3 * (nC - 1)]; // there are nC - 1 // interfaces for (int c = 0; c < nC - 1; c++) { scanRanges[0][c] = (c + 1) * slicesPerChunk; scanRanges[1][c] = (c + 1) * slicesPerChunk + 1; scanRanges[2][c] = c * slicesPerChunk; // forward and reverse // algorithm // hard scanRanges[3][c] = (c + 2) * slicesPerChunk; } // stitch back for (int c = nC - 1; c < 2 * (nC - 1); c++) { scanRanges[0][c] = (2 * nC - c - 2) * slicesPerChunk - 1; scanRanges[1][c] = (2 * nC - c - 2) * slicesPerChunk; scanRanges[2][c] = (2 * nC - c - 3) * slicesPerChunk; scanRanges[3][c] = (2 * nC - c - 1) * slicesPerChunk; } // stitch forwards (paranoid third pass) for (int c = 2 * (nC - 1); c < 3 * (nC - 1); c++) { scanRanges[0][c] = (-2 * nC + c + 3) * slicesPerChunk; scanRanges[1][c] = (-2 * nC + c + 3) * slicesPerChunk + 1; scanRanges[2][c] = (-2 * nC + c + 2) * slicesPerChunk; scanRanges[3][c] = (-2 * nC + c + 4) * slicesPerChunk; } for (int i = 0; i < scanRanges.length; i++) { for (int c = 0; c < scanRanges[i].length; c++) { if (scanRanges[i][c] > nSlices) { scanRanges[i][c] = nSlices; } } } scanRanges[3][nC - 2] = nSlices; return scanRanges; } /** * Calculate surface area of the isosurface * * @param points in 3D triangle mesh * @return surface area */ private static double getSurfaceArea(final List<Point3f> points) { if (points == null) { return 0; } double sumArea = 0; final int nPoints = points.size(); final Point3f origin = new Point3f(0.0f, 0.0f, 0.0f); for (int n = 0; n < nPoints; n += 3) { IJ.showStatus("Calculating surface area..."); final Point3f cp = crossProduct(points.get(n), points.get(n + 1), points .get(n + 2)); final double deltaArea = 0.5 * cp.distance(origin); sumArea += deltaArea; } return sumArea; } private static double[] getSurfaceAreas( final Collection<List<Point3f>> surfacePoints) { return surfacePoints.stream().mapToDouble(ParticleCounter::getSurfaceArea) .toArray(); } private static ArrayList<List<Point3f>> getSurfacePoints(final ImagePlus imp, final int[][] particleLabels, final int[][] limits, final int resampling, final int nParticles) { final Calibration cal = imp.getCalibration(); final ArrayList<List<Point3f>> surfacePoints = new ArrayList<>(); final boolean[] channels = { true, false, false }; for (int p = 0; p < nParticles; p++) { IJ.showStatus("Getting surface meshes..."); IJ.showProgress(p, nParticles); if (p > 0) { final ImagePlus binaryImp = getBinaryParticle(p, imp, particleLabels, limits, resampling); // noinspection TypeMayBeWeakened final MCTriangulator mct = new MCTriangulator(); @SuppressWarnings("unchecked") final List<Point3f> points = mct.getTriangles(binaryImp, 128, channels, resampling); final double xOffset = (limits[p][0] - 1) * cal.pixelWidth; final double yOffset = (limits[p][2] - 1) * cal.pixelHeight; final double zOffset = (limits[p][4] - 1) * cal.pixelDepth; for (final Point3f point : points) { point.x += xOffset; point.y += yOffset; point.z += zOffset; } surfacePoints.add(points); if (points.isEmpty()) { IJ.log("Particle " + p + " resulted in 0 surface points"); } } else { surfacePoints.add(null); } } return surfacePoints; } private static double[] getSurfaceVolume( final Collection<List<Point3f>> surfacePoints) { return surfacePoints.stream().mapToDouble(p -> { if (p == null) { return 0; } final CustomTriangleMesh mesh = new CustomTriangleMesh(p); return Math.abs(mesh.getVolume()); }).toArray(); } private static double[] getVolumes(final ImagePlus imp, final long[] particleSizes) { final Calibration cal = imp.getCalibration(); final double voxelVolume = cal.pixelWidth * cal.pixelHeight * cal.pixelDepth; final int nLabels = particleSizes.length; final double[] particleVolumes = new double[nLabels]; for (int i = 0; i < nLabels; i++) { particleVolumes[i] = voxelVolume * particleSizes[i]; } return particleVolumes; } private static boolean isRadiiValid(final double[] radii) { for (int r = 0; r < 3; r++) { if (Double.isNaN(radii[r])) { return false; } } return true; } /** * Join particle p to particle b, relabelling p with b. * * @param b a particle label. * @param p another particle label. * @param particleLabels array of particle labels * @param particleLists list of particle voxel coordinates * @param w stack width */ private static void joinBlobs(final int b, final int p, final int[][] particleLabels, final List<ArrayList<short[]>> particleLists, final int w) { for (final short[] voxelB : particleLists.get(p)) { particleLists.get(b).add(voxelB); final int iB = voxelB[1] * w + voxelB[0]; particleLabels[voxelB[2]][iB] = b; } particleLists.get(p).clear(); } private static void joinMappedStructures(final ImagePlus imp, final int[][] particleLabels, final int nParticles, final int phase) { IJ.showStatus("Mapping structures and joining..."); final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final ArrayList<HashSet<Integer>> map = new ArrayList<>(nParticles + 1); final int[] lut = new int[nParticles + 1]; // set each label to be its own root final int initialCapacity = 1; for (int i = 0; i < nParticles + 1; i++) { lut[i] = i; final HashSet<Integer> set = new HashSet<>(initialCapacity); set.add(i); map.add(set); } // populate the first list with neighbourhoods int[] nbh = null; if (phase == FORE) nbh = new int[26]; else if (phase == BACK) nbh = new int[6]; for (int z = 0; z < d; z++) { IJ.showStatus("Building neighbourhood list"); IJ.showProgress(z, d - 1); final int[] slice = particleLabels[z]; for (int y = 0; y < h; y++) { final int yw = y * w; for (int x = 0; x < w; x++) { final int centre = slice[yw + x]; // ignore background if (centre == 0) continue; if (phase == FORE) get26Neighborhood(nbh, particleLabels, x, y, z, w, h, d); else if (phase == BACK) get6Neighborhood(nbh, particleLabels, x, y, z, w, h, d); addNeighboursToMap(map, nbh, centre); } } } // map now contains for every value the set of first degree neighbours IJ.showStatus("Minimising list and generating LUT..."); // place to store counts of each label final int[] counter = new int[lut.length]; // place to map lut values and targets // lutList lists the indexes which point to each transformed lutvalue // for quick updating final ArrayList<HashSet<Integer>> lutList = new ArrayList<>(nParticles); // initialise the lutList for (int i = 0; i <= nParticles; i++) { lutList.add(new HashSet<>(2)); } // set it up. ArrayList index is now the transformed value // list contains the lut indices that have the transformed value for (int i = 1; i < nParticles; i++) { final HashSet<Integer> list = lutList.get(lut[i]); list.add(i); } // initialise LUT with minimal label in set updateLUTwithMinPosition(lut, map, lutList); // find the minimal position of each value findFirstAppearance(lut, map); // de-chain the lut array minimiseLutArray(lut); int duplicates = Integer.MAX_VALUE; boolean snowball = true; boolean merge = true; boolean update = true; boolean find = true; boolean minimise = true; boolean inconsistent = true; while ((duplicates > 0) && snowball && merge && update && find && minimise && inconsistent) { snowball = snowballLUT(lut, map, lutList); duplicates = countDuplicates(counter, map, lut); // merge duplicates merge = mergeDuplicates(map, counter, duplicates, lut, lutList); // update the LUT update = updateLUTwithMinPosition(lut, map, lutList); find = findFirstAppearance(lut, map); // minimise the LUT minimise = minimiseLutArray(lut); inconsistent = !checkConsistence(lut, map); } // replace all labels with LUT values applyLUT(particleLabels, lut, w, h, d); IJ.showStatus("LUT applied"); } /** * Joins semi-labelled particles using a non-recursive algorithm * * @param imp an image. * @param particleLabels particles in the image. * @param phase foreground or background */ private void joinStructures(final ImagePlus imp, final int[][] particleLabels, final int phase) { final int w = imp.getWidth(); final int h = imp.getHeight(); final int d = imp.getImageStackSize(); final int[] bounds = { w, h, d }; final long[] particleSizes = getParticleSizes(particleLabels); final int nBlobs = particleSizes.length; final ArrayList<ArrayList<short[]>> particleLists = getParticleLists( particleLabels, nBlobs, w, h, d); final BiFunction<int[], int[], List<int[]>> neighbourhoodFinder; if (phase == BACK) { neighbourhoodFinder = ParticleCounter::get6NeighbourhoodCoordinates; } else { neighbourhoodFinder = ParticleCounter::get26NeighbourhoodCoordinates; } for (int b = 1; b < nBlobs; b++) { IJ.showStatus("Joining substructures..."); IJ.showProgress(b, nBlobs); final ArrayList<short[]> blob = particleLists.get(b); if (blob.isEmpty()) { continue; } for (final short[] voxel : blob) { final int[] tmp = { voxel[0], voxel[1], voxel[2] }; final List<int[]> coordinates = neighbourhoodFinder.apply(tmp, bounds); for (final int[] coordinate : coordinates) { final int index = coordinate[1] * w + coordinate[0]; final int label = particleLabels[coordinate[2]][index]; if (label > b) { joinBlobs(b, label, particleLabels, particleLists, w); } } } } } /** * Create a work array * * @param imp an image. * @return byte[][] work array */ private static byte[][] makeWorkArray(final ImagePlus imp) { final int s = imp.getStackSize(); final int p = imp.getWidth() * imp.getHeight(); final byte[][] workArray = new byte[s][p]; final ImageStack stack = imp.getStack(); for (int z = 0; z < s; z++) { final ImageProcessor ip = stack.getProcessor(z + 1); for (int i = 0; i < p; i++) { workArray[z][i] = (byte) ip.get(i); } } return workArray; } private static boolean mergeDuplicates(final List<HashSet<Integer>> map, final int[] counter, final int duplicates, final int[] lut, final List<HashSet<Integer>> lutList) { boolean changed = false; // create a list of duplicate values to check for final int[] dupList = new int[duplicates]; final int l = counter.length; int dup = 0; for (int i = 1; i < l; i++) { if (counter[i] > 1) dupList[dup] = i; dup++; } // find duplicates hiding in sets which are greater than the lut for (int i = 1; i < l; i++) { final HashSet<Integer> set = map.get(i); if (set.isEmpty()) continue; for (final int d : dupList) { // if we are in the lut key of this value, continue final int lutValue = lut[d]; if (lutValue == i) continue; // otherwise check to see if the non-lut set contains our dup if (set.contains(d)) { // we found a dup, merge whole set back to lut changed = true; final Iterator<Integer> iter = set.iterator(); final HashSet<Integer> target = map.get(lutValue); while (iter.hasNext()) { final Integer val = iter.next(); target.add(val); lut[val] = lutValue; } // empty the set set.clear(); updateLUT(i, lutValue, lut, lutList); // move to the next set break; } } } return changed; } /** * Gets rid of redundant particle labels * * @param particleLabels particles in the image. */ private void minimiseLabels(final int[][] particleLabels) { IJ.showStatus("Minimising labels..."); final int d = particleLabels.length; final long[] particleSizes = getParticleSizes(particleLabels); final int nLabels = particleSizes.length; final int[] newLabel = new int[nLabels]; int minLabel = 0; // find the minimised labels for (int i = 0; i < nLabels; i++) { if (particleSizes[i] > 0) { if (i == minLabel) { newLabel[i] = i; minLabel++; continue; } newLabel[i] = minLabel; particleSizes[minLabel] = particleSizes[i]; particleSizes[i] = 0; minLabel++; } } // now replace labels final int wh = particleLabels[0].length; for (int z = 0; z < d; z++) { IJ.showStatus("Replacing with minimised labels..."); IJ.showProgress(z, d); final int[] slice = particleLabels[z]; for (int i = 0; i < wh; i++) { final int p = slice[i]; if (p > 0) { slice[i] = newLabel[p]; } } } } private static boolean minimiseLutArray(final int[] lutArray) { final int l = lutArray.length; boolean changed = false; for (int key = 1; key < l; key++) { final int value = lutArray[key]; // this is a root if (value == key) continue; // otherwise update the current key with the // value from the referred key final int minValue = lutArray[value]; lutArray[key] = minValue; changed = true; } return changed; } /** * Check whole array replacing m with n * * @param particleLabels particles labelled in the image. * @param m value to be replaced * @param n new value * @param startZ first z coordinate to check * @param endZ last+1 z coordinate to check */ private static void replaceLabel(final int[][] particleLabels, final int m, final int n, final int startZ, final int endZ) { final int s = particleLabels[0].length; for (int z = startZ; z < endZ; z++) { for (int i = 0; i < s; i++) if (particleLabels[z][i] == m) { particleLabels[z][i] = n; } } } private static void replaceLabelsWithMinimum( final Iterable<int[]> coordinates, final byte[][] workArray, final int[][] particleLabels, final int w, final int phase, final int minZ, final int maxZ) { final int minimumLabel = findMinimumLabel(coordinates, workArray, particleLabels, w, phase, 0); for (final int[] coordinate : coordinates) { final int vX = coordinate[0]; final int vY = coordinate[1]; final int vZ = coordinate[2]; final int offset = getOffset(vX, vY, w); if (workArray[vZ][offset] == phase) { final int label = particleLabels[vZ][offset]; if (label != 0 && label != minimumLabel) { replaceLabel(particleLabels, label, minimumLabel, minZ, maxZ); } } } } /** * Iterate backwards over map entries, moving set values to their new lut * positions in the map. Updates LUT value of shifted values * * @param lut a color look-up table. * @param map a map of LUT values. * @return false if nothing changed, true if something changed */ private static boolean snowballLUT(final int[] lut, final List<HashSet<Integer>> map, final List<HashSet<Integer>> lutList) { boolean changed = false; for (int i = lut.length - 1; i > 0; i IJ.showStatus("Snowballing labels..."); IJ.showProgress(lut.length - i + 1, lut.length); final int lutValue = lut[i]; if (lutValue < i) { changed = true; final HashSet<Integer> set = map.get(i); final HashSet<Integer> target = map.get(lutValue); for (final Integer n : set) { target.add(n); lut[n] = lutValue; } // set is made empty // if later tests come across empty sets, then // must look up the lut to find the new location of the // neighbour network set.clear(); // update lut so that anything pointing // to cleared set points to the new set updateLUT(i, lutValue, lut, lutList); } } return changed; } /** * Replace old value with new value in LUT using map * * @param oldValue a LUT value to be replaced. * @param newValue new value of the LUT value. * @param lut a look-up table. * @param lutlist hash of LUT values. */ private static void updateLUT(final int oldValue, final int newValue, final int[] lut, final List<HashSet<Integer>> lutlist) { final HashSet<Integer> list = lutlist.get(oldValue); final HashSet<Integer> newList = lutlist.get(newValue); for (final Integer in : list) { lut[in] = newValue; newList.add(in); } list.clear(); } private static boolean updateLUTwithMinPosition(final int[] lut, final List<HashSet<Integer>> map, final List<HashSet<Integer>> lutList) { final int l = lut.length; final boolean changed = false; for (int i = 1; i < l; i++) { final HashSet<Integer> set = map.get(i); if (set.isEmpty()) continue; // find minimal value or lut value in the set int min = Integer.MAX_VALUE; int minLut = Integer.MAX_VALUE; for (final Integer val : set) { min = Math.min(min, val); minLut = Math.min(minLut, lut[val]); } // min now contains the smaller of the neighbours or their LUT // values min = Math.min(min, minLut); // add minimal value to lut final HashSet<Integer> target = map.get(min); for (final Integer val : set) { target.add(val); if (lut[val] > min) lut[val] = min; } set.clear(); updateLUT(i, min, lut, lutList); } return changed; } private static boolean withinBounds(final int m, final int n, final int o, final int w, final int h, final int d) { return (m >= 0 && m < w && n >= 0 && n < h && o >= 0 && o < d); } /** Particle joining method */ public enum JOINING { MULTI, LINEAR, MAPPED } private final class ConnectStructuresThread extends Thread { private final ImagePlus imp; private final int thread; private final int nThreads; private final int nChunks; private final int phase; private final byte[][] workArray; private final int[][] particleLabels; private final int[][] chunkRanges; private ConnectStructuresThread(final int thread, final int nThreads, final ImagePlus imp, final byte[][] workArray, final int[][] particleLabels, final int phase, final int nChunks, final int[][] chunkRanges) { this.imp = imp; this.thread = thread; this.nThreads = nThreads; this.workArray = workArray; this.particleLabels = particleLabels; this.phase = phase; this.nChunks = nChunks; this.chunkRanges = chunkRanges; } @Override public void run() { for (int k = thread; k < nChunks; k += nThreads) { // assign singleChunkRange for chunk k from chunkRanges final int[][] singleChunkRange = new int[4][1]; for (int i = 0; i < 4; i++) { singleChunkRange[i][0] = chunkRanges[i][k]; } chunkString = ": chunk " + (k + 1) + "/" + nChunks; connectStructures(imp, workArray, particleLabels, phase, singleChunkRange); } } } Object[] getParticles(final ImagePlus imp, final int slicesPerChunk, final int phase) { final byte[][] workArray = makeWorkArray(imp); return getParticles(imp, workArray, slicesPerChunk, 0.0, Double.POSITIVE_INFINITY, phase, false); } Object[] getParticles(final ImagePlus imp, final byte[][] workArray, final int slicesPerChunk, final int phase) { return getParticles(imp, workArray, slicesPerChunk, 0.0, Double.POSITIVE_INFINITY, phase, false); } /** * Gets number of chunks needed to divide a stack into evenly-sized sets of * slices. * * @param imp input image * @param slicesPerChunk number of slices per chunk * @return number of chunks */ static int getNChunks(final ImagePlus imp, final int slicesPerChunk) { final double d = imp.getImageStackSize(); return (int) Math.ceil(d / slicesPerChunk); } /** * Get a 2 d array that defines the z-slices to scan within while connecting * particles within chunkified stacks. * * @param imp an image. * @param nC number of chunks * @param slicesPerChunk number of slices chunks process. * @return scanRanges int[][] containing 4 limits: int[0][] - start of outer * for; int[1][] end of outer for; int[3][] start of inner for; int[4] * end of inner 4. Second dimension is chunk number. */ static int[][] getChunkRanges(final ImagePlus imp, final int nC, final int slicesPerChunk) { final int nSlices = imp.getImageStackSize(); final int[][] scanRanges = new int[4][nC]; scanRanges[0][0] = 0; // the first chunk starts at the first (zeroth) // slice scanRanges[2][0] = 0; // and that is what replaceLabel() will work on // first if (nC == 1) { scanRanges[1][0] = nSlices; scanRanges[3][0] = nSlices; } else if (nC > 1) { scanRanges[1][0] = slicesPerChunk; scanRanges[3][0] = slicesPerChunk; for (int c = 1; c < nC; c++) { for (int i = 0; i < 4; i++) { scanRanges[i][c] = scanRanges[i][c - 1] + slicesPerChunk; } } // reduce the last chunk to nSlices scanRanges[1][nC - 1] = nSlices; scanRanges[3][nC - 1] = nSlices; } return scanRanges; } /** * Get the sizes of all the particles as a voxel count * * @param particleLabels particles in the image. * @return particleSizes sizes of the particles. */ long[] getParticleSizes(final int[][] particleLabels) { IJ.showStatus("Getting " + sPhase + " particle sizes"); final int d = particleLabels.length; final int wh = particleLabels[0].length; // find the highest value particleLabel int maxParticle = 0; for (final int[] slice : particleLabels) { for (int i = 0; i < wh; i++) { maxParticle = Math.max(maxParticle, slice[i]); } } final long[] particleSizes = new long[maxParticle + 1]; for (int z = 0; z < d; z++) { final int[] slice = particleLabels[z]; for (int i = 0; i < wh; i++) { particleSizes[slice[i]]++; } IJ.showProgress(z, d); } return particleSizes; } /** * Set the value of this instance's labelMethod field * * @param label one of ParticleCounter.MULTI or .LINEAR */ void setLabelMethod(final JOINING label) { labelMethod = label; } }
package jp.kshoji.driver.midi.device; import android.hardware.usb.UsbDevice; import android.hardware.usb.UsbDeviceConnection; import android.hardware.usb.UsbEndpoint; import android.hardware.usb.UsbInterface; import android.hardware.usb.UsbRequest; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.nio.ByteBuffer; import java.util.LinkedList; import java.util.Queue; import jp.kshoji.driver.midi.util.ReusableByteArrayOutputStream; import jp.kshoji.driver.midi.util.UsbMidiDeviceUtils; /** * MIDI Output Device * * @author K.Shoji */ public final class MidiOutputDevice { private final UsbDevice usbDevice; final UsbDeviceConnection usbDeviceConnection; private final UsbInterface usbInterface; final UsbEndpoint outputEndpoint; final WaiterThread waiterThread; private static final int BUFFER_POOL_SIZE = 1024; final LinkedList<byte[]> bufferPool = new LinkedList<>(); private ReusableByteArrayOutputStream sysexTransferDataStream = new ReusableByteArrayOutputStream(); /** * Constructor * * @param usbDevice the UsbDevice * @param usbDeviceConnection the UsbDeviceConnection * @param usbInterface the UsbInterface * @param usbEndpoint the UsbEndpoint */ public MidiOutputDevice(@NonNull UsbDevice usbDevice, @NonNull UsbDeviceConnection usbDeviceConnection, @NonNull UsbInterface usbInterface, @NonNull UsbEndpoint usbEndpoint) { this.usbDevice = usbDevice; this.usbDeviceConnection = usbDeviceConnection; this.usbInterface = usbInterface; waiterThread = new WaiterThread(); outputEndpoint = usbEndpoint; this.usbDeviceConnection.claimInterface(this.usbInterface, true); waiterThread.setName("MidiOutputDevice[" + usbDevice.getDeviceName() + "].WaiterThread"); waiterThread.start(); for (int i = 0; i < BUFFER_POOL_SIZE; i++) { bufferPool.addLast(new byte[4]); } } /** * stop to use this device. */ void stop() { usbDeviceConnection.releaseInterface(usbInterface); resume(); waiterThread.stopFlag = true; // blocks while the thread will stop while (waiterThread.isAlive()) { try { waiterThread.interrupt(); Thread.sleep(100); } catch (InterruptedException e) { // ignore } } } /** * Suspends event sending */ public void suspend() { waiterThread.suspendFlag = true; waiterThread.interrupt(); } /** * Resumes event sending */ public void resume() { waiterThread.suspendFlag = false; waiterThread.interrupt(); } /** * Get the product name * * @return the product name. null if API Level < {@link android.os.Build.VERSION_CODES#HONEYCOMB_MR2 }, or the product name is truly null */ @Nullable public String getProductName() { return UsbMidiDeviceUtils.getProductName(usbDevice, usbDeviceConnection); } /** * Get the manufacturer name * * @return the manufacturer name. null if API Level < {@link android.os.Build.VERSION_CODES#HONEYCOMB_MR2 }, or the manufacturer name is truly null */ @Nullable public String getManufacturerName() { return UsbMidiDeviceUtils.getManufacturerName(usbDevice, usbDeviceConnection); } /** * Get the device name(linux device path) * @return the device name(linux device path) */ @NonNull public String getDeviceAddress() { return usbDevice.getDeviceName(); } /** * @return the usbDevice */ @NonNull public UsbDevice getUsbDevice() { return usbDevice; } /** * @return the usbInterface */ @Deprecated @NonNull public UsbInterface getUsbInterface() { return usbInterface; } /** * @return the usbEndpoint */ @Deprecated @NonNull public UsbEndpoint getUsbEndpoint() { return outputEndpoint; } /** * Sending thread for output data. Loops infinitely while stopFlag == false. * * @author K.Shoji */ private final class WaiterThread extends Thread { final Queue<byte[]> queue = new LinkedList<byte[]>(); volatile boolean stopFlag; volatile boolean suspendFlag; private UsbRequest usbRequest; /** * Constructor */ WaiterThread() { stopFlag = false; suspendFlag = false; } @Override public void run() { byte[] dequedDataBuffer; int queueSize = 0; final int maxPacketSize = outputEndpoint.getMaxPacketSize(); byte[] endpointBuffer = new byte[maxPacketSize]; int endpointBufferLength = 0; int bufferPosition; int dequedDataBufferLength; int usbRequestFailCount; while (stopFlag == false) { dequedDataBuffer = null; synchronized (queue) { queueSize = queue.size(); if (queueSize > 0) { dequedDataBuffer = queue.poll(); } } if (suspendFlag) { try { // sleep until interrupted sleep(500); } catch (InterruptedException e) { // interrupted: event queued, or stopFlag/suspendFlag changed. } continue; } if (dequedDataBuffer != null) { dequedDataBufferLength = dequedDataBuffer.length; // usbRequest.queue() is not thread-safe synchronized (usbDeviceConnection) { if (usbRequest == null) { usbRequest = new UsbRequest(); usbRequest.initialize(usbDeviceConnection, outputEndpoint); } // usbRequest can't send data larger than maxPacketSize. split the data. for (bufferPosition = 0; bufferPosition < dequedDataBufferLength; bufferPosition += maxPacketSize) { if (bufferPosition + maxPacketSize > dequedDataBufferLength) { endpointBufferLength = dequedDataBufferLength % maxPacketSize; } else { endpointBufferLength = maxPacketSize; } System.arraycopy(dequedDataBuffer, bufferPosition, endpointBuffer, 0, endpointBufferLength); usbRequestFailCount = 0; // if device disconnected, usbRequest.queue returns false while (usbRequest.queue(ByteBuffer.wrap(endpointBuffer), endpointBufferLength) == false) { // loop until queue completed usbRequestFailCount++; if (usbRequestFailCount > 10) { // maybe disconnected stopFlag = true; break; } } if (stopFlag) { break; } usbRequestFailCount = 0; while (usbRequest.equals(usbDeviceConnection.requestWait()) == false) { // loop until result received usbRequestFailCount++; if (usbRequestFailCount > 10) { // maybe disconnected stopFlag = true; break; } } } } if (dequedDataBuffer.length == 4) { synchronized (queue) { bufferPool.addLast(dequedDataBuffer); } } } // no more data in queue, sleep. if (queueSize == 0 && !interrupted()) { try { // sleep until interrupted sleep(500); } catch (InterruptedException e) { // interrupted: event queued, or stopFlag changed. } } } if (usbRequest != null) { usbRequest.close(); } } } /** * Sends MIDI message to output device. * * @param codeIndexNumber Code Index Number(CIN) * @param cable the cable ID 0-15 * @param byte1 the first byte * @param byte2 the second byte * @param byte3 the third byte */ private void sendMidiMessage(int codeIndexNumber, int cable, int byte1, int byte2, int byte3) { while (bufferPool.isEmpty()) { try { Thread.sleep(10); } catch (InterruptedException ignored) { } } synchronized (waiterThread.queue) { byte[] writeBuffer = bufferPool.removeFirst(); writeBuffer[0] = (byte) (((cable & 0xf) << 4) | (codeIndexNumber & 0xf)); writeBuffer[1] = (byte) byte1; writeBuffer[2] = (byte) byte2; writeBuffer[3] = (byte) byte3; waiterThread.queue.add(writeBuffer); } // message has been queued, so interrupt the waiter thread waiterThread.interrupt(); } /** * Send a MIDI message with 3 bytes raw MIDI data * * @param cable the cable ID 0-15 * @param byte1 the first byte * @param byte2 the second byte: ignored when 1 byte message * @param byte3 the third byte: ignored when 1-2 byte message */ public void sendMidiMessage(int cable, int byte1, int byte2, int byte3) { int codeIndexNumber = 0; switch (byte1 & 0xf0) { case 0x80: // Note Off codeIndexNumber = 0x8; break; case 0x90: // Note On codeIndexNumber = 0x9; break; case 0xa0: // Poly Pressure codeIndexNumber = 0xa; break; case 0xb0: // Control Change codeIndexNumber = 0xb; break; case 0xc0: // Program Change codeIndexNumber = 0xc; break; case 0xd0: // Channel Pressure codeIndexNumber = 0xd; break; case 0xe0: // Pitch Bend codeIndexNumber = 0xe; break; case 0xf0: // SysEx with 3 bytes switch (byte1) { case 0xf0: // Start Of Exclusive if (byte2 == 0xf7) { // 2 byte SysEx(F0 F7) codeIndexNumber = 0x6; } else if (byte3 == 0xf7) { // 3 byte SysEx(F0 xx F7) codeIndexNumber = 0x7; } else { // ignored return; } break; case 0xf7: // End of Exclusive // ignored return; case 0xf4: // (Undefined MIDI System Common) case 0xf5: // (Undefined MIDI System Common / Bus Select?) case 0xf9: // (Undefined MIDI System Real-time) case 0xfd: // (Undefined MIDI System Real-time) // ignored return; case 0xf6: // Tune Request case 0xf8: // Timing Clock case 0xfa: // Start case 0xfb: // Continue case 0xfc: // Stop case 0xfe: // Active Sensing case 0xff: // System Reset // Single byte message codeIndexNumber = 0x5; break; case 0xf1: // MIDI Time Code case 0xf3: // Song Select // Two byte message codeIndexNumber = 0x2; break; case 0xf2: // Song Point Pointer // Three byte message codeIndexNumber = 0x3; break; default: break; } break; default: // ignored return; } sendMidiMessage(codeIndexNumber, cable, byte1, byte2, byte3); } /** * Miscellaneous function codes. Reserved for future extensions. Code Index Number : 0x0 * * @param cable the cable ID 0-15 * @param byte1 the first byte * @param byte2 the second byte * @param byte3 the third byte */ public void sendMidiMiscellaneousFunctionCodes(int cable, int byte1, int byte2, int byte3) { sendMidiMessage(0x0, cable, byte1, byte2, byte3); } /** * Cable events. Reserved for future expansion. Code Index Number : 0x1 * * @param cable the cable ID 0-15 * @param byte1 the first byte * @param byte2 the second byte * @param byte3 the third byte */ public void sendMidiCableEvents(int cable, int byte1, int byte2, int byte3) { sendMidiMessage(0x1, cable, byte1, byte2, byte3); } /** * System Common messages, or SysEx ends with following single byte. Code Index Number : 0x2 0x3 0x5 * * @param cable the cable ID 0-15 * @param bytes bytes.length:1, 2, or 3 */ public void sendMidiSystemCommonMessage(int cable, byte bytes[]) { if (bytes == null) { return; } switch (bytes.length) { case 1: sendMidiMessage(0x5, cable, bytes[0] & 0xff, 0, 0); break; case 2: sendMidiMessage(0x2, cable, bytes[0] & 0xff, bytes[1] & 0xff, 0); break; case 3: sendMidiMessage(0x3, cable, bytes[0] & 0xff, bytes[1] & 0xff, bytes[2] & 0xff); break; default: // do nothing. break; } } /** * SysEx Code Index Number : 0x4, 0x5, 0x6, 0x7 * * @param cable the cable ID 0-15 * @param systemExclusive : start with 'F0', and end with 'F7' */ public void sendMidiSystemExclusive(int cable, @NonNull byte[] systemExclusive) { if (systemExclusive.length > 3) { sysexTransferDataStream.reset(); for (int sysexIndex = 0; sysexIndex < systemExclusive.length; sysexIndex += 3) { if ((sysexIndex + 3 < systemExclusive.length)) { // sysex starts or continues... sysexTransferDataStream.write((((cable & 0xf) << 4) | 0x4)); sysexTransferDataStream.write(systemExclusive[sysexIndex] & 0xff); sysexTransferDataStream.write(systemExclusive[sysexIndex + 1] & 0xff); sysexTransferDataStream.write(systemExclusive[sysexIndex + 2] & 0xff); } else { switch (systemExclusive.length % 3) { case 1: // sysex end with 1 byte sysexTransferDataStream.write((((cable & 0xf) << 4) | 0x5)); sysexTransferDataStream.write(systemExclusive[sysexIndex] & 0xff); sysexTransferDataStream.write(0); sysexTransferDataStream.write(0); break; case 2: // sysex end with 2 bytes sysexTransferDataStream.write((((cable & 0xf) << 4) | 0x6)); sysexTransferDataStream.write(systemExclusive[sysexIndex] & 0xff); sysexTransferDataStream.write(systemExclusive[sysexIndex + 1] & 0xff); sysexTransferDataStream.write(0); break; case 0: // sysex end with 3 bytes sysexTransferDataStream.write((((cable & 0xf) << 4) | 0x7)); sysexTransferDataStream.write(systemExclusive[sysexIndex] & 0xff); sysexTransferDataStream.write(systemExclusive[sysexIndex + 1] & 0xff); sysexTransferDataStream.write(systemExclusive[sysexIndex + 2] & 0xff); break; default: break; } } } synchronized (waiterThread.queue) { // allocating new byte[] here... waiterThread.queue.add(sysexTransferDataStream.toByteArray()); } // message has been queued, so interrupt the waiter thread waiterThread.interrupt(); } else { switch (systemExclusive.length) { case 1: // sysex end with 1 byte sendMidiMessage(0x5, cable & 0xf, systemExclusive[0], 0, 0); break; case 2: // sysex end with 2 bytes sendMidiMessage(0x6, cable & 0xf, systemExclusive[0], systemExclusive[1], 0); break; case 3: // sysex end with 3 bytes sendMidiMessage(0x7, cable & 0xf, systemExclusive[0], systemExclusive[1], systemExclusive[2]); break; } } } /** * Note-off Code Index Number : 0x8 * * @param cable * 0-15 * @param channel * 0-15 * @param note * 0-127 * @param velocity * 0-127 */ public void sendMidiNoteOff(int cable, int channel, int note, int velocity) { sendMidiMessage(0x8, cable, 0x80 | (channel & 0xf), note, velocity); } /** * Note-on Code Index Number : 0x9 * * @param cable the cable ID 0-15 * @param channel the MIDI channel number 0-15 * @param note * 0-127 * @param velocity * 0-127 */ public void sendMidiNoteOn(int cable, int channel, int note, int velocity) { sendMidiMessage(0x9, cable, 0x90 | (channel & 0xf), note, velocity); } /** * Poly-KeyPress Code Index Number : 0xa * * @param cable the cable ID 0-15 * @param channel the MIDI channel number 0-15 * @param note * 0-127 * @param pressure * 0-127 */ public void sendMidiPolyphonicAftertouch(int cable, int channel, int note, int pressure) { sendMidiMessage(0xa, cable, 0xa0 | (channel & 0xf), note, pressure); } /** * Control Change Code Index Number : 0xb * * @param cable the cable ID 0-15 * @param channel the MIDI channel number 0-15 * @param function * 0-127 * @param value * 0-127 */ public void sendMidiControlChange(int cable, int channel, int function, int value) { sendMidiMessage(0xb, cable, 0xb0 | (channel & 0xf), function, value); } /** * Program Change Code Index Number : 0xc * * @param cable the cable ID 0-15 * @param channel the MIDI channel number 0-15 * @param program * 0-127 */ public void sendMidiProgramChange(int cable, int channel, int program) { sendMidiMessage(0xc, cable, 0xc0 | (channel & 0xf), program, 0); } /** * Channel Pressure Code Index Number : 0xd * * @param cable the cable ID 0-15 * @param channel the MIDI channel number 0-15 * @param pressure * 0-127 */ public void sendMidiChannelAftertouch(int cable, int channel, int pressure) { sendMidiMessage(0xd, cable, 0xd0 | (channel & 0xf), pressure, 0); } /** * PitchBend Change Code Index Number : 0xe * * @param cable the cable ID 0-15 * @param channel the MIDI channel number 0-15 * @param amount 0(low)-8192(center)-16383(high) */ public void sendMidiPitchWheel(int cable, int channel, int amount) { sendMidiMessage(0xe, cable, 0xe0 | (channel & 0xf), amount & 0x7f, (amount >> 7) & 0x7f); } /** * Single Byte Code Index Number : 0xf * * @param cable the cable ID 0-15 * @param byte1 the first byte */ public void sendMidiSingleByte(int cable, int byte1) { sendMidiMessage(0xf, cable, byte1, 0, 0); } /** * RPN message * * @param cable the cable ID 0-15 * @param channel the MIDI channel number 0-15 * @param function 14bits * @param value 7bits or 14bits */ public void sendRPNMessage(int cable, int channel, int function, int value) { sendRPNMessage(cable, channel, (function >> 7) & 0x7f, function & 0x7f, value); } /** * RPN message * * @param cable the cable ID 0-15 * @param channel the MIDI channel number 0-15 * @param functionMSB higher 7bits * @param functionLSB lower 7bits * @param value 7bits or 14bits */ public void sendRPNMessage(int cable, int channel, int functionMSB, int functionLSB, int value) { // send the function sendMidiControlChange(cable, channel, 101, functionMSB & 0x7f); sendMidiControlChange(cable, channel, 100, functionLSB & 0x7f); // send the value if ((value >> 7) > 0) { sendMidiControlChange(cable, channel, 6, (value >> 7) & 0x7f); sendMidiControlChange(cable, channel, 38, value & 0x7f); } else { sendMidiControlChange(cable, channel, 6, value & 0x7f); } // send the NULL function sendMidiControlChange(cable, channel, 101, 0x7f); sendMidiControlChange(cable, channel, 100, 0x7f); } /** * NRPN message * * @param cable the cable ID 0-15 * @param channel the MIDI channel number 0-15 * @param function 14bits * @param value 7bits or 14bits */ public void sendNRPNMessage(int cable, int channel, int function, int value) { sendNRPNMessage(cable, channel, (function >> 7) & 0x7f, function & 0x7f, value); } /** * NRPN message * * @param cable the cable ID 0-15 * @param channel the MIDI channel number 0-15 * @param functionMSB higher 7bits * @param functionLSB lower 7bits * @param value 7bits or 14bits */ public void sendNRPNMessage(int cable, int channel, int functionMSB, int functionLSB, int value) { // send the function sendMidiControlChange(cable, channel, 99, functionMSB & 0x7f); sendMidiControlChange(cable, channel, 98, functionLSB & 0x7f); // send the value if ((value >> 7) > 0) { sendMidiControlChange(cable, channel, 6, (value >> 7) & 0x7f); sendMidiControlChange(cable, channel, 38, value & 0x7f); } else { sendMidiControlChange(cable, channel, 6, value & 0x7f); } // send the NULL function sendMidiControlChange(cable, channel, 101, 0x7f); sendMidiControlChange(cable, channel, 100, 0x7f); } }
package org.voovan.network.nio; import org.voovan.Global; import org.voovan.network.SocketContext; import org.voovan.tools.log.Logger; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketOption; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.spi.SelectorProvider; public class NioServerSocket extends SocketContext{ private SelectorProvider provider; private Selector selector; private ServerSocketChannel serverSocketChannel; /** * * * @param host * @param port * @param readTimeout , : * @throws IOException */ public NioServerSocket(String host,int port,int readTimeout) throws IOException{ super(host, port, readTimeout); init(); } /** * * @param host * @param port * @param idleInterval , : * @param readTimeout , : * @throws IOException */ public NioServerSocket(String host,int port,int readTimeout, int idleInterval) throws IOException{ super(host, port, readTimeout, idleInterval); init(); } /** * * @throws IOException */ private void init() throws IOException{ provider = SelectorProvider.provider(); serverSocketChannel = provider.openServerSocketChannel(); serverSocketChannel.socket().setSoTimeout(this.readTimeout); serverSocketChannel.configureBlocking(false); selector = provider.openSelector(); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); serverSocketChannel.bind(new InetSocketAddress(host, port), 1000); } @Override public void setIdleInterval(int idleInterval) { this.idleInterval = idleInterval; } /** * Socket Option * * @param name SocketOption, :ServerSocketChannel.setOption * @param value SocketOption * @throws IOException IO */ public <T> void setOption(SocketOption<T> name, T value) throws IOException { serverSocketChannel.setOption(name, value); } /** * SocketChannel * @return SocketChannel */ public ServerSocketChannel socketChannel(){ return this.serverSocketChannel; } /** * * * @throws IOException IO */ @Override public void start() throws IOException { NioSelector eventListener = new NioSelector(selector,this); eventListener.eventChose(); } /** * * * @throws IOException IO */ @Override public void syncStart() throws IOException { Global.getThreadPool().execute(new Runnable(){ public void run() { try { start(); } catch (IOException e) { e.printStackTrace(); } } }); } @Override protected void acceptStart() throws IOException { throw new RuntimeException("Unsupport method"); } @Override public boolean isOpen() { if(serverSocketChannel!=null){ return serverSocketChannel.isOpen(); } return false; } @Override public boolean isConnected() { if(serverSocketChannel!=null){ return serverSocketChannel.isOpen(); }else{ return false; } } @Override public boolean close() { if(serverSocketChannel!=null && serverSocketChannel.isOpen()){ try{ serverSocketChannel.close(); return true; } catch(IOException e){ Logger.error("SocketChannel close failed",e); return false; } }else{ return true; } } }
package dk.aau.sw402F15.tests.typechecker; import dk.aau.sw402F15.TypeChecker.Exceptions.IllegalAssignment; import dk.aau.sw402F15.TypeChecker.Exceptions.IllegalComparison; import dk.aau.sw402F15.TypeChecker.TypeChecker; import dk.aau.sw402F15.parser.lexer.Lexer; import dk.aau.sw402F15.parser.lexer.LexerException; import dk.aau.sw402F15.parser.node.Start; import dk.aau.sw402F15.parser.parser.Parser; import dk.aau.sw402F15.parser.parser.ParserException; import org.junit.Test; import java.io.IOException; import java.io.PushbackReader; import java.io.StringReader; public class TypeCheckerTests { @Test public void checkIntDeclaration(){ checkCode("int i = 0;"); } @Test public void checkBoolDeclaration() { checkCode("bool b = true;"); } @Test public void checkDecimalDeclaration() { checkCode("float b = 1.1;"); } @Test(expected = IllegalAssignment.class) public void checkIntDeclarationSetToBool() { checkCode("int i = true;"); } @Test(expected = IllegalAssignment.class) public void checkIntDeclarationSetToDecimal() { checkCode("int i = 1.1;"); } @Test(expected = IllegalAssignment.class) public void checkBoolDeclarationSetToInt() { checkCode("bool b = 1;"); } @Test(expected = IllegalAssignment.class) public void checkBoolDeclarationSetToDecimal() { checkCode("bool b = 1.1;"); } @Test(expected = IllegalAssignment.class) public void checkDecimalSetToBool(){ checkCode("float f = true;"); } @Test(expected = IllegalAssignment.class) public void checkDecimalSetToInt(){ checkCode("float f = 1;"); } @Test public void checkIntIntComparisonGreater(){ checkCode("bool b = 1 > 2;"); } @Test public void checkIntIntComparisonGreaterOrEqual(){ checkCode("bool b = 1 >= 2;"); } @Test public void checkIntIntComparisonLess(){ checkCode("bool b = 1 < 2;"); } @Test public void checkIntIntComparisonLessOrEqual(){ checkCode("bool b = 1 <= 2;"); } @Test(expected = IllegalComparison.class) public void checkIntDecimalComparisonGreater(){ checkCode("bool b = 1 > 1.1;"); } @Test(expected = IllegalComparison.class) public void checkIntDecimalComparisonGreaterOrEqual(){ checkCode("bool b = 1 >= 1.1;"); } @Test(expected = IllegalComparison.class) public void checkIntDecimalComparisonLess(){ checkCode("bool b = 1 < 1.1;"); } @Test(expected = IllegalComparison.class) public void checkIntDecimalComparisonLessOrEqual(){ checkCode("bool b = 1 <= 1.1;"); } @Test(expected = IllegalComparison.class) public void checkIntBoolComparisonGreater(){ checkCode("bool b = 1 > true;"); } @Test(expected = IllegalComparison.class) public void checkIntBoolComparisonGreaterOrEqual(){ checkCode("bool b = 1 >= true;"); } @Test(expected = IllegalComparison.class) public void checkIntBoolComparisonLess(){ checkCode("bool b = 1 < true;"); } @Test(expected = IllegalComparison.class) public void checkIntBoolComparisonLessOrEqual(){ checkCode("bool b = 1 <= true;"); } @Test(expected = IllegalAssignment.class) public void checkAssignBoolExprToInt() { checkCode("int i = 7 < 8;"); } private void checkCode(String code) { Start node = null; try { node = getParser(code).parse(); } catch (ParserException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (LexerException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } // Apply typechecker node.apply(new TypeChecker()); } private Parser getParser(String code) { return new Parser(new Lexer(new PushbackReader(new StringReader(code), 1024))); } }
package com.blankj.bus; public class BusTest { // @Test // public void test() throws Exception { // String rootPath = "/Users/blankj/Repo/AndroidUtilCode/app/build/intermediates/transforms/busTransform/debug/43/"; // File root = new File(rootPath); // ClassPool mPool = new ClassPool(null); // mPool.appendSystemPath(); // mPool.appendClassPath(rootPath); // mPool.appendClassPath("/Users/blankj/Library/Android/sdk/platforms/android-27/android.jar"); // HashMap<String, String> busMap = new HashMap<>(); // if (root.isDirectory()) { // Collection<File> files = FileUtils.listFiles(root, new String[]{"class"}, true); // for (File file : files) { // String fileName = file.getName(); // String filePath = file.getCanonicalPath(); // String packagePath = filePath.replace(rootPath, ""); // String className = packagePath.replace(System.getProperty("file.separator"), "."); // // delete .class // className = className.substring(0, className.length() - 6); // CtClass ctClass = mPool.get(className); // CtMethod[] methods = ctClass.getDeclaredMethods(); // for (CtMethod method : methods) { // if (method.hasAnnotation(BusUtils.Subscribe.class)) { // String name = ((BusUtils.Subscribe) method.getAnnotation(BusUtils.Subscribe.class)).name(); // if (busMap.containsKey(name)) { // System.out.println("bus of " + name + " has registered." + method.getLongName()); // continue; // String longMethodName = method.getLongName(); // if (Modifier.isStatic(method.getModifiers())) { // String sign = method.getReturnType().getName() + ' ' + longMethodName; // busMap.put(name, sign); // } else {// may be is kotlin // processKt(mPool, busMap, method, name, longMethodName); // System.out.println(JsonUtils.getFormatJson(busMap)); // CtClass ctClass = mPool.makeClass("com.blankj.bus.BusUtils"); // String src = "" + // "public static Object post(String name, Object[] objects) {\n" + // " if (name == null || name.length() == 0) return null;\n" + // " return null;\n" + // CtMethod make = CtNewMethod.make(src, ctClass); // ctClass.addMethod(make); // make.insertAfter(getInsertContent(busMap)); // ctClass.debugWriteFile(); // private void processKt(ClassPool mPool, // HashMap<String, String> busMap, // CtMethod method, String name, // String longMethodName) throws NotFoundException { // CtClass innerClass = method.getDeclaringClass(); // try { // CtField instance = innerClass.getField("INSTANCE"); // System.out.println("find INSTANCE: " + name + ": " + longMethodName); // int i = longMethodName.lastIndexOf('('); // String temp = longMethodName.substring(0, i); // int j = temp.lastIndexOf('.'); // String sign = method.getReturnType().getName() + ' ' // + longMethodName.substring(0, j) // + ".INSTANCE" // + longMethodName.substring(j); // System.out.println(sign); // busMap.put(name, sign); // } catch (NotFoundException ignore) { // String innerClassSimpleName = innerClass.getSimpleName(); // if (innerClassSimpleName.contains("$") && !innerClassSimpleName.endsWith("$")) { // String innerClassName = innerClass.getName(); // String outerClassName = innerClassName.substring(0, innerClassName.lastIndexOf('$')); // CtClass outerClass = mPool.get(outerClassName); // try { // CtField ctField = outerClass.getField(innerClassSimpleName.substring(innerClassSimpleName.lastIndexOf('$') + 1)); // String fieldName = ctField.getName(); // String methodName = longMethodName.replace("$" + fieldName, "." + fieldName); // String sign = method.getReturnType().getName() + ' ' + methodName; // busMap.put(name, sign); // } catch (NotFoundException e) { // System.out.println(longMethodName + "is not static"); // } else { // System.out.println(longMethodName + "is not static"); // private static String getInsertContent(HashMap<String, String> bus) { // final StringBuilder sb = new StringBuilder(); // bus.forEach(new BiConsumer<String, String>() { // @Override // public void accept(String name, String sign) { // String[] method = sign.split(" "); // String returnType = method[0]; // String methodName = method[1]; // sb.append("if (\"").append(name).append("\".equals($1)) {\n"); // int st = methodName.indexOf('('); // int end = methodName.length(); // String params = methodName.substring(st + 1, end - 1); // if (!params.equals("")) { // String[] paramArr = params.split(","); // StringBuilder args = new StringBuilder(); // for (int i = 0; i < paramArr.length; i++) { // if (paramArr[i].equals("char")) { // args.append(",$2[").append(i).append("].toString().charAt(0)"); // } else if (paramArr[i].equals("boolean")) { // args.append(",Boolean.parseBoolean($2[").append(i).append("].toString())"); // } else if (paramArr[i].equals("byte")) { // args.append(",Byte.parseByte($2[").append(i).append("].toString())"); // } else if (paramArr[i].equals("short")) { // args.append(",Short.parseShort($2[").append(i).append("].toString())"); // } else if (paramArr[i].equals("int")) { // args.append(",Integer.parseInt($2[").append(i).append("].toString())"); // } else if (paramArr[i].equals("long")) { // args.append(",Long.parseLong($2[").append(i).append("].toString())"); // } else if (paramArr[i].equals("float")) { // args.append(",Float.parseFloat($2[").append(i).append("].toString())"); // } else if (paramArr[i].equals("double")) { // args.append(",Double.parseDouble($2[").append(i).append("].toString())"); // } else { // args.append(",(").append(paramArr[i]).append(")$2[").append(i).append("]"); // methodName = methodName.substring(0, st + 1) + args.substring(1) + ")"; // if (returnType.equals("void")) { // sb.append(methodName).append(";\n").append("return null;\n"); // } else { // sb.append("return ($w)").append(methodName).append(";\n"); // sb.append("}"); // return sb.toString(); }
package org.cytoscape.group.internal; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Set; import org.cytoscape.event.CyEventHelper; import org.cytoscape.group.CyGroup; import org.cytoscape.group.CyGroupManager; import org.cytoscape.group.events.GroupAboutToBeRemovedEvent; import org.cytoscape.group.events.GroupAddedToNetworkEvent; import org.cytoscape.group.events.GroupNodesAddedEvent; import org.cytoscape.group.events.GroupNodesRemovedEvent; import org.cytoscape.group.events.GroupEdgesAddedEvent; import org.cytoscape.group.events.GroupEdgesRemovedEvent; import org.cytoscape.group.events.GroupCollapsedEvent; import org.cytoscape.group.events.GroupAboutToCollapseEvent; import org.cytoscape.model.CyEdge; import org.cytoscape.model.CyColumn; import org.cytoscape.model.CyNetwork; import org.cytoscape.model.CyNode; import org.cytoscape.model.CyRow; import org.cytoscape.model.CyTable; import org.cytoscape.model.CyIdentifiable; import org.cytoscape.model.subnetwork.CyRootNetwork; import org.cytoscape.model.subnetwork.CySubNetwork; // TODO: Update attributes class CyGroupImpl implements CyGroup { final private static String CHILDREN_ATTR = "NumChildren"; final private static String DESCENDENTS_ATTR = "NumDescendents"; final private static String GROUP_COLLAPSED_ATTR = "__groupCollapsed"; final private static String ISMETA_EDGE_ATTR = "__isMetaEdge"; final private CyEventHelper cyEventHelper; final private CyGroupManager mgr; private CyNode groupNode; private Set<CyEdge> externalEdges; private Set<CyEdge> metaEdges; private CyRootNetwork rootNetwork = null; private Set<CyNetwork> networkSet = null; private Set<CyNetwork> collapseSet = null; private boolean nodeProvided = false; // We'll need this when we destroy ourselves CyGroupImpl(final CyEventHelper eventHelper, final CyGroupManager mgr, CyNetwork network, CyNode node, List<CyNode>nodes, List<CyEdge>edges) { this.cyEventHelper = eventHelper; this.mgr = mgr; this.rootNetwork = ((CySubNetwork)network).getRootNetwork(); if (node == null) this.groupNode = this.rootNetwork.addNode(); else { nodeProvided = true; this.groupNode = node; } this.externalEdges = new HashSet<CyEdge>(); this.metaEdges = new HashSet<CyEdge>(); this.networkSet = new HashSet<CyNetwork>(); this.collapseSet = new HashSet<CyNetwork>(); networkSet.add(rootNetwork); networkSet.add(network); if (nodes == null) nodes = new ArrayList<CyNode>(); Set<CyNode> nodeMap = new HashSet<CyNode>(nodes); if (edges != null) { List<CyEdge> intEdges = new ArrayList<CyEdge>(); // Remove those edges in the list that aren't attached to nodes in // the list. Otherwise, we'll wind up adding nodes to the group // that the user didn't request. for (CyEdge e: edges) { if (nodeMap.contains(e.getSource()) && nodeMap.contains(e.getTarget())) { intEdges.add(e); } else { externalEdges.add(e); } } edges = intEdges; } else if (edges == null) { // Create the edge lists edges = new ArrayList<CyEdge>(); // Get all of the edges and put them in the right lists for (CyNode n: nodes) { List<CyEdge> aEdges = network.getAdjacentEdgeList(n, CyEdge.Type.ANY); for (CyEdge e: aEdges) { if (nodeMap.contains(e.getSource()) && nodeMap.contains(e.getTarget())) { edges.add(e); } else { // This is an external edge, which means that we need to create // a corresponding meta-edge externalEdges.add(e); } } } } CySubNetwork np = (CySubNetwork)groupNode.getNetworkPointer(); // If we already have a network pointer and we didn't get // nodes or edges, and the network pointer points to the same // root network, then it may have been provided by the session loader if (np != null && nodeProvided && edges.size() == 0 && nodes.size() == 0 && np.getRootNetwork().equals(this.rootNetwork)) { CySubNetwork groupNet = np; // See if we're already collapsed if (getGroupCollapsedAttribute(network)) { // Yes, reflect it... collapseSet.add(network); } } else { // Create the subnetwork CySubNetwork groupNet = rootNetwork.addSubNetwork(nodes, edges); groupNode.setNetworkPointer(groupNet); } // Update our meta-edges updateMetaEdges(true); // Initialize our attributes updateCountAttributes(rootNetwork); setGroupCollapsedAttribute(network, false); } /** * @see org.cytoscape.group.CyGroup#getGroupNode() */ @Override public CyNode getGroupNode() { return groupNode; } /** * @see org.cytoscape.group.CyGroup#getNodeList() */ @Override public List<CyNode> getNodeList() { return getGroupNetwork().getNodeList(); } /** * @see org.cytoscape.group.CyGroup#getInternalEdgeList() */ @Override public List<CyEdge> getInternalEdgeList() { return getGroupNetwork().getEdgeList(); } /** * @see org.cytoscape.group.CyGroup#getExternalEdgeList() */ @Override public Set<CyEdge> getExternalEdgeList() { return externalEdges; } /** * @see org.cytoscape.group.CyGroup#getGroupNetwork() */ @Override public CySubNetwork getGroupNetwork() { return (CySubNetwork)groupNode.getNetworkPointer(); } /** * @see org.cytoscape.group.CyGroup#addNode() */ private synchronized void addNode(CyNode node) { if (!rootNetwork.containsNode(node)) throwIllegalArgumentException("Can only add a node in the same network tree"); getGroupNetwork().addNode(node); } /** * @see org.cytoscape.group.CyGroup#addInternalEdge() */ private synchronized void addInternalEdge(CyEdge edge) { if (!rootNetwork.containsEdge(edge)) throwIllegalArgumentException("Can only add an edge in the same network tree"); getGroupNetwork().addEdge(edge); } /** * @see org.cytoscape.group.CyGroup#addExternalEdge() */ protected synchronized void addExternalEdge(CyEdge edge) { if (!rootNetwork.containsEdge(edge)) throwIllegalArgumentException("Can only add an edge in the same network tree"); if (!externalEdges.contains(edge)) externalEdges.add(edge); } /** * @see org.cytoscape.group.CyGroup#addNodes() */ @Override public synchronized void addNodes(List<CyNode> nodes) { Set<CyEdge> edgeSet = new HashSet<CyEdge>(); for (CyNode n: nodes) { if (!rootNetwork.containsNode(n)) throwIllegalArgumentException("Can only add a node in the same network tree"); addNode(n); edgeSet.addAll(rootNetwork.getAdjacentEdgeList(n, CyEdge.Type.ANY)); } for (CyEdge e: edgeSet) { if (getGroupNetwork().containsNode(e.getSource()) && getGroupNetwork().containsNode(e.getTarget())) { addInternalEdge(e); } else { addExternalEdge(e); } } updateMetaEdges(false); for (CyNetwork net: collapseSet) { updateCountAttributes(net); } cyEventHelper.fireEvent(new GroupNodesAddedEvent(CyGroupImpl.this, nodes)); } /** * @see org.cytoscape.group.CyGroup#addEdges() */ @Override public synchronized void addEdges(List<CyEdge> edges) { for (CyEdge edge: edges) { CyNode source = edge.getSource(); CyNode target = edge.getTarget(); if(getGroupNetwork().containsNode(source) && getGroupNetwork().containsNode(target)) getGroupNetwork().addEdge(edge); else if (getGroupNetwork().containsNode(source) || getGroupNetwork().containsNode(target)) externalEdges.add(edge); else throwIllegalArgumentException("Attempted to add an edge that has no node in the group"); } cyEventHelper.fireEvent(new GroupEdgesAddedEvent(CyGroupImpl.this, edges)); } /** * @see org.cytoscape.group.CyGroup#removeNodes() */ @Override public synchronized void removeNodes(List<CyNode> nodes) { List<CyEdge> netEdges = new ArrayList<CyEdge>(); for (CyNode node: nodes) { List<CyEdge> edges = rootNetwork.getAdjacentEdgeList(node, CyEdge.Type.ANY); for (CyEdge edge: edges) { if (externalEdges.contains(edge)) externalEdges.remove(edge); else { netEdges.add(edge); } } } if (netEdges.size() > 0) getGroupNetwork().removeEdges(netEdges); getGroupNetwork().removeNodes(nodes); updateMetaEdges(false); for (CyNetwork net: collapseSet) { updateCountAttributes(net); } cyEventHelper.fireEvent(new GroupNodesRemovedEvent(CyGroupImpl.this, nodes)); } /** * @see org.cytoscape.group.CyGroup#removeEdges() */ @Override public synchronized void removeEdges(List<CyEdge> edges) { List<CyEdge> netEdges = new ArrayList<CyEdge>(); for (CyEdge edge: edges) { if (getGroupNetwork().containsEdge(edge)) netEdges.add(edge); else if (externalEdges.contains(edge)) externalEdges.remove(edge); else if (metaEdges.contains(edge)) metaEdges.remove(edge); } cyEventHelper.fireEvent(new GroupEdgesRemovedEvent(CyGroupImpl.this, edges)); } /** * @see org.cytoscape.group.CyGroup#getRootNetwork() */ @Override public CyRootNetwork getRootNetwork() { return this.rootNetwork; } /** * @see org.cytoscape.group.CyGroup#getNetworkSet() */ @Override public Set<CyNetwork> getNetworkSet() { return networkSet; } /** * @see org.cytoscape.group.CyGroup#isInNetwork() */ @Override public boolean isInNetwork(CyNetwork network) { return networkSet.contains(network); } /** * @see org.cytoscape.group.CyGroup#addGroupToNetwork() */ @Override public synchronized void addGroupToNetwork(CyNetwork network) { // First, we need to make sure this network is in the same // root network as the group node if (!inSameRoot(network)) throwIllegalArgumentException("Network not in same root network as group"); if(!networkSet.contains(network)) networkSet.add(network); // Notify cyEventHelper.fireEvent(new GroupAddedToNetworkEvent(CyGroupImpl.this, network)); } /** * @see org.cytoscape.group.CyGroup#removeGroupFromNetwork() */ @Override public synchronized void removeGroupFromNetwork(CyNetwork network) { // Notify cyEventHelper.fireEvent(new GroupAboutToBeRemovedEvent(CyGroupImpl.this, network)); if(networkSet.contains(network)) networkSet.remove(network); } /** * @see org.cytoscape.group.CyGroup#collapse() */ @Override public void collapse(CyNetwork net) { if (isCollapsed(net)) return; // Already collapsed if (!networkSet.contains(net)) return; // We're not in that network CySubNetwork subnet = (CySubNetwork) net; // First collapse any children that are groups for (CyNode node: getNodeList()) { // Is this a group? if (mgr.isGroup(node, net)) { // Yes, collapse it mgr.getGroup(node,net).collapse(net); } } // Now collapse ourselves cyEventHelper.fireEvent(new GroupAboutToCollapseEvent(CyGroupImpl.this, net, true)); // Remove all of the nodes from the target network subnet.removeNodes(getNodeList()); subnet.addNode(groupNode); // Add the group node and it's edges List<CyEdge> groupNodeEdges = rootNetwork.getAdjacentEdgeList(groupNode, CyEdge.Type.ANY); for (CyEdge e: groupNodeEdges) subnet.addEdge(e); Set<CyNode> memberNodes = new HashSet<CyNode>(getNodeList()); // Add the meta-edges for (CyEdge e: getMetaEdgeList()) { subnet.addEdge(e); } collapseSet.add(net); // Update attributes? setGroupCollapsedAttribute(net, true); updateCountAttributes(net); // OK, all done cyEventHelper.fireEvent(new GroupCollapsedEvent(CyGroupImpl.this, net, true)); } /** * @see org.cytoscape.group.CyGroup#expand() */ @Override public void expand(CyNetwork net) { if (!isCollapsed(net)) return; // Already expanded if (!networkSet.contains(net)) return; // We're not in that network cyEventHelper.fireEvent(new GroupAboutToCollapseEvent(CyGroupImpl.this, net, false)); CySubNetwork subnet = (CySubNetwork) net; // Expand it. // Remove the group node from the target network subnet.removeNodes(Collections.singletonList(groupNode)); // Add all of the member nodes and edges in for (CyNode n: getNodeList()) subnet.addNode(n); // Add all of the interior edges in for (CyEdge e: getInternalEdgeList()) subnet.addEdge(e); // Add all of the exterior edges in for (CyEdge e: getExternalEdgeList()) { // We need to be careful to only add the edge in // if both the edge and the target are available // since the target node might have been part of a // collapsed group if (subnet.containsNode(e.getSource()) && subnet.containsNode(e.getTarget())) { subnet.addEdge(e); } } collapseSet.remove(net); // Update attributes setGroupCollapsedAttribute(net, false); // Finish up cyEventHelper.fireEvent(new GroupCollapsedEvent(CyGroupImpl.this, net, false)); } /** * @see org.cytoscape.group.CyGroup#isCollapsed() */ @Override public boolean isCollapsed(CyNetwork net) { return collapseSet.contains(net); } /** * Destroy this group. This will destroy the subnetwork, all metaEdges, and * the group node (if we created it). This is meant to be called from the * CyGroupManager, only. */ public void destroyGroup() { for (CyNetwork net: networkSet) expand(net); // Destroy the subNetwork rootNetwork.removeSubNetwork(getGroupNetwork()); groupNode.setNetworkPointer(null); // Release all of our external edges externalEdges = null; // Remove all of our metaEdges from the root network rootNetwork.removeEdges(metaEdges); // If our group node was not provided, destroy it if (!nodeProvided && rootNetwork.containsNode(groupNode)) { rootNetwork.removeNodes(Collections.singletonList(groupNode)); } networkSet = null; collapseSet = null; } protected synchronized void addMetaEdge(CyEdge edge) { if (!metaEdges.contains(edge)) metaEdges.add(edge); } protected synchronized void removeMetaEdge(CyEdge edge) { if (!metaEdges.contains(edge)) metaEdges.remove(edge); } protected Set<CyEdge> getMetaEdgeList() { return metaEdges; } @Override public String toString() { return "Group suid: " + groupNode.getSUID() + " node: " + groupNode; } private boolean inSameRoot(CyNetwork network) { CyRootNetwork root = ((CySubNetwork) network).getRootNetwork(); if (!root.equals(rootNetwork)) return false; return true; } private void throwIllegalArgumentException(String message) { throw new IllegalArgumentException(message); } /** * This method is the central method for the creation and maintenance of a * meta-node. Essentially, it is responsible for creating all of the meta-edges * that connect this meta-node to external nodes. * * Basic approach: * for each external edge: * add a meta-edge to the parter * if the partner is a group and the group is in our network: * add ourselves to the group's outer edges list (recursively) * add ourselves to the partner's meta edge list * if the partner is in a group: * add ourselves to the group's meta edge list */ private void updateMetaEdges(boolean ignoreMetaEdges) { metaEdges = new HashSet<CyEdge>(); // We need to use a list iterator because we might need to add new // edges to our outer edge list and we want to add them to the // iterator to re-examine them ListIterator<CyEdge> iterator = (new ArrayList<CyEdge>(externalEdges)).listIterator(); while (iterator.hasNext()) { CyEdge edge = iterator.next(); CyNode node = getPartner(edge); if (ignoreMetaEdges && isMeta(edge)) { this.addMetaEdge(edge); continue; } // If the edge is already on our group node, don't create a metaedge for it if (edge.getSource() == groupNode || edge.getTarget() == groupNode) continue; // Create the meta-edge to the external node, but maintain the directionality // of the original edge CyEdge metaEdge = createMetaEdge(edge, node, groupNode); for (CyNetwork net: networkSet) { CyGroup metaPartner = mgr.getGroup(node, net); if (metaPartner != null) { // Recursively add links to the appropriate children addPartnerEdges(metaPartner, net); ((CyGroupImpl)metaPartner).addMetaEdge(metaEdge); } // Now, handle the case where the partner is a member of one or more groups List<CyGroup> nodeGroups = mgr.getGroupsForNode(node); if (nodeGroups != null && nodeGroups.size() > 0) { addPartnerMetaEdges(net, edge, node, metaEdge); } } } } protected int getDescendents(CyNetwork net) { int nDescendents = getGroupNetwork().getNodeCount(); for (CyNode node: getGroupNetwork().getNodeList()) { CyGroup group = mgr.getGroup(node, net); if (group != null) nDescendents += ((CyGroupImpl)group).getDescendents(net); } return nDescendents; } // Find the edge in our partner that links to us protected void addPartnerEdges(CyGroup metaPartner, CyNetwork net) { Set<CyEdge> partnerEdges = metaPartner.getExternalEdgeList(); Set<CyEdge> newEdges = new HashSet<CyEdge>(); for (CyEdge edge: partnerEdges) { CyNode source = edge.getSource(); CyNode target = edge.getTarget(); CyNode partner = null; boolean directed = edge.isDirected(); if (getGroupNetwork().containsNode(target)) { source = groupNode; partner = target; } else if (getGroupNetwork().containsNode(source)) { target = groupNode; partner = source; } else { continue; } // Create a new edge CyEdge newEdge = rootNetwork.addEdge(source, target, directed); newEdges.add(newEdge); externalEdges.add(edge); CyGroup partnerMeta = mgr.getGroup(partner, net); if (partnerMeta != null) addPartnerEdges(partnerMeta, net); metaEdges.add(newEdge); } for (CyEdge edge: newEdges) { ((CyGroupImpl)metaPartner).addExternalEdge(edge); } } private CyEdge createMetaEdge(CyEdge edge, CyNode node, CyNode groupNode) { CyEdge metaEdge = null; if (isIncoming(edge)) metaEdge = rootNetwork.addEdge(node, groupNode, edge.isDirected()); else metaEdge = rootNetwork.addEdge(groupNode, node, edge.isDirected()); // Add the name and mark this as a meta-edge String edgeName = rootNetwork.getRow(edge).get(CyNetwork.NAME, String.class); rootNetwork.getRow(metaEdge).set(CyNetwork.NAME, "meta-"+edgeName); createIfNecessary(metaEdge, CyNetwork.HIDDEN_ATTRS, ISMETA_EDGE_ATTR, Boolean.class); rootNetwork.getRow(metaEdge, CyNetwork.HIDDEN_ATTRS).set(ISMETA_EDGE_ATTR, Boolean.TRUE); return metaEdge; } private void addPartnerMetaEdges(CyNetwork net, CyEdge connectingEdge, CyNode partnerNode, CyEdge metaEdge) { for (CyGroup partnerGroup: mgr.getGroupsForNode(partnerNode)) { // Are we partners in this network? if (!partnerGroup.getNetworkSet().contains(net)) continue; CyEdge metaMetaEdge = null; CyGroupImpl partner = (CyGroupImpl)partnerGroup; if (isIncoming(connectingEdge)) { metaMetaEdge = createMetaEdge(connectingEdge, partnerGroup.getGroupNode(), this.groupNode); } else { metaMetaEdge = createMetaEdge(connectingEdge, this.groupNode, partnerGroup.getGroupNode()); } partner.addMetaEdge(metaMetaEdge); partner.addMetaEdge(metaEdge); // Now, get our partner's metaEdges and add any that point to our children for (CyEdge outerEdge: partner.getMetaEdgeList()) { if (isConnectingEdge(outerEdge)) addExternalEdge(outerEdge); } } } private boolean isMeta(CyEdge edge) { Boolean meta = rootNetwork.getRow(edge, CyNetwork.HIDDEN_ATTRS). get(ISMETA_EDGE_ATTR, Boolean.class, Boolean.FALSE); return meta.booleanValue(); } private boolean isConnectingEdge(CyEdge edge) { CyNode source = edge.getSource(); CyNode target = edge.getTarget(); if (getGroupNetwork().containsNode(source) || getGroupNetwork().containsNode(target)) return true; return false; } private boolean isIncoming(CyEdge edge) { CyNode source = edge.getSource(); if (source.equals(groupNode) || getGroupNetwork().containsNode(source)) return false; return true; } private CyNode getPartner(CyEdge edge) { CyNode source = edge.getSource(); CyNode target = edge.getTarget(); if (source.equals(groupNode) || getGroupNetwork().containsNode(source)) return target; return source; } private void createIfNecessary(CyIdentifiable entry, String tableName, String attribute, Class type) { CyTable table = rootNetwork.getRow(entry, tableName).getTable(); if (table.getColumn(attribute) == null) table.createColumn(attribute, type, false); return; } /** * Set the state attribute for this group. The problem is that a group might be in * different states in different networks, so this is a list of the form: * [network1:state,network2:state,...] */ private void setGroupCollapsedAttribute(CyNetwork net, boolean collapsed) { String netName = net.getDefaultNetworkTable().getRow(net.getSUID()).get(CyNetwork.NAME, String.class); if (netName == null) netName = "(null)"; // Handle the unnamed network CyRow groupRow = rootNetwork.getRow(groupNode, CyNetwork.HIDDEN_ATTRS); if (groupRow == null) return; CyTable hiddenTable = groupRow.getTable(); CyColumn stateColumn = hiddenTable.getColumn(GROUP_COLLAPSED_ATTR); List<String> newList = new ArrayList<String>(); if (stateColumn == null) { hiddenTable.createListColumn(GROUP_COLLAPSED_ATTR, String.class, true); } List<String> stateList = groupRow.getList(GROUP_COLLAPSED_ATTR, String.class); if (stateList == null) { newList.add(netName+":"+collapsed); } else { for (String s: stateList) { String[] tokens = s.split(":"); if (netName.equals(tokens[0])) { newList.add(netName+":"+collapsed); } else { newList.add(s); } } } groupRow.set(GROUP_COLLAPSED_ATTR, newList); return; } // This is public so we can call it from our session loaded events public boolean getGroupCollapsedAttribute(CyNetwork net) { String netName = net.getDefaultNetworkTable().getRow(net.getSUID()).get(net.NAME, String.class); if (netName == null) netName = "(null)"; CyRow groupRow = rootNetwork.getRow(groupNode, CyNetwork.HIDDEN_ATTRS); if (groupRow == null) return false; CyTable hiddenTable = groupRow.getTable(); CyColumn stateColumn = hiddenTable.getColumn(GROUP_COLLAPSED_ATTR); if (stateColumn == null) { return false; } List<String> stateList = groupRow.getList(GROUP_COLLAPSED_ATTR, String.class); for (String s: stateList) { String[] tokens = s.split(":"); if (netName.equals(tokens[0])) { return Boolean.valueOf(tokens[1]).booleanValue(); } } return false; } public void updateCountAttributes(CyNetwork net) { CyTable nodeTable = net.getDefaultNodeTable(); CyColumn childrenColumn = nodeTable.getColumn(CHILDREN_ATTR); if (childrenColumn == null) { nodeTable.createColumn(CHILDREN_ATTR, Integer.class, true); } if (!nodeTable.rowExists(groupNode.getSUID())) { // Shouldn't happen! return; } CyRow groupRow = nodeTable.getRow(groupNode.getSUID()); groupRow.set(CHILDREN_ATTR, getGroupNetwork().getNodeCount()); CyColumn descendentsColumn = nodeTable.getColumn(DESCENDENTS_ATTR); if (descendentsColumn == null) { nodeTable.createColumn(DESCENDENTS_ATTR, Integer.class, true); } int nDescendents = getGroupNetwork().getNodeCount(); for (CyNode node: getGroupNetwork().getNodeList()) { if (mgr.isGroup(node, rootNetwork)) { Integer d = nodeTable.getRow(node.getSUID()).get(DESCENDENTS_ATTR, Integer.class); if (d != null) nDescendents += d.intValue(); } } groupRow.set(DESCENDENTS_ATTR, nDescendents); } }
package hex.deeplearning; import hex.ConfusionMatrix; import hex.deeplearning.DeepLearningModel.DeepLearningParameters.ClassSamplingMethod; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import water.*; import water.fvec.Frame; import water.fvec.NFSFileVec; import water.fvec.Vec; import water.parser.ParseDataset; import water.rapids.Env; import water.rapids.Exec; import water.util.Log; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Random; import static hex.ConfusionMatrix.buildCM; import static hex.deeplearning.DeepLearningModel.DeepLearningParameters; public class DeepLearningProstateTest extends TestUtil { @BeforeClass() public static void setup() { stall_till_cloudsize(1); } @Test public void run() throws Exception { runFraction(0.0001f); } public void runFraction(float fraction) { long seed = 0xDECAF; Random rng = new Random(seed); String[] datasets = new String[2]; int[][] responses = new int[datasets.length][]; datasets[0] = "smalldata/logreg/prostate.csv"; responses[0] = new int[]{1,2,8}; //CAPSULE (binomial), AGE (regression), GLEASON (multi-class) datasets[1] = "smalldata/iris/iris.csv"; responses[1] = new int[]{4}; //Iris-type (multi-class) HashSet<Long> checkSums = new LinkedHashSet<>(); int testcount = 0; int count = 0; for (int i = 0; i < datasets.length; ++i) { final String dataset = datasets[i]; NFSFileVec nfs = NFSFileVec.make(find_test_file(dataset)); Frame frame = ParseDataset.parse(Key.make(), nfs._key); NFSFileVec vnfs = NFSFileVec.make(find_test_file(dataset)); Frame vframe = ParseDataset.parse(Key.make(), vnfs._key); Scope.enter(); try { for (int resp : responses[i]) { boolean classification = !(i == 0 && resp == 2); if (classification && !frame.vec(resp).isEnum()) { Scope.track(frame.replace(resp, frame.vec(resp).toEnum())._key); DKV.put(frame._key, frame); } for (DeepLearningParameters.Loss loss : new DeepLearningParameters.Loss[]{ DeepLearningParameters.Loss.CrossEntropy, DeepLearningParameters.Loss.Huber, DeepLearningParameters.Loss.Absolute, DeepLearningParameters.Loss.MeanSquare }) { if ( !classification && loss == DeepLearningParameters.Loss.CrossEntropy ) continue; for (boolean replicate : new boolean[]{ true, false, }) { for (boolean load_balance : new boolean[]{ true, false, }) { for (boolean shuffle : new boolean[]{ true, false, }) { for (boolean balance_classes : new boolean[]{ true, false, }) { for (ClassSamplingMethod csm : new ClassSamplingMethod[]{ ClassSamplingMethod.Stratified, ClassSamplingMethod.Uniform }) { for (int scoretraining : new int[]{ 200, 20, 0, }) { for (int scorevalidation : new int[]{ 200, 20, 0, }) { for (int vf : new int[]{ 0, //no validation 1, //same as source -1, //different validation frame }) { for (int n_folds : new int[]{ 0, }) { if (n_folds != 0 && vf != 0) continue; for (boolean keep_cv_splits : new boolean[]{false}) { //otherwise it leaks for (boolean override_with_best_model : new boolean[]{false, true}) { for (int train_samples_per_iteration : new int[]{ -2, //auto-tune -1, //N epochs per iteration 0, //1 epoch per iteration rng.nextInt(200), // <1 epoch per iteration 500, //>1 epoch per iteration }) { DeepLearningModel model1 = null, model2 = null, tmp_model = null; Key dest, dest_tmp; count++; if (fraction < rng.nextFloat()) continue; try { Scope.enter(); Log.info("**************************)"); Log.info("Starting test #" + count); Log.info("**************************)"); final double epochs = 7 + rng.nextDouble() + rng.nextInt(4); final int[] hidden = new int[]{1 + rng.nextInt(4), 1 + rng.nextInt(6)}; Frame valid = null; //no validation if (vf == 1) valid = frame; //use the same frame for validation else if (vf == -1) valid = vframe; //different validation frame (here: from the same file) // build the model, with all kinds of shuffling/rebalancing/sampling { Log.info("Using seed: " + seed); DeepLearningParameters p = new DeepLearningParameters(); p._destination_key = Key.make(Key.make().toString() + "first"); dest_tmp = p._destination_key; p._checkpoint = null; p._train = frame._key; p._response_column = frame._names[resp]; p._valid = valid==null ? null : valid._key; p._hidden = hidden; // p.best_model_key = best_model_key; p._override_with_best_model = override_with_best_model; p._epochs = epochs; p._loss = loss; if (n_folds > 0) { H2O.unimpl(); // p._n_folds = n_folds; } p._keep_cross_validation_splits = keep_cv_splits; p._seed = seed; p._train_samples_per_iteration = train_samples_per_iteration; p._force_load_balance = load_balance; p._replicate_training_data = replicate; p._shuffle_training_data = shuffle; p._score_training_samples = scoretraining; p._score_validation_samples = scorevalidation; p._classification_stop = -1; p._regression_stop = -1; p._balance_classes = classification && balance_classes; p._quiet_mode = true; p._score_validation_sampling = csm; // Log.info(new String(p.writeJSON(new AutoBuffer()).buf()).replace(",","\n")); DeepLearning dl = new DeepLearning(p); try { model1 = dl.trainModel().get(); checkSums.add(model1.checksum()); } catch (Throwable t) { throw t; } finally { dl.remove(); } Log.info("Trained for " + model1.epoch_counter + " epochs."); assert( ((p._train_samples_per_iteration <= 0 || p._train_samples_per_iteration >= frame.numRows()) && model1.epoch_counter > epochs) || Math.abs(model1.epoch_counter - epochs)/epochs < 0.20 ); if (n_folds != 0) // test HTML of cv models { throw H2O.unimpl(); // for (Key k : model1.get_params().xval_models) { // DeepLearningModel cv_model = UKV.get(k); // StringBuilder sb = new StringBuilder(); // cv_model.generateHTML("cv", sb); // cv_model.delete(); } } // Do some more training via checkpoint restart // For n_folds, continue without n_folds (not yet implemented) - from now on, model2 will have n_folds=0... DeepLearningParameters p = new DeepLearningParameters(); tmp_model = DKV.get(dest_tmp).get(); //this actually *requires* frame to also still be in UKV (because of DataInfo...) Assert.assertTrue(tmp_model.model_info().get_processed_total() >= frame.numRows() * epochs); assert (tmp_model != null); p._destination_key = Key.make(); dest = p._destination_key; p._checkpoint = dest_tmp; // p._n_folds = 0; p._valid = valid == null ? null : valid._key; p._response_column = frame._names[resp]; p._override_with_best_model = override_with_best_model; p._epochs = epochs; p._loss = loss; p._seed = seed; p._train_samples_per_iteration = train_samples_per_iteration; p._balance_classes = classification && balance_classes; p._train = frame._key; DeepLearning dl = new DeepLearning(p); try { model1 = dl.trainModel().get(); } catch (Throwable t) { throw t; } finally { dl.remove(); } // score and check result (on full data) model2 = DKV.get(dest).get(); //this actually *requires* frame to also still be in DKV (because of DataInfo...) if (valid == null) valid = frame; double threshold = 0; if (model2._output.isClassifier()) { Frame pred = null, pred2 = null; try { pred = model2.score(valid); // Build a POJO, validate same results Assert.assertTrue(model2.testJavaScoring(valid,pred,1e-2)); hex.ModelMetrics mm = hex.ModelMetrics.getFromDKV(model2, valid); double error = 0; // binary if (model2._output.nclasses() == 2) { assert (resp == 1); threshold = mm.auc().defaultThreshold(); error = mm.auc().defaultErr(); // check that auc.cm() is the right CM Assert.assertEquals(new ConfusionMatrix(mm.auc().defaultCM(), new String[]{"0", "1"}).err(), error, 1e-15); // check that calcError() is consistent as well (for CM=null, AUC!=null) Assert.assertEquals(mm.cm().err(), error, 1e-15); } // confirm that orig CM was made with threshold 0.5 // put pred2 into DKV, and allow access pred2 = new Frame(Key.make("pred2"), pred.names(), pred.vecs()); pred2.delete_and_lock(null); pred2.unlock(null); if (model2._output.nclasses() == 2) { // manually make labels with AUC-given threshold for best F1 String ast = "(= ([ %pred2 \"null\" #0) (G ([ %pred2 \"null\" #2) #"+threshold+"))"; Env ev = Exec.exec(ast); try { pred2 = ev.popAry(); // pop0 pops w/o lowering refs, let remove_and_unlock handle cleanup } finally { if (ev != null) ev.remove_and_unlock(); } double threshErr2 = buildCM(valid.vecs()[resp].toEnum(), pred2.vecs()[0].toEnum()).err(); Assert.assertEquals(threshErr2, error, 1e-15); } } finally { if (pred != null) pred.delete(); if (pred2 != null) pred2.delete(); } } //classifier else { Frame pred = model2.score(valid); // Build a POJO, validate same results Assert.assertTrue(model1.testJavaScoring(frame,pred,1e-2)); pred.delete(); } Log.info("Parameters combination " + count + ": PASS"); testcount++; } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } finally { if (model1 != null) { model1.delete_xval_models(); model1.delete(); } if (model2 != null) { model2.delete_xval_models(); model2.delete(); } if (tmp_model != null) { tmp_model.delete_xval_models(); tmp_model.delete(); } Scope.exit(); } } } } } } } } } } } } } } } } finally { frame.delete(); vframe.delete(); Scope.exit(); } } Assert.assertTrue(checkSums.size() == testcount); Log.info("\n\n============================================="); Log.info("Tested " + testcount + " out of " + count + " parameter combinations."); Log.info("============================================="); } public static class Mid extends DeepLearningProstateTest { @Test @Ignore public void run() throws Exception { runFraction(0.01f); } //for nightly tests } public static class Short extends DeepLearningProstateTest { @Test @Ignore public void run() throws Exception { runFraction(0.001f); } } }
package io.github.ihongs.serv.matrix; import io.github.ihongs.Cnst; import io.github.ihongs.Core; import io.github.ihongs.HongsException; import io.github.ihongs.HongsExemption; import io.github.ihongs.action.ActionHelper; import io.github.ihongs.action.FormSet; import io.github.ihongs.db.DB; import io.github.ihongs.db.Model; import io.github.ihongs.db.Table; import io.github.ihongs.dh.search.SearchEntity; import io.github.ihongs.dh.lucene.field.*; import io.github.ihongs.util.Dict; import io.github.ihongs.util.Synt; import io.github.ihongs.util.Tool; import java.io.File; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.index.Term; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.BooleanClause; /** * * * : * add,set,put,del , ; * save(String,Map) , . * * @author Hongs */ public class Data extends SearchEntity { public static final String PART_ID_KEY = "pt"; protected final String conf ; protected final String form ; private String userId = null; private Set<String> nmCols = null; private Set<String> wdCols = null; private Set<String> skCols = null; protected Set<String> dcUrls = new LinkedHashSet(); /** * * @param conf * @param form */ protected Data(String conf, String form) { super(null, null, null); this.conf = conf; this.form = form; } /** * * Core * @param conf * @param form * @return */ public static Data getInstance(String conf, String form) { Data inst; Core core = Core.getInstance(); String name = Data.class.getName() +":"+ conf +":"+ form; if (core.containsKey(name)) { inst = (Data) core.got(name); } else { inst = new Data (conf, form); core.put ( name, inst ); } return inst; } /** * * , * , * NullPointerException * @return */ protected final Map gotFields() { return super . getFields(); } /** * * , * , * NullPointerException * @return */ protected final Map gotParams() { return super . getParams(); } /** * * . * @return */ @Override public Map getParams() { try { return gotParams(); } catch (NullPointerException ex) { getFields(); return gotParams(); } } /** * * , * , * 0x1104 * @return */ @Override public Map getFields() { try { return gotFields(); } catch (NullPointerException ex) { } /** * centra/data * centre/data * * * */ Map fields = null; Map fieldx = null; String cnf = conf; do { try { fields = FormSet.getInstance(cnf).getForm(form); } catch (HongsException ex) { if (ex.getErrno() != 0x10e8 && ex.getErrno() != 0x10ea) { throw ex.toExemption(); } break; } if (fields != null && cnf.startsWith("centre/")) { cnf = "centra/" + cnf.substring (7); } else { break; } try { fieldx = FormSet.getInstance(cnf).getForm(form); } catch (HongsException ex) { if (ex.getErrno() != 0x10e8 && ex.getErrno() != 0x10ea) { throw ex.toExemption(); } break; } fieldx = new LinkedHashMap(fieldx); fieldx.putAll(fields); fields = fieldx ; } while ( false ); if ( null == fields) { throw new HongsExemption(0x1104, "Data form conf '" + conf + "' is not exists") .setLocalizedOptions(conf); } setFields(fields); return fields ; } public Model getModel() throws HongsException { String tn = Synt.declare(getParams().get("db-table"), "matrix.data"); if ("".equals(tn) || "none".equals(tn)) { return null; } return DB.getInstance("matrix").getModel(tn); } public Table getTable() throws HongsException { String tn = Synt.declare(getParams().get("db-table"), "matrix.data"); if ("".equals(tn) || "none".equals(tn)) { return null; } return DB.getInstance("matrix").getTable(tn); } @Override public String getDbPath() { String path = conf.replaceFirst("^(centre|centra)/" , "") +"/"+ form; path = Synt.declare(getParams().get("db-path"),path); Map m = new HashMap(); m.put("SERVER_ID", Core.SERVER_ID); m.put("CORE_PATH", Core.CORE_PATH); m.put("DATA_PATH", Core.DATA_PATH); path = Tool.inject(path, m); if ( ! new File(path).isAbsolute()) path = Core.DATA_PATH + "/lucene/" + path; return path; } @Override public String getDbName() { String name = conf.replaceFirst("^(centre|centra)/" , "") +"/"+ form; return Synt.declare(getParams().get("db-name"),name); } public String getFormId() { return Synt.declare(getParams().get("form_id"),form); } public String getPartId() { return Synt.declare(getParams().get("part_id"), String.class ); } public String getUserId() { if ( null == userId ) { try { userId = (String) ActionHelper.getInstance() . getSessibute(Cnst.UID_SES); } catch (UnsupportedOperationException e ) { throw new NullPointerException("Call setUserId first"); } if ( null == userId ) { throw new NullPointerException("Call setUserId first"); } } return userId; } public void setUserId(String cuId) { userId = cuId; } /** * * @param rd * @return id,name(listable) * @throws HongsException */ @Override public Map create(Map rd) throws HongsException { long ct = System.currentTimeMillis() / 1000 ; String id = Core.newIdentity(); save ( ct , id , rd ); call ( ct , id , "create" ); Set<String> fs = getListable(); if (null != fs && ! fs.isEmpty( )) { Map sd = new LinkedHashMap( ); for(String fn : fs) { if ( ! fn.contains( "." )) { sd.put( fn, rd.get(fn) ); } } sd.put(Cnst.ID_KEY, id); return sd; } else { rd.put(Cnst.ID_KEY, id); return rd; } } /** * * @param rd * @return * @throws HongsException */ @Override public int update(Map rd) throws HongsException { int cn = 0; long ct = System.currentTimeMillis() / 1000 ; Set<String> ids = Synt.declare(rd.get(Cnst.ID_KEY), new HashSet()); permit (rd, ids , 0x1096); for(String id : ids) { cn += save(ct, id, rd); call(ct, id, "update"); } return cn; } /** * * @param rd * @return * @throws HongsException */ @Override public int delete(Map rd) throws HongsException { int cn = 0; long ct = System.currentTimeMillis() / 1000 ; Set<String> ids = Synt.declare(rd.get(Cnst.ID_KEY), new HashSet()); permit (rd, ids , 0x1097); for(String id : ids) { cn += drop(ct, id, rd); call(ct, id, "delete"); } return cn; } /** * * @param rd * @return * @throws HongsException */ public int revert(Map rd) throws HongsException { long ct = System.currentTimeMillis() / 1000 ; String id = ( String ) rd.get( Cnst.ID_KEY ); permit(rd , Synt.setOf(id), 0x1096 ); int cn = redo(ct, id, rd); call(ct, id, "revert"); return cn; } /** * * * : * , * . * * @param id * @param rd * @return * @throws HongsException */ public int save(String id, Map rd) throws HongsException { /** * * set * md */ if (id == null || id.length() == 0) { throw new NullPointerException("Id must be set in set"); } Document doc = getDoc(id); if (doc != null) { Map md = padDat(doc ); md . putAll( rd ); rd = md; } rd.put(Cnst.ID_KEY , id ); setDoc( id , padDoc (rd)); Table table = getTable( ); if (table == null) return 1 ; String fid = getFormId(); String uid = getUserId(); Object[] param = new String[] {id, fid, "0"}; String where = "`id`=? AND `form_id`=? AND `etime`=?"; Map ud = table.fetchCase() .filter( where,param ) .select( Cnst.ID_KEY ) .getOne( ); if (ud == null || ud.isEmpty()) { ud = new HashMap ( ); ud.put( "id", id ); ud.put("form_id", fid); ud.put("user_id", uid); ud.put("state", 1 ); ud.put("etime", 0 ); ud.put("ctime", System.currentTimeMillis() / 1000 ); } String nm; nm = io.github.ihongs.util.Data.toString(rd, true); ud.put("data", nm); nm = Synt.asString(rd.get("name")); if (nm != null && !nm.isEmpty()) { nm = substr(nm, Synt.defxult((Integer) ((Map) table.getFields().get("name")).get("size"), 255)); ud.put("name", nm); } nm = Synt.asString(rd.get("memo")); if (nm != null && !nm.isEmpty()) { nm = substr(nm, Synt.defxult((Integer) ((Map) table.getFields().get("memo")).get("size"), 255)); ud.put("memo", nm); } if (ud.containsKey("etime")) { return table.insert(ud); } else { return table.update(ud, where, param); } } /** * * @param ctime * @param id * @param rd * @return 1, 0 * @throws HongsException */ public int save(long ctime, String id, Map rd) throws HongsException { Table table = getTable( ); String fid = getFormId(); String uid = getUserId(); Object[] param = new String[] {id, fid, "0"}; String where = "`id`=? AND `form_id`=? AND `etime`=?"; int st ; Map dd = get( id ); if (! dd.isEmpty() ) { st = 2; if (table != null) { Map od = table.fetchCase( ) .filter( where, param ) .select("ctime, state") .getOne( ); if (! od.isEmpty()) { if ( Synt.declare ( od.get("state"), 0 ) == 0 ) { throw new HongsException(0x1104, ""); } if ( Synt.declare ( od.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } } } } else { st = 1; if (table != null) { Map od = table.fetchCase( ) .filter( where, param ) .select("ctime, state, data") .getOne( ); if (! od.isEmpty()) { if ( Synt.declare ( od.get("state"), 0 ) == 0 ) { throw new HongsException(0x1104, ""); } if ( Synt.declare ( od.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } dd = (Map) io.github.ihongs.util.Data.toObject(od.get("data").toString()); st = 2; } } } int i = 0; Map<String,Map> fields = getFields(); for(String fn : fields . keySet( ) ) { if ( "id". equals(fn)) { dd.put(fn , id); } else if (rd.containsKey(fn)) { Object fr = rd.get(fn); Object fo = dd.get(fn); dd.put(fn , fr); if (! canSkip (fn, fr, fo) ) { i ++; } } } if (i == 0) { return 0; } / if (table != null) { Map ud = new HashMap(); ud.put("etime", ctime); Map nd = new HashMap(); nd.put("ctime", ctime); nd.put("etime", 0 ); nd.put("state", st ); nd.put("id", id ); nd.put("form_id", fid); nd.put("user_id", uid); String nm; nm = io.github.ihongs.util.Data.toString(rd, true); ud.put("data", nm); nm = Synt.asString(dd.get("name")); if (nm != null && !nm.isEmpty()) { nm = substr(nm, Synt.defxult((Integer) ((Map) table.getFields().get("name")).get("size"), 255)); ud.put("name", nm); } nm = Synt.asString(rd.get("memo")); if (nm != null && !nm.isEmpty()) { nm = substr(nm, Synt.defxult((Integer) ((Map) table.getFields().get("memo")).get("size"), 255)); ud.put("memo", nm); } table.update(ud, where, param); table.insert(nd); } / Document doc = new Document(); dd.put(Cnst.ID_KEY, id); padDoc(doc, dd , null ); setDoc(id, doc); return 1; } /** * * @param ctime * @param id * @param rd * @return 1, 0 * @throws HongsException */ public int drop(long ctime, String id, Map rd) throws HongsException { Table table = getTable( ); String fid = getFormId(); String uid = getUserId(); Object[] param = new String[] {id, fid, "0"}; String where = "`id`=? AND `form_id`=? AND `etime`=?"; if (table != null) { Map dd = table.fetchCase() .filter( where, param) .select("ctime, state, name, data") .getOne( ); if (dd.isEmpty()) { delDoc( id ); return 0; // throw new HongsException(0x1104, ""); } if ( Synt.declare ( dd.get("state"), 0 ) == 0 ) { delDoc( id ); return 0; // throw new HongsException(0x1100, ""); } if ( Synt.declare ( dd.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } Map ud = new HashMap(); ud.put("etime", ctime); Map nd = new HashMap(); nd.put("ctime", ctime); nd.put("etime", 0 ); nd.put("state", 0 ); nd.put("id", id ); nd.put("form_id", fid); nd.put("user_id", uid); nd.put("memo", rd.get("memo")); nd.put("name", dd.get("name")); nd.put("data", dd.get("data")); table.update(ud, where, param); table.insert(nd); } / delDoc(id); return 1; } /** * * @param ctime * @param id * @param rd * @return 1, 0 * @throws HongsException */ public int redo(long ctime, String id, Map rd) throws HongsException { Table table = getTable( ); String fid = getFormId(); String uid = getUserId(); long rtime = Synt.declare (rd.get("rtime"), 0L); Object[] param = new String[] {id, fid, "0" }; String where = "`id`=? AND `form_id`=? AND `etime`=?"; Object[] para2 = new Object[] {id, fid,rtime}; String wher2 = "`id`=? AND `form_id`=? AND `ctime`=?"; / if (table == null) { throw new HongsException(0x1100, ""); } Map ld = table.fetchCase() .filter( where, param) .select("ctime") .getOne( ); if ( Synt.declare ( ld.get("ctime"), 0L ) >= ctime ) { throw new HongsException(0x1100, ", "); } Map dd = table.fetchCase() .filter( wher2, para2) .getOne( ); if (dd.isEmpty()) { throw new HongsException(0x1100, ""); } if ( Synt.declare ( dd.get("state"), 0 ) != 0 ) { if ( Synt.declare ( dd.get("etime"), 0L ) == 0L ) { throw new HongsException(0x1100, ""); }} / Map ud = new HashMap(); ud.put("etime", ctime); dd.put("ctime", ctime); dd.put("rtime", rtime); dd.put("etime", 0 ); dd.put("state", 3 ); dd.put("form_id", fid); dd.put("user_id", uid); dd.put("memo" , rd.get("memo")); table.update(ud , where, param); table.insert(dd); / dd = (Map) io.github.ihongs.util.Data.toObject(dd.get("data").toString()); Document doc = new Document( ); dd.put(Cnst.ID_KEY, id); padDoc(doc, dd , null ); setDoc(id, doc); return 1; } /** * * @param xtime * @param id * @param on * @return 1, 0 * @throws HongsException */ public int call(long xtime, String id, String on) throws HongsException { String url = (String) getParams().get("callback"); if (url == null || "".equals(url)) { return 0; } String fid = getFormId(); dcUrls.add(Tool.inject(url, Synt.mapOf( "form_id", fid, "id" , id , "type" , on , "time" , xtime ))); return 1 ; } @Override public void close() { super . close(); try { DataCaller dc = DataCaller.getInstance(); for(String du : dcUrls) { dc.add(du); } } catch (HongsException e ) { throw e.toExemption ( ); } finally { dcUrls.clear(); } } @Override public Query getQuery(Map rd) throws HongsException { Query q = super.getQuery(rd); String pd = getPartId(); if (null != pd) { Query p = new TermQuery( new Term("@" + PART_ID_KEY, pd) ); BooleanQuery.Builder b = new BooleanQuery.Builder(); b.add(p, BooleanClause.Occur.MUST); b.add(q, BooleanClause.Occur.MUST); q = b.build(); } return q; } @Override protected void padDoc(Document doc, Map map, Set rep) { if (rep != null && rep.isEmpty( )) { rep = null; } String pd = getPartId(); if (null != pd) { doc.add(new StringField("@" + PART_ID_KEY, pd, Field.Store.NO)); } Map<String, Map> fields = getFields(); for(Map.Entry<String, Map> e : fields.entrySet()) { Map m = e.getValue(); String k = e.getKey (); Object v = Dict.getParam(map , k); doc.removeFields(k); if (rep != null && !rep.contains(k)) { continue; } /** * : * * 2019/03/23 * */ if (k != null) switch (k) { case "name": if (Synt.declare(m.get("readonly"), false)) { v = getName(map); } break; case "word": if (Synt.declare(m.get("readonly"), false)) { v = getWord(map); } break; } if (v == null || k == null || k.equals("@") || unstated( m )) { continue; } IField f ; String t = datatype(m); boolean r = repeated(m); boolean s = sortable(m); boolean p = srchable(m); boolean q = findable(m); boolean g =!unstored(m); if (Cnst.ID_KEY.equals(k)) { q = true; g = true; } if (t != null) switch (t) { case "int": if ("".equals(v)) continue; f = new IntField(); p = false; break; case "long": if ("".equals(v)) continue; f = new LongField(); p = false; break; case "float": if ("".equals(v)) continue; f = new FloatField(); p = false; break; case "double": if ("".equals(v)) continue; f = new DoubleField(); p = false; break; case "date": if ("".equals(v)) continue; f = new LongField(); p = false; break; case "sorted": if ("".equals(v)) continue; f = new LongField(); s = true ; g = false; p = false; q = false; break; case "stored": f = new StringFiald(); g = true ; p = false; q = false; s = false; break; case "object": if ("".equals(v)) continue; f = new ObjectFiald(); g = true ; p = false; q = false; s = false; break; case "search": f = new StringFiald(); p = true ; g = false; q = false; s = false; break; default: f = new StringFiald(); } else { f = new StringFiald(); } /** * : * textview * */ Object x = v; if (p && "textview".equals(m.get("__type__"))) { x = Tool.stripEnds( Tool.stripTags( Tool.stripCros( Synt.asString ( x ) )) ); } if (r) { if (g) { if (v instanceof Object [ ]) { for (Object w: (Object [ ]) v) { doc.add(f.get(k, w)); } } else if (v instanceof Collection) { for (Object w: (Collection) v) { doc.add(f.get(k, w)); } } else { Set a = Synt.asSet ( v ); for (Object w: a ) { doc.add(f.get(k, w)); } v = a; } } Set a = Synt.asSet(v); if (s && a != null && !a.isEmpty()) { Object w = a.toArray( )[0]; doc.add(f.odr(k, w)); } if (q && a != null && !a.isEmpty()) { for (Object w: a) { doc.add(f.whr(k, w)); } } if (p && a != null && !a.isEmpty()) { for (Object w: a) { doc.add(f.wdr(k, w)); } } } else { if (g) { doc.add(f.get(k, v)); } if (s) { doc.add(f.odr(k, v)); } if (q) { doc.add(f.whr(k, v)); } if (p) { doc.add(f.wdr(k, x)); } } } } /** * * true , * true . * @param fn * @param fr * @param fo * @return */ protected boolean canSkip(String fn, Object fr, Object fo) { if (getSkipable().contains(fn)) { return true ; } if (fr == null && fo == null) { return true ; } if (fr == null || fo == null) { return false; } // JSON if (fr instanceof Map || fr instanceof Collection || fr instanceof Object [ ]) { fr = io.github.ihongs.util.Data.toString(fr, true); fo = io.github.ihongs.util.Data.toString(fo, true); } return fr.equals(fo); } /** * * @param dd * @return */ protected String getName(Map dd) { StringBuilder nn = new StringBuilder(); Set < String> ns = getNameable( ); for ( String fn : ns ) { Object fv = dd.get(fn); if (fv == null) continue ; if (fv instanceof Collection) for (Object fw : (Collection) fv ) { nn.append(fw).append(' '); } else { nn.append(fv).append(' '); } } String nm = nn.toString().trim( ); if (! ns.contains("name") && 99 < nm.length( ) ) { return nm.substring(0, 99) + "..."; } else { return nm; } } /** * * @param dd * @return */ protected String getWord(Map dd) { StringBuilder nn = new StringBuilder(); Set < String> ns = getWordable( ); for ( String fn : ns ) { Object fv = dd.get(fn); if (fv == null) continue ; if (fv instanceof Collection) for (Object fw : (Collection) fv ) { nn.append(fw).append(' '); } else { nn.append(fv).append(' '); } } String nm = nn.toString().trim( ); if (! ns.contains("word") && ! ns.contains("id") ) { return dd.get("id") +" "+ nm ; } else { return nm; } } /** * * @param t * @return */ @Override public Set<String> getCaseTypes(String t) { if ("_wordable".equals(t)) { return Synt.setOf("string", "search", "text", "textarea", "textview"); } else if ("_nameable".equals(t)) { return Synt.setOf("string", "search", "text"); } else { return super.getCaseTypes(t); } } @Override public Set<String> getWordable() { if (null != wdCols) { return wdCols; } Map fs = (Map) getFields().get("word"); if (fs != null && !Synt.declare(fs.get("readonly"), false)) { wdCols = Synt.setOf("word"); } else { wdCols = getCaseNames( "wordable"); if (wdCols.isEmpty()) { wdCols = getCaseNames("_wordable"); } wdCols.remove("word"); } return wdCols; } // @Override public Set<String> getNameable() { if (null != nmCols) { return nmCols; } Map fs = (Map) getFields().get("name"); if (fs != null && !Synt.declare(fs.get("readonly"), false)) { nmCols = Synt.setOf("name"); } else { nmCols = getCaseNames( "nameable"); if (nmCols.isEmpty()) { nmCols = getCaseNames("_nameable"); } nmCols.remove("name"); } return nmCols; } // @Override public Set<String> getSkipable() { if (null != skCols) { return skCols; } skCols = new HashSet(getCaseNames("skipable")); skCols.add("mtime"); skCols.add("muser"); skCols.add("memo" ); return skCols; } /** * * @see io.github.ihongs.db.Table.checkMainValues * @return */ private static String substr(String str, int len) { int l = 0, i , c; for(i = 0; i < str.length(); i ++) { c = Character.codePointAt(str, i); if (c >= 0 && c <= 255) { l += 1; } else { l += 2; } if (l > len) { str = str.substring( 0, i - 1 ); break ; } } return str; } }
package com.morihacky.android.icobutton; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; import android.util.AttributeSet; import android.util.StateSet; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.morihacky.android.icobutton.core.IcoButtonViewHelper; import static com.morihacky.android.icobutton.core.IcoButtonViewHelper.ICON_ALIGN_LEFT_OF_TEXT; public class IcoButton extends ViewGroup { public static final String HOLO_BLUE = "#ff0099cc"; public static final String WHITE = "#ffffff"; private final Context _context; private AttributeSet _attributes; private View _btn; private TextView _btnText; private ImageView _btnIcon; private IcoButtonViewHelper _icoViewHelper; private int _hpadding; private int _spacingBtwIconAndText; public IcoButton(Context context) { super(context); _context = context; _initializeView(); } public IcoButton(Context context, AttributeSet attributes) { super(context, attributes); _context = context; _attributes = attributes; _initializeView(); } public IcoButton(Context context, AttributeSet attributes, int defStyle) { super(context, attributes, defStyle); _context = context; _attributes = attributes; _initializeView(); } // public API public void setText(String text) { _btnText.setText(text); } public void setIcon(Drawable icon) { _btnIcon.setImageDrawable(icon); } // Custom ViewGroup implementation /** * This method helps the app understand the precise dimensions of this view * including any child views. * * This is done by: * 1. specifying dimensions of each child view (measureChild) * 2. calculating the overall dimensions by adding up the child view dimensions + padding (as Android expects every individual view to control its padding) * 3. setting the overall dimensions (setMeasureDimension) * * @param widthMeasureSpec packed data that gives us two attributes(mode & size) for the width of this whole view * @param heightMeasureSpec packed data that gives us two attributes(mode & size) for the height of this whole view */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { _checkForNestedXmlViews(); // measureChild measures the view thus allowing us to get individual heights/widths from the children measureChild(_btnIcon, widthMeasureSpec, heightMeasureSpec); measureChild(_btnText, widthMeasureSpec, heightMeasureSpec); int totalWidth; int mode = MeasureSpec.getMode(widthMeasureSpec); switch (mode) { case MeasureSpec.EXACTLY: totalWidth = MeasureSpec.getSize(widthMeasureSpec); break; default: totalWidth = 2 * _hpadding + _spacingBtwIconAndText + _btnIcon.getMeasuredWidth() + _btnText.getMeasuredWidth(); } final int totalHeight = Math.max(_btnIcon.getMeasuredHeight(), _btnText.getMeasuredHeight()) + getPaddingTop() + getPaddingBottom(); setMeasuredDimension(totalWidth, totalHeight); } /** * This method helps the app understand how to layout each child in the view * given the dimensions from {@link #onMeasure(int, int)} */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (changed) { _icoViewHelper.setTotalWidth(getMeasuredWidth()); _icoViewHelper.setTotalHeight(getMeasuredHeight()); _icoViewHelper.setIcoWidth(_btnIcon.getMeasuredWidth()); _icoViewHelper.setTextHeight(_btnText.getMeasuredHeight()); } _icoViewHelper.setTextWidth(_btnText.getMeasuredWidth()); _btnIcon.layout(_icoViewHelper.getLeftForIcon(), _icoViewHelper.getTopForIcon(), _icoViewHelper.getRightForIcon(), _icoViewHelper.getBottomForIcon()); _btnText.layout(_icoViewHelper.getLeftForText(), _icoViewHelper.getTopForText(), _icoViewHelper.getRightForText(), _icoViewHelper.getBottomForText()); } /** * The default is true and is only required if your container is scrollable */ @Override public boolean shouldDelayChildPressedState() { return false; } // private helpers private void _checkForNestedXmlViews() { // No nested views if (getChildCount() == 2) { return; } // More than 2 nested views if (getChildCount() > 4) { throw new IllegalArgumentException("We already have an EditText, can only have one"); } View firstView = getChildAt(2); if (!(firstView instanceof TextView) && !(firstView instanceof ImageView)) { throw new IllegalArgumentException("Only TextView and ImageView supported"); } if (firstView instanceof TextView) { _btnText = (TextView) firstView; } else { _btnIcon = (ImageView) firstView; } if (getChildCount() == 3) { return; } View secondView = getChildAt(3); if (!(secondView instanceof TextView) && !(secondView instanceof ImageView)) { throw new IllegalArgumentException("Only TextView and ImageView supported"); } if (secondView instanceof TextView) { _btnText = (TextView) secondView; } else { _btnIcon = (ImageView) secondView; } } private void _initializeView() { if (_context == null) { return; } _btn = LayoutInflater.from(_context) .inflate(R.layout.com_morihacky_android_icobutton, this, true); _btnText = (TextView) findViewById(R.id.com_morihacky_android_icobutton_text); _btnIcon = (ImageView) findViewById(R.id.com_morihacky_android_icobutton_icon); _setupView(); } private void _setupView() { TypedArray xmlAttrs = _context.obtainStyledAttributes(_attributes, R.styleable.IcoButton); if (xmlAttrs == null) { return; } _icoViewHelper = new IcoButtonViewHelper(); _setupButton(xmlAttrs); _setupButtonText(xmlAttrs); _setupButtonIcon(xmlAttrs); xmlAttrs.recycle(); } private void _setupButton(TypedArray xmlAttrs) { _btn.setClickable(true); int color = xmlAttrs.getColor(R.styleable.IcoButton_color, Color.parseColor(HOLO_BLUE)); _btn.setBackgroundDrawable(_getStateListDrawableForButtonColor(color, true)); _icoViewHelper.setIcoAlign(xmlAttrs.getInt(R.styleable.IcoButton_iconAlign, ICON_ALIGN_LEFT_OF_TEXT)); _hpadding = xmlAttrs.getDimensionPixelSize(R.styleable.IcoButton_hpadding, _convertDpToPixels(10)); _icoViewHelper.setHorizontalPadding(_hpadding); int vpadding = xmlAttrs.getDimensionPixelSize(R.styleable.IcoButton_vpadding, _convertDpToPixels(10)); _btn.setPadding(_hpadding, vpadding, _hpadding, vpadding); _spacingBtwIconAndText = xmlAttrs.getDimensionPixelSize(R.styleable.IcoButton_spacingBtwIcoAndTxt, 10); _icoViewHelper.setSpacingBtwIconAndText(_spacingBtwIconAndText); } private void _setupButtonText(TypedArray xmlAttrs) { boolean allCaps = xmlAttrs.getBoolean(R.styleable.IcoButton_txtAllCaps, false); String btnText = xmlAttrs.getString(R.styleable.IcoButton_txt); if (allCaps) { btnText = btnText.toUpperCase(); } _btnText.setText(btnText); _btnText.setTextColor(xmlAttrs.getColor(R.styleable.IcoButton_txtColor, Color.parseColor(WHITE))); _btnText.setTextSize(TypedValue.COMPLEX_UNIT_PX, xmlAttrs.getDimensionPixelSize(R.styleable.IcoButton_txtSize, _convertDpToPixels(16))); } private void _setupButtonIcon(TypedArray xmlAttrs) { _btnIcon.setAdjustViewBounds(true); _btnIcon.setMaxHeight((int) (_btnText.getTextSize() * 1.2)); // TODO: parametrize this _btnIcon.setImageDrawable(xmlAttrs.getDrawable(R.styleable.IcoButton_drawable)); } private StateListDrawable _getStateListDrawableForButtonColor(int buttonColor, boolean darken) { // Creating bitmap for color which will be used at normal state Rect rectNormal = new Rect(0, 0, 1, 1); Bitmap imageNormal = Bitmap.createBitmap(rectNormal.width(), rectNormal.height(), Bitmap.Config.ARGB_8888); Canvas canvasNormal = new Canvas(imageNormal); Paint paintNormal = new Paint(); paintNormal.setColor(buttonColor); canvasNormal.drawRect(rectNormal, paintNormal); // Creating bitmap for color which will be used at pressed state Rect rectPressed = new Rect(0, 0, 1, 1); Bitmap imagePressed = Bitmap.createBitmap(rectPressed.width(), rectPressed.height(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(imagePressed); int colorPressed = _darkenOrLightenColor(buttonColor, darken); Paint paintPressed = new Paint(); paintPressed.setColor(colorPressed); canvas.drawRect(rectPressed, paintPressed); RectF bounds = new RectF(); bounds.round(rectPressed); // Now assigning states to StateListDrawable StateListDrawable stateListDrawable = new StateListDrawable(); stateListDrawable.addState(new int[]{ android.R.attr.state_pressed }, new BitmapDrawable(imagePressed)); stateListDrawable.addState(StateSet.WILD_CARD, new BitmapDrawable(imageNormal)); return stateListDrawable; } private int _darkenOrLightenColor(int color, boolean darken) { float[] hsv = new float[3]; Color.colorToHSV(color, hsv); // value component if (darken) { hsv[2] *= Math.max(hsv[2] * 0.8f, 0); } else { hsv[2] = Math.max(hsv[2] * 1.5f, 1); } return Color.HSVToColor(hsv); } private int _convertDpToPixels(int dps) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dps, getResources().getDisplayMetrics()); } }
package org.intermine.task; 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.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.intermine.metadata.AttributeDescriptor; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.CollectionDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.MetaDataException; import org.intermine.metadata.Model; import org.intermine.metadata.PrimaryKey; import org.intermine.metadata.PrimaryKeyUtil; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.intermine.DatabaseSchema; import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl; import org.intermine.sql.Database; import org.intermine.sql.DatabaseUtil; import org.intermine.util.StringUtil; import org.intermine.util.SynchronisedIterator; import java.sql.Connection; import java.sql.SQLException; import org.apache.log4j.Logger; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; /** * Task to create indexes on a database holding objects conforming to a given model by * reading that model's primary key configuration information. * By default three types of index are created: for the specified primary key fields, for all N-1 * relations, and for the indirection table columns of M-N relations. * Alternatively, if attributeIndexes is true, indexes are created for all non-primary key * attributes instead. * Note that all "id" columns are indexed automatically by virtue of InterMineTorqueModelOuput * specifying them as primary key columns. * @author Mark Woodbridge * @author Kim Rutherford */ public class CreateIndexesTask extends Task { private String alias; private Connection c; private boolean attributeIndexes = false; private DatabaseSchema schema = null; private Database database = null; private static final Logger LOG = Logger.getLogger(CreateIndexesTask.class); private Map tableIndexesDone = Collections.synchronizedMap(new HashMap()); private Set indexesMade = Collections.synchronizedSet(new HashSet()); private static final int POSTGRESQL_INDEX_NAME_LIMIT = 63; private int extraThreads = 3; private ObjectStore objectStore; /** * Set the ObjectStore alias. Currently the ObjectStore must be an ObjectStoreInterMineImpl. * * @param alias the ObjectStore alias */ public void setAlias(String alias) { if (objectStore != null) { throw new BuildException("set one of alias and objectStore, not both"); } this.alias = alias; } /** * Set the ObjectStore to use. Can be set instead of alias. * * @param objectStore ObjectStore to create indexes on */ public void setObjectStore(ObjectStore objectStore) { if (alias != null) { throw new BuildException("set one of alias and objectStore, not both"); } this.objectStore = objectStore; } /** * Set the attributeIndexes flag. Index the attributes that are not part of the * primary key if and only if the flag is set. * * @param attributeIndexes flag for attribute indexes */ public void setAttributeIndexes(boolean attributeIndexes) { this.attributeIndexes = attributeIndexes; } /** * Set the number of extra worker threads. If the database server is multi-CPU, it might help to * have multiple threads hitting it. * * @param extraThreads number of extra threads apart from the main thread */ public void setExtraThreads(int extraThreads) { this.extraThreads = extraThreads; } /** * Sets up the instance variables * * @throws BuildException if something is wrong */ public void setUp() throws BuildException { if (alias == null && objectStore == null) { throw new BuildException("exactly one of alias and objectStore must be set"); } if (objectStore == null) { try { objectStore = ObjectStoreFactory.getObjectStore(alias); } catch (Exception e) { throw new BuildException("Exception while creating ObjectStore", e); } } if (objectStore instanceof ObjectStoreInterMineImpl) { ObjectStoreInterMineImpl osii = ((ObjectStoreInterMineImpl) objectStore); database = osii.getDatabase(); schema = osii.getSchema(); } else { // change comment on setAlias() when this changes throw new BuildException("the alias (" + alias + ") does not refer to an " + "ObjectStoreInterMineImpl"); } } /** * {@inheritDoc} */ public void execute() throws BuildException { setUp(); Model m = schema.getModel(); Map statements = new TreeMap(); Map clds = new TreeMap(); ClassDescriptor cld = null; try { for (Iterator i = m.getClassDescriptors().iterator(); i.hasNext();) { cld = (ClassDescriptor) i.next(); Map cldIndexes = new TreeMap(); if (attributeIndexes) { getAttributeIndexStatements(cld, cldIndexes); } else { getStandardIndexStatements(cld, cldIndexes); } if (!cldIndexes.isEmpty()) { compressNames(cldIndexes); statements.putAll(cldIndexes); clds.put(cld.getName(), cldIndexes); } } } catch (MetaDataException e) { String message = "Error creating indexes for " + cld.getType(); throw new BuildException(message, e); } checkForIndexNameClashes(statements); IndexStatement indexStatement = null; try { c = database.getConnection(); c.setAutoCommit(true); // Drop all the indexes first, then re-create them. That ensures that if we try to // create an index with the same name twice we get an exception. Postgresql has a // limit on index name length (63) and will truncate longer names with a NOTICE rather // than an error. Iterator statementsIter = clds.keySet().iterator(); while (statementsIter.hasNext()) { String indexName = (String) statementsIter.next(); indexStatement = (IndexStatement) statements.get(indexName); dropIndex(indexName); } Iterator cldsIter = new SynchronisedIterator(clds.entrySet().iterator()); Set threads = new HashSet(); synchronized (threads) { for (int i = 1; i <= extraThreads; i++) { Thread worker = new Thread(new Worker(threads, cldsIter, i)); threads.add(new Integer(i)); worker.setName("CreateIndexesTask extra thread " + i); worker.start(); } } try { while (cldsIter.hasNext()) { Map.Entry cldEntry = (Map.Entry) cldsIter.next(); String cldName = (String) cldEntry.getKey(); LOG.info("Thread 0 processing class " + cldName); statementsIter = ((Map) cldEntry.getValue()).entrySet().iterator(); while (statementsIter.hasNext()) { Map.Entry statementEntry = (Map.Entry) statementsIter.next(); String indexName = (String) statementEntry.getKey(); indexStatement = (IndexStatement) statementEntry.getValue(); createIndex(c, indexName, indexStatement, 0); } } } catch (NoSuchElementException e) { // This is fine - just a consequence of concurrent access to the iterator. It means // the end of the iterator has been reached, so there is no more work to do. } LOG.info("Thread 0 finished"); synchronized (threads) { while (threads.size() != 0) { LOG.info(threads.size() + " threads left"); threads.wait(); } } LOG.info("All threads finished"); } catch (Exception e) { String message = "Error creating indexes"; if (indexStatement != null) { message = "Error creating indexes for " + indexStatement.getTableName() + "(" + indexStatement.getColumnNames() + ")"; } throw new BuildException(message, e); } finally { if (c != null) { try { c.close(); } catch (SQLException e) { // empty } } } } private class Worker implements Runnable { private int threadNo; private Set threads; private Iterator cldsIter; /** * Create a new Worker object. * @param threads the Thread indexes * @param cldsIter an Iterator over the classes to index * @param threadNo the thread index of this thread */ public Worker(Set threads, Iterator cldsIter, int threadNo) { this.threads = threads; this.cldsIter = cldsIter; this.threadNo = threadNo; } public void run() { Connection conn = null; try { try { conn = database.getConnection(); conn.setAutoCommit(true); while (cldsIter.hasNext()) { Map.Entry cldEntry = (Map.Entry) cldsIter.next(); String cldName = (String) cldEntry.getKey(); LOG.info("Thread " + threadNo + " processing class " + cldName); Iterator statementsIter = ((Map) cldEntry.getValue()).entrySet().iterator(); while (statementsIter.hasNext()) { Map.Entry statementEntry = (Map.Entry) statementsIter.next(); String indexName = (String) statementEntry.getKey(); IndexStatement st = (IndexStatement) statementEntry.getValue(); createIndex(conn, indexName, st, threadNo); } } } catch (NoSuchElementException e) { // rmpty } finally { try { if (conn != null) { conn.close(); } } finally { LOG.info("Thread " + threadNo + " finished"); synchronized (threads) { threads.remove(new Integer(threadNo)); threads.notify(); } } } } catch (SQLException e) { LOG.error("Thread " + threadNo + " failed", e); } } } private static final int MAX_ITERATIONS = 10; /** * If an index name is longer than the Postgres limit (63), try shortening it by removing * the last lowercase letters in each part of the name. eg. change * TransposableElementInsertionSite__LocatedSequenceFeature__key_indentifer_org to * TranspElemenInsertSite__LocateSequenFeatur__key_indentifer_org */ private void compressNames(Map statements) { Set statementNames = new HashSet(statements.keySet()); Iterator statementsIter = statementNames.iterator(); while (statementsIter.hasNext()) { String origIndexName = (String) statementsIter.next(); if (origIndexName.length() > POSTGRESQL_INDEX_NAME_LIMIT) { String indexName = origIndexName; // Don't compress the class names too match - start by shortening the longest parts // of the class names for (int i = MAX_ITERATIONS; i > 0; i Pattern pattern = Pattern.compile("([A-Z][a-z]{1," + i + "})[a-z]*"); Matcher matcher = pattern.matcher(indexName); String newIndexName = matcher.replaceAll("$1"); if (newIndexName.length() <= POSTGRESQL_INDEX_NAME_LIMIT) { Object indexStatement = statements.get(origIndexName); statements.remove(origIndexName); statements.put(newIndexName, indexStatement); break; } } } } } private void checkForIndexNameClashes(Map statements) throws BuildException { // index names truncated to 63 characters Map truncNames = new HashMap(); Iterator statementsIter = statements.keySet().iterator(); while (statementsIter.hasNext()) { String indexName = (String) statementsIter.next(); String truncName; if (indexName.length() > POSTGRESQL_INDEX_NAME_LIMIT) { truncName = indexName.substring(0, POSTGRESQL_INDEX_NAME_LIMIT); } else { truncName = indexName; } if (truncNames.containsKey(truncName)) { throw new BuildException("tried to create a non-unique index name: " + truncName + " from " + indexName + " and " + truncNames.get(truncName)); } else { truncNames.put(truncName, indexName); } } } /** * Add indexes for primary keys, indirection tables and 1-N relations to the relevant tables for * a given ClassDescriptor * @param cld the ClassDescriptor * @param statements the index creation statements for the given cld are added to this Map. * The key is the index name, the value is a IndexStatement. * @throws MetaDataException if a field os not found in model */ protected void getStandardIndexStatements(ClassDescriptor cld, Map statements) throws MetaDataException { // Set of fieldnames that already are the first element of an index. Set doneFieldNames = new HashSet(); String cldTableName = DatabaseUtil.getTableName(cld); boolean simpleClass = !InterMineObject.class.isAssignableFrom(cld.getType()); //add an index for each primary key Map primaryKeys = PrimaryKeyUtil.getPrimaryKeys(cld); for (Iterator i = primaryKeys.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); String keyName = (String) entry.getKey(); PrimaryKey key = (PrimaryKey) entry.getValue(); List fieldNames = new ArrayList(); for (Iterator j = key.getFieldNames().iterator(); j.hasNext();) { String fieldName = (String) j.next(); FieldDescriptor fd = cld.getFieldDescriptorByName(fieldName); if (fd == null) { throw new MetaDataException("field (" + fieldName + ") not found for class: " + cld.getName() + " for key name " + keyName + "."); } fieldNames.add(DatabaseUtil.getColumnName(fd)); } // create indexes on this class and on all subclasses Set clds = new HashSet(Collections.singleton(cld)); clds.addAll(cld.getModel().getAllSubs(cld)); for (Iterator k = clds.iterator(); k.hasNext();) { ClassDescriptor nextCld = (ClassDescriptor) k.next(); ClassDescriptor tableMaster = schema.getTableMaster(nextCld); String tableName = DatabaseUtil.getTableName(tableMaster); if (!schema.getMissingTables().contains(tableName.toLowerCase())) { String indexNameBase; if (tableName.equals(cldTableName)) { indexNameBase = tableName + "__" + keyName; } else { indexNameBase = tableName + "__" + cldTableName.subSequence(0, (cldTableName.length() > 16 ? 15 : cldTableName.length())) + "__" + keyName; } addStatement(statements, indexNameBase, tableName, StringUtil.join(fieldNames, ", ") + (simpleClass ? "" : ", id"), nextCld, tableMaster); doneFieldNames.add(fieldNames.get(0)); } } } //and one for each bidirectional N-to-1 relation to increase speed of //e.g. company.getDepartments for (Iterator i = cld.getAllReferenceDescriptors().iterator(); i.hasNext();) { ReferenceDescriptor ref = (ReferenceDescriptor) i.next(); ClassDescriptor tableMaster = schema.getTableMaster(cld); String tableName = DatabaseUtil.getTableName(tableMaster); if (FieldDescriptor.N_ONE_RELATION == ref.relationType()) { if (!schema.getMissingTables().contains(tableName.toLowerCase())) { String fieldName = DatabaseUtil.getColumnName(ref); if (!doneFieldNames.contains(fieldName)) { addStatement(statements, cldTableName + "__" + ref.getName(), tableName, fieldName + (simpleClass ? "" : ", id"), cld, tableMaster); } } } } //finally add an index to all M-to-N indirection table columns //for (Iterator i = cld.getAllCollectionDescriptors().iterator(); i.hasNext();) { for (Iterator i = cld.getCollectionDescriptors().iterator(); i.hasNext();) { CollectionDescriptor col = (CollectionDescriptor) i.next(); if (FieldDescriptor.M_N_RELATION == col.relationType()) { String tableName = DatabaseUtil.getIndirectionTableName(col); String columnName = DatabaseUtil.getInwardIndirectionColumnName(col, schema.getVersion()); String columnName2 = DatabaseUtil.getOutwardIndirectionColumnName(col, schema.getVersion()); if ((columnName.compareTo(columnName2) < 0) || (col.getReverseReferenceDescriptor() == null)) { addStatement(statements, tableName + "__" + columnName, tableName, columnName + ", " + columnName2, cld, null); addStatement(statements, tableName + "__" + columnName2, tableName, columnName2 + ", " + columnName, cld, null); } } } } protected void getAttributeIndexStatements(ClassDescriptor cld, Map statements) { Map primaryKeys = PrimaryKeyUtil.getPrimaryKeys(cld); String tableName = DatabaseUtil.getTableName(cld); if (!schema.getMissingTables().contains(tableName.toLowerCase())) { ATTRIBUTE: for (Iterator attributeIter = cld.getAllAttributeDescriptors().iterator(); attributeIter.hasNext();) { AttributeDescriptor att = (AttributeDescriptor) attributeIter.next(); if (att.getName().equals("id")) { continue; } String fieldName = DatabaseUtil.getColumnName(att); if (!att.getType().equals("java.lang.String")) { // if the attribute is the first column of a primary key, don't bother creating // another index for it - unless it's a String attribute in which case we want // to create a LOWER() index for (Iterator primaryKeyIter = primaryKeys.entrySet().iterator(); primaryKeyIter.hasNext();) { Map.Entry primaryKeyEntry = (Map.Entry) primaryKeyIter.next(); PrimaryKey key = (PrimaryKey) primaryKeyEntry.getValue(); String firstKeyField = (String) key.getFieldNames().iterator().next(); if (firstKeyField.equals(att.getName())) { continue ATTRIBUTE; } } } String indexName = tableName + "__" + att.getName(); if (att.getType().equals("java.lang.String")) { // we add 'text_pattern_ops' so that LIKE queries will use the index. see: addStatement(statements, indexName + "_like", tableName, "lower(" + fieldName + ") text_pattern_ops", cld, null); // this index is used by = and IN constraints addStatement(statements, indexName + "_equals", tableName, "lower(" + fieldName + ")", cld, null); } else { addStatement(statements, indexName, tableName, fieldName, cld, null); } } } } private void addStatement(Map statements, String indexName, String tableName, String columnNames, ClassDescriptor cld, ClassDescriptor tableMaster) { if (statements.containsKey(indexName)) { IndexStatement indexStatement = (IndexStatement) statements.get(indexName); if (!indexStatement.getColumnNames().equals(columnNames) || !indexStatement.getTableName().equals(tableName)) { throw new IllegalArgumentException("Tried to created two indexes with the " + "same name: " + indexName); } } IndexStatement indexStatement = new IndexStatement(tableName, columnNames, cld, tableMaster); statements.put(indexName, indexStatement); } /** * Drop an index by name, ignoring any resulting errors * @param indexName the index name */ protected void dropIndex(String indexName) { try { if (!indexesMade.contains(indexName)) { execute(c, "drop index " + indexName); } } catch (SQLException e) { // ignore because the exception is probably because the index doesn't exist } } /** * Create an named index on the specified columns of a table. * * @param conn a Connection * @param indexName the index name * @param indexStatement the IndexStatement * @param threadNo the number of the calling thread */ protected void createIndex(Connection conn, String indexName, IndexStatement indexStatement, int threadNo) { String tableName = indexStatement.getTableName(); LOG.info("Thread " + threadNo + " creating index: " + indexName); Set indexesForTable = (Set) tableIndexesDone.get(tableName); if (indexesForTable == null) { indexesForTable = Collections.synchronizedSet(new HashSet()); tableIndexesDone.put(tableName, indexesForTable); } if (!indexesForTable.contains(indexStatement.getColumnNames())) { try { execute(conn, indexStatement.getStatementString(indexName)); } catch (SQLException e) { // ignore - we just don't create this index LOG.error("failed to create index " + indexName + " for " + tableName + "(" + indexStatement.getColumnNames() + ")", e); System.err .println("Failed to create index " + indexName); } } indexesForTable.add(indexStatement.getColumnNames()); indexesMade.add(indexName); } /** * Execute an sql statement. * * @param conn a Connection * @param sql the sql string for the statement to execute * @throws SQLException if an error occurs */ protected void execute(Connection conn, String sql) throws SQLException { conn.createStatement().execute(sql); } } /** * A simple representation of an SQL index statement. * @author Kim Rutherford */ class IndexStatement { private String tableName; private String columnNames; private ClassDescriptor cld; private ClassDescriptor tableMaster; /** * Return an IndexStatement that can be used to create an index on the specified columns of a * table. * @param tableName the table name * @param columnNames the column names * @param cld the class descriptor of the class to index * @param tableMaster the class descriptor of the table master to index */ IndexStatement(String tableName, String columnNames, ClassDescriptor cld, ClassDescriptor tableMaster) { this.tableName = tableName; this.columnNames = columnNames; this.cld = cld; this.tableMaster = tableMaster; } /** * Return the columnNames argument that was passed to the constructor. * @return the columnNames */ String getColumnNames() { return columnNames; } /** * Return the tableName argument that was passed to the constructor. * @return the tableName */ String getTableName() { return tableName; } /** * Return the cld argument that was passed to the constructor. * @return the cld */ ClassDescriptor getCld() { return cld; } /** * Return the tableMaster that was passed to the constructor. * @return the tableMaster */ ClassDescriptor getTableMaster() { return tableMaster; } /** * Return the SQL String to use to create the index. * @param indexName the index name to substitute into the statement. * @return the SQL String */ String getStatementString(String indexName) { return "create index " + indexName + " on " + tableName + "(" + columnNames + ")"; } }
package org.intermine.task; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.Set; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.intermine.metadata.Model; import org.intermine.modelproduction.ModelMerger; import org.intermine.modelproduction.xml.InterMineModelParser; /** * Task to merge a single additions file into an intermine XML model. * * @see org.intermine.modelproduction.ModelMerger * @author Thomas Riley */ public class ModelMergerTask extends Task { protected File inputModelFile; protected File additionsFile; protected File outputModelFile; /** * Set the model to add additions to. * @param file path to model file */ public void setInputModelFile(File file) { inputModelFile = file; } /** * The file containing model additions. * @param file the additions file */ public void setAdditionsFile(File file) { additionsFile = file; } /** * Path of file to write resulting model to. May be the same as <code>inputModelFile</code>. * @param file path to write resulting model to */ public void setOutputFile(File file) { outputModelFile = file; } /** * Merge additions into input model and write resulting model to output file. * * @see Task#execute */ public void execute() throws BuildException { try { InterMineModelParser parser = new InterMineModelParser(); FileReader reader = new FileReader(inputModelFile); Model model = parser.process(reader); reader.close(); Set additionClds = parser.generateClassDescriptors(new FileReader(additionsFile)); Model merged = ModelMerger.mergeModel(model, additionClds); FileWriter writer = new FileWriter(outputModelFile); writer.write(merged.toString()); writer.close(); } catch (Exception e) { throw new BuildException(e); } } }
package com.irunninglog.spring.ping; import com.irunninglog.api.ping.IPing; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("prototype") final class Ping implements IPing { private String timestamp; @Override public IPing setTimestamp(String timestamp) { this.timestamp = timestamp; return this; } @Override public String getTimestamp() { return "timestamp"; } }
package org.broadinstitute.sting.gatk.traversals; import org.apache.log4j.Logger; import org.broadinstitute.sting.gatk.datasources.providers.ShardDataProvider; import org.broadinstitute.sting.gatk.datasources.shards.Shard; import org.broadinstitute.sting.gatk.walkers.Walker; import org.broadinstitute.sting.gatk.ReadMetrics; import org.broadinstitute.sting.gatk.GenomeAnalysisEngine; import org.broadinstitute.sting.utils.*; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; import org.broadinstitute.sting.utils.exceptions.UserException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.*; public abstract class TraversalEngine<M,T,WalkerType extends Walker<M,T>,ProviderType extends ShardDataProvider> { // Time in milliseconds since we initialized this engine private static final int HISTORY_WINDOW_SIZE = 50; private static class ProcessingHistory { double elapsedSeconds; long unitsProcessed; long bpProcessed; GenomeLoc loc; public ProcessingHistory(double elapsedSeconds, GenomeLoc loc, long unitsProcessed, long bpProcessed) { this.elapsedSeconds = elapsedSeconds; this.loc = loc; this.unitsProcessed = unitsProcessed; this.bpProcessed = bpProcessed; } } /** * Simple utility class that makes it convenient to print unit adjusted times */ private static class MyTime { double t; // in Seconds int precision; // for format public MyTime(double t, int precision) { this.t = t; this.precision = precision; } public MyTime(double t) { this(t, 1); } /** * Instead of 10000 s, returns 2.8 hours * @return */ public String toString() { double unitTime = t; String unit = "s"; if ( t > 120 ) { unitTime = t / 60; // minutes unit = "m"; if ( unitTime > 120 ) { unitTime /= 60; // hours unit = "h"; if ( unitTime > 100 ) { unitTime /= 24; // days unit = "d"; if ( unitTime > 20 ) { unitTime /= 7; // days unit = "w"; } } } } return String.format("%6."+precision+"f %s", unitTime, unit); } } /** lock object to sure updates to history are consistent across threads */ private static final Object lock = new Object(); LinkedList<ProcessingHistory> history = new LinkedList<ProcessingHistory>(); /** We use the SimpleTimer to time our run */ private SimpleTimer timer = new SimpleTimer("Traversal"); // How long can we go without printing some progress info? private long lastProgressPrintTime = -1; // When was the last time we printed progress log? private long PROGRESS_PRINT_FREQUENCY = 10 * 1000; // in milliseconds private final double TWO_HOURS_IN_SECONDS = 2.0 * 60.0 * 60.0; private final double TWELVE_HOURS_IN_SECONDS = 12.0 * 60.0 * 60.0; // for performance log private static final boolean PERFORMANCE_LOG_ENABLED = true; private final Object performanceLogLock = new Object(); private File performanceLogFile; private PrintStream performanceLog = null; private long lastPerformanceLogPrintTime = -1; // When was the last time we printed to the performance log? private final long PERFORMANCE_LOG_PRINT_FREQUENCY = PROGRESS_PRINT_FREQUENCY; // in milliseconds /** Size, in bp, of the area we are processing. Updated once in the system in initial for performance reasons */ long targetSize = -1; GenomeLocSortedSet targetIntervals = null; /** our log, which we want to capture anything from this class */ protected static Logger logger = Logger.getLogger(TraversalEngine.class); protected GenomeAnalysisEngine engine; // ABSTRACT METHODS /** * Gets the named traversal type associated with the given traversal. * @return A user-friendly name for the given traversal type. */ protected abstract String getTraversalType(); /** * this method must be implemented by all traversal engines * * @param walker the walker to run with * @param dataProvider the data provider that generates data given the shard * @param sum the accumulator * * @return an object of the reduce type */ public abstract T traverse(WalkerType walker, ProviderType dataProvider, T sum); // Common timing routines /** * Initialize the traversal engine. After this point traversals can be run over the data * @param engine GenomeAnalysisEngine for this traversal */ public void initialize(GenomeAnalysisEngine engine) { if ( engine == null ) throw new ReviewedStingException("BUG: GenomeAnalysisEngine cannot be null!"); this.engine = engine; if ( PERFORMANCE_LOG_ENABLED && engine.getArguments() != null && engine.getArguments().performanceLog != null ) { synchronized(this.performanceLogLock) { performanceLogFile = engine.getArguments().performanceLog; createNewPerformanceLog(); } } // if we don't have any intervals defined, create intervals from the reference itself if ( this.engine.getIntervals() == null ) targetIntervals = GenomeLocSortedSet.createSetFromSequenceDictionary(engine.getReferenceDataSource().getReference().getSequenceDictionary()); else targetIntervals = this.engine.getIntervals(); targetSize = targetIntervals.coveredSize(); } private void createNewPerformanceLog() { synchronized(performanceLogLock) { try { performanceLog = new PrintStream(new FileOutputStream(engine.getArguments().performanceLog)); List<String> pLogHeader = Arrays.asList("elapsed.time", "units.processed", "processing.speed", "bp.processed", "bp.speed", "genome.fraction.complete", "est.total.runtime", "est.time.remaining"); performanceLog.println(Utils.join("\t", pLogHeader)); } catch (FileNotFoundException e) { throw new UserException.CouldNotCreateOutputFile(engine.getArguments().performanceLog, e); } } } /** * Should be called to indicate that we're going to process records and the timer should start ticking */ public void startTimers() { timer.start(); lastProgressPrintTime = timer.currentTime(); } /** * @param curTime (current runtime, in millisecs) * @param lastPrintTime the last time we printed, in machine milliseconds * @param printFreq maximum permitted difference between last print and current times * * @return true if the maximum interval (in millisecs) has passed since the last printing */ private boolean maxElapsedIntervalForPrinting(final long curTime, long lastPrintTime, long printFreq) { return (curTime - lastPrintTime) > printFreq; } /** * Forward request to printProgress * * @param shard the given shard currently being processed. * @param loc the location */ public void printProgress(Shard shard, GenomeLoc loc) { // A bypass is inserted here for unit testing. // TODO: print metrics outside of the traversal engine to more easily handle cumulative stats. ReadMetrics cumulativeMetrics = engine.getCumulativeMetrics() != null ? engine.getCumulativeMetrics().clone() : new ReadMetrics(); cumulativeMetrics.incrementMetrics(shard.getReadMetrics()); printProgress(loc, cumulativeMetrics, false); } /** * Utility routine that prints out process information (including timing) every N records or * every M seconds, for N and M set in global variables. * * @param loc Current location, can be null if you are at the end of the traversal * @param metrics Metrics of reads filtered in/out. * @param mustPrint If true, will print out info, regardless of nRecords or time interval */ private void printProgress(GenomeLoc loc, ReadMetrics metrics, boolean mustPrint) { final long nRecords = metrics.getNumIterations(); if ( nRecords == 1 && mustPrint == false ) { logger.info("[INITIALIZATION COMPLETE; TRAVERSAL STARTING]"); logger.info(String.format("%15s processed.%s runtime per.1M.%s completed total.runtime remaining", "Location", getTraversalType(), getTraversalType())); } else { final long curTime = timer.currentTime(); boolean printProgress = mustPrint || maxElapsedIntervalForPrinting(curTime, lastProgressPrintTime, PROGRESS_PRINT_FREQUENCY); boolean printLog = performanceLog != null && maxElapsedIntervalForPrinting(curTime, lastPerformanceLogPrintTime, PERFORMANCE_LOG_PRINT_FREQUENCY); if ( printProgress || printLog ) { ProcessingHistory last = updateHistory(loc, metrics); final MyTime elapsed = new MyTime(last.elapsedSeconds); final MyTime bpRate = new MyTime(secondsPerMillionBP(last)); final MyTime unitRate = new MyTime(secondsPerMillionElements(last)); final double fractionGenomeTargetCompleted = calculateFractionGenomeTargetCompleted(last); final MyTime estTotalRuntime = new MyTime(elapsed.t / fractionGenomeTargetCompleted); final MyTime timeToCompletion = new MyTime(estTotalRuntime.t - elapsed.t); if ( printProgress ) { lastProgressPrintTime = curTime; // dynamically change the update rate so that short running jobs receive frequent updates while longer jobs receive fewer updates if ( estTotalRuntime.t > TWELVE_HOURS_IN_SECONDS ) PROGRESS_PRINT_FREQUENCY = 60 * 1000; // in milliseconds else if ( estTotalRuntime.t > TWO_HOURS_IN_SECONDS ) PROGRESS_PRINT_FREQUENCY = 30 * 1000; // in milliseconds else PROGRESS_PRINT_FREQUENCY = 10 * 1000; // in milliseconds // String common = String.format("%4.1e %s in %s, %s per 1M %s, %4.1f%% complete, est. runtime %s, %s remaining", // nRecords*1.0, getTraversalType(), elapsed, unitRate, // getTraversalType(), 100*fractionGenomeTargetCompleted, // estTotalRuntime, timeToCompletion); // if (loc != null) // logger.info(String.format("%20s: processing %s", loc, common)); // else // logger.info(String.format("Processing %s", common)); logger.info(String.format("%15s %5.2e %s %s %4.1f%% %s %s", loc == null ? "done" : loc, nRecords*1.0, elapsed, unitRate, 100*fractionGenomeTargetCompleted, estTotalRuntime, timeToCompletion)); } if ( printLog ) { lastPerformanceLogPrintTime = curTime; synchronized(performanceLogLock) { performanceLog.printf("%.2f\t%d\t%.2e\t%d\t%.2e\t%.2e\t%.2f\t%.2f%n", elapsed.t, nRecords, unitRate.t, last.bpProcessed, bpRate.t, fractionGenomeTargetCompleted, estTotalRuntime.t, timeToCompletion.t); } } } } } /** * Keeps track of the last HISTORY_WINDOW_SIZE data points for the progress meter. Currently the * history isn't used in any way, but in the future it'll become valuable for more accurate estimates * for when a process will complete. * * @param loc our current position. If null, assumes we are done traversing * @param metrics information about what's been processed already * @return */ private final ProcessingHistory updateHistory(GenomeLoc loc, ReadMetrics metrics) { synchronized (lock) { if ( history.size() > HISTORY_WINDOW_SIZE ) history.pop(); long nRecords = metrics.getNumIterations(); long bpProcessed = loc == null ? targetSize : targetIntervals.sizeBeforeLoc(loc); // null -> end of processing history.add(new ProcessingHistory(timer.getElapsedTime(), loc, nRecords, bpProcessed)); return history.getLast(); } } /** How long in seconds to process 1M traversal units? */ private final double secondsPerMillionElements(ProcessingHistory last) { return (last.elapsedSeconds * 1000000.0) / Math.max(last.unitsProcessed, 1); } /** How long in seconds to process 1M bp on the genome? */ private final double secondsPerMillionBP(ProcessingHistory last) { return (last.elapsedSeconds * 1000000.0) / Math.max(last.bpProcessed, 1); } /** What fractoin of the target intervals have we covered? */ private final double calculateFractionGenomeTargetCompleted(ProcessingHistory last) { return (1.0*last.bpProcessed) / targetSize; } /** * Called after a traversal to print out information about the traversal process */ public void printOnTraversalDone(ReadMetrics cumulativeMetrics) { printProgress(null, cumulativeMetrics, true); final double elapsed = timer.getElapsedTime(); // count up the number of skipped reads by summing over all filters long nSkippedReads = 0L; for ( Map.Entry<Class, Long> countsByFilter: cumulativeMetrics.getCountsByFilter().entrySet()) nSkippedReads += countsByFilter.getValue(); logger.info(String.format("Total runtime %.2f secs, %.2f min, %.2f hours", elapsed, elapsed / 60, elapsed / 3600)); if ( cumulativeMetrics.getNumReadsSeen() > 0 ) logger.info(String.format("%d reads were filtered out during traversal out of %d total (%.2f%%)", nSkippedReads, cumulativeMetrics.getNumReadsSeen(), 100.0 * MathUtils.ratio(nSkippedReads,cumulativeMetrics.getNumReadsSeen()))); for ( Map.Entry<Class, Long> filterCounts : cumulativeMetrics.getCountsByFilter().entrySet() ) { long count = filterCounts.getValue(); logger.info(String.format(" -> %d reads (%.2f%% of total) failing %s", count, 100.0 * MathUtils.ratio(count,cumulativeMetrics.getNumReadsSeen()), Utils.getClassName(filterCounts.getKey()))); } if ( performanceLog != null ) performanceLog.close(); } /** * Gets the filename to which performance data is currently being written. * @return Filename to which performance data is currently being written. */ public String getPerformanceLogFileName() { synchronized(performanceLogLock) { return performanceLogFile.getAbsolutePath(); } } /** * Sets the filename of the log for performance. If set, will write performance data. * @param fileName filename to use when writing performance data. */ public void setPerformanceLogFileName(String fileName) { File file = new File(fileName); synchronized(performanceLogLock) { // Ignore multiple calls to reset the same lock. if(performanceLogFile != null && performanceLogFile.equals(fileName)) return; // Close an existing log if(performanceLog != null) performanceLog.close(); performanceLogFile = file; createNewPerformanceLog(); } } /** * Gets the frequency with which performance data is written. * @return Frequency, in seconds, of performance log writes. */ public long getPerformanceProgressPrintFrequencySeconds() { return PROGRESS_PRINT_FREQUENCY; } /** * How often should the performance log message be written? * @param seconds number of seconds between messages indicating performance frequency. */ public void setPerformanceProgressPrintFrequencySeconds(long seconds) { PROGRESS_PRINT_FREQUENCY = seconds; } }
package me.Cooltimmetje.PretparkCore.Managers; import com.gmail.filoghost.holographicdisplays.api.Hologram; import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; import me.Cooltimmetje.PretparkCore.Main; import me.Cooltimmetje.PretparkCore.Utilities.*; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.inventory.Inventory; import java.util.ArrayList; public class NpcManager implements Listener { static String world = "world"; static Entity gadgetEntity; static int FIREWORK_COST = 100; static int FIREWORKRIDE_COST = 200; static int STAFFPUNCH_COST = 300; static ArrayList<Entity> entitys = new ArrayList<>(); static ArrayList<Hologram> holograms = new ArrayList<>(); public static void spawnNPCs(){ Entity pet = Bukkit.getWorld(world).spawnEntity(new Location(Bukkit.getWorld(world), -1249, 55, 242, -120, 0).add(0.5, 0, 0.5), EntityType.VILLAGER); EntityUtils.noAI(pet); entitys.add(pet); Hologram petHolo = HologramsAPI.createHologram(Main.getPlugin(), pet.getLocation().add(0, 2.6, 0)); petHolo.appendTextLine(MiscUtils.color("&bPet Shop")); petHolo.appendTextLine(MiscUtils.color("&7&lSoonTM")); holograms.add(petHolo); Entity merchant = Bukkit.getWorld(world).spawnEntity(new Location(Bukkit.getWorld(world), -1197, 54, 59, -15, 0).add(0.5, 0, 0.5), EntityType.VILLAGER); EntityUtils.noAI(merchant); entitys.add(merchant); Hologram merchantHolo = HologramsAPI.createHologram(Main.getPlugin(), merchant.getLocation().add(0, 2.6, 0)); merchantHolo.appendTextLine(MiscUtils.color("&bKleding Shop")); merchantHolo.appendTextLine(MiscUtils.color("&7&lSoonTM")); holograms.add(merchantHolo); Entity gadget = Bukkit.getWorld(world).spawnEntity(new Location(Bukkit.getWorld(world), -1249, 55, 238, -50, 0).add(0.5,0,0.5), EntityType.VILLAGER); gadgetEntity = gadget; EntityUtils.noAI(gadget); entitys.add(gadget); Hologram gadgetHolo = HologramsAPI.createHologram(Main.getPlugin(), gadget.getLocation().add(0, 2.6, 0)); gadgetHolo.appendTextLine(MiscUtils.color("&bGadget Shop")); gadgetHolo.appendTextLine(MiscUtils.color("&a&lRIGHT CLICK")); holograms.add(gadgetHolo); Entity food = Bukkit.getWorld(world).spawnEntity(new Location(Bukkit.getWorld(world), -1184, 54, 60, -180, 0).add(0.5,0,0.5), EntityType.VILLAGER); EntityUtils.noAI(food); entitys.add(food); Hologram foodHolo = HologramsAPI.createHologram(Main.getPlugin(), gadget.getLocation().add(0, 2.6, 0)); foodHolo.appendTextLine(MiscUtils.color("&bCocktail Bar")); foodHolo.appendTextLine(MiscUtils.color("&7&lSoonTM")); holograms.add(foodHolo); } public static void removeNPCs(){ for(Hologram hologram : holograms){ hologram.delete(); } for(Entity entity : entitys){ entity.remove(); } } @EventHandler public void onEntityRightClick(PlayerInteractEntityEvent event){ Player p = event.getPlayer(); Entity e = event.getRightClicked(); if((e instanceof Villager) && !(e instanceof Minecart)){ if(e == gadgetEntity){ event.setCancelled(true); openGadget(p); } } } private void openGadget(Player p) { Inventory inv = Bukkit.createInventory(null, 54, "Gadget Shop"); int slot = 1; for(Material m : GadgetManager.name.keySet()){ String name,lore; boolean hasPerm = p.hasPermission(GadgetManager.permission.get(m)); StringBuilder nameSb = new StringBuilder(); if(hasPerm){ nameSb.append("&a"); } else { nameSb.append("&c"); } name = nameSb.append(GadgetManager.name.get(m)).toString().trim(); String[] loreArray = GadgetManager.lore.get(m); StringBuilder loreSb = new StringBuilder(); loreSb.append("&3COOLDOWN: &b").append(GadgetManager.cooldown.get(m)).append(" seconden \n \n"); for (String aLoreArray : loreArray) { loreSb.append(aLoreArray).append("\n"); } loreSb.append(" \n"); if(hasPerm){ loreSb.append("&aUNLOCKED"); } else { loreSb.append("&cLOCKED &8\u00BB &aKlik om te kopen."); loreSb.append("&3Dit kost: &6").append(GadgetManager.cost.get(m)); } lore = loreSb.toString().trim(); ItemUtils.createChestDisplay(m, 1, 0, name, lore, inv, slot); slot = slot + 1; } p.openInventory(inv); } @EventHandler @SuppressWarnings("all") public void onInventoryClick(InventoryClickEvent event){ if(event.getInventory().getName().equals("Gadget Shop")){ Player p = (Player) event.getWhoClicked(); event.setCancelled(true); if(event.getCurrentItem().hasItemMeta()) { Material m = event.getCurrentItem().getType(); if (p.hasPermission(GadgetManager.permission.get(m))) { ChatUtils.sendMsgTag(p, "GadgetShop", ChatUtils.error + "Je hebt dit al gekocht!"); } else { if (PlayerUtils.getCoins(p) >= GadgetManager.cost.get(m)) { Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "manuaddp " + p.getName() + " " + GadgetManager.permission.get(m)); Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "mansave"); PlayerUtils.takeCoins(p, GadgetManager.cost.get(m), "je hebt een gadget gekocht!"); openGadget(p); } else { ChatUtils.sendMsgTag(p, "GadgetShop", ChatUtils.error + "Je hebt niet genoeg coins!"); } } } else { return; } } else { return; } } @EventHandler public void onEntityDamage(EntityDamageEvent event){ if(entitys.contains(event.getEntity())){ event.setCancelled(true); } } }
package com.traits.scheduler; import com.traits.model.BaseProject; import com.traits.model.BaseTask; import com.traits.model.TaskCache; import com.traits.storage.BaseStorage; import com.traits.storage.MongoDBStorage; import com.traits.storage.MySQLStorage; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.quartz.*; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.*; import java.util.Calendar; import java.util.regex.*; @DisallowConcurrentExecution public class TaskTrigger implements Job { Logger logger = Logger.getLogger("scheduler"); private String dbtype, host, database, table, user, passwd; private int port; private HashMap<String, BaseProject> _projectMap; private HashMap<String, BaseTask> _initTaskMap; private HashSet<String> _successOrPassedTaskSet; private static SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); private Pattern depReg = Pattern.compile("(day|hour|minute|second)\\((0|-\\d+)\\)((-|\\+)\\d+)*,\\s*(\\d+)"); public TaskTrigger() { String configPath = this.getClass().getClassLoader().getResource("/").getPath() + "conf.properties"; Properties confProperties = new Properties(); try { confProperties.load(new FileInputStream(configPath)); } catch (IOException e) { logger.debug(e.getMessage()); } dbtype = confProperties.getProperty("task.storage", "mysql"); host = confProperties.getProperty("task.host", "127.0.0.1"); port = Integer.parseInt(confProperties.getProperty("task.port", "3306")); database = confProperties.getProperty("task.db", "scheduler"); user = confProperties.getProperty("task.user", null); passwd = confProperties.getProperty("task.password", null); } public void loadProjects(BaseStorage _storage) throws Exception { _projectMap = new HashMap<String, BaseProject>(); for (BaseProject p : _storage.getProjects()) { _projectMap.put(p.getId(), p); } } public void loadInitTasks(BaseStorage _storage) throws Exception { _initTaskMap = new HashMap<String, BaseTask>(); for (BaseTask t : _storage.getInitTasks()) { _initTaskMap.put(t.getId(), t); } } public void loadSuccessOrPassedTask(BaseStorage _storage) throws Exception { _successOrPassedTaskSet = _storage.getSuccessOrPassedTasks(); } public static Date day(double current, int delta) { double day = ((long) (current / (86400.0))) * (86400L); double baseTimeStamp = day - delta * 86400; return new Date((long) (baseTimeStamp * 1000)); } public static Date hour(double current, int delta) { double hour = ((long) (current / (3600.0))) * (3600); double baseTimeStamp = hour - delta * 3600; return new Date((long) (baseTimeStamp * 1000)); } public static Date minute(double current, int delta) { double minute = ((long) (current / (60.0))) * (60); double baseTimeStamp = minute - delta * 60; return new Date((long) (baseTimeStamp * 1000)); } public static Date second(double current, int delta) { double second = ((long) current); double baseTimeStamp = second - delta; return new Date((long) (baseTimeStamp * 1000)); } public ArrayList<String> parseDependence(BaseProject _self, HashMap<String, BaseProject> _projectMap, Date lunchDate) { ArrayList<String> dep = new ArrayList<String>(); // projectId basetime, count // task.test1:[(day(-3)+2345, 12),(hour(-2), 1),(minute(0), 3)]; String depStr = _self.getDependence(); String[] deps = StringUtils.split(depStr.replace(" ", "").replace("\r\n|\r|\n", ""), ";"); for (String each : deps) { String[] tmp = StringUtils.split(each.trim(), ":"); if (tmp.length == 2) { String pid = tmp[0]; double lunchTimeStamp = lunchDate.getTime() / 1000.0; String tmp1; if (tmp[1].startsWith("[(") && tmp[1].endsWith(")]")) { tmp1 = tmp[1].substring(2, tmp[1].length() - 2); } else if (tmp[1].startsWith("(") && tmp[1].endsWith(")")) { tmp1 = tmp[1].substring(1, tmp[1].length() - 1); } else { logger.error("dependence is parsed error"); continue; } String[] tmp2 = tmp1.replace("),(", "\1").split("\1"); for (String rule : tmp2) { java.util.regex.Matcher mat = depReg.matcher(rule); if (mat.find()) { try { String fun = mat.group(1); int delta = Integer.valueOf(mat.group(2) == null ? "0" : mat.group(2)); int offset = Integer.valueOf(mat.group(3) == null ? "0" : mat.group(3)); int count = Integer.valueOf(mat.group(5)); Method method = this.getClass().getMethod(fun, double.class, int.class); Date base = (Date) method.invoke(null, lunchTimeStamp, delta); if (_projectMap.containsKey(pid)) { BaseProject p = _projectMap.get(pid); Date tmpd2 = new Date(base.getTime() + offset * 1000); if (tmpd2.getTime() > lunchDate.getTime()) { logger.warn("basetime is not allowed before lunchtime"); tmpd2 = lunchDate; } ArrayList<Date> reqDate = p.getCron().getTimeBefore(tmpd2, count); for (Date tmpdate : reqDate) { dep.add(String.format("%s @ %s", p.getId(), df.format(tmpdate))); } } } catch (Exception e) { logger.error("dependence is parsed error"); logger.error(e.getMessage()); e.printStackTrace(); continue; } } else { logger.error(String.format("dependence %s is parsed error", rule)); continue; } } } } return dep; } public boolean checkTask(HashSet<String> _successOrPassedTaskSet, HashMap<String, BaseProject> _projectMap, BaseProject project, BaseTask task, Date lunchDate) { if (project.getDependence() == null || project.getDependence().equals("")) { task.setDependence_finish_rate(1.0); return true; } ArrayList<String> requireTasks = parseDependence(project, _projectMap, lunchDate); for (String s : requireTasks) { logger.debug("requre Task: " + s); } int total = requireTasks.size(); int matched = 0; for (String req : requireTasks) { if (_successOrPassedTaskSet.contains(req)) { matched += 1; } } if (total == matched) { task.setDependence_finish_rate(1.0); return true; } else { task.setDependence_finish_rate(matched / total); return false; } } public void execute(JobExecutionContext context) throws JobExecutionException { logger.info(">> TaskTrigger execute"); BaseStorage _storage = null; TaskCache tc = TaskCache.getInstance(); try { if (dbtype.equals("mysql")) { _storage = new MySQLStorage(host, port, database, user, passwd); } else if (dbtype.equals("mongodb")) { _storage = new MongoDBStorage(host, port, database, user, passwd); } else { _storage = new MySQLStorage(host, port, database, user, passwd); } loadProjects(_storage); loadInitTasks(_storage); loadSuccessOrPassedTask(_storage); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); return; } for (Map.Entry<String, BaseTask> kv : _initTaskMap.entrySet()) { BaseTask t = kv.getValue(); String pid = t.getProject_id(); if (_projectMap.containsKey(pid)) { BaseProject p = _projectMap.get(pid); if ( (((long)((t.getLunchtime() + p.getDelay()) * 1000)) < (new Date()).getTime() && checkTask(_successOrPassedTaskSet, _projectMap, p, t, new Date((new Double(t.getLunchtime() * 1000)).longValue()))) || t.getStatus() == BaseTask.Status.FORCERUNNING) { // the task satifies dependence t.setStatus(BaseTask.Status.ACTIVE); t.setUpdatetime(((double) (new Date()).getTime()) / 1000.0); try { _storage.saveOneTask(t); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } } else { // task does not satifies dependence t.setStatus(BaseTask.Status.CHECKING); t.setUpdatetime(((double) (new Date()).getTime()) / 1000.0); t.setTriggertime((((new Date()).getTime() + 60 * 10 * 1000) / 1000.0 + p.getDelay())); try { _storage.saveOneTask(t); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } tc.get_taskMap().put(t.getTriggertime(), t); } } } for (Map.Entry<Double, BaseTask> t : tc.get_taskMap().entrySet()) { Double triggerTime = t.getKey(); BaseTask task = t.getValue(); if (triggerTime < ((new Date()).getTime() / 1000.0)) { String pid = task.getProject_id(); if (_projectMap.containsKey(pid)) { BaseProject p = _projectMap.get(pid); if (p.getStatus() == BaseProject.Status.RUNNING || p.getStatus() == BaseProject.Status.DEBUG) { // running or debug if (checkTask(_successOrPassedTaskSet, _projectMap, p, task, new Date((new Double(task.getLunchtime() * 1000)).longValue()))){ // the task satifies dependence task.setStatus(BaseTask.Status.ACTIVE); task.setUpdatetime(((double) (new Date()).getTime()) / 1000.0); try { _storage.saveOneTask(task); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } tc.get_taskMap().pollFirstEntry(); } else { // does not satify dependence task.setStatus(BaseTask.Status.CHECKING); task.setUpdatetime(((double) (new Date()).getTime()) / 1000.0); task.setTriggertime(((double) (new Date()).getTime() + 60 * 10 * 1000) / 1000.0); try { _storage.saveOneTask(task); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } tc.get_taskMap().pollFirstEntry(); // TODO check task if it exists longer than 30 days tc.get_taskMap().put(task.getTriggertime(), task); } } else { // stop delete... if (p.getStatus() == BaseProject.Status.DELETE) { task.setStatus(BaseTask.Status.DELETE); } else { task.setStatus(BaseTask.Status.STOP); } task.setUpdatetime(((double) (new Date()).getTime()) / 1000.0); task.setEndtime(((double) (new Date()).getTime()) / 1000.0); try { _storage.saveOneTask(task); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } tc.get_taskMap().pollFirstEntry(); } } else { // delete task.setStatus(BaseTask.Status.DELETE); task.setUpdatetime(((double) (new Date()).getTime()) / 1000.0); task.setEndtime(((double) (new Date()).getTime()) / 1000.0); try { _storage.saveOneTask(task); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } tc.get_taskMap().pollFirstEntry(); } } else { // time don't arrive break; } } logger.info("<< TaskTrigger execute"); } }
package php.runtime.ext.core.reflection; import php.runtime.Memory; import php.runtime.common.HintType; import php.runtime.common.Messages; import php.runtime.env.Environment; import php.runtime.invoke.DynamicMethodInvoker; import php.runtime.invoke.Invoker; import php.runtime.invoke.StaticMethodInvoker; import php.runtime.lang.IObject; import php.runtime.memory.ArrayMemory; import php.runtime.memory.LongMemory; import php.runtime.memory.ObjectMemory; import php.runtime.memory.StringMemory; import php.runtime.reflection.ClassEntity; import php.runtime.reflection.MethodEntity; import php.runtime.reflection.ParameterEntity; import php.runtime.reflection.support.AbstractFunctionEntity; import java.util.Arrays; import static php.runtime.annotation.Reflection.*; @Name("ReflectionMethod") @Signature({ @Arg(value = "name", type = HintType.STRING, readOnly = true), @Arg(value = "class", type = HintType.STRING, readOnly = true) }) public class ReflectionMethod extends ReflectionFunctionAbstract { public final static int IS_STATIC = 1 ; public final static int IS_PUBLIC = 256 ; public final static int IS_PROTECTED = 512 ; public final static int IS_PRIVATE = 1024 ; public final static int IS_ABSTRACT = 2 ; public final static int IS_FINAL = 4 ; protected MethodEntity methodEntity; protected ArrayMemory cachedParameters; protected boolean hackAccess = false; public ReflectionMethod(Environment env, MethodEntity methodEntity) { super(env); setEntity(methodEntity); } public ReflectionMethod(Environment env, ClassEntity clazz) { super(env, clazz); } public void setEntity(MethodEntity entity) { this.methodEntity = entity; getProperties().put("name", new StringMemory(entity.getName())); getProperties().put("class", new StringMemory(entity.getClazz().getName())); } @Signature({@Arg("class"), @Arg("name")}) public Memory __construct(Environment env, Memory... args){ ClassEntity classEntity; Memory _class = args[0]; if (_class.isObject()) classEntity = _class.toValue(ObjectMemory.class).getReflection(); else classEntity = env.fetchClass(_class.toString(), true); if (classEntity == null){ exception(env, Messages.ERR_CLASS_NOT_FOUND.fetch(_class)); return Memory.NULL; } MethodEntity entity = classEntity.findMethod(args[1].toString().toLowerCase()); if (entity == null){ exception(env, Messages.ERR_METHOD_NOT_FOUND.fetch(_class, args[1])); return Memory.NULL; } setEntity(entity); return Memory.NULL; } @Override protected AbstractFunctionEntity getEntity() { return methodEntity; } @Override @Signature public Memory getParameters(Environment env, Memory... args) { if (cachedParameters != null) return cachedParameters; ParameterEntity[] parameters = methodEntity.getParameters(Integer.MAX_VALUE); ClassEntity entity = env.fetchClass("ReflectionParameter"); ArrayMemory result = new ArrayMemory(); int i = 0; for(ParameterEntity param : parameters){ ReflectionParameter e = new ReflectionParameter(env, entity); e.setEntity(param); e.setFunctionEntity(methodEntity); e.setPosition(i); i++; result.add(new ObjectMemory(e)); } return cachedParameters = result; } @Signature public Memory getDeclaringClass(Environment env, Memory... args){ ClassEntity entity = env.fetchClass("ReflectionClass"); ReflectionClass r = new ReflectionClass(env, entity); r.setEntity(methodEntity.getClazz()); return new ObjectMemory(r); } @Signature public Memory getModifiers(Environment env, Memory... args){ int mod = 0; if (methodEntity.isAbstract()) mod |= IS_ABSTRACT; if (methodEntity.isFinal()) mod |= IS_FINAL; if (methodEntity.isPrivate()) mod |= IS_PRIVATE; else if (methodEntity.isProtected()) mod |= IS_PROTECTED; else if (methodEntity.isPublic()) mod |= IS_PUBLIC; if (methodEntity.isStatic()) mod |= IS_STATIC; return LongMemory.valueOf(mod); } @Signature public Memory getPrototype(Environment env, Memory... args){ if (methodEntity.getPrototype() == null) return Memory.NULL; ClassEntity classEntity = env.fetchClass("ReflectionMethod"); ReflectionMethod r = new ReflectionMethod(env, classEntity); r.setEntity(methodEntity.getPrototype()); return new ObjectMemory(r); } @Signature public Memory isConstructor(Environment env, Memory... args) { return methodEntity.getClazz().methodConstruct == methodEntity ? Memory.TRUE : Memory.FALSE; } @Signature public Memory isDestruct(Environment env, Memory... args) { return methodEntity.getClazz().methodDestruct == methodEntity ? Memory.TRUE : Memory.FALSE; } @Signature public Memory isAbstract(Environment env, Memory... args){ return methodEntity.isAbstract() ? Memory.TRUE : Memory.FALSE; } @Signature public Memory isFinal(Environment env, Memory... args){ return methodEntity.isFinal() ? Memory.TRUE : Memory.FALSE; } @Signature public Memory isStatic(Environment env, Memory... args){ return methodEntity.isStatic() ? Memory.TRUE : Memory.FALSE; } @Signature public Memory isPublic(Environment env, Memory... args){ return methodEntity.isPublic() ? Memory.TRUE : Memory.FALSE; } @Signature public Memory isProtected(Environment env, Memory... args){ return methodEntity.isProtected() ? Memory.TRUE : Memory.FALSE; } @Signature public Memory isPrivate(Environment env, Memory... args){ return methodEntity.isPrivate() ? Memory.TRUE : Memory.FALSE; } @Signature(@Arg("accessible")) public Memory setAccessible(Environment env, Memory... args){ hackAccess = args[0].toBoolean(); return Memory.NULL; } @Signature({@Arg(value = "object", optional = @Optional, type = HintType.OBJECT)}) public Memory invoke(Environment env, Memory... args) throws Throwable { Memory self = args[0]; Memory[] arguments = args.length == 1 ? new Memory[0] : Arrays.copyOfRange(args, 1, args.length - 1); Invoker invoker; if (self.isNull()) { invoker = new StaticMethodInvoker(env, env.trace(), methodEntity.getClazzName(), methodEntity); } else { invoker = new DynamicMethodInvoker(env, env.trace(), self.toObject(IObject.class), methodEntity); } return invoker.call(arguments); } @Signature({ @Arg(value = "object", optional = @Optional, type = HintType.OBJECT), @Arg(value = "args", type = HintType.ARRAY) }) public Memory invokeArgs(Environment env, Memory... args) throws Throwable { Memory self = args[0]; Memory[] arguments = args[1].toValue(ArrayMemory.class).values(); Invoker invoker; if (self.isNull()) { invoker = new StaticMethodInvoker(env, env.trace(), methodEntity.getClazzName(), methodEntity); } else { invoker = new DynamicMethodInvoker(env, env.trace(), self.toObject(IObject.class), methodEntity); } return invoker.call(arguments); } @Signature(@Arg("object")) public Memory getClosure(final Environment env, Memory... args) throws Throwable { IObject object; if (args[0].isNull()){ object = null; } else if (args[0].isObject()) { object = args[0].toValue(ObjectMemory.class).value; } else { exception(env, "Argument 1 must be NULL or object, %s given", args[0].getRealType().toString()); return Memory.NULL; } if (object == null && !methodEntity.isStatic()){ exception(env, "Cannot use method as static"); return Memory.NULL; } else if (object != null && methodEntity.isStatic()){ exception(env, "Cannot use method as non static"); return Memory.NULL; } return new ObjectMemory(methodEntity.getClosure(env, object)); } }
package com.fsck.k9.ui.messageview; import android.app.PendingIntent; import android.content.Context; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.annotation.ColorRes; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.fsck.k9.R; import org.openintents.openpgp.OpenPgpSignatureResult; import org.openintents.openpgp.util.OpenPgpUtils; public class OpenPgpHeaderView extends LinearLayout { private Context context; private OpenPgpHeaderViewCallback callback; private OpenPgpSignatureResult signatureResult; private boolean encrypted; private PendingIntent pendingIntent; private ImageView resultEncryptionIcon; private TextView resultEncryptionText; private ImageView resultSignatureIcon; private TextView resultSignatureText; private LinearLayout resultSignatureLayout; private TextView resultSignatureName; private TextView resultSignatureEmail; private Button resultSignatureButton; public OpenPgpHeaderView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } @Override public void onFinishInflate() { resultEncryptionIcon = (ImageView) findViewById(R.id.result_encryption_icon); resultEncryptionText = (TextView) findViewById(R.id.result_encryption_text); resultSignatureIcon = (ImageView) findViewById(R.id.result_signature_icon); resultSignatureText = (TextView) findViewById(R.id.result_signature_text); resultSignatureLayout = (LinearLayout) findViewById(R.id.result_signature_layout); resultSignatureName = (TextView) findViewById(R.id.result_signature_name); resultSignatureEmail = (TextView) findViewById(R.id.result_signature_email); resultSignatureButton = (Button) findViewById(R.id.result_signature_button); } public void setCallback(OpenPgpHeaderViewCallback callback) { this.callback = callback; } public void setOpenPgpData(OpenPgpSignatureResult signatureResult, boolean encrypted, PendingIntent pendingIntent) { this.signatureResult = signatureResult; this.encrypted = encrypted; this.pendingIntent = pendingIntent; initializeEncryptionHeader(); initializeSignatureHeader(); } private void initializeEncryptionHeader() { if (encrypted) { setEncryptionImageAndTextColor(CryptoState.ENCRYPTED); resultEncryptionText.setText(R.string.openpgp_result_encrypted); } else { setEncryptionImageAndTextColor(CryptoState.NOT_ENCRYPTED); resultEncryptionText.setText(R.string.openpgp_result_not_encrypted); } } private void initializeSignatureHeader() { initializeSignatureButton(); if (signatureResult == null) { displayNotSigned(); return; } switch (signatureResult.getStatus()) { case OpenPgpSignatureResult.SIGNATURE_ERROR: { displaySignatureError(); break; } case OpenPgpSignatureResult.SIGNATURE_SUCCESS_CERTIFIED: { displaySignatureSuccessCertified(); break; } case OpenPgpSignatureResult.SIGNATURE_KEY_MISSING: { displaySignatureKeyMissing(); break; } case OpenPgpSignatureResult.SIGNATURE_SUCCESS_UNCERTIFIED: { displaySignatureSuccessUncertified(); break; } case OpenPgpSignatureResult.SIGNATURE_KEY_EXPIRED: { displaySignatureKeyExpired(); break; } case OpenPgpSignatureResult.SIGNATURE_KEY_REVOKED: { displaySignatureKeyRevoked(); break; } } } private void initializeSignatureButton() { if (isSignatureButtonUsed()) { setSignatureButtonClickListener(); } else { hideSignatureButton(); } } private boolean isSignatureButtonUsed() { return pendingIntent != null; } private void setSignatureButtonClickListener() { resultSignatureButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { callback.onPgpSignatureButtonClick(pendingIntent); } }); } private void hideSignatureButton() { resultSignatureButton.setVisibility(View.GONE); resultSignatureButton.setOnClickListener(null); } private void showSignatureButtonWithTextIfNecessary(@StringRes int stringId) { if (isSignatureButtonUsed()) { resultSignatureButton.setVisibility(View.VISIBLE); resultSignatureButton.setText(stringId); } } private void displayNotSigned() { setSignatureImageAndTextColor(CryptoState.NOT_SIGNED); resultSignatureText.setText(R.string.openpgp_result_no_signature); hideSignatureLayout(); } private void displaySignatureError() { setSignatureImageAndTextColor(CryptoState.INVALID); resultSignatureText.setText(R.string.openpgp_result_invalid_signature); hideSignatureLayout(); } private void displaySignatureSuccessCertified() { setSignatureImageAndTextColor(CryptoState.VERIFIED); resultSignatureText.setText(R.string.openpgp_result_signature_certified); displayUserIdAndSignatureButton(); } private void displaySignatureKeyMissing() { setSignatureImageAndTextColor(CryptoState.UNKNOWN_KEY); resultSignatureText.setText(R.string.openpgp_result_signature_missing_key); setUserId(signatureResult); showSignatureButtonWithTextIfNecessary(R.string.openpgp_result_action_lookup); showSignatureLayout(); } private void displaySignatureSuccessUncertified() { setSignatureImageAndTextColor(CryptoState.UNVERIFIED); resultSignatureText.setText(R.string.openpgp_result_signature_uncertified); displayUserIdAndSignatureButton(); } private void displaySignatureKeyExpired() { setSignatureImageAndTextColor(CryptoState.EXPIRED); resultSignatureText.setText(R.string.openpgp_result_signature_expired_key); displayUserIdAndSignatureButton(); } private void displaySignatureKeyRevoked() { setSignatureImageAndTextColor(CryptoState.REVOKED); resultSignatureText.setText(R.string.openpgp_result_signature_revoked_key); displayUserIdAndSignatureButton(); } private void displayUserIdAndSignatureButton() { setUserId(signatureResult); showSignatureButtonWithTextIfNecessary(R.string.openpgp_result_action_show); showSignatureLayout(); } private void setUserId(OpenPgpSignatureResult signatureResult) { final OpenPgpUtils.UserInfo userInfo = OpenPgpUtils.splitUserId(signatureResult.getPrimaryUserId()); if (userInfo.name != null) { resultSignatureName.setText(userInfo.name); } else { resultSignatureName.setText(R.string.openpgp_result_no_name); } if (userInfo.email != null) { resultSignatureEmail.setText(userInfo.email); } else { resultSignatureEmail.setText(R.string.openpgp_result_no_email); } } private void hideSignatureLayout() { resultSignatureLayout.setVisibility(View.GONE); } private void showSignatureLayout() { resultSignatureLayout.setVisibility(View.VISIBLE); } private void setEncryptionImageAndTextColor(CryptoState state) { setStatusImageAndTextColor(resultEncryptionIcon, resultEncryptionText, state); } private void setSignatureImageAndTextColor(CryptoState state) { setStatusImageAndTextColor(resultSignatureIcon, resultSignatureText, state); } private void setStatusImageAndTextColor(ImageView statusIcon, TextView statusText, CryptoState state) { Drawable statusImageDrawable = context.getResources().getDrawable(state.getDrawableId()); statusIcon.setImageDrawable(statusImageDrawable); int color = context.getResources().getColor(state.getColorId()); statusIcon.setColorFilter(color, PorterDuff.Mode.SRC_IN); if (statusText != null) { statusText.setTextColor(color); } } private enum CryptoState { VERIFIED(R.drawable.status_signature_verified_cutout, R.color.openpgp_green), ENCRYPTED(R.drawable.status_lock_closed, R.color.openpgp_green), UNAVAILABLE(R.drawable.status_signature_unverified_cutout, R.color.openpgp_orange), UNVERIFIED(R.drawable.status_signature_unverified_cutout, R.color.openpgp_orange), UNKNOWN_KEY(R.drawable.status_signature_unknown_cutout, R.color.openpgp_orange), REVOKED(R.drawable.status_signature_revoked_cutout, R.color.openpgp_red), EXPIRED(R.drawable.status_signature_expired_cutout, R.color.openpgp_red), NOT_ENCRYPTED(R.drawable.status_lock_open, R.color.openpgp_red), NOT_SIGNED(R.drawable.status_signature_unknown_cutout, R.color.openpgp_red), INVALID(R.drawable.status_signature_invalid_cutout, R.color.openpgp_red); private final int drawableId; private final int colorId; CryptoState(@DrawableRes int drawableId, @ColorRes int colorId) { this.drawableId = drawableId; this.colorId = colorId; } @DrawableRes public int getDrawableId() { return drawableId; } @ColorRes public int getColorId() { return colorId; } } }
package org.CG.infrastructure.drawings; import javax.media.opengl.GL; public class LineInPixelMatrix extends Drawing { public LineInPixelMatrix(int[] parameters) { super(parameters); } @Override public void draw(GL gl) { int[] start = {parameters[0], parameters[1]}; int[] end = {parameters[2], parameters[3]}; int dx = end[0] - start[0]; int dy = end[1] - start[1]; int octant = findOctect(dx, dy); start = translate(start, octant); end = translate(end, octant); // Start[x] must be smaller than end[x]. If it isn't, swap points. if (start[0] > end[0]) { int[] t = start; start = end; end = t; } // Calculate E and NE constants for the Midpoint Line algorithm. int x = (int) start[0]; int y = (int) start[1]; dx = (int) (end[0] - start[0]); dy = (int) (end[1] - start[1]); int incE = 2 * (dy - dx); int incNE = 2 * dy; int d = 2 * dy - dx; // Set line color. Default is white. gl.glColor3ub((byte) parameters[4], (byte) parameters[5], (byte) parameters[6]); gl.glBegin(GL.GL_POINTS); int[] point = restore(x, y, octant); gl.glVertex2i(point[0], point[1]); while (x < end[0]) { if (d <= 0) { d += incNE; } else { d += incE; y++; } x++; point = restore(x, y, octant); gl.glVertex2i(point[0], point[1]); } gl.glEnd(); } /** * Find in which octant the line is, based on its slope. * * @param dx The difference between ending-point-x and starting-point-x. * @param dy The difference between ending-point-y and starting-point-y. * @return x, x e [0,8], where x represents the octant (anticlockwise order). */ protected int findOctect(int dx, int dy) { double d = Math.atan(((double) dy) / dx); d = (d >= 0) ? d : 2 * Math.PI + d; return (int) (4 * d / Math.PI); } protected int[] translate(int[] point, int octant) { return translate(point[0], point[1], octant); } /** * Based on its original @octant, find the representative coordinate of the point (x,y) in the 1st octant. * * @param x The 1st coordinate of the point. * @param y The 2nd coordinate of the point. * @param octant The octant from which that point originally belongs. * @return a pair (x1, y1) that represents the translation of (x,y) to the 1st octant. */ protected int[] translate(int x, int y, int octant) { if (octant == 0) { return new int[]{x, y}; } if (octant == 1) { return new int[]{y, x}; } if (octant == 2) { return new int[]{-y, x}; } if (octant == 3) { return new int[]{-x, y}; } if (octant == 4) { return new int[]{-x, -y}; } if (octant == 5) { return new int[]{-y, -x}; } if (octant == 6) { return new int[]{y, -x}; } if (octant == 7) { return new int[]{x, -y}; } throw new RuntimeException("Unknown octant " + octant); } protected int[] restore(int[] point, int octant) { return restore(point[0], point[1], octant); } /** * Restore a point from the 1st octant to its original octant. * * @param x The 1st coordinate of the point in the 1st octant. * @param y The 2nd coordinate of the point in the 1st octant. * @param octant The octant to which the point should be restored. * @return a pair (x1, y1) that represents the restored point (x, y) to its original octant. */ protected int[] restore(int x, int y, int octant) { if (octant == 0) { return new int[]{x, y}; } if (octant == 1) { return new int[]{y, x}; } if (octant == 2) { return new int[]{y, -x}; } if (octant == 3) { return new int[]{-x, y}; } if (octant == 4) { return new int[]{-x, -y}; } if (octant == 5) { return new int[]{-y, -x}; } if (octant == 6) { return new int[]{-y, x}; } if (octant == 7) { return new int[]{x, -y}; } throw new RuntimeException("Unknown octant " + octant); } }
package org.concord.datagraph.ui; import java.awt.event.ActionEvent; import javax.swing.Action; import javax.swing.Icon; import org.concord.data.stream.PointsDataStore; import org.concord.datagraph.engine.ControllableDataGraphable; import org.concord.framework.data.stream.DataStore; import org.concord.graph.engine.GraphableList; import org.concord.graph.util.ui.ResourceLoader; import org.concord.swing.SelectableAction; /** * DrawDataGraphableAction * Class name and description * * Date created: Mar 14, 2005 * * @author imoncada<p> * */ public class DrawDataGraphableAction extends SelectableAction { protected ControllableDataGraphable dataGraphable; protected GraphableList objList; public DrawDataGraphableAction() { super(); setName("Draw"); } /** * Sets the name of the icon * (Equivalent to the Action.NAME property) * @param name */ public void setName(String name) { putValue(Action.NAME, name); } /** * Sets the icon of the action given the url */ public void setIcon(String strURL) { setIcon(ResourceLoader.getImageIcon(strURL, "")); } /** * Sets the icon of the action * (Equivalent to the Action.SMALL_ICON property) * @param icon icon of the action */ public void setIcon(Icon icon) { putValue(Action.SMALL_ICON, icon); } /** * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { super.actionPerformed(e); if (isSelected()){ if (dataGraphable == null){ createDefaultDataGraphable(); } dataGraphable.setDragMode(ControllableDataGraphable.DRAGMODE_ADDMULTIPLEPOINTS); } else{ if (dataGraphable != null){ dataGraphable.setDragMode(ControllableDataGraphable.DRAGMODE_NONE); } } } private void createDefaultDataGraphable() { if (objList == null) return; ControllableDataGraphable dg = new ControllableDataGraphable(); DataStore points = new PointsDataStore(); dg.setDataStore(points, 0, 1); dg.setConnectPoints(true); dg.setLineType(ControllableDataGraphable.LINETYPE_FUNCTION); objList.add(dg); setDataGraphable(dg); } /** * @return Returns the dataGraphable. */ public ControllableDataGraphable getDataGraphable() { return dataGraphable; } /** * @param dataGraphable The dataGraphable to set. */ public void setDataGraphable(ControllableDataGraphable dataGraphable) { this.dataGraphable = dataGraphable; } /** * @return Returns the objList. */ public GraphableList getGraphableList() { return objList; } /** * @param objList The objList to set. */ public void setGraphableList(GraphableList objList) { this.objList = objList; } }
package org.grouplens.lenskit.eval; import java.io.File; import java.util.List; import org.codehaus.plexus.util.DirectoryScanner; import org.grouplens.lenskit.dtree.DataNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utilities for parsing configurations. * * @since 0.8 * @author Michael Ekstrand <ekstrand@cs.umn.edu> * */ public class ConfigUtils { private static final Logger logger = LoggerFactory.getLogger(ConfigUtils.class); public static DirectoryScanner configureScanner(DataNode node) { File base = new File(node.getAttribute("dir", ".")); logger.debug("Creating scanner in `{}'", base); String[] includes = getPatterns(node.getChildren("include")); logger.debug("Using include patterns {}", includes); String[] excludes = getPatterns(node.getChildren("exclude")); logger.debug("Using exclude patterns {}", excludes); DirectoryScanner ds = new DirectoryScanner(); ds.setBasedir(base); ds.setIncludes(includes); ds.setExcludes(excludes); return ds; } static String[] getPatterns(List<DataNode> nodes) { String[] ps = new String[nodes.size()]; int i = 0; for (DataNode node: nodes) { ps[i] = node.getValue(); i++; } return ps; } }
package org.kopi.ebics.xml; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.crypto.spec.SecretKeySpec; import org.kopi.ebics.exception.EbicsException; import org.kopi.ebics.interfaces.ContentFactory; import org.kopi.ebics.io.Splitter; import org.kopi.ebics.schema.h003.DataTransferRequestType; import org.kopi.ebics.schema.h003.FULOrderParamsType; import org.kopi.ebics.schema.h003.FileFormatType; import org.kopi.ebics.schema.h003.MutableHeaderType; import org.kopi.ebics.schema.h003.StaticHeaderOrderDetailsType; import org.kopi.ebics.schema.h003.StaticHeaderType; import org.kopi.ebics.schema.h003.DataEncryptionInfoType.EncryptionPubKeyDigest; import org.kopi.ebics.schema.h003.DataTransferRequestType.DataEncryptionInfo; import org.kopi.ebics.schema.h003.DataTransferRequestType.SignatureData; import org.kopi.ebics.schema.h003.EbicsRequestDocument.EbicsRequest; import org.kopi.ebics.schema.h003.EbicsRequestDocument.EbicsRequest.Body; import org.kopi.ebics.schema.h003.EbicsRequestDocument.EbicsRequest.Header; import org.kopi.ebics.schema.h003.ParameterDocument.Parameter; import org.kopi.ebics.schema.h003.ParameterDocument.Parameter.Value; import org.kopi.ebics.schema.h003.StaticHeaderOrderDetailsType.OrderType; import org.kopi.ebics.schema.h003.StaticHeaderType.BankPubKeyDigests; import org.kopi.ebics.schema.h003.StaticHeaderType.Product; import org.kopi.ebics.schema.h003.StaticHeaderType.BankPubKeyDigests.Authentication; import org.kopi.ebics.schema.h003.StaticHeaderType.BankPubKeyDigests.Encryption; import org.kopi.ebics.session.EbicsSession; import org.kopi.ebics.utils.Utils; /** * The <code>UInitializationRequestElement</code> is the common initialization * element for all ebics file uploads. * * @author Hachani * */ public class UInitializationRequestElement extends InitializationRequestElement { /** * Constructs a new <code>UInitializationRequestElement</code> for uploads initializations. * @param session the current ebics session. * @param orderType the upload order type * @param userData the user data to be uploaded * @throws EbicsException */ public UInitializationRequestElement(EbicsSession session, org.kopi.ebics.session.OrderType orderType, byte[] userData) throws EbicsException { super(session, orderType, generateName(orderType)); this.userData = userData; keySpec = new SecretKeySpec(nonce, "EAS"); splitter = new Splitter(userData); } @Override public void buildInitialization() throws EbicsException { EbicsRequest request; Header header; Body body; MutableHeaderType mutable; StaticHeaderType xstatic; Product product; BankPubKeyDigests bankPubKeyDigests; Authentication authentication; Encryption encryption; DataTransferRequestType dataTransfer; DataEncryptionInfo dataEncryptionInfo; SignatureData signatureData; EncryptionPubKeyDigest encryptionPubKeyDigest; StaticHeaderOrderDetailsType orderDetails; FULOrderParamsType fULOrderParams; OrderType orderType; FileFormatType fileFormat; List<Parameter> parameters; userSignature = new UserSignature(session.getUser(), generateName("UserSignature"), session.getConfiguration().getSignatureVersion(), userData); userSignature.build(); userSignature.validate(); splitter.readInput(session.getConfiguration().isCompressionEnabled(), keySpec); mutable = EbicsXmlFactory.createMutableHeaderType("Initialisation", null); product = EbicsXmlFactory.createProduct(session.getProduct().getLanguage(), session.getProduct().getName()); authentication = EbicsXmlFactory.createAuthentication(session.getConfiguration().getAuthenticationVersion(), "http://www.w3.org/2001/04/xmlenc#sha256", decodeHex(session.getUser().getPartner().getBank().getX002Digest())); encryption = EbicsXmlFactory.createEncryption(session.getConfiguration().getEncryptionVersion(), "http://www.w3.org/2001/04/xmlenc#sha256", decodeHex(session.getUser().getPartner().getBank().getE002Digest())); bankPubKeyDigests = EbicsXmlFactory.createBankPubKeyDigests(authentication, encryption); orderType = EbicsXmlFactory.createOrderType(type.getOrderType()); fileFormat = EbicsXmlFactory.createFileFormatType(session.getConfiguration().getLocale().getCountry().toUpperCase(), session.getSessionParam("FORMAT")); fULOrderParams = EbicsXmlFactory.createFULOrderParamsType(fileFormat); parameters = new ArrayList<Parameter>(); if (Boolean.parseBoolean(session.getSessionParam("TEST"))) { Parameter parameter; Value value; value = EbicsXmlFactory.createValue("String", "TRUE"); parameter = EbicsXmlFactory.createParameter("TEST", value); parameters.add(parameter); } if (Boolean.parseBoolean(session.getSessionParam("EBCDIC"))) { Parameter parameter; Value value; value = EbicsXmlFactory.createValue("String", "TRUE"); parameter = EbicsXmlFactory.createParameter("EBCDIC", value); parameters.add(parameter); } if (parameters.size() > 0) { fULOrderParams.setParameterArray(parameters.toArray(new Parameter[parameters.size()])); } orderDetails = EbicsXmlFactory.createStaticHeaderOrderDetailsType(session.getUser().getPartner().nextOrderId(), "DZHNN", orderType, fULOrderParams); xstatic = EbicsXmlFactory.createStaticHeaderType(session.getBankID(), nonce, splitter.getSegmentNumber(), session.getUser().getPartner().getPartnerId(), product, session.getUser().getSecurityMedium(), session.getUser().getUserId(), Calendar.getInstance(), orderDetails, bankPubKeyDigests); header = EbicsXmlFactory.createEbicsRequestHeader(true, mutable, xstatic); encryptionPubKeyDigest = EbicsXmlFactory.createEncryptionPubKeyDigest(session.getConfiguration().getEncryptionVersion(), "http://www.w3.org/2001/04/xmlenc#sha256", decodeHex(session.getUser().getPartner().getBank().getE002Digest())); signatureData = EbicsXmlFactory.createSignatureData(true, Utils.encrypt(Utils.zip(userSignature.prettyPrint()), keySpec)); dataEncryptionInfo = EbicsXmlFactory.createDataEncryptionInfo(true, encryptionPubKeyDigest, generateTransactionKey()); dataTransfer = EbicsXmlFactory.createDataTransferRequestType(dataEncryptionInfo, signatureData); body = EbicsXmlFactory.createEbicsRequestBody(dataTransfer); request = EbicsXmlFactory.createEbicsRequest(session.getConfiguration().getRevision(), session.getConfiguration().getVersion(), header, body); document = EbicsXmlFactory.createEbicsRequestDocument(request); } @Override public byte[] toByteArray() { setSaveSuggestedPrefixes("http: return super.toByteArray(); } /** * Returns the user signature data. * @return the user signature data. */ public UserSignature getUserSignature() { return userSignature; } /** * Returns the content of a given segment. * @param segment the segment number * @return the content of the given segment */ public ContentFactory getContent(int segment) { return splitter.getContent(segment); } /** * Returns the total segment number. * @return the total segment number. */ public int getSegmentNumber() { return splitter.getSegmentNumber(); } // DATA MEMBERS private byte[] userData; private UserSignature userSignature; private SecretKeySpec keySpec; private Splitter splitter; private static final long serialVersionUID = -8083183483311283608L; }
package org.ojalgo.optimisation.integer; import static org.ojalgo.constant.PrimitiveMath.*; import static org.ojalgo.function.PrimitiveFunction.*; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; import org.ojalgo.access.AccessUtils; import org.ojalgo.function.aggregator.Aggregator; import org.ojalgo.matrix.store.MatrixStore; import org.ojalgo.matrix.store.PrimitiveDenseStore; import org.ojalgo.netio.BasicLogger; import org.ojalgo.netio.CharacterRing; import org.ojalgo.netio.CharacterRing.PrinterBuffer; import org.ojalgo.optimisation.ExpressionsBasedModel; import org.ojalgo.optimisation.Optimisation; import org.ojalgo.optimisation.Variable; import org.ojalgo.type.TypeUtils; /** * IntegerSolver * * @author apete */ public final class OldIntegerSolver extends IntegerSolver { final class BranchAndBoundNodeTask extends RecursiveTask<Boolean> { private final NodeKey myKey; private final PrinterBuffer myPrinter = OldIntegerSolver.this.isDebug() ? new CharacterRing().asPrinter() : null; private BranchAndBoundNodeTask(final NodeKey key) { super(); myKey = key; } BranchAndBoundNodeTask() { super(); myKey = new NodeKey(OldIntegerSolver.this.getModel()); } @Override public String toString() { return myKey.toString(); } private boolean isNodeDebug() { return (myPrinter != null) && OldIntegerSolver.this.isDebug(); } @Override protected Boolean compute() { if (this.isNodeDebug()) { myPrinter.println("\nBranch&Bound Node"); myPrinter.println(myKey.toString()); myPrinter.println(OldIntegerSolver.this.toString()); } if (!OldIntegerSolver.this.isIterationAllowed() || !OldIntegerSolver.this.isIterationNecessary()) { if (this.isNodeDebug()) { myPrinter.println("Reached iterations or time limit - stop!"); this.flush(OldIntegerSolver.this.getModel().options.debug_appender); } return false; } if (OldIntegerSolver.this.isExplored(this)) { if (this.isNodeDebug()) { myPrinter.println("Node previously explored!"); this.flush(OldIntegerSolver.this.getModel().options.debug_appender); } return true; } else { OldIntegerSolver.this.markAsExplored(this); } if (!OldIntegerSolver.this.isGoodEnoughToContinueBranching(myKey.objective)) { if (this.isNodeDebug()) { myPrinter.println("No longer a relevant node!"); this.flush(OldIntegerSolver.this.getModel().options.debug_appender); } return true; } ExpressionsBasedModel tmpNodeModel = this.getModel(); final Result tmpBestResultSoFar = OldIntegerSolver.this.getBestResultSoFar(); final Optimisation.Result tmpNodeResult = tmpNodeModel.solve(tmpBestResultSoFar); if (this.isNodeDebug()) { myPrinter.println("Node Result: {}", tmpNodeResult); } OldIntegerSolver.this.incrementIterationsCount(); if (tmpNodeResult.getState().isOptimal()) { if (this.isNodeDebug()) { myPrinter.println("Node solved to optimality!"); } if (OldIntegerSolver.this.options.validate && !tmpNodeModel.validate(tmpNodeResult)) { // This should not be possible. There is a bug somewhere. myPrinter.println("Node solution marked as OPTIMAL, but is actually INVALID/INFEASIBLE/FAILED. Stop this branch!"); myPrinter.println("Lower bounds: {}", Arrays.toString(myKey.getLowerBounds())); myPrinter.println("Upper bounds: {}", Arrays.toString(myKey.getUpperBounds())); tmpNodeModel.validate(tmpNodeResult, myPrinter); this.flush(OldIntegerSolver.this.getModel().options.debug_appender); return false; } final int tmpBranchIndex = OldIntegerSolver.this.identifyNonIntegerVariable(tmpNodeResult, myKey); final double tmpSolutionValue = OldIntegerSolver.this.evaluateFunction(tmpNodeResult); if (tmpBranchIndex == -1) { if (this.isNodeDebug()) { myPrinter.println("Integer solution! Store it among the others, and stop this branch!"); } final Optimisation.Result tmpIntegerSolutionResult = new Optimisation.Result(Optimisation.State.FEASIBLE, tmpSolutionValue, tmpNodeResult); OldIntegerSolver.this.markInteger(myKey, tmpIntegerSolutionResult); if (this.isNodeDebug()) { myPrinter.println(OldIntegerSolver.this.getBestResultSoFar().toString()); BasicLogger.debug(); BasicLogger.debug(OldIntegerSolver.this.toString()); // BasicLogger.debug(DaemonPoolExecutor.INSTANCE.toString()); this.flush(OldIntegerSolver.this.getModel().options.debug_appender); } } else { if (this.isNodeDebug()) { myPrinter.println("Not an Integer Solution: " + tmpSolutionValue); } final double tmpVariableValue = tmpNodeResult.doubleValue(OldIntegerSolver.this.getGlobalIndex(tmpBranchIndex)); if (OldIntegerSolver.this.isGoodEnoughToContinueBranching(tmpSolutionValue)) { if (this.isNodeDebug()) { myPrinter.println("Still hope, branching on {} @ {} >>> {}", tmpBranchIndex, tmpVariableValue, tmpNodeModel.getVariable(OldIntegerSolver.this.getGlobalIndex(tmpBranchIndex))); this.flush(OldIntegerSolver.this.getModel().options.debug_appender); } tmpNodeModel.dispose(); tmpNodeModel = null; final BranchAndBoundNodeTask tmpLowerBranchTask = this.createLowerBranch(tmpBranchIndex, tmpVariableValue, tmpSolutionValue); final BranchAndBoundNodeTask tmpUpperBranchTask = this.createUpperBranch(tmpBranchIndex, tmpVariableValue, tmpSolutionValue); // return tmpLowerBranchTask.compute() && tmpUpperBranchTask.compute(); tmpUpperBranchTask.fork(); final boolean tmpLowerBranchValue = tmpLowerBranchTask.compute(); final boolean tmpUpperBranchValue = tmpUpperBranchTask.join(); return tmpLowerBranchValue & tmpUpperBranchValue; // if (tmpLowerBranchValue) { // return tmpUpperBranchValue; // } else { // tmpUpperBranchTask.tryUnfork(); // tmpUpperBranchTask.cancel(true); // return false; } else { if (this.isNodeDebug()) { myPrinter.println("Can't find better integer solutions - stop this branch!"); this.flush(OldIntegerSolver.this.getModel().options.debug_appender); } } } } else { if (this.isNodeDebug()) { myPrinter.println("Failed to solve node problem - stop this branch!"); this.flush(OldIntegerSolver.this.getModel().options.debug_appender); } } return true; } BranchAndBoundNodeTask createLowerBranch(final int branchIndex, final double nonIntegerValue, final double parentObjectiveValue) { final NodeKey tmpKey = myKey.createLowerBranch(branchIndex, nonIntegerValue, parentObjectiveValue); return new BranchAndBoundNodeTask(tmpKey); } BranchAndBoundNodeTask createUpperBranch(final int branchIndex, final double nonIntegerValue, final double parentObjectiveValue) { final NodeKey tmpKey = myKey.createUpperBranch(branchIndex, nonIntegerValue, parentObjectiveValue); return new BranchAndBoundNodeTask(tmpKey); } void flush(final BasicLogger.Printer receiver) { if ((myPrinter != null) && (receiver != null)) { myPrinter.flush(receiver); } } NodeKey getKey() { return myKey; } ExpressionsBasedModel getModel() { final ExpressionsBasedModel retVal = OldIntegerSolver.this.getModel().relax(false); // if (retVal.options.debug_appender != null) { // retVal.options.debug_appender = new CharacterRing().asPrinter(); final int[] tmpIntegerIndeces = OldIntegerSolver.this.getIntegerIndeces(); for (int i = 0; i < tmpIntegerIndeces.length; i++) { final BigDecimal tmpLowerBound = myKey.getLowerBound(i); final BigDecimal tmpUpperBound = myKey.getUpperBound(i); final Variable tmpVariable = retVal.getVariable(tmpIntegerIndeces[i]); tmpVariable.lower(tmpLowerBound); tmpVariable.upper(tmpUpperBound); BigDecimal tmpValue = tmpVariable.getValue(); if (tmpValue != null) { if (tmpLowerBound != null) { tmpValue = tmpValue.max(tmpLowerBound); } if (tmpUpperBound != null) { tmpValue = tmpValue.min(tmpUpperBound); } tmpVariable.setValue(tmpValue); } } if (OldIntegerSolver.this.isIntegerSolutionFound()) { final double tmpBestValue = OldIntegerSolver.this.getBestResultSoFar().getValue(); final double tmpGap = ABS.invoke(tmpBestValue * OldIntegerSolver.this.options.mip_gap); if (retVal.isMinimisation()) { retVal.limitObjective(null, TypeUtils.toBigDecimal(tmpBestValue - tmpGap, OldIntegerSolver.this.options.problem)); } else { retVal.limitObjective(TypeUtils.toBigDecimal(tmpBestValue + tmpGap, OldIntegerSolver.this.options.problem), null); } } return retVal; } } private final Set<NodeKey> myExploredNodes = Collections.synchronizedSet(new HashSet<NodeKey>()); private final int[] myIntegerIndeces; OldIntegerSolver(final ExpressionsBasedModel model, final Options solverOptions) { super(model, solverOptions); final List<Variable> tmpIntegerVariables = model.getIntegerVariables(); myIntegerIndeces = new int[tmpIntegerVariables.size()]; for (int i = 0; i < myIntegerIndeces.length; i++) { final Variable tmpVariable = tmpIntegerVariables.get(i); myIntegerIndeces[i] = model.indexOf(tmpVariable); } //options.debug = System.out; } public Result solve(final Result kickStarter) { // Must verify that it actually is an integer solution // The kickStarter may be user-supplied if ((kickStarter != null) && kickStarter.getState().isFeasible() && this.getModel().validate(kickStarter)) { this.markInteger(null, kickStarter); } this.resetIterationsCount(); final BranchAndBoundNodeTask tmpNodeTask = new BranchAndBoundNodeTask(); final boolean tmpNormalExit = ForkJoinPool.commonPool().invoke(tmpNodeTask); Optimisation.Result retVal = this.getBestResultSoFar(); if (retVal.getState().isFeasible()) { if (tmpNormalExit) { retVal = new Optimisation.Result(State.OPTIMAL, retVal); } else { retVal = new Optimisation.Result(State.FEASIBLE, retVal); } } else { if (tmpNormalExit) { retVal = new Optimisation.Result(State.INFEASIBLE, retVal); } else { retVal = new Optimisation.Result(State.FAILED, retVal); } } return retVal; } @Override public String toString() { return TypeUtils.format("Solutions={} Nodes/Iterations={} {}", this.countIntegerSolutions(), this.countExploredNodes(), this.getBestResultSoFar()); } @Override protected MatrixStore<Double> extractSolution() { return PrimitiveDenseStore.FACTORY.columns(this.getBestResultSoFar()); } @Override protected boolean initialise(final Result kickStarter) { return true; } @Override protected boolean needsAnotherIteration() { return !this.getState().isOptimal(); } @Override protected boolean validate() { boolean retVal = true; this.setState(State.VALID); try { if (!(retVal = this.getModel().validate())) { retVal = false; this.setState(State.INVALID); } } catch (final Exception ex) { retVal = false; this.setState(State.FAILED); } return retVal; } int countExploredNodes() { return myExploredNodes.size(); } int getGlobalIndex(final int integerIndex) { return myIntegerIndeces[integerIndex]; } final int[] getIntegerIndeces() { return myIntegerIndeces; } /** * Should return the index of the (best) variable to branch on. Returning a negative index means an * integer solition has been found (no further branching). */ int identifyNonIntegerVariable(final Optimisation.Result nodeResult, final NodeKey nodeKey) { int retVal = -1; double tmpFraction; double tmpMaxFraction = ZERO; for (int i = 0; i < myIntegerIndeces.length; i++) { tmpFraction = nodeKey.getFraction(i, nodeResult.doubleValue(myIntegerIndeces[i])); if (this.isIntegerSolutionFound()) { final MatrixStore<Double> tmpGradient = this.getGradient(AccessUtils.asPrimitive1D(nodeResult)); tmpFraction *= (ONE + (ABS.invoke(tmpGradient.doubleValue(myIntegerIndeces[i])) / tmpGradient.aggregateAll(Aggregator.LARGEST))); } if ((tmpFraction > tmpMaxFraction) && !options.integer.isZero(tmpFraction)) { retVal = i; tmpMaxFraction = tmpFraction; } } return retVal; } boolean isExplored(final BranchAndBoundNodeTask aNodeTask) { return myExploredNodes.contains(aNodeTask.getKey()); } void markAsExplored(final BranchAndBoundNodeTask aNodeTask) { myExploredNodes.add(aNodeTask.getKey()); } }
package org.pentaho.di.job.entries.getpop; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.HashSet; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.Session; import javax.mail.Store; import javax.mail.URLName; import javax.mail.Flags.Flag; import javax.mail.internet.MimeUtility; import javax.mail.search.AndTerm; import javax.mail.search.BodyTerm; import javax.mail.search.ComparisonTerm; import javax.mail.search.FlagTerm; import javax.mail.search.FromStringTerm; import javax.mail.search.NotTerm; import javax.mail.search.ReceivedDateTerm; import javax.mail.search.RecipientStringTerm; import javax.mail.search.SearchTerm; import javax.mail.search.SubjectTerm; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.i18n.BaseMessages; import com.sun.mail.imap.IMAPSSLStore; import com.sun.mail.pop3.POP3SSLStore; /** * MailConnection handles the process of connecting to, reading from POP3/IMAP. * * @author Samatar * @since 01-04-2009 * */ public class MailConnection { private static Class<?> PKG = JobEntryGetPOP.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ /** * Target mail server. */ private String server; private int port; private String username; private String password; private boolean usessl; private boolean write; private boolean useproxy; private String proxyusername; /** * Protocol used. * Should be PROTOCOL_POP3 (0) for POP3 and PROTOCOL_IMAP (1) to IMAP */ private int protocol; private Properties prop; private Session session=null; private Store store=null; private Folder folder=null; /** * Contains the list of retrieved messages */ private Message[] messages; /** * Contains the current message */ private Message message; private SearchTerm searchTerm=null;; /** * Counts the number of message fetched */ private int messagenr; /** * Counts the number of message saved in a file */ private int nrSavedMessages; /** * Counts the number of message move to a folder */ private int nrMovedMessages; /** * Counts the number of message deleted */ private int nrDeletedMessages; /** * Counts the number of attached files saved in a file */ private int nrSavedAttachedFiles; /** * IMAP folder if user want to move some messages */ private Folder destinationIMAPFolder=null; private LogChannelInterface log; /** * Construct a new Database MailConnection * @param protocol the protocol used : MailConnection.PROTOCOL_POP3 or MailConnection.PROTOCOL_IMAP. * @param server the target server (ip ou name) * @param port port number on the server * @param password * @param usessl specify if the connection is established via SSL * @param useproxy specify if we use proxy authentication * @param proxyusername proxy authorised user */ public MailConnection(LogChannelInterface log, int protocol, String server, int port, String username, String password, boolean usessl, boolean useproxy, String proxyusername) throws KettleException { this.log=log; //Get system properties try { this.prop = System.getProperties(); } catch (SecurityException s) { this.prop = new Properties(); } this.port=port; this.server=server; this.username=username; this.password=password; this.usessl=usessl; this.protocol=protocol; this.nrSavedMessages=0; this.nrDeletedMessages=0; this.nrMovedMessages=0; this.nrSavedAttachedFiles=0; this.messagenr=-1; this.useproxy=useproxy; this.proxyusername=proxyusername; try{ if(useproxy) { // Need here to pass a proxy // use SASL authentication this.prop.put("mail.imap.sasl.enable", "true"); this.prop.put("mail.imap.sasl.authorizationid", proxyusername); } if(protocol==MailConnectionMeta.PROTOCOL_POP3) { this.prop.setProperty("mail.pop3s.rsetbeforequit","true"); this.prop.setProperty("mail.pop3.rsetbeforequit","true"); } String protocolString=(protocol==MailConnectionMeta.PROTOCOL_POP3)?"pop3":"imap"; if(usessl) { // Supports IMAP/POP3 connection with SSL, the connection is established via SSL. this.prop.setProperty("mail."+protocolString+".socketFactory.class", "javax.net.ssl.SSLSocketFactory"); this.prop.setProperty("mail."+protocolString+".socketFactory.fallback", "false"); this.prop.setProperty("mail."+protocolString+".port",""+port); this.prop.setProperty("mail."+protocolString+".socketFactory.port",""+port); //Create session object this.session = Session.getInstance(this.prop, null ); this.session.setDebug(log.isDebug()); if(this.port==-1) { this.port=((protocol==MailConnectionMeta.PROTOCOL_POP3)?MailConnectionMeta.DEFAULT_SSL_POP3_PORT:MailConnectionMeta.DEFAULT_SSL_IMAP_PORT); } URLName url = new URLName(protocolString, server, port, "", username, password); this.store = (protocol==MailConnectionMeta.PROTOCOL_POP3)?new POP3SSLStore(this.session, url):new IMAPSSLStore(this.session, url); url=null; } else { this.session = Session.getInstance(this.prop, null); this.session.setDebug(log.isDebug()); this.store = this.session.getStore(protocolString); } if(log.isDetailed()) log.logDetailed(toString(),BaseMessages.getString(PKG, "JobGetMailsFromPOP.NewConnectionDefined")); }catch(Exception e) { throw new KettleException(BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.NewConnection",Const.NVL(this.server,"")),e); } } /** * @return Returns the connection status. * true if the connection is still opened */ public boolean isConnected() { return (this.store!=null && this.store.isConnected()); } /** * @return Returns the use of SSL. * true if the connection use SSL */ public boolean isUseSSL() { return this.usessl; } /** * @return Returns the use of proxy. * true if the connection use proxy */ public boolean isUseProxy() { return this.useproxy; } /** * @return Returns the proxy username. */ public String getProxyUsername() { return this.proxyusername; } /** * @return Returns the store * */ public Store getStore() { return this.store; } /** * @return Returns the folder * */ public Folder getFolder() { return this.folder; } /** * Open the connection. * @throws KettleException if something went wrong. */ public void connect() throws KettleException { if(log.isDetailed()) log.logDetailed(toString(),BaseMessages.getString(PKG, "JobGetMailsFromPOP.Connecting",this.server, this.username, ""+this.port)); try{ if(this.usessl) { // Supports IMAP/POP3 connection with SSL, // the connection is established via SSL. this.store.connect(); }else { if(this.port>-1) this.store.connect(this.server,this.port,this.username,this.password); else this.store.connect(this.server,this.username,this.password); } if(log.isDetailed()) log.logDetailed(toString(),BaseMessages.getString(PKG, "JobGetMailsFromPOP.Connected",this.server, this.username, ""+this.port)); } catch(Exception e){ throw new KettleException(BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.Connecting",this.server, this.username, Const.NVL(""+this.port,"")),e); } } /** * Open the default folder (INBOX) * @param write open the folder in write mode * @throws KettleException if something went wrong. */ public void openFolder(boolean write) throws KettleException { openFolder(null, true, write); } /** * Open the folder. * @param foldername the name of the folder to open * @param write open the folder in write mode * @throws KettleException if something went wrong. */ public void openFolder(String foldername, boolean write) throws KettleException { openFolder(foldername, false, write); } /** * Open the folder. * @param foldername the name of the folder to open * @param defaultFolder true to open the default folder (INBOX) * @param write open the folder in write mode * @throws KettleException if something went wrong. */ public void openFolder(String foldername, boolean defaultFolder, boolean write) throws KettleException { this.write=write; try { if(getFolder()!=null) { // A folder is already opened //before make sure to close it closeFolder(true); } if(defaultFolder) { // get the default folder this.folder = this.store.getDefaultFolder().getFolder(MailConnectionMeta.INBOX_FOLDER); if(this.folder==null) throw new KettleException(BaseMessages.getString(PKG, "JobGetMailsFromPOP.InvalidDefaultFolder.Label")); if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) throw new KettleException(BaseMessages.getString(PKG, "MailConnection.DefaultFolderCanNotHoldMessage")); }else { // Open specified Folder (for IMAP) if(this.protocol==MailConnectionMeta.PROTOCOL_IMAP) { this.folder=this.store.getFolder(foldername); } if (this.folder == null || !this.folder.exists()) throw new KettleException(BaseMessages.getString(PKG, "JobGetMailsFromPOP.InvalidFolder.Label")); } if(this.write) { if(log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "MailConnection.OpeningFolderInWriteMode.Label", getFolderName())); this.folder.open(Folder.READ_WRITE); }else { if(log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "MailConnection.OpeningFolderInReadMode.Label", getFolderName())); this.folder.open(Folder.READ_ONLY); } if(log.isDetailed()) log.logDetailed(toString(), BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Label", getFolderName())); if(log.isDebug()) { // display some infos on folder log.logDebug(toString(), BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Name", getFolderName())); log.logDebug(toString(), BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.FullName", this.folder.getFullName())); log.logDebug(toString(), BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Url", this.folder.getURLName().toString())); log.logDebug(toString(), BaseMessages.getString(PKG, "JobGetMailsFromPOP.FolderOpened.Subscribed", ""+this.folder.isSubscribed())); } } catch (Exception e) { throw new KettleException(defaultFolder?BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.OpeningDefaultFolder"):BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.OpeningFolder",foldername),e); } } /** * Clear search terms. */ public void clearFilters() { this.nrSavedMessages=0; this.nrDeletedMessages=0; this.nrMovedMessages=0; this.nrSavedAttachedFiles=0; if(this.searchTerm!=null) { this.searchTerm=null; } } /** * Disconnect from the server and close folder, connection. * @throws KettleException */ public void disconnect() throws KettleException { disconnect(true); } /** * Close folder. * @param expunge expunge folder * @throws KettleException */ public void closeFolder(boolean expunge) throws KettleException { try { if(this.folder!=null && this.folder.isOpen()) { if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "MailConnection.ClosingFolder",getFolderName())); this.folder.close(expunge); this.folder=null; this.messages=null; this.message=null; this.messagenr=-1; if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "MailConnection.FolderClosed",getFolderName())); } }catch(Exception e){ throw new KettleException(BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.ClosingFolder",getFolderName()),e); } } /** * Add search term. * @param Term search term to add */ private void addSearchTerm(SearchTerm Term) { if (this.searchTerm != null) { this.searchTerm = new AndTerm(this.searchTerm, Term); } else { this.searchTerm = Term; } } /** * Set filter on subject. * @param subject messages will be filtered on subject * @param notTerm negate condition */ public void setSubjectTerm(String subject, boolean notTerm) { if (!Const.isEmpty(subject)) { if(notTerm) addSearchTerm(new NotTerm(new SubjectTerm(subject))); else addSearchTerm(new SubjectTerm(subject)); } } /** * Search all messages with body containing the word bodyfilter * @param bodyfilter * @param notTerm negate condition */ public void setBodyTerm(String bodyfilter, boolean notTerm) { if (!Const.isEmpty(bodyfilter)) { if(notTerm) addSearchTerm(new NotTerm(new BodyTerm(bodyfilter))); else addSearchTerm(new BodyTerm(bodyfilter)); } } /** * Set filter on message sender. * @param sender messages will be filtered on sender * @param notTerm negate condition */ public void setSenderTerm(String sender, boolean notTerm) { if (!Const.isEmpty(sender)) { if(notTerm) addSearchTerm(new NotTerm(new FromStringTerm(sender))); else addSearchTerm(new FromStringTerm(sender)); } } /** * Set filter on receipient. * @param receipient messages will be filtered on receipient * @param notTerm negate condition */ public void setReceipientTerm(String receipient) { if (!Const.isEmpty(receipient)) { addSearchTerm(new RecipientStringTerm(Message.RecipientType.TO,receipient)); } } /** * Set filter on message received date. * @param receiveddate messages will be filtered on receiveddate * @param notTerm negate condition */ public void setReceivedDateTermEQ(Date receiveddate) { addSearchTerm(new ReceivedDateTerm(ComparisonTerm.EQ, receiveddate)); } /** * Set filter on message received date. * @param futureDate messages will be filtered on futureDate * @param notTerm negate condition */ public void setReceivedDateTermLT(Date futureDate) { addSearchTerm(new ReceivedDateTerm(ComparisonTerm.LT, futureDate)); } /** * Set filter on message received date. * @param pastDate messages will be filtered on pastDate * @param notTerm negate condition */ public void setReceivedDateTermGT(Date pastDate) { addSearchTerm(new ReceivedDateTerm(ComparisonTerm.GT, pastDate)); } public void setReceivedDateTermBetween(Date beginDate, Date endDate) { addSearchTerm( new AndTerm(new ReceivedDateTerm(ComparisonTerm.LT, endDate), new ReceivedDateTerm(ComparisonTerm.GT, beginDate))); } public void setFlagTermNew() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.RECENT), true)); } public void setFlagTermOld() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.RECENT), false)); } public void setFlagTermRead() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.SEEN), true)); } public void setFlagTermUnread() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.SEEN), false)); } public void setFlagTermFlagged() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.FLAGGED), true)); } public void setFlagTermNotFlagged() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.FLAGGED), false)); } public void setFlagTermDraft() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.DRAFT), true)); } public void setFlagTermNotDraft() { addSearchTerm(new FlagTerm(new Flags(Flags.Flag.DRAFT), false)); } /** * Retrieve all messages from server * @throws KettleException */ public void retrieveMessages() throws KettleException { try { // search term? if(this.searchTerm!=null) { this.messages = this.folder.search(this.searchTerm); }else { this.messages = this.folder.getMessages(); } } catch (Exception e) { this.messages=null; throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.RetrieveMessages",getFolderName()),e); } } /* public void retrieveUnreadMessages() throws Exception { if(this.protocol==PROTOCOL_POP3) throw new KettleException("Cette fonction est uniquement accessible pour le protocol POP3!"); try { Message msgsAll[]; // search term? if(this.searchTerm!=null) { msgsAll = this.folder.search(this.searchTerm); }else { msgsAll = this.folder.getMessages(); } int unreadMsgs = this.folder.getUnreadMessageCount(); int msgCount = msgsAll.length; this.messages = this.folder.getMessages(msgCount - unreadMsgs + 1, msgCount); } catch (Exception e) { this.messages= null; } }*/ /** * Disconnect from the server and close folder, connection. * @param expunge expunge folder * @throws KettleException */ public void disconnect(boolean expunge) throws KettleException { if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "MailConnection.ClosingConnection")); try{ //close the folder, passing in a true value to expunge the deleted message closeFolder(expunge); clearFilters(); if(this.store != null) {this.store.close();this.store=null;} if(this.session != null) {this.session=null;} if(this.destinationIMAPFolder!=null) this.destinationIMAPFolder.close(expunge); if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "MailConnection.ConnectionClosed")); }catch(Exception e) { throw new KettleException(BaseMessages.getString(PKG, "JobGetMailsFromPOP.Error.ClosingConnection"),e); } } /** * Export message content to a filename. * @param filename the target filename * @param foldername the parent folder of filename * @throws KettleException. */ public void saveMessageContentToFile(String filename, String foldername) throws KettleException { File file=null; OutputStream os= null; try { file = new File(foldername,filename); os = new FileOutputStream(file); getMessage().writeTo(os); updateSavedMessagesCounter(); }catch(Exception e) { throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.SavingMessageContent", ""+this.message.getMessageNumber(), filename, foldername),e); }finally { if(os!=null) { try{ os.close();os=null; }catch(Exception e){}; } if(file!=null) file=null; } } /** * Save attached files to a folder. * @param foldername the target foldername * @throws KettleException. */ public void saveAttachedFiles(String foldername) throws KettleException { saveAttachedFiles(foldername, null); } /** * Save attached files to a folder. * @param foldername the target foldername * @param pattern regular expression to filter on files * @throws KettleException. */ public void saveAttachedFiles(String foldername, Pattern pattern) throws KettleException { Object content=null; try { content = getMessage().getContent(); if (content instanceof Multipart) { handleMultipart(foldername,(Multipart)content, pattern); } }catch(Exception e) { throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.SavingAttachedFiles",""+this.message.getMessageNumber(), foldername),e); }finally { if(content!=null) content=null; } } private void handleMultipart(String foldername,Multipart multipart, Pattern pattern) throws KettleException { try { for (int i=0, n=multipart.getCount(); i<n; i++) { handlePart(foldername,multipart.getBodyPart(i), pattern); } }catch(Exception e) { throw new KettleException(e); } } private void handlePart(String foldername,Part part,Pattern pattern) throws KettleException { try { String disposition = part.getDisposition(); // The RFC2183 doesn't REQUIRE Content-Disposition header field so we'll create one to // fake out the code below. if (disposition == null || disposition.length() < 1) { disposition = Part.ATTACHMENT; } if ( disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE) ) { String MimeText=null; try{ MimeText=MimeUtility.decodeText(part.getFileName()); }catch(Exception e){} // ignore this .. if(MimeText!=null) { String filename=MimeUtility.decodeText(part.getFileName()); if(isWildcardMatch(filename, pattern)) { // Save file saveFile(foldername,filename, part.getInputStream()); updateSavedAttachedFilesCounter(); if(log.isDetailed()) log.logDetailed(toString(),BaseMessages.getString(PKG, "JobGetMailsFromPOP.AttachedFileSaved", filename,""+getMessage().getMessageNumber(),foldername)); } } } }catch(Exception e) { throw new KettleException(e); } } private static void saveFile(String foldername,String filename, InputStream input) throws KettleException { FileOutputStream fos=null; BufferedOutputStream bos=null; File file=null; BufferedInputStream bis =null; try { if (filename == null) { filename = File.createTempFile("xx", ".out").getName(); } // Do no overwrite existing file file = new File(foldername,filename); for (int i=0; file.exists(); i++) { file = new File(foldername,filename+i); } fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bis = new BufferedInputStream(input); int aByte; while ((aByte = bis.read()) != -1) { bos.write(aByte); } }catch(Exception e) { throw new KettleException(e); }finally { try { if(bos!=null) { bos.flush();bos.close();}; if(bis!=null) {bis.close();bis=null;}; file=null;}catch(Exception e){}; } } private boolean isWildcardMatch(String filename, Pattern pattern) { boolean retval=true; if (pattern!=null){ Matcher matcher = pattern.matcher(filename); retval= (matcher.matches()); } return retval; } /** * Delete current fetched message * @throws KettleException */ public void deleteMessage() throws KettleException { try{ this.message.setFlag(Flags.Flag.DELETED, true); updateDeletedMessagesCounter(); }catch(Exception e){ throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.DeletingMessage",""+getMessage().getMessageNumber()),e); } } /** * Set destination folder * @param foldername destination foldername * @param createFolder flag create folder if needed * @throws KettleException */ public void setDestinationFolder(String foldername, boolean createFolder) throws KettleException { try { // Open destination folder this.destinationIMAPFolder = store.getFolder(foldername); if(!this.destinationIMAPFolder.exists()) { if(createFolder) { // Create folder this.destinationIMAPFolder.create(Folder.HOLDS_MESSAGES); }else { throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.FolderNotFound",foldername)); } } }catch(Exception e) { throw new KettleException(e); } } /** * Move current message to a target folder. (IMAP) * You must call setDestinationFolder before calling this method * @throws KettleException */ public void moveMessage() throws KettleException { try { // move all messages this.folder.copyMessages(new Message[] {this.message}, this.destinationIMAPFolder); updatedMovedMessagesCounter(); // Make sure to delete messages deleteMessage(); }catch(Exception e) { throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.MovingMessage","" +getMessage().getMessageNumber(), this.destinationIMAPFolder.getName()),e); } } /** * Returns the foldername. * @return foldername */ public String getFolderName(){ if(this.folder==null) return ""; return this.folder.getName(); } /** * Returns the server name/Ip. * @return server */ public String getServer() { return server; } /** * Returns the protocol. * @return protocol */ public int getProtocol() { return protocol; } /** * Returns all messages. * @return all messages */ public Message[] getMessages() { return messages; } private void updateMessageNr() { this.messagenr++; } private int getMessageNr() { return this.messagenr; } /** * Get next message. * @throws KettleException */ public void fetchNext() throws KettleException { updateMessageNr(); try{ this.message= this.messages[getMessageNr()]; }catch(Exception e){ throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.FetchingMessages"),e); } } /** * Returns the current message. * @return current message */ public Message getMessage() { return this.message; } /** * Returns the number of messages. * @return messages count */ public int getMessagesCount() { return this.messages.length; } public void updateSavedMessagesCounter(){ this.nrSavedMessages++; } public int getSavedMessagesCounter() { return this.nrSavedMessages; } public int getSavedAttachedFilesCounter() { return this.nrSavedAttachedFiles; } public void updateSavedAttachedFilesCounter(){ this.nrSavedAttachedFiles++; } public int getDeletedMessagesCounter() { return this.nrDeletedMessages; } private void updateDeletedMessagesCounter(){ this.nrDeletedMessages++; } private void setDeletedMessagesCounter(){ this.nrDeletedMessages=getMessagesCount(); } /** * Returns count of moved messages. * @return count of moved messages */ public int getMovedMessagesCounter() { return this.nrMovedMessages; } /** * Update count of moved messages. */ private void updatedMovedMessagesCounter(){ this.nrMovedMessages++; } /** * Set count of moved messages. */ private void setMovedMessagesCounter(){ this.nrMovedMessages=getMessagesCount(); } /** * Delete messages. * @throws KettleException */ public void deleteMessages(boolean setCounter) throws KettleException { try { this.folder.setFlags(this.messages, new Flags(Flags.Flag.DELETED), true); if(setCounter) setDeletedMessagesCounter(); } catch(Exception e) { throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.DeletingMessage"),e); } } /** * Move messages to a folder. * You must call setDestinationFolder before calling this method * @throws KettleException */ public void moveMessages() throws KettleException { try { this.folder.copyMessages(this.messages, this.destinationIMAPFolder); deleteMessages(false); setMovedMessagesCounter(); }catch(Exception e) { throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.MovingMessages", this.destinationIMAPFolder.getName()),e); } } /** * Check if a folder exists on server (only IMAP). * @param foldername the name of the folder * @return true is folder exists */ public boolean folderExists(String foldername) { boolean retval =false; Folder dfolder=null; try { // Open destination folder dfolder = this.store.getFolder(foldername); if(dfolder.exists()) retval=true; }catch(Exception e) { } finally { try { if(dfolder!=null) dfolder.close(false); }catch(Exception e){}; } return retval; } private HashSet<String> returnSubfolders(Folder folder) throws KettleException{ HashSet<String> list= new HashSet<String>(); try { if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { Folder[] f = folder.list(); for (int i = 0; i < f.length; i++) { // Search for sub folders if ((f[i].getType() & Folder.HOLDS_FOLDERS) != 0) { list.add(f[i].getFullName()); list.addAll(returnSubfolders(f[i])); } } } }catch(MessagingException m) { throw new KettleException(m); } return list; } /** * Returns all subfolders * of the specified folder * @param taget parent folder * @return sub folders */ public String[] returnAllFolders(Folder folder) throws KettleException { HashSet<String> list= new HashSet<String>(); list=returnSubfolders(folder); return (String[]) list.toArray(new String[list.size()]); } /** * Returns all subfolders * of the current folder * @return sub folders */ public String[] returnAllFolders() throws KettleException { return returnAllFolders(getFolder()); } /** * Returns all subfolders * of the folder folder * @param folder target folder * @return sub folders */ public String[] returnAllFolders(String folder) throws KettleException { Folder dfolder=null; String[] retval=null; try { if(Const.isEmpty(folder)) { // Default folder dfolder=getStore().getDefaultFolder(); }else { dfolder = getStore().getFolder(folder); } retval= returnAllFolders(dfolder); }catch(Exception e) { } finally { try { if(dfolder!=null) dfolder.close(false); }catch(Exception e){}; } return retval; } public String getMessageBody() throws Exception { return getMessageBody((Part) getMessage()); } /** * Return the primary text content of the message. */ private String getMessageBody(Part p) throws MessagingException, Exception { /** * Returns if message is new * @return true if new message */ public boolean isMessageNew() { try { return getMessage().isSet(Flag.RECENT); } catch(MessagingException e) { return false; } } /** * Returns if message is read * @return true if message is read */ public boolean isMessageRead() { try { return getMessage().isSet(Flag.SEEN); } catch(MessagingException e) { return false; } } /** * Returns if message is read * @return true if message is flagged */ public boolean isMessageFlagged() { try { return getMessage().isSet(Flag.FLAGGED); } catch(MessagingException e) { return false; } } /** * Returns if message is deleted * @return true if message is deleted */ public boolean isMessageDeleted() { try { return getMessage().isSet(Flag.DELETED); } catch(MessagingException e) { return false; } } /** * Returns if message is Draft * @return true if message is Draft */ public boolean isMessageDraft() { try { return getMessage().isSet(Flag.DRAFT); } catch(MessagingException e) { return false; } } public String toString() { if (getServer()!=null) return getServer(); else return "-"; } /** * Returns attached files count for the current message * @return true if message is Draft * @param pattern (optional) */ public int getAttachedFilesCount(Pattern pattern) throws KettleException { Object content=null; int retval=0; try { content = getMessage().getContent(); if (content instanceof Multipart) { Multipart multipart=(Multipart)content; for (int i=0, n=multipart.getCount(); i<n; i++) { Part part=multipart.getBodyPart(i); String disposition = part.getDisposition(); if ((disposition != null) && ( disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE) ) ) { String MimeText=null; try{ MimeText=MimeUtility.decodeText(part.getFileName()); }catch(Exception e){} // ignore this .. if(MimeText!=null) { String filename=MimeUtility.decodeText(part.getFileName()); if(isWildcardMatch(filename, pattern)) retval++; } } } } }catch(Exception e) { throw new KettleException(BaseMessages.getString(PKG, "MailConnection.Error.CountingAttachedFiles", ""+this.message.getMessageNumber()),e); }finally { if(content!=null) content=null; } return retval; } }
package org.pentaho.di.trans.steps.hbaseinput; import java.io.IOException; import java.net.URL; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HTable; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.filter.CompareFilter; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.RegexStringComparator; import org.apache.hadoop.hbase.filter.SingleColumnValueFilter; import org.apache.hadoop.hbase.filter.SubstringComparator; import org.apache.hadoop.hbase.filter.WritableByteArrayComparable; import org.apache.hadoop.hbase.util.Bytes; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.hbase.mapping.DeserializedBooleanComparator; import org.pentaho.hbase.mapping.DeserializedNumericComparator; import org.pentaho.hbase.mapping.HBaseValueMeta; import org.pentaho.hbase.mapping.Mapping; import org.pentaho.hbase.mapping.MappingAdmin; /** * Class providing an input step for reading data from an HBase table * according to meta data mapping info stored in a separate HBase table * called "pentaho_mappings". See org.pentaho.hbase.mapping.Mapping for * details on the meta data format. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision$ * */ public class HBaseInput extends BaseStep implements StepInterface { protected HBaseInputMeta m_meta; protected HBaseInputData m_data; protected TransMeta m_transMeta; public HBaseInput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); m_transMeta = transMeta; } /** Configuration object for connecting to HBase */ protected Configuration m_connection; /** The mapping admin object for interacting with mapping information */ protected MappingAdmin m_mappingAdmin; /** The mapping information to use in order to decode HBase column values */ protected Mapping m_tableMapping; /** Information from the mapping */ protected Map<String, HBaseValueMeta> m_columnsMappedByAlias; /** User-selected columns from the mapping (null indicates output all columns) */ protected List<HBaseValueMeta> m_userOutputColumns; /** Table object for the table to read from */ protected HTable m_sourceTable; /** Scanner over the result rows */ protected ResultScanner m_resultSet; public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { if (first) { first = false; m_meta = (HBaseInputMeta)smi; m_data = (HBaseInputData)sdi; // Get the connection to HBase try { m_connection = HBaseInputData. getHBaseConnection(m_transMeta.environmentSubstitute(m_meta.getZookeeperHosts()), HBaseInputData. stringToURL(m_transMeta.environmentSubstitute(m_meta.getCoreConfigURL())), HBaseInputData. stringToURL(m_transMeta.environmentSubstitute(m_meta.getDefaultConfigURL()))); } catch (IOException ex) { throw new KettleException("Unable to obtain a connection to HBase."); } try { m_mappingAdmin = new MappingAdmin(m_connection); } catch (Exception ex) { throw new KettleException("Unable to create a MappingAdmin connection"); } // check on the existence and readiness of the target table HBaseAdmin admin = null; try { admin = new HBaseAdmin(m_connection); } catch (Exception ex) { throw new KettleException("Unable to obtain a connection to HBase."); } String sourceName = m_transMeta.environmentSubstitute(m_meta.getSourceTableName()); try { if (!admin.tableExists(sourceName)) { throw new KettleException("Source table \"" + sourceName + "\" does not exist!"); } if (admin.isTableDisabled(sourceName) || !admin.isTableAvailable(sourceName)) { throw new KettleException("Source table \"" + sourceName + "\" is not available!"); } } catch (IOException ex) { throw new KettleException("A problem occurred when trying to check " + "availablility/readyness of source table \"" + sourceName + "\""); } // Get mapping details for the source table try { m_tableMapping = m_mappingAdmin.getMapping(m_transMeta. environmentSubstitute(m_meta.getSourceTableName()), m_transMeta.environmentSubstitute(m_meta.getSourceMappingName())); m_columnsMappedByAlias = m_tableMapping.getMappedColumns(); } catch (IOException ex) { throw new KettleException(ex.getMessage()); } // conversion mask to use for user specified key values in range scan. // This can come from user-specified field information OR it can be // provided in the keyStart/keyStop values by suffixing the value with // "@converionMask" String dateOrNumberConversionMaskForKey = null; // if there are any user-chosen output fields in the meta data then // check them against table mapping. All selected fields must be present // in the mapping m_userOutputColumns = m_meta.getOutputFields(); if (m_userOutputColumns != null && m_userOutputColumns.size() > 0) { for (HBaseValueMeta vm : m_userOutputColumns) { if (!vm.isKey()) { if (m_columnsMappedByAlias.get(vm.getAlias()) == null) { throw new KettleException("Unable to find user-selected column " + "\"" + vm.getAlias() + "\" in the table mapping \"" + m_tableMapping.getTableName() + HBaseValueMeta.SEPARATOR + m_tableMapping.getMappingName() + "\""); } } else { dateOrNumberConversionMaskForKey = vm.getConversionMask(); } } } // Set up the scan Scan s = null; if (Const.isEmpty(m_meta.getKeyStartValue()) && Const.isEmpty(m_meta.getKeyStopValue())) { s = new Scan(); // scan all rows } else { byte[] keyLowerBound = null; String keyStartS = m_transMeta.environmentSubstitute(m_meta.getKeyStartValue()); String convM = dateOrNumberConversionMaskForKey; if (m_tableMapping.getKeyType() != Mapping.KeyType.STRING) { // allow a conversion mask in the start key field to override any specified for // the key in the user specified fields String[] parts = keyStartS.split("@"); if (parts.length == 2) { keyStartS = parts[0]; convM = parts[1]; } if (!Const.isEmpty(convM) && convM.length() > 0) { if (m_tableMapping.getKeyType() == Mapping.KeyType.DATE || m_tableMapping.getKeyType() == Mapping.KeyType.UNSIGNED_DATE) { SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern(convM); try { Date d = sdf.parse(keyStartS); keyLowerBound = HBaseValueMeta.encodeKeyValue(d, m_tableMapping.getKeyType()); } catch (ParseException e) { throw new KettleException("Unable to parse lower bound key value \"" + keyStartS + "\""); } } else { // Number type // Double/Float or Long/Integer DecimalFormat df = new DecimalFormat(); df.applyPattern(convM); Number num = null; try { num = df.parse(keyStartS); keyLowerBound = HBaseValueMeta.encodeKeyValue(num, m_tableMapping.getKeyType()); } catch (ParseException e) { throw new KettleException("Unable to parse lower bound key value \"" + keyStartS + "\""); } } } else { // just try it as a string keyLowerBound = HBaseValueMeta. encodeKeyValue(keyStartS, m_tableMapping.getKeyType()); } } else { // it is a string keyLowerBound = HBaseValueMeta. encodeKeyValue(keyStartS, m_tableMapping.getKeyType()); } if (Const.isEmpty(m_meta.getKeyStopValue())) { s = new Scan(keyLowerBound); } else { byte[] keyUpperBound = null; String keyStopS = m_transMeta.environmentSubstitute(m_meta.getKeyStopValue()); convM = dateOrNumberConversionMaskForKey; if (m_tableMapping.getKeyType() != Mapping.KeyType.STRING) { // allow a conversion mask in the stop key field to override any specified for // the key in the user specified fields String[] parts = keyStopS.split("@"); if (parts.length == 2) { keyStopS = parts[0]; convM = parts[1]; } if (!Const.isEmpty(convM) && convM.length() > 0) { if (m_tableMapping.getKeyType() == Mapping.KeyType.DATE || m_tableMapping.getKeyType() == Mapping.KeyType.UNSIGNED_DATE) { SimpleDateFormat sdf = new SimpleDateFormat(); sdf.applyPattern(convM); try { Date d = sdf.parse(keyStopS); keyUpperBound = HBaseValueMeta.encodeKeyValue(d, m_tableMapping.getKeyType()); } catch (ParseException e) { throw new KettleException("Unable to parse upper bound key value \"" + keyStopS + "\""); } } else { // Number type // Double/Float or Long/Integer DecimalFormat df = new DecimalFormat(); df.applyPattern(convM); Number num = null; try { num = df.parse(keyStopS); keyUpperBound = HBaseValueMeta.encodeKeyValue(num, m_tableMapping.getKeyType()); } catch (ParseException e) { throw new KettleException("Unable to parse upper bound key value \"" + keyStopS + "\""); } } } else { // just try it as a string keyUpperBound = HBaseValueMeta. encodeKeyValue(keyStopS, m_tableMapping.getKeyType()); } } else { // it is a string keyUpperBound = HBaseValueMeta. encodeKeyValue(keyStartS, m_tableMapping.getKeyType()); } s = new Scan(keyLowerBound, keyUpperBound); } } // set any user-specified scanner caching if (!Const.isEmpty(m_meta.getScannerCacheSize())) { String temp = m_transMeta.environmentSubstitute(m_meta.getScannerCacheSize()); int sc = Integer.parseInt(temp); s.setCaching(sc); logBasic("Set scanner caching to " + sc + " rows."); } // LIMIT THE SCAN TO JUST THE COLUMNS IN THE MAPPING // User-selected output columns? if (m_userOutputColumns != null && m_userOutputColumns.size() > 0) { for (HBaseValueMeta currentCol : m_userOutputColumns) { if (!currentCol.isKey()) { String colFamilyName = currentCol.getColumnFamily(); String qualifier = currentCol.getColumnName(); s.addColumn(Bytes.toBytes(colFamilyName), Bytes.toBytes(qualifier)); } } } else { // all the columns in the mapping Set<String> aliasSet = m_columnsMappedByAlias.keySet(); for (String name : aliasSet) { HBaseValueMeta currentCol = m_columnsMappedByAlias.get(name); String colFamilyName = currentCol.getColumnFamily(); String qualifier = currentCol.getColumnName(); s.addColumn(Bytes.toBytes(colFamilyName), Bytes.toBytes(qualifier)); } } // set any filters if (m_meta.getColumnFilters() != null && m_meta.getColumnFilters().size() > 0) { FilterList fl = null; if (m_meta.getMatchAnyFilter()) { fl = new FilterList(FilterList.Operator.MUST_PASS_ONE); } else { fl = new FilterList(FilterList.Operator.MUST_PASS_ALL); } for (ColumnFilter cf : m_meta.getColumnFilters()) { HBaseValueMeta mappedCol = m_columnsMappedByAlias.get(cf.getFieldAlias()); if (mappedCol == null) { throw new KettleException("Column filter \"" + cf.getFieldAlias() + "\" is not in the mapping!"); } // check the type (if set in the ColumnFilter) against the type // of this field in the mapping if (!Const.isEmpty(cf.getFieldType())) { if (!mappedCol.getHBaseTypeDesc().equalsIgnoreCase(cf.getFieldType())) { throw new KettleException("Type (" + cf.getFieldType() + ") of column filter for \"" + cf.getFieldAlias() + "\" does not match type specified " + "for this field in the mapping (" + mappedCol.getHBaseTypeDesc() + ")"); } } CompareFilter.CompareOp comp = null; byte[] family = Bytes.toBytes(mappedCol.getColumnFamily()); byte[] qualifier = Bytes.toBytes(mappedCol.getColumnName()); ColumnFilter.ComparisonType op = cf.getComparisonOperator(); switch (op) { case EQUAL: comp = CompareFilter.CompareOp.EQUAL; break; case NOT_EQUAL: comp = CompareFilter.CompareOp.NOT_EQUAL; break; case GREATER_THAN: comp = CompareFilter.CompareOp.GREATER; break; case GREATER_THAN_OR_EQUAL: comp = CompareFilter.CompareOp.GREATER_OR_EQUAL; break; case LESS_THAN: comp = CompareFilter.CompareOp.LESS; break; case LESS_THAN_OR_EQUAL: comp = CompareFilter.CompareOp.LESS_OR_EQUAL; break; } String comparisonString = cf.getConstant().trim(); if (comp != null) { byte[] comparisonRaw = null; // do the numeric comparison stuff if (mappedCol.isNumeric()) { // Double/Float or Long/Integer DecimalFormat df = new DecimalFormat(); if (!Const.isEmpty(cf.getFormat())) { df.applyPattern(cf.getFormat()); } Number num = null; try { num = df.parse(comparisonString); } catch (ParseException e) { throw new KettleException(e.getMessage()); } if (mappedCol.isInteger()) { if (!mappedCol.getIsLongOrDouble()) { comparisonRaw = Bytes.toBytes(num.intValue()); } else { comparisonRaw = Bytes.toBytes(num.longValue()); } } else { if (!mappedCol.getIsLongOrDouble()) { comparisonRaw = Bytes.toBytes(num.floatValue()); } else { comparisonRaw = Bytes.toBytes(num.doubleValue()); } } if (!cf.getSignedComparison()) { // comparisonRaw = Bytes.toBytes(compI); SingleColumnValueFilter scf = new SingleColumnValueFilter(family, qualifier, comp, comparisonRaw); scf.setFilterIfMissing(true); fl.addFilter(scf); } else { // custom comparator for signed comparison DeserializedNumericComparator comparator = null; if (mappedCol.isInteger()) { if (mappedCol.getIsLongOrDouble()) { comparator = new DeserializedNumericComparator(mappedCol.isInteger(), mappedCol.getIsLongOrDouble(), num.longValue()); } else { comparator = new DeserializedNumericComparator(mappedCol.isInteger(), mappedCol.getIsLongOrDouble(), num.intValue()); } } else { if (mappedCol.getIsLongOrDouble()) { comparator = new DeserializedNumericComparator(mappedCol.isInteger(), mappedCol.getIsLongOrDouble(), num.doubleValue()); } else { comparator = new DeserializedNumericComparator(mappedCol.isInteger(), mappedCol.getIsLongOrDouble(), num.floatValue()); } } SingleColumnValueFilter scf = new SingleColumnValueFilter(family, qualifier, comp, comparator); scf.setFilterIfMissing(true); fl.addFilter(scf); } } else if (mappedCol.isDate()) { SimpleDateFormat sdf = new SimpleDateFormat(); if (!Const.isEmpty(cf.getFormat())) { sdf.applyPattern(cf.getFormat()); } Date d = null; try { d = sdf.parse(comparisonString); } catch (ParseException e) { throw new KettleException(e.getMessage()); } long dateAsMillis = d.getTime(); if (!cf.getSignedComparison()) { comparisonRaw = Bytes.toBytes(dateAsMillis); SingleColumnValueFilter scf = new SingleColumnValueFilter(family, qualifier, comp, comparisonRaw); scf.setFilterIfMissing(true); fl.addFilter(scf); } else { // custom comparator for signed comparison DeserializedNumericComparator comparator = new DeserializedNumericComparator(true, true, dateAsMillis); SingleColumnValueFilter scf = new SingleColumnValueFilter(family, qualifier, comp, comparator); scf.setFilterIfMissing(true); fl.addFilter(scf); } } else if (mappedCol.isBoolean()) { // temporarily encode it so that we can use the utility routine in HBaseValueMeta byte[] tempEncoded = Bytes.toBytes(comparisonString); Boolean decodedB = HBaseValueMeta.decodeBoolFromString(tempEncoded); // skip if we can't parse the comparison value if (decodedB == null) { continue; } // System.err.println("::::::::::::: Here " + decodedB); DeserializedBooleanComparator comparator = new DeserializedBooleanComparator(decodedB.booleanValue()); SingleColumnValueFilter scf = new SingleColumnValueFilter(family, qualifier, comp, comparator); scf.setFilterIfMissing(true); fl.addFilter(scf); } } else { WritableByteArrayComparable comparator = null; comp = CompareFilter.CompareOp.EQUAL; if (cf.getComparisonOperator() == ColumnFilter.ComparisonType.SUBSTRING) { comparator = new SubstringComparator(comparisonString); } else { comparator = new RegexStringComparator(comparisonString); } SingleColumnValueFilter scf = new SingleColumnValueFilter(family, qualifier, comp, comparator); scf.setFilterIfMissing(true); fl.addFilter(scf); } } if (fl != null && fl.getFilters().size() > 0) { s.setFilter(fl); } } try { m_sourceTable = new HTable(m_connection, m_tableMapping.getTableName()); m_resultSet = m_sourceTable.getScanner(s); } catch (IOException e) { throw new KettleException(e.getMessage()); } // set up the output fields (using the mapping) m_data.setOutputRowMeta(new RowMeta()); m_meta.getFields(m_data.getOutputRowMeta(), getStepname(), null, null, this); } Result r = null; try { r = m_resultSet.next(); } catch (IOException e) { throw new KettleException(e.getMessage()); } if (r == null) { m_resultSet.close(); try { m_sourceTable.close(); } catch (IOException e) { throw new KettleException("Problem closing connection to HBase table: " + e.getMessage()); } setOutputDone(); return false; } int size = (m_userOutputColumns != null && m_userOutputColumns.size() > 0) ? m_userOutputColumns.size() : m_tableMapping.getMappedColumns().keySet().size() + 1; // + 1 for the key Object[] outputRowData = RowDataUtil.allocateRowData(size); // User-selected output columns? if (m_userOutputColumns != null && m_userOutputColumns.size() > 0) { for (HBaseValueMeta currentCol : m_userOutputColumns) { if (currentCol.isKey()) { byte[] rawKey = r.getRow(); Object decodedKey = HBaseValueMeta.decodeKeyValue(rawKey, m_tableMapping); int keyIndex = m_data.getOutputRowMeta().indexOfValue(currentCol.getAlias()); outputRowData[keyIndex] = decodedKey; } else { String colFamilyName = currentCol.getColumnFamily(); String qualifier = currentCol.getColumnName(); KeyValue kv = r.getColumnLatest(Bytes.toBytes(colFamilyName), Bytes.toBytes(qualifier)); int outputIndex = m_data.getOutputRowMeta().indexOfValue(currentCol.getAlias()); if (outputIndex < 0) { throw new KettleException("HBase column \"" + currentCol.getAlias() + "\" doesn't seem to be defined in the output"); } Object decodedVal = HBaseValueMeta.decodeColumnValue(kv, currentCol); outputRowData[outputIndex] = decodedVal; } } } else { // all the columns in the mapping // do the key first byte[] rawKey = r.getRow(); Object decodedKey = HBaseValueMeta.decodeKeyValue(rawKey, m_tableMapping); int keyIndex = m_data.getOutputRowMeta().indexOfValue(m_tableMapping.getKeyName()); outputRowData[keyIndex] = decodedKey; Set<String> aliasSet = m_columnsMappedByAlias.keySet(); for (String name : aliasSet) { HBaseValueMeta currentCol = m_columnsMappedByAlias.get(name); String colFamilyName = currentCol.getColumnFamily(); String qualifier = currentCol.getColumnName(); KeyValue kv = r.getColumnLatest(Bytes.toBytes(colFamilyName), Bytes.toBytes(qualifier)); int outputIndex = m_data.getOutputRowMeta().indexOfValue(name); if (outputIndex < 0) { throw new KettleException("HBase column \"" + name + "\" doesn't seem " + "to be defined in the output"); } Object decodedVal = HBaseValueMeta.decodeColumnValue(kv, currentCol); outputRowData[outputIndex] = decodedVal; } } // output the row putRow(m_data.getOutputRowMeta(), outputRowData); return true; } // TODO handle error rows (see CsvInput). Unexpected lengths of values in columns // perhaps could be sent to the error stream somehow. // Do we need this?? /* public boolean isWaitingForData() { return true; } */ }
package org.torproject.jtor.circuits.impl; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import javax.net.ssl.SSLSocket; import org.torproject.jtor.TorException; import org.torproject.jtor.circuits.Circuit; import org.torproject.jtor.circuits.Connection; import org.torproject.jtor.circuits.ConnectionClosedException; import org.torproject.jtor.circuits.ConnectionConnectException; import org.torproject.jtor.circuits.cells.Cell; import org.torproject.jtor.crypto.TorRandom; import org.torproject.jtor.directory.Router; import org.torproject.jtor.logging.Logger; /** * This class represents a transport link between two onion routers or * between an onion proxy and an entry router. * */ public class ConnectionImpl implements Connection { private final static int DEFAULT_CONNECT_TIMEOUT = 10000; private final SSLSocket socket; private final ConnectionManagerImpl manager; private final Logger logger; private InputStream input; private OutputStream output; private final Router router; private final Map<Integer, CircuitImpl> circuitMap; private final BlockingQueue<Cell> connectionControlCells; private int currentId = 1; private boolean isConnected; private final Thread readCellsThread; ConnectionImpl(ConnectionManagerImpl manager, Logger logger, SSLSocket socket, Router router) { this.manager = manager; this.logger = logger; this.socket = socket; this.router = router; this.circuitMap = new HashMap<Integer, CircuitImpl>(); this.readCellsThread = new Thread(createReadCellsRunnable()); this.readCellsThread.setDaemon(true); this.connectionControlCells = new LinkedBlockingQueue<Cell>(); initializeCurrentCircuitId(); } private void initializeCurrentCircuitId() { final TorRandom random = new TorRandom(); currentId = random.nextInt(0xFFFF) + 1; } public Router getRouter() { return router; } int allocateCircuitId(CircuitImpl circuit) { synchronized(circuitMap) { while(circuitMap.containsKey(currentId)) incrementNextId(); circuitMap.put(currentId, circuit); return currentId; } } private void incrementNextId() { currentId++; if(currentId > 0xFFFF) currentId = 1; } public boolean isConnected() { return isConnected; } public void connect() { if(isConnected) return; try { doConnect(); } catch (SocketTimeoutException e) { throw new ConnectionConnectException("Connect timed out"); } catch (IOException e) { throw new ConnectionConnectException(e.getMessage()); } catch (InterruptedException e) { throw new ConnectionConnectException("Handshake interrupted"); } manager.addActiveConnection(this); isConnected = true; } private void doConnect() throws IOException, InterruptedException { socket.connect(routerToSocketAddress(router), DEFAULT_CONNECT_TIMEOUT); input = socket.getInputStream(); output = socket.getOutputStream(); readCellsThread.start(); final ConnectionHandshakeV2 handshake = new ConnectionHandshakeV2(this, socket); handshake.runHandshake(); } private SocketAddress routerToSocketAddress(Router router) { final InetAddress address = router.getAddress().toInetAddress(); return new InetSocketAddress(address, router.getOnionPort()); } public void sendCell(Cell cell) { if(!socket.isConnected()) throw new ConnectionClosedException("Cannot send cell because connection is not connected"); synchronized(output) { try { output.write(cell.getCellBytes()); } catch (IOException e) { closeSocket(); manager.removeActiveConnection(this); throw new ConnectionClosedException(); } } } private Cell recvCell() { try { return CellImpl.readFromInputStream(input); } catch (IOException e) { closeSocket(); manager.removeActiveConnection(this); throw new ConnectionClosedException(); } } private void closeSocket() { try { socket.close(); isConnected = false; } catch (IOException e) { logger.warning("Error closing socket: "+ e.getMessage()); } } private Runnable createReadCellsRunnable() { return new Runnable() { public void run() { readCellsLoop(); } }; } private void readCellsLoop() { while(!Thread.interrupted()) { try { processCell( recvCell() ); } catch(ConnectionClosedException e) { notifyCircuitsLinkClosed(); return; } catch(TorException e) { logger.warning("Unhandled Tor exception reading and processing cells: "+ e.getMessage()); e.printStackTrace(); } } } private void notifyCircuitsLinkClosed() { } Cell readConnectionControlCell() { try { return connectionControlCells.take(); } catch (InterruptedException e) { closeSocket(); throw new ConnectionClosedException(); } } private void processCell(Cell cell) { final int command = cell.getCommand(); if(command == Cell.RELAY) { processRelayCell(cell); return; } switch(command) { case Cell.NETINFO: case Cell.VERSIONS: connectionControlCells.add(cell); break; case Cell.CREATED: case Cell.CREATED_FAST: processControlCell(cell); break; case Cell.DESTROY: processDestroyCell(cell); break; default: // Ignore everything else break; } } private void processRelayCell(Cell cell) { synchronized(circuitMap) { final CircuitImpl circuit = circuitMap.get(cell.getCircuitId()); if(circuit == null) { logger.warning("Could not deliver relay cell for circuit id = "+ cell.getCircuitId() +" on connection "+ this +". Circuit not found"); return; } circuit.deliverRelayCell(cell); } } private void processControlCell(Cell cell) { synchronized(circuitMap) { final CircuitImpl circuit = circuitMap.get(cell.getCircuitId()); if(circuit == null) { logger.warning("Could not deliver control cell for circuit id = "+ cell.getCircuitId() +" on connection "+ this +". Circuit not found"); return; } circuit.deliverControlCell(cell); } } private void processDestroyCell(Cell cell) { logger.debug("DESTROY cell received ("+ CellImpl.errorToDescription(cell.getByte() & 0xFF) +")"); synchronized(circuitMap) { final CircuitImpl circuit = circuitMap.remove(cell.getCircuitId()); if(circuit == null) return; circuit.destroyCircuit(); } } void removeCircuit(Circuit circuit) { synchronized(circuitMap) { circuitMap.remove(circuit.getCircuitId()); if(circuitMap.size() == 0) { manager.removeActiveConnection(this); closeSocket(); } } } public String toString() { return "!" + router.getNickname() + "!"; } }
package gov.nih.nci.calab.service.submit; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.AssociatedFile; import gov.nih.nci.calab.domain.LabFile; import gov.nih.nci.calab.domain.Report; import gov.nih.nci.calab.domain.nano.particle.Nanoparticle; import gov.nih.nci.calab.service.search.SearchSampleService; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CalabConstants; import gov.nih.nci.calab.service.util.CananoConstants; import gov.nih.nci.calab.service.util.PropertyReader; import gov.nih.nci.calab.service.util.file.HttpFileUploadSessionData; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.apache.struts.upload.FormFile; /** * This class include services to submit the report to the file system and saves * the path to the database and sets user visibility for the report * * @author pansu * */ public class SubmitReportService { private static Logger logger = Logger.getLogger(SubmitReportService.class); public void submit(String[] particleNames, String reportType, FormFile report, String title, String description, String comment, String[] visibilities) throws Exception { // TODO saves reportFile to the file system String rootPath = PropertyReader.getProperty( CalabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir"); if (rootPath.charAt(rootPath.length() - 1) == File.separatorChar) rootPath = rootPath.substring(0, rootPath.length() - 1); String path = File.separator + "reports" + File.separator; File pathDir = new File(rootPath + path); if (!pathDir.exists()) pathDir.mkdirs(); HttpFileUploadSessionData sData = new HttpFileUploadSessionData(); String tagFileName = sData.getTimeStamp() + "_" + report.getFileName(); String outputFilename = rootPath + path + tagFileName; FileOutputStream oStream = new FileOutputStream( new File(outputFilename)); this.saveFile(report.getInputStream(), oStream); LabFile dataFile = null; if (reportType.equalsIgnoreCase(CananoConstants.NCL_REPORT)) dataFile = new Report(); else dataFile = new AssociatedFile(); dataFile.setDescription(description); dataFile.setFilename(report.getFileName()); dataFile.setPath(path + tagFileName); dataFile.setTitle(title); Date date = new Date(); dataFile.setCreatedDate(date); dataFile.setComments(comment); // TODO daves reportFile path to the database // look up the samples for each particleNames IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); ida.store(dataFile); } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving report File: "); throw e; } finally { ida.close(); } Nanoparticle particle = null; SearchSampleService service = new SearchSampleService(); for (String particleName : particleNames) { try { ida.open(); List results = ida .search("select particle from Nanoparticle particle left join fetch particle.reportCollection where particle.name='" + particleName + "'"); for (Object obj : results) { particle = (Nanoparticle) obj; } if (particle != null) { if (reportType.equalsIgnoreCase(CananoConstants.NCL_REPORT)) particle.getReportCollection().add(dataFile); else particle.getAssociatedFileCollection().add(dataFile); } } catch (Exception e) { e.printStackTrace(); ida.rollback(); logger.error("Problem saving report File: "); throw e; } finally { ida.close(); } } UserService userService = new UserService(CalabConstants.CSM_APP_NAME); // String fileName = report.getFileName(); for (String visibility : visibilities) { // by default, always set visibility to NCL_PI and NCL_Researcher to // be true // TODO once the files is successfully saved, use fileId instead of // fileName for (String defaultGroup : CananoConstants.DEFAULT_VISIBLE_GROUPS) { userService.secureObject(dataFile.getId().toString(), defaultGroup, CalabConstants.CSM_READ_ROLE); } userService.secureObject(dataFile.getId().toString(), visibility, CalabConstants.CSM_READ_ROLE); } } public void saveFile(InputStream is, FileOutputStream os) { byte[] bytes = new byte[32768]; try { int numRead = 0; while ((numRead = is.read(bytes)) > 0) { os.write(bytes, 0, numRead); } os.close(); } catch (Exception e) { } } }
package gov.nih.nci.ncicb.cadsr.loader.ui; import gov.nih.nci.ncicb.cadsr.domain.AdminComponent; import gov.nih.nci.ncicb.cadsr.domain.Concept; import gov.nih.nci.ncicb.cadsr.domain.DataElement; import gov.nih.nci.ncicb.cadsr.domain.Definition; import gov.nih.nci.ncicb.cadsr.domain.DomainObjectFactory; import gov.nih.nci.ncicb.cadsr.domain.ObjectClass; import gov.nih.nci.ncicb.cadsr.loader.UserSelections; import gov.nih.nci.ncicb.cadsr.loader.event.ElementChangeEvent; import gov.nih.nci.ncicb.cadsr.loader.event.ElementChangeListener; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.AttributeNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ClassNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.NodeUtil; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.ReviewableUMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.tree.UMLNode; import gov.nih.nci.ncicb.cadsr.loader.ui.util.UIUtil; import gov.nih.nci.ncicb.cadsr.loader.util.ObjectUpdater; import gov.nih.nci.ncicb.cadsr.loader.util.RunMode; import gov.nih.nci.ncicb.cadsr.loader.util.StringUtil; import gov.nih.nci.ncicb.cadsr.loader.util.UserPreferences; import gov.nih.nci.ncicb.cadsr.loader.util.UserPreferencesEvent; import gov.nih.nci.ncicb.cadsr.loader.util.UserPreferencesListener; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; import java.util.ArrayList; import java.util.List; public class ConceptEditorPanel extends JPanel implements KeyListener, UserPreferencesListener { private List<PropertyChangeListener> propChangeListeners = new ArrayList<PropertyChangeListener>(); private List<ElementChangeListener> changeListeners = new ArrayList<ElementChangeListener>(); private ConceptEditorPanel _this = this; private UMLNode node; private Concept[] concepts; private ConceptUI[] conceptUIs; private JPanel gridPanel; private JScrollPane scrollPane; private JLabel conceptLabel = new JLabel(); private JLabel nameLabel = new JLabel(); private boolean remove = false, orderChanged = false; private static EvsDialog evsDialog; private static boolean editable = false; static { UserSelections selections = UserSelections.getInstance(); editable = selections.getProperty("MODE").equals(RunMode.Curator); } private UserPreferences prefs = UserPreferences.getInstance(); public ConceptEditorPanel(UMLNode node) { this.node = node; initConcepts(); } public void addPropertyChangeListener(PropertyChangeListener l) { propChangeListeners.add(l); } private void firePropertyChangeEvent(PropertyChangeEvent evt) { for(PropertyChangeListener l : propChangeListeners) l.propertyChange(evt); } public void updateNode(UMLNode node) { this.node = node; initConcepts(); updateConcepts(concepts); } private void initConcepts() { concepts = NodeUtil.getConceptsFromNode(node); } //new Concept[] getConcepts() { return concepts; } //new // public boolean isReviewed() // return ((ReviewableUMLNode)node).isReviewed(); //new public UMLNode getNode() { return node; } boolean areAllFieldEntered() { for(int i=0; i < conceptUIs.length; i++) { if(conceptUIs[i].code.getText().trim().equals("") | conceptUIs[i].name.getText().trim().equals("") | conceptUIs[i].defSource.getText().trim().equals("") | conceptUIs[i].def.getText().trim().equals("")) { return false; } } return true; } private void updateConcepts(Concept[] concepts) { this.concepts = concepts; this.removeAll(); initUI(); this.updateUI(); } public void apply(boolean toAll) { boolean update = remove; remove = false; Concept[] newConcepts = new Concept[concepts.length]; for(int i = 0; i<concepts.length; i++) { newConcepts[i] = concepts[i]; // concept code has not changed if(conceptUIs[i].code.getText().equals(concepts[i].getPreferredName())) { concepts[i].setLongName(conceptUIs[i].name.getText()); concepts[i].setPreferredDefinition(conceptUIs[i].def.getText()); concepts[i].setDefinitionSource(conceptUIs[i].defSource.getText()); } else { // concept code has changed Concept concept = DomainObjectFactory.newConcept(); concept.setPreferredName(conceptUIs[i].code.getText()); concept.setLongName(conceptUIs[i].name.getText()); concept.setPreferredDefinition(conceptUIs[i].def.getText()); concept.setDefinitionSource(conceptUIs[i].defSource.getText()); newConcepts[i] = concept; update = true; } } update = orderChanged | update; if(update) { if(toAll) { Object o = node.getUserObject(); if(o instanceof DataElement) { DataElement de = (DataElement)o; ObjectUpdater.updateByAltName(de.getDataElementConcept().getProperty().getLongName(), concepts, newConcepts); } } else ObjectUpdater.update((AdminComponent)node.getUserObject(), concepts, newConcepts); concepts = newConcepts; } orderChanged = false; firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, false)); //setSaveButtonState(false); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.ADD, null, true)); //addButton.setEnabled(true); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.REVIEW, null, true)); //reviewButton.setEnabled(true); fireElementChangeEvent(new ElementChangeEvent(node)); } void initUI() { //private void initUI() { prefs.addUserPreferencesListener(this); this.setLayout(new BorderLayout()); JPanel summaryPanel = new JPanel(new GridBagLayout()); JLabel summaryTitle = new JLabel("UML Concept Code Summary: "); JLabel summaryNameTitle = new JLabel("UML Concept Name Summary: "); insertInBag(summaryPanel, summaryTitle, 0, 0); insertInBag(summaryPanel, conceptLabel, 1, 0); insertInBag(summaryPanel, summaryNameTitle, 0, 1); insertInBag(summaryPanel, nameLabel, 1, 1); this.add(summaryPanel,BorderLayout.NORTH); initViewPanel(); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SETUP, null, true)); //initButtonPanel(); } private void initViewPanel() { gridPanel = new JPanel(new GridBagLayout()); scrollPane = new JScrollPane(gridPanel); conceptUIs = new ConceptUI[concepts.length]; JPanel[] conceptPanels = new JPanel[concepts.length]; if(prefs.getUmlDescriptionOrder().equals("first")) insertInBag(gridPanel, createDescriptionPanel(), 0, 0); for(int i = 0; i<concepts.length; i++) { conceptUIs[i] = new ConceptUI(concepts[i]); String title = i == 0?"Primary Concept":"Qualifier Concept" +" conceptPanels[i] = new JPanel(); conceptPanels[i].setBorder (BorderFactory.createTitledBorder(title)); conceptPanels[i].setLayout(new BorderLayout()); JPanel mainPanel = new JPanel(new GridBagLayout()); insertInBag(mainPanel, conceptUIs[i].labels[0], 0, 0); insertInBag(mainPanel, conceptUIs[i].labels[1], 0, 1); insertInBag(mainPanel, conceptUIs[i].labels[2], 0, 2); insertInBag(mainPanel, conceptUIs[i].labels[3], 0, 3); insertInBag(mainPanel, conceptUIs[i].code, 1, 0, 2, 1); insertInBag(mainPanel, conceptUIs[i].name, 1, 1, 2, 1); insertInBag(mainPanel, conceptUIs[i].defScrollPane, 1, 2, 2, 1); insertInBag(mainPanel, conceptUIs[i].defSource, 1, 3,1, 1); JButton evsButton = new JButton("Evs Link"); insertInBag(mainPanel, evsButton, 2, 3); JButton upButton = new JButton(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("up-arrow.gif"))); JButton downButton = new JButton(new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("down-arrow.gif"))); upButton.setPreferredSize(new Dimension(28, 35)); downButton.setPreferredSize(new Dimension(28, 35)); JPanel arrowPanel = new JPanel(new GridBagLayout()); insertInBag(arrowPanel, upButton, 0, 0); insertInBag(arrowPanel, downButton, 0, 6); conceptPanels[i].add(mainPanel, BorderLayout.CENTER); conceptPanels[i].add(arrowPanel, BorderLayout.EAST); insertInBag(gridPanel, conceptPanels[i], 0, conceptPanels.length - i); conceptUIs[i].code.addKeyListener(this); conceptUIs[i].name.addKeyListener(this); conceptUIs[i].def.addKeyListener(this); conceptUIs[i].defSource.addKeyListener(this); final int index = i; if(index == 0) downButton.setVisible(false); if(index == concepts.length-1) upButton.setVisible(false); downButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Concept temp = concepts[index-1]; concepts[index-1] = concepts[index]; concepts[index] = temp; updateConcepts(concepts); orderChanged = true; firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, areAllFieldEntered())); //setSaveButtonState(areAllFieldEntered()); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.REVIEW, null, false)); //reviewButton.setEnabled(false); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.ADD, null, false)); //addButton.setEnabled(false); } }); upButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { Concept temp = concepts[index]; concepts[index] = concepts[index+1]; concepts[index+1] = temp; updateConcepts(concepts); orderChanged = true; firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, areAllFieldEntered())); //setSaveButtonState(areAllFieldEntered()); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.REVIEW, null, false)); //reviewButton.setEnabled(false); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.ADD, null, false)); //addButton.setEnabled(false); } }); evsButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (evsDialog == null) evsDialog = new EvsDialog(); UIUtil.putToCenter(evsDialog); if(prefs.getEvsAutoSearch()) evsDialog.startSearch(conceptUIs[index].name.getText()); evsDialog.setVisible(true); Concept c = evsDialog.getConcept(); if(c != null) { conceptUIs[index].code.setText(c.getPreferredName()); conceptUIs[index].name.setText(c.getLongName()); conceptUIs[index].def.setText(c.getPreferredDefinition()); conceptUIs[index].defSource.setText(c.getDefinitionSource()); if(areAllFieldEntered()) { firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, true)); //setSaveButtonState(true); // addButton.setEnabled(true); } else { firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, false)); //setSaveButtonState(false); // addButton.setEnabled(false); } firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.REVIEW, null, false)); //reviewButton.setEnabled(false); } } }); } updateHeaderLabels(); if(prefs.getUmlDescriptionOrder().equals("last")) insertInBag(gridPanel, createDescriptionPanel(), 0, concepts.length + 1); this.add(scrollPane, BorderLayout.CENTER); } private void updateHeaderLabels() { String s = ""; for(int i = 0; i < concepts.length; i++) { s = conceptUIs[i].code.getText() + " " + s; } conceptLabel.setText(s); s = ""; for(int i = 0; i < concepts.length; i++) { s = conceptUIs[i].name.getText() + " " + s; } nameLabel.setText(s); } private JPanel createDescriptionPanel() { JPanel umlPanel = new JPanel(); String s = "UML Class Documentation"; Object o = node.getUserObject(); if(node instanceof AttributeNode) { s = "UML Attribute Description"; } umlPanel.setBorder (BorderFactory.createTitledBorder(s)); umlPanel.setLayout(new BorderLayout()); JTextArea descriptionArea = new JTextArea(5, 54); JScrollPane descScrollPane = new JScrollPane(descriptionArea); if(node instanceof ClassNode) { ObjectClass oc = (ObjectClass) node.getUserObject(); descriptionArea.setText(oc.getPreferredDefinition()); } else if(node instanceof AttributeNode) { DataElement de = (DataElement) node.getUserObject(); for(Definition def : (List<Definition>) de.getDefinitions()) { descriptionArea.setText(def.getDefinition()); break; } } descriptionArea.setLineWrap(true); descriptionArea.setEditable(false); if(StringUtil.isEmpty(descriptionArea.getText())) { umlPanel.setVisible(false); } umlPanel.add(descScrollPane, BorderLayout.CENTER); return umlPanel; } public void applyPressed() { updateHeaderLabels(); apply(false); } public void addPressed() { Concept[] newConcepts = new Concept[concepts.length + 1]; for(int i = 0; i<concepts.length; i++) { newConcepts[i] = concepts[i]; } Concept concept = DomainObjectFactory.newConcept(); concept.setPreferredName(""); concept.setLongName(""); concept.setDefinitionSource(""); concept.setPreferredDefinition(""); newConcepts[newConcepts.length - 1] = concept; concepts = newConcepts; this.remove(scrollPane); initViewPanel(); this.updateUI(); if(concepts.length > 1) firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.DELETE, null, true)); //deleteButton.setEnabled(true); if(areAllFieldEntered()) { firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, true)); //setSaveButtonState(true); } else { firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, false)); //setSaveButtonState(false); } firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.ADD, null, false)); //addButton.setEnabled(false); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.REVIEW, null, false)); //reviewButton.setEnabled(false); } public void removePressed() { Concept[] newConcepts = new Concept[concepts.length - 1]; for(int i = 0; i<newConcepts.length; i++) { newConcepts[i] = concepts[i]; } concepts = newConcepts; _this.remove(scrollPane); initViewPanel(); if(areAllFieldEntered()) { firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, true)); //setSaveButtonState(true); } else { firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, false)); //setSaveButtonState(false); } firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.ADD, null, false)); //addButton.setEnabled(false); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.REVIEW, null, false)); //reviewButton.setEnabled(false); if(concepts.length < 2) firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.DELETE, null, false)); //deleteButton.setEnabled(false); this.updateUI(); remove = true; } public void setRemove(boolean value) { remove = value; } public void keyTyped(KeyEvent evt) {} public void keyPressed(KeyEvent evt) {} /** * Text Change Use Case. */ public void keyReleased(KeyEvent evt) { if(areAllFieldEntered()) { // addButton.setEnabled(true); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, true)); //setSaveButtonState(true); } else { // addButton.setEnabled(false); firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.SAVE, null, false)); //setSaveButtonState(false); } firePropertyChangeEvent( new PropertyChangeEvent(this, ButtonPanel.REVIEW, null, false)); //reviewButton.setEnabled(false); updateHeaderLabels(); } public void preferenceChange(UserPreferencesEvent event) { if(event.getTypeOfEvent() == UserPreferencesEvent.UML_DESCRIPTION) { _this.remove(scrollPane); initViewPanel(); } } private void fireElementChangeEvent(ElementChangeEvent event) { for(ElementChangeListener l : changeListeners) l.elementChanged(event); } public void addElementChangeListener(ElementChangeListener listener) { changeListeners.add(listener); } private void insertInBag(JPanel bagComp, Component comp, int x, int y) { insertInBag(bagComp, comp, x, y, 1, 1); } private void insertInBag(JPanel bagComp, Component comp, int x, int y, int width, int height) { JPanel p = new JPanel(); p.add(comp); bagComp.add(p, new GridBagConstraints(x, y, width, height, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0)); } } class ConceptUI { // initialize once the mode in which we're running private static boolean editable = false; static { UserSelections selections = UserSelections.getInstance(); editable = selections.getProperty("MODE").equals(RunMode.Curator); } JLabel[] labels = new JLabel[] { new JLabel("Concept Code"), new JLabel("Concept Preferred Name"), new JLabel("Concept Definition"), new JLabel("Concept Definition Source") }; JTextField code = new JTextField(10); JTextField name = new JTextField(20); JTextArea def = new JTextArea(); JTextField defSource = new JTextField(10); JScrollPane defScrollPane; public ConceptUI(Concept concept) { initUI(concept); } private void initUI(Concept concept) { def.setFont(new Font("Serif", Font.ITALIC, 16)); def.setLineWrap(true); def.setWrapStyleWord(true); defScrollPane = new JScrollPane(def); defScrollPane .setVerticalScrollBarPolicy (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); defScrollPane.setPreferredSize(new Dimension(400, 100)); code.setText(concept.getPreferredName()); name.setText(concept.getLongName()); def.setText(concept.getPreferredDefinition()); defSource.setText(concept.getDefinitionSource()); // if(!editable) { // code.setEnabled(false); // name.setEnabled(false); // def.setEnabled(false); // defSource.setEnabled(false); } }
package hso.autonomy.agent.general.agentruntime; import java.io.Serializable; import java.util.Map; import hso.autonomy.agent.communication.action.IAction; import hso.autonomy.agent.communication.channel.IChannelManager; import hso.autonomy.agent.communication.channel.IChannelManager.ChannelManagerStatus; import hso.autonomy.agent.communication.perception.IPerception; import hso.autonomy.agent.communication.perception.IPerceptor; import hso.autonomy.agent.decision.behavior.BehaviorMap; import hso.autonomy.agent.decision.decider.IDecisionMaker; import hso.autonomy.agent.general.agentmeta.IAgentMetaModel; import hso.autonomy.agent.model.agentmodel.IAgentModel; import hso.autonomy.agent.model.thoughtmodel.IThoughtModel; import hso.autonomy.agent.model.worldmodel.IWorldModel; import hso.autonomy.util.observer.IObserver; /** * The AgentRuntime is the core orchestrating component in the magma * agent-framework. * <h5>Tasks:</h5> * <ul> * <li>Create and setup components based on ComponentFactory</li> * <li>Manage internal triggering of all components during a "agent-cycle"</li> * </ul> * * @author Stefan Glaser */ public abstract class AgentRuntime implements IObserver<Map<String, IPerceptor>>, Serializable { /** the meta model describing the robot model */ protected transient IAgentMetaModel agentMetaModel; /** low level perception processing of the agent */ protected transient IPerception perception; /** low level action processing of the agent */ protected transient IAction action; /** the model for all visible objects */ protected IThoughtModel thoughtModel; /** all behaviors available for the agent */ protected transient BehaviorMap behaviors; /** decision making instance */ protected IDecisionMaker decisionMaker; private boolean printExceptionOnce = false; protected transient IChannelManager channelManager; protected boolean reportStats; protected int cycles = 0; /** * This method handles the main-loop of the magma agent framework. It is * called from the IServerConnection, when a new server-message is received. * The main loop is responsible for triggering all components of the agent * system in the correct sequence, in order to ensure a proper application * flow! <br> * If you are new to the agent framework, this method is a good starting * point for understanding the flow of the agent framework. <b>Beware of * changing the call order! This will definitively have massive effects on * the agent system behavior!</b> */ @Override public void update(Map<String, IPerceptor> content) { try { // this is a model update call perception.updatePerceptors(content); // then trigger models to update all internal sensor-values and // process vision-sensor information // (Localizer component is triggered inside WorldModel). boolean decide = thoughtModel.update(perception); if (decide) { // Once the model-layer is updated, trigger the DecisionMaker in // order to make a decision, based on the updated situation. onDecide(); // After a decision is taken, new commands should be set in the // model layer and are now ready to send - therefore trigger the // ThoughtModel to reflect the effector-commands onPrepareAction(); // At the end of each cycle call the action to send the actual // actions (all effector-values) to the server. action.sendAction(); } onEndUpdateLoop(); cycles++; } catch (Throwable e) { System.err.println("Crash!!! " + e); if (!printExceptionOnce) { e.printStackTrace(); printExceptionOnce = true; } } } protected void onPrepareAction() { thoughtModel.mapStateToAction(action, false); } protected void onDecide() { decisionMaker.decide(); } protected void onEndUpdateLoop() { } /** * Starts the connection to the server, will only return after disconnection * Uses default IP and port * * @return true, if connection was successful and the agent stopped receiving * messages, false if connection was refused or the server shut down */ public boolean startClient() { if (!channelManager.start()) { return false; } while (channelManager.isConnected()) { try { synchronized (channelManager) { channelManager.wait(); } Map<String, IPerceptor> nextMap; while ((nextMap = channelManager.getNextPerceptorMap()) != null) { update(nextMap); } } catch (InterruptedException | RuntimeException e) { e.printStackTrace(); } } reportStats(); return channelManager.getStatus() != ChannelManagerStatus.LOST_MAIN_CONNECTION; } protected void reportStats() { } /** * Check if the agent is connected to the server */ public boolean isConnected() { return channelManager.isConnected(); } /** * Stops the connection to the server after the next message was received */ public void stopClient() { channelManager.stop(); } public IAgentMetaModel getAgentMetaModel() { return agentMetaModel; } public IPerception getPerception() { return perception; } public IAction getAction() { return action; } public IAgentModel getAgentModel() { return thoughtModel.getAgentModel(); } public IWorldModel getWorldModel() { return thoughtModel.getWorldModel(); } public IThoughtModel getThoughtModel() { return thoughtModel; } public BehaviorMap getBehaviors() { return behaviors; } public IDecisionMaker getDecisionMaker() { return decisionMaker; } public IChannelManager getChannelManager() { return channelManager; } public void setMaxGain(float motorGain) { action.setMaxGain(motorGain); } public float getMaxGain() { return action.getMaxGain(); } }
package info.guardianproject.otr.app.im.app; import info.guardianproject.otr.app.im.R; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ListView; public class AccountsFragment extends ListFragment { private AccountListActivity mActivity; private View mEmptyView; @Override public void onAttach(Activity activity) { super.onAttach(activity); mActivity = (AccountListActivity)activity; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setListAdapter(mActivity.getAdapter()); } @Override public void onDetach() { super.onDetach(); mActivity = null; } @Override public void onListItemClick(ListView l, View v, int position, long id) { } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mEmptyView = inflater.inflate(R.layout.empty_account_view, container, false); mEmptyView.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (getListView().getCount() == 0) { mActivity.showExistingAccountListDialog(); } } }); return super.onCreateView(inflater, container, savedInstanceState); } public void onViewCreated(View view, Bundle savedInstanceState) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity()); boolean themeDark = settings.getBoolean("themeDark", false); String themebg = settings.getString("pref_background", null); ((ViewGroup)getListView().getParent()).addView(mEmptyView); getListView().setEmptyView(mEmptyView); if (themebg == null && (!themeDark)) { getListView().setBackgroundColor(getResources().getColor(android.R.color.white)); mEmptyView.setBackgroundColor(getResources().getColor(android.R.color.white)); } } }
package hex; import water.exceptions.H2OIllegalArgumentException; import water.fvec.Frame; import water.util.ArrayUtils; public class ModelMetricsRegression extends ModelMetricsSupervised { public final double _residual_deviance; public ModelMetricsRegression(Model model, Frame frame, double mse, double sigma, double deviance) { super(model, frame, mse, null, sigma); _residual_deviance = deviance; } public static ModelMetricsRegression getFromDKV(Model model, Frame frame) { ModelMetrics mm = ModelMetrics.getFromDKV(model, frame); if (! (mm instanceof ModelMetricsRegression)) throw new H2OIllegalArgumentException("Expected to find a Regression ModelMetrics for model: " + model._key.toString() + " and frame: " + frame._key.toString(), "Expected to find a ModelMetricsRegression for model: " + model._key.toString() + " and frame: " + frame._key.toString() + " but found a: " + mm.getClass()); return (ModelMetricsRegression) mm; } public static class MetricBuilderRegression extends MetricBuilderSupervised { double _sumdeviance; public MetricBuilderRegression() { super(1,null); //this will make _work = new float[2]; } // ds[0] has the prediction and ds[1] is ignored @Override public double[] perRow(double ds[], float[] yact, Model m) {return perRow(ds, yact, 1, 0, m);} @Override public double[] perRow(double ds[], float[] yact, double w, double o, Model m) { if( Float.isNaN(yact[0]) ) return ds; // No errors if actual is missing if(ArrayUtils.hasNaNs(ds)) return ds; // No errors if prediction has missing values (can happen for GLM) if(w == 0 || Double.isNaN(w)) return ds; // Compute error double err = yact[0] - ds[0]; // Error: distance from the actual _sumsqe += w*err*err; // Squared error assert !Double.isNaN(_sumsqe); if (m!=null) _sumdeviance += m.deviance(w, yact[0], ds[0]); _count++; _wcount += w; _wY += w*yact[0]; _wYY += w*yact[0]*yact[0]; return ds; // Flow coding } // Having computed a MetricBuilder, this method fills in a ModelMetrics public ModelMetrics makeModelMetrics( Model m, Frame f) { double mse = _sumsqe / _wcount; return m._output.addModelMetrics(new ModelMetricsRegression( m, f, mse, weightedSigma(), _sumdeviance)); } public String toString() {return " mse = " + _sumsqe / _wcount;} } }
package fr.paris.lutece.portal.web.system; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Locale; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import fr.paris.lutece.portal.business.portlet.PortletType; import fr.paris.lutece.portal.business.portlet.PortletTypeHome; import fr.paris.lutece.portal.service.admin.AdminUserService; import fr.paris.lutece.portal.service.database.AppConnectionService; import fr.paris.lutece.portal.service.i18n.I18nService; import fr.paris.lutece.portal.service.message.AdminMessage; import fr.paris.lutece.portal.service.message.AdminMessageService; import fr.paris.lutece.portal.service.plugin.Plugin; import fr.paris.lutece.portal.service.plugin.PluginService; import fr.paris.lutece.portal.service.template.AppTemplateService; import fr.paris.lutece.portal.service.util.AppLogService; import fr.paris.lutece.portal.web.admin.AdminFeaturesPageJspBean; import fr.paris.lutece.util.ReferenceList; import fr.paris.lutece.util.html.HtmlTemplate; /** * This class provides the user interface to manage the lutece plugins * (install, enable, disable) */ public class PluginJspBean extends AdminFeaturesPageJspBean { // Constants public static final String RIGHT_MANAGE_PLUGINS = "CORE_PLUGINS_MANAGEMENT"; private static final String TEMPLATE_MANAGE_PLUGINS = "admin/system/manage_plugins.html"; private static final String MARK_PLUGINS_LIST = "plugins_list"; private static final String MARK_POOLS_LIST = "pools_list"; private static final String MARK_FILTER_LIST = "filter_list"; private static final String MARK_CURRENT_FILTER = "current_filter"; private static final String PROPERTY_PLUGIN_MESSAGE = "portal.system.message.confirmDisable"; private static final String PROPERTY_PLUGIN_PORTLET_EXIST_MESSAGE = "portal.system.message.portletExist"; private static final String PARAM_PLUGIN_NAME = "plugin_name"; private static final String PARAM_PLUGIN_TYPE = "plugin_type"; private static final String PARAM_DB_POOL_NAME = "db_pool_name"; private static final String PARAM_PLUGIN_TYPE_ALL = "all"; private static final String PARAM_PLUGIN_TYPE_PORTLET = "portlet"; private static final String PARAM_PLUGIN_TYPE_APPLICATION = "application"; private static final String PARAM_PLUGIN_TYPE_FEATURE = "feature"; private static final String PARAM_PLUGIN_TYPE_INSERTSERVICE = "insertservice"; private static final String PARAM_PLUGIN_TYPE_CONTENTSERVICE = "contentservice"; private static final String PROPERTY_PLUGIN_TYPE_NAME_ALL = "portal.system.pluginType.name.all"; private static final String PROPERTY_PLUGIN_TYPE_NAME_APPLICATION = "portal.system.pluginType.name.application"; private static final String PROPERTY_PLUGIN_TYPE_NAME_PORTLET = "portal.system.pluginType.name.portlet"; private static final String PROPERTY_PLUGIN_TYPE_NAME_FEATURE = "portal.system.pluginType.name.feature"; private static final String PROPERTY_PLUGIN_TYPE_NAME_INSERTSERVICE = "portal.system.pluginType.name.insertService"; private static final String PROPERTY_PLUGIN_TYPE_NAME_CONTENTSERVICE = "portal.system.pluginType.name.contentService"; private static final String TEMPLATE_PLUGIN_DETAILS = "/admin/system/view_plugin.html"; /** * Returns the plugins management page * * @param request The Http request * @return Html page */ public String getManagePlugins( HttpServletRequest request ) { Locale locale = AdminUserService.getLocale( request ); String strPluginTypeFilter = request.getParameter( PARAM_PLUGIN_TYPE ); Collection<Plugin> listPlugins = PluginService.getPluginList( ); HashMap<String, Object> model = new HashMap<String, Object>( ); model.put( MARK_PLUGINS_LIST, filterPluginsList( listPlugins, strPluginTypeFilter ) ); model.put( MARK_POOLS_LIST, getPoolsList( ) ); model.put( MARK_FILTER_LIST, getPluginTypeFilterList( locale ) ); model.put( MARK_CURRENT_FILTER, ( strPluginTypeFilter != null ) ? strPluginTypeFilter : "" ); HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_MANAGE_PLUGINS, locale, model ); return getAdminPage( template.getHtml( ) ); } /** * Install a plugin * * @param request The Http request * @param context The servlet context * @return the url of the page containing a log essage */ public String doInstallPlugin( HttpServletRequest request, ServletContext context ) { try { String strPluginName = request.getParameter( PARAM_PLUGIN_NAME ); Plugin plugin = PluginService.getPlugin( strPluginName ); plugin.install( ); } catch ( Exception e ) { AppLogService.error( e.getMessage( ), e ); } return getHomeUrl( request ); } /** * Uninstall a plugin * * @param request The Http request * @param context The servlet context * @return the url of the page containing a log essage */ public String doUninstallPlugin( HttpServletRequest request, ServletContext context ) { try { String strPluginName = request.getParameter( PARAM_PLUGIN_NAME ); Plugin plugin = PluginService.getPlugin( strPluginName ); plugin.uninstall( ); } catch ( Exception e ) { AppLogService.error( e.getMessage( ), e ); } return getHomeUrl( request ); } /** * Returns the page of confirmation for uninstalling a plugin * * @param request The Http Request * @return the HTML page */ public String getConfirmUninstallPlugin( HttpServletRequest request ) { String strPluginName = request.getParameter( PARAM_PLUGIN_NAME ); Plugin plugin = PluginService.getPlugin( strPluginName ); Collection<PortletType> listPortletTypes = plugin.getPortletTypes( ); String strMessageKey = PROPERTY_PLUGIN_MESSAGE; String strUrl = "jsp/admin/system/DoUninstallPlugin.jsp?plugin_name=" + strPluginName; String strAdminMessageUrl = AdminMessageService.getMessageUrl( request, strMessageKey, strUrl, "", AdminMessage.TYPE_WARNING ); for ( PortletType portletType : listPortletTypes ) { String strPluginHomeClass = portletType.getHomeClass( ); if ( ( plugin.getType( ) & Plugin.PLUGIN_TYPE_PORTLET ) != 0 ) { if ( isPortletExists( strPluginHomeClass ) ) { strMessageKey = PROPERTY_PLUGIN_PORTLET_EXIST_MESSAGE; strAdminMessageUrl = AdminMessageService.getMessageUrl( request, strMessageKey, AdminMessage.TYPE_WARNING ); } } } return strAdminMessageUrl; } /** * Defines the database connection pool to be used by the plugin * @param request The http request * @return the URL to redirect after this action */ public String doModifyPluginPool( HttpServletRequest request ) { String strPluginName = request.getParameter( PARAM_PLUGIN_NAME ); String strDbPoolName = request.getParameter( PARAM_DB_POOL_NAME ); try { Plugin plugin = PluginService.getPlugin( strPluginName ); plugin.updatePoolName( strDbPoolName ); } catch ( Exception e ) { AppLogService.error( e.getMessage( ), e ); } return getHomeUrl( request ); } /** * Displays a plugin's description * @param request The HTTP request * @return The popup HTML code */ public String getPluginDescription( HttpServletRequest request ) { String strPluginName = request.getParameter( PARAM_PLUGIN_NAME ); Plugin plugin = PluginService.getPlugin( strPluginName ); // set the locale for the feature labels I18nService.localizeCollection( plugin.getRights( ), getLocale( ) ); // set the locale for the portlet types labels I18nService.localizeCollection( plugin.getPortletTypes( ), getLocale( ) ); // set the locale for the link services labels I18nService.localizeCollection( plugin.getInsertServices( ), getLocale( ) ); HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_PLUGIN_DETAILS, getLocale( ), plugin ); return getAdminPage( template.getHtml( ) ); } // Private implementation /** * Return a filter list of plugins * @param listPlugins the COllection of plugins * @param strPluginTypeFilter The filter * @return list The list of plugins */ private Collection<Plugin> filterPluginsList( Collection<Plugin> listPlugins, String strPluginTypeFilter ) { Collection<Plugin> list = new ArrayList<Plugin>( ); for ( Plugin plugin : listPlugins ) { // Checks for filtering the plugin list if ( strPluginTypeFilter != null ) { if ( strPluginTypeFilter.equals( PARAM_PLUGIN_TYPE_APPLICATION ) && ( ( plugin.getType( ) & Plugin.PLUGIN_TYPE_APPLICATION ) == 0 ) ) { // skip this plugin continue; } if ( strPluginTypeFilter.equals( PARAM_PLUGIN_TYPE_PORTLET ) && ( ( plugin.getType( ) & Plugin.PLUGIN_TYPE_PORTLET ) == 0 ) ) { // skip this plugin continue; } if ( strPluginTypeFilter.equals( PARAM_PLUGIN_TYPE_FEATURE ) && ( ( plugin.getType( ) & Plugin.PLUGIN_TYPE_FEATURE ) == 0 ) ) { // skip this plugin continue; } if ( strPluginTypeFilter.equals( PARAM_PLUGIN_TYPE_INSERTSERVICE ) && ( ( plugin.getType( ) & Plugin.PLUGIN_TYPE_INSERTSERVICE ) == 0 ) ) { // skip this plugin continue; } if ( strPluginTypeFilter.equals( PARAM_PLUGIN_TYPE_CONTENTSERVICE ) && ( ( plugin.getType( ) & Plugin.PLUGIN_TYPE_CONTENTSERVICE ) == 0 ) ) { // skip this plugin continue; } } list.add( plugin ); } return list; } /** * Create a ReferenceList containing all Plugin types * @param locale The Locale * @return A ReferenceList containing all Plugin types */ private ReferenceList getPluginTypeFilterList( Locale locale ) { ReferenceList list = new ReferenceList( ); list.addItem( PARAM_PLUGIN_TYPE_ALL, I18nService.getLocalizedString( PROPERTY_PLUGIN_TYPE_NAME_ALL, locale ) ); list.addItem( PARAM_PLUGIN_TYPE_APPLICATION, I18nService.getLocalizedString( PROPERTY_PLUGIN_TYPE_NAME_APPLICATION, locale ) ); list.addItem( PARAM_PLUGIN_TYPE_PORTLET, I18nService.getLocalizedString( PROPERTY_PLUGIN_TYPE_NAME_PORTLET, locale ) ); list.addItem( PARAM_PLUGIN_TYPE_FEATURE, I18nService.getLocalizedString( PROPERTY_PLUGIN_TYPE_NAME_FEATURE, locale ) ); list.addItem( PARAM_PLUGIN_TYPE_INSERTSERVICE, I18nService.getLocalizedString( PROPERTY_PLUGIN_TYPE_NAME_INSERTSERVICE, locale ) ); list.addItem( PARAM_PLUGIN_TYPE_CONTENTSERVICE, I18nService.getLocalizedString( PROPERTY_PLUGIN_TYPE_NAME_CONTENTSERVICE, locale ) ); return list; } /** * Return a list of pools * @return listPools the list of pools */ private ReferenceList getPoolsList( ) { ReferenceList listPools = new ReferenceList( ); listPools.addItem( AppConnectionService.NO_POOL_DEFINED, " " ); AppConnectionService.getPoolList( listPools ); return listPools; } /** * Returns the status of the existence of a portlet on the site * * @param strPluginHomeClass The home class of the plugin * @return The existence status as a boolean */ private boolean isPortletExists( String strPluginHomeClass ) { String strPortletTypeId = PortletTypeHome.getPortletTypeId( strPluginHomeClass ); return ( PortletTypeHome.getNbPortletTypeByPortlet( strPortletTypeId ) != 0 ); } }
package org.apache.commons.lang.builder; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class ToStringBuilder { /** * The default style of output to use */ private static ToStringStyle defaultStyle = ToStringStyle.DEFAULT_STYLE; /** * Current toString buffer */ private final StringBuffer buffer; /** * The style of output to use */ private final ToStringStyle style; /** * The object being output */ private final Object object; public ToStringBuilder(Object object) { this(object, getDefaultStyle(), null); } public ToStringBuilder(Object object, ToStringStyle style) { this(object, style, null); } public ToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) { super(); if (object == null) { throw new IllegalArgumentException("The object to create a toString for must not be null"); } if (style == null) { style = getDefaultStyle(); } if (buffer == null) { buffer = new StringBuffer(512); } this.buffer = buffer; this.style = style; this.object = object; style.appendStart(buffer, object); } /** * <p>Gets the default <code>ToStringStyle</code> to use.</p> * * <p>This could allow the <code>ToStringStyle</code> to be * controlled for an entire application with one call.</p> * * <p>This might be used to have a verbose * <code>ToStringStyle</code> during development and a compact * <code>ToStringStyle</code> in production.</p> * * @return the default <code>ToStringStyle</code> */ public static ToStringStyle getDefaultStyle() { return defaultStyle; } public static void setDefaultStyle(ToStringStyle style) { if (style == null) { throw new IllegalArgumentException("The style must not be null"); } defaultStyle = style; } public static String reflectionToString(Object object) { return reflectionToString(object, null, false, null); } public static String reflectionToString(Object object, ToStringStyle style) { return reflectionToString(object, style, false, null); } public static String reflectionToString(Object object, ToStringStyle style, boolean outputTransients) { return reflectionToString(object, style, outputTransients, null); } public static String reflectionToString(Object object, ToStringStyle style, boolean outputTransients, Class reflectUpToClass) { if (object == null) { throw new IllegalArgumentException("The object must not be null"); } if (style == null) { style = getDefaultStyle(); } ToStringBuilder builder = new ToStringBuilder(object, style); Class clazz = object.getClass(); reflectionAppend(object, clazz, builder, outputTransients); while (clazz.getSuperclass() != null && clazz != reflectUpToClass) { clazz = clazz.getSuperclass(); reflectionAppend(object, clazz, builder, outputTransients); } return builder.toString(); } /** * Appends the fields and values defined by the given object of the * given Class. * * @param object the object to append details of * @param clazz the class to append details of * @param builder the builder to append to * @param outputTransients whether to output transient fields */ private static void reflectionAppend(Object object, Class clazz, ToStringBuilder builder, boolean outputTransients) { Field[] fields = clazz.getDeclaredFields(); Field.setAccessible(fields, true); for (int i = 0; i < fields.length; ++i) { Field f = fields[i]; if (outputTransients || !Modifier.isTransient(f.getModifiers())) { if (!Modifier.isStatic(f.getModifiers())) { try { builder.append(f.getName(), f.get(object)); } catch (IllegalAccessException ex) { //this can't happen. Would get a Security exception instead //throw a runtime exception in case the impossible happens. } } } } } /** * <p>Append the <code>toString</code> from the superclass.</p> * * <p>This method asumes that the superclass uses the same <code>ToStringStyle</code> * as this one.</p> * * <p>If the <code>superToString</code> is null, no change is made.</p> * * @param superToString the result of <code>super.toString()</code> * @return this */ public ToStringBuilder appendSuper(String superToString) { if (superToString != null) { style.appendSuper(buffer, superToString); } return this; } /** * <p>Append the <code>toString</code> from another object.</p> * * <p>This method is useful where a class delegates most of the implementation of * it's properties to another class. You can then call toString() on the other * class and pass the result into this method.</p> * * <pre> * private AnotherObject delegate; * private String fieldInThisClass; * * public String toString() { * return new ToStringBuilder(this). * appendToString(delegate.toString()). * append(fieldInThisClass). * toString(); * }</pre> * * <p>This method asumes that the other object uses the same <code>ToStringStyle</code> * as this one.</p> * * <p>If the <code>toString</code> is null, no change is made.</p> * * @param toString the result of <code>toString()</code> on another object * @return this */ public ToStringBuilder appendToString(String toString) { if (toString != null) { style.appendToString(buffer, toString); } return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value.</p> * * @param object the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(Object object) { style.append(buffer, null, object, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value.</p> * * @param fieldName the field name * @param object the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, Object object) { style.append(buffer, fieldName, object, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * value.</p> * * @param fieldName the field name * @param object the value to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, * <code>false</code> for summary info * @return this */ public ToStringBuilder append(String fieldName, Object object, boolean fullDetail) { style.append(buffer, fieldName, object, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(long value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, long value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(int value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, int value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>short</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(short value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>short</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, short value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>char</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(char value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>char</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, char value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>byte</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(byte value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>byte</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, byte value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>double</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(double value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>double</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, double value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>float</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(float value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>float</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, float value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>boolean</code> * value.</p> * * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(boolean value) { style.append(buffer, null, value); return this; } /** * <p>Append to the <code>toString</code> an <code>boolean</code> * value.</p> * * @param fieldName the field name * @param value the value to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, boolean value) { style.append(buffer, fieldName, value); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(Object[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(String fieldName, Object[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> an <code>Object</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, Object[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(long[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>long</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, long[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>long</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, long[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>int</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(int[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for an <code>int</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, int[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> an <code>int</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, int[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>short</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(short[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>short</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, short[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>short</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array. * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, short[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>char</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(char[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>char</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, char[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>char</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, char[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>byte</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(byte[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>byte</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, byte[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>byte</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array. * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, byte[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>double</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(double[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>double</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, double[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>double</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, double[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>float</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(float[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>float</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, float[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>float</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, float[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * array.</p> * * @param array the array to add to the <code>toString</code> * @return this */ public ToStringBuilder append(boolean[] array) { style.append(buffer, null, array, null); return this; } /** * <p>Append a <code>hashCode</code> for a <code>boolean</code> * array.</p> * * @param fieldName the field name * @param array the array to add to the <code>hashCode</code> * @return this */ public ToStringBuilder append(String fieldName, boolean[] array) { style.append(buffer, fieldName, array, null); return this; } /** * <p>Append to the <code>toString</code> a <code>boolean</code> * array.</p> * * <p>A boolean parameter controls the level of detail to show. * Setting <code>true</code> will output the array in full. Setting * <code>false</code> will output a summary, typically the size of * the array.</p> * * @param fieldName the field name * @param array the array to add to the <code>toString</code> * @param fullDetail <code>true</code> for detail, <code>false</code> * for summary info * @return this */ public ToStringBuilder append(String fieldName, boolean[] array, boolean fullDetail) { style.append(buffer, fieldName, array, new Boolean(fullDetail)); return this; } /** * <p>Gets the <code>ToStringStyle</code> being used.</p> * * @return the <code>ToStringStyle</code> being used */ public ToStringStyle getStyle() { return style; } /** * <p>Gets the <code>StringBuffer</code> being populated.</p> * * @return the <code>StringBuffer</code> being populated */ public StringBuffer getStringBuffer() { return buffer; } /** * <p>Returns the built <code>toString</code>.</p> * * <p>This method appends the end of the buffer, and can only be called once. * Use {@link #getStringBuffer} to get the current string state.</p> * * @return the String <code>toString</code> */ public String toString() { style.appendEnd(buffer, object); return buffer.toString(); } }
package org.broadinstitute.variant.vcf; import net.sf.samtools.util.BlockCompressedInputStream; import org.broad.tribble.AsciiFeatureCodec; import org.broad.tribble.Feature; import org.broad.tribble.NameAwareCodec; import org.broad.tribble.TribbleException; import org.broad.tribble.util.ParsingUtils; import org.broadinstitute.variant.utils.GeneralUtils; import org.broadinstitute.variant.variantcontext.*; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.zip.GZIPInputStream; public abstract class AbstractVCFCodec extends AsciiFeatureCodec<VariantContext> implements NameAwareCodec { public final static int MAX_ALLELE_SIZE_BEFORE_WARNING = (int)Math.pow(2, 20); protected final static int NUM_STANDARD_FIELDS = 8; // INFO is the 8th column // we have to store the list of strings that make up the header until they're needed protected VCFHeader header = null; protected VCFHeaderVersion version = null; // a mapping of the allele protected Map<String, List<Allele>> alleleMap = new HashMap<String, List<Allele>>(3); // for ParsingUtils.split protected String[] GTValueArray = new String[100]; protected String[] genotypeKeyArray = new String[100]; protected String[] infoFieldArray = new String[1000]; protected String[] infoValueArray = new String[1000]; // for performance testing purposes public static boolean validate = true; // a key optimization -- we need a per thread string parts array, so we don't allocate a big array over and over // todo: make this thread safe? protected String[] parts = null; protected String[] genotypeParts = null; protected final String[] locParts = new String[6]; // for performance we cache the hashmap of filter encodings for quick lookup protected HashMap<String,List<String>> filterHash = new HashMap<String,List<String>>(); // we store a name to give to each of the variant contexts we emit protected String name = "Unknown"; protected int lineNo = 0; protected Map<String, String> stringCache = new HashMap<String, String>(); protected boolean warnedAboutNoEqualsForNonFlag = false; /** * If true, then we'll magically fix up VCF headers on the fly when we read them in */ protected boolean doOnTheFlyModifications = true; protected AbstractVCFCodec() { super(VariantContext.class); } /** * Creates a LazyParser for a LazyGenotypesContext to use to decode * our genotypes only when necessary. We do this instead of eagarly * decoding the genotypes just to turn around and reencode in the frequent * case where we don't actually want to manipulate the genotypes */ class LazyVCFGenotypesParser implements LazyGenotypesContext.LazyParser { final List<Allele> alleles; final String contig; final int start; LazyVCFGenotypesParser(final List<Allele> alleles, final String contig, final int start) { this.alleles = alleles; this.contig = contig; this.start = start; } @Override public LazyGenotypesContext.LazyData parse(final Object data) { //System.out.printf("Loading genotypes... %s:%d%n", contig, start); return createGenotypeMap((String) data, alleles, contig, start); } } /** * parse the filter string, first checking to see if we already have parsed it in a previous attempt * @param filterString the string to parse * @return a set of the filters applied */ protected abstract List<String> parseFilters(String filterString); /** * create a VCF header from a set of header record lines * * @param headerStrings a list of strings that represent all the ## and # entries * @return a VCFHeader object */ protected VCFHeader parseHeaderFromLines( final List<String> headerStrings, final VCFHeaderVersion version ) { this.version = version; Set<VCFHeaderLine> metaData = new LinkedHashSet<VCFHeaderLine>(); Set<String> sampleNames = new LinkedHashSet<String>(); int contigCounter = 0; // iterate over all the passed in strings for ( String str : headerStrings ) { if ( !str.startsWith(VCFHeader.METADATA_INDICATOR) ) { String[] strings = str.substring(1).split(VCFConstants.FIELD_SEPARATOR); if ( strings.length < VCFHeader.HEADER_FIELDS.values().length ) throw new TribbleException.InvalidHeader("there are not enough columns present in the header line: " + str); int arrayIndex = 0; for (VCFHeader.HEADER_FIELDS field : VCFHeader.HEADER_FIELDS.values()) { try { if (field != VCFHeader.HEADER_FIELDS.valueOf(strings[arrayIndex])) throw new TribbleException.InvalidHeader("we were expecting column name '" + field + "' but we saw '" + strings[arrayIndex] + "'"); } catch (IllegalArgumentException e) { throw new TribbleException.InvalidHeader("unknown column name '" + strings[arrayIndex] + "'; it does not match a legal column header name."); } arrayIndex++; } boolean sawFormatTag = false; if ( arrayIndex < strings.length ) { if ( !strings[arrayIndex].equals("FORMAT") ) throw new TribbleException.InvalidHeader("we were expecting column name 'FORMAT' but we saw '" + strings[arrayIndex] + "'"); sawFormatTag = true; arrayIndex++; } while ( arrayIndex < strings.length ) sampleNames.add(strings[arrayIndex++]); if ( sawFormatTag && sampleNames.size() == 0 ) throw new TribbleException.InvalidHeader("The FORMAT field was provided but there is no genotype/sample data"); } else { if ( str.startsWith(VCFConstants.INFO_HEADER_START) ) { final VCFInfoHeaderLine info = new VCFInfoHeaderLine(str.substring(7), version); metaData.add(info); } else if ( str.startsWith(VCFConstants.FILTER_HEADER_START) ) { final VCFFilterHeaderLine filter = new VCFFilterHeaderLine(str.substring(9), version); metaData.add(filter); } else if ( str.startsWith(VCFConstants.FORMAT_HEADER_START) ) { final VCFFormatHeaderLine format = new VCFFormatHeaderLine(str.substring(9), version); metaData.add(format); } else if ( str.startsWith(VCFConstants.CONTIG_HEADER_START) ) { final VCFContigHeaderLine contig = new VCFContigHeaderLine(str.substring(9), version, VCFConstants.CONTIG_HEADER_START.substring(2), contigCounter++); metaData.add(contig); } else if ( str.startsWith(VCFConstants.ALT_HEADER_START) ) { final VCFSimpleHeaderLine alt = new VCFSimpleHeaderLine(str.substring(6), version, VCFConstants.ALT_HEADER_START.substring(2), Arrays.asList("ID", "Description")); metaData.add(alt); } else { int equals = str.indexOf("="); if ( equals != -1 ) metaData.add(new VCFHeaderLine(str.substring(2, equals), str.substring(equals+1))); } } } this.header = new VCFHeader(metaData, sampleNames); if ( doOnTheFlyModifications ) this.header = VCFStandardHeaderLines.repairStandardHeaderLines(this.header); return this.header; } /** * Explicitly set the VCFHeader on this codec. This will overwrite the header read from the file * and the version state stored in this instance; conversely, reading the header from a file will * overwrite whatever is set here. The returned header may not be identical to the header argument * since the header lines may be "repaired" (i.e., rewritten) if doOnTheFlyModifications is set. */ public VCFHeader setVCFHeader(final VCFHeader header, final VCFHeaderVersion version) { this.version = version; if (this.doOnTheFlyModifications) this.header = VCFStandardHeaderLines.repairStandardHeaderLines(header); else this.header = header; return this.header; } /** * the fast decode function * @param line the line of text for the record * @return a feature, (not guaranteed complete) that has the correct start and stop */ public Feature decodeLoc(String line) { return decodeLine(line, false); } /** * decode the line into a feature (VariantContext) * @param line the line * @return a VariantContext */ public VariantContext decode(String line) { return decodeLine(line, true); } private VariantContext decodeLine(final String line, final boolean includeGenotypes) { // the same line reader is not used for parsing the header and parsing lines, if we see a #, we've seen a header line if (line.startsWith(VCFHeader.HEADER_INDICATOR)) return null; // our header cannot be null, we need the genotype sample names and counts if (header == null) throw new TribbleException("VCF Header cannot be null when decoding a record"); if (parts == null) parts = new String[Math.min(header.getColumnCount(), NUM_STANDARD_FIELDS+1)]; final int nParts = ParsingUtils.split(line, parts, VCFConstants.FIELD_SEPARATOR_CHAR, true); // if we have don't have a header, or we have a header with no genotyping data check that we // have eight columns. Otherwise check that we have nine (normal columns + genotyping data) if (( (header == null || !header.hasGenotypingData()) && nParts != NUM_STANDARD_FIELDS) || (header != null && header.hasGenotypingData() && nParts != (NUM_STANDARD_FIELDS + 1)) ) throw new TribbleException("Line " + lineNo + ": there aren't enough columns for line " + line + " (we expected " + (header == null ? NUM_STANDARD_FIELDS : NUM_STANDARD_FIELDS + 1) + " tokens, and saw " + nParts + " )"); return parseVCFLine(parts, includeGenotypes); } /** * parse out the VCF line * * @param parts the parts split up * @return a variant context object */ private VariantContext parseVCFLine(final String[] parts, final boolean includeGenotypes) { VariantContextBuilder builder = new VariantContextBuilder(); builder.source(getName()); // increment the line count // TODO -- because of the way the engine utilizes Tribble, we can parse a line multiple times (especially when // TODO -- the first record is far along the contig) and the line counter can get out of sync lineNo++; // parse out the required fields final String chr = getCachedString(parts[0]); builder.chr(chr); int pos = -1; try { pos = Integer.valueOf(parts[1]); } catch (NumberFormatException e) { generateException(parts[1] + " is not a valid start position in the VCF format"); } builder.start(pos); if ( parts[2].length() == 0 ) generateException("The VCF specification requires a valid ID field"); else if ( parts[2].equals(VCFConstants.EMPTY_ID_FIELD) ) builder.noID(); else builder.id(parts[2]); final String ref = getCachedString(parts[3].toUpperCase()); final String alts = getCachedString(parts[4].toUpperCase()); builder.log10PError(parseQual(parts[5])); final List<String> filters = parseFilters(getCachedString(parts[6])); if ( filters != null ) builder.filters(new HashSet<String>(filters)); final Map<String, Object> attrs = parseInfo(parts[7]); builder.attributes(attrs); if ( attrs.containsKey(VCFConstants.END_KEY) ) { // update stop with the end key if provided try { builder.stop(Integer.valueOf(attrs.get(VCFConstants.END_KEY).toString())); } catch (Exception e) { generateException("the END value in the INFO field is not valid"); } } else { builder.stop(pos + ref.length() - 1); } // get our alleles, filters, and setup an attribute map final List<Allele> alleles = parseAlleles(ref, alts, lineNo); builder.alleles(alleles); // do we have genotyping data if (parts.length > NUM_STANDARD_FIELDS && includeGenotypes) { final LazyGenotypesContext.LazyParser lazyParser = new LazyVCFGenotypesParser(alleles, chr, pos); final int nGenotypes = header.getNGenotypeSamples(); LazyGenotypesContext lazy = new LazyGenotypesContext(lazyParser, parts[8], nGenotypes); // did we resort the sample names? If so, we need to load the genotype data if ( !header.samplesWereAlreadySorted() ) lazy.decode(); builder.genotypesNoValidation(lazy); } VariantContext vc = null; try { vc = builder.make(); } catch (Exception e) { generateException(e.getMessage()); } return vc; } /** * get the name of this codec * @return our set name */ public String getName() { return name; } /** * set the name of this codec * @param name new name */ public void setName(String name) { this.name = name; } /** * Return a cached copy of the supplied string. * * @param str string * @return interned string */ protected String getCachedString(String str) { String internedString = stringCache.get(str); if ( internedString == null ) { internedString = new String(str); stringCache.put(internedString, internedString); } return internedString; } /** * parse out the info fields * @param infoField the fields * @return a mapping of keys to objects */ private Map<String, Object> parseInfo(String infoField) { Map<String, Object> attributes = new HashMap<String, Object>(); if ( infoField.length() == 0 ) generateException("The VCF specification requires a valid (non-zero length) info field"); if ( !infoField.equals(VCFConstants.EMPTY_INFO_FIELD) ) { if ( infoField.indexOf("\t") != -1 || infoField.indexOf(" ") != -1 ) generateException("The VCF specification does not allow for whitespace in the INFO field. Offending field value was \"" + infoField + "\""); int infoFieldSplitSize = ParsingUtils.split(infoField, infoFieldArray, VCFConstants.INFO_FIELD_SEPARATOR_CHAR, false); for (int i = 0; i < infoFieldSplitSize; i++) { String key; Object value; int eqI = infoFieldArray[i].indexOf("="); if ( eqI != -1 ) { key = infoFieldArray[i].substring(0, eqI); String valueString = infoFieldArray[i].substring(eqI+1); // split on the INFO field separator int infoValueSplitSize = ParsingUtils.split(valueString, infoValueArray, VCFConstants.INFO_FIELD_ARRAY_SEPARATOR_CHAR, false); if ( infoValueSplitSize == 1 ) { value = infoValueArray[0]; final VCFInfoHeaderLine headerLine = header.getInfoHeaderLine(key); if ( headerLine != null && headerLine.getType() == VCFHeaderLineType.Flag && value.equals("0") ) { // deal with the case where a flag field has =0, such as DB=0, by skipping the add continue; } } else { ArrayList<String> valueList = new ArrayList<String>(infoValueSplitSize); for ( int j = 0; j < infoValueSplitSize; j++ ) valueList.add(infoValueArray[j]); value = valueList; } } else { key = infoFieldArray[i]; final VCFInfoHeaderLine headerLine = header.getInfoHeaderLine(key); if ( headerLine != null && headerLine.getType() != VCFHeaderLineType.Flag ) { if ( GeneralUtils.DEBUG_MODE_ENABLED && ! warnedAboutNoEqualsForNonFlag ) { System.err.println("Found info key " + key + " without a = value, but the header says the field is of type " + headerLine.getType() + " but this construct is only value for FLAG type fields"); warnedAboutNoEqualsForNonFlag = true; } value = VCFConstants.MISSING_VALUE_v4; } else { value = true; } } // this line ensures that key/value pairs that look like key=; are parsed correctly as MISSING if ( "".equals(value) ) value = VCFConstants.MISSING_VALUE_v4; attributes.put(key, value); } } return attributes; } /** * create a an allele from an index and an array of alleles * @param index the index * @param alleles the alleles * @return an Allele */ protected static Allele oneAllele(String index, List<Allele> alleles) { if ( index.equals(VCFConstants.EMPTY_ALLELE) ) return Allele.NO_CALL; final int i; try { i = Integer.valueOf(index); } catch ( NumberFormatException e ) { throw new TribbleException.InternalCodecException("The following invalid GT allele index was encountered in the file: " + index); } if ( i >= alleles.size() ) throw new TribbleException.InternalCodecException("The allele with index " + index + " is not defined in the REF/ALT columns in the record"); return alleles.get(i); } /** * parse genotype alleles from the genotype string * @param GT GT string * @param alleles list of possible alleles * @param cache cache of alleles for GT * @return the allele list for the GT string */ protected static List<Allele> parseGenotypeAlleles(String GT, List<Allele> alleles, Map<String, List<Allele>> cache) { // cache results [since they are immutable] and return a single object for each genotype List<Allele> GTAlleles = cache.get(GT); if ( GTAlleles == null ) { StringTokenizer st = new StringTokenizer(GT, VCFConstants.PHASING_TOKENS); GTAlleles = new ArrayList<Allele>(st.countTokens()); while ( st.hasMoreTokens() ) { String genotype = st.nextToken(); GTAlleles.add(oneAllele(genotype, alleles)); } cache.put(GT, GTAlleles); } return GTAlleles; } /** * parse out the qual value * @param qualString the quality string * @return return a double */ protected static Double parseQual(String qualString) { // if we're the VCF 4 missing char, return immediately if ( qualString.equals(VCFConstants.MISSING_VALUE_v4)) return VariantContext.NO_LOG10_PERROR; Double val = Double.valueOf(qualString); // check to see if they encoded the missing qual score in VCF 3 style, with either the -1 or -1.0. check for val < 0 to save some CPU cycles if ((val < 0) && (Math.abs(val - VCFConstants.MISSING_QUALITY_v3_DOUBLE) < VCFConstants.VCF_ENCODING_EPSILON)) return VariantContext.NO_LOG10_PERROR; // scale and return the value return val / -10.0; } /** * parse out the alleles * @param ref the reference base * @param alts a string of alternates to break into alleles * @param lineNo the line number for this record * @return a list of alleles, and a pair of the shortest and longest sequence */ protected static List<Allele> parseAlleles(String ref, String alts, int lineNo) { List<Allele> alleles = new ArrayList<Allele>(2); // we are almost always biallelic // ref checkAllele(ref, true, lineNo); Allele refAllele = Allele.create(ref, true); alleles.add(refAllele); if ( alts.indexOf(",") == -1 ) // only 1 alternatives, don't call string split parseSingleAltAllele(alleles, alts, lineNo); else for ( String alt : alts.split(",") ) parseSingleAltAllele(alleles, alt, lineNo); return alleles; } /** * check to make sure the allele is an acceptable allele * @param allele the allele to check * @param isRef are we the reference allele? * @param lineNo the line number for this record */ private static void checkAllele(String allele, boolean isRef, int lineNo) { if ( allele == null || allele.length() == 0 ) generateException(generateExceptionTextForBadAlleleBases(""), lineNo); if ( GeneralUtils.DEBUG_MODE_ENABLED && MAX_ALLELE_SIZE_BEFORE_WARNING != -1 && allele.length() > MAX_ALLELE_SIZE_BEFORE_WARNING ) { System.err.println(String.format("Allele detected with length %d exceeding max size %d at approximately line %d, likely resulting in degraded VCF processing performance", allele.length(), MAX_ALLELE_SIZE_BEFORE_WARNING, lineNo)); } if ( isSymbolicAllele(allele) ) { if ( isRef ) { generateException("Symbolic alleles not allowed as reference allele: " + allele, lineNo); } } else { // check for VCF3 insertions or deletions if ( (allele.charAt(0) == VCFConstants.DELETION_ALLELE_v3) || (allele.charAt(0) == VCFConstants.INSERTION_ALLELE_v3) ) generateException("Insertions/Deletions are not supported when reading 3.x VCF's. Please" + " convert your file to VCF4 using VCFTools, available at http://vcftools.sourceforge.net/index.html", lineNo); if (!Allele.acceptableAlleleBases(allele)) generateException(generateExceptionTextForBadAlleleBases(allele), lineNo); if ( isRef && allele.equals(VCFConstants.EMPTY_ALLELE) ) generateException("The reference allele cannot be missing", lineNo); } } /** * Generates the exception text for the case where the allele string contains unacceptable bases. * * @param allele non-null allele string * @return non-null exception text string */ private static String generateExceptionTextForBadAlleleBases(final String allele) { if ( allele.length() == 0 ) return "empty alleles are not permitted in VCF records"; if ( allele.contains("[") || allele.contains("]") || allele.contains(":") || allele.contains(".") ) return "VCF support for complex rearrangements with breakends has not yet been implemented"; return "unparsable vcf record with allele " + allele; } /** * return true if this is a symbolic allele (e.g. <SOMETAG>) or * structural variation breakend (with [ or ]), otherwise false * @param allele the allele to check * @return true if the allele is a symbolic allele, otherwise false */ private static boolean isSymbolicAllele(String allele) { return (allele != null && allele.length() > 2 && ((allele.startsWith("<") && allele.endsWith(">")) || (allele.contains("[") || allele.contains("]")))); } /** * parse a single allele, given the allele list * @param alleles the alleles available * @param alt the allele to parse * @param lineNo the line number for this record */ private static void parseSingleAltAllele(List<Allele> alleles, String alt, int lineNo) { checkAllele(alt, false, lineNo); Allele allele = Allele.create(alt, false); if ( ! allele.isNoCall() ) alleles.add(allele); } public final static boolean canDecodeFile(final String potentialInput, final String MAGIC_HEADER_LINE) { try { return isVCFStream(new FileInputStream(potentialInput), MAGIC_HEADER_LINE) || isVCFStream(new GZIPInputStream(new FileInputStream(potentialInput)), MAGIC_HEADER_LINE) || isVCFStream(new BlockCompressedInputStream(new FileInputStream(potentialInput)), MAGIC_HEADER_LINE); } catch ( FileNotFoundException e ) { return false; } catch ( IOException e ) { return false; } } private final static boolean isVCFStream(final InputStream stream, final String MAGIC_HEADER_LINE) { try { byte[] buff = new byte[MAGIC_HEADER_LINE.length()]; int nread = stream.read(buff, 0, MAGIC_HEADER_LINE.length()); boolean eq = Arrays.equals(buff, MAGIC_HEADER_LINE.getBytes()); return eq; // String firstLine = new String(buff); // return firstLine.startsWith(MAGIC_HEADER_LINE); } catch ( IOException e ) { return false; } catch ( RuntimeException e ) { return false; } finally { try { stream.close(); } catch ( IOException e ) {} } } /** * create a genotype map * * @param str the string * @param alleles the list of alleles * @return a mapping of sample name to genotype object */ public LazyGenotypesContext.LazyData createGenotypeMap(final String str, final List<Allele> alleles, final String chr, final int pos) { if (genotypeParts == null) genotypeParts = new String[header.getColumnCount() - NUM_STANDARD_FIELDS]; int nParts = ParsingUtils.split(str, genotypeParts, VCFConstants.FIELD_SEPARATOR_CHAR); if ( nParts != genotypeParts.length ) generateException("there are " + (nParts-1) + " genotypes while the header requires that " + (genotypeParts.length-1) + " genotypes be present for all records at " + chr + ":" + pos, lineNo); ArrayList<Genotype> genotypes = new ArrayList<Genotype>(nParts); // get the format keys int nGTKeys = ParsingUtils.split(genotypeParts[0], genotypeKeyArray, VCFConstants.GENOTYPE_FIELD_SEPARATOR_CHAR); // cycle through the sample names Iterator<String> sampleNameIterator = header.getGenotypeSamples().iterator(); // clear out our allele mapping alleleMap.clear(); // cycle through the genotype strings for (int genotypeOffset = 1; genotypeOffset < nParts; genotypeOffset++) { int GTValueSplitSize = ParsingUtils.split(genotypeParts[genotypeOffset], GTValueArray, VCFConstants.GENOTYPE_FIELD_SEPARATOR_CHAR); final String sampleName = sampleNameIterator.next(); final GenotypeBuilder gb = new GenotypeBuilder(sampleName); // check to see if the value list is longer than the key list, which is a problem if (nGTKeys < GTValueSplitSize) generateException("There are too many keys for the sample " + sampleName + ", keys = " + parts[8] + ", values = " + parts[genotypeOffset]); int genotypeAlleleLocation = -1; if (nGTKeys >= 1) { gb.maxAttributes(nGTKeys - 1); for (int i = 0; i < nGTKeys; i++) { final String gtKey = genotypeKeyArray[i]; boolean missing = i >= GTValueSplitSize; // todo -- all of these on the fly parsing of the missing value should be static constants if (gtKey.equals(VCFConstants.GENOTYPE_KEY)) { genotypeAlleleLocation = i; } else if ( missing ) { // if its truly missing (there no provided value) skip adding it to the attributes } else if (gtKey.equals(VCFConstants.GENOTYPE_FILTER_KEY)) { final List<String> filters = parseFilters(getCachedString(GTValueArray[i])); if ( filters != null ) gb.filters(filters); } else if ( GTValueArray[i].equals(VCFConstants.MISSING_VALUE_v4) ) { // don't add missing values to the map } else { if (gtKey.equals(VCFConstants.GENOTYPE_QUALITY_KEY)) { if ( GTValueArray[i].equals(VCFConstants.MISSING_GENOTYPE_QUALITY_v3) ) gb.noGQ(); else gb.GQ((int)Math.round(Double.valueOf(GTValueArray[i]))); } else if (gtKey.equals(VCFConstants.GENOTYPE_ALLELE_DEPTHS)) { gb.AD(decodeInts(GTValueArray[i])); } else if (gtKey.equals(VCFConstants.GENOTYPE_PL_KEY)) { gb.PL(decodeInts(GTValueArray[i])); } else if (gtKey.equals(VCFConstants.GENOTYPE_LIKELIHOODS_KEY)) { gb.PL(GenotypeLikelihoods.fromGLField(GTValueArray[i]).getAsPLs()); } else if (gtKey.equals(VCFConstants.DEPTH_KEY)) { gb.DP(Integer.valueOf(GTValueArray[i])); } else { gb.attribute(gtKey, GTValueArray[i]); } } } } // check to make sure we found a genotype field if our version is less than 4.1 file if ( version != VCFHeaderVersion.VCF4_1 && genotypeAlleleLocation == -1 ) generateException("Unable to find the GT field for the record; the GT field is required in VCF4.0"); if ( genotypeAlleleLocation > 0 ) generateException("Saw GT field at position " + genotypeAlleleLocation + ", but it must be at the first position for genotypes when present"); final List<Allele> GTalleles = (genotypeAlleleLocation == -1 ? new ArrayList<Allele>(0) : parseGenotypeAlleles(GTValueArray[genotypeAlleleLocation], alleles, alleleMap)); gb.alleles(GTalleles); gb.phased(genotypeAlleleLocation != -1 && GTValueArray[genotypeAlleleLocation].indexOf(VCFConstants.PHASED) != -1); // add it to the list try { genotypes.add(gb.make()); } catch (TribbleException e) { throw new TribbleException.InternalCodecException(e.getMessage() + ", at position " + chr+":"+pos); } } return new LazyGenotypesContext.LazyData(genotypes, header.getSampleNamesInOrder(), header.getSampleNameToOffset()); } private final static String[] INT_DECODE_ARRAY = new String[10000]; private final static int[] decodeInts(final String string) { final int nValues = ParsingUtils.split(string, INT_DECODE_ARRAY, ','); final int[] values = new int[nValues]; for ( int i = 0; i < nValues; i++ ) values[i] = Integer.valueOf(INT_DECODE_ARRAY[i]); return values; } /** * Forces all VCFCodecs to not perform any on the fly modifications to the VCF header * of VCF records. Useful primarily for raw comparisons such as when comparing * raw VCF records */ public final void disableOnTheFlyModifications() { doOnTheFlyModifications = false; } protected void generateException(String message) { throw new TribbleException(String.format("The provided VCF file is malformed at approximately line number %d: %s", lineNo, message)); } protected static void generateException(String message, int lineNo) { throw new TribbleException(String.format("The provided VCF file is malformed at approximately line number %d: %s", lineNo, message)); } }
package org.concord.otrunk.view.document; import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.StringReader; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Element; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.concord.framework.otrunk.OTChangeEvent; import org.concord.framework.otrunk.OTChangeNotifying; import org.concord.framework.otrunk.OTID; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectService; import org.concord.framework.otrunk.OTUser; import org.concord.framework.otrunk.view.OTExternalAppService; import org.concord.framework.otrunk.view.OTFrame; import org.concord.framework.otrunk.view.OTJComponentView; import org.concord.framework.otrunk.view.OTView; import org.concord.framework.otrunk.view.OTViewContainer; import org.concord.framework.otrunk.view.OTViewContainerChangeEvent; import org.concord.framework.otrunk.view.OTViewEntry; import org.concord.framework.otrunk.view.OTViewEntryAware; import org.concord.framework.otrunk.view.OTXHTMLView; import org.concord.otrunk.OTrunkUtil; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.helpers.DefaultHandler; /** * @author scott * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Generation - Code and Comments */ public class OTDocumentView extends AbstractOTDocumentView implements ChangeListener, HyperlinkListener, OTXHTMLView, OTViewEntryAware { public static boolean addedCustomLayout = false; protected JTabbedPane tabbedPane = null; protected JComponent previewComponent = null; protected JEditorPane editorPane = null; DocumentBuilderFactory xmlDocumentFactory = null; DocumentBuilder xmlDocumentBuilder = null; protected JTextArea parsedTextArea = null; protected OTObject otObject; protected DocumentConfig documentConfig; protected OTViewEntry viewEntry; private KeyEventDispatcher sourceViewDispatcher; public final static String XHTML_PREFIX_START = // "<?xml version='1.0' encoding='UTF-8'?>\n" + "<html xmlns='http: + "\n" + "<head>\n" + "<title>default</title>\n" + "<style type=\"text/css\">\n"; public final static String XHTML_PREFIX_END = "</style>" + "</head>\n" + "<body>\n"; public final static String XHTML_SUFFIX = "</body>\n" + "</html>"; protected void setup(OTObject doc) { // Don't call super.setup() to avoid listening to the ot object // inneccesarily pfObject = (OTDocument) doc; } protected Action viewSourceAction = new AbstractAction("View Source.."){ public void actionPerformed(ActionEvent e) { tabbedPane = new JTabbedPane(); textArea = new JTextArea(textAreaModel); textArea.setEnabled(false); JScrollPane scrollPane = new JScrollPane(textArea); tabbedPane.add("Source", scrollPane); parsedTextArea.setEnabled(false); scrollPane = new JScrollPane(parsedTextArea); tabbedPane.add("Parsed", scrollPane); JFrame frame = new JFrame("Source"); frame.getContentPane().add(tabbedPane); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setSize(600, 600); frame.setVisible(true); } }; private MouseListener mouseListener = new MouseAdapter(){ private void showPopup(MouseEvent e) { JPopupMenu menu = new JPopupMenu(); menu.add(viewSourceAction); Point pt = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), previewComponent); menu.show(previewComponent, pt.x, pt.y); } public void mousePressed(MouseEvent e) { if(!e.isPopupTrigger()){ return; } showPopup(e); } public void mouseReleased(MouseEvent e) { if(!e.isPopupTrigger()){ return; } showPopup(e); } }; public JComponent getComponent(OTObject otObject) { this.otObject = otObject; setup(otObject); initTextAreaModel(); ((OTChangeNotifying)otObject).addOTChangeListener(this); if (tabbedPane != null) { tabbedPane.removeChangeListener(this); } // need to use the PfCDEditorKit updateFormatedView(); setReloadOnViewEntryChange(true); if (documentConfig != null){ OTViewContainer thisViewContainer = getViewContainer(); if (thisViewContainer != null){ getViewContainer().setUpdateable(documentConfig.getViewContainerIsUpdateable()); } } // JScrollPane renderedScrollPane = new JScrollPane(previewComponent); // renderedScrollPane.getViewport().setViewPosition(new Point(0,0)); previewComponent.addMouseListener(mouseListener); if (System.getProperty("otrunk.view.debug", "").equals("true")) { tabbedPane = new JTabbedPane(); // need to add a listener so we can update the view pane tabbedPane.add("View", previewComponent); textArea = new JTextArea(textAreaModel); JScrollPane scrollPane = new JScrollPane(textArea); tabbedPane.add("Edit", scrollPane); parsedTextArea.setEnabled(false); scrollPane = new JScrollPane(parsedTextArea); tabbedPane.add("Parsed", scrollPane); tabbedPane.addChangeListener(this); return tabbedPane; } else { return previewComponent; } } public String updateFormatedView() { if (pfObject == null) return null; // System.out.println(this+" updateFormatedView"); String markupLanguage = pfObject.getMarkupLanguage(); if (markupLanguage == null) { markupLanguage = System.getProperty("org.concord.portfolio.markup", null); } String bodyText = null; try { // The textAreaModel is out source for the text. It was setup by // the initTextAreaModel method. It also listens to the pfObject // so if it changes, the textAreaModel will get updated too. bodyText = textAreaModel.getText(0, textAreaModel.getLength()); } catch (BadLocationException e) { System.err.println("OTDocumentView: " + e.getMessage()); System.err.println(" continuing by requesting documentText"); bodyText = pfObject.getDocumentText(); } bodyText = substituteIncludables(bodyText); // default to html viewer for now // FIXME the handling of the plain markup is to test the new view entry // code // it isn't quite valid because plain text might have html chars in it // so it will get parsed incorrectly. if (markupLanguage == null || markupLanguage.equals(OTDocument.MARKUP_PFHTML) || markupLanguage.equals(OTDocument.MARKUP_PLAIN)) { if (editorPane == null) { editorPane = new JEditorPane(); OTHTMLFactory kitViewFactory = new OTHTMLFactory(this); OTDocumentEditorKit editorKit = new OTDocumentEditorKit( kitViewFactory); editorPane.setEditorKit(editorKit); editorPane.setEditable(false); editorPane.addHyperlinkListener(this); } bodyText = htmlizeText(bodyText); if (documentConfig != null) { String css = documentConfig.getCssText(); String XHTML_PREFIX = XHTML_PREFIX_START + css + XHTML_PREFIX_END; bodyText = XHTML_PREFIX + bodyText + XHTML_SUFFIX; } // when this text is set it will recreate all the // OTDocumentObjectViews, so we need to clear and // close all the old panels first removeAllSubViews(); editorPane.setText(bodyText); HTMLDocument doc = (HTMLDocument) editorPane.getDocument(); doc.setBase(otObject.getOTObjectService().getCodebase(otObject)); previewComponent = editorPane; // we used to set thie caret pos so the view would // scroll to the top, but now we disable scrolling // during the load, and that seems to work better // there is no flicker that way. // editorPane.setCaretPosition(0); } else { System.err.println("xhtml markup not supported"); } if (parsedTextArea == null) { parsedTextArea = new JTextArea(); } parsedTextArea.setText(bodyText); return bodyText; } /** * This method gets the object with idStr and tries to get the view entry * with the viewIdStr. If the viewIdStr is not null then it gets the view * for that view entry and the current view mode, and determines if it is a * {@link OTXHTMLView}. If it is then it gets the html text of that view. * If the viewIdStr is null then asks the viewFactory for a view of this * object which implements the OTXHTMLView interface. If such a view exists * then that is used to get the text. * * The text returned is intended for use by the Matcher.appendReplacement * method. So $0 means to just leave the text as is. Because of this any * text needs to be escaped, specifically $ and \ needs to be escaped. * {@link OTrunkUtil#escapeReplacement(String)} * * So far this is only used by the substitueIncludables method * * @see OTrunkUtil#escapeReplacement(String) * @see #substituteIncludables(String) * */ public String getIncludableReplacement(String idStr, String viewIdStr, String modeStr, String userStr) { // lookup the object at this id OTObject referencedObject = getReferencedObject(idStr); if (referencedObject == null) { return "$0"; } if (userStr != null) { referencedObject = getRuntimeObject(referencedObject, userStr); } OTViewEntry viewEntry = null; if (viewIdStr != null) { OTObject viewEntryTmp = getReferencedObject(viewIdStr); if (viewEntryTmp instanceof OTViewEntry) { viewEntry = (OTViewEntry) viewEntryTmp; } else { System.err.println("viewid reference to a non viewEntry object"); System.err.println(" doc: " + pfObject.getGlobalId()); System.err.println(" refid: " + idStr); System.err.println(" viewid: " + viewIdStr); } } OTView view = null; String viewMode = getViewMode(); if (modeStr != null) { if (modeStr.length() == 0) { viewMode = null; } else { viewMode = modeStr; } } if (viewEntry != null) { view = getViewFactory().getView(referencedObject, viewEntry, viewMode); } else { view = getViewFactory().getView(referencedObject, OTXHTMLView.class, viewMode); // if there isnt' a xhtml view and there is a view mode, then see if // that viewMode of the jcomponent view is an xhtmlview. // this logic is really contorted. The mixing of viewmodes and // renderings needs to be well defined. // TODO scytacki Feb 12, 2008 - this logic has been moved into the getView method of the viewfactory // so if nothing goes wrong we should remove it from here. if (view == null && getViewMode() != null) { view = getViewFactory().getView(referencedObject, OTJComponentView.class, viewMode); } } if (view instanceof OTXHTMLView && ((OTXHTMLView)view).getEmbedXHTMLView()) { OTXHTMLView xhtmlView = (OTXHTMLView) view; try { String replacement = xhtmlView.getXHTMLText(referencedObject); if (replacement == null) { // this is an empty embedded object System.err.println("empty embedd obj: " + idStr); return ""; } return OTrunkUtil.escapeReplacement(replacement); } catch (Exception e) { System.err .println("Failed to generate xhtml version of embedded object"); e.printStackTrace(); } } return "$0"; } public String substituteIncludables(String inText) { if (inText == null) { return null; } Pattern p = Pattern.compile("<object refid=\"([^\"]*)\"[^>]*>"); Pattern pViewId = Pattern.compile("viewid=\"([^\"]*)\""); Pattern pMode = Pattern.compile("mode=\"([^\"]*)\""); Pattern pUser = Pattern.compile("user=\"([^\"]*)\""); Matcher m = p.matcher(inText); StringBuffer parsed = new StringBuffer(); while (m.find()) { String id = m.group(1); String element = m.group(0); Matcher mViewId = pViewId.matcher(element); String viewIdStr = null; if (mViewId.find()) { viewIdStr = mViewId.group(1); } Matcher mMode = pMode.matcher(element); String modeStr = null; if (mMode.find()) { modeStr = mMode.group(1); } Matcher mUser = pUser.matcher(element); String userStr = null; if (mUser.find()) { userStr = mUser.group(1); } String replacement = getIncludableReplacement(id, viewIdStr, modeStr, userStr); try { m.appendReplacement(parsed, replacement); } catch (IllegalArgumentException e) { System.err.println("bad replacement: " + replacement); e.printStackTrace(); } } m.appendTail(parsed); return parsed.toString(); } public String htmlizeText(String inText) { if (inText == null) { return null; } inText = inText.replaceAll("<p[ ]*/>", "<p></p>"); inText = inText.replaceAll("<div(.*)/>", "<div$1></div>"); return inText.replaceAll("<([^>]*)/>", "<$1>"); } // FIXME: Does this do anything anymore? Nothing seems to call it. -SF public Document parseString(String text, String systemId) { try { if (xmlDocumentFactory == null) { xmlDocumentFactory = DocumentBuilderFactory.newInstance(); xmlDocumentFactory.setValidating(true); xmlDocumentBuilder = xmlDocumentFactory.newDocumentBuilder(); // TODO Fix this xmlDocumentBuilder.setErrorHandler(new DefaultHandler()); } StringReader stringReader = new StringReader(text); InputSource inputSource = new InputSource(stringReader); inputSource.setSystemId(systemId); return xmlDocumentBuilder.parse(inputSource); } catch (Exception e) { e.printStackTrace(); } return null; } /* * (non-Javadoc) * * @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent) */ public void stateChanged(ChangeEvent event) { // System.out.println(this+" -- TABS stateChanged"); updateFormatedView(); } public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { try { String linkTarget = e.getDescription(); if (linkTarget.startsWith("http") || linkTarget.startsWith("file")) { OTExternalAppService extAppService = (OTExternalAppService)getViewService(OTExternalAppService.class); if(extAppService.showDocument(new URL(linkTarget))){ return; } } OTObject linkObj = getReferencedObject(linkTarget); if (linkObj == null) { // It wasn't an external link, and wasn't a reference to an OTObject // lets assume it's a relative link to an external resource // System.err.println("Invalid link: " + e.getDescription()); // System.err.print("Trying with codebase..."); URL codebase = otObject.getOTObjectService().getCodebase(otObject); if (codebase == null) { System.err.println("Invalid link: " + e.getDescription()); return; } // construct a new URL using the document's codebase as a base URL newTarget = new URL(codebase, linkTarget); if (newTarget != null) { // try to launch the url in a browser window OTExternalAppService extAppService = (OTExternalAppService)getViewService(OTExternalAppService.class); if (extAppService.showDocument(newTarget)) { // System.err.println(" success!"); } else { System.err.println("Invalid link: " + e.getDescription()); } // System.err.println("New url was: " + newTarget.toExternalForm()); } return; } Element aElement = e.getSourceElement(); AttributeSet attribs = aElement.getAttributes(); // this is a hack because i don't really know what is going on // here AttributeSet tagAttribs = (AttributeSet) attribs .getAttribute(HTML.Tag.A); String target = null; String viewEntryId = null; String modeStr = null; if(tagAttribs != null){ target = (String) tagAttribs .getAttribute(HTML.Attribute.TARGET); viewEntryId = (String) tagAttribs.getAttribute("viewid"); modeStr = (String) tagAttribs.getAttribute("mode"); } OTViewEntry viewEntry = null; if (viewEntryId != null) { viewEntry = (OTViewEntry) getReferencedObject(viewEntryId); if (viewEntry == null) { System.err.println("Invalid link viewid attrib: " + viewEntryId); return; } } OTFrame targetFrame = null; if (target != null){ // they want to use a frame targetFrame = (OTFrame) getReferencedObject(target); if (targetFrame == null) { System.err.println("Invalid link target attrib: " + target); return; } } // mode used for switching viewmodes if (modeStr != null && modeStr.length() == 0) { modeStr = null; } else if (modeStr == null) { modeStr = getViewMode(); } if (target == null) { // FIXME deal with the mode getViewContainer().setCurrentObject(linkObj, viewEntry); } else { putObjectInFrame(linkObj, viewEntry, targetFrame, modeStr); } } catch (Throwable t) { t.printStackTrace(); } } } /** * This method is extracted from hyperlinkUpdate so subclasses * can override it. * * @param linkObj * @param viewEntry * @param targetFrame * @param modeStr */ public void putObjectInFrame(OTObject linkObj, OTViewEntry viewEntry, OTFrame targetFrame, String modeStr) { getFrameManager().putObjectInFrame(linkObj, viewEntry, targetFrame, modeStr); } public String getXHTMLText(OTObject otObject) { if (otObject == null) { throw new IllegalArgumentException("otObject can't be null"); } pfObject = (OTDocument) otObject; // return updateFormatedView().replace(viewEntry.getCss(), ""); String bodyText = pfObject.getDocumentText(); bodyText = substituteIncludables(bodyText); return bodyText; } /* * (non-Javadoc) * * @see org.concord.framework.otrunk.view.OTViewConfigAware#setViewConfig(org.concord.framework.otrunk.OTObject) */ public void setViewEntry(OTViewEntry viewEntry) { super.setViewEntry(viewEntry); this.viewEntry = viewEntry; if (viewEntry instanceof DocumentConfig) { documentConfig = (DocumentConfig) viewEntry; setViewMode(documentConfig.getMode()); } } /** * Retrieves the CSS style text used for the document view. * @return String containing (raw) CSS definitions, or a blank string. */ /** protected String getCssText() { String css = ""; if (documentConfig.getCss() != null && documentConfig.getCss().length() > 0){ css += documentConfig.getCss(); } if (documentConfig.getCssBlocks() != null && documentConfig.getCssBlocks().getVector().size() > 0){ Vector cssBlocks = documentConfig.getCssBlocks().getVector(); for (int i = 0; i < cssBlocks.size(); i++) { OTCssText cssText = (OTCssText) cssBlocks.get(i); // retrieve CSS definitions (originally) from the otml file String text = cssText.getCssText(); // if no cssText, then get src which is a URL for the css file if (text == null) { text = ""; URL url = cssText.getSrc(); if (url != null) { try { URLConnection urlConnection = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line = reader.readLine(); while (line != null) { text += line; line = reader.readLine(); } } catch (IOException e){ text = ""; e.printStackTrace(); } } } css += " " + text; } } return css; } */ // If one of the child objects is replaced by another, we swap the old and new // object in the documentRefs, and then change the object references in the // html to refer to the new object. public void currentObjectChanged(OTViewContainerChangeEvent evt) { if (evt.getEventType() == OTViewContainerChangeEvent.REPLACE_CURRENT_OBJECT_EVT){ OTObject oldObject = evt.getPreviousObject(); OTObject newObject = evt.getValue(); if (otObject instanceof OTCompoundDoc){ OTCompoundDoc compoundDoc = (OTCompoundDoc) otObject; compoundDoc.getDocumentRefsAsObjectList().remove(oldObject); compoundDoc.getDocumentRefsAsObjectList().add(newObject); String newBodyText = compoundDoc.getBodyText().replaceAll( otObject.getOTObjectService().getExternalID(oldObject), otObject.getOTObjectService().getExternalID(newObject)); compoundDoc.setBodyText(newBodyText); updateFormatedView(); } } } public boolean getEmbedXHTMLView() { return true; } public OTObject getRuntimeObject(OTObject object, String userStr) { try { OTObjectService objectService = otObject.getOTObjectService(); OTID userId = objectService.getOTID(userStr); OTUser user = (OTUser) objectService.getOTObject(userId); return getOTrunk().getUserRuntimeObject(object, user); } catch (Exception e) { e.printStackTrace(); return null; } } public void stateChanged(OTChangeEvent e) { super.stateChanged(e); updateFormatedView(); } public void viewClosed() { super.viewClosed(); if(editorPane != null){ editorPane.removeHyperlinkListener(this); } if(previewComponent != null){ previewComponent.removeMouseListener(mouseListener); mouseListener = null; } } }
package com.example.pluginmain; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout.LayoutParams; import android.widget.Toast; import com.example.pluginsharelib.SharePOJO; import com.example.pluginsharelib.ShareService; import com.example.plugintest.IMyAidlInterface; import com.plugin.content.PluginDescriptor; import com.plugin.core.localservice.LocalServiceManager; import com.plugin.core.manager.PluginCallback; import com.plugin.core.manager.PluginManagerHelper; import com.plugin.util.FileUtil; import com.plugin.util.LogUtil; import com.plugin.util.ResourceUtil; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Iterator; public class MainActivity extends AppCompatActivity { private ViewGroup mList; private Button install; boolean isInstalled = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); setTitle(""); initView(); listAll(); registerReceiver(pluginInstallEvent, new IntentFilter(PluginCallback.ACTION_PLUGIN_CHANGED)); // //Actionreceiver // Intent intent = new Intent("test.rst2");//ReceiveacitonReceiver // intent.putExtra("testParam", "testParam"); // sendBroadcast(intent); //serviceservice startService(new Intent(this, MainService.class)); } private void initView() { mList = (ViewGroup) findViewById(R.id.list); install = (Button) findViewById(R.id.install); final Handler handler = new Handler(); install.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isInstalled) { isInstalled = true; try { String[] files = getAssets().list(""); for (String apk : files) { if (apk.endsWith(".apk")) { copyAndInstall(apk); } } } catch (IOException e) { e.printStackTrace(); } } else { Toast.makeText(MainActivity.this, "1", Toast.LENGTH_LONG).show(); } } }); } private void copyAndInstall(String name) { try { InputStream assestInput = getAssets().open(name); String dest = getExternalFilesDir(null).getAbsolutePath() + "/" + name; if (FileUtil.copyFile(assestInput, dest)) { PluginManagerHelper.installPlugin(dest); } else { assestInput = getAssets().open(name); dest = getCacheDir().getAbsolutePath() + "/" + name; if (FileUtil.copyFile(assestInput, dest)) { PluginManagerHelper.installPlugin(dest); } else { Toast.makeText(MainActivity.this, "assetsApk" + dest, Toast.LENGTH_LONG).show(); } } } catch (IOException e) { e.printStackTrace(); Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show(); } } private void listAll() { ViewGroup root = mList; root.removeAllViews(); Collection<PluginDescriptor> plugins = PluginManagerHelper.getPlugins(); Iterator<PluginDescriptor> itr = plugins.iterator(); while (itr.hasNext()) { final PluginDescriptor pluginDescriptor = itr.next(); Button button = new Button(this); button.setPadding(10, 25, 10, 25); LayoutParams layoutParam = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParam.topMargin = 25; layoutParam.bottomMargin = 25; layoutParam.gravity = Gravity.LEFT; root.addView(button, layoutParam); LogUtil.d("id", pluginDescriptor.getPackageName()); button.setText("" + ResourceUtil.getLabel(pluginDescriptor) + ", V" + pluginDescriptor.getVersion()); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent launchIntent = getPackageManager().getLaunchIntentForPackage(pluginDescriptor.getPackageName()); if (launchIntent == null) { Toast.makeText(MainActivity.this, "" + pluginDescriptor.getPackageName() + "Launcher", Toast.LENGTH_SHORT).show(); //Launcher Intent intent = new Intent(MainActivity.this, DetailActivity.class); intent.putExtra("plugin_id", pluginDescriptor.getPackageName()); startActivity(intent); } else { //Launcher if (!pluginDescriptor.isStandalone()) { launchIntent.putExtra("paramVO", new SharePOJO("VO")); } startActivity(launchIntent); } //IntentActivity //Intent intent = new Intent("test.abc"); //startActivity(intent); } }); } if (plugins.size() >0) { Button button = new Button(this); button.setPadding(10, 25, 10, 25); LayoutParams layoutParam = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParam.topMargin = 25; layoutParam.bottomMargin = 25; layoutParam.gravity = Gravity.LEFT; root.addView(button, layoutParam); button.setText(""); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, TestSkinActivity.class); startActivity(intent); } }); button = new Button(this); button.setPadding(10, 25, 10, 25); layoutParam = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParam.topMargin = 25; layoutParam.bottomMargin = 25; layoutParam.gravity = Gravity.LEFT; root.addView(button, layoutParam); button.setText(""); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, TestViewActivity.class); startActivity(intent); } }); button = new Button(this); button.setPadding(10, 25, 10, 25); layoutParam = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParam.topMargin = 25; layoutParam.bottomMargin = 25; layoutParam.gravity = Gravity.LEFT; root.addView(button, layoutParam); button.setText("Service AIDL"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (scn == null) { scn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { IMyAidlInterface iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service); try { iMyAidlInterface.basicTypes(1, 2L, true, 0.1f, 0.01d, "AIDL"); Toast.makeText(MainActivity.this, "onServiceConnected", Toast.LENGTH_LONG).show(); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { } }; } bindService(new Intent("test.lmn"), scn, Context.BIND_AUTO_CREATE); //localservice ShareService ss = (ShareService)LocalServiceManager.getService("share_service"); if (ss != null) { SharePOJO pojo = ss.doSomething("localservice"); Toast.makeText(MainActivity.this, pojo.name, Toast.LENGTH_LONG).show(); } } }); button = new Button(this); button.setPadding(10, 25, 10, 25); layoutParam = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParam.topMargin = 25; layoutParam.bottomMargin = 25; layoutParam.gravity = Gravity.LEFT; root.addView(button, layoutParam); button.setText("tabActiviytActivity"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, TestTabActivity.class); startActivity(intent); } }); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(pluginInstallEvent); if (scn != null) { unbindService(scn); scn = null; } }; private ServiceConnection scn; private final BroadcastReceiver pluginInstallEvent = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(MainActivity.this, "" + intent.getStringExtra("id") + " "+ intent.getStringExtra("type") + "", Toast.LENGTH_SHORT).show(); listAll(); }; }; @Override protected void onResume() { super.onResume(); FileUtil.printAll(new File(getApplicationInfo().dataDir)); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { LogUtil.d(keyCode); return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { LogUtil.d(keyCode); return super.onKeyUp(keyCode, event); } }