diff
stringlengths
164
2.11M
is_single_chunk
bool
2 classes
is_single_function
bool
2 classes
buggy_function
stringlengths
0
335k
fixed_function
stringlengths
23
335k
diff --git a/src/main/java/org/imirsel/nema/model/Job.java b/src/main/java/org/imirsel/nema/model/Job.java index 2708744..b4874e6 100644 --- a/src/main/java/org/imirsel/nema/model/Job.java +++ b/src/main/java/org/imirsel/nema/model/Job.java @@ -1,369 +1,369 @@ package org.imirsel.nema.model; import java.io.Serializable; import java.util.Date; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.JoinColumn; import javax.persistence.Transient; import org.hibernate.annotations.GenerationTime; import org.hibernate.annotations.Proxy; /** * Represents a NEMA DIY job. * * @author shirk * @since 1.0 */ @Entity @Table(name="job") @Proxy(lazy=false) public class Job implements Serializable, Cloneable { /** * Version of this class. */ private static final long serialVersionUID = 3383935885803288343L; static public enum JobStatus { UNKNOWN(-1), SCHEDULED(0), SUBMITTED(1), STARTED(2), FINISHED(3), FAILED(4), ABORTED(5); private final int code; private JobStatus(int code) { this.code = code; } public int getCode() { return code; } @Override public String toString() { String name = null; switch (code) { case -1: { name = "Unknown"; break; } case 0: { name = "Scheduled"; break; } case 1: { name = "Submitted"; break; } case 2: { name = "Started"; break; } case 3: { name = "Finished"; break; } case 4: { name = "Failed"; break; } case 5: { name = "Aborted"; break; } } return name; } static public JobStatus toJobStatus(int code) { JobStatus status = null; switch (code) { case -1: { status = JobStatus.UNKNOWN; break; } case 0: { status = JobStatus.SCHEDULED; break; } case 1: { status = JobStatus.SUBMITTED; break; } case 2: { status = JobStatus.STARTED; break; } case 3: { status = JobStatus.FINISHED; break; } case 4: { status = JobStatus.FAILED; break; } case 5: { status = JobStatus.ABORTED; break; } } return status; } } private Long id; private String token; private String name; private String description; private String host; private Integer port; private Integer execPort; private Date submitTimestamp; private Date startTimestamp; private Date endTimestamp; private Date updateTimestamp; private Integer statusCode = -1; private Long ownerId; private String ownerEmail; private Flow flow; private Integer numTries = 0; private String executionInstanceId; private Set<JobResult> results; @Id @Column(name="id") @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name="description",length=20000000) public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Column(name="host") public String getHost() { return host; } public void setHost(String host) { this.host = host; } @Column(name="port") public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } @Column(name="submitTimestamp") public Date getSubmitTimestamp() { return submitTimestamp; } public void setSubmitTimestamp(Date submitTimestamp) { this.submitTimestamp = submitTimestamp; } @Column(name="startTimestamp",updatable=false,insertable=false) public Date getStartTimestamp() { return startTimestamp; } public void setStartTimestamp(Date startTimestamp) { this.startTimestamp = startTimestamp; } @Column(name="endTimestamp") public Date getEndTimestamp() { return endTimestamp; } public void setEndTimestamp(Date endTimestamp) { this.endTimestamp = endTimestamp; } @Column(name="statusCode",nullable=false) public Integer getStatusCode() { return statusCode; } public void setStatusCode(Integer statusCode) { // This is a nasty hack to work around the race condition that exists // when the Meandre server updates the job as started, and then the // flow service writes it as submitted. if(this.statusCode==2 && statusCode < 2) { return; } if(!this.statusCode.equals(statusCode)) { setUpdateTimestamp(new Date()); this.statusCode = statusCode; } } @Column(name="token",nullable=false) public String getToken() { return token; } public void setToken(String token) { this.token = token; } @Column(name="name",nullable=false) public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="updateTimestamp",updatable=false,insertable=false) @org.hibernate.annotations.Generated(GenerationTime.ALWAYS) public Date getUpdateTimestamp() { return updateTimestamp; } public void setUpdateTimestamp(Date updateTimestamp) { this.updateTimestamp = updateTimestamp; } @Column(name="ownerId", nullable=false) public Long getOwnerId() { return ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; } @Column(name="ownerEmail", nullable=false) public String getOwnerEmail() { return ownerEmail; } public void setOwnerEmail(String ownerEmail) { this.ownerEmail = ownerEmail; } @JoinColumn(name = "flowInstanceId") @ManyToOne(fetch=FetchType.EAGER,optional=false) public Flow getFlow() { return flow; } public void setFlow(Flow flow) { this.flow = flow; } @Column(name="executionInstanceId",length=20000000) public String getExecutionInstanceId() { return executionInstanceId; } public void setExecutionInstanceId(String executionInstanceId) { this.executionInstanceId = executionInstanceId; } @Transient public JobStatus getJobStatus() { return JobStatus.toJobStatus(statusCode); } public void setJobStatus(JobStatus status) { this.statusCode = status.getCode(); } - @JoinColumn(name="id") + @JoinColumn(name="jobId") @OneToMany(mappedBy="job", fetch=FetchType.EAGER) public Set<JobResult> getResults() { return results; } public void setResults(Set<JobResult> results) { this.results = results; } @Transient public boolean isRunning() { return getJobStatus() == JobStatus.STARTED; } @Transient public boolean isDone() { if (statusCode == JobStatus.FINISHED.getCode() || statusCode == JobStatus.FAILED.getCode() || statusCode == JobStatus.ABORTED.getCode()) { return true; } return false; } @Column(name="numTries",nullable=false) public Integer getNumTries() { return numTries; } public void setNumTries(Integer numTries) { this.numTries = numTries; } public void incrementNumTries() { numTries++; } @Column(name="execPort") public Integer getExecPort() { return execPort; } public void setExecPort(Integer execPort) { this.execPort = execPort; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Job other = (Job) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public Job clone() { Job clone = new Job(); clone.setId(this.getId()); clone.setName(this.getName()); clone.setDescription(this.getDescription()); clone.setSubmitTimestamp(this.getSubmitTimestamp()); clone.setStartTimestamp(this.getStartTimestamp()); clone.setEndTimestamp(this.getEndTimestamp()); clone.setUpdateTimestamp(this.getUpdateTimestamp()); clone.setHost(this.getHost()); clone.setPort(this.getPort()); clone.setFlow(this.getFlow()); clone.setExecPort(this.getExecPort()); clone.setExecutionInstanceId(this.getExecutionInstanceId()); clone.setStatusCode(this.getStatusCode()); clone.setNumTries(this.getNumTries()); clone.setOwnerEmail(this.getOwnerEmail()); clone.setOwnerId(this.getOwnerId()); clone.setResults(this.getResults()); clone.setToken(this.getToken()); return clone; } }
true
false
null
null
diff --git a/src/ucbang/gui/Field.java b/src/ucbang/gui/Field.java index c7d7b4f..37b2dc6 100644 --- a/src/ucbang/gui/Field.java +++ b/src/ucbang/gui/Field.java @@ -1,726 +1,726 @@ package ucbang.gui; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import ucbang.core.Card; import ucbang.core.Deck; import ucbang.core.Player; import ucbang.network.Client; public class Field implements MouseListener, MouseMotionListener{ Client client; public BSHashMap<Card, Clickable> clickies = new BSHashMap<Card, Clickable>(); CardDisplayer cd; Point pointOnCard; Clickable movingCard; Card clicked; ArrayList<Card> pick; public ArrayList<HandSpace> handPlacer = new ArrayList<HandSpace>(); //to avoid npe String description; Point describeWhere; long lastMouseMoved = System.currentTimeMillis(); int tooltipWidth = 0; int tooltipHeight = 0; Point hoverpoint; public Field(CardDisplayer cd, Client c) { this.cd=cd; client = c; } /** * Adds a card to the specified location, owned by the specified player * <p>This method specifies the location of the card to be placed, so for most * cases it should not be used. Use add(Card, int, boolean) whenever possible</p> * @param card The card to be added * @param x The x coordinate of the location * @param y The y coordinate of the location * @param player The player who owns the card * @param field Whether the card is in the field or not */ public void add(Card card, int x, int y, int player, boolean field){ clickies.put(card, new CardSpace(card, new Rectangle(x,y,60,90), player, field)); } /** * Removes the last card in the hand of a player, used when * the player is an opponent whose hand is unknown and they just * played a card * @param player the player whose hand to remove a card from */ public void removeLast(int player){ clickies.remove(handPlacer.get(player).removeLast().card); } /** * Adds a card to the field owned by the specified player * <p>This method is "smart" and can locate cards automatically. * Use this whenever players exist</p> * @param card * @param player * @param field */ public void add(Card card, int player, boolean field){ if(client.id==player) System.out.println("Client has "+client.player.hand.size()+"cards in his hand."); if(card.type==1){//this a character card int x=350; int y=200; clickies.put(card, new CardSpace(card, new Rectangle(x, y,60,90), player, false)); }else{ HandSpace hs = handPlacer.get(player); int fieldoffset = (field?100:0); double handoffset = 30*(!field?client.players.get(player).hand.size():client.players.get(player).field.size()); int xoffset = (int)(handoffset * Math.sin(hs.theta))+(int)(fieldoffset*Math.sin(hs.theta)); int yoffset = (int)(handoffset * Math.cos(hs.theta))+(int)(fieldoffset*Math.cos(hs.theta)); - int x=(int) hs.rect.x+hs.rect.width+xoffset; + int x=(int) hs.rect.x+hs.rect.width-xoffset; int y=(int) hs.rect.y+yoffset; CardSpace cs = new CardSpace(card, new Rectangle(x,y, 60,90), player, field); clickies.put(card, cs); hs.addCard(cs); //if(hs.autoSort) sortHandSpace(hs); } } int textHeight(String message, Graphics2D graphics){ int lineheight=(int)graphics.getFont().getStringBounds("|", graphics.getFontRenderContext()).getHeight(); return message.split("\n").length*lineheight; } int textWidth(String message, Graphics2D graphics){ String[] lines = message.split("\n"); int width=0; for(int i=0;i<lines.length;i++){ int w=(int)graphics.getFont().getStringBounds(lines[i], graphics.getFontRenderContext()).getWidth(); if(width<w) width=w; } return width; } void improvedDrawString(String message, int x, int y, Graphics2D graphics){ int lineheight=(int)graphics.getFont().getStringBounds("|", graphics.getFontRenderContext()).getHeight(); String[] lines = message.split("\n"); for(int i=0;i<lines.length;i++){ graphics.drawString(lines[i], x, y+i*lineheight); } } public void paint(Graphics2D graphics){ for(HandSpace hs : handPlacer){ if(hs.autoSort) graphics.fill(hs.rect); else graphics.draw(hs.rect); } //draw HP cards first /*Iterator<CardSpace> it = hpcards.iterator(); while(it.hasNext()){ CardSpace hp = it.next(); cd.paint("BULLETBACK", graphics, hp.rect.x, hp.rect.y, hp.rect.width, hp.rect.height, Color.BLUE, Color.GRAY); }*/ Iterator<Clickable> iter = clickies.values().iterator(); ArrayList<CardSpace> Char = new ArrayList<CardSpace>(); ArrayList<CardSpace> Bullet = new ArrayList<CardSpace>(); while(iter.hasNext()){ Clickable temp = iter.next(); if(temp instanceof CardSpace){ CardSpace crd = (CardSpace)temp; if(crd.card.name=="BULLETBACK"){ Bullet.add(crd); } else if(crd.card.type==1){ Char.add(crd); } else{ Color inner; switch(crd.card.location){ case 0: inner=Color.BLACK; break; case 1: if(crd.card.type==5) inner=new Color(100,100,200); else{ inner = ((crd.card.name!="JAIL"||crd.card.name!="DYNAMITE")?inner=new Color(100,200,100):new Color(100,100,200)); } break; default: inner=new Color(200,100,100); } //Color outer=client.id==1?Color.RED:Color.BLUE; Color outer; switch(crd.playerid){ case 0: outer = Color.RED; break; case 1: outer = Color.BLUE; break; case 2: outer = Color.CYAN; break; case 3: outer = Color.MAGENTA; break; case 4: outer = Color.YELLOW; break; case 5: outer = Color.ORANGE; break; case 6: outer = Color.GREEN; break; case 7: outer = Color.LIGHT_GRAY; break; case 8: outer = Color.WHITE; break; case 9: outer = Color.PINK; break; default: outer = Color.BLACK; break; } cd.paint(crd.card.name, graphics, crd.rect.x, crd.rect.y, crd.rect.width, temp.rect.height, inner,outer); } }else if(temp instanceof HandSpace){ HandSpace hs = (HandSpace)temp; graphics.draw3DRect(hs.rect.x, hs.rect.y, hs.rect.width, hs.rect.height, true); }else{ System.out.println("WTF"); } } for(CardSpace crd:Bullet){ cd.paint(crd.card.name, graphics, crd.rect.x, crd.rect.y, crd.rect.width, crd.rect.height, Color.BLACK, Color.BLACK); } for(CardSpace crd:Char){ cd.paint(crd.card.name, graphics, crd.rect.x, crd.rect.y, crd.rect.width, crd.rect.height, Color.BLACK, Color.BLACK); } if(description==null&&System.currentTimeMillis()-lastMouseMoved>1000){ //create description Clickable cl = binarySearchCardAtPoint(hoverpoint); if (cl instanceof CardSpace) { CardSpace cs = (CardSpace) cl; if (cs != null && cs.card != null){ if(cs.card.description.equals("")) description = cs.card.name.replace('_', ' '); else description = cs.card.name+" - "+cs.card.description; if(cs.card.type==1){ if(client.players.get(cs.playerid).maxLifePoints>0) description = description + "\n" + client.players.get(cs.playerid).lifePoints +"HP";; //TODO: add distance to tooltip? } describeWhere = hoverpoint; tooltipWidth = textWidth(description, graphics); tooltipHeight = textHeight(description, graphics); } } } if(description!=null){ Rectangle2D bounds=graphics.getFont().getStringBounds(description, graphics.getFontRenderContext()); Color temp=graphics.getColor(); graphics.setColor(Color.YELLOW); graphics.fill3DRect(describeWhere.x, describeWhere.y-(int)bounds.getHeight()+32, tooltipWidth, tooltipHeight,false); graphics.setColor(Color.BLACK); improvedDrawString(description, describeWhere.x, describeWhere.y+30,graphics); graphics.setColor(temp); } } public Clickable binarySearchCardAtPoint(Point ep){ //bsearch method int start; int end; ArrayList<Clickable> al = clickies.values(); //search the values arrayList for... if(al.isEmpty()||ep==null)return null; int a = 0, b = al.size(), index = al.size() / 2; while (a != b) { if (ep.y > al.get(index).rect.y + 85) { // the "start" is the value of the card whose bottom is closest to the cursor (and on the cursor) a = index + 1; } else { b = index; } index = a + (b - a) / 2; } start = a; a = 0; b = al.size(); index = al.size() / 2; while (a != b) { if (ep.y > al.get(index).rect.y) { // the "end" is the value of the card whose top is closest to the cursor (and on the cursor) a = index + 1; } else { b = index; } index = a + (b - a) / 2; } end = a - 1; for (int n = end; n>= start; n--) { Clickable s = al.get(n); if (s.rect.contains(ep.x, ep.y)) { return al.get(n); } } return null; } public void start2(){ handPlacer = new ArrayList<HandSpace>(client.numPlayers); double theta; HandSpace hs = null; clear(); for(int player = 0; player<client.numPlayers; player++){ theta = -(player-client.id)*(2*Math.PI/client.numPlayers)-Math.PI/2; int hsx = client.gui.width/2+(int)((client.gui.width-150)/2*Math.cos(theta)); int hsy = 280-(int)(220*Math.sin(theta)); hs=new HandSpace(new Rectangle(hsx, hsy,10,10), player, theta); handPlacer.add(hs); Card chara=null; if(client.players.get(player).character>=0){ System.out.println(player+":"+Deck.Characters.values()[client.players.get(player).character]); chara = new Card(Deck.Characters.values()[client.players.get(player).character]); }else if(client.id==player){ System.out.println(player+":"+Deck.Characters.values()[client.player.character]); chara = new Card(Deck.Characters.values()[client.player.character]); } if(chara!=null){ int x=(int) hs.rect.x-60; int y=(int) hs.rect.y; CardSpace csp = new CardSpace(chara,new Rectangle(x,y-60,60,90), player, false); //generate HP card Card hp = new Card(Deck.CardName.BULLETBACK); CardSpace hps = new CardSpace(hp, new Rectangle(x+ 10 * client.players.get(player).maxLifePoints,y-60,90,60),player, false); hps.setPartner(csp); csp.setPartner(hps); //hps.rotate(1); clickies.put(hp, hps); clickies.put(chara, csp); hs.setCharHP(csp, hps); } } } public void clear(){ pointOnCard = null; movingCard = null; clickies.clear(); } public void mouseClicked(MouseEvent e) { Point ep=e.getPoint(); ////the ugly proxy skip turn button if(new Rectangle(760, 560, 40, 40).contains(ep)){ if(client.prompting&&!client.forceDecision){ client.outMsgs.add("Prompt:-1"); client.prompting = false; } return; } Clickable cl = binarySearchCardAtPoint(ep); if (cl instanceof CardSpace) { CardSpace cs = (CardSpace) cl; if (cs != null && cs.card != null){ if(cs.playerid != -1) client.gui.appendText(String.valueOf(client.players.get(cs.playerid).hand.indexOf(cs.card))+" "+(cs.hs!=null?String.valueOf(cs.hs.cards.indexOf(cs)):"")); else if(pick != null) client.gui.appendText(String.valueOf(pick.contains(cs.card))); } else return; if (e.getButton() == MouseEvent.BUTTON3) { //Put right click stuff here, or not }else if (client.prompting){ if(pick!= null && pick.contains(cs.card)) { System.out.println("000000000000000000000000000000 "+pick.size()+" "+client.player.hand.size()); System.out.println("sending prompt..."); if (cs.card.type == 1) { client.outMsgs.add("Prompt:" + pick.indexOf(cs.card)); client.player.hand.clear(); //you just picked a character card clear(); } else { client.outMsgs.add("Prompt:" + pick.indexOf(cs.card)); } pick = null; client.prompting = false; } else if(client.forceDecision==false){ //it's your turn if(client.targetingPlayer){ if(cs.card.type==1||cs.card.name=="BULLETBACK"){ client.targetingPlayer = false; client.prompting = false; client.outMsgs.add("Prompt:" + cs.playerid); } } else if(client.nextPrompt==-1){ Player p = client.players.get(cs.playerid); if(cs.card.location==0){ client.nextPrompt = p.hand.indexOf(cs.card); client.gui.appendText("Index of card is "+client.nextPrompt); } else{ client.nextPrompt = ((0-client.players.get(cs.playerid).field.indexOf(cs.card))-3); client.gui.appendText("lol "+client.nextPrompt); } client.outMsgs.add("Prompt:"+p.id); } else{ client.outMsgs.add("Prompt:" + ((0-client.player.field.indexOf(cs.card))-3)); pick = null; client.prompting = false; } } else{ System.out.println("i was prompting, but a bad card was given"); } } } else if(cl == null){ for(HandSpace cs : handPlacer) if(cs.rect.contains(e.getPoint())){ cl=cs; } if(cl!=null){ if(e.getButton()==MouseEvent.BUTTON1) sortHandSpace((HandSpace)cl); if(e.getButton()==MouseEvent.BUTTON3) ((HandSpace)cl).autoSort = !((HandSpace)cl).autoSort; } } } public void mousePressed(MouseEvent e) { movingCard = binarySearchCardAtPoint(e.getPoint()); if(movingCard==null){//placer handler for(HandSpace cs : handPlacer) if(cs.rect.contains(e.getPoint())){ movingCard=cs; } } if(movingCard!=null){ pointOnCard = new Point(e.getPoint().x-movingCard.rect.x, e.getPoint().y-movingCard.rect.y); //System.out.println("picked up card"); } } public void mouseReleased(MouseEvent e) { if(movingCard!=null){ //System.out.println("card dropped"); } movingCard = null; description = null; } public void mouseDragged(MouseEvent e) { //System.out.println("dragging"); lastMouseMoved = System.currentTimeMillis(); if(movingCard!=null){ movingCard.move(Math.max(0, Math.min(e.getPoint().x-pointOnCard.x,client.gui.getWidth()-55)),Math.max(0, Math.min(e.getPoint().y-pointOnCard.y,client.gui.getHeight()-85))); //replace boundaries with width()/height() of frame? } else{ //System.out.println("not dragging"); } } public void sortHandSpace(HandSpace hs){ if(hs==null){ System.out.println("WTWFWTWFWWTFWTWTWWAFSFASFASFS"); return; } client.gui.appendText("Sorting..."); int player = hs.playerid; for(int n = 0; n<hs.cards.size(); n++){ int x = (int) hs.rect.x+hs.rect.width+30*n; int y = (int) hs.rect.y+(0); //more trinarytrinary fun! hs.cards.get(n).rect.x = x; hs.cards.get(n).rect.y = y; } for(int n = 0; n<hs.fieldCards.size(); n++){ int x = (int) hs.rect.x+hs.rect.width+30*n; int y = (int) hs.rect.y+(0) +(player==client.id?-100:100); //more trinarytrinary fun! hs.fieldCards.get(n).rect.x = x; hs.fieldCards.get(n).rect.y = y; } } public class BSHashMap<K,V> extends HashMap<K,V>{ ArrayList<V> occupied = new ArrayList<V>(); public V put(K key, V value){ occupied.add(value); return super.put(key, value); } public ArrayList<V> values(){ ArrayList<V> al = new ArrayList<V>(); Collections.sort(occupied, new Comparator(){ public int compare(Object o1, Object o2) { return ((Comparable<Object>)o1).compareTo(o2); } }); al.addAll(occupied); return al; } public void clear(){ occupied.clear(); super.clear(); } public V remove(Object o){ if(o instanceof Card){ CardSpace cs =(CardSpace)get(o); if(cs==null){ client.gui.appendText("WTFWTFWTF"); } if(cs.hs != null){ if(!cs.field) cs.hs.cards.remove(cs); else cs.hs.fieldCards.remove(cs); if(cs.hs.autoSort){ sortHandSpace(cs.hs); } } //System.out.println(cs.card.name+" "+cs.playerid+" "+(cs.hs==null)+" "+handPlacer.get(cs.playerid).fieldCards.contains(cs)); } occupied.remove(get(o)); V oo = super.remove(o); return oo; } } /* * Contains a card and a rectangle */ private class CardSpace extends Clickable{ public Card card; public boolean field; HandSpace hs; /** * @param c The card this CardSpace describes * @param r The bounds of the card * @param player The player who owns the card * @param f Whether the card is on the field * @param partner The parent container of the card */ public CardSpace(Card c, Rectangle r, int player, boolean f){ super(r); card = c; rect = r; playerid = player; field = f; if(!handPlacer.isEmpty()&& player != -1) hs = handPlacer.get(playerid); } } public class HandSpace extends Clickable{ public ArrayList<CardSpace> cards = new ArrayList<CardSpace>(); public ArrayList<CardSpace> fieldCards = new ArrayList<CardSpace>(); CardSpace character, hp; boolean autoSort = true; double theta; /** * @param r * @param player * @param theta */ public HandSpace(Rectangle r, int player, double theta){ super(r); playerid = player; this.theta = theta; } /** * @param character * @param hp */ public void setCharHP(CardSpace character, CardSpace hp){ this.character = character; this.hp = hp; } /** * @param card */ public void addCard(CardSpace card){ if(!card.field) cards.add(card); else fieldCards.add(card); } /** * @return */ public CardSpace removeLast(){ return cards.remove(cards.size()-1); } /* (non-Javadoc) * @see ucbang.gui.Field.Clickable#move(int, int) */ public void move(int x, int y){ int dx = x-rect.x; int dy = y-rect.y; super.move(x, y); Iterator<CardSpace> iter = cards.iterator(); while(iter.hasNext()){ iter.next().translate(dx, dy); } //add a special boolean here iter = fieldCards.iterator(); while(iter.hasNext()){ iter.next().translate(dx, dy); } if(character!=null)character.translate(dx, dy); if(hp!=null)hp.translate(dx, dy); } /* (non-Javadoc) * @see ucbang.gui.Field.Clickable#translate(int, int) */ public void translate(int dx, int dy){ super.translate(dx, dy); Iterator<CardSpace> iter = cards.iterator(); while(iter.hasNext()){ iter.next().translate(dx, dy); } //add a special boolean here iter = fieldCards.iterator(); while(iter.hasNext()){ iter.next().translate(dx, dy); } if(character!=null)character.translate(dx, dy); if(hp!=null)hp.translate(dx, dy); } } /** * @author Ibrahim * */ private abstract class Clickable implements Comparable<Clickable>{ public Rectangle rect; //public int location; //position of card on field or in hand public int playerid; public AffineTransform at; private int oldrotation=0; private Clickable partner; /** * @param r */ public Clickable(Rectangle r){ rect=r; } public int compareTo(Clickable o) { if(o.rect.getLocation().y!=rect.getLocation().y) return ((Integer)rect.getLocation().y).compareTo(o.rect.getLocation().y); else return ((Integer)rect.getLocation().x).compareTo(o.rect.getLocation().x); } /** * Moves the Clickable to the specified location * @param x * @param y */ public void move(int x, int y){ int dx = x-rect.x; int dy = y-rect.y; if(at!=null)at.translate(rect.x-x, rect.y-y); rect.setLocation(x, y); if(partner!=null){ partner.translate(dx, dy); } } /** * Sets the Clickable's partner. * <p>If a Clickable has a partner defined, moving it will also * translate the partner so that they move together.</p> * @param partner the other Clickable to be set as the partner */ public void setPartner(Clickable partner){ this.partner=partner; } /** * Rotates the clickable the specified number of quadrants, i.e. 90 degree intervals. * <p>This is fairly buggy, and should not be called more than once under any circumstances for * a given card or type of card. Deprecated until further notice, since only the bullet card is * currently rotated. For rotation to work nicely, Clickable will have to store an image of the * card or whatever so that it is rotated independently of other instances of the same card. * @param quadrant the number of 90 degree intervals to rotate */ public void rotate(int quadrant){//rotates in terms of 90 degree increments. call with 0 to reset. int realrotation=quadrant-oldrotation; if(realrotation>0 && realrotation<4){ if(this instanceof CardSpace){ cd.rotateImage(((CardSpace)this).card.name, quadrant); } at = AffineTransform.getQuadrantRotateInstance(realrotation, rect.x+rect.width/2, rect.y+rect.height/2); oldrotation=quadrant; PathIterator iter = rect.getPathIterator(at); int i=0; float[] pts= new float[6]; int newx=-1, newy=-1, newwidth=-1, newheight=-1; while(!iter.isDone()){ int type = iter.currentSegment(pts); switch(type){ case PathIterator.SEG_MOVETO : //temp.add((int)pts[0],(int)pts[1]); //System.out.println(pts[0]+","+pts[1]); break; case PathIterator.SEG_LINETO : if(i==1){ newx=(int) pts[0];//misnomers for this part lol. newy=(int) pts[1]; }else if(i==3){ newwidth=(int)Math.abs(newx-(int)pts[0]); newheight=(int)Math.abs(newy-(int)pts[1]); newx=(int) pts[0]; newy=(int) pts[1]; } break; } i++; iter.next(); } rect = new Rectangle(newx, newy, newwidth, newheight); System.out.println(rect); at=null; }else{ //at=null; } } /** * @param dx * @param dy */ public void translate(int dx, int dy){ rect.translate(dx, dy); } } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mouseMoved(MouseEvent e) { lastMouseMoved = System.currentTimeMillis(); hoverpoint=e.getPoint(); description=null; } /** * Scales all objects to the newly resized coordinates. * @param width * @param height * @param width2 * @param height2 */ public void resize(int width, int height, int width2, int height2) { ArrayList<Clickable> stuff = clickies.values(); Iterator<Clickable> iter = stuff.iterator(); for(HandSpace hs: handPlacer){ hs.move(hs.rect.x*width2/width, hs.rect.y*height2/height); } } /** * Sets the given players's HP and updates the bullet display accordingly * @param playerid the id of the player whose HP changed * @param lifePoints the amount of HP the player lost */ public void setHP(int playerid, int lifePoints) { if(lifePoints == 0) //bug when saloon is played when you have full hp return; CardSpace hpc = handPlacer.get(playerid).hp; hpc.translate(-10*lifePoints, 0); } }
true
false
null
null
diff --git a/src/test/java/edu/uw/zookeeper/SimpleServerAndClient.java b/src/test/java/edu/uw/zookeeper/SimpleServerAndClient.java index 73349246..f3fd7f39 100644 --- a/src/test/java/edu/uw/zookeeper/SimpleServerAndClient.java +++ b/src/test/java/edu/uw/zookeeper/SimpleServerAndClient.java @@ -1,148 +1,150 @@ package edu.uw.zookeeper; import java.net.InetSocketAddress; import java.util.List; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Service; import edu.uw.zookeeper.client.SimpleClientBuilder; import edu.uw.zookeeper.common.RuntimeModule; import edu.uw.zookeeper.net.intravm.IntraVmNetModule; import edu.uw.zookeeper.server.SimpleServerBuilder; public class SimpleServerAndClient implements ZooKeeperApplication.RuntimeBuilder<List<Service>, SimpleServerAndClient> { public static SimpleServerAndClient defaults() { return new SimpleServerAndClient(); } protected final RuntimeModule runtime; protected final IntraVmNetModule netModule; protected final SimpleServerBuilder serverBuilder; protected final SimpleClientBuilder clientBuilder; protected SimpleServerAndClient() { this(null, null, null, null); } protected SimpleServerAndClient( IntraVmNetModule netModule, SimpleServerBuilder server, SimpleClientBuilder client, RuntimeModule runtime) { this.netModule = netModule; this.serverBuilder = server; this.clientBuilder = client; this.runtime = runtime; } @Override public RuntimeModule getRuntimeModule() { return runtime; } @Override public SimpleServerAndClient setRuntimeModule( RuntimeModule runtime) { if (this.runtime == runtime) { return this; } else { return newInstance( netModule, (serverBuilder == null) ? serverBuilder : serverBuilder.setRuntimeModule(runtime), (clientBuilder == null) ? clientBuilder : clientBuilder.setRuntimeModule(runtime), runtime); } } public IntraVmNetModule getNetModule() { return netModule; } public SimpleServerAndClient setNetModule(IntraVmNetModule netModule) { if (this.netModule == netModule) { return this; } else { return newInstance(netModule, serverBuilder, clientBuilder, runtime); } } public SimpleServerBuilder getServerBuilder() { return serverBuilder; } public SimpleServerAndClient setServerBuilder(SimpleServerBuilder serverBuilder) { if (this.serverBuilder == serverBuilder) { return this; } else { return newInstance(netModule, serverBuilder, clientBuilder, runtime); } } public SimpleClientBuilder getClientBuilder() { return clientBuilder; } public SimpleServerAndClient setClientBuilder(SimpleClientBuilder clientBuilder) { if (this.clientBuilder == clientBuilder) { return this; } else { return newInstance(netModule, serverBuilder, clientBuilder, runtime); } } @Override public SimpleServerAndClient setDefaults() { if (runtime == null) { return setRuntimeModule(getDefaultRuntimeModule()).setDefaults(); } if (netModule == null) { return setNetModule(getDefaultNetModule()).setDefaults(); } if (serverBuilder == null) { return setServerBuilder(getDefaultServerBuilder().setDefaults()).setDefaults(); } if (clientBuilder == null) { return setClientBuilder(getDefaultClientBuilder().setDefaults()).setDefaults(); } return this; } @Override public List<Service> build() { return setDefaults().getServices(); } protected SimpleServerAndClient newInstance( IntraVmNetModule netModule, - SimpleServerBuilder server, - SimpleClientBuilder client, + SimpleServerBuilder serverBuilder, + SimpleClientBuilder clientBuilder, RuntimeModule runtime) { return new SimpleServerAndClient(netModule, serverBuilder, clientBuilder, runtime); } protected RuntimeModule getDefaultRuntimeModule() { return DefaultRuntimeModule.defaults(); } protected IntraVmNetModule getDefaultNetModule() { return IntraVmNetModule.defaults(); } protected SimpleServerBuilder getDefaultServerBuilder() { ServerInetAddressView address = ServerInetAddressView.of((InetSocketAddress) netModule.factory().addresses().get()); - return SimpleServerBuilder.defaults(address, netModule).setRuntimeModule(runtime); + return SimpleServerBuilder.defaults( + address, netModule).setRuntimeModule(runtime); } protected SimpleClientBuilder getDefaultClientBuilder() { - return SimpleClientBuilder.defaults(serverBuilder.getConnectionBuilder().getAddress(), netModule).setRuntimeModule(runtime); + return SimpleClientBuilder.defaults( + serverBuilder.getConnectionBuilder().getAddress(), netModule).setRuntimeModule(runtime); } protected List<Service> getServices() { List<Service> services = Lists.newLinkedList(); services.addAll(serverBuilder.build()); services.addAll(clientBuilder.build()); return services; } } \ No newline at end of file
false
false
null
null
diff --git a/gpswinggui/src/main/java/org/geopublishing/geopublisher/swing/GpSwingUtil.java b/gpswinggui/src/main/java/org/geopublishing/geopublisher/swing/GpSwingUtil.java index dc5626fe..be890862 100644 --- a/gpswinggui/src/main/java/org/geopublishing/geopublisher/swing/GpSwingUtil.java +++ b/gpswinggui/src/main/java/org/geopublishing/geopublisher/swing/GpSwingUtil.java @@ -1,548 +1,548 @@ package org.geopublishing.geopublisher.swing; /******************************************************************************* * Copyright (c) 2010 Stefan A. Tzeggai. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v2.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * Stefan A. Tzeggai - initial API and implementation ******************************************************************************/ import java.awt.Component; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import javax.swing.JOptionPane; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.geopublishing.atlasViewer.AVProps; import org.geopublishing.atlasViewer.AtlasConfig; import org.geopublishing.atlasViewer.AtlasRefInterface; import org.geopublishing.atlasViewer.dp.DpEntry; import org.geopublishing.atlasViewer.dp.DpRef; import org.geopublishing.atlasViewer.dp.Group; import org.geopublishing.atlasViewer.dp.layer.DpLayer; import org.geopublishing.atlasViewer.dp.media.DpMedia; import org.geopublishing.atlasViewer.exceptions.AtlasImportException; import org.geopublishing.atlasViewer.map.Map; import org.geopublishing.atlasViewer.swing.AVSwingUtil; import org.geopublishing.atlasViewer.swing.AtlasSwingWorker; import org.geopublishing.geopublisher.AMLExporter; import org.geopublishing.geopublisher.AtlasConfigEditable; import org.geopublishing.geopublisher.GpUtil; import org.geopublishing.geopublisher.gui.internal.GPDialogManager; import schmitzm.io.IOUtil; import schmitzm.jfree.chart.style.ChartStyle; import schmitzm.lang.LangUtil; import schmitzm.swing.ExceptionDialog; import schmitzm.swing.SwingUtil; import skrueger.i8n.I8NUtil; public class GpSwingUtil extends GpUtil { private static final Logger LOGGER = Logger.getLogger(GpSwingUtil.class); /** * Deletes a {@link DpEntry}. This deletes the Entry from the Atlas' * datapool, as well as all references to it, as well as the folder on disk. * * @param ace * {@link AtlasConfigEditable} where the {@link DpEntry} is part * of. * @param dpe * {@link DpEntry} to be deleted. * @param askUserToVerify * If <code>true</code>, the user will be asked for confirmation. * The confirmation will list all references. If * <code>false</code>, the DPE and all references are * automatically removed. * * @return <code>null</code> if the deletion failed or was aborted by the * user. Otherwise the removed {@link DpEntry}. */ public static DpEntry<?> deleteDpEntry(Component owner, AtlasConfigEditable ace, DpEntry<?> dpe, boolean askUserToVerify) { LinkedList<AtlasRefInterface<?>> references = new LinkedList<AtlasRefInterface<?>>(); // **************************************************************************** // Go through all mapPoolEntries and groups and count the references to // this DatapoolEntry // **************************************************************************** Set<Map> mapsWithReferences = new HashSet<Map>(); for (Map map : ace.getMapPool().values()) { for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) { if (ref.getTargetId().equals(dpe.getId())) { references.add(ref); mapsWithReferences.add(map); } } for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) { if (ref.getTargetId().equals(dpe.getId())) { references.add(ref); mapsWithReferences.add(map); } } map.getAdditionalStyles().remove(dpe.getId()); map.getSelectedStyleIDs().remove(dpe.getId()); } int countRefsInMappool = references.size(); // **************************************************************************** // Go through all group tree count the references to this DatapoolEntry // **************************************************************************** Group group = ace.getFirstGroup(); Group.findReferencesTo(group, dpe, references, false); if (askUserToVerify) { // Ask the user if she still wants to delete the DPE, even though // references exist. int res = JOptionPane.showConfirmDialog(owner, GpUtil.R( "DeleteDpEntry.QuestionDeleteDpeAndReferences", dpe .getFilename(), countRefsInMappool, LangUtil .stringConcatWithSep(", ", mapsWithReferences), references.size() - countRefsInMappool, dpe.getTitle() .toString()), GpUtil .R("DataPoolWindow_Action_DeleteDPE_label" + " " + dpe.getTitle()), JOptionPane.YES_NO_OPTION); - if (res == JOptionPane.NO_OPTION) + if (res != JOptionPane.YES_OPTION) return null; } // Close all dialogs that use this layer if (!GPDialogManager.closeAllMapComposerDialogsUsing(dpe)) return null; // **************************************************************************** // Delete the references first. Kill DesignMapViewJDialogs if affected. // Abort everything if the user doesn't want to close the // DesignMapViewJDialog. // **************************************************************************** for (Map map : ace.getMapPool().values()) { boolean affected = false; // Check all the layers final LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>> layersNew = new LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>>(); for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) { if (!ref.getTargetId().equals(dpe.getId())) layersNew.add(ref); else { affected = true; } } // Check all the media final List<DpRef<DpMedia<? extends ChartStyle>>> mediaNew = new LinkedList<DpRef<DpMedia<? extends ChartStyle>>>(); for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) { if (!ref.getTargetId().equals(dpe.getId())) mediaNew.add(ref); else { affected = true; } } // Close any open DesignMapViewJDialogs or abort if the user doesn't // want to close. if (affected) { if (!GPDialogManager.dm_MapComposer.close(map)) return null; } // Now we change this map map.setLayers(layersNew); map.setMedia(mediaNew); } Group.findReferencesTo(group, dpe, references, true); final File dir = new File(ace.getDataDir(), dpe.getDataDirname()); try { FileUtils.deleteDirectory(dir); } catch (IOException e) { ExceptionDialog.show(owner, e); } return ace.getDataPool().remove(dpe.getId()); } /** * Checks if a filename is OK for the AV. Asks the use to accespt the * changed name * * @param owner * GUI owner * @param nameCandidate * Filename to check, e.g. bahn.jpg * @return <code>null</code> if the user didn't accept the new filename. * * @throws AtlasImportException * if the user doesn't like the change of the filename. */ public static String cleanFilenameWithUI(Component owner, String nameCandidate) throws AtlasImportException { String cleanName = IOUtil.cleanFilename(nameCandidate); if (!cleanName.equals(nameCandidate)) { /** * The candidate was not clean. Ask the user to accept the new name * or cancel. */ if (!AVSwingUtil.askOKCancel(owner, R("Cleanfile.Question", nameCandidate, cleanName))) { throw new AtlasImportException(R( "Cleanfile.Denied.ImportCancelled", nameCandidate)); } } return cleanName; } /** * Validates, that all directory references actually exist. If some * directory is missing, asks the user if he want's to delete the entry and * all references to it.<br/> * Also checks that all directories in <code>ad/data</code> folder are * actually referenced. If now, the used is asked to delete the folder.</br> * This method also initializes the size-cache for every {@link DpEntry}. */ public static void validate(AtlasConfigEditable ace, final Component owner) { LOGGER.debug("starting validation of datatpool"); LinkedList<DpEntry<?>> errorEntries = new LinkedList<DpEntry<?>>(); // **************************************************************************** // First collect all erroneous DpEntries... // **************************************************************************** for (DpEntry<?> dpe : ace.getDataPool().values()) { File dir = new File(ace.getDataDir(), dpe.getDataDirname()); // Checking for possible errors... if (!dir.exists() || !dir.isDirectory()) { errorEntries.add(dpe); } else { // Calculate the size of the folder now and cache it for // later... ace.getFolderSize(dpe); } } // **************************************************************************** // ... now delete them. (We should not modify a datapool that we are // iterating through. // **************************************************************************** for (final DpEntry<?> dpe : errorEntries) { final String msg1 = GpUtil.R( "AtlasLoader.Validation.dpe.invalid.msg", dpe.getTitle(), dpe.getId()); final String msg2 = GpUtil.R( "AtlasLoader.Validation.dpe.invalid.msg.folderDoesnExist", new File(ace.getDataDir(), dpe.getDataDirname()) .getAbsolutePath()); final String question = GpUtil .R("AtlasLoader.Validation.dpe.invalid.msg.exitOrRemoveQuestion"); if (AVSwingUtil.askYesNo(owner, msg1 + "\n" + msg2 + "\n" + question)) { deleteDpEntry(owner, ace, dpe, false); } } cleanFolder(ace, owner); } /** * Checks the data dir folder of the {@link AtlasConfigEditable} and asks to * delete any unexpected folders. * * @param owner * if <code>null</code> all files will be deleted automatically */ public static void cleanFolder(AtlasConfigEditable ace, final Component owner) { // **************************************************************************** // now list all directories in ad/html and check whether they are // actually used // **************************************************************************** for (File dir : ace.getHtmlDir().listFiles()) { if (!dir.isDirectory()) continue; if (dir.getName().startsWith(".")) continue; // if (dir.getName().equals(AtlasConfigEditable.IMAGES_DIRNAME)) // continue; if (dir.getName().equals(AtlasConfigEditable.ABOUT_DIRNAME)) continue; boolean isReferenced = false; for (Map map : ace.getMapPool().values()) { if (ace.getHtmlDirFor(map).getName().equals(dir.getName())) { isReferenced = true; break; } } if (isReferenced) continue; LOGGER.info("The map directory " + IOUtil.escapePath(dir) + " is not referenced in the atlas."); askToDeleteUnreferencedFolder(ace.getHtmlDir(), owner, dir); } // **************************************************************************** // now list all directories in ad/data and check whether they are // actually used // **************************************************************************** for (File dir : ace.getDataDir().listFiles()) { if (!dir.isDirectory()) continue; if (dir.getName().startsWith(".")) { continue; } boolean isReferenced = false; for (DpEntry<?> dpe : ace.getDataPool().values()) { if (dpe.getDataDirname().equals(dir.getName())) { isReferenced = true; break; } } if (isReferenced) continue; LOGGER.info("The directory " + IOUtil.escapePath(dir) + " is not referenced in the atlas."); askToDeleteUnreferencedFolder(ace.getDataDir(), owner, dir); } } /** * Asks to delete a file or folder and returns <code>true</code> if the file * has been deleted. */ private static boolean askToDeleteUnreferencedFolder(File dir, final Component owner, File d) { boolean askDelete = true; if (owner != null) askDelete = AVSwingUtil .askOKCancel( owner, GpSwingUtil .R("UnreferencedDirectoryFoundInAtlasDataDir_AskIfItShouldBeDeleted", IOUtil.escapePath(dir), d.getName())); if (askDelete) { if (owner != null) LOGGER.info("User allowed to delete folder " + IOUtil.escapePath(d) + "."); else LOGGER.info("Automatically delete folder " + IOUtil.escapePath(d) + "."); if ((d.isDirectory() && new File(d, ".svn").exists())) { LOGGER.info("Please use:\nsvn del \"" + IOUtil.escapePath(d) + "\" && svn commit \"" + IOUtil.escapePath(d) + "\" -m \"deleted an unused directory\""); if (owner != null) AVSwingUtil .showMessageDialog( owner, GpSwingUtil .R("UnreferencedDirectoryFoundInAtlasDataDir_WillNotBeDeletedDueToSvnButOfferTheCommand", d.getName(), IOUtil.escapePath(d))); } else { // Just delete the directory! return FileUtils.deleteQuietly(d); } } return false; } /** * Save the {@link AtlasConfig} to its project directory * * @param parentGUI * If not <code>null</code>, the user get's feedback message * SaveAtlas.Success.Message * * @return false Only if there happened an error while saving. If there is * nothing to save, returns true; */ public static boolean save(final AtlasConfigEditable ace, final Component parentGUI, boolean confirm) { SwingUtil.checkOnEDT(); ; AtlasSwingWorker<Boolean> swingWorker = new AtlasSwingWorker<Boolean>( parentGUI) { @Override protected Boolean doInBackground() throws Exception { AMLExporter amlExporter = new AMLExporter(ace); if (amlExporter.saveAtlasConfigEditable(statusDialog)) { ace.getProperties().save( new File(ace.getAtlasDir(), AVProps.PROPERTIESFILE_RESOURCE_NAME)); new File(ace.getAtlasDir(), AtlasConfigEditable.ATLAS_GPA_FILENAME) .createNewFile(); return true; } return false; } }; try { Boolean saved = swingWorker.executeModal(); if (saved && confirm) { JOptionPane.showMessageDialog(parentGUI, GeopublisherGUI.R("SaveAtlas.Success.Message")); } return saved; } catch (Exception e) { ExceptionDialog.show(parentGUI, e); return false; } } /** * Returns a {@link List} of {@link File}s that point to the HTML info files * of a DpLayer. The order of the {@link File}s in the {@link List} is equal * to the order of the languages.<br/> * All HTML files returned to exist! If they don't exist they are being * created with a default text. * * @param dpl * {@link DpLayer} that the HTML files belong to. */ static public List<File> getHTMLFilesFor( DpLayer<?, ? extends ChartStyle> dpl) { List<File> htmlFiles = new ArrayList<File>(); AtlasConfigEditable ac = (AtlasConfigEditable) dpl.getAtlasConfig(); File dir = new File(ac.getDataDir(), dpl.getDataDirname()); for (String lang : ac.getLanguages()) { try { File htmlFile = new File( (FilenameUtils.removeExtension(new File(dir, dpl .getFilename()).getCanonicalPath()) + "_" + lang + ".html")); if (!htmlFile.exists()) { LOGGER.info("Creating a default info HTML file for dpe " + dpl.getTitle() + "\n at " + htmlFile.getAbsolutePath()); /** * Create a default HTML About window */ FileWriter fw = new FileWriter(htmlFile); fw.write(GpUtil.R("DPLayer.HTMLInfo.DefaultHTMLFile", I8NUtil.getFirstLocaleForLang(lang) .getDisplayLanguage(), dpl.getTitle())); fw.flush(); fw.close(); } htmlFiles.add(htmlFile); } catch (IOException e) { LOGGER.error(e); ExceptionDialog.show(GeopublisherGUI.getInstance().getJFrame(), e); } } return htmlFiles; } /** * Returns a {@link List} of {@link File}s that point to the HTML info * filesfor a {@link Map}. The order of the {@link File}s in the * {@link List} is equal to the order of the languages.<br/> * All HTML files returned to exist! If they don't exist they are being * created with a default text. * * @param dpl * {@link DpLayer} that the HTML files belong to. */ public static List<File> getHTMLFilesFor(Map map) { List<File> htmlFiles = new ArrayList<File>(); AtlasConfigEditable ace = (AtlasConfigEditable) map.getAc(); File dir = new File(ace.getHtmlDir(), map.getId()); dir.mkdirs(); for (String lang : ace.getLanguages()) { try { File htmlFile = new File(new File(dir, "index" + "_" + lang + ".html").getCanonicalPath()); if (!htmlFile.exists()) { LOGGER.info("Creating a default info HTML file for map " + map.getTitle() + "\n at " + htmlFile.getAbsolutePath()); /** * Create a default HTML About window */ FileWriter fw = new FileWriter(htmlFile); fw.write(GpUtil.R("Map.HTMLInfo.DefaultHTMLFile", I8NUtil .getFirstLocaleForLang(lang).getDisplayLanguage(), map.getTitle())); fw.flush(); fw.close(); } htmlFiles.add(htmlFile); } catch (IOException e) { LOGGER.error(e); ExceptionDialog.show(GeopublisherGUI.getInstance().getJFrame(), e); } } return htmlFiles; } }
true
true
public static DpEntry<?> deleteDpEntry(Component owner, AtlasConfigEditable ace, DpEntry<?> dpe, boolean askUserToVerify) { LinkedList<AtlasRefInterface<?>> references = new LinkedList<AtlasRefInterface<?>>(); // **************************************************************************** // Go through all mapPoolEntries and groups and count the references to // this DatapoolEntry // **************************************************************************** Set<Map> mapsWithReferences = new HashSet<Map>(); for (Map map : ace.getMapPool().values()) { for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) { if (ref.getTargetId().equals(dpe.getId())) { references.add(ref); mapsWithReferences.add(map); } } for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) { if (ref.getTargetId().equals(dpe.getId())) { references.add(ref); mapsWithReferences.add(map); } } map.getAdditionalStyles().remove(dpe.getId()); map.getSelectedStyleIDs().remove(dpe.getId()); } int countRefsInMappool = references.size(); // **************************************************************************** // Go through all group tree count the references to this DatapoolEntry // **************************************************************************** Group group = ace.getFirstGroup(); Group.findReferencesTo(group, dpe, references, false); if (askUserToVerify) { // Ask the user if she still wants to delete the DPE, even though // references exist. int res = JOptionPane.showConfirmDialog(owner, GpUtil.R( "DeleteDpEntry.QuestionDeleteDpeAndReferences", dpe .getFilename(), countRefsInMappool, LangUtil .stringConcatWithSep(", ", mapsWithReferences), references.size() - countRefsInMappool, dpe.getTitle() .toString()), GpUtil .R("DataPoolWindow_Action_DeleteDPE_label" + " " + dpe.getTitle()), JOptionPane.YES_NO_OPTION); if (res == JOptionPane.NO_OPTION) return null; } // Close all dialogs that use this layer if (!GPDialogManager.closeAllMapComposerDialogsUsing(dpe)) return null; // **************************************************************************** // Delete the references first. Kill DesignMapViewJDialogs if affected. // Abort everything if the user doesn't want to close the // DesignMapViewJDialog. // **************************************************************************** for (Map map : ace.getMapPool().values()) { boolean affected = false; // Check all the layers final LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>> layersNew = new LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>>(); for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) { if (!ref.getTargetId().equals(dpe.getId())) layersNew.add(ref); else { affected = true; } } // Check all the media final List<DpRef<DpMedia<? extends ChartStyle>>> mediaNew = new LinkedList<DpRef<DpMedia<? extends ChartStyle>>>(); for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) { if (!ref.getTargetId().equals(dpe.getId())) mediaNew.add(ref); else { affected = true; } } // Close any open DesignMapViewJDialogs or abort if the user doesn't // want to close. if (affected) { if (!GPDialogManager.dm_MapComposer.close(map)) return null; } // Now we change this map map.setLayers(layersNew); map.setMedia(mediaNew); } Group.findReferencesTo(group, dpe, references, true); final File dir = new File(ace.getDataDir(), dpe.getDataDirname()); try { FileUtils.deleteDirectory(dir); } catch (IOException e) { ExceptionDialog.show(owner, e); } return ace.getDataPool().remove(dpe.getId()); }
public static DpEntry<?> deleteDpEntry(Component owner, AtlasConfigEditable ace, DpEntry<?> dpe, boolean askUserToVerify) { LinkedList<AtlasRefInterface<?>> references = new LinkedList<AtlasRefInterface<?>>(); // **************************************************************************** // Go through all mapPoolEntries and groups and count the references to // this DatapoolEntry // **************************************************************************** Set<Map> mapsWithReferences = new HashSet<Map>(); for (Map map : ace.getMapPool().values()) { for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) { if (ref.getTargetId().equals(dpe.getId())) { references.add(ref); mapsWithReferences.add(map); } } for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) { if (ref.getTargetId().equals(dpe.getId())) { references.add(ref); mapsWithReferences.add(map); } } map.getAdditionalStyles().remove(dpe.getId()); map.getSelectedStyleIDs().remove(dpe.getId()); } int countRefsInMappool = references.size(); // **************************************************************************** // Go through all group tree count the references to this DatapoolEntry // **************************************************************************** Group group = ace.getFirstGroup(); Group.findReferencesTo(group, dpe, references, false); if (askUserToVerify) { // Ask the user if she still wants to delete the DPE, even though // references exist. int res = JOptionPane.showConfirmDialog(owner, GpUtil.R( "DeleteDpEntry.QuestionDeleteDpeAndReferences", dpe .getFilename(), countRefsInMappool, LangUtil .stringConcatWithSep(", ", mapsWithReferences), references.size() - countRefsInMappool, dpe.getTitle() .toString()), GpUtil .R("DataPoolWindow_Action_DeleteDPE_label" + " " + dpe.getTitle()), JOptionPane.YES_NO_OPTION); if (res != JOptionPane.YES_OPTION) return null; } // Close all dialogs that use this layer if (!GPDialogManager.closeAllMapComposerDialogsUsing(dpe)) return null; // **************************************************************************** // Delete the references first. Kill DesignMapViewJDialogs if affected. // Abort everything if the user doesn't want to close the // DesignMapViewJDialog. // **************************************************************************** for (Map map : ace.getMapPool().values()) { boolean affected = false; // Check all the layers final LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>> layersNew = new LinkedList<DpRef<DpLayer<?, ? extends ChartStyle>>>(); for (DpRef<DpLayer<?, ? extends ChartStyle>> ref : map.getLayers()) { if (!ref.getTargetId().equals(dpe.getId())) layersNew.add(ref); else { affected = true; } } // Check all the media final List<DpRef<DpMedia<? extends ChartStyle>>> mediaNew = new LinkedList<DpRef<DpMedia<? extends ChartStyle>>>(); for (DpRef<DpMedia<? extends ChartStyle>> ref : map.getMedia()) { if (!ref.getTargetId().equals(dpe.getId())) mediaNew.add(ref); else { affected = true; } } // Close any open DesignMapViewJDialogs or abort if the user doesn't // want to close. if (affected) { if (!GPDialogManager.dm_MapComposer.close(map)) return null; } // Now we change this map map.setLayers(layersNew); map.setMedia(mediaNew); } Group.findReferencesTo(group, dpe, references, true); final File dir = new File(ace.getDataDir(), dpe.getDataDirname()); try { FileUtils.deleteDirectory(dir); } catch (IOException e) { ExceptionDialog.show(owner, e); } return ace.getDataPool().remove(dpe.getId()); }
diff --git a/listey/src/com/blumenthal/listey/TimeStampedNode.java b/listey/src/com/blumenthal/listey/TimeStampedNode.java index 6e239b0..f16da8d 100644 --- a/listey/src/com/blumenthal/listey/TimeStampedNode.java +++ b/listey/src/com/blumenthal/listey/TimeStampedNode.java @@ -1,320 +1,321 @@ /** * */ package com.blumenthal.listey; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.gson.Gson; /** * This is the base class for the nodes in the Listey data hierarchy. * It allows us to reuse some of the generic methods in the hierarchy. * * @author David * */ public abstract class TimeStampedNode implements Comparable<TimeStampedNode>{ private static final Logger log = Logger.getLogger(TimeStampedNode.class.getName()); public static enum Status { ACTIVE, COMPLETED, DELETED } /** * @return the lastUpdate */ public abstract Long getLastUpdate(); /** * @return the uniqueId */ public abstract String getUniqueId(); /** * @return the status */ public abstract Status getStatus(); /** * @return the entity kind */ public abstract String getKind(); /** * @param parent * @return the entity key for Entity object corresponding to this object */ public Key getEntityKey(Key parent) { return KeyFactory.createKey(parent, getKind(), getUniqueId()); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TimeStampedNode other = (TimeStampedNode) obj; if (getUniqueId() == null) { if (other.getUniqueId() != null) return false; } else if (!getUniqueId().equals(other.getUniqueId())) return false; return true; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getUniqueId() == null) ? 0 : getUniqueId().hashCode()); return result; }//hashCode /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(TimeStampedNode o) { return getUniqueId().compareTo(o.getUniqueId()); } /** Make a copy using json serialization */ public TimeStampedNode makeCopy() { //true value means the json string should include all the fields Gson gson = ListeyDataMultipleUsers.getGson(true); String json = gson.toJson(this); TimeStampedNode copy = gson.fromJson(json, this.getClass()); -getLog().finest(getClass() + "::makeCopy: " + json); return copy; }//makeCopy + public abstract TimeStampedNode makeShallowCopy(); + /** * * @return This returns an array of Maps. Each of the Lists in the array * is a subList of other TimeSTampedNodes that needs to be compared. * If there are no subMaps, returns null. */ public List<Map<String, ? extends TimeStampedNode>> subMapsToCompare() { return null; } /** * * @return This returns an array of Lists. Each of the Lists in the array * is a subList of other TimeSTampedNodes that needs to be compared. * Returns null if the subclass doesn't even implement lists. */ public List<Iterable<? extends TimeStampedNode>> subIterablesToCompare() { return null; } /** * If we realize we actually need to add a new subclass map entry, we'll call this method to add it. * Top layer of multidimensional list is for each subIter type. * Next layer is for each item to be added to that type. * Subclasses that have subMaps need to override this to add the params. This will * always call with the correct number of entries in the top layer in the correct order. * @param subMapEntriesToAdd */ public void addSubMapEntries(List<List<? extends TimeStampedNode>> subMapEntriesToAdd) { //base class does nothing } /** * If we realize we actually need to add a new subclass iterator entry, we'll call this method to add it. * Top layer of multidimensional list is for each subIter type. * Next layer is for each item to be added to that type. * Subclasses that have subIters need to override this to add the params. This will * always call with the correct number of entries in the top layer in the correct order. * @param subIterEntriesToAdd */ public void addSubIterEntries(List<List<? extends TimeStampedNode>> subIterEntriesToAdd) { //base class does nothing } public abstract Entity toEntity(DataStoreUniqueId uniqueIdCreator, Key parent); /** Default implementation just calls toEntity() and returns that * * @param uniqueIdCreator * @param parent * @return */ public List<Entity> toEntities(DataStoreUniqueId uniqueIdCreator, Key parent) { List<Entity> rv = new ArrayList<Entity>(); rv.add(toEntity(uniqueIdCreator, parent)); return rv; }//toEntities public abstract boolean shallowEquals(TimeStampedNode other); public static TimeStampedNode compareAndUpdate(DataStoreUniqueId uniqueIdCreator, Key parent, TimeStampedNode serverObj, TimeStampedNode clientObj, List<Entity> updateEntities, List<Entity> deleteEntities) { TimeStampedNode rv = null; //New from the client if (serverObj == null) { if (clientObj.getStatus().equals(Status.ACTIVE)) { rv = clientObj.makeCopy(); updateEntities.addAll(rv.toEntities(uniqueIdCreator, parent)); }//new list else { //deleted on client, don't add to server, nothing to do } }//serverList == null //New from the server else if (clientObj == null) { rv = serverObj.makeCopy(); //no need to update any entities on the server, just the client }//clientList == null else {//both nodes already exist //use the most recent top-level object, or the client version if they're the same TimeStampedNode newer; if (serverObj.getLastUpdate() > clientObj.getLastUpdate()) { newer = serverObj; - rv = newer.makeCopy(); + rv = newer.makeShallowCopy(); } else { newer = clientObj; - rv = newer.makeCopy(); + rv = newer.makeShallowCopy(); if (!clientObj.shallowEquals(serverObj)) { //If the top-level object changed on the client then push it on the update list Entity thisEntity = rv.toEntity(uniqueIdCreator, parent); if (thisEntity != null) updateEntities.add(thisEntity); } }//client is newer Key thisEntityKey = rv.getEntityKey(parent); //Now compare and update each sub-level object //MAPS #################################################### List<Map<String, ? extends TimeStampedNode>> clientSubMaps = clientObj.subMapsToCompare(); if (clientSubMaps != null) { List<Map<String, ? extends TimeStampedNode>> serverSubMaps = serverObj.subMapsToCompare(); List<List<? extends TimeStampedNode>> subMapAddLists = new ArrayList<List<? extends TimeStampedNode>>(); for (int i=0; i<clientSubMaps.size(); i++) { List<TimeStampedNode> subMapEntriesToAdd = new ArrayList<TimeStampedNode>(); subMapAddLists.add(subMapEntriesToAdd); Map<String, ? extends TimeStampedNode> clientSubMap = clientSubMaps.get(i); Map<String, ? extends TimeStampedNode> serverSubMap = serverSubMaps.get(i); Set<TimeStampedNode> fullSet = new HashSet<TimeStampedNode>(clientSubMap.values()); fullSet.addAll(serverSubMap.values()); for (TimeStampedNode fullSetList : fullSet) { TimeStampedNode clientSubObj = clientSubMap.get(fullSetList.getUniqueId()); TimeStampedNode serverSubObj = serverSubMap.get(fullSetList.getUniqueId()); TimeStampedNode updatedObj = TimeStampedNode.compareAndUpdate(uniqueIdCreator, thisEntityKey, serverSubObj, clientSubObj, updateEntities, deleteEntities); if (updatedObj != null) subMapEntriesToAdd.add(updatedObj); }//for each subObj }//for each submap rv.addSubMapEntries(subMapAddLists); }//if any submaps exist //ITERABLES #################################################### List<Iterable<? extends TimeStampedNode>> clientSubIters = clientObj.subIterablesToCompare(); if (clientSubIters != null) { List<Iterable<? extends TimeStampedNode>> serverSubIters = serverObj.subIterablesToCompare(); List<List<? extends TimeStampedNode>> subIterAddLists = new ArrayList<List<? extends TimeStampedNode>>(); for (int i=0; i<clientSubIters.size(); i++) { List<TimeStampedNode> subIterEntriesToAdd = new ArrayList<TimeStampedNode>(); subIterAddLists.add(subIterEntriesToAdd); Iterator<? extends TimeStampedNode> clientSubIter = clientSubIters.get(i).iterator(); Iterator<? extends TimeStampedNode> serverSubIter = serverSubIters.get(i).iterator(); TimeStampedNode clientSubObj = clientSubIter.hasNext() ? clientSubIter.next() : null; TimeStampedNode serverSubObj = serverSubIter.hasNext() ? serverSubIter.next() : null; while (true) { if (clientSubObj == null && serverSubObj == null) break; TimeStampedNode clientToCompare=clientSubObj, serverToCompare=serverSubObj; //Since the iterables are sorted, we know if the client one is more than the server one //that the server one is missing, and vice versa if (clientSubObj == null || (serverSubObj != null && clientSubObj.compareTo(serverSubObj)>0)) { //add server obj to client clientToCompare=null; //Increment server iterator serverSubObj = serverSubIter.hasNext() ? serverSubIter.next() : null; } else if (serverSubObj == null || (clientSubObj != null && serverSubObj.compareTo(clientSubObj)>0)) { //add client obj to server serverToCompare = null; //Increment client iterator clientSubObj = clientSubIter.hasNext() ? clientSubIter.next() : null; } else { //Increment both iterators serverSubObj = serverSubIter.hasNext() ? serverSubIter.next() : null; clientSubObj = clientSubIter.hasNext() ? clientSubIter.next() : null; } //Same object, so compare and update if needed TimeStampedNode updatedObj = TimeStampedNode.compareAndUpdate(uniqueIdCreator, thisEntityKey, serverToCompare, clientToCompare, updateEntities, deleteEntities); if (updatedObj != null) subIterEntriesToAdd.add(updatedObj); }//for each subObj }//for each subIter rv.addSubIterEntries(subIterAddLists); }//if any subiters exist }//neither list is null return rv; }//compareAndUpdate /** * @return the log */ protected static Logger getLog() { return log; } }//TimeStampedNode
false
false
null
null
diff --git a/src/de/ub0r/android/websms/WebSMS.java b/src/de/ub0r/android/websms/WebSMS.java index af8de30f..3fec5a00 100644 --- a/src/de/ub0r/android/websms/WebSMS.java +++ b/src/de/ub0r/android/websms/WebSMS.java @@ -1,1721 +1,1721 @@ /* * Copyright (C) 2010 Felix Bechstein, Lado Kumsiashvili * * This file is part of WebSMS. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; If not, see <http://www.gnu.org/licenses/>. */ package de.ub0r.android.websms; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.KeyFactory; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.DatePickerDialog.OnDateSetListener; import android.app.TimePickerDialog.OnTimeSetListener; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ResolveInfo; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.telephony.TelephonyManager; import android.telephony.gsm.SmsMessage; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.EditText; import android.widget.GridView; import android.widget.ImageView; import android.widget.MultiAutoCompleteTextView; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import de.ub0r.android.websms.connector.common.Connector; import de.ub0r.android.websms.connector.common.ConnectorCommand; import de.ub0r.android.websms.connector.common.ConnectorSpec; import de.ub0r.android.websms.connector.common.Utils; import de.ub0r.android.websms.connector.common.ConnectorSpec.SubConnectorSpec; /** * Main Activity. * * @author flx */ @SuppressWarnings("deprecation") public class WebSMS extends Activity implements OnClickListener, OnDateSetListener, OnTimeSetListener { /** Tag for output. */ private static final String TAG = "WebSMS"; /** Static reference to running Activity. */ private static WebSMS me; /** Preference's name: last version run. */ private static final String PREFS_LAST_RUN = "lastrun"; /** Preference's name: user's phonenumber. */ static final String PREFS_SENDER = "sender"; /** Preference's name: default prefix. */ static final String PREFS_DEFPREFIX = "defprefix"; /** Preference's name: update balace on start. */ private static final String PREFS_AUTOUPDATE = "autoupdate"; /** Preference's name: exit after sending. */ private static final String PREFS_AUTOEXIT = "autoexit"; /** Preference's name: show mobile numbers only. */ private static final String PREFS_MOBILES_ONLY = "mobiles_only"; /** Preference's name: vibrate on failed sending. */ static final String PREFS_FAIL_VIBRATE = "fail_vibrate"; /** Preference's name: sound on failed sending. */ static final String PREFS_FAIL_SOUND = "fail_sound"; /** Preferemce's name: enable change connector button. */ private static final String PREFS_HIDE_CHANGE_CONNECTOR_BUTTON = // . "hide_change_connector_button"; /** Preferemce's name: hide clear recipients button. */ private static final String PREFS_HIDE_CLEAR_RECIPIENTS_BUTTON = // . "hide_clear_recipients_button"; /** Preference's name: hide send menu item. */ private static final String PREFS_HIDE_SEND_IN_MENU = "hide_send_in_menu"; /** Preferemce's name: hide emoticons button. */ private static final String PREFS_HIDE_EMO_BUTTON = "hide_emo_button"; /** Preferemce's name: hide cancel button. */ private static final String PREFS_HIDE_CANCEL_BUTTON = "hide_cancel_button"; /** Cache {@link ConnectorSpec}s. */ private static final String PREFS_CONNECTORS = "connectors"; /** Preference's name: hide ads. */ private static final String PREFS_HIDEADS = "hideads"; /** Path to file containing signatures of UID Hash. */ private static final String NOADS_SIGNATURES = "/sdcard/websms.noads"; /** Preference's name: to. */ private static final String PREFS_TO = "to"; /** Preference's name: text. */ private static final String PREFS_TEXT = "text"; /** Preference's name: selected {@link ConnectorSpec} ID. */ private static final String PREFS_CONNECTOR_ID = "connector_id"; /** Preference's name: selected {@link SubConnectorSpec} ID. */ private static final String PREFS_SUBCONNECTOR_ID = "subconnector_id"; /** Sleep before autoexit. */ private static final int SLEEP_BEFORE_EXIT = 75; /** Buffersize for saving and loading Connectors. */ private static final int BUFSIZE = 4096; /** Preferences: hide ads. */ private static boolean prefsNoAds = false; /** Show AdView on top. */ private boolean onTop = false; /** Hased IMEI. */ private static String imeiHash = null; /** Preferences: selected {@link ConnectorSpec}. */ private static ConnectorSpec prefsConnectorSpec = null; /** Preferences: selected {@link SubConnectorSpec}. */ private static SubConnectorSpec prefsSubConnectorSpec = null; /** Save prefsConnectorSpec.getPackage() here. */ private static String prefsConnectorID = null; /** List of available {@link ConnectorSpec}s. */ private static final ArrayList<ConnectorSpec> CONNECTORS = // . new ArrayList<ConnectorSpec>(); /** Crypto algorithm for signing UID hashs. */ private static final String ALGO = "RSA"; /** Crypto hash algorithm for signing UID hashs. */ private static final String SIGALGO = "SHA1with" + ALGO; /** My public key for verifying UID hashs. */ private static final String KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNAD" + "CBiQKBgQCgnfT4bRMLOv3rV8tpjcEqsNmC1OJaaEYRaTHOCC" + "F4sCIZ3pEfDcNmrZZQc9Y0im351ekKOzUzlLLoG09bsaOeMd" + "Y89+o2O0mW9NnBch3l8K/uJ3FRn+8Li75SqoTqFj3yCrd9IT" + "sOJC7PxcR5TvNpeXsogcyxxo3fMdJdjkafYwIDAQAB"; /** Array of md5(prefsSender) for which no ads should be displayed. */ private static final String[] NO_AD_HASHS = { "57a3c7c19329fd84c2252a9b2866dd93", // mirweb "10b7a2712beee096acbc67416d7d71a1", // mo "f6b3b72300e918436b4c4c9fdf909e8c", // joerg s. "4c18f7549b643045f0ff69f61e8f7e72", // frank j. "7684154558d19383552388d9bc92d446", // henning k. "64c7414288e9a9b57a33e034f384ed30", // dominik l. "c479a2e701291c751f0f91426bcaabf3", // bernhard g. "ae7dfedf549f98a349ad8c2068473c6b", // dominik k.-v. "18bc29cd511613552861da6ef51766ce", // niels b. "2985011f56d0049b0f4f0caed3581123", // sven l. "64724033da297a915a89023b11ac2e47", // wilfried m. "cfd8d2efb3eac39705bd62c4dfe5e72d", // achim e. "ca56e7518fdbda832409ef07edd4c273", // michael s. "bed2f068ca8493da4179807d1afdbd83", // axel q. "4c35400c4fa3ffe2aefcf1f9131eb855", // gerhard s. "1177c6e67f98cdfed6c84d99e85d30de", // daniel p. "3f082dd7e21d5c64f34a69942c474ce7", // andre j. "5383540b2f8c298532f874126b021e73", // marco a. "6e8bbb35091219a80e278ae61f31cce9", // mario s. "9f01eae4eaecd9158a2caddc04bad77e", // andreas p. "6c9620882d65a1700f223a3f30952c07", // steffen e. }; /** true if preferences got opened. */ static boolean doPreferences = false; /** Dialog: updates. */ private static final int DIALOG_UPDATE = 2; /** Dialog: custom sender. */ private static final int DIALOG_CUSTOMSENDER = 3; /** Dialog: send later: date. */ private static final int DIALOG_SENDLATER_DATE = 4; /** Dialog: send later: time. */ private static final int DIALOG_SENDLATER_TIME = 5; /** Dialog: pre donate. */ private static final int DIALOG_PREDONATE = 6; /** Dialog: post donate. */ private static final int DIALOG_POSTDONATE = 7; /** Dialog: emo. */ private static final int DIALOG_EMO = 8; /** Size of the emoticons png. */ private static final int EMOTICONS_SIZE = 30; /** Intent's extra for error messages. */ static final String EXTRA_ERRORMESSAGE = // . "de.ub0r.android.intent.extra.ERRORMESSAGE"; /** Persistent Message store. */ private static String lastMsg = null; /** Persistent Recipient store. */ private static String lastTo = null; /** Backup for params: custom sender. */ private static String lastCustomSender = null; /** Backup for params: send later. */ private static long lastSendLater = -1; /** {@link MultiAutoCompleteTextView} holding recipients. */ private MultiAutoCompleteTextView etTo; /** {@link EditText} holding text. */ private EditText etText; /** {@link TextView} holding balances. */ private TextView tvBalances; /** {@link View} holding extras. */ private View vExtras; /** {@link View} holding custom sender. */ private View vCustomSender; /** {@link View} holding flashsms. */ private View vFlashSMS; /** {@link View} holding send later. */ private View vSendLater; /** Text's label. */ private TextView etTextLabel; /** Show extras. */ private boolean showExtras = false; /** TextWatcher updating char count on writing. */ private TextWatcher textWatcher = new TextWatcher() { /** * {@inheritDoc} */ public void afterTextChanged(final Editable s) { int[] l = SmsMessage.calculateLength(s, false); WebSMS.this.etTextLabel.setText(l[0] + "/" + l[2]); } /** Needed dummy. */ public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) { } /** Needed dummy. */ public void onTextChanged(final CharSequence s, final int start, final int before, final int count) { } }; /** * Parse data pushed by {@link Intent}. * * @param intent * {@link Intent} */ private void parseIntent(final Intent intent) { final String action = intent.getAction(); if (action == null) { return; } - final Uri uri = intent.getData(); if (uri != null) { // launched by clicking a sms: link, target number is in URI. final String scheme = uri.getScheme(); - if (scheme.equals("sms") || scheme.equals("smsto")) { + if (scheme != null + && (scheme.equals("sms") || scheme.equals("smsto"))) { final String s = uri.getSchemeSpecificPart(); this.parseSchemeSpecificPart(s); + this.displayAds(true); } - this.displayAds(true); } final Bundle extras = intent.getExtras(); if (extras != null) { - String s = extras.getCharSequence(Intent.EXTRA_TEXT).toString(); + CharSequence s = extras.getCharSequence(Intent.EXTRA_TEXT); if (s != null) { ((EditText) this.findViewById(R.id.text)).setText(s); - lastMsg = s; + lastMsg = s.toString(); } s = extras.getString(EXTRA_ERRORMESSAGE); if (s != null) { Toast.makeText(this, s, Toast.LENGTH_LONG).show(); } } } /** * parseSchemeSpecificPart from {@link Uri} and initialize WebSMS * properties. * * @param part * scheme specific part */ private void parseSchemeSpecificPart(final String part) { String s = part; if (s == null) { return; } s = s.trim(); if (s.endsWith(",")) { s = s.substring(0, s.length() - 1).trim(); } if (s.indexOf('<') < 0) { // try to fetch recipient's name from phonebook String n = ContactsWrapper.getInstance().getNameForNumber(this, s); if (n != null) { s = n + " <" + s + ">, "; } } ((EditText) this.findViewById(R.id.to)).setText(s); lastTo = s; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public final void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); // save ref to me. me = this; // Restore preferences final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(this); // inflate XML this.setContentView(R.layout.main); this.etTo = (MultiAutoCompleteTextView) this.findViewById(R.id.to); this.etText = (EditText) this.findViewById(R.id.text); this.etTextLabel = (TextView) this.findViewById(R.id.text_); this.tvBalances = (TextView) this.findViewById(R.id.freecount); this.vExtras = this.findViewById(R.id.extras); this.vCustomSender = this.findViewById(R.id.custom_sender); this.vFlashSMS = this.findViewById(R.id.flashsms); this.vSendLater = this.findViewById(R.id.send_later); // display changelog? String v0 = p.getString(PREFS_LAST_RUN, ""); String v1 = this.getString(R.string.app_version); if (!v0.equals(v1)) { SharedPreferences.Editor editor = p.edit(); editor.putString(PREFS_LAST_RUN, v1); editor.remove(PREFS_CONNECTORS); // remove cache editor.commit(); this.showDialog(DIALOG_UPDATE); } v0 = null; v1 = null; // get cached Connectors String s = p.getString(PREFS_CONNECTORS, ""); if (s.length() == 0) { this.updateConnectors(); } else if (CONNECTORS.size() == 0) { // skip static remaining connectors try { ArrayList<ConnectorSpec> cache; cache = (ArrayList<ConnectorSpec>) (new ObjectInputStream( new BufferedInputStream(new ByteArrayInputStream( Base64Coder.decode(s)), BUFSIZE))).readObject(); CONNECTORS.addAll(cache); if (p.getBoolean(PREFS_AUTOUPDATE, false)) { final String defPrefix = p .getString(PREFS_DEFPREFIX, "+49"); final String defSender = p.getString(PREFS_SENDER, ""); for (ConnectorSpec c : CONNECTORS) { runCommand(me, c, ConnectorCommand.update(defPrefix, defSender)); } } } catch (Exception e) { Log.d(TAG, "error loading connectors", e); } } s = null; Log.d(TAG, "loaded connectors: " + CONNECTORS.size()); this.reloadPrefs(); lastTo = p.getString(PREFS_TO, ""); lastMsg = p.getString(PREFS_TEXT, ""); // register Listener this.findViewById(R.id.send_).setOnClickListener(this); this.findViewById(R.id.cancel).setOnClickListener(this); this.findViewById(R.id.change_connector).setOnClickListener(this); this.findViewById(R.id.change_connector_u).setOnClickListener(this); this.vExtras.setOnClickListener(this); this.vCustomSender.setOnClickListener(this); this.vSendLater.setOnClickListener(this); this.findViewById(R.id.clear).setOnClickListener(this); this.findViewById(R.id.emo).setOnClickListener(this); this.findViewById(R.id.emo_u).setOnClickListener(this); this.tvBalances.setOnClickListener(this); this.etText.addTextChangedListener(this.textWatcher); this.etTo.setAdapter(new MobilePhoneAdapter(this)); this.etTo.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); this.etTo.requestFocus(); this.parseIntent(this.getIntent()); // check default prefix if (!p.getString(PREFS_DEFPREFIX, "").startsWith("+")) { WebSMS.this.log(R.string.log_wrong_defprefix); } } /** * {@inheritDoc} */ @Override protected final void onNewIntent(final Intent intent) { super.onNewIntent(intent); this.parseIntent(intent); } /** * Update {@link ConnectorSpec}s. */ private void updateConnectors() { // query for connectors final Intent i = new Intent(Connector.ACTION_CONNECTOR_UPDATE); Log.d(TAG, "send broadcast: " + i.getAction()); this.sendBroadcast(i); } /** * {@inheritDoc} */ @Override protected final void onResume() { super.onResume(); // set accounts' balance to gui this.updateBalance(); // if coming from prefs.. if (doPreferences) { this.reloadPrefs(); this.updateConnectors(); doPreferences = false; final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(this); final String defPrefix = p.getString(PREFS_DEFPREFIX, "+49"); final String defSender = p.getString(PREFS_SENDER, ""); final ConnectorSpec[] css = getConnectors( ConnectorSpec.CAPABILITIES_BOOTSTRAP, // . (short) (ConnectorSpec.STATUS_ENABLED | // . ConnectorSpec.STATUS_READY)); for (ConnectorSpec cs : css) { runCommand(this, cs, ConnectorCommand.bootstrap(defPrefix, defSender)); } } else { // check is count of connectors changed final List<ResolveInfo> ri = this.getPackageManager() .queryBroadcastReceivers( new Intent(Connector.ACTION_CONNECTOR_UPDATE), 0); final int s1 = ri.size(); final int s2 = CONNECTORS.size(); if (s1 != s2) { Log.d(TAG, "clear connector cache (" + s1 + "/" + s2 + ")"); CONNECTORS.clear(); this.updateConnectors(); } } this.setButtons(); // reload text/recipient from local store if (lastMsg != null) { this.etText.setText(lastMsg); } else { this.etText.setText(""); } if (lastTo != null) { this.etTo.setText(lastTo); } else { this.etTo.setText(""); } if (lastTo != null && lastTo.length() > 0) { this.etText.requestFocus(); } else { this.etTo.requestFocus(); } } /** * Update balance. */ private void updateBalance() { final StringBuilder buf = new StringBuilder(); final ConnectorSpec[] css = getConnectors( ConnectorSpec.CAPABILITIES_UPDATE, // . ConnectorSpec.STATUS_ENABLED); for (ConnectorSpec cs : css) { final String b = cs.getBalance(); if (b == null || b.length() == 0) { continue; } if (buf.length() > 0) { buf.append(", "); } buf.append(cs.getName()); buf.append(": "); buf.append(b); } this.tvBalances.setText(this.getString(R.string.free_) + " " + buf.toString() + " " + this.getString(R.string.click_for_update)); } /** * {@inheritDoc} */ @Override protected final void onPause() { super.onPause(); // store input data to persitent stores lastMsg = this.etText.getText().toString(); lastTo = this.etTo.getText().toString(); // store input data to preferences final Editor editor = PreferenceManager.getDefaultSharedPreferences( this).edit(); // common editor.putString(PREFS_TO, lastTo); editor.putString(PREFS_TEXT, lastMsg); // commit changes editor.commit(); this.savePreferences(); } @Override protected final void onDestroy() { super.onDestroy(); final Editor editor = PreferenceManager.getDefaultSharedPreferences( this).edit(); try { final ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream objOut = new ObjectOutputStream( new BufferedOutputStream(out, BUFSIZE)); objOut.writeObject(CONNECTORS); objOut.close(); final String s = String.valueOf(Base64Coder.encode(out .toByteArray())); Log.d(TAG, s); editor.putString(PREFS_CONNECTORS, s); } catch (IOException e) { editor.remove(PREFS_CONNECTORS); Log.e(TAG, "IO", e); } editor.commit(); } /** * Read static variables holding preferences. */ private void reloadPrefs() { final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(this); final boolean bShowChangeConnector = !p.getBoolean( PREFS_HIDE_CHANGE_CONNECTOR_BUTTON, false); final boolean bShowEmoticons = !p.getBoolean(PREFS_HIDE_EMO_BUTTON, false); final boolean bShowCancel = !p.getBoolean(PREFS_HIDE_CANCEL_BUTTON, false); final boolean bShowClearRecipients = !p.getBoolean( PREFS_HIDE_CLEAR_RECIPIENTS_BUTTON, false); View v = this.findViewById(R.id.clear); if (bShowClearRecipients) { v.setVisibility(View.VISIBLE); } else { v.setVisibility(View.GONE); } if (bShowChangeConnector && bShowEmoticons && bShowCancel) { this.findViewById(R.id.upper).setVisibility(View.VISIBLE); this.findViewById(R.id.change_connector).setVisibility(View.GONE); this.findViewById(R.id.emo).setVisibility(View.GONE); } else { this.findViewById(R.id.upper).setVisibility(View.GONE); v = this.findViewById(R.id.change_connector); if (bShowChangeConnector) { v.setVisibility(View.VISIBLE); } else { v.setVisibility(View.GONE); } v = this.findViewById(R.id.emo); if (bShowEmoticons) { v.setVisibility(View.VISIBLE); } else { v.setVisibility(View.GONE); } v = this.findViewById(R.id.cancel); if (bShowCancel) { v.setVisibility(View.VISIBLE); } else { v.setVisibility(View.GONE); } } prefsConnectorID = p.getString(PREFS_CONNECTOR_ID, ""); prefsConnectorSpec = getConnectorByID(prefsConnectorID); if (prefsConnectorSpec != null && prefsConnectorSpec.hasStatus(ConnectorSpec.STATUS_ENABLED)) { prefsSubConnectorSpec = prefsConnectorSpec.getSubConnector(p .getString(PREFS_SUBCONNECTOR_ID, "")); if (prefsSubConnectorSpec == null) { prefsSubConnectorSpec = prefsConnectorSpec.// . getSubConnectors()[0]; } } else { ConnectorSpec[] connectors = getConnectors( ConnectorSpec.CAPABILITIES_SEND, ConnectorSpec.STATUS_ENABLED); if (connectors.length == 1) { prefsConnectorSpec = connectors[0]; prefsSubConnectorSpec = prefsConnectorSpec // . .getSubConnectors()[0]; Toast.makeText( this, this.getString(R.string.connectors_switch) + " " + prefsConnectorSpec.getName(), Toast.LENGTH_LONG).show(); } else { prefsConnectorSpec = null; prefsSubConnectorSpec = null; } } MobilePhoneAdapter.setMoileNubersObly(p.getBoolean(PREFS_MOBILES_ONLY, false)); prefsNoAds = this.hideAds(); // TODO: remove following lines String hash = Utils.md5(p.getString(PREFS_SENDER, "")); if (!prefsNoAds) { for (String h : NO_AD_HASHS) { if (hash.equals(h)) { prefsNoAds = true; break; } } if (!prefsNoAds && this.getImeiHash() != null) { for (String h : NO_AD_HASHS) { if (imeiHash.equals(h)) { prefsNoAds = true; break; } } } } // this is for transition p.edit().putBoolean(PREFS_HIDEADS, prefsNoAds).commit(); this.displayAds(false); this.setButtons(); } /** * Check for signature updates. * * @return true if ads should be hidden */ private boolean hideAds() { final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(this); final File f = new File(NOADS_SIGNATURES); try { if (f.exists()) { final BufferedReader br = new BufferedReader(new FileReader(f)); final byte[] publicKey = Base64Coder.decode(KEY); final KeyFactory keyFactory = KeyFactory.getInstance(ALGO); PublicKey pk = keyFactory .generatePublic(new X509EncodedKeySpec(publicKey)); final String h = this.getImeiHash(); boolean ret = false; while (true) { String l = br.readLine(); if (l == null) { break; } try { byte[] signature = Base64Coder.decode(l); Signature sig = Signature.getInstance(SIGALGO); sig.initVerify(pk); sig.update(h.getBytes()); ret = sig.verify(signature); if (ret) { break; } } catch (IllegalArgumentException e) { Log.w(TAG, "error reading line", e); } } br.close(); f.delete(); p.edit().putBoolean(PREFS_HIDEADS, ret).commit(); } } catch (Exception e) { Log.e(TAG, "error reading signatures", e); } return p.getBoolean(PREFS_HIDEADS, false); } /** * Show/hide, enable/disable send buttons. */ private void setButtons() { if (prefsConnectorSpec != null && prefsSubConnectorSpec != null && prefsConnectorSpec.hasStatus(ConnectorSpec.STATUS_ENABLED)) { final boolean sFlashsms = prefsSubConnectorSpec .hasFeatures(SubConnectorSpec.FEATURE_FLASHSMS); final boolean sCustomsender = prefsSubConnectorSpec .hasFeatures(SubConnectorSpec.FEATURE_CUSTOMSENDER); final boolean sSendLater = prefsSubConnectorSpec .hasFeatures(SubConnectorSpec.FEATURE_SENDLATER); if (sFlashsms || sCustomsender || sSendLater) { this.vExtras.setVisibility(View.VISIBLE); } else { this.vExtras.setVisibility(View.GONE); } if (this.showExtras && sFlashsms) { this.vFlashSMS.setVisibility(View.VISIBLE); } else { this.vFlashSMS.setVisibility(View.GONE); } if (this.showExtras && sCustomsender) { this.vCustomSender.setVisibility(View.VISIBLE); } else { this.vCustomSender.setVisibility(View.GONE); } if (this.showExtras && sSendLater) { this.vSendLater.setVisibility(View.VISIBLE); } else { this.vSendLater.setVisibility(View.GONE); } String t = this.getString(R.string.app_name) + " - " + prefsConnectorSpec.getName(); if (prefsConnectorSpec.getSubConnectorCount() > 1) { t += " - " + prefsSubConnectorSpec.getName(); } this.setTitle(t); ((TextView) this.findViewById(R.id.text_connector)) .setText(prefsConnectorSpec.getName()); ((Button) this.findViewById(R.id.send_)).setEnabled(true); } else { this.setTitle(R.string.app_name); ((TextView) this.findViewById(R.id.text_connector)).setText(""); ((Button) this.findViewById(R.id.send_)).setEnabled(false); if (getConnectors(0, 0).length != 0) { Toast.makeText(this, R.string.log_noselectedconnector, Toast.LENGTH_SHORT).show(); } } } /** * Resets persistent store. */ private void reset() { this.etText.setText(""); this.etTo.setText(""); lastMsg = null; lastTo = null; lastCustomSender = null; lastSendLater = -1; // save user preferences SharedPreferences.Editor editor = PreferenceManager .getDefaultSharedPreferences(this).edit(); editor.putString(PREFS_TO, ""); editor.putString(PREFS_TEXT, ""); // commit changes editor.commit(); } /** Save prefs. */ final void savePreferences() { if (prefsConnectorSpec != null) { PreferenceManager.getDefaultSharedPreferences(this).edit() .putString(PREFS_CONNECTOR_ID, prefsConnectorSpec.getPackage()).commit(); } } /** * Run Connector.doUpdate(). */ private void updateFreecount() { final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(this); final String defPrefix = p.getString(PREFS_DEFPREFIX, "+49"); final String defSender = p.getString(PREFS_SENDER, ""); final ConnectorSpec[] css = getConnectors( ConnectorSpec.CAPABILITIES_UPDATE, // . (short) (ConnectorSpec.STATUS_ENABLED | // . ConnectorSpec.STATUS_READY)); for (ConnectorSpec cs : css) { if (cs.isRunning()) { // skip running connectors Log.d(TAG, "skip running connector: " + cs.getName()); continue; } runCommand(this, cs, ConnectorCommand.update(defPrefix, defSender)); } } /** * Send a command as broadcast. * * @param context * WebSMS required for performance issues * @param connector * {@link ConnectorSpec} * @param command * {@link ConnectorCommand} */ static final void runCommand(final WebSMS context, final ConnectorSpec connector, final ConnectorCommand command) { connector.setErrorMessage((String) null); final Intent intent = command.setToIntent(null); short t = command.getType(); switch (t) { case ConnectorCommand.TYPE_BOOTSTRAP: intent.setAction(connector.getPackage() + Connector.ACTION_RUN_BOOTSTRAP); connector.addStatus(ConnectorSpec.STATUS_BOOTSTRAPPING); break; case ConnectorCommand.TYPE_SEND: intent.setAction(connector.getPackage() // . + Connector.ACTION_RUN_SEND); connector.setToIntent(intent); connector.addStatus(ConnectorSpec.STATUS_SENDING); break; case ConnectorCommand.TYPE_UPDATE: intent.setAction(connector.getPackage() + Connector.ACTION_RUN_UPDATE); connector.addStatus(ConnectorSpec.STATUS_UPDATING); break; default: break; } if (me != null && (t == ConnectorCommand.TYPE_BOOTSTRAP || // . t == ConnectorCommand.TYPE_UPDATE)) { me.setProgressBarIndeterminateVisibility(true); } Log.d(TAG, "send broadcast: " + intent.getAction()); context.sendBroadcast(intent); } /** * {@inheritDoc} */ public final void onClick(final View v) { switch (v.getId()) { case R.id.freecount: this.updateFreecount(); return; case R.id.send_: this.send(prefsConnectorSpec, WebSMS.getSelectedSubConnectorID()); return; case R.id.cancel: this.reset(); return; case R.id.clear: this.etTo.setText(""); lastTo = null; return; case R.id.change_connector: case R.id.change_connector_u: this.changeConnectorMenu(); return; case R.id.extras: this.showExtras = !this.showExtras; this.setButtons(); return; case R.id.custom_sender: final CheckBox cs = (CheckBox) this.vCustomSender; if (cs.isChecked()) { this.showDialog(DIALOG_CUSTOMSENDER); } else { lastCustomSender = null; } return; case R.id.send_later: final CheckBox sl = (CheckBox) this.vSendLater; if (sl.isChecked()) { this.showDialog(DIALOG_SENDLATER_DATE); } else { lastSendLater = -1; } return; case R.id.emo: case R.id.emo_u: this.showDialog(DIALOG_EMO); return; default: return; } } /** * {@inheritDoc} */ @Override public final boolean onCreateOptionsMenu(final Menu menu) { MenuInflater inflater = this.getMenuInflater(); inflater.inflate(R.menu.menu, menu); if (prefsNoAds) { menu.removeItem(R.id.item_donate); } final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(this); final boolean bShowSendButton = !p.getBoolean(PREFS_HIDE_SEND_IN_MENU, false); if (!bShowSendButton) { menu.removeItem(R.id.item_send); } return true; } /** * Display "change connector" menu. */ private void changeConnectorMenu() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_menu_share); builder.setTitle(R.string.change_connector_); final ArrayList<String> items = new ArrayList<String>(); final ConnectorSpec[] css = getConnectors( ConnectorSpec.CAPABILITIES_SEND, ConnectorSpec.STATUS_ENABLED); SubConnectorSpec[] scs; String n; for (ConnectorSpec cs : css) { scs = cs.getSubConnectors(); if (scs.length <= 1) { items.add(cs.getName()); } else { n = cs.getName() + " - "; for (SubConnectorSpec sc : scs) { items.add(n + sc.getName()); } } } scs = null; n = null; if (items.size() == 0) { Toast.makeText(this, R.string.log_noreadyconnector, Toast.LENGTH_LONG).show(); } builder.setItems(items.toArray(new String[0]), new DialogInterface.OnClickListener() { public void onClick(final DialogInterface d, // . final int item) { final SubConnectorSpec[] ret = ConnectorSpec .getSubConnectorReturnArray(); prefsConnectorSpec = getConnectorByName( items.get(item), ret); prefsSubConnectorSpec = ret[0]; WebSMS.this.setButtons(); // save user preferences final Editor e = PreferenceManager .getDefaultSharedPreferences(WebSMS.this) .edit(); e.putString(PREFS_CONNECTOR_ID, prefsConnectorSpec .getPackage()); e.putString(PREFS_SUBCONNECTOR_ID, prefsSubConnectorSpec.getID()); e.commit(); } }); builder.create().show(); } /** *{@inheritDoc} */ @Override public final boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.item_send: // send by menu item this.send(prefsConnectorSpec, WebSMS.getSelectedSubConnectorID()); return true; case R.id.item_settings: // start settings activity this.startActivity(new Intent(this, Preferences.class)); return true; case R.id.item_donate: this.showDialog(DIALOG_PREDONATE); return true; case R.id.item_connector: this.changeConnectorMenu(); return true; default: return false; } } /** * Create a Emoticons {@link Dialog}. * * @return Emoticons {@link Dialog} */ private Dialog createEmoticonsDialog() { final Dialog d = new Dialog(this); d.setTitle(R.string.emo_); d.setContentView(R.layout.emo); d.setCancelable(true); final GridView gridview = (GridView) d.findViewById(R.id.gridview); gridview.setAdapter(new BaseAdapter() { // references to our images private Integer[] mThumbIds = { R.drawable.emo_im_angel, R.drawable.emo_im_cool, R.drawable.emo_im_crying, R.drawable.emo_im_foot_in_mouth, R.drawable.emo_im_happy, R.drawable.emo_im_kissing, R.drawable.emo_im_laughing, R.drawable.emo_im_lips_are_sealed, R.drawable.emo_im_money_mouth, R.drawable.emo_im_sad, R.drawable.emo_im_surprised, R.drawable.emo_im_tongue_sticking_out, R.drawable.emo_im_undecided, R.drawable.emo_im_winking, R.drawable.emo_im_wtf, R.drawable.emo_im_yelling }; @Override public long getItemId(final int position) { return 0; } @Override public Object getItem(final int position) { return null; } @Override public int getCount() { return this.mThumbIds.length; } @Override public View getView(final int position, final View convertView, final ViewGroup parent) { ImageView imageView; if (convertView == null) { // if it's not recycled, // initialize some attributes imageView = new ImageView(WebSMS.this); imageView.setLayoutParams(new GridView.LayoutParams( EMOTICONS_SIZE, EMOTICONS_SIZE)); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); // imageView.setPadding(0, 0, 0, 0); } else { imageView = (ImageView) convertView; } imageView.setImageResource(this.mThumbIds[position]); return imageView; } }); gridview.setOnItemClickListener(new OnItemClickListener() { /** Emoticon id: angel. */ private static final int EMO_ANGEL = 0; /** Emoticon id: cool. */ private static final int EMO_COOL = 1; /** Emoticon id: crying. */ private static final int EMO_CRYING = 2; /** Emoticon id: foot in mouth. */ private static final int EMO_FOOT_IN_MOUTH = 3; /** Emoticon id: happy. */ private static final int EMO_HAPPY = 4; /** Emoticon id: kissing. */ private static final int EMO_KISSING = 5; /** Emoticon id: laughing. */ private static final int EMO_LAUGHING = 6; /** Emoticon id: lips are sealed. */ private static final int EMO_LIPS_SEALED = 7; /** Emoticon id: money. */ private static final int EMO_MONEY = 8; /** Emoticon id: sad. */ private static final int EMO_SAD = 9; /** Emoticon id: suprised. */ private static final int EMO_SUPRISED = 10; /** Emoticon id: tongue sticking out. */ private static final int EMO_TONGUE = 11; /** Emoticon id: undecided. */ private static final int EMO_UNDICIDED = 12; /** Emoticon id: winking. */ private static final int EMO_WINKING = 13; /** Emoticon id: wtf. */ private static final int EMO_WTF = 14; /** Emoticon id: yell. */ private static final int EMO_YELL = 15; @Override public void onItemClick(final AdapterView<?> adapter, final View v, final int id, final long arg3) { EditText et = WebSMS.this.etText; String e = null; switch (id) { case EMO_ANGEL: e = "O:-)"; break; case EMO_COOL: e = "8-)"; break; case EMO_CRYING: e = ";-)"; break; case EMO_FOOT_IN_MOUTH: e = ":-?"; break; case EMO_HAPPY: e = ":-)"; break; case EMO_KISSING: e = ":-*"; break; case EMO_LAUGHING: e = ":-D"; break; case EMO_LIPS_SEALED: e = ":-X"; break; case EMO_MONEY: e = ":-$"; break; case EMO_SAD: e = ":-("; break; case EMO_SUPRISED: e = ":o"; break; case EMO_TONGUE: e = ":-P"; break; case EMO_UNDICIDED: e = ":-\\"; break; case EMO_WINKING: e = ";-)"; break; case EMO_WTF: e = "o.O"; break; case EMO_YELL: e = ":O"; break; default: break; } et.setText(et.getText() + e); d.dismiss(); } }); return d; } /** * {@inheritDoc} */ @Override protected final Dialog onCreateDialog(final int id) { Dialog d; AlertDialog.Builder builder; switch (id) { case DIALOG_PREDONATE: builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_menu_star); builder.setTitle(R.string.donate_); builder.setMessage(R.string.predonate); builder.setPositiveButton(R.string.donate_, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int which) { try { WebSMS.this.startActivity(new Intent( Intent.ACTION_VIEW, Uri.parse(// . WebSMS.this.getString(// . R.string.donate_url)))); } catch (ActivityNotFoundException e) { Log.e(TAG, "no browser", e); } finally { WebSMS.this.showDialog(DIALOG_POSTDONATE); } } }); builder.setNegativeButton(android.R.string.cancel, null); return builder.create(); case DIALOG_POSTDONATE: builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.ic_menu_star); builder.setTitle(R.string.remove_ads_); builder.setMessage(R.string.postdonate); builder.setPositiveButton(R.string.send_, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int which) { final Intent in = new Intent(Intent.ACTION_SEND); in.putExtra(Intent.EXTRA_EMAIL, new String[] { WebSMS.this.getString(// . R.string.donate_mail), "" }); // FIXME: "" is a k9 hack. This is fixed in market // on 26.01.10. wait some more time.. in.putExtra(Intent.EXTRA_TEXT, WebSMS.this .getImeiHash()); in.putExtra(Intent.EXTRA_SUBJECT, WebSMS.this .getString(// . R.string.app_name) + " " + WebSMS.this.getString(// . R.string.donate_subject)); in.setType("text/plain"); WebSMS.this.startActivity(in); } }); builder.setNegativeButton(android.R.string.cancel, null); return builder.create(); case DIALOG_UPDATE: builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(R.string.changelog_); final String[] changes = this.getResources().getStringArray( R.array.updates); final StringBuilder buf = new StringBuilder(); Object o = this.getPackageManager().getLaunchIntentForPackage( "de.ub0r.android.smsdroid"); if (o == null) { buf.append(changes[0]); } for (int i = 1; i < changes.length; i++) { buf.append("\n\n"); buf.append(changes[i]); } builder.setIcon(android.R.drawable.ic_menu_info_details); builder.setMessage(buf.toString().trim()); builder.setCancelable(true); builder.setPositiveButton(android.R.string.ok, null); if (o == null) { builder.setNeutralButton("get SMSdroid", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface d, final int which) { try { WebSMS.this.startActivity(// . new Intent( Intent.ACTION_VIEW, Uri.parse(// . "market://search?q=pname:de.ub0r.android.smsdroid"))); } catch (ActivityNotFoundException e) { Log.e(TAG, "no market", e); } } }); } return builder.create(); case DIALOG_CUSTOMSENDER: builder = new AlertDialog.Builder(this); builder.setTitle(R.string.custom_sender); builder.setCancelable(true); final EditText et = new EditText(this); builder.setView(et); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int id) { WebSMS.lastCustomSender = et.getText().toString(); } }); builder.setNegativeButton(android.R.string.cancel, null); return builder.create(); case DIALOG_SENDLATER_DATE: Calendar c = Calendar.getInstance(); return new DatePickerDialog(this, this, c.get(Calendar.YEAR), c .get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)); case DIALOG_SENDLATER_TIME: c = Calendar.getInstance(); return new MyTimePickerDialog(this, this, c .get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true); case DIALOG_EMO: return this.createEmoticonsDialog(); default: return null; } } /** * Log text. * * @param text * text as resID */ public final void log(final int text) { this.log(this.getString(text)); } /** * Log text. * * @param text * text */ public final void log(final String text) { try { Toast.makeText(this.getApplicationContext(), text, Toast.LENGTH_LONG).show(); } catch (RuntimeException e) { Log.e(TAG, null, e); } } /** * Show AdView on top or on bottom. * * @param top * display ads on top. */ private void displayAds(final boolean top) { if (prefsNoAds) { // do not display any ads for donators return; } if (top) { // switch to AdView on top this.onTop = true; } if (this.onTop) { Log.d(TAG, "display ads on top"); this.findViewById(R.id.ad).setVisibility(View.VISIBLE); this.findViewById(R.id.ad_bottom).setVisibility(View.GONE); } else { Log.d(TAG, "display ads on bottom"); this.findViewById(R.id.ad).setVisibility(View.GONE); this.findViewById(R.id.ad_bottom).setVisibility(View.VISIBLE); } } /** * Send text. * * @param connector * which connector should be used. * @param subconnector * selected {@link SubConnectorSpec} ID */ private void send(final ConnectorSpec connector, // . final String subconnector) { // fetch text/recipient final String to = this.etTo.getText().toString(); final String text = this.etText.getText().toString(); if (to.length() == 0 || text.length() == 0) { return; } this.displayAds(true); CheckBox v = (CheckBox) this.findViewById(R.id.flashsms); final boolean flashSMS = (v.getVisibility() == View.VISIBLE) && v.isEnabled() && v.isChecked(); final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(this); final String defPrefix = p.getString(PREFS_DEFPREFIX, "+49"); final String defSender = p.getString(PREFS_SENDER, ""); final String[] tos = Utils.parseRecipients(to); final ConnectorCommand command = ConnectorCommand.send(subconnector, defPrefix, defSender, tos, text, flashSMS); command.setCustomSender(lastCustomSender); command.setSendLater(lastSendLater); try { if (connector.getSubConnector(subconnector).hasFeatures( SubConnectorSpec.FEATURE_MULTIRECIPIENTS) || tos.length == 1) { runCommand(this, connector, command); } else { ConnectorCommand cc; for (String t : tos) { if (t.trim().length() < 1) { continue; } cc = (ConnectorCommand) command.clone(); cc.setRecipients(t); runCommand(this, connector, cc); } } } catch (Exception e) { Log.e(TAG, null, e); } finally { this.reset(); if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean( PREFS_AUTOEXIT, false)) { try { Thread.sleep(SLEEP_BEFORE_EXIT); } catch (InterruptedException e) { Log.e(TAG, null, e); } this.finish(); } } } /** * @return ID of selected {@link SubConnectorSpec} */ private static String getSelectedSubConnectorID() { if (prefsSubConnectorSpec == null) { return null; } return prefsSubConnectorSpec.getID(); } /** * A Date was set. * * @param view * DatePicker View * @param year * year set * @param monthOfYear * month set * @param dayOfMonth * day set */ public final void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) { final Calendar c = Calendar.getInstance(); if (lastSendLater > 0) { c.setTimeInMillis(lastSendLater); } c.set(Calendar.YEAR, year); c.set(Calendar.MONTH, monthOfYear); c.set(Calendar.DAY_OF_MONTH, dayOfMonth); lastSendLater = c.getTimeInMillis(); MyTimePickerDialog.setOnlyQuaters(prefsSubConnectorSpec .hasFeatures(SubConnectorSpec.FEATURE_SENDLATER_QUARTERS)); this.showDialog(DIALOG_SENDLATER_TIME); } /** * A Time was set. * * @param view * TimePicker View * @param hour * hour set * @param minutes * minutes set */ public final void onTimeSet(final TimePicker view, final int hour, final int minutes) { if (prefsSubConnectorSpec .hasFeatures(SubConnectorSpec.FEATURE_SENDLATER_QUARTERS) && minutes % 15 != 0) { Toast.makeText(this, R.string.error_sendlater_quater, Toast.LENGTH_LONG).show(); return; } final Calendar c = Calendar.getInstance(); if (lastSendLater > 0) { c.setTimeInMillis(lastSendLater); } c.set(Calendar.HOUR_OF_DAY, hour); c.set(Calendar.MINUTE, minutes); lastSendLater = c.getTimeInMillis(); } /** * Get MD5 hash of the IMEI (device id). * * @return MD5 hash of IMEI */ private String getImeiHash() { if (imeiHash == null) { // get imei TelephonyManager mTelephonyMgr = (TelephonyManager) this .getSystemService(TELEPHONY_SERVICE); final String did = mTelephonyMgr.getDeviceId(); if (did != null) { imeiHash = Utils.md5(did); } } return imeiHash; } /** * Add or update a {@link ConnectorSpec}. * * @param connector * connector */ static final void addConnector(final ConnectorSpec connector) { synchronized (CONNECTORS) { if (connector == null || connector.getPackage() == null || connector.getName() == null) { return; } ConnectorSpec c = getConnectorByID(connector.getPackage()); if (c != null) { c.setErrorMessage((String) null); // fix sticky error status c.update(connector); } else { final String name = connector.getName(); if (connector.getSubConnectorCount() == 0 || name == null || connector.getPackage() == null) { Log.w(TAG, "skipped adding defect connector: " + name); return; } Log.d(TAG, "add connector with id: " + connector.getPackage()); Log.d(TAG, "add connector with name: " + name); boolean added = false; final int l = CONNECTORS.size(); ConnectorSpec cs; try { for (int i = 0; i < l; i++) { cs = CONNECTORS.get(i); if (name.compareToIgnoreCase(cs.getName()) < 0) { CONNECTORS.add(i, connector); added = true; break; } } } catch (NullPointerException e) { Log.e(TAG, "error while sorting", e); } if (!added) { CONNECTORS.add(connector); } c = connector; if (me != null) { final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(me); // update connectors balance if needed if (c.getBalance() == null && c.isReady() && !c.isRunning() && c.hasCapabilities(// . ConnectorSpec.CAPABILITIES_UPDATE) && p.getBoolean(PREFS_AUTOUPDATE, false)) { final String defPrefix = p.getString(PREFS_DEFPREFIX, "+49"); final String defSender = p.getString(PREFS_SENDER, ""); runCommand(me, c, ConnectorCommand.update(defPrefix, defSender)); } } } if (me != null) { final SharedPreferences p = PreferenceManager .getDefaultSharedPreferences(me); if (prefsConnectorSpec == null && prefsConnectorID.equals(connector.getPackage())) { prefsConnectorSpec = connector; prefsSubConnectorSpec = connector.getSubConnector(p .getString(PREFS_SUBCONNECTOR_ID, "")); me.setButtons(); } final String b = c.getBalance(); final String ob = c.getOldBalance(); if (b != null && (ob == null || !b.equals(ob))) { me.updateBalance(); } boolean runningConnectors = getConnectors( ConnectorSpec.CAPABILITIES_UPDATE, ConnectorSpec.STATUS_ENABLED | ConnectorSpec.STATUS_UPDATING).length != 0; if (!runningConnectors) { runningConnectors = getConnectors( ConnectorSpec.CAPABILITIES_BOOTSTRAP, ConnectorSpec.STATUS_ENABLED | ConnectorSpec.STATUS_BOOTSTRAPPING// . ).length != 0; } me.setProgressBarIndeterminateVisibility(runningConnectors); if (prefsConnectorSpec != null && prefsConnectorSpec.equals(c)) { me.setButtons(); } } } } /** * Get {@link ConnectorSpec} by ID. * * @param id * ID * @return {@link ConnectorSpec} */ private static ConnectorSpec getConnectorByID(final String id) { synchronized (CONNECTORS) { if (id == null) { return null; } final int l = CONNECTORS.size(); ConnectorSpec c; for (int i = 0; i < l; i++) { c = CONNECTORS.get(i); if (id.equals(c.getPackage())) { return c; } } } return null; } /** * Get {@link ConnectorSpec} by name. * * @param name * name * @param returnSelectedSubConnector * if not null, array[0] will be set to selected * {@link SubConnectorSpec} * @return {@link ConnectorSpec} */ private static ConnectorSpec getConnectorByName(final String name, final SubConnectorSpec[] returnSelectedSubConnector) { synchronized (CONNECTORS) { if (name == null) { return null; } final int l = CONNECTORS.size(); ConnectorSpec c; String n; SubConnectorSpec[] scs; for (int i = 0; i < l; i++) { c = CONNECTORS.get(i); n = c.getName(); if (name.startsWith(n)) { if (name.length() == n.length()) { if (returnSelectedSubConnector != null) { returnSelectedSubConnector[0] = c .getSubConnectors()[0]; } return c; } else if (returnSelectedSubConnector != null) { scs = c.getSubConnectors(); if (scs == null || scs.length == 0) { continue; } for (SubConnectorSpec sc : scs) { if (name.endsWith(sc.getName())) { returnSelectedSubConnector[0] = sc; return c; } } } } } } return null; } /** * Get {@link ConnectorSpec}s by capabilities and/or status. * * @param capabilities * capabilities needed * @param status * status required {@link SubConnectorSpec} * @return {@link ConnectorSpec}s */ static final ConnectorSpec[] getConnectors(final int capabilities, final int status) { synchronized (CONNECTORS) { final ArrayList<ConnectorSpec> ret = new ArrayList<ConnectorSpec>( CONNECTORS.size()); final int l = CONNECTORS.size(); ConnectorSpec c; for (int i = 0; i < l; i++) { c = CONNECTORS.get(i); if (c.hasCapabilities((short) capabilities) && c.hasStatus((short) status)) { ret.add(c); } } return ret.toArray(new ConnectorSpec[0]); } } }
false
false
null
null
diff --git a/src/MainCLI.java b/src/MainCLI.java index 4d164ed..2609268 100644 --- a/src/MainCLI.java +++ b/src/MainCLI.java @@ -1,116 +1,111 @@ /** * Created with IntelliJ IDEA. * User: JKillNazi * Date: 12/3/12 * Time: 6:36 PM */ import jargs.gnu.CmdLineParser; public class MainCLI extends CmdLineParser { private static class Parser extends CmdLineParser { /** * Initialize all the possible arguments(short and long way) * -g | --gui = asks JSecure to show its nice GUI (DEFAULT: <???>) * -v | --verbose = tells JSecure to speak loud (DEFAULT: <???>) * -n | --numeric = allows JSecure to use numbers while generating the password (DEFAULT: <???>) * -a | --alpha = allows JSecure to use letters while generating the password (DEFAULT: <???>) * -p | --punct = allows JSecure to use punctuation characters while generating the password (DEFAULT: <???>) * -l | --length = tells JSecure the wished length for the password (DEFAULT: <???>) * -h | --help = asks for JSecure to show you this help menu */ CmdLineParser.Option optGUI; CmdLineParser.Option optVvv; CmdLineParser.Option optLen; CmdLineParser.Option optAlpha; CmdLineParser.Option optNum; CmdLineParser.Option optPunct; CmdLineParser.Option optHelp; //TODO: DICTIONARY and SCRUBBLED OPTIONS public Parser() { optGUI = this.addBooleanOption('g',"gui"); optVvv = this.addBooleanOption('v',"verbose"); optAlpha = this.addBooleanOption('a',"alpha"); optNum = this.addBooleanOption('n',"numeric"); optPunct = this.addBooleanOption('p',"punct"); optHelp = this.addBooleanOption('h',"help"); optLen = this.addIntegerOption('l',"length"); } } public static void main(String[] args) { /** * Main method,here everything will take place(parsing of the options,generation of the secure password,etc...) */ //TODO: fix the "NO ARGS==ULLPOINT EXCEPTION" int EXIT_STATUS=0; /**EXIT STATUES: * 0 = no errors * 1 = wrong or illegal option * 2 = unknown option * 3 = unknown error * */ Parser parser = new Parser(); //The Parser class will take care of all the options SecurePassword pass = new SecurePassword(); try { //Try to parse the args parser.parse(args); if (((Boolean) parser.getOptionValue(parser.optHelp))) { //IF the -h | --help option has been used IGNORE the others and show the message,then quit System.out.println("JSecure is a OPEN SOURCE software written in java that helps you generating strong passwords based on your needs.\n= AVAIABLE OPTIONS =\n" + " -"+parser.optGUI.shortForm() +" | --"+parser.optGUI.longForm() +" = asks JSecure to show its nice GUI (DEFAULT <???>).\n" + " -"+parser.optVvv.shortForm() +" | --"+parser.optVvv.longForm() +" = tells JSecure to speak loud (DEFAULT <???>).\n" + " -"+parser.optNum.shortForm() +" | --"+parser.optNum.longForm() +" = allows JSecure to use numbers while generating the password (DEFAULT <???>).\n" + " -"+parser.optAlpha.shortForm()+" | --"+parser.optAlpha.longForm() +" = allows JSecure to use letters while generating the password (DEFAULT <???>).\n" + " -"+parser.optPunct.shortForm() +" | --"+parser.optPunct.longForm()+" = allows JSecure to use punctuation characters while generating the password (DEFAULT <???>).\n" + " -"+parser.optLen.shortForm()+" | --"+parser.optLen.longForm()+" <value>"+" = tells JSecure the wished length for the password (DEFAULT: <???>).\n" + " -"+parser.optHelp.shortForm()+" | --"+parser.optHelp.longForm() +" = asks JSecure to show you this help menu.\n" + " -? | --credits " +" = asks to JSecure to show the credits/about informations.\n" + //TODO:credits/about option "\nUSAGE: java Main <options> \n" + " java -jar JSecure.jar <options>"); } else { //ELSE get the values from the other options /* *========================NOTE======================== *If an option has not been used it returns NULL. So let's say i run: * "java -jar JSecure.jar -a -l 10 -p" *-n will be null,so: * "pass.setNumeric((Boolean) parser.getOptionValue(parser.optNum));" *will set the isNumeric to NULL! *Be sure to check if we pass NULL to a Setter to make it "ignore" and leave the default option! **/ /**SET THE NEEDED PARAMETERS TO GENERATE THE PASSWORD*/ pass.setAlpha((Boolean) parser.getOptionValue(parser.optAlpha)); //Set isAlpha pass.setNumeric((Boolean) parser.getOptionValue(parser.optNum)); //Set isNumeric pass.setPunctuation((Boolean) parser.getOptionValue(parser.optPunct)); //Set isPunc pass.setLength((Integer) parser.getOptionValue(parser.optLen)); //Set passLength } } catch (IllegalOptionValueException e) { //e.printStackTrace(); - System.out.println("USAGE: java Main -h \n " + - "java -jar JSecure.jar -h"); EXIT_STATUS=1; } catch (UnknownOptionException e) { //e.printStackTrace(); - System.out.println("USAGE: java Main -h \n " + - "java -jar JSecure.jar -h"); EXIT_STATUS=2; } catch (NullPointerException e) { //e.printStackTrace(); - System.out.println("USAGE: java Main -h \n " + - "java -jar JSecure.jar -h"); EXIT_STATUS=1; } - + if(EXIT_STATUS != 0) System.out.println("USAGE: java Main -h \n " + + "java -jar JSecure.jar -h"); System.exit(EXIT_STATUS); } }
false
false
null
null
diff --git a/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java b/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java index 0f55423..d49efdc 100644 --- a/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java +++ b/TekkitRestrict/src/com/github/dreadslicer/tekkitrestrict/TRNoDupe.java @@ -1,138 +1,138 @@ package com.github.dreadslicer.tekkitrestrict; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; public class TRNoDupe { @SuppressWarnings("unused") private static boolean preventAlcDupe, preventRMDupe, preventTransmuteDupe; public static int dupeAttempts = 0; public static String lastPlayer = ""; public static void reload() { preventAlcDupe = tekkitrestrict.config.getBoolean("PreventAlcDupe"); preventRMDupe = tekkitrestrict.config .getBoolean("PreventRMFurnaceDupe"); preventTransmuteDupe = tekkitrestrict.config .getBoolean("PreventTransmuteDupe"); } public static void handleDupes(InventoryClickEvent event) { // event.getInventory(); Player player = tekkitrestrict.getInstance().getServer() .getPlayer(event.getWhoClicked().getName()); int slot = event.getSlot(); String title = event.getView().getTopInventory().getTitle() .toLowerCase(); - tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick()); + //tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick()); // RMDupe Slot35 if (!TRPermHandler.hasPermission(player, "dupe", "bypass", "")) { // tekkitrestrict.log.info("t0-"+title+"-"); if (title.equals("rm furnace")) { // tekkitrestrict.log.info("t1"); if (slot == 35) { // tekkitrestrict.log.info("t2"); if (event.isShiftClick()) { // tekkitrestrict.log.info("t3"); if (preventRMDupe) { event.setCancelled(true); player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a RM Furnace!"); TRLogger.Log("Dupe", player.getName() + " attempted to dupe using a RM Furnace!"); } else { TRLogger.Log("Dupe", player.getName() + " duped using a RM Furnace!"); } dupeAttempts++; TRLogger.broadcastDupe(player.getName(), "the RM Furnace", "RMFurnace"); } } } else if (title.equals("tank cart")) { // tekkitrestrict.log.info("t1"); if (slot == 35) { // tekkitrestrict.log.info("t2"); if (event.isShiftClick()) { event.setCancelled(true); player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a Tank Cart!"); TRLogger.Log("Dupe", player.getName() + " attempted to dupe using a Tank Cart!"); dupeAttempts++; TRLogger.broadcastDupe(player.getName(), "the Tank Cart", "TankCart"); } } } else if (title.equals("trans tablet")) { // slots-6 7 5 3 1 0 2 int item = event.getCurrentItem().getTypeId(); if (item == 27557) { } if (item == 27558) { } if (item == 27559) { } if (item == 27560) { } if (item == 27561) { } if (item == 27591) { } if (event.isShiftClick()) { // if (isKlein) { boolean isslot = slot == 0 || slot == 1 || slot == 2 || slot == 3 || slot == 4 || slot == 5 || slot == 6 || slot == 7; if (isslot) { if (preventTransmuteDupe) { event.setCancelled(true); player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click any "); player.sendRawMessage(" item out of the transmutation table!"); TRLogger.Log("Dupe", player.getName() + " attempted to transmute dupe!"); } else { TRLogger.Log("Dupe", player.getName() + " attempted to transmute dupe!"); } dupeAttempts++; TRLogger.broadcastDupe(player.getName(), "the Transmutation Table", "transmute"); } // } } } } } public static void handleDropDupes( org.bukkit.event.player.PlayerDropItemEvent e) { Player player = e.getPlayer(); TRNoDupe_BagCache cache; if ((cache = TRNoDupe_BagCache.check(player)) != null) { if (cache.hasBHBInBag) { try { TRNoDupe_BagCache.expire(cache); e.setCancelled(true); player.kickPlayer("[TRDupe] you have a Black Hole Band in your [" + cache.inBagColor + "] Alchemy Bag! Please remove it NOW!"); TRLogger.Log("Dupe", player.getName() + " [" + cache.inBagColor + " bag] attempted to dupe with the " + cache.dupeItem + "!"); TRLogger.broadcastDupe(player.getName(), "the Alchemy Bag and " + cache.dupeItem, "alc"); } catch (Exception err) { } } } } }
true
true
public static void handleDupes(InventoryClickEvent event) { // event.getInventory(); Player player = tekkitrestrict.getInstance().getServer() .getPlayer(event.getWhoClicked().getName()); int slot = event.getSlot(); String title = event.getView().getTopInventory().getTitle() .toLowerCase(); tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick()); // RMDupe Slot35 if (!TRPermHandler.hasPermission(player, "dupe", "bypass", "")) { // tekkitrestrict.log.info("t0-"+title+"-"); if (title.equals("rm furnace")) { // tekkitrestrict.log.info("t1"); if (slot == 35) { // tekkitrestrict.log.info("t2"); if (event.isShiftClick()) { // tekkitrestrict.log.info("t3"); if (preventRMDupe) { event.setCancelled(true); player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a RM Furnace!"); TRLogger.Log("Dupe", player.getName() + " attempted to dupe using a RM Furnace!"); } else { TRLogger.Log("Dupe", player.getName() + " duped using a RM Furnace!"); } dupeAttempts++; TRLogger.broadcastDupe(player.getName(), "the RM Furnace", "RMFurnace"); } } } else if (title.equals("tank cart")) { // tekkitrestrict.log.info("t1"); if (slot == 35) { // tekkitrestrict.log.info("t2"); if (event.isShiftClick()) { event.setCancelled(true); player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a Tank Cart!"); TRLogger.Log("Dupe", player.getName() + " attempted to dupe using a Tank Cart!"); dupeAttempts++; TRLogger.broadcastDupe(player.getName(), "the Tank Cart", "TankCart"); } } } else if (title.equals("trans tablet")) { // slots-6 7 5 3 1 0 2 int item = event.getCurrentItem().getTypeId(); if (item == 27557) { } if (item == 27558) { } if (item == 27559) { } if (item == 27560) { } if (item == 27561) { } if (item == 27591) { } if (event.isShiftClick()) { // if (isKlein) { boolean isslot = slot == 0 || slot == 1 || slot == 2 || slot == 3 || slot == 4 || slot == 5 || slot == 6 || slot == 7; if (isslot) { if (preventTransmuteDupe) { event.setCancelled(true); player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click any "); player.sendRawMessage(" item out of the transmutation table!"); TRLogger.Log("Dupe", player.getName() + " attempted to transmute dupe!"); } else { TRLogger.Log("Dupe", player.getName() + " attempted to transmute dupe!"); } dupeAttempts++; TRLogger.broadcastDupe(player.getName(), "the Transmutation Table", "transmute"); } // } } } } }
public static void handleDupes(InventoryClickEvent event) { // event.getInventory(); Player player = tekkitrestrict.getInstance().getServer() .getPlayer(event.getWhoClicked().getName()); int slot = event.getSlot(); String title = event.getView().getTopInventory().getTitle() .toLowerCase(); //tekkitrestrict.log.info("t0-"+title+"-"+slot+"-"+event.isShiftClick()); // RMDupe Slot35 if (!TRPermHandler.hasPermission(player, "dupe", "bypass", "")) { // tekkitrestrict.log.info("t0-"+title+"-"); if (title.equals("rm furnace")) { // tekkitrestrict.log.info("t1"); if (slot == 35) { // tekkitrestrict.log.info("t2"); if (event.isShiftClick()) { // tekkitrestrict.log.info("t3"); if (preventRMDupe) { event.setCancelled(true); player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a RM Furnace!"); TRLogger.Log("Dupe", player.getName() + " attempted to dupe using a RM Furnace!"); } else { TRLogger.Log("Dupe", player.getName() + " duped using a RM Furnace!"); } dupeAttempts++; TRLogger.broadcastDupe(player.getName(), "the RM Furnace", "RMFurnace"); } } } else if (title.equals("tank cart")) { // tekkitrestrict.log.info("t1"); if (slot == 35) { // tekkitrestrict.log.info("t2"); if (event.isShiftClick()) { event.setCancelled(true); player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click here while using a Tank Cart!"); TRLogger.Log("Dupe", player.getName() + " attempted to dupe using a Tank Cart!"); dupeAttempts++; TRLogger.broadcastDupe(player.getName(), "the Tank Cart", "TankCart"); } } } else if (title.equals("trans tablet")) { // slots-6 7 5 3 1 0 2 int item = event.getCurrentItem().getTypeId(); if (item == 27557) { } if (item == 27558) { } if (item == 27559) { } if (item == 27560) { } if (item == 27561) { } if (item == 27591) { } if (event.isShiftClick()) { // if (isKlein) { boolean isslot = slot == 0 || slot == 1 || slot == 2 || slot == 3 || slot == 4 || slot == 5 || slot == 6 || slot == 7; if (isslot) { if (preventTransmuteDupe) { event.setCancelled(true); player.sendRawMessage("[TRDupe] you are not allowed to Shift+Click any "); player.sendRawMessage(" item out of the transmutation table!"); TRLogger.Log("Dupe", player.getName() + " attempted to transmute dupe!"); } else { TRLogger.Log("Dupe", player.getName() + " attempted to transmute dupe!"); } dupeAttempts++; TRLogger.broadcastDupe(player.getName(), "the Transmutation Table", "transmute"); } // } } } } }
diff --git a/treeview/src/main/uk/ac/starlink/treeview/ImageHDUDataNode.java b/treeview/src/main/uk/ac/starlink/treeview/ImageHDUDataNode.java index ea8f910b3..75c5698a0 100644 --- a/treeview/src/main/uk/ac/starlink/treeview/ImageHDUDataNode.java +++ b/treeview/src/main/uk/ac/starlink/treeview/ImageHDUDataNode.java @@ -1,288 +1,288 @@ package uk.ac.starlink.treeview; import java.io.IOException; import java.nio.Buffer; import java.nio.ByteBuffer; import java.util.Iterator; import javax.swing.Icon; import javax.swing.JComponent; import nom.tam.fits.BasicHDU; import nom.tam.fits.FitsException; import nom.tam.fits.Header; import uk.ac.starlink.array.AccessMode; import uk.ac.starlink.array.BridgeNDArray; import uk.ac.starlink.array.MouldArrayImpl; import uk.ac.starlink.array.NDArray; import uk.ac.starlink.array.NDShape; import uk.ac.starlink.ast.AstException; import uk.ac.starlink.ast.AstObject; import uk.ac.starlink.ast.FitsChan; import uk.ac.starlink.ast.Frame; import uk.ac.starlink.ast.FrameSet; import uk.ac.starlink.ast.SkyFrame; import uk.ac.starlink.fits.FitsArrayBuilder; import uk.ac.starlink.fits.MappedFile; import uk.ac.starlink.splat.util.SplatException; /** * An implementation of the {@link DataNode} interface for * representing Header and Data Units (HDUs) in FITS files. * * @author Mark Taylor (Starlink) * @version $Id$ */ public class ImageHDUDataNode extends HDUDataNode { private Icon icon; private String name; private String description; private String hduType; private JComponent fullview; private Header header; private NDShape shape; private final String dataType; private String blank; private BufferMaker bufmaker; private Number badval; private FrameSet wcs; private String wcsEncoding; /** * Initialises an <code>ImageHDUDataNode</code> from a <code>Header</code> * object. * * @param hdr a FITS header object * from which the node is to be created. * @param bufmaker an object capable of constructing the NIO buffer * containing the header+data on demand */ public ImageHDUDataNode( Header hdr, BufferMaker bufmaker ) throws NoSuchDataException { super( hdr ); this.header = hdr; this.bufmaker = bufmaker; hduType = getHduType(); if ( hduType != "Image" ) { throw new NoSuchDataException( "Not an Image HDU" ); } long[] axes = getDimsFromHeader( hdr ); int ndim = axes.length; if ( axes != null && ndim > 0 ) { shape = new NDShape( new long[ ndim ], axes ); } boolean hasBlank = hdr.containsKey( "BLANK" ); badval = null; blank = "<none>"; switch ( hdr.getIntValue( "BITPIX" ) ) { case BasicHDU.BITPIX_BYTE: dataType = "byte"; if ( hasBlank ) { int val = hdr.getIntValue( "BLANK" ); blank = "" + val; badval = new Byte( (byte) val ); } break; case BasicHDU.BITPIX_SHORT: dataType = "short"; if ( hasBlank ) { int val = hdr.getIntValue( "BLANK" ); blank = "" + val; badval = new Short( (short) val ); } break; case BasicHDU.BITPIX_INT: dataType = "int"; if ( hasBlank ) { int val = hdr.getIntValue( "BLANK" ); blank = "" + val; badval = new Integer( val ); } break; case BasicHDU.BITPIX_FLOAT: dataType = "float"; blank = null; break; case BasicHDU.BITPIX_DOUBLE: dataType = "double"; blank = null; break; case BasicHDU.BITPIX_LONG: throw new NoSuchDataException( "64-bit integers not supported by FITS" ); default: dataType = null; } if ( Driver.hasAST ) { try { final Iterator hdrIt = hdr.iterator(); Iterator lineIt = new Iterator() { public boolean hasNext() { return hdrIt.hasNext(); } public Object next() { return hdrIt.next().toString(); } public void remove() { throw new UnsupportedOperationException(); } }; FitsChan chan = new FitsChan( lineIt ); wcsEncoding = chan.getEncoding(); AstObject aobj = chan.read(); if ( aobj != null && aobj instanceof FrameSet ) { wcs = (FrameSet) aobj; } else { wcsEncoding = null; wcs = null; } } catch ( AstException e ) { wcsEncoding = null; wcs = null; } } else { wcsEncoding = null; wcs = null; } description = "(" + hduType + ( ( shape != null ) - ? ( " " + shape.toString() + " " ) + ? ( " " + NDShape.toString( shape.getDims() ) + " " ) : "" ) + ")"; } public boolean allowsChildren() { // return false; return wcs != null; } public DataNode[] getChildren() { if ( wcs == null ) { // if ( true ) { return new DataNode[ 0 ]; } else { DataNode wcschild; try { wcschild = new WCSDataNode( wcs ); } catch ( NoSuchDataException e ) { wcschild = new ErrorDataNode( e ); } return new DataNode[] { wcschild }; } } public Icon getIcon() { if ( icon == null ) { if ( shape != null ) { icon = IconFactory.getInstance() .getArrayIcon( shape.getNumDims() ); } else { icon = IconFactory.getInstance() .getIcon( IconFactory.HDU ); } } return icon; } public boolean hasFullView() { return true; } public JComponent getFullView() { if ( fullview == null ) { DetailViewer dv = new DetailViewer( this ); fullview = dv.getComponent(); dv.addSeparator(); dv.addKeyedItem( "HDU type", hduType ); if ( shape != null ) { dv.addKeyedItem( "Shape", shape ); } if ( dataType != null ) { dv.addKeyedItem( "Pixel type", dataType ); } if ( blank != null ) { dv.addKeyedItem( "Blank value", blank ); } dv.addKeyedItem( "Number of header cards", header.getNumberOfCards() ); if ( wcs != null ) { dv.addSubHead( "World coordinate system" ); dv.addKeyedItem( "Encoding", wcsEncoding ); uk.ac.starlink.ast.Frame frm = wcs.getFrame( FrameSet.AST__CURRENT ); dv.addKeyedItem( "Naxes", frm.getNaxes() ); if ( frm instanceof SkyFrame ) { SkyFrame sfrm = (SkyFrame) frm; dv.addKeyedItem( "Epoch", sfrm.getEpoch() ); dv.addKeyedItem( "Equinox", sfrm.getEquinox() ); dv.addKeyedItem( "Projection", sfrm.getProjection() ); dv.addKeyedItem( "System", sfrm.getSystem() ); } } dv.addPane( "Header cards", new ComponentMaker() { public JComponent getComponent() { return new TextViewer( header.iterator() ); } } ); if ( shape != null && bufmaker != null ) { try { ByteBuffer bbuf = bufmaker.makeBuffer(); MappedFile mf = new MappedFile( bbuf ); NDArray nda = FitsArrayBuilder.getInstance() .makeNDArray( mf, AccessMode.READ ); if ( ! nda.getShape().equals( shape ) ) { nda = new BridgeNDArray( new MouldArrayImpl( nda, shape ) ); } NDArrayDataNode.addDataViews( dv, nda, wcs ); } catch ( IOException e ) { dv.logError( e ); } } } return fullview; } public String getDescription() { return description; } public String getNodeTLA() { return "IMG"; } public String getNodeType() { return "FITS Image HDU"; } private static long[] getDimsFromHeader( Header hdr ) { try { int naxis = hdr.getIntValue( "NAXIS" ); long[] dimensions = new long[ naxis ]; for ( int i = 0; i < naxis; i++ ) { String key = "NAXIS" + ( i + 1 ); if ( hdr.containsKey( key ) ) { dimensions[ i ] = hdr.getLongValue( key ); } else { throw new FitsException( "No header card + " + key ); } } return dimensions; } catch ( Exception e ) { return null; } } }
true
true
public ImageHDUDataNode( Header hdr, BufferMaker bufmaker ) throws NoSuchDataException { super( hdr ); this.header = hdr; this.bufmaker = bufmaker; hduType = getHduType(); if ( hduType != "Image" ) { throw new NoSuchDataException( "Not an Image HDU" ); } long[] axes = getDimsFromHeader( hdr ); int ndim = axes.length; if ( axes != null && ndim > 0 ) { shape = new NDShape( new long[ ndim ], axes ); } boolean hasBlank = hdr.containsKey( "BLANK" ); badval = null; blank = "<none>"; switch ( hdr.getIntValue( "BITPIX" ) ) { case BasicHDU.BITPIX_BYTE: dataType = "byte"; if ( hasBlank ) { int val = hdr.getIntValue( "BLANK" ); blank = "" + val; badval = new Byte( (byte) val ); } break; case BasicHDU.BITPIX_SHORT: dataType = "short"; if ( hasBlank ) { int val = hdr.getIntValue( "BLANK" ); blank = "" + val; badval = new Short( (short) val ); } break; case BasicHDU.BITPIX_INT: dataType = "int"; if ( hasBlank ) { int val = hdr.getIntValue( "BLANK" ); blank = "" + val; badval = new Integer( val ); } break; case BasicHDU.BITPIX_FLOAT: dataType = "float"; blank = null; break; case BasicHDU.BITPIX_DOUBLE: dataType = "double"; blank = null; break; case BasicHDU.BITPIX_LONG: throw new NoSuchDataException( "64-bit integers not supported by FITS" ); default: dataType = null; } if ( Driver.hasAST ) { try { final Iterator hdrIt = hdr.iterator(); Iterator lineIt = new Iterator() { public boolean hasNext() { return hdrIt.hasNext(); } public Object next() { return hdrIt.next().toString(); } public void remove() { throw new UnsupportedOperationException(); } }; FitsChan chan = new FitsChan( lineIt ); wcsEncoding = chan.getEncoding(); AstObject aobj = chan.read(); if ( aobj != null && aobj instanceof FrameSet ) { wcs = (FrameSet) aobj; } else { wcsEncoding = null; wcs = null; } } catch ( AstException e ) { wcsEncoding = null; wcs = null; } } else { wcsEncoding = null; wcs = null; } description = "(" + hduType + ( ( shape != null ) ? ( " " + shape.toString() + " " ) : "" ) + ")"; }
public ImageHDUDataNode( Header hdr, BufferMaker bufmaker ) throws NoSuchDataException { super( hdr ); this.header = hdr; this.bufmaker = bufmaker; hduType = getHduType(); if ( hduType != "Image" ) { throw new NoSuchDataException( "Not an Image HDU" ); } long[] axes = getDimsFromHeader( hdr ); int ndim = axes.length; if ( axes != null && ndim > 0 ) { shape = new NDShape( new long[ ndim ], axes ); } boolean hasBlank = hdr.containsKey( "BLANK" ); badval = null; blank = "<none>"; switch ( hdr.getIntValue( "BITPIX" ) ) { case BasicHDU.BITPIX_BYTE: dataType = "byte"; if ( hasBlank ) { int val = hdr.getIntValue( "BLANK" ); blank = "" + val; badval = new Byte( (byte) val ); } break; case BasicHDU.BITPIX_SHORT: dataType = "short"; if ( hasBlank ) { int val = hdr.getIntValue( "BLANK" ); blank = "" + val; badval = new Short( (short) val ); } break; case BasicHDU.BITPIX_INT: dataType = "int"; if ( hasBlank ) { int val = hdr.getIntValue( "BLANK" ); blank = "" + val; badval = new Integer( val ); } break; case BasicHDU.BITPIX_FLOAT: dataType = "float"; blank = null; break; case BasicHDU.BITPIX_DOUBLE: dataType = "double"; blank = null; break; case BasicHDU.BITPIX_LONG: throw new NoSuchDataException( "64-bit integers not supported by FITS" ); default: dataType = null; } if ( Driver.hasAST ) { try { final Iterator hdrIt = hdr.iterator(); Iterator lineIt = new Iterator() { public boolean hasNext() { return hdrIt.hasNext(); } public Object next() { return hdrIt.next().toString(); } public void remove() { throw new UnsupportedOperationException(); } }; FitsChan chan = new FitsChan( lineIt ); wcsEncoding = chan.getEncoding(); AstObject aobj = chan.read(); if ( aobj != null && aobj instanceof FrameSet ) { wcs = (FrameSet) aobj; } else { wcsEncoding = null; wcs = null; } } catch ( AstException e ) { wcsEncoding = null; wcs = null; } } else { wcsEncoding = null; wcs = null; } description = "(" + hduType + ( ( shape != null ) ? ( " " + NDShape.toString( shape.getDims() ) + " " ) : "" ) + ")"; }
diff --git a/src/me/rigi/acceptrules/AcceptRulesListener.java b/src/me/rigi/acceptrules/AcceptRulesListener.java index e4626ef..7a96640 100644 --- a/src/me/rigi/acceptrules/AcceptRulesListener.java +++ b/src/me/rigi/acceptrules/AcceptRulesListener.java @@ -1,83 +1,83 @@ package me.rigi.acceptrules; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; public class AcceptRulesListener implements Listener { @EventHandler public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event){ Player player = event.getPlayer(); String[] args = event.getMessage().split(" "); if(args[0].equalsIgnoreCase(AcceptRulesMain.RulesCmd)){ if(!(AcceptRulesMain.readed.contains(player))){ AcceptRulesMain.readed.add(player); } }else{ - if(AcceptRulesMain.BlockCmds && !(args[0].equalsIgnoreCase("/acceptrules"))){ + if(AcceptRulesMain.BlockCmds && !args[0].equalsIgnoreCase("/acceptrules") && !AcceptRulesMain.players.contains(event.getPlayer().getName())){ player.sendMessage(ChatColor.DARK_RED+AcceptRulesMain.InformMsg); event.setCancelled(true); } } } @EventHandler public void onPlayerJoin(PlayerJoinEvent event){ if(!AcceptRulesMain.players.contains(event.getPlayer().getName())){ if(AcceptRulesMain.TpOnJoin==true){ event.getPlayer().teleport(AcceptRulesMain.SpawnPosition); } if(AcceptRulesMain.Inform==true){ final Player player = event.getPlayer(); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(new AcceptRulesMain(), new Runnable() { public void run() { player.sendMessage(AcceptRulesMain.InformMsg); } }, 10L); } } } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { Player player = event.getPlayer(); if(AcceptRulesMain.AllowBuild==false){ if (AcceptRulesMain.players.contains(player.getName())){ }else{ event.setCancelled(true); player.sendMessage(ChatColor.DARK_RED+AcceptRulesMain.CantBuildMsg); } } } @EventHandler public void onBlockBreak(BlockBreakEvent event) { Player player = event.getPlayer(); if(AcceptRulesMain.AllowBuild==false){ if (AcceptRulesMain.players.contains(player.getName())){ }else{ event.setCancelled(true); player.sendMessage(ChatColor.DARK_RED+AcceptRulesMain.CantBuildMsg); } } } @EventHandler public void onPlayerMove(PlayerMoveEvent event){ if((!AcceptRulesMain.players.contains(event.getPlayer().getName()))&& (AcceptRulesMain.AllowMove == false)){ event.setCancelled(true); } } }
true
false
null
null
diff --git a/fog.routing.hrm/src/de/tuilmenau/ics/fog/ui/eclipse/editors/HRMViewer.java b/fog.routing.hrm/src/de/tuilmenau/ics/fog/ui/eclipse/editors/HRMViewer.java index 7f671601..7a169a23 100644 --- a/fog.routing.hrm/src/de/tuilmenau/ics/fog/ui/eclipse/editors/HRMViewer.java +++ b/fog.routing.hrm/src/de/tuilmenau/ics/fog/ui/eclipse/editors/HRMViewer.java @@ -1,2020 +1,2025 @@ /******************************************************************************* * Forwarding on Gates Simulator/Emulator - Hierarchical Routing Management * Copyright (c) 2012, Integrated Communication Systems Group, TU Ilmenau. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. ******************************************************************************/ package de.tuilmenau.ics.fog.ui.eclipse.editors; import java.io.FileNotFoundException; import java.text.Collator; import java.util.HashMap; import java.util.LinkedList; import java.util.Locale; import java.util.Observable; import java.util.Observer; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.layout.TableColumnLayout; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.MenuDetectEvent; import org.eclipse.swt.events.MenuDetectListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.EditorPart; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import de.tuilmenau.ics.fog.IEvent; import de.tuilmenau.ics.fog.eclipse.ui.editors.EditorInput; import de.tuilmenau.ics.fog.eclipse.utils.Resources; import de.tuilmenau.ics.fog.packets.hierarchical.SignalingMessageHrm; import de.tuilmenau.ics.fog.packets.hierarchical.topology.AnnounceCoordinator; import de.tuilmenau.ics.fog.routing.hierarchical.HRMController; import de.tuilmenau.ics.fog.routing.hierarchical.HRMConfig; -import de.tuilmenau.ics.fog.routing.hierarchical.HRMRoutingService; import de.tuilmenau.ics.fog.routing.hierarchical.RoutingEntry; import de.tuilmenau.ics.fog.routing.hierarchical.RoutingTable; import de.tuilmenau.ics.fog.routing.hierarchical.management.Cluster; import de.tuilmenau.ics.fog.routing.hierarchical.management.ClusterMember; import de.tuilmenau.ics.fog.routing.hierarchical.management.ClusterName; import de.tuilmenau.ics.fog.routing.hierarchical.management.ComChannel; import de.tuilmenau.ics.fog.routing.hierarchical.management.ComChannelPacketMetaData; import de.tuilmenau.ics.fog.routing.hierarchical.management.ControlEntity; import de.tuilmenau.ics.fog.routing.hierarchical.management.Coordinator; import de.tuilmenau.ics.fog.routing.hierarchical.management.CoordinatorAsClusterMember; import de.tuilmenau.ics.fog.routing.hierarchical.management.HierarchyLevel; import de.tuilmenau.ics.fog.routing.naming.hierarchical.HRMID; import de.tuilmenau.ics.fog.routing.naming.hierarchical.L2Address; import de.tuilmenau.ics.fog.ui.Logging; /** * The HRM viewer, which depicts all information from an HRM controller. * */ public class HRMViewer extends EditorPart implements Observer, Runnable, IEvent { private static boolean HRM_VIEWER_DEBUGGING = HRMConfig.DebugOutput.GUI_SHOW_VIEWER_STEPS; private static boolean HRM_VIEWER_SHOW_SINGLE_ENTITY_CLUSTERING_CONTROLS = true; private static boolean HRM_VIEWER_SHOW_SINGLE_ENTITY_ELECTION_CONTROLS = true; private static boolean HRM_VIEWER_SHOW_ALWAYS_ALL_CLUSTERS = true; private static final boolean GUI_SHOW_COLORED_BACKGROUND_FOR_CONTROL_ENTITIES = true; private HRMController mHRMController = null; private Composite mShell = null; private Display mDisplay = null; private Composite mContainerRoutingTable = null; private Composite mContainerHRMID2L2ADDRTable = null; private Composite mGlobalContainer = null; private Composite mContainer = null; private Composite mToolBtnContainer = null; private Composite mToolChlBoxContainer = null; private ScrolledComposite mScroller = null; private Button mBtnPriorityLog = null; private Button mBtnClusteringLog = null; private Button mBtnClusterMembersLog = null; private Button mBtnHRMIDLog = null; private Button mBtnHRGLog = null; private Button mBtnSuperiorCoordinatorsLog = null; private Button mBtnUsedClusterAddressesLog = null; private Button mBtnTopologyReports = null; private Button mBtnShareRoutes = null; private Button mBtnClusterMembers = null; private Button mBtnCoordClusterMembers = null; private Button mBtnCoordAnnounce = null; private Table mTableRoutingTable = null; private int mGuiCounter = 0; private boolean mNextGUIUpdateResetsOnlyRoutingTable = false; private boolean mShowClusterMembers = false; private boolean mShowCoordinatorAsClusterMembers = false; /** * Stores the time stamp of the last GUI update */ private Double mTimestampLastGUIUpdate = new Double(0); /** * Stores the simulation time for the next GUI update. */ private double mTimeNextGUIUpdate = 0; /** * Stores the ID of the HRM plug-in */ private static final String PLUGIN_ID = "de.tuilmenau.ics.fog.routing.hrm"; /** * Stores the path to the HRM icons */ private static final String PATH_ICONS = "/icons/"; /** * Reference pointer to ourself */ private HRMViewer mHRMViewer = this; public HRMViewer() { } private GridData createGridData(boolean grabSpace, int colSpan) { GridData gridData = new GridData(); gridData.horizontalAlignment = SWT.FILL; gridData.grabExcessHorizontalSpace = grabSpace; gridData.horizontalSpan = colSpan; return gridData; } private void createButtons(Composite pParent) { if(mGuiCounter == 1){ mToolBtnContainer = new Composite(pParent, SWT.NONE); GridLayout tLayout1 = new GridLayout(7, false); mToolBtnContainer.setLayout(tLayout1); mToolBtnContainer.setLayoutData(createGridData(true, 1)); mToolChlBoxContainer = new Composite(pParent, SWT.NONE); GridLayout tLayout2 = new GridLayout(5, false); mToolChlBoxContainer.setLayout(tLayout2); mToolChlBoxContainer.setLayoutData(createGridData(true, 1)); } /** * Push buttons */ // **** show priority update log **** if(mGuiCounter == 1){ mBtnPriorityLog = new Button(mToolBtnContainer, SWT.PUSH); mBtnPriorityLog.setText("Show priority update events"); mBtnPriorityLog.setLayoutData(createGridData(false, 1)); mBtnPriorityLog.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { Logging.log(this, "Connectivity priority updates: " + mHRMController.getGUIDescriptionConnectivityPriorityUpdates()); Logging.log(this, "Hierarchy priority updates: " + mHRMController.getGUIDescriptionHierarchyPriorityUpdates()); } public String toString() { return mHRMViewer.toString(); } }); } // **** show update cluster log **** if(mGuiCounter == 1){ mBtnClusteringLog = new Button(mToolBtnContainer, SWT.PUSH); mBtnClusteringLog.setText("Show clustering events"); mBtnClusteringLog.setLayoutData(createGridData(false, 1)); mBtnClusteringLog.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { Logging.log(this, "Clustering updates: " + mHRMController.getGUIDescriptionClusterUpdates()); } public String toString() { return mHRMViewer.toString(); } }); } // **** show active ClusterMember update log **** if(mGuiCounter == 1){ mBtnClusterMembersLog = new Button(mToolBtnContainer, SWT.PUSH); mBtnClusterMembersLog.setText("Show active ClusterMember events"); mBtnClusterMembersLog.setLayoutData(createGridData(false, 1)); mBtnClusterMembersLog.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { Logging.log(this, "Active ClusterMember updates: " + ((String)mHRMController.getGUIDescriptionNodeElectionStateChanges())); } public String toString() { return mHRMViewer.toString(); } }); } // **** show HRMID update log **** if(mGuiCounter == 1){ mBtnHRMIDLog = new Button(mToolBtnContainer, SWT.PUSH); mBtnHRMIDLog.setText("Show HRMID events"); mBtnHRMIDLog.setLayoutData(createGridData(false, 1)); mBtnHRMIDLog.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { Logging.log(this, "HRMID updates: " + mHRMController.getGUIDescriptionHRMIDChanges()); } public String toString() { return mHRMViewer.toString(); } }); } // **** show HRG update log **** if(mGuiCounter == 1){ mBtnHRGLog = new Button(mToolBtnContainer, SWT.PUSH); mBtnHRGLog.setText("Show HRG events"); mBtnHRGLog.setLayoutData(createGridData(false, 1)); mBtnHRGLog.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { Logging.log(this, "HRG updates: " + mHRMController.getGUIDescriptionHRGChanges()); } public String toString() { return mHRMViewer.toString(); } }); } // **** show superior coordinators **** if(mGuiCounter == 1){ mBtnSuperiorCoordinatorsLog = new Button(mToolBtnContainer, SWT.PUSH); mBtnSuperiorCoordinatorsLog.setText("Show superior coordinators"); mBtnSuperiorCoordinatorsLog.setLayoutData(createGridData(false, 1)); mBtnSuperiorCoordinatorsLog.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { LinkedList<ClusterName> tSuperiorCoordinators = mHRMController.getAllSuperiorCoordinators(); Logging.log(this, "Superior coordinators:"); int i = 0; for(ClusterName tSuperiorCoordinator : tSuperiorCoordinators){ Logging.log(this, " ..[" + i + "]: Coordinator" + tSuperiorCoordinator.getGUICoordinatorID() + "@" + tSuperiorCoordinator.getHierarchyLevel().getValue() + "(Cluster" + tSuperiorCoordinator.getGUIClusterID() + ")"); } } public String toString() { return mHRMViewer.toString(); } }); } // **** show superior coordinators **** if(mGuiCounter == 1){ mBtnUsedClusterAddressesLog = new Button(mToolBtnContainer, SWT.PUSH); mBtnUsedClusterAddressesLog.setText("Show used addresses"); mBtnUsedClusterAddressesLog.setLayoutData(createGridData(false, 1)); mBtnUsedClusterAddressesLog.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { Logging.log(this, "Used cluster addresses: " + mHRMController.getGUIDEscriptionUsedAddresses()); } public String toString() { return mHRMViewer.toString(); } }); } /** * Check buttons */ // **** hide/show cluster members **** if(mGuiCounter == 1){ mBtnClusterMembers = new Button(mToolChlBoxContainer, SWT.CHECK); } mBtnClusterMembers.setText("ClusterMembers"); if(mShowClusterMembers){ mBtnClusterMembers.setSelection(true); }else{ mBtnClusterMembers.setSelection(false); } if(mGuiCounter == 1){ mBtnClusterMembers.setLayoutData(createGridData(false, 1)); mBtnClusterMembers.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { mShowClusterMembers = !mShowClusterMembers; startGUIUpdateTimer(); } }); } // **** hide/show coordinators-as-cluster-members **** if(mGuiCounter == 1){ mBtnCoordClusterMembers = new Button(mToolChlBoxContainer, SWT.CHECK); } mBtnCoordClusterMembers.setText("CoordinatorAsClusterMembers"); if(mShowCoordinatorAsClusterMembers){ mBtnCoordClusterMembers.setSelection(true); }else{ mBtnCoordClusterMembers.setSelection(false); } if(mGuiCounter == 1){ mBtnCoordClusterMembers.setLayoutData(createGridData(false, 1)); mBtnCoordClusterMembers.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { mShowCoordinatorAsClusterMembers = !mShowCoordinatorAsClusterMembers; startGUIUpdateTimer(); } }); } // **** deactivate/activate coordinator announcements **** if(mGuiCounter == 1){ mBtnCoordAnnounce = new Button(mToolChlBoxContainer, SWT.CHECK); } mBtnCoordAnnounce.setText("Coordinator announcements"); if (Coordinator.GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS){ mBtnCoordAnnounce.setSelection(true); }else{ mBtnCoordAnnounce.setSelection(false); } if(mGuiCounter == 1){ mBtnCoordAnnounce.setLayoutData(createGridData(false, 1)); mBtnCoordAnnounce.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { Coordinator.GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS = !Coordinator.GUI_USER_CTRL_COORDINATOR_ANNOUNCEMENTS; } }); } // **** deactivate/activate topology reports **** if(mGuiCounter == 1){ mBtnTopologyReports = new Button(mToolChlBoxContainer, SWT.CHECK); } mBtnTopologyReports.setText("Topology reports"); if (HRMController.GUI_USER_CTRL_REPORT_TOPOLOGY){ mBtnTopologyReports.setSelection(true); }else{ mBtnTopologyReports.setSelection(false); } if(mGuiCounter == 1){ mBtnTopologyReports.setLayoutData(createGridData(false, 1)); mBtnTopologyReports.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { HRMController.GUI_USER_CTRL_REPORT_TOPOLOGY = !HRMController.GUI_USER_CTRL_REPORT_TOPOLOGY; } }); } // **** deactivate/activate share routes **** if(mGuiCounter == 1){ mBtnShareRoutes = new Button(mToolChlBoxContainer, SWT.CHECK); } mBtnShareRoutes.setText("Share routes"); if (HRMController.GUI_USER_CTRL_SHARE_ROUTES){ mBtnShareRoutes.setSelection(true); }else{ mBtnShareRoutes.setSelection(false); } if(mGuiCounter == 1){ mBtnShareRoutes.setLayoutData(createGridData(false, 1)); mBtnShareRoutes.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent pEvent) { HRMController.GUI_USER_CTRL_SHARE_ROUTES = !HRMController.GUI_USER_CTRL_SHARE_ROUTES; } }); } } /** * Resets all parts of the EditorPart */ private void destroyPartControl() { mContainer.dispose(); //HINT: don't dispose the mScroller object here, this would lead to GUI display problems mShell.redraw(); } /** * Creates all needed parts of the EditorPart. * * @param pParent the parent shell */ @Override public void createPartControl(Composite pParent) { mGuiCounter++; mShell = pParent; mDisplay = pParent.getDisplay(); if (mGuiCounter == 1){ mGlobalContainer = new Composite(pParent, SWT.NONE);//NO_BACKGROUND); GridLayout gridLayout = new GridLayout(1, false); mGlobalContainer.setLayout(gridLayout); } if (mGuiCounter == 1){ mScroller = new ScrolledComposite(mGlobalContainer, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER); GridData tScrollerLayoutData = new GridData(); tScrollerLayoutData.horizontalAlignment = SWT.FILL; tScrollerLayoutData.verticalAlignment = SWT.FILL; tScrollerLayoutData.grabExcessVerticalSpace = true; tScrollerLayoutData.grabExcessHorizontalSpace = true; tScrollerLayoutData.horizontalSpan = 1; mScroller.setExpandHorizontal(true); mScroller.setLayout(new GridLayout()); mScroller.setLayoutData(tScrollerLayoutData); // fix the mouse wheel function mScroller.addListener(SWT.Activate, new Listener() { public void handleEvent(Event e) { mScroller.setFocus(); } }); // fix the vertical scrolling speed mScroller.getVerticalBar().setIncrement(mScroller.getVerticalBar().getIncrement() * 20 /* 20 times faster */); } mContainer = new Composite(mScroller, SWT.NONE); mContainer.setLayout(new GridLayout(1, false)); mContainer.setLayoutData(new GridData(GridData.FILL_BOTH)); mScroller.setContent(mContainer); /** * Clusters, coordinators, ... */ if (HRM_VIEWER_DEBUGGING){ Logging.log(this, "Found clusters: " + mHRMController.getAllClusters().size()); Logging.log(this, "Found coordinators: " + mHRMController.getAllCoordinators().size()); } /** * GUI part 0: list clusters */ for(int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){ for (Cluster tCluster: mHRMController.getAllClusters(i)) { // show only those cluster which also have a coordinator if((HRM_VIEWER_SHOW_ALWAYS_ALL_CLUSTERS) || (tCluster.hasLocalCoordinator())){ // print info. about cluster printClusterMember(mContainer, tCluster); } } } /** * GUI part: list cluster members */ if (mShowClusterMembers){ for(int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){ for(ClusterMember tClusterMemeber : mHRMController.getAllClusterMembers(i)){ if (!(tClusterMemeber instanceof Cluster)){ // print info. about cluster printClusterMember(mContainer, tClusterMemeber); } } } } /** * GUI part: list coordinator as cluster members */ if(mShowCoordinatorAsClusterMembers){ for(CoordinatorAsClusterMember tCoordinatorAsClusterMember : mHRMController.getAllCoordinatorAsClusterMembers()){ // print info. about cluster printClusterMember(mContainer, tCoordinatorAsClusterMember); } } /** * GUI part 1: list coordinators */ for(int i = 0; i < HRMConfig.Hierarchy.HEIGHT; i++){ for (Coordinator tCoordinator: mHRMController.getAllCoordinators(i)) { // print info. about cluster printCoordinator(mContainer, tCoordinator); } } /** * GUI part 2: table of known mappings from HRMID to L2Addresses */ if (HRM_VIEWER_DEBUGGING){ Logging.log(this, "Printing HRMID-2-L2Address mapping..."); } // create the headline StyledText tSignaturesLabel4 = new StyledText(mContainer, SWT.BORDER); String tHRMIDsStr = ""; LinkedList<HRMID> tListHRMIDs = mHRMController.getHRMIDs(); for(HRMID tHRMID : tListHRMIDs){ if(tHRMIDsStr != ""){ tHRMIDsStr += ", "; } tHRMIDsStr += tHRMID.toString(); } tSignaturesLabel4.setText("Mappings from HRMID to L2Address (local HRMIDs: " + tHRMIDsStr + ")"); tSignaturesLabel4.setForeground(new Color(mShell.getDisplay(), 0, 0, 0)); tSignaturesLabel4.setBackground(new Color(mShell.getDisplay(), 222, 222, 222)); StyleRange style4 = new StyleRange(); style4.start = 0; style4.length = tSignaturesLabel4.getText().length(); style4.fontStyle = SWT.BOLD; tSignaturesLabel4.setStyleRange(style4); // create the GUI container mContainerHRMID2L2ADDRTable = new Composite(mContainer, SWT.NONE); GridData tLayoutDataMappingTable = new GridData(SWT.FILL, SWT.FILL, true, true); tLayoutDataMappingTable.horizontalSpan = 1; mContainerHRMID2L2ADDRTable.setLayoutData(tLayoutDataMappingTable); // create the table final Table tTableMappingTable = new Table(mContainerHRMID2L2ADDRTable, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); tTableMappingTable.setHeaderVisible(true); tTableMappingTable.setLinesVisible(true); // create the columns and define the texts for the header row // col. 0 TableColumn tTableHRMID = new TableColumn(tTableMappingTable, SWT.NONE, 0); tTableHRMID.setText("HRMID"); // col. 1 TableColumn tTableL2Addr = new TableColumn(tTableMappingTable, SWT.NONE, 1); tTableL2Addr.setText("L2 address"); HashMap<HRMID, L2Address> tHRMIDToL2AddressMapping = mHRMController.getHRS().getHRMIDToL2AddressMapping(); if (HRM_VIEWER_DEBUGGING){ Logging.log(this, "Found " + tHRMIDToL2AddressMapping.keySet().size() + " HRMID-to-L2Address mappings"); } if ((tHRMIDToL2AddressMapping != null) && (!tHRMIDToL2AddressMapping.isEmpty())) { int tRowNumber = 0; for(HRMID tAddr : tHRMIDToL2AddressMapping.keySet()) { L2Address tL2Addr = tHRMIDToL2AddressMapping.get(tAddr); // create the table row TableItem tTableRow = new TableItem(tTableMappingTable, SWT.NONE, tRowNumber); /** * Column 0: the neighbor name */ tTableRow.setText(0, tAddr.toString()); /** * Column 1: route */ tTableRow.setText(1, tL2Addr.toString()); tRowNumber++; } } TableColumn[] columns4 = tTableMappingTable.getColumns(); for (int k = 0; k < columns4.length; k++){ columns4[k].pack(); } tTableMappingTable.setLayoutData(new GridData(GridData.FILL_BOTH)); // create the container layout TableColumnLayout tLayoutMappingTable = new TableColumnLayout(); mContainerHRMID2L2ADDRTable.setLayout(tLayoutMappingTable); // assign each column a layout weight tLayoutMappingTable.setColumnData(tTableHRMID, new ColumnWeightData(3)); tLayoutMappingTable.setColumnData(tTableL2Addr, new ColumnWeightData(3)); /** * GUI part 3: HRM routing table of the node */ createRoutingTable(mContainer); /** * Tool buttons */ createButtons(mGlobalContainer); // arrange the GUI content in order to full the entire space if (mGuiCounter == 1){ mScroller.setSize(mScroller.computeSize(SWT.DEFAULT, SWT.DEFAULT)); } mContainer.setSize(mContainer.computeSize(SWT.DEFAULT, SWT.DEFAULT)); mContainerRoutingTable.setSize(mContainerRoutingTable.computeSize(SWT.DEFAULT, SWT.DEFAULT)); mContainerHRMID2L2ADDRTable.setSize(mContainerHRMID2L2ADDRTable.computeSize(SWT.DEFAULT, SWT.DEFAULT)); //mToolBtnContainer.setSize(mToolBtnContainer.computeSize(SWT.DEFAULT, 20)); } /** * Draws the routing table view * * @param pParent the parent GUI container */ private void createRoutingTable(Composite pParent) { if (HRM_VIEWER_DEBUGGING){ Logging.log(this, "Printing HRM routing table..."); } // create the headline StyledText tSignaturesLabel2 = new StyledText(pParent, SWT.BORDER); tSignaturesLabel2.setText("HRM Routing Table"); tSignaturesLabel2.setForeground(new Color(mShell.getDisplay(), 0, 0, 0)); tSignaturesLabel2.setBackground(new Color(mShell.getDisplay(), 222, 222, 222)); StyleRange style3 = new StyleRange(); style3.start = 0; style3.length = tSignaturesLabel2.getText().length(); style3.fontStyle = SWT.BOLD; tSignaturesLabel2.setStyleRange(style3); // create the GUI container mContainerRoutingTable = new Composite(pParent, SWT.NONE); GridData tLayoutDataRoutingTable = new GridData(SWT.FILL, SWT.FILL, true, true); tLayoutDataRoutingTable.horizontalSpan = 1; mContainerRoutingTable.setLayoutData(tLayoutDataRoutingTable); // create the table mTableRoutingTable = new Table(mContainerRoutingTable, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); mTableRoutingTable.setHeaderVisible(true); mTableRoutingTable.setLinesVisible(true); // create the columns and define the texts for the header row // col. 0 TableColumn tTableColDest = new TableColumn(mTableRoutingTable, SWT.NONE, 0); tTableColDest.setText("Dest."); // col. 1 TableColumn tTableColNext = new TableColumn(mTableRoutingTable, SWT.NONE, 1); tTableColNext.setText("Next hop"); // col. 2 TableColumn tTableColHops = new TableColumn(mTableRoutingTable, SWT.NONE, 2); tTableColHops.setText("Hops"); // col. 3 TableColumn tTableColUtil = new TableColumn(mTableRoutingTable, SWT.NONE, 3); tTableColUtil.setText("Util. [%]"); // col. 4 TableColumn tTableColDelay = new TableColumn(mTableRoutingTable, SWT.NONE, 4); tTableColDelay.setText("MinDelay [ms]"); // col. 5 TableColumn tTableColDR = new TableColumn(mTableRoutingTable, SWT.NONE, 5); tTableColDR.setText("MaxDR [Kb/s]"); // col. 6 TableColumn tTableColLoop = new TableColumn(mTableRoutingTable, SWT.NONE, 6); tTableColLoop.setText("Loopback?"); // col. 7 TableColumn tTableColDirectNeighbor = new TableColumn(mTableRoutingTable, SWT.NONE, 7); tTableColDirectNeighbor.setText("Route to neighbor"); // col. 8 TableColumn tTableColSource = new TableColumn(mTableRoutingTable, SWT.NONE, 8); tTableColSource.setText("Source"); // col. 9 TableColumn tTableColNextL2 = new TableColumn(mTableRoutingTable, SWT.NONE, 9); tTableColNextL2.setText("NextL2"); // col. 10 TableColumn tTableColTimeout = new TableColumn(mTableRoutingTable, SWT.NONE, 10); tTableColTimeout.setText("Timeout"); updateRoutingTable(); TableColumn[] columns2 = mTableRoutingTable.getColumns(); for (int k = 0; k < columns2.length; k++){ columns2[k].pack(); } mTableRoutingTable.setLayoutData(new GridData(GridData.FILL_BOTH));//SWT.FILL, SWT.TOP, true, true, 1, 1)); // create the container layout TableColumnLayout tLayoutRoutingTable2 = new TableColumnLayout(); mContainerRoutingTable.setLayout(tLayoutRoutingTable2); // assign each column a layout weight tLayoutRoutingTable2.setColumnData(tTableColDest, new ColumnWeightData(1)); tLayoutRoutingTable2.setColumnData(tTableColNext, new ColumnWeightData(1)); tLayoutRoutingTable2.setColumnData(tTableColHops, new ColumnWeightData(1)); tLayoutRoutingTable2.setColumnData(tTableColUtil, new ColumnWeightData(1)); tLayoutRoutingTable2.setColumnData(tTableColDelay, new ColumnWeightData(1)); tLayoutRoutingTable2.setColumnData(tTableColDR, new ColumnWeightData(1)); tLayoutRoutingTable2.setColumnData(tTableColLoop, new ColumnWeightData(1)); tLayoutRoutingTable2.setColumnData(tTableColDirectNeighbor, new ColumnWeightData(1)); tLayoutRoutingTable2.setColumnData(tTableColSource, new ColumnWeightData(1)); tLayoutRoutingTable2.setColumnData(tTableColNextL2, new ColumnWeightData(3)); tLayoutRoutingTable2.setColumnData(tTableColTimeout, new ColumnWeightData(1)); /** * Add a listener to allow re-sorting of the table based on the destination per table row */ tTableColDest.addListener(SWT.Selection, new Listener() { public void handleEvent(Event e) { // sort column 2 TableItem[] tAllRows = mTableRoutingTable.getItems(); Collator collator = Collator.getInstance(Locale.getDefault()); for (int i = 1; i < tAllRows.length; i++) { String value1 = tAllRows[i].getText(1); for (int j = 0; j < i; j++) { String value2 = tAllRows[j].getText(1); if (collator.compare(value1, value2) < 0) { // copy table row data String[] tRowData = { tAllRows[i].getText(0), tAllRows[i].getText(1) }; // delete table row "i" tAllRows[i].dispose(); // create new table row TableItem tRow = new TableItem(mTableRoutingTable, SWT.NONE, j); tRow.setText(tRowData); // update data of table rows tAllRows = mTableRoutingTable.getItems(); break; } } } } }); } /** * Draws GUI elements for depicting coordinator information. * * @param pParent the parent GUI container * @param pCoordinator selected coordinator */ private void printCoordinator(Composite pParent, Coordinator pCoordinator) { if (HRM_VIEWER_DEBUGGING) Logging.log(this, "Printing coordinator \"" + pCoordinator.toString() +"\""); /** * GUI part 0: name of the coordinator */ printNAME(pParent, pCoordinator); /** * GUI part 1: tool box */ if(pCoordinator != null) { ToolBar tToolbar = new ToolBar(pParent, SWT.NONE); if (HRM_VIEWER_SHOW_SINGLE_ENTITY_CLUSTERING_CONTROLS){ if(!pCoordinator.getHierarchyLevel().isHighest()) { if ((pCoordinator.getCluster().getElector() != null) && (pCoordinator.getCluster().getElector().isWinner()) && (!pCoordinator.isClustered())){ ToolItem toolItem3 = new ToolItem(tToolbar, SWT.PUSH); toolItem3.setText("[Create cluster]"); toolItem3.addListener(SWT.Selection, new ListenerClusterHierarchy(this, pCoordinator)); } } } ToolItem toolItem4 = new ToolItem(tToolbar, SWT.PUSH); toolItem4.setText("[Create all level " + pCoordinator.getHierarchyLevel().getValue() + " clusters]"); toolItem4.addListener(SWT.Selection, new ListenerClusterHierarchyLevel(this, pCoordinator)); tToolbar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1)); } /** * GUI part 2: table about comm. channels */ if(!pCoordinator.getHierarchyLevel().isHighest()){ printComChannels(pParent, pCoordinator); } Label separator = new Label (pParent, SWT.SEPARATOR | SWT.HORIZONTAL); separator.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1)); separator.setVisible(true); } private void printComChannels(Composite pParent, final ControlEntity pControlEntity) { // create the container Composite tContainerComChannels = new Composite(pParent, SWT.NONE); GridData tLayoutDataMappingTable = new GridData(SWT.FILL, SWT.FILL, true, true); tLayoutDataMappingTable.horizontalSpan = 1; tContainerComChannels.setLayoutData(tLayoutDataMappingTable); final Table tTable = new Table(tContainerComChannels, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); /** * The table header */ TableColumn tColumnPeer = new TableColumn(tTable, SWT.NONE, 0); tColumnPeer.setText("Peer"); TableColumn tColumnPeerNode = new TableColumn(tTable, SWT.NONE, 1); tColumnPeerNode.setText("Peer Node"); TableColumn tColumnActiveLink = new TableColumn(tTable, SWT.NONE, 2); tColumnActiveLink.setText("Active Link"); TableColumn tColumnPeerPriority = new TableColumn(tTable, SWT.NONE, 3); tColumnPeerPriority.setText("Peer Priority"); TableColumn tColumnPeerEP = new TableColumn(tTable, SWT.NONE, 4); tColumnPeerEP.setText("Peer End Point"); TableColumn tColumnRoute = new TableColumn(tTable, SWT.NONE, 5); tColumnRoute.setText("Route to peer"); TableColumn tColumnPeerHRMID = new TableColumn(tTable, SWT.NONE, 6); tColumnPeerHRMID.setText("Peer HRMID"); TableColumn tColumnDirection = new TableColumn(tTable, SWT.NONE, 7); tColumnDirection.setText("Connected"); TableColumn tColumnSendPackets = new TableColumn(tTable, SWT.NONE, 8); tColumnSendPackets.setText("Sent packets"); TableColumn tColumnReceivedPackets = new TableColumn(tTable, SWT.NONE, 9); tColumnReceivedPackets.setText("Received packets"); TableColumn tColumnState = new TableColumn(tTable, SWT.NONE, 10); tColumnState.setText("State"); TableColumn tColumnParentHRMID = new TableColumn(tTable, SWT.NONE, 11); tColumnParentHRMID.setText("Parent HRMID"); TableColumn tColumnQueue = new TableColumn(tTable, SWT.NONE, 12); tColumnQueue.setText("Queue"); tTable.setHeaderVisible(true); tTable.setLinesVisible(true); /** * The table content */ LinkedList<ComChannel> tComChannels = pControlEntity.getComChannels(); if(pControlEntity instanceof Coordinator){ Coordinator tCoordinator = (Coordinator)pControlEntity; tComChannels = tCoordinator.getClusterMembershipComChannels(); } int j = 0; if (HRM_VIEWER_DEBUGGING) Logging.log(this, "Amount of known comm. channels is " + tComChannels.size()); for(ComChannel tComChannel : tComChannels) { if (HRM_VIEWER_DEBUGGING) Logging.log(this, "Updating table item number " + j); // table row TableItem tRow = null; // get reference to already existing table row if (tTable.getItemCount() > j) { tRow = tTable.getItem(j); } // create a table row if necessary if (tRow == null){ tRow = new TableItem(tTable, SWT.NONE, j); } /** * Column 0: peer */ String tIsSuperiorCoordinatorChannel = ""; String tIsActiveCluster = ""; if(pControlEntity instanceof Coordinator){ Coordinator tCoordinator = (Coordinator)pControlEntity; if(tComChannel == tCoordinator.superiorCoordinatorComChannel()){ tIsSuperiorCoordinatorChannel = "*"; } CoordinatorAsClusterMember tCoordinatorAsClusterMember = (CoordinatorAsClusterMember) tComChannel.getParent(); if(tCoordinatorAsClusterMember.isActiveCluster()){ tIsActiveCluster = "+"; } } tRow.setText(0, tIsSuperiorCoordinatorChannel + tIsActiveCluster + ((tComChannel.getPeer() != null) ? tComChannel.getPeer().toString() : tComChannel.getRemoteClusterName().toString())); /** * Column 1: peer node */ tRow.setText(1, (tComChannel.getPeerL2Address() != null ? tComChannel.getPeerL2Address().toString() : "??")); /** * Column 2: active link */ tRow.setText(2, tComChannel.isLinkActive() ? "yes" : "no"); /** * Column 3: */ tRow.setText(3, Float.toString(tComChannel.getPeerPriority().getValue())); /** * Column 4: */ if (tComChannel.getRemoteClusterName() != null){ if ((pControlEntity.getHierarchyLevel().isHigherLevel()) && (pControlEntity instanceof Cluster)){ ClusterName tRemoteClusterName = tComChannel.getRemoteClusterName(); int tPeerLevel = tRemoteClusterName.getHierarchyLevel().getValue() - 1 /* the connected remote entity is always one level below because it is reported with an increment */; tRow.setText(4, "Coordinator" + tRemoteClusterName.getGUICoordinatorID() + "@" + (tPeerLevel) + "(Cluster" + tRemoteClusterName.getGUIClusterID() + "@" + tPeerLevel + ")"); }else{ tRow.setText(4, tComChannel.getRemoteClusterName().toString()); } }else{ tRow.setText(4, "??"); } /** * Column 5: */ if (tComChannel.getRouteToPeer() != null){ tRow.setText(5, tComChannel.getRouteToPeer().toString()); }else{ tRow.setText(5, "??"); } /** * Column 6: */ HRMID tPeerHRMID = tComChannel.getPeerHRMID(); tRow.setText(6, (tPeerHRMID != null ? tPeerHRMID.toString() : "undef.")); /** * Column 7: */ tRow.setText(7, tComChannel.getDirection().toString()); /** * Column 8: */ tRow.setText(8, Integer.toString(tComChannel.countSentPackets())); /** * Column 9: */ tRow.setText(9, Integer.toString(tComChannel.countReceivedPackets())); /** * Column 10: */ tRow.setText(10, tComChannel.getState().toString()); /** * Column 11: */ HRMID tParentHRMID = tComChannel.getParent().getHRMID(); tRow.setText(11, (tParentHRMID != null ? tParentHRMID.toString() : "undef.")); /** * Column 12: */ tRow.setText(12, Integer.toString(tComChannel.getPacketQueue().size())); j++; } TableColumn[] cols = tTable.getColumns(); for(int k=0; k < cols.length; k++) cols[k].pack(); tTable.setLayoutData(new GridData(GridData.FILL_BOTH)); // create the container layout TableColumnLayout tLayoutMappingTable = new TableColumnLayout(); tContainerComChannels.setLayout(tLayoutMappingTable); // assign each column a layout weight tLayoutMappingTable.setColumnData(tColumnPeer, new ColumnWeightData(3)); tLayoutMappingTable.setColumnData(tColumnPeerNode, new ColumnWeightData(3)); tLayoutMappingTable.setColumnData(tColumnActiveLink, new ColumnWeightData(1)); tLayoutMappingTable.setColumnData(tColumnPeerPriority, new ColumnWeightData(1)); tLayoutMappingTable.setColumnData(tColumnPeerEP, new ColumnWeightData(3)); tLayoutMappingTable.setColumnData(tColumnRoute, new ColumnWeightData(3)); tLayoutMappingTable.setColumnData(tColumnPeerHRMID, new ColumnWeightData(1)); tLayoutMappingTable.setColumnData(tColumnDirection, new ColumnWeightData(1)); tLayoutMappingTable.setColumnData(tColumnSendPackets, new ColumnWeightData(1)); tLayoutMappingTable.setColumnData(tColumnReceivedPackets, new ColumnWeightData(1)); tLayoutMappingTable.setColumnData(tColumnState, new ColumnWeightData(1)); tLayoutMappingTable.setColumnData(tColumnParentHRMID, new ColumnWeightData(1)); tLayoutMappingTable.setColumnData(tColumnQueue, new ColumnWeightData(1)); /** * The table context menu */ final LinkedList<ComChannel> tfComChannels = tComChannels; tTable.addMenuDetectListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent pEvent) { final int tSelectedIndex = tTable.getSelectionIndex(); // was there a row selected? if (tSelectedIndex != -1){ // identify which row was clicked. TableItem tSelectedRow = tTable.getItem(tSelectedIndex); tSelectedRow.getData(); //Logging.log(this, "Context menu for comm. channels of entity: " + pControlEntity + ", index: " + tSelectedIndex + ", row data: " + tSelectedRow); /** * Create the context menu */ Menu tMenu = new Menu(tTable); MenuItem tMenuItem = new MenuItem(tMenu, SWT.NONE); tMenuItem.setText("Show packet I/O"); tMenuItem.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent pEvent) { //Logging.log(this, "Default selected: " + pEvent); showPackets(tfComChannels.get(tSelectedIndex)); } public void widgetSelected(SelectionEvent pEvent) { //Logging.log(this, "Widget selected: " + pEvent); showPackets(tfComChannels.get(tSelectedIndex)); } }); MenuItem tMenuItem1 = new MenuItem(tMenu, SWT.NONE); tMenuItem1.setText("Show link activation events"); tMenuItem1.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent pEvent) { //Logging.log(this, "Default selected: " + pEvent); showLinkActivationEvents(tfComChannels.get(tSelectedIndex)); } public void widgetSelected(SelectionEvent pEvent) { //Logging.log(this, "Widget selected: " + pEvent); showLinkActivationEvents(tfComChannels.get(tSelectedIndex)); } }); MenuItem tMenuItem2 = new MenuItem(tMenu, SWT.NONE); tMenuItem2.setText("Show session"); tMenuItem2.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent pEvent) { //Logging.log(this, "Default selected: " + pEvent); showSession(tfComChannels.get(tSelectedIndex)); } public void widgetSelected(SelectionEvent pEvent) { //Logging.log(this, "Widget selected: " + pEvent); showSession(tfComChannels.get(tSelectedIndex)); } }); MenuItem tMenuItem3 = new MenuItem(tMenu, SWT.NONE); tMenuItem3.setText("Show peer HRMIDs"); tMenuItem3.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent pEvent) { //Logging.log(this, "Default selected: " + pEvent); showPeerHRMIDs(tfComChannels.get(tSelectedIndex)); } public void widgetSelected(SelectionEvent pEvent) { //Logging.log(this, "Widget selected: " + pEvent); showPeerHRMIDs(tfComChannels.get(tSelectedIndex)); } }); MenuItem tMenuItem4 = new MenuItem(tMenu, SWT.NONE); tMenuItem4.setText("Show assigned peer HRMIDs"); tMenuItem4.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent pEvent) { //Logging.log(this, "Default selected: " + pEvent); showAssignedPeerHRMIDs(tfComChannels.get(tSelectedIndex)); } public void widgetSelected(SelectionEvent pEvent) { //Logging.log(this, "Widget selected: " + pEvent); showAssignedPeerHRMIDs(tfComChannels.get(tSelectedIndex)); } }); MenuItem tMenuItem5 = new MenuItem(tMenu, SWT.NONE); tMenuItem5.setText("Show packet queue"); tMenuItem5.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent pEvent) { //Logging.log(this, "Default selected: " + pEvent); showPacketQueue(tfComChannels.get(tSelectedIndex)); } public void widgetSelected(SelectionEvent pEvent) { //Logging.log(this, "Widget selected: " + pEvent); showPacketQueue(tfComChannels.get(tSelectedIndex)); } }); MenuItem tMenuItem6 = new MenuItem(tMenu, SWT.NONE); tMenuItem6.setText("Show shared routing table"); tMenuItem6.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent pEvent) { //Logging.log(this, "Default selected: " + pEvent); showSharedRoutes(tfComChannels.get(tSelectedIndex)); } public void widgetSelected(SelectionEvent pEvent) { //Logging.log(this, "Widget selected: " + pEvent); showSharedRoutes(tfComChannels.get(tSelectedIndex)); } }); MenuItem tMenuItem7 = new MenuItem(tMenu, SWT.NONE); tMenuItem7.setText("Show reported routing table"); tMenuItem7.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent pEvent) { //Logging.log(this, "Default selected: " + pEvent); showReportedRoutes(tfComChannels.get(tSelectedIndex)); } public void widgetSelected(SelectionEvent pEvent) { //Logging.log(this, "Widget selected: " + pEvent); showReportedRoutes(tfComChannels.get(tSelectedIndex)); } }); tTable.setMenu(tMenu); } } }); } private void showAssignedPeerHRMIDs(ComChannel pComChannel) { Logging.log(this, "Assigned peer HRMIDs of: " + pComChannel); int i = 0; for (HRMID tHRMID : pComChannel.getAssignedPeerHRMIDs()){ Logging.log(this, " ..[" + i + "]: " + tHRMID); i++; } } private void showPacketQueue(ComChannel pComChannel) { Logging.log(this, "Remaining packets in queue of: " + pComChannel); int i = 0; for (SignalingMessageHrm tPacket : pComChannel.getPacketQueue()){ Logging.log(this, " ..[" + i + "]: " + tPacket); i++; } } private void showSharedRoutes(ComChannel pComChannel) { Logging.log(this, "Shared routing table received via: " + pComChannel); int i = 0; for (RoutingEntry tEntry : pComChannel.getSharedRoutingTable()){ Logging.log(this, " ..[" + i + "]: " + tEntry); Logging.log(this, " ..cause:"); int j = 0; for (String tCauseString : tEntry.getCause()){ Logging.trace(this, " ..[" + j + "]: " + tCauseString); j++; } i++; } } private void showReportedRoutes(ComChannel pComChannel) { Logging.log(this, "Reported routing table received via: " + pComChannel); int i = 0; for (RoutingEntry tEntry : pComChannel.getReportedRoutingTable()){ Logging.log(this, " ..[" + i + "]: " + tEntry); Logging.log(this, " ..cause:"); int j = 0; for (String tCauseString : tEntry.getCause()){ Logging.trace(this, " ..[" + j + "]: " + tCauseString); j++; } i++; } } private void showPeerHRMIDs(ComChannel pComChannel) { Logging.log(this, "Peer HRMIDs of: " + pComChannel); int i = 0; for (HRMID tHRMID : pComChannel.getPeerHRMIDs()){ Logging.log(this, " ..[" + i + "]: " + tHRMID); i++; } } private void showSession(ComChannel pComChannel) { Logging.log(this, "Session for: " + pComChannel); Logging.log(this, " ..session: " + pComChannel.getParentComSession()); LinkedList<ComChannel> tChannels = pComChannel.getParentComSession().getAllComChannels(); for(ComChannel tComChannel : tChannels){ Logging.log(this, " ..channel: " + tComChannel); } tChannels = pComChannel.getParentComSession().getAllFormerChannels(); for(ComChannel tComChannel : tChannels){ Logging.log(this, " ..former channel: " + tComChannel); } } private void showPackets(ComChannel pComChannel) { Logging.log(this, "Packet I/O for: " + pComChannel); LinkedList<ComChannelPacketMetaData> tPacketsMetaData = pComChannel.getSeenPackets(); if(tPacketsMetaData != null){ int i = 0; for (ComChannelPacketMetaData tPacketMetaData: tPacketsMetaData){ if(tPacketMetaData.getPacket() instanceof AnnounceCoordinator){ AnnounceCoordinator tAnnounceCoordinatorPacket = (AnnounceCoordinator)tPacketMetaData.getPacket(); Logging.log(this, " ..[" + i + "] (" + (tPacketMetaData.wasSent() ? "S" : "R") + " @ " + tPacketMetaData.getTimetstamp() + "): " + tPacketMetaData.getPacket() + ", passed clusters: " + tAnnounceCoordinatorPacket.getGUIPassedClusters()+ ", passed nodes: " + tAnnounceCoordinatorPacket.getPassedNodes()); }else{ Logging.log(this, " ..[" + i + "] (" + (tPacketMetaData.wasSent() ? "S" : "R") + " @ " + tPacketMetaData.getTimetstamp() + "): " + tPacketMetaData.getPacket()); } i++; } } } private void showLinkActivationEvents(ComChannel pComChannel) { Logging.log(this, "Link activation events for: " + pComChannel + pComChannel.getDescriptionLinkActivation()); } private void showRoutingEntryCause(RoutingEntry pRoutingEntry) { Logging.log(this, "Cause for: " + pRoutingEntry); int i = 0; for (String tCauseString : pRoutingEntry.getCause()){ Logging.trace(this, " ..[" + i + "]: " + tCauseString); i++; } } private void printNAME(Composite pParent, ControlEntity pEntity) { Composite tContainerName = new Composite(pParent, SWT.NONE); GridLayout tLayout1 = new GridLayout(2, false); tContainerName.setLayout(tLayout1); /** * name part 0: front image */ if(pEntity instanceof Coordinator){ String tImagePath = ""; try { tImagePath = Resources.locateInPlugin(PLUGIN_ID, PATH_ICONS, "Coordinator_Level" + Integer.toString(pEntity.getHierarchyLevel().getValue()) + ".gif"); } catch (FileNotFoundException e) { //ignore } //Logging.log(this, "Loading front image: " + tImagePath); Image tFrontImage = new Image(mDisplay, tImagePath); Label tFronImageLabel = new Label(tContainerName, SWT.NONE); tFronImageLabel.setSize(16, 20); tFronImageLabel.setImage(tFrontImage); tFronImageLabel.setLayoutData(createGridData(true, 1)); } if(pEntity instanceof Cluster){ String tImagePath = ""; try { tImagePath = Resources.locateInPlugin(PLUGIN_ID, PATH_ICONS, "Cluster_Level" + Integer.toString(pEntity.getHierarchyLevel().getValue()) + ".png"); } catch (FileNotFoundException e) { //ignore } //Logging.log(this, "Loading front image: " + tImagePath); Image tFrontImage = new Image(mDisplay, tImagePath); Label tFronImageLabel = new Label(tContainerName, SWT.NONE); tFronImageLabel.setSize(45, 20); tFronImageLabel.setImage(tFrontImage); tFronImageLabel.setLayoutData(createGridData(true, 1)); } /** * name part 1: the name */ StyledText tClusterLabel = new StyledText(tContainerName, SWT.BORDER);; tClusterLabel.setForeground(new Color(mShell.getDisplay(), 0, 0, 0)); boolean tClusterHeadWithoutCoordinator = false; boolean tClusterMemberOfInactiveCluster = false; /** * BACKGROUND COLOR */ if (GUI_SHOW_COLORED_BACKGROUND_FOR_CONTROL_ENTITIES){ boolean tBackgroundSet = false; if (pEntity instanceof Cluster){ Cluster tCluster =(Cluster) pEntity; if ((tCluster.getElector() != null) && (tCluster.getElector().finished())){ if(tCluster.hasLocalCoordinator()){ tClusterLabel.setBackground(new Color(mShell.getDisplay(), 111, 222, 111)); }else{ tClusterHeadWithoutCoordinator = true; tClusterLabel.setBackground(new Color(mShell.getDisplay(), 111, 222, 222)); } tBackgroundSet = true; } }else{ if(pEntity instanceof ClusterMember){ ClusterMember tClusterMember = (ClusterMember)pEntity; tClusterMemberOfInactiveCluster = !tClusterMember.isActiveCluster(); if(tClusterMemberOfInactiveCluster){ tClusterLabel.setBackground(new Color(mShell.getDisplay(), 111, 222, 222)); }else{ tClusterLabel.setBackground(new Color(mShell.getDisplay(), 151, 222, 151)); } tBackgroundSet = true; } } if (pEntity instanceof Coordinator){ Coordinator tCoordinator =(Coordinator) pEntity; if ((tCoordinator.isClustered()) || (tCoordinator.getHierarchyLevel().isHighest())){ tClusterLabel.setBackground(new Color(mShell.getDisplay(), 111, 222, 111)); tBackgroundSet = true; } } if (!tBackgroundSet){ tClusterLabel.setBackground(new Color(mShell.getDisplay(), 222, 111, 111)); } }else{ tClusterLabel.setBackground(new Color(mShell.getDisplay(), 222, 222, 222)); } /** * TEXT */ String tFormerHRMIDs = (pEntity.getDescriptionFormerHRMIDs() != "" ? " (FormerHRMIDs: " + pEntity.getDescriptionFormerHRMIDs() + ")" : ""); String tNetworkInterface = ""; String tL0HRMID = ""; if (pEntity instanceof ClusterMember){ ClusterMember tClusterMember = (ClusterMember) pEntity; tNetworkInterface = (tClusterMember.getBaseHierarchyLevelNetworkInterface() != null ? " (" + tClusterMember.getBaseHierarchyLevelNetworkInterface().toString() + ")": ""); if(tClusterMember.getL0HRMID() != null){ tL0HRMID = " (L0-HRMID: " + tClusterMember.getL0HRMID().toString() + ")"; } } if (pEntity instanceof Cluster){ Cluster tCluster = (Cluster) pEntity; boolean tClusterCanBeActive = tCluster.getElector().isAllowedToWin(); tClusterLabel.setText(pEntity.toString() + " Priority=" + pEntity.getPriority().getValue() + " UniqueID=" + tCluster.getClusterID() + " Election=" + tCluster.getElector().getElectionStateStr() + (tClusterHeadWithoutCoordinator ? " (inactive cluster)" : "") + (!tClusterCanBeActive ? " [ZOMBIE]" : "") + (tCluster.getDescriptionFormerGUICoordinatorIDs() != "" ? " (Former Coordinators=" + tCluster.getDescriptionFormerGUICoordinatorIDs() + ")" : "") + tFormerHRMIDs + tNetworkInterface + tL0HRMID); }else{ if(pEntity instanceof Coordinator){ Coordinator tCoordinator = (Coordinator)pEntity; tClusterLabel.setText(pEntity.toString() + " Priority=" + pEntity.getPriority().getValue() + tFormerHRMIDs + " Announces=" + tCoordinator.countAnnounces() + " AddressBroadcasts=" + tCoordinator.getCluster().countAddressBroadcasts()); }else{ tClusterLabel.setText(pEntity.toString() + " Priority=" + pEntity.getPriority().getValue() + tFormerHRMIDs + (tClusterMemberOfInactiveCluster ? " (inactive cluster)" : "") + tNetworkInterface + tL0HRMID); } } /** * STYLE/LAYOUT */ StyleRange style1 = new StyleRange(); style1.start = 0; style1.length = tClusterLabel.getText().length(); style1.fontStyle = SWT.BOLD; tClusterLabel.setStyleRange(style1); if((pEntity instanceof Coordinator) || (pEntity instanceof Cluster)){ tClusterLabel.setLayoutData(createGridData(true, 1)); }else{ tClusterLabel.setLayoutData(createGridData(true, 2)); } } /** * Draws GUI elements for depicting cluster information. * * @param pCluster selected cluster */ private void printClusterMember(Composite pParent, ClusterMember pClusterMember) { // on which hierarchy level are we? int tHierarchyLevel = pClusterMember.getHierarchyLevel().getValue(); if (HRM_VIEWER_DEBUGGING) Logging.log(this, "Printing cluster (member) \"" + pClusterMember.toString() +"\""); /** * GUI part 0: name of the cluster */ printNAME(pParent, pClusterMember); /** * GUI part 1: tool box */ if(pClusterMember != null) { ToolBar tToolbar = new ToolBar(pParent, SWT.NONE); if (HRM_VIEWER_SHOW_SINGLE_ENTITY_ELECTION_CONTROLS){ if ((pClusterMember.getElector() != null) && (!pClusterMember.getElector().finished())){ ToolItem toolItem1 = new ToolItem(tToolbar, SWT.PUSH); toolItem1.setText("[Elect coordinator]"); toolItem1.addListener(SWT.Selection, new ListenerElectCoordinator(this, pClusterMember)); } } ToolItem toolItem2 = new ToolItem(tToolbar, SWT.PUSH); toolItem2.setText("[Elect all level " + tHierarchyLevel + " coordinators]"); toolItem2.addListener(SWT.Selection, new ListenerElectHierarchyLevelCoordinators(this, pClusterMember)); tToolbar.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1)); } /** * GUI part 2: table about comm. channels */ printComChannels(pParent, pClusterMember); Label separator = new Label (pParent, SWT.SEPARATOR | SWT.HORIZONTAL); separator.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 1, 1)); separator.setVisible(true); } @SuppressWarnings("deprecation") @Override public void init(IEditorSite pSite, IEditorInput pInput) throws PartInitException { setSite(pSite); setInput(pInput); // get selected object to show in editor Object tInputObject; if(pInput instanceof EditorInput) { tInputObject = ((EditorInput) pInput).getObj(); } else { tInputObject = null; } if (HRM_VIEWER_DEBUGGING) Logging.log(this, "Initiating HRM viewer " + tInputObject + " (class=" + tInputObject.getClass() +")"); if(tInputObject != null) { // update title of editor setTitle(tInputObject.toString()); if(tInputObject instanceof HRMController) { mHRMController = (HRMController) tInputObject; } else { throw new PartInitException("Invalid input object " +tInputObject +". Bus expected."); } // update name of editor part setPartName(toString()); } else { throw new PartInitException("No input for editor."); } // register this GUI at the corresponding HRMController if (mHRMController != null){ mHRMController.registerGUI(this); } } /** * overloaded dispose() function for unregistering from the HRMController instance */ public void dispose() { // unregister this GUI at the corresponding HRMController if (mHRMController != null){ mHRMController.unregisterGUI(this); } // call the original implementation super.dispose(); } @Override public void doSave(IProgressMonitor arg0) { } @Override public void doSaveAs() { } @Override public boolean isDirty() { return false; } @Override public boolean isSaveAsAllowed() { return false; } @Override public void setFocus() { } @Override public Object getAdapter(Class required) { if(getClass().equals(required)) return this; Object res = super.getAdapter(required); if(res == null) { res = Platform.getAdapterManager().getAdapter(this, required); if(res == null) res = Platform.getAdapterManager().getAdapter(mHRMController, required); } return res; } /** * Thread main function, which is used if an asynchronous GUI update is needed. * In this case, the GUI update has to be delayed in order to do it within the main GUI thread. */ @Override public void run() { resetGUI(); } /** * Destroys the content of the routing table */ private void updateRoutingTable() { + int tOldSelectedIndex = mTableRoutingTable.getSelectionIndex(); + mTableRoutingTable.removeAll(); RoutingTable tRoutingTable = mHRMController.getHRS().getRoutingTable(); if (HRM_VIEWER_DEBUGGING){ Logging.log(this, "Found " + tRoutingTable.size() + " entries in the local routing table"); } Color tColLoop = new Color(mDisplay, 210, 210, 250); Color tColNeighbor = new Color(mDisplay, 210, 250, 210); Color tColGeneral = new Color(mDisplay, 250, 210, 210); if ((tRoutingTable != null) && (!tRoutingTable.isEmpty())) { int tRowNumber = 0; for(RoutingEntry tEntry : tRoutingTable) { if ((HRMConfig.DebugOutput.GUI_SHOW_RELATIVE_ADDRESSES) || (tEntry.getDest() == null) || (!tEntry.getDest().isRelativeAddress())){ // create the table row TableItem tTableRow = new TableItem(mTableRoutingTable, SWT.NONE, tRowNumber); /** * Column 0: destination */ tTableRow.setText(0, tEntry.getDest() != null ? tEntry.getDest().toString() : "undef."); /** * Column 1: next hop */ if (tEntry.getNextHop() != null) { tTableRow.setText(1, tEntry.getNextHop().toString()); }else{ tTableRow.setText(1, "??"); } /** * Column 2: hop costs */ if (tEntry.getHopCount() != RoutingEntry.NO_HOP_COSTS){ tTableRow.setText(2, Integer.toString(tEntry.getHopCount())); }else{ tTableRow.setText(2, "none"); } /** * Column 3: utilization */ if (tEntry.getUtilization() != RoutingEntry.NO_UTILIZATION){ tTableRow.setText(3, Float.toString(tEntry.getUtilization() * 100)); }else{ tTableRow.setText(3, "N/A"); } /** * Column 4: min. delay */ if (tEntry.getMinDelay() != RoutingEntry.NO_DELAY){ tTableRow.setText(4, Long.toString(tEntry.getMinDelay())); }else{ tTableRow.setText(4, "none"); } /** * Column 5: max. data rate */ if (tEntry.getMaxDataRate() != RoutingEntry.INFINITE_DATARATE){ tTableRow.setText(5, Long.toString(tEntry.getMaxDataRate())); }else{ tTableRow.setText(5, "inf."); } /** * Column 6: loopback? */ if (tEntry.isLocalLoop()){ tTableRow.setText(6, "yes"); }else{ tTableRow.setText(6, "no"); } /** * Column 7: direct neighbor? */ if (tEntry.isRouteToDirectNeighbor()){ tTableRow.setText(7, "yes"); }else{ tTableRow.setText(7, "no"); } /** * Column 8: source */ if (tEntry.getSource() != null) { tTableRow.setText(8, tEntry.getSource().toString()); }else{ tTableRow.setText(8, "??"); } /** * Column 9: next hop L2Address */ if (tEntry.getNextHopL2Address() != null) { tTableRow.setText(9, tEntry.getNextHopL2Address().toString()); }else{ tTableRow.setText(9, "??"); } /** * Column 10: timeout */ if (tEntry.getTimeout() > 0) { tTableRow.setText(10, Double.toString(tEntry.getTimeout())); }else{ tTableRow.setText(10, "none"); } /** * Cells coloring */ for(int i = 0; i < 11; i++){ if(tEntry.isLocalLoop()){ tTableRow.setBackground(i, tColLoop); }else if (tEntry.isRouteToDirectNeighbor()){ tTableRow.setBackground(i, tColNeighbor); }else{ tTableRow.setBackground(i, tColGeneral); } } tRowNumber++; } } + mTableRoutingTable.setItemCount(tRowNumber); } + if(tOldSelectedIndex > 0){ + mTableRoutingTable.select(tOldSelectedIndex); + } + /** * The table context menu */ final RoutingTable tfRoutingTable = tRoutingTable; mTableRoutingTable.addMenuDetectListener(new MenuDetectListener() { @Override public void menuDetected(MenuDetectEvent pEvent) { final int tSelectedIndex = mTableRoutingTable.getSelectionIndex(); // was there a row selected? if (tSelectedIndex != -1){ // identify which row was clicked. TableItem tSelectedRow = mTableRoutingTable.getItem(tSelectedIndex); tSelectedRow.getData(); //Logging.log(this, "Context menu for comm. channels of entity: " + pControlEntity + ", index: " + tSelectedIndex + ", row data: " + tSelectedRow); /** * Create the context menu */ Menu tMenu = new Menu(mTableRoutingTable); MenuItem tMenuItem = new MenuItem(tMenu, SWT.NONE); tMenuItem.setText("Show cause for this entry"); tMenuItem.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent pEvent) { //Logging.log(this, "Default selected: " + pEvent); showRoutingEntryCause(tfRoutingTable.get(tSelectedIndex)); } public void widgetSelected(SelectionEvent pEvent) { //Logging.log(this, "Widget selected: " + pEvent); showRoutingEntryCause(tfRoutingTable.get(tSelectedIndex)); } }); mTableRoutingTable.setMenu(tMenu); } } }); } /** * Resets the routing table and updates it */ private synchronized void redrawRoutingTable() { updateRoutingTable(); mNextGUIUpdateResetsOnlyRoutingTable = false; } private synchronized void redrawGUI() { if(!mScroller.isDisposed()){ Point tOldScrollPosition = mScroller.getOrigin(); destroyPartControl(); createPartControl(mShell); mScroller.setOrigin(tOldScrollPosition); }else{ Logging.warn(this, "Scroller is already disposed"); } } /** * Resets the GUI and updates everything in this EditorPart */ private void resetGUI() { // store the time of this (last) GUI update mTimestampLastGUIUpdate = mHRMController.getSimulationTime(); // reset stored GUI update time mTimeNextGUIUpdate = 0; if(!mDisplay.isDisposed()) { if(Thread.currentThread() != mDisplay.getThread()) { //switches to different thread mDisplay.asyncExec(this); } else { if (mNextGUIUpdateResetsOnlyRoutingTable){ redrawRoutingTable(); }else{ redrawGUI(); } } } } /** * Function for receiving notifications about changes in the corresponding HRMController instance */ @Override public void update(Observable pSource, Object pReason) { if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){ if(pReason instanceof RoutingEntry){ RoutingEntry tEntry = (RoutingEntry)pReason; Logging.log(this, "Got notification from " + pSource + " because of:"); Logging.log(this, " ..entry: \"" + tEntry + "\""); Logging.log(this, " ..cause: " + tEntry.getCause()); }else{ Logging.log(this, "Got notification from " + pSource + " because of \"" + pReason + "\""); } } if(pReason instanceof RoutingEntry){ startRoutingTableUpdateTimer(); }else{ startGUIUpdateTimer(); } } private synchronized void startRoutingTableUpdateTimer() { if (HRMConfig.DebugOutput.GUI_SHOW_NOTIFICATIONS){ Logging.log(this, "Got a routing table update"); } mNextGUIUpdateResetsOnlyRoutingTable = true; // trigger GUI update startGUIUpdateTimer(); } /** * Starts the timer for the "update GUI" event. * If the timer is already started nothing is done. */ private synchronized void startGUIUpdateTimer() { // is a GUI update already planned? if (mTimeNextGUIUpdate == 0){ // when was the last GUI update? is the time period okay for a new update? -> determine a timeout for a new GUI update double tNow = mHRMController.getSimulationTime(); double tTimeout = mTimestampLastGUIUpdate.longValue() + HRMConfig.DebugOutput.GUI_NODE_DISPLAY_UPDATE_INTERVAL; if ((mTimestampLastGUIUpdate.doubleValue() == 0) || (tNow > tTimeout)){ mTimeNextGUIUpdate = tNow; // register next trigger mHRMController.getAS().getTimeBase().scheduleIn(0, this); }else{ mTimeNextGUIUpdate = tTimeout; // register next trigger mHRMController.getAS().getTimeBase().scheduleIn(tTimeout - tNow, this); } }else{ // timer is already started, we ignore the repeated request } } /** * This function is called when the event is fired by the main event system. */ @Override public void fire() { // reset stored GUI update time mTimeNextGUIUpdate = 0; // trigger GUI update resetGUI(); } /** * Returns a descriptive string about this object * * @return the descriptive string */ public String toString() { return "HRM viewer" + (mHRMController != null ? "@" + mHRMController.getNodeGUIName() : ""); } /** * Listener for electing coordinator for this cluster. */ private class ListenerElectCoordinator implements Listener { private ClusterMember ClusterMember = null; private HRMViewer mHRMViewer = null; private ListenerElectCoordinator(HRMViewer pHRMViewer, ClusterMember pClusterMember) { super(); ClusterMember = pClusterMember; mHRMViewer = pHRMViewer; } @Override public void handleEvent(Event event) { if (HRM_VIEWER_DEBUGGING){ Logging.log(this, "GUI-TRIGGER: Starting election for " + ClusterMember); } // start the election for the selected cluster ClusterMember.getElector().startElection(); } public String toString() { return mHRMViewer.toString() + "@" + getClass().getSimpleName(); } } /** * Listener for electing coordinators for all clusters on this hierarchy level. */ private class ListenerElectHierarchyLevelCoordinators implements Listener { private ClusterMember mClusterMember = null; private HRMViewer mHRMViewer = null; private ListenerElectHierarchyLevelCoordinators(HRMViewer pHRMViewer, ClusterMember pClusterMember) { super(); mClusterMember = pClusterMember; mHRMViewer = pHRMViewer; } @Override public void handleEvent(Event event) { // get the hierarchy level of the selected cluster HierarchyLevel tLocalClusterLevel = mClusterMember.getHierarchyLevel(); // iterate over all HRMControllers for(HRMController tHRMController : HRMController.getALLHRMControllers()) { // iterate over all clusters from the current HRMController for (Cluster tCluster: tHRMController.getAllClusters()) { // check the hierarchy of the found cluster if (tLocalClusterLevel.equals(tCluster.getHierarchyLevel())){ if (HRM_VIEWER_DEBUGGING){ Logging.log(this, "GUI-TRIGGER: Starting election for " + tCluster); } // start the election for the found cluster tCluster.getElector().startElection(); } } } } public String toString() { return mHRMViewer.toString() + "@" + getClass().getSimpleName(); } } /** * Listener for clustering the network on a defined hierarchy level. */ private class ListenerClusterHierarchyLevel implements Listener { private Coordinator mCoordinator = null; private HRMViewer mHRMViewer = null; private ListenerClusterHierarchyLevel(HRMViewer pHRMViewer, Coordinator pCoordinator) { super(); mCoordinator = pCoordinator; mHRMViewer = pHRMViewer; } @Override public void handleEvent(Event event) { // get the hierarchy level of the selected cluster HierarchyLevel tLocalClusterLevel = mCoordinator.getHierarchyLevel(); // check if we are at the max. hierarchy height if(!tLocalClusterLevel.isHighest()) { // iterate over all HRMControllers for(HRMController tHRMController : HRMController.getALLHRMControllers()) { tHRMController.cluster(null, new HierarchyLevel(this, tLocalClusterLevel.getValue() + 1)); } }else{ Logging.err(this, "Maximum hierarchy height " + (tLocalClusterLevel.getValue()) + " is already reached."); } } public String toString() { return mHRMViewer.toString() + "@" + getClass().getSimpleName(); } } /** * Listener for clustering the network, including the current cluster's coordinator and its siblings. */ private class ListenerClusterHierarchy implements Listener { private Coordinator mCoordinator = null; private HRMViewer mHRMViewer = null; private ListenerClusterHierarchy(HRMViewer pHRMViewer, Coordinator pCoordinator) { super(); mCoordinator = pCoordinator; mHRMViewer = pHRMViewer; } @Override public void handleEvent(Event event) { // check if we are at the max. hierarchy height if(!mCoordinator.getHierarchyLevel().isHighest()) { if (mCoordinator != null){ if (HRM_VIEWER_DEBUGGING){ Logging.log(this, "GUI-TRIGGER: Starting clustering for coordinator " + mCoordinator); } // start the clustering of the selected cluster's coordinator and its neighbors mHRMController.cluster(null, new HierarchyLevel(this, mCoordinator.getHierarchyLevel().getValue() + 1)); }else{ Logging.err(this, "Coordinator is invalid, skipping clustering request"); } }else{ Logging.err(this, "Maximum hierarchy height " + (mCoordinator.getHierarchyLevel().getValue()) + " is already reached."); } } public String toString() { return mHRMViewer.toString() + "@" + getClass().getSimpleName(); } } }
false
false
null
null
diff --git a/src/main/java/net/minecraft/src/RenderItem.java b/src/main/java/net/minecraft/src/RenderItem.java index 0ec477d5..e98523c2 100644 --- a/src/main/java/net/minecraft/src/RenderItem.java +++ b/src/main/java/net/minecraft/src/RenderItem.java @@ -1,547 +1,549 @@ package net.minecraft.src; import java.util.Random; import net.minecraft.client.Minecraft; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; // Spout Start import org.newdawn.slick.opengl.Texture; import org.spoutcraft.api.block.design.BlockDesign; import org.spoutcraft.api.material.MaterialData; import org.spoutcraft.client.io.CustomTextureManager; // Spout End public class RenderItem extends Render { private RenderBlocks renderBlocks = new RenderBlocks(); /** The RNG used in RenderItem (for bobbing itemstacks on the ground) */ private Random random = new Random(); public boolean field_77024_a = true; /** Defines the zLevel of rendering of item on GUI. */ public float zLevel = 0.0F; public static boolean field_82407_g = false; public RenderItem() { this.shadowSize = 0.15F; this.shadowOpaque = 0.75F; } // Spout Start @Override protected void loadTexture(String texture) { if (this.renderManager != null && this.renderManager.renderEngine != null) { int textureId = this.renderManager.renderEngine.getTexture(texture); if (textureId >= 0) { this.renderManager.renderEngine.bindTexture(textureId); } } } // Spout End /** * Renders the item */ public void doRenderItem(EntityItem par1EntityItem, double par2, double par4, double par6, float par8, float par9) { // Spout Start // Sanity Checks if (par1EntityItem == null || par1EntityItem.item == null) { return; } // Spout End this.random.setSeed(187L); ItemStack var10 = par1EntityItem.item; if (var10.getItem() != null) { // GL11.glPushMatrix(); // Spout delate to later, if no custom design given float var11 = MathHelper.sin(((float)par1EntityItem.age + par9) / 10.0F + par1EntityItem.hoverStart) * 0.1F + 0.1F; float var12 = (((float)par1EntityItem.age + par9) / 20.0F + par1EntityItem.hoverStart) * (180F / (float)Math.PI); byte var13 = 1; if (par1EntityItem.item.stackSize > 1) { var13 = 2; } if (par1EntityItem.item.stackSize > 5) { var13 = 3; } if (par1EntityItem.item.stackSize > 20) { var13 = 4; } // Spout Start boolean custom = false; BlockDesign design = null; if (var10.itemID == 318) { org.spoutcraft.api.material.CustomItem item = MaterialData.getCustomItem(var10.getItemDamage()); if (item != null) { String textureURI = item.getTexture(); if (textureURI == null) { org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage()); design = block != null ? block.getBlockDesign() : null; textureURI = design != null ? design.getTexureURL() : null; } if (textureURI != null) { Texture texture = CustomTextureManager.getTextureFromUrl(item.getAddon().getDescription().getName(), textureURI); if (texture != null) { GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID()); custom = true; } } } /* * org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage()); design = block != null ? block.getBlockDesign() : null; if (design != null && * design.getTextureAddon() != null && design.getTexureURL() != null) { Texture texture = CustomTextureManager.getTextureFromUrl(design.getTextureAddon(), design.getTexureURL()); if * (texture != null) { this.renderManager.renderEngine.bindTexture(texture.getTextureID()); custom = true; } } */ } GL11.glEnable(GL12.GL_RESCALE_NORMAL); if (design != null && custom) { //GL11.glScalef(0.25F, 0.25F, 0.25F); design.renderItemstack((org.spoutcraft.api.entity.Item)par1EntityItem.spoutEnty, (float)par2, (float)(par4 + var11), (float)par6, var12, 0.25F, random); } else { GL11.glPushMatrix(); // the push from above if (!custom) { if (var10.itemID < 256) { this.loadTexture("/terrain.png"); } else { this.loadTexture("/gui/items.png"); } } // Spout End GL11.glTranslatef((float)par2, (float)par4 + var11, (float)par6); GL11.glEnable(GL12.GL_RESCALE_NORMAL); Block var14 = Block.blocksList[var10.itemID]; int var16; float var19; float var20; float var24; if (var14 != null && RenderBlocks.renderItemIn3d(var14.getRenderType())) { GL11.glRotatef(var12, 0.0F, 1.0F, 0.0F); if (field_82407_g) { GL11.glScalef(1.25F, 1.25F, 1.25F); GL11.glTranslatef(0.0F, 0.05F, 0.0F); GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); } this.loadTexture("/terrain.png"); float var22 = 0.25F; var16 = var14.getRenderType(); if (var16 == 1 || var16 == 19 || var16 == 12 || var16 == 2) { var22 = 0.5F; } GL11.glScalef(var22, var22, var22); for (int var23 = 0; var23 < var13; ++var23) { GL11.glPushMatrix(); if (var23 > 0) { var24 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22; var19 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22; var20 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22; GL11.glTranslatef(var24, var19, var20); } var24 = 1.0F; this.renderBlocks.renderBlockAsItem(var14, var10.getItemDamage(), var24); GL11.glPopMatrix(); } } else { int var15; float var17; if (var10.getItem().requiresMultipleRenderPasses()) { if (field_82407_g) { GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F); GL11.glTranslatef(0.0F, -0.05F, 0.0F); GL11.glDisable(GL11.GL_LIGHTING); } else { GL11.glScalef(0.5F, 0.5F, 0.5F); } this.loadTexture("/gui/items.png"); for (var15 = 0; var15 <= 1; ++var15) { var16 = var10.getItem().getIconFromDamageForRenderPass(var10.getItemDamage(), var15); var17 = 1.0F; if (this.field_77024_a) { int var18 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, var15); var19 = (float)(var18 >> 16 & 255) / 255.0F; var20 = (float)(var18 >> 8 & 255) / 255.0F; float var21 = (float)(var18 & 255) / 255.0F; GL11.glColor4f(var19 * var17, var20 * var17, var21 * var17, 1.0F); } this.func_77020_a(var16, var13); } } else { if (field_82407_g) { GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F); GL11.glTranslatef(0.0F, -0.05F, 0.0F); GL11.glDisable(GL11.GL_LIGHTING); } else { GL11.glScalef(0.5F, 0.5F, 0.5F); } var15 = var10.getIconIndex(); if (var14 != null) { this.loadTexture("/terrain.png"); } else { - this.loadTexture("/gui/items.png"); + if (!custom) { + this.loadTexture("/gui/items.png"); + } } if (this.field_77024_a) { var16 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, 0); var17 = (float)(var16 >> 16 & 255) / 255.0F; var24 = (float)(var16 >> 8 & 255) / 255.0F; var19 = (float)(var16 & 255) / 255.0F; var20 = 1.0F; GL11.glColor4f(var17 * var20, var24 * var20, var19 * var20, 1.0F); } // Spout Start this.renderItemBillboard(var15, var13, custom); // Spout End } } GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); } // Spout } } // Spout Start private void func_77020_a(int var1, int var2) { renderItemBillboard(var1, var2, false); } private void renderItemBillboard(int par1, int par2, boolean customTexture) { // Spout End Tessellator var3 = Tessellator.instance; float var4 = (float)(par1 % 16 * 16 + 0) / 256.0F; float var5 = (float)(par1 % 16 * 16 + 16) / 256.0F; float var6 = (float)(par1 / 16 * 16 + 0) / 256.0F; float var7 = (float)(par1 / 16 * 16 + 16) / 256.0F; float var8 = 1.0F; float var9 = 0.5F; float var10 = 0.25F; // Spout Start if (customTexture) { var4 = 0F; var5 = 1F; var6 = 1F; var7 = 0F; } // Spout End for (int var11 = 0; var11 < par2; ++var11) { GL11.glPushMatrix(); if (var11 > 0) { float var12 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F; float var13 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F; float var14 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.3F; GL11.glTranslatef(var12, var13, var14); } GL11.glRotatef(180.0F - this.renderManager.playerViewY, 0.0F, 1.0F, 0.0F); var3.startDrawingQuads(); var3.setNormal(0.0F, 1.0F, 0.0F); var3.addVertexWithUV((double)(0.0F - var9), (double)(0.0F - var10), 0.0D, (double)var4, (double)var7); var3.addVertexWithUV((double)(var8 - var9), (double)(0.0F - var10), 0.0D, (double)var5, (double)var7); var3.addVertexWithUV((double)(var8 - var9), (double)(1.0F - var10), 0.0D, (double)var5, (double)var6); var3.addVertexWithUV((double)(0.0F - var9), (double)(1.0F - var10), 0.0D, (double)var4, (double)var6); var3.draw(); GL11.glPopMatrix(); } } /** * Renders the item's icon or block into the UI at the specified position. */ public void renderItemIntoGUI(FontRenderer par1FontRenderer, RenderEngine par2RenderEngine, ItemStack par3ItemStack, int par4, int par5) { int var6 = par3ItemStack.itemID; int var7 = par3ItemStack.getItemDamage(); int var8 = par3ItemStack.getIconIndex(); int var10; float var12; float var13; float var16; // Spout Start boolean custom = false; BlockDesign design = null; if (var6 == 318) { org.spoutcraft.api.material.CustomItem item = MaterialData.getCustomItem(var7); if (item != null) { String textureURI = item.getTexture(); if (textureURI == null) { org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var7); design = block != null ? block.getBlockDesign() : null; textureURI = design != null ? design.getTexureURL() : null; } if (textureURI != null) { Texture texture = CustomTextureManager.getTextureFromUrl(item.getAddon().getDescription().getName(), textureURI); if (texture != null) { GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID()); custom = true; } } } } if (!custom) { if (var6 < 256) { loadTexture("/terrain.png"); } else { loadTexture("/gui/items.png"); } } if (design != null && custom) { design.renderItemOnHUD((float)(par4 - 2), (float)(par5 + 3), -3.0F + this.zLevel); } else if (var6 < 256 && RenderBlocks.renderItemIn3d(Block.blocksList[var6].getRenderType())) { // Spout End par2RenderEngine.bindTexture(par2RenderEngine.getTexture("/terrain.png")); Block var15 = Block.blocksList[var6]; GL11.glPushMatrix(); GL11.glTranslatef((float)(par4 - 2), (float)(par5 + 3), -3.0F + this.zLevel); GL11.glScalef(10.0F, 10.0F, 10.0F); GL11.glTranslatef(1.0F, 0.5F, 1.0F); GL11.glScalef(1.0F, 1.0F, -1.0F); GL11.glRotatef(210.0F, 1.0F, 0.0F, 0.0F); GL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F); var10 = Item.itemsList[var6].getColorFromItemStack(par3ItemStack, 0); var16 = (float)(var10 >> 16 & 255) / 255.0F; var12 = (float)(var10 >> 8 & 255) / 255.0F; var13 = (float)(var10 & 255) / 255.0F; if (this.field_77024_a) { GL11.glColor4f(var16, var12, var13, 1.0F); } GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); this.renderBlocks.useInventoryTint = this.field_77024_a; this.renderBlocks.renderBlockAsItem(var15, var7, 1.0F); this.renderBlocks.useInventoryTint = true; GL11.glPopMatrix(); } else { int var9; if (Item.itemsList[var6].requiresMultipleRenderPasses()) { GL11.glDisable(GL11.GL_LIGHTING); par2RenderEngine.bindTexture(par2RenderEngine.getTexture("/gui/items.png")); for (var9 = 0; var9 <= 1; ++var9) { var10 = Item.itemsList[var6].getIconFromDamageForRenderPass(var7, var9); int var11 = Item.itemsList[var6].getColorFromItemStack(par3ItemStack, var9); var12 = (float)(var11 >> 16 & 255) / 255.0F; var13 = (float)(var11 >> 8 & 255) / 255.0F; float var14 = (float)(var11 & 255) / 255.0F; if (this.field_77024_a) { GL11.glColor4f(var12, var13, var14, 1.0F); } this.renderTexturedQuad(par4, par5, var10 % 16 * 16, var10 / 16 * 16, 16, 16); } GL11.glEnable(GL11.GL_LIGHTING); } else if (var8 >= 0) { GL11.glDisable(GL11.GL_LIGHTING); if (var6 < 256) { par2RenderEngine.bindTexture(par2RenderEngine.getTexture("/terrain.png")); } else { par2RenderEngine.bindTexture(par2RenderEngine.getTexture("/gui/items.png")); } var9 = Item.itemsList[var6].getColorFromItemStack(par3ItemStack, 0); float var17 = (float)(var9 >> 16 & 255) / 255.0F; var16 = (float)(var9 >> 8 & 255) / 255.0F; var12 = (float)(var9 & 255) / 255.0F; if (this.field_77024_a) { GL11.glColor4f(var17, var16, var12, 1.0F); } // Spout Start if (custom) { Tessellator tes = Tessellator.instance; tes.startDrawingQuads(); tes.addVertexWithUV((double)(par4 + 0), (double)(par5 + 16), (double)0, 0, 0); tes.addVertexWithUV((double)(par4 + 16), (double)(par5 + 16), (double)0, 1, 0); tes.addVertexWithUV((double)(par4 + 16), (double)(par5 + 0), (double)0, 1, 1); tes.addVertexWithUV((double)(par4 + 0), (double)(par5 + 0), (double)0, 0, 1); tes.draw(); } else this.renderTexturedQuad(par4, par5, var8 % 16 * 16, var8 / 16 * 16, 16, 16); // Spout End GL11.glEnable(GL11.GL_LIGHTING); } } GL11.glEnable(GL11.GL_CULL_FACE); } /** * Render the item's icon or block into the GUI, including the glint effect. */ public void renderItemAndEffectIntoGUI(FontRenderer par1FontRenderer, RenderEngine par2RenderEngine, ItemStack par3ItemStack, int par4, int par5) { if (par3ItemStack != null) { this.renderItemIntoGUI(par1FontRenderer, par2RenderEngine, par3ItemStack, par4, par5); if (par3ItemStack != null && par3ItemStack.hasEffect()) { GL11.glDepthFunc(GL11.GL_GREATER); GL11.glDisable(GL11.GL_LIGHTING); GL11.glDepthMask(false); par2RenderEngine.bindTexture(par2RenderEngine.getTexture("%blur%/misc/glint.png")); this.zLevel -= 50.0F; GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_DST_COLOR, GL11.GL_DST_COLOR); GL11.glColor4f(0.5F, 0.25F, 0.8F, 1.0F); this.func_77018_a(par4 * 431278612 + par5 * 32178161, par4 - 2, par5 - 2, 20, 20); GL11.glDisable(GL11.GL_BLEND); GL11.glDepthMask(true); this.zLevel += 50.0F; GL11.glEnable(GL11.GL_LIGHTING); GL11.glDepthFunc(GL11.GL_LEQUAL); } } } private void func_77018_a(int par1, int par2, int par3, int par4, int par5) { for (int var6 = 0; var6 < 2; ++var6) { if (var6 == 0) { GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); } if (var6 == 1) { GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE); } float var7 = 0.00390625F; float var8 = 0.00390625F; float var9 = (float)(Minecraft.getSystemTime() % (long)(3000 + var6 * 1873)) / (3000.0F + (float)(var6 * 1873)) * 256.0F; float var10 = 0.0F; Tessellator var11 = Tessellator.instance; float var12 = 4.0F; if (var6 == 1) { var12 = -1.0F; } var11.startDrawingQuads(); var11.addVertexWithUV((double)(par2 + 0), (double)(par3 + par5), (double)this.zLevel, (double)((var9 + (float)par5 * var12) * var7), (double)((var10 + (float)par5) * var8)); var11.addVertexWithUV((double)(par2 + par4), (double)(par3 + par5), (double)this.zLevel, (double)((var9 + (float)par4 + (float)par5 * var12) * var7), (double)((var10 + (float)par5) * var8)); var11.addVertexWithUV((double)(par2 + par4), (double)(par3 + 0), (double)this.zLevel, (double)((var9 + (float)par4) * var7), (double)((var10 + 0.0F) * var8)); var11.addVertexWithUV((double)(par2 + 0), (double)(par3 + 0), (double)this.zLevel, (double)((var9 + 0.0F) * var7), (double)((var10 + 0.0F) * var8)); var11.draw(); } } /** * Renders the item's overlay information. Examples being stack count or damage on top of the item's image at the * specified position. */ public void renderItemOverlayIntoGUI(FontRenderer par1FontRenderer, RenderEngine par2RenderEngine, ItemStack par3ItemStack, int par4, int par5) { if (par3ItemStack != null) { if (par3ItemStack.stackSize > 1) { String var6 = "" + par3ItemStack.stackSize; GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_DEPTH_TEST); par1FontRenderer.drawStringWithShadow(var6, par4 + 19 - 2 - par1FontRenderer.getStringWidth(var6), par5 + 6 + 3, 16777215); GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_DEPTH_TEST); } // Spout Start NBTTagList list = par3ItemStack.getAllEnchantmentTagList(); short max = -1; short amnt = -1; if (list != null) { for (int i = 0; i < list.tagCount(); i++) { NBTBase tag = list.tagAt(i); if (tag instanceof NBTTagCompound) { NBTTagCompound ench = (NBTTagCompound)tag; short id = ench.getShort("id"); short lvl = ench.getShort("lvl"); if (id == 254) amnt = lvl; //Enchantment DURABILITY = new SpoutEnchantment(254); if (id == 255) max = lvl; //Enchantment MAX_DURABILITY = new SpoutEnchantment(255); } } } boolean override = max > 0 && amnt > 0 && amnt < max; if (par3ItemStack.isItemDamaged() || override) { int var11 = (int)Math.round(13.0D - (double)(override ? amnt : par3ItemStack.getItemDamageForDisplay()) * 13.0D / (double)(override ? max : par3ItemStack.getMaxDamage())); int var7 = (int)Math.round(255.0D - (double)(override ? amnt : par3ItemStack.getItemDamageForDisplay()) * 255.0D / (double)(override ? max : par3ItemStack.getMaxDamage())); // Spout End GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDisable(GL11.GL_TEXTURE_2D); Tessellator var8 = Tessellator.instance; int var9 = 255 - var7 << 16 | var7 << 8; int var10 = (255 - var7) / 4 << 16 | 16128; this.renderQuad(var8, par4 + 2, par5 + 13, 13, 2, 0); this.renderQuad(var8, par4 + 2, par5 + 13, 12, 1, var10); this.renderQuad(var8, par4 + 2, par5 + 13, var11, 1, var9); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } } } /** * Adds a quad to the tesselator at the specified position with the set width and height and color. Args: tessellator, * x, y, width, height, color */ private void renderQuad(Tessellator par1Tessellator, int par2, int par3, int par4, int par5, int par6) { par1Tessellator.startDrawingQuads(); par1Tessellator.setColorOpaque_I(par6); par1Tessellator.addVertex((double)(par2 + 0), (double)(par3 + 0), 0.0D); par1Tessellator.addVertex((double)(par2 + 0), (double)(par3 + par5), 0.0D); par1Tessellator.addVertex((double)(par2 + par4), (double)(par3 + par5), 0.0D); par1Tessellator.addVertex((double)(par2 + par4), (double)(par3 + 0), 0.0D); par1Tessellator.draw(); } /** * Adds a textured quad to the tesselator at the specified position with the specified texture coords, width and * height. Args: x, y, u, v, width, height */ public void renderTexturedQuad(int par1, int par2, int par3, int par4, int par5, int par6) { float var7 = 0.00390625F; float var8 = 0.00390625F; Tessellator var9 = Tessellator.instance; var9.startDrawingQuads(); var9.addVertexWithUV((double)(par1 + 0), (double)(par2 + par6), (double)this.zLevel, (double)((float)(par3 + 0) * var7), (double)((float)(par4 + par6) * var8)); var9.addVertexWithUV((double)(par1 + par5), (double)(par2 + par6), (double)this.zLevel, (double)((float)(par3 + par5) * var7), (double)((float)(par4 + par6) * var8)); var9.addVertexWithUV((double)(par1 + par5), (double)(par2 + 0), (double)this.zLevel, (double)((float)(par3 + par5) * var7), (double)((float)(par4 + 0) * var8)); var9.addVertexWithUV((double)(par1 + 0), (double)(par2 + 0), (double)this.zLevel, (double)((float)(par3 + 0) * var7), (double)((float)(par4 + 0) * var8)); var9.draw(); } /** * Actually renders the given argument. This is a synthetic bridge method, always casting down its argument and then * handing it off to a worker function which does the actual work. In all probabilty, the class Render is generic * (Render<T extends Entity) and this method has signature public void doRender(T entity, double d, double d1, * double d2, float f, float f1). But JAD is pre 1.5 so doesn't do that. */ public void doRender(Entity par1Entity, double par2, double par4, double par6, float par8, float par9) { this.doRenderItem((EntityItem)par1Entity, par2, par4, par6, par8, par9); } }
true
true
public void doRenderItem(EntityItem par1EntityItem, double par2, double par4, double par6, float par8, float par9) { // Spout Start // Sanity Checks if (par1EntityItem == null || par1EntityItem.item == null) { return; } // Spout End this.random.setSeed(187L); ItemStack var10 = par1EntityItem.item; if (var10.getItem() != null) { // GL11.glPushMatrix(); // Spout delate to later, if no custom design given float var11 = MathHelper.sin(((float)par1EntityItem.age + par9) / 10.0F + par1EntityItem.hoverStart) * 0.1F + 0.1F; float var12 = (((float)par1EntityItem.age + par9) / 20.0F + par1EntityItem.hoverStart) * (180F / (float)Math.PI); byte var13 = 1; if (par1EntityItem.item.stackSize > 1) { var13 = 2; } if (par1EntityItem.item.stackSize > 5) { var13 = 3; } if (par1EntityItem.item.stackSize > 20) { var13 = 4; } // Spout Start boolean custom = false; BlockDesign design = null; if (var10.itemID == 318) { org.spoutcraft.api.material.CustomItem item = MaterialData.getCustomItem(var10.getItemDamage()); if (item != null) { String textureURI = item.getTexture(); if (textureURI == null) { org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage()); design = block != null ? block.getBlockDesign() : null; textureURI = design != null ? design.getTexureURL() : null; } if (textureURI != null) { Texture texture = CustomTextureManager.getTextureFromUrl(item.getAddon().getDescription().getName(), textureURI); if (texture != null) { GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID()); custom = true; } } } /* * org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage()); design = block != null ? block.getBlockDesign() : null; if (design != null && * design.getTextureAddon() != null && design.getTexureURL() != null) { Texture texture = CustomTextureManager.getTextureFromUrl(design.getTextureAddon(), design.getTexureURL()); if * (texture != null) { this.renderManager.renderEngine.bindTexture(texture.getTextureID()); custom = true; } } */ } GL11.glEnable(GL12.GL_RESCALE_NORMAL); if (design != null && custom) { //GL11.glScalef(0.25F, 0.25F, 0.25F); design.renderItemstack((org.spoutcraft.api.entity.Item)par1EntityItem.spoutEnty, (float)par2, (float)(par4 + var11), (float)par6, var12, 0.25F, random); } else { GL11.glPushMatrix(); // the push from above if (!custom) { if (var10.itemID < 256) { this.loadTexture("/terrain.png"); } else { this.loadTexture("/gui/items.png"); } } // Spout End GL11.glTranslatef((float)par2, (float)par4 + var11, (float)par6); GL11.glEnable(GL12.GL_RESCALE_NORMAL); Block var14 = Block.blocksList[var10.itemID]; int var16; float var19; float var20; float var24; if (var14 != null && RenderBlocks.renderItemIn3d(var14.getRenderType())) { GL11.glRotatef(var12, 0.0F, 1.0F, 0.0F); if (field_82407_g) { GL11.glScalef(1.25F, 1.25F, 1.25F); GL11.glTranslatef(0.0F, 0.05F, 0.0F); GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); } this.loadTexture("/terrain.png"); float var22 = 0.25F; var16 = var14.getRenderType(); if (var16 == 1 || var16 == 19 || var16 == 12 || var16 == 2) { var22 = 0.5F; } GL11.glScalef(var22, var22, var22); for (int var23 = 0; var23 < var13; ++var23) { GL11.glPushMatrix(); if (var23 > 0) { var24 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22; var19 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22; var20 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22; GL11.glTranslatef(var24, var19, var20); } var24 = 1.0F; this.renderBlocks.renderBlockAsItem(var14, var10.getItemDamage(), var24); GL11.glPopMatrix(); } } else { int var15; float var17; if (var10.getItem().requiresMultipleRenderPasses()) { if (field_82407_g) { GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F); GL11.glTranslatef(0.0F, -0.05F, 0.0F); GL11.glDisable(GL11.GL_LIGHTING); } else { GL11.glScalef(0.5F, 0.5F, 0.5F); } this.loadTexture("/gui/items.png"); for (var15 = 0; var15 <= 1; ++var15) { var16 = var10.getItem().getIconFromDamageForRenderPass(var10.getItemDamage(), var15); var17 = 1.0F; if (this.field_77024_a) { int var18 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, var15); var19 = (float)(var18 >> 16 & 255) / 255.0F; var20 = (float)(var18 >> 8 & 255) / 255.0F; float var21 = (float)(var18 & 255) / 255.0F; GL11.glColor4f(var19 * var17, var20 * var17, var21 * var17, 1.0F); } this.func_77020_a(var16, var13); } } else { if (field_82407_g) { GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F); GL11.glTranslatef(0.0F, -0.05F, 0.0F); GL11.glDisable(GL11.GL_LIGHTING); } else { GL11.glScalef(0.5F, 0.5F, 0.5F); } var15 = var10.getIconIndex(); if (var14 != null) { this.loadTexture("/terrain.png"); } else { this.loadTexture("/gui/items.png"); } if (this.field_77024_a) { var16 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, 0); var17 = (float)(var16 >> 16 & 255) / 255.0F; var24 = (float)(var16 >> 8 & 255) / 255.0F; var19 = (float)(var16 & 255) / 255.0F; var20 = 1.0F; GL11.glColor4f(var17 * var20, var24 * var20, var19 * var20, 1.0F); } // Spout Start this.renderItemBillboard(var15, var13, custom); // Spout End } } GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); } // Spout } }
public void doRenderItem(EntityItem par1EntityItem, double par2, double par4, double par6, float par8, float par9) { // Spout Start // Sanity Checks if (par1EntityItem == null || par1EntityItem.item == null) { return; } // Spout End this.random.setSeed(187L); ItemStack var10 = par1EntityItem.item; if (var10.getItem() != null) { // GL11.glPushMatrix(); // Spout delate to later, if no custom design given float var11 = MathHelper.sin(((float)par1EntityItem.age + par9) / 10.0F + par1EntityItem.hoverStart) * 0.1F + 0.1F; float var12 = (((float)par1EntityItem.age + par9) / 20.0F + par1EntityItem.hoverStart) * (180F / (float)Math.PI); byte var13 = 1; if (par1EntityItem.item.stackSize > 1) { var13 = 2; } if (par1EntityItem.item.stackSize > 5) { var13 = 3; } if (par1EntityItem.item.stackSize > 20) { var13 = 4; } // Spout Start boolean custom = false; BlockDesign design = null; if (var10.itemID == 318) { org.spoutcraft.api.material.CustomItem item = MaterialData.getCustomItem(var10.getItemDamage()); if (item != null) { String textureURI = item.getTexture(); if (textureURI == null) { org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage()); design = block != null ? block.getBlockDesign() : null; textureURI = design != null ? design.getTexureURL() : null; } if (textureURI != null) { Texture texture = CustomTextureManager.getTextureFromUrl(item.getAddon().getDescription().getName(), textureURI); if (texture != null) { GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture.getTextureID()); custom = true; } } } /* * org.spoutcraft.api.material.CustomBlock block = MaterialData.getCustomBlock(var10.getItemDamage()); design = block != null ? block.getBlockDesign() : null; if (design != null && * design.getTextureAddon() != null && design.getTexureURL() != null) { Texture texture = CustomTextureManager.getTextureFromUrl(design.getTextureAddon(), design.getTexureURL()); if * (texture != null) { this.renderManager.renderEngine.bindTexture(texture.getTextureID()); custom = true; } } */ } GL11.glEnable(GL12.GL_RESCALE_NORMAL); if (design != null && custom) { //GL11.glScalef(0.25F, 0.25F, 0.25F); design.renderItemstack((org.spoutcraft.api.entity.Item)par1EntityItem.spoutEnty, (float)par2, (float)(par4 + var11), (float)par6, var12, 0.25F, random); } else { GL11.glPushMatrix(); // the push from above if (!custom) { if (var10.itemID < 256) { this.loadTexture("/terrain.png"); } else { this.loadTexture("/gui/items.png"); } } // Spout End GL11.glTranslatef((float)par2, (float)par4 + var11, (float)par6); GL11.glEnable(GL12.GL_RESCALE_NORMAL); Block var14 = Block.blocksList[var10.itemID]; int var16; float var19; float var20; float var24; if (var14 != null && RenderBlocks.renderItemIn3d(var14.getRenderType())) { GL11.glRotatef(var12, 0.0F, 1.0F, 0.0F); if (field_82407_g) { GL11.glScalef(1.25F, 1.25F, 1.25F); GL11.glTranslatef(0.0F, 0.05F, 0.0F); GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); } this.loadTexture("/terrain.png"); float var22 = 0.25F; var16 = var14.getRenderType(); if (var16 == 1 || var16 == 19 || var16 == 12 || var16 == 2) { var22 = 0.5F; } GL11.glScalef(var22, var22, var22); for (int var23 = 0; var23 < var13; ++var23) { GL11.glPushMatrix(); if (var23 > 0) { var24 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22; var19 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22; var20 = (this.random.nextFloat() * 2.0F - 1.0F) * 0.2F / var22; GL11.glTranslatef(var24, var19, var20); } var24 = 1.0F; this.renderBlocks.renderBlockAsItem(var14, var10.getItemDamage(), var24); GL11.glPopMatrix(); } } else { int var15; float var17; if (var10.getItem().requiresMultipleRenderPasses()) { if (field_82407_g) { GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F); GL11.glTranslatef(0.0F, -0.05F, 0.0F); GL11.glDisable(GL11.GL_LIGHTING); } else { GL11.glScalef(0.5F, 0.5F, 0.5F); } this.loadTexture("/gui/items.png"); for (var15 = 0; var15 <= 1; ++var15) { var16 = var10.getItem().getIconFromDamageForRenderPass(var10.getItemDamage(), var15); var17 = 1.0F; if (this.field_77024_a) { int var18 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, var15); var19 = (float)(var18 >> 16 & 255) / 255.0F; var20 = (float)(var18 >> 8 & 255) / 255.0F; float var21 = (float)(var18 & 255) / 255.0F; GL11.glColor4f(var19 * var17, var20 * var17, var21 * var17, 1.0F); } this.func_77020_a(var16, var13); } } else { if (field_82407_g) { GL11.glScalef(0.5128205F, 0.5128205F, 0.5128205F); GL11.glTranslatef(0.0F, -0.05F, 0.0F); GL11.glDisable(GL11.GL_LIGHTING); } else { GL11.glScalef(0.5F, 0.5F, 0.5F); } var15 = var10.getIconIndex(); if (var14 != null) { this.loadTexture("/terrain.png"); } else { if (!custom) { this.loadTexture("/gui/items.png"); } } if (this.field_77024_a) { var16 = Item.itemsList[var10.itemID].getColorFromItemStack(var10, 0); var17 = (float)(var16 >> 16 & 255) / 255.0F; var24 = (float)(var16 >> 8 & 255) / 255.0F; var19 = (float)(var16 & 255) / 255.0F; var20 = 1.0F; GL11.glColor4f(var17 * var20, var24 * var20, var19 * var20, 1.0F); } // Spout Start this.renderItemBillboard(var15, var13, custom); // Spout End } } GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); } // Spout } }
diff --git a/src/main/java/org/i5y/json/workshop/currency/Rates.java b/src/main/java/org/i5y/json/workshop/currency/Rates.java index c53ad34..c208653 100644 --- a/src/main/java/org/i5y/json/workshop/currency/Rates.java +++ b/src/main/java/org/i5y/json/workshop/currency/Rates.java @@ -1,133 +1,136 @@ package org.i5y.json.workshop.currency; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import javax.json.Json; import javax.json.JsonArrayBuilder; import javax.json.JsonNumber; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import javax.json.JsonValue; public class Rates { public static class RateNotPresentException extends RuntimeException { private static final long serialVersionUID = 1L; } /** * Get an exchange rate from USD to the provided currency on a certain date * * @param currency * @param date * formatted e.g. 2012-12-01 * @return * @throws RateNotPresentException * if the rate is not available for the currency/date pair */ public static double getRate(String currency, String date) { JsonObject obj = createJsonReader(date).readObject(); return getRate(obj, currency); } private static double getRate(JsonObject jsonDoc, String currency) { JsonObject rates = jsonDoc.getValue("rates", JsonObject.class); if (rates != null) { JsonValue jn = rates.get(currency); if (jn instanceof JsonNumber) { return ((JsonNumber) jn).getDoubleValue(); } else { throw new RateNotPresentException(); } } else { throw new RateNotPresentException(); } } /** + * Find currencies which have an exchange rate of 1 on a given date * * @param date * @return + * * @throws RateNotPresentException + * if the rates are not available for the given date */ public static Collection<String> findBaseEquivalentCurrencies(String date) { JsonObject obj = createJsonReader(date).readObject(); JsonObject rates = obj.getValue("rates", JsonObject.class); Collection<String> result = new HashSet<>(); String baseCurrency = obj.getStringValue("base", "USD"); if (rates != null) { for (Entry<String, JsonValue> entry : rates.entrySet()) { if (entry.getValue() instanceof JsonNumber) { if (((JsonNumber) entry.getValue()).getDoubleValue() == 1.0) { if (!entry.getKey().equals(baseCurrency)) { result.add(entry.getKey()); } } } } } else { throw new RateNotPresentException(); } return result; } /** * Generates a JSON report for a specific currency for a week from the * provided date in the format: * * { currency : "USD", rates: [ { timestamp :"Sat Feb 01 23:00:09 GMT 2013", * value: 1.x}, ...] } * * @param currency * @param date * @return */ public static JsonObject generateWeekReport(String currency, String startDate) { String[] segments = startDate.split("-"); int day = Integer.parseInt(segments[2]); List<String> dates = new ArrayList<>(); for (int i = 0; i < 7; i++) { String dayStr = Integer.toString(day + i); if (dayStr.length() == 1) dayStr = "0" + dayStr; dates.add(segments[0] + "-" + segments[1] + "-" + dayStr); } JsonArrayBuilder ratesArrayBuilder = Json.createArrayBuilder(); for (String date : dates) { JsonObject obj = createJsonReader(date).readObject(); JsonNumber jn = obj.getValue("timestamp", JsonNumber.class); long time = jn.getLongValue(); double rate = getRate(obj, currency); ratesArrayBuilder.add(Json.createObjectBuilder() .add("timestamp", new Date(time * 1000l).toString()) .add("rate", rate)); } JsonObjectBuilder objectBuilder = Json.createObjectBuilder() .add("currency", currency).add("rates", ratesArrayBuilder); return objectBuilder.build(); } /** * Return a JsonReader object which will read the document for the * appropriate date * * @param date * @return */ private static JsonReader createJsonReader(String date) { InputStream is = Rates.class.getResourceAsStream("/" + date + ".json"); return Json.createReader(is); } }
false
false
null
null
diff --git a/src/share/classes/com/sun/javafx/runtime/sequence/SequencesBase.java b/src/share/classes/com/sun/javafx/runtime/sequence/SequencesBase.java index 6de0bb621..064b6ab55 100755 --- a/src/share/classes/com/sun/javafx/runtime/sequence/SequencesBase.java +++ b/src/share/classes/com/sun/javafx/runtime/sequence/SequencesBase.java @@ -1,1095 +1,1095 @@ /* * Copyright 2008-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.javafx.runtime.sequence; import java.util.*; import com.sun.javafx.runtime.TypeInfo; import com.sun.javafx.runtime.Util; import com.sun.javafx.runtime.FXBase; import com.sun.javafx.runtime.NumericTypeInfo; /** * SequencesBase * * @author Brian Goetz */ public class SequencesBase { /*******************************************/ /* Converting between sequences and arrays */ /*******************************************/ /** Convert a T[] to a Sequence<T> */ public static<T> Sequence<T> fromArray(TypeInfo<T> ti, T[] values) { if (values == null) return ti.emptySequence; return new ObjectArraySequence<T>(ti, values); } /** Convert a long[] to a Sequence<Long> */ public static Sequence<Long> fromArray(long[] values) { if (values == null) return TypeInfo.Long.emptySequence; return new LongArraySequence(values, 0, values.length); } /** Convert an int[] to a Sequence<Integer> */ public static Sequence<Integer> fromArray(int[] values) { if (values == null) return TypeInfo.Integer.emptySequence; return new IntArraySequence(values, 0, values.length); } /** Convert a short[] to a Sequence<Short> */ public static Sequence<Short> fromArray(short[] values) { if (values == null) return TypeInfo.Short.emptySequence; return new ShortArraySequence(values, 0, values.length); } /** Convert a char[] to a Sequence<Character> */ public static Sequence<Character> fromArray(char[] values) { if (values == null) return TypeInfo.Character.emptySequence; return new CharArraySequence(values, 0, values.length); } /** Convert a byte[] to a Sequence<Byte> */ public static Sequence<Byte> fromArray(byte[] values) { if (values == null) return TypeInfo.Byte.emptySequence; return new ByteArraySequence(values, 0, values.length); } /** Convert a double[] to a Sequence<Double> */ public static Sequence<Double> fromArray(double[] values) { if (values == null) return TypeInfo.Double.emptySequence; return new DoubleArraySequence(values, 0, values.length); } /** Convert a float[] to a Sequence<Float> */ public static Sequence<Float> fromArray(float[] values) { if (values == null) return TypeInfo.Float.emptySequence; return new FloatArraySequence(values, 0, values.length); } /** Convert a boolean[] to a Sequence<Boolean> */ public static Sequence<Boolean> fromArray(boolean[] values) { if (values == null) return TypeInfo.Boolean.emptySequence; return new BooleanArraySequence(values, 0, values.length); } /** Convert a Sequence<T> to an array */ public static<T> T[] toArray(Sequence<? extends T> seq) { T[] unboxed = Util.<T>newObjectArray(seq.size()); int i=0; for (T val : seq) { unboxed[i++] = val; } return unboxed; } /** Convert a Sequence<Long> to an array */ public static long[] toLongArray(Sequence<? extends Number> seq) { int size = seq.size(); long[] unboxed = new long[size]; for (int i = size; --i >= 0; ) unboxed[i] = seq.getAsLong(i); return unboxed; } /** Convert a Sequence<Integer> to an array */ public static int[] toIntArray(Sequence<? extends Number> seq) { int size = seq.size(); int[] unboxed = new int[size]; for (int i = size; --i >= 0; ) unboxed[i] = seq.getAsInt(i); return unboxed; } /** Convert a Sequence<Short> to an array */ public static short[] toShortArray(Sequence<? extends Number> seq) { int size = seq.size(); short[] unboxed = new short[size]; for (int i = size; --i >= 0; ) unboxed[i] = seq.getAsShort(i); return unboxed; } /** Convert a Sequence<Byte> to an array */ public static byte[] toByteArray(Sequence<? extends Number> seq) { int size = seq.size(); byte[] unboxed = new byte[size]; for (int i = size; --i >= 0; ) unboxed[i] = seq.getAsByte(i); return unboxed; } /** Convert a Sequence<Double> to a double array */ public static double[] toDoubleArray(Sequence<? extends Number> seq) { int size = seq.size(); double[] unboxed = new double[size]; for (int i = size; --i >= 0; ) unboxed[i] = seq.getAsDouble(i); return unboxed; } /** Convert a Sequence<Double> to a float array */ public static float[] toFloatArray(Sequence<? extends Number> seq) { int size = seq.size(); float[] unboxed = new float[size]; for (int i = size; --i >= 0; ) unboxed[i] = seq.getAsFloat(i); return unboxed; } /** Convert a Sequence<Boolean> to an array */ public static boolean[] toBooleanArray(Sequence<? extends Boolean> seq) { int size = seq.size(); boolean[] unboxed = new boolean[size]; for (int i = size; --i >= 0; ) unboxed[i] = seq.getAsBoolean(i); return unboxed; } @SuppressWarnings("unchecked") public static<T> ObjectArraySequence<T> forceNonSharedArraySequence(TypeInfo<T> typeInfo, Sequence<? extends T> value) { ObjectArraySequence<T> arr; block: { if (value instanceof ObjectArraySequence) { arr = (ObjectArraySequence) value; if (! arr.isShared()) { // FIXME: arr.setElementType(typeInfo); return arr; } // Special case - we might as well re-use an empty array. if (arr.array.length == 0) { arr = new ObjectArraySequence(typeInfo, arr.array, true); break block; } } arr = new ObjectArraySequence(typeInfo, value); } arr.incrementSharing(); return arr; } public static<T> T incrementSharing(T value) { if (value instanceof ArraySequence) ((ArraySequence) value).incrementSharing(); return value; } /***************************************************/ /* Methods for constructing sequences from scratch */ /***************************************************/ /** Factory for simple sequence generation */ public static<T> Sequence<T> make(TypeInfo<T> ti, T... values) { if (values == null || values.length == 0) return ti.emptySequence; else return new ObjectArraySequence<T>(ti, values); } /** Factory for simple sequence generation */ public static<T> Sequence<T> make(TypeInfo<T> ti, T[] values, int size) { if (values == null || size <= 0) return ti.emptySequence; else return new ObjectArraySequence<T>(ti, values, 0, size); } public static<T> Sequence<T> makeViaHandoff(TypeInfo<T> ti, T[] values) { return new ObjectArraySequence<T>(ti, values, true); } /** Factory for simple sequence generation */ public static<T> Sequence<T> make(TypeInfo<T> ti, List<? extends T> values) { if (values == null || values.size() == 0) return ti.emptySequence; else return new ObjectArraySequence<T>(ti, values); } /** Create an Integer range sequence ranging from lower to upper inclusive. */ public static Sequence<Integer> range(int lower, int upper) { return new IntRangeSequence(lower, upper); } /** Create an Integer range sequence ranging from lower to upper inclusive, incrementing by the specified step. */ public static Sequence<Integer> range(int lower, int upper, int step) { return new IntRangeSequence(lower, upper, step); } /** Create an Integer range sequence ranging from lower to upper exclusive. */ public static Sequence<Integer> rangeExclusive(int lower, int upper) { return new IntRangeSequence(lower, upper, true); } /** Create an Integer range sequence ranging from lower to upper exnclusive, incrementing by the specified step. */ public static Sequence<Integer> rangeExclusive(int lower, int upper, int step) { return new IntRangeSequence(lower, upper, step, true); } /** Create a double range sequence ranging from lower to upper inclusive, incrementing by 1.0 */ public static Sequence<Float> range(float lower, float upper) { return new NumberRangeSequence(lower, upper, 1.0f); } /** Create a double range sequence ranging from lower to upper inclusive, incrementing by the specified step. */ public static Sequence<Float> range(float lower, float upper, float step) { return new NumberRangeSequence(lower, upper, step); } /** Create a double range sequence ranging from lower to upper exnclusive */ public static Sequence<Float> rangeExclusive(float lower, float upper) { return new NumberRangeSequence(lower, upper, 1.0f, true); } /** Create a double range sequence ranging from lower to upper exnclusive, incrementing by the specified step. */ public static Sequence<Float> rangeExclusive(float lower, float upper, float step) { return new NumberRangeSequence(lower, upper, step, true); } /** Create a filtered sequence. A filtered sequence contains some, but not necessarily all, of the elements * of another sequence, in the same order as that sequence. If bit n is set in the BitSet, then the element * at position n of the original sequence appears in the filtered sequence. */ public static<T> Sequence<T> filter(Sequence<T> seq, BitSet bits) { int cardinality = bits.cardinality(); if (cardinality == 0) return seq.getEmptySequence(); else if (cardinality == seq.size() && bits.nextClearBit(0) == seq.size()) return seq; else { ObjectArraySequence<T> result = new ObjectArraySequence(cardinality, seq.getElementType()); for (int i = bits.nextSetBit(0), next = 0; i >= 0; i = bits.nextSetBit(i + 1)) result.add(seq.get(i)); return result; } } /** Extract a subsequence from the specified sequence, starting as the specified start position, and up to but * not including the specified end position. If the start position is negative it is assumed to be zero; if the * end position is greater than seq.size() it is assumed to be seq.size(). */ public static<T> Sequence<T> subsequence(Sequence<T> seq, int start, int end) { // OPT: for small sequences, just copy the elements if (start >= end) return seq.getEmptySequence(); else if (start <= 0 && end >= seq.size()) return seq; else { start = Math.max(start, 0); end = Math.min(end, seq.size()); return SubSequence.make(seq, end-start, start, 1); } } public static int calculateSize(int start, int bound, int step, boolean exclusive) { if (Math.abs((long) start - (long) bound) + ((long) (exclusive ? 0 : 1)) > Integer.MAX_VALUE) throw new IllegalArgumentException("Range sequence too big"); if (bound == start) { return exclusive ? 0 : 1; } else { int size = Math.max(0, ((bound - start) / step) + 1); if (exclusive) { boolean tooBig = (step > 0) ? (start + (size-1)*step >= bound) : (start + (size-1)*step <= bound); if (tooBig && size > 0) --size; } return (int) size; } } /* NOTE Possible future functionality, to allow a step in a slice expression. * This is a sketch, which needs some tweaking to handle corner cases, * plus some compiler work. * NOTE The generalization to step!=1, except as used by the reverse * function, is UNTESTED. public static<T> Sequence<T> subsequence(Sequence<T> seq, int start, int bound, int step, boolean exclusive) { // FIXME canonicalize start (if out of range) int size = calculateSize(start, bound, step, exclusive); return SubSequence.make(seq, start, size, step); } */ /** Create a sequence containing a single element, the specified value */ public static<T> Sequence<T> singleton(TypeInfo<T> ti, T t) { if (t == null) return ti.emptySequence; else return new SingletonSequence<T>(ti, t); } /** Create an empty sequence */ public static<T> Sequence<T> emptySequence(Class<T> clazz) { return TypeInfo.getTypeInfo(clazz).emptySequence; } /** Reverse an existing sequence */ public static<T> Sequence<T> reverse(Sequence<T> sequence) { int ssize = sequence.size(); return SubSequence.make(sequence, ssize, ssize-1, -1); } /** Convert a Collection<T> to a Sequence<T> */ @SuppressWarnings("unchecked") public static<T> Sequence<T> fromCollection(TypeInfo<T> ti, Collection<T> values) { if (values == null) return ti.emptySequence; // OPT: Use handoff, pre-size array return new ObjectArraySequence<T>(ti, (T[]) values.toArray()); } /**********************************************/ /* Utility methods for dealing with sequences */ /**********************************************/ /** Upcast a sequence of T to a sequence of superclass-of-T */ @SuppressWarnings("unchecked") public static<T> Sequence<T> upcast(Sequence<? extends T> sequence) { return (Sequence<T>) sequence; } /** Convert any numeric sequence to any other numeric sequence */ public static<T extends Number, V extends Number> Sequence<T> convertNumberSequence(NumericTypeInfo<T> toType, NumericTypeInfo<V> fromType, Sequence<? extends V> seq) { if (Sequences.size(seq) == 0) return toType.emptySequence; int length = seq.size(); T[] toArray = toType.makeArray(length); int i=0; for (V val : seq) { toArray[i++] = toType.asPreferred(fromType, val); } return new ObjectArraySequence<T>(toType, toArray, 0, length); } /** How large is this sequence? Can be applied to any object. */ public static int size(Object seq) { if (seq instanceof Sequence) return ((Sequence) seq).size(); else return seq == null ? 0 : 1; } /** How large is this sequence? */ public static int size(Sequence seq) { return (seq == null) ? 0 : seq.size(); } @SuppressWarnings("unchecked") public static<T> Iterator<T> iterator(Sequence<T> seq) { return (seq == null)? (Iterator<T>) TypeInfo.Object.emptySequence.iterator() : seq.iterator(); } @SuppressWarnings("unchecked") public static<T> Iterator<T> iterator(Sequence<T> seq, int startPos, int endPos) { return (seq == null)? (Iterator<T>) TypeInfo.Object.emptySequence.iterator() : seq.iterator(startPos, endPos); } public static<T> boolean isEqual(Sequence<?> one, Sequence<?> other) { int oneSize = size(one); int otherSize = size(other); if (oneSize == 0) return (otherSize == 0); else if (oneSize != otherSize) return false; else { Iterator<?> it1 = one.iterator(); Iterator<?> it2 = other.iterator(); while (it1.hasNext()) { if (! it1.next().equals(it2.next())) return false; } return true; } } public static<T> boolean isEqualByContentIdentity(Sequence<? extends T> one, Sequence<? extends T> other) { int oneSize = size(one); if (oneSize == 0) return size(other) == 0; else if (oneSize != size(other)) return false; else { Iterator<? extends T> it1 = one.iterator(); Iterator<? extends T> it2 = other.iterator(); while (it1.hasNext()) { if (it1.next() != it2.next()) return false; } return true; } } public static<T> boolean sliceEqual(Sequence<? extends T> seq, int startPos, int endPos/*exclusive*/, Sequence<? extends T> slice) { int size = size(slice); if (endPos - startPos != size) return false; /* For most (but not all) Sequences types, indexing is faster. Iterator<? extends T> seqIterator = iterator(seq, startPos, endPos-1); for (Iterator<? extends T> sliceIterator = iterator(slice); sliceIterator.hasNext(); ) { if (!seqIterator.next().equals(sliceIterator.next())) { return false; } } */ for (int i = 0; i < size; i++) { if (!seq.get(startPos+i).equals(slice.get(i))) return false; } return true; } public static<T> Sequence<? extends T> forceNonNull(TypeInfo<T> typeInfo, Sequence<? extends T> seq) { return seq == null ? typeInfo.emptySequence : seq; } /** * Return the single value of a sequence. * Return null if the sequence zero zero or more than 1 elements. * Thid is used to implement 'seq instanceof T'. */ public static <T> T getSingleValue (Sequence<T> seq) { if (seq == null || seq.size() != 1) return null; return seq.get(0); } /*************************/ /* Sorting and searching */ /*************************/ /** * Searches the specified sequence for the specified object using the * binary search algorithm. The sequence must be sorted into ascending * order according to the natural ordering of its elements (as by * the sort(Sequence<T>) method) prior to making this call. * * If it is not sorted, the results are undefined. If the array contains * multiple elements equal to the specified object, there is no guarantee * which one will be found. * * @param seq The sequence to be searched. * @param key The value to be searched for. * @return Index of the search key, if it is contained in the array; * otherwise, (-(insertion point) - 1). The insertion point is * defined as the point at which the key would be inserted into the * array: the index of the first element greater than the key, or * a.length if all elements in the array are less than the specified * key. Note that this guarantees that the return value will be >= 0 * if and only if the key is found. */ public static <T extends Comparable> int binarySearch (Sequence<? extends T> seq, T key) { if (seq.isEmpty()) return -1; final int length = seq.size(); T[] array = Util.<T>newComparableArray(length); seq.toArray(0, length, array, 0); return Arrays.binarySearch(array, key); } /** * Searches the specified array for the specified object using the * binary search algorithm. The array must be sorted into ascending * order according to the specified comparator (as by the * sort(Sequence<T>, Comparator<? super T>) method) prior to making * this call. * * If it is not sorted, the results are undefined. If the array contains * multiple elements equal to the specified object, there is no guarantee * which one will be found. * * @param seq The sequence to be searched. * @param key The value to be searched for. * @param c The comparator by which the array is ordered. A null value * indicates that the elements' natural ordering should be used. * @return Index of the search key, if it is contained in the array; * otherwise, (-(insertion point) - 1). The insertion point is * defined as the point at which the key would be inserted into the * array: the index of the first element greater than the key, or * a.length if all elements in the array are less than the specified * key. Note that this guarantees that the return value will be >= 0 * if and only if the key is found. */ public static <T> int binarySearch(Sequence<? extends T> seq, T key, Comparator<? super T> c) { if (seq.isEmpty()) return -1; final int length = seq.size(); T[] array = Util.<T>newObjectArray(length); seq.toArray(0, length, array, 0); return Arrays.binarySearch(array, (T)key, c); } /** * Searches the specified sequence for the specified object. * * If the sequence contains multiple elements equal to the specified object, * the first occurence in the sequence will be returned. * * The method nextIndexOf can be used in consecutive calls to iterate * through all occurences of a specified object. * * @param seq The sequence to be searched. * @param key The value to be searched for. * @return Index of the search key, if it is contained in the array; * otherwise -1. */ public static<T> int indexByIdentity(Sequence<? extends T> seq, T key) { return nextIndexByIdentity(seq, key, 0); } /** * Searches the specified sequence for an object with the same value. The * objects are compared using the method equals(). If the sequence is sorted, * binarySearch should be used instead. * * If the sequence contains multiple elements equal to the specified object, * the first occurence in the sequence will be returned. * * The method nextIndexOf can be used in consecutive calls to iterate * through all occurences of a specified object. * * @param seq The sequence to be searched. * @param key The value to be searched for. * @return Index of the search key, if it is contained in the array; * otherwise -1. */ public static<T> int indexOf(Sequence<? extends T> seq, T key) { return nextIndexOf(seq, key, 0); } /** * Returns the element with the maximum value in the specified sequence, * according to the natural ordering of its elements. All elements in the * sequence must implement the Comparable interface. Furthermore, all * elements in the sequence must be mutually comparable (that is, * e1.compareTo(e2) must not throw a ClassCastException for any elements * e1 and e2 in the sequence). * * If the sequence contains multiple elements with the maximum value, * there is no guarantee which one will be found. * * @param seq The sequence to be searched. * @return The element with the maximum value. */ @SuppressWarnings("unchecked") public static <T extends Comparable> T max (Sequence<T> seq) { if (seq == null || seq.isEmpty()) throw new IllegalArgumentException("empty sequence passed to Sequences.max"); T result = seq.get(0); for (T val : seq) { if (result.compareTo(val) < 0) { result = val; } } return result; } /** * Returns the element with the maximum value in the specified sequence, * according to the specified comparator. All elements in the sequence must * be mutually comparable by the specified comparator (that is, * c.compare(e1, e2) must not throw a ClassCastException for any elements * e1 and e2 in the sequence). * * If the sequence contains multiple elements with the maximum value, * there is no guarantee which one will be found. * * @param seq The sequence to be searched. * @param c The comparator to determine the order of the sequence. * A null value indicates that the elements' natural ordering * should be used. * @return The element with the maximum value. */ @SuppressWarnings("unchecked") public static <T> T max (Sequence<T> seq, Comparator<? super T> c) { if (seq == null || seq.isEmpty()) throw new IllegalArgumentException("empty sequence passed to Sequences.max"); if (c == null) return (T)max((Sequence<Comparable>)seq); T result = seq.get(0); for (T val : seq) { if (c.compare(result, val) < 0) { result = val; } } return result; } /** * Returns the element with the minimum value in the specified sequence, * according to the natural ordering of its elements. All elements in the * sequence must implement the Comparable interface. Furthermore, all * elements in the sequence must be mutually comparable (that is, * e1.compareTo(e2) must not throw a ClassCastException for any elements * e1 and e2 in the sequence). * * If the sequence contains multiple elements with the minimum value, * there is no guarantee which one will be found. * * @param seq The sequence to be searched. * @return The element with the maximum value. */ @SuppressWarnings("unchecked") public static <T extends Comparable> T min (Sequence<T> seq) { if (seq == null || seq.isEmpty()) throw new IllegalArgumentException("empty sequence passed to Sequences.min"); T result = seq.get(0); for (T val : seq) { if (result.compareTo(val) > 0) { result = val; } } return result; } /** * Returns the element with the minimum value in the specified sequence, * according to the specified comparator. All elements in the sequence must * be mutually comparable by the specified comparator (that is, * c.compare(e1, e2) must not throw a ClassCastException for any elements * e1 and e2 in the sequence). * * If the sequence contains multiple elements with the minimum value, * there is no guarantee which one will be found. * * @param seq The sequence to be searched. * @param c The comparator to determine the order of the sequence. * A null value indicates that the elements' natural ordering * should be used. * @return The element with the minimum value. */ @SuppressWarnings("unchecked") public static <T> T min (Sequence<T> seq, Comparator<? super T> c) { if (seq == null || seq.isEmpty()) throw new IllegalArgumentException("empty sequence passed to Sequences.min"); if (c == null) return (T)min((Sequence<Comparable>)seq); T result = seq.get(0); for (T val : seq) { if (c.compare(result, val) > 0) result = val; } return result; } /** * Searches the specified sequence for an object with the same value, * starting the search at the specified position. The objects are compared * using the method equals(). * * If the sequence contains multiple elements equal to the specified object, * the first occurence in the subsequence will be returned. * * @param seq The sequence to be searched. * @param key The value to be searched for. * @param pos The position in the sequence to start the search. If pos is * negative or 0 the whole sequence will be searched. * @return Index of the search key, if it is contained in the array; * otherwise -1. */ public static<T> int nextIndexByIdentity(Sequence<? extends T> seq, T key, int pos) { if (seq == null) return -1; if (key == null) throw new NullPointerException(); Iterator<? extends T> it = seq.iterator(); int i; for (i=0; i<pos && it.hasNext(); ++i) it.next(); for (; it.hasNext(); ++i) if (it.next() == key) return i; return -1; } /** * Searches the specified sequence for the specified object, starting the * search at the specified position. * * If the sequence contains multiple elements equal to the specified object, * the first occurence in the subsequence will be returned. * * @param seq The sequence to be searched. * @param key The value to be searched for. * @param pos The position in the sequence to start the search. If pos is * negative or 0 the whole sequence will be searched. * @return Index of the search key, if it is contained in the array; * otherwise -1. */ public static<T> int nextIndexOf(Sequence<? extends T> seq, T key, int pos) { if (seq == null) return -1; if (key == null) throw new NullPointerException(); Iterator<? extends T> it = seq.iterator(); int i; for (i=0; i<pos && it.hasNext(); ++i) it.next(); for (; it.hasNext(); ++i) if (it.next().equals(key)) return i; return -1; } /** * Sorts the specified sequence of objects into ascending order, according * to the natural ordering of its elements. All elements in the sequence * must implement the Comparable interface. Furthermore, all elements in * the sequence must be mutually comparable (that is, e1.compareTo(e2) * must not throw a ClassCastException for any elements e1 and e2 in the * sequence). * * This method is immutative, the result is returned in a new sequence, * while the original sequence is left untouched. * * This sort is guaranteed to be stable: equal elements will not be * reordered as a result of the sort. * * The sorting algorithm is a modified mergesort (in which the merge is * omitted if the highest element in the low sublist is less than the * lowest element in the high sublist). This algorithm offers guaranteed * n*log(n) performance. * * @param seq The sequence to be sorted. * @return The sorted sequence. */ public static <T extends Comparable> Sequence<? extends T> sort (Sequence<T> seq) { if (seq.isEmpty()) return seq.getEmptySequence(); final int length = seq.size(); T[] array = Util.<T>newComparableArray(length); seq.toArray(0, length, array, 0); Arrays.sort(array); return Sequences.<T>make(seq.getElementType(), array); } /** * Sorts the specified sequence of objects according to the order induced * by the specified comparator. All elements in the sequence must be * mutually comparable by the specified comparator (that is, * c.compare(e1, e2) must not throw a ClassCastException for any elements * e1 and e2 in the sequence). * * This method is immutative, the result is returned in a new sequence, * while the original sequence is left untouched. * * This sort is guaranteed to be stable: equal elements will not be * reordered as a result of the sort. * * The sorting algorithm is a modified mergesort (in which the merge is * omitted if the highest element in the low sublist is less than the * lowest element in the high sublist). This algorithm offers guaranteed * n*log(n) performance. * * @param seq The sequence to be sorted. * @param c The comparator to determine the order of the sequence. * A null value indicates that the elements' natural ordering * should be used. * @return The sorted sequence. */ public static <T> Sequence<? extends T> sort (Sequence<T> seq, Comparator<? super T> c) { if (seq.isEmpty()) return seq.getEmptySequence(); final int length = seq.size(); T[] array = Util.<T>newObjectArray(length); seq.toArray(0, length, array, 0); Arrays.sort(array, c); return Sequences.<T>make(seq.getElementType(), array); } /* Only used by the testing framework - should be moved. FIXME */ public static<T> Sequence<? extends T> insert(TypeInfo<T> typeInfo, Sequence<? extends T> sequence, T value) { ObjectArraySequence<T> arr = forceNonSharedArraySequence(typeInfo, sequence); arr.add(value); return arr; } /** Returns a new sequence containing the randomly shuffled * contents of the existing sequence * */ public static <T> Sequence<T> shuffle (Sequence<T> seq) { T[] array = toArray(seq); List<? extends T> list = Arrays.asList(array); Collections.shuffle(list); return Sequences.make(seq.getElementType(), list); } public static <T> int sizeOfOldValue(ArraySequence<T> buffer, Sequence<? extends T> oldValue, int hiIndex/*exclusive*/) { if (oldValue != null) return oldValue.size(); return buffer.getRawArrayLength() - buffer.gapEnd + hiIndex; } public static <T> int sizeOfNewElements(ArraySequence<T> buffer, int loIndex, Sequence<? extends T> newElements) { if (newElements != null) return newElements.size(); return buffer.gapStart - loIndex; } public static <T> T getFromOldValue(ArraySequence<T> buffer, Sequence<? extends T> oldValue, int startPos, int endPos, int k) { if (oldValue != null) return oldValue.get(k); if (k >= 0) { if (k >= startPos) k += buffer.gapEnd - endPos; int alen = buffer.getRawArrayLength(); if (k < alen) { return buffer.getRawArrayElementAsObject(k); } } return buffer.getDefaultValue(); } public static <T> T getFromNewElements(ArraySequence<T> buffer, int loIndex, Sequence<? extends T> newElements, int k) { if (newElements != null) return newElements.get(k); if (k >= 0) { k = k + loIndex; if (k < buffer.gapStart) return buffer.get(k); } return buffer.getDefaultValue(); } public static <T> Sequence<? extends T> getOldValue(ArraySequence<T> buffer, Sequence<? extends T> oldValue, int loIndex, int hiIndex/*exclusive*/) { if (oldValue != null) return oldValue; return buffer.extractOldValue(loIndex, hiIndex); } public static <T> Sequence<? extends T> getNewElements(ArraySequence<T> buffer, int startPos, Sequence<? extends T> newElements) { if (newElements != null) return newElements; buffer.incrementSharing(); return Sequences.subsequence(buffer, startPos, buffer.gapStart); } public static <T> Sequence<? extends T> replaceSlice(Sequence<? extends T> oldValue, T newValue, int startPos, int endPos/*exclusive*/) { if (newValue != null ? (endPos == startPos+1 && newValue.equals(oldValue.get( startPos))) : endPos == startPos) { // FIXME set valid?? return oldValue; } int oldSize = oldValue.size(); if (startPos < 0) startPos = 0; else if (startPos > oldSize) startPos = oldSize; if (endPos > oldSize) endPos = oldSize; else if (endPos < startPos) endPos = startPos; ObjectArraySequence<T> arr = forceNonSharedArraySequence((TypeInfo<T>) oldValue.getElementType(), oldValue); arr.replace(startPos, endPos, (T) newValue, true); arr.clearOldValues(endPos-startPos); return arr; } public static <T> void replaceSlice(FXBase instance, int varNum, T newValue, int startPos, int endPos/*exclusive*/) { Sequence<? extends T> oldValue = (Sequence<? extends T>) instance.get$(varNum); Sequence<? extends T> arr = replaceSlice(oldValue, newValue, startPos, endPos); // FIXME var.setValid(); // TODO: invalidate(varNum, startPos, endPos, newValue==null?0:1); instance.set$(varNum, arr); } - public static <T> Sequence<? extends T> replaceSlice(Sequence<? extends T> oldValue, int startPos, int endPos/*exclusive*/, Sequence<? extends T> newValues) { + public static <T> Sequence<? extends T> replaceSlice(Sequence<? extends T> oldValue, Sequence<? extends T> newValues, int startPos, int endPos/*exclusive*/) { if (sliceEqual(oldValue, startPos, endPos, newValues)) { // FIXME set valid?? return oldValue; } int inserted = newValues==null? 0 : newValues.size(); int oldSize = oldValue.size(); if (startPos < 0) startPos = 0; else if (startPos > oldSize) startPos = oldSize; if (endPos > oldSize) endPos = oldSize; else if (endPos < startPos) endPos = startPos; ObjectArraySequence<T> arr = forceNonSharedArraySequence((TypeInfo<T>) oldValue.getElementType(), oldValue); arr.replace(startPos, endPos, newValues, 0, inserted, true); arr.clearOldValues(endPos-startPos); return arr; } - public static <T> void replaceSlice(FXBase instance, int varNum, int startPos, int endPos/*exclusive*/, Sequence<? extends T> newValues) { + public static <T> void replaceSlice(FXBase instance, int varNum, Sequence<? extends T> newValues, int startPos, int endPos/*exclusive*/) { Sequence<? extends T> oldValue = (Sequence<? extends T>) instance.get$(varNum); - Sequence<? extends T> arr = replaceSlice(oldValue, startPos, endPos, newValues); + Sequence<? extends T> arr = replaceSlice(oldValue, newValues, startPos, endPos); instance.set$(varNum, arr); } public static <T> Sequence<? extends T> set(Sequence<? extends T> oldValue, T newValue, int index) { return replaceSlice(oldValue, newValue, index, index + 1); } public static <T> T set(FXBase instance, int varNum, T newValue, int index) { replaceSlice(instance, varNum, newValue, index, index + 1); return newValue; } public static <T> Sequence<? extends T> insert(Sequence<? extends T> oldValue, T newValue) { if (newValue == null) return oldValue; int oldSize = oldValue.size(); ObjectArraySequence<T> arr = forceNonSharedArraySequence((TypeInfo<T>) oldValue.getElementType(), oldValue); arr.replace(oldSize, oldSize, (T) newValue, true); return arr; } public static <T> void insert(FXBase instance, int varNum, T newValue) { if (newValue == null) return; Sequence<? extends T> oldValue = (Sequence<? extends T>) instance.get$(varNum); Sequence<? extends T> arr = insert(oldValue, newValue); // FIXME var.setValid(); // TODO: invalidate(varNum, startPos, endPos, newValue==null?0:1); instance.set$(varNum, arr); } public static <T> Sequence<? extends T> insert(Sequence<? extends T> oldValue, Sequence<? extends T> values) { int inserted = values.size(); if (inserted == 0) return oldValue; int oldSize = oldValue.size(); ObjectArraySequence<T> arr = forceNonSharedArraySequence((TypeInfo<T>) oldValue.getElementType(), oldValue); arr.replace(oldSize, oldSize, values, 0, inserted, true); return arr; } public static <T> void insert(FXBase instance, int varNum, Sequence<? extends T> values) { int inserted = values.size(); if (inserted == 0) return; Sequence<? extends T> oldValue = (Sequence<? extends T>) instance.get$(varNum); Sequence<? extends T> arr = insert(oldValue, values); // FIXME var.setValid(); // TODO: invalidate(varNum, startPos, endPos, ...); instance.set$(varNum, arr); } public static <T> void insertBefore(FXBase instance, int varNum, T value, int position) { replaceSlice(instance, varNum, value, position, position); } public static <T> void insertBefore(FXBase instance, int varNum, Sequence<? extends T> values, int position) { - replaceSlice(instance, varNum, position, position, values); + replaceSlice(instance, varNum, values, position, position); } public static <T> Sequence<? extends T> insertBefore(Sequence<? extends T> oldValue, T value, int position) { return replaceSlice(oldValue, value, position, position); } public static <T> Sequence<? extends T> insertBefore(Sequence<? extends T> oldValue, Sequence<? extends T> values, int position) { - return replaceSlice(oldValue, position, position, values); + return replaceSlice(oldValue, values, position, position); } public static <T> void deleteIndexed(FXBase instance, int varNum, int position) { - replaceSlice(instance, varNum, position, position+1, (Sequence<? extends T>)null); + replaceSlice(instance, varNum, (Sequence<? extends T>)null, position, position+1); } public static <T> Sequence<? extends T> deleteIndexed(Sequence<? extends T> oldValue, int position) { - return replaceSlice(oldValue, position, position+1, (Sequence<? extends T>)null); + return replaceSlice(oldValue, (Sequence<? extends T>)null, position, position+1); } public static <T> void deleteSlice(FXBase instance, int varNum, int begin, int end) { - replaceSlice(instance, varNum, begin, end, (Sequence<? extends T>)null); + replaceSlice(instance, varNum, (Sequence<? extends T>)null, begin, end); } public static <T> Sequence<? extends T> deleteSlice(Sequence<? extends T> oldValue, int begin, int end) { - return replaceSlice(oldValue, begin, end, (Sequence<? extends T>)null); + return replaceSlice(oldValue, (Sequence<? extends T>)null, begin, end); } public static <T> void deleteValue(FXBase instance, int varNum, T value) { Sequence<? extends T> oldValue = (Sequence<? extends T>) instance.get$(varNum); // It's tempting to just do: // Sequence<? extends T> arr = deleteValue(oldValue, value); // instance.set$(varNum, arr); // However, in hat case triggers won't run properly. int hi = -1; for (int i = oldValue.size(); ; ) { boolean matches = --i < 0 ? false : oldValue.get(i).equals(value); if (matches) { if (hi < 0) hi = i; } else if (hi >= 0) { deleteSlice(instance, varNum, i+1, hi+1); // The following may be redundant - but just in case: oldValue = (Sequence<? extends T>) instance.get$(varNum); hi = -1; } if (i < 0) break; } } public static <T> Sequence<? extends T> deleteValue(Sequence<? extends T> oldValue, T value) { int hi = -1; for (int i = oldValue.size(); ; ) { boolean matches = --i < 0 ? false : oldValue.get(i).equals(value); if (matches) { if (hi < 0) hi = i; } else if (hi >= 0) { oldValue = deleteSlice(oldValue, i+1, hi+1); hi = -1; } if (i < 0) break; } return oldValue; } public static <T> Sequence<? extends T> deleteAll(Sequence<? extends T> oldValue) { - return replaceSlice(oldValue, 0, oldValue.size(), (Sequence<? extends T>)null); + return replaceSlice(oldValue, (Sequence<? extends T>)null, 0, oldValue.size()); } public static <T> void deleteAll(FXBase instance, int varNum) { Sequence<? extends T> oldValue = (Sequence<? extends T>) instance.get$(varNum); Sequence<? extends T> arr = deleteAll(oldValue); // FIXME var.setValid(); // TODO: invalidate(varNum, startPos, endPos, ...); instance.set$(varNum, arr); } }
false
false
null
null
diff --git a/src/YUICompressor.java b/src/YUICompressor.java index 97c7bec..2282aae 100644 --- a/src/YUICompressor.java +++ b/src/YUICompressor.java @@ -1,961 +1,964 @@ /* * YUI Compressor * Author: Julien Lecomte <[email protected]> * Copyright (c) 2007, Yahoo! Inc. All rights reserved. * Code licensed under the BSD License: * http://developer.yahoo.net/yui/license.txt */ import jargs.gnu.CmdLineParser; import org.mozilla.javascript.*; import java.io.*; import java.nio.charset.Charset; import java.util.*; public class YUICompressor { static final ArrayList ones; static final ArrayList twos; static final ArrayList threes; static final Set builtin = new HashSet(); static final Map literals = new Hashtable(); static { // This list contains all the 3 characters or less built-in global // symbols available in a browser. Please add to this list if you // see anything missing. builtin.add("NaN"); builtin.add("top"); ones = new ArrayList(); for (char c = 'A'; c <= 'Z'; c++) ones.add(Character.toString(c)); for (char c = 'a'; c <= 'z'; c++) ones.add(Character.toString(c)); Collections.shuffle(ones); twos = new ArrayList(); for (int i = 0; i < ones.size(); i++) { String one = (String) ones.get(i); for (char c = 'A'; c <= 'Z'; c++) twos.add(one + Character.toString(c)); for (char c = 'a'; c <= 'z'; c++) twos.add(one + Character.toString(c)); for (char c = '0'; c <= '9'; c++) twos.add(one + Character.toString(c)); } // Remove two-letter JavaScript reserved words and built-in globals... twos.remove("as"); twos.remove("is"); twos.remove("do"); twos.remove("if"); twos.remove("in"); twos.removeAll(builtin); Collections.shuffle(twos); threes = new ArrayList(); for (int i = 0; i < twos.size(); i++) { String two = (String) twos.get(i); for (char c = 'A'; c <= 'Z'; c++) threes.add(two + Character.toString(c)); for (char c = 'a'; c <= 'z'; c++) threes.add(two + Character.toString(c)); for (char c = '0'; c <= '9'; c++) threes.add(two + Character.toString(c)); } // Remove three-letter JavaScript reserved words and built-in globals... threes.remove("for"); threes.remove("int"); threes.remove("new"); threes.remove("try"); threes.remove("use"); threes.remove("var"); threes.removeAll(builtin); Collections.shuffle(threes); // That's up to ((26+26)*(1+(26+26+10)))*(1+(26+26+10))-8 // (206,380 symbols per scope) literals.put(new Integer(Token.TRUE), "true"); literals.put(new Integer(Token.FALSE), "false"); literals.put(new Integer(Token.NULL), "null"); literals.put(new Integer(Token.THIS), "this"); literals.put(new Integer(Token.FUNCTION), "function "); literals.put(new Integer(Token.COMMA), ","); literals.put(new Integer(Token.LC), "{"); literals.put(new Integer(Token.RC), "}"); literals.put(new Integer(Token.LP), "("); literals.put(new Integer(Token.RP), ")"); literals.put(new Integer(Token.LB), "["); literals.put(new Integer(Token.RB), "]"); literals.put(new Integer(Token.DOT), "."); literals.put(new Integer(Token.NEW), "new "); literals.put(new Integer(Token.DELPROP), "delete "); literals.put(new Integer(Token.IF), "if"); literals.put(new Integer(Token.ELSE), "else"); literals.put(new Integer(Token.FOR), "for"); literals.put(new Integer(Token.IN), " in "); literals.put(new Integer(Token.WITH), "with"); literals.put(new Integer(Token.WHILE), "while"); literals.put(new Integer(Token.DO), "do"); literals.put(new Integer(Token.TRY), "try"); literals.put(new Integer(Token.CATCH), "catch"); literals.put(new Integer(Token.FINALLY), "finally"); literals.put(new Integer(Token.THROW), "throw "); literals.put(new Integer(Token.SWITCH), "switch"); literals.put(new Integer(Token.BREAK), "break"); literals.put(new Integer(Token.CONTINUE), "continue"); literals.put(new Integer(Token.CASE), "case "); literals.put(new Integer(Token.DEFAULT), "default"); literals.put(new Integer(Token.RETURN), "return "); literals.put(new Integer(Token.VAR), "var "); literals.put(new Integer(Token.SEMI), ";"); literals.put(new Integer(Token.ASSIGN), "="); literals.put(new Integer(Token.ASSIGN_ADD), "+="); literals.put(new Integer(Token.ASSIGN_SUB), "-="); literals.put(new Integer(Token.ASSIGN_MUL), "*="); literals.put(new Integer(Token.ASSIGN_DIV), "/="); literals.put(new Integer(Token.ASSIGN_MOD), "%="); literals.put(new Integer(Token.ASSIGN_BITOR), "|="); literals.put(new Integer(Token.ASSIGN_BITXOR), "^="); literals.put(new Integer(Token.ASSIGN_BITAND), "&="); literals.put(new Integer(Token.ASSIGN_LSH), "<<="); literals.put(new Integer(Token.ASSIGN_RSH), ">>="); literals.put(new Integer(Token.ASSIGN_URSH), ">>>="); literals.put(new Integer(Token.HOOK), "?"); literals.put(new Integer(Token.OBJECTLIT), ":"); literals.put(new Integer(Token.COLON), ":"); literals.put(new Integer(Token.OR), "||"); literals.put(new Integer(Token.AND), "&&"); literals.put(new Integer(Token.BITOR), "|"); literals.put(new Integer(Token.BITXOR), "^"); literals.put(new Integer(Token.BITAND), "&"); literals.put(new Integer(Token.SHEQ), "==="); literals.put(new Integer(Token.SHNE), "!=="); literals.put(new Integer(Token.EQ), "=="); literals.put(new Integer(Token.NE), "!="); literals.put(new Integer(Token.LE), "<="); literals.put(new Integer(Token.LT), "<"); literals.put(new Integer(Token.GE), ">="); literals.put(new Integer(Token.GT), ">"); literals.put(new Integer(Token.INSTANCEOF), " instanceof "); literals.put(new Integer(Token.LSH), "<<"); literals.put(new Integer(Token.RSH), ">>"); literals.put(new Integer(Token.URSH), ">>>"); literals.put(new Integer(Token.TYPEOF), "typeof "); literals.put(new Integer(Token.VOID), "void "); literals.put(new Integer(Token.NOT), "!"); literals.put(new Integer(Token.BITNOT), "~"); literals.put(new Integer(Token.POS), "+"); literals.put(new Integer(Token.NEG), "-"); literals.put(new Integer(Token.INC), "++"); literals.put(new Integer(Token.DEC), "--"); literals.put(new Integer(Token.ADD), "+"); literals.put(new Integer(Token.SUB), "-"); literals.put(new Integer(Token.MUL), "*"); literals.put(new Integer(Token.DIV), "/"); literals.put(new Integer(Token.MOD), "%"); literals.put(new Integer(Token.COLONCOLON), "::"); literals.put(new Integer(Token.DOTDOT), ".."); literals.put(new Integer(Token.DOTQUERY), ".("); literals.put(new Integer(Token.XMLATTR), "@"); } public static void main(String args[]) { if (args.length < 1) { usage(); System.exit(1); } CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option warnOpt = parser.addBooleanOption("warn"); CmdLineParser.Option nomungeOpt = parser.addBooleanOption("nomunge"); CmdLineParser.Option helpOpt = parser.addBooleanOption('h', "help"); CmdLineParser.Option charsetOpt = parser.addStringOption("charset"); CmdLineParser.Option outputOpt = parser.addStringOption('o', "output"); try { parser.parse(args); } catch (CmdLineParser.OptionException e) { usage(); System.exit(1); } String[] fileArgs = parser.getRemainingArgs(); if (fileArgs.length == 0) { usage(); System.exit(1); } String filename = fileArgs[0]; Boolean help = (Boolean) parser.getOptionValue(helpOpt); if (help != null && help.booleanValue()) { usage(); System.exit(0); } boolean warn = parser.getOptionValue(warnOpt) != null; boolean munge = parser.getOptionValue(nomungeOpt) == null; String charset = (String) parser.getOptionValue(charsetOpt); String output = (String) parser.getOptionValue(outputOpt); try { YUICompressor compressor = new YUICompressor(filename, munge, warn, charset, output); compressor.buildSymbolTree(); compressor.mungeSymboltree(); compressor.printSymbolTree(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static void usage() { System.out.println("Usage: java -jar yuicompressor.jar\n" + " [-h, --help] [--warn] [--nomunge]\n" + " [--charset character-set] [-o outfile] infile"); } private static ArrayList readTokens(String source) { int offset = 0; ArrayList tokens = new ArrayList(); int length = source.length(); StringBuffer sb = new StringBuffer(); while (offset < length) { int token = source.charAt(offset++); switch (token) { case Token.NAME: case Token.REGEXP: sb.setLength(0); offset = printSourceString(source, offset, false, sb); tokens.add(new JavaScriptToken(token, sb.toString())); break; case Token.STRING: sb.setLength(0); offset = printSourceString(source, offset, true, sb); tokens.add(new JavaScriptToken(token, sb.toString())); break; case Token.NUMBER: sb.setLength(0); offset = printSourceNumber(source, offset, sb); tokens.add(new JavaScriptToken(token, sb.toString())); break; default: String literal = (String) YUICompressor.literals.get(new Integer(token)); if (literal != null) { tokens.add(new JavaScriptToken(token, literal)); } break; } } return tokens; } private static int printSourceString(String source, int offset, boolean asQuotedString, StringBuffer sb) { int length = source.charAt(offset); ++offset; if ((0x8000 & length) != 0) { length = ((0x7FFF & length) << 16) | source.charAt(offset); ++offset; } if (sb != null) { String str = source.substring(offset, offset + length); if (!asQuotedString) { sb.append(str); } else { sb.append('"'); sb.append(escapeString(str, '"')); sb.append('"'); } } return offset + length; } private static String escapeString(String s, char escapeQuote) { assert escapeQuote == '"' || escapeQuote == '\''; if (s == null) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0, L = s.length(); i < L; i++) { int c = s.charAt(i); switch (c) { case'\b': sb.append("\\b"); break; case'\f': sb.append("\\f"); break; case'\n': sb.append("\\n"); break; case'\r': sb.append("\\r"); break; case'\t': sb.append("\\t"); break; case 0xb: sb.append("\\v"); break; case'\\': sb.append("\\\\"); break; case'"': sb.append("\\\""); break; default: if (c < ' ') { // Control character: 2-digit hex. Note: Can I ever get // in this situation? Shouldn't rhino report an error? sb.append("\\x"); // Append hexadecimal form of c left-padded with 0. int hexSize = 2; for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) { int digit = 0xf & (c >> shift); int hc = (digit < 10) ? '0' + digit : 'a' - 10 + digit; sb.append((char) hc); } } else { sb.append((char) c); } break; } } return sb.toString(); } private static int printSourceNumber(String source, int offset, StringBuffer sb) { double number = 0.0; char type = source.charAt(offset); ++offset; if (type == 'S') { if (sb != null) { number = source.charAt(offset); } ++offset; } else if (type == 'J' || type == 'D') { if (sb != null) { long lbits; lbits = (long) source.charAt(offset) << 48; lbits |= (long) source.charAt(offset + 1) << 32; lbits |= (long) source.charAt(offset + 2) << 16; lbits |= (long) source.charAt(offset + 3); if (type == 'J') { number = lbits; } else { number = Double.longBitsToDouble(lbits); } } offset += 4; } else { // Bad source throw new RuntimeException(); } if (sb != null) { sb.append(ScriptRuntime.numberToString(number, 10)); } return offset; } private boolean munge; private boolean warn; private String charset; private String output; private int offset; private int braceNesting; private ArrayList tokens; private Stack scopes = new Stack(); private ScriptOrFnScope globalScope = new ScriptOrFnScope(-1, null); private Hashtable indexedScopes = new Hashtable(); YUICompressor(String filename, boolean munge, boolean warn, String charset, String output) throws IOException { this.munge = munge; this.warn = warn; if (charset == null || !Charset.isSupported(charset)) { charset = System.getProperty("file.encoding"); if (charset == null) { charset = "UTF-8"; } System.out.println("\n[INFO] Using charset " + charset); } this.charset = charset; if (output == null) { // Get the file extension... int idx = filename.lastIndexOf('.'); if (idx >= 0 && idx < filename.length() - 1) { output = filename.substring(0, idx) + "-min" + filename.substring(idx); } else { output = filename + "-min.js"; } } this.output = output; Reader in = new InputStreamReader(new FileInputStream(filename), charset); CompilerEnvirons env = new CompilerEnvirons(); ErrorReporter reporter = new JavaScriptErrorReporter(System.err, filename, true); Parser parser = new Parser(env, reporter); try { parser.parse(in, filename, 1); } catch (EvaluatorException e) { System.exit(2); } String encodedSource = parser.getEncodedSource(); this.tokens = readTokens(encodedSource); } private ScriptOrFnScope getCurrentScope() { return (ScriptOrFnScope) scopes.peek(); } private void enterScope(ScriptOrFnScope scope) { scopes.push(scope); } private void leaveCurrentScope() { scopes.pop(); } private JavaScriptToken consumeToken() { return (JavaScriptToken) tokens.get(offset++); } private JavaScriptToken getToken(int delta) { return (JavaScriptToken) tokens.get(offset + delta); } /* * Returns the identifier for the specified symbol defined in * the specified scope or in any scope above it. Returns null * if this symbol does not have a corresponding identifier. */ private Identifier getIdentifier(String symbol, ScriptOrFnScope scope) { Identifier identifier; while (scope != null) { identifier = scope.getIdentifier(symbol); if (identifier != null) return identifier; scope = scope.getParentScope(); } return null; } /* * Returns the highest function scope containing the specified scope. */ private ScriptOrFnScope getHighestFnScope(ScriptOrFnScope scope) { + if (scope == globalScope) { + return scope; + } while (scope.getParentScope() != globalScope) { scope = scope.getParentScope(); } return scope; } private String getDebugString(int max) { assert max > 0; StringBuffer result = new StringBuffer(); int start = Math.max(offset - max, 0); int end = Math.min(offset + max, tokens.size()); for (int i = start; i < end; i++) { JavaScriptToken token = (JavaScriptToken) tokens.get(i); if (i == offset) result.append(" ---> "); result.append(token.getValue()); if (i == offset) result.append(" <--- "); } return result.toString(); } private void buildSymbolTree() { offset = 0; braceNesting = 0; scopes.clear(); indexedScopes.clear(); indexedScopes.put(new Integer(0), globalScope); parseScope(globalScope); } private void parseFunctionDeclaration() { String symbol; JavaScriptToken token; ScriptOrFnScope currentScope, fnScope; currentScope = getCurrentScope(); token = consumeToken(); if (token.getType() == Token.NAME) { // Get the name of the function and declare it in the current scope. symbol = token.getValue(); if (currentScope.getIdentifier(symbol) != null && warn) { System.out.println("\n[WARNING] The function " + symbol + " has already been declared in the same scope...\n" + getDebugString(10)); } currentScope.declareIdentifier(symbol); token = consumeToken(); } assert token.getType() == Token.LP; fnScope = new ScriptOrFnScope(braceNesting, currentScope); indexedScopes.put(new Integer(offset), fnScope); // Parse function arguments. while ((token = consumeToken()).getType() != Token.RP) { assert token.getType() == Token.NAME || token.getType() == Token.COMMA; if (token.getType() == Token.NAME) { fnScope.declareIdentifier(token.getValue()); } } parseScope(fnScope); } private void parseCatch() { String symbol; JavaScriptToken token; ScriptOrFnScope currentScope; token = getToken(0); assert token.getType() == Token.CATCH; token = consumeToken(); assert token.getType() == Token.LP; token = consumeToken(); assert token.getType() == Token.NAME; // We must declare the exception identifier in the containing function // scope to avoid errors related to the obfuscation process. No need to // display a warning if the symbol was already declared here... symbol = token.getValue(); currentScope = getCurrentScope(); currentScope.declareIdentifier(symbol); token = consumeToken(); assert token.getType() == Token.RP; } private void parseExpression() { // Parse the expression until we encounter a comma or a semi-colon // in the same brace nesting, bracket nesting and paren nesting. // Parse functions if any... String symbol; JavaScriptToken token; ScriptOrFnScope currentScope; int expressionBraceNesting = braceNesting; int bracketNesting = 0; int parensNesting = 0; int length = tokens.size(); while (offset < length) { token = consumeToken(); switch (token.getType()) { case Token.SEMI: case Token.COMMA: if (braceNesting == expressionBraceNesting && bracketNesting == 0 && parensNesting == 0) { return; } break; case Token.FUNCTION: parseFunctionDeclaration(); break; case Token.LC: braceNesting++; break; case Token.RC: braceNesting--; assert braceNesting >= expressionBraceNesting; break; case Token.LB: bracketNesting++; break; case Token.RB: bracketNesting--; break; case Token.LP: parensNesting++; break; case Token.RP: parensNesting--; break; case Token.NAME: symbol = token.getValue(); if (symbol.equals("eval")) { currentScope = getCurrentScope(); getHighestFnScope(currentScope).markForMunging(false); if (warn) { System.out.println("\n[WARNING] Using 'eval' is not recommended.\n" + getDebugString(10)); if (munge) { System.out.println("Note: Using 'eval' reduces the level of compression."); } } } break; } } } private void parseScope(ScriptOrFnScope scope) { String symbol; JavaScriptToken token; int length = tokens.size(); enterScope(scope); while (offset < length) { token = consumeToken(); switch (token.getType()) { case Token.VAR: // The var keyword is followed by at least one symbol name. // If several symbols follow, they are comma separated. for (; ;) { token = consumeToken(); assert token.getType() == Token.NAME; symbol = token.getValue(); if (scope.getIdentifier(symbol) == null) { scope.declareIdentifier(symbol); } else if (warn) { System.out.println("\n[WARNING] The variable " + symbol + " has already been declared in the same scope...\n" + getDebugString(10)); } token = getToken(0); assert token.getType() == Token.SEMI || token.getType() == Token.ASSIGN || token.getType() == Token.COMMA || token.getType() == Token.IN; if (token.getType() == Token.IN) { break; } else { parseExpression(); token = getToken(-1); if (token.getType() == Token.SEMI) { break; } } } break; case Token.FUNCTION: parseFunctionDeclaration(); break; case Token.LC: braceNesting++; break; case Token.RC: braceNesting--; assert braceNesting >= scope.getBraceNesting(); if (braceNesting == scope.getBraceNesting()) { leaveCurrentScope(); return; } break; case Token.WITH: getHighestFnScope(scope).markForMunging(false); if (warn) { System.out.println("\n[WARNING] Using 'with' is not recommended.\n" + getDebugString(10)); if (munge) { // Inside a 'with' block, it is impossible to figure out // statically whether a symbol is a local variable or an // object member. As a consequence, the only thing we can // do is turn the obfuscation off for the highest scope // containing the 'with' block. System.out.println("Note: Using 'with' reduces the level of compression."); } } break; case Token.CATCH: parseCatch(); break; case Token.NAME: symbol = token.getValue(); if (symbol.equals("eval")) { getHighestFnScope(scope).markForMunging(false); if (warn) { System.out.println("\n[WARNING] Using 'eval' is not recommended.\n" + getDebugString(10)); if (munge) { System.out.println("Note: Using 'eval' reduces the level of compression."); } } } break; } } } private void mungeSymboltree() { if (!munge) { return; } // One problem with obfuscation resides in the use of undeclared // and un-namespaced global symbols that are 3 characters or less // in length. Here is an example: // // var declaredGlobalVar; // // function declaredGlobalFn() { // var localvar; // localvar = abc; // abc is an undeclared global symbol // } // // In the example above, there is a slim chance that localvar may be // munged to 'abc', conflicting with the undeclared global symbol // abc, creating a potential bug. The following code detects such // global symbols. This must be done AFTER all the files have been // parsed, and BEFORE munging the symbol tree. Note that declaring // extra symbols in the global scope won't hurt. // // Since we have to go through all the tokens, we could use the // opportunity to count the number of times each identifier is used. // The goal would be, in the future, to use the least number of // characters to represent the most used identifiers. offset = 0; braceNesting = 0; scopes.clear(); String symbol; JavaScriptToken token; ScriptOrFnScope currentScope; Identifier identifier; int length = tokens.size(); enterScope(globalScope); while (offset < length) { token = consumeToken(); currentScope = getCurrentScope(); switch (token.getType()) { case Token.NAME: symbol = token.getValue(); if ((offset < 2 || getToken(-2).getType() != Token.DOT) && getToken(0).getType() != Token.OBJECTLIT) { identifier = getIdentifier(symbol, currentScope); if (identifier == null) { if (symbol.length() <= 3 && !builtin.contains(symbol)) { // Here, we found an undeclared and un-namespaced symbol that is // 3 characters or less in length. Declare it in the global scope. // We don't need to declare longer symbols since they won't cause // any conflict with other munged symbols. globalScope.declareIdentifier(symbol); if (warn) { System.out.println("\n[WARNING] Found an undeclared symbol: " + symbol + "\n" + getDebugString(10)); } } } } break; case Token.FUNCTION: token = consumeToken(); if (token.getType() == Token.NAME) { token = consumeToken(); } assert token.getType() == Token.LP; currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset)); enterScope(currentScope); while (consumeToken().getType() != Token.RP) { } token = consumeToken(); assert token.getType() == Token.LC; braceNesting++; break; case Token.LC: braceNesting++; break; case Token.RC: braceNesting--; assert braceNesting >= currentScope.getBraceNesting(); if (braceNesting == currentScope.getBraceNesting()) { leaveCurrentScope(); } break; } } globalScope.munge(); } private void printSymbolTree() throws IOException { offset = 0; braceNesting = 0; scopes.clear(); String symbol; JavaScriptToken token; ScriptOrFnScope currentScope; Identifier identifier; int length = tokens.size(); StringBuffer result = new StringBuffer(); enterScope(globalScope); while (offset < length) { token = consumeToken(); currentScope = getCurrentScope(); switch (token.getType()) { case Token.NAME: symbol = token.getValue(); if (offset >= 2 && getToken(-2).getType() == Token.DOT || getToken(0).getType() == Token.OBJECTLIT) { result.append(symbol); } else { identifier = getIdentifier(symbol, currentScope); if (identifier != null && identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } } break; case Token.REGEXP: case Token.NUMBER: case Token.STRING: result.append(token.getValue()); break; case Token.FUNCTION: result.append("function"); token = consumeToken(); if (token.getType() == Token.NAME) { result.append(" "); symbol = token.getValue(); identifier = getIdentifier(symbol, currentScope); assert identifier != null; if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } token = consumeToken(); } assert token.getType() == Token.LP; result.append("("); currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset)); enterScope(currentScope); while ((token = consumeToken()).getType() != Token.RP) { assert token.getType() == Token.NAME || token.getType() == Token.COMMA; if (token.getType() == Token.NAME) { symbol = token.getValue(); identifier = getIdentifier(symbol, currentScope); assert identifier != null; if (identifier.getMungedValue() != null) { result.append(identifier.getMungedValue()); } else { result.append(symbol); } } else if (token.getType() == Token.COMMA) { result.append(","); } } result.append(")"); token = consumeToken(); assert token.getType() == Token.LC; result.append("{"); braceNesting++; break; case Token.LC: result.append("{"); braceNesting++; break; case Token.RC: result.append("}"); braceNesting--; assert braceNesting >= currentScope.getBraceNesting(); if (braceNesting == currentScope.getBraceNesting()) { leaveCurrentScope(); } break; default: String literal = (String) literals.get(new Integer(token.getType())); if (literal != null) { result.append(literal); } else if (warn) { System.out.println("\n[WARNING] This symbol cannot be printed: " + token.getValue()); } break; } } Writer out = new OutputStreamWriter(new FileOutputStream(output), charset); out.write(result.toString()); out.close(); } }
true
false
null
null
diff --git a/src/ee/lutsu/alpha/mc/aperf/aPerf.java b/src/ee/lutsu/alpha/mc/aperf/aPerf.java index 56024da..b793050 100644 --- a/src/ee/lutsu/alpha/mc/aperf/aPerf.java +++ b/src/ee/lutsu/alpha/mc/aperf/aPerf.java @@ -1,167 +1,168 @@ package ee.lutsu.alpha.mc.aperf; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartedEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; import java.io.File; import java.io.IOException; import java.util.logging.Level; import ee.lutsu.alpha.mc.aperf.commands.BaseCommand; import ee.lutsu.alpha.mc.aperf.commands.CmdPerf; import ee.lutsu.alpha.mc.aperf.commands.CommandsManager; import ee.lutsu.alpha.mc.aperf.sys.GeneralModule; import ee.lutsu.alpha.mc.aperf.sys.ModuleBase; import ee.lutsu.alpha.mc.aperf.sys.entity.EntityModule; import ee.lutsu.alpha.mc.aperf.sys.entity.EntitySafeListModule; import ee.lutsu.alpha.mc.aperf.sys.entity.ItemGrouperModule; import ee.lutsu.alpha.mc.aperf.sys.entity.SpawnLimiterModule; import ee.lutsu.alpha.mc.aperf.sys.packet.PacketManagerModule; import ee.lutsu.alpha.mc.aperf.sys.tile.TileEntityModule; import net.minecraft.command.ServerCommandManager; import net.minecraft.server.MinecraftServer; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.Property; @Mod( modid = "aPerf", name = "aPerf", version = "1.4.7.2" ) @NetworkMod( clientSideRequired = false, serverSideRequired = true ) public class aPerf { public static String MOD_NAME = "aPerf"; public File configFile; public Configuration config; public CommandsManager commandsManager = new CommandsManager(this); public ModuleBase[] modules = new ModuleBase[] { GeneralModule.instance, EntityModule.instance, EntitySafeListModule.instance, TileEntityModule.instance, SpawnLimiterModule.instance, ItemGrouperModule.instance, PacketManagerModule.Instance }; @Mod.Instance("aPerf") public static aPerf instance; @Mod.PreInit public void preInit(FMLPreInitializationEvent ev) { configFile = ev.getSuggestedConfigurationFile(); } @Mod.Init public void load(FMLInitializationEvent var1) { - reload(); } @Mod.ServerStarted public void modsLoaded(FMLServerStartedEvent var1) { + reload(); + for (ModuleBase m : modules) { for(BaseCommand cmd : m.getCommands()) commandsManager.register(cmd); } ServerCommandManager mgr = (ServerCommandManager)MinecraftServer.getServer().getCommandManager(); mgr.registerCommand(new CmdPerf()); } public void loadConfig() { config = new Configuration(configFile, true); try { config.load(); for (ModuleBase m : modules) m.loadConfig(); } catch (Exception var8) { FMLLog.log(Level.SEVERE, var8, MOD_NAME + " was unable to load it's configuration successfully", new Object[0]); throw new RuntimeException(var8); } finally { config.save(); // re-save to add the missing configuration variables } } public boolean isEnabled(ModuleBase module) { Property prop = config.get("Modules", "Enable-" + module.getClass().getSimpleName(), module.getDefaultEnabled()); return prop.getBoolean(module.getDefaultEnabled()); } public void setAutoLoad(ModuleBase module, boolean load) { Property prop = config.get("Modules", "Enable-" + module.getClass().getSimpleName(), false); prop.value = String.valueOf(load); config.save(); } protected void enableModules() { try { for (ModuleBase m : modules) { if (m.isVisible() && isEnabled(m)) m.enable(); } } finally { config.save(); } } protected void disableModules() { for (ModuleBase m : modules) { if (m.isEnabled()) m.disable(); } } public void reload() { loadConfig(); try { disableModules(); enableModules(); } catch (Exception ex) { Log.severe("Load failed"); throw new RuntimeException(ex.getMessage(), ex); } Log.info("Loaded"); } } diff --git a/src/ee/lutsu/alpha/mc/aperf/sys/entity/EntityModule.java b/src/ee/lutsu/alpha/mc/aperf/sys/entity/EntityModule.java index b9daad8..5768823 100644 --- a/src/ee/lutsu/alpha/mc/aperf/sys/entity/EntityModule.java +++ b/src/ee/lutsu/alpha/mc/aperf/sys/entity/EntityModule.java @@ -1,63 +1,63 @@ package ee.lutsu.alpha.mc.aperf.sys.entity; import java.util.ArrayList; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.server.MinecraftServer; import net.minecraft.world.World; import com.google.common.base.Optional; import ee.lutsu.alpha.mc.aperf.sys.ModuleBase; import ee.lutsu.alpha.mc.aperf.sys.objects.Filter; import ee.lutsu.alpha.mc.aperf.sys.objects.FilterCollection; public class EntityModule extends ModuleBase { public static EntityModule instance = new EntityModule(); public FilterCollection safeList; public EntityModule() { addCommand(new ee.lutsu.alpha.mc.aperf.sys.entity.cmd.EntityList()); addCommand(new ee.lutsu.alpha.mc.aperf.sys.entity.cmd.EntityRemoving()); visible = false; } public int removeEntities(Filter filter, Entity centered, int range) { int removed = 0; int distSq = range * range; for (World w : MinecraftServer.getServer().worldServers) { ArrayList<Entity> toRemove = new ArrayList<Entity>(); for (int i = 0; i < w.loadedEntityList.size(); i++) { Entity ent = (Entity)w.loadedEntityList.get(i); if (ent instanceof EntityPlayer) continue; if (EntitySafeListModule.isEntitySafe(ent)) continue; - if (centered != null && range >= 0 && ent.getDistanceSqToEntity(centered) < distSq) + if (centered != null && range >= 0 && ent.getDistanceSqToEntity(centered) > distSq) continue; if (!filter.hitsAll(ent)) continue; toRemove.add(ent); } for (Entity e : toRemove) EntityHelper.removeEntity(e); removed += toRemove.size(); } return removed; } }
false
false
null
null
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java index 78461e4..2d51be4 100644 --- a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java +++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java @@ -1,612 +1,616 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.vfs2.provider.ram; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import org.apache.commons.vfs2.RandomAccessContent; import org.apache.commons.vfs2.util.RandomAccessMode; /** * RAM File Random Access Content. * @author <a href="http://commons.apache.org/vfs/team-list.html">Commons VFS team</a> */ public class RamFileRandomAccessContent implements RandomAccessContent { /** * File Pointer */ protected int filePointer = 0; /** * Buffer */ private byte[] buf; /** * buffer */ private final byte[] buffer8 = new byte[8]; /** * buffer */ private final byte[] buffer4 = new byte[4]; /** * buffer */ private final byte[] buffer2 = new byte[2]; /** * buffer */ private final byte[] buffer1 = new byte[1]; /** * Mode */ private final RandomAccessMode mode; /** * File */ private final RamFileObject file; private final InputStream rafis; /** * @param file The file to access. * @param mode The access mode. */ public RamFileRandomAccessContent(RamFileObject file, RandomAccessMode mode) { super(); this.buf = file.getData().getBuffer(); this.file = file; this.mode = mode; rafis = new InputStream() { @Override public int read() throws IOException { try { return readByte(); } catch (EOFException e) { return -1; } } @Override public long skip(long n) throws IOException { seek(getFilePointer() + n); return n; } @Override public void close() throws IOException { } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { - int retLen = Math.min(len, getLeftBytes()); - RamFileRandomAccessContent.this.readFully(b, off, retLen); + int retLen = -1; + final int left = getLeftBytes(); + if (left > 0) { + retLen = Math.min(len, left); + RamFileRandomAccessContent.this.readFully(b, off, retLen); + } return retLen; } @Override public int available() throws IOException { return getLeftBytes(); } }; } /* * (non-Javadoc) * * @see org.apache.commons.vfs2.RandomAccessContent#getFilePointer() */ public long getFilePointer() throws IOException { return this.filePointer; } /* * (non-Javadoc) * * @see org.apache.commons.vfs2.RandomAccessContent#seek(long) */ public void seek(long pos) throws IOException { if (pos < 0) { throw new IOException("Attempt to position before the start of the file"); } this.filePointer = (int) pos; } /* * (non-Javadoc) * * @see org.apache.commons.vfs2.RandomAccessContent#length() */ public long length() throws IOException { return buf.length; } /* * (non-Javadoc) * * @see org.apache.commons.vfs2.RandomAccessContent#close() */ public void close() throws IOException { } /* * (non-Javadoc) * * @see java.io.DataInput#readByte() */ public byte readByte() throws IOException { return (byte) this.readUnsignedByte(); } /* * (non-Javadoc) * * @see java.io.DataInput#readChar() */ public char readChar() throws IOException { int ch1 = this.readUnsignedByte(); int ch2 = this.readUnsignedByte(); return (char) ((ch1 << 8) + (ch2 << 0)); } /* * (non-Javadoc) * * @see java.io.DataInput#readDouble() */ public double readDouble() throws IOException { return Double.longBitsToDouble(this.readLong()); } /* * (non-Javadoc) * * @see java.io.DataInput#readFloat() */ public float readFloat() throws IOException { return Float.intBitsToFloat(this.readInt()); } /* * (non-Javadoc) * * @see java.io.DataInput#readInt() */ public int readInt() throws IOException { return (readUnsignedByte() << 24) | (readUnsignedByte() << 16) | (readUnsignedByte() << 8) | readUnsignedByte(); } /* * (non-Javadoc) * * @see java.io.DataInput#readUnsignedByte() */ public int readUnsignedByte() throws IOException { if (filePointer < buf.length) { return buf[filePointer++] & 0xFF; } else { throw new EOFException(); } } /* * (non-Javadoc) * * @see java.io.DataInput#readUnsignedShort() */ public int readUnsignedShort() throws IOException { this.readFully(buffer2); return toUnsignedShort(buffer2); } /* * (non-Javadoc) * * @see java.io.DataInput#readLong() */ public long readLong() throws IOException { this.readFully(buffer8); return toLong(buffer8); } /* * (non-Javadoc) * * @see java.io.DataInput#readShort() */ public short readShort() throws IOException { this.readFully(buffer2); return toShort(buffer2); } /* * (non-Javadoc) * * @see java.io.DataInput#readBoolean() */ public boolean readBoolean() throws IOException { return (this.readUnsignedByte() != 0); } /* * (non-Javadoc) * * @see java.io.DataInput#skipBytes(int) */ public int skipBytes(int n) throws IOException { if (n < 0) { throw new IndexOutOfBoundsException( "The skip number can't be negative"); } long newPos = filePointer + n; if (newPos > buf.length) { throw new IndexOutOfBoundsException("Tyring to skip too much bytes"); } seek(newPos); return n; } /* * (non-Javadoc) * * @see java.io.DataInput#readFully(byte[]) */ public void readFully(byte[] b) throws IOException { this.readFully(b, 0, b.length); } /* * (non-Javadoc) * * @see java.io.DataInput#readFully(byte[], int, int) */ public void readFully(byte[] b, int off, int len) throws IOException { if (len < 0) { throw new IndexOutOfBoundsException("Length is lower than 0"); } if (len > this.getLeftBytes()) { throw new IndexOutOfBoundsException("Read length (" + len + ") is higher than buffer left bytes (" + this.getLeftBytes() + ") "); } System.arraycopy(buf, filePointer, b, off, len); filePointer += len; } private int getLeftBytes() { return buf.length - filePointer; } /* * (non-Javadoc) * * @see java.io.DataInput#readUTF() */ public String readUTF() throws IOException { return DataInputStream.readUTF(this); } /* * (non-Javadoc) * * @see java.io.DataOutput#write(byte[], int, int) */ public void write(byte[] b, int off, int len) throws IOException { if (this.getLeftBytes() < len) { int newSize = this.buf.length + len - this.getLeftBytes(); this.file.resize(newSize); this.buf = this.file.getData().getBuffer(); } System.arraycopy(b, off, this.buf, filePointer, len); this.filePointer += len; } /* * (non-Javadoc) * * @see java.io.DataOutput#write(byte[]) */ public void write(byte[] b) throws IOException { this.write(b, 0, b.length); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeByte(int) */ public void writeByte(int i) throws IOException { this.write(i); } /** * Build a long from first 8 bytes of the array. * * @param b The byte[] to convert. * @return A long. */ public static long toLong(byte[] b) { return ((((long) b[7]) & 0xFF) + ((((long) b[6]) & 0xFF) << 8) + ((((long) b[5]) & 0xFF) << 16) + ((((long) b[4]) & 0xFF) << 24) + ((((long) b[3]) & 0xFF) << 32) + ((((long) b[2]) & 0xFF) << 40) + ((((long) b[1]) & 0xFF) << 48) + ((((long) b[0]) & 0xFF) << 56)); } /** * Build a 8-byte array from a long. No check is performed on the array * length. * * @param n The number to convert. * @param b The array to fill. * @return A byte[]. */ public static byte[] toBytes(long n, byte[] b) { b[7] = (byte) (n); n >>>= 8; b[6] = (byte) (n); n >>>= 8; b[5] = (byte) (n); n >>>= 8; b[4] = (byte) (n); n >>>= 8; b[3] = (byte) (n); n >>>= 8; b[2] = (byte) (n); n >>>= 8; b[1] = (byte) (n); n >>>= 8; b[0] = (byte) (n); return b; } /** * Build a short from first 2 bytes of the array. * @param b The byte[] to convert. * @return A short. */ public static short toShort(byte[] b) { return (short) toUnsignedShort(b); } /** * Build a short from first 2 bytes of the array. * * @param b The byte[] to convert. * @return A short. */ public static int toUnsignedShort(byte[] b) { return ((b[1] & 0xFF) + ((b[0] & 0xFF) << 8)); } /* * (non-Javadoc) * * @see java.io.DataOutput#write(int) */ public void write(int b) throws IOException { buffer1[0] = (byte) b; this.write(buffer1); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeBoolean(boolean) */ public void writeBoolean(boolean v) throws IOException { this.write(v ? 1 : 0); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeBytes(java.lang.String) */ public void writeBytes(String s) throws IOException { write(s.getBytes()); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeChar(int) */ public void writeChar(int v) throws IOException { buffer2[0] = (byte) ((v >>> 8) & 0xFF); buffer2[1] = (byte) ((v >>> 0) & 0xFF); write(buffer2); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeChars(java.lang.String) */ public void writeChars(String s) throws IOException { int len = s.length(); for (int i = 0; i < len; i++) { writeChar(s.charAt(i)); } } /* * (non-Javadoc) * * @see java.io.DataOutput#writeDouble(double) */ public void writeDouble(double v) throws IOException { writeLong(Double.doubleToLongBits(v)); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeFloat(float) */ public void writeFloat(float v) throws IOException { writeInt(Float.floatToIntBits(v)); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeInt(int) */ public void writeInt(int v) throws IOException { buffer4[0] = (byte) ((v >>> 24) & 0xFF); buffer4[1] = (byte) ((v >>> 16) & 0xFF); buffer4[2] = (byte) ((v >>> 8) & 0xFF); buffer4[3] = (byte) (v & 0xFF); write(buffer4); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeLong(long) */ public void writeLong(long v) throws IOException { write(toBytes(v, buffer8)); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeShort(int) */ public void writeShort(int v) throws IOException { buffer2[0] = (byte) ((v >>> 8) & 0xFF); buffer2[1] = (byte) (v & 0xFF); write(buffer2); } /* * (non-Javadoc) * * @see java.io.DataOutput#writeUTF(java.lang.String) */ public void writeUTF(String str) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(str.length()); DataOutputStream dataOut = new DataOutputStream(out); dataOut.writeUTF(str); dataOut.flush(); dataOut.close(); byte[] b = out.toByteArray(); write(b); } /* * (non-Javadoc) * * @see java.io.DataInput#readLine() */ public String readLine() throws IOException { throw new UnsupportedOperationException("deprecated"); } public InputStream getInputStream() throws IOException { return rafis; } }
true
true
public RamFileRandomAccessContent(RamFileObject file, RandomAccessMode mode) { super(); this.buf = file.getData().getBuffer(); this.file = file; this.mode = mode; rafis = new InputStream() { @Override public int read() throws IOException { try { return readByte(); } catch (EOFException e) { return -1; } } @Override public long skip(long n) throws IOException { seek(getFilePointer() + n); return n; } @Override public void close() throws IOException { } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { int retLen = Math.min(len, getLeftBytes()); RamFileRandomAccessContent.this.readFully(b, off, retLen); return retLen; } @Override public int available() throws IOException { return getLeftBytes(); } }; }
public RamFileRandomAccessContent(RamFileObject file, RandomAccessMode mode) { super(); this.buf = file.getData().getBuffer(); this.file = file; this.mode = mode; rafis = new InputStream() { @Override public int read() throws IOException { try { return readByte(); } catch (EOFException e) { return -1; } } @Override public long skip(long n) throws IOException { seek(getFilePointer() + n); return n; } @Override public void close() throws IOException { } @Override public int read(byte[] b) throws IOException { return read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { int retLen = -1; final int left = getLeftBytes(); if (left > 0) { retLen = Math.min(len, left); RamFileRandomAccessContent.this.readFully(b, off, retLen); } return retLen; } @Override public int available() throws IOException { return getLeftBytes(); } }; }
diff --git a/src/WeaponEntity.java b/src/WeaponEntity.java index 05c777f..ff2e294 100644 --- a/src/WeaponEntity.java +++ b/src/WeaponEntity.java @@ -1,45 +1,39 @@ import java.awt.Image; public class WeaponEntity extends Entity { private int weaponType; private Image itemIcon; private Image itemRenderPicture; private boolean gotOwner; public WeaponEntity(double xPosition, double yPosition, double zPosition, Equipment weapon) { super(xPosition, yPosition, zPosition); this.weaponType = weapon.getStat_Type(); this.itemIcon = weapon.getItemIcon(); this.itemRenderPicture = weapon.getItemRenderPicture(); // TODO Auto-generated constructor stub } private void createWeaponHitbox() { }; @Override - protected void updateHitboxes() { - // TODO Auto-generated method stub - - } - - @Override protected void updateSpeed() { // TODO Auto-generated method stub } @Override public boolean checkForCollision(Entity e) { // TODO Auto-generated method stub return false; } @Override public boolean checkForCollision(Hitbox h) { // TODO Auto-generated method stub return false; } }
true
false
null
null
diff --git a/TextAnnot-WWW/src/obir/otr/ObirProject.java b/TextAnnot-WWW/src/obir/otr/ObirProject.java index 3189c79..3b50dcd 100644 --- a/TextAnnot-WWW/src/obir/otr/ObirProject.java +++ b/TextAnnot-WWW/src/obir/otr/ObirProject.java @@ -1,839 +1,840 @@ package obir.otr; import java.awt.Color; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Scanner; import javax.swing.SwingUtilities; import obir.ir.Corpus; import obir.ir.indexing.SemanticIndexing; import obir.misc.ColorManager; import edu.stanford.smi.protege.exception.OntologyLoadException; import edu.stanford.smi.protege.model.Project; import edu.stanford.smi.protege.ui.ProjectManager; import edu.stanford.smi.protegex.owl.ProtegeOWL; import edu.stanford.smi.protegex.owl.database.OWLDatabaseModel; import edu.stanford.smi.protegex.owl.jena.JenaOWLModel; import edu.stanford.smi.protegex.owl.model.OWLIndividual; import edu.stanford.smi.protegex.owl.model.OWLModel; import edu.stanford.smi.protegex.owl.model.RDFProperty; import edu.stanford.smi.protegex.owl.model.RDFSClass; /** * Main class gathering crucial pieces of information for the current project, such as the used OTR, corpus * @author Axel Reymonet * */ public class ObirProject { /** * Indicates whose domain OTR is currently opened */ private static String domainPartner; /** * Indicates whether all elements are considered the same for all domain partners */ private static boolean isPrototypeGeneric; /** * Plugin properties to read from a config file */ private static Properties fixedPluginProperties = null ; /** * Language used in the corpus */ private static String language; /** * Set of documents to work with */ private static Corpus corpus; /** * Current OTR */ private static OTR otr; /** * Current Protégé OWL model */ private static OWLModel model; /** * Current processor aiming at indexing semantically the corpus */ private static SemanticIndexing indexingProcessor; /** * Set of fields which will be semantically indexed in each XML document of the corpus */ private static HashMap<String,HashMap<String,String>> semanticFields; /** * Set of fields which will be classically indexed in each XML document of the corpus */ private static HashMap<String,HashMap<String,String>> classicFields; /** * Indice to name instances (term occurrence or concept instance) */ static int COUNT; /** * Current color manager associating a term or concept with a color */ static ColorManager colorMgr; /** * Static plugin property file */ //public static File propertiesFile; private static String propertyDir; /** * Static boolean allowing to choose the global debug state for the plugin */ public static boolean debug = false; /** * An auto-saving task */ public static AutoSaveTask autoSaveTask; /** * Static string corresponding to the name of the file created for each query */ public static String xmlQueryFile = "query.xml"; public static final String ARKEO = "arkeo"; public static final String ARTAL = "artal"; private static ObirProject instance = null; public static boolean isFirstInitializing = true; private ObirProject() { if (instance==null) instance = this; } /** * Constructor called when opening only semantic search engine * @param otrFile the OTR with the annotations * @param corpusDir the corresponding corpus directory */ public ObirProject(File otrFile,File corpusDir, String propertyFilePath, OWLModel owlmodel) { this(); colorMgr = new ColorManager(); //model = (OWLModel)ProjectManager.getProjectManager().getCurrentProject().getKnowledgeBase(); model=owlmodel; propertyDir=propertyFilePath.replace("plugin.properties", ""); File propertiesFile= new File(propertyFilePath); initParameters(propertiesFile); otr = new OTR(otrFile, propertyDir); corpus = new Corpus(corpusDir); } /** * Method that returns the parameter directory * @return */ public static String getParameterDir(){ return propertyDir; } /** * Method that sets the searchable fields according to the information in the property file * @param prop */ public static void setSearchableFields(Properties prop){ semanticFields = new HashMap<String,HashMap<String,String>>(); classicFields = new HashMap<String,HashMap<String,String>>(); HashSet<String> semXMLTags = new HashSet<String>(); // System.out.println("semantic fields loaded: "+pluginProperties.getProperty("field.searchable.semantic")); Scanner scan = new Scanner(prop.getProperty("field.searchable.semantic")); scan.useDelimiter(","); while (scan.hasNext()) { semXMLTags.add(scan.next().replaceAll(" ", "")); } HashSet<String> classicXMLTags = new HashSet<String>(); scan.reset(); // System.out.println("classic fields loaded: "+pluginProperties.getProperty("field.searchable.classic")); scan = new Scanner(prop.getProperty("field.searchable.classic")); scan.useDelimiter(","); while (scan.hasNext()) { classicXMLTags.add(scan.next().replaceAll(" ", "")); } File paramDir = new File(propertyDir); String [] paramFiles = paramDir.list(); for (String filename:paramFiles) { if (filename.startsWith("stylesheet_") && filename.endsWith(".xslt")) { String xsltLang = filename.substring(filename.indexOf("stylesheet_")+11, filename.lastIndexOf(".xslt")); File xsltFile = new File(paramDir,filename); BufferedReader xsltRead; try { xsltRead = new BufferedReader(new FileReader(xsltFile)); String line = xsltRead.readLine(); String interestingXMLTag = null; while (line!=null) { // line = (new String(line.getBytes(),"UTF-8")).toString(); if (interestingXMLTag!=null) { String htmlTag = line.substring(line.indexOf("<br/><b>")+8,line.indexOf("</b><br/>")); if (semXMLTags.contains(interestingXMLTag)) { HashMap<String,String> htmlTagByLang = new HashMap<String, String>(); if (semanticFields.containsKey(interestingXMLTag)) htmlTagByLang = semanticFields.get(interestingXMLTag); htmlTagByLang.put(xsltLang,htmlTag); semanticFields.put(interestingXMLTag, htmlTagByLang); } if (classicXMLTags.contains(interestingXMLTag)) { HashMap<String,String> htmlTagByLang = new HashMap<String, String>(); if (classicFields.containsKey(interestingXMLTag)) htmlTagByLang = classicFields.get(interestingXMLTag); htmlTagByLang.put(xsltLang,htmlTag); classicFields.put(interestingXMLTag, htmlTagByLang); } interestingXMLTag = null; } else //if <xsl:template match="preliminary"> { if (line.contains("<xsl:template match=")) { String tagID = line.substring(line.indexOf("<xsl:template match=")+21, line.lastIndexOf("\"")); if (semXMLTags.contains(tagID)||classicXMLTags.contains(tagID)) interestingXMLTag = tagID; } } line = xsltRead.readLine(); } } catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} } } } /** * Initialization of parameters from the property file * @param propertiesFile */ private void initParameters(File propertiesFile) { // Load the properties file fixedPluginProperties = new Properties() ; try { System.err.println(propertiesFile.getAbsolutePath()+" can read: "+propertiesFile.canRead()); java.io.FileInputStream configurationFile = new java.io.FileInputStream(propertiesFile); fixedPluginProperties.load(configurationFile); } catch (IOException e) { System.out.println("Impossible to find file " + propertiesFile.getAbsolutePath()); } // System.out.println("genericity loaded: "+pluginProperties.getProperty("plugin.generic")); setPrototypeGenericity(new Boolean(fixedPluginProperties.getProperty("plugin.generic"))); // System.out.println("partner loaded: "+pluginProperties.getProperty("plugin.partner")); setDomainPartner(fixedPluginProperties.getProperty("plugin.partner")); // System.out.println("language loaded: "+pluginProperties.getProperty("plugin.language")); language = fixedPluginProperties.getProperty("plugin.language"); String colorParams = fixedPluginProperties.getProperty("categories.colors"); if (colorParams!=null) { Scanner scan = new Scanner(colorParams); scan.useDelimiter(","); while (scan.hasNext()) { String param = scan.next(); String categ = param.substring(0, param.indexOf(":")); Color color = Color.decode(param.substring(param.indexOf("#"))); colorMgr.overrideColor(categ, color, true); } } setSearchableFields(fixedPluginProperties); String autoIndex =(String)fixedPluginProperties.getProperty("plugin.autoindex"); if (autoIndex==null) fixedPluginProperties.setProperty("plugin.autoindex", "false"); indexingProcessor = new SemanticIndexing(new Boolean(autoIndex)); } /** * Indicates whose domain OTR is currently used * @return the current domain partner */ public static String getDomainPartner() { return domainPartner; } public static boolean isPrototypeGeneric() { return isPrototypeGeneric; } /** * @param property * @return true iff the propery is defined in the OTR namespace (not in protege, swrl, etc.) (prop can be a metaproperty) */ public static boolean isOTRProperty(RDFProperty property) { //NOTE does not work with sub-ontologies (they have different namespaces) //SOLUTION: filter out protege and swrl namespaces explicitly //return property.getNamespace().equals(getOWLModel().getNamespaceManager().getDefaultNamespace()) ; String [] forbiddenPrefixes = {"http://www.w3.org/", "http://protege.stanford.edu", "http://swrl.stanford.edu"}; String propertyNameSpace = property.getNamespace(); + if(propertyNameSpace==null) return false; for(String prefix : forbiddenPrefixes){ if(propertyNameSpace.startsWith(prefix)) return false; } return true; } /** * @param prop * @return true iff prop is a domain property */ public static boolean isDomainProperty(RDFProperty prop) { RDFSClass domain = prop.getDomain(false) ; return ObirProject.isOTRProperty(prop) && (domain!=null) && (!domain.equals(model.getOWLNamedClass(OTR.TERM))) && (!domain.equals(model.getOWLNamedClass(OTR.CONCEPT))) && (!domain.equals(model.getOWLNamedClass(OTR.TERM_OCCURRENCE)))&& (!domain.equals(model.getOWLNamedClass(OTR.DOCUMENT)))&& (!domain.equals(model.getOWLNamedClass(OTR.COMPARABLE_CONCEPT))) ; } /** * Sets the genericity of the prototype * @param isPrototypeGeneric boolean to set */ public static void setPrototypeGenericity(boolean isGeneric) { isPrototypeGeneric = isGeneric; } /** * Sets the domain partner, therefore sets the weighting scheme used for retrieval * @param partner "arkeo" for concepts only, "artal" for concepts and relations */ public static void setDomainPartner(String partner) { domainPartner = partner; } /** * Plugin properties getter * @return the properties associated with the plugin */ public static Properties getPluginProperties(){ return fixedPluginProperties; } /** * Language getter * @return the language of the indexed corpus */ public static String getDefaultLanguage() { return language; } /** * Corpus getter * @return the set of documents to work with */ public static Corpus getCorpus() { return corpus; } /** * Increments a counter to give unique IDs to OWL individuals (i.e. term occurrences, concept or document instances) * @return an unused name to use as an ID */ public static String generateNextIndName(){ while (otr.getOntology().getOWLIndividual("Onto_Individual_"+COUNT)!=null) COUNT ++; return "Onto_Individual_"+COUNT; } /** * Resets the OWL individual counter */ public static void restartIndividualNumbering() { COUNT = 0; } /** * OTR getter * @return the current OTR */ public static OTR getOTR() { return otr; } /** * Prot�g� OWL model getter * @return the current OWL model */ public static OWLModel getOWLModel() { return model; } /** * Prot�g� OWL model setter * @param oModel a given OWL model */ public static void setOWLModel(OWLModel oModel) { model = oModel; } /** * Color manager getter * @return the current color manager */ public static ColorManager getColorManager() { return colorMgr; } /** * Copy the file into newFile Path * Works only on Windows... * @param file : the string giving the source filename * @param newFilepath : the string giving the destination filename */ public static void copyFileTo(String file, String newFilepath) { try { java.lang.Runtime l_Runtime = java.lang.Runtime.getRuntime(); String[] cmdArray = new String[3]; cmdArray[0]="cmd"; cmdArray[1]="/c"; cmdArray[2]="\"copy "+file+" "+newFilepath+"\""; java.lang.Process l_Proc = l_Runtime.exec(cmdArray); l_Proc.waitFor(); } catch(java.lang.InterruptedException ie) {ie.printStackTrace();} catch (java.io.IOException ioe) {ioe.printStackTrace();} } /** * Static method to get the first key under which a value is stored into a map. * @param map a given map * @param value the value stored in a map under one (or more) key(s) * @return the first appropriate key */ @SuppressWarnings("unchecked") public static Object getKeyFromValue(Map map,Object value) { for (Object key:map.keySet()) if (map.get(key).equals(value)) return key; return null; } /** * Indexing processor getter * @return the processor in charge of semantic indexing */ public static SemanticIndexing getIndexingProcessor() { return indexingProcessor; } /** * Semantic fields getter * @return the fields of the corpus which are semantically indexed */ public static HashMap<String,HashMap<String,String>> getSemanticFields() { return semanticFields; } /** * Semantic fields getter * @return the fields of the corpus which are classically indexed */ public static HashMap<String,HashMap<String,String>> getClassicFields() { return classicFields; } public static void printDebug(String s) { if (debug) System.out.println(s); } public static ObirProject getInstance() { return instance; } //DB version public static void exportOnlyOTR(OWLModel model,String otrExportName) { //TODO } //Local file version @SuppressWarnings("unchecked") private static void exportOnlyOTR(OWLModel model,File exportOntoFile) { File annotationFile = new File(((JenaOWLModel)model).getOWLFilePath().replace("file:/", "")); if (exportOntoFile.exists()) exportOntoFile.delete(); obir.otr.ObirProject.copyFileTo(annotationFile.getAbsolutePath().replaceAll("/", "\\\\"), exportOntoFile.getAbsolutePath().replaceAll("/", "\\\\")); try { InputStream in = new FileInputStream(exportOntoFile); JenaOWLModel onto = ProtegeOWL.createJenaOWLModelFromInputStream(in); for (OWLIndividual ind:(Collection<OWLIndividual>)onto.getOWLIndividuals()) ind.delete(); HashSet errors = new HashSet(); onto.save(new FileOutputStream(exportOntoFile.getAbsolutePath()), "RDF/XML-ABBREV", errors); } catch (FileNotFoundException e) {e.printStackTrace();} catch (OntologyLoadException e) {e.printStackTrace();} } /** * Actually saves the OTR and corpus annotations into 2 different files * @param isUserTriggered indicates whether the save is manually or automatically triggered */ @SuppressWarnings("unchecked") public static void doSaving(boolean isUserTriggered) { boolean isOTRLocal = true; if (ObirProject.getOWLModel() instanceof OWLDatabaseModel) isOTRLocal = false; String owlfilepath = otr.getPath(); if (isUserTriggered) { if (isOTRLocal) { String ontoBackupPath = owlfilepath.replaceAll("file:///", "")+".bak"; File ontoBackupFile = new File(ontoBackupPath); if (ontoBackupFile.exists()) ontoBackupFile.delete(); obir.otr.ObirProject.copyFileTo(owlfilepath.replaceAll("file:///", "").replaceAll("/", "\\\\"), ontoBackupFile.getAbsolutePath().replaceAll("/", "\\\\")); } else { //TODO copie de sauvegarde de table en BD } } try { Project currentProject = ProjectManager.getProjectManager().getCurrentProject(); if (isUserTriggered) { HashSet errors = new HashSet(); if(currentProject != null) currentProject.save(errors); } else { if (isOTRLocal) { HashSet errors = new HashSet(); File ontoBackup = null; String ontoPath = ((JenaOWLModel)currentProject.getKnowledgeBase()).getOWLFilePath(); if (ontoPath!=null) ontoBackup = new File(ontoPath.replace(".owl", ".tmp").replace("file:/","")); else ontoBackup = new File(new File(currentProject.getProjectDirectoryURI()),"project.tmp"); if (ontoBackup.exists()) ontoBackup.delete(); ontoBackup.createNewFile(); ((JenaOWLModel)getOWLModel()).save(new FileOutputStream(ontoBackup), "RDF/XML-ABBREV", errors); } else { //TODO } } } catch (Exception e) { e.printStackTrace(); } } public static void doOTRExporting(OWLModel model,String key) { // OWLModel model = ObirProject.getInstance().getOWLModel(); if (model instanceof JenaOWLModel) { String filepath = key; if (!filepath.endsWith(".owl")) filepath = filepath+".owl"; File exportedFile = new File(filepath); ObirProject.exportOnlyOTR(model,exportedFile); // return exportedFile; } else if (model instanceof OWLDatabaseModel) { //TODO code permettant l'export // return key; } // return null; } /** * Launches the saving process on current OTR and corpus annotations * @returns true iff the project has been saved */ public static boolean saveProject() { if (!otr.isAutoSaveInProgress()) { System.err.println("Saving project..."); ObirProject.getOWLModel().getOWLProject().getSettingsMap().setString("dynamo_corpus",ObirProject.getCorpus().getDirectoryPath().replace("\\", "/")); (new ObirProject.SaveTask()).run(); } else { return false ; } return true ; } static class AutoInitializer extends Thread { /** * M�thode appel�e dans une autre thread lors de la construction d'un * objet de type Task */ @Override public void run(){ if (!otr.isAutoSaveInProgress()) { getIndexingProcessor().launchIndexing(corpus.getDirectory(),true,true); } } protected void onFailure(Throwable t) { t.printStackTrace(); } } /** * Internal class corresponding to an automatic saving process * @author Axel Reymonet */ public static class AutoSaveTask extends Thread { /** * M�thode appel�e dans une autre thread lors de la construction d'un objet de type Task */ @Override public void run() { boolean retry = false; while (true) { if ( ! retry ) try { java.lang.Thread.sleep(1200000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if ( ! this.interrupted() && otr.isAutoSavePossible()) { retry = false; otr.setAutoSaveInProgress(true); doSaving(false); otr.setAutoSaveInProgress(false); } else { try { java.lang.Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } retry = true; } } } protected void onFailure(Throwable t) { t.printStackTrace(); } } /** * Internal class corresponding to a manual saving process * @author Axel Reymonet */ public static class SaveTask extends Thread{ @Override public void run() { otr.setAutoSavePossible(false); doSaving(true); otr.setAutoSavePossible(true); } } public static class ExportTask extends Thread { OWLModel myModel; String key; public ExportTask(OWLModel model,String pointer) { myModel = model; key = pointer; } @Override public void run() { otr.setAutoSavePossible(false); doOTRExporting(myModel,key); otr.setAutoSavePossible(true); } } /** * Internal class corresponding to a previous project deletion process (basically, its only use is to display a progress bar during the instance deletion) */ public static class DeleteTask extends Thread { /** * M�thode appel�e dans une autre thread lors de la construction d'un objet de type Task */ @SuppressWarnings("unchecked") @Override public void run() { int nb_instances = getOWLModel().getOWLIndividuals().size() ; int i = 0 ; //boolean eventGenerationEnabled = model.setGenerateEventsEnabled(false) ; getOWLModel().setDispatchEventsEnabled(false) ; for (OWLIndividual ind:(Collection<OWLIndividual>)getOWLModel().getOWLIndividuals()) { if (ind!=null) ind.delete(); } getOWLModel().setDispatchEventsEnabled(true) ; SwingUtilities.invokeLater(new Runnable() { public void run() { getOWLModel().flushEvents(); } }); ObirProject.getCorpus().clear(); // resetEditedFiles(); } } public static boolean blockDispatchEvents() { boolean previousDispatchEventState = model.getDispatchEventsEnabled(); if (previousDispatchEventState) { model.setDispatchEventsEnabled(false); return true; } return false; } public static void unblockDispatchEvents(boolean needed) { if (needed) { model.setDispatchEventsEnabled(true) ; SwingUtilities.invokeLater(new Runnable() { public void run() { model.flushEvents(); } }); } } }
true
false
null
null
diff --git a/src/org/meta_environment/rascal/interpreter/strategy/All.java b/src/org/meta_environment/rascal/interpreter/strategy/All.java index 954781fedc..9e19614a1f 100644 --- a/src/org/meta_environment/rascal/interpreter/strategy/All.java +++ b/src/org/meta_environment/rascal/interpreter/strategy/All.java @@ -1,45 +1,45 @@ package org.meta_environment.rascal.interpreter.strategy; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.type.Type; import org.meta_environment.rascal.interpreter.IEvaluatorContext; import org.meta_environment.rascal.interpreter.result.AbstractFunction; import org.meta_environment.rascal.interpreter.result.ElementResult; import org.meta_environment.rascal.interpreter.result.OverloadedFunctionResult; import org.meta_environment.rascal.interpreter.result.Result; public class All extends Strategy { public All(AbstractFunction function) { super(function); } @Override public Result<?> call(Type[] argTypes, IValue[] argValues, IEvaluatorContext ctx) { Visitable result = VisitableFactory.make(argValues[0]); for (int i = 0; i < result.arity(); i++) { IValue child = result.get(i).getValue(); result = result.set(i, VisitableFactory.make(function.call(new Type[]{child.getType()}, new IValue[]{child}, ctx).getValue())); } return new ElementResult<IValue>(result.getValue().getType(), result.getValue(), ctx); } public static IValue makeAll(IValue arg) { if (arg instanceof AbstractFunction) { AbstractFunction function = (AbstractFunction) arg; if (function.isStrategy()) { return new All(new StrategyFunction(function)); } } else if (arg instanceof OverloadedFunctionResult) { OverloadedFunctionResult res = (OverloadedFunctionResult) arg; for (AbstractFunction function: res.iterable()) { - if (function.isTypePreserving()) { + if (function.isStrategy()) { return new All(new StrategyFunction(function)); } } } throw new RuntimeException("Unexpected strategy argument "+arg); } }
true
true
public static IValue makeAll(IValue arg) { if (arg instanceof AbstractFunction) { AbstractFunction function = (AbstractFunction) arg; if (function.isStrategy()) { return new All(new StrategyFunction(function)); } } else if (arg instanceof OverloadedFunctionResult) { OverloadedFunctionResult res = (OverloadedFunctionResult) arg; for (AbstractFunction function: res.iterable()) { if (function.isTypePreserving()) { return new All(new StrategyFunction(function)); } } } throw new RuntimeException("Unexpected strategy argument "+arg); }
public static IValue makeAll(IValue arg) { if (arg instanceof AbstractFunction) { AbstractFunction function = (AbstractFunction) arg; if (function.isStrategy()) { return new All(new StrategyFunction(function)); } } else if (arg instanceof OverloadedFunctionResult) { OverloadedFunctionResult res = (OverloadedFunctionResult) arg; for (AbstractFunction function: res.iterable()) { if (function.isStrategy()) { return new All(new StrategyFunction(function)); } } } throw new RuntimeException("Unexpected strategy argument "+arg); }
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxInitializationBuilder.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxInitializationBuilder.java index e706b63bd..f91ef60f1 100755 --- a/src/share/classes/com/sun/tools/javafx/comp/JavafxInitializationBuilder.java +++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxInitializationBuilder.java @@ -1,2161 +1,2164 @@ /* * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.tools.javafx.comp; import com.sun.tools.mjavac.code.*; import com.sun.tools.mjavac.code.Scope.Entry; import com.sun.tools.mjavac.code.Symbol.ClassSymbol; import com.sun.tools.mjavac.code.Symbol.MethodSymbol; import com.sun.tools.mjavac.code.Symbol.VarSymbol; import com.sun.tools.mjavac.tree.JCTree; import com.sun.tools.mjavac.tree.JCTree.*; import com.sun.tools.mjavac.util.*; import com.sun.tools.mjavac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javafx.code.JavafxFlags; import com.sun.tools.javafx.code.JavafxSymtab; import com.sun.tools.javafx.comp.JavafxAnalyzeClass.*; import static com.sun.tools.javafx.comp.JavafxDefs.*; import com.sun.tools.javafx.tree.*; import java.util.HashMap; import java.util.HashSet; import java.util.Map; /** * Build the representation(s) of a JavaFX class. Includes class initialization, attribute and function proxies. * With support for mixins. * * @author Robert Field * @author Lubo Litchev * @author Per Bothner * @author Zhiqun Chen * @author Jim Laskey */ public class JavafxInitializationBuilder extends JavafxTranslationSupport { protected static final Context.Key<JavafxInitializationBuilder> javafxInitializationBuilderKey = new Context.Key<JavafxInitializationBuilder>(); static final boolean SCRIPT_LEVEL_AT_TOP = true; private final JavafxToJava toJava; private final JavafxClassReader reader; private final JavafxOptimizationStatistics optStat; private static final int VFLAG_IS_INITIALIZED = 0; private static final int VFLAG_DEFAULTS_APPLIED = 1; private static final int VFLAG_BITS_PER_VAR = 2; private Name outerAccessorFieldName; private Name makeInitMap; private Name updateInstanceName; private Name varNumName; private Name varLocalNumName; private Name varWordName; private Name varChangedName; private Name varOldValueName; private Name varNewValueName; final Type assignBindExceptionType; final Type assignDefExceptionType; void TODO() { throw new RuntimeException("Not yet implemented"); } public static class LiteralInitVarMap { private int count = 1; public Map<VarSymbol, Integer> varMap = new HashMap<VarSymbol, Integer>(); public ListBuffer<VarSymbol> varList = ListBuffer.lb(); public int addVar(VarSymbol sym) { Integer value = varMap.get(sym); if (value == null) { value = new Integer(count++); varMap.put(sym, value); varList.append(sym); } return value.intValue(); } public int size() { return varMap.size(); } } public static class LiteralInitClassMap { public Map<ClassSymbol, LiteralInitVarMap> classMap = new HashMap<ClassSymbol, LiteralInitVarMap>(); public LiteralInitVarMap getVarMap(ClassSymbol sym) { LiteralInitVarMap map = classMap.get(sym); if (map == null) { map = new LiteralInitVarMap(); classMap.put(sym, map); } return map; } public int size() { return classMap.size(); } } public static JavafxInitializationBuilder instance(Context context) { JavafxInitializationBuilder instance = context.get(javafxInitializationBuilderKey); if (instance == null) instance = new JavafxInitializationBuilder(context); return instance; } protected JavafxInitializationBuilder(Context context) { super(context); context.put(javafxInitializationBuilderKey, this); toJava = JavafxToJava.instance(context); reader = (JavafxClassReader) JavafxClassReader.instance(context); optStat = JavafxOptimizationStatistics.instance(context); outerAccessorFieldName = names.fromString("accessOuterField$"); makeInitMap = names.fromString("makeInitMap$"); updateInstanceName = names.fromString("instance$"); varNumName = names.fromString("varNum$"); varLocalNumName = names.fromString("varLocalNum$"); varWordName = names.fromString("varWord$"); varChangedName = names.fromString("varChanged$"); varOldValueName = names.fromString("varOldValue$"); varNewValueName = names.fromString("varNewValue$"); { Name name = names.fromString(runtimePackageNameString + ".AssignToBoundException"); ClassSymbol sym = reader.jreader.enterClass(name); assignBindExceptionType = types.erasure( sym.type ); } { Name name = names.fromString(runtimePackageNameString + ".AssignToDefException"); ClassSymbol sym = reader.enterClass(name); assignDefExceptionType = types.erasure( sym.type ); } } /** * Hold the result of analyzing the class. * */ static class JavafxClassModel { final Name interfaceName; final List<JCExpression> interfaces; final List<JCTree> iDefinitions; final List<JCTree> additionalClassMembers; final List<JCExpression> additionalImports; final Type superType; final ClassSymbol superClassSym; final List<ClassSymbol> superClasses; final List<ClassSymbol> immediateMixins; final List<ClassSymbol> allMixins; JavafxClassModel( Name interfaceName, List<JCExpression> interfaces, List<JCTree> iDefinitions, List<JCTree> addedClassMembers, List<JCExpression> additionalImports, Type superType, ClassSymbol superClassSym, List<ClassSymbol> superClasses, List<ClassSymbol> immediateMixins, List<ClassSymbol> allMixins) { this.interfaceName = interfaceName; this.interfaces = interfaces; this.iDefinitions = iDefinitions; this.additionalClassMembers = addedClassMembers; this.additionalImports = additionalImports; this.superType = superType; this.superClassSym = superClassSym; this.superClasses = superClasses; this.immediateMixins = immediateMixins; this.allMixins = allMixins; } } /** * Analyze the class. * * Determine what methods will be needed to access attributes. * Determine what methods will be needed to proxy to the static implementations of functions. * Determine what other misc fields and methods will be needed. * Create the corresponding interface. * * Return all this as a JavafxClassModel for use in translation. * */ JavafxClassModel createJFXClassModel(JFXClassDeclaration cDecl, List<TranslatedVarInfo> translatedAttrInfo, List<TranslatedOverrideClassVarInfo> translatedOverrideAttrInfo, List<TranslatedFuncInfo> translatedFuncInfo, LiteralInitClassMap initClassMap, ListBuffer<JCStatement> translatedInitBlocks, ListBuffer<JCStatement> translatedPostInitBlocks) { DiagnosticPosition diagPos = cDecl.pos(); Type superType = types.superType(cDecl); ClassSymbol outerTypeSym = outerTypeSymbol(cDecl); // null unless inner class with outer reference boolean isLibrary = toJava.getAttrEnv().toplevel.isLibrary; boolean isRunnable = toJava.getAttrEnv().toplevel.isRunnable; JavafxAnalyzeClass analysis = new JavafxAnalyzeClass(diagPos, cDecl.sym, translatedAttrInfo, translatedOverrideAttrInfo, translatedFuncInfo, names, types, reader, typeMorpher); JavaCodeMaker javaCodeMaker = new JavaCodeMaker(analysis); List<VarInfo> classVarInfos = analysis.classVarInfos(); List<VarInfo> scriptVarInfos = analysis.scriptVarInfos(); List<FuncInfo> classFuncInfos = analysis.classFuncInfos(); List<FuncInfo> scriptFuncInfos = analysis.scriptFuncInfos(); boolean hasStatics = !scriptVarInfos.isEmpty() || !scriptFuncInfos.isEmpty(); int classVarCount = analysis.getClassVarCount(); int scriptVarCount = analysis.getScriptVarCount(); List<MethodSymbol> needDispatch = analysis.needDispatch(); ClassSymbol fxSuperClassSym = analysis.getFXSuperClassSym(); List<ClassSymbol> superClasses = analysis.getSuperClasses(); List<ClassSymbol> immediateMixinClasses = analysis.getImmediateMixins(); List<ClassSymbol> allMixinClasses = analysis.getAllMixins(); boolean isMixinClass = cDecl.isMixinClass(); boolean isScriptClass = cDecl.isScriptClass(); boolean isAnonClass = analysis.isAnonClass(); boolean hasFxSuper = fxSuperClassSym != null; // Have to populate the var map for anon classes. // TODO: figure away to avoid this if not used (needs global knowledge.) LiteralInitVarMap varMap = isAnonClass ? initClassMap.getVarMap(analysis.getCurrentClassSymbol()) : null; ListBuffer<JCTree> cDefinitions = ListBuffer.lb(); // additional class members needed ListBuffer<JCTree> iDefinitions = ListBuffer.lb(); if (!isMixinClass) { cDefinitions.appendList(javaCodeMaker.makeAttributeNumbers(classVarInfos, classVarCount, varMap)); cDefinitions.appendList(javaCodeMaker.makeAttributeFields(classVarInfos)); cDefinitions.appendList(javaCodeMaker.makeAttributeAccessorMethods(classVarInfos)); cDefinitions.appendList(javaCodeMaker.makeApplyDefaultsMethod()); cDefinitions.appendList(javaCodeMaker.makeUpdateMethod()); JCStatement initMap = isAnonClass ? javaCodeMaker.makeInitVarMapInit(varMap) : null; if (outerTypeSym == null) { cDefinitions.append(javaCodeMaker.makeJavaEntryConstructor()); } else { cDefinitions.append(javaCodeMaker.makeOuterAccessorField(outerTypeSym)); cDefinitions.append(javaCodeMaker.makeOuterAccessorMethod(outerTypeSym)); } cDefinitions.appendList(javaCodeMaker.makeFunctionProxyMethods(needDispatch)); cDefinitions.append(javaCodeMaker.makeFXEntryConstructor(outerTypeSym)); cDefinitions.appendList(javaCodeMaker.makeInitMethod(defs.userInitName, translatedInitBlocks, immediateMixinClasses)); cDefinitions.appendList(javaCodeMaker.makeInitMethod(defs.postInitName, translatedPostInitBlocks, immediateMixinClasses)); cDefinitions.appendList(javaCodeMaker.gatherFunctions(classFuncInfos)); if (isScriptClass && hasStatics) { Name scriptName = cDecl.getName().append(defs.scriptClassSuffixName); ListBuffer<JCTree> sDefinitions = ListBuffer.lb(); if (SCRIPT_LEVEL_AT_TOP) { // With this approach script-level attribute fields and methods, functions, and class maps are top-level statics // script-level into class X cDefinitions.appendList(javaCodeMaker.makeAttributeFields(scriptVarInfos)); cDefinitions.appendList(javaCodeMaker.makeAttributeAccessorMethods(scriptVarInfos)); cDefinitions.appendList(javaCodeMaker.gatherFunctions(scriptFuncInfos)); cDefinitions.appendList(javaCodeMaker.makeInitClassMaps(initClassMap)); // script-level into class X.X$Script sDefinitions.appendList(javaCodeMaker.makeAttributeNumbers(scriptVarInfos, scriptVarCount, null)); sDefinitions.appendList(javaCodeMaker.makeUpdateMethod()); sDefinitions.appendList(javaCodeMaker.makeScriptLevelAccess(scriptName, true, isRunnable)); //needed: sDefinitions.appendList(javaCodeMaker.makeApplyDefaultsMethod()); } else { // With this approach all script-level members and support statics are in script-class sDefinitions.appendList(javaCodeMaker.makeAttributeNumbers(scriptVarInfos, scriptVarCount, null)); sDefinitions.appendList(javaCodeMaker.makeAttributeFields(scriptVarInfos)); sDefinitions.appendList(javaCodeMaker.makeAttributeAccessorMethods(scriptVarInfos)); sDefinitions.appendList(javaCodeMaker.makeInitClassMaps(initClassMap)); sDefinitions.appendList(javaCodeMaker.makeUpdateMethod()); sDefinitions.appendList(javaCodeMaker.gatherFunctions(scriptFuncInfos)); sDefinitions.appendList(javaCodeMaker.makeScriptLevelAccess(scriptName, true, isRunnable)); } JCClassDecl script = javaCodeMaker.makeScript(scriptName, sDefinitions.toList()); cDefinitions.appendList(javaCodeMaker.makeScriptLevelAccess(scriptName, false, isRunnable)); cDefinitions.append(javaCodeMaker.makeInitStaticAttributesBlock(scriptName, scriptVarInfos, initMap)); cDefinitions.append(script); } else { cDefinitions.append(javaCodeMaker.makeInitStaticAttributesBlock(null, null, initMap)); } if (!hasFxSuper) { // Has a non-JavaFX super, so we can't use FXBase, therefore we need // to clone the necessary vars and methods. // This code must be after all methods have been added to cDefinitions, // A set of methods to exclude from cloning. HashSet<String> excludes = new HashSet<String>(); // Exclude any methods generated by the init builder. for (JCTree member : cDefinitions) { if (member.getTag() == JCTree.METHODDEF) { JCMethodDecl jcmeth = (JCMethodDecl)member; excludes.add(jcMethodDeclStr(jcmeth)); } } // Clone what is needed from FXBase/FXObject. cDefinitions.appendList(javaCodeMaker.cloneFXBase(excludes)); } } else { // Mixin class cDefinitions.appendList(javaCodeMaker.makeAttributeFields(classVarInfos)); iDefinitions.appendList(javaCodeMaker.makeMemberVariableAccessorInterfaceMethods()); // Static(script) vars are exposed in class cDefinitions.appendList(javaCodeMaker.makeAttributeFields(scriptVarInfos)); cDefinitions.appendList(javaCodeMaker.makeAttributeAccessorMethods(scriptVarInfos)); cDefinitions.appendList(javaCodeMaker.makeUpdateMethod()); cDefinitions.append (javaCodeMaker.makeInitStaticAttributesBlock(null, null, null)); cDefinitions.appendList(javaCodeMaker.makeMixinAccessorMethods(classVarInfos)); iDefinitions.appendList(javaCodeMaker.makeFunctionInterfaceMethods()); iDefinitions.appendList(javaCodeMaker.makeOuterAccessorInterfaceMembers()); cDefinitions.appendList(javaCodeMaker.makeInitMethod(defs.userInitName, translatedInitBlocks, immediateMixinClasses)); cDefinitions.appendList(javaCodeMaker.makeInitMethod(defs.postInitName, translatedPostInitBlocks, immediateMixinClasses)); cDefinitions.appendList(javaCodeMaker.gatherFunctions(classFuncInfos)); } Name interfaceName = isMixinClass ? interfaceName(cDecl) : null; return new JavafxClassModel( interfaceName, makeImplementingInterfaces(diagPos, cDecl, immediateMixinClasses), iDefinitions.toList(), cDefinitions.toList(), makeAdditionalImports(diagPos, cDecl, immediateMixinClasses), superType, fxSuperClassSym, superClasses, immediateMixinClasses, allMixinClasses); } // // Build a string that can be compared against MethodSymbol.toString() // private static String jcMethodDeclStr(JCMethodDecl meth) { String str = meth.name.toString() + "("; boolean needsComma = false; for (JCVariableDecl varDecl : meth.getParameters()) { if (needsComma) str += ","; str += varDecl.vartype.toString(); needsComma = true; } str += ")"; return str; } private List<JCExpression> makeImplementingInterfaces(DiagnosticPosition diagPos, JFXClassDeclaration cDecl, List<ClassSymbol> baseInterfaces) { ListBuffer<JCExpression> implementing = ListBuffer.lb(); if (cDecl.isMixinClass()) { implementing.append(makeIdentifier(diagPos, fxObjectString)); implementing.append(makeIdentifier(diagPos, fxMixinString)); } else { implementing.append(makeIdentifier(diagPos, fxObjectString)); } for (JFXExpression intf : cDecl.getImplementing()) { implementing.append(makeType(diagPos, intf.type, false)); } for (ClassSymbol baseClass : baseInterfaces) { implementing.append(makeType(diagPos, baseClass.type, true)); } return implementing.toList(); } private List<JCExpression> makeAdditionalImports(DiagnosticPosition diagPos, JFXClassDeclaration cDecl, List<ClassSymbol> baseInterfaces) { // Add import statements for all the base classes and basClass $Mixin(s). // There might be references to them when the methods/attributes are rolled up. ListBuffer<JCExpression> additionalImports = new ListBuffer<JCExpression>(); for (ClassSymbol baseClass : baseInterfaces) { if (baseClass.type != null && baseClass.type.tsym != null && baseClass.type.tsym.packge() != cDecl.sym.packge() && // Work around javac bug (CR 6695838) baseClass.type.tsym.packge() != syms.unnamedPackage) { // Work around javac bug. the visitImport of Attr // is casting to JCFieldAcces, but if you have imported an // JCIdent only a ClassCastException is thrown. additionalImports.append(makeType( diagPos,baseClass.type, false)); additionalImports.append(makeType( diagPos,baseClass.type, true)); } } return additionalImports.toList(); } // Add the methods and field for accessing the outer members. Also add a constructor with an extra parameter // to handle the instantiation of the classes that access outer members private ClassSymbol outerTypeSymbol(JFXClassDeclaration cdecl) { if (cdecl.sym != null && toJava.getHasOuters().contains(cdecl.sym)) { Symbol typeOwner = cdecl.sym.owner; while (typeOwner != null && typeOwner.kind != Kinds.TYP) { typeOwner = typeOwner.owner; } if (typeOwner != null) { // Only return an interface class if it's a mixin. return !isMixinClass((ClassSymbol)typeOwner) ? (ClassSymbol)typeOwner.type.tsym : reader.jreader.enterClass(names.fromString(typeOwner.type.toString() + mixinSuffix)); } } return null; } protected String getSyntheticPrefix() { return "ifx$"; } //----------------------------------------------------------------------------------------------------------------------------- // // This class is used to simplify the construction of java code in the // initialization builder. // class JavaCodeMaker extends JavaTreeBuilder { // The current class analysis/ private final JavafxAnalyzeClass analysis; JavaCodeMaker(JavafxAnalyzeClass analysis) { super(analysis.getCurrentClassPos()); this.analysis = analysis; } // // Methods for managing the current diagnostic position. // private void setDiagPos(VarInfo ai) { setDiagPos(ai.pos()); } private void resetDiagPos() { setDiagPos(analysis.getCurrentClassPos()); } // // Returns the current class decl. // public JFXClassDeclaration getCurrentClassDecl() { return analysis.getCurrentClassDecl(); } // // Returns the current class symbol. // public ClassSymbol getCurrentClassSymbol() { return analysis.getCurrentClassSymbol(); } // // Returns true if the sym is the current class symbol. // public boolean isCurrentClassSymbol(Symbol sym) { return analysis.isCurrentClassSymbol(sym); } // // Returns true if the current class is a mixin. // public boolean isMixinClass() { return analysis.isMixinClass(); } // // // This method generates a simple java integer field then adds to the buffer. // private JCVariableDecl addSimpleIntVariable(long modifiers, Name name, int value) { // Construct the variable itself. return makeVar(modifiers, syms.intType, name, makeInt(value)); } // // This method generates a java field for a varInfo. // private JCVariableDecl makeVariableField(VarInfo varInfo, JCModifiers mods, Type varType, Name name, JCExpression varInit) { setDiagPos(varInfo); // Define the type. JCExpression type = makeType(varType); // Construct the variable itself. JCVariableDecl var = m().VarDef(mods, name, type, varInit); // Update the statistics. optStat.recordClassVar(varInfo.getSymbol()); optStat.recordConcreteField(); return var; } // // Build the location and value field for each attribute. // public List<JCTree> makeAttributeFields(List<? extends VarInfo> attrInfos) { // Buffer for new vars. ListBuffer<JCTree> vars = ListBuffer.lb(); for (VarInfo ai : attrInfos) { // Only process attributes declared in this class (includes mixins.) if (ai.needsCloning() && !ai.isOverride()) { // Set the current diagnostic position. setDiagPos(ai); // Grab the variable symbol. VarSymbol varSym = ai.getSymbol(); // The fields need to be available to reflection. // TODO deal with defs. JCModifiers mods = m().Modifiers(Flags.PUBLIC | (ai.getFlags() & Flags.STATIC)); // Apply annotations, if current class then add source annotations. if (isCurrentClassSymbol(varSym.owner)) { List<JCAnnotation> annotations = List.<JCAnnotation>of(m().Annotation( makeIdentifier(diagPos, JavafxSymtab.sourceNameAnnotationClassNameString), List.<JCExpression>of(m().Literal(varSym.name.toString())))); mods = addAccessAnnotationModifiers(diagPos, varSym.flags(), mods, annotations); } else { mods = addInheritedAnnotationModifiers(diagPos, varSym.flags(), mods); } // Construct the value field vars.append(makeVariableField(ai, mods, ai.getRealType(), attributeValueName(varSym), needsDefaultValue(ai.getVMI()) ? makeDefaultValue(diagPos, ai.getVMI()) : null)); } } return vars.toList(); } // // This method constructs modifiers for getters/setters and proxies. // private JCModifiers proxyModifiers(VarInfo ai, boolean isAbstract) { // Copy old flags from VarInfo. long oldFlags = ai.getFlags(); // Determine new flags. long newFlags = (oldFlags & Flags.STATIC) | Flags.PUBLIC; if (isAbstract) { newFlags|= Flags.ABSTRACT; } else if (isMixinClass()) { newFlags|= Flags.STATIC; } // Set up basic flags. JCModifiers mods = m().Modifiers(newFlags); // If var is in current class. if (isCurrentClassSymbol(ai.getSymbol().owner)) { // Use local access modifiers. mods = addAccessAnnotationModifiers(ai.pos(), oldFlags, mods); } else { // Use inherited modifiers. mods = addInheritedAnnotationModifiers(ai.pos(), oldFlags, mods); } return mods; } // // These methods return an expression for testing/setting/clearing a var flag. // JCExpression makeFlagExpression(VarSymbol varSym, String action, String flag) { return call( getReceiver(varSym), names.fromString(action + flag), getVOFF(varSym)); } // // These methods returns a statement for setting/clearing a var flag. // JCStatement makeFlagStatement(VarSymbol varSym, String action, String flag) { return makeExec(makeFlagExpression(varSym, action, flag)); } // // Generate a reference to the VOFF$ . // For static vars this is: pkg.X.X$Script.VOFF$varName // For instance vars this is just: VOFF$varName // private JCExpression getVOFF(VarSymbol varSym) { JCExpression context = null; if (varSym.isStatic()) { // construct a script-level class reference expression // pkg.X.X$Script context = select( makeType(getCurrentClassSymbol().type, false), getCurrentClassSymbol().getSimpleName().append(defs.scriptClassSuffixName)); } return select(context, attributeOffsetName(varSym)); } // // Return a receiver$ ident if is a mixin otherwise null. // private JCExpression getReceiver() { if (isMixinClass()) { return id(defs.receiverName); } return null; } private JCExpression getReceiver(VarSymbol varSym) { if (varSym.isStatic()) { return call(defs.scriptLevelAccessMethod); } return getReceiver(); } private JCExpression getReceiver(VarInfo varInfo) { return getReceiver(varInfo.getSymbol()); } // // This method gathers all the translated functions in funcInfos. // public List<JCTree> gatherFunctions(List<FuncInfo> funcInfos) { ListBuffer<JCTree> buffer = ListBuffer.lb(); for (FuncInfo func : funcInfos) { if (func instanceof TranslatedFuncInfo) { buffer.appendList(((TranslatedFuncInfo)func).jcFunction()); } } return buffer.toList(); } // // Return a parameter list, prefixing the receiver if a mixin. // private List<JCVariableDecl> makeParamList(boolean isAbstract, JCVariableDecl... params) { ListBuffer<JCVariableDecl> buffer = ListBuffer.lb(); if (isMixinClass() && !isAbstract) { buffer.append(makeReceiverParam(getCurrentClassDecl())); } for (JCVariableDecl param : params) { buffer.append(param); } return buffer.toList(); } // // This method constructs the getter method for the specified attribute. // private JCTree makeGetterAccessorMethod(VarInfo varInfo, boolean needsBody) { // Symbol used on the method. VarSymbol varSym = varInfo.getSymbol(); // Real type for var. Type type = varInfo.getRealType(); // Assume no body. ListBuffer<JCStatement> stmts = null; if (needsBody) { // Prepare to accumulate statements. stmts = ListBuffer.lb(); // Symbol used when accessing the variable. VarSymbol proxyVarSym = varInfo.proxyVarSym(); // Name of variable. Name name = attributeValueName(proxyVarSym); if (varInfo.hasBoundDefinition() || varInfo.isMixinVar()) { // !isValidValue$(VOFF$var) JCExpression condition = makeNot(makeFlagExpression(proxyVarSym, varFlagActionTest, varFlagValid)); // Prepare to accumulate body of if. ListBuffer<JCStatement> ifStmts = ListBuffer.lb(); // Set to new value. if (varInfo.isMixinVar()) { // Mixin.evaluate$var(this); ifStmts.append(makeSuperCall((ClassSymbol)varSym.owner, attributeEvaluateName(varSym), id(names._this))); // setIsValidValue(VOFF$var); ifStmts.append(makeFlagStatement(proxyVarSym, varFlagActionSet, varFlagValid)); } else { assert varInfo.boundInit() != null : "Oops! No boundInit. varInfo = " + varInfo + ", preface = " + varInfo.boundPreface(); // set$var(init/bound expression) ifStmts.appendList(varInfo.boundPreface()); ifStmts.append(callStmt(getReceiver(), attributeBeName(varSym), varInfo.boundInit())); } // if (!isValidValue$(VOFF$var)) { set$var(init/bound expression); } stmts.append(m().If(condition, m().Block(0L, ifStmts.toList()), null)); } // Construct and add: return $var; stmts.append(m().Return(id(name))); } // Construct method. JCMethodDecl method = makeMethod(proxyModifiers(varInfo, !needsBody), type, attributeGetterName(varSym), makeParamList(!needsBody), stmts); optStat.recordProxyMethod(); return method; } // // This method constructs the setter method for the specified attribute. // private JCTree makeSetterAccessorMethod(VarInfo varInfo, boolean needsBody) { // Symbol used on the method. VarSymbol varSym = varInfo.getSymbol(); // Real type for var. Type type = varInfo.getRealType(); // Assume no body. ListBuffer<JCStatement> stmts = null; if (needsBody) { // Prepare to accumulate statements. stmts = ListBuffer.lb(); if (varInfo.hasBoundDefinition() && !varInfo.hasBiDiBoundDefinition()) { stmts.append(makeThrow(assignBindExceptionType)); } else if (varInfo.isDef()) { stmts.append(makeThrow(assignDefExceptionType)); } else { // Symbol used when accessing the variable. VarSymbol proxyVarSym = varInfo.proxyVarSym(); // $var Name varName = attributeValueName(proxyVarSym); // set$var(value) stmts.append(callStmt(getReceiver(), attributeBeName(varSym), id(varNewValueName))); // return $var; stmts.append(m().Return(id(varName))); } } // Construct method. JCMethodDecl method = makeMethod(proxyModifiers(varInfo, !needsBody), type, attributeSetterName(varSym), makeParamList(!needsBody, makeParam(type, varNewValueName)), stmts); optStat.recordProxyMethod(); return method; } // // This method constructs the be method for the specified attribute. // private JCTree makeBeAccessorMethod(VarInfo varInfo, boolean needsBody) { // Symbol used on the method. VarSymbol varSym = varInfo.getSymbol(); // Real type for var. Type type = varInfo.getRealType(); // Assume no body. ListBuffer<JCStatement> stmts = null; if (needsBody) { // Prepare to accumulate statements. stmts = ListBuffer.lb(); // Symbol used when accessing the variable. VarSymbol proxyVarSym = varInfo.proxyVarSym(); // $var Name varName = attributeValueName(proxyVarSym); // T varOldValue$ = $var; stmts.append(makeVar(Flags.FINAL, type, varOldValueName, id(varName))); // Prepare to accumulate trigger statements. ListBuffer<JCStatement> ifStmts = ListBuffer.lb(); // $var = value ifStmts.append(makeExec(m().Assign(id(varName), id(varNewValueName)))); // invalidate$() ifStmts.append(callStmt(getReceiver(), attributeInvalidateName(varSym))); // setIsValidValue(VOFF$var); ifStmts.append(makeFlagStatement(proxyVarSym, varFlagActionSet, varFlagValid)); // onReplace$(varOldValue$, varNewValue$) ifStmts.append(callStmt(getReceiver(), attributeOnReplaceName(varSym), id(varOldValueName), id(varNewValueName))); // varOldValue$ != varNewValue$ // or !varOldValue$.isEquals(varNewValue$) test for Objects and Sequences JCExpression testExpr = type.isPrimitive() ? makeNotEqual(id(varOldValueName), id(varNewValueName)) : makeNot(runtime(diagPos, defs.Util_isEqual, List.<JCExpression>of(id(varOldValueName), id(varNewValueName)))); // if (varOldValue$ != varNewValue$) { handle change } stmts.append(m().If(testExpr, m().Block(0L, ifStmts.toList()), null)); + + // return $var; + stmts.append(m().Return(id(varName))); } // Construct method. JCMethodDecl method = makeMethod(proxyModifiers(varInfo, !needsBody), - syms.voidType, + type, attributeBeName(varSym), makeParamList(!needsBody, makeParam(type, varNewValueName)), stmts); optStat.recordProxyMethod(); return method; } // // Determine if this override needs an invalidate method // Must be in sync with makeInvalidateAccessorMethod // private boolean needOverrideInvalidateAccessorMethod(VarInfo varInfo) { if (varInfo.hasBoundDefinition()) { return false; } if (varInfo.isMixinVar()) { // based on makeInvalidateAccessorMethod return true; } else { if (varInfo instanceof TranslatedVarInfoBase) { return ((TranslatedVarInfoBase) varInfo).boundBinders().nonEmpty(); } else { return false; } } } // // This method constructs the invalidate method for the specified attribute. // private JCTree makeInvalidateAccessorMethod(VarInfo varInfo, boolean needsBody) { // Symbol used on the method. VarSymbol varSym = varInfo.getSymbol(); // Assume no body. ListBuffer<JCStatement> stmts = null; if (needsBody) { // Prepare to accumulate statements. stmts = ListBuffer.lb(); // Symbol used when accessing the variable. VarSymbol proxyVarSym = varInfo.proxyVarSym(); // Prepare to accumulate if statements. ListBuffer<JCStatement> ifStmts = ListBuffer.lb(); // Debug tracing stmts.appendList(makeDebugTrace(attributeInvalidateName(varSym) + " called")); ifStmts.appendList(makeDebugTrace(attributeInvalidateName(varSym) + " entered")); // Call super first. ClassSymbol superClassSym = analysis.getFXSuperClassSym(); boolean isOverride = varInfo.isOverride() && superClassSym != null; if (isOverride) { ifStmts.append(makeSuperCall(superClassSym, attributeInvalidateName(varSym))); } // clearValidValue$(VOFF$var); if (!isOverride) { ifStmts.append(makeFlagStatement(proxyVarSym, varFlagActionClear, varFlagValid)); } // Handle binders. if (varInfo.isMixinVar()) { // Mixin.onReplace$var(this, oldValue, newValue); ifStmts.append(makeSuperCall((ClassSymbol)varSym.owner, attributeInvalidateName(varSym), id(names._this))); } else { if (varInfo instanceof TranslatedVarInfoBase) { for (VarSymbol otherVarSym : ((TranslatedVarInfoBase)varInfo).boundBinders()) { // invalidate$var(); ifStmts.append(callStmt(getReceiver(), attributeInvalidateName(otherVarSym))); } } } // notifyDependents(VOFF$var); if (!isOverride) { ifStmts.append(callStmt(getReceiver(varInfo), defs.attributeNotifyDependentsName, getVOFF(proxyVarSym))); } // isValid JCExpression test = makeFlagExpression(proxyVarSym, varFlagActionTest, varFlagValid); // if (!isValidValue$(VOFF$var)) { ... invalidate code ... } stmts.append(m().If(test, m().Block(0L, ifStmts.toList()), null)); } // Construct method. JCMethodDecl method = makeMethod(proxyModifiers(varInfo, !needsBody), syms.voidType, attributeInvalidateName(varSym), makeParamList(!needsBody), stmts); optStat.recordProxyMethod(); return method; } // // This method constructs the onreplace$ method for the specified attribute. // private JCTree makeOnReplaceAccessorMethod(VarInfo varInfo, boolean needsBody) { // Symbol used on the method. VarSymbol varSym = varInfo.getSymbol(); // Real type for var. Type type = varInfo.getRealType(); // Assume no body. ListBuffer<JCStatement> stmts = null; // Assume the onReplace arg names. Name oldValueName = varOldValueName; Name newValueName = varNewValueName; if (needsBody) { // Prepare to accumulate statements. stmts = ListBuffer.lb(); // Forward to the mixin. if (!isMixinClass() && varInfo.isMixinVar()) { // Mixin.onReplace$var(this, oldValue, newValue); stmts.append(makeSuperCall((ClassSymbol)varSym.owner, attributeOnReplaceName(varSym), id(names._this), id(oldValueName), id(newValueName))); } else { // Symbol used when accessing the variable. VarSymbol proxyVarSym = varInfo.proxyVarSym(); // Fetch the on replace statement or null. JCStatement onReplace = varInfo.onReplaceAsInline(); // Need to capture init state if has trigger. if (onReplace != null) { // Gather specified var info. JFXVar oldVar = varInfo.onReplace().getOldValue(); JFXVar newVar = varInfo.onReplace().getNewElements(); // Check to see if the on replace has an old value. if (oldVar != null) { // Change the onReplace arg name. oldValueName = oldVar.getName(); } // Check to see if the on replace has a new value. if (newVar != null) { // Change the onReplace arg name. newValueName = newVar.getName(); } // Insert the trigger. stmts.append(onReplace); } // Call super first. ClassSymbol superClassSym = analysis.getFXSuperClassSym(); if (varInfo.isOverride() && superClassSym != null) { stmts.prepend(makeSuperCall(superClassSym, attributeOnReplaceName(varSym), id(oldValueName), id(newValueName))); } } } // Construct method. JCMethodDecl method = makeMethod(proxyModifiers(varInfo, !needsBody), syms.voidType, attributeOnReplaceName(varSym), makeParamList(!needsBody, makeParam(type, oldValueName), makeParam(type, newValueName)), stmts); optStat.recordProxyMethod(); return method; } // // This method constructs a mixin applyDefault method. // private List<JCTree> makeMixinApplyDefaultsMethod(VarInfo varInfo) { // Prepare to accumulate methods. ListBuffer<JCTree> methods = ListBuffer.lb(); // Fetch the attribute symbol. VarSymbol varSym = varInfo.getSymbol(); // True if the the user specified a default. boolean hasDefault = varInfo.getDefaultInitStatement() != null; // If the var is defined in the current class or it has a (override) default. if (isCurrentClassSymbol(varSym.owner) || hasDefault) { // Prepare to accumulate statements. ListBuffer<JCStatement> stmts = ListBuffer.lb(); // Get body of applyDefaults$. JCStatement deflt = makeApplyDefaultsStatement(varInfo, true); if (deflt != null) { stmts.append(deflt); } // Mixins need a receiver arg. List<JCVariableDecl> args = List.<JCVariableDecl>of(makeReceiverParam(getCurrentClassDecl())); // Construct method. JCMethodDecl method = makeMethod(Flags.PUBLIC | Flags.STATIC, syms.voidType, attributeApplyDefaultsName(varSym), makeParamList(false), stmts); methods.append(method); } return methods.toList(); } // // This method constructs a mixin evaluate method. // private List<JCTree> makeMixinEvaluateAccessorMethod(VarInfo varInfo) { // Prepare to accumulate methods. ListBuffer<JCTree> methods = ListBuffer.lb(); // Fetch the attribute symbol. VarSymbol varSym = varInfo.getSymbol(); // If the var is defined in the current class or it has a bind. if (isCurrentClassSymbol(varSym.owner) || varInfo.hasBoundDefinition()) { // Prepare to accumulate statements. ListBuffer<JCStatement> stmts = ListBuffer.lb(); if (varInfo.hasBoundDefinition()) { assert varInfo.boundInit() != null; // set$var(init/bound expression) stmts.appendList(varInfo.boundPreface()); stmts.append(callStmt(getReceiver(), attributeBeName(varSym), varInfo.boundInit())); } // Construct method. JCMethodDecl method = makeMethod(Flags.PUBLIC | Flags.STATIC, syms.voidType, attributeEvaluateName(varSym), makeParamList(false), stmts); methods.append(method); } return methods.toList(); } // // This method constructs a mixin invalidate method. // private List<JCTree> makeMixinInvalidateAccessorMethod(VarInfo varInfo) { // Prepare to accumulate methods. ListBuffer<JCTree> methods = ListBuffer.lb(); // Only defined translated vars. if (varInfo instanceof TranslatedVarInfoBase) { // Prepare to accumulate statements. ListBuffer<JCStatement> stmts = ListBuffer.lb(); // Fetch the attribute symbol. VarSymbol varSym = varInfo.getSymbol(); // Call super first. ClassSymbol superClassSym = analysis.getFXSuperClassSym(); if (varInfo.isOverride() && superClassSym != null) { stmts.append(makeSuperCall(superClassSym, attributeInvalidateName(varSym), id(defs.receiverName))); } for (VarSymbol otherVarSym : ((TranslatedVarInfoBase)varInfo).boundBinders()) { // invalidate$var(); stmts.append(callStmt(getReceiver(), attributeInvalidateName(otherVarSym))); } // Construct method. JCMethodDecl method = makeMethod(Flags.PUBLIC | Flags.STATIC, syms.voidType, attributeInvalidateName(varSym), makeParamList(false), stmts); methods.append(method); } return methods.toList(); } // // This method constructs the accessor methods for an attribute. // public List<JCTree> makeAnAttributeAccessorMethods(VarInfo ai, boolean needsBody) { ListBuffer<JCTree> accessors = ListBuffer.lb(); setDiagPos(ai.pos()); if (ai.useAccessors()) { if (!ai.isOverride()) { accessors.append(makeGetterAccessorMethod(ai, needsBody)); accessors.append(makeSetterAccessorMethod(ai, needsBody)); accessors.append(makeBeAccessorMethod(ai, needsBody)); accessors.append(makeInvalidateAccessorMethod(ai, needsBody)); accessors.append(makeOnReplaceAccessorMethod(ai, needsBody)); } else if (needsBody) { if (ai.hasInitializer()) { // Bound or not, we need getter & setter on override since we // may be switching between bound and non-bound or visa versa accessors.append(makeGetterAccessorMethod(ai, needsBody)); accessors.append(makeSetterAccessorMethod(ai, needsBody)); } if (needOverrideInvalidateAccessorMethod(ai)) { accessors.append(makeInvalidateAccessorMethod(ai, needsBody)); } if (ai.onReplace() != null) { accessors.append(makeOnReplaceAccessorMethod(ai, needsBody)); } } } return accessors.toList(); } // // This method constructs the accessor methods for each attribute. // public List<JCTree> makeAttributeAccessorMethods(List<VarInfo> attrInfos) { ListBuffer<JCTree> accessors = ListBuffer.lb(); for (VarInfo ai : attrInfos) { // Only create accessors for declared and proxied vars. if (ai.needsCloning()) { accessors.appendList(makeAnAttributeAccessorMethods(ai, true)); } } return accessors.toList(); } // // This method constructs the abstract interfaces for the accessors in // a mixin class. // public List<JCTree> makeMemberVariableAccessorInterfaceMethods() { // Buffer for new decls. ListBuffer<JCTree> accessors = ListBuffer.lb(); // TranslatedVarInfo for the current class. List<TranslatedVarInfo> translatedAttrInfo = analysis.getTranslatedAttrInfo(); // Only for vars within the class. for (VarInfo ai : translatedAttrInfo) { if (!ai.isStatic()) { accessors.appendList(makeAnAttributeAccessorMethods(ai, false)); } } return accessors.toList(); } // // This method constructs mixin accessor methods. // private List<JCTree> makeMixinAccessorMethods(List<? extends VarInfo> attrInfos) { // Prepare to accumulate methods. ListBuffer<JCTree> accessors = ListBuffer.lb(); for (VarInfo ai : attrInfos) { // Set diagnostic position for attribute. setDiagPos(ai.pos()); if (ai.needsCloning()) { accessors.appendList(makeMixinApplyDefaultsMethod(ai)); accessors.appendList(makeMixinEvaluateAccessorMethod(ai)); accessors.appendList(makeMixinInvalidateAccessorMethod(ai)); accessors.append(makeOnReplaceAccessorMethod(ai, true)); } } return accessors.toList(); } // // This method generates an enumeration for each of the instance attributes // of the class. // public List<JCTree> makeAttributeNumbers(List<VarInfo> attrInfos, int varCount, LiteralInitVarMap varMap) { // Buffer for new members. ListBuffer<JCTree> members = ListBuffer.lb(); // Reset diagnostic position to current class. resetDiagPos(); // Construct a static count variable (VCNT$), -1 indicates count has not been initialized. members.append(addSimpleIntVariable(Flags.STATIC | Flags.PUBLIC, defs.varCountName, -1)); // Construct a static count accessor method (VCNT$) members.append(makeVCNT$(attrInfos, varCount)); // Construct a virtual count accessor method (count$) members.append(makecount$()); // Accumulate variable numbering. for (VarInfo ai : attrInfos) { // Only variables actually declared. if (ai.needsCloning() && !ai.isOverride()) { // Set diagnostic position for attribute. setDiagPos(ai.pos()); // Construct offset var. Name name = attributeOffsetName(ai.getSymbol()); // Construct and add: public static int VOFF$name = n; members.append(makeVar(Flags.STATIC | Flags.PUBLIC, syms.intType, name, null)); } // Add to var map if an anon class. if (varMap != null) varMap.addVar(ai.getSymbol()); } return members.toList(); } // // The method constructs the VCNT$ method for the current class. // public JCTree makeVCNT$(List<VarInfo> attrInfos, int varCount) { // Prepare to accumulate statements. ListBuffer<JCStatement> stmts = ListBuffer.lb(); // Reset diagnostic position to current class. resetDiagPos(); // Grab the super class. ClassSymbol superClassSym = analysis.getFXSuperClassSym(); // Prepare to accumulate statements in the if. ListBuffer<JCStatement> ifStmts = ListBuffer.lb(); // VCNT$ = super.VCNT$() + n or VCNT$ = n; JCExpression setVCNT$Expr; // If has a javafx superclass. if (superClassSym == null) { // n setVCNT$Expr = makeInt(varCount); } else { // super.VCNT$() + n setVCNT$Expr = makeBinary(JCTree.PLUS, call(superClassSym.type, defs.varCountName), makeInt(varCount)); } Name countName = names.fromString("$count"); // final int $count = VCNT$ = super.VCNT$() + n; ifStmts.append(makeVar(Flags.FINAL, syms.intType, countName, m().Assign(id(defs.varCountName), setVCNT$Expr))); for (VarInfo ai : attrInfos) { // Only variables actually declared. if (ai.needsCloning() && !ai.isOverride()) { // Set diagnostic position for attribute. setDiagPos(ai.pos()); // Offset var name. Name name = attributeOffsetName(ai.getSymbol()); // VCNT$ - n + i; JCExpression setVOFF$Expr = makeBinary(JCTree.PLUS, id(countName), makeInt(ai.getEnumeration() - varCount)); // VOFF$var = VCNT$ - n + i; ifStmts.append(makeExec(m().Assign(id(name), setVOFF$Expr))); } } // VCNT$ == -1 JCExpression condition = makeEqual(id(defs.varCountName), makeInt(-1)); // if (VCNT$ == -1) { ... stmts.append(m().If(condition, m().Block(0, ifStmts.toList()), null)); // return VCNT$; stmts.append(m().Return(id(defs.varCountName))); // Construct method. JCMethodDecl method = makeMethod(Flags.PUBLIC | Flags.STATIC, syms.intType, defs.varCountName, List.<JCVariableDecl>nil(), stmts); return method; } // // The method constructs the count$ method for the current class. // public JCTree makecount$() { // Prepare to accumulate statements. ListBuffer<JCStatement> stmts = ListBuffer.lb(); // Reset diagnostic position to current class. resetDiagPos(); // VCNT$() JCExpression countExpr = call(defs.varCountName); // Construct and add: return VCNT$(); stmts.append(m().Return(countExpr)); // Construct method. JCMethodDecl method = makeMethod(Flags.PUBLIC, syms.intType, defs.attributeCountMethodName, List.<JCVariableDecl>nil(), stmts); return method; } // // Clones a field declared in FXBase as an non-static field. It also creates // FXObject accessor method. // private List<JCTree> cloneFXBaseVar(VarSymbol var, HashSet<String> excludes) { // Buffer for cloned members. ListBuffer<JCTree> members = ListBuffer.lb(); // Var name as a string. String str = var.name.toString(); // Var modifier flags. long flags = var.flags(); // If it's an excluded name or a static then skip it. if (excludes.contains(str) || (flags & (Flags.SYNTHETIC | Flags.STATIC)) != 0) { return members.toList(); } // Var FX type. Type type = var.asType(); // Clone the var. members.append(makeVar(flags, type, str, null)); // Construct the getter. ListBuffer<JCStatement> stmts = ListBuffer.lb(); Name name = names.fromString("get" + str); stmts.append(m().Return(id(var))); // public int getVar { return Var; } JCMethodDecl getMeth = makeMethod(flags, type, name, List.<JCVariableDecl>nil(), stmts); // Add to members. members.append(getMeth); // Add to the exclusion set. excludes.add(jcMethodDeclStr(getMeth)); // Construct the setter. stmts = ListBuffer.lb(); name = names.fromString("set" + str); Name argName = names.fromString("value"); JCVariableDecl arg = makeParam(type, argName); stmts.append(m().Exec(m().Assign(id(var), id(argName)))); // public void setVar(final int value) { Var = value; } JCMethodDecl setMeth = makeMethod(flags, syms.voidType, name, List.<JCVariableDecl>of(arg), stmts); // Add to members. members.append(setMeth); // Add to the exclusion set. excludes.add(jcMethodDeclStr(setMeth)); // Return the new members. return members.toList(); } // // Clones a method declared as an FXObject interface to call the static // equivalent in FXBase. // private List<JCTree> cloneFXBaseMethod(MethodSymbol method, HashSet<String> excludes) { // Buffer for cloned members. ListBuffer<JCTree> members = ListBuffer.lb(); // Method modifier flags. long flags = method.flags(); // If it's an excluded name or a static then skip it. if (excludes.contains(method.toString()) || (flags & (Flags.SYNTHETIC | Flags.STATIC)) != 0) { return members.toList(); } // List of arguments to new method. ListBuffer<JCVariableDecl> args = ListBuffer.lb(); // List of arguments to call supporting FXBase method. ListBuffer<JCExpression> callArgs = ListBuffer.lb(); // Add this to to the call. callArgs.append(id(names._this)); // Add arguments to both lists. for (VarSymbol argSym : method.getParameters()) { Type argType = argSym.asType(); args.append(makeParam(argSym.asType(), argSym.name)); callArgs.append(id(argSym)); } // Buffer for statements. ListBuffer<JCStatement> stmts = ListBuffer.lb(); // Method return type. Type returnType = method.getReturnType(); // Basic call to supporting FXBase method. JCExpression fxBaseCall = call(makeType(syms.javafx_FXBaseType), method.name, callArgs); // Exec or return based on return type. if (returnType == syms.voidType) { stmts.append(makeExec(fxBaseCall)); } else { stmts.append(m().Return(fxBaseCall)); } // public type meth$(t0 arg0, ...) { return FXBase.meth$(this, arg0, ...); } members.append(makeMethod(Flags.PUBLIC, returnType, method.name, args.toList(), stmts)); return members.toList(); } // // This method clones the contents of FXBase and FXObject when inheriting // from a java class. // public List<JCTree> cloneFXBase(HashSet<String> excludes) { // Buffer for cloned members. ListBuffer<JCTree> members = ListBuffer.lb(); // Reset diagnostic position to current class. resetDiagPos(); // Retrieve FXBase and FXObject. ClassSymbol fxBaseSym = (ClassSymbol)syms.javafx_FXBaseType.tsym; ClassSymbol fxObjectSym = (ClassSymbol)syms.javafx_FXObjectType.tsym; Entry e; // Clone the vars in FXBase. for (e = fxBaseSym.members().elems; e != null && e.sym != null; e = e.sibling) { if (e.sym instanceof VarSymbol) { members.appendList(cloneFXBaseVar((VarSymbol)e.sym, excludes)); } } // Clone the interfaces in FXObject. for (e = fxObjectSym.members().elems; e != null && e.sym != null; e = e.sibling) { if (e.sym instanceof MethodSymbol) { members.appendList(cloneFXBaseMethod((MethodSymbol)e.sym, excludes)); } } return members.toList(); } // // This method constructs the statements needed to apply defaults to a given var. // private JCStatement makeApplyDefaultsStatement(VarInfo ai, boolean isMixinClass) { if (ai.hasBoundDefinition()) { // bind, don't set in applyDefaults$ return null; } // Assume the worst. JCStatement stmt = null; // Get init statement. JCStatement init = ai.getDefaultInitStatement(); if (init != null) { // a default exists, either on the direct attribute or on an override stmt = init; } else if (!isMixinClass) { if (ai.isMixinVar()) { // Fetch the attribute symbol. VarSymbol varSym = ai.getSymbol(); // Construct the name of the method. Name methodName = attributeApplyDefaultsName(varSym); // Include defaults for mixins into real classes. stmt = makeSuperCall((ClassSymbol)varSym.owner, methodName, id(names._this)); } else if (ai instanceof TranslatedVarInfo) { //TODO: see SequenceVariable.setDefault() and JFXC-885 // setDefault() isn't really done for sequences /** if (!ai.isSequence()) { // Make .setDefault() if Location (without clearing initialize bit) to fire trigger. JCStatement setter = makeSetDefaultStatement(ai); if (setter != null) { stmt = setter; } } * ***/ } } return stmt; } // // This method constructs the current class's applyDefaults$ method. // public List<JCTree> makeApplyDefaultsMethod() { // Buffer for new methods. ListBuffer<JCTree> methods = ListBuffer.lb(); // Number of variables in current class. int count = analysis.getClassVarCount(); // Grab the super class. ClassSymbol superClassSym = analysis.getFXSuperClassSym(); // Prepare to accumulate statements. ListBuffer<JCStatement> stmts = ListBuffer.lb(); // Reset diagnostic position to current class. resetDiagPos(); // Prepare to accumulate cases. ListBuffer<JCCase> cases = ListBuffer.lb(); // Prepare to accumulate overrides. ListBuffer<JCStatement> overrides = ListBuffer.lb(); // Gather the instance attributes. List<VarInfo> attrInfos = analysis.classVarInfos(); for (VarInfo ai : attrInfos) { // Only declared attributes with default expressions. if (ai.needsCloning() && !ai.isOverride()) { // Prepare to accumulate case statements. ListBuffer<JCStatement> caseStmts = ListBuffer.lb(); // Get body of applyDefaults$. JCStatement deflt = makeApplyDefaultsStatement(ai, isMixinClass()); // Something to set when we have a default. if (deflt != null) { // applyDefaults$var(); caseStmts.append(deflt); } // Build the case { // return JCStatement returnExpr = m().Return(null); caseStmts.append(returnExpr); // case tag number JCExpression tag = makeInt(ai.getEnumeration() - count); // Add the case, something like: // case i: applyDefaults$var(); return; cases.append(m().Case(tag, caseStmts.toList())); } } else { // Get init statement. JCStatement init = ai.getDefaultInitStatement(); if (init != null) { // varNum == VOFF$var JCExpression isRightVarExpr = makeEqual(id(varNumName), id(attributeOffsetName(ai.getSymbol()))); // { init; return; } JCBlock block = m().Block(0, List.<JCStatement>of(init, m().Return(null))); // if (varNum == VOFF$var) { init; return; } overrides.append(m().If(isRightVarExpr, block, null)); } } } // Reset diagnostic position to current class. resetDiagPos(); // Has some defaults. boolean hasDefaults = cases.nonEmpty() || overrides.nonEmpty(); // If there were some location vars. if (cases.nonEmpty()) { // varNum - VCNT$ JCExpression tagExpr = makeBinary(JCTree.MINUS, id(varNumName), id(defs.varCountName)); // Construct and add: switch(varNum - VCNT$) { ... } stmts.append(m().Switch(tagExpr, cases.toList())); } // Add overrides. stmts.appendList(overrides); // generate method if it is worthwhile or we have to. if (hasDefaults || superClassSym == null) { // If there is a super class. if (superClassSym != null) { // super JCExpression selector = id(names._super); // (varNum) List<JCExpression> args = List.<JCExpression>of(id(varNumName)); // Construct and add: return super.applyDefaults$(varNum); stmts.append(callStmt(selector, defs.attributeApplyDefaultsPrefixMethodName, args)); } // Construct method. JCMethodDecl method = makeMethod(Flags.PUBLIC, syms.voidType, defs.attributeApplyDefaultsPrefixMethodName, List.<JCVariableDecl>of(makeParam(syms.intType, varNumName)), stmts); // Add to the methods list. methods.append(method); } return methods.toList(); } // // This method constructs the current class's update$ method. // public List<JCTree> makeUpdateMethod() { // Buffer for new methods. ListBuffer<JCTree> methods = ListBuffer.lb(); // Prepare to accumulate statements. ListBuffer<JCStatement> stmts = ListBuffer.lb(); // Grab the super class. ClassSymbol superClassSym = analysis.getFXSuperClassSym(); // Reset diagnostic position to current class. resetDiagPos(); // Get the update map. HashMap<VarSymbol, HashMap<VarSymbol, HashSet<VarInfo>>> updateMap = analysis.getUpdateMap(); // generate method if it is worthwhile or we have to. if (!updateMap.isEmpty() || superClassSym == null) { JCStatement ifInstanceStmt = null; // Loop for instance symbol. for (VarSymbol instanceVar : updateMap.keySet()) { HashMap<VarSymbol, HashSet<VarInfo>> instanceMap = updateMap.get(instanceVar); // Loop for reference symbol. JCStatement ifReferenceStmt = null; for (VarSymbol referenceVar : instanceMap.keySet()) { HashSet<VarInfo> referenceSet = instanceMap.get(referenceVar); ListBuffer<JCStatement> invalidateStmts = ListBuffer.lb(); // Loop for local vars. for (VarInfo varInfo : referenceSet) { VarSymbol proxyVarSym = varInfo.proxyVarSym(); invalidateStmts.append(callStmt(getReceiver(varInfo), attributeInvalidateName(proxyVarSym))); } Type instanceType = referenceVar.owner.type; JCExpression referenceSelect = m().Select(makeType(instanceType), attributeOffsetName(referenceVar)); JCExpression ifReferenceCond = makeBinary(JCTree.EQ, id(varNumName), referenceSelect); ifReferenceStmt = m().If(ifReferenceCond, m().Block(0L, invalidateStmts.toList()), ifReferenceStmt); } JCExpression ifInstanceCond = makeBinary(JCTree.EQ, id(updateInstanceName), id(attributeValueName(instanceVar))); ifInstanceStmt = m().If(ifInstanceCond, m().Block(0L, List.<JCStatement>of(ifReferenceStmt)), ifInstanceStmt); } if (ifInstanceStmt != null) { stmts.append(ifInstanceStmt); } // If there is a super class. if (superClassSym != null) { // super JCExpression selector = id(names._super); // (varNum) List<JCExpression> args = List.<JCExpression>of(id(updateInstanceName), id(varNumName)); // Construct and add: return super.applyDefaults$(varNum); stmts.append(callStmt(selector, defs.attributeUpdatePrefixMethodName, args)); } // Construct method. JCMethodDecl method = makeMethod(Flags.PUBLIC, syms.voidType, defs.attributeUpdatePrefixMethodName, List.<JCVariableDecl>of(makeParam(syms.javafx_FXObjectType, updateInstanceName), makeParam(syms.intType, varNumName)), stmts); // Add to the methods list. methods.append(method); } return methods.toList(); } // // This method constructs the initializer for a var map. // public JCExpression makeInitVarMapExpression(ClassSymbol cSym, LiteralInitVarMap varMap) { // Reset diagnostic position to current class. resetDiagPos(); // Build up the argument list for the call. ListBuffer<JCExpression> args = ListBuffer.lb(); // X.VCNT$() args.append(call(cSym.type, defs.varCountName)); // For each var declared in order (to make the switch tags align to the vars.) for (VarSymbol vSym : varMap.varList.toList()) { // ..., X.VOFF$x, ... args.append(select(makeType(cSym.type), attributeOffsetName(vSym))); } // FXBase.makeInitMap$(X.VCNT$(), X.VOFF$a, ...) return call(syms.javafx_FXBaseType, makeInitMap, args); } // // This method constructs a single var map declaration. // public JCVariableDecl makeInitVarMapDecl(ClassSymbol cSym, LiteralInitVarMap varMap) { // Reset diagnostic position to current class. resetDiagPos(); // Fetch name of map. Name mapName = varMapName(cSym); // static short[] Map$X; return makeVar(Flags.STATIC, syms.javafx_ShortArray, mapName, null); } // // This method constructs a single var map initial value. // public JCStatement makeInitVarMapInit(LiteralInitVarMap varMap) { // Get current class symbol. ClassSymbol cSym = getCurrentClassSymbol(); // Reset diagnostic position to current class. resetDiagPos(); // Fetch name of map. Name mapName = varMapName(cSym); // Map$X = FXBase.makeInitMap$(X.VCNT$(), X.VOFF$a, ...); return makeExec(m().Assign(id(mapName), makeInitVarMapExpression(cSym, varMap))); } // // This method constructs declarations for var maps used by literal initializers. // public List<JCTree> makeInitClassMaps(LiteralInitClassMap initClassMap) { // Buffer for new vars and methods. ListBuffer<JCTree> members = ListBuffer.lb(); // Reset diagnostic position to current class. resetDiagPos(); // For each class initialized in the current class. for (ClassSymbol cSym : initClassMap.classMap.keySet()) { // Get the var map for the referencing class. LiteralInitVarMap varMap = initClassMap.classMap.get(cSym); // Add to var to list. members.append(makeInitVarMapDecl(cSym, varMap)); // Fetch name of map. Name mapName = varMapName(cSym); // Prepare to accumulate statements. ListBuffer<JCStatement> stmts = ListBuffer.lb(); if (analysis.isAnonClass(cSym)) { // Construct and add: return MAP$X; stmts.append(m().Return(id(mapName))); } else { // MAP$X == null JCExpression condition = makeNullCheck(id(mapName)); // MAP$X = FXBase.makeInitMap$(X.VCNT$, X.VOFF$a, ...) JCExpression assignExpr = m().Assign(id(mapName), makeInitVarMapExpression(cSym, varMap)); // Construct and add: return MAP$X == null ? (MAP$X = FXBase.makeInitMap$(X.VCNT$, X.VOFF$a, ...)) : MAP$X; stmts.append(m().Return(m().Conditional(condition, assignExpr, id(mapName)))); } // Construct lazy accessor method. JCMethodDecl method = makeMethod(Flags.PUBLIC | Flags.STATIC, syms.javafx_ShortArray, varGetMapName(cSym), List.<JCVariableDecl>nil(), stmts); // Add method to list. members.append(method); } return members.toList(); } // // This method constructs a super call with appropriate arguments. // private JCStatement makeSuperCall(ClassSymbol cSym, Name name, JCExpression... args) { ListBuffer<JCExpression> buffer = ListBuffer.lb(); for (JCExpression arg : args) { buffer.append(arg); } return makeSuperCall(cSym, name, buffer.toList()); } private JCStatement makeSuperCall(ClassSymbol cSym, Name name, List<JCExpression> args) { // If this is from a mixin class then we need to use receiver$ otherwise this. boolean fromMixinClass = isMixinClass(); // If this is to a mixin class then we need to use receiver$ otherwise this. boolean toMixinClass = JavafxAnalyzeClass.isMixinClass(cSym); // If this class doesn't have a javafx super then punt to FXBase. boolean toFXBase = cSym == null; // Add in the receiver if necessary. if (toMixinClass || toFXBase) { // Determine the receiver name. Name receiver = fromMixinClass ? defs.receiverName : names._this; args.prepend(id(receiver)); } // Determine the selector. JCExpression selector; if (toMixinClass) { selector = makeType(cSym.type, false); } else if (toFXBase) { selector = makeType(syms.javafx_FXBaseType, false); } else { selector = id(names._super); } // Construct the call. return callStmt(selector, name, args); } // // Construct the static block for setting defaults // public JCBlock makeInitStaticAttributesBlock(Name scriptName, List<VarInfo> attrInfo, JCStatement initMap) { // Buffer for init statements. ListBuffer<JCStatement> stmts = ListBuffer.lb(); // Initialize the var map for anon class. if (initMap != null) { stmts.append(initMap); } if (scriptName != null) { stmts.append(callStmt(id(scriptName), defs.scriptLevelAccessMethod)); } if (attrInfo != null) { for (VarInfo ai : attrInfo) { JCStatement init = ai.getDefaultInitStatement(); if (init != null) { stmts.append(init); } } } return m().Block(Flags.STATIC, stmts.toList()); } // // This method generates the code for a userInit or postInit method. public List<JCTree> makeInitMethod(Name methName, ListBuffer<JCStatement> translatedInitBlocks, List<ClassSymbol> immediateMixinClasses) { // Prepare to accumulate methods. ListBuffer<JCTree> methods = ListBuffer.lb(); ClassSymbol superClassSym = analysis.getFXSuperClassSym(); // Only create method if necessary (rely on FXBase.) if (translatedInitBlocks.nonEmpty() || immediateMixinClasses.nonEmpty() || isMixinClass() || superClassSym == null) { List<JCVariableDecl> receiverVarDeclList; ListBuffer<JCStatement> stmts = ListBuffer.lb(); // Mixin super calls will be handled when inserted into real classes. if (!isMixinClass()) { //TODO: // Some implementation code is still generated assuming a receiver parameter. Until this is fixed // var receiver = this; stmts.append(makeVar(Flags.FINAL, id(interfaceName(getCurrentClassDecl())), defs.receiverName, id(names._this))); receiverVarDeclList = List.<JCVariableDecl>nil(); if (superClassSym != null) { stmts.append(callStmt(id(names._super), methName)); } for (ClassSymbol mixinClassSym : immediateMixinClasses) { String mixinName = mixinClassSym.fullname.toString(); stmts.append(callStmt(id(names.fromString(mixinName)), methName, m().TypeCast(makeType(mixinClassSym), id(names._this)))); } } else { receiverVarDeclList = List.<JCVariableDecl>of(makeReceiverParam(getCurrentClassDecl())); } stmts.appendList(translatedInitBlocks); methods.append(makeMethod(!isMixinClass() ? Flags.PUBLIC : (Flags.PUBLIC | Flags.STATIC), syms.voidType, methName, receiverVarDeclList, stmts.toList())); } return methods.toList(); } private JCMethodDecl makeConstructor(List<JCVariableDecl> params, List<JCStatement> cStats) { resetDiagPos(); return m().MethodDef(m().Modifiers(Flags.PUBLIC), names.init, makeType(syms.voidType), List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), m().Block(0L, cStats), null); } // // Make a constructor to be called by Java code. // Simply pass up to super, unless this is the last JavaFX class, in which case add object initialization // public JCMethodDecl makeJavaEntryConstructor() { // public Foo() { // this(false); // initialize$(); // } return makeConstructor(List.<JCVariableDecl>nil(), List.of( callStmt(names._this, makeBoolean(false)), callStmt(defs.initializeName))); } // // Make a constructor to be called by JavaFX code. // public JCMethodDecl makeFXEntryConstructor(ClassSymbol outerTypeSym) { ListBuffer<JCStatement> stmts = ListBuffer.lb(); Name dummyParamName = names.fromString("dummy"); // call the FX version of the constructor in the superclass // public Foo(boolean dummy) { // super(dummy); // } if (analysis.getFXSuperClassSym() != null) { stmts.append(callStmt(names._super, id(dummyParamName))); } else { stmts.append(callStmt(defs.initFXBaseName)); } // Construct the parameters ListBuffer<JCVariableDecl> params = ListBuffer.lb(); if (outerTypeSym != null) { // add a parameter and a statement to constructor for the outer instance reference params.append(makeParam(outerTypeSym.type, outerAccessorFieldName) ); JCFieldAccess cSelect = m().Select(id(names._this), outerAccessorFieldName); stmts.append(makeExec(m().Assign(cSelect, id(outerAccessorFieldName)))); } params.append(makeParam(syms.booleanType, dummyParamName)); return makeConstructor(params.toList(), stmts.toList()); } // // Make the field for accessing the outer members // public JCTree makeOuterAccessorField(ClassSymbol outerTypeSym) { resetDiagPos(); // Create the field to store the outer instance reference return m().VarDef(m().Modifiers(Flags.PUBLIC), outerAccessorFieldName, id(outerTypeSym), null); } // // Make the method for accessing the outer members // public JCTree makeOuterAccessorMethod(ClassSymbol outerTypeSym) { resetDiagPos(); ListBuffer<JCStatement> stmts = ListBuffer.lb(); VarSymbol vs = new VarSymbol(Flags.PUBLIC, outerAccessorFieldName, outerTypeSym.type, getCurrentClassSymbol()); stmts.append(m().Return(id(vs))); return makeMethod(Flags.PUBLIC, outerTypeSym.type, defs.outerAccessorName, List.<JCVariableDecl>nil(), stmts); } // // Make a method body which redirects to the actual implementation in a static method of the defining class. // private JCBlock makeDispatchBody(MethodSymbol sym, boolean isBound, boolean isStatic) { ClassSymbol cSym = analysis.getCurrentClassSymbol(); ListBuffer<JCExpression> args = ListBuffer.lb(); if (!isStatic) { // Add the this argument, so the static implementation method is invoked args.append(m().TypeCast(id(interfaceName(getCurrentClassDecl())), id(names._this))); } for (VarSymbol var : sym.params) { args.append(id(var)); } JCExpression receiver = isCurrentClassSymbol(sym.owner) ? null : makeType(sym.owner.type, false); JCExpression expr = call(receiver, functionName(sym, !isStatic, isBound), args); JCStatement stmt = (sym.getReturnType() == syms.voidType) ? m().Exec(expr) : m().Return(expr); return m().Block(0L, List.<JCStatement>of(stmt)); } // // Make a method from a MethodSymbol and an optional method body. // Make a bound version if "isBound" is set. // private void appendMethodClones(ListBuffer<JCTree> methods, MethodSymbol sym, boolean needsBody) { resetDiagPos(); //TODO: static test is broken boolean isBound = (sym.flags() & JavafxFlags.BOUND) != 0; JCBlock body = needsBody ? makeDispatchBody(sym, isBound, (sym.flags() & Flags.STATIC) != 0) : null; // build the parameter list ListBuffer<JCVariableDecl> params = ListBuffer.lb(); for (VarSymbol vsym : sym.getParameters()) { if (isBound) { TODO(); } params.append(m().VarDef(m().Modifiers(0L), vsym.name, makeType(vsym.asType()), null)); } // make the method JCModifiers mods = m().Modifiers(Flags.PUBLIC | (body == null? Flags.ABSTRACT : 0L)); if (isCurrentClassSymbol(sym.owner)) mods = addAccessAnnotationModifiers(diagPos, sym.flags(), mods); else mods = addInheritedAnnotationModifiers(diagPos, sym.flags(), mods); methods.append(m().MethodDef( mods, functionName(sym, false, isBound), makeReturnTypeTree(diagPos, sym, isBound), List.<JCTypeParameter>nil(), params.toList(), List.<JCExpression>nil(), body, null)); if (needsBody) { optStat.recordProxyMethod(); } } // // Add proxies which redirect to the static implementation for every concrete method // public List<JCTree> makeFunctionProxyMethods(List<MethodSymbol> needDispatch) { ListBuffer<JCTree> methods = ListBuffer.lb(); for (MethodSymbol sym : needDispatch) { if ((sym.flags() & Flags.PRIVATE) == 0) { appendMethodClones(methods, sym, true); } } return methods.toList(); } // // Add interface declarations for declared methods. // public List<JCTree> makeFunctionInterfaceMethods() { ListBuffer<JCTree> methods = ListBuffer.lb(); for (JFXTree def : getCurrentClassDecl().getMembers()) { if (def.getFXTag() == JavafxTag.FUNCTION_DEF) { JFXFunctionDefinition func = (JFXFunctionDefinition) def; MethodSymbol sym = func.sym; if ((sym.flags() & (Flags.SYNTHETIC | Flags.STATIC | Flags.PRIVATE)) == 0) { appendMethodClones(methods, sym, false); } } } return methods.toList(); } // // This method constructs a script class. // public JCClassDecl makeScript(Name scriptName, List<JCTree> definitions) { JCModifiers classMods = m().Modifiers(Flags.PUBLIC | Flags.STATIC); classMods = addAccessAnnotationModifiers(diagPos, 0, classMods); JCClassDecl script =m().ClassDef( classMods, scriptName, List.<JCTypeParameter>nil(), makeType(syms.javafx_FXBaseType), List.<JCExpression>of(makeType(syms.javafx_FXObjectType)), definitions); return script; } // // Methods for accessing the outer members. // public List<JCTree> makeOuterAccessorInterfaceMembers() { ListBuffer<JCTree> members = ListBuffer.lb(); ClassSymbol cSym = getCurrentClassSymbol(); if (cSym != null && toJava.getHasOuters().contains(cSym)) { Symbol typeOwner = cSym.owner; while (typeOwner != null && typeOwner.kind != Kinds.TYP) { typeOwner = typeOwner.owner; } if (typeOwner != null) { ClassSymbol returnSym = reader.enterClass(names.fromString(typeOwner.type.toString() + mixinSuffix)); JCMethodDecl accessorMethod = m().MethodDef( m().Modifiers(Flags.PUBLIC), defs.outerAccessorName, id(returnSym), List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), null, null); members.append(accessorMethod); optStat.recordProxyMethod(); } } return members.toList(); } // // Add definitions to class to access the script-level sole instance. // private List<JCTree> makeScriptLevelAccess(Name scriptName, boolean scriptLevel, boolean isRunnable) { ListBuffer<JCTree> members = ListBuffer.lb(); ListBuffer<JCStatement> stmts = ListBuffer.lb(); if (scriptLevel) { // sole instance field members.append(makeVar(Flags.PRIVATE | Flags.STATIC, id(scriptName), defs.scriptLevelAccessField, null)); // sole instance lazy creation method JCExpression condition = makeNullCheck(id(defs.scriptLevelAccessField)); JCExpression assignExpr = m().Assign( id(defs.scriptLevelAccessField), m().NewClass(null, null, id(scriptName), List.<JCExpression>nil(), null)); stmts.append(m().If(condition, makeExec(assignExpr), null)); stmts.append(m().Return(id(defs.scriptLevelAccessField))); } else { stmts.append(m().Return(call(id(scriptName), defs.scriptLevelAccessMethod))); } members.append(makeMethod(Flags.PUBLIC | Flags.STATIC, id(scriptName), defs.scriptLevelAccessMethod, null, stmts.toList())); // If module is runnable, create a run method that redirects to the sole instance version if (!SCRIPT_LEVEL_AT_TOP && !scriptLevel && isRunnable) { members.append(makeMethod(Flags.PUBLIC | Flags.STATIC, syms.objectType, defs.internalRunFunctionName, List.<JCVariableDecl>of(m().Param(defs.arg0Name, types.sequenceType(syms.stringType), null)), List.<JCStatement>of(m().Return(call( call(defs.scriptLevelAccessMethod), defs.internalRunFunctionName, id(defs.arg0Name)))))); } return members.toList(); } } }
false
false
null
null
diff --git a/drools-planner-examples/src/test/java/org/drools/planner/examples/tsp/TspPerformanceTest.java b/drools-planner-examples/src/test/java/org/drools/planner/examples/tsp/TspPerformanceTest.java index d8cca3e5..30195ac0 100644 --- a/drools-planner-examples/src/test/java/org/drools/planner/examples/tsp/TspPerformanceTest.java +++ b/drools-planner-examples/src/test/java/org/drools/planner/examples/tsp/TspPerformanceTest.java @@ -1,55 +1,55 @@ /* * Copyright 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.planner.examples.tsp; import java.io.File; import org.drools.planner.config.EnvironmentMode; import org.drools.planner.examples.common.app.SolverPerformanceTest; import org.drools.planner.examples.common.persistence.SolutionDao; import org.drools.planner.examples.tsp.persistence.TspDaoImpl; import org.junit.Test; public class TspPerformanceTest extends SolverPerformanceTest { @Override protected String createSolverConfigResource() { return "/org/drools/planner/examples/tsp/solver/tspSolverConfig.xml"; } @Override protected SolutionDao createSolutionDao() { return new TspDaoImpl(); } // ************************************************************************ // Tests // ************************************************************************ @Test(timeout = 600000) public void solveModel_a2_1() { File unsolvedDataFile = new File("data/tsp/unsolved/europe40.xml"); - runSpeedTest(unsolvedDataFile, "-218451"); + runSpeedTest(unsolvedDataFile, "-217957"); } @Test(timeout = 600000) public void solveModel_a2_1FastAssert() { File unsolvedDataFile = new File("data/tsp/unsolved/europe40.xml"); - runSpeedTest(unsolvedDataFile, "-219798", EnvironmentMode.FAST_ASSERT); + runSpeedTest(unsolvedDataFile, "-219637", EnvironmentMode.FAST_ASSERT); } }
false
false
null
null
diff --git a/src/com/podevs/android/pokemononline/battle/BattleActivity.java b/src/com/podevs/android/pokemononline/battle/BattleActivity.java index e8da8f8e..7afd2a99 100644 --- a/src/com/podevs/android/pokemononline/battle/BattleActivity.java +++ b/src/com/podevs/android/pokemononline/battle/BattleActivity.java @@ -1,1070 +1,1071 @@ package com.podevs.android.pokemononline.battle; import java.util.Locale; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.ResultReceiver; import android.os.SystemClock; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.Window; import android.webkit.WebView; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import com.android.launcher.DragController; import com.android.launcher.DragLayer; import com.android.launcher.PokeDragIcon; import com.podevs.android.pokemononline.Command; import com.podevs.android.pokemononline.NetworkService; import com.podevs.android.pokemononline.R; import com.podevs.android.pokemononline.TextProgressBar; import com.podevs.android.pokemononline.chat.ChatActivity; import com.podevs.android.pokemononline.poke.PokeEnums.Gender; import com.podevs.android.pokemononline.poke.PokeEnums.Status; import com.podevs.android.pokemononline.poke.ShallowBattlePoke; import com.podevs.android.pokemononline.poke.ShallowShownPoke; import com.podevs.android.pokemononline.poke.UniqueID; import com.podevs.android.utilities.Baos; class MyResultReceiver extends ResultReceiver { private Receiver mReceiver; public MyResultReceiver(Handler handler) { super(handler); } public void setReceiver(Receiver receiver) { mReceiver = receiver; } public interface Receiver { public void onReceiveResult(int resultCode, Bundle resultData); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (mReceiver != null) { mReceiver.onReceiveResult(resultCode, resultData); } } } @SuppressLint("DefaultLocale") public class BattleActivity extends Activity implements MyResultReceiver.Receiver{ private MyResultReceiver mRecvr; private static ComponentName servName = new ComponentName("com.podevs.android.pokemonresources", "com.podevs.android.pokemonresources.SpriteService"); public enum BattleDialog { RearrangeTeam, ConfirmForfeit, OppDynamicInfo, MyDynamicInfo, MoveInfo } public final static int SWIPE_TIME_THRESHOLD = 100; final static String pkgName = "com.podevs.android.pokemononline"; private static final String TAG = "Battle"; DragLayer mDragLayer; ViewPager realViewSwitcher; RelativeLayout battleView; TextProgressBar[] hpBars = new TextProgressBar[2]; TextView[] currentPokeNames = new TextView[2]; TextView[] currentPokeLevels = new TextView[2]; ImageView[] currentPokeGenders = new ImageView[2]; ImageView[] currentPokeStatuses = new ImageView[2]; TextView[] attackNames = new TextView[4]; TextView[] attackPPs = new TextView[4]; RelativeLayout[] attackLayouts = new RelativeLayout[4]; TextView[] timers = new TextView[2]; TextView[] pokeListNames = new TextView[6]; TextView[] pokeListItems = new TextView[6]; TextView[] pokeListAbilities = new TextView[6]; TextView[] pokeListHPs = new TextView[6]; ImageView[] pokeListIcons = new ImageView[6]; PokeDragIcon[] myArrangePokeIcons = new PokeDragIcon[6]; ImageView[] oppArrangePokeIcons = new ImageView[6]; RelativeLayout[] pokeListButtons = new RelativeLayout[6]; TextView[][] pokeListMovePreviews = new TextView[6][4]; TextView infoView; ScrollView infoScroll; TextView[] names = new TextView[2]; ImageView[][] pokeballs = new ImageView[2][6]; WebView[] pokeSprites = new WebView[2]; RelativeLayout struggleLayout; LinearLayout attackRow1; LinearLayout attackRow2; SpectatingBattle battle = null; public Battle activeBattle = null; boolean useAnimSprites = true; BattleMove lastClickedMove; Resources resources; public NetworkService netServ = null; int me, opp; class HpAnimator implements Runnable { int i, goal; boolean finished; public void setGoal(int i, int goal) { this.i = i; this.goal = goal; finished = false; } public void run() { while(goal < hpBars[i].getProgress()) { runOnUiThread(new Runnable() { public void run() { hpBars[i].incrementProgressBy(-1); hpBars[i].setText(hpBars[i].getProgress() + "%"); checkHpColor(); } }); try { Thread.sleep(40); } catch (InterruptedException e) { // TODO Auto-generated catch block } } while(goal > hpBars[i].getProgress()) { runOnUiThread(new Runnable() { public void run() { hpBars[i].incrementProgressBy(1); hpBars[i].setText(hpBars[i].getProgress() + "%"); checkHpColor(); } }); try { Thread.sleep(40); } catch (InterruptedException e) { // TODO Auto-generated catch block } } synchronized (battle) { battle.notify(); } } public void setHpBarToGoal() { runOnUiThread(new Runnable() { public void run() { hpBars[i].setProgress(goal); hpBars[i].setText(hpBars[i].getProgress() + "%"); checkHpColor(); } }); } void checkHpColor() { runOnUiThread(new Runnable() { public void run() { int progress = hpBars[i].getProgress(); Rect bounds = hpBars[i].getProgressDrawable().getBounds(); if(progress > 50) hpBars[i].setProgressDrawable(resources.getDrawable(R.drawable.green_progress)); else if(progress <= 50 && progress > 20) hpBars[i].setProgressDrawable(resources.getDrawable(R.drawable.yellow_progress)); else hpBars[i].setProgressDrawable(resources.getDrawable(R.drawable.red_progress)); hpBars[i].getProgressDrawable().setBounds(bounds); // XXX the hp bars won't display properly unless I do this. Spent many hours trying // to figure out why int increment = (hpBars[i].getProgress() == 100) ? -1 : 1; hpBars[i].incrementProgressBy(increment); hpBars[i].incrementProgressBy(-1 * increment); } }); } }; public HpAnimator hpAnimator = new HpAnimator(); View mainLayout, teamLayout; private class MyAdapter extends PagerAdapter { @Override public int getCount() { return isSpectating() ? 1 : 2; } @Override public Object instantiateItem(ViewGroup container, int position) { switch (position) { case 0: container.addView(mainLayout);return mainLayout; case 1: container.addView(teamLayout);return teamLayout; } return null; } @Override public boolean isViewFromObject(View arg0, Object arg1) { return (Object)arg0 == arg1; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View)object); } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { Log.w(TAG, "Battle id: " + getIntent().getIntExtra("battleId", -1)); super.onCreate(savedInstanceState); mRecvr = new MyResultReceiver(new Handler()); mRecvr.setReceiver(this); try { getPackageManager().getApplicationInfo("com.podevs.android.pokemonresources", 0); } catch (NameNotFoundException e) { Log.d("BattleActivity", "Animated sprites not found"); useAnimSprites = false; } bindService(new Intent(BattleActivity.this, NetworkService.class), connection, Context.BIND_AUTO_CREATE); resources = getResources(); realViewSwitcher = (ViewPager) new ViewPager(this); mainLayout = getLayoutInflater().inflate(R.layout.battle_mainscreen, null); - realViewSwitcher.setAdapter(new MyAdapter()); - setContentView(realViewSwitcher); if (mainLayout.findViewById(R.id.smallBattleWindow) != null) { /* Small screen, set full screen otherwise pokemon are cropped */ requestWindowFeature(Window.FEATURE_NO_TITLE); } + + realViewSwitcher.setAdapter(new MyAdapter()); + setContentView(realViewSwitcher); infoView = (TextView)mainLayout.findViewById(R.id.infoWindow); infoScroll = (ScrollView)mainLayout.findViewById(R.id.infoScroll); battleView = (RelativeLayout)mainLayout.findViewById(R.id.battleScreen); struggleLayout = (RelativeLayout)mainLayout.findViewById(R.id.struggleLayout); attackRow1 = (LinearLayout)mainLayout.findViewById(R.id.attackRow1); attackRow2 = (LinearLayout)mainLayout.findViewById(R.id.attackRow2); struggleLayout.setOnClickListener(new OnClickListener() { public void onClick(View v) { netServ.socket.sendMessage(activeBattle.constructAttack((byte)-1), Command.BattleMessage); // This is how you struggle } }); } private Handler handler = new Handler(); private Runnable updateTimeTask = new Runnable() { public void run() { for(int i = 0; i < 2; i++) { int seconds; if (battle.ticking[i]) { long millis = SystemClock.uptimeMillis() - battle.startingTime[i]; seconds = battle.remainingTime[i] - (int) (millis / 1000); } else seconds = battle.remainingTime[i]; if(seconds < 0) seconds = 0; else if(seconds > 300) seconds = 300; int minutes = (seconds / 60); seconds = seconds % 60; timers[i].setText(String.format("%02d:%02d", minutes, seconds)); } handler.postDelayed(this, 200); } }; public void setHpBarTo(final int i, final int goal) { hpAnimator.setGoal(i, goal); hpAnimator.setHpBarToGoal(); } public void animateHpBarTo(final int i, final int goal) { hpAnimator.setGoal(i, goal); new Thread(hpAnimator).start(); } public void updateBattleInfo(boolean scroll) { runOnUiThread(new Runnable() { public void run() { if (battle == null) return; synchronized (battle.histDelta) { infoView.append(battle.histDelta); if (battle.histDelta.length() != 0 || true) { infoScroll.post(new Runnable() { public void run() { infoScroll.smoothScrollTo(0, infoView.getMeasuredHeight()); } }); } infoScroll.invalidate(); battle.hist.append(battle.histDelta); battle.histDelta.clear(); } } }); } public void updatePokes(byte player) { if (player == me) updateMyPoke(); else updateOppPoke(player); } public void updatePokeballs() { runOnUiThread(new Runnable() { public void run() { for (int i = 0; i < 2; i++) { for (int j = 0; j < 6; j++) { pokeballs[i][j].setImageResource(resources.getIdentifier("status" + battle.pokes[i][j].status(), "drawable", pkgName)); } } } }); } private String getSprite(ShallowBattlePoke poke, boolean front) { String res; UniqueID uID; if (poke.specialSprites.isEmpty()) uID = poke.uID; else uID = poke.specialSprites.peek(); if (uID.pokeNum < 0) res = "empty_sprite"; else { res = "p" + uID.pokeNum + (uID.subNum == 0 ? "" : "_" + uID.subNum) + (front ? "_front" : "_back"); if (resources.getIdentifier(res + "f", "drawable", pkgName) != 0) // Special female sprite res = res + "f" + (poke.shiny ? "s" : ""); } System.out.println("SPRITE: " + res); int ident = resources.getIdentifier(res, "drawable", pkgName); if (ident == 0) // No sprite found. Default to missingNo. return "missingno.png"; else return res + ".png"; } private String getAnimSprite(ShallowBattlePoke poke, boolean front) { String res; UniqueID uID; if (poke.specialSprites.isEmpty()) uID = poke.uID; else uID = poke.specialSprites.peek(); if (poke.uID.pokeNum < 0) res = null; else { res = String.format("anim%03d", uID.pokeNum) + (uID.subNum == 0 ? "" : "_" + uID.subNum) + (poke.gender == Gender.Female.ordinal() ? "f" : "") + (front ? "_front" : "_back") + (poke.shiny ? "s" : "") + ".gif"; } return res; } public void updateCurrentPokeListEntry() { runOnUiThread(new Runnable() { public void run() { synchronized(battle) { BattlePoke battlePoke = activeBattle.myTeam.pokes[0]; pokeListHPs[0].setText(battlePoke.currentHP + "/" + battlePoke.totalHP); } // TODO: Status ailments and stuff } }); } public void updateMovePP(final int moveNum) { runOnUiThread(new Runnable() { public void run() { BattleMove move = activeBattle.displayedMoves[moveNum]; attackPPs[moveNum].setText("PP " + move.currentPP + "/" + move.totalPP); } }); } public void onReceiveResult(int resultCode, Bundle resultData) { if (resultCode != Activity.RESULT_OK) return; String path = resultData.getString("path"); if (resultData.getBoolean("me")) { pokeSprites[me].loadDataWithBaseURL(path, "<head><style type=\"text/css\">body{background-position:center bottom;background-repeat:no-repeat; background-image:url('" + resultData.getString("sprite") + "');}</style><body></body>", "text/html", "utf-8", null); } else { pokeSprites[opp].loadDataWithBaseURL(path, "<head><style type=\"text/css\">body{background-position:center bottom;background-repeat:no-repeat; background-image:url('" + resultData.getString("sprite") + "');}</style><body></body>", "text/html", "utf-8", null); } } public boolean isSpectating() { return activeBattle == null; } public void updateMyPoke() { if (isSpectating()) { updateOppPoke(me); return; } runOnUiThread(new Runnable() { public void run() { ShallowBattlePoke poke = battle.currentPoke(me); // Load correct moveset and name if(poke != null) { currentPokeNames[me].setText(poke.rnick); currentPokeLevels[me].setText("Lv. " + poke.level); currentPokeGenders[me].setImageResource(resources.getIdentifier("battle_gender" + poke.gender, "drawable", pkgName)); currentPokeStatuses[me].setImageResource(resources.getIdentifier("battle_status" + poke.status(), "drawable", pkgName)); setHpBarTo(me, poke.lifePercent); BattlePoke battlePoke = activeBattle.myTeam.pokes[0]; for(int i = 0; i < 4; i++) { BattleMove move = activeBattle.displayedMoves[i]; updateMovePP(i); attackNames[i].setText(move.toString()); String type; if (move.num == 237) type = Type.values()[battlePoke.hiddenPowerType()].toString(); else type = move.getTypeString(); type = type.toLowerCase(Locale.UK); attackLayouts[i].setBackgroundResource(resources.getIdentifier(type + "_type_button", "drawable", pkgName)); } String sprite = null; if (battle.shouldShowPreview || poke.status() == Status.Koed.poValue()) { sprite = "empty_sprite.png"; } else if (poke.sub) { sprite = "sub_back.png"; } else { if (useAnimSprites) { Intent data = new Intent(); data.setComponent(servName); data.putExtra("me", true); data.putExtra("sprite", getAnimSprite(poke, false)); data.putExtra("cb", mRecvr); startService(data); } else { sprite = getSprite(poke, false); } } if (sprite != null) { pokeSprites[me].loadDataWithBaseURL("file:///android_res/drawable/", "<head><style type=\"text/css\">body{background-position:center bottom;background-repeat:no-repeat; background-image:url('" + sprite + "');}</style><body></body>", "text/html", "utf-8", null); } } } }); updateTeam(); } public void updateOppPoke(final int opp) { runOnUiThread(new Runnable() { public void run() { ShallowBattlePoke poke = battle.currentPoke(opp); // Load correct moveset and name if(poke != null) { currentPokeNames[opp].setText(poke.rnick); currentPokeLevels[opp].setText("Lv. " + poke.level); currentPokeGenders[opp].setImageResource(resources.getIdentifier("battle_gender" + poke.gender, "drawable", pkgName)); currentPokeStatuses[opp].setImageResource(resources.getIdentifier("battle_status" + poke.status(), "drawable", pkgName)); setHpBarTo(opp, poke.lifePercent); String sprite = null; if (battle.shouldShowPreview || poke.status() == Status.Koed.poValue()) { sprite = "empty_sprite.png"; } else if (poke.sub) { sprite = opp == me ? "sub_back.png" : "sub_front.png"; } else { if (useAnimSprites) { Intent data = new Intent(); data.setComponent(servName); data.putExtra("me", false); data.putExtra("sprite", getAnimSprite(poke, opp != me)); data.putExtra("cb", mRecvr); startService(data); } else { sprite = getSprite(poke, opp != me); } } if (sprite != null) { pokeSprites[opp].loadDataWithBaseURL("file:///android_res/drawable/", "<head><style type=\"text/css\">body{background-position:center bottom;background-repeat:no-repeat; background-image:url('" + sprite + "');}</style><body></body>", "text/html", "utf-8", null); } } } }); } public void updateButtons() { if (isSpectating()) { return; } runOnUiThread(new Runnable() { public void run() { if (!checkStruggle()) { for (int i = 0; i < 4; i++) { if (activeBattle.allowAttack && !activeBattle.clicked) { setAttackButtonEnabled(i, activeBattle.allowAttacks[i]); } else { setAttackButtonEnabled(i, false); } } } for(int i = 0; i < 6; i++) { if (activeBattle.myTeam.pokes[i].status() != Status.Koed.poValue() && !activeBattle.clicked) setPokeListButtonEnabled(i, activeBattle.allowSwitch); else setPokeListButtonEnabled(i, false); } } }); } public boolean checkStruggle() { // This method should hide moves, show the button if necessary and return whether it showed the button boolean struggle = activeBattle.shouldStruggle; if(struggle) { attackRow1.setVisibility(View.GONE); attackRow2.setVisibility(View.GONE); struggleLayout.setVisibility(View.VISIBLE); } else { attackRow1.setVisibility(View.VISIBLE); attackRow2.setVisibility(View.VISIBLE); struggleLayout.setVisibility(View.GONE); } return struggle; } private Drawable getIcon(UniqueID uid) { int resID = resources.getIdentifier("pi" + uid.pokeNum + (uid.subNum == 0 ? "" : "_" + uid.subNum) + "_icon", "drawable", pkgName); if (resID == 0) resID = resources.getIdentifier("pi" + uid.pokeNum + "_icon", "drawable", pkgName); return resources.getDrawable(resID); } public void updateTeam() { runOnUiThread(new Runnable() { public void run() { for (int i = 0; i < 6; i++) { BattlePoke poke = activeBattle.myTeam.pokes[i]; pokeListIcons[i].setImageDrawable(getIcon(poke.uID)); pokeListNames[i].setText(poke.nick); pokeListHPs[i].setText(poke.currentHP + "/" + poke.totalHP); pokeListItems[i].setText(poke.itemString); pokeListAbilities[i].setText(poke.abilityString); for (int j = 0; j < 4; j++) { pokeListMovePreviews[i][j].setText(poke.moves[j].toString()); pokeListMovePreviews[i][j].setShadowLayer((float)1, 1, 1, resources.getColor(activeBattle.allowSwitch && !activeBattle.clicked ? R.color.poke_text_shadow_enabled : R.color.poke_text_shadow_disabled)); String type; if (poke.moves[j].num == 237) type = Type.values()[poke.hiddenPowerType()].toString(); else type = poke.moves[j].getTypeString(); type = type.toLowerCase(Locale.UK); pokeListMovePreviews[i][j].setBackgroundResource(resources.getIdentifier(type + "_type_button", "drawable", pkgName)); } } } }); } public void switchToPokeViewer() { runOnUiThread(new Runnable() { public void run() { realViewSwitcher.setCurrentItem(1, true); } }); } public void onResume() { // XXX we might want more stuff here super.onResume(); if (battle != null) checkRearrangeTeamDialog(); } @Override public void onBackPressed() { startActivity(new Intent(BattleActivity.this, ChatActivity.class)); finish(); } private ServiceConnection connection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { netServ = ((NetworkService.LocalBinder)service).getService(); int battleId = getIntent().getIntExtra("battleId", 0); battle = netServ.activeBattles.get(battleId); if (battle == null) { battle = netServ.spectatedBattles.get(battleId); } if (battle == null) { startActivity(new Intent(BattleActivity.this, ChatActivity.class)); finish(); netServ.closeBattle(battleId); //remove the possibly ongoing notification return; } /* Is it a spectating battle or not? */ try { activeBattle = (Battle) battle; } catch (ClassCastException ex) { } if (isSpectating()) { /* If it's a spectating battle, we remove the info view's bottom margin */ RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)infoScroll.getLayoutParams(); params.setMargins(params.leftMargin, params.topMargin, params.rightMargin, ((RelativeLayout.LayoutParams)attackRow2.getLayoutParams()).bottomMargin); infoScroll.setLayoutParams(params); } else { teamLayout = getLayoutInflater().inflate(R.layout.battle_teamscreen, null); for(int i = 0; i < 4; i++) { attackNames[i] = (TextView)mainLayout.findViewById(resources.getIdentifier("attack" + (i+1) + "Name", "id", pkgName)); attackPPs[i] = (TextView)mainLayout.findViewById(resources.getIdentifier("attack" + (i+1) + "PP", "id", pkgName)); attackLayouts[i] = (RelativeLayout)mainLayout.findViewById(resources.getIdentifier("attack" + (i+1) + "Layout", "id", pkgName)); attackLayouts[i].setOnClickListener(battleListener); attackLayouts[i].setOnLongClickListener(moveListener); } for(int i = 0; i < 6; i++) { pokeListNames[i] = (TextView)teamLayout.findViewById(resources.getIdentifier("pokename" + (i+1), "id", pkgName)); pokeListHPs[i] = (TextView)teamLayout.findViewById(resources.getIdentifier("hp" + (i+1), "id", pkgName)); pokeListItems[i] = (TextView)teamLayout.findViewById(resources.getIdentifier("item" + (i+1), "id", pkgName)); pokeListAbilities[i] = (TextView)teamLayout.findViewById(resources.getIdentifier("ability" + (i+1), "id", pkgName)); pokeListButtons[i] = (RelativeLayout)teamLayout.findViewById(resources.getIdentifier("pokeViewLayout" + (i+1), "id", pkgName)); pokeListButtons[i].setOnClickListener(battleListener); pokeListIcons[i] = (ImageView)teamLayout.findViewById(resources.getIdentifier("pokeViewIcon" + (i+1), "id", pkgName)); for(int j = 0; j < 4; j++) pokeListMovePreviews[i][j] = (TextView)teamLayout.findViewById(resources.getIdentifier("p" + (i+1) + "_attack" + (j+1), "id", pkgName)); } } battleView.setBackgroundResource(resources.getIdentifier("bg" + battle.background, "drawable", pkgName)); // Set the UI to display the correct info me = battle.me; opp = battle.opp; // We don't know which timer is which until the battle starts, // so set them here. timers[me] = (TextView)mainLayout.findViewById(R.id.timerB); timers[opp] = (TextView)mainLayout.findViewById(R.id.timerA); names[me] = (TextView)mainLayout.findViewById(R.id.nameB); names[opp] = (TextView)mainLayout.findViewById(R.id.nameA); for (int i = 0; i < 6; i++) { pokeballs[me][i] = (ImageView)mainLayout.findViewById(resources.getIdentifier("pokeball" + (i + 1) + "B", "id", pkgName)); pokeballs[opp][i] = (ImageView)mainLayout.findViewById(resources.getIdentifier("pokeball" + (i + 1) + "A", "id", pkgName)); } updatePokeballs(); names[me].setText(battle.players[me].nick()); names[opp].setText(battle.players[opp].nick()); hpBars[me] = (TextProgressBar)mainLayout.findViewById(R.id.hpBarB); hpBars[opp] = (TextProgressBar)mainLayout.findViewById(R.id.hpBarA); currentPokeNames[me] = (TextView)mainLayout.findViewById(R.id.currentPokeNameB); currentPokeNames[opp] = (TextView)mainLayout.findViewById(R.id.currentPokeNameA); currentPokeLevels[me] = (TextView)mainLayout.findViewById(R.id.currentPokeLevelB); currentPokeLevels[opp] = (TextView)mainLayout.findViewById(R.id.currentPokeLevelA); currentPokeGenders[me] = (ImageView)mainLayout.findViewById(R.id.currentPokeGenderB); currentPokeGenders[opp] = (ImageView)mainLayout.findViewById(R.id.currentPokeGenderA); currentPokeStatuses[me] = (ImageView)mainLayout.findViewById(R.id.currentPokeStatusB); currentPokeStatuses[opp] = (ImageView)mainLayout.findViewById(R.id.currentPokeStatusA); pokeSprites[me] = (WebView)mainLayout.findViewById(R.id.pokeSpriteB); pokeSprites[opp] = (WebView)mainLayout.findViewById(R.id.pokeSpriteA); for(int i = 0; i < 2; i++) { pokeSprites[i].setOnLongClickListener(spriteListener); pokeSprites[i].setBackgroundColor(0); } infoView.setOnLongClickListener(new OnLongClickListener() { public boolean onLongClick(View view) { final EditText input = new EditText(BattleActivity.this); new AlertDialog.Builder(BattleActivity.this) .setTitle("Battle Chat") .setMessage("Send Battle Message") .setView(input) .setPositiveButton("Send", new DialogInterface.OnClickListener() { public void onClick(DialogInterface i, int j) { String message = input.getText().toString(); if (message.length() > 0) { Baos msg = new Baos(); msg.putInt(BattleActivity.this.battle.bID); msg.putString(message); if (activeBattle != null) { netServ.socket.sendMessage(msg, Command.BattleChat); } else { netServ.socket.sendMessage(msg, Command.SpectateBattleChat); } } } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }).show(); return false; } }); // Don't set battleActivity until after we've finished // getting UI elements. Otherwise there's a race condition if Battle // wants to update one of our UI elements we haven't gotten yet. synchronized(battle) { battle.activity = BattleActivity.this; } // Load scrollback infoView.setText(battle.hist); updateBattleInfo(true); // Prompt a UI update of the pokemon updateMyPoke(); updateOppPoke(opp); // Enable or disable buttons updateButtons(); // Start timer updating handler.postDelayed(updateTimeTask, 100); checkRearrangeTeamDialog(); } public void onServiceDisconnected(ComponentName className) { battle.activity = null; netServ = null; } }; public void end() { runOnUiThread(new Runnable() { public void run() { BattleActivity.this.finish(); } } ); } @Override public void onDestroy() { unbindService(connection); super.onDestroy(); } public OnTouchListener dialogListener = new OnTouchListener() { public boolean onTouch(View v, MotionEvent e) { int id = v.getId(); for(int i = 0; i < 6; i++) { if(id == myArrangePokeIcons[i].getId() && e.getAction() == MotionEvent.ACTION_DOWN) { Object dragInfo = v; mDragLayer.startDrag(v, myArrangePokeIcons[i], dragInfo, DragController.DRAG_ACTION_MOVE); break; } } return true; } }; public OnClickListener battleListener = new OnClickListener() { public void onClick(View v) { int id = v.getId(); // Check to see if click was on attack button for(int i = 0; i < 4; i++) if(id == attackLayouts[i].getId()) netServ.socket.sendMessage(activeBattle.constructAttack((byte)i), Command.BattleMessage); // Check to see if click was on pokelist button for(int i = 0; i < 6; i++) { if(id == pokeListButtons[i].getId()) { netServ.socket.sendMessage(activeBattle.constructSwitch((byte)i), Command.BattleMessage); realViewSwitcher.setCurrentItem(0, true); } } activeBattle.clicked = true; updateButtons(); } }; public OnLongClickListener moveListener = new OnLongClickListener() { public boolean onLongClick(View v) { int id = v.getId(); for(int i = 0; i < 4; i++) if(id == attackLayouts[i].getId() && !attackNames[i].equals("No Move")) { lastClickedMove = activeBattle.displayedMoves[i]; showDialog(BattleDialog.MoveInfo.ordinal()); return true; } return false; } }; public OnLongClickListener spriteListener = new OnLongClickListener() { public boolean onLongClick(View v) { if(v.getId() == pokeSprites[me].getId()) showDialog(BattleDialog.MyDynamicInfo.ordinal()); else showDialog(BattleDialog.OppDynamicInfo.ordinal()); return true; } }; void setPokeListButtonEnabled(int num, boolean enabled) { setLayoutEnabled(pokeListButtons[num], enabled); setTextViewEnabled(pokeListNames[num], enabled); setTextViewEnabled(pokeListItems[num], enabled); setTextViewEnabled(pokeListAbilities[num], enabled); setTextViewEnabled(pokeListHPs[num], enabled); //setTextViewEnabled(pokeListIcons[num], enabled); for(int i = 0; i < 4; i++) setTextViewEnabled(pokeListMovePreviews[num][i], enabled); } void setAttackButtonEnabled(int num, boolean enabled) { attackLayouts[num].setEnabled(enabled); attackNames[num].setEnabled(enabled); attackNames[num].setShadowLayer((float)1.5, 1, 1, resources.getColor(enabled ? R.color.poke_text_shadow_enabled : R.color.poke_text_shadow_disabled)); attackPPs[num].setEnabled(enabled); attackPPs[num].setShadowLayer((float)1.5, 1, 1, resources.getColor(enabled ? R.color.pp_text_shadow_enabled : R.color.pp_text_shadow_disabled)); } void setLayoutEnabled(ViewGroup v, boolean enabled) { v.setEnabled(enabled); v.getBackground().setAlpha(enabled ? 255 : 128); } void setTextViewEnabled(TextView v, boolean enabled) { v.setEnabled(enabled); v.setTextColor(v.getTextColors().withAlpha(enabled ? 255 : 128).getDefaultColor()); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(isSpectating() ? R.menu.spectatingbattleoptions : R.menu.battleoptions, menu); menu.findItem(R.id.sounds).setChecked(getSharedPreferences("battle", MODE_PRIVATE).getBoolean("pokemon_cries", true)); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); if (!isSpectating()) { if (activeBattle.gotEnd) { menu.findItem(R.id.close).setVisible(true); menu.findItem(R.id.cancel).setVisible(false); menu.findItem(R.id.forfeit).setVisible(false); menu.findItem(R.id.draw).setVisible(false); } else { /* No point in canceling if no action done */ menu.findItem(R.id.close).setVisible(false); menu.findItem(R.id.cancel).setVisible(activeBattle.clicked); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.cancel: netServ.socket.sendMessage(activeBattle.constructCancel(), Command.BattleMessage); break; case R.id.forfeit: if (netServ != null && netServ.isBattling() && !battle.gotEnd) showDialog(BattleDialog.ConfirmForfeit.ordinal()); break; case R.id.close: netServ.stopWatching(battle.bID); break; case R.id.draw: netServ.socket.sendMessage(activeBattle.constructDraw(), Command.BattleMessage); break; case R.id.sounds: item.setChecked(!item.isChecked()); getSharedPreferences("battle", Context.MODE_PRIVATE).edit().putBoolean("pokemon_cries", item.isChecked()).commit(); break; } return true; } public void notifyRearrangeTeamDialog() { runOnUiThread(new Runnable() { public void run() { checkRearrangeTeamDialog(); } } ); } private void checkRearrangeTeamDialog() { if (netServ != null && netServ.isBattling() && battle.shouldShowPreview) { showDialog(BattleDialog.RearrangeTeam.ordinal()); } } void endBattle() { if (netServ != null && netServ.socket != null && netServ.socket.isConnected() && netServ.isBattling()) { Baos bID = new Baos(); bID.putInt(battle.bID); netServ.socket.sendMessage(bID, Command.BattleFinished); } } protected Dialog onCreateDialog(final int id) { int player = me; final AlertDialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); switch(BattleDialog.values()[id]) { case RearrangeTeam: { View layout = inflater.inflate(R.layout.rearrange_team_dialog, (LinearLayout)findViewById(R.id.rearrange_team_dialog)); builder.setView(layout) .setPositiveButton("Done", new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int which) { netServ.socket.sendMessage(activeBattle.constructRearrange(), Command.BattleMessage); battle.shouldShowPreview = false; removeDialog(id); }}) .setCancelable(false); dialog = builder.create(); mDragLayer = (DragLayer)layout.findViewById(R.id.drag_my_poke); for(int i = 0; i < 6; i++){ BattlePoke poke = activeBattle.myTeam.pokes[i]; myArrangePokeIcons[i] = (PokeDragIcon)layout.findViewById(resources.getIdentifier("my_arrange_poke" + (i+1), "id", pkgName)); myArrangePokeIcons[i].setOnTouchListener(dialogListener); myArrangePokeIcons[i].setImageDrawable(getIcon(poke.uID)); myArrangePokeIcons[i].num = i; myArrangePokeIcons[i].battleActivity = this; ShallowShownPoke oppPoke = activeBattle.oppTeam.pokes[i]; oppArrangePokeIcons[i] = (ImageView)layout.findViewById(resources.getIdentifier("foe_arrange_poke" + (i+1), "id", pkgName)); oppArrangePokeIcons[i].setImageDrawable(getIcon(oppPoke.uID)); } return dialog; } case ConfirmForfeit: builder.setMessage("Really Forfeit?") .setCancelable(true) .setPositiveButton("Forfeit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { endBattle(); } }) .setNegativeButton("Cancel", null); return builder.create(); case OppDynamicInfo: player = opp; case MyDynamicInfo: if(netServ != null && battle != null) { final Dialog simpleDialog = new Dialog(this); simpleDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); simpleDialog.setContentView(R.layout.dynamic_info_layout); TextView t = (TextView)simpleDialog.findViewById(R.id.nameTypeView); t.setText((player == me ? activeBattle.myTeam.pokes[0] : battle.currentPoke(player)).nameAndType()); t = (TextView)simpleDialog.findViewById(R.id.statNamesView); t.setText(battle.dynamicInfo[player].statsAndHazards()); t = (TextView)simpleDialog.findViewById(R.id.statNumsView); if (player == me) t.setText(activeBattle.myTeam.pokes[0].printStats()); else t.setVisibility(View.GONE); t = (TextView)simpleDialog.findViewById(R.id.statBoostView); String s = battle.dynamicInfo[player].boosts(player == me); if (!"\n\n\n\n".equals(s)) t.setText(s); else t.setVisibility(View.GONE); simpleDialog.setCanceledOnTouchOutside(true); simpleDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { removeDialog(id); } }); simpleDialog.findViewById(R.id.dynamic_info_layout).setOnClickListener(new OnClickListener() { public void onClick(View v) { simpleDialog.cancel(); } }); return simpleDialog; } case MoveInfo: dialog = builder.setTitle(lastClickedMove.name) .setMessage(lastClickedMove.descAndEffects()) .setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { removeDialog(id); } }) .create(); dialog.setCanceledOnTouchOutside(true); return dialog; default: return new Dialog(this); } } } \ No newline at end of file
false
false
null
null
diff --git a/src/StudentAssignment.java b/src/StudentAssignment.java index 48cd643..2e7a8fb 100644 --- a/src/StudentAssignment.java +++ b/src/StudentAssignment.java @@ -1,46 +1,46 @@ // Author(s): Richard Ceus // Date Modified: 4/10/12 // Filename: StudentAssignment.java import java.util.*; public class StudentAssignment extends Assignment { private double grade; public StudentAssignment(Calendar date, int number) { super(date, number); grade = 0.0; } public StudentAssignment(Assignment asst){ super(asst); } public double getGrade() { calculateGrade(); return grade; } public void calculateGrade() { - int correct; - int total; + int correct = 0; + int total = 0; for(int count = 0; count > questionList.size(); count++) { if (questionList.get(count).compareAnswers()) { correct++; } total++; } grade = correct/total; } }
true
true
public void calculateGrade() { int correct; int total; for(int count = 0; count > questionList.size(); count++) { if (questionList.get(count).compareAnswers()) { correct++; } total++; } grade = correct/total; }
public void calculateGrade() { int correct = 0; int total = 0; for(int count = 0; count > questionList.size(); count++) { if (questionList.get(count).compareAnswers()) { correct++; } total++; } grade = correct/total; }
diff --git a/src/lang/LuaFoldingBuilder.java b/src/lang/LuaFoldingBuilder.java index d70d5b1d..708d1b24 100644 --- a/src/lang/LuaFoldingBuilder.java +++ b/src/lang/LuaFoldingBuilder.java @@ -1,105 +1,106 @@ /* * Copyright 2010 Jon S Akhtar (Sylvanaar) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sylvanaar.idea.Lua.lang; import com.intellij.lang.ASTNode; import com.intellij.lang.folding.FoldingBuilder; import com.intellij.lang.folding.FoldingDescriptor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.sylvanaar.idea.Lua.lang.parser.LuaElementTypes; import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaTableConstructor; import com.sylvanaar.idea.Lua.lang.psi.statements.LuaFunctionDefinitionStatement; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import static com.sylvanaar.idea.Lua.lang.lexer.LuaTokenTypes.LONGCOMMENT; /** * Created by IntelliJ IDEA. * User: Jon S Akhtar * Date: Apr 10, 2010 * Time: 2:54:53 PM */ public class LuaFoldingBuilder implements FoldingBuilder { @NotNull @Override public FoldingDescriptor[] buildFoldRegions(@NotNull ASTNode node, @NotNull Document document) { List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>(); appendDescriptors(node, document, descriptors); return descriptors.toArray(new FoldingDescriptor[descriptors.size()]); } private void appendDescriptors(final ASTNode node, final Document document, final List<FoldingDescriptor> descriptors) { try { if (isFoldableNode(node)) { final PsiElement psiElement = node.getPsi(); if (psiElement instanceof LuaFunctionDefinitionStatement) { LuaFunctionDefinitionStatement stmt = (LuaFunctionDefinitionStatement) psiElement; + System.out.println(stmt.getText()); descriptors.add(new FoldingDescriptor(node, new TextRange(stmt.getParameters().getTextRange().getEndOffset() + 1, node.getTextRange().getEndOffset()))); } if (psiElement instanceof LuaTableConstructor) { LuaTableConstructor stmt = (LuaTableConstructor) psiElement; - if (stmt.getTextLength() > 2) + if (stmt.getText().indexOf("\n")>0) descriptors.add(new FoldingDescriptor(node, new TextRange(stmt.getTextRange().getStartOffset() + 1, node.getTextRange().getEndOffset() - 1))); } } if (node.getElementType() == LONGCOMMENT && node.getTextLength() > 2) { descriptors.add(new FoldingDescriptor(node, node.getTextRange())); } ASTNode child = node.getFirstChildNode(); while (child != null) { appendDescriptors(child, document, descriptors); child = child.getTreeNext(); } } catch (Exception ignored) { } } private boolean isFoldableNode(ASTNode node) { return node.getElementType() == LuaElementTypes.FUNCTION_DEFINITION || node.getElementType() == LuaElementTypes.TABLE_CONSTUCTOR; } @Override public String getPlaceholderText(@NotNull ASTNode node) { if (node.getElementType() == LONGCOMMENT) return "comment"; return "..."; } @Override public boolean isCollapsedByDefault(@NotNull ASTNode node) { return false; } }
false
true
private void appendDescriptors(final ASTNode node, final Document document, final List<FoldingDescriptor> descriptors) { try { if (isFoldableNode(node)) { final PsiElement psiElement = node.getPsi(); if (psiElement instanceof LuaFunctionDefinitionStatement) { LuaFunctionDefinitionStatement stmt = (LuaFunctionDefinitionStatement) psiElement; descriptors.add(new FoldingDescriptor(node, new TextRange(stmt.getParameters().getTextRange().getEndOffset() + 1, node.getTextRange().getEndOffset()))); } if (psiElement instanceof LuaTableConstructor) { LuaTableConstructor stmt = (LuaTableConstructor) psiElement; if (stmt.getTextLength() > 2) descriptors.add(new FoldingDescriptor(node, new TextRange(stmt.getTextRange().getStartOffset() + 1, node.getTextRange().getEndOffset() - 1))); } } if (node.getElementType() == LONGCOMMENT && node.getTextLength() > 2) { descriptors.add(new FoldingDescriptor(node, node.getTextRange())); } ASTNode child = node.getFirstChildNode(); while (child != null) { appendDescriptors(child, document, descriptors); child = child.getTreeNext(); } } catch (Exception ignored) { } }
private void appendDescriptors(final ASTNode node, final Document document, final List<FoldingDescriptor> descriptors) { try { if (isFoldableNode(node)) { final PsiElement psiElement = node.getPsi(); if (psiElement instanceof LuaFunctionDefinitionStatement) { LuaFunctionDefinitionStatement stmt = (LuaFunctionDefinitionStatement) psiElement; System.out.println(stmt.getText()); descriptors.add(new FoldingDescriptor(node, new TextRange(stmt.getParameters().getTextRange().getEndOffset() + 1, node.getTextRange().getEndOffset()))); } if (psiElement instanceof LuaTableConstructor) { LuaTableConstructor stmt = (LuaTableConstructor) psiElement; if (stmt.getText().indexOf("\n")>0) descriptors.add(new FoldingDescriptor(node, new TextRange(stmt.getTextRange().getStartOffset() + 1, node.getTextRange().getEndOffset() - 1))); } } if (node.getElementType() == LONGCOMMENT && node.getTextLength() > 2) { descriptors.add(new FoldingDescriptor(node, node.getTextRange())); } ASTNode child = node.getFirstChildNode(); while (child != null) { appendDescriptors(child, document, descriptors); child = child.getTreeNext(); } } catch (Exception ignored) { } }
diff --git a/csharp-squid/src/main/java/com/sonar/csharp/squid/api/CSharpGrammar.java b/csharp-squid/src/main/java/com/sonar/csharp/squid/api/CSharpGrammar.java index a61353eea..065455ef5 100644 --- a/csharp-squid/src/main/java/com/sonar/csharp/squid/api/CSharpGrammar.java +++ b/csharp-squid/src/main/java/com/sonar/csharp/squid/api/CSharpGrammar.java @@ -1,344 +1,344 @@ /* * Copyright (C) 2010 SonarSource SA * All rights reserved * mailto:contact AT sonarsource DOT com */ package com.sonar.csharp.squid.api; import com.sonar.sslr.api.Grammar; import com.sonar.sslr.api.Rule; /** * Listing of the syntactic elements of the C# grammar */ public class CSharpGrammar implements Grammar { public Rule literal; public Rule rightShift; public Rule rightShiftAssignment; // A.2.1 Basic concepts public Rule compilationUnit; // OK public Rule namespaceName; // OK public Rule typeName; // OK public Rule namespaceOrTypeName; // OK // A.2.2 Types public Rule simpleType; // OK // NOT NECESSARY public Rule numericType; // OK - tested via SimpleTypeTest // NOT NECESSARY public Rule integralType; // OK - tested via SimpleTypeTest public Rule floatingPointType; // OK - tested via SimpleTypeTest // NOT NECESSARY public Rule rankSpecifier; // OK public Rule rankSpecifiers; public Rule typePrimary; public Rule nullableType; // OK // NOT NECESSARYY public Rule pointerType; // OK, moved from unsafe code to remove the left recursions public Rule arrayType; // OK public Rule type; // OK public Rule nonArrayType; // LATER public Rule nonNullableValueType; public Rule classType; // OK, type bin public Rule interfaceType; // OK, type bin public Rule enumType; // LATER // NOT NECESSARY, type bin public Rule delegateType; // LATER, type bin // A.2.3 Variables public Rule variableReference; // LATER // A.2.4 Expressions public Rule primaryExpressionPrimary; // LATER public Rule primaryNoArrayCreationExpression; // LATER public Rule postElementAccess; // OK public Rule postMemberAccess; // OK public Rule postInvocation; // OK public Rule postIncrement; // OK public Rule postDecrement; // OK public Rule postPointerMemberAccess; // OK, moved from unsafe code to remove the left recursions, originally pointerMemberAccess - public Rule postfixExpression; // OK + public Rule postfixExpression; // LATER public Rule primaryExpression; // OK public Rule argumentList; // LATER public Rule argument; // OK public Rule argumentName; // OK public Rule argumentValue; // OK public Rule simpleName; // OK public Rule parenthesizedExpression; // OK public Rule memberAccess; // OK, last part of the rule is in postMemberAccess public Rule predefinedType; // OK public Rule thisAccess; // LATER public Rule baseAccess; // OK public Rule objectCreationExpression; // OK public Rule objectOrCollectionInitializer; // OK public Rule objectInitializer; // OK public Rule memberInitializer; // OK public Rule initializerValue; // OK public Rule collectionInitializer; // OK public Rule elementInitializer; // OK public Rule expressionList; // LATER public Rule arrayCreationExpression; // OK public Rule delegateCreationExpression; // OK public Rule anonymousObjectCreationExpression; // OK public Rule anonymousObjectInitializer; // OK public Rule memberDeclarator; // OK public Rule typeOfExpression; // OK public Rule unboundTypeName; // OK public Rule genericDimensionSpecifier; // OK public Rule checkedExpression; // OK public Rule uncheckedExpression; // OK public Rule defaultValueExpression; // OK public Rule unaryExpression; // OK public Rule preIncrementExpression; // OK - tested via UnaryExpressionTest public Rule preDecrementExpression; // OK - tested via UnaryExpressionTest public Rule castExpression; // OK - tested via UnaryExpressionTest public Rule multiplicativeExpression; // OK public Rule additiveExpression; // OK public Rule shiftExpression; // OK public Rule relationalExpression; // OK public Rule equalityExpression; // OK public Rule andExpression; // OK public Rule exclusiveOrExpression; // OK public Rule inclusiveOrExpression; // OK public Rule conditionalAndExpression; // OK public Rule conditionalOrExpression; // OK public Rule nullCoalescingExpression; // OK public Rule conditionalExpression; // OK public Rule lambdaExpression; // OK public Rule anonymousMethodExpression; // OK public Rule anonymousFunctionSignature; // OK public Rule explicitAnonymousFunctionSignature; // OK public Rule explicitAnonymousFunctionParameter; // OK public Rule anonymousFunctionParameterModifier; // OK public Rule implicitAnonymousFunctionSignature; // OK public Rule implicitAnonymousFunctionParameter; // OK public Rule anonymousFunctionBody; // OK public Rule queryExpression; // OK public Rule fromClause; // OK public Rule queryBody; // OK public Rule queryBodyClause; // OK public Rule letClause; // OK public Rule whereClause; // OK public Rule joinClause; // OK public Rule joinIntoClause; // OK public Rule orderByClause; // OK public Rule ordering; // OK public Rule orderingDirection; // OK public Rule selectOrGroupClause; // OK public Rule selectClause; // OK public Rule groupClause; // OK public Rule queryContinuation; // OK public Rule assignment; // OK public Rule expression; // OK public Rule nonAssignmentExpression; // OK public Rule constantExpression; // LATER public Rule booleanExpression; // LATER // A.2.5 Statement public Rule statement; // OK public Rule embeddedStatement; // OK public Rule block; // BRIDGE TEST ONLY public Rule labeledStatement; // OK public Rule declarationStatement; // OK public Rule localVariableDeclaration; // OK public Rule localVariableDeclarator; // OK - tested via LocalVariableDeclarationTest public Rule localVariableInitializer; // OK public Rule localConstantDeclaration; // OK public Rule constantDeclarator; // OK public Rule expressionStatement; // OK public Rule selectionStatement; // NO NEED public Rule ifStatement; // OK public Rule switchStatement; // OK public Rule switchSection; // OK public Rule switchLabel; // OK public Rule iterationStatement; // OK public Rule whileStatement; // OK public Rule doStatement; // OK public Rule forStatement; // OK public Rule forInitializer; // OK public Rule forCondition; // NO NEED public Rule forIterator; // NO NEED public Rule statementExpressionList; // OK public Rule foreachStatement; // OK public Rule jumpStatement; // OK public Rule breakStatement; // OK public Rule continueStatement; // OK public Rule gotoStatement; // OK public Rule returnStatement; // OK public Rule throwStatement; // OK public Rule tryStatement; // OK public Rule catchClauses; // OK public Rule specificCatchClause; // OK public Rule generalCatchClause; // OK public Rule finallyClause; // OK public Rule checkedStatement; // OK public Rule uncheckedStatement; // OK public Rule lockStatement; // OK public Rule usingStatement; // OK public Rule resourceAcquisition; // OK - tested via UsingStatementTest public Rule yieldStatement; // OK public Rule namespaceDeclaration; // OK public Rule qualifiedIdentifier; // OK public Rule namespaceBody; // OK public Rule externAliasDirective; // OK public Rule usingDirective; // OK public Rule usingAliasDirective; // OK - tested via UsingDirectiveTest public Rule usingNamespaceDirective; // OK - tested via UsingDirectiveTest public Rule namespaceMemberDeclaration; // OK public Rule typeDeclaration; // OK public Rule qualifiedAliasMember; // OK // A.2.6 Classes public Rule classDeclaration; // OK public Rule classModifier; // OK public Rule classBase; // OK public Rule interfaceTypeList; // LATER public Rule classBody; // OK public Rule classMemberDeclaration; // LATER public Rule constantDeclaration; // OK public Rule constantModifier; // OK - tested via ConstantDeclarationTest public Rule fieldDeclaration; // OK public Rule fieldModifier; // OK - tested via FieldDeclarationTest public Rule variableDeclarator; // OK public Rule variableInitializer; // OK public Rule methodDeclaration; // LATER public Rule methodHeader; // OK public Rule methodModifier; // OK - tested via MethodHeaderTest public Rule returnType; // OK public Rule memberName; // OK public Rule methodBody; // LATER public Rule formalParameterList; // OK public Rule fixedParameters; // LATER public Rule fixedParameter; // OK public Rule parameterModifier; // OK - tested via FixedParameterTest public Rule parameterArray; // OK public Rule propertyDeclaration; // OK public Rule propertyModifier; // OK - tested via PropertyDeclarationTest public Rule accessorDeclarations; // OK public Rule getAccessorDeclaration; // OK public Rule setAccessorDeclaration; // OK public Rule accessorModifier; // OK public Rule accessorBody; // LATER public Rule eventDeclaration; // OK public Rule eventModifier; // OK - tested via EventDeclarationTest public Rule eventAccessorDeclarations; // OK public Rule addAccessorDeclaration; // OK - tested via EventAccessorDeclarationTest public Rule removeAccessorDeclaration; // OK - tested via EventAccessorDeclarationTest public Rule indexerDeclaration; // OK public Rule indexerModifier; // OK - tested via IndexerDeclarationTest public Rule indexerDeclarator; // OK public Rule operatorDeclaration; // OK public Rule operatorModifier; // OK - tested via OperatorDeclarationTest public Rule operatorDeclarator; // OK public Rule unaryOperatorDeclarator; // OK public Rule overloadableUnaryOperator; // OK - tested via UnaryOperatorDeclaration public Rule binaryOperatorDeclarator; // OK public Rule overloadableBinaryOperator; // OK - tested via BinaryOperatorDeclaration public Rule conversionOperatorDeclarator; // OK public Rule operatorBody; // LATER public Rule constructorDeclaration; // OK public Rule constructorModifier; // OK - tested via ConstructorDeclarationTest public Rule constructorDeclarator; // OK public Rule constructorInitializer; // OK public Rule constructorBody; // OK public Rule staticConstructorDeclaration; // OK public Rule staticConstructorModifiers; // OK public Rule staticConstructorBody; // LATER public Rule destructorDeclaration; // OK public Rule destructorBody; // LATER // A.2.7 Struct public Rule structDeclaration; // OK public Rule structModifier; // OK - tested via StructDeclarationTest public Rule structInterfaces; // OK public Rule structBody; // OK public Rule structMemberDeclaration; // OK - tested via StructBodyTest // A.2.8 Arrays public Rule arrayInitializer; // OK public Rule variableInitializerList; // OK // A.2.9 Interfaces public Rule interfaceDeclaration; // OK public Rule interfaceModifier; // OK - tested via InterfaceDeclarationTest public Rule variantTypeParameterList; // OK public Rule variantTypeParameter; // OK public Rule varianceAnnotation; // OK public Rule interfaceBase; // OK public Rule interfaceBody; // OK public Rule interfaceMemberDeclaration; // OK - tested via InterfaceBodyDeclaration public Rule interfaceMethodDeclaration; // OK public Rule interfacePropertyDeclaration; // OK public Rule interfaceAccessors; // OK public Rule interfaceEventDeclaration; // OK public Rule interfaceIndexerDeclaration; // OK // A.2.10 Enums public Rule enumDeclaration; // OK public Rule enumBase; // OK public Rule enumBody; // OK public Rule enumModifier; // OK - tested via EnumDeclarationTest public Rule enumMemberDeclarations; // OK public Rule enumMemberDeclaration; // OK // A.2.11 Delegates public Rule delegateDeclaration; // OK public Rule delegateModifier; // OK - tested via DelegateDeclarationTest // A.2.12 Attributes public Rule globalAttributes; // LATER public Rule globalAttributeSection; // OK public Rule globalAttributeTargetSpecifier; // OK public Rule globalAttributeTarget; // OK public Rule attributes; // LATER public Rule attributeSection; // OK public Rule attributeTargetSpecifier; // OK public Rule attributeTarget; // OK public Rule attributeList; // OK public Rule attribute; // OK public Rule attributeName; // LATER public Rule attributeArguments; // OK public Rule positionalArgument; // LATER public Rule namedArgument; // OK public Rule attributeArgumentExpression; // OK // A.2.13 Generics public Rule typeParameterList; // OK public Rule typeParameters; // OK public Rule typeParameter; // OK - tested via TypeParametersTest public Rule typeArgumentList; // OK public Rule typeArgument; // OK - tested via TypeArgumentListTest public Rule typeParameterConstraintsClauses; // LATER public Rule typeParameterConstraintsClause; // OK public Rule typeParameterConstraints; // OK public Rule primaryConstraint; // OK public Rule secondaryConstraints; // OK public Rule constructorConstraint; // OK // A.3 Unsafe code public Rule unsafeStatement; // OK // pointerType was moved to the types part in order to remove the left recursions public Rule pointerIndirectionExpression; // OK // pointerMemberAccess was moved to the expressions part (as postPointerMemberAccess) in order to remove the left recursions public Rule pointerElementAccess; // OK public Rule addressOfExpression; // OK public Rule sizeOfExpression; // OK public Rule fixedStatement; // OK public Rule fixedPointerDeclarator; // OK public Rule fixedPointerInitializer; // OK public Rule fixedSizeBufferDeclaration; // OK public Rule fixedSizeBufferModifier; // OK public Rule fixedSizeBufferDeclarator; // OK public Rule stackallocInitializer; // OK /** * ${@inheritDoc} */ public Rule getRootRule() { return compilationUnit; } }
true
false
null
null
diff --git a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/random/ParallelRandomDemo.java b/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/random/ParallelRandomDemo.java index 14a07dc0..439fc9d7 100644 --- a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/random/ParallelRandomDemo.java +++ b/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/random/ParallelRandomDemo.java @@ -1,159 +1,159 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.nativelibs4java.opencl.demos.random; import com.nativelibs4java.opencl.util.ParallelRandom; import com.nativelibs4java.opencl.CLBuildException; import com.nativelibs4java.opencl.CLContext; import com.nativelibs4java.opencl.CLEvent; import com.nativelibs4java.opencl.CLIntBuffer; import com.nativelibs4java.opencl.CLMem.MapFlags; import com.nativelibs4java.opencl.CLMem.Usage; import com.nativelibs4java.opencl.CLQueue; import com.nativelibs4java.opencl.JavaCL; import com.nativelibs4java.util.NIOUtils; import java.io.IOException; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author ochafik */ public class ParallelRandomDemo { private static void println(IntBuffer b) { for (int i = 0, n = b.capacity(); i < n; i++) { if (i > 0) System.out.print(", "); System.out.print(b.get(i)); if (i > 32) System.out.print("..."); } System.out.println(); } static class Stat { long total; long times; boolean skippedFirst; void add(long value) { if (!skippedFirst) { skippedFirst = true; return; } total += value; times++; } long average() { return times == 0 ? 0 : total / times; } } public static void main(String[] args) { try { CLContext context = JavaCL.createBestContext(); CLQueue queue = context.createDefaultQueue(); int warmupSize = 16; ParallelRandom demo = new ParallelRandom(queue, warmupSize, System.currentTimeMillis()); - println(demo.getSeeds().read(queue)); + println((IntBuffer)demo.getSeeds().read(queue)); IntBuffer b = demo.next(); println(b); b = demo.next(); println(b); b = demo.next(); println(b); gc(); long start = System.nanoTime(); int loops = 2800; Random random = new Random(); int res = 0; for (int i = loops; i-- != 0;) { //demo.next(b); //demo.next(); demo.doNext(); res |= random.nextInt(); } demo.getQueue().finish(); long time = System.nanoTime() - start; System.err.println("Warmup took " + time + " ns"); Stat stat; int testSize = 1024 * 1024;//1024 * 1024; int testLoops = 10; System.err.println("n = " + testSize); demo = new ParallelRandom(queue, testSize, System.currentTimeMillis()); b = demo.next(); gc(); stat = new Stat(); for (int iTest = 0; iTest < testLoops; iTest++) { start = System.nanoTime(); //b = demo.next();//b); demo.doNext(); demo.getQueue().finish(); time = System.nanoTime() - start; stat.add(time); //System.err.println("[OpenCL] Cost per random number = " + (time / (double)testSize) + " ns"); } long avgCL = stat.average(); System.err.println("[OpenCL] Avg Cost per random number = " + (stat.average() / (double)testSize) + " ns"); System.err.println(); gc(); stat = new Stat(); for (int iTest = 0; iTest < testLoops; iTest++) { start = System.nanoTime(); for (int i = testSize; i-- != 0;) res |= random.nextInt(); time = System.nanoTime() - start; stat.add(time); //System.err.println("[Random.nextInt()] Cost per random number = " + (time / (double)testSize) + " ns"); } long avgJava = stat.average(); System.err.println("[Random.nextInt()] Avg Cost per random number = " + (stat.average() / (double)testSize) + " ns"); System.err.println(); double timesCLFasterThanJava = avgJava / (double)avgCL; System.err.println("Java / CL (avg) = " + timesCLFasterThanJava); System.err.println(res); // make sure no brutal optimization happens System.err.println(b.get(0)); // make sure no brutal optimization happens //println(b); } catch (IOException ex) { Logger.getLogger(ParallelRandom.class.getName()).log(Level.SEVERE, null, ex); } } static void gc() { try { System.gc(); Thread.sleep(200); System.gc(); Thread.sleep(200); } catch (InterruptedException ex) { Logger.getLogger(ParallelRandom.class.getName()).log(Level.SEVERE, null, ex); } } } diff --git a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/sobelfilter/SobelFilterDemo.java b/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/sobelfilter/SobelFilterDemo.java index 6f965d83..cd560c4e 100644 --- a/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/sobelfilter/SobelFilterDemo.java +++ b/libraries/OpenCL/Demos/src/main/java/com/nativelibs4java/opencl/demos/sobelfilter/SobelFilterDemo.java @@ -1,186 +1,186 @@ /* * JavaCL - Java API and utilities for OpenCL * http://javacl.googlecode.com/ * * Copyright (c) 2009-2010, Olivier Chafik (http://ochafik.free.fr/) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Olivier Chafik nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY OLIVIER CHAFIK AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.nativelibs4java.opencl.demos.sobelfilter; import javax.swing.*; import java.nio.*; import com.nativelibs4java.opencl.*; import com.nativelibs4java.opencl.util.*; import com.nativelibs4java.opencl.demos.SetupUtils; import com.ochafik.util.listenable.Pair; import java.awt.image.*; import java.io.*; import java.nio.FloatBuffer; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import com.sun.jna.Platform; import java.awt.FileDialog; public class SobelFilterDemo { static File chooseFile() { if (Platform.isMac()) { FileDialog d = new FileDialog((java.awt.Frame)null); d.setMode(FileDialog.LOAD); d.show(); String f = d.getFile(); if (f != null) return new File(new File(d.getDirectory()), d.getFile()); } else { JFileChooser chooser = new JFileChooser(); if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) return chooser.getSelectedFile(); } return null; } public static void main(String[] args) { try { SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable(); File imageFile = chooseFile(); if (imageFile == null) return; BufferedImage image = ImageIO.read(imageFile); int width = image.getWidth(), height = image.getHeight(); //int step = 32; // image = image.getSubimage(0, 0, (width / step) * step, (height / step) * step); //image = image.getSubimage(0, 0, 512, 512);//(width / step) * step, (height / step) * step); JFrame f = new JFrame("JavaCL Sobel Filter Demo"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SobelFilterDemo demo = new SobelFilterDemo(); Pair<BufferedImage, BufferedImage> imgs = demo.computeSobel(image); f.getContentPane().add("Center", //new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, // new JScrollPane(new JLabel(new ImageIcon(image))), new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(new JLabel(new ImageIcon(imgs.getFirst()))), new JScrollPane(new JLabel(new ImageIcon(imgs.getSecond()))) ) {/** * */ private static final long serialVersionUID = 8267014922143370639L; { setResizeWeight(0.5); }} //) ); f.pack(); f.setVisible(true); } catch (Throwable th) { th.printStackTrace(); SetupUtils.exception(th); } } CLContext context; CLQueue queue; SimpleSobel sobel; - ReductionUtils.Reductor<FloatBuffer> floatMinReductor; + ReductionUtils.Reductor<Float> floatMinReductor; public SobelFilterDemo() throws IOException, CLBuildException { context = JavaCL.createBestContext(); queue = context.createDefaultQueue(); sobel = new SimpleSobel(context); floatMinReductor = ReductionUtils.createReductor(context, ReductionUtils.Operation.Max, OpenCLType.Float, 1); } public static int roundUp(int group_size, int global_size) { int r = global_size % group_size; return r == 0 ? global_size : global_size + group_size - r; } public Pair<BufferedImage, BufferedImage> computeSobel(BufferedImage img) throws IOException, CLBuildException { int width = img.getWidth(), height = img.getHeight(); int dataSize = height * width; int[] pixels = img.getRGB(0, 0, width, height, null, 0, width); CLFloatBuffer gradients = context.createFloatBuffer(CLMem.Usage.InputOutput, dataSize), directions = context.createFloatBuffer(CLMem.Usage.InputOutput, dataSize); CLEvent evt = sobel.simpleSobel(queue, context.createIntBuffer(CLMem.Usage.Input, IntBuffer.wrap(pixels), true).asCLByteBuffer(), width, height, gradients, directions, new int[] { width, height }, null//new int[] { 1, 1 } ); //queue.finish(); //float[] test = new float[1000]; //gradients.read(queue).get(test); - float gradientMax = floatMinReductor.reduce(queue, gradients, dataSize, 32, evt).get(); - float dirMax = floatMinReductor.reduce(queue, directions, dataSize, 32, evt).get(); + float gradientMax = ((FloatBuffer)floatMinReductor.reduce(queue, gradients, dataSize, 32, evt)).get(); + float dirMax = ((FloatBuffer)floatMinReductor.reduce(queue, directions, dataSize, 32, evt)).get(); //CLEvent.waitFor(evtGradMax, evtDirMax); CLIntBuffer gradientPixels = context.createIntBuffer(CLMem.Usage.Output, dataSize); CLIntBuffer directionPixels = context.createIntBuffer(CLMem.Usage.Output, dataSize); //CLEvent evtGrad = sobel.normalizeImage(queue, gradients, gradientMax, gradientPixels.asCLByteBuffer(), new int[] { dataSize }, null); //CLEvent evtDir = sobel.normalizeImage(queue, directions, dirMax, directionPixels.asCLByteBuffer(), new int[] { dataSize }, null); queue.finish(); BufferedImage gradientsImage = getRowsOrderImage(queue, gradientPixels, width, height, pixels);//, evtGrad); BufferedImage directionsImage = getRowsOrderImage(queue, directionPixels, width, height, pixels);//, evtDir); return new Pair<BufferedImage, BufferedImage>(gradientsImage, directionsImage); } static BufferedImage getRowsOrderImage(CLQueue queue, CLIntBuffer buffer, int width, int height, int[] pixelsTemp, CLEvent... eventsToWaitFor) { queue.finish(); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); int[] pixels = pixelsTemp == null ? new int[width * height] : pixelsTemp; - buffer.read(queue, eventsToWaitFor).get(pixels); + ((IntBuffer)buffer.read(queue, eventsToWaitFor)).get(pixels); img.setRGB(0, 0, width,height, pixels, 0, width); return img; } }
false
false
null
null
diff --git a/org.eclipse.text/src/org/eclipse/jface/text/TextUtilities.java b/org.eclipse.text/src/org/eclipse/jface/text/TextUtilities.java index bc85c4a68..d3c3a3a62 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/TextUtilities.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/TextUtilities.java @@ -1,570 +1,570 @@ /******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. + * Copyright (c) 2000, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.text; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.Assert; /** * A collection of text functions. * <p> - * This class is neither intended to be instantiated nor instantiated. + * This class is neither intended to be instantiated nor subclassed. * </p> */ public class TextUtilities { /** * Default line delimiters used by the text functions of this class. */ public final static String[] DELIMITERS= new String[] { "\n", "\r", "\r\n" }; //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ /** * Default line delimiters used by these text functions. * * @deprecated use DELIMITERS instead */ public final static String[] fgDelimiters= DELIMITERS; /** * Determines which one of default line delimiters appears first in the list. If none of them the * hint is returned. * * @param text the text to be checked * @param hint the line delimiter hint * @return the line delimiter */ public static String determineLineDelimiter(String text, String hint) { try { int[] info= indexOf(DELIMITERS, text, 0); return DELIMITERS[info[1]]; } catch (ArrayIndexOutOfBoundsException x) { } return hint; } /** * Returns the starting position and the index of the first matching search string * in the given text that is greater than the given offset. If more than one search * string matches with the same starting position then the longest one is returned. * * @param searchStrings the strings to search for * @param text the text to be searched * @param offset the offset at which to start the search * @return an <code>int[]</code> with two elements where the first is the starting offset, the second the index of the found * search string in the given <code>searchStrings</code> array, returns <code>[-1, -1]</code> if no match exists */ public static int[] indexOf(String[] searchStrings, String text, int offset) { int[] result= { -1, -1 }; int zeroIndex= -1; for (int i= 0; i < searchStrings.length; i++) { int length= searchStrings[i].length(); if (length == 0) { zeroIndex= i; continue; } int index= text.indexOf(searchStrings[i], offset); if (index >= 0) { if (result[0] == -1) { result[0]= index; result[1]= i; } else if (index < result[0]) { result[0]= index; result[1]= i; } else if (index == result[0] && length > searchStrings[result[1]].length()) { result[0]= index; result[1]= i; } } } if (zeroIndex > -1 && result[0] == -1) { result[0]= 0; result[1]= zeroIndex; } return result; } /** * Returns the index of the longest search string with which the given text ends or * <code>-1</code> if none matches. * * @param searchStrings the strings to search for * @param text the text to search * @return the index in <code>searchStrings</code> of the longest string with which <code>text</code> ends or <code>-1</code> */ public static int endsWith(String[] searchStrings, String text) { int index= -1; for (int i= 0; i < searchStrings.length; i++) { if (text.endsWith(searchStrings[i])) { if (index == -1 || searchStrings[i].length() > searchStrings[index].length()) index= i; } } return index; } /** * Returns the index of the longest search string with which the given text starts or <code>-1</code> * if none matches. * * @param searchStrings the strings to search for * @param text the text to search * @return the index in <code>searchStrings</code> of the longest string with which <code>text</code> starts or <code>-1</code> */ public static int startsWith(String[] searchStrings, String text) { int index= -1; for (int i= 0; i < searchStrings.length; i++) { if (text.startsWith(searchStrings[i])) { if (index == -1 || searchStrings[i].length() > searchStrings[index].length()) index= i; } } return index; } /** * Returns the index of the first compare string that equals the given text or <code>-1</code> * if none is equal. * * @param compareStrings the strings to compare with * @param text the text to check * @return the index of the first equal compare string or <code>-1</code> */ public static int equals(String[] compareStrings, String text) { for (int i= 0; i < compareStrings.length; i++) { if (text.equals(compareStrings[i])) return i; } return -1; } /** * Returns a document event which is an accumulation of a list of document events, * <code>null</code> if the list of documentEvents is empty. * The document of the document events are ignored. * * @param unprocessedDocument the document to which the document events would be applied * @param documentEvents the list of document events to merge * @return returns the merged document event * @throws BadLocationException might be thrown if document is not in the correct state with respect to document events */ public static DocumentEvent mergeUnprocessedDocumentEvents(IDocument unprocessedDocument, List documentEvents) throws BadLocationException { if (documentEvents.size() == 0) return null; final Iterator iterator= documentEvents.iterator(); final DocumentEvent firstEvent= (DocumentEvent) iterator.next(); // current merged event final IDocument document= unprocessedDocument; int offset= firstEvent.getOffset(); int length= firstEvent.getLength(); final StringBuffer text= new StringBuffer(firstEvent.getText() == null ? "" : firstEvent.getText()); //$NON-NLS-1$ while (iterator.hasNext()) { final int delta= text.length() - length; final DocumentEvent event= (DocumentEvent) iterator.next(); final int eventOffset= event.getOffset(); final int eventLength= event.getLength(); final String eventText= event.getText() == null ? "" : event.getText(); //$NON-NLS-1$ // event is right from merged event if (eventOffset > offset + length + delta) { final String string= document.get(offset + length, (eventOffset - delta) - (offset + length)); text.append(string); text.append(eventText); length= (eventOffset - delta) + eventLength - offset; // event is left from merged event } else if (eventOffset + eventLength < offset) { final String string= document.get(eventOffset + eventLength, offset - (eventOffset + eventLength)); text.insert(0, string); text.insert(0, eventText); length= offset + length - eventOffset; offset= eventOffset; // events overlap each other } else { final int start= Math.max(0, eventOffset - offset); final int end= Math.min(text.length(), eventLength + eventOffset - offset); text.replace(start, end, eventText); offset= Math.min(offset, eventOffset); final int totalDelta= delta + eventText.length() - eventLength; length= text.length() - totalDelta; } } return new DocumentEvent(document, offset, length, text.toString()); } /** * Returns a document event which is an accumulation of a list of document events, * <code>null</code> if the list of document events is empty. * The document events being merged must all refer to the same document, to which * the document changes have been already applied. * * @param documentEvents the list of document events to merge * @return returns the merged document event * @throws BadLocationException might be thrown if document is not in the correct state with respect to document events */ public static DocumentEvent mergeProcessedDocumentEvents(List documentEvents) throws BadLocationException { if (documentEvents.size() == 0) return null; final ListIterator iterator= documentEvents.listIterator(documentEvents.size()); final DocumentEvent firstEvent= (DocumentEvent) iterator.previous(); // current merged event final IDocument document= firstEvent.getDocument(); int offset= firstEvent.getOffset(); int length= firstEvent.getLength(); int textLength= firstEvent.getText() == null ? 0 : firstEvent.getText().length(); while (iterator.hasPrevious()) { final int delta= length - textLength; final DocumentEvent event= (DocumentEvent) iterator.previous(); final int eventOffset= event.getOffset(); final int eventLength= event.getLength(); final int eventTextLength= event.getText() == null ? 0 : event.getText().length(); // event is right from merged event if (eventOffset > offset + textLength + delta) { length= (eventOffset - delta) - (offset + textLength) + length + eventLength; textLength= (eventOffset - delta) + eventTextLength - offset; // event is left from merged event } else if (eventOffset + eventTextLength < offset) { length= offset - (eventOffset + eventTextLength) + length + eventLength; textLength= offset + textLength - eventOffset; offset= eventOffset; // events overlap each other } else { final int start= Math.max(0, eventOffset - offset); final int end= Math.min(length, eventTextLength + eventOffset - offset); length += eventLength - (end - start); offset= Math.min(offset, eventOffset); final int totalDelta= delta + eventLength - eventTextLength; textLength= length - totalDelta; } } final String text= document.get(offset, textLength); return new DocumentEvent(document, offset, length, text); } /** * Removes all connected document partitioners from the given document and stores them * under their partitioning name in a map. This map is returned. After this method has been called * the given document is no longer connected to any document partitioner. * * @param document the document * @return the map containing the removed partitioners */ public static Map removeDocumentPartitioners(IDocument document) { Map partitioners= new HashMap(); if (document instanceof IDocumentExtension3) { IDocumentExtension3 extension3= (IDocumentExtension3) document; String[] partitionings= extension3.getPartitionings(); for (int i= 0; i < partitionings.length; i++) { IDocumentPartitioner partitioner= extension3.getDocumentPartitioner(partitionings[i]); if (partitioner != null) { extension3.setDocumentPartitioner(partitionings[i], null); partitioner.disconnect(); partitioners.put(partitionings[i], partitioner); } } } else { IDocumentPartitioner partitioner= document.getDocumentPartitioner(); if (partitioner != null) { document.setDocumentPartitioner(null); partitioner.disconnect(); partitioners.put(IDocumentExtension3.DEFAULT_PARTITIONING, partitioner); } } return partitioners; } /** * Connects the given document with all document partitioners stored in the given map under * their partitioning name. This method cleans the given map. * * @param document the document * @param partitioners the map containing the partitioners to be connected * @since 3.0 */ public static void addDocumentPartitioners(IDocument document, Map partitioners) { if (document instanceof IDocumentExtension3) { IDocumentExtension3 extension3= (IDocumentExtension3) document; Iterator e= partitioners.keySet().iterator(); while (e.hasNext()) { String partitioning= (String) e.next(); IDocumentPartitioner partitioner= (IDocumentPartitioner) partitioners.get(partitioning); partitioner.connect(document); extension3.setDocumentPartitioner(partitioning, partitioner); } partitioners.clear(); } else { IDocumentPartitioner partitioner= (IDocumentPartitioner) partitioners.get(IDocumentExtension3.DEFAULT_PARTITIONING); partitioner.connect(document); document.setDocumentPartitioner(partitioner); } } /** * Returns the content type at the given offset of the given document. * * @param document the document * @param partitioning the partitioning to be used * @param offset the offset * @param preferOpenPartitions <code>true</code> if precedence should be * given to a open partition ending at <code>offset</code> over a * closed partition starting at <code>offset</code> * @return the content type at the given offset of the document * @throws BadLocationException if offset is invalid in the document * @since 3.0 */ public static String getContentType(IDocument document, String partitioning, int offset, boolean preferOpenPartitions) throws BadLocationException { if (document instanceof IDocumentExtension3) { IDocumentExtension3 extension3= (IDocumentExtension3) document; try { return extension3.getContentType(partitioning, offset, preferOpenPartitions); } catch (BadPartitioningException x) { return IDocument.DEFAULT_CONTENT_TYPE; } } return document.getContentType(offset); } /** * Returns the partition of the given offset of the given document. * * @param document the document * @param partitioning the partitioning to be used * @param offset the offset * @param preferOpenPartitions <code>true</code> if precedence should be * given to a open partition ending at <code>offset</code> over a * closed partition starting at <code>offset</code> * @return the content type at the given offset of this viewer's input * document * @throws BadLocationException if offset is invalid in the given document * @since 3.0 */ public static ITypedRegion getPartition(IDocument document, String partitioning, int offset, boolean preferOpenPartitions) throws BadLocationException { if (document instanceof IDocumentExtension3) { IDocumentExtension3 extension3= (IDocumentExtension3) document; try { return extension3.getPartition(partitioning, offset, preferOpenPartitions); } catch (BadPartitioningException x) { return new TypedRegion(0, document.getLength(), IDocument.DEFAULT_CONTENT_TYPE); } } return document.getPartition(offset); } /** * Computes and returns the partitioning for the given region of the given * document for the given partitioning name. * * @param document the document * @param partitioning the partitioning name * @param offset the region offset * @param length the region length * @param includeZeroLengthPartitions whether to include zero-length partitions * @return the partitioning for the given region of the given document for * the given partitioning name * @throws BadLocationException if the given region is invalid for the given * document * @since 3.0 */ public static ITypedRegion[] computePartitioning(IDocument document, String partitioning, int offset, int length, boolean includeZeroLengthPartitions) throws BadLocationException { if (document instanceof IDocumentExtension3) { IDocumentExtension3 extension3= (IDocumentExtension3) document; try { return extension3.computePartitioning(partitioning, offset, length, includeZeroLengthPartitions); } catch (BadPartitioningException x) { return new ITypedRegion[0]; } } return document.computePartitioning(offset, length); } /** * Computes and returns the partition managing position categories for the * given document or <code>null</code> if this was impossible. * * @param document the document * @return the partition managing position categories or <code>null</code> * @since 3.0 */ public static String[] computePartitionManagingCategories(IDocument document) { if (document instanceof IDocumentExtension3) { IDocumentExtension3 extension3= (IDocumentExtension3) document; String[] partitionings= extension3.getPartitionings(); if (partitionings != null) { Set categories= new HashSet(); for (int i= 0; i < partitionings.length; i++) { IDocumentPartitioner p= extension3.getDocumentPartitioner(partitionings[i]); if (p instanceof IDocumentPartitionerExtension2) { IDocumentPartitionerExtension2 extension2= (IDocumentPartitionerExtension2) p; String[] c= extension2.getManagingPositionCategories(); if (c != null) { for (int j= 0; j < c.length; j++) categories.add(c[j]); } } } String[] result= new String[categories.size()]; categories.toArray(result); return result; } } return null; } /** * Returns the default line delimiter for the given document. This is either the delimiter of the first line, or the platform line delimiter if it is * a legal line delimiter or the first one of the legal line delimiters. The default line delimiter should be used when performing document * manipulations that span multiple lines. * * @param document the document * @return the document's default line delimiter * @since 3.0 */ public static String getDefaultLineDelimiter(IDocument document) { if (document instanceof IDocumentExtension4) return ((IDocumentExtension4)document).getDefaultLineDelimiter(); String lineDelimiter= null; try { lineDelimiter= document.getLineDelimiter(0); } catch (BadLocationException x) { } if (lineDelimiter != null) return lineDelimiter; String sysLineDelimiter= System.getProperty("line.separator"); //$NON-NLS-1$ String[] delimiters= document.getLegalLineDelimiters(); Assert.isTrue(delimiters.length > 0); for (int i= 0; i < delimiters.length; i++) { if (delimiters[i].equals(sysLineDelimiter)) { lineDelimiter= sysLineDelimiter; break; } } if (lineDelimiter == null) lineDelimiter= delimiters[0]; return lineDelimiter; } /** * Returns <code>true</code> if the two regions overlap. Returns <code>false</code> if one of the * arguments is <code>null</code>. * * @param left the left region * @param right the right region * @return <code>true</code> if the two regions overlap, <code>false</code> otherwise * @since 3.0 */ public static boolean overlaps(IRegion left, IRegion right) { if (left == null || right == null) return false; int rightEnd= right.getOffset() + right.getLength(); int leftEnd= left.getOffset()+ left.getLength(); if (right.getLength() > 0) { if (left.getLength() > 0) return left.getOffset() < rightEnd && right.getOffset() < leftEnd; return right.getOffset() <= left.getOffset() && left.getOffset() < rightEnd; } if (left.getLength() > 0) return left.getOffset() <= right.getOffset() && right.getOffset() < leftEnd; return left.getOffset() == right.getOffset(); } /** * Returns a copy of the given string array. * * @param array the string array to be copied * @return a copy of the given string array or <code>null</code> when <code>array</code> is <code>null</code> * @since 3.1 */ public static String[] copy(String[] array) { if (array != null) { String[] copy= new String[array.length]; System.arraycopy(array, 0, copy, 0, array.length); return copy; } return null; } /** * Returns a copy of the given integer array. * * @param array the integer array to be copied * @return a copy of the given integer array or <code>null</code> when <code>array</code> is <code>null</code> * @since 3.1 */ public static int[] copy(int[] array) { if (array != null) { int[] copy= new int[array.length]; System.arraycopy(array, 0, copy, 0, array.length); return copy; } return null; } }
false
false
null
null
diff --git a/datatables-core/src/main/java/com/github/dandelion/datatables/core/feature/AjaxFeature.java b/datatables-core/src/main/java/com/github/dandelion/datatables/core/feature/AjaxFeature.java index 7704e0f0..8027b227 100644 --- a/datatables-core/src/main/java/com/github/dandelion/datatables/core/feature/AjaxFeature.java +++ b/datatables-core/src/main/java/com/github/dandelion/datatables/core/feature/AjaxFeature.java @@ -1,63 +1,69 @@ /* * [The "BSD licence"] * Copyright (c) 2012 Dandelion * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Dandelion nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.github.dandelion.datatables.core.feature; import com.github.dandelion.datatables.core.asset.Configuration; -import com.github.dandelion.datatables.core.asset.JavascriptSnippet; +import com.github.dandelion.datatables.core.asset.Configuration.Mode; +import com.github.dandelion.datatables.core.asset.JavascriptFunction; +import com.github.dandelion.datatables.core.callback.CallbackType; import com.github.dandelion.datatables.core.constants.DTConstants; import com.github.dandelion.datatables.core.exception.BadConfigurationException; import com.github.dandelion.datatables.core.html.HtmlTable; /** - * TODO + * Feature automatically added to the table when using AJAX sources. * * @author Thibault Duchateau * @since 0.8.2 */ public class AjaxFeature extends AbstractFeature { @Override public String getName() { return null; } @Override public String getVersion() { return null; } @Override public void setup(HtmlTable table) throws BadConfigurationException { addConfiguration(new Configuration(DTConstants.DT_B_DEFER_RENDER, true)); addConfiguration(new Configuration(DTConstants.DT_S_AJAXDATAPROP, "")); addConfiguration(new Configuration(DTConstants.DT_S_AJAX_SOURCE, table.getDatasourceUrl())); - addConfiguration(new Configuration("fnInitComplete", new JavascriptSnippet("function() { oTable_" + table.getId() + ".fnAdjustColumnSizing(true);}"))); + addConfiguration( + new Configuration( + CallbackType.INIT.getName(), + new JavascriptFunction("oTable_" + table.getId() + ".fnAdjustColumnSizing(true);",CallbackType.INIT.getArgs()), + Mode.APPEND)); } } \ No newline at end of file diff --git a/datatables-core/src/main/java/com/github/dandelion/datatables/core/feature/ServerSideFeature.java b/datatables-core/src/main/java/com/github/dandelion/datatables/core/feature/ServerSideFeature.java index 3231559e..39c13018 100644 --- a/datatables-core/src/main/java/com/github/dandelion/datatables/core/feature/ServerSideFeature.java +++ b/datatables-core/src/main/java/com/github/dandelion/datatables/core/feature/ServerSideFeature.java @@ -1,66 +1,70 @@ /* * [The "BSD licence"] * Copyright (c) 2012 Dandelion * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Dandelion nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.github.dandelion.datatables.core.feature; import com.github.dandelion.datatables.core.asset.Configuration; -import com.github.dandelion.datatables.core.asset.JavascriptSnippet; -import com.github.dandelion.datatables.core.constants.DTConstants; +import com.github.dandelion.datatables.core.asset.Configuration.Mode; +import com.github.dandelion.datatables.core.asset.JavascriptFunction; +import com.github.dandelion.datatables.core.callback.CallbackType; import com.github.dandelion.datatables.core.exception.BadConfigurationException; import com.github.dandelion.datatables.core.html.HtmlTable; /** * <p> * Feature that is always enabled when server-side processing has been * activated. * <p> * Removing the fnAddjustColumnSizing will cause strange column's width at each * interaction with the table (paging, sorting, filtering ...) * * @author Thibault Duchateau * @since 0.8.2 */ public class ServerSideFeature extends AbstractFeature { @Override public String getName() { return null; } @Override public String getVersion() { return null; } @Override public void setup(HtmlTable table) throws BadConfigurationException { - addConfiguration(new Configuration(DTConstants.DT_FN_INIT_COMPLETE, new JavascriptSnippet( - "function() { oTable_" + table.getId() + ".fnAdjustColumnSizing(true);}"))); + addConfiguration( + new Configuration( + CallbackType.INIT.getName(), + new JavascriptFunction("oTable_" + table.getId() + ".fnAdjustColumnSizing(true);",CallbackType.INIT.getArgs()), + Mode.APPEND)); } } \ No newline at end of file
false
false
null
null
diff --git a/sitebricks-mail/src/test/java/com/google/sitebricks/mail/MailClientIntegrationTest.java b/sitebricks-mail/src/test/java/com/google/sitebricks/mail/MailClientIntegrationTest.java index 15f69d6..377f73b 100644 --- a/sitebricks-mail/src/test/java/com/google/sitebricks/mail/MailClientIntegrationTest.java +++ b/sitebricks-mail/src/test/java/com/google/sitebricks/mail/MailClientIntegrationTest.java @@ -1,154 +1,155 @@ package com.google.sitebricks.mail; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.ListenableFuture; import com.google.inject.Guice; import com.google.sitebricks.mail.Mail.Auth; import com.google.sitebricks.mail.MailClient.WireError; import com.google.sitebricks.mail.imap.Folder; import com.google.sitebricks.mail.imap.Message; +import java.util.Date; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @author [email protected] (Dhanji R. Prasanna) */ public class MailClientIntegrationTest { static { java.util.logging.ConsoleHandler fh = new java.util.logging.ConsoleHandler(); java.util.logging.Logger.getLogger("").addHandler(fh); java.util.logging.Logger.getLogger("").setLevel(java.util.logging.Level.FINEST); } public static void main(String... args) throws InterruptedException, ExecutionException { Mail mail = Guice.createInjector().getInstance(Mail.class); final String username = System.getProperty("sitebricks-mail.username"); final String password = System.getProperty("sitebricks-mail.password"); Preconditions.checkArgument(username != null && password != null); MailClientHandler.addUserForVerboseLogging(username, true); NettyImapClient.addUserForVerboseOutput(username, true); final MailClient client = mail.clientOf("imap.gmail.com", 993).prepare(Auth.SSL, username, password); try { client.connect(); } catch (Exception e) { e.printStackTrace(); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>"); WireError lastError = client.lastError(); System.out.println(lastError.expected()); System.out.println(lastError.message()); System.out.println(lastError.trace()); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>"); } List<String> capabilities = client.capabilities(); System.out.println("CAPS: " + capabilities); System.out.println("FOLDERS: " + client.listFolders().get()); // try { // Folder f = client.open("Thumping through the brush.", false).get(); // System.out.println("Expected failure attempting to open invalid folder."); // } catch (ExecutionException ee) { // // expected. // } // final ListenableFuture<FolderStatus> fStatus = // client.statusOf("[Gmail]/All Mail"); ListenableFuture<Folder> future = client.open("[Gmail]/All Mail", true); final Folder allMail = future.get(); // final FolderStatus folderStatus = fStatus.get(); // System.out // .println("Folder opened: " + allMail.getName() + " with count " + folderStatus.getMessages()); final ExecutorService executor = Executors.newCachedThreadPool(); future.addListener(new Runnable() { @Override public void run() { final ListenableFuture<List<Integer>> messageStatuses = - client.searchUid(allMail, "is:read"); + client.searchUid(allMail, "is:read", new Date(System.currentTimeMillis() - (500L * 24L * 60L * 60L * 1000L))); try { System.out.println(messageStatuses.get()); // for (MessageStatus messageStatus : messageStatuses.get()) { // System.out.println(messageStatus); // } // fetchUidAndDump(client, allMail, 33285, executor).await(); // fetchUidAndDump(client, allMail, 33288, executor).await(); client.disconnect(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }, executor); } private static CountDownLatch fetchUidAndDump(final MailClient client, Folder allMail, int uid, ExecutorService executor) { final ListenableFuture<Message> msgFuture = client.fetchUid(allMail, uid); final CountDownLatch countDownLatch = new CountDownLatch(1); msgFuture.addListener(new Runnable() { @Override public void run() { try { Message message = msgFuture.get(); // System.out.println(ToStringBuilder.reflectionToString(message)); for (Message.BodyPart bodyPart : message.getBodyParts()) { // System.out.println(ToStringBuilder.reflectionToString(bodyPart)); } System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>"); System.out.println(message.getImapUid()); System.out.println(message.getHeaders().get("Message-ID")); System.out.println(message.getHeaders()); System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>\n\n\n"); // System.out.println("Gmail flags set: " + // client.addFlags(allMail, message.getImapUid(), // ImmutableSet.of(Flag.SEEN)).get()); // System.out // .println("Matched UID: " + (message.getImapUid() == messageStatuses.get() // .iterator() // .next() // .getImapUid())); // System.out.println("Fetched: " + message); dumpBodyParts(message.getBodyParts(), ""); countDownLatch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }, executor); return countDownLatch; } private static void dumpBodyParts(List<Message.BodyPart> parts, String indent) { if (parts != null) { for (Message.BodyPart part : parts) { if (part != null) { System.out.println(indent + "Body part:"); System.out.println(indent + part.getHeaders().entries()); System.out.println(indent + part.getBody()); dumpBodyParts(part.getBodyParts(), indent + ">>>>"); } } } } }
false
false
null
null
diff --git a/src/com/epam/memegen/MemeDao.java b/src/com/epam/memegen/MemeDao.java index 4f95536..dc2b08e 100644 --- a/src/com/epam/memegen/MemeDao.java +++ b/src/com/epam/memegen/MemeDao.java @@ -1,386 +1,387 @@ package com.epam.memegen; import java.io.IOException; import java.io.StringWriter; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.datastore.DatastoreFailureException; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.CompositeFilterOperator; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Query.FilterPredicate; import com.google.appengine.api.datastore.Query.SortDirection; import com.google.appengine.api.memcache.ConsistentErrorHandler; import com.google.appengine.api.memcache.Expiration; import com.google.appengine.api.memcache.InvalidValueException; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheService.IdentifiableValue; import com.google.appengine.api.memcache.MemcacheService.SetPolicy; import com.google.appengine.api.memcache.MemcacheServiceException; import com.google.appengine.api.memcache.MemcacheServiceFactory; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.stream.JsonWriter; import org.apache.commons.lang3.StringEscapeUtils; /** * Memcache contains JSONs for: * <li>Every meme by its long id. * <li>All memes by key "ALL". * <li>Popular memes by key "POPULAR". * <li>Top memes by key "TOP". * <li>Last meme Date by key "LAST_TS". */ public class MemeDao { private static final Logger logger = Logger.getLogger(MemeDao.class.getName()); private static final String KIND = "Meme"; public static final String LAST_TS = "LAST_TS"; public static final String ALL = "ALL"; public static final String POPULAR = "POPULAR"; public static final String TOP = "TOP"; private final Key allKey = KeyFactory.createKey(KIND, "ALL"); private final MemcacheService memcache = MemcacheServiceFactory.getMemcacheService(); private final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); private final Util util = new Util(); private final Expiration expiration = Expiration.byDeltaSeconds(666); // 11 minutes public MemeDao() { memcache.setErrorHandler(new ConsistentErrorHandler() { public void handleServiceError(MemcacheServiceException ex) { logger.log(Level.WARNING, "MemcacheServiceException", ex); } public void handleDeserializationError(InvalidValueException ivx) { throw ivx; } }); } public static String getMemcacheKey(HttpServletRequest req) { String key = req.getRequestURI() + req.getQueryString(); return key; } public String getAllAsJson(HttpServletRequest req, String filter) throws IOException { if (!util.isAuthenticated()) { return "[]"; } String sinceS = req.getParameter("since"); Long since; try { since = sinceS == null ? null : Long.parseLong(sinceS); } catch (NumberFormatException e) { since = null; } String limitS = req.getParameter("top"); Integer limit; try { limit = limitS == null ? null : Integer.parseInt(limitS); } catch (NumberFormatException e) { limit = null; } // Lookup memcache if (since != null) { Long lastTs = (Long) memcache.get(LAST_TS); if (lastTs != null && lastTs <= since) { // User asked for memes younger than the youngest. return "[]"; } } else if (limit == null) { String json = null; if (filter.equals("all")) { json = (String) memcache.get(ALL); } else if (filter.equals("popular")) { json = (String) memcache.get(POPULAR); } else if (filter.equals("top")) { json = (String) memcache.get(TOP); } if (json != null) { return json; } } Date youngest = null; Query q = new Query(KIND, allKey); if (filter.equals("all")) { q.addSort("date", SortDirection.DESCENDING); q.setFilter(FilterOperator.EQUAL.of("deleted", false)); } if (filter.equals("popular")) { q.addSort("date", SortDirection.DESCENDING); q.setFilter(CompositeFilterOperator.and( FilterOperator.EQUAL.of("deleted", false), FilterOperator.EQUAL.of("isPositive", true))); } if (filter.equals("top")) { q.addSort("rating", SortDirection.DESCENDING); q.setFilter(FilterOperator.EQUAL.of("deleted", false)); } if (since != null) { q.setFilter(new FilterPredicate("date", FilterOperator.GREATER_THAN, new Date(since))); } FetchOptions options = FetchOptions.Builder.withPrefetchSize(1000); if (limit != null) { options.limit(limit); } PreparedQuery prepared = datastore.prepare(q); Iterable<Entity> iterable = prepared.asIterable(options); StringWriter out = new StringWriter(); JsonWriter w = new JsonWriter(out); // Remember that embedding json into welcome page needs escaping. w.setIndent(" "); w.beginArray(); for (Entity entity : iterable) { Date date = (Date) entity.getProperty("date"); if (youngest == null || youngest.before(date)) { youngest = date; } toJson(entity, w); } w.endArray(); w.close(); String value = out.toString(); if (limit == null && since == null) { if (filter.equals("all")) { memcache.put(ALL, value, expiration); } else if (filter.equals("popular")) { memcache.put(POPULAR, value, expiration); } else if (filter.equals("top")) { memcache.put(TOP, value, expiration); } } if (youngest != null) { memcache.put(LAST_TS, youngest.getTime(), expiration); } return value; } public String getAsJson(long id) throws IOException { if (!util.isAuthenticated()) { return "{}"; } // Lookup memcache String json = (String) memcache.get(id); if (json != null) { return json; } Key key = KeyFactory.createKey(allKey, KIND, id); Entity entity; try { entity = datastore.get(key); StringWriter out = new StringWriter(1000); JsonWriter w = new JsonWriter(out); w.setIndent(" "); toJson(entity, w); json = out.toString(); } catch (EntityNotFoundException e) { return null; } memcache.put(id, json); return json; } private String toJson(Entity meme) throws IOException { StringWriter sw = new StringWriter(1000); JsonWriter w = new JsonWriter(sw); w.setIndent(" "); toJson(meme, w); return sw.toString(); } private void toJson(Entity meme, JsonWriter w) throws IOException { w.beginObject(); long id = meme.getKey().getId(); w.name("id").value(id); String fileName = (String) meme.getProperty("fileName"); String src = "/image/" + id; if (fileName != null) { fileName = StringEscapeUtils.escapeHtml4(fileName); src = src + "/" + fileName; } BlobKey blobKey = (BlobKey) meme.getProperty("blobKey"); if (blobKey == null) { throw new IllegalStateException(); } String escaped = StringEscapeUtils.escapeHtml4(blobKey.getKeyString()); w.name("blobKey").value(escaped); w.name("src").value("/image/meme" + id + "?blobKey=" + escaped); Date date = (Date) meme.getProperty("date"); if (date != null) w.name("timestamp").value(date.getTime()); String topText = (String) meme.getProperty("topText"); String centerText = (String) meme.getProperty("centerText"); String bottomText = (String) meme.getProperty("bottomText"); if (topText != null) { w.name("top").value(StringEscapeUtils.escapeHtml4(topText)); } if (centerText != null) { w.name("center").value(StringEscapeUtils.escapeHtml4(centerText)); } if (bottomText != null) { w.name("bottom").value(StringEscapeUtils.escapeHtml4(bottomText)); } if (meme.hasProperty("rating")) { - long rating = (Long) meme.getProperty("rating"); + // Dev SDK is buggy, reads Integer as Long. + Number rating = (Number) meme.getProperty("rating"); w.name("rating").value(rating); } w.endObject(); } public String create(JsonElement jsonElement) throws IOException { if (!util.isAuthenticated()) { return "{}"; } String top = null; String center = null; String bottom = null; String blobKey = null; try { JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonElement topJE = jsonObject.get("top"); JsonElement centerJE = jsonObject.get("center"); JsonElement bottomJE = jsonObject.get("bottom"); JsonElement blobKeyJE = jsonObject.get("blobKey"); if (topJE != null && topJE.isJsonPrimitive()) { top = topJE.getAsString(); } if (centerJE != null && centerJE.isJsonPrimitive()) { center = centerJE.getAsString(); } if (bottomJE != null && bottomJE.isJsonPrimitive()) { bottom = bottomJE.getAsString(); } if (blobKeyJE != null && blobKeyJE.isJsonPrimitive()) { blobKey = blobKeyJE.getAsString(); } } catch (JsonParseException e) { throw new IllegalArgumentException(e); } catch (ClassCastException e) { throw new IllegalArgumentException(e); } catch (IllegalStateException e) { throw new IllegalArgumentException(e); } catch (UnsupportedOperationException e) { throw new IOException(e); } if (blobKey == null) { throw new IllegalArgumentException("No 'blobKey' param"); } return create(blobKey, top, center, bottom); } private String create(String blobKey, String top, String center, String bottom) throws IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Entity entity = new Entity(KIND, allKey); entity.setProperty("deleted", false); entity.setProperty("blobKey", new BlobKey(blobKey)); Date justCreatedDate = new Date(); entity.setProperty("date", justCreatedDate); entity.setProperty("rating", 0); entity.setProperty("isPositive", true); if (!Util.isNullOrEmpty(top)) { entity.setProperty("topText", top); } if (!Util.isNullOrEmpty(center)) { entity.setProperty("centerText", center); } if (!Util.isNullOrEmpty(bottom)) { entity.setProperty("bottomText", bottom); } Key key; try { key = datastore.put(entity); } catch (DatastoreFailureException e) { // May be like "the id allocated for a new entity was already in use, please try again". // I think retry once is OK. key = datastore.put(entity); } // Put to memcache. String json = toJson(entity); memcache.put(key.getId(), json); memcache.delete(ALL); memcache.delete(POPULAR); memcache.delete(TOP); // Set LAST_TS, taking care of for race conditions. long timestamp = justCreatedDate.getTime(); boolean result = false; int i = 0; while (!result) { if (i++ > 50) { logger.severe("Infinite loop"); break; } IdentifiableValue ident = memcache.getIdentifiable(LAST_TS); if (ident != null) { Long lastDateInMemcache = (Long) ident.getValue(); if (lastDateInMemcache != null && lastDateInMemcache >= timestamp) { break; } result = memcache.putIfUntouched(LAST_TS, ident, timestamp); } else { result = memcache.put(LAST_TS, timestamp, expiration, SetPolicy.ADD_ONLY_IF_NOT_PRESENT); } } return json; } public void delete(long id) throws EntityNotFoundException, IOException { if (!util.isAuthenticated()) { return; } DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(allKey, KIND, id); Entity entity; entity = datastore.get(key); entity.setProperty("deleted", true); datastore.put(entity); memcache.delete(id); memcache.delete(LAST_TS); memcache.delete(ALL); } }
true
false
null
null
diff --git a/de.peeeq.wurstscript/src/de/peeeq/wurstscript/BackupController.java b/de.peeeq.wurstscript/src/de/peeeq/wurstscript/BackupController.java index e2828055..9ed63976 100644 --- a/de.peeeq.wurstscript/src/de/peeeq/wurstscript/BackupController.java +++ b/de.peeeq.wurstscript/src/de/peeeq/wurstscript/BackupController.java @@ -1,92 +1,90 @@ package de.peeeq.wurstscript; import java.io.File; import java.io.IOException; +import com.google.common.base.Charsets; import com.google.common.io.Files; public class BackupController { File backupFolder; int backupLimit; /** * create a backup of the mapfile */ public void makeBackup(String mapFileName, int limit) throws Error, IOException { File mapFile = new File(mapFileName); if (!mapFile.exists()) { throw new Error("Mapfile " + mapFile + " does not exist."); } backupFolder = new File("./backups/"); backupFolder.mkdirs(); backupLimit = limit; if (backupLimit > 998) { backupLimit = 998; } WLogger.info(mapFileName); String mapName = mapFileName.substring(mapFileName.lastIndexOf("\\")+1,mapFileName.lastIndexOf(".")); WLogger.info(mapName); int count = backupCount(mapName); WLogger.info("Count " + count); if (count > backupLimit ) { deleteOldBackups(mapName); count--; } File backupFile = new File("./backups/" + mapName + "-" + toCorrectString(count+1) + ".w3x"); Files.copy(mapFile, backupFile); } - public String toCorrectString(int i){ + private String toCorrectString(int i){ String val = String.valueOf(i); if ( i < 10 ){ val = "00" + val; }else if ( i < 100 ){ val = "0" + val; } return val; } - public int backupCount(String mapName) throws Error, IOException { + private int backupCount(String mapName) throws Error, IOException { int count = 0; for ( File f : backupFolder.listFiles()) { String name = f.getName(); if (name.lastIndexOf("-") > 0){ if (name.length() > 4 && name.substring(0,name.lastIndexOf("-")).equals(mapName) ) { count++; } } } return count; } - public void deleteOldBackups(String mapName) throws Error, IOException { + private void deleteOldBackups(String mapName) throws Error, IOException { File[] files = new File[backupLimit+1]; for ( File f : backupFolder.listFiles()) { String name = f.getName(); if (name.lastIndexOf("-") > 0){ if (name.length() > 4 && name.substring(0,name.lastIndexOf("-")).equals(mapName) ) { files[Integer.valueOf(name.substring(name.lastIndexOf("-")+1,name.lastIndexOf(".")))-1] = f; } } } files[0].delete(); for ( int i = 1; i <= backupLimit; i++ ) { File f = files[i]; String name = f.getName(); WLogger.info("Current in array: " + name); - name = name.replaceFirst("-"+toCorrectString(i+1)+".", "-"+toCorrectString(i)+"."); + name = name.replaceFirst("-"+toCorrectString(i+1)+"\\.", "-"+toCorrectString(i)+"."); WLogger.info("Current in array replaced: " + name); File backupFile = new File("./backups/" + name ); Files.copy(f, backupFile); f.delete(); } } - - - }
false
false
null
null
diff --git a/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/EmpiricalSubstitutionGenotypeLikelihoods.java b/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/EmpiricalSubstitutionGenotypeLikelihoods.java index 8eaf4e72a..2b681a440 100755 --- a/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/EmpiricalSubstitutionGenotypeLikelihoods.java +++ b/java/src/org/broadinstitute/sting/gatk/walkers/genotyper/EmpiricalSubstitutionGenotypeLikelihoods.java @@ -1,278 +1,279 @@ package org.broadinstitute.sting.gatk.walkers.genotyper; import org.broadinstitute.sting.utils.BaseUtils; import org.broadinstitute.sting.utils.QualityUtils; import static java.lang.Math.log10; import java.util.TreeMap; import java.util.EnumMap; import net.sf.samtools.SAMRecord; import net.sf.samtools.SAMReadGroupRecord; public class EmpiricalSubstitutionGenotypeLikelihoods extends GenotypeLikelihoods { // -------------------------------------------------------------------------------------------------------------- // // Static methods to manipulate machine platforms // // -------------------------------------------------------------------------------------------------------------- public enum SequencerPlatform { SOLEXA, // Solexa / Illumina ROCHE454, // 454 SOLID, // SOLiD UNKNOWN // No idea -- defaulting to 1/3 } private final static String SAM_PLATFORM_TAG = "PL"; private static TreeMap<String, SequencerPlatform> PLFieldToSequencerPlatform = new TreeMap<String, SequencerPlatform>(); private static void bind(String s, SequencerPlatform x) { PLFieldToSequencerPlatform.put(s, x); PLFieldToSequencerPlatform.put(s.toUpperCase(), x); PLFieldToSequencerPlatform.put(s.toLowerCase(), x); } // // Static list of platforms supported by this system. // static { bind("LS454", SequencerPlatform.ROCHE454); bind("454", SequencerPlatform.ROCHE454); bind("ILLUMINA", SequencerPlatform.SOLEXA); bind("solid", SequencerPlatform.SOLID); } public static SequencerPlatform standardizeSequencerPlatform( final String sequencerString ) { - String lcSequencerString = sequencerString.toLowerCase(); + String lcSequencerString = sequencerString == null ? null : sequencerString.toLowerCase(); if ( sequencerString != null && PLFieldToSequencerPlatform.containsKey(lcSequencerString) ) { return PLFieldToSequencerPlatform.get(lcSequencerString); } else { return SequencerPlatform.UNKNOWN; } } private static SAMRecord lastReadForPL = null; private static SequencerPlatform plOfLastRead = null; public static SequencerPlatform getReadSequencerPlatform( SAMRecord read ) { if ( lastReadForPL != read ) { lastReadForPL = read; final String readGroupString = ((String)read.getAttribute("RG")); SAMReadGroupRecord readGroup = readGroupString == null ? null : read.getHeader().getReadGroup(readGroupString); final String platformName = readGroup == null ? null : (String)readGroup.getAttribute(SAM_PLATFORM_TAG); plOfLastRead = standardizeSequencerPlatform(platformName); } return plOfLastRead; } // -------------------------------------------------------------------------------------------------------------- // // Static methods to get at the transition tables themselves // // -------------------------------------------------------------------------------------------------------------- /** * A matrix of value i x j -> log10(p) where * * i - char of the miscalled base (i.e., A) * j - char of the presumed true base (i.e., C) * log10p - empirical probability p that A is actually C * * The table is available for each technology */ private final static EnumMap<SequencerPlatform, double[][]> log10pTrueGivenMiscall = new EnumMap<SequencerPlatform, double[][]>(SequencerPlatform.class); private static void addMisCall(final SequencerPlatform pl, char miscalledBase, char trueBase, double p) { if ( ! log10pTrueGivenMiscall.containsKey(pl) ) log10pTrueGivenMiscall.put(pl, new double[4][4]); double[][] misCallProbs = log10pTrueGivenMiscall.get(pl); int i = BaseUtils.simpleBaseToBaseIndex(miscalledBase); int j = BaseUtils.simpleBaseToBaseIndex(trueBase); misCallProbs[i][j] = log10(p); } private static double getProbMiscallIsBase(SequencerPlatform pl, char miscalledBase, char trueBase) { int i = BaseUtils.simpleBaseToBaseIndex(miscalledBase); int j = BaseUtils.simpleBaseToBaseIndex(trueBase); double logP = log10pTrueGivenMiscall.get(pl)[i][j]; if ( logP == 0.0 ) throw new RuntimeException(String.format("Bad miscall base request miscalled=%c true=%b", miscalledBase, trueBase)); else return logP; } private static void addSolexa() { SequencerPlatform pl = SequencerPlatform.SOLEXA; addMisCall(pl, 'A', 'C', 57.7/100.0); addMisCall(pl, 'A', 'G', 17.1/100.0); addMisCall(pl, 'A', 'T', 25.2/100.0); addMisCall(pl, 'C', 'A', 34.9/100.0); addMisCall(pl, 'C', 'G', 11.3/100.0); addMisCall(pl, 'C', 'T', 53.9/100.0); addMisCall(pl, 'G', 'A', 31.9/100.0); addMisCall(pl, 'G', 'C', 5.1/100.0); addMisCall(pl, 'G', 'T', 63.0/100.0); addMisCall(pl, 'T', 'A', 45.8/100.0); addMisCall(pl, 'T', 'C', 22.1/100.0); addMisCall(pl, 'T', 'G', 32.0/100.0); } private static void addSOLiD() { SequencerPlatform pl = SequencerPlatform.SOLID; addMisCall(pl, 'A', 'C', 18.7/100.0); addMisCall(pl, 'A', 'G', 42.5/100.0); addMisCall(pl, 'A', 'T', 38.7/100.0); addMisCall(pl, 'C', 'A', 27.0/100.0); addMisCall(pl, 'C', 'G', 18.9/100.0); addMisCall(pl, 'C', 'T', 54.1/100.0); addMisCall(pl, 'G', 'A', 61.0/100.0); addMisCall(pl, 'G', 'C', 15.7/100.0); addMisCall(pl, 'G', 'T', 23.2/100.0); addMisCall(pl, 'T', 'A', 40.5/100.0); addMisCall(pl, 'T', 'C', 34.3/100.0); addMisCall(pl, 'T', 'G', 25.2/100.0); } private static void add454() { SequencerPlatform pl = SequencerPlatform.ROCHE454; addMisCall(pl, 'A', 'C', 23.2/100.0); addMisCall(pl, 'A', 'G', 42.6/100.0); addMisCall(pl, 'A', 'T', 34.3/100.0); addMisCall(pl, 'C', 'A', 19.7/100.0); addMisCall(pl, 'C', 'G', 8.4/100.0); addMisCall(pl, 'C', 'T', 71.9/100.0); addMisCall(pl, 'G', 'A', 71.5/100.0); addMisCall(pl, 'G', 'C', 6.6/100.0); addMisCall(pl, 'G', 'T', 21.9/100.0); addMisCall(pl, 'T', 'A', 43.8/100.0); addMisCall(pl, 'T', 'C', 37.8/100.0); addMisCall(pl, 'T', 'G', 18.5/100.0); } private static void addUnknown() { SequencerPlatform pl = SequencerPlatform.UNKNOWN; for ( char b1 : BaseUtils.BASES ) { for ( char b2 : BaseUtils.BASES ) { if ( b1 != b2 ) addMisCall(pl, b1, b2, 1.0/3.0); } } } static { addSolexa(); add454(); addSOLiD(); addUnknown(); } // -------------------------------------------------------------------------------------------------------------- // // The actual objects themselves // // -------------------------------------------------------------------------------------------------------------- private boolean raiseErrorOnUnknownPlatform = true; private SequencerPlatform defaultPlatform = SequencerPlatform.UNKNOWN; // // forwarding constructors -- don't do anything at all // public EmpiricalSubstitutionGenotypeLikelihoods() { super(); } public EmpiricalSubstitutionGenotypeLikelihoods(DiploidGenotypePriors priors) { super(priors); } public EmpiricalSubstitutionGenotypeLikelihoods(DiploidGenotypePriors priors, boolean raiseErrorOnUnknownPlatform) { super(priors); this.raiseErrorOnUnknownPlatform = raiseErrorOnUnknownPlatform; } public EmpiricalSubstitutionGenotypeLikelihoods(DiploidGenotypePriors priors, SequencerPlatform assumeUnknownPlatformsAreThis) { super(priors); if ( assumeUnknownPlatformsAreThis != null ) { raiseErrorOnUnknownPlatform = false; defaultPlatform = assumeUnknownPlatformsAreThis; } } /** * Cloning of the object * @return * @throws CloneNotSupportedException */ protected Object clone() throws CloneNotSupportedException { return super.clone(); } // ----------------------------------------------------------------------------------------------------------------- // // // caching routines // // // ----------------------------------------------------------------------------------------------------------------- static GenotypeLikelihoods[][][][][] EMPIRICAL_CACHE = new GenotypeLikelihoods[EmpiricalSubstitutionGenotypeLikelihoods.SequencerPlatform.values().length][BaseUtils.BASES.length][QualityUtils.MAX_QUAL_SCORE][MAX_PLOIDY][2]; protected GenotypeLikelihoods getSetCache( char observedBase, byte qualityScore, int ploidy, SAMRecord read, int offset, GenotypeLikelihoods val ) { SequencerPlatform pl = getReadSequencerPlatform(read); int a = pl.ordinal(); int i = BaseUtils.simpleBaseToBaseIndex(observedBase); int j = qualityScore; int k = ploidy; int x = strandIndex(! read.getReadNegativeStrandFlag()); if ( val != null ) EMPIRICAL_CACHE[a][i][j][k][x] = val; return EMPIRICAL_CACHE[a][i][j][k][x]; } // ----------------------------------------------------------------------------------------------------------------- // // // calculation of p(B|GT) // // // ----------------------------------------------------------------------------------------------------------------- protected double log10PofTrueBaseGivenMiscall(char observedBase, char chromBase, SAMRecord read, int offset) { boolean fwdStrand = ! read.getReadNegativeStrandFlag(); SequencerPlatform pl = getReadSequencerPlatform(read); if ( pl == SequencerPlatform.UNKNOWN ) { if ( raiseErrorOnUnknownPlatform ) throw new RuntimeException("Unknown Sequencer platform for read " + read.format()); else { pl = defaultPlatform; + //System.out.printf("Using default platform %s", pl); } } //System.out.printf("%s for %s%n", pl, read); double log10p = 0.0; if ( fwdStrand ) { log10p = getProbMiscallIsBase(pl, observedBase, chromBase); } else { log10p = getProbMiscallIsBase(pl, BaseUtils.simpleComplement(observedBase), BaseUtils.simpleComplement(chromBase)); } //System.out.printf("p = %f for %s %c %c fwd=%b %d at %s%n", pow(10,log10p), pl, observedBase, chromBase, fwdStrand, offset, read.getReadName() ); return log10p; } }
false
false
null
null
diff --git a/org.eclipse.jubula.client.ui/src/org/eclipse/jubula/client/ui/widgets/AutConfigComponent.java b/org.eclipse.jubula.client.ui/src/org/eclipse/jubula/client/ui/widgets/AutConfigComponent.java index e1488dfed..d83c36c64 100644 --- a/org.eclipse.jubula.client.ui/src/org/eclipse/jubula/client/ui/widgets/AutConfigComponent.java +++ b/org.eclipse.jubula.client.ui/src/org/eclipse/jubula/client/ui/widgets/AutConfigComponent.java @@ -1,1410 +1,1410 @@ /******************************************************************************* * Copyright (c) 2004, 2010 BREDEX GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * BREDEX GmbH - initial API and implementation and/or initial documentation *******************************************************************************/ package org.eclipse.jubula.client.ui.widgets; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.eclipse.core.databinding.validation.IValidator; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.jface.window.Window; import org.eclipse.jubula.client.core.communication.ConnectionException; import org.eclipse.jubula.client.core.communication.ServerConnection; import org.eclipse.jubula.client.core.events.DataEventDispatcher; import org.eclipse.jubula.client.ui.Plugin; import org.eclipse.jubula.client.ui.businessprocess.ConnectServerBP; import org.eclipse.jubula.client.ui.constants.Constants; import org.eclipse.jubula.client.ui.constants.Layout; import org.eclipse.jubula.client.ui.dialogs.RemoteFileBrowserDialog; import org.eclipse.jubula.client.ui.i18n.Messages; import org.eclipse.jubula.client.ui.provider.ControlDecorator; import org.eclipse.jubula.client.ui.utils.DialogStatusParameter; import org.eclipse.jubula.client.ui.utils.DialogUtils; import org.eclipse.jubula.client.ui.utils.RemoteFileStore; import org.eclipse.jubula.client.ui.utils.ServerManager; import org.eclipse.jubula.client.ui.utils.ServerManager.Server; import org.eclipse.jubula.client.ui.utils.Utils; import org.eclipse.jubula.tools.constants.AutConfigConstants; import org.eclipse.jubula.tools.constants.StringConstants; import org.eclipse.jubula.tools.exception.Assert; import org.eclipse.jubula.tools.i18n.I18n; import org.eclipse.jubula.tools.messagehandling.MessageIDs; import org.eclipse.osgi.util.NLS; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Widget; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PreferencesUtil; /** * @author BREDEX GmbH * @created Sep 12, 2007 * */ public abstract class AutConfigComponent extends ScrolledComposite { /** layout for buttons */ public static final GridData BUTTON_LAYOUT; /** number of columns for layout purposes */ public static final int NUM_COLUMNS = 3; static { BUTTON_LAYOUT = new GridData(); BUTTON_LAYOUT.horizontalAlignment = GridData.FILL; BUTTON_LAYOUT.grabExcessHorizontalSpace = true; } /** * This private inner class contains a new ModifyListener. * * @author BREDEX GmbH * @created 22.11.2006 */ private class WidgetModifyListener implements ModifyListener { /** * {@inheritDoc} */ @SuppressWarnings("synthetic-access") public void modifyText(ModifyEvent e) { Object source = e.getSource(); boolean checked = false; if (source.equals(m_autConfigNameTextField)) { checked = true; } else if (source.equals(m_autIdTextField)) { checked = true; } else if (source.equals(m_autWorkingDirectoryTextField)) { checked = true; } if (checked) { checkAll(); return; } Assert.notReached(Messages.EventActivatedByUnknownWidget + StringConstants.DOT); } } /** * This private inner class contains a new SelectionListener. * * @author BREDEX GmbH * @created 13.07.2005 */ private class WidgetSelectionListener implements SelectionListener { /** * {@inheritDoc} */ @SuppressWarnings("synthetic-access") public void widgetSelected(SelectionEvent e) { Object source = e.getSource(); if (source.equals(m_addServerButton)) { handleAddServerButtonEvent(); return; } else if (source.equals(m_basicModeButton) || source.equals(m_advancedModeButton) || source.equals(m_expertModeButton)) { selectModeButton((Button)source); return; } else if (source.equals(m_autWorkingDirectoryButton)) { if (isRemoteRequest()) { remoteBrowse(true, AutConfigConstants.WORKING_DIR, m_autWorkingDirectoryTextField, Messages.AUTConfigComponentSelectWorkDir); } else { DirectoryDialog directoryDialog = new DirectoryDialog( Plugin.getShell(), SWT.APPLICATION_MODAL | SWT.ON_TOP); handleWorkDirButtonEvent(directoryDialog); } return; } Assert.notReached(Messages.EventActivatedByUnknownWidget + StringConstants.LEFT_PARENTHESES + source + StringConstants.RIGHT_PARENTHESES + StringConstants.DOT); } /** * {@inheritDoc} */ public void widgetDefaultSelected(SelectionEvent e) { // nothing } } /** * Possible modes for the dialog * * @author BREDEX GmbH * @created Sep 10, 2007 */ public static enum Mode { /** basic mode */ BASIC, /** advanced mode */ ADVANCED, /** expert mode */ EXPERT } /** the current mode */ private Mode m_mode; /** mapping from mode buttons to modes */ private Map<Button, Mode> m_buttonToModeMap = new HashMap<Button, Mode>(); /** name of the AUT that will be using this configuration */ private String m_autName; /** if the name of the aut config has been modified from its default */ private boolean m_nameModified; /** The IAUTConfigPO this component displays/edits */ private Map<String, String> m_autConfig; /** list of the stored servers */ private ServerManager m_listOfServers = ServerManager.getInstance(); /** parameter list for callback method of the <code>IDialogStatusListener</code> */ private java.util.List<DialogStatusParameter> m_paramList = new ArrayList<DialogStatusParameter>(); /** the the WidgetSelectionListener */ private WidgetSelectionListener m_selectionListener; /** the WidgetModifyListener */ private WidgetModifyListener m_modifyListener; /** Composite representing the basic area */ private Composite m_basicAreaComposite; /** Composite representing the advanced area */ private Composite m_advancedAreaComposite; /** Composite representing the expert area */ private Composite m_expertAreaComposite; /** Composite representing the monitoring area */ private Composite m_monitoringAreaComposite; /** Composite holding the entire contents of this config component */ private Composite m_contentComposite; /** gui component */ private JBText m_autConfigNameTextField; /** gui component */ private Combo m_serverCombo; /** gui component */ private Button m_addServerButton; /** gui component */ private JBText m_autWorkingDirectoryTextField; /** gui component */ private Button m_autWorkingDirectoryButton; /** gui component */ private JBText m_autIdTextField; /** validator for the AUT ID text field */ private IValidator m_autIdValidator; /** The basic mode button. */ private Button m_basicModeButton; /** The advanced button. */ private Button m_advancedModeButton; /** The expert mode button. */ private Button m_expertModeButton; /** Whether the AUT config component supports multiple modes */ private boolean m_isMultiMode; /** Whether this object has finished initializing */ private boolean m_isinitialized; /** * @param parent {@inheritDoc} * @param style {@inheritDoc} * @param autConfig data to be displayed/edited * @param autName the name of the AUT that will be using this configuration. * @param isMultiMode whether this component supports multiple modes. */ public AutConfigComponent(Composite parent, int style, Map<String, String> autConfig, String autName, boolean isMultiMode) { super(parent, style); m_isinitialized = false; m_autConfig = autConfig; m_autName = autName; m_nameModified = !isDataNew(autConfig) && autConfig.get(AutConfigConstants.CONFIG_NAME).equals( NLS.bind(Messages.AUTConfigComponentDefaultAUTConfigName, new String [] { autName, autConfig.get(AutConfigConstants.SERVER) })); m_isMultiMode = isMultiMode; if (m_isMultiMode) { IPreferenceStore prefStore = PlatformUI.getPreferenceStore(); String prefMode = prefStore.getString(Constants.AUT_CONFIG_DIALOG_MODE); if (prefMode != null && prefMode.length() != 0) { m_mode = Mode.valueOf(prefMode); } else { m_mode = Mode.BASIC; } } createGUI(); populateGUI(autConfig); init(); if (m_isMultiMode) { setCurrentMode(m_mode); getDisplay().asyncExec(new Runnable() { public void run() { // Since we're resizing after everything is initialized, // it's possible that the dialog is already disposed here. if (!isDisposed()) { resize(); getShell().pack(true); } } }); } else { setCompositeVisible(m_basicAreaComposite, true); resize(); } m_isinitialized = true; } /** * transmits that a Java toolkit is to be used * @return true if Java toolkit is used */ protected boolean isJavaAut() { return false; } /** * @return the text field for the AUT working directory */ protected JBText getAutWorkingDirField() { return m_autWorkingDirectoryTextField; } /** * @return the monitoringAreaComposite */ public Composite getMonitoringAreaComposite() { return m_monitoringAreaComposite; } /** * Populates all areas with data from the given map. * * @param data The data to use for population. */ private void populateGUI(Map<String, String> data) { populateBasicArea(data); populateAdvancedArea(data); populateExpertArea(data); populateMonitoringArea(data); } /** * {@inheritDoc} */ public void setVisible(boolean visible) { if (StringConstants.EMPTY.equals(m_autConfigNameTextField.getText())) { m_autConfigNameTextField.setFocus(); m_autConfigNameTextField.setText( NLS.bind(Messages.AUTConfigComponentDefaultAUTConfigName, new String [] { m_autName, m_serverCombo.getText() })); m_autConfigNameTextField.setSelection(0, m_autConfigNameTextField.getText().length()); } } /** * @return the AUT-Config-Map */ private Map<String, String> getAutConfig() { return m_autConfig; } /** initialize the GUI components */ private void createGUI() { m_contentComposite = new Composite(this, SWT.NONE); initGuiLayout(m_contentComposite); createHeader(m_contentComposite); if (m_isMultiMode) { createModeButtons(m_contentComposite); } m_basicAreaComposite = new Composite(m_contentComposite, SWT.NONE); m_advancedAreaComposite = new Composite(m_contentComposite, SWT.NONE); m_expertAreaComposite = new Composite(m_contentComposite, SWT.NONE); m_monitoringAreaComposite = new Composite( m_contentComposite, SWT.NONE); createLayout(m_basicAreaComposite); createLayout(m_advancedAreaComposite); createLayout(m_expertAreaComposite); createLayout(m_monitoringAreaComposite); createBasicArea(m_basicAreaComposite); createAdvancedArea(m_advancedAreaComposite); createExpertArea(m_expertAreaComposite); createMonitoringArea(m_monitoringAreaComposite); setContent(m_contentComposite); } /** * @param areaComposite The composite for which to create and set a layout. */ private void createLayout(Composite areaComposite) { areaComposite.setLayout( Layout.createDefaultGridLayout(NUM_COLUMNS)); GridData gridData = new GridData(GridData.BEGINNING); gridData.horizontalSpan = NUM_COLUMNS; areaComposite.setLayoutData(gridData); } /** * Creates the header area (above the mode buttons). * * @param parent The parent composite */ protected abstract void createHeader(Composite parent); /** * Populates GUI for the advanced configuration section. * * @param data Map representing the data to use for population. */ protected abstract void populateExpertArea(Map<String, String> data); /** * Populates GUI for the advanced configuration section. Subclasses may * override this empty implementation. * * @param data * Map representing the data to use for population. */ protected void populateMonitoringArea(Map<String, String> data) { // by default do nothing } /** * Populates GUI for the advanced configuration section. * * @param data Map representing the data to use for population. */ protected abstract void populateAdvancedArea(Map<String, String> data); /** * Populates GUI for the basic configuration section. * * @param data Map representing the data to use for population. */ protected void populateBasicArea(Map<String, String> data) { fillServerCombo(); if (!isDataNew(data)) { m_serverCombo.select(m_serverCombo.indexOf(StringUtils .defaultString(data.get(AutConfigConstants.SERVER)))); m_autConfigNameTextField.setText(StringUtils.defaultString( data.get(AutConfigConstants.CONFIG_NAME), NLS.bind(Messages.AUTConfigComponentDefaultAUTConfigName, new String [] { m_autName, m_serverCombo.getText() }))); m_autIdTextField.setText(StringUtils.defaultString( data.get(AutConfigConstants.AUT_ID))); m_autWorkingDirectoryTextField.setText(StringUtils .defaultString(data.get(AutConfigConstants.WORKING_DIR))); } else { // set some default values m_serverCombo.select(m_serverCombo.indexOf(StringUtils .defaultString(Constants.LOCALHOST1))); m_autConfigNameTextField.setText( NLS.bind(Messages.AUTConfigComponentDefaultAUTConfigName, new String [] { m_autName, m_serverCombo.getText() })); } } /** * @param data The map to check. * @return <code>true</code> if the given map is newly created and defaults * should be used. Otherwise, <code>false</code>. */ protected boolean isDataNew(Map<String, String> data) { return data == null || data.isEmpty(); } /** * @param basicAreaComposite The composite that represents the basic area. */ protected void createBasicArea(Composite basicAreaComposite) { initGUIConfigAndServer(basicAreaComposite); } /** * Create this dialog's advanced area component. * * @param advancedAreaComposite Composite representing the advanced area. */ protected void createAdvancedArea(Composite advancedAreaComposite) { setCompositeVisible(advancedAreaComposite, false); } /** * Create this dialog's expert area component. * * @param expertAreaComposite Composite representing the expert area. */ protected void createExpertArea(Composite expertAreaComposite) { setCompositeVisible(expertAreaComposite, false); } /** * Create this dialog's monitoring area component * @param monitoringComposite Compostie representing the ccArea * */ protected void createMonitoringArea(Composite monitoringComposite) { setCompositeVisible(monitoringComposite, true); } /** * Inits the AUT-Configuration and Server area. * * @param parent The parent Composite. */ private void initGUIConfigAndServer(Composite parent) { // name property UIComponentHelper.createLabel(parent, "AUTConfigComponent.configName"); //$NON-NLS-1$ m_autConfigNameTextField = UIComponentHelper.createTextField(parent, 2); // server chooser initGuiServerChooser(parent); // AUT ID field ControlDecorator.decorateInfo( UIComponentHelper.createLabel(parent, "AUTConfigComponent.autId"), //$NON-NLS-1$, "AUTConfigComponent.autId.helpText", false); //$NON-NLS-1$ m_autIdTextField = UIComponentHelper.createTextField(parent, 2); UIComponentHelper.createSeparator(parent, NUM_COLUMNS); // AUT directory editor if (!isJavaAut()) { createAutDirectoryEditor(parent); } } /** * Inits the AUT working dir area. * * @param parent The parent Composite. */ protected void createAutDirectoryEditor(Composite parent) { UIComponentHelper.createLabel(parent, "AUTConfigComponent.workDir"); //$NON-NLS-1$ m_autWorkingDirectoryTextField = UIComponentHelper.createTextField( parent, 1); m_autWorkingDirectoryButton = new Button(UIComponentHelper .createLayoutComposite(parent), SWT.PUSH); m_autWorkingDirectoryButton.setText(Messages.AUTConfigComponentBrowse); m_autWorkingDirectoryButton.setLayoutData(BUTTON_LAYOUT); } /** * * @param parent The parent Composite. */ private void initGuiServerChooser(Composite parent) { UIComponentHelper.createLabel(parent, "AUTConfigComponent.server"); //$NON-NLS-1$ m_serverCombo = new Combo(parent, SWT.READ_ONLY); GridData comboGrid = new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1); Layout.addToolTipAndMaxWidth(comboGrid, m_serverCombo); m_serverCombo.setLayoutData(comboGrid); m_addServerButton = new Button(UIComponentHelper .createLayoutComposite(parent), SWT.PUSH); m_addServerButton.setText(Messages.AUTConfigComponentAddServer); m_addServerButton.setLayoutData(BUTTON_LAYOUT); } /** * Sets the current mode for the dialog (ex. basic, advanced, expert). * * @param mode Button representing the mode to activate. */ private void setCurrentMode(Mode mode) { m_basicModeButton.setSelection(false); m_advancedModeButton.setSelection(false); m_expertModeButton.setSelection(false); for (Button key : m_buttonToModeMap.keySet()) { if (m_buttonToModeMap.get(key) == mode) { key.setSelection(true); break; } } IPreferenceStore prefStore = PlatformUI.getPreferenceStore(); if (mode == Mode.BASIC) { prefStore.setValue( Constants.AUT_CONFIG_DIALOG_MODE, Mode.BASIC.name()); setCompositeVisible(m_advancedAreaComposite, false); setCompositeVisible(m_expertAreaComposite, false); setCompositeVisible(m_monitoringAreaComposite, false); } else if (mode == Mode.ADVANCED) { prefStore.setValue( Constants.AUT_CONFIG_DIALOG_MODE, Mode.ADVANCED.name()); setCompositeVisible(m_advancedAreaComposite, true); setCompositeVisible(m_expertAreaComposite, false); setCompositeVisible(m_monitoringAreaComposite, false); } else if (mode == Mode.EXPERT) { prefStore.setValue( Constants.AUT_CONFIG_DIALOG_MODE, Mode.EXPERT.name()); setCompositeVisible(m_advancedAreaComposite, true); setCompositeVisible(m_expertAreaComposite, true); setCompositeVisible(m_monitoringAreaComposite, true); } resize(); getShell().pack(true); } /** * checks if BASIC mode is selected * @return mode == BASIC */ protected boolean isBasicMode() { IPreferenceStore prefStore = PlatformUI.getPreferenceStore(); String mode = prefStore.getString(Constants.AUT_CONFIG_DIALOG_MODE); return mode.equals(Mode.BASIC.name()); } /** * Resizes the content composite based on added/removed components. */ protected void resize() { Point newSize = m_contentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT); m_contentComposite.setSize(newSize); m_contentComposite.layout(); } /** * Sets the visibility of the given composite and adjusts the parent * layout as necessary. Assumes that the composite is part of a grid layout. * * @param composite The composite for which to set the visibility. * @param visible Whether the composite should be made visible or invisible. */ private void setCompositeVisible(Composite composite, boolean visible) { composite.setVisible(visible); ((GridData)composite.getLayoutData()).exclude = !visible; } /** * set the layout for the component * @param comp the composite to set the layout for */ private void initGuiLayout(Composite comp) { GridLayout compositeLayout = new GridLayout(); compositeLayout.numColumns = NUM_COLUMNS; compositeLayout.horizontalSpacing = Layout.SMALL_HORIZONTAL_SPACING; compositeLayout.verticalSpacing = Layout.SMALL_VERTICAL_SPACING; compositeLayout.marginHeight = Layout.SMALL_MARGIN_HEIGHT; compositeLayout.marginWidth = Layout.SMALL_MARGIN_WIDTH; comp.setLayout(compositeLayout); GridData compositeData = new GridData(SWT.FILL, SWT.FILL, true, true); compositeData.grabExcessHorizontalSpace = false; compositeData.grabExcessVerticalSpace = true; comp.setLayoutData(compositeData); } /** * Fills the server combo box. */ private void fillServerCombo() { boolean checkListeners = m_selectionListener != null; if (checkListeners) { deinstallListeners(); } m_serverCombo.removeAll(); String currentlySelectedServer = getConfigValue(AutConfigConstants.SERVER); if (currentlySelectedServer != null && currentlySelectedServer.trim().length() != 0 && !m_listOfServers.getServerNames().contains( currentlySelectedServer)) { String defaultServerInfo = Plugin.getDefault().getPreferenceStore() .getDefaultString(Constants.SERVER_SETTINGS_KEY); String defaultServerPort = defaultServerInfo.substring(defaultServerInfo.indexOf( StringConstants.COLON) + 1); m_listOfServers.addServer( new ServerManager.Server( currentlySelectedServer, Integer.valueOf(defaultServerPort))); Utils.createMessageDialog(MessageIDs.I_SERVER_NAME_ADDED, null, new String [] {Messages.ServerName + StringConstants.COLON + StringConstants.SPACE + currentlySelectedServer + StringConstants.NEWLINE + Messages.ServerPortDefault + defaultServerPort}); } for (String serverName : m_listOfServers.getServerNames()) { m_serverCombo.add(serverName); } if (checkListeners) { installListeners(); } } /** * Inits the buttons that control the mode (basic, advanced, expert). * * @param parent The parent Composite. */ protected void createModeButtons(Composite parent) { Composite modeButtons = UIComponentHelper.createLayoutComposite(parent, 3); GridData modeButtonsData = new GridData(GridData.BEGINNING); modeButtonsData.horizontalSpan = NUM_COLUMNS; modeButtons.setLayoutData(modeButtonsData); m_basicModeButton = new Button(modeButtons, SWT.TOGGLE); m_basicModeButton.setText(Messages.AUTConfigComponentShowBasic); m_basicModeButton.setSelection(true); m_buttonToModeMap.put(m_basicModeButton, Mode.BASIC); m_advancedModeButton = new Button(modeButtons, SWT.TOGGLE); m_advancedModeButton.setText(Messages.AUTConfigComponentShowAdvanced); m_buttonToModeMap.put(m_advancedModeButton, Mode.ADVANCED); m_expertModeButton = new Button(modeButtons, SWT.TOGGLE); m_expertModeButton.setText(Messages.AUTConfigComponentShowExpert); m_buttonToModeMap.put(m_expertModeButton, Mode.EXPERT); } /** * installs all listeners to the gui components. All components visualizing * a property do have some sort of modification listeners which store * edited data in the edited instance. Some gui components have additional * listeners for data validatuion or permission reevaluation. */ protected void installListeners() { WidgetSelectionListener selectionListener = getSelectionListener(); WidgetModifyListener modifyListener = getModifyListener(); if (m_isMultiMode) { m_basicModeButton.addSelectionListener(selectionListener); m_advancedModeButton.addSelectionListener(selectionListener); m_expertModeButton.addSelectionListener(selectionListener); } m_addServerButton.addSelectionListener(selectionListener); m_autConfigNameTextField.addModifyListener(modifyListener); m_autIdTextField.addModifyListener(modifyListener); m_autWorkingDirectoryButton.addSelectionListener(selectionListener); m_autWorkingDirectoryTextField.addModifyListener(modifyListener); } /** * deinstalls all listeners to the gui components. All components visualizing * a property do have some sort of modification listeners which store * edited data in the edited instance. Some gui components have additional * listeners for data validatuion or permission reevaluation. */ protected void deinstallListeners() { WidgetSelectionListener selectionListener = getSelectionListener(); WidgetModifyListener modifyListener = getModifyListener(); if (m_isMultiMode) { m_basicModeButton.removeSelectionListener(selectionListener); m_advancedModeButton.removeSelectionListener(selectionListener); m_expertModeButton.removeSelectionListener(selectionListener); } m_addServerButton.removeSelectionListener(selectionListener); m_autConfigNameTextField.removeModifyListener(modifyListener); m_autIdTextField.removeModifyListener(modifyListener); m_autWorkingDirectoryButton.removeSelectionListener( selectionListener); m_autWorkingDirectoryTextField.removeModifyListener(modifyListener); } /** * Maps the given value to the given key for the AUT Configuration. If * the given key already has a value mapped to it, this value will be * overwritten. * * Updates the enablement of all fields based on the new status of * the AUT Configuration. Subclasses should extend this method to update the * fields that they define. * * @param key The key for the mapping. * @param value The value for the mapping. * @return <code>true</code> if the configuration was changed as a result * of this method call (i.e. if <code>value</code> was <em>not</em> * already mapped to <code>key</code>). Otherwise * <code>false</code>. Note that there is no need to update fields * if the mapping has not changed. */ protected boolean putConfigValue(String key, String value) { String previousValue = StringUtils.defaultString(getAutConfig().put(key, value)); boolean wasEmpty = previousValue.length() == 0; boolean isEmpty = StringUtils.defaultString(value).length() == 0; boolean areBothEmpty = wasEmpty && isEmpty; if (isEmpty) { getAutConfig().remove(key); } return (!m_isinitialized && !areBothEmpty) || !value.equals(previousValue); } /** * * @param key The key being searched for in the AUT Configuration. * @return The value mapped to <code>key</code> in the AUT Configuration. */ protected String getConfigValue(String key) { final String value = getAutConfig().get(key); return value != null ? value : StringConstants.EMPTY; } /** * Overwrites the AUT Configuration with keys and values from the given * map. * * @param newConfig The new configuration data. */ protected void setConfig(Map<String, String> newConfig) { Utils.makeAutConfigCopy(newConfig, getAutConfig()); } /** * Checks whether the currently selected server is localhost. Subclasses * may extend this method to enable/disable browse buttons. * @return <code>true</code>, if the currently selected server is localhost */ protected boolean checkLocalhostServer() { boolean enable = isLocalhost(); m_autWorkingDirectoryButton.setEnabled(enable || isRemoteRequest()); return enable; } /** * @return if the current aut starter is localhost */ private boolean isLocalhost() { boolean enable; try { final String serverComboText = getServerCombo().getText(); final InetAddress localHost = InetAddress.getLocalHost(); final String canonicalHostName = localHost.getCanonicalHostName(); enable = (Constants.LOCALHOST1.equals(serverComboText.toLowerCase()) || Constants.LOCALHOST2.equals(serverComboText) || localHost.getHostName().equals(serverComboText) || localHost.getHostAddress().equals(serverComboText) || (canonicalHostName != null && canonicalHostName.equals(serverComboText))); } catch (UnknownHostException e) { enable = false; } return enable; } /** * Handles the button event. */ public void handleAddServerButtonEvent() { openServerPrefPage(); } /** * The action of the AUT config name field. * @return <code>null</code> if the new value is valid. Otherwise, returns * a status parameter indicating the cause of the problem. */ public DialogStatusParameter modifyAutConfigFieldAction() { m_nameModified = !m_autConfigNameTextField.getText().equals( NLS.bind(Messages.AUTConfigComponentDefaultAUTConfigName, new String [] { m_autName, m_serverCombo.getText() })); DialogStatusParameter error = null; putConfigValue(AutConfigConstants.CONFIG_NAME, m_autConfigNameTextField.getText()); if (!isValid(m_autConfigNameTextField, false)) { if (m_autConfigNameTextField.getText().length() == 0) { error = createErrorStatus( Messages.AUTConfigComponentEmptyAUTConfigName); } else { error = createErrorStatus( Messages.AUTConfigComponentWrongAUTConfigName); } } return error; } /** * The action of the AUT ID field. * @return <code>null</code> if the new value is valid. Otherwise, returns * a status parameter indicating the cause of the problem. */ public DialogStatusParameter modifyAutIdFieldAction() { DialogStatusParameter error = null; String newAutIdValue = m_autIdTextField.getText(); // FIXME zeb This null check is necessary at the moment because the creator // of AutConfigComponents is in the ToolkitSupport project, which // is not aware of model (PO) objects nor of databinding classes // (IValidator). This dependency issue should be resolved, and // the validator should be set in the constructor, rather than // in a separate setter method. if (m_autIdValidator != null) { IStatus validationStatus = m_autIdValidator.validate(newAutIdValue); if (!validationStatus.isOK()) { if (validationStatus.getSeverity() == IStatus.ERROR) { error = createErrorStatus(validationStatus.getMessage()); } else { error = createWarningStatus(validationStatus.getMessage()); } } } putConfigValue(AutConfigConstants.AUT_ID, newAutIdValue); return error; } /** * Opens the server preference page */ protected void openServerPrefPage() { PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn( - null, Constants.JB_PREF_PAGE_AUTAGENT, null, null); + getShell(), Constants.JB_PREF_PAGE_AUTAGENT, null, null); DialogUtils.setWidgetNameForModalDialog(dialog); dialog.open(); m_listOfServers = ServerManager.getInstance(); String oldServer = m_serverCombo.getText(); fillServerCombo(); m_serverCombo.setText(oldServer); } /** * * @return The server selection combo box. */ protected Combo getServerCombo() { return m_serverCombo; } /** * * @return The server list. */ protected ServerManager getServerList() { return m_listOfServers; } /** * @param modifiedWidget The modified widget. * @param emptyAllowed true, if an empty string is allowed as input. * @return True, if the input of the widget is correct.False, otherwise. */ protected boolean isValid(Widget modifiedWidget, boolean emptyAllowed) { if (modifiedWidget instanceof DirectCombo) { DirectCombo combo = (DirectCombo)modifiedWidget; int textLength = combo.getText().length(); String text = combo.getText(); return checkTextInput(emptyAllowed, textLength, text); } if (modifiedWidget instanceof JBText) { JBText textField = (JBText)modifiedWidget; int textLength = textField.getText().length(); String text = textField.getText(); return checkTextInput(emptyAllowed, textLength, text); } return true; } /** * @return true if the aut config is for the currently connected AUT starter */ protected boolean isRemoteRequest() { boolean enable; try { final Server currentServer = ConnectServerBP.getInstance().getCurrentServer(); if (currentServer == null) { return false; } if (isLocalhost()) { return false; } final String serverName = getServerCombo().getText().toLowerCase(); final InetAddress serverAddress = InetAddress.getByName(serverName); final String canonicalServerName = serverAddress.getCanonicalHostName().toLowerCase(); final String currentServerName = currentServer.getName().toLowerCase(); final InetAddress currentServerAddress = InetAddress.getByName(currentServerName); final String canonicalCurrentServerName = currentServerAddress.getCanonicalHostName().toLowerCase(); enable = currentServerName.equals(serverName) || currentServerAddress.equals(serverAddress) || canonicalCurrentServerName.equals(canonicalServerName); } catch (UnknownHostException e) { enable = false; } return enable; } /** * @param emptyAllowed true, if an empty string is allowed as input. * @param textLength the text length * @param text the text input * @return true, if text input is validated successful */ private boolean checkTextInput(boolean emptyAllowed, int textLength, String text) { if ((textLength == 0 && !emptyAllowed) || (text.startsWith(" ") || text.endsWith(" "))) { //$NON-NLS-1$ //$NON-NLS-2$ return false; } return true; } /** * Notifies the DialogStatusListenerManager about the text input state */ private void fireError() { DataEventDispatcher.getInstance().getDialogStatusListenerMgr() .fireNotification(m_paramList); } /** * Notifies the DialogStatusListenerManager about the text input state * @param message The message for the new status. * @return the new status parameter. */ protected DialogStatusParameter createWarningStatus(String message) { DialogStatusParameter param = new DialogStatusParameter(); param.setButtonState(true); param.setStatusType(IMessageProvider.WARNING); param.setMessage(message); return param; } /** * Notifies the DialogStatusListenerManager about the text input state * @param message The message for the new status. * @return the new status parameter. */ protected DialogStatusParameter createErrorStatus(String message) { DialogStatusParameter param = new DialogStatusParameter(); param.setButtonState(false); param.setStatusType(IMessageProvider.ERROR); param.setMessage(message); return param; } /** * Sets no error text / image. * @param noEntries true if there are neither errors nor warnings */ private void setIsValid(boolean noEntries) { if (noEntries) { DialogStatusParameter param = new DialogStatusParameter(); param.setButtonState(true); param.setStatusType(IMessageProvider.NONE); param.setMessage(Messages.ProjectWizardAUTData); m_paramList.clear(); m_paramList.add(param); } DataEventDispatcher.getInstance().getDialogStatusListenerMgr() .fireNotification(m_paramList); } /** * @return <code>true</code> if the Aut Config is newly created and defaults * should be used. Otherwise, <code>false</code>. */ protected boolean isConfigNew() { return m_autConfig == null || m_autConfig.isEmpty(); } /** * Enables the given mode button, deselecting all other mode buttons. * * @param button The mode button to select. */ private void selectModeButton(Button button) { setCurrentMode(m_buttonToModeMap.get(button)); } /** * Inits the state, installs all needed listeners, and performs an initial * check for validity of all fields. */ protected void init() { initState(); installListeners(); checkAll(m_paramList); } /** * Checks validity of all fields. */ public final void checkAll() { checkAll(m_paramList); if (m_paramList.isEmpty()) { setIsValid(true); } else { boolean isValid = true; for (DialogStatusParameter entry : m_paramList) { if (entry.getStatusType() == IMessageProvider.ERROR) { isValid = false; break; } } if (isValid) { setIsValid(false); } else { fireError(); } } m_paramList.clear(); } /** * Checks validity of all fields. Subclasses should extend this method to * validate their added fields. * * @param paramList A list to which status messages (errors) can be added. */ protected void checkAll(java.util.List<DialogStatusParameter> paramList) { addError(paramList, modifyAutConfigFieldAction()); addError(paramList, modifyAutIdFieldAction()); addError(paramList, modifyServerComboAction()); addError(paramList, modifyWorkingDirFieldAction()); } /** * Adds the given error to the list, if the error exists. * * @param paramList The list to which the error will be added. * @param error The error to be added. If this value is <code>null</code>, * the list is not changed. */ protected void addError(List<DialogStatusParameter> paramList, DialogStatusParameter error) { if (error != null) { paramList.add(error); } } /** * * @param error Adds an {@link DialogStatusParameter} to the Error list. */ protected void addError(DialogStatusParameter error) { if (error != null) { m_paramList.add(error); } } /** * Sets initial editable state for components */ protected void initState() { m_autConfigNameTextField.setEnabled(true); m_serverCombo.setEnabled(true); } /** Handles the server-list event. * @return False, if the server name combo box contents an error. */ public DialogStatusParameter modifyServerComboAction() { boolean isValid = false; if (m_serverCombo.getSelectionIndex() != -1) { putConfigValue(AutConfigConstants.SERVER, m_serverCombo.getItem( m_serverCombo.getSelectionIndex())); isValid = true; } if (isValid) { if (!m_nameModified) { boolean checkListeners = m_selectionListener != null; if (checkListeners) { deinstallListeners(); } m_autConfigNameTextField.setText( NLS.bind( Messages.AUTConfigComponentDefaultAUTConfigName, new String [] { m_autName, m_serverCombo.getText() })); if (checkListeners) { installListeners(); } } return null; } return createErrorStatus(Messages.AUTConfigComponentNoServer); } /** * * @return the single instance of the selection listener. */ @SuppressWarnings("synthetic-access") private WidgetSelectionListener getSelectionListener() { if (m_selectionListener == null) { m_selectionListener = new WidgetSelectionListener(); } return m_selectionListener; } /** * * @return the single instance of the modify listener. */ @SuppressWarnings("synthetic-access") private WidgetModifyListener getModifyListener() { if (m_modifyListener == null) { m_modifyListener = new WidgetModifyListener(); } return m_modifyListener; } /** * @return the Text component for the Configuration name. */ protected JBText getAutConfigNameTextField() { return m_autConfigNameTextField; } /** * The action of the working directory field. * @return <code>null</code> if the new value is valid. Otherwise, returns * a status parameter indicating the cause of the problem. */ public DialogStatusParameter modifyWorkingDirFieldAction() { DialogStatusParameter error = null; boolean isEmpty = m_autWorkingDirectoryTextField.getText().length() <= 0; if (isValid(m_autWorkingDirectoryTextField, true) && !isEmpty) { if (checkLocalhostServer()) { File dir = new File(m_autWorkingDirectoryTextField.getText()); if (!dir.isAbsolute()) { // Start from server dir, rather than client dir dir = new File("../server/" + //$NON-NLS-1$ m_autWorkingDirectoryTextField.getText()); } if (!dir.isDirectory()) { try { error = createWarningStatus(NLS.bind( Messages.AUTConfigComponentNoDir, new String [] {dir.getCanonicalPath()})); } catch (IOException e) { error = createWarningStatus(NLS.bind( Messages.AUTConfigComponentFileNotFound, new String [] { m_autWorkingDirectoryTextField.getText()})); } } } } else if (!isEmpty) { error = createErrorStatus(Messages.AUTConfigComponentWrongWorkDir); } putConfigValue(AutConfigConstants.WORKING_DIR, m_autWorkingDirectoryTextField.getText()); return error; } /** * * @return the text field for the Working Directory. */ protected JBText getWorkingDirTextField() { return m_autWorkingDirectoryTextField; } /** * Handles the button event. * @param directoryDialog The directory dialog. */ public void handleWorkDirButtonEvent(DirectoryDialog directoryDialog) { String directory; directoryDialog.setMessage(Messages.AUTConfigComponentSelectWorkDir); File path = new File(m_autWorkingDirectoryTextField.getText()); String filterPath = Utils.getLastDirPath(); if (path.exists()) { try { filterPath = path.getCanonicalPath(); } catch (IOException e) { // Just use the default path which is already set } } directoryDialog.setFilterPath(filterPath); directory = directoryDialog.open(); if (directory != null) { m_autWorkingDirectoryTextField.setText(directory); Utils.storeLastDirPath(directoryDialog.getFilterPath()); putConfigValue(AutConfigConstants.WORKING_DIR, m_autWorkingDirectoryTextField.getText()); } } /** * handle the browse request * @param folderSelection true if only folders can be selected * @param configVarKey key for storing the result * @param textfield control for visualizing the value * @param title window title * @return true if the user selected a new entry and no error occured */ protected boolean remoteBrowse(boolean folderSelection, String configVarKey, JBText textfield, String title) { boolean valueChanged = false; RemoteFileBrowserDialog directoryDialog = new RemoteFileBrowserDialog( this.getShell(), false, folderSelection ? IResource.FOLDER : IResource.FILE); try { String oldPath = getConfigValue(configVarKey); if (oldPath == null || oldPath.length() == 0) { oldPath = "."; //$NON-NLS-1$ } RemoteFileStore baseRemoteFS = new RemoteFileStore( ServerConnection.getInstance().getCommunicator(), ".", //$NON-NLS-1$ folderSelection); StringBuilder modPath = new StringBuilder(oldPath); baseRemoteFS = handleOldPath(baseRemoteFS, modPath); directoryDialog.setInput(baseRemoteFS); directoryDialog.setInitialSelection(new RemoteFileStore( ServerConnection.getInstance().getCommunicator(), oldPath .toString(), folderSelection)); directoryDialog.setFSRoots(baseRemoteFS.getRootFSs()); directoryDialog.setTitle(title); directoryDialog.setMessage( Messages.AUTConfigComponentSelectEntries); if (directoryDialog.open() == Window.OK) { final RemoteFileStore resDir = (RemoteFileStore)directoryDialog .getFirstResult(); if (resDir != null) { final String path = resDir.getPath(); textfield.setText(path); putConfigValue(configVarKey, path); valueChanged = true; } } } catch (ConnectionException e) { //FIXME: tobi NLS not found ErrorDialog.openError(Plugin.getShell(), I18n .getString("AutConfigComponent.ERROR_TITLE"), null, //$NON-NLS-1$ new Status(IStatus.WARNING, Plugin.PLUGIN_ID, I18n .getString("AutConfigComponent.ERROR_COMM"))); //$NON-NLS-1$ } return valueChanged; } /** * check for root entries and modify the necessary values * @param remoteFS original remote FS * @param path original path * @return the original or a new RemoteFileStore if the path begins with * a root fs entry */ private RemoteFileStore handleOldPath(RemoteFileStore remoteFS, StringBuilder path) { for (String root : remoteFS.getRootFSs()) { if (path.toString().startsWith(root)) { path.delete(0, root.length()); return new RemoteFileStore(remoteFS.getCommunicator(), root, remoteFS.fetchInfo().isDirectory()); } } return remoteFS; } /** * @param validator The validator to set. */ // FIXME zeb This method is necessary at the moment because the creator // of AutConfigComponents is in the ToolkitSupport project, which // is not aware of model (PO) objects nor of databinding classes // (IValidator). This dependency issue should be resolved, and // the validator should be set in the constructor, rather than // in a separate setter method. public void setAutIdValidator(IValidator validator) { m_autIdValidator = validator; } }
true
false
null
null
diff --git a/de.jpaw.persistence.dsl/src/de/jpaw/persistence/dsl/scoping/BDDLScopeProvider.java b/de.jpaw.persistence.dsl/src/de/jpaw/persistence/dsl/scoping/BDDLScopeProvider.java index c6088a0a..4a093e49 100644 --- a/de.jpaw.persistence.dsl/src/de/jpaw/persistence/dsl/scoping/BDDLScopeProvider.java +++ b/de.jpaw.persistence.dsl/src/de/jpaw/persistence/dsl/scoping/BDDLScopeProvider.java @@ -1,104 +1,103 @@ /* * Copyright 2012 Michael Bischoff * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.jpaw.persistence.dsl.scoping; import java.util.ArrayList; import java.util.List; import org.eclipse.emf.ecore.EObject; //import org.eclipse.xtext.naming.DefaultDeclarativeQualifiedNameProvider; //import org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider; import org.eclipse.xtext.scoping.impl.ImportNormalizer; import org.eclipse.xtext.scoping.impl.ImportedNamespaceAwareLocalScopeProvider; import de.jpaw.bonaparte.dsl.bonScript.ClassDefinition; import de.jpaw.bonaparte.dsl.bonScript.PackageDefinition; import de.jpaw.bonaparte.dsl.generator.XUtil; import de.jpaw.persistence.dsl.bDDL.CollectionDefinition; import de.jpaw.persistence.dsl.bDDL.EntityDefinition; import de.jpaw.persistence.dsl.bDDL.ForeignKeyDefinition; import de.jpaw.persistence.dsl.bDDL.ListOfColumns; import de.jpaw.persistence.dsl.bDDL.SingleColumn; import de.jpaw.persistence.dsl.generator.YUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class contains custom scoping description. * * see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#scoping * on how and when to use it * */ /* The following code is based on guidelines found on the net, given by Jan Kohnlein (http://www.eclipse.org/forums/index.php/t/359674/) * Quote: "add your imports as an ImportNormalizer. * The method createImportedNamespaceResolver(String, boolean) helps you create such * an object. The XtendImportedNamespaceScopeProvider does something similar." * ... * "Don't forget to bind your subclass of the ImportedNamespaceAwareScopeProviderin the runtime module of your language." * */ public class BDDLScopeProvider extends ImportedNamespaceAwareLocalScopeProvider { // was autogenerated: AbstractDeclarativeScopeProvider { private static Log logger = LogFactory.getLog("BDDLScopeProvider"); // jcl private void recursivelyAddColumnsOfClassAndParents(List<ImportNormalizer> preliminaryResult, ClassDefinition cl, boolean ignoreCase) { while (cl != null) { //System.out.println("DEBUG: POJO is " + cl.getName()); if (cl.eContainer() == null) // occurs if a previously referenced import is deleted... return; PackageDefinition bonScriptPd = (PackageDefinition)cl.eContainer(); // ATTN: the bonScript one! // alternative way to get the namespace could be to run it through a new DefaultDeclarativeQualifiedNameProvider(); String qualifiedImportNamespace = bonScriptPd.getName() + "." + cl.getName() + ".*"; //System.out.println("DEBUG: adding " + qualifiedImportNamespace + " to imports..."); preliminaryResult.add(createImportedNamespaceResolver(qualifiedImportNamespace, ignoreCase)); cl = XUtil.getParent(cl); } } private List<ImportNormalizer> getColumnsSub(EntityDefinition entity, boolean ignoreCase) { List<ImportNormalizer> preliminaryResult = new ArrayList<ImportNormalizer>(50); //ListOfColumns loc = (ListOfColumns)context; //System.out.println("DEBUG: Resolver invoked for ListOfColumns inside " + entity.getName()); recursivelyAddColumnsOfClassAndParents(preliminaryResult, entity.getPojoType(), ignoreCase); // also add the fields of the entity category class (& parents) if (entity.getTableCategory() != null) recursivelyAddColumnsOfClassAndParents(preliminaryResult, entity.getTableCategory().getTrackingColumns(), ignoreCase); // also add the fields in a potential tenant discriminator class if (YUtil.getInheritanceRoot(entity).getTenantClass() != null) recursivelyAddColumnsOfClassAndParents(preliminaryResult, YUtil.getInheritanceRoot(entity).getTenantClass(), ignoreCase); //System.out.println("DEBUG: Resolver found " + preliminaryResult.size() + " entries"); return preliminaryResult; } - @Override protected List<ImportNormalizer> internalGetImportedNamespaceResolvers(EObject context, boolean ignoreCase) { List<ImportNormalizer> preliminaryResult; if ((context instanceof ListOfColumns || context instanceof SingleColumn || context instanceof ForeignKeyDefinition || context instanceof CollectionDefinition) && context.eContainer() != null) { // the only valid reference in a list of columns is a column of the entity referenced. - preliminaryResult = getColumnsSub((EntityDefinition)context.eContainer(), ignoreCase); + preliminaryResult = getColumnsSub(YUtil.getBaseEntity(context.eContainer()), ignoreCase); } else { preliminaryResult = super.internalGetImportedNamespaceResolvers(context, ignoreCase); } return preliminaryResult; } }
false
false
null
null
diff --git a/jtrim-gui/src/main/java/org/jtrim/swing/access/ComponentDecorator.java b/jtrim-gui/src/main/java/org/jtrim/swing/access/ComponentDecorator.java index 37e93151..375f12c8 100644 --- a/jtrim-gui/src/main/java/org/jtrim/swing/access/ComponentDecorator.java +++ b/jtrim-gui/src/main/java/org/jtrim/swing/access/ComponentDecorator.java @@ -1,403 +1,403 @@ package org.jtrim.swing.access; import java.awt.Component; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.TimeUnit; import javax.swing.JLayer; import javax.swing.JPanel; import javax.swing.RootPaneContainer; import org.jtrim.access.AccessChangeAction; import org.jtrim.access.AccessManager; import org.jtrim.access.HierarchicalRight; import org.jtrim.utils.ExceptionHelper; /** * Defines an {@code AccessChangeAction} implementation which decorates a * Swing component if the associated group of right becomes unavailable. The * component is required to be a {@link JLayer JLayer} or top level window * having a {@link JRootPane root pane}. * <P> * The {@code ComponentDecorator} decorates the component using its glass pane. * That is, when the associated group of rights becomes unavailable, it will * replace the glass pane of the components with the one provided to the * {@code ComponentDecorator} at construction time (by a factory class). * <P> * When you expect that usually the group of right is only unavailable for a * very short period of time, it is possible to define a two kinds of * decorations {@code ComponentDecorator}. One to apply immediately after the * group of rights becomes unavailable and one after a specified time elapses * and the group of rights is still unavailable. This is useful to prevent * flickering if the group of rights becomes available within the specified * time (that is, if the glass pane set up immediately does not have a visual * effect). * <P> * Note that if the glass pane which is to be set by the * {@code ComponentDecorator} can have the focus (as defined by the method * {@link Component#isFocusable()}) and the component decorated by the * {@code ComponentDecorator} has the focus (or one of its subcomponents), the * focus will be moved to the newly set glass pane (if possible). * * <h3>Thread safety</h3> * The {@link #onChangeAccess(AccessManager, boolean) onChangeAccess} may only * be called from the AWT event dispatch thread. Therefore, the * {@link AccessManager} governing the rights must be set to use an executor * which submits tasks to the AWT event dispatch thread (or wrap the * {@code ComponentDecorator} in an {@code AccessChangeAction} which makes sure * that the {@code onChangeAccess} method does not get called on an * inappropriate thread). * * <h4>Synchronization transparency</h4> * Methods of this class are not <I>synchronization transparent</I>. * * @see org.jtrim.access.RightGroupHandler * * @author Kelemen Attila */ public final class ComponentDecorator implements AccessChangeAction { private final Decorator decorator; /** * Creates a new {@code ComponentDecorator} decorating a window. The passed * component must inherit from (directly or indirectly) * {@link java.awt.Component Component}. * <P> * Using this constructor, whenever the checked group of rights becomes * unavailable, the glass pane for the specified window will be set to the * {@code JPanel} created by the {@code decorator} without any delay. * * @param window the window to be decorated. This argument cannot be * {@code null} and must subclass {@link java.awt.Component Component}. * @param decorator the {@code DecoratorPanelFactory} which defines the * panel to be used as a glass pane for the window. This argument cannot * be {@code null}. * * @throws ClassCastException if the passed argument is not an instance of * {@link java.awt.Component Component} * @throws NullPointerException if any of the passed argument is * {@code null} */ public ComponentDecorator(RootPaneContainer window, DecoratorPanelFactory decorator) { this(new WindowWrapper(window), new DelayedDecorator(decorator, 0, TimeUnit.MILLISECONDS)); } /** * Creates a new {@code ComponentDecorator} decorating a window. The passed * component must inherit from (directly or indirectly) * {@link java.awt.Component Component}. * * @param window the window to be decorated. This argument cannot be * {@code null} and must subclass {@link java.awt.Component Component}. * @param decorator the {@code DelayedDecorator} which defines the panels * to be used as a glass pane for the window. This argument cannot be * {@code null}. * * @throws ClassCastException if the passed argument is not an instance of * {@link java.awt.Component Component} * @throws NullPointerException if any of the passed argument is * {@code null} */ public ComponentDecorator(RootPaneContainer window, DelayedDecorator decorator) { this(new WindowWrapper(window), decorator); } /** * Creates a new {@code ComponentDecorator} decorating a specific component. * The passed {@link JLayer JLayer} must contain the component to be * decorated. * <P> * Using this constructor, whenever the checked group of rights becomes * unavailable, the glass pane for the specified {@code JLayer} will be * set to the {@code JPanel} created by the {@code decorator} without any * delay. * * @param component the component to be decorated. This argument cannot be * {@code null}. * @param decorator the {@code DecoratorPanelFactory} which defines the * panel to be used as a glass pane for the {@code JLayer} component. This * argument cannot be {@code null}. * * @throws NullPointerException if any of the passed argument is * {@code null} */ public ComponentDecorator(JLayer<?> component, DecoratorPanelFactory decorator) { this(new JLayerWrapper(component), new DelayedDecorator(decorator, 0, TimeUnit.MILLISECONDS)); } /** * Creates a new {@code ComponentDecorator} decorating a specific component. * The passed {@link JLayer JLayer} must contain the component to be * decorated. * * @param component the component to be decorated. This argument cannot be * {@code null}. * @param decorator the {@code DelayedDecorator} which defines the panels * to be used as a glass pane for the {@code JLayer} component. This * argument cannot be {@code null}. * * @throws NullPointerException if any of the passed argument is * {@code null} */ public ComponentDecorator(JLayer<?> component, DelayedDecorator decorator) { this(new JLayerWrapper(component), decorator); } private ComponentDecorator(GlassPaneContainer container, DelayedDecorator decorator) { this.decorator = new Decorator(container, decorator); } /** * Sets or restores the glass pane of the Swing component specified at * construction time as required by the availability of the associated group * of rights. * * @param accessManager the {@code AccessManager} which is passed to the * {@link DecoratorPanelFactory} instances specified at construction time. * This argument cannot be {@code null}. * @param available the {@code boolean} value defining if the glass pane of * the Swing component specified at construction time must be set or * restored */ @Override public void onChangeAccess( AccessManager<?, HierarchicalRight> accessManager, boolean available) { decorator.onChangeAccess(accessManager, available); } private static boolean isFocused(Component component) { if (component == null) { return false; } if (component.isFocusOwner()) { return true; } if (component instanceof JLayer) { if (isFocused(((JLayer<?>)component).getView())) { return true; } } if (component instanceof Container) { Component[] subComponents; synchronized (component.getTreeLock()) { subComponents = ((Container)component).getComponents(); } if (subComponents != null) { for (Component subComponent: subComponents) { if (isFocused(subComponent)) { return true; } } } } return false; } private static class Decorator { private final RestorableGlassPaneContainer component; private final DelayedDecorator decorator; private ComponentState state; private javax.swing.Timer currentDecorateTimer; public Decorator(GlassPaneContainer component, DelayedDecorator decorator) { ExceptionHelper.checkNotNullArgument(decorator, "decorator"); this.component = new RestorableGlassPaneContainer(component); this.decorator = decorator; this.state = ComponentState.NOT_DECORDATED; this.currentDecorateTimer = null; } public void onChangeAccess( AccessManager<?, HierarchicalRight> accessManager, boolean available) { if (available) { stopCurrentDecorating(); } else { if (state == ComponentState.NOT_DECORDATED) { component.saveGlassPane(); int delayMillis = (int)Math.min( decorator.getDecoratorPatience(TimeUnit.MILLISECONDS), (long)Integer.MAX_VALUE); if (delayMillis == 0) { setDecoration(accessManager); } else { startDelayedDecoration(accessManager, delayMillis); } } } } private void setDecoration(AccessManager<?, HierarchicalRight> accessManager) { component.setGlassPane(decorator.getMainDecorator().createPanel( component.getComponent(), accessManager)); state = ComponentState.DECORATED; } private void startDelayedDecoration( final AccessManager<?, HierarchicalRight> accessManager, int delayMillis) { component.setGlassPane(decorator.getImmediateDecorator().createPanel( component.getComponent(), accessManager)); state = ComponentState.WAIT_DECORATED; javax.swing.Timer timer = new javax.swing.Timer(delayMillis, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (currentDecorateTimer != e.getSource()) { return; } currentDecorateTimer = null; if (state == ComponentState.WAIT_DECORATED) { setDecoration(accessManager); } } }); currentDecorateTimer = timer; timer.setRepeats(false); timer.start(); } private void stopCurrentDecorating() { if (currentDecorateTimer != null) { currentDecorateTimer.stop(); currentDecorateTimer = null; - removeDecoration(); } + removeDecoration(); } private void removeDecoration() { component.restoreGlassPane(); state = ComponentState.NOT_DECORDATED; } } private enum ComponentState { NOT_DECORDATED, WAIT_DECORATED, DECORATED } private static class RestorableGlassPaneContainer implements GlassPaneContainer { private final GlassPaneContainer wrapped; private boolean hasSavedGlassPane; private Component savedGlassPane; private boolean savedGlassPaneVisible; public RestorableGlassPaneContainer(GlassPaneContainer wrapped) { this.wrapped = wrapped; this.hasSavedGlassPane = false; this.savedGlassPane = null; this.savedGlassPaneVisible = false; } @Override public Component getGlassPane() { return wrapped.getGlassPane(); } public void saveGlassPane() { savedGlassPane = wrapped.getGlassPane(); savedGlassPaneVisible = savedGlassPane != null ? savedGlassPane.isVisible() : false; hasSavedGlassPane = true; } public void restoreGlassPane() { if (hasSavedGlassPane) { wrapped.setGlassPane(savedGlassPane); if (savedGlassPane != null) { savedGlassPane.setVisible(savedGlassPaneVisible); } savedGlassPane = null; // Allow it to be garbage collected hasSavedGlassPane = false; } } @Override public void setGlassPane(Component glassPane) { wrapped.setGlassPane(glassPane); glassPane.setVisible(true); if (glassPane.isFocusable() && isFocused(wrapped.getComponent())) { glassPane.requestFocusInWindow(); } } @Override public Component getComponent() { return wrapped.getComponent(); } } private interface GlassPaneContainer { public Component getGlassPane(); public void setGlassPane(Component glassPane); public Component getComponent(); } private static class JLayerWrapper implements GlassPaneContainer { private final JLayer<?> component; public JLayerWrapper(JLayer<?> component) { ExceptionHelper.checkNotNullArgument(component, "component"); this.component = component; } @Override public void setGlassPane(Component glassPane) { component.setGlassPane((JPanel)glassPane); component.revalidate(); } @Override public Component getGlassPane() { return component.getGlassPane(); } @Override public Component getComponent() { return component; } } private static class WindowWrapper implements GlassPaneContainer { private final RootPaneContainer asContainer; private final Component asComponent; public WindowWrapper(RootPaneContainer window) { ExceptionHelper.checkNotNullArgument(window, "window"); this.asContainer = window; this.asComponent = (Component)window; } @Override public void setGlassPane(Component glassPane) { asContainer.setGlassPane(glassPane); asComponent.revalidate(); } @Override public Component getGlassPane() { return asContainer.getGlassPane(); } @Override public Component getComponent() { return asComponent; } } }
false
false
null
null
diff --git a/src/main/java/org/multibit/viewsystem/swing/view/ticker/TickerTablePanel.java b/src/main/java/org/multibit/viewsystem/swing/view/ticker/TickerTablePanel.java index 8c3d64a4..e7b8a44c 100644 --- a/src/main/java/org/multibit/viewsystem/swing/view/ticker/TickerTablePanel.java +++ b/src/main/java/org/multibit/viewsystem/swing/view/ticker/TickerTablePanel.java @@ -1,376 +1,376 @@ /** * Copyright 2011 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.multibit.viewsystem.swing.view.ticker; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import org.joda.money.BigMoney; import org.multibit.controller.MultiBitController; import org.multibit.viewsystem.View; import org.multibit.viewsystem.swing.ColorAndFontConstants; import org.multibit.viewsystem.swing.MultiBitFrame; import org.multibit.viewsystem.swing.view.panels.HelpContentsPanel; import org.multibit.viewsystem.swing.view.components.FontSizer; import org.multibit.viewsystem.swing.view.components.MultiBitLabel; /** * A panel with a table showing the exchange rate data. * * @author jim * */ public class TickerTablePanel extends JPanel { private static final long serialVersionUID = 1235108820207842662L; private MultiBitController controller; private MultiBitFrame mainFrame; private JTable table; private TickerTableModel tickerTableModel; private JScrollPane scrollPane; private static final String SPACER = " "; // 2 spaces private static final int HORIZONTAL_DELTA = 30; private static final int SCROLLBAR_WIDTH = 20; - private static final int PER_COLUMN_DELTA = 2; + private static final int PER_COLUMN_DELTA = 6; FontMetrics fontMetrics; Font font; private int idealHeight; public TickerTablePanel(MultiBitFrame mainFrame, MultiBitController controller) { this.controller = controller; this.mainFrame = mainFrame; font = FontSizer.INSTANCE.getAdjustedDefaultFontWithDelta(-1); fontMetrics = getFontMetrics(font); initUI(); applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); } private void initUI() { createTicker(); } private void createTicker() { setBackground(ColorAndFontConstants.BACKGROUND_COLOR); setLayout(new GridBagLayout()); setOpaque(true); setFocusable(false); setToolTipText(HelpContentsPanel.createMultilineTooltipText(new String[] { controller.getLocaliser().getString("tickerTablePanel.tooltip"), "\n ", controller.getLocaliser().getString("tickerTablePanel.tooltip.clickToConfigure") })); // on mouse click - view the exchanges tab MouseListener viewPreferencesMouseListener = new MouseAdapter() { @Override public void mouseReleased(MouseEvent arg0) { controller.displayView(View.PREFERENCES_VIEW); } }; String tickerTooltipText = HelpContentsPanel.createMultilineTooltipText(new String[] { controller.getLocaliser().getString("tickerTablePanel.tooltip"), "\n ", controller.getLocaliser().getString("tickerTablePanel.tooltip.clickToConfigure") }); addMouseListener(viewPreferencesMouseListener); GridBagConstraints constraints = new GridBagConstraints(); tickerTableModel = new TickerTableModel(controller); table = new JTable(tickerTableModel); table.setOpaque(true); table.setShowGrid(true); table.setGridColor(Color.lightGray); table.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); table.setComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); table.setRowHeight(getFontMetrics(FontSizer.INSTANCE.getAdjustedDefaultFont()).getHeight()); table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); table.setRowSelectionAllowed(false); table.setColumnSelectionAllowed(false); table.getTableHeader().setReorderingAllowed(false); table.setToolTipText(tickerTooltipText); table.addMouseListener(viewPreferencesMouseListener); table.getTableHeader().addMouseListener(viewPreferencesMouseListener); table.getTableHeader().setToolTipText(tickerTooltipText); table.getTableHeader().setBorder(BorderFactory.createMatteBorder(1, 1, 0, 0, Color.LIGHT_GRAY)); table.getTableHeader().setFont(FontSizer.INSTANCE.getAdjustedDefaultFontWithDelta(-1)); int tableHeaderVerticalInsets = table.getTableHeader().getInsets().top + table.getTableHeader().getInsets().bottom; int tickerWidth = setupColumnWidths(); setupTableHeaders(); idealHeight = (fontMetrics.getHeight() + table.getRowMargin()) * tickerTableModel.getRowCount() + fontMetrics.getHeight() + tableHeaderVerticalInsets + tickerTableModel.getRowCount() + 8; setPreferredSize(new Dimension(tickerWidth, idealHeight)); scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scrollPane.setComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())); scrollPane.setBorder(BorderFactory.createEmptyBorder()); scrollPane.addMouseListener(viewPreferencesMouseListener); setupScrollPane(tickerWidth); constraints.fill = GridBagConstraints.BOTH; constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 1; constraints.weightx = 1; constraints.weighty = 1; constraints.anchor = GridBagConstraints.CENTER; add(scrollPane, constraints); } private int setupColumnWidths() { // Column widths. String[] columnVariables = tickerTableModel.getColumnVariables(); int tickerWidth = HORIZONTAL_DELTA; if (tickerTableModel.getRowCount() > 1) { // There may be a scroll bar so give it some space. tickerWidth += SCROLLBAR_WIDTH; } int numberOfColumns = Math.min(table.getColumnCount(), columnVariables.length); for (int i = 0; i < numberOfColumns; i++) { // work out width int columnWidth; if (TickerTableModel.TICKER_COLUMN_CURRENCY.equals(columnVariables[i])) { columnWidth = PER_COLUMN_DELTA + Math.max(Math.max( fontMetrics.stringWidth(controller.getLocaliser().getString("tickerTableModel." + columnVariables[i])), fontMetrics.stringWidth((String)tickerTableModel.getValueAt(0, i))), fontMetrics.stringWidth((String)tickerTableModel.getValueAt(1, i))); } else if (TickerTableModel.TICKER_COLUMN_EXCHANGE.equals(columnVariables[i])) { columnWidth = PER_COLUMN_DELTA + Math.max(Math.max( fontMetrics.stringWidth(controller.getLocaliser().getString("tickerTableModel." + columnVariables[i])), fontMetrics.stringWidth((String)tickerTableModel.getValueAt(0, i))), fontMetrics.stringWidth((String)tickerTableModel.getValueAt(1, i))); } else { columnWidth = PER_COLUMN_DELTA + Math.max( fontMetrics.stringWidth(controller.getLocaliser().getString("tickerTableModel." + columnVariables[i])), fontMetrics.stringWidth("000000.00000")); } tickerWidth += columnWidth; table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth); } return tickerWidth; } private void setupTableHeaders() { // Column justification. String[] columnVariables = tickerTableModel.getColumnVariables(); int numberOfColumns = Math.min(table.getColumnCount(), columnVariables.length); for (int i = 0; i < numberOfColumns; i++) { TableCellRenderer columnRenderer; if (i == numberOfColumns - 1) { columnRenderer = new CurrencyCenterJustifiedWithRightBorderRenderer(); } else { columnRenderer = new CurrencyCenterJustifiedRenderer(); } table.getColumnModel().getColumn(i).setCellRenderer(columnRenderer); } TableCellRenderer renderer = table.getTableHeader().getDefaultRenderer(); JLabel label = (JLabel) renderer; label.setHorizontalAlignment(JLabel.CENTER); } private void setupScrollPane(int tickerWidth) { scrollPane.getViewport().setPreferredSize( new Dimension(tickerWidth, idealHeight)); scrollPane.setMinimumSize(new Dimension(tickerWidth, Math.min(idealHeight, MultiBitFrame.HEIGHT_OF_HEADER))); scrollPane.setOpaque(false); scrollPane.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); scrollPane.getViewport().setOpaque(false); scrollPane.getViewport().setBackground(ColorAndFontConstants.BACKGROUND_COLOR); } public void update() { int tickerWidth = setupColumnWidths(); setupTableHeaders(); setupScrollPane(tickerWidth); table.invalidate(); table.validate(); table.repaint(); invalidate(); validate(); repaint(); mainFrame.getHeaderPanel().invalidate(); mainFrame.getHeaderPanel().validate(); mainFrame.getHeaderPanel().repaint(); } class TrailingJustifiedRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1549545L; MultiBitLabel label = new MultiBitLabel(""); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { label.setHorizontalAlignment(SwingConstants.TRAILING); label.setOpaque(true); label.setFont(font); String text = ""; if (value != null) { if (value instanceof BigMoney) { //text = ((BigMoney) value).getAmount().toPlainString(); text = controller.getLocaliser().bigMoneyValueToString(((BigMoney) value)); } else { text = value.toString(); } } label.setText(text + SPACER); if (column == 0) { label.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.LIGHT_GRAY)); } Color backgroundColor = (row % 2 == 0 ? ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR : ColorAndFontConstants.BACKGROUND_COLOR); label.setBackground(backgroundColor); label.setForeground(table.getForeground()); return label; } } class LeadingJustifiedRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1549545L; MultiBitLabel label = new MultiBitLabel(""); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { label.setHorizontalAlignment(SwingConstants.LEADING); label.setOpaque(true); label.setFont(font); String text = ""; if (value != null) { if (value instanceof BigMoney) { //text = ((BigMoney) value).getAmount().toPlainString(); text = controller.getLocaliser().bigMoneyValueToString(((BigMoney) value)); } else { text = value.toString(); } } label.setText(SPACER + text); if (column == 0) { label.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.LIGHT_GRAY)); } Color backgroundColor = (row % 2 == 0 ? ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR : ColorAndFontConstants.BACKGROUND_COLOR); label.setBackground(backgroundColor); label.setForeground(table.getForeground()); return label; } } class CurrencyCenterJustifiedRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 1549545L; MultiBitLabel label = new MultiBitLabel(""); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { label.setHorizontalAlignment(SwingConstants.CENTER); label.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); label.setOpaque(true); label.setText((String) value); label.setFont(font); label.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.LIGHT_GRAY)); Color backgroundColor = (row % 2 == 0 ? ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR : ColorAndFontConstants.BACKGROUND_COLOR); label.setBackground(backgroundColor); label.setForeground(table.getForeground()); return label; } } class CurrencyCenterJustifiedWithRightBorderRenderer extends DefaultTableCellRenderer { private static final long serialVersionUID = 9949545L; MultiBitLabel label = new MultiBitLabel(""); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { label.setHorizontalAlignment(SwingConstants.CENTER); label.setBackground(ColorAndFontConstants.BACKGROUND_COLOR); label.setOpaque(true); label.setText((String) value); label.setFont(font); label.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 1, Color.LIGHT_GRAY)); Color backgroundColor = (row % 2 == 0 ? ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR : ColorAndFontConstants.BACKGROUND_COLOR); label.setBackground(backgroundColor); label.setForeground(table.getForeground()); return label; } } } \ No newline at end of file
true
false
null
null
diff --git a/ttools/src/main/uk/ac/starlink/ttools/taplint/JobStage.java b/ttools/src/main/uk/ac/starlink/ttools/taplint/JobStage.java index 1843862e9..514e77c5f 100644 --- a/ttools/src/main/uk/ac/starlink/ttools/taplint/JobStage.java +++ b/ttools/src/main/uk/ac/starlink/ttools/taplint/JobStage.java @@ -1,898 +1,898 @@ package uk.ac.starlink.ttools.taplint; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Pattern; import org.xml.sax.SAXException; import uk.ac.starlink.util.ByteList; import uk.ac.starlink.vo.TableMeta; import uk.ac.starlink.vo.TapQuery; import uk.ac.starlink.vo.UwsJob; import uk.ac.starlink.vo.UwsJobInfo; import uk.ac.starlink.vo.UwsStage; /** * TapLint stage which submits and manipulates UWS jobs, mostly to check * that the UWS operations are performing correctly. * * @author Mark Taylor * @since 24 Jun 2011 */ public class JobStage implements Stage { private final MetadataHolder metaHolder_; private final long pollMillis_; // This expression pinched at random without testing from // "http://www.pelagodesign.com/blog/2009/05/20/" + // "iso-8601-date-validation-that-doesnt-suck/" private final static Pattern ISO8601_REGEX = Pattern.compile( "^([\\+-]?\\d{4}(?!\\d{2}\\b))" + "((-?)((0[1-9]|1[0-2])(\\3([12]\\d|0[1-9]|3[01]))?" + "|W([0-4]\\d|5[0-2])(-?[1-7])?" + "|(00[1-9]|0[1-9]\\d|[12]\\d{2}|3([0-5]\\d|6[1-6])))" + "([T\\s]((([01]\\d|2[0-3])((:?)[0-5]\\d)?|24\\:?00)" + "([\\.,]\\d+(?!:))?)?(\\17[0-5]\\d([\\.,]\\d+)?)?" + "([zZ]|([\\+-])([01]\\d|2[0-3]):?([0-5]\\d)?)?)?)?$" ); /** * Constructor. * * @param metaHolder supplies table metadata at run time so we know * what to query * @param pollMillis number of milliseconds between polling attempts * when waiting for a normal job to complete */ public JobStage( MetadataHolder metaHolder, long pollMillis ) { metaHolder_ = metaHolder; pollMillis_ = pollMillis; } public String getDescription() { return "Test asynchronous UWS/TAP behaviour"; } public void run( Reporter reporter, URL serviceUrl ) { TableMeta[] tmetas = metaHolder_.getTableMetadata(); if ( tmetas == null || tmetas.length == 0 ) { reporter.report( ReportType.FAILURE, "NOTM", "No table metadata available " + "(earlier stages failed/skipped? " + " - will not attempt UWS tests" ); return; } new UwsRunner( reporter, serviceUrl, tmetas[ 0 ], pollMillis_ ).run(); } /** * Class which does the work for this stage. */ private static class UwsRunner implements Runnable { private final Reporter reporter_; private final URL serviceUrl_; private final TableMeta tmeta_; private final long poll_; private final String shortAdql_; private final String runId1_; private final String runId2_; /** * Constructor. * * @param reporter destination for validation messages * @param serviceUrl base URL of TAP service * @param tmeta example table metadata * @param poll number of milliseconds between polls when waiting */ UwsRunner( Reporter reporter, URL serviceUrl, TableMeta tmeta, long poll ) { reporter_ = reporter; serviceUrl_ = serviceUrl; tmeta_ = tmeta; poll_ = poll; shortAdql_ = "SELECT TOP 100 * FROM " + tmeta.getName(); runId1_ = "TAPLINT-001"; runId2_ = "TAPLINT-002"; } /** * Invokes subordinate checking tasks. */ public void run() { checkCreateAbortDelete( shortAdql_ ); checkCreateDelete( shortAdql_ ); checkCreateRun( shortAdql_ ); } /** * Runs sequence which creates, aborts and then deletes a job. * * @param adql adql text for query */ private void checkCreateAbortDelete( String adql ) { UwsJob job = createJob( adql ); if ( job == null ) { return; } URL jobUrl = job.getJobUrl(); checkPhase( job, "PENDING" ); checkParameter( job, "REQUEST", "doQuery", true ); checkParameter( job, "RUNID", runId1_, false ); if ( postParameter( job, "runId", runId2_ ) ) { checkParameter( job, "RUNID", runId2_, false ); } if ( postPhase( job, "ABORT" ) ) { checkPhase( job, "ABORTED" ); } // should check 303 response here really if ( postKeyValue( job, "", "ACTION", "DELETE" ) ) { checkDeleted( job ); } } /** * Runs sequence which creates and then deletes a job. * * @param adql adql text for query */ private void checkCreateDelete( String adql ) { UwsJob job = createJob( adql ); if ( job == null ) { return; } URL jobUrl = job.getJobUrl(); checkPhase( job, "PENDING" ); URLConnection conn; try { conn = jobUrl.openConnection(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "HTOF", "Failed to contact " + jobUrl, e ); return; } if ( ! ( conn instanceof HttpURLConnection ) ) { reporter_.report( ReportType.ERROR, "NOHT", "Job url " + jobUrl + " not HTTP?" ); return; } HttpURLConnection hconn = (HttpURLConnection) conn; int response; try { hconn.setRequestMethod( "DELETE" ); hconn.setInstanceFollowRedirects( false ); hconn.connect(); response = hconn.getResponseCode(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "HTDE", "Failed to perform HTTP DELETE to " + jobUrl, e ); return; } checkDeleted( job ); } /** * Runs sequence which creates and then runs a job. * * @param adql adql text for query */ private void checkCreateRun( String adql ) { UwsJob job = createJob( adql ); if ( job == null ) { return; } URL jobUrl = job.getJobUrl(); checkEndpoints( job ); checkPhase( job, "PENDING" ); if ( ! postPhase( job, "RUN" ) ) { return; } String phase; try { job.readPhase(); phase = job.getLastPhase(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "RDPH", "Can't read phase for job " + jobUrl, e ); return; } if ( ! new HashSet( Arrays.asList( new String[] { "QUEUED", "EXECUTING", "SUSPENDED", "ERROR", "COMPLETED", } ) ).contains( phase ) ) { String msg = new StringBuilder() .append( "Incorrect phase " ) .append( phase ) .append( " for started job " ) .append( jobUrl ) .toString(); reporter_.report( ReportType.ERROR, "BAPH", msg ); } if ( UwsStage.FINISHED == UwsStage.forPhase( phase ) ) { reporter_.report( ReportType.INFO, "JOFI", "Job completed immediately - " + "can't test phase progression" ); delete( job ); return; } waitForFinish( job ); } /** * Checks that a job has a given phase. * * @param job job to check * @param mustPhase asserted phase string */ private void checkPhase( UwsJob job, String mustPhase ) { URL phaseUrl = resourceUrl( job, "/phase" ); String resourcePhase = readTextContent( phaseUrl, true ); UwsJobInfo jobInfo = readJobInfo( job ); String infoPhase = jobInfo == null ? null : jobInfo.getPhase(); String phase = resourcePhase != null ? resourcePhase : infoPhase; if ( phase != null ) { if ( ! mustPhase.equals( phase ) ) { String msg = new StringBuilder() .append( "Phase " ) .append( phase ) .append( " != " ) .append( mustPhase ) .toString(); reporter_.report( ReportType.ERROR, "PHUR", msg ); } } if ( infoPhase != null && resourcePhase != null && ! ( infoPhase.equals( resourcePhase ) ) ) { String msg = new StringBuilder() .append( "Phase mismatch between job info " ) .append( "and /phase URL " ) .append( '(' ) .append( infoPhase ) .append( " != " ) .append( resourcePhase ) .append( ')' ) .toString(); reporter_.report( ReportType.ERROR, "JDPH", msg ); } } /** * Checks that a job parameter has a given value. * * @param job job to check * @param name job parameter name * @param value asserted parameter value * @param mandatory true iff parameter must be supported by TAP * implementation */ private void checkParameter( UwsJob job, final String name, final String mustValue, boolean mandatory ) { UwsJobInfo jobInfo = readJobInfo( job ); if ( jobInfo == null ) { return; } UwsJobInfo.Parameter param = getParamMap( jobInfo ).get( name.toUpperCase() ); String actualValue = param == null ? null : param.getValue(); if ( mustValue == null ) { if ( actualValue == null ) { // ok } else { String msg = new StringBuilder() .append( "Parameter " ) .append( name ) .append( " has value " ) .append( actualValue ) .append( " not blank in job document" ) .toString(); reporter_.report( ReportType.ERROR, "PANZ", msg ); } } else if ( actualValue == null && ! mandatory ) { // ok } else if ( ! mustValue.equals( actualValue ) ) { String msg = new StringBuilder() .append( "Parameter " ) .append( name ) .append( " has value " ) .append( actualValue ) .append( " not " ) .append( mustValue ) .append( " in job document" ) .toString(); reporter_.report( ReportType.ERROR, "PAMM", msg ); } } /** * Perform checks of resource declared types and contents for various * job sub-resources. * * @param job job to check */ private void checkEndpoints( UwsJob job ) { /* Check and read the job document. */ URL jobUrl = job.getJobUrl(); readContent( jobUrl, "text/xml", true ); UwsJobInfo jobInfo; try { jobInfo = job.readJob(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "JDIO", "Error reading job document " + jobUrl, e ); return; } catch ( SAXException e ) { reporter_.report( ReportType.ERROR, "JDSX", "Error parsing job document " + jobUrl, e ); return; } if ( jobInfo == null ) { reporter_.report( ReportType.ERROR, "JDNO", "No job document found " + jobUrl ); return; } /* Check the job ID is consistent between the job URL and * job info content. */ if ( ! jobUrl.toString().endsWith( "/" + jobInfo.getJobId() ) ) { String msg = new StringBuilder() .append( "Job ID mismatch; " ) .append( jobInfo.getJobId() ) .append( " is not final path element of " ) .append( jobUrl ) .toString(); reporter_.report( ReportType.ERROR, "JDID", msg ); } /* Check the type of the quote resource. */ URL quoteUrl = resourceUrl( job, "/quote" ); String quote = readTextContent( quoteUrl, true ); /* Check the type and content of the executionduration, and * whether it matches that in the job document. */ URL durationUrl = resourceUrl( job, "/executionduration" ); String duration = readTextContent( durationUrl, true ); checkInt( durationUrl, duration ); if ( ! equals( duration, jobInfo.getExecutionDuration() ) ) { String msg = new StringBuilder() .append( "Execution duration mismatch between job info " ) .append( "and /executionduration URL " ) .append( '(' ) .append( jobInfo.getExecutionDuration() ) .append( " != " ) .append( duration ) .append( ')' ) .toString(); reporter_.report( ReportType.ERROR, "JDED", msg ); } /* Check the type and content of the destruction time, and * whether it matches that in the job document. */ URL destructUrl = resourceUrl( job, "/destruction" ); String destruct = readTextContent( destructUrl, true ); checkDateTime( destructUrl, destruct ); if ( ! equals( destruct, jobInfo.getDestruction() ) ) { String msg = new StringBuilder() .append( "Destruction time mismatch between job info " ) .append( "and /destruction URL " ) .append( '(' ) .append( jobInfo.getDestruction() ) .append( " != " ) .append( destruct ) .append( ')' ) .toString(); reporter_.report( ReportType.ERROR, "JDDE", msg ); } } /** * Checks that a job has been deleted, and no longer exists. * * @param job job to check */ private void checkDeleted( UwsJob job ) { URL jobUrl = job.getJobUrl(); URLConnection conn; try { conn = jobUrl.openConnection(); conn.connect(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "DEOP", "Can't open connection to " + jobUrl, e ); return; } if ( conn instanceof HttpURLConnection ) { int code; try { code = ((HttpURLConnection) conn).getResponseCode(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "DEHT", "Bad HTTP connection to " + jobUrl, e ); return; } if ( code != 404 ) { String msg = new StringBuilder() .append( "Deleted job " ) .append( "gives HTTP response " ) .append( code ) .append( " not 404" ) .append( " for " ) .append( jobUrl ) .toString(); reporter_.report( ReportType.ERROR, "DENO", msg ); } } else { reporter_.report( ReportType.ERROR, "NOHT", "Job " + jobUrl + " not HTTP?" ); } } /** * Returns the URL of a job subresource, supressing exceptions. * * @param job job object * @param subResource resource subpath, starting "/" * @return resource URL, or null in the unlikely event of failure */ private URL resourceUrl( UwsJob job, String subResource ) { String urlStr = job.getJobUrl() + subResource; try { return new URL( urlStr ); } catch ( MalformedURLException e ) { reporter_.report( ReportType.FAILURE, "MURL", "Bad URL " + urlStr + "??", e ); return null; } } /** * Sets a parameter value for a UWS job. * * @param job UWS job * @param name parameter name * @param value parameter value * @return true iff parameter was set successfully */ private boolean postParameter( UwsJob job, String name, String value ) { return postKeyValue( job, "/parameters", name, value ); } /** * Posts the phase for a UWS job. * * @param job UWS job * @param phase UWS phase string * @return true iff phase was posted successfully */ private boolean postPhase( UwsJob job, String phase ) { return postKeyValue( job, "/phase", "PHASE", phase ); } /** * POSTs a key=value pair to a resource URL relating to a UWS job. * * @param job UWS job * @param subResource relative path of resource within job * (include leading "/") * @param key key string * @param value value string * @return true iff POST completed successfully */ private boolean postKeyValue( UwsJob job, String subResource, String key, String value ) { URL url; try { url = new URL( job.getJobUrl() + subResource ); } catch ( MalformedURLException e ) { throw (AssertionError) new AssertionError().initCause( e ); } Map<String,String> map = new HashMap<String,String>(); map.put( key, value ); int code; String responseMsg; try { HttpURLConnection conn = UwsJob.postUnipartForm( url, map ); code = conn.getResponseCode(); responseMsg = conn.getResponseMessage(); } catch ( IOException e ) { String msg = new StringBuilder() .append( "Failed to POST parameter " ) .append( key ) .append( "=" ) .append( value ) .append( " to " ) .append( url ) .toString(); reporter_.report( ReportType.ERROR, "POER", msg, e ); return false; } if ( code >= 400 ) { String msg = new StringBuilder() .append( "Error response " ) .append( code ) .append( " " ) .append( responseMsg ) .append( " for POST " ) .append( key ) .append( "=" ) .append( value ) .append( " to " ) .append( url ) .toString(); reporter_.report( ReportType.ERROR, "PORE", msg ); return false; } String msg = new StringBuilder() .append( "POSTed " ) .append( key ) .append( "=" ) .append( value ) .append( " to " ) .append( url ) .toString(); reporter_.report( ReportType.INFO, "POPA", msg ); return true; } /** * Deletes a job. * * @param job UWS job */ private void delete( UwsJob job ) { try { job.postDelete(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "DENO", "Failed to delete job " + job.getJobUrl(), e ); return; } checkDeleted( job ); } /** * Waits for a running job to complete. * * @param job UWS job */ private void waitForFinish( UwsJob job ) { URL jobUrl = job.getJobUrl(); while ( UwsStage.forPhase( job.getLastPhase() ) != UwsStage.FINISHED ) { String phase = job.getLastPhase(); UwsStage stage = UwsStage.forPhase( phase ); switch ( stage ) { case UNSTARTED: reporter_.report( ReportType.ERROR, "RUPH", "Incorrect phase " + phase + " for started job " + jobUrl ); return; case ILLEGAL: case UNKNOWN: reporter_.report( ReportType.ERROR, "BAPH", "Bad phase " + phase + " for job " + jobUrl ); return; case RUNNING: try { Thread.sleep( poll_ ); } catch ( InterruptedException e ) { reporter_.report( ReportType.FAILURE, "INTR", "Interrupted??" ); return; } break; case FINISHED: break; default: throw new AssertionError(); } try { job.readPhase(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "RDPH", "Can't read phase for job " + jobUrl ); return; } } } /** * Constructs a name->param map from a UwsJobInfo object. * * @param jobInfo job metadata structure describing a UWS job * @return name->param map */ private Map<String,UwsJobInfo.Parameter> getParamMap( UwsJobInfo jobInfo ) { Map<String,UwsJobInfo.Parameter> paramMap = new LinkedHashMap<String,UwsJobInfo.Parameter>(); if ( jobInfo != null && jobInfo.getParameters() != null ) { UwsJobInfo.Parameter[] params = jobInfo.getParameters(); for ( int ip = 0; ip < params.length; ip++ ) { UwsJobInfo.Parameter param = params[ ip ]; String name = param.getId(); if ( name == null || name.length() == 0 ) { reporter_.report( ReportType.ERROR, "PANO", "Parameter with no name" ); } else { String upName = param.getId().toUpperCase(); if ( paramMap.containsKey( upName ) ) { String msg = new StringBuilder() .append( "Duplicate parameter " ) .append( upName ) .append( " in job parameters list" ) .toString(); reporter_.report( ReportType.ERROR, "PADU", msg ); } else { paramMap.put( upName, param ); } } } } return paramMap; } /** * Reads the metadata object for a job. * * @param job UWS job * @return job info, or null if it couldn't be read */ private UwsJobInfo readJobInfo( UwsJob job ) { try { return job.readJob(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "JBIO", "Error reading job info", e ); return null; } catch ( SAXException e ) { reporter_.report( ReportType.ERROR, "JBSP", "Error parsing job info", e ); return null; } } /** * Creates a UWS job based on a given adql query string. * * @param adql query text * @return new job, or null if there was an error */ private UwsJob createJob( String adql ) { TapQuery tq; Map<String,String> paramMap = new LinkedHashMap<String,String>(); paramMap.put( "RUNID", runId1_ ); try { tq = new TapQuery( serviceUrl_, adql, paramMap, null, 0 ); } catch ( IOException e ) { throw new AssertionError( "no upload!" ); } UwsJob job; try { job = UwsJob.createJob( tq.getServiceUrl() + "/async", tq.getStringParams(), tq.getStreamParams() ); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "QFAA", "Failed to submit TAP query " + shortAdql_, e ); return null; } reporter_.report( ReportType.INFO, "CJOB", "Created new job " + job.getJobUrl() ); return job; } /** * Equality utility for two strings. * * @param s1 string 1, may be null * @param s2 string 2, may be null * @return true iff they are equal */ private boolean equals( String s1, String s2 ) { return s1 == null || s1.trim().length() == 0 ? ( s2 == null || s2.trim().length() == 0 ) : s1.equals( s2 ); } /** * Checks that the content of a given URL is an integer. * * @param url source of text, for reporting * @param txt text content */ private void checkInt( URL url, String txt ) { try { Long.parseLong( txt ); } catch ( NumberFormatException e ) { String msg = new StringBuilder() .append( "Not integer content " ) .append( '"' ) .append( txt ) .append( '"' ) .append( " from " ) .append( url ) .toString(); reporter_.report( ReportType.ERROR, "IFMT", msg ); } } /** * Checks that the content of a given URL is a ISO-8601 date. * * @param url source of text, for reporting * @param txt text content */ private void checkDateTime( URL url, String txt ) { if ( txt != null ) { if ( ! ISO8601_REGEX.matcher( txt ).matches() ) { String msg = new StringBuilder() .append( "Not ISO-8601 content " ) .append( '"' ) .append( txt ) .append( '"' ) .append( " from " ) .append( url ) .toString(); reporter_.report( ReportType.WARNING, "TFMT", msg ); } } } /** * Returns the content of a given URL, checking that it has text/plain * declared MIME type. * * @param url URL to read * @param mustExist true if non-existence should trigger error report * @return content string (assumed UTF-8), or null */ private String readTextContent( URL url, boolean mustExist ) { byte[] buf = readContent( url, "text/plain", mustExist ); try { return buf == null ? null : new String( buf, "UTF-8" ); } catch ( UnsupportedEncodingException e ) { reporter_.report( ReportType.FAILURE, "UTF8", "Unknown encoding UTF-8??", e ); return null; } } /** * Reads the content of a URL and checks that it has a given declared * MIME type. * * @param url URL to read * @param mimeType required declared Content-Type * @param mustExist true if non-existence should trigger error report * @return content bytes, or null */ private byte[] readContent( URL url, String mimeType, boolean mustExist ) { if ( url == null ) { return null; } HttpURLConnection hconn; int responseCode; String responseMsg; try { URLConnection conn = url.openConnection(); conn = TapQuery.followRedirects( conn ); if ( ! ( conn instanceof HttpURLConnection ) ) { reporter_.report( ReportType.WARNING, "HURL", "Redirect to non-HTTP URL? " + conn.getURL() ); return null; } hconn = (HttpURLConnection) conn; hconn.connect(); responseCode = hconn.getResponseCode(); responseMsg = hconn.getResponseMessage(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "EURL", "Error contacting URL " + url ); return null; } if ( responseCode != 200 ) { if ( mustExist ) { String msg = new StringBuilder() .append( "Non-OK response " ) .append( responseCode ) .append( " " ) .append( responseMsg ) .append( " from " ) .append( url ) .toString(); reporter_.report( ReportType.ERROR, "NFND", msg ); } return null; } InputStream in = null; byte[] buf; try { in = new BufferedInputStream( hconn.getInputStream() ); ByteList blist = new ByteList(); for ( int b; ( b = in.read() ) >= 0; ) { blist.add( (byte) b ); } buf = blist.toByteArray(); } catch ( IOException e ) { reporter_.report( ReportType.WARNING, "RDIO", "Error reading resource " + url ); buf = null; } finally { if ( in != null ) { try { in.close(); } catch ( IOException e ) { } } } String ctype = hconn.getContentType(); - if ( ctype == null && ctype.trim().length() == 0 ) { + if ( ctype == null || ctype.trim().length() == 0 ) { reporter_.report( ReportType.WARNING, "NOCT", "No Content-Type header for " + url ); } else if ( ! ctype.startsWith( mimeType ) ) { String msg = new StringBuilder() .append( "Incorrect Content-Type " ) .append( ctype ) .append( " != " ) .append( mimeType ) .append( " for " ) .append( url ) .toString(); reporter_.report( ReportType.ERROR, "GMIM", msg ); return buf; } return buf; } } }
true
true
private byte[] readContent( URL url, String mimeType, boolean mustExist ) { if ( url == null ) { return null; } HttpURLConnection hconn; int responseCode; String responseMsg; try { URLConnection conn = url.openConnection(); conn = TapQuery.followRedirects( conn ); if ( ! ( conn instanceof HttpURLConnection ) ) { reporter_.report( ReportType.WARNING, "HURL", "Redirect to non-HTTP URL? " + conn.getURL() ); return null; } hconn = (HttpURLConnection) conn; hconn.connect(); responseCode = hconn.getResponseCode(); responseMsg = hconn.getResponseMessage(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "EURL", "Error contacting URL " + url ); return null; } if ( responseCode != 200 ) { if ( mustExist ) { String msg = new StringBuilder() .append( "Non-OK response " ) .append( responseCode ) .append( " " ) .append( responseMsg ) .append( " from " ) .append( url ) .toString(); reporter_.report( ReportType.ERROR, "NFND", msg ); } return null; } InputStream in = null; byte[] buf; try { in = new BufferedInputStream( hconn.getInputStream() ); ByteList blist = new ByteList(); for ( int b; ( b = in.read() ) >= 0; ) { blist.add( (byte) b ); } buf = blist.toByteArray(); } catch ( IOException e ) { reporter_.report( ReportType.WARNING, "RDIO", "Error reading resource " + url ); buf = null; } finally { if ( in != null ) { try { in.close(); } catch ( IOException e ) { } } } String ctype = hconn.getContentType(); if ( ctype == null && ctype.trim().length() == 0 ) { reporter_.report( ReportType.WARNING, "NOCT", "No Content-Type header for " + url ); } else if ( ! ctype.startsWith( mimeType ) ) { String msg = new StringBuilder() .append( "Incorrect Content-Type " ) .append( ctype ) .append( " != " ) .append( mimeType ) .append( " for " ) .append( url ) .toString(); reporter_.report( ReportType.ERROR, "GMIM", msg ); return buf; } return buf; }
private byte[] readContent( URL url, String mimeType, boolean mustExist ) { if ( url == null ) { return null; } HttpURLConnection hconn; int responseCode; String responseMsg; try { URLConnection conn = url.openConnection(); conn = TapQuery.followRedirects( conn ); if ( ! ( conn instanceof HttpURLConnection ) ) { reporter_.report( ReportType.WARNING, "HURL", "Redirect to non-HTTP URL? " + conn.getURL() ); return null; } hconn = (HttpURLConnection) conn; hconn.connect(); responseCode = hconn.getResponseCode(); responseMsg = hconn.getResponseMessage(); } catch ( IOException e ) { reporter_.report( ReportType.ERROR, "EURL", "Error contacting URL " + url ); return null; } if ( responseCode != 200 ) { if ( mustExist ) { String msg = new StringBuilder() .append( "Non-OK response " ) .append( responseCode ) .append( " " ) .append( responseMsg ) .append( " from " ) .append( url ) .toString(); reporter_.report( ReportType.ERROR, "NFND", msg ); } return null; } InputStream in = null; byte[] buf; try { in = new BufferedInputStream( hconn.getInputStream() ); ByteList blist = new ByteList(); for ( int b; ( b = in.read() ) >= 0; ) { blist.add( (byte) b ); } buf = blist.toByteArray(); } catch ( IOException e ) { reporter_.report( ReportType.WARNING, "RDIO", "Error reading resource " + url ); buf = null; } finally { if ( in != null ) { try { in.close(); } catch ( IOException e ) { } } } String ctype = hconn.getContentType(); if ( ctype == null || ctype.trim().length() == 0 ) { reporter_.report( ReportType.WARNING, "NOCT", "No Content-Type header for " + url ); } else if ( ! ctype.startsWith( mimeType ) ) { String msg = new StringBuilder() .append( "Incorrect Content-Type " ) .append( ctype ) .append( " != " ) .append( mimeType ) .append( " for " ) .append( url ) .toString(); reporter_.report( ReportType.ERROR, "GMIM", msg ); return buf; } return buf; }
diff --git a/src/com/android/camera/CameraScreenNail.java b/src/com/android/camera/CameraScreenNail.java index 2e820c10..d981af38 100644 --- a/src/com/android/camera/CameraScreenNail.java +++ b/src/com/android/camera/CameraScreenNail.java @@ -1,324 +1,327 @@ /* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.camera; import android.annotation.TargetApi; import android.graphics.SurfaceTexture; import android.util.Log; import com.android.gallery3d.common.ApiHelper; import com.android.gallery3d.ui.GLCanvas; import com.android.gallery3d.ui.RawTexture; import com.android.gallery3d.ui.SurfaceTextureScreenNail; /* * This is a ScreenNail which can display camera's preview. */ @TargetApi(ApiHelper.VERSION_CODES.HONEYCOMB) public class CameraScreenNail extends SurfaceTextureScreenNail { private static final String TAG = "CAM_ScreenNail"; private static final int ANIM_NONE = 0; // Capture animation is about to start. private static final int ANIM_CAPTURE_START = 1; // Capture animation is running. private static final int ANIM_CAPTURE_RUNNING = 2; // Switch camera animation needs to copy texture. private static final int ANIM_SWITCH_COPY_TEXTURE = 3; // Switch camera animation shows the initial feedback by darkening the // preview. private static final int ANIM_SWITCH_DARK_PREVIEW = 4; // Switch camera animation is waiting for the first frame. private static final int ANIM_SWITCH_WAITING_FIRST_FRAME = 5; // Switch camera animation is about to start. private static final int ANIM_SWITCH_START = 6; // Switch camera animation is running. private static final int ANIM_SWITCH_RUNNING = 7; private boolean mVisible; // True if first onFrameAvailable has been called. If screen nail is drawn // too early, it will be all white. private boolean mFirstFrameArrived; private Listener mListener; private final float[] mTextureTransformMatrix = new float[16]; // Animation. private CaptureAnimManager mCaptureAnimManager = new CaptureAnimManager(); private SwitchAnimManager mSwitchAnimManager = new SwitchAnimManager(); private int mAnimState = ANIM_NONE; private RawTexture mAnimTexture; // Some methods are called by GL thread and some are called by main thread. // This protects mAnimState, mVisible, and surface texture. This also makes // sure some code are atomic. For example, requestRender and setting // mAnimState. private Object mLock = new Object(); private OnFrameDrawnListener mOneTimeFrameDrawnListener; private float mAspectRatio; private int mRenderWidth; private int mRenderHeight; private int mPreviewWidth; private int mPreviewHeight; private boolean mFullScreen; public interface Listener { void requestRender(); // Preview has been copied to a texture. void onPreviewTextureCopied(); } public interface OnFrameDrawnListener { void onFrameDrawn(CameraScreenNail c); } public CameraScreenNail(Listener listener) { mListener = listener; } public void setFullScreen(boolean full) { mFullScreen = full; } @Override public void setSize(int w, int h) { super.setSize(w, h); if (w > h) { mAspectRatio = (float) w / h; } else { mAspectRatio = (float) h / w; } updateRenderSize(); } private void setPreviewLayoutSize(int w, int h) { mPreviewWidth = w; mPreviewHeight = h; updateRenderSize(); } private void updateRenderSize() { // these callbacks above come at different times, // so make sure we have all the data if (mPreviewWidth != 0 && mAspectRatio > 0) { if (mPreviewWidth > mPreviewHeight) { mRenderWidth = Math.max(mPreviewWidth, (int) (mPreviewHeight * mAspectRatio)); mRenderHeight = Math.max(mPreviewHeight, (int)(mPreviewWidth / mAspectRatio)); } else { mRenderWidth = Math.max(mPreviewWidth, (int) (mPreviewHeight / mAspectRatio)); mRenderHeight = Math.max(mPreviewHeight, (int) (mPreviewWidth * mAspectRatio)); } } } @Override public void acquireSurfaceTexture() { synchronized (mLock) { mFirstFrameArrived = false; super.acquireSurfaceTexture(); mAnimTexture = new RawTexture(getWidth(), getHeight(), true); } } @Override public void releaseSurfaceTexture() { synchronized (mLock) { super.releaseSurfaceTexture(); mAnimState = ANIM_NONE; // stop the animation } } public void copyTexture() { synchronized (mLock) { mListener.requestRender(); mAnimState = ANIM_SWITCH_COPY_TEXTURE; } } public void animateSwitchCamera() { Log.v(TAG, "animateSwitchCamera"); synchronized (mLock) { if (mAnimState == ANIM_SWITCH_DARK_PREVIEW) { // Do not request render here because camera has been just // started. We do not want to draw black frames. mAnimState = ANIM_SWITCH_WAITING_FIRST_FRAME; } } } public void animateCapture(int animOrientation) { synchronized (mLock) { mCaptureAnimManager.setOrientation(animOrientation); mListener.requestRender(); mAnimState = ANIM_CAPTURE_START; } } private void callbackIfNeeded() { if (mOneTimeFrameDrawnListener != null) { mOneTimeFrameDrawnListener.onFrameDrawn(this); mOneTimeFrameDrawnListener = null; } } public void directDraw(GLCanvas canvas, int x, int y, int width, int height) { super.draw(canvas, x, y, width, height); } @Override public void draw(GLCanvas canvas, int x, int y, int width, int height) { synchronized (mLock) { if (!mVisible) mVisible = true; SurfaceTexture surfaceTexture = getSurfaceTexture(); if (surfaceTexture == null || !mFirstFrameArrived) return; switch (mAnimState) { case ANIM_NONE: if (mFullScreen && (mRenderWidth != 0)) { // overscale image to make it fullscreen x = (x + width / 2) - mRenderWidth / 2; y = (y + height / 2) - mRenderHeight / 2; width = mRenderWidth; height = mRenderHeight; } super.draw(canvas, x, y, width, height); break; case ANIM_SWITCH_COPY_TEXTURE: copyPreviewTexture(canvas); mSwitchAnimManager.setReviewDrawingSize(width, height); mListener.onPreviewTextureCopied(); mAnimState = ANIM_SWITCH_DARK_PREVIEW; // The texture is ready. Fall through to draw darkened // preview. case ANIM_SWITCH_DARK_PREVIEW: case ANIM_SWITCH_WAITING_FIRST_FRAME: // Consume the frame. If the buffers are full, // onFrameAvailable will not be called. Animation state // relies on onFrameAvailable. surfaceTexture.updateTexImage(); mSwitchAnimManager.drawDarkPreview(canvas, x, y, width, height, mAnimTexture); break; case ANIM_SWITCH_START: mSwitchAnimManager.startAnimation(); mAnimState = ANIM_SWITCH_RUNNING; break; case ANIM_CAPTURE_START: copyPreviewTexture(canvas); if (mRenderWidth > 0) { // overscale image to make it fullscreen x = (x + width / 2) - mRenderWidth / 2; y = (y + height / 2) - mRenderHeight / 2; width = mRenderWidth; height = mRenderHeight; } mCaptureAnimManager.startAnimation(x, y, width, height); mAnimState = ANIM_CAPTURE_RUNNING; break; } if (mAnimState == ANIM_CAPTURE_RUNNING || mAnimState == ANIM_SWITCH_RUNNING) { boolean drawn; if (mAnimState == ANIM_CAPTURE_RUNNING) { drawn = mCaptureAnimManager.drawAnimation(canvas, this, mAnimTexture); } else { drawn = mSwitchAnimManager.drawAnimation(canvas, x, y, width, height, this, mAnimTexture); } if (drawn) { mListener.requestRender(); } else { // Continue to the normal draw procedure if the animation is // not drawn. mAnimState = ANIM_NONE; if (mRenderWidth != 0) { // overscale image to make it fullscreen x = (x + width / 2) - mRenderWidth / 2; y = (y + height / 2) - mRenderHeight / 2; width = mRenderWidth; height = mRenderHeight; } super.draw(canvas, x, y, width, height); } } callbackIfNeeded(); } // mLock } private void copyPreviewTexture(GLCanvas canvas) { int width = mAnimTexture.getWidth(); int height = mAnimTexture.getHeight(); canvas.beginRenderTarget(mAnimTexture); // Flip preview texture vertically. OpenGL uses bottom left point // as the origin (0, 0). canvas.translate(0, height); canvas.scale(1, -1, 1); getSurfaceTexture().getTransformMatrix(mTextureTransformMatrix); canvas.drawTexture(mExtTexture, mTextureTransformMatrix, 0, 0, width, height); canvas.endRenderTarget(); } @Override public void noDraw() { synchronized (mLock) { mVisible = false; } } @Override public void recycle() { synchronized (mLock) { mVisible = false; } } @Override public void onFrameAvailable(SurfaceTexture surfaceTexture) { synchronized (mLock) { + if (getSurfaceTexture() != surfaceTexture) { + return; + } mFirstFrameArrived = true; if (mVisible) { if (mAnimState == ANIM_SWITCH_WAITING_FIRST_FRAME) { mAnimState = ANIM_SWITCH_START; } // We need to ask for re-render if the SurfaceTexture receives a new // frame. mListener.requestRender(); } } } // We need to keep track of the size of preview frame on the screen because // it's needed when we do switch-camera animation. See comments in // SwitchAnimManager.java. This is based on the natural orientation, not the // view system orientation. public void setPreviewFrameLayoutSize(int width, int height) { synchronized (mLock) { mSwitchAnimManager.setPreviewFrameLayoutSize(width, height); setPreviewLayoutSize(width, height); } } public void setOneTimeOnFrameDrawnListener(OnFrameDrawnListener l) { synchronized (mLock) { mFirstFrameArrived = false; mOneTimeFrameDrawnListener = l; } } }
true
false
null
null
diff --git a/android-aac-enc/src/com/todoroo/aacenc/AACRecorder.java b/android-aac-enc/src/com/todoroo/aacenc/AACRecorder.java index b7ac2a27d..f476f7aa6 100644 --- a/android-aac-enc/src/com/todoroo/aacenc/AACRecorder.java +++ b/android-aac-enc/src/com/todoroo/aacenc/AACRecorder.java @@ -1,100 +1,100 @@ package com.todoroo.aacenc; import java.io.ByteArrayOutputStream; import java.io.IOException; import android.content.Context; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder.AudioSource; /** * This class combines an Android AudioRecord and our own AACEncoder * to directly record an AAC audio file from the mic. Users should call * startRecording() and stopRecording() in sequence, and then listen * for the encodingFinished() callback to perform final actions like * converting to M4A format. * @author Sam * */ public class AACRecorder { private AudioRecord audioRecord; private AACEncoder encoder; private boolean recording; private AACRecorderCallbacks listener; private static final int SAMPLE_RATE = 8000; private static final int NOTIFICATION_PERIOD = 160; private static final int MIN_BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT) * 10; public interface AACRecorderCallbacks { public void encodingFinished(); } private Thread readerThread = new Thread() { private byte[] readBuffer = new byte[NOTIFICATION_PERIOD * 2]; public void run() { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(SAMPLE_RATE * 2); int bytesRead = 0; while(recording) { bytesRead = audioRecord.read(readBuffer, 0, readBuffer.length); try { baos.write(readBuffer); } catch (IOException e) { // } if (bytesRead <= 0) break; } encoder.encode(baos.toByteArray()); finishRecording(); baos.reset(); } }; public AACRecorder() { encoder = new AACEncoder(); } public synchronized void startRecording(String tempFile) { if (recording) return; audioRecord = new AudioRecord(AudioSource.MIC, SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, MIN_BUFFER_SIZE); audioRecord.setPositionNotificationPeriod(NOTIFICATION_PERIOD); encoder.init(64000, 1, SAMPLE_RATE, 16, tempFile); recording = true; audioRecord.startRecording(); readerThread.start(); } public synchronized void stopRecording() { if (!recording) return; audioRecord.stop(); } public synchronized void finishRecording() { recording = false; audioRecord.release(); encoder.uninit(); if (listener != null) listener.encodingFinished(); } public void setListener(AACRecorderCallbacks listener) { this.listener = listener; } } diff --git a/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java b/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java index 97fa0a0d3..ee179366c 100644 --- a/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java +++ b/astrid/plugin-src/com/todoroo/astrid/files/AACRecordingActivity.java @@ -1,107 +1,107 @@ package com.todoroo.astrid.files; import java.io.IOException; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.TextView; import android.widget.Toast; import com.timsu.astrid.R; import com.todoroo.aacenc.AACRecorder; import com.todoroo.aacenc.AACRecorder.AACRecorderCallbacks; import com.todoroo.aacenc.AACToM4A; import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.astrid.service.ThemeService; public class AACRecordingActivity extends Activity implements AACRecorderCallbacks { public static final String EXTRA_TEMP_FILE = "tempFile"; //$NON-NLS-1$ public static final String EXTRA_TASK_ID = "taskId"; //$NON-NLS-1$ public static final String RESULT_OUTFILE = "outfile"; //$NON-NLS-1$ private AACRecorder recorder; private String tempFile; private long taskId; private ProgressDialog pd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aac_record_activity); setupUi(); tempFile = getIntent().getStringExtra(EXTRA_TEMP_FILE); taskId = getIntent().getLongExtra(EXTRA_TASK_ID, 0L); recorder = new AACRecorder(); recorder.setListener(this); recorder.startRecording(tempFile); } private void setupUi() { View stopRecording = findViewById(R.id.stop_recording); stopRecording.setBackgroundColor(getResources().getColor(ThemeService.getThemeColor())); stopRecording.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { stopRecording(); } }); View dismiss = findViewById(R.id.dismiss); dismiss.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { recorder.stopRecording(); finish(); } }); TextView speechBubble = (TextView) findViewById(R.id.reminder_message); speechBubble.setText(R.string.audio_speak_now); } private void stopRecording() { recorder.stopRecording(); - pd = DialogUtilities.progressDialog(this, getString(R.string.audio_err_encoding)); + pd = DialogUtilities.progressDialog(this, getString(R.string.audio_encoding)); pd.show(); } @SuppressWarnings("nls") @Override public void encodingFinished() { try { StringBuilder filePathBuilder = new StringBuilder(); filePathBuilder.append(getExternalFilesDir("audio").toString()) .append("/") .append(taskId) .append("_") .append(DateUtilities.now()) .append("_audio.mp4"); String outFile = filePathBuilder.toString(); new AACToM4A().convert(this, tempFile, outFile); Intent result = new Intent(); result.putExtra(RESULT_OUTFILE, outFile); setResult(RESULT_OK, result); finish(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, R.string.audio_err_encoding, Toast.LENGTH_LONG); } pd.dismiss(); } }
false
false
null
null
diff --git a/thucydides-core/src/test/java/net/thucydides/core/pages/integration/WhenWaitingForElementsWithTheFluentElementAPI.java b/thucydides-core/src/test/java/net/thucydides/core/pages/integration/WhenWaitingForElementsWithTheFluentElementAPI.java index 3ab05fbc..a81b234c 100644 --- a/thucydides-core/src/test/java/net/thucydides/core/pages/integration/WhenWaitingForElementsWithTheFluentElementAPI.java +++ b/thucydides-core/src/test/java/net/thucydides/core/pages/integration/WhenWaitingForElementsWithTheFluentElementAPI.java @@ -1,194 +1,196 @@ package net.thucydides.core.pages.integration; +import net.thucydides.core.annotations.WithDriver; import net.thucydides.core.webdriver.WebDriverFacade; import net.thucydides.core.webdriver.WebDriverFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.openqa.selenium.By; import org.openqa.selenium.ElementNotVisibleException; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; public class WhenWaitingForElementsWithTheFluentElementAPI extends FluentElementAPITestsBaseClass { static StaticSitePage page; static StaticSitePage chromePage; @BeforeClass public static void setupDriver() { driver = new WebDriverFacade(FirefoxDriver.class, new WebDriverFactory()); chromeDriver = new WebDriverFacade(ChromeDriver.class, new WebDriverFactory()); page = new StaticSitePage(driver, 750); page.open(); page.addJQuerySupport(); chromePage = new StaticSitePage(chromeDriver, 750); chromePage.open(); } @AfterClass public static void closeBrowser() { driver.quit(); chromeDriver.quit(); } @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void should_optionally_type_enter_after_entering_text() { refresh(chromePage); assertThat(chromePage.firstName.getAttribute("value"), is("<enter first name>")); chromePage.element(chromePage.firstName).typeAndEnter("joe"); assertThat(chromePage.firstName.getAttribute("value"), is("<enter first name>")); } @Test public void should_optionally_type_tab_after_entering_text_on_linux() { if (runningOnLinux()) { refresh(chromePage); assertThat(chromePage.firstName.getAttribute("value"), is("<enter first name>")); chromePage.element(chromePage.firstName).typeAndTab("joe"); assertThat(chromePage.element(chromePage.lastName).hasFocus(), is(true)); } } @Test + @Ignore("Known issue with tabs in Firefox") public void should_optionally_type_tab_after_entering_text_in_firefox() { refresh(page); assertThat(page.firstName.getAttribute("value"), is("<enter first name>")); page.element(page.firstName).typeAndTab("joe"); assertThat(page.element(page.lastName).hasFocus(), is(true)); } @Test public void should_trigger_blur_event_when_focus_leaves_field_in_chrome() { StaticSitePage page = new StaticSitePage(chromeDriver, 750); page.open(); assertThat(page.firstName.getAttribute("value"), is("<enter first name>")); assertThat(page.focusmessage.getText(), is("")); page.element(page.firstName).typeAndTab("joe"); assertThat(page.focusmessage.getText(), is("focus left firstname")); } @Test public void should_wait_for_element_to_be_visible_and_enabled_before_clicking() { page.element(page.checkbox).click(); } @Test public void should_be_able_to_build_composite_wait_until_enabled_clauses() throws InterruptedException { refresh(page); page.waitForCondition().until(page.firstAndLastNameAreEnabled()); } @Test public void should_be_able_to_build_composite_wait_until_disabled_clauses() throws InterruptedException { refresh(page); page.waitForCondition().until(page.twoFieldsAreDisabled()); } @Test public void should_let_you_remove_the_focus_from_the_current_active_field() { StaticSitePage page = new StaticSitePage(chromeDriver, 750); refresh(page); page.element(page.firstName).click(); assertThat(page.element(page.focusmessage).getText(), is("")); page.blurActiveElement(); page.element(page.focusmessage).shouldContainText("focus left firstname"); } @Ignore("Not working yet for firefox") @Test public void should_let_you_remove_the_focus_from_the_current_active_field_in_firefox() { if (runningOnLinux()) { page.element(page.firstName).click(); assertThat(page.element(page.focusmessage).getText(), is("")); page.blurActiveElement(); page.element(page.focusmessage).shouldContainText("focus left firstname"); } } @Test public void should_wait_for_text_to_dissapear() { refresh(page); page.waitForTextToDisappear("Dissapearing text"); assertThat(page.containsText("Dissapearing text"), is(false)); } @Test public void should_wait_for_text_in_element_to_dissapear() { refresh(page); page.waitForTextToDisappear(page.dissapearingtext, "Dissapearing text"); assertThat(page.containsText("Dissapearing text"), is(false)); } @Test public void should_wait_for_elements_to_appear() { refresh(chromePage); chromePage.waitForAnyRenderedElementOf(By.id("city")); assertThat(chromePage.element(chromePage.city).isCurrentlyVisible(), is(true)); } @Test public void should_display_meaningful_error_messages_in_firefox_if_waiting_for_field_that_does_not_appear() { refresh(page); expectedException.expect(ElementNotVisibleException.class); expectedException.expectMessage(allOf(containsString("Unable to locate element"), containsString("fieldDoesNotExist"))); page.setWaitForTimeout(200); refresh(page); page.element(page.fieldDoesNotExist).waitUntilVisible(); } @Test public void should_wait_for_field_to_be_enabled_using_alternative_style() throws InterruptedException { page.firstName().waitUntilVisible(); page.firstName().waitUntilEnabled(); } }
false
false
null
null
diff --git a/modules/quercus/src/com/caucho/quercus/env/ResourceValue.java b/modules/quercus/src/com/caucho/quercus/env/ResourceValue.java index 2687e4d57..4b1e5416f 100644 --- a/modules/quercus/src/com/caucho/quercus/env/ResourceValue.java +++ b/modules/quercus/src/com/caucho/quercus/env/ResourceValue.java @@ -1,114 +1,122 @@ /* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.quercus.env; import com.caucho.vfs.WriteStream; -import java.io.Closeable; import java.io.IOException; import java.util.IdentityHashMap; /** * Represents a PHP resource */ public class ResourceValue extends Value implements EnvCleanup { @Override public boolean isResource() { return true; } /** * Implements the EnvCleanup interface. */ public void cleanup() { } /** * By default close() will call cleanup(). * If implementation specific logic is * needed to clean up resources it should * be defined in an overloaded cleanup(). */ public void close() { cleanup(); } /** * Converts to a key. */ @Override public Value toKey() { return new LongValue(System.identityHashCode(this)); } + + /** + * Serializes the value. + */ + @Override + public void serialize(Env env, StringBuilder sb) + { + sb.append("i:0;"); + } /** * Converts to a string. */ @Override public String toString() { if (ResourceValue.class.equals(getClass())) { return ResourceValue.class.getSimpleName() + "[]"; } else { return ResourceValue.class.getSimpleName() + "[" + getClass().getSimpleName() + "]"; } } @Override protected void varDumpImpl(Env env, WriteStream out, int depth, IdentityHashMap<Value, String> valueSet) throws IOException { out.print("resource(" + toString(env) + ")"); } @Override protected void printRImpl(Env env, WriteStream out, int depth, IdentityHashMap<Value, String> valueSet) throws IOException { out.print("resource(" + toString(env) + ")"); } }
false
false
null
null
diff --git a/src/main/java/Main.java b/src/main/java/Main.java index 062b2db..1b7489c 100644 --- a/src/main/java/Main.java +++ b/src/main/java/Main.java @@ -1,51 +1,58 @@ import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.pircbotx.Configuration; import org.pircbotx.PircBotX; import bot.Bot; import bot.BotConfig; +import bot.BotHandler; import bot.config.EnvironmentVars; +import bot.di.Module; + +import com.google.inject.Guice; +import com.google.inject.Injector; public class Main extends HttpServlet { private static final long serialVersionUID = -7490600326997334112L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().print( "I'm just alive so the bot counts as a webapp :)"); } public static void main(String[] args) throws Exception { - BotConfig botConfig = new BotConfig(); + Injector injector = Guice.createInjector(new Module()); + BotConfig botConfig = new BotConfig(injector.getInstance(BotHandler.class)); + Configuration<PircBotX> config = botConfig.createConfig(); PircBotX pircbotx = new PircBotX(config); Bot bot = new Bot(pircbotx); bot.start(); } private static void launchServer() throws Exception, InterruptedException { Server server = new Server(Integer.valueOf(System .getenv(EnvironmentVars.PORT))); ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS); context.setContextPath("/"); server.setHandler(context); context.addServlet(new ServletHolder(new Main()), "/*"); server.start(); server.join(); } }
false
false
null
null
diff --git a/src/org/apache/xml/utils/DefaultErrorHandler.java b/src/org/apache/xml/utils/DefaultErrorHandler.java index 8062f9ca..9b8750a4 100644 --- a/src/org/apache/xml/utils/DefaultErrorHandler.java +++ b/src/org/apache/xml/utils/DefaultErrorHandler.java @@ -1,260 +1,261 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xml.utils; import org.xml.sax.*; import javax.xml.transform.ErrorListener; import javax.xml.transform.TransformerException; import javax.xml.transform.SourceLocator; /** * <meta name="usage" content="general"/> * Implement SAX error handler for default reporting. */ public class DefaultErrorHandler implements ErrorHandler, ErrorListener { /** * Constructor DefaultErrorHandler */ public DefaultErrorHandler() { } /** * Receive notification of a warning. * * <p>SAX parsers will use this method to report conditions that * are not errors or fatal errors as defined by the XML 1.0 * recommendation. The default behaviour is to take no action.</p> * * <p>The SAX parser must continue to provide normal parsing events * after invoking this method: it should still be possible for the * application to process the document through to the end.</p> * * @param exception The warning information encapsulated in a * SAX parse exception. * @throws SAXException Any SAX exception, possibly * wrapping another exception. */ public void warning(SAXParseException exception) throws SAXException { printLocation(exception); System.out.println("Parser warning: " + exception.getMessage()); } /** * Receive notification of a recoverable error. * * <p>This corresponds to the definition of "error" in section 1.2 * of the W3C XML 1.0 Recommendation. For example, a validating * parser would use this callback to report the violation of a * validity constraint. The default behaviour is to take no * action.</p> * * <p>The SAX parser must continue to provide normal parsing events * after invoking this method: it should still be possible for the * application to process the document through to the end. If the * application cannot do so, then the parser should report a fatal * error even if the XML 1.0 recommendation does not require it to * do so.</p> * * @param exception The error information encapsulated in a * SAX parse exception. * @throws SAXException Any SAX exception, possibly * wrapping another exception. */ public void error(SAXParseException exception) throws SAXException { printLocation(exception); - System.out.println("Parser error: " + exception.getMessage()); + + throw exception; } /** * Receive notification of a non-recoverable error. * * <p>This corresponds to the definition of "fatal error" in * section 1.2 of the W3C XML 1.0 Recommendation. For example, a * parser would use this callback to report the violation of a * well-formedness constraint.</p> * * <p>The application must assume that the document is unusable * after the parser has invoked this method, and should continue * (if at all) only for the sake of collecting addition error * messages: in fact, SAX parsers are free to stop reporting any * other events once this method has been invoked.</p> * * @param exception The error information encapsulated in a * SAX parse exception. * @throws SAXException Any SAX exception, possibly * wrapping another exception. */ public void fatalError(SAXParseException exception) throws SAXException { printLocation(exception); throw exception; } /** * Receive notification of a warning. * * <p>SAX parsers will use this method to report conditions that * are not errors or fatal errors as defined by the XML 1.0 * recommendation. The default behaviour is to take no action.</p> * * <p>The SAX parser must continue to provide normal parsing events * after invoking this method: it should still be possible for the * application to process the document through to the end.</p> * * @param exception The warning information encapsulated in a * SAX parse exception. * @throws javax.xml.transform.TransformerException Any SAX exception, possibly * wrapping another exception. * @see javax.xml.transform.TransformerException */ public void warning(TransformerException exception) throws TransformerException { printLocation(exception); System.out.println(exception.getMessage()); } /** * Receive notification of a recoverable error. * * <p>This corresponds to the definition of "error" in section 1.2 * of the W3C XML 1.0 Recommendation. For example, a validating * parser would use this callback to report the violation of a * validity constraint. The default behaviour is to take no * action.</p> * * <p>The SAX parser must continue to provide normal parsing events * after invoking this method: it should still be possible for the * application to process the document through to the end. If the * application cannot do so, then the parser should report a fatal * error even if the XML 1.0 recommendation does not require it to * do so.</p> * * @param exception The error information encapsulated in a * SAX parse exception. * @throws javax.xml.transform.TransformerException Any SAX exception, possibly * wrapping another exception. * @see javax.xml.transform.TransformerException */ public void error(TransformerException exception) throws TransformerException { printLocation(exception); - System.out.println("Parser error: " + exception.getMessage()); + throw exception; } /** * Receive notification of a non-recoverable error. * * <p>This corresponds to the definition of "fatal error" in * section 1.2 of the W3C XML 1.0 Recommendation. For example, a * parser would use this callback to report the violation of a * well-formedness constraint.</p> * * <p>The application must assume that the document is unusable * after the parser has invoked this method, and should continue * (if at all) only for the sake of collecting addition error * messages: in fact, SAX parsers are free to stop reporting any * other events once this method has been invoked.</p> * * @param exception The error information encapsulated in a * SAX parse exception. * @throws javax.xml.transform.TransformerException Any SAX exception, possibly * wrapping another exception. * @see javax.xml.transform.TransformerException */ public void fatalError(TransformerException exception) throws TransformerException { printLocation(exception); throw exception; } private void printLocation(org.xml.sax.SAXParseException exception) { // System.out.println("Parser fatal error: "+exception.getMessage()); String id = (null != exception.getSystemId()) ? exception.getSystemId() : "SystemId Unknown"; System.out.println(id + "; Line " + exception.getLineNumber() + "; Column " + exception.getColumnNumber()); } private void printLocation(TransformerException exception) { SourceLocator locator = exception.getLocator(); if(null != locator) { // System.out.println("Parser fatal error: "+exception.getMessage()); String id = (locator.getPublicId() != locator.getPublicId()) ? locator.getPublicId() : (null != locator.getSystemId()) ? locator.getSystemId() : "SystemId Unknown"; System.out.println(id + "; Line " + locator.getLineNumber() + "; Column " + locator.getColumnNumber()); } } }
false
false
null
null
diff --git a/src/java/net/percederberg/mibble/MibLoaderLog.java b/src/java/net/percederberg/mibble/MibLoaderLog.java index 53e3089..94acc28 100644 --- a/src/java/net/percederberg/mibble/MibLoaderLog.java +++ b/src/java/net/percederberg/mibble/MibLoaderLog.java @@ -1,491 +1,491 @@ /* * MibLoaderLog.java * * This work is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This work is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Copyright (c) 2004 Per Cederberg. All rights reserved. */ package net.percederberg.mibble; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import net.percederberg.grammatica.parser.ParseException; import net.percederberg.grammatica.parser.ParserLogException; /** * A MIB loader log. This class contains error and warning messages * from loading a MIB file and all imports not previously loaded. * * @author Per Cederberg, <per at percederberg dot net> * @version 2.6 * @since 2.0 */ public class MibLoaderLog { /** * The log entries. */ private ArrayList entries = new ArrayList(); /** * The log error count. */ private int errors = 0; /** * The log warning count. */ private int warnings = 0; /** * Creates a new loader log without entries. */ public MibLoaderLog() { // Nothing initialization needed } /** * Returns the number of errors in the log. * * @return the number of errors in the log */ public int errorCount() { return errors; } /** * Returns the number of warnings in the log. * * @return the number of warnings in the log */ public int warningCount() { return warnings; } /** * Adds a log entry to this log. * * @param entry the log entry to add */ public void add(LogEntry entry) { if (entry.isError()) { errors++; } if (entry.isWarning()) { warnings++; } entries.add(entry); } /** * Adds an internal error message to the log. Internal errors are * only issued when possible bugs are encountered. They are * counted as errors. * * @param location the file location * @param message the error message */ public void addInternalError(FileLocation location, String message) { add(new LogEntry(LogEntry.INTERNAL_ERROR, location, message)); } /** * Adds an internal error message to the log. Internal errors are * only issued when possible bugs are encountered. They are * counted as errors. * * @param file the file affected * @param message the error message */ public void addInternalError(File file, String message) { addInternalError(new FileLocation(file), message); } /** * Adds an error message to the log. * * @param location the file location * @param message the error message */ public void addError(FileLocation location, String message) { add(new LogEntry(LogEntry.ERROR, location, message)); } /** * Adds an error message to the log. * * @param file the file affected * @param line the line number * @param column the column number * @param message the error message */ public void addError(File file, int line, int column, String message) { addError(new FileLocation(file, line, column), message); } /** * Adds a warning message to the log. * * @param location the file location * @param message the warning message */ public void addWarning(FileLocation location, String message) { add(new LogEntry(LogEntry.WARNING, location, message)); } /** * Adds a warning message to the log. * * @param file the file affected * @param line the line number * @param column the column number * @param message the warning message */ public void addWarning(File file, int line, int column, String message) { addWarning(new FileLocation(file, line, column), message); } /** * Adds all log entries from another log. * * @param log the MIB loader log */ public void addAll(MibLoaderLog log) { for (int i = 0; i < log.entries.size(); i++) { add((LogEntry) log.entries.get(i)); } } /** * Adds all errors from a parser log exception. * * @param file the file affected * @param log the parser log exception */ void addAll(File file, ParserLogException log) { ParseException e; for (int i = 0; i < log.getErrorCount(); i++) { e = log.getError(i); addError(file, e.getLine(), e.getColumn(), e.getErrorMessage()); } } /** * Returns an iterator with all the log entries. The iterator * will only return LogEntry instances. * * @return an iterator with all the log entries * * @see LogEntry * * @since 2.2 */ public Iterator entries() { return entries.iterator(); } /** * Prints all log entries to the specified output stream. * * @param output the output stream to use */ public void printTo(PrintStream output) { printTo(new PrintWriter(output)); } /** * Prints all log entries to the specified output stream. * * @param output the output stream to use */ public void printTo(PrintWriter output) { printTo(output, 70); } /** * Prints all log entries to the specified output stream. * * @param output the output stream to use * @param margin the print margin * * @since 2.2 */ public void printTo(PrintWriter output, int margin) { StringBuffer buffer = new StringBuffer(); LogEntry entry; String str; for (int i = 0; i < entries.size(); i++) { entry = (LogEntry) entries.get(i); buffer.setLength(0); switch (entry.getType()) { case LogEntry.ERROR: buffer.append("Error: "); break; case LogEntry.WARNING: buffer.append("Warning: "); break; default: buffer.append("Internal Error: "); break; } buffer.append("in "); buffer.append(relativeFilename(entry.getFile())); if (entry.getLineNumber() > 0) { buffer.append(": line "); buffer.append(entry.getLineNumber()); } buffer.append(":\n"); str = linebreakString(entry.getMessage(), " ", margin); buffer.append(str); str = entry.readLine(); - if (str != null) { + if (str != null && str.length() >= entry.getColumnNumber()) { buffer.append("\n\n"); buffer.append(str); buffer.append("\n"); for (int j = 1; j < entry.getColumnNumber(); j++) { if (str.charAt(j - 1) == '\t') { buffer.append("\t"); } else { buffer.append(" "); } } buffer.append("^"); } output.println(buffer.toString()); } output.flush(); } /** * Creates a relative file name from a file. This method will * return the absolute file name if the file unless the current * directory is a parent to the file. * * @param file the file to calculate relative name for * * @return the relative name if found, or * the absolute name otherwise */ private String relativeFilename(File file) { String currentPath; String filePath; if (file == null) { return "<unknown file>"; } try { currentPath = new File(".").getCanonicalPath(); filePath = file.getCanonicalPath(); if (filePath.startsWith(currentPath)) { filePath = filePath.substring(currentPath.length()); if (filePath.charAt(0) == '/' || filePath.charAt(0) == '\\') { return filePath.substring(1); } else { return filePath; } } } catch (IOException e) { // Do nothing } return file.toString(); } /** * Breaks a string into multiple lines. This method will also add * a prefix to each line in the resulting string. The prefix * length will be taken into account when breaking the line. Line * breaks will only be inserted as replacements for space * characters. * * @param str the string to line break * @param prefix the prefix to add to each line * @param length the maximum line length * * @return the new formatted string */ private String linebreakString(String str, String prefix, int length) { StringBuffer buffer = new StringBuffer(); int pos; while (str.length() + prefix.length() > length) { pos = str.lastIndexOf(' ', length - prefix.length()); if (pos < 0) { pos = str.indexOf(' '); if (pos < 0) { break; } } buffer.append(prefix); buffer.append(str.substring(0, pos)); str = str.substring(pos + 1); buffer.append("\n"); } buffer.append(prefix); buffer.append(str); return buffer.toString(); } /** * A log entry. This class holds all the details in an error or a * warning log entry. * * @author Per Cederberg, <per at percederberg dot net> * @version 2.2 * @since 2.2 */ public class LogEntry { /** * The internal error log entry type constant. */ public static final int INTERNAL_ERROR = 1; /** * The error log entry type constant. */ public static final int ERROR = 2; /** * The warning log entry type constant. */ public static final int WARNING = 3; /** * The log entry type. */ private int type; /** * The log entry file reference. */ private FileLocation location; /** * The log entry message. */ private String message; /** * Creates a new log entry. * * @param type the log entry type * @param location the log entry file reference * @param message the log entry message */ public LogEntry(int type, FileLocation location, String message) { this.type = type; if (location == null || location.getFile() == null) { this.location = new FileLocation(new File("<unknown file>")); } else { this.location = location; } this.message = message; } /** * Checks if this is an error log entry. * * @return true if this is an error log entry, or * false otherwise */ public boolean isError() { return type == INTERNAL_ERROR || type == ERROR; } /** * Checks if this is a warning log entry. * * @return true if this is a warning log entry, or * false otherwise */ public boolean isWarning() { return type == WARNING; } /** * Returns the log entry type. * * @return the log entry type * * @see #INTERNAL_ERROR * @see #ERROR * @see #WARNING */ public int getType() { return type; } /** * Returns the file this entry applies to. * * @return the file affected */ public File getFile() { return location.getFile(); } /** * Returns the line number. * * @return the line number */ public int getLineNumber() { return location.getLineNumber(); } /** * Returns the column number. * * @return the column number */ public int getColumnNumber() { return location.getColumnNumber(); } /** * Returns the log entry message. * * @return the log entry message */ public String getMessage() { return message; } /** * Reads the line from the referenced file. If the file couldn't * be opened or read correctly, null will be returned. The line * will NOT contain the terminating '\n' character. * * @return the line read, or * null if not found */ public String readLine() { return location.readLine(); } } }
true
true
public void printTo(PrintWriter output, int margin) { StringBuffer buffer = new StringBuffer(); LogEntry entry; String str; for (int i = 0; i < entries.size(); i++) { entry = (LogEntry) entries.get(i); buffer.setLength(0); switch (entry.getType()) { case LogEntry.ERROR: buffer.append("Error: "); break; case LogEntry.WARNING: buffer.append("Warning: "); break; default: buffer.append("Internal Error: "); break; } buffer.append("in "); buffer.append(relativeFilename(entry.getFile())); if (entry.getLineNumber() > 0) { buffer.append(": line "); buffer.append(entry.getLineNumber()); } buffer.append(":\n"); str = linebreakString(entry.getMessage(), " ", margin); buffer.append(str); str = entry.readLine(); if (str != null) { buffer.append("\n\n"); buffer.append(str); buffer.append("\n"); for (int j = 1; j < entry.getColumnNumber(); j++) { if (str.charAt(j - 1) == '\t') { buffer.append("\t"); } else { buffer.append(" "); } } buffer.append("^"); } output.println(buffer.toString()); } output.flush(); }
public void printTo(PrintWriter output, int margin) { StringBuffer buffer = new StringBuffer(); LogEntry entry; String str; for (int i = 0; i < entries.size(); i++) { entry = (LogEntry) entries.get(i); buffer.setLength(0); switch (entry.getType()) { case LogEntry.ERROR: buffer.append("Error: "); break; case LogEntry.WARNING: buffer.append("Warning: "); break; default: buffer.append("Internal Error: "); break; } buffer.append("in "); buffer.append(relativeFilename(entry.getFile())); if (entry.getLineNumber() > 0) { buffer.append(": line "); buffer.append(entry.getLineNumber()); } buffer.append(":\n"); str = linebreakString(entry.getMessage(), " ", margin); buffer.append(str); str = entry.readLine(); if (str != null && str.length() >= entry.getColumnNumber()) { buffer.append("\n\n"); buffer.append(str); buffer.append("\n"); for (int j = 1; j < entry.getColumnNumber(); j++) { if (str.charAt(j - 1) == '\t') { buffer.append("\t"); } else { buffer.append(" "); } } buffer.append("^"); } output.println(buffer.toString()); } output.flush(); }
diff --git a/src/com/tactfactory/mda/template/ActivityGenerator.java b/src/com/tactfactory/mda/template/ActivityGenerator.java index 241f3b2d..65523744 100644 --- a/src/com/tactfactory/mda/template/ActivityGenerator.java +++ b/src/com/tactfactory/mda/template/ActivityGenerator.java @@ -1,574 +1,573 @@ /** * This file is part of the Harmony package. * * (c) Mickael Gaillard <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package com.tactfactory.mda.template; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Locale; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; -import com.sun.xml.internal.ws.util.StringUtils; import com.tactfactory.mda.annotation.Column.Type; import com.tactfactory.mda.meta.ApplicationMetadata; import com.tactfactory.mda.meta.ClassMetadata; import com.tactfactory.mda.meta.FieldMetadata; import com.tactfactory.mda.meta.TranslationMetadata; import com.tactfactory.mda.meta.TranslationMetadata.Group; import com.tactfactory.mda.plateforme.BaseAdapter; import com.tactfactory.mda.utils.ConsoleUtils; import com.tactfactory.mda.utils.TactFileUtils; import com.tactfactory.mda.utils.PackageUtils; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; /** * Generate the CRUD activities. */ public class ActivityGenerator extends BaseGenerator { /** "template". */ private static final String LOWER_TEMPLATE = "template"; /** "Template". */ private static final String TEMPLATE = "Template"; /** "name". */ private static final String NAME = "name"; /** The local namespace. */ private String localNameSpace; /** Are the entities writable ? */ private boolean isWritable = true; /** Has the project a date ? */ private boolean isDate; /** Has the project a time ? */ private boolean isTime; /** * Constructor. * @param adapter The adapter to use * @throws Exception */ public ActivityGenerator(final BaseAdapter adapter) throws Exception { this(adapter, true); // Make entities for (final ClassMetadata meta : this.getAppMetas().getEntities().values()) { if (!meta.getFields().isEmpty() && !meta.isInternal()) { // copy Widget if (this.isDate && this.isTime) { break; } else { for (final FieldMetadata field : meta.getFields().values()) { final String type = field.getType(); if (!this.isDate && ( type.equals(Type.DATE.getValue()) || type.equals(Type.DATETIME.getValue()))) { this.isDate = true; } if (!this.isTime && ( type.equals(Type.TIME.getValue()) || type.equals(Type.DATETIME.getValue()))) { this.isTime = true; } } } } } } /** * Constructor. * @param adapter The adapter to use. * @param writable Are the entities writable ? (default to true) * @throws Exception */ public ActivityGenerator(final BaseAdapter adapter, final Boolean writable) throws Exception { super(adapter); this.isWritable = writable; this.setDatamodel( ApplicationMetadata.INSTANCE.toMap(this.getAdapter())); } /** * Generate all activities for every entity. */ public final void generateAll() { ConsoleUtils.display(">> Generate CRUD view..."); for (final ClassMetadata cm : this.getAppMetas().getEntities().values()) { if (!cm.isInternal() && !cm.getFields().isEmpty()) { cm.makeString("label"); this.getDatamodel().put( TagConstant.CURRENT_ENTITY, cm.getName()); this.localNameSpace = this.getAdapter().getNameSpace(cm, this.getAdapter().getController()) + "." + cm.getName().toLowerCase(Locale.ENGLISH); this.generateAllAction(cm.getName()); } } if (this.isDate) { this.updateWidget("CustomDatePickerDialog.java", "dialog_date_picker.xml"); } if (this.isTime) { this.updateWidget("CustomTimePickerDialog.java", "dialog_time_picker.xml"); } } /** * Generate all actions (List, Show, Edit, Create). * @param entityName The entity for which to generate the crud. */ public final void generateAllAction(final String entityName) { ConsoleUtils.display(">>> Generate CRUD view for " + entityName); try { if (this.isWritable) { ConsoleUtils.display(" with write actions"); this.generateCreateAction(entityName); this.generateEditAction(entityName); TranslationMetadata.addDefaultTranslation( "common_create", "Create", Group.COMMON); TranslationMetadata.addDefaultTranslation( "common_edit", "Edit", Group.COMMON); TranslationMetadata.addDefaultTranslation( entityName.toLowerCase(Locale.ENGLISH) + "_progress_save_title", entityName + " save progress", Group.MODEL); TranslationMetadata.addDefaultTranslation( entityName.toLowerCase(Locale.ENGLISH) + "_progress_save_message", entityName + " is saving to database…", Group.MODEL); } this.generateShowAction(entityName); this.generateListAction(entityName); TranslationMetadata.addDefaultTranslation( entityName.toLowerCase(Locale.ENGLISH) + "_progress_load_title", entityName + " Loading progress", Group.MODEL); TranslationMetadata.addDefaultTranslation( entityName.toLowerCase(Locale.ENGLISH) + "_progress_load_message", entityName + " is loading…", Group.MODEL); new TranslationGenerator(this.getAdapter()).generateStringsXml(); } catch (final Exception e) { ConsoleUtils.displayError(e); } } /** List Action. * @param entityName The entity to generate * @throws IOException * @throws TemplateException */ protected final void generateListAction(final String entityName) { final ArrayList<String> javas = new ArrayList<String>(); javas.add("%sListActivity.java"); javas.add("%sListFragment.java"); javas.add("%sListAdapter.java"); javas.add("%sListLoader.java"); final ArrayList<String> xmls = new ArrayList<String>(); xmls.add("activity_%s_list.xml"); xmls.add("fragment_%s_list.xml"); xmls.add("row_%s.xml"); for (final String java : javas) { this.makeSourceControler( String.format(java, TEMPLATE), String.format(java, entityName)); } for (final String xml : xmls) { this.makeResourceLayout( String.format(xml, LOWER_TEMPLATE), String.format(xml, entityName.toLowerCase(Locale.ENGLISH))); } this.updateManifest("ListActivity", entityName); TranslationMetadata.addDefaultTranslation( entityName.toLowerCase(Locale.ENGLISH) + "_empty_list", entityName + " list is empty !", Group.MODEL); } /** Show Action. * @param entityName The entity to generate * @throws IOException * @throws TemplateException */ protected final void generateShowAction(final String entityName) { final ArrayList<String> javas = new ArrayList<String>(); javas.add("%sShowActivity.java"); javas.add("%sShowFragment.java"); final ArrayList<String> xmls = new ArrayList<String>(); xmls.add("activity_%s_show.xml"); xmls.add("fragment_%s_show.xml"); for (final String java : javas) { this.makeSourceControler( String.format(java, TEMPLATE), String.format(java, entityName)); } for (final String xml : xmls) { this.makeResourceLayout( String.format(xml, LOWER_TEMPLATE), String.format(xml, entityName.toLowerCase(Locale.ENGLISH))); } this.updateManifest("ShowActivity", entityName); TranslationMetadata.addDefaultTranslation( entityName.toLowerCase(Locale.ENGLISH) + "_error_load", entityName + " loading error…", Group.MODEL); } /** Edit Action. * @param entityName The entity to generate * @throws IOException * @throws TemplateException */ protected final void generateEditAction(final String entityName) { final ArrayList<String> javas = new ArrayList<String>(); javas.add("%sEditActivity.java"); javas.add("%sEditFragment.java"); final ArrayList<String> xmls = new ArrayList<String>(); xmls.add("activity_%s_edit.xml"); xmls.add("fragment_%s_edit.xml"); for (final String java : javas) { this.makeSourceControler( String.format(java, TEMPLATE), String.format(java, entityName)); } for (final String xml : xmls) { this.makeResourceLayout( String.format(xml, LOWER_TEMPLATE), String.format(xml, entityName.toLowerCase(Locale.ENGLISH))); } this.updateManifest("EditActivity", entityName); TranslationMetadata.addDefaultTranslation( entityName.toLowerCase(Locale.ENGLISH) + "_error_edit", entityName + " edition error…;", Group.MODEL); } /** Create Action. * @param entityName The entity to generate * @throws IOException * @throws TemplateException */ protected final void generateCreateAction(final String entityName) { final ArrayList<String> javas = new ArrayList<String>(); javas.add("%sCreateActivity.java"); javas.add("%sCreateFragment.java"); final ArrayList<String> xmls = new ArrayList<String>(); xmls.add("activity_%s_create.xml"); xmls.add("fragment_%s_create.xml"); for (final String java : javas) { this.makeSourceControler( String.format(java, TEMPLATE), String.format(java, entityName)); } for (final String xml : xmls) { this.makeResourceLayout( String.format(xml, LOWER_TEMPLATE), String.format(xml, entityName.toLowerCase(Locale.ENGLISH))); } this.updateManifest("CreateActivity", entityName); TranslationMetadata.addDefaultTranslation( entityName.toLowerCase(Locale.ENGLISH) + "_error_create", entityName + " creation error…;", Group.MODEL); } /** Make Java Source Code. * * @param template Template path file. * For list activity is "TemplateListActivity.java" * @param filename The destination file name. */ private void makeSourceControler(final String template, final String filename) { final String fullFilePath = String.format("%s%s/%s", this.getAdapter().getSourcePath(), PackageUtils.extractPath(this.localNameSpace) .toLowerCase(Locale.ENGLISH), filename); final String fullTemplatePath = String.format("%s%s", this.getAdapter().getTemplateSourceControlerPath(), template); super.makeSource(fullTemplatePath, fullFilePath, false); } /** * Make Resource file. * * @param template Template path file. * @param filename Resource file. * prefix is type of view "row_" or "activity_" or "fragment_" with * postfix is type of action and extension file : * "_list.xml" or "_edit.xml". */ private void makeResourceLayout(final String template, final String filename) { final String fullFilePath = String.format("%s/%s", this.getAdapter().getRessourceLayoutPath(), filename); final String fullTemplatePath = String.format("%s/%s", this.getAdapter().getTemplateRessourceLayoutPath(), template); super.makeSource(fullTemplatePath, fullFilePath, false); } /** Make Manifest file. * * @param cfg Template engine * @throws IOException * @throws TemplateException */ public final void makeManifest(final Configuration cfg) throws IOException, TemplateException { final File file = TactFileUtils.makeFile(this.getAdapter().getManifestPathFile()); // Debug Log ConsoleUtils.displayDebug( "Generate Manifest : " + file.getAbsoluteFile()); // Create final Template tpl = cfg.getTemplate( this.getAdapter().getTemplateManifestPathFile()); final OutputStreamWriter output = new OutputStreamWriter( new FileOutputStream(file), TactFileUtils.DEFAULT_ENCODING); tpl.process(this.getDatamodel(), output); output.flush(); output.close(); } /** * Update Android Manifest. * @param classF The class file name * @param entityName the entity for which to update the manifest for. */ private void updateManifest(final String classF, final String entityName) { String classFile = entityName + classF; final String pathRelatif = String.format(".%s.%s.%s", this.getAdapter().getController(), entityName.toLowerCase(Locale.ENGLISH), classFile); // Debug Log ConsoleUtils.displayDebug("Update Manifest : " + pathRelatif); try { // Make engine final SAXBuilder builder = new SAXBuilder(); final File xmlFile = TactFileUtils.makeFile( this.getAdapter().getManifestPathFile()); // Load XML File final Document doc = builder.build(xmlFile); // Load Root element final Element rootNode = doc.getRootElement(); // Load Name space (required for manipulate attributes) final Namespace ns = rootNode.getNamespace("android"); // Find Application Node Element findActivity = null; // Find a element final Element applicationNode = rootNode.getChild("application"); if (applicationNode != null) { // Find Activity Node final List<Element> activities = applicationNode.getChildren("activity"); // Find many elements for (final Element activity : activities) { // Load attribute value if (activity.hasAttributes() && activity.getAttributeValue(NAME, ns) .equals(pathRelatif)) { findActivity = activity; break; } } // If not found Node, create it if (findActivity == null) { // Create new element findActivity = new Element("activity"); // Add Attributes to element findActivity.setAttribute(NAME, pathRelatif, ns); final Element findFilter = new Element("intent-filter"); final Element findAction = new Element("action"); final Element findCategory = new Element("category"); final Element findData = new Element("data"); // Add Child element findFilter.addContent(findAction); findFilter.addContent(findCategory); findFilter.addContent(findData); findActivity.addContent(findFilter); applicationNode.addContent(findActivity); } // Set values findActivity.setAttribute("label", "@string/app_name", ns); findActivity.setAttribute("exported", "false", ns); final Element filterActivity = findActivity.getChild("intent-filter"); if (filterActivity != null) { StringBuffer data = new StringBuffer(); String action = "VIEW"; if (pathRelatif.matches(".*List.*")) { data.append("vnd.android.cursor.collection/"); } else { data.append("vnd.android.cursor.item/"); if (pathRelatif.matches(".*Edit.*")) { action = "EDIT"; } else if (pathRelatif.matches(".*Create.*")) { action = "INSERT"; } } data.append( this.getAppMetas().getProjectNameSpace() .replace('/', '.')); data.append('.'); data.append(entityName); filterActivity.getChild("action").setAttribute( NAME, "android.intent.action." + action, ns); filterActivity.getChild("category").setAttribute( NAME, "android.intent.category.DEFAULT", ns); filterActivity.getChild("data").setAttribute( "mimeType", data.toString(), ns); } // Clean code applicationNode.sortChildren(new Comparator<Element>() { @Override public int compare(final Element o1, final Element o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); } // Write to File final XMLOutputter xmlOutput = new XMLOutputter(); // Make beautiful file with indent !!! xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, new OutputStreamWriter( new FileOutputStream(xmlFile.getAbsoluteFile()), TactFileUtils.DEFAULT_ENCODING)); } catch (final IOException io) { ConsoleUtils.displayError(io); } catch (final JDOMException e) { ConsoleUtils.displayError(e); } } /** * Update Widget. * @param widgetName The widget name. * @param layoutName The layout name. */ protected final void updateWidget(final String widgetName, final String layoutName) { super.makeSource( String.format("%s%s", this.getAdapter().getTemplateWidgetPath(), widgetName), String.format("%s%s", this.getAdapter().getWidgetPath(), widgetName), false); this.makeResourceLayout(layoutName, layoutName); } } diff --git a/src/com/tactfactory/mda/template/ProviderGenerator.java b/src/com/tactfactory/mda/template/ProviderGenerator.java index 6de516c5..51736bea 100644 --- a/src/com/tactfactory/mda/template/ProviderGenerator.java +++ b/src/com/tactfactory/mda/template/ProviderGenerator.java @@ -1,218 +1,218 @@ /** * This file is part of the Harmony package. * * (c) Mickael Gaillard <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package com.tactfactory.mda.template; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Comparator; import java.util.List; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import com.google.common.base.CaseFormat; import com.tactfactory.mda.meta.TranslationMetadata; import com.tactfactory.mda.meta.TranslationMetadata.Group; import com.tactfactory.mda.plateforme.BaseAdapter; import com.tactfactory.mda.utils.ConsoleUtils; import com.tactfactory.mda.utils.TactFileUtils; import com.tactfactory.mda.utils.PackageUtils; /** * The provider generator. * */ public class ProviderGenerator extends BaseGenerator { /** The local name space. */ private String localNameSpace; /** The provider name. */ private String nameProvider; /** * Constructor. * @param adapter The adapter to use. * @throws Exception */ public ProviderGenerator(final BaseAdapter adapter) throws Exception { super(adapter); this.nameProvider = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, this.getAppMetas().getName() + "Provider"); this.localNameSpace = this.getAppMetas().getProjectNameSpace().replace('/', '.') + "." + this.getAdapter().getProvider(); this.setDatamodel(this.getAppMetas().toMap(this.getAdapter())); this.getDatamodel().put( TagConstant.LOCAL_NAMESPACE, this.localNameSpace); } /** * Generate the provider. */ public final void generateProvider() { try { this.makeSourceProvider("TemplateProvider.java", this.nameProvider + ".java"); this.updateManifest(); TranslationMetadata.addDefaultTranslation( "uri_not_supported", "URI not supported", Group.PROVIDER); TranslationMetadata.addDefaultTranslation( "app_provider_name", "Provider of " + this.getAppMetas().getName(), Group.PROVIDER); TranslationMetadata.addDefaultTranslation( "app_provider_description", "Provider of " + this.getAppMetas().getName() + " for acces to data", Group.PROVIDER); new TranslationGenerator(this.getAdapter()).generateStringsXml(); } catch (final Exception e) { ConsoleUtils.displayError(e); } } /** * Make Java Source Code. * * @param template Template path file. * <br/>For list activity is "TemplateListActivity.java" * @param filename The destination file name */ private void makeSourceProvider(final String template, final String filename) { final String fullFilePath = String.format("%s%s/%s", this.getAdapter().getSourcePath(), PackageUtils.extractPath(this.localNameSpace) .toLowerCase(), filename); final String fullTemplatePath = String.format("%s%s", this.getAdapter().getTemplateSourceProviderPath(), template); super.makeSource(fullTemplatePath, fullFilePath, false); } /** * Update Android Manifest. */ private void updateManifest() { final String pathRelatif = String.format("%s.%s", this.localNameSpace, this.nameProvider); // Debug Log ConsoleUtils.displayDebug("Update Manifest : " + pathRelatif); try { // Make engine final SAXBuilder builder = new SAXBuilder(); final File xmlFile = TactFileUtils.makeFile( this.getAdapter().getManifestPathFile()); // Load XML File final Document doc = builder.build(xmlFile); // Load Root element final Element rootNode = doc.getRootElement(); // Load Name space (required for manipulate attributes) final Namespace ns = rootNode.getNamespace("android"); // Find Application Node Element findProvider = null; // Find a element final Element applicationNode = rootNode.getChild("application"); if (applicationNode != null) { // Find Activity Node final List<Element> providers = applicationNode.getChildren("provider"); // Find many elements for (final Element provider : providers) { if (provider.hasAttributes() && provider.getAttributeValue("name", ns) .equals(pathRelatif)) { // Load attribute value findProvider = provider; break; } } // If not found Node, create it if (findProvider == null) { // Create new element findProvider = new Element("provider"); // Add Attributes to element findProvider.setAttribute("name", pathRelatif, ns); applicationNode.addContent(findProvider); } // Set values findProvider.setAttribute("authorities", this.getAppMetas().getProjectNameSpace() - .replace('/', '.'), + .replace('/', '.') + "provider", ns); findProvider.setAttribute("label", "@string/app_provider_name", ns); findProvider.setAttribute("description", "@string/app_provider_description", ns); // Clean code applicationNode.sortChildren(new Comparator<Element>() { @Override public int compare(final Element o1, final Element o2) { return o1.getName().compareToIgnoreCase(o2.getName()); } }); } // Write to File final XMLOutputter xmlOutput = new XMLOutputter(); // Make beautiful file with indent !!! xmlOutput.setFormat(Format.getPrettyFormat()); xmlOutput.output(doc, new OutputStreamWriter( new FileOutputStream(xmlFile.getAbsoluteFile()), TactFileUtils.DEFAULT_ENCODING)); } catch (final IOException io) { ConsoleUtils.displayError(io); } catch (final JDOMException e) { ConsoleUtils.displayError(e); } } }
false
false
null
null
diff --git a/bundles/ParserZip/src/main/java/org/paxle/parser/zip/impl/ZipParser.java b/bundles/ParserZip/src/main/java/org/paxle/parser/zip/impl/ZipParser.java index 111cc429..3f96467b 100644 --- a/bundles/ParserZip/src/main/java/org/paxle/parser/zip/impl/ZipParser.java +++ b/bundles/ParserZip/src/main/java/org/paxle/parser/zip/impl/ZipParser.java @@ -1,83 +1,92 @@ /** * This file is part of the Paxle project. * Visit http://www.paxle.net for more information. * Copyright 2007-2009 the original author or authors. * * Licensed under the terms of the Common Public License 1.0 ("CPL 1.0"). * Any use, reproduction or distribution of this program constitutes the recipient's acceptance of this agreement. * The full license text is available under http://www.opensource.org/licenses/cpl1.0.txt * or in the file LICENSE.txt in the root directory of the Paxle distribution. * * Unless required by applicable law or agreed to in writing, this software is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package org.paxle.parser.zip.impl; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.paxle.core.doc.IParserDocument; import org.paxle.core.doc.ParserDocument; import org.paxle.core.io.IOTools; import org.paxle.parser.ISubParser; import org.paxle.parser.ParserContext; import org.paxle.parser.ParserException; import org.paxle.parser.iotools.SubParserDocOutputStream; /** * @scr.component * @scr.service interface="org.paxle.parser.ISubParser" * @scr.property name="MimeTypes" private="true" * values.1="application/zip" * values.2="application/x-zip" * values.3="application/x-zip-compressed" * values.4="application/java-archive" */ public class ZipParser implements ISubParser { public IParserDocument parse(URI location, String charset, InputStream is) throws ParserException, UnsupportedEncodingException, IOException { final ParserContext context = ParserContext.getCurrentContext(); final IParserDocument pdoc = new ParserDocument(); final ZipInputStream zis = new ZipInputStream(is); ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { if (ze.isDirectory()) continue; - final SubParserDocOutputStream sos = new SubParserDocOutputStream( - context.getTempFileManager(), - context.getCharsetDetector(), - pdoc, location, ze.getName(), ze.getSize()); + final long size = ze.getSize(); + final SubParserDocOutputStream sos; + if (size == -1) { + sos = new SubParserDocOutputStream( + context.getTempFileManager(), + context.getCharsetDetector(), + pdoc, location, ze.getName()); + } else { + sos = new SubParserDocOutputStream( + context.getTempFileManager(), + context.getCharsetDetector(), + pdoc, location, ze.getName(), size); + } try { - IOTools.copy(zis, sos, ze.getSize()); + IOTools.copy(zis, sos, size); // size == -1 is ok here } finally { try { sos.close(); } catch (IOException e) { if (e.getCause() instanceof ParserException) { throw (ParserException)e.getCause(); } else { throw e; } } } } pdoc.setStatus(IParserDocument.Status.OK); return pdoc; } public IParserDocument parse(URI location, String charset, File content) throws ParserException, UnsupportedEncodingException, IOException { final FileInputStream fis = new FileInputStream(content); try { return parse(location, charset, fis); } finally { fis.close(); } } }
false
true
public IParserDocument parse(URI location, String charset, InputStream is) throws ParserException, UnsupportedEncodingException, IOException { final ParserContext context = ParserContext.getCurrentContext(); final IParserDocument pdoc = new ParserDocument(); final ZipInputStream zis = new ZipInputStream(is); ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { if (ze.isDirectory()) continue; final SubParserDocOutputStream sos = new SubParserDocOutputStream( context.getTempFileManager(), context.getCharsetDetector(), pdoc, location, ze.getName(), ze.getSize()); try { IOTools.copy(zis, sos, ze.getSize()); } finally { try { sos.close(); } catch (IOException e) { if (e.getCause() instanceof ParserException) { throw (ParserException)e.getCause(); } else { throw e; } } } } pdoc.setStatus(IParserDocument.Status.OK); return pdoc; }
public IParserDocument parse(URI location, String charset, InputStream is) throws ParserException, UnsupportedEncodingException, IOException { final ParserContext context = ParserContext.getCurrentContext(); final IParserDocument pdoc = new ParserDocument(); final ZipInputStream zis = new ZipInputStream(is); ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { if (ze.isDirectory()) continue; final long size = ze.getSize(); final SubParserDocOutputStream sos; if (size == -1) { sos = new SubParserDocOutputStream( context.getTempFileManager(), context.getCharsetDetector(), pdoc, location, ze.getName()); } else { sos = new SubParserDocOutputStream( context.getTempFileManager(), context.getCharsetDetector(), pdoc, location, ze.getName(), size); } try { IOTools.copy(zis, sos, size); // size == -1 is ok here } finally { try { sos.close(); } catch (IOException e) { if (e.getCause() instanceof ParserException) { throw (ParserException)e.getCause(); } else { throw e; } } } } pdoc.setStatus(IParserDocument.Status.OK); return pdoc; }
diff --git a/org.eclipse.mylyn.java.tests/src/org/eclipse/mylyn/java/tests/ContextManagerTest.java b/org.eclipse.mylyn.java.tests/src/org/eclipse/mylyn/java/tests/ContextManagerTest.java index 66d34bd96..c257ba01a 100644 --- a/org.eclipse.mylyn.java.tests/src/org/eclipse/mylyn/java/tests/ContextManagerTest.java +++ b/org.eclipse.mylyn.java.tests/src/org/eclipse/mylyn/java/tests/ContextManagerTest.java @@ -1,407 +1,387 @@ /******************************************************************************* * Copyright (c) 2004 - 2005 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.java.tests; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPlugin; -import org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.mylar.core.AbstractRelationshipProvider; import org.eclipse.mylar.core.IMylarContext; import org.eclipse.mylar.core.IMylarContextListener; import org.eclipse.mylar.core.IMylarContextNode; import org.eclipse.mylar.core.IMylarStructureBridge; import org.eclipse.mylar.core.InteractionEvent; import org.eclipse.mylar.core.MylarPlugin; import org.eclipse.mylar.core.internal.MylarContext; import org.eclipse.mylar.core.internal.MylarContextManager; import org.eclipse.mylar.core.internal.ScalingFactors; import org.eclipse.mylar.core.tests.AbstractContextTest; import org.eclipse.mylar.core.tests.support.TestProject; import org.eclipse.mylar.java.JavaEditingMonitor; import org.eclipse.mylar.java.JavaStructureBridge; import org.eclipse.mylar.java.MylarJavaPlugin; -import org.eclipse.mylar.ui.InterestFilter; import org.eclipse.mylar.ui.actions.AbstractInterestManipulationAction; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.internal.Workbench; /** * @author Mik Kersten */ public class ContextManagerTest extends AbstractContextTest { protected MylarContextManager manager = MylarPlugin.getContextManager(); protected JavaEditingMonitor monitor = new JavaEditingMonitor(); - private InterestFilter filter; - private PackageExplorerPart explorer; - protected TestProject project1; protected IPackageFragment p1; protected IType type1; protected String taskId = "123"; protected MylarContext taskscape; protected ScalingFactors scaling = new ScalingFactors(); @Override protected void setUp() throws Exception { assertNotNull(MylarJavaPlugin.getDefault()); project1 = new TestProject("project1"); p1 = project1.createPackage("p1"); type1 = project1.createType(p1, "Type1.java", "public class Type1 { }" ); taskscape = new MylarContext("1", scaling); manager.contextActivated(taskscape); assertNotNull(MylarJavaPlugin.getDefault()); } @Override protected void tearDown() throws Exception { project1.dispose(); manager.contextDeleted(taskId, taskId); } class LandmarksModelListener implements IMylarContextListener { public int numAdditions = 0; public int numDeletions = 0; public void interestChanged(IMylarContextNode info) { // don't care about this event } public void landmarkAdded(IMylarContextNode element) { numAdditions++; } public void landmarkRemoved(IMylarContextNode element) { numDeletions++; } public void modelUpdated() { // don't care about this event } public void relationshipsChanged() { // don't care about this event } public void presentationSettingsChanging(UpdateKind kind) { // don't care about this event } public void presentationSettingsChanged(UpdateKind kind) { // don't care about this event } public void nodeDeleted(IMylarContextNode node) { // don't care about this event } public void interestChanged(List<IMylarContextNode> nodes) { // don't care about this event } public void contextActivated(IMylarContext taskscapeActivated) { // don't care about this event } public void contextDeactivated(IMylarContext taskscapeDeactivated) { // don't care about this event } } - public void testPatternMatch() { - assertFalse(filter.select(explorer.getTreeViewer(), null, type1)); - monitor.selectionChanged(PackageExplorerPart.getFromActivePerspective(), new StructuredSelection(type1)); - manager.contextActivated(taskscape); - - monitor.selectionChanged(PackageExplorerPart.getFromActivePerspective(), new StructuredSelection(type1)); - assertTrue(filter.select(explorer.getTreeViewer(), null, type1)); - -// filter.setExcludedMatches("*.java"); -// assertFalse(filter.select(explorer.getTreeViewer(), null, type1)); -// -// filter.setExcludedMatches("foo"); -// assertTrue(filter.select(explorer.getTreeViewer(), null, type1)); - } - public void testEdgeReset() throws CoreException, InterruptedException, InvocationTargetException { IWorkbenchPart part = Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActivePart(); IMethod m1 = type1.createMethod("public void m1() { }", null, true, null); IPackageFragment p2 = project1.createPackage("p2"); IType type2 = project1.createType(p2, "Type2.java", "public class Type2 { }" ); IMethod m2 = type2.createMethod("void m2() { }", null, true, null); assertTrue(m1.exists()); assertEquals(1, type1.getMethods().length); monitor.selectionChanged(part, new StructuredSelection(m1)); IMylarContextNode m1Node = MylarPlugin.getContextManager().getNode(m1.getHandleIdentifier()); assertTrue(m1Node.getDegreeOfInterest().isInteresting()); monitor.selectionChanged(part, new StructuredSelection(m2)); IMylarContextNode m2Node = MylarPlugin.getContextManager().getNode(m2.getHandleIdentifier()); manager.handleInteractionEvent(mockInterestContribution( m2.getHandleIdentifier(), scaling.getLandmark())); assertTrue(m2Node.getDegreeOfInterest().isLandmark()); AbstractRelationshipProvider provider = MylarJavaPlugin.getStructureBridge().getProviders().get(0); provider.createEdge(m2Node, m1Node.getStructureKind(), m2.getHandleIdentifier()); assertEquals(1, m2Node.getEdges().size()); manager.resetLandmarkRelationshipsOfKind(provider.getId()); assertEquals(0, m2Node.getEdges().size()); } public void testPredictedInterest() { IMylarContextNode node = MylarPlugin.getContextManager().getNode("doesn't exist"); assertFalse(node.getDegreeOfInterest().isInteresting()); assertFalse(node.getDegreeOfInterest().isPropagated()); } public void testErrorInterest() throws CoreException, InterruptedException, InvocationTargetException { IViewPart problemsPart = JavaPlugin.getActivePage().showView("org.eclipse.ui.views.ProblemView"); assertNotNull(problemsPart); IWorkbenchPart part = Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActivePart(); IMethod m1 = type1.createMethod("public void m1() { }", null, true, null); IPackageFragment p2 = project1.createPackage("p2"); IType type2 = project1.createType(p2, "Type2.java", "public class Type2 { }" ); IMethod m2 = type2.createMethod("void m2() { new p1.Type1().m1(); }", null, true, null); assertTrue(m1.exists()); assertEquals(1, type1.getMethods().length); monitor.selectionChanged(part, new StructuredSelection(m1)); IMylarContextNode m1Node = MylarPlugin.getContextManager().getNode(m1.getHandleIdentifier()); assertTrue(m1Node.getDegreeOfInterest().isInteresting()); // delete method to cause error m1.delete(true, null); assertEquals(0, type1.getMethods().length); project1.build(); IMarker[] markers = type2.getResource().findMarkers( IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, false, IResource.DEPTH_INFINITE); assertEquals(1, markers.length); String resourceHandle = new JavaStructureBridge().getHandleIdentifier(m2.getCompilationUnit()); assertTrue(MylarPlugin.getContextManager().getNode(resourceHandle).getDegreeOfInterest().isInteresting()); // put it back type1.createMethod("public void m1() { }", null, true, null); project1.build(); assertFalse(MylarPlugin.getContextManager().getNode(resourceHandle).getDegreeOfInterest().isInteresting()); } public void testParentInterestAfterDecay() throws JavaModelException { IWorkbenchPart part = Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActivePart(); IMethod m1 = type1.createMethod("void m1() { }", null, true, null); StructuredSelection sm1 = new StructuredSelection(m1); monitor.selectionChanged(part, sm1); IMylarContextNode node = MylarPlugin.getContextManager().getNode(m1.getHandleIdentifier()); assertTrue(node.getDegreeOfInterest().isInteresting()); IMylarStructureBridge bridge = MylarPlugin.getDefault().getStructureBridge(node.getStructureKind()); IMylarContextNode parent = MylarPlugin.getContextManager().getNode(bridge.getParentHandle(node.getElementHandle())); assertTrue(parent.getDegreeOfInterest().isInteresting()); assertTrue(parent.getDegreeOfInterest().isPropagated()); for (int i = 0; i < 1/(scaling.getDecay().getValue())*3; i++) { MylarPlugin.getContextManager().handleInteractionEvent(mockSelection()); } assertFalse(MylarPlugin.getContextManager().getNode(m1.getHandleIdentifier()).getDegreeOfInterest().isInteresting()); MylarPlugin.getContextManager().handleInteractionEvent(mockSelection(m1.getHandleIdentifier())); assertTrue(MylarPlugin.getContextManager().getNode(m1.getHandleIdentifier()).getDegreeOfInterest().isInteresting()); } public void testIncremenOfParentDoi() throws JavaModelException { IWorkbenchPart part = Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActivePart(); IMethod m1 = type1.createMethod("void m1() { }", null, true, null); StructuredSelection sm1 = new StructuredSelection(m1); monitor.selectionChanged(part, sm1); IMylarContextNode node = MylarPlugin.getContextManager().getNode(m1.getHandleIdentifier()); assertTrue(node.getDegreeOfInterest().isInteresting()); IJavaElement parent = m1.getParent(); int level = 1; do { level++; IMylarContextNode parentNode = MylarPlugin.getContextManager().getNode(parent.getHandleIdentifier()); // assertEquals(scaling.getParentPropagationIncrement(level), parentNode.getDegreeOfInterest().getValue()); assertEquals(node.getDegreeOfInterest().getValue(), parentNode.getDegreeOfInterest().getValue()); parent = parent.getParent(); } while (parent != null); } public void testExternalizationEquivalence() { } public void testLandmarks() throws CoreException, IOException { LandmarksModelListener listener = new LandmarksModelListener(); manager.addListener(listener); IWorkbenchPart part = Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActivePart(); IMethod m1 = type1.createMethod("void m1() { }", null, true, null); StructuredSelection sm1 = new StructuredSelection(m1); monitor.selectionChanged(part, sm1); manager.handleInteractionEvent(mockInterestContribution( m1.getHandleIdentifier(), scaling.getLandmark())); // packages can't be landmarks manager.handleInteractionEvent(mockInterestContribution( m1.getCompilationUnit().getParent().getHandleIdentifier(), scaling.getLandmark())); // source folders can't be landmarks manager.handleInteractionEvent(mockInterestContribution( m1.getCompilationUnit().getParent().getParent().getHandleIdentifier(), scaling.getLandmark())); // projects can't be landmarks manager.handleInteractionEvent(mockInterestContribution( m1.getCompilationUnit().getParent().getParent().getParent().getHandleIdentifier(), scaling.getLandmark())); assertEquals(1, MylarPlugin.getContextManager().getActiveLandmarks().size()); assertEquals(1, listener.numAdditions); manager.handleInteractionEvent(mockInterestContribution( m1.getHandleIdentifier(), -scaling.getLandmark())); assertEquals(1, listener.numDeletions); } public void testManipulation() throws JavaModelException { InterestManipulationAction action = new InterestManipulationAction(); IWorkbenchPart part = Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActivePart(); IMethod m1 = type1.createMethod("void m1() { }", null, true, null); StructuredSelection sm1 = new StructuredSelection(m1); monitor.selectionChanged(part, sm1); IMylarContextNode node = MylarPlugin.getContextManager().getNode(m1.getHandleIdentifier()); assertFalse(node.getDegreeOfInterest().isLandmark()); assertTrue(MylarPlugin.getContextManager().getActiveNode() != null); action.changeInterestForSelected(true); assertTrue(node.getDegreeOfInterest().isLandmark()); action.changeInterestForSelected(true); assertEquals(node.getDegreeOfInterest().getValue(), scaling.getLandmark() + scaling.get(InteractionEvent.Kind.SELECTION).getValue()); action.changeInterestForSelected(false); assertFalse(node.getDegreeOfInterest().isLandmark()); assertTrue(node.getDegreeOfInterest().isInteresting()); action.changeInterestForSelected(false); assertFalse(node.getDegreeOfInterest().isInteresting()); assertEquals(node.getDegreeOfInterest().getValue(), -scaling.get(InteractionEvent.Kind.SELECTION).getValue()); action.changeInterestForSelected(false); assertEquals(node.getDegreeOfInterest().getValue(), -scaling.get(InteractionEvent.Kind.SELECTION).getValue()); } class InterestManipulationAction extends AbstractInterestManipulationAction { @Override protected boolean isIncrement() { return true; } public void changeInterestForSelected(boolean increment) { super.manipulateInterestForNode(MylarPlugin.getContextManager().getActiveNode(), increment); } }; } // public void testDoiSelectionAndDecay() throws Exception { // listener.selectionChanged(explorer, selectionFoo); // // DoiInfo info = model.getDoi(typeFoo); // assertNotNull(info); // assertEquals( // TaskscapeManager.INCREMENT_SELECTION - TaskscapeManager.DECREMENET_DECAY, // model.getDoi(typeFoo).getValue(), // .1f); // // listener.selectionChanged(explorer, selectionFoo); // assertEquals( // TaskscapeManager.INCREMENT_SELECTION - TaskscapeManager.DECREMENET_DECAY, // model.getDoi(typeFoo).getValue(), // .1f); // // listener.selectionChanged(explorer, selectionBar); // assertEquals( // TaskscapeManager.INCREMENT_SELECTION - TaskscapeManager.DECREMENET_DECAY, // model.getDoi(typeBar).getValue(), // .1f); // // // listener.selectionChanged(explorer, selectionFoo); // assertEquals( // (2 * TaskscapeManager.INCREMENT_SELECTION) - (3 * TaskscapeManager.DECREMENET_DECAY), // model.getDoi(typeFoo).getValue(), // .1f); // } // public void testDoiElementPurge() { // listener.selectionChanged(explorer, selectionBar); // reset last selection // listener.selectionChanged(explorer, selectionBaz); // for (int i = 0; i < -1 * (TaskscapeManager.THRESHOLD_PURGE/TaskscapeManager.DECREMENET_DECAY); i += TaskscapeManager.INCREMENT_SELECTION) { // listener.selectionChanged(explorer, selectionFoo); // listener.selectionChanged(explorer, selectionBar); // assertNotNull(model.getDoi(typeFoo)); // } // assertNull(model.getDoi(typeBaz)); // } // public void testSessions() throws IOException, FileNotFoundException { // usage.clearUsageDataAndStore(); // UsageStore store = usage.getStore(); // store.getUsageFile().delete(); // // UsageSession session = new UsageSession(); // session.getCardinalStatistic(UsageSession.NUM_SELECTIONS_PATHFINDER).increment(); // session.getCardinalStatistic(UsageSession.NUM_SELECTIONS_PATHFINDER).increment(); // // String startTime = session.getTemporalStatistic(UsageSession.START_TIME).getTime(); // store.saveUsageData(session); // // List sessions = store.readUsageFile(store.getUsageFile()); // assertEquals(1, sessions.size()); // assertEquals(startTime, ((UsageSession)sessions.get(0)).getTemporalStatistic(UsageSession.START_TIME).getTime()); // assertEquals(2, ((UsageSession)sessions.get(0)).getCardinalStatistic(UsageSession.NUM_SELECTIONS_PATHFINDER).getCount()); // // // try { // Thread.sleep(1000); // to ensure that time is 1s off // } catch (InterruptedException e) { // e.printStackTrace(); // } // // UsageSession session2 = new UsageSession(); // session2.getCardinalStatistic(UsageSession.NUM_SELECTIONS_PATHFINDER).increment(); // String startTime2 = session2.getTemporalStatistic(UsageSession.START_TIME).getTime(); // store.saveUsageData(session2); // // List bothSessions = store.readUsageFile(store.getUsageFile()); // assertEquals(2, bothSessions.size()); // assertEquals(((UsageSession)bothSessions.get(1)).getTemporalStatistic(UsageSession.START_TIME).getTime(), startTime2); // // TaskscapeManager manager = new TaskscapeManager(); // UsageSession merged = usage.getGlobalMergedSession(); // assertEquals(3, merged.getCardinalStatistic(UsageSession.NUM_SELECTIONS_PATHFINDER).getCount()); // }
false
false
null
null
diff --git a/remote/server/src/java/org/openqa/selenium/remote/server/DefaultDriverSessions.java b/remote/server/src/java/org/openqa/selenium/remote/server/DefaultDriverSessions.java index 6c2ac54db..925e04855 100644 --- a/remote/server/src/java/org/openqa/selenium/remote/server/DefaultDriverSessions.java +++ b/remote/server/src/java/org/openqa/selenium/remote/server/DefaultDriverSessions.java @@ -1,100 +1,100 @@ /* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.remote.server; import org.openqa.selenium.Capabilities; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.SessionId; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class DefaultDriverSessions implements DriverSessions { private final DriverFactory factory; private final Map<SessionId, Session> sessionIdToDriver = new ConcurrentHashMap<SessionId, Session>(); private static Map<Capabilities, String> defaultDrivers = new HashMap<Capabilities, String>() {{ put(DesiredCapabilities.chrome(), "org.openqa.selenium.chrome.ChromeDriver"); put(DesiredCapabilities.firefox(), "org.openqa.selenium.firefox.FirefoxDriver"); put(DesiredCapabilities.htmlUnit(), "org.openqa.selenium.htmlunit.HtmlUnitDriver"); put(DesiredCapabilities.internetExplorer(), "org.openqa.selenium.ie.InternetExplorerDriver"); }}; public DefaultDriverSessions() { this(Platform.getCurrent(), new DriverFactory()); } protected DefaultDriverSessions(Platform runningOn, DriverFactory factory) { this.factory = factory; registerDefaults(runningOn); } private void registerDefaults(Platform current) { if (current.equals(Platform.ANDROID)){ registerDriver(DesiredCapabilities.android(), "org.openqa.selenium.android.AndroidDriver"); return; } for (Map.Entry<Capabilities, String> entry : defaultDrivers.entrySet()) { Capabilities caps = entry.getKey(); if (caps.getPlatform() != null && caps.getPlatform().is(current)) { registerDriver(caps, entry.getValue()); } else if (caps.getPlatform() == null) { registerDriver(caps, entry.getValue()); } } } private void registerDriver(Capabilities caps, String className) { try { registerDriver(caps, Class.forName(className).asSubclass(WebDriver.class)); } catch (ClassNotFoundException e) { // OK. Fall through. We just won't be able to create these } catch (NoClassDefFoundError e) { // OK. Missing a dependency, which is obviously a Bad Thing // TODO(simon): Log this! } } public SessionId newSession(Capabilities desiredCapabilities) throws Exception { - Session session = new Session(factory, desiredCapabilities); + Session session = Session.createSession(factory, desiredCapabilities); SessionId sessionId = new SessionId(String.valueOf(System.currentTimeMillis())); sessionIdToDriver.put(sessionId, session); return sessionId; } public Session get(SessionId sessionId) { return sessionIdToDriver.get(sessionId); } public void deleteSession(SessionId sessionId) { final Session removedSession = sessionIdToDriver.remove(sessionId); if (removedSession != null){ removedSession.close(); } } public void registerDriver(Capabilities capabilities, Class<? extends WebDriver> implementation) { factory.registerDriver(capabilities, implementation); } } diff --git a/remote/server/src/java/org/openqa/selenium/remote/server/Session.java b/remote/server/src/java/org/openqa/selenium/remote/server/Session.java index 7aae12506..ad19522e8 100644 --- a/remote/server/src/java/org/openqa/selenium/remote/server/Session.java +++ b/remote/server/src/java/org/openqa/selenium/remote/server/Session.java @@ -1,154 +1,158 @@ /* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.remote.server; import org.openqa.selenium.Capabilities; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Platform; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.browserlaunchers.CapabilityType; import org.openqa.selenium.html5.ApplicationCache; import org.openqa.selenium.html5.BrowserConnection; import org.openqa.selenium.html5.DatabaseStorage; import org.openqa.selenium.html5.LocationContext; import org.openqa.selenium.html5.WebStorage; import org.openqa.selenium.internal.FindsByCssSelector; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.events.EventFiringWebDriver; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class Session { private final EventFiringWebDriver driver; private final KnownElements knownElements; private final ThreadPoolExecutor executor; private final Capabilities capabilities; private volatile String base64EncodedImage; private final BrowserCreator browserCreator; + //This method is to avoid constructor escape of partially constructed session object + public static Session createSession(final DriverFactory factory, + final Capabilities capabilities) throws Exception { + Session session = new Session(factory, capabilities); + if (!session.browserCreator.isAndroid()){ + session.driver.register(new SnapshotScreenListener(session)); + } + return session; + } - - public Session(final DriverFactory factory, final Capabilities capabilities) throws Exception { + private Session(final DriverFactory factory, final Capabilities capabilities) throws Exception { this.knownElements = new KnownElements(); browserCreator = new BrowserCreator(factory, capabilities); final FutureTask<EventFiringWebDriver> webDriverFutureTask = new FutureTask<EventFiringWebDriver>(browserCreator); executor = new ThreadPoolExecutor(1, 1, 600L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); // Ensure that the browser is created on the single thread. this.driver = execute(webDriverFutureTask); this.capabilities = browserCreator.getCapabilityDescription(); } public void close(){ executor.shutdown(); } public <X> X execute(FutureTask<X> future) throws Exception { executor.execute(future); return future.get(); } public WebDriver getDriver() { return driver; } public KnownElements getKnownElements() { return knownElements; } public Capabilities getCapabilities() { return capabilities; } public void attachScreenshot(String base64EncodedImage) { this.base64EncodedImage = base64EncodedImage; } public String getAndClearScreenshot() { String temp = this.base64EncodedImage; base64EncodedImage = null; return temp; } private class BrowserCreator implements Callable<EventFiringWebDriver> { private final DriverFactory factory; private final Capabilities capabilities; private volatile Capabilities describedCapabilities; private volatile boolean isAndroid = false; BrowserCreator(DriverFactory factory, Capabilities capabilities) { this.factory = factory; this.capabilities = capabilities; } public EventFiringWebDriver call() throws Exception { WebDriver rawDriver = factory.newInstance(capabilities); Capabilities actualCapabilities = capabilities; if (rawDriver instanceof RemoteWebDriver) { actualCapabilities = ((RemoteWebDriver) rawDriver).getCapabilities(); isAndroid = actualCapabilities.getPlatform().is(Platform.ANDROID); } describedCapabilities = getDescription( rawDriver, actualCapabilities); - EventFiringWebDriver wrappedDriver = new EventFiringWebDriver(rawDriver); - if (!isAndroid) { - wrappedDriver.register(new SnapshotScreenListener(Session.this)); - } - return wrappedDriver; + return new EventFiringWebDriver(rawDriver); } public Capabilities getCapabilityDescription() { return describedCapabilities; } public boolean isAndroid() { return isAndroid; } private DesiredCapabilities getDescription(WebDriver instance, Capabilities capabilities) { DesiredCapabilities caps = new DesiredCapabilities(capabilities.asMap()); caps.setJavascriptEnabled(instance instanceof JavascriptExecutor); if (instance instanceof TakesScreenshot) { caps.setCapability(CapabilityType.TAKES_SCREENSHOT, true); } else if (instance instanceof DatabaseStorage) { caps.setCapability(CapabilityType.SUPPORTS_SQL_DATABASE, true); } else if (instance instanceof LocationContext) { caps.setCapability(CapabilityType.SUPPORTS_LOCATION_CONTEXT, true); } else if (instance instanceof ApplicationCache) { caps.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, true); } else if (instance instanceof BrowserConnection) { caps.setCapability(CapabilityType.SUPPORTS_BROWSER_CONNECTION, true); } else if (instance instanceof WebStorage) { caps.setCapability(CapabilityType.SUPPORTS_WEB_STORAGE, true); } if (instance instanceof FindsByCssSelector) { caps.setCapability(CapabilityType.SUPPORTS_FINDING_BY_CSS, true); } return caps; } } }
false
false
null
null
diff --git a/source/org/jivesoftware/smack/ServerTrustManager.java b/source/org/jivesoftware/smack/ServerTrustManager.java index 100125a7..3a788da1 100644 --- a/source/org/jivesoftware/smack/ServerTrustManager.java +++ b/source/org/jivesoftware/smack/ServerTrustManager.java @@ -1,375 +1,369 @@ /** * $RCSfile$ * $Revision: $ * $Date: $ * * Copyright 2003-2005 Jive Software. * Copyright 2001-2006 The Apache Software Foundation. * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.cert.CertPath; import java.security.cert.CertPathValidator; import java.security.cert.CertPathValidatorException; import java.security.cert.Certificate; import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; -import java.security.cert.CertificateNotYetValidException; import java.security.cert.CertificateParsingException; import java.security.cert.PKIXParameters; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.X509TrustManager; /** * Trust manager that checks all certificates presented by the server. This class * is used during TLS negotiation. It is possible to disable/enable some or all checkings * by configuring the {@link ConnectionConfiguration}. The truststore file that contains * knows and trusted CA root certificates can also be configure in {@link ConnectionConfiguration}. * * @author Gaston Dombiak */ class ServerTrustManager implements X509TrustManager { private static Pattern cnPattern = Pattern.compile("(?i)(cn=)([^,]*)"); - private ConnectionConfiguration configuration; - /** * Holds the domain of the remote server we are trying to connect */ private String server; private KeyStore trustStore; private boolean secureConnectionRequired; /** * @param secureConnectionRequired If true, the connection will be rejected if the certificate * can't be verified. If false, the connection will be allowed, but isSecureConnection will * return false. */ public ServerTrustManager(String server, ConnectionConfiguration configuration, boolean secureConnectionRequired) throws XMPPException { - this.configuration = configuration; this.server = server; this.secureConnectionRequired = secureConnectionRequired; try { trustStore = getKeyStore(configuration.getTruststorePath(), configuration.getTruststoreType(), configuration.getTruststorePassword()); } catch (RuntimeException e) { throw e; } // don't catch unchecked exceptions below catch (Exception e) { if(secureConnectionRequired) throw new XMPPException("Error creating keystore", e); // If a secure connection isn't required anyway, just clear trustStore. trustStore = null; } } private static InputStream getTruststoreStream(String path) throws IOException { // If an explicit path was specified, only use it. if(path != null) return new FileInputStream(path); // If an explicit root certificate path isn't specified, search for one // using the paths described here: // http://download.oracle.com/javase/1,5.0/docs/guide/security/jsse/JSSERefGuide.html String javaHome = System.getProperty("java.home"); String[] defaultTruststorePaths = { System.getProperty("javax.net.ssl.trustStore"), javaHome + "/lib/security/jssecacerts", javaHome + "/lib/security/cacerts" }; for(String candidate: Arrays.asList(defaultTruststorePaths)) { if(candidate == null) continue; try { return new FileInputStream(candidate); } catch(IOException e) { // Ignore and keep searching. } } throw new IOException("No truststore path located"); } /* Loading the keystore can take some time (almost a second) on slower systems, * so load it the first time we need it and then cache it. The keystore we load * depends on the configuration. */ private static class KeyStoreCacheParams { public String path, type, password; public boolean equals(Object rhs) { if(!(rhs instanceof KeyStoreCacheParams)) return false; KeyStoreCacheParams rhsParams = (KeyStoreCacheParams) rhs; return path == rhsParams.path && type == rhsParams.type && password == rhsParams.password; } public int hashCode() { int hash = 0; if(path != null) hash += path.hashCode(); if(type != null) hash += type.hashCode(); if(password != null) hash += password.hashCode(); return hash; } }; private static HashMap<KeyStoreCacheParams, KeyStore> trustStoreCache = new HashMap<KeyStoreCacheParams, KeyStore>(); /** Load a KeyStore of root certificates from disk, caching the result. */ private static synchronized KeyStore getKeyStore(String path, String type, String password) throws Exception { KeyStoreCacheParams params = new KeyStoreCacheParams(); params.path = path; params.type = type; params.password = password; KeyStore trustStore = trustStoreCache.get(params); if(trustStore != null) return trustStore; InputStream in = null; try { in = new BufferedInputStream(getTruststoreStream(path)); trustStore = KeyStore.getInstance(type); trustStore.load(in, password != null? password.toCharArray():null); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { // Ignore. } } } trustStoreCache.put(params, trustStore); return trustStore; } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } public void checkServerTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException { // If a secure connection isn't required, don't perform checks here. The caller // can still run certificate checks separately, using SSLSession.getPeerCertificates // and calling checkCertificates directly. // // This is important, because if the caller only wants to display warnings on // insecure connections and not prevent using encryption entirely, we must not // throw an exception here, or getPeerCertificates will refuse to tell what the // certificates are. if(!secureConnectionRequired) return; checkCertificates(x509Certificates); } public void checkCertificates(X509Certificate[] x509Certificates) throws CertificateException { List<X509Certificate> certList = new ArrayList<X509Certificate>(); for(int i = 0; i < x509Certificates.length; ++i) certList.add(x509Certificates[i]); CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertPath certPath = cf.generateCertPath(certList); List<String> peerIdentities = getPeerIdentity(x509Certificates[0]); if(!hostMatchesCertificate(peerIdentities, server)) { CertPathValidatorException e = new CertPathValidatorException("Hostname verification failed", null, certPath, 0); throw new CertificateException(e); } try { PKIXParameters params = new PKIXParameters(trustStore); // Work around "No CRLs found for issuer" being thrown for every certificate. params.setRevocationEnabled(false); CertPathValidator validator = CertPathValidator.getInstance("PKIX"); validator.validate(certPath, params); } catch (GeneralSecurityException e) { throw new CertificateException(e); } } // Parts of the following based on org.apache.http: static boolean hostMatchesCertificate(List<String> peerIdentities, String fqdn) { for(String identity: peerIdentities) { boolean doWildcard = identity.startsWith("*.") && countDots(identity) >= 2 && // never allow *.com acceptableCountryWildcard(identity) && !isIPv4Address(fqdn); if (doWildcard) { // Remove the wildcard String peerIdentity = peerIdentities.get(0).substring(1); // Check if the requested subdomain matches the certified domain if (fqdn.endsWith(peerIdentity) && countDots(peerIdentity) == countDots(fqdn)) return true; } else if(fqdn.equals(identity)) { return true; } } return false; } private final static String[] BAD_COUNTRY_2LDS = { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info", "lg", "ne", "net", "or", "org" }; private static boolean acceptableCountryWildcard(String cn) { int cnLen = cn.length(); if(cnLen >= 7 && cnLen <= 9) { // Look for the '.' in the 3rd-last position: if(cn.charAt(cnLen - 3) == '.') { // Trim off the [*.] and the [.XX]. String s = cn.substring(2, cnLen - 3); // And test against the sorted array of bad 2lds: int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s); return x < 0; } } return true; } private static final Pattern IPV4_PATTERN = Pattern.compile( "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"); private static boolean isIPv4Address(final String input) { return IPV4_PATTERN.matcher(input).matches(); } /** * Counts the number of dots "." in a string. * @param s string to count dots from * @return number of dots */ public static int countDots(final String s) { int count = 0; for(int i = 0; i < s.length(); i++) { if(s.charAt(i) == '.') count++; } return count; } /** * Verify a certificate chain. On success, return normally. On verification failure, * throws {@link CertificateExceptionDetail}. */ public void checkCertificates(Certificate[] certificates) throws CertificateException { X509Certificate[] x509Certificates; try { x509Certificates = new X509Certificate[certificates.length]; for(int i = 0; i < certificates.length; ++i) { X509Certificate cert = (X509Certificate) certificates[i]; x509Certificates[i] = cert; } } catch(ClassCastException e) { // One of the certificates wasn't an X509Certificate. Assume the connection // is insecure. throw new CertificateException("Received a non-X509 certificate", e); } checkCertificates(x509Certificates); } /** * @param x509Certificate the certificate the holds the identity of the remote server. * @return the identity of the remote server as defined in the specified certificate. */ public static List<String> getPeerIdentity(X509Certificate x509Certificate) { // Look the identity in the subjectAltName extension if available List<String> names = new Vector<String>(); String name = x509Certificate.getSubjectDN().getName(); Matcher matcher = cnPattern.matcher(name); if (matcher.find()) { name = matcher.group(2); } names.add(name); names.addAll(getSubjectAlternativeNames(x509Certificate)); return names; } /** * Returns the JID representation of an XMPP entity contained as a SubjectAltName extension * in the certificate. If none was found then return <tt>null</tt>. * * @param certificate the certificate presented by the remote entity. * @return the JID representation of an XMPP entity contained as a SubjectAltName extension * in the certificate. If none was found then return <tt>null</tt>. */ private static List<String> getSubjectAlternativeNames(X509Certificate certificate) { Collection<List<?>> altNames; try { altNames = certificate.getSubjectAlternativeNames(); } catch (CertificateParsingException e) { e.printStackTrace(); return Collections.emptyList(); } // Check that the certificate includes the SubjectAltName extension if (altNames == null) return Collections.emptyList(); List<String> identities = new ArrayList<String>(); // Use the type OtherName to search for the certified server name for (List item: altNames) { Integer type = (Integer) item.get(0); if (type == 2) { String s = (String) item.get(1); identities.add(s); } } return identities; } }
false
false
null
null
diff --git a/src/test/de/fzi/cjunit/jpf/util/ExceptionFactoryTest.java b/src/test/de/fzi/cjunit/jpf/util/ExceptionFactoryTest.java index 4d2e18f..109f94b 100644 --- a/src/test/de/fzi/cjunit/jpf/util/ExceptionFactoryTest.java +++ b/src/test/de/fzi/cjunit/jpf/util/ExceptionFactoryTest.java @@ -1,88 +1,88 @@ /* * This file is covered by the terms of the Common Public License v1.0. * * Copyright (c) SZEDER Gábor * * Parts of this software were developed within the JEOPARD research * project, which received funding from the European Union's Seventh * Framework Programme under grant agreement No. 216682. */ package de.fzi.cjunit.jpf.util; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import org.junit.Test; +import java.lang.reflect.Constructor; + import de.fzi.cjunit.jpf.exceptioninfo.ExceptionInfoDefaultImpl; import de.fzi.cjunit.testutils.TestException; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; public class ExceptionFactoryTest { @Test public void createExceptionHandlesNull() throws Throwable { assertThat(new ExceptionFactory().createException(null), equalTo(null)); } @Test public void testGetCheckedConstructorReturnConstructor() { Constructor<?> constructor = new ExceptionFactory().getCheckedConstructor( Throwable.class, String.class); assertThat(constructor, not(nullValue())); Class<?> declaringClass = constructor.getDeclaringClass(); assertThat(declaringClass.equals(Throwable.class), equalTo(true)); assertThat(constructor.getParameterTypes().length, equalTo(1)); Class<?> parameterType = constructor.getParameterTypes()[0]; assertThat(parameterType.equals(String.class), equalTo(true)); } @Test public void testGetCheckedConstructorReturnNull() { Constructor<?> constructor = new ExceptionFactory().getCheckedConstructor( Object.class, String.class); assertThat(constructor, nullValue()); } @Test public void testGetExceptionConstructorFindStringConstructor() { Constructor<?> constructor = new ExceptionFactory() .getExceptionConstructor(Exception.class); assertThat(constructor, not(nullValue())); assertThat(constructor.getParameterTypes().length, equalTo(1)); Class<?> parameterType = constructor.getParameterTypes()[0]; assertThat(parameterType.equals(String.class), equalTo(true)); } @Test public void testGetExceptionConstructorFindObjectConstructor() { Constructor<?> constructor = new ExceptionFactory() .getExceptionConstructor(AssertionError.class); assertThat(constructor, not(nullValue())); assertThat(constructor.getParameterTypes().length, equalTo(1)); Class<?> parameterType = constructor.getParameterTypes()[0]; assertThat(parameterType.equals(Object.class), equalTo(true)); } @Test(expected=NoSuchMethodException.class) public void testExceptionOnNonExistingConstructor() throws Throwable { ExceptionFactory ef = new ExceptionFactory() { @Override protected Constructor<?> getExceptionConstructor( Class<?> exceptionClass) { return null; } }; ef.createException(new ExceptionInfoDefaultImpl(new TestException())); } }
false
false
null
null
diff --git a/core/src/test/java/com/predic8/membrane/core/interceptor/authentication/BasicAuthenticationInterceptorIntegrationTest.java b/core/src/test/java/com/predic8/membrane/core/interceptor/authentication/BasicAuthenticationInterceptorIntegrationTest.java index 5ec58e82..058187ad 100644 --- a/core/src/test/java/com/predic8/membrane/core/interceptor/authentication/BasicAuthenticationInterceptorIntegrationTest.java +++ b/core/src/test/java/com/predic8/membrane/core/interceptor/authentication/BasicAuthenticationInterceptorIntegrationTest.java @@ -1,68 +1,69 @@ /* Copyright 2011, 2012 predic8 GmbH, www.predic8.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.predic8.membrane.core.interceptor.authentication; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.predic8.membrane.core.HttpRouter; import com.predic8.membrane.core.interceptor.authentication.BasicAuthenticationInterceptor.User; import com.predic8.membrane.core.rules.Rule; import com.predic8.membrane.core.rules.ServiceProxy; import com.predic8.membrane.core.rules.ServiceProxyKey; import com.predic8.membrane.test.AssertUtils; public class BasicAuthenticationInterceptorIntegrationTest { private HttpRouter router = new HttpRouter(); @Before public void setup() throws Exception { Rule rule = new ServiceProxy(new ServiceProxyKey("localhost", "*", ".*", 3001), "thomas-bayer.com", 80); router.getRuleManager().addProxyAndOpenPortIfNew(rule); BasicAuthenticationInterceptor interceptor = new BasicAuthenticationInterceptor(); List<User> users = new ArrayList<BasicAuthenticationInterceptor.User>(); users.add(new BasicAuthenticationInterceptor.User("admin", "admin")); interceptor.setUsers(users ); router.addUserFeatureInterceptor(interceptor); router.init(); } @Test public void testDeny() throws Exception { + AssertUtils.disableHTTPAuthentication(); AssertUtils.getAndAssert(401, "http://localhost:3001/axis2/services/BLZService?wsdl"); } @Test public void testAccept() throws Exception { AssertUtils.setupHTTPAuthentication("localhost", 3001, "admin", "admin"); AssertUtils.getAndAssert200("http://localhost:3001/axis2/services/BLZService?wsdl"); } @After public void teardown() throws IOException { AssertUtils.closeConnections(); router.shutdown(); } }
true
false
null
null
diff --git a/addon-web-mvc-datatables/src/main/java/org/gvnix/addon/datatables/DatatablesMetadata.java b/addon-web-mvc-datatables/src/main/java/org/gvnix/addon/datatables/DatatablesMetadata.java index eed46f3d..0ef2487e 100644 --- a/addon-web-mvc-datatables/src/main/java/org/gvnix/addon/datatables/DatatablesMetadata.java +++ b/addon-web-mvc-datatables/src/main/java/org/gvnix/addon/datatables/DatatablesMetadata.java @@ -1,2716 +1,2716 @@ /* * gvNIX. Spring Roo based RAD tool for Generalitat Valenciana * Copyright (C) 2013 Generalitat Valenciana * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/copyleft/gpl.html>. */ package org.gvnix.addon.datatables; import static org.gvnix.addon.datatables.DatatablesConstants.*; import static org.springframework.roo.model.JdkJavaType.LIST; import static org.springframework.roo.model.SpringJavaType.MODEL; import static org.springframework.roo.model.SpringJavaType.MODEL_ATTRIBUTE; import static org.springframework.roo.model.SpringJavaType.REQUEST_MAPPING; import static org.springframework.roo.model.SpringJavaType.RESPONSE_BODY; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.builder.ToStringBuilder; import org.gvnix.addon.jpa.query.JpaQueryMetadata; import org.gvnix.addon.web.mvc.batch.WebJpaBatchMetadata; import org.gvnix.support.WebItdBuilderHelper; import org.springframework.roo.addon.finder.FieldToken; import org.springframework.roo.addon.finder.ReservedToken; import org.springframework.roo.addon.finder.Token; import org.springframework.roo.addon.web.mvc.controller.details.DateTimeFormatDetails; import org.springframework.roo.addon.web.mvc.controller.details.FinderMetadataDetails; import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold; import org.springframework.roo.addon.web.mvc.controller.scaffold.WebScaffoldAnnotationValues; import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.FieldMetadata; import org.springframework.roo.classpath.details.FieldMetadataBuilder; import org.springframework.roo.classpath.details.MemberFindingUtils; import org.springframework.roo.classpath.details.MethodMetadata; import org.springframework.roo.classpath.details.MethodMetadataBuilder; import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType; import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder; import org.springframework.roo.classpath.details.annotations.StringAttributeValue; import org.springframework.roo.classpath.details.comments.CommentStructure; import org.springframework.roo.classpath.details.comments.JavadocComment; import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem; import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder; import org.springframework.roo.classpath.scanner.MemberDetails; import org.springframework.roo.metadata.MetadataIdentificationUtils; import org.springframework.roo.model.DataType; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.project.LogicalPath; import org.springframework.roo.support.logging.HandlerUtils; /** * {@link GvNIXDatatables} metadata * * @author gvNIX Team * @since 1.1.0 */ public class DatatablesMetadata extends AbstractItdTypeDetailsProvidingMetadataItem { @SuppressWarnings("unused") private static final Logger LOGGER = HandlerUtils .getLogger(DatatablesMetadata.class); // Constants private static final String PROVIDES_TYPE_STRING = DatatablesMetadata.class .getName(); private static final String PROVIDES_TYPE = MetadataIdentificationUtils .create(PROVIDES_TYPE_STRING); public static final String getMetadataIdentiferType() { return PROVIDES_TYPE; } public static final String createIdentifier(JavaType javaType, LogicalPath path) { return PhysicalTypeIdentifierNamingUtils.createIdentifier( PROVIDES_TYPE_STRING, javaType, path); } public static final JavaType getJavaType(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getJavaType( PROVIDES_TYPE_STRING, metadataIdentificationString); } public static final LogicalPath getPath(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.getPath(PROVIDES_TYPE_STRING, metadataIdentificationString); } public static boolean isValid(String metadataIdentificationString) { return PhysicalTypeIdentifierNamingUtils.isValid(PROVIDES_TYPE_STRING, metadataIdentificationString); } /** * Annotation values */ private final DatatablesAnnotationValues annotationValues; /** * Entity property which is its identifier (as roo only use one property, * this includes the embedded pks) */ private final FieldMetadata entityIdentifier; /** * Related entity */ private final JavaType entity; /** * Related entity member details */ private final MemberDetails entityMemberDetails; /** * Entity name to use in var names */ private final String entityName; /** * Related entity plural */ private final String entityPlural; /** * If related entity has date properties */ private final Map<JavaSymbolName, DateTimeFormatDetails> entityDatePatterns; /** * Method name to get entity manager from entity class */ private final JavaSymbolName entityEntityManagerMethod; /** * Batch services metadata */ private final WebJpaBatchMetadata webJpaBatchMetadata; /** * Jpa Query metadata */ private final JpaQueryMetadata jpaQueryMetadata; /** * Field which holds conversionService */ private FieldMetadata conversionService; /** * Itd builder herlper */ private WebItdBuilderHelper helper; private final WebScaffoldAnnotationValues webScaffoldAnnotationValues; /** * Information about finders */ private final Map<FinderMetadataDetails, QueryHolderTokens> findersRegistered; /** * Name to use for findAll method (name includes entity plurar) */ private final JavaSymbolName findAllMethodName; /** * Name to use for renderItem method (name includes entity plural) */ private final JavaSymbolName renderItemsMethodName; /** * Name to use for findByParamters method (name includes entity plural) */ private final JavaSymbolName findByParametersMethodName; /** * JavaType for List entity elements */ private final JavaType entityListType; public DatatablesMetadata(String identifier, JavaType aspectName, PhysicalTypeMetadata governorPhysicalTypeMetadata, DatatablesAnnotationValues annotationValues, JavaType entity, MemberDetails entityMemberDetails, List<FieldMetadata> identifierProperties, String entityPlural, JavaSymbolName entityManagerMethodName, Map<JavaSymbolName, DateTimeFormatDetails> datePatterns, JavaType webScaffoldAspectName, WebJpaBatchMetadata webJpaBatchMetadata, JpaQueryMetadata jpaQueryMetadata, WebScaffoldAnnotationValues webScaffoldAnnotationValues, Map<FinderMetadataDetails, QueryHolderTokens> findersRegistered) { super(identifier, aspectName, governorPhysicalTypeMetadata); Validate.isTrue(isValid(identifier), "Metadata identification string '" + identifier + "' does not appear to be a valid"); this.annotationValues = annotationValues; this.helper = new WebItdBuilderHelper(this, builder.getImportRegistrationResolver()); // Roo only uses one property this.entityIdentifier = identifierProperties.get(0); this.entity = entity; this.entityMemberDetails = entityMemberDetails; this.entityName = JavaSymbolName.getReservedWordSafeName(entity) .getSymbolName(); this.entityPlural = entityPlural; this.entityEntityManagerMethod = entityManagerMethodName; this.entityDatePatterns = datePatterns; this.webJpaBatchMetadata = webJpaBatchMetadata; this.jpaQueryMetadata = jpaQueryMetadata; this.webScaffoldAnnotationValues = webScaffoldAnnotationValues; // Prepare method names which includes entity plural this.findAllMethodName = new JavaSymbolName( "findAll".concat(StringUtils.capitalize(entityPlural))); this.renderItemsMethodName = new JavaSymbolName( "render".concat(StringUtils.capitalize(entityPlural))); this.findByParametersMethodName = new JavaSymbolName("find".concat( StringUtils.capitalize(entityPlural)).concat("ByParameters")); this.entityListType = new JavaType(LIST.getFullyQualifiedTypeName(), 0, DataType.TYPE, null, Arrays.asList(entity)); // store finders information if (findersRegistered != null) { this.findersRegistered = Collections .unmodifiableMap(findersRegistered); } else { this.findersRegistered = null; } // Adding precedence declaration // This aspect before webScaffold builder.setDeclarePrecedence(aspectName, webScaffoldAspectName); // Adding field definition builder.addField(getConversionServiceField()); // Adding methods builder.addMethod(getListDatatablesRequestMethod()); builder.addMethod(getPopulateDatatablesConfig()); builder.addMethod(getListRooRequestMethod()); builder.addMethod(getPopulateParameterMapMethod()); builder.addMethod(getGetPropertyMapMethod()); // Detail methods builder.addMethod(getListDatatablesDetailMethod()); builder.addMethod(getCreateDatatablesDetailMethod()); builder.addMethod(getUpdateDatatablesDetailMethod()); builder.addMethod(getDeleteDatatablesDetailMethod()); // Add AJAX mode required methods if (isAjax()) { if (isStantardMode()) { builder.addMethod(getFindAllMethod()); } else { // Render mode requires this methods builder.addMethod(getPopulateItemForRenderMethod()); builder.addMethod(getRenderItemsMethod()); builder.addMethod(getFindAllMethodRenderMode()); } // add ajax request for finders if (this.findersRegistered != null) { for (Entry<FinderMetadataDetails, QueryHolderTokens> finder : this.findersRegistered .entrySet()) { builder.addMethod(getAjaxFinderMethod(finder.getKey(), finder.getValue())); } } } else if (!isStantardMode()) { // Non-Standard view mode requires AJAX data mode throw new IllegalArgumentException(aspectName .getFullyQualifiedTypeName() .concat(".@GvNIXDatatables: 'mode = ") .concat(annotationValues.getMode()) .concat("' requires 'ajax = true'")); } else { // DOM standard mode requires finder by parameters builder.addMethod(getFindByParametersMethod()); } // Create a representation of the desired output ITD itdTypeDetails = builder.build(); } /** * Gets <code>renderXXX</code> method. <br> * This method renders the required jspx for item an store it in a List of * Map(String,String) * * @return */ private MethodMetadata getRenderItemsMethod() { JavaType entitySearchResult = new JavaType( SEARCH_RESULTS.getFullyQualifiedTypeName(), 0, DataType.TYPE, null, Arrays.asList(entity)); // Define method parameter types List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType .convertFromJavaTypes(entitySearchResult, HTTP_SERVLET_REQUEST, HTTP_SERVLET_RESPONSE); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(renderItemsMethodName, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); throwsTypes.add(SERVLET_EXCEPTION); throwsTypes.add(IO_EXCEPTION); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(new JavaSymbolName("searchResult")); parameterNames.add(REQUEST_PARAM_NAME); parameterNames.add(RESPONSE_PARAM_NAME); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); buildRenderItemsMethodBody(bodyBuilder); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, renderItemsMethodName, LIST_MAP_STRING_STRING, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Builds the method body of <code>renderXXX</code> method. <br> * This method renders the required jspx for item an store it in a List of * Map(String,String) * * @param bodyBuilder */ private void buildRenderItemsMethodBody( InvocableMemberBodyBuilder bodyBuilder) { String entityTypeName = helper.getFinalTypeName(entity); bodyBuilder.appendFormalLine(""); bodyBuilder.appendFormalLine("// Prepare result"); String entityListVar = StringUtils.uncapitalize(entityPlural); /* * List<Pets> pets = searchResult.getResults(); */ bodyBuilder.appendFormalLine(String.format( "%s %s = searchResult.getResults();", helper.getFinalTypeName(entityListType), entityListVar)); /* * List<Map<String, String>> result = new ArrayList<Map<String, * String>>(); */ bodyBuilder.appendFormalLine(String.format( "%s result = new %s(%s.size());", helper.getFinalTypeName(LIST_MAP_STRING_STRING), helper.getFinalTypeName(ARRAYLIST_MAP_STRING_STRING), entityListVar)); bodyBuilder.appendFormalLine(String.format( "String controllerPath = \"%s\";", webScaffoldAnnotationValues.getPath())); bodyBuilder.appendFormalLine(String.format( "String pageToUse = \"%s\";", annotationValues.getMode())); bodyBuilder .appendFormalLine("String renderUrl = String.format(\"/WEB-INF/views/%s/%s.jspx\", controllerPath, pageToUse);"); bodyBuilder.appendFormalLine(""); bodyBuilder.appendFormalLine("// For every element"); // for (Pet pet : owners) { bodyBuilder.appendFormalLine(String.format("for (%s %s: %s) {", entityTypeName, entityName, entityListVar)); bodyBuilder.indent(); // Map<String, String> row = new HashMap<String, String>(); bodyBuilder.appendFormalLine(String.format("%s item = new %s();", helper.getFinalTypeName(MAP_STRING_STRING), helper.getFinalTypeName(HASHMAP_STRING_STRING))); // final StringWriter buffer = new StringWriter(); bodyBuilder.appendFormalLine(String.format( "final %s buffer = new %s();", helper.getFinalTypeName(STRING_WRITER), helper.getFinalTypeName(STRING_WRITER))); // TODO Check it can get dispatcher outside of for bodyBuilder.appendFormalLine("// Call JSP to render current entity"); // RequestDispatcher dispatcher = // request.getRequestDispatcher("/WEB-INF/views/owners/show.jspx"); bodyBuilder.appendFormalLine(String.format( "%s dispatcher = %s.getRequestDispatcher(renderUrl);", helper.getFinalTypeName(REQUEST_DISPATCHER), REQUEST_PARAM_NAME.getSymbolName())); bodyBuilder.appendFormalLine(""); // populateItemForRender(request, pet); bodyBuilder.appendFormalLine(String.format( "populateItemForRender(%s, %s);", REQUEST_PARAM_NAME.getSymbolName(), entityName)); // dispatcher.include(request, new HttpServletResponseWrapper(response) // { bodyBuilder.appendFormalLine(String.format( "dispatcher.include(%s, new %s(%s) {", REQUEST_PARAM_NAME.getSymbolName(), helper.getFinalTypeName(HTTP_SERVLET_RESPONSE_WRAPPER), RESPONSE_PARAM_NAME.getSymbolName())); bodyBuilder.indent(); // private PrintWriter writer = new PrintWriter(buffer); bodyBuilder.appendFormalLine(String.format( "private %s writer = new %s(buffer);", helper.getFinalTypeName(PRINT_WRITER), helper.getFinalTypeName(PRINT_WRITER))); // @Override bodyBuilder.appendFormalLine("@Override"); // public PrintWriter getWriter() throws IOException { bodyBuilder.appendFormalLine(String.format( "public %s getWriter() throws %s {", helper.getFinalTypeName(PRINT_WRITER), helper.getFinalTypeName(IO_EXCEPTION))); bodyBuilder.indent(); // return writer; bodyBuilder.appendFormalLine("return writer;"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("});"); bodyBuilder.appendFormalLine(""); // String render = buffer.toString(); bodyBuilder.appendFormalLine("String render = buffer.toString();"); bodyBuilder.appendFormalLine("// Load item id)"); // row.put("DT_RowId", // conversionService_datatables.convert(owner.getId(), String.class)); bodyBuilder .appendFormalLine(String .format("item.put(\"DT_RowId\", %s.convert(%s.get%s(), String.class));", getConversionServiceField().getFieldName() .getSymbolName(), entityName, StringUtils.capitalize(entityIdentifier .getFieldName().getSymbolName()))); bodyBuilder .appendFormalLine("// Put rendered content into first column (uses column index)"); // row.put(Integer.toString(rowIdx), showOwner); bodyBuilder.appendFormalLine("item.put(\"0\", render);"); bodyBuilder.appendFormalLine(""); bodyBuilder.appendFormalLine("result.add(item);"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(""); bodyBuilder.appendFormalLine("return result;"); } /** * Gets <code>getFindByParameters</code> method. <br> * This method generates a item List based on a parameters received in the * request. Used by DOM mode listDatatables. * * @return */ private MethodMetadata getFindByParametersMethod() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType .convertFromJavaTypes(entity, ENUMERATION_STRING); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(findByParametersMethodName, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(new JavaSymbolName(entityName)); parameterNames.add(new JavaSymbolName("propertyNames")); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); buildFindByParametersMapMethodBody(bodyBuilder); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, findByParametersMethodName, entityListType, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Builds body method for <code>getFindByParameters</code> method. <br> * This method generates a item List based on a parameters received in the * request. Used by DOM mode listDatatables. * * @param bodyBuilder */ private void buildFindByParametersMapMethodBody( InvocableMemberBodyBuilder bodyBuilder) { // Gets propertyMap bodyBuilder.appendFormalLine("// Gets propertyMap"); // Map<String, Object> propertyMap = getPropertyMap(visit, // propertyNames); bodyBuilder.appendFormalLine(String.format( "%s propertyMap = %s(%s, propertyNames);", helper.getFinalTypeName(MAP_STRING_OBJECT), GET_PROPERTY_MAP.getSymbolName(), entityName)); // bodyBuilder.appendFormalLine(""); // // // if there is a filter bodyBuilder.appendFormalLine("// if there is a filter"); // if (!propertyMap.isEmpty()) { bodyBuilder.appendFormalLine("if (!propertyMap.isEmpty()) {"); bodyBuilder.indent(); // // Prepare a predicate bodyBuilder.appendFormalLine("// Prepare a predicate"); // BooleanBuilder baseFilterPredicate = new BooleanBuilder(); bodyBuilder.appendFormalLine(String.format( "%s baseFilterPredicate = new %s();", helper.getFinalTypeName(QDSL_BOOLEAN_BUILDER), helper.getFinalTypeName(QDSL_BOOLEAN_BUILDER))); bodyBuilder.appendFormalLine(""); // // Base filter. Using BooleanBuilder, a cascading builder for bodyBuilder .appendFormalLine("// Base filter. Using BooleanBuilder, a cascading builder for"); // // Predicate expressions bodyBuilder.appendFormalLine("// Predicate expressions"); // PathBuilder<Visit> entity = new PathBuilder<Visit>(Visit.class, // "entity"); bodyBuilder.appendFormalLine(String.format( "%s<%s> entity = new %s<%s>(%s.class, \"entity\");", helper.getFinalTypeName(QDSL_PATH_BUILDER), helper.getFinalTypeName(entity), helper.getFinalTypeName(QDSL_PATH_BUILDER), helper.getFinalTypeName(entity), helper.getFinalTypeName(entity))); bodyBuilder.appendFormalLine(""); // // // Build base filter bodyBuilder.appendFormalLine("// Build base filter"); // for (String key : propertyMap.keySet()) { bodyBuilder .appendFormalLine("for (String key : propertyMap.keySet()) {"); bodyBuilder.indent(); // baseFilterPredicate.and(entity.get(key).eq(propertyMap.get(key))); bodyBuilder .appendFormalLine("baseFilterPredicate.and(entity.get(key).eq(propertyMap.get(key)));"); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(""); // // // Create a query with filter bodyBuilder.appendFormalLine("// Create a query with filter"); // JPAQuery query = new JPAQuery(Visit.entityManager()); bodyBuilder.appendFormalLine(String.format( "%s query = new %s(%s.entityManager());", helper.getFinalTypeName(QDSL_JPA_QUERY), helper.getFinalTypeName(QDSL_JPA_QUERY), helper.getFinalTypeName(entity))); // query = query.from(entity); bodyBuilder.appendFormalLine("query = query.from(entity);"); // bodyBuilder.appendFormalLine(""); // // execute query bodyBuilder.appendFormalLine("// execute query"); // return query.where(baseFilterPredicate).list(entity); bodyBuilder .appendFormalLine("return query.where(baseFilterPredicate).list(entity);"); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(""); // // // no filter: return all elements bodyBuilder.appendFormalLine("// no filter: return all elements"); // return Visit.findAllVisits(); bodyBuilder.appendFormalLine(String.format("return %s.findAll%s();", helper.getFinalTypeName(entity), StringUtils.capitalize(entityPlural))); } /** * Gets <code>getPropertyMap</code> method. <br> * This method returns a Map with bean properties which appears on a * Enumeration (usually from httpRequest.getParametersNames()) * * @return */ private MethodMetadata getGetPropertyMapMethod() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType .convertFromJavaTypes(entity, ENUMERATION_STRING); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(GET_PROPERTY_MAP, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(new JavaSymbolName(entityName)); parameterNames.add(new JavaSymbolName("propertyNames")); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); buildGetPropertyMapMethodBody(bodyBuilder); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, GET_PROPERTY_MAP, MAP_STRING_OBJECT, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Returns <code>listDatatablesDetail</code> method <br> * This method is default list request handler for detail datatables * controllers * * @return */ private MethodMetadata getListDatatablesDetailMethod() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType .convertFromJavaTypes(MODEL, HTTP_SERVLET_REQUEST); // Include Item in parameters to use spring's binder to get baseFilter // values parameterTypes.add(new AnnotatedJavaType(entity, new AnnotationMetadataBuilder(MODEL_ATTRIBUTE).build())); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(new JavaSymbolName( DatatablesConstants.LIST_DATATABLES_DETAIL_METHOD_NAME), parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // @RequestMapping AnnotationMetadataBuilder methodAnnotation = new AnnotationMetadataBuilder(); methodAnnotation.setAnnotationType(REQUEST_MAPPING); // @RequestMapping(... produces = "text/html") methodAnnotation .addStringAttribute( DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_NAME, DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_VALUE_HTML); // @RequestMapping(... value ="/list") methodAnnotation .addStringAttribute( DatatablesConstants.REQUEST_MAPPING_ANNOTATION_VALUE_ATTRIBUTE_NAME, DatatablesConstants.REQUEST_MAPPING_ANNOTATION_VALUE_ATTRIBUTE_VALUE_LIST); annotations.add(methodAnnotation); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(UI_MODEL); parameterNames.add(new JavaSymbolName( DatatablesConstants.REQUEST_PARAMETER_NAME)); // Include Item in parameters to use spring's binder to get baseFilter // values parameterNames.add(new JavaSymbolName(entityName)); // Add method javadoc (not generated to disk because #10229) CommentStructure comments = new CommentStructure(); JavadocComment javadoc = new JavadocComment( "Show only the list view fragment for entity as detail datatables into a master datatables."); comments.addComment(javadoc, CommentStructure.CommentLocation.BEGINNING); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); // [Code generated] bodyBuilder .appendFormalLine("// Do common datatables operations: get entity list filtered by request parameters"); if (!isAjax()) { // listDatatables(uiModel, request, pet); bodyBuilder.appendFormalLine(LIST_DATATABLES.getSymbolName() .concat("(uiModel, request, ") .concat(entity.getSimpleTypeName().toLowerCase()) .concat(");")); } else { // listDatatables(uiModel, request); bodyBuilder.appendFormalLine(LIST_DATATABLES.getSymbolName() .concat("(uiModel, request);")); } bodyBuilder .appendFormalLine("// Show only the list fragment (without footer, header, menu, etc.) "); // return "forward:/WEB-INF/views/pets/list.jspx"; bodyBuilder.appendFormalLine("return \"forward:/WEB-INF/views/".concat( webScaffoldAnnotationValues.getPath()).concat("/list.jspx\";")); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, new JavaSymbolName( DatatablesConstants.LIST_DATATABLES_DETAIL_METHOD_NAME), JavaType.STRING, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); methodBuilder.setCommentStructure(comments); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Returns <code>createDatatablesDetail</code> method <br> * This method is default create request handler for detail datatables * controllers * * @return */ private MethodMetadata getCreateDatatablesDetailMethod() { // @RequestMapping(method = RequestMethod.POST, produces = "text/html", // params = "datatablesRedirect") // public String createDatatablesDetail(@RequestParam(value = // "datatablesRedirect", required = true) String redirect, // @Valid Pet pet, BindingResult bindingResult, Model uiModel, // HttpServletRequest httpServletRequest) { // Define method parameter types List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>(); parameterTypes.add(helper.createRequestParam(JavaType.STRING, "datatablesRedirect", true, null)); parameterTypes.add(new AnnotatedJavaType(entity, new AnnotationMetadataBuilder(new JavaType( "javax.validation.Valid")).build())); parameterTypes.addAll(AnnotatedJavaType.convertFromJavaTypes( new JavaType("org.springframework.validation.BindingResult"), MODEL, HTTP_SERVLET_REQUEST)); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(new JavaSymbolName( "createDatatablesDetail"), parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // @RequestMapping(method = RequestMethod.POST, produces = "text/html", // params = "datatablesRedirect") AnnotationMetadataBuilder requestMappingAnnotation = helper .getRequestMappingAnnotation( null, null, null, DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_VALUE_HTML, null, null); requestMappingAnnotation.addEnumAttribute("method", REQUEST_METHOD, "POST"); requestMappingAnnotation.addStringAttribute("params", "datatablesRedirect"); annotations.add(requestMappingAnnotation); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names final List<JavaSymbolName> parameterNames = Arrays.asList( new JavaSymbolName("redirect"), new JavaSymbolName(entity .getSimpleTypeName().toLowerCase()), new JavaSymbolName("bindingResult"), UI_MODEL, new JavaSymbolName("httpServletRequest")); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder .appendFormalLine("// Do common create operations (check errors, populate, persist, ...)"); // String view = create(pet, bindingResult, uiModel, // httpServletRequest); bodyBuilder.appendFormalLine("String view = create(".concat( entity.getSimpleTypeName().toLowerCase()).concat( ", bindingResult, uiModel, httpServletRequest);")); // if (bindingResult.hasErrors() || redirect == null || // redirect.trim().isEmpty()) { // return view; // } bodyBuilder .appendFormalLine("// If binding errors or no redirect, return common create error view (remain in create form)"); bodyBuilder .appendFormalLine("if (bindingResult.hasErrors() || redirect == null || redirect.trim().isEmpty()) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return view;"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder .appendFormalLine("// If create success, redirect to given URL: master datatables"); // return "redirect:".concat(redirect); bodyBuilder.appendFormalLine("return \"redirect:\".concat(redirect);"); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, new JavaSymbolName( "createDatatablesDetail"), JavaType.STRING, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Returns <code>updateDatatablesDetail</code> method <br> * This method is default update request handler for detail datatables * controllers * * @return */ private MethodMetadata getUpdateDatatablesDetailMethod() { // @RequestMapping(method = RequestMethod.PUT, produces = "text/html", // params = "datatablesRedirect") // public String updateDatatablesDetail(@RequestParam(value = // "datatablesRedirect", required = true) String redirect, // @Valid Pet pet, BindingResult bindingResult, Model uiModel, // HttpServletRequest httpServletRequest) { // Define method parameter types List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>(); parameterTypes.add(helper.createRequestParam(JavaType.STRING, "datatablesRedirect", true, null)); parameterTypes.add(new AnnotatedJavaType(entity, new AnnotationMetadataBuilder(new JavaType( "javax.validation.Valid")).build())); parameterTypes.addAll(AnnotatedJavaType.convertFromJavaTypes( new JavaType("org.springframework.validation.BindingResult"), MODEL, HTTP_SERVLET_REQUEST)); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(new JavaSymbolName( "updateDatatablesDetail"), parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // @RequestMapping(method = RequestMethod.PUT, produces = "text/html", // params = "datatablesRedirect") AnnotationMetadataBuilder requestMappingAnnotation = helper .getRequestMappingAnnotation( null, null, null, DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_VALUE_HTML, null, null); requestMappingAnnotation.addEnumAttribute("method", REQUEST_METHOD, "PUT"); requestMappingAnnotation.addStringAttribute("params", "datatablesRedirect"); annotations.add(requestMappingAnnotation); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names final List<JavaSymbolName> parameterNames = Arrays.asList( new JavaSymbolName("redirect"), new JavaSymbolName(entity .getSimpleTypeName().toLowerCase()), new JavaSymbolName("bindingResult"), UI_MODEL, new JavaSymbolName("httpServletRequest")); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder .appendFormalLine("// Do common update operations (check errors, populate, merge, ...)"); // String view = update(pet, bindingResult, uiModel, // httpServletRequest); bodyBuilder.appendFormalLine("String view = update(".concat( entity.getSimpleTypeName().toLowerCase()).concat( ", bindingResult, uiModel, httpServletRequest);")); // if (bindingResult.hasErrors() || redirect == null || // redirect.trim().isEmpty()) { // return view; // } bodyBuilder .appendFormalLine("// If binding errors or no redirect, return common update error view (remain in update form)"); bodyBuilder .appendFormalLine("if (bindingResult.hasErrors() || redirect == null || redirect.trim().isEmpty()) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return view;"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder .appendFormalLine("// If update success, redirect to given URL: master datatables"); // return "redirect:".concat(redirect); bodyBuilder.appendFormalLine("return \"redirect:\".concat(redirect);"); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, new JavaSymbolName( "updateDatatablesDetail"), JavaType.STRING, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Returns <code>deleteDatatablesDetail</code> method <br> * This method is default delete request handler for detail datatables * controllers * * @return */ private MethodMetadata getDeleteDatatablesDetailMethod() { // @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, // produces = "text/html", params = "datatablesRedirect") // public String deleteDatatablesDetail(@RequestParam(value = // "datatablesRedirect", required = true) String redirect, // @PathVariable("id") Long id, @RequestParam(value = "page", required = // false) Integer page, // @RequestParam(value = "size", required = false) Integer size, Model // uiModel) { // Define method parameter types List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>(); parameterTypes.add(helper.createRequestParam(JavaType.STRING, "datatablesRedirect", true, null)); final List<AnnotationAttributeValue<?>> annotationAttributes = new ArrayList<AnnotationAttributeValue<?>>(); annotationAttributes.add(new StringAttributeValue(new JavaSymbolName( "value"), "id")); parameterTypes.add(new AnnotatedJavaType(entityIdentifier .getFieldType(), new AnnotationMetadataBuilder(new JavaType( "org.springframework.web.bind.annotation.PathVariable"), annotationAttributes).build())); parameterTypes.add(helper.createRequestParam(JavaType.INT_OBJECT, "page", false, null)); parameterTypes.add(helper.createRequestParam(JavaType.INT_OBJECT, "size", false, null)); parameterTypes.addAll(AnnotatedJavaType.convertFromJavaTypes(MODEL)); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(new JavaSymbolName( "deleteDatatablesDetail"), parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, // produces = "text/html", params = "datatablesRedirect") AnnotationMetadataBuilder requestMappingAnnotation = helper .getRequestMappingAnnotation( null, null, null, DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_VALUE_HTML, null, null); requestMappingAnnotation.addEnumAttribute("method", REQUEST_METHOD, "DELETE"); requestMappingAnnotation.addStringAttribute("params", "datatablesRedirect"); requestMappingAnnotation.addStringAttribute("value", "/{id}"); annotations.add(requestMappingAnnotation); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names final List<JavaSymbolName> parameterNames = Arrays.asList( new JavaSymbolName("redirect"), new JavaSymbolName("id"), new JavaSymbolName("page"), new JavaSymbolName("size"), UI_MODEL); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder .appendFormalLine("// Do common delete operations (find, remove, add pagination attributes, ...)"); // String view = delete(id, page, size, uiModel); bodyBuilder .appendFormalLine("String view = delete(id, page, size, uiModel);"); // if (redirect == null || redirect.trim().isEmpty()) { // return view; // } bodyBuilder .appendFormalLine("// If no redirect, return common list view"); bodyBuilder .appendFormalLine("if (redirect == null || redirect.trim().isEmpty()) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("return view;"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder .appendFormalLine("// Redirect to given URL: master datatables"); // return "redirect:".concat(redirect); bodyBuilder.appendFormalLine("return \"redirect:\".concat(redirect);"); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, new JavaSymbolName( "deleteDatatablesDetail"), JavaType.STRING, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Build body method <code>getPropertyMap</code> method. <br> * This method returns a Map with bean properties which appears on a * Enumeration (usually from httpRequest.getParametersNames()) * * @return */ private void buildGetPropertyMapMethodBody( InvocableMemberBodyBuilder bodyBuilder) { // Map<String, Object> propertyValuesMap = new HashMap<String, // Object>(); bodyBuilder.appendFormalLine(String.format( "%s propertyValuesMap = new %s();", helper.getFinalTypeName(MAP_STRING_OBJECT), helper.getFinalTypeName(HASHMAP_STRING_OBJECT))); // bodyBuilder.appendFormalLine(""); // // If no entity or properties given, return empty Map bodyBuilder .appendFormalLine("// If no entity or properties given, return empty Map"); // if(entity == null || propertyNames == null) { bodyBuilder.appendFormalLine(String.format( "if(%s == null || propertyNames == null) {", entityName)); bodyBuilder.indent(); // return propertyValuesMap; bodyBuilder.appendFormalLine("return propertyValuesMap;"); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); bodyBuilder.appendFormalLine(""); // List<String> properties = new ArrayList<String>(); bodyBuilder.appendFormalLine(String.format("%s properties = new %s();", helper.getFinalTypeName(LIST_STRING), helper.getFinalTypeName(ARRAYLIST_STRING))); // CollectionUtils.addAll(properties, propertyNames); bodyBuilder.appendFormalLine(String.format( "%s.addAll(properties, propertyNames);", helper.getFinalTypeName(COLLECTION_UTILS))); // bodyBuilder.appendFormalLine(""); // // There must be at least one property name, otherwise return empty // Map bodyBuilder .appendFormalLine("// There must be at least one property name, otherwise return empty Map"); // if(properties.isEmpty()) { bodyBuilder.appendFormalLine("if (properties.isEmpty()) {"); bodyBuilder.indent(); // return propertyValuesMap; bodyBuilder.appendFormalLine("return propertyValuesMap;"); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); // bodyBuilder.appendFormalLine(""); // // Iterate over given properties to get each property value bodyBuilder .appendFormalLine("// Iterate over given properties to get each property value"); // BeanWrapper entityBean = new BeanWrapperImpl(entity); bodyBuilder.appendFormalLine(String.format( "%s entityBean = new %s(%s);", helper.getFinalTypeName(BEAN_WRAPPER), helper.getFinalTypeName(BEAN_WRAPPER_IMP), entityName)); // for (String propertyName : properties) { bodyBuilder .appendFormalLine("for (String propertyName : properties) {"); bodyBuilder.indent(); // if (entityBean.isReadableProperty(propertyName)) { bodyBuilder .appendFormalLine("if (entityBean.isReadableProperty(propertyName)) {"); bodyBuilder.indent(); // Object propertyValue = null; bodyBuilder.appendFormalLine("Object propertyValue = null;"); // try { bodyBuilder.appendFormalLine("try {"); bodyBuilder.indent(); // propertyValue = entityBean.getPropertyValue(propertyName); bodyBuilder .appendFormalLine("propertyValue = entityBean.getPropertyValue(propertyName);"); // } catch (Exception e){ bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("} catch (Exception e){"); bodyBuilder.indent(); // // TODO log warning bodyBuilder.appendFormalLine("// TODO log warning"); // continue; bodyBuilder.appendFormalLine("continue;"); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); // propertyValuesMap.put(propertyName, propertyValue); bodyBuilder .appendFormalLine("propertyValuesMap.put(propertyName, propertyValue);"); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); // return propertyValuesMap; bodyBuilder.appendFormalLine("return propertyValuesMap;"); } /** * Gets <code>populateParameterMap</code> method. This method transforms a * HttpServlerRequest Map<String,String[]> into a Map<String,String> * * @return */ private MethodMetadata getPopulateParameterMapMethod() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType .convertFromJavaTypes(HTTP_SERVLET_REQUEST); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(POPULATE_PARAMETERS_MAP, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(new JavaSymbolName( DatatablesConstants.REQUEST_PARAMETER_NAME)); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); buildPopulateParameterMapMethodBody(bodyBuilder); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, POPULATE_PARAMETERS_MAP, MAP_STRING_STRING, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Build body method of <code>populateParameterMap</code> method. This * method transforms a HttpServlerRequest Map<String,String[]> into a * Map<String,String> * * @param bodyBuilder */ private void buildPopulateParameterMapMethodBody( InvocableMemberBodyBuilder bodyBuilder) { // Map<String, Object> params; bodyBuilder.appendFormalLine(String.format("%s params;", helper.getFinalTypeName(MAP_STRING_OBJECT))); // if (request == null) { bodyBuilder.appendFormalLine("if (request == null) {"); bodyBuilder.indent(); // params = Collections.emptyMap(); bodyBuilder.appendFormalLine(String.format("params = %s.emptyMap();", helper.getFinalTypeName(COLLECTIONS))); // } else { bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("} else {"); bodyBuilder.indent(); // params = new HashMap<String, Object>(request.getParameterMap()); bodyBuilder.appendFormalLine(String.format( "params = new %s(request.getParameterMap());", helper.getFinalTypeName(HASHMAP_STRING_OBJECT))); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); // bodyBuilder.appendFormalLine(""); // Map<String, String> allParams = new HashMap<String, // String>(params.size()); bodyBuilder.appendFormalLine(String.format( "%s allParams = new %s(params.size());", helper.getFinalTypeName(MAP_STRING_STRING), helper.getFinalTypeName(HASHMAP_STRING_STRING))); // bodyBuilder.appendFormalLine(""); // String value; bodyBuilder.appendFormalLine("String value;"); // String objValue; bodyBuilder.appendFormalLine("Object objValue;"); // for (String key : params.keySet()) { bodyBuilder.appendFormalLine("for (String key : params.keySet()) {"); bodyBuilder.indent(); bodyBuilder.appendFormalLine("objValue = params.get(key);"); // if (objValue instanceof String[]) { bodyBuilder.appendFormalLine("if (objValue instanceof String[]) {"); bodyBuilder.indent(); // value = ((String[]) entry.getValue())[0]; bodyBuilder.appendFormalLine("value = ((String[]) objValue)[0];"); // } else { bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("} else {"); bodyBuilder.indent(); // value = (String) entry.getValue(); bodyBuilder.appendFormalLine("value = (String) objValue;"); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); // allParams.put(entry.getKey(), value); bodyBuilder.appendFormalLine("allParams.put(key, value);"); // } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); // return allParams; bodyBuilder.appendFormalLine("return allParams;"); } /** * Gets a method to manage AJAX data request of a datatables which draw the * result of a Roo Dynamic finder. * * @param finderMethod * @param queryHolder * @return */ private MethodMetadata getAjaxFinderMethod( FinderMetadataDetails finderMethod, QueryHolderTokens queryHolder) { // Define method parameter types List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>(); // Add datatable request parameters parameterTypes.add(new AnnotatedJavaType(DATATABLES_CRITERIA_TYPE, new AnnotationMetadataBuilder(DATATABLES_PARAMS).build())); // Prepares @RequestParam method parameters based on // finder information List<AnnotatedJavaType> finderParamTypes = finderMethod .getFinderMethodMetadata().getParameterTypes(); List<JavaSymbolName> finderParamNames = finderMethod .getFinderMethodMetadata().getParameterNames(); JavaType paramType; for (int i = 0; i < finderParamTypes.size(); i++) { paramType = finderParamTypes.get(i).getJavaType(); if (paramType.isBoolean()) { // Boolean's false value is omitted on request, so must be // optional (by default will get false) parameterTypes.add(helper.createRequestParam(paramType, finderParamNames.get(i).getSymbolName(), false, null)); } else { parameterTypes.add(helper.createRequestParam(paramType, finderParamNames.get(i).getSymbolName(), null, null)); } } if (!isStantardMode()) { // For render mode request and response are needed to // perform internal request for item render parameterTypes.add(AnnotatedJavaType .convertFromJavaType(HTTP_SERVLET_REQUEST)); parameterTypes.add(AnnotatedJavaType .convertFromJavaType(HTTP_SERVLET_RESPONSE)); } JavaSymbolName methodName = new JavaSymbolName( finderMethod.getFinderName()); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(methodName, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // get Finder-name value String finderNameValue = finderMethod.getFinderName(); finderNameValue = finderNameValue.substring(finderNameValue .indexOf("By")); // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); AnnotationMetadataBuilder methodAnnotation = new AnnotationMetadataBuilder(); methodAnnotation.setAnnotationType(REQUEST_MAPPING); methodAnnotation.addStringAttribute("headers", "Accept=application/json"); methodAnnotation .addStringAttribute( DatatablesConstants.REQUEST_MAPPING_ANNOTATION_VALUE_ATTRIBUTE_NAME, "/datatables/ajax"); methodAnnotation.addStringAttribute("params", "ajax_find=".concat(finderNameValue)); methodAnnotation .addStringAttribute( DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_NAME, "application/json"); annotations.add(methodAnnotation); annotations.add(new AnnotationMetadataBuilder(RESPONSE_BODY)); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); if (!isStantardMode()) { // On render mode internal render request // can throw ServletException or IOException throwsTypes.add(SERVLET_EXCEPTION); throwsTypes.add(IO_EXCEPTION); } // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(CRITERIA_PARAM_NAME); for (JavaSymbolName paramName : finderParamNames) { parameterNames.add(paramName); } if (!isStantardMode()) { // For render mode request and response are needed to // perform internal request for item render parameterNames.add(REQUEST_PARAM_NAME); parameterNames.add(RESPONSE_PARAM_NAME); } // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); buildFinderAjaxMethodBody(bodyBuilder, finderMethod, queryHolder); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, methodName, FIND_ALL_RETURN, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Build body method to manage AJAX data request of a datatables which draw * the result of a Roo Dynamic finder. * * @param bodyBuilder * @param finderMethod * @param queryHolder */ private void buildFinderAjaxMethodBody( InvocableMemberBodyBuilder bodyBuilder, FinderMetadataDetails finderMethod, QueryHolderTokens queryHolder) { // BooleanBuilder baseFilterPredicate = new BooleanBuilder(); bodyBuilder.appendFormalLine(String.format("%s baseSearch = new %s();", helper.getFinalTypeName(QDSL_BOOLEAN_BUILDER), helper.getFinalTypeName(QDSL_BOOLEAN_BUILDER))); bodyBuilder.appendFormalLine(""); bodyBuilder .appendFormalLine("// Base Search. Using BooleanBuilder, a cascading builder for"); bodyBuilder.appendFormalLine("// Predicate expressions"); String path_builder = helper.getFinalTypeName(QDSL_PATH_BUILDER); String entity_class = helper.getFinalTypeName(entity); // PathBuilder<Pet> entity = new PathBuilder<Pet>(Pet.class, "entity"); bodyBuilder.appendFormalLine(String.format( "%s<%s> entity = new %s<%s>(%s.class, \"entity\");", path_builder, entity_class, path_builder, entity_class, entity_class)); bodyBuilder.appendFormalLine(""); // Build code to generate QueryDsl predicate to include base filter // on Datatables.findByCriteria buildFinderAjaxBaseSearch(bodyBuilder, finderMethod, queryHolder); bodyBuilder.appendFormalLine(""); // Build Datatables.findByCriteria call code buildFindByCriteriaCall(bodyBuilder, true); // Build code for response based on SearchResult if (isStantardMode()) { // Build code to delegate on Datatables.populateDataSearch buildPopulateDataSearchCall(bodyBuilder); } else { // Build code to call RenderItem method buildPopulateDataSearchCallRenderMode(bodyBuilder); } } /** * Builds code to create a QueryDsl predicate which implements a Roo dynamic * filter condition * * @param bodyBuilder * @param finderMethod * @param queryHolder */ private void buildFinderAjaxBaseSearch( InvocableMemberBodyBuilder bodyBuilder, FinderMetadataDetails finderMethod, QueryHolderTokens queryHolder) { FieldToken lastFieldToken = null; // flag set when a FieldTocken is located boolean isNewField = true; // Flag set when a condition is generated // but not included yet boolean isConditionApplied = false; // Helper which can generated the expression // required for generate the predicate FinderToDslHelper fHelper = new FinderToDslHelper(finderMethod, queryHolder, helper); // Holds current expression StringBuilder expBuilder = null; for (final Token token : queryHolder.getTokens()) { if (token instanceof ReservedToken) { // Current token isn't a field final String reservedToken = token.getValue(); if (lastFieldToken == null) { // Any operator must be preceded by refereed field // XXX Throw a "wrong format" exception? continue; } // prepare field name final String fieldName = lastFieldToken.getField() .getFieldName().getSymbolName(); // Add PathBuilder to expression expBuilder = new StringBuilder("entity"); // XXX Currently ManyToMany and OneToMany // properties are not supported by Roo finders if (!lastFieldToken.getField().getFieldType() .isCommonCollectionType()) { // If previous token was a field // include Path getter if (isNewField) { JavaType fieldType = fHelper .getFieldTypeOfFinder(fieldName); Validate.notNull( fieldType, "Field type not found for '%s' field in '%s' finder", fieldName, finderMethod.getFinderName()); expBuilder.append(fHelper.getDslGetterFor(fieldName, fieldType)); if (reservedToken.equalsIgnoreCase("Like")) { // Add function toLower (and cast to string if it's // needed) expBuilder.append(fHelper .getToLowerOperatorFor(fieldType)); } // mark as field getter is already processed isNewField = false; // mark as condition is no included isConditionApplied = false; } if (reservedToken.equalsIgnoreCase("And")) { if (!isConditionApplied) { // use .eq() operator if condition not applied expBuilder.append(fHelper .getEqualExpression(fieldName)); } // filterCondition.and( {exp}); bodyBuilder.appendFormalLine(fHelper .getDslAnd(expBuilder.toString())); expBuilder = null; isConditionApplied = true; } else if (reservedToken.equalsIgnoreCase("Or")) { if (!isConditionApplied) { // use .eq() operator if condition not applied expBuilder.append(fHelper .getEqualExpression(fieldName)); } bodyBuilder.appendFormalLine(fHelper .getDslOr(expBuilder.toString())); expBuilder = null; isConditionApplied = true; } else if (reservedToken.equalsIgnoreCase("Between")) { // use .between(minField,maxField) expression expBuilder.append(fHelper .getBetweenExpression(fieldName)); } else if (reservedToken.equalsIgnoreCase("Like")) { // use .like() expression expBuilder.append(fHelper.getLikeExpression(fieldName)); } else if (reservedToken.equalsIgnoreCase("IsNotNull")) { // builder.append(" IS NOT NULL "); // use isNotNull() expression expBuilder.append(".isNotNull()"); } else if (reservedToken.equalsIgnoreCase("IsNull")) { // builder.append(" IS NULL "); // use isNull() expression expBuilder.append(".isNull()"); } else if (reservedToken.equalsIgnoreCase("Not")) { // builder.append(" IS NOT "); // use not() expression expBuilder.append(".not()"); } else if (reservedToken.equalsIgnoreCase("NotEquals")) { // builder.append(" != "); expBuilder.append(fHelper .getNotEqualExpression(fieldName)); } else if (reservedToken.equalsIgnoreCase("LessThan")) { // builder.append(" < "); expBuilder.append(fHelper .getLessThanExpression(fieldName)); } else if (reservedToken.equalsIgnoreCase("LessThanEquals")) { // builder.append(" <= "); expBuilder.append(fHelper .getLessThanEqualsExpression(fieldName)); } else if (reservedToken.equalsIgnoreCase("GreaterThan")) { // builder.append(" > "); expBuilder.append(fHelper .getGreaterThanExpression(fieldName)); } else if (reservedToken .equalsIgnoreCase("GreaterThanEquals")) { // builder.append(" >= "); expBuilder.append(fHelper .getGreaterThanEqualseExpression(fieldName)); } else if (reservedToken.equalsIgnoreCase("Equals")) { // builder.append(" = "); expBuilder .append(fHelper.getEqualExpression(fieldName)); } } } else { // current token is a field lastFieldToken = (FieldToken) token; isNewField = true; } } if (isNewField) { // New field is located but no operation // has found. generate an expression using // equals operator expBuilder = new StringBuilder("entity"); if (lastFieldToken != null && !lastFieldToken.getField().getFieldType() .isCommonCollectionType()) { String fieldName = lastFieldToken.getField().getFieldName() .getSymbolName(); JavaType fieldType = fHelper.getFieldTypeOfFinder(fieldName); expBuilder .append(fHelper.getDslGetterFor(fieldName, fieldType)); expBuilder.append(fHelper.getEqualExpression(fieldName)); } isConditionApplied = false; } if (!isConditionApplied) { // There is an expression not included in predicate yet. // Include it using "and" join if (expBuilder != null) { // filterCondition.and( {exp}); bodyBuilder.appendFormalLine(fHelper.getDslAnd(expBuilder .toString())); } } } /** * Gets <code>populateDatatablesConfig</code> method <br> * This method insert on Model all configuration properties which will need * ".tagx" to render final page. <br> * This properties are: * <ul> * <li><em>datatablesHasBatchSupport</em> informs if there is batch entity * operations support on controller (used for multi-row delete operation)</li> * <li><em>datatablesUseAjax</em> informs datatables data mode ( * <em>true</em> : AJAX <em>false</em> DOM)</li> * <li><em>finderNameParam</em> sets the name of parameter that will contain * the {@code finderName} (only for AJAX mode)</li> * <li><em>datatablesStandardMode</em> informs render mode (<em>true</em> * for standard datatable view; <em>false</em> for single-item-page, * one-cell-per-item or render-jspx datatable modes)</li> * </ul> * * @return */ private MethodMetadata getPopulateDatatablesConfig() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType .convertFromJavaTypes(MODEL); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(POPULATE_DATATABLES_CONFIG, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); AnnotationMetadataBuilder annotation = new AnnotationMetadataBuilder( MODEL_ATTRIBUTE); // @ModelAttribute annotations.add(annotation); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(UI_MODEL); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder.appendFormalLine(String.format( "uiModel.addAttribute(\"datatablesHasBatchSupport\", %s);", hasJpaBatchSupport())); bodyBuilder.appendFormalLine(String.format( "uiModel.addAttribute(\"datatablesUseAjax\",%s);", isAjax())); bodyBuilder.appendFormalLine(String.format( "uiModel.addAttribute(\"datatablesStandardMode\",%s);", isStantardMode())); if (isAjax()) { bodyBuilder .appendFormalLine("uiModel.addAttribute(\"finderNameParam\",\"ajax_find\");"); } // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, POPULATE_DATATABLES_CONFIG, JavaType.VOID_PRIMITIVE, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Gets <code>populateItemForRender</code> method <br> * This methods prepares request attributes to render a entity item in * non-standard render mode. User can make push-in of this method to * customize the parameters received on target .jspx view. * * @return */ private MethodMetadata getPopulateItemForRenderMethod() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType .convertFromJavaTypes(HTTP_SERVLET_REQUEST, entity); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(POPULATE_ITEM_FOR_RENDER, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(REQUEST_PARAM_NAME); parameterNames.add(new JavaSymbolName(entityName)); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); buildPopulateItemForRenderMethodBody(bodyBuilder); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, POPULATE_ITEM_FOR_RENDER, JavaType.VOID_PRIMITIVE, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Build standard body method for <code>populateItemForRender</code> method <br> * This methods prepares request attributes to render a entity item in * non-standard render mode. User can make push-in of this method to * customize the parameters received on target .jspx view. * * @param bodyBuilder */ private void buildPopulateItemForRenderMethodBody( InvocableMemberBodyBuilder bodyBuilder) { // Model uiModel = new ExtendedModelMap(); bodyBuilder.appendFormalLine(String.format("%s uiModel = new %s();", MODEL, EXTENDED_MODEL_MAP)); bodyBuilder.appendFormalLine(""); // request.setAttribute("pet", pet); bodyBuilder.appendFormalLine(String.format( "%s.setAttribute(\"%s\", %s);", REQUEST_PARAM_NAME.getSymbolName(), entityName, entityName )); // request.setAttribute("itemId", // conversion_service.convert(pet.getId(), String.class); bodyBuilder .appendFormalLine(String .format("%s.setAttribute(\"itemId\", %s.convert(%s.get%s(),String.class));", REQUEST_PARAM_NAME.getSymbolName(), getConversionServiceField().getFieldName() .getSymbolName(), entityName, StringUtils.capitalize(entityIdentifier .getFieldName().getSymbolName()))); bodyBuilder.appendFormalLine(""); // Add date patterns (if any) if (!entityDatePatterns.isEmpty()) { // Delegates on Roo standard populate date patterns method // addDateTimeFormatPatterns(uiModel); bodyBuilder.appendFormalLine("addDateTimeFormatPatterns(uiModel);"); bodyBuilder.appendFormalLine(""); } // Load uiModel attributes into request bodyBuilder.appendFormalLine("// Load uiModel attributes into request"); // Map<String,Object> modelMap = uiModel.asMap(); bodyBuilder.appendFormalLine(String.format( "%s modelMap = uiModel.asMap();", helper.getFinalTypeName(MAP_STRING_OBJECT))); // for (Entry<String,Object> entry : uiModel.asMap().entrySet()){ bodyBuilder.appendFormalLine(String.format( "for (%s key : modelMap.keySet()){", helper.getFinalTypeName(JavaType.STRING))); bodyBuilder.indent(); // request.setAttribute(entry.getKey(), entry.getValue()); bodyBuilder .appendFormalLine("request.setAttribute(key, modelMap.get(key));"); bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); } /** * Returns <code>listDatatables</code> method <br> * This method is default list request handler for datatables controllers * * @return */ private MethodMetadata getListDatatablesRequestMethod() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = AnnotatedJavaType .convertFromJavaTypes(MODEL, HTTP_SERVLET_REQUEST); if (!isAjax()) { // In DOM mode we include Item in parameters to use // spring's binder to get baseFilter values parameterTypes.add(new AnnotatedJavaType(entity, new AnnotationMetadataBuilder(MODEL_ATTRIBUTE).build())); } // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(LIST_DATATABLES, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // @RequestMapping AnnotationMetadataBuilder methodAnnotation = new AnnotationMetadataBuilder(); methodAnnotation.setAnnotationType(REQUEST_MAPPING); // @RequestMapping(method = RequestMethod.GET... methodAnnotation.addEnumAttribute("method", REQUEST_METHOD, "GET"); // @RequestMapping(... produces = "text/html") methodAnnotation .addStringAttribute( DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_NAME, DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_VALUE_HTML); annotations.add(methodAnnotation); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(UI_MODEL); parameterNames.add(new JavaSymbolName( DatatablesConstants.REQUEST_PARAMETER_NAME)); if (!isAjax()) { // In DOM mode we include Item in parameters to use // spring's binder to get baseFilter values parameterNames.add(new JavaSymbolName(entityName)); } // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); if (isAjax()) { buildListDatatablesRequesMethodAjaxBody(bodyBuilder); } else { buildListDatatablesRequesMethodDomBody(bodyBuilder); } // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, LIST_DATATABLES, JavaType.STRING, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Build method body for <code>listDatatables</code> method for DOM mode * * @param bodyBuilder */ private void buildListDatatablesRequesMethodDomBody( InvocableMemberBodyBuilder bodyBuilder) { String listVarName = StringUtils.uncapitalize(entityPlural); bodyBuilder .appendFormalLine("// Get data (filtered by received parameters) and put it on pageContext"); // List<Visit> visits = // findByParameters(visit,request.getParameterNames()); bodyBuilder .appendFormalLine(String .format("@SuppressWarnings(\"unchecked\") %s %s = %s(%s, request != null ? request.getParameterNames() : null);", helper.getFinalTypeName(entityListType), listVarName, findByParametersMethodName.getSymbolName(), entityName)); // uiModel.addAttribute("pets",pets); bodyBuilder.appendFormalLine(String.format( "%s.addAttribute(\"%s\",%s);", UI_MODEL.getSymbolName(), entityPlural.toLowerCase(), listVarName)); buildListDatatablesRequestMethodDetailBody(bodyBuilder); // return "pets/list"; bodyBuilder.appendFormalLine(String.format("return \"%s/list\";", webScaffoldAnnotationValues.getPath())); } /** * Build method body for <code>listDatatables</code> method for AJAX mode * * @param bodyBuilder */ private void buildListDatatablesRequesMethodAjaxBody( InvocableMemberBodyBuilder bodyBuilder) { // [Code generated] Map<String, String> params = // populateParameterMap(request); bodyBuilder.appendFormalLine(String.format("%s params = %s(request);", helper.getFinalTypeName(MAP_STRING_STRING), POPULATE_PARAMETERS_MAP.getSymbolName())); // [Code generated] if (!params.isEmpty()) { bodyBuilder.appendFormalLine("if (!params.isEmpty()) {"); bodyBuilder.indent(); // [Code generated] uiModel.addAttribute("baseFilter", params); bodyBuilder .appendFormalLine("uiModel.addAttribute(\"baseFilter\", params);"); // [Code generated] } bodyBuilder.indentRemove(); bodyBuilder.appendFormalLine("}"); buildListDatatablesRequestMethodDetailBody(bodyBuilder); // [Code generated] return "pets/list"; bodyBuilder.appendFormalLine(String.format("return \"%s/list\";", webScaffoldAnnotationValues.getPath())); } /** * Build method body for <code>listDatatables</code> method for AJAX mode * * @param bodyBuilder */ private void buildListDatatablesRequestMethodDetailBody( InvocableMemberBodyBuilder bodyBuilder) { String[] fieldNames = getDetailFields(); if (fieldNames.length > 0) { bodyBuilder .appendFormalLine("// Add attribute available into view with information about each detail datatables "); bodyBuilder.appendFormalLine("Map<String, String> details;"); bodyBuilder .appendFormalLine("List<Map<String, String>> detailsInfo = new ArrayList<Map<String, String>>(" .concat(String.valueOf(fieldNames.length)).concat( ");")); List<FieldMetadata> entityFields = entityMemberDetails.getFields(); for (int i = 0; i < fieldNames.length; i++) { String fieldName = fieldNames[i]; for (FieldMetadata entityField : entityFields) { if (entityField.getFieldName().getSymbolName() .equals(fieldName)) { AnnotationMetadata entityFieldOneToManyAnnotation = entityField .getAnnotation(new JavaType( "javax.persistence.OneToMany")); - if (entityFieldOneToManyAnnotation != null) { + if (entityFieldOneToManyAnnotation != null && entityFieldOneToManyAnnotation.getAttribute("mappedBy") != null) { String entityFieldOneToManyAnnotationMappedBy = entityFieldOneToManyAnnotation .getAttribute("mappedBy").getValue() .toString(); if (entityFieldOneToManyAnnotationMappedBy != null) { bodyBuilder .appendFormalLine("details = new HashMap<String, String>();"); // TODO Get entity path bodyBuilder .appendFormalLine("// Base path for detail datatables entity (to get detail datatables fragment URL)"); bodyBuilder .appendFormalLine("details.put(\"path\", \"" .concat(entityField .getFieldName() .getSymbolName()) .concat("\");")); bodyBuilder .appendFormalLine("// Property name in detail entity with the relation to master entity"); bodyBuilder .appendFormalLine("details.put(\"mappedBy\", \"" .concat(entityFieldOneToManyAnnotationMappedBy) .concat("\");")); bodyBuilder .appendFormalLine("detailsInfo.add(details);"); } } } } } bodyBuilder .appendFormalLine("uiModel.addAttribute(\"detailsInfo\", detailsInfo);"); } } /** * Redefines {@code list} Roo webScaffod method to delegate on * {@link #LIST_DATATABLES} * * @return */ private MethodMetadata getListRooRequestMethod() { // public String OwnerController.list( // @RequestParam(value = "page", required = false) Integer page, // @RequestParam(value = "size", required = false) Integer size, // Model uiModel) { // Define method parameter types final List<AnnotatedJavaType> parameterTypes = Arrays.asList(helper .createRequestParam(JavaType.INT_OBJECT, "page", false, null), helper.createRequestParam(JavaType.INT_OBJECT, "size", false, null), new AnnotatedJavaType(MODEL)); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(LIST_ROO, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); // @RequestMapping(produces = "text/html") annotations .add(helper .getRequestMappingAnnotation( null, null, null, DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_VALUE_HTML, null, null)); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names final List<JavaSymbolName> parameterNames = Arrays.asList( new JavaSymbolName("page"), new JavaSymbolName("size"), UI_MODEL); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); bodyBuilder .appendFormalLine("// overrides the standard Roo list method and"); bodyBuilder.appendFormalLine("// delegates on datatables list method"); // return listDatatables(uiModel); if (isAjax()) { bodyBuilder.appendFormalLine(String.format( "return %s(uiModel, null);", LIST_DATATABLES.getSymbolName())); } else { bodyBuilder.appendFormalLine(String.format( "return %s(uiModel, null, null);", LIST_DATATABLES.getSymbolName())); } // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, LIST_ROO, JavaType.STRING, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Returns <code>findAllMethod</code> method <br> * This method handles datatables AJAX request for data which are no related * to a Roo Dynamic finder. * * @return */ private MethodMetadata getFindAllMethod() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>(); parameterTypes.add(new AnnotatedJavaType(DATATABLES_CRITERIA_TYPE, new AnnotationMetadataBuilder(DATATABLES_PARAMS).build())); parameterTypes.add(new AnnotatedJavaType(entity, new AnnotationMetadataBuilder(MODEL_ATTRIBUTE).build())); parameterTypes.addAll(AnnotatedJavaType .convertFromJavaTypes(HTTP_SERVLET_REQUEST)); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(findAllMethodName, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); AnnotationMetadataBuilder methodAnnotation = new AnnotationMetadataBuilder(); methodAnnotation.setAnnotationType(REQUEST_MAPPING); methodAnnotation.addStringAttribute("headers", "Accept=application/json"); methodAnnotation .addStringAttribute( DatatablesConstants.REQUEST_MAPPING_ANNOTATION_VALUE_ATTRIBUTE_NAME, "/datatables/ajax"); methodAnnotation .addStringAttribute( DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_NAME, "application/json"); annotations.add(methodAnnotation); annotations.add(new AnnotationMetadataBuilder(RESPONSE_BODY)); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(CRITERIA_PARAM_NAME); parameterNames.add(new JavaSymbolName(StringUtils .uncapitalize(entityName))); parameterNames.add(REQUEST_PARAM_NAME); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); buildFindAllDataMethodBody(bodyBuilder); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, findAllMethodName, FIND_ALL_RETURN, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Returns <code>findAll</code> method for render-a-view visualization mode. <br> * This method handles datatables AJAX request for data which are no related * to a Roo Dynamic finder. * * @return */ private MethodMetadata getFindAllMethodRenderMode() { // Define method parameter types List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>(); parameterTypes.add(new AnnotatedJavaType(DATATABLES_CRITERIA_TYPE, new AnnotationMetadataBuilder(DATATABLES_PARAMS).build())); parameterTypes.add(new AnnotatedJavaType(entity, new AnnotationMetadataBuilder(MODEL_ATTRIBUTE).build())); parameterTypes.add(AnnotatedJavaType .convertFromJavaType(HTTP_SERVLET_REQUEST)); parameterTypes.add(AnnotatedJavaType .convertFromJavaType(HTTP_SERVLET_RESPONSE)); // Check if a method with the same signature already exists in the // target type final MethodMetadata method = methodExists(findAllMethodName, parameterTypes); if (method != null) { // If it already exists, just return the method and omit its // generation via the ITD return method; } // Define method annotations List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(); AnnotationMetadataBuilder methodAnnotation = new AnnotationMetadataBuilder(); methodAnnotation.setAnnotationType(REQUEST_MAPPING); methodAnnotation.addStringAttribute("headers", "Accept=application/json"); methodAnnotation .addStringAttribute( DatatablesConstants.REQUEST_MAPPING_ANNOTATION_VALUE_ATTRIBUTE_NAME, "/datatables/ajax"); methodAnnotation .addStringAttribute( DatatablesConstants.REQUEST_MAPPING_ANNOTATION_PRODUCES_ATTRIBUTE_NAME, "application/json"); annotations.add(methodAnnotation); annotations.add(new AnnotationMetadataBuilder(RESPONSE_BODY)); // Define method throws types (none in this case) List<JavaType> throwsTypes = new ArrayList<JavaType>(); throwsTypes.add(SERVLET_EXCEPTION); throwsTypes.add(IO_EXCEPTION); // Define method parameter names List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>(); parameterNames.add(CRITERIA_PARAM_NAME); parameterNames.add(new JavaSymbolName(entityName)); parameterNames.add(REQUEST_PARAM_NAME); parameterNames.add(RESPONSE_PARAM_NAME); // Create the method body InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); buildFindAllMethodBodyRenderMode(bodyBuilder); // Use the MethodMetadataBuilder for easy creation of MethodMetadata MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder( getId(), Modifier.PUBLIC, findAllMethodName, FIND_ALL_RETURN, parameterTypes, parameterNames, bodyBuilder); methodBuilder.setAnnotations(annotations); methodBuilder.setThrowsTypes(throwsTypes); return methodBuilder.build(); // Build and return a MethodMetadata // instance } /** * Build method body for <code>findAll</code> method for render-a-view * visualization mode * * @param bodyBuilder */ private void buildFindAllMethodBodyRenderMode( InvocableMemberBodyBuilder bodyBuilder) { // Build call to FindByCriteria buildFindByCriteriaCall(bodyBuilder, false); buildPopulateDataSearchCallRenderMode(bodyBuilder); } /** * Build method-code to call Datatables.populateDataSearch method. * * @param bodyBuilder */ private void buildPopulateDataSearchCallRenderMode( InvocableMemberBodyBuilder bodyBuilder) { bodyBuilder.appendFormalLine(String.format( "%s rows = %s(searchResult, %s, %s);", helper.getFinalTypeName(LIST_MAP_STRING_STRING), renderItemsMethodName.getSymbolName(), REQUEST_PARAM_NAME.getSymbolName(), RESPONSE_PARAM_NAME.getSymbolName())); /* * DataSet<Map<String, String>> dataSet = new DataSet<Map<String, * String>>(rows, totalRecords, recordsFound); */ bodyBuilder.appendFormalLine(String.format( "%s dataSet = new %s(rows, totalRecords, recordsFound); ", helper.getFinalTypeName(DATA_SET_MAP_STRING_STRING), helper.getFinalTypeName(DATA_SET_MAP_STRING_STRING))); // return DatatablesResponse.build(dataSet,criterias); bodyBuilder.appendFormalLine(String.format( "return %s.build(dataSet,%s);", helper.getFinalTypeName(DATATABLES_RESPONSE), CRITERIA_PARAM_NAME.getSymbolName())); } /** * Build method-code to call Datatables.findByCriteria method. <br> * Generated code will depend on entity has JPAQuery metadata and if there * is a base search. * * @param bodyBuilder * @param baseSearch * @return */ private String buildFindByCriteriaCall( InvocableMemberBodyBuilder bodyBuilder, boolean baseSearch) { final String entityTypeName = helper.getFinalTypeName(entity); JavaType serachResult = new JavaType( SEARCH_RESULTS.getFullyQualifiedTypeName(), 0, DataType.TYPE, null, Arrays.asList(entity)); if (jpaQueryMetadata != null) { String filterByInfo = String.format("%s.%s()", entityTypeName, jpaQueryMetadata.getFilterByMethodName().getSymbolName()); String orderByInfo = String.format("%s.%s()", entityTypeName, jpaQueryMetadata.getOrderByMethodName().getSymbolName()); // SearchResults<Pet> searchResult = // DatatablesUtils.findByCriteria(Pet.class, // Pet.getFilterByAssociations(), Pet.getOrderByAssociations(), // Pet.entityManager(), criterias); if (baseSearch) { bodyBuilder .appendFormalLine(String .format("%s searchResult = %s.findByCriteria(entity, %s.%s(), %s, baseSearch);", helper.getFinalTypeName(serachResult), helper.getFinalTypeName(DATATABLES_UTILS), entityTypeName, entityEntityManagerMethod .getSymbolName(), CRITERIA_PARAM_NAME.getSymbolName())); } else { bodyBuilder .appendFormalLine("// URL parameters are used as base search filters"); // Enumeration<String> parameterNames = // (Enumeration<String>)request.getParameterNames(); bodyBuilder.appendFormalLine(String.format( "%s parameterNames = (%s) %s.getParameterNames();", helper.getFinalTypeName(ENUMERATION_STRING), helper.getFinalTypeName(ENUMERATION_STRING), REQUEST_PARAM_NAME.getSymbolName())); // Map<String, Object> baseSearchValuesMap = getPropertyMap(pet, // parameterNames); bodyBuilder .appendFormalLine(String .format("%s baseSearchValuesMap = getPropertyMap(%s, parameterNames);", helper.getFinalTypeName(MAP_STRING_OBJECT), entityName)); bodyBuilder .appendFormalLine(String .format("%s searchResult = %s.findByCriteria(%s.class, %s, %s, %s.%s(), %s, baseSearchValuesMap);", helper.getFinalTypeName(serachResult), helper.getFinalTypeName(DATATABLES_UTILS), entityTypeName, filterByInfo, orderByInfo, entityTypeName, entityEntityManagerMethod .getSymbolName(), CRITERIA_PARAM_NAME.getSymbolName())); } } else { // SearchResults<Pet> searchResult = // DatatablesUtils.findByCriteria(Pet.class, // Pet.getFilterByAssociations(), Pet.getOrderByAssociations(), // Pet.entityManager(), criterias); if (baseSearch) { bodyBuilder .appendFormalLine(String .format("%s searchResult = %s.findByCriteria(entity, %s.%s(), %s, baseSearch);", helper.getFinalTypeName(serachResult), helper.getFinalTypeName(DATATABLES_UTILS), entityTypeName, entityEntityManagerMethod .getSymbolName(), CRITERIA_PARAM_NAME.getSymbolName())); } else { bodyBuilder .appendFormalLine("// URL parameters are used as base search filters"); // Enumeration<String> parameterNames = // (Enumeration<String>)request.getParameterNames(); bodyBuilder.appendFormalLine(String.format( "%s parameterNames = (%s) %s.getParameterNames();", helper.getFinalTypeName(ENUMERATION_STRING), helper.getFinalTypeName(ENUMERATION_STRING), REQUEST_PARAM_NAME.getSymbolName())); // Map<String, Object> baseSearchValuesMap = getPropertyMap(pet, // parameterNames); bodyBuilder .appendFormalLine(String .format("%s baseSearchValuesMap = getPropertyMap(%s, parameterNames);", helper.getFinalTypeName(MAP_STRING_OBJECT), entityName)); bodyBuilder .appendFormalLine(String .format("%s searchResult = %s.findByCriteria(%s.class, %s.%s(), %s, baseSearchValuesMap);", helper.getFinalTypeName(serachResult), helper.getFinalTypeName(DATATABLES_UTILS), entityTypeName, entityTypeName, entityEntityManagerMethod .getSymbolName(), CRITERIA_PARAM_NAME.getSymbolName())); } } bodyBuilder.appendFormalLine(""); bodyBuilder.appendFormalLine("// Get datatables required counts"); // long totalRecords = searchResult.getTotalCount(); bodyBuilder .appendFormalLine("long totalRecords = searchResult.getTotalCount();"); // long recordsFound = findResult.getResultsCount(); bodyBuilder .appendFormalLine("long recordsFound = searchResult.getResultsCount();"); return entityTypeName; } /** * Build method body for <code>findAll</code> method * * @param bodyBuilder */ private void buildFindAllDataMethodBody( InvocableMemberBodyBuilder bodyBuilder) { // Build call to FindByCriteria buildFindByCriteriaCall(bodyBuilder, false); buildPopulateDataSearchCall(bodyBuilder); } /** * Build method-code to perform a call to Datatables.populateDateSet method * * @param bodyBuilder */ private void buildPopulateDataSearchCall( InvocableMemberBodyBuilder bodyBuilder) { bodyBuilder.appendFormalLine(""); bodyBuilder.appendFormalLine("// Entity pk field name"); // String pkFieldName = "id"; bodyBuilder.appendFormalLine(String.format( "String pkFieldName = \"%s\";", entityIdentifier.getFieldName() .getSymbolName())); bodyBuilder.appendFormalLine(""); /* * DataSet<Map<String, String>> dataSet = * DatatablesUtils.populateDataSet(searchResult.getResult(), * pkFieldName, totalRecords, recordsFound, criterias.getColumnDefs(), * null, conversionService_datatables); */ bodyBuilder .appendFormalLine(String .format("%s dataSet = %s.populateDataSet(searchResult.getResults(), pkFieldName, totalRecords, recordsFound, criterias.getColumnDefs(), null, %s); ", helper.getFinalTypeName(DATA_SET_MAP_STRING_STRING), helper.getFinalTypeName(DATATABLES_UTILS), getConversionServiceField().getFieldName() .getSymbolName())); // return DatatablesResponse.build(dataSet,criterias); bodyBuilder.appendFormalLine(String.format( "return %s.build(dataSet,%s);", helper.getFinalTypeName(DATATABLES_RESPONSE), CRITERIA_PARAM_NAME.getSymbolName())); } /** * Create metadata for auto-wired convertionService field. * * @return a FieldMetadata object */ public FieldMetadata getConversionServiceField() { if (conversionService == null) { JavaSymbolName curName = new JavaSymbolName( "conversionService_datatables"); // Check if field exist FieldMetadata currentField = governorTypeDetails .getDeclaredField(curName); if (currentField != null) { if (currentField.getAnnotation(AUTOWIRED) == null || !currentField.getFieldType().equals( CONVERSION_SERVICE)) { // No compatible field: look for new name currentField = null; JavaSymbolName newName = curName; int i = 1; while (governorTypeDetails.getDeclaredField(newName) != null) { newName = new JavaSymbolName(curName.getSymbolName() .concat(StringUtils.repeat('_', i))); i++; } curName = newName; } } if (currentField != null) { conversionService = currentField; } else { // create field List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>( 1); annotations.add(new AnnotationMetadataBuilder(AUTOWIRED)); // Using the FieldMetadataBuilder to create the field // definition. final FieldMetadataBuilder fieldBuilder = new FieldMetadataBuilder( getId(), Modifier.PUBLIC, annotations, curName, // Field CONVERSION_SERVICE); // Field type conversionService = fieldBuilder.build(); // Build and return a // FieldMetadata // instance } } return conversionService; } /** * Informs if a method is already defined on class * * @param methodName * @param paramTypes * @return */ private MethodMetadata methodExists(JavaSymbolName methodName, List<AnnotatedJavaType> paramTypes) { return MemberFindingUtils.getDeclaredMethod(governorTypeDetails, methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(paramTypes)); } // Typically, no changes are required beyond this point public String toString() { final ToStringBuilder builder = new ToStringBuilder(this); builder.append("identifier", getId()); builder.append("valid", valid); builder.append("aspectName", aspectName); builder.append("destinationType", destination); builder.append("governor", governorPhysicalTypeMetadata.getId()); builder.append("ajax", String.valueOf(annotationValues.isAjax())); builder.append("itdTypeDetails", itdTypeDetails); return builder.toString(); } /** * @return related JPA entity */ public JavaType getEntity() { return entity; } /** * @return {@link GvNIXDatatables} annotation values */ public DatatablesAnnotationValues getAnnotationValues() { return annotationValues; } /** * @return {@link RooWebScaffold} annotation values */ public WebScaffoldAnnotationValues getWebScaffoldAnnotationValues() { return webScaffoldAnnotationValues; } /** * @return controllers use AJAX data mode or not (DOM) */ public boolean isAjax() { return annotationValues.isAjax(); } /** * @return controller entity properties for detail datatables */ public String[] getDetailFields() { return annotationValues.getDetailFields(); } /** * @return informs if controllers has JPA-Batch-operations support available */ public boolean hasJpaBatchSupport() { return webJpaBatchMetadata != null; } /** * @return datatables shows a standard list or use render-a-view mode */ public boolean isStantardMode() { return annotationValues.isStandardMode(); } /** * @return information about dynamic finder registered on the controller */ public Map<FinderMetadataDetails, QueryHolderTokens> getFindersRegistered() { return findersRegistered; } }
true
false
null
null
diff --git a/dedicaMNS/src/com/edwise/dedicamns/beans/ActivityDay.java b/dedicaMNS/src/com/edwise/dedicamns/beans/ActivityDay.java index ddc1d86..a2a75eb 100644 --- a/dedicaMNS/src/com/edwise/dedicamns/beans/ActivityDay.java +++ b/dedicaMNS/src/com/edwise/dedicamns/beans/ActivityDay.java @@ -1,110 +1,110 @@ /** * */ package com.edwise.dedicamns.beans; import java.io.Serializable; import com.edwise.dedicamns.utils.DayUtils; /** * @author edwise * */ public class ActivityDay implements Serializable { /** * */ private static final long serialVersionUID = 4988047922232822611L; private String hours; private String projectId; private String subProjectId; private String subProject; private String task; private String idActivity; - private boolean isUpdate; - private boolean toRemove; + private boolean isUpdate = false; + private boolean toRemove = false; public ActivityDay() { } public ActivityDay(ActivityDay copyActivityDay) { this.copyActivityDayData(copyActivityDay); } public String getIdActivity() { return idActivity; } public void setIdActivity(String idActivity) { this.idActivity = idActivity; } public String getHours() { return hours; } public void setHours(String hours) { this.hours = hours; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getSubProjectId() { return subProjectId; } public void setSubProjectId(String subProjectId) { this.subProjectId = subProjectId; } public String getSubProject() { return subProject; } public void setSubProject(String subProject) { this.subProject = subProject; } public String getTask() { return task; } public void setTask(String task) { this.task = DayUtils.getTaskNameWithoutNBSP(task); } public boolean isUpdate() { return isUpdate; } public void setUpdate(boolean isUpdate) { this.isUpdate = isUpdate; } public boolean isToRemove() { return toRemove; } public void setToRemove(boolean toRemove) { this.toRemove = toRemove; } public void copyActivityDayData(ActivityDay activityDay) { this.hours = activityDay.getHours(); this.projectId = activityDay.getProjectId(); this.subProjectId = activityDay.getSubProjectId(); this.subProject = activityDay.getSubProject(); this.task = activityDay.getTask(); } } diff --git a/dedicaMNS/src/com/edwise/dedicamns/connections/impl/MNSWebConnectionImpl.java b/dedicaMNS/src/com/edwise/dedicamns/connections/impl/MNSWebConnectionImpl.java index 0cfce9a..d0082eb 100644 --- a/dedicaMNS/src/com/edwise/dedicamns/connections/impl/MNSWebConnectionImpl.java +++ b/dedicaMNS/src/com/edwise/dedicamns/connections/impl/MNSWebConnectionImpl.java @@ -1,647 +1,649 @@ /** * */ package com.edwise.dedicamns.connections.impl; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.List; import net.maxters.android.ntlm.NTLM; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import com.edwise.dedicamns.R; import com.edwise.dedicamns.asynctasks.AppData; import com.edwise.dedicamns.beans.ActivityDay; import com.edwise.dedicamns.beans.DayRecord; import com.edwise.dedicamns.beans.MonthListBean; import com.edwise.dedicamns.beans.MonthReportBean; import com.edwise.dedicamns.beans.MonthReportRecord; import com.edwise.dedicamns.beans.MonthYearBean; import com.edwise.dedicamns.beans.ProjectSubprojectBean; import com.edwise.dedicamns.connections.ConnectionException; import com.edwise.dedicamns.connections.WebConnection; import com.edwise.dedicamns.db.DatabaseHelper; import com.edwise.dedicamns.utils.DayUtils; /** * @author edwise * */ public class MNSWebConnectionImpl implements WebConnection { private static final String LOGTAG = MNSWebConnectionImpl.class.toString(); private static final int TIMEOUT_GETDATA = 60000; private static final int TIMEOUT_CONNECTION = 30000; private static final int FIRST_YEAR = 2004; private static final String DOMAIN = "medianet2k"; private static final String URL_STR = "http://dedicaciones.medianet.es"; private static final String URL_STR_ACCOUNTS = "http://dedicaciones.medianet.es/Home/Accounts"; private static final String URL_STR_CREATE = "http://dedicaciones.medianet.es/Home/CreateActivity"; private static final String URL_STR_MODIFY = "http://dedicaciones.medianet.es/Home/EditActivity"; private static final String URL_STR_DELETE = "http://dedicaciones.medianet.es/Home/DeleteActivity"; private static final String URL_STR_CHANGE_DATE = "http://dedicaciones.medianet.es/Home/ChangeDate"; private static final String URL_STR_MONTH_REPORT = "http://dedicaciones.medianet.es/Home/MonthReport"; private DefaultHttpClient httpClient = null; private MonthYearBean monthYears = null; private ProjectSubprojectBean projects = null; @Override public boolean isOnline(Activity activity) { boolean online = false; ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { online = true; } return online; } @Override public Integer connectWeb(String userName, String password) throws ConnectionException { int responseCode; try { Log.d(LOGTAG, "connectWeb... inicio..."); responseCode = doLoginAndGetCookie(URL_STR, DOMAIN, userName, password); Log.d(LOGTAG, "connectWeb... fin..."); } catch (Exception e) { Log.e(LOGTAG, "Error en el acceso web", e); throw new ConnectionException(e); } return responseCode; } private int doLoginAndGetCookie(final String urlStr, final String domain, final String userName, final String password) throws ClientProtocolException, IOException, URISyntaxException { long beginTime = System.currentTimeMillis(); URL url = new URL(urlStr); createHttpClient(); NTLM.setNTLM(httpClient, userName, password, domain, null, -1); HttpGet get = new HttpGet(url.toURI()); HttpResponse resp = httpClient.execute(get); Log.d(LOGTAG, "StatusCode: " + resp.getStatusLine().getStatusCode() + " StatusLine: " + resp.getStatusLine().getReasonPhrase()); long endTime = System.currentTimeMillis(); Log.d(LOGTAG, "Tiempo login: " + (endTime - beginTime)); // 200 OK. 401 error return resp.getStatusLine().getStatusCode(); } private void createHttpClient() { httpClient = new DefaultHttpClient(); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_CONNECTION); HttpConnectionParams.setSoTimeout(params, TIMEOUT_GETDATA); } @Override public List<String> getMonths() { return this.monthYears.getMonths(); } @Override public List<String> getYears() { return this.monthYears.getYears(); } @Override public List<String> getArrayProjects() { return this.projects.getProjects(); } @Override public List<String> getArraySubProjects(String projectId) { return this.projects.getSubProjects(projectId); } @Override public void populateDBProjectsAndSubprojects() throws ConnectionException { long beginTime = System.currentTimeMillis(); this.projects = null; fillDBProyectsAndSubProyects(); long endTime = System.currentTimeMillis(); Log.d(LOGTAG, "Tiempo carga proyectos: " + (endTime - beginTime)); } @Override public void fillProyectsAndSubProyectsCached() throws ConnectionException { if (this.projects == null) { this.projects = AppData.getDatabaseHelper().getAllProjectsAndSubProjects(); } } private void fillDBProyectsAndSubProyects() throws ConnectionException { String html = this.getHttpContent(URL_STR_ACCOUNTS); Document document = Jsoup.parse(html); DatabaseHelper db = AppData.getDatabaseHelper(); String defaultSubProject = AppData.getCurrentActivity().getString(R.string.defaultSubProject); Elements selectSpansAccounts = document.select("span.Account"); if (selectSpansAccounts != null) { Iterator<Element> it = selectSpansAccounts.iterator(); while (it.hasNext()) { Element span = it.next(); String projectId = parseStringProjectId(span.html()); Element liParent = span.parent(); Element nextLiOrUl = liParent.nextElementSibling(); List<String> subProjects = new ArrayList<String>(); subProjects.add(defaultSubProject); if (nextLiOrUl != null) { Elements selectSpansSubAccounts = nextLiOrUl.select("span.Subaccount"); if (selectSpansSubAccounts != null) { Iterator<Element> subIt = selectSpansSubAccounts.iterator(); while (subIt.hasNext()) { Element subSpan = subIt.next(); subProjects.add(DayUtils.replaceAcutes(subSpan.html())); } } } db.insertProject(projectId, (String[]) subProjects.toArray(new String[subProjects.size()])); } } } private String parseStringProjectId(String projectName) { return projectName.trim().substring(0, projectName.indexOf(" -")); } @Override public void fillMonthsAndYearsCached() { if (monthYears == null) { fillMonthsAndYears(); } } private void fillMonthsAndYears() { List<String> months = generateMonthsList(); List<String> years = generateYearsList(); this.monthYears = new MonthYearBean(months, years); } private List<String> generateMonthsList() { List<String> monthsList = new ArrayList<String>(); monthsList.add("Enero"); monthsList.add("Febrero"); monthsList.add("Marzo"); monthsList.add("Abril"); monthsList.add("Mayo"); monthsList.add("Junio"); monthsList.add("Julio"); monthsList.add("Agosto"); monthsList.add("Septiembre"); monthsList.add("Octubre"); monthsList.add("Noviembre"); monthsList.add("Diciembre"); return monthsList; } private List<String> generateYearsList() { List<String> yearsList = new ArrayList<String>(); Calendar today = Calendar.getInstance(); int lastYear = today.get(Calendar.YEAR); if (today.get(Calendar.MONTH) == Calendar.DECEMBER) { // Si es diciembre, le añadimos ya el año siguiente, deberia estar ya... lastYear++; } for (int i = FIRST_YEAR; i <= lastYear; i++) { yearsList.add(String.valueOf(i)); } return yearsList; } private String getHttpContent(String url) throws ConnectionException { String html = null; try { long beginTime = System.currentTimeMillis(); URL urlObject = new URL(url); HttpGet get = new HttpGet(urlObject.toURI()); HttpResponse resp = httpClient.execute(get); Log.d(LOGTAG, "StatusCodeGET: " + resp.getStatusLine().getStatusCode() + " StatusLineGET: " + resp.getStatusLine().getReasonPhrase()); if (resp.getStatusLine().getStatusCode() != 200) { throw new ConnectionException("Error en la conexión, statusCode: " + resp.getStatusLine().getStatusCode()); } InputStream is = resp.getEntity().getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); html = writer.toString(); long endTime = System.currentTimeMillis(); Log.d(LOGTAG, "Tiempo conexión a " + url + ": " + (endTime - beginTime)); } catch (URISyntaxException e) { Log.e(LOGTAG, "Error de URI en el acceso getHttp a " + url, e); throw new ConnectionException(e); } catch (IOException e) { Log.e(LOGTAG, "Error IO en el acceso getHttp a " + url, e); throw new ConnectionException(e); } return html; } @Override public MonthListBean getListDaysAndActivitiesForCurrentMonth() throws ConnectionException { long beginTime = System.currentTimeMillis(); String html = this.getHttpContent(URL_STR); Document document = Jsoup.parse(html); Elements optionsMonth = document.select("#month > option[selected]"); Element optionMonth = optionsMonth.first(); String month = optionMonth.html(); String numMonth = optionMonth.val(); Elements optionsYear = document.select("#year > option[selected]"); Element optionYear = optionsYear.first(); String year = optionYear.html(); List<DayRecord> listDays = getListDaysMonth(document, numMonth, year, true); MonthListBean monthList = new MonthListBean(month, year, listDays); long endTime = System.currentTimeMillis(); Log.d(LOGTAG, "Tiempo carga lista mensual: " + (endTime - beginTime)); return monthList; } @Override public List<DayRecord> getListDaysAndActivitiesForMonthAndYear(int month, String year, boolean withActivities) throws ConnectionException { long beginTime = System.currentTimeMillis(); String html = doPostChangeDate(month, year); Document document = Jsoup.parse(html); List<DayRecord> listDays = getListDaysMonth(document, Integer.toString(month), year, withActivities); long endTime = System.currentTimeMillis(); Log.d(LOGTAG, "Tiempo carga lista mensual: " + (endTime - beginTime)); return listDays; } private String doPostChangeDate(int month, String year) throws ConnectionException { String html = null; try { URL urlObject = new URL(URL_STR_CHANGE_DATE); HttpPost post = new HttpPost(urlObject.toURI()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("IsValidation", "False")); nameValuePairs.add(new BasicNameValuePair("ActiveView", "Index")); nameValuePairs.add(new BasicNameValuePair("month", Integer.toString(month))); nameValuePairs.add(new BasicNameValuePair("year", year)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse resp = httpClient.execute(post); if (resp.getStatusLine().getStatusCode() != 200) { throw new ConnectionException("Error en la conexión, statusCode: " + resp.getStatusLine().getStatusCode()); } InputStream is = resp.getEntity().getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); html = writer.toString(); } catch (URISyntaxException e) { Log.e(LOGTAG, "Error de URI en el acceso doPostChangeDate a " + URL_STR_CHANGE_DATE, e); throw new ConnectionException(e); } catch (IOException e) { Log.e(LOGTAG, "Error IO en el acceso doPostChangeDate a " + URL_STR_CHANGE_DATE, e); throw new ConnectionException(e); } return html; } private List<DayRecord> getListDaysMonth(Document document, String numMonth, String year, boolean withActivities) throws ConnectionException { List<DayRecord> listDays = new ArrayList<DayRecord>(); Elements selectUlDays = document.select("#ListOfDays"); if (selectUlDays != null) { Element ulDays = selectUlDays.first(); Elements liDays = ulDays.children(); Iterator<Element> itDays = liDays.iterator(); while (itDays.hasNext()) { Element liDay = itDays.next(); Elements spanDayNumbers = liDay.select(".DayNumber"); Elements spanDayNInitials = liDay.select(".DayInitials"); Elements spanTotalHours = liDay.select(".TotalHours"); DayRecord dayRecord = new DayRecord(); dayRecord.setHours(spanTotalHours.first().html()); dayRecord.setIsWeekend("WeekendDay".equals(liDay.className())); dayRecord.setIsHoliday("Holiday".equals(liDay.className())); dayRecord.setDayNum(Integer.valueOf(spanDayNumbers.first().html())); dayRecord.setDayName(DayUtils.replaceAcutes(spanDayNInitials.first().html())); dayRecord.setDateForm(DayUtils.createDateString(dayRecord.getDayNum(), numMonth, year)); if (withActivities) { Elements selectUlActivities = liDay.select("ul.Activities"); Element ulActivities = selectUlActivities.first(); Elements liActivities = ulActivities.children(); Iterator<Element> itAct = liActivities.iterator(); while (itAct.hasNext()) { Element liActivity = itAct.next(); ActivityDay activityDay = new ActivityDay(); activityDay.setIdActivity(liActivity.select("input#id").val()); activityDay.setHours(liActivity.select("div.ActivityHours").html()); activityDay.setProjectId(liActivity.select("div.ActivityAccount span").html()); activityDay.setSubProject(""); activityDay.setSubProjectId(liActivity.select("div.ActivitySubaccount span").html()); activityDay.setTask(liActivity.select("div.ActivityTask").html()); activityDay.setUpdate(true); // Para marcarla como a actualizar, si la modificamos dayRecord.getActivities().add(activityDay); } } listDays.add(dayRecord); } } else { throw new ConnectionException("No existen datos de días en la página recibida!"); } return listDays; } @Override public Integer saveDay(ActivityDay activityDay, String dateForm, int dayNum) throws ConnectionException { Integer result = 0; String html = null; if (activityDay.isUpdate()) { html = this.doPostModify(activityDay, dateForm); } else { html = this.doPostCreate(activityDay, dateForm); } + // TODO refactorizar esto, ver como hacerlo (leer TODO del saveDayBatch) + Document document = Jsoup.parse(html); Elements errors = document.select(".input-validation-error"); if (errors != null && errors.size() > 0) { result = -3; } else { // Ok if (!activityDay.isUpdate()) { // Tenemos que obtener en este caso el id activityDay.setIdActivity(getIdFromActivityCreated(dayNum, document, activityDay)); } result = 1; } return result; } private String getIdFromActivityCreated(int dayNum, Document document, ActivityDay activityDay) { Elements divFrm = document.select("div#frmAC" + dayNum); Element divParent = divFrm.first().parent(); Elements liActivities = divParent.select("li.Activity"); Iterator<Element> it = liActivities.iterator(); String id = null; while (it.hasNext()) { Element liActivity = it.next(); String projectId = liActivity.select("div.ActivityAccount span").html(); String subProjectId = liActivity.select("div.ActivitySubaccount span").html(); String task = liActivity.select("div.ActivityTask").html(); if (activityDay.getProjectId().equals(projectId) && activityDay.getSubProjectId().equals(subProjectId) && activityDay.getTask().equals(DayUtils.getTaskNameWithoutNBSP(task))) { // Encontrada, nos quedamos con su id id = liActivity.select("input#id").val(); break; } } return id; } @Override public Integer removeDay(ActivityDay activityDay) throws ConnectionException { return doDelete(activityDay) ? 1 : -4; } private String doPostCreate(ActivityDay activityDay, String dateActivity) throws ConnectionException { String html = null; try { long beginTime = System.currentTimeMillis(); URL urlObject = new URL(URL_STR_CREATE); HttpPost post = new HttpPost(urlObject.toURI()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("Date", dateActivity)); nameValuePairs.add(new BasicNameValuePair("createActivity.Hours", activityDay.getHours())); nameValuePairs.add(new BasicNameValuePair("createActivity.AccountCode", activityDay.getProjectId())); nameValuePairs.add(new BasicNameValuePair("createActivity.SubaccountCode", activityDay.getSubProjectId())); nameValuePairs.add(new BasicNameValuePair("createActivity.Task", activityDay.getTask())); nameValuePairs.add(new BasicNameValuePair("ihScroll20", "0")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse resp = httpClient.execute(post); if (resp.getStatusLine().getStatusCode() != 200) { throw new ConnectionException("Error en la conexión, statusCode: " + resp.getStatusLine().getStatusCode()); } InputStream is = resp.getEntity().getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); html = writer.toString(); long endTime = System.currentTimeMillis(); Log.d(LOGTAG, "Tiempo conexión a " + URL_STR_CREATE + ": " + (endTime - beginTime)); } catch (URISyntaxException e) { Log.e(LOGTAG, "Error de URI en el acceso doPostCreate a " + URL_STR_CREATE, e); throw new ConnectionException(e); } catch (IOException e) { Log.e(LOGTAG, "Error IO en el acceso doPostCreate a " + URL_STR_CREATE, e); throw new ConnectionException(e); } return html; } private String doPostModify(ActivityDay activityDay, String dateActivity) throws ConnectionException { String html = null; try { long beginTime = System.currentTimeMillis(); URL urlObject = new URL(URL_STR_MODIFY); HttpPost post = new HttpPost(urlObject.toURI()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("Date", dateActivity)); nameValuePairs.add(new BasicNameValuePair("editActivity.id", activityDay.getIdActivity())); nameValuePairs.add(new BasicNameValuePair("id", activityDay.getIdActivity())); nameValuePairs.add(new BasicNameValuePair("editActivity.Hours", activityDay.getHours())); nameValuePairs.add(new BasicNameValuePair("editActivity.AccountCode", activityDay.getProjectId())); nameValuePairs.add(new BasicNameValuePair("editActivity.SubaccountCode", activityDay.getSubProjectId())); nameValuePairs.add(new BasicNameValuePair("editActivity.Task", activityDay.getTask())); nameValuePairs.add(new BasicNameValuePair("ihScroll" + activityDay.getIdActivity(), "0")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse resp = httpClient.execute(post); if (resp.getStatusLine().getStatusCode() != 200) { throw new ConnectionException("Error en la conexión, statusCode: " + resp.getStatusLine().getStatusCode()); } InputStream is = resp.getEntity().getContent(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); html = writer.toString(); long endTime = System.currentTimeMillis(); Log.d(LOGTAG, "Tiempo conexión a " + URL_STR_MODIFY + ": " + (endTime - beginTime)); } catch (URISyntaxException e) { Log.e(LOGTAG, "Error de URI en el acceso doPostModify a " + URL_STR_MODIFY, e); throw new ConnectionException(e); } catch (IOException e) { Log.e(LOGTAG, "Error IO en el acceso doPostModify a " + URL_STR_MODIFY, e); throw new ConnectionException(e); } return html; } private boolean doDelete(ActivityDay activityDay) throws ConnectionException { boolean deleted = false; StringBuilder urlWithParams = new StringBuilder(); urlWithParams.append(URL_STR_DELETE).append("?id=").append(activityDay.getIdActivity()).append("&ihdScroll") .append(activityDay.getIdActivity()).append("=0"); String html = this.getHttpContent(urlWithParams.toString()); if (html == null || html.length() == 0) { Log.w(LOGTAG, "No se ha podido borrar correctamente la actividad: " + activityDay.getIdActivity()); deleted = false; } else { deleted = true; } return deleted; } @Override public Integer saveDayBatch(DayRecord dayRecord) throws ConnectionException { Integer result = 0; for (ActivityDay activityDay : dayRecord.getActivities()) { // TODO Issue #15 esto es incorrecto, deberiamos llamar a saveDay, refactorizandolo antes. Necesitamos hacer // un setIdActivity al guardar cada actividad!!! // Si lo hacemos de esa manera nueva, quizá sea más lento... revisarlo bien. // ES NECESARIO hacerlo: el idactivity lo necesitamos para modificar o borrar, debemos tenerlo. // Y OJO!!! este metodo se llama desde el batch mensual!!! String html = this.doPostCreate(activityDay, dayRecord.getDateForm()); Document document = Jsoup.parse(html); Elements errors = document.select(".input-validation-error"); if (errors != null && errors.size() > 0) { result = -3; break; } else { // Ok result = 1; } } return result; } @Override public MonthReportBean getMonthReport() throws ConnectionException { long beginTime = System.currentTimeMillis(); String html = this.getHttpContent(URL_STR_MONTH_REPORT); Document document = Jsoup.parse(html); Elements optionsMonth = document.select("#month > option[selected]"); Element optionMonth = optionsMonth.first(); String month = optionMonth.html(); Elements optionsYear = document.select("#year > option[selected]"); Element optionYear = optionsYear.first(); String year = optionYear.html(); MonthReportBean monthReport = new MonthReportBean(month, year); Elements listOfAccounts = document.select("#ListOfAccounts"); Iterator<Element> accountIterator = listOfAccounts.select(".Account").iterator(); while (accountIterator.hasNext()) { Element accountHours = accountIterator.next(); MonthReportRecord monthReportRecord = createMonthReportRecordFromHtml(accountHours.html()); monthReport.addMonthReportRecord(monthReportRecord); } Elements totalHours = document.select(".HoursSum"); Element totalHoursElement = totalHours.first(); monthReport.setTotal(getTotalHoursFromHtml(totalHoursElement.html())); long endTime = System.currentTimeMillis(); Log.d(LOGTAG, "Tiempo carga informe mensual: " + (endTime - beginTime)); return monthReport; } private MonthReportRecord createMonthReportRecordFromHtml(String htmlAccount) { // Ejemplo valor htmlAccount -> BBVA68 : 161 horas String[] projectAndHours = htmlAccount.split(":"); String[] hours = projectAndHours[1].trim().split("\\s+"); return new MonthReportRecord(projectAndHours[0].trim(), hours[0]); } private String getTotalHoursFromHtml(String htmlTotalHours) { // Ejemplo valor htmlTotalHours -> Total: 161 horas String[] totalAndHours = htmlTotalHours.split(":"); String[] hours = totalAndHours[1].trim().split("\\s+"); return hours[0]; } }
false
false
null
null
diff --git a/org.eclipse.mylyn.bugzilla.tests/src/org/eclipse/mylyn/bugzilla/tests/TaskListNotificationManagerTest.java b/org.eclipse.mylyn.bugzilla.tests/src/org/eclipse/mylyn/bugzilla/tests/TaskListNotificationManagerTest.java index b81fa23ad..b4db922f5 100644 --- a/org.eclipse.mylyn.bugzilla.tests/src/org/eclipse/mylyn/bugzilla/tests/TaskListNotificationManagerTest.java +++ b/org.eclipse.mylyn.bugzilla.tests/src/org/eclipse/mylyn/bugzilla/tests/TaskListNotificationManagerTest.java @@ -1,136 +1,136 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.bugzilla.tests; import java.util.Date; import junit.framework.TestCase; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaRepositoryQuery; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaTask; import org.eclipse.mylyn.internal.tasks.core.LocalTask; import org.eclipse.mylyn.internal.tasks.ui.TaskListNotificationManager; import org.eclipse.mylyn.internal.tasks.ui.notifications.AbstractNotification; import org.eclipse.mylyn.internal.tasks.ui.notifications.TaskListNotification; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.AbstractTask.RepositoryTaskSyncState; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; /** * @author Rob Elves */ public class TaskListNotificationManagerTest extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testTaskListNotificationReminder() throws InterruptedException { Date now = new Date(); AbstractTask task0 = new LocalTask("0", "t0 - test 0"); AbstractTask task1 = new LocalTask("1", "t1 - test 1"); AbstractTask task2 = new LocalTask("2", "t2 - test 2"); task0.setScheduledForDate(new Date(now.getTime() - 2000)); task1.setScheduledForDate(new Date(now.getTime() - 2000)); task2.setScheduledForDate(new Date(now.getTime() - 2000)); TasksUiPlugin.getTaskListManager().getTaskList().addTask(task0); TasksUiPlugin.getTaskListManager().getTaskList().addTask(task1); TasksUiPlugin.getTaskListManager().getTaskList().addTask(task2); TaskListNotificationManager notificationManager = TasksUiPlugin.getTaskListNotificationManager(); notificationManager.collectNotifications(); task0 = TasksUiPlugin.getTaskListManager().getTaskList().getTask("local-0"); assertNotNull(task0); assertTrue(task0.isReminded()); task1 = TasksUiPlugin.getTaskListManager().getTaskList().getTask("local-1"); assertNotNull(task1); assertTrue(task1.isReminded()); task2 = TasksUiPlugin.getTaskListManager().getTaskList().getTask("local-2"); assertNotNull(task2); assertTrue(task2.isReminded()); } public void testTaskListNotificationIncoming() { TaskRepository repository = new TaskRepository("bugzilla", "https://bugs.eclipse.org/bugs"); TasksUiPlugin.getRepositoryManager().addRepository(repository, TasksUiPlugin.getDefault().getRepositoriesFilePath()); AbstractTask task = new BugzillaTask("https://bugs.eclipse.org/bugs", "142891", "label"); assertEquals(RepositoryTaskSyncState.SYNCHRONIZED, task.getSynchronizationState()); assertFalse(task.isNotified()); TasksUiPlugin.getTaskListManager().getTaskList().addTask(task); TaskListNotificationManager notificationManager = TasksUiPlugin.getTaskListNotificationManager(); notificationManager.collectNotifications(); TaskListNotification notification = new TaskListNotification(task); notification.setDescription("Unread task"); - assertTrue(notificationManager.getNotifications().contains(new TaskListNotification(task))); + assertTrue(notificationManager.getNotifications().contains(notification)); task = TasksUiPlugin.getTaskListManager().getTaskList().getTask("https://bugs.eclipse.org/bugs-142891"); assertNotNull(task); assertTrue(task.isNotified()); } public void testTaskListNotificationQueryIncoming() { BugzillaTask hit = new BugzillaTask("https://bugs.eclipse.org/bugs", "1", "summary"); assertFalse(hit.isNotified()); BugzillaRepositoryQuery query = new BugzillaRepositoryQuery("https://bugs.eclipse.org/bugs", "queryUrl", "summary"); TasksUiPlugin.getTaskListManager().getTaskList().addQuery(query); TasksUiPlugin.getTaskListManager().getTaskList().addTask(hit, query); TaskListNotificationManager notificationManager = TasksUiPlugin.getTaskListNotificationManager(); assertFalse(hit.isNotified()); notificationManager.collectNotifications(); for (AbstractNotification notification : notificationManager.getNotifications()) { notification.getLabel().equals(hit.getSummary()); } //assertTrue(notificationManager.getNotifications().contains(new TaskListNotificationQueryIncoming(hit))); assertTrue(hit.isNotified()); } public void testTaskListNotificationQueryIncomingRepeats() { TasksUiPlugin.getTaskListManager().resetTaskList(); BugzillaTask hit = new BugzillaTask("https://bugs.eclipse.org/bugs", "1", "summary"); String hitHandle = hit.getHandleIdentifier(); assertFalse(hit.isNotified()); BugzillaRepositoryQuery query = new BugzillaRepositoryQuery("https://bugs.eclipse.org/bugs", "queryUrl", "summary"); TasksUiPlugin.getTaskListManager().getTaskList().addQuery(query); TasksUiPlugin.getTaskListManager().getTaskList().addTask(hit, query); TaskListNotificationManager notificationManager = TasksUiPlugin.getTaskListNotificationManager(); notificationManager.collectNotifications(); for (AbstractNotification notification : notificationManager.getNotifications()) { notification.getLabel().equals(hit.getSummary()); } //assertTrue(notificationManager.getNotifications().iterator().next().equals(new TaskListNotificationQueryIncoming(hit))); assertTrue(hit.isNotified()); TasksUiPlugin.getTaskListManager().saveTaskList(); TasksUiPlugin.getTaskListManager().resetTaskList(); assertEquals(0, TasksUiPlugin.getTaskListManager().getTaskList().getQueries().size()); assertTrue(TasksUiPlugin.getTaskListManager().readExistingOrCreateNewList()); assertEquals(1, TasksUiPlugin.getTaskListManager().getTaskList().getQueries().size()); BugzillaTask hitLoaded = (BugzillaTask) TasksUiPlugin.getTaskListManager().getTaskList().getTask(hitHandle); assertNotNull(hitLoaded); assertTrue(hitLoaded.isNotified()); } }
true
false
null
null
diff --git a/src/com/android/providers/calendar/CalendarSyncAdapter.java b/src/com/android/providers/calendar/CalendarSyncAdapter.java index a9ae863..a9e7988 100644 --- a/src/com/android/providers/calendar/CalendarSyncAdapter.java +++ b/src/com/android/providers/calendar/CalendarSyncAdapter.java @@ -1,1736 +1,1739 @@ /* ** ** Copyright 2006, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** See the License for the specific language governing permissions and ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** limitations under the License. */ package com.android.providers.calendar; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AuthenticatorException; import android.accounts.Constants; import android.accounts.OperationCanceledException; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.SyncContext; import android.content.SyncResult; import android.content.SyncableContentProvider; import android.database.Cursor; import android.database.CursorJoiner; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.SystemProperties; import android.pim.ICalendar; import android.pim.RecurrenceSet; import android.provider.Calendar; import android.provider.Calendar.Calendars; import android.provider.Calendar.Events; import android.provider.SubscribedFeeds; import android.provider.SyncConstValue; import android.text.TextUtils; import android.text.format.Time; import android.util.Config; import android.util.Log; import com.google.android.gdata.client.AndroidGDataClient; import com.google.android.gdata.client.AndroidXmlParserFactory; import com.google.android.googlelogin.GoogleLoginServiceConstants; import com.google.android.providers.AbstractGDataSyncAdapter; import com.google.wireless.gdata.calendar.client.CalendarClient; import com.google.wireless.gdata.calendar.data.CalendarEntry; import com.google.wireless.gdata.calendar.data.CalendarsFeed; import com.google.wireless.gdata.calendar.data.EventEntry; import com.google.wireless.gdata.calendar.data.EventsFeed; import com.google.wireless.gdata.calendar.data.Reminder; import com.google.wireless.gdata.calendar.data.When; import com.google.wireless.gdata.calendar.data.Who; import com.google.wireless.gdata.calendar.parser.xml.XmlCalendarGDataParserFactory; import com.google.wireless.gdata.client.GDataServiceClient; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.client.QueryParams; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.data.Feed; import com.google.wireless.gdata.data.StringUtils; import com.google.wireless.gdata.parser.GDataParser; import com.google.wireless.gdata.parser.ParseException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Set; import java.util.TimeZone; import java.util.Vector; import java.net.URLDecoder; /** * SyncAdapter for Google Calendar. Fetches the list of the user's calendars, * and for each calendar that is marked as &quot;selected&quot; in the web * interface, syncs that calendar. */ public final class CalendarSyncAdapter extends AbstractGDataSyncAdapter { /* package */ static final String USER_AGENT_APP_VERSION = "Android-GData-Calendar/1.1"; private static final String SELECT_BY_ACCOUNT = Calendars._SYNC_ACCOUNT + "=? AND " + Calendars._SYNC_ACCOUNT_TYPE + "=?"; private static final String SELECT_BY_ACCOUNT_AND_FEED = SELECT_BY_ACCOUNT + " AND " + Calendars.URL + "=?"; private static final String[] CALENDAR_KEY_COLUMNS = new String[]{Calendars._SYNC_ACCOUNT, Calendars._SYNC_ACCOUNT_TYPE, Calendars.URL}; private static final String CALENDAR_KEY_SORT_ORDER = Calendars._SYNC_ACCOUNT + "," + Calendars._SYNC_ACCOUNT_TYPE + "," + Calendars.URL; private static final String[] FEEDS_KEY_COLUMNS = new String[]{SubscribedFeeds.Feeds._SYNC_ACCOUNT, SubscribedFeeds.Feeds._SYNC_ACCOUNT_TYPE, SubscribedFeeds.Feeds.FEED}; private static final String FEEDS_KEY_SORT_ORDER = SubscribedFeeds.Feeds._SYNC_ACCOUNT + ", " + SubscribedFeeds.Feeds._SYNC_ACCOUNT_TYPE + ", " + SubscribedFeeds.Feeds.FEED; private static final String PRIVATE_FULL = "/private/full"; private static final String FEEDS_SUBSTRING = "/feeds/"; private static final String FULL_SELFATTENDANCE = "/full-selfattendance/"; /** System property to enable sliding window sync **/ private static final String USE_SLIDING_WINDOW = "sync.slidingwindows"; public static class SyncInfo { // public String feedUrl; public long calendarId; public String calendarTimezone; } private static final String TAG = "Sync"; private static final Integer sTentativeStatus = Events.STATUS_TENTATIVE; private static final Integer sConfirmedStatus = Events.STATUS_CONFIRMED; private static final Integer sCanceledStatus = Events.STATUS_CANCELED; private final CalendarClient mCalendarClient; private ContentResolver mContentResolver; private static final String[] CALENDARS_PROJECTION = new String[] { Calendars._ID, // 0 Calendars.SELECTED, // 1 Calendars._SYNC_TIME, // 2 Calendars.URL, // 3 Calendars.DISPLAY_NAME, // 4 Calendars.TIMEZONE, // 5 Calendars.SYNC_EVENTS // 6 }; // Counters for sync event logging private static int mServerDiffs; private static int mRefresh; /** These are temporary until a real policy is implemented. **/ private static final long MONTH_IN_MS = 2592000000L; // 30 days private static final long YEAR_IN_MS = 31600000000L; // approximately protected CalendarSyncAdapter(Context context, SyncableContentProvider provider) { super(context, provider); mCalendarClient = new CalendarClient( new AndroidGDataClient(context, USER_AGENT_APP_VERSION), new XmlCalendarGDataParserFactory(new AndroidXmlParserFactory())); } @Override protected Object createSyncInfo() { return new SyncInfo(); } @Override protected Entry newEntry() { return new EventEntry(); } @Override protected Cursor getCursorForTable(ContentProvider cp, Class entryClass) { if (entryClass != EventEntry.class) { throw new IllegalArgumentException("unexpected entry class, " + entryClass.getName()); } return cp.query(Calendar.Events.CONTENT_URI, null, null, null, null); } @Override protected Cursor getCursorForDeletedTable(ContentProvider cp, Class entryClass) { if (entryClass != EventEntry.class) { throw new IllegalArgumentException("unexpected entry class, " + entryClass.getName()); } return cp.query(Calendar.Events.DELETED_CONTENT_URI, null, null, null, null); } @Override protected String cursorToEntry(SyncContext context, Cursor c, Entry entry, Object info) throws ParseException { EventEntry event = (EventEntry) entry; SyncInfo syncInfo = (SyncInfo) info; String feedUrl = c.getString(c.getColumnIndex(Calendars.URL)); // update the sync info. this will be used later when we update the // provider with the results of sending this entry to the calendar // server. syncInfo.calendarId = c.getLong(c.getColumnIndex(Events.CALENDAR_ID)); syncInfo.calendarTimezone = c.getString(c.getColumnIndex(Events.EVENT_TIMEZONE)); if (TextUtils.isEmpty(syncInfo.calendarTimezone)) { // if the event timezone is not set -- e.g., when we're creating an // event on the device -- we will use the timezone for the calendar. syncInfo.calendarTimezone = c.getString(c.getColumnIndex(Events.TIMEZONE)); } // id event.setId(c.getString(c.getColumnIndex(Events._SYNC_ID))); event.setEditUri(c.getString(c.getColumnIndex(Events._SYNC_VERSION))); // status byte status; int localStatus = c.getInt(c.getColumnIndex(Events.STATUS)); switch (localStatus) { case Events.STATUS_CANCELED: status = EventEntry.STATUS_CANCELED; break; case Events.STATUS_CONFIRMED: status = EventEntry.STATUS_CONFIRMED; break; case Events.STATUS_TENTATIVE: status = EventEntry.STATUS_TENTATIVE; break; default: // should not happen status = EventEntry.STATUS_TENTATIVE; break; } event.setStatus(status); // visibility byte visibility; int localVisibility = c.getInt(c.getColumnIndex(Events.VISIBILITY)); switch (localVisibility) { case Events.VISIBILITY_DEFAULT: visibility = EventEntry.VISIBILITY_DEFAULT; break; case Events.VISIBILITY_CONFIDENTIAL: visibility = EventEntry.VISIBILITY_CONFIDENTIAL; break; case Events.VISIBILITY_PRIVATE: visibility = EventEntry.VISIBILITY_PRIVATE; break; case Events.VISIBILITY_PUBLIC: visibility = EventEntry.VISIBILITY_PUBLIC; break; default: // should not happen Log.e(TAG, "Unexpected value for visibility: " + localVisibility + "; using default visibility."); visibility = EventEntry.VISIBILITY_DEFAULT; break; } event.setVisibility(visibility); byte transparency; int localTransparency = c.getInt(c.getColumnIndex(Events.TRANSPARENCY)); switch (localTransparency) { case Events.TRANSPARENCY_OPAQUE: transparency = EventEntry.TRANSPARENCY_OPAQUE; break; case Events.TRANSPARENCY_TRANSPARENT: transparency = EventEntry.TRANSPARENCY_TRANSPARENT; break; default: // should not happen Log.e(TAG, "Unexpected value for transparency: " + localTransparency + "; using opaque transparency."); transparency = EventEntry.TRANSPARENCY_OPAQUE; break; } event.setTransparency(transparency); // could set the html uri, but there's no need to, since it should not be edited. // title event.setTitle(c.getString(c.getColumnIndex(Events.TITLE))); // description event.setContent(c.getString(c.getColumnIndex(Events.DESCRIPTION))); // where event.setWhere(c.getString(c.getColumnIndex(Events.EVENT_LOCATION))); // attendees long eventId = c.getInt(c.getColumnIndex(Events._SYNC_LOCAL_ID)); addAttendeesToEntry(eventId, event); // comment uri event.setCommentsUri(c.getString(c.getColumnIndexOrThrow(Events.COMMENTS_URI))); Time utc = new Time(Time.TIMEZONE_UTC); boolean allDay = c.getInt(c.getColumnIndex(Events.ALL_DAY)) != 0; String startTime = null; String endTime = null; // start time int dtstartColumn = c.getColumnIndex(Events.DTSTART); if (!c.isNull(dtstartColumn)) { long dtstart = c.getLong(dtstartColumn); utc.set(dtstart); startTime = utc.format3339(allDay); } // end time int dtendColumn = c.getColumnIndex(Events.DTEND); if (!c.isNull(dtendColumn)) { long dtend = c.getLong(dtendColumn); utc.set(dtend); endTime = utc.format3339(allDay); } When when = new When(startTime, endTime); event.addWhen(when); // reminders Integer hasReminder = c.getInt(c.getColumnIndex(Events.HAS_ALARM)); if (hasReminder != null && hasReminder.intValue() != 0) { addRemindersToEntry(eventId, event); } // extendedProperties Integer hasExtendedProperties = c.getInt(c.getColumnIndex(Events.HAS_EXTENDED_PROPERTIES)); if (hasExtendedProperties != null && hasExtendedProperties.intValue() != 0) { addExtendedPropertiesToEntry(eventId, event); } long originalStartTime = -1; String originalId = c.getString(c.getColumnIndex(Events.ORIGINAL_EVENT)); int originalStartTimeIndex = c.getColumnIndex(Events.ORIGINAL_INSTANCE_TIME); if (!c.isNull(originalStartTimeIndex)) { originalStartTime = c.getLong(originalStartTimeIndex); } if ((originalStartTime != -1) && !TextUtils.isEmpty(originalId)) { // We need to use the "originalAllDay" field for the original event // in order to format the "originalStartTime" correctly. boolean originalAllDay = c.getInt(c.getColumnIndex(Events.ORIGINAL_ALL_DAY)) != 0; String timezone = c.getString(c.getColumnIndex(Events.EVENT_TIMEZONE)); if (TextUtils.isEmpty(timezone)) { timezone = TimeZone.getDefault().getID(); } Time originalTime = new Time(timezone); originalTime.set(originalStartTime); utc.set(originalStartTime); event.setOriginalEventStartTime(utc.format3339(originalAllDay)); event.setOriginalEventId(originalId); } // recurrences. ICalendar.Component component = new ICalendar.Component("DUMMY", null /* parent */); if (RecurrenceSet.populateComponent(c, component)) { addRecurrenceToEntry(component, event); } + // For now, always want to send event notifications + event.setSendEventNotifications(true); + // if this is a new entry, return the feed url. otherwise, return null; the edit url is // already in the entry. if (event.getEditUri() == null) { return feedUrl; } else { return null; } } private void addAttendeesToEntry(long eventId, EventEntry event) throws ParseException { Cursor c = getContext().getContentResolver().query( Calendar.Attendees.CONTENT_URI, null, "event_id=" + eventId, null, null); try { int nameIndex = c.getColumnIndexOrThrow(Calendar.Attendees.ATTENDEE_NAME); int emailIndex = c.getColumnIndexOrThrow(Calendar.Attendees.ATTENDEE_EMAIL); int statusIndex = c.getColumnIndexOrThrow(Calendar.Attendees.ATTENDEE_STATUS); int typeIndex = c.getColumnIndexOrThrow(Calendar.Attendees.ATTENDEE_TYPE); int relIndex = c.getColumnIndexOrThrow(Calendar.Attendees.ATTENDEE_RELATIONSHIP); while (c.moveToNext()) { Who who = new Who(); who.setValue(c.getString(nameIndex)); who.setEmail(c.getString(emailIndex)); int status = c.getInt(statusIndex); switch (status) { case Calendar.Attendees.ATTENDEE_STATUS_NONE: who.setStatus(Who.STATUS_NONE); break; case Calendar.Attendees.ATTENDEE_STATUS_ACCEPTED: who.setStatus(Who.STATUS_ACCEPTED); break; case Calendar.Attendees.ATTENDEE_STATUS_DECLINED: who.setStatus(Who.STATUS_DECLINED); break; case Calendar.Attendees.ATTENDEE_STATUS_INVITED: who.setStatus(Who.STATUS_INVITED); break; case Calendar.Attendees.ATTENDEE_STATUS_TENTATIVE: who.setStatus(Who.STATUS_TENTATIVE); break; default: Log.e(TAG, "Unknown attendee status: " + status); who.setStatus(Who.STATUS_NONE); break; } int type = c.getInt(typeIndex); switch (type) { case Calendar.Attendees.TYPE_NONE: who.setType(Who.TYPE_NONE); break; case Calendar.Attendees.TYPE_REQUIRED: who.setType(Who.TYPE_REQUIRED); break; case Calendar.Attendees.TYPE_OPTIONAL: who.setType(Who.TYPE_OPTIONAL); break; default: Log.e(TAG, "Unknown attendee type: " + type); who.setType(Who.TYPE_NONE); break; } int rel = c.getInt(relIndex); switch (rel) { case Calendar.Attendees.RELATIONSHIP_NONE: who.setRelationship(Who.RELATIONSHIP_NONE); break; case Calendar.Attendees.RELATIONSHIP_ATTENDEE: who.setRelationship(Who.RELATIONSHIP_ATTENDEE); break; case Calendar.Attendees.RELATIONSHIP_ORGANIZER: who.setRelationship(Who.RELATIONSHIP_ORGANIZER); break; case Calendar.Attendees.RELATIONSHIP_SPEAKER: who.setRelationship(Who.RELATIONSHIP_SPEAKER); break; case Calendar.Attendees.RELATIONSHIP_PERFORMER: who.setRelationship(Who.RELATIONSHIP_PERFORMER); break; default: Log.e(TAG, "Unknown attendee relationship: " + rel); who.setRelationship(Who.RELATIONSHIP_NONE); break; } event.addAttendee(who); } } finally { c.close(); } } private void addRemindersToEntry(long eventId, EventEntry event) throws ParseException { Cursor c = getContext().getContentResolver().query( Calendar.Reminders.CONTENT_URI, null, "event_id=" + eventId, null, null); try { int methodIndex = c.getColumnIndex(Calendar.Reminders.METHOD); int minutesIndex = c.getColumnIndex(Calendar.Reminders.MINUTES); while (c.moveToNext()) { Reminder reminder = new Reminder(); reminder.setMinutes(c.getInt(minutesIndex)); int method = c.getInt(methodIndex); switch(method) { case Calendar.Reminders.METHOD_DEFAULT: reminder.setMethod(Reminder.METHOD_DEFAULT); break; case Calendar.Reminders.METHOD_ALERT: reminder.setMethod(Reminder.METHOD_ALERT); break; case Calendar.Reminders.METHOD_EMAIL: reminder.setMethod(Reminder.METHOD_EMAIL); break; case Calendar.Reminders.METHOD_SMS: reminder.setMethod(Reminder.METHOD_SMS); break; default: throw new ParseException("illegal method, " + method); } event.addReminder(reminder); } } finally { c.close(); } } private void addExtendedPropertiesToEntry(long eventId, EventEntry event) throws ParseException { Cursor c = getContext().getContentResolver().query( Calendar.ExtendedProperties.CONTENT_URI, null, "event_id=" + eventId, null, null); try { int nameIndex = c.getColumnIndex(Calendar.ExtendedProperties.NAME); int valueIndex = c.getColumnIndex(Calendar.ExtendedProperties.VALUE); while (c.moveToNext()) { String name = c.getString(nameIndex); String value = c.getString(valueIndex); event.addExtendedProperty(name, value); } } finally { c.close(); } } private void addRecurrenceToEntry(ICalendar.Component component, EventEntry event) { // serialize the component into a Google Calendar recurrence string // we don't serialize the entire component, since we have a dummy // wrapper (BEGIN:DUMMY, END:DUMMY). StringBuilder sb = new StringBuilder(); // append the properties boolean first = true; for (String propertyName : component.getPropertyNames()) { for (ICalendar.Property property : component.getProperties(propertyName)) { if (first) { first = false; } else { sb.append("\n"); } property.toString(sb); } } // append the sub-components List<ICalendar.Component> children = component.getComponents(); if (children != null) { for (ICalendar.Component child : children) { if (first) { first = false; } else { sb.append("\n"); } child.toString(sb); } } event.setRecurrence(sb.toString()); } @Override protected void deletedCursorToEntry(SyncContext context, Cursor c, Entry entry) { EventEntry event = (EventEntry) entry; event.setId(c.getString(c.getColumnIndex(Events._SYNC_ID))); event.setEditUri(c.getString(c.getColumnIndex(Events._SYNC_VERSION))); event.setStatus(EventEntry.STATUS_CANCELED); } protected boolean handleAllDeletedUnavailable(GDataSyncData syncData, String feed) { syncData.feedData.remove(feed); final Account account = getAccount(); getContext().getContentResolver().delete(Calendar.Calendars.CONTENT_URI, Calendar.Calendars._SYNC_ACCOUNT + "=? AND " + Calendar.Calendars._SYNC_ACCOUNT_TYPE + "=? AND " + Calendar.Calendars.URL + "=?", new String[]{account.mName, account.mType, feed}); return true; } @Override public void onSyncStarting(SyncContext context, Account account, boolean manualSync, SyncResult result) { mContentResolver = getContext().getContentResolver(); mServerDiffs = 0; mRefresh = 0; super.onSyncStarting(context, account, manualSync, result); } private void deletedEntryToContentValues(Long syncLocalId, EventEntry event, ContentValues values) { // see #deletedCursorToEntry. this deletion cannot be an exception to a recurrence (e.g., // deleting an instance of a repeating event) -- new recurrence exceptions would be // insertions. values.clear(); // Base sync info values.put(Events._SYNC_LOCAL_ID, syncLocalId); values.put(Events._SYNC_ID, event.getId()); values.put(Events._SYNC_VERSION, event.getEditUri()); } /** * Clear out the map and stuff an Entry into it in a format that can * be inserted into a content provider. * * If a date is before 1970 or past 2038, ENTRY_INVALID is returned, and DTSTART * is set to -1. This is due to the current 32-bit time restriction and * will be fixed in a future release. * * @return ENTRY_OK, ENTRY_DELETED, or ENTRY_INVALID */ private int entryToContentValues(EventEntry event, Long syncLocalId, ContentValues map, Object info) { SyncInfo syncInfo = (SyncInfo) info; // There are 3 cases for parsing a date-time string: // // 1. The date-time string specifies a date and time with a time offset. // (The "normal" format.) // 2. The date-time string is just a date, used for all-day events, // with no time or time offset fields. (The "all-day" format.) // 3. The date-time string specifies a date and time, but no time // offset. (The "floating" format, not supported yet.) // // Case 1: Time.parse3339() converts the date-time string to UTC and // sets the Time.timezone to UTC. It does not matter what the initial // Time.timezone field was set to. The initial timezone is ignored. // // Case 2: The date-time string doesn't specify the time. // Time.parse3339() just sets the date but not the time (hour, minute, // second) fields. (The time fields should be zero, meaning midnight.) // This code then sets the timezone to UTC (because this is an all-day // event). It does not matter in this case either what the initial // Time.timezone field was set to. // // Case 3: This is a "floating time" (which we do not support yet). // In this case, it will matter what the initial Time.timezone is set // to. It should use UTC. If I specify a floating time of 1pm then I // want that event displayed at 1pm in every timezone. The easiest way // to support this would be store it as 1pm in UTC and mark the event // as "isFloating" (with a new database column). Then when displaying // the event, the code checks "isFloating" and just leaves the time at // 1pm without doing any conversion to the local timezone. // // So in all cases, it is correct to set the Time.timezone to UTC. Time time = new Time(Time.TIMEZONE_UTC); map.clear(); // Base sync info map.put(Events._SYNC_ID, event.getId()); String version = event.getEditUri(); final Account account = getAccount(); if (!StringUtils.isEmpty(version)) { // Always rewrite the edit URL to https for dasher account to avoid // redirection. map.put(Events._SYNC_VERSION, rewriteUrlforAccount(account, version)); } // see if this is an exception to an existing event/recurrence. String originalId = event.getOriginalEventId(); String originalStartTime = event.getOriginalEventStartTime(); boolean isRecurrenceException = false; if (!StringUtils.isEmpty(originalId) && !StringUtils.isEmpty(originalStartTime)) { isRecurrenceException = true; time.parse3339(originalStartTime); map.put(Events.ORIGINAL_EVENT, originalId); map.put(Events.ORIGINAL_INSTANCE_TIME, time.toMillis(false /* use isDst */)); map.put(Events.ORIGINAL_ALL_DAY, time.allDay ? 1 : 0); } // Event status byte status = event.getStatus(); switch (status) { case EventEntry.STATUS_CANCELED: if (!isRecurrenceException) { return ENTRY_DELETED; } map.put(Events.STATUS, sCanceledStatus); break; case EventEntry.STATUS_TENTATIVE: map.put(Events.STATUS, sTentativeStatus); break; case EventEntry.STATUS_CONFIRMED: map.put(Events.STATUS, sConfirmedStatus); break; default: // should not happen return ENTRY_INVALID; } map.put(Events._SYNC_LOCAL_ID, syncLocalId); // Updated time, only needed for non-deleted items String updated = event.getUpdateDate(); map.put(Events._SYNC_TIME, updated); map.put(Events._SYNC_DIRTY, 0); // visibility switch (event.getVisibility()) { case EventEntry.VISIBILITY_DEFAULT: map.put(Events.VISIBILITY, Events.VISIBILITY_DEFAULT); break; case EventEntry.VISIBILITY_CONFIDENTIAL: map.put(Events.VISIBILITY, Events.VISIBILITY_CONFIDENTIAL); break; case EventEntry.VISIBILITY_PRIVATE: map.put(Events.VISIBILITY, Events.VISIBILITY_PRIVATE); break; case EventEntry.VISIBILITY_PUBLIC: map.put(Events.VISIBILITY, Events.VISIBILITY_PUBLIC); break; default: // should not happen Log.e(TAG, "Unexpected visibility " + event.getVisibility()); return ENTRY_INVALID; } // transparency switch (event.getTransparency()) { case EventEntry.TRANSPARENCY_OPAQUE: map.put(Events.TRANSPARENCY, Events.TRANSPARENCY_OPAQUE); break; case EventEntry.TRANSPARENCY_TRANSPARENT: map.put(Events.TRANSPARENCY, Events.TRANSPARENCY_TRANSPARENT); break; default: // should not happen Log.e(TAG, "Unexpected transparency " + event.getTransparency()); return ENTRY_INVALID; } // html uri String htmlUri = event.getHtmlUri(); if (!StringUtils.isEmpty(htmlUri)) { // TODO: convert this desktop url into a mobile one? // htmlUri = htmlUri.replace("/event?", "/mevent?"); // but a little more robust map.put(Events.HTML_URI, htmlUri); } // title String title = event.getTitle(); if (!StringUtils.isEmpty(title)) { map.put(Events.TITLE, title); } // content String content = event.getContent(); if (!StringUtils.isEmpty(content)) { map.put(Events.DESCRIPTION, content); } // where String where = event.getWhere(); if (!StringUtils.isEmpty(where)) { map.put(Events.EVENT_LOCATION, where); } // Calendar ID map.put(Events.CALENDAR_ID, syncInfo.calendarId); // comments uri String commentsUri = event.getCommentsUri(); if (commentsUri != null) { map.put(Events.COMMENTS_URI, commentsUri); } boolean timesSet = false; // see if there are any reminders for this event if (event.getReminders() != null) { // just store that we have reminders. the caller will have // to update the reminders table separately. map.put(Events.HAS_ALARM, 1); } // see if there are any extended properties for this event if (event.getExtendedProperties() != null) { // just store that we have extended properties. the caller will have // to update the extendedproperties table separately. map.put(Events.HAS_EXTENDED_PROPERTIES, 1); } // dtstart & dtend When when = event.getFirstWhen(); if (when != null) { String startTime = when.getStartTime(); if (!StringUtils.isEmpty(startTime)) { time.parse3339(startTime); // we also stash away the event's timezone. // this timezone might get overwritten below, if this event is // a recurrence (recurrences are defined in terms of the // timezone of the creator of the event). // note that we treat all day events as occurring in the UTC timezone, so // an event on 05/08/2007 occurs on 05/08/2007, no matter what timezone the device // is in. // TODO: handle the "floating" timezone. if (time.allDay) { map.put(Events.ALL_DAY, 1); map.put(Events.EVENT_TIMEZONE, Time.TIMEZONE_UTC); } else { map.put(Events.EVENT_TIMEZONE, syncInfo.calendarTimezone); } long dtstart = time.toMillis(false /* use isDst */); if (dtstart < 0) { if (Config.LOGD) { Log.d(TAG, "dtstart out of range: " + startTime); } map.put(Events.DTSTART, -1); // Flag to caller that date is out of range return ENTRY_INVALID; } map.put(Events.DTSTART, dtstart); timesSet = true; } String endTime = when.getEndTime(); if (!StringUtils.isEmpty(endTime)) { time.parse3339(endTime); long dtend = time.toMillis(false /* use isDst */); if (dtend < 0) { if (Config.LOGD) { Log.d(TAG, "dtend out of range: " + endTime); } map.put(Events.DTSTART, -1); // Flag to caller that date is out of range return ENTRY_INVALID; } map.put(Events.DTEND, dtend); } } // rrule String recurrence = event.getRecurrence(); if (!TextUtils.isEmpty(recurrence)) { ICalendar.Component recurrenceComponent = new ICalendar.Component("DUMMY", null /* parent */); ICalendar ical = null; try { ICalendar.parseComponent(recurrenceComponent, recurrence); } catch (ICalendar.FormatException fe) { if (Config.LOGD) { Log.d(TAG, "Unable to parse recurrence: " + recurrence); } return ENTRY_INVALID; } if (!RecurrenceSet.populateContentValues(recurrenceComponent, map)) { return ENTRY_INVALID; } timesSet = true; } if (!timesSet) { return ENTRY_INVALID; } map.put(SyncConstValue._SYNC_ACCOUNT, account.mName); map.put(SyncConstValue._SYNC_ACCOUNT_TYPE, account.mType); map.put(Events.HAS_ATTENDEE_DATA, !event.getId().contains(FULL_SELFATTENDANCE)); return ENTRY_OK; } public void updateProvider(Feed feed, Long syncLocalId, Entry entry, ContentProvider provider, Object info, GDataSyncData.FeedData feedSyncData) throws ParseException { SyncInfo syncInfo = (SyncInfo) info; EventEntry event = (EventEntry) entry; ContentValues map = new ContentValues(); // use the calendar's timezone, if provided in the feed. // this overwrites whatever was in the db. if ((feed != null) && (feed instanceof EventsFeed)) { EventsFeed eventsFeed = (EventsFeed) feed; syncInfo.calendarTimezone = eventsFeed.getTimezone(); } if (entry.isDeleted()) { deletedEntryToContentValues(syncLocalId, event, map); if (Config.LOGV) { Log.v(TAG, "Deleting entry: " + map); } provider.insert(Events.DELETED_CONTENT_URI, map); return; } int entryState = entryToContentValues(event, syncLocalId, map, syncInfo); // See if event is inside the window if (entryState == ENTRY_OK && feedSyncData.newWindowEnd == 0) { // A regular sync. Accept the event if it is inside the sync window or // it is a recurrence exception for something inside the sync window. Long dtstart = map.getAsLong(Events.DTSTART); if (dtstart != null && dtstart < feedSyncData.windowEnd) { // dstart inside window, keeping event } else { Long originalInstanceTime = map.getAsLong(Events.ORIGINAL_INSTANCE_TIME); if (originalInstanceTime != null && originalInstanceTime.longValue() <= feedSyncData.windowEnd) { // originalInstanceTime inside the window, keeping event } else { // "Rejecting event as outside window return; } } } if (entryState == ENTRY_DELETED) { if (Config.LOGV) { Log.v(TAG, "Got deleted entry from server: " + map); } provider.insert(Events.DELETED_CONTENT_URI, map); } else if (entryState == ENTRY_OK) { if (Config.LOGV) { Log.v(TAG, "Got entry from server: " + map); } Uri result = provider.insert(Events.CONTENT_URI, map); long rowId = ContentUris.parseId(result); // handle the reminders for the event Integer hasAlarm = map.getAsInteger(Events.HAS_ALARM); if (hasAlarm != null && hasAlarm == 1) { // reminders should not be null Vector alarms = event.getReminders(); if (alarms == null) { Log.e(TAG, "Have an alarm but do not have any reminders " + "-- should not happen."); throw new IllegalStateException("Have an alarm but do not have any reminders"); } Enumeration reminders = alarms.elements(); while (reminders.hasMoreElements()) { ContentValues reminderValues = new ContentValues(); reminderValues.put(Calendar.Reminders.EVENT_ID, rowId); Reminder reminder = (Reminder) reminders.nextElement(); byte method = reminder.getMethod(); switch (method) { case Reminder.METHOD_DEFAULT: reminderValues.put(Calendar.Reminders.METHOD, Calendar.Reminders.METHOD_DEFAULT); break; case Reminder.METHOD_ALERT: reminderValues.put(Calendar.Reminders.METHOD, Calendar.Reminders.METHOD_ALERT); break; case Reminder.METHOD_EMAIL: reminderValues.put(Calendar.Reminders.METHOD, Calendar.Reminders.METHOD_EMAIL); break; case Reminder.METHOD_SMS: reminderValues.put(Calendar.Reminders.METHOD, Calendar.Reminders.METHOD_SMS); break; default: // should not happen. return false? we'd have to // roll back the event. Log.e(TAG, "Unknown reminder method: " + method + " should not happen!"); } int minutes = reminder.getMinutes(); reminderValues.put(Calendar.Reminders.MINUTES, minutes == Reminder.MINUTES_DEFAULT ? Calendar.Reminders.MINUTES_DEFAULT : minutes); if (provider.insert(Calendar.Reminders.CONTENT_URI, reminderValues) == null) { throw new ParseException("Unable to insert reminders."); } } } // handle attendees for the event Vector attendees = event.getAttendees(); Enumeration attendeesEnum = attendees.elements(); while (attendeesEnum.hasMoreElements()) { Who who = (Who) attendeesEnum.nextElement(); ContentValues attendeesValues = new ContentValues(); attendeesValues.put(Calendar.Attendees.EVENT_ID, rowId); attendeesValues.put(Calendar.Attendees.ATTENDEE_NAME, who.getValue()); attendeesValues.put(Calendar.Attendees.ATTENDEE_EMAIL, who.getEmail()); byte status; switch (who.getStatus()) { case Who.STATUS_NONE: status = Calendar.Attendees.ATTENDEE_STATUS_NONE; break; case Who.STATUS_INVITED: status = Calendar.Attendees.ATTENDEE_STATUS_INVITED; break; case Who.STATUS_ACCEPTED: status = Calendar.Attendees.ATTENDEE_STATUS_ACCEPTED; break; case Who.STATUS_TENTATIVE: status = Calendar.Attendees.ATTENDEE_STATUS_TENTATIVE; break; case Who.STATUS_DECLINED: status = Calendar.Attendees.ATTENDEE_STATUS_DECLINED; break; default: Log.w(TAG, "Unknown attendee status " + who.getStatus()); status = Calendar.Attendees.ATTENDEE_STATUS_NONE; } attendeesValues.put(Calendar.Attendees.ATTENDEE_STATUS, status); byte rel; switch (who.getRelationship()) { case Who.RELATIONSHIP_NONE: rel = Calendar.Attendees.RELATIONSHIP_NONE; break; case Who.RELATIONSHIP_ORGANIZER: rel = Calendar.Attendees.RELATIONSHIP_ORGANIZER; break; case Who.RELATIONSHIP_ATTENDEE: rel = Calendar.Attendees.RELATIONSHIP_ATTENDEE; break; case Who.RELATIONSHIP_PERFORMER: rel = Calendar.Attendees.RELATIONSHIP_PERFORMER; break; case Who.RELATIONSHIP_SPEAKER: rel = Calendar.Attendees.RELATIONSHIP_SPEAKER; break; default: Log.w(TAG, "Unknown attendee relationship " + who.getRelationship()); rel = Calendar.Attendees.RELATIONSHIP_NONE; } attendeesValues.put(Calendar.Attendees.ATTENDEE_RELATIONSHIP, rel); byte type; switch (who.getType()) { case Who.TYPE_NONE: type = Calendar.Attendees.TYPE_NONE; break; case Who.TYPE_REQUIRED: type = Calendar.Attendees.TYPE_REQUIRED; break; case Who.TYPE_OPTIONAL: type = Calendar.Attendees.TYPE_OPTIONAL; break; default: Log.w(TAG, "Unknown attendee type " + who.getType()); type = Calendar.Attendees.TYPE_NONE; } attendeesValues.put(Calendar.Attendees.ATTENDEE_TYPE, type); if (provider.insert(Calendar.Attendees.CONTENT_URI, attendeesValues) == null) { throw new ParseException("Unable to insert attendees."); } } // handle the extended properties for the event Integer hasExtendedProperties = map.getAsInteger(Events.HAS_EXTENDED_PROPERTIES); if (hasExtendedProperties != null && hasExtendedProperties.intValue() != 0) { // extended properties should not be null // TODO: make the extended properties a bit more OO? Hashtable extendedProperties = event.getExtendedProperties(); if (extendedProperties == null) { Log.e(TAG, "Have extendedProperties but do not have any properties" + "-- should not happen."); throw new IllegalStateException( "Have extendedProperties but do not have any properties"); } Enumeration propertyNames = extendedProperties.keys(); while (propertyNames.hasMoreElements()) { String propertyName = (String) propertyNames.nextElement(); String propertyValue = (String) extendedProperties.get(propertyName); ContentValues extendedPropertyValues = new ContentValues(); extendedPropertyValues.put(Calendar.ExtendedProperties.EVENT_ID, rowId); extendedPropertyValues.put(Calendar.ExtendedProperties.NAME, propertyName); extendedPropertyValues.put(Calendar.ExtendedProperties.VALUE, propertyValue); if (provider.insert(Calendar.ExtendedProperties.CONTENT_URI, extendedPropertyValues) == null) { throw new ParseException("Unable to insert extended properties."); } } } } else { // If the DTSTART == -1, then the date was out of range. We don't // need to throw a ParseException because the user can create // dates on the web that we can't handle on the phone. For // example, events with dates before Dec 13, 1901 can be created // on the web but cannot be handled on the phone. Long dtstart = map.getAsLong(Events.DTSTART); if (dtstart != null && dtstart == -1) { return; } if (Config.LOGV) { Log.v(TAG, "Got invalid entry from server: " + map); } throw new ParseException("Got invalid entry from server: " + map); } } /** * Converts an old non-sliding-windows database to sliding windows * @param feedSyncData State of the sync. */ private void upgradeToSlidingWindows(GDataSyncData.FeedData feedSyncData) { feedSyncData.windowEnd = getSyncWindowEnd(); // TODO: Should prune old events } @Override public void getServerDiffs(SyncContext context, SyncData baseSyncData, SyncableContentProvider tempProvider, Bundle extras, Object baseSyncInfo, SyncResult syncResult) { final ContentResolver cr = getContext().getContentResolver(); mServerDiffs++; final boolean syncingSingleFeed = (extras != null) && extras.containsKey("feed"); final boolean syncingMetafeedOnly = (extras != null) && extras.containsKey("metafeedonly"); if (syncingSingleFeed) { if (syncingMetafeedOnly) { Log.d(TAG, "metafeedonly and feed both set."); return; } StringBuilder sb = new StringBuilder(); extrasToStringBuilder(extras, sb); String feedUrl = extras.getString("feed"); GDataSyncData.FeedData feedSyncData = getFeedData(feedUrl, baseSyncData); if (feedSyncData != null && feedSyncData.windowEnd == 0) { upgradeToSlidingWindows(feedSyncData); } else if (feedSyncData == null) { feedSyncData = new GDataSyncData.FeedData(0, 0, false, "", 0); feedSyncData.windowEnd = getSyncWindowEnd(); ((GDataSyncData) baseSyncData).feedData.put(feedUrl, feedSyncData); } if (extras.getBoolean("moveWindow", false)) { // This is a move window sync. Set the new end. // Setting newWindowEnd makes this a sliding window expansion sync. if (feedSyncData.newWindowEnd == 0) { feedSyncData.newWindowEnd = getSyncWindowEnd(); } } else { // TODO The window move needs to be done only occasionally if (getSyncWindowEnd() > feedSyncData.windowEnd) { // Schedule a move-the-window sync Bundle syncExtras = new Bundle(); syncExtras.clear(); syncExtras.putBoolean("moveWindow", true); syncExtras.putString("feed", feedUrl); mContentResolver.startSync(Calendar.CONTENT_URI, syncExtras); } } getServerDiffsForFeed(context, baseSyncData, tempProvider, feedUrl, baseSyncInfo, syncResult); return; } // At this point, either metafeed sync or poll. // For the poll (or metafeed sync), refresh the list of calendars. // we can move away from this when we move to the new allcalendars feed, which is // syncable. until then, we'll rely on the daily poll to keep the list of calendars // up to date. mRefresh++; context.setStatusText("Fetching list of calendars"); fetchCalendarsFromServer(); if (syncingMetafeedOnly) { // If not polling, nothing more to do. return; } // select the set of calendars for this account. final Account account = getAccount(); final String[] accountSelectionArgs = new String[]{account.mName, account.mType}; Cursor cursor = cr.query(Calendar.Calendars.CONTENT_URI, CALENDARS_PROJECTION, SELECT_BY_ACCOUNT, accountSelectionArgs, null /* sort order */); Bundle syncExtras = new Bundle(); try { while (cursor.moveToNext()) { boolean syncEvents = (cursor.getInt(6) == 1); String feedUrl = cursor.getString(3); if (!syncEvents) { continue; } // schedule syncs for each of these feeds. syncExtras.clear(); syncExtras.putAll(extras); syncExtras.putString("feed", feedUrl); ContentResolver.requestSync(account, Calendar.Calendars.CONTENT_URI.getAuthority(), syncExtras); } } finally { cursor.close(); } } /** * Gets end of the sliding sync window. * Window is approximately 1 year from now on approximately month boundaries. * Could make this accurately hit month boundaries if it matters. * * @return end of window in ms */ private static long getSyncWindowEnd() { long now = System.currentTimeMillis(); if ("true".equals(SystemProperties.get(USE_SLIDING_WINDOW))) { return ((now + YEAR_IN_MS)/ MONTH_IN_MS) * MONTH_IN_MS; } else { return Long.MAX_VALUE; } } private void getServerDiffsForFeed(SyncContext context, SyncData baseSyncData, SyncableContentProvider tempProvider, String feed, Object baseSyncInfo, SyncResult syncResult) { final SyncInfo syncInfo = (SyncInfo) baseSyncInfo; final GDataSyncData syncData = (GDataSyncData) baseSyncData; final Account account = getAccount(); Cursor cursor = getContext().getContentResolver().query(Calendar.Calendars.CONTENT_URI, CALENDARS_PROJECTION, SELECT_BY_ACCOUNT_AND_FEED, new String[] { account.mName, account.mType, feed }, null /* sort order */); ContentValues map = new ContentValues(); int maxResults = getMaxEntriesPerSync(); try { if (!cursor.moveToFirst()) { return; } // TODO: refactor all of this, so we don't have to rely on // member variables getting updated here in order for the // base class hooks to work. syncInfo.calendarId = cursor.getLong(0); boolean syncEvents = (cursor.getInt(6) == 1); long syncTime = cursor.getLong(2); String feedUrl = cursor.getString(3); String name = cursor.getString(4); String origCalendarTimezone = syncInfo.calendarTimezone = cursor.getString(5); if (!syncEvents) { // should not happen. non-syncable feeds should not be scheduled for syncs nor // should they get tickled. if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Ignoring sync request for non-syncable feed."); } return; } context.setStatusText("Syncing " + name); // call the superclass implementation to sync the current // calendar from the server. getServerDiffsImpl(context, tempProvider, getFeedEntryClass(), feedUrl, syncInfo, maxResults, syncData, syncResult); if (mSyncCanceled || syncResult.hasError()) { return; } // update the timezone for this calendar if it changed if (!TextUtils.equals(syncInfo.calendarTimezone, origCalendarTimezone)) { map.clear(); map.put(Calendars.TIMEZONE, syncInfo.calendarTimezone); mContentResolver.update( ContentUris.withAppendedId(Calendars.CONTENT_URI, syncInfo.calendarId), map, null, null); } } finally { cursor.close(); } } @Override protected void initTempProvider(SyncableContentProvider cp) { // TODO: don't use the real db's calendar id's. create new ones locally and translate // during CalendarProvider's merge. // populate temp provider with calendar ids, so joins work. ContentValues map = new ContentValues(); final Account account = getAccount(); Cursor c = getContext().getContentResolver().query( Calendar.Calendars.CONTENT_URI, CALENDARS_PROJECTION, SELECT_BY_ACCOUNT, new String[]{account.mName, account.mType}, null /* sort order */); final int idIndex = c.getColumnIndexOrThrow(Calendars._ID); final int urlIndex = c.getColumnIndexOrThrow(Calendars.URL); final int timezoneIndex = c.getColumnIndexOrThrow(Calendars.TIMEZONE); while (c.moveToNext()) { map.clear(); map.put(Calendars._ID, c.getLong(idIndex)); map.put(Calendars.URL, c.getString(urlIndex)); map.put(Calendars.TIMEZONE, c.getString(timezoneIndex)); cp.insert(Calendar.Calendars.CONTENT_URI, map); } c.close(); } public void onAccountsChanged(Account[] accountsArray) { if (!"yes".equals(SystemProperties.get("ro.config.sync"))) { return; } // - Get a cursor (A) over all selected calendars over all accounts // - Get a cursor (B) over all subscribed feeds for calendar // - If an item is in A but not B then add a subscription // - If an item is in B but not A then remove the subscription ContentResolver cr = getContext().getContentResolver(); Cursor cursorA = null; Cursor cursorB = null; try { cursorA = Calendar.Calendars.query(cr, null /* projection */, Calendar.Calendars.SELECTED + "=1", CALENDAR_KEY_SORT_ORDER); int urlIndexA = cursorA.getColumnIndexOrThrow(Calendar.Calendars.URL); int accountNameIndexA = cursorA.getColumnIndexOrThrow(Calendar.Calendars._SYNC_ACCOUNT); int accountTypeIndexA = cursorA.getColumnIndexOrThrow(Calendar.Calendars._SYNC_ACCOUNT_TYPE); cursorB = SubscribedFeeds.Feeds.query(cr, FEEDS_KEY_COLUMNS, SubscribedFeeds.Feeds.AUTHORITY + "=?", new String[]{Calendar.AUTHORITY}, FEEDS_KEY_SORT_ORDER); int urlIndexB = cursorB.getColumnIndexOrThrow(SubscribedFeeds.Feeds.FEED); int accountNameIndexB = cursorB.getColumnIndexOrThrow(SubscribedFeeds.Feeds._SYNC_ACCOUNT); int accountTypeIndexB = cursorB.getColumnIndexOrThrow(SubscribedFeeds.Feeds._SYNC_ACCOUNT_TYPE); for (CursorJoiner.Result joinerResult : new CursorJoiner(cursorA, CALENDAR_KEY_COLUMNS, cursorB, FEEDS_KEY_COLUMNS)) { switch (joinerResult) { case LEFT: SubscribedFeeds.addFeed( cr, cursorA.getString(urlIndexA), new Account(cursorA.getString(accountNameIndexA), cursorA.getString(accountTypeIndexA)), Calendar.AUTHORITY, CalendarClient.SERVICE); break; case RIGHT: SubscribedFeeds.deleteFeed( cr, cursorB.getString(urlIndexB), new Account(cursorB.getString(accountNameIndexB), cursorB.getString(accountTypeIndexB)), Calendar.AUTHORITY); break; case BOTH: // do nothing, since the subscription already exists break; } } } finally { // check for null in case an exception occurred before the cursors got created if (cursorA != null) cursorA.close(); if (cursorB != null) cursorB.close(); } } /** * Should not get called. The feed url changes depending on which calendar is being sync'd * to/from the device, and thus is determined and passed around as a local variable, where * appropriate. */ protected String getFeedUrl(Account account) { throw new UnsupportedOperationException("getFeedUrl() should not get called."); } protected Class getFeedEntryClass() { return EventEntry.class; } // XXX temporary debugging private static void extrasToStringBuilder(Bundle bundle, StringBuilder sb) { sb.append("["); for (String key : bundle.keySet()) { sb.append(key).append("=").append(bundle.get(key)).append(" "); } sb.append("]"); } @Override protected void updateQueryParameters(QueryParams params, GDataSyncData.FeedData feedSyncData) { if (feedSyncData.newWindowEnd > 0) { // Advancing the sliding window: set the parameters to the new part of the window params.setUpdatedMin(null); params.setParamValue("requirealldeleted", "false"); Time startMinTime = new Time(Time.TIMEZONE_UTC); Time startMaxTime = new Time(Time.TIMEZONE_UTC); startMinTime.set(feedSyncData.windowEnd); startMaxTime.set(feedSyncData.newWindowEnd); String startMin = startMinTime.format("%Y-%m-%dT%H:%M:%S.000Z"); String startMax = startMaxTime.format("%Y-%m-%dT%H:%M:%S.000Z"); params.setParamValue("start-min", startMin); params.setParamValue("start-max", startMax); } else if (params.getUpdatedMin() == null) { // if this is the first sync, only bother syncing starting from // one month ago. // TODO: remove this restriction -- we may want all of // historical calendar events. Time lastMonth = new Time(Time.TIMEZONE_UTC); lastMonth.setToNow(); --lastMonth.month; lastMonth.normalize(true /* ignore isDst */); // TODO: move start-min to CalendarClient? // or create CalendarQueryParams subclass (extra class)? String startMin = lastMonth.format("%Y-%m-%dT%H:%M:%S.000Z"); params.setParamValue("start-min", startMin); // Note: start-max is not set for regular syncs. The sync needs to pick up events // outside the window in case an event inside the window got moved outside. // The event will be discarded later. } // HACK: specify that we want to expand recurrences in the past, // so the server does not expand any recurrences. we do this to // avoid a large number of gd:when elements that we do not need, // since we process gd:recurrence elements instead. params.setParamValue("recurrence-expansion-start", "1970-01-01"); params.setParamValue("recurrence-expansion-end", "1970-01-01"); // we want to get the events ordered by last modified, so we can // recover in case we cannot process the entire feed. params.setParamValue("orderby", "lastmodified"); params.setParamValue("sortorder", "ascending"); } @Override protected GDataServiceClient getGDataServiceClient() { return mCalendarClient; } protected void getStatsString(StringBuffer sb, SyncResult result) { super.getStatsString(sb, result); if (mRefresh > 0) { sb.append("F").append(mRefresh); } if (mServerDiffs > 0) { sb.append("s").append(mServerDiffs); } } private void fetchCalendarsFromServer() { if (mCalendarClient == null) { Log.w(TAG, "Cannot fetch calendars -- calendar url defined."); return; } Account account = null; String authToken = null; try { // TODO: allow caller to specify which account's feeds should be updated Account[] accounts = AccountManager.get(getContext()) .blockingGetAccountsWithTypeAndFeatures( GoogleLoginServiceConstants.ACCOUNT_TYPE, new String[]{GoogleLoginServiceConstants.FEATURE_GOOGLE_OR_DASHER}); if (accounts.length == 0) { Log.w(TAG, "Unable to update calendars from server -- no users configured."); return; } account = accounts[0]; Bundle bundle = AccountManager.get(getContext()).getAuthToken( account, mCalendarClient.getServiceName(), true /* notifyAuthFailure */, null /* callback */, null /* handler */) .getResult(); authToken = bundle.getString(Constants.AUTHTOKEN_KEY); if (authToken == null) { Log.w(TAG, "Unable to update calendars from server -- could not " + "authenticate user " + account); return; } } catch (IOException e) { Log.w(TAG, "Unable to update calendars from server -- could not " + "authenticate user " + account, e); return; } catch (AuthenticatorException e) { Log.w(TAG, "Unable to update calendars from server -- could not " + "authenticate user " + account, e); return; } catch (OperationCanceledException e) { Log.w(TAG, "Unable to update calendars from server -- could not " + "authenticate user " + account, e); return; } // get the current set of calendars. we'll need to pay attention to // which calendars we get back from the server, so we can delete // calendars that have been deleted from the server. Set<Long> existingCalendarIds = new HashSet<Long>(); getCurrentCalendars(existingCalendarIds); // get and process the calendars meta feed GDataParser parser = null; try { String feedUrl = mCalendarClient.getUserCalendarsUrl(account.mName); feedUrl = CalendarSyncAdapter.rewriteUrlforAccount(account, feedUrl); parser = mCalendarClient.getParserForUserCalendars(feedUrl, authToken); // process the calendars processCalendars(account, parser, existingCalendarIds); } catch (ParseException pe) { Log.w(TAG, "Unable to process calendars from server -- could not " + "parse calendar feed.", pe); return; } catch (IOException ioe) { Log.w(TAG, "Unable to process calendars from server -- encountered " + "i/o error", ioe); return; } catch (HttpException e) { switch (e.getStatusCode()) { case HttpException.SC_UNAUTHORIZED: Log.w(TAG, "Unable to process calendars from server -- could not " + "authenticate user.", e); return; case HttpException.SC_GONE: Log.w(TAG, "Unable to process calendars from server -- encountered " + "an AllDeletedUnavailableException, this should never happen", e); return; default: Log.w(TAG, "Unable to process calendars from server -- error", e); return; } } finally { if (parser != null) { parser.close(); } } // delete calendars that are no longer sent from the server. final Uri calendarContentUri = Calendars.CONTENT_URI; final ContentResolver cr = getContext().getContentResolver(); for (long calId : existingCalendarIds) { // NOTE: triggers delete all events, instances for this calendar. cr.delete(ContentUris.withAppendedId(calendarContentUri, calId), null /* where */, null /* selectionArgs */); } } private void getCurrentCalendars(Set<Long> calendarIds) { final ContentResolver cr = getContext().getContentResolver(); Cursor cursor = cr.query(Calendars.CONTENT_URI, new String[] { Calendars._ID }, null /* selection */, null /* selectionArgs */, null /* sort */); if (cursor != null) { try { while (cursor.moveToNext()) { calendarIds.add(cursor.getLong(0)); } } finally { cursor.close(); } } } private void processCalendars(Account account, GDataParser parser, Set<Long> existingCalendarIds) throws ParseException, IOException { final ContentResolver cr = getContext().getContentResolver(); CalendarsFeed feed = (CalendarsFeed) parser.init(); Entry entry = null; final Uri calendarContentUri = Calendars.CONTENT_URI; ArrayList<ContentValues> inserts = new ArrayList<ContentValues>(); while (parser.hasMoreData()) { entry = parser.readNextEntry(entry); if (Config.LOGV) Log.v(TAG, "Read entry: " + entry.toString()); CalendarEntry calendarEntry = (CalendarEntry) entry; ContentValues map = new ContentValues(); String feedUrl = calendarEntryToContentValues(account, feed, calendarEntry, map); if (TextUtils.isEmpty(feedUrl)) { continue; } long calId = -1; Cursor c = cr.query(calendarContentUri, new String[] { Calendars._ID }, Calendars.URL + "='" + feedUrl + '\'' /* selection */, null /* selectionArgs */, null /* sort */); if (c != null) { try { if (c.moveToFirst()) { calId = c.getLong(0); existingCalendarIds.remove(calId); } } finally { c.close(); } } if (calId != -1) { if (Config.LOGV) Log.v(TAG, "Updating calendar " + map); // don't override the existing "selected" or "hidden" settings. map.remove(Calendars.SELECTED); map.remove(Calendars.HIDDEN); cr.update(ContentUris.withAppendedId(calendarContentUri, calId), map, null /* where */, null /* selectionArgs */); } else { // Select this calendar for syncing and display if it is // selected and not hidden. int syncAndDisplay = 0; if (calendarEntry.isSelected() && !calendarEntry.isHidden()) { syncAndDisplay = 1; } map.put(Calendars.SYNC_EVENTS, syncAndDisplay); map.put(Calendars.SELECTED, syncAndDisplay); map.put(Calendars.HIDDEN, 0); map.put(Calendars._SYNC_ACCOUNT, account.mName); map.put(Calendars._SYNC_ACCOUNT_TYPE, account.mType); if (Config.LOGV) Log.v(TAG, "Adding calendar " + map); inserts.add(map); } } if (!inserts.isEmpty()) { if (Config.LOGV) Log.v(TAG, "Bulk updating calendar list."); cr.bulkInsert(calendarContentUri, inserts.toArray(new ContentValues[inserts.size()])); } } /** * Convert the CalenderEntry to a Bundle that can be inserted/updated into the * Calendars table. */ private String calendarEntryToContentValues(Account account, CalendarsFeed feed, CalendarEntry entry, ContentValues map) { map.clear(); String url = entry.getAlternateLink(); if (TextUtils.isEmpty(url)) { // yuck. the alternate link was not available. we should // reconstruct from the id. url = entry.getId(); if (!TextUtils.isEmpty(url)) { url = convertCalendarIdToFeedUrl(url); } else { if (Config.LOGV) { Log.v(TAG, "Cannot generate url for calendar feed."); } return null; } } url = rewriteUrlforAccount(account, url); map.put(Calendars.URL, url); map.put(Calendars.OWNER_ACCOUNT, calendarEmailAddressFromFeedUrl(url)); map.put(Calendars.NAME, entry.getTitle()); // TODO: map.put(Calendars.DISPLAY_NAME, entry.getTitle()); map.put(Calendars.TIMEZONE, entry.getTimezone()); String colorStr = entry.getColor(); if (!TextUtils.isEmpty(colorStr)) { int color = Color.parseColor(colorStr); // Ensure the alpha is set to max color |= 0xff000000; map.put(Calendars.COLOR, color); } map.put(Calendars.SELECTED, entry.isSelected() ? 1 : 0); map.put(Calendars.HIDDEN, entry.isHidden() ? 1 : 0); int accesslevel; switch (entry.getAccessLevel()) { case CalendarEntry.ACCESS_NONE: accesslevel = Calendars.NO_ACCESS; break; case CalendarEntry.ACCESS_READ: accesslevel = Calendars.READ_ACCESS; break; case CalendarEntry.ACCESS_FREEBUSY: accesslevel = Calendars.FREEBUSY_ACCESS; break; case CalendarEntry.ACCESS_EDITOR: accesslevel = Calendars.EDITOR_ACCESS; break; case CalendarEntry.ACCESS_OWNER: accesslevel = Calendars.OWNER_ACCESS; break; default: accesslevel = Calendars.NO_ACCESS; } map.put(Calendars.ACCESS_LEVEL, accesslevel); // TODO: use the update time, when calendar actually supports this. // right now, calendar modifies the update time frequently. map.put(Calendars._SYNC_TIME, System.currentTimeMillis()); return url; } // TODO: unit test. protected static final String convertCalendarIdToFeedUrl(String url) { // id: http://www.google.com/calendar/feeds/<username>/<cal id> // desired feed: // http://www.google.com/calendar/feeds/<cal id>/<projection> int start = url.indexOf(FEEDS_SUBSTRING); if (start != -1) { // strip out the */ in /feeds/*/ start += FEEDS_SUBSTRING.length(); int end = url.indexOf('/', start); if (end != -1) { url = url.replace(url.substring(start, end + 1), ""); } url = url + PRIVATE_FULL; } return url; } /** * Extracts the calendar email from a calendar feed url. * @param feed the calendar feed url * @return the calendar email that is in the feed url or null if it can't * find the email address. */ public static String calendarEmailAddressFromFeedUrl(String feed) { // Example feed url: // https://www.google.com/calendar/feeds/foo%40gmail.com/private/full-noattendees String[] pathComponents = feed.split("/"); if (pathComponents.length > 5 && "feeds".equals(pathComponents[4])) { try { return URLDecoder.decode(pathComponents[5], "UTF-8"); } catch (UnsupportedEncodingException e) { Log.e(TAG, "unable to url decode the email address in calendar " + feed); return null; } } Log.e(TAG, "unable to find the email address in calendar " + feed); return null; } }
true
false
null
null
diff --git a/common/ccm/compression/block/Compressed.java b/common/ccm/compression/block/Compressed.java index 2282d72..5cf02ca 100644 --- a/common/ccm/compression/block/Compressed.java +++ b/common/ccm/compression/block/Compressed.java @@ -1,273 +1,273 @@ package ccm.compression.block; import java.util.ArrayList; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.Icon; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.Explosion; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import ccm.compression.client.renderer.block.CompressedBlockRenderer; import ccm.compression.item.block.CompressedItemBlock; import ccm.compression.tileentity.CompressedTile; import ccm.compression.utils.lib.Archive; import ccm.nucleum.omnium.utils.handler.TileHandler; import ccm.nucleum.omnium.utils.helper.NBTHelper; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class Compressed extends BlockContainer { public static final String name = "Compressed"; public Compressed(final int id) { super(id, Material.rock); setUnlocalizedName(name); GameRegistry.registerBlock(this, CompressedItemBlock.class, getUnlocalizedName()); TileHandler.registerTile(name, CompressedTile.class); } @Override public TileEntity createNewTileEntity(final World world) { return TileHandler.getTileInstance(name); } private static CompressedTile getTile(final IBlockAccess world, final int x, final int y, final int z) { CompressedTile finished = null; TileEntity tmp = world.getBlockTileEntity(x, y, z); if (tmp != null) { if (tmp instanceof CompressedTile) { finished = (CompressedTile) tmp; } } return finished; } private static Block getBlock(final IBlockAccess world, final int x, final int y, final int z) { CompressedTile tmp = getTile(world, x, y, z); if (tmp != null) { Block block = tmp.getBlock(); if (block != null) { return block; } } return Block.sponge; } @Override public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { ItemStack stack = new ItemStack(world.getBlockId(x, y, z), 1, world.getBlockMetadata(x, y, z)); CompressedTile tile = getTile(world, x, y, z); if (tile != null) { NBTHelper.setInteger(stack, Archive.NBT_COMPRESSED_BLOCK_ID, tile.getBlock().blockID); NBTHelper.setByte(stack, Archive.NBT_COMPRESSED_BLOCK_META, tile.getMeta()); } return stack; } @Override public void registerIcons(IconRegister register) { for (CompressedType type : CompressedType.values()) { type.setIcon(register.registerIcon(Archive.MOD_ID + ":condensedOverlay_" + type.ordinal())); } } @Override public void onBlockPlacedBy(final World world, final int x, final int y, final int z, final EntityLivingBase entity, final ItemStack item) { super.onBlockPlacedBy(world, x, y, z, entity, item); CompressedTile tile = getTile(world, x, y, z); if (tile != null) { tile.setBlockID(NBTHelper.getInteger(item, Archive.NBT_COMPRESSED_BLOCK_ID)); tile.setBlockMeta(NBTHelper.getByte(item, Archive.NBT_COMPRESSED_BLOCK_META)); } } @Override public ArrayList<ItemStack> getBlockDropped(final World world, final int x, final int y, final int z, final int metadata, final int fortune) { ArrayList<ItemStack> ret = new ArrayList<ItemStack>(); CompressedTile tile = getTile(world, x, y, z); if (tile != null) { int count = quantityDropped(metadata, fortune, world.rand); for (int i = 0; i < count; i++) { int id = idDropped(metadata, world.rand, fortune); if (id > 0) { ItemStack stack = new ItemStack(id, 1, metadata); NBTHelper.setInteger(stack, Archive.NBT_COMPRESSED_BLOCK_ID, tile.getBlock().blockID); NBTHelper.setByte(stack, Archive.NBT_COMPRESSED_BLOCK_META, tile.getMeta()); ret.add(stack); } } } return ret; } @Override public Icon getBlockTexture(final IBlockAccess world, final int x, final int y, final int z, final int side) { - return getBlock(world, x, y, z).getBlockTexture(world, x, y, z, side); + return getBlock(world, x, y, z).getIcon(side, ((CompressedTile) world.getBlockTileEntity(x, y, z)).getMeta()); } /** * Called when the block is clicked by a player. Args: x, y, z, entityPlayer */ @Override public void onBlockClicked(final World world, final int x, final int y, final int z, final EntityPlayer player) { getBlock(world, x, y, z).onBlockClicked(world, x, y, z, player); } @Override @SideOnly(Side.CLIENT) /** * A randomly called display update to be able to add particles or other items for display */ public void randomDisplayTick(final World world, final int x, final int y, final int z, final Random rand) { getBlock(world, x, y, z).randomDisplayTick(world, x, y, z, rand); } @Override @SideOnly(Side.CLIENT) /** * Goes straight to getLightBrightnessForSkyBlocks for Blocks, does some fancy computing for Fluids */ public int getMixedBrightnessForBlock(final IBlockAccess world, final int x, final int y, final int z) { return getBlock(world, x, y, z).getMixedBrightnessForBlock(world, x, y, z); } @Override @SideOnly(Side.CLIENT) /** * How bright to render this block based on the light its receiving. Args: iBlockAccess, x, y, z */ public float getBlockBrightness(final IBlockAccess world, final int x, final int y, final int z) { return getBlock(world, x, y, z).getBlockBrightness(world, x, y, z); } /** * Can add to the passed in vector for a movement vector to be applied to the entity. Args: x, y, z, entity, vec3d */ @Override public void velocityToAddToEntity(final World world, final int x, final int y, final int z, final Entity entity, final Vec3 par6Vec3) { getBlock(world, x, y, z).velocityToAddToEntity(world, x, y, z, entity, par6Vec3); } @Override @SideOnly(Side.CLIENT) /** * Returns the bounding box of the wired rectangular prism to render. */ public AxisAlignedBB getSelectedBoundingBoxFromPool(final World world, final int x, final int y, final int z) { return getBlock(world, x, y, z).getSelectedBoundingBoxFromPool(world, x, y, z); } /** * Called on server worlds only when the block has been replaced by a different block ID, or the same block with a different metadata value, but before the new metadata value * is set. Args: World, x, y, z, old block ID, old metadata */ @Override public void breakBlock(final World world, final int x, final int y, final int z, final int par5, final int par6) { getBlock(world, x, y, z).breakBlock(world, x, y, z, par5, par6); } /** * Called whenever an entity is walking on top of this block. Args: world, x, y, z, entity */ @Override public void onEntityWalking(final World world, final int x, final int y, final int z, final Entity entity) { getBlock(world, x, y, z).onEntityWalking(world, x, y, z, entity); } /** * Ticks the block if it's been scheduled */ @Override public void updateTick(final World world, final int x, final int y, final int z, final Random rand) { getBlock(world, x, y, z).updateTick(world, x, y, z, rand); } /** * Called upon block activation (right click on the block.) */ @Override public boolean onBlockActivated(final World world, final int x, final int y, final int z, final EntityPlayer player, final int par6, final float par7, final float par8, final float par9) { return getBlock(world, x, y, z).onBlockActivated(world, x, y, z, player, 0, 0.0F, 0.0F, 0.0F); } /** * Called upon the block being destroyed by an explosion */ @Override public void onBlockDestroyedByExplosion(final World world, final int x, final int y, final int z, final Explosion explosion) { getBlock(world, x, y, z).onBlockDestroyedByExplosion(world, x, y, z, explosion); } @Override public float getExplosionResistance(final Entity entity, final World world, final int x, final int y, final int z, final double explosionX, final double explosionY, final double explosionZ) { int metadata = world.getBlockMetadata(x, y, z); return ((getBlock(world, x, y, z).getExplosionResistance(entity)) * ((int) Math.pow(2, 1 + metadata))); } @Override public float getBlockHardness(final World world, final int x, final int y, final int z) { int metadata = world.getBlockMetadata(x, y, z); return ((getBlock(world, x, y, z).getBlockHardness(world, x, y, z)) * ((int) Math.pow(2, 1 + metadata))); } @Override public int getRenderType() { return CompressedBlockRenderer.id; } @Override public Icon getIcon(int side, int meta) { return Block.slowSand.getBlockTextureFromSide(side); } } \ No newline at end of file diff --git a/common/ccm/compression/client/renderer/block/CompressedBlockRenderer.java b/common/ccm/compression/client/renderer/block/CompressedBlockRenderer.java index 73e04fc..0ccdd05 100644 --- a/common/ccm/compression/client/renderer/block/CompressedBlockRenderer.java +++ b/common/ccm/compression/client/renderer/block/CompressedBlockRenderer.java @@ -1,108 +1,105 @@ package ccm.compression.client.renderer.block; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Icon; import net.minecraft.world.IBlockAccess; import net.minecraftforge.common.ForgeDirection; import org.lwjgl.opengl.GL11; import ccm.compression.block.CompressedType; import ccm.compression.tileentity.CompressedTile; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import cpw.mods.fml.client.registry.RenderingRegistry; public class CompressedBlockRenderer implements ISimpleBlockRenderingHandler { public final static int id = RenderingRegistry.getNextAvailableRenderId(); @Override public int getRenderId() { return id; } @Override public boolean shouldRender3DInInventory() { return true; } @Override public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { if (!renderer.hasOverrideBlockTexture()) { TileEntity temp = world.getBlockTileEntity(x, y, z); if (temp != null) { if (temp instanceof CompressedTile) { CompressedTile tile = (CompressedTile) temp; if (tile.getBlock() != null) { - Icon original = tile.getBlock().getIcon(0, tile.getMeta()); Icon overlay = CompressedType.getOverlay(tile.getBlockMetadata()); - renderer.setOverrideBlockTexture(original); renderer.setRenderBoundsFromBlock(block); renderer.renderStandardBlock(block, x, y, z); - renderer.clearOverrideBlockTexture(); renderer.setOverrideBlockTexture(overlay); renderer.setRenderBoundsFromBlock(block); renderer.renderStandardBlock(block, x, y, z); renderer.clearOverrideBlockTexture(); return true; } } } } renderer.renderStandardBlock(block, x, y, z); return false; } @Override public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { Tessellator tessellator = Tessellator.instance; GL11.glTranslatef(-0.5F, -0.5F, -0.5F); tessellator.startDrawingQuads(); tessellator.setNormal(0.0F, -1.0F, 0.0F); renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, ForgeDirection.DOWN.ordinal(), metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(0.0F, 1.0F, 0.0F); renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, ForgeDirection.UP.ordinal(), metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(0.0F, 0.0F, -1.0F); renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, ForgeDirection.NORTH.ordinal(), metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(0.0F, 0.0F, 1.0F); renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, ForgeDirection.SOUTH.ordinal(), metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(-1.0F, 0.0F, 0.0F); renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, ForgeDirection.WEST.ordinal(), metadata)); tessellator.draw(); tessellator.startDrawingQuads(); tessellator.setNormal(1.0F, 0.0F, 0.0F); renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, renderer.getBlockIconFromSideAndMetadata(block, ForgeDirection.EAST.ordinal(), metadata)); tessellator.draw(); GL11.glTranslatef(0.5F, 0.5F, 0.5F); } } \ No newline at end of file
false
false
null
null
diff --git a/components/bio-formats/src/loci/formats/in/LeicaReader.java b/components/bio-formats/src/loci/formats/in/LeicaReader.java index 423921ef9..02ab41237 100644 --- a/components/bio-formats/src/loci/formats/in/LeicaReader.java +++ b/components/bio-formats/src/loci/formats/in/LeicaReader.java @@ -1,1135 +1,1135 @@ // // LeicaReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.*; import java.text.*; import java.util.*; import loci.common.*; import loci.formats.*; import loci.formats.meta.FilterMetadata; import loci.formats.meta.MetadataStore; /** * LeicaReader is the file format reader for Leica files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/LeicaReader.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/LeicaReader.java">SVN</a></dd></dl> * * @author Melissa Linkert linkert at wisc.edu */ public class LeicaReader extends FormatReader { // -- Constants - public static final String[] LEI_SUFFIX = {"lei"}; /** All Leica TIFFs have this tag. */ private static final int LEICA_MAGIC_TAG = 33923; /** IFD tags. */ private static final Integer SERIES = new Integer(10); private static final Integer IMAGES = new Integer(15); private static final Integer DIMDESCR = new Integer(20); private static final Integer FILTERSET = new Integer(30); private static final Integer TIMEINFO = new Integer(40); private static final Integer SCANNERSET = new Integer(50); private static final Integer EXPERIMENT = new Integer(60); private static final Integer LUTDESC = new Integer(70); private static final Hashtable CHANNEL_PRIORITIES = createChannelPriorities(); private static Hashtable createChannelPriorities() { Hashtable h = new Hashtable(); h.put("red", new Integer(0)); h.put("green", new Integer(1)); h.put("blue", new Integer(2)); h.put("cyan", new Integer(3)); h.put("magenta", new Integer(4)); h.put("yellow", new Integer(5)); h.put("black", new Integer(6)); h.put("gray", new Integer(7)); h.put("", new Integer(8)); return h; } // -- Static fields -- private static Hashtable dimensionNames = makeDimensionTable(); // -- Fields -- protected Hashtable[] ifds; /** Array of IFD-like structures containing metadata. */ protected Hashtable[] headerIFDs; /** Helper readers. */ protected MinimalTiffReader tiff; /** Array of image file names. */ protected Vector[] files; /** Number of series in the file. */ private int numSeries; /** Name of current LEI file */ private String leiFilename; private Vector seriesNames; private Vector seriesDescriptions; private int lastPlane = 0; private float[][] physicalSizes; private int[][] channelMap; // -- Constructor -- /** Constructs a new Leica reader. */ public LeicaReader() { super("Leica", new String[] {"lei", "tif", "tiff"}); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { if (checkSuffix(name, LEI_SUFFIX)) return true; if (!checkSuffix(name, TiffReader.TIFF_SUFFIXES)) return false; if (!open) return false; // not allowed to touch the file system // check for that there is an .lei file in the same directory String prefix = name; if (prefix.indexOf(".") != -1) { prefix = prefix.substring(0, prefix.lastIndexOf(".")); } Location lei = new Location(prefix + ".lei"); if (!lei.exists()) { lei = new Location(prefix + ".LEI"); while (!lei.exists() && prefix.indexOf("_") != -1) { prefix = prefix.substring(0, prefix.lastIndexOf("_")); lei = new Location(prefix + ".lei"); if (!lei.exists()) lei = new Location(prefix + ".LEI"); } } return lei.exists(); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessStream) */ public boolean isThisType(RandomAccessStream stream) throws IOException { if (!FormatTools.validStream(stream, blockCheckLen, false)) return false; Hashtable ifd = TiffTools.getFirstIFD(stream); return ifd.containsKey(new Integer(LEICA_MAGIC_TAG)); } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); tiff.setId((String) files[series].get(lastPlane)); return tiff.get8BitLookupTable(); } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); tiff.setId((String) files[series].get(lastPlane)); return tiff.get16BitLookupTable(); } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return FormatTools.MUST_GROUP; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); FormatTools.checkPlaneNumber(this, no); if (!isRGB()) { int[] pos = getZCTCoords(no); pos[1] = indexOf(pos[1], channelMap[series]); if (pos[1] >= 0) no = getIndex(pos[0], pos[1], pos[2]); } lastPlane = no; tiff.setId((String) files[series].get(no)); return tiff.openBytes(0, buf, x, y, w, h); } /* @see loci.formats.IFormatReader#getUsedFiles() */ public String[] getUsedFiles() { FormatTools.assertId(currentId, true, 1); Vector v = new Vector(); v.add(leiFilename); for (int i=0; i<files.length; i++) { for (int j=0; j<files[i].size(); j++) { v.add(files[i].get(j)); } } return (String[]) v.toArray(new String[0]); } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { if (in != null) in.close(); if (tiff != null) tiff.close(); tiff = null; if (!fileOnly) { super.close(); leiFilename = null; files = null; ifds = headerIFDs = null; tiff = null; seriesNames = null; numSeries = 0; lastPlane = 0; channelMap = null; physicalSizes = null; seriesDescriptions = null; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { if (debug) debug("LeicaReader.initFile(" + id + ")"); close(); if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) { // need to find the associated .lei file if (ifds == null) super.initFile(id); in = new RandomAccessStream(id); in.order(TiffTools.checkHeader(in).booleanValue()); in.seek(0); status("Finding companion file name"); // open the TIFF file and look for the "Image Description" field ifds = TiffTools.getIFDs(in); if (ifds == null) throw new FormatException("No IFDs found"); String descr = TiffTools.getComment(ifds[0]); // remove anything of the form "[blah]" descr = descr.replaceAll("\\[.*.\\]\n", ""); // each remaining line in descr is a (key, value) pair, // where '=' separates the key from the value String lei = id.substring(0, id.lastIndexOf(File.separator) + 1); StringTokenizer lines = new StringTokenizer(descr, "\n"); String line = null, key = null, value = null; while (lines.hasMoreTokens()) { line = lines.nextToken(); if (line.indexOf("=") == -1) continue; key = line.substring(0, line.indexOf("=")).trim(); value = line.substring(line.indexOf("=") + 1).trim(); addMeta(key, value); if (key.startsWith("Series Name")) lei += value; } // now open the LEI file Location l = new Location(lei).getAbsoluteFile(); if (l.exists()) { initFile(lei); return; } else { l = l.getParentFile(); String[] list = l.list(); for (int i=0; i<list.length; i++) { if (checkSuffix(list[i], LEI_SUFFIX)) { initFile( new Location(l.getAbsolutePath(), list[i]).getAbsolutePath()); return; } } } throw new FormatException("LEI file not found."); } // parse the LEI file super.initFile(id); leiFilename = new File(id).exists() ? new Location(id).getAbsolutePath() : id; in = new RandomAccessStream(id); seriesNames = new Vector(); byte[] fourBytes = new byte[4]; in.read(fourBytes); core[0].littleEndian = (fourBytes[0] == TiffTools.LITTLE && fourBytes[1] == TiffTools.LITTLE && fourBytes[2] == TiffTools.LITTLE && fourBytes[3] == TiffTools.LITTLE); in.order(isLittleEndian()); status("Reading metadata blocks"); in.skipBytes(8); int addr = in.readInt(); Vector v = new Vector(); Hashtable ifd; while (addr != 0) { ifd = new Hashtable(); v.add(ifd); in.seek(addr + 4); int tag = in.readInt(); while (tag != 0) { // create the IFD structure int offset = in.readInt(); long pos = in.getFilePointer(); in.seek(offset + 12); int size = in.readInt(); byte[] data = new byte[size]; in.read(data); ifd.put(new Integer(tag), data); in.seek(pos); tag = in.readInt(); } addr = in.readInt(); } numSeries = v.size(); core = new CoreMetadata[numSeries]; for (int i=0; i<numSeries; i++) { core[i] = new CoreMetadata(); } channelMap = new int[numSeries][]; files = new Vector[numSeries]; headerIFDs = (Hashtable[]) v.toArray(new Hashtable[0]); // determine the length of a filename int nameLength = 0; int maxPlanes = 0; status("Parsing metadata blocks"); core[0].littleEndian = !isLittleEndian(); int seriesIndex = 0; boolean[] valid = new boolean[numSeries]; for (int i=0; i<headerIFDs.length; i++) { valid[i] = true; if (headerIFDs[i].get(SERIES) != null) { byte[] temp = (byte[]) headerIFDs[i].get(SERIES); nameLength = DataTools.bytesToInt(temp, 8, isLittleEndian()) * 2; } Vector f = new Vector(); byte[] tempData = (byte[]) headerIFDs[i].get(IMAGES); RandomAccessStream data = new RandomAccessStream(tempData); data.order(isLittleEndian()); int tempImages = data.readInt(); if (((long) tempImages * nameLength) > data.length()) { data.order(!isLittleEndian()); tempImages = data.readInt(); data.order(isLittleEndian()); } File dirFile = new File(id).getAbsoluteFile(); String[] listing = null; String dirPrefix = ""; if (dirFile.exists()) { listing = dirFile.getParentFile().list(); dirPrefix = dirFile.getParent(); if (!dirPrefix.endsWith(File.separator)) dirPrefix += File.separator; } else { listing = (String[]) Location.getIdMap().keySet().toArray(new String[0]); } Vector list = new Vector(); for (int k=0; k<listing.length; k++) { if (checkSuffix(listing[k], TiffReader.TIFF_SUFFIXES)) { list.add(listing[k]); } } boolean tiffsExist = true; data.seek(20); String prefix = ""; for (int j=0; j<tempImages; j++) { // read in each filename prefix = getString(data, nameLength); f.add(dirPrefix + prefix); // test to make sure the path is valid Location test = new Location((String) f.get(f.size() - 1)); if (test.exists()) list.remove(prefix); if (tiffsExist) tiffsExist = test.exists(); } data.close(); tempData = null; // at least one of the TIFF files was renamed if (!tiffsExist) { // Strategy for handling renamed files: // 1) Assume that files for each series follow a pattern. // 2) Assign each file group to the first series with the correct count. status("Handling renamed TIFF files"); listing = (String[]) list.toArray(new String[0]); // grab the file patterns Vector filePatterns = new Vector(); for (int q=0; q<listing.length; q++) { Location l = new Location(dirPrefix, listing[q]); l = l.getAbsoluteFile(); FilePattern pattern = new FilePattern(l); AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false); String fp = pattern.getPattern(); if (guess.getAxisCountS() >= 1) { String pre = pattern.getPrefix(guess.getAxisCountS()); Vector fileList = new Vector(); for (int n=0; n<listing.length; n++) { Location p = new Location(dirPrefix, listing[n]); if (p.getAbsolutePath().startsWith(pre)) { fileList.add(listing[n]); } } fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix, (String[]) fileList.toArray(new String[0])); } if (fp != null && !filePatterns.contains(fp)) { filePatterns.add(fp); } } for (int q=0; q<filePatterns.size(); q++) { String[] pattern = new FilePattern((String) filePatterns.get(q)).getFiles(); if (pattern.length == tempImages) { // make sure that this pattern hasn't already been used boolean validPattern = true; for (int n=0; n<i; n++) { if (files[n] == null) continue; if (files[n].contains(pattern[0])) { validPattern = false; break; } } if (validPattern) { files[i] = new Vector(); for (int n=0; n<pattern.length; n++) { files[i].add(pattern[n]); } } } } } else files[i] = f; if (files[i] == null) valid[i] = false; else { core[i].imageCount = files[i].size(); if (core[i].imageCount > maxPlanes) maxPlanes = core[i].imageCount; } } int invalidCount = 0; for (int i=0; i<valid.length; i++) { if (!valid[i]) invalidCount++; } numSeries -= invalidCount; int[] count = new int[core.length]; for (int i=0; i<core.length; i++) { count[i] = core[i].imageCount; } Vector[] tempFiles = files; Hashtable[] tempIFDs = headerIFDs; core = new CoreMetadata[numSeries]; files = new Vector[numSeries]; headerIFDs = new Hashtable[numSeries]; int index = 0; for (int i=0; i<numSeries; i++) { core[i] = new CoreMetadata(); while (!valid[index]) index++; core[i].imageCount = count[index]; files[i] = tempFiles[index]; Object[] sorted = files[i].toArray(); Arrays.sort(sorted); files[i].clear(); for (int q=0; q<sorted.length; q++) { files[i].add(sorted[q]); } headerIFDs[i] = tempIFDs[index]; index++; } tiff = new MinimalTiffReader(); status("Populating metadata"); if (headerIFDs == null) headerIFDs = ifds; int fileLength = 0; int resolution = -1; String[][] timestamps = new String[headerIFDs.length][]; seriesDescriptions = new Vector(); physicalSizes = new float[headerIFDs.length][5]; MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); for (int i=0; i<headerIFDs.length; i++) { String prefix = "Series " + i + " "; byte[] temp = (byte[]) headerIFDs[i].get(SERIES); if (temp != null) { // the series data // ID_SERIES RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); addMeta(prefix + "Version", stream.readInt()); addMeta(prefix + "Number of Series", stream.readInt()); fileLength = stream.readInt(); addMeta(prefix + "Length of filename", fileLength); Integer extLen = new Integer(stream.readInt()); if (extLen.intValue() > fileLength) { - stream.seek(0); + stream.seek(8); core[0].littleEndian = !isLittleEndian(); stream.order(isLittleEndian()); fileLength = stream.readInt(); extLen = new Integer(stream.readInt()); } addMeta(prefix + "Length of file extension", extLen); addMeta(prefix + "Image file extension", getString(stream, extLen.intValue())); stream.close(); } temp = (byte[]) headerIFDs[i].get(IMAGES); if (temp != null) { // the image data // ID_IMAGES RandomAccessStream s = new RandomAccessStream(temp); s.order(isLittleEndian()); core[i].imageCount = s.readInt(); core[i].sizeX = s.readInt(); core[i].sizeY = s.readInt(); addMeta(prefix + "Number of images", core[i].imageCount); addMeta(prefix + "Image width", core[i].sizeX); addMeta(prefix + "Image height", core[i].sizeY); addMeta(prefix + "Bits per Sample", s.readInt()); addMeta(prefix + "Samples per pixel", s.readInt()); String p = getString(s, fileLength * 2); s.close(); StringTokenizer st = new StringTokenizer(p, "_"); StringBuffer buf = new StringBuffer(); st.nextToken(); while (st.hasMoreTokens()) { String token = st.nextToken(); String lcase = token.toLowerCase(); if (!checkSuffix(lcase, TiffReader.TIFF_SUFFIXES) && !lcase.startsWith("ch0") && !lcase.startsWith("c0") && !lcase.startsWith("z0")) { if (buf.length() > 0) buf.append("_"); buf.append(token); } } seriesNames.add(buf.toString()); } temp = (byte[]) headerIFDs[i].get(DIMDESCR); if (temp != null) { // dimension description // ID_DIMDESCR RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); addMeta(prefix + "Voxel Version", stream.readInt()); int voxelType = stream.readInt(); core[i].rgb = voxelType == 20; addMeta(prefix + "VoxelType", voxelType == 20 ? "RGB" : "gray"); int bpp = stream.readInt(); addMeta(prefix + "Bytes per pixel", bpp); switch (bpp) { case 1: case 3: core[i].pixelType = FormatTools.UINT8; break; case 2: case 6: core[i].pixelType = FormatTools.UINT16; break; case 4: core[i].pixelType = FormatTools.UINT32; break; default: throw new FormatException("Unsupported bytes per pixel (" + bpp + ")"); } core[i].dimensionOrder = "XY"; resolution = stream.readInt(); addMeta(prefix + "Real world resolution", resolution); int length = stream.readInt() * 2; addMeta(prefix + "Maximum voxel intensity", getString(stream, length)); length = stream.readInt() * 2; addMeta(prefix + "Minimum voxel intensity", getString(stream, length)); length = stream.readInt(); stream.skipBytes(length * 2); stream.skipBytes(4); // version number length = stream.readInt(); for (int j=0; j<length; j++) { int dimId = stream.readInt(); String dimType = (String) dimensionNames.get(new Integer(dimId)); if (dimType == null) dimType = ""; int size = stream.readInt(); int distance = stream.readInt(); int strlen = stream.readInt(); String physicalSize = getString(stream, strlen * 2); String unit = ""; if (physicalSize.indexOf(" ") != -1) { unit = physicalSize.substring(physicalSize.indexOf(" ") + 1); physicalSize = physicalSize.substring(0, physicalSize.indexOf(" ")); } float physical = Float.parseFloat(physicalSize) / size; if (unit.equals("m")) { physical *= 1000000; } if (dimType.equals("x")) { core[i].sizeX = size; physicalSizes[i][0] = physical; } else if (dimType.equals("y")) { core[i].sizeY = size; physicalSizes[i][1] = physical; } else if (dimType.indexOf("z") != -1) { core[i].sizeZ = size; if (core[i].dimensionOrder.indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } physicalSizes[i][2] = physical; } else if (dimType.equals("channel")) { core[i].sizeC = size; if (core[i].dimensionOrder.indexOf("C") == -1) { core[i].dimensionOrder += "C"; } physicalSizes[i][3] = physical; } else { core[i].sizeT = size; if (core[i].dimensionOrder.indexOf("T") == -1) { core[i].dimensionOrder += "T"; } physicalSizes[i][4] = physical; } addMeta(prefix + "Dim" + j + " type", dimType); addMeta(prefix + "Dim" + j + " size", size); addMeta(prefix + "Dim" + j + " distance between sub-dimensions", distance); addMeta(prefix + "Dim" + j + " physical length", physicalSize + " " + unit); int len = stream.readInt(); addMeta(prefix + "Dim" + j + " physical origin", getString(stream, len * 2)); } int len = stream.readInt(); addMeta(prefix + "Series name", getString(stream, len)); len = stream.readInt(); String description = getString(stream, len); seriesDescriptions.add(description); addMeta(prefix + "Series description", description); stream.close(); } parseInstrumentData((byte[]) headerIFDs[i].get(FILTERSET), store, i); temp = (byte[]) headerIFDs[i].get(TIMEINFO); if (temp != null) { // time data // ID_TIMEINFO RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); stream.seek(0); int nDims = stream.readInt(); addMeta(prefix + "Number of time-stamped dimensions", nDims); addMeta(prefix + "Time-stamped dimension", stream.readInt()); for (int j=0; j < nDims; j++) { addMeta(prefix + "Dimension " + j + " ID", stream.readInt()); addMeta(prefix + "Dimension " + j + " size", stream.readInt()); addMeta(prefix + "Dimension " + j + " distance between dimensions", stream.readInt()); } int numStamps = stream.readInt(); addMeta(prefix + "Number of time-stamps", numStamps); timestamps[i] = new String[numStamps]; for (int j=0; j<numStamps; j++) { timestamps[i][j] = getString(stream, 64); addMeta(prefix + "Timestamp " + j, timestamps[i][j]); } if (stream.getFilePointer() < stream.length()) { int numTMs = stream.readInt(); addMeta(prefix + "Number of time-markers", numTMs); for (int j=0; j<numTMs; j++) { int numDims = stream.readInt(); String time = "Time-marker " + j + " Dimension "; for (int k=0; k<numDims; k++) { addMeta(prefix + time + k + " coordinate", stream.readInt()); } addMeta(prefix + "Time-marker " + j, getString(stream, 64)); } } stream.close(); } parseInstrumentData((byte[]) headerIFDs[i].get(SCANNERSET), store, i); temp = (byte[]) headerIFDs[i].get(EXPERIMENT); if (temp != null) { // experiment data // ID_EXPERIMENT RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); stream.seek(8); int len = stream.readInt(); String description = getString(stream, len * 2); addMeta(prefix + "Image Description", description); len = stream.readInt(); addMeta(prefix + "Main file extension", getString(stream, len * 2)); len = stream.readInt(); addMeta(prefix + "Single image format identifier", getString(stream, len * 2)); len = stream.readInt(); addMeta(prefix + "Single image extension", getString(stream, len * 2)); stream.close(); } temp = (byte[]) headerIFDs[i].get(LUTDESC); if (temp != null) { // LUT data // ID_LUTDESC RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); int nChannels = stream.readInt(); if (nChannels > 0) core[i].indexed = true; addMeta(prefix + "Number of LUT channels", nChannels); addMeta(prefix + "ID of colored dimension", stream.readInt()); channelMap[i] = new int[nChannels]; String[] luts = new String[nChannels]; for (int j=0; j<nChannels; j++) { String p = "LUT Channel " + j; addMeta(prefix + p + " version", stream.readInt()); addMeta(prefix + p + " inverted?", stream.read() == 1); int length = stream.readInt(); addMeta(prefix + p + " description", getString(stream, length)); length = stream.readInt(); addMeta(prefix + p + " filename", getString(stream, length)); length = stream.readInt(); luts[j] = getString(stream, length); addMeta(prefix + p + " name", luts[j]); luts[j] = luts[j].toLowerCase(); stream.skipBytes(8); } stream.close(); // finish setting up channel mapping for (int q=0; q<channelMap[i].length; q++) { if (!CHANNEL_PRIORITIES.containsKey(luts[q])) luts[q] = ""; channelMap[i][q] = ((Integer) CHANNEL_PRIORITIES.get(luts[q])).intValue(); } int[] sorted = new int[channelMap[i].length]; Arrays.fill(sorted, -1); for (int q=0; q<sorted.length; q++) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int n=0; n<channelMap[i].length; n++) { if (channelMap[i][n] < min && !containsValue(sorted, n)) { min = channelMap[i][n]; minIndex = n; } } sorted[q] = minIndex; } for (int q=0; q<channelMap[i].length; q++) { channelMap[i][sorted[q]] = q; } } core[i].orderCertain = true; core[i].littleEndian = isLittleEndian(); core[i].falseColor = true; core[i].metadataComplete = true; core[i].interleaved = false; } for (int i=0; i<numSeries; i++) { setSeries(i); if (getSizeZ() == 0) core[i].sizeZ = 1; if (getSizeT() == 0) core[i].sizeT = 1; if (getSizeC() == 0) core[i].sizeC = 1; if (getImageCount() == 0) core[i].imageCount = 1; if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) { core[i].sizeZ = 1; core[i].sizeT = 1; } tiff.setId((String) files[i].get(0)); core[i].sizeX = tiff.getSizeX(); core[i].sizeY = tiff.getSizeY(); core[i].rgb = tiff.isRGB(); core[i].indexed = tiff.isIndexed(); core[i].sizeC *= tiff.getSizeC(); if (getDimensionOrder().indexOf("C") == -1) { core[i].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } if (getDimensionOrder().indexOf("T") == -1) { core[i].dimensionOrder += "T"; } long firstPlane = 0; if (i < timestamps.length && timestamps[i] != null && timestamps[i].length > 0) { SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS"); Date date = parse.parse(timestamps[i][0], new ParsePosition(0)); firstPlane = date.getTime(); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); store.setImageCreationDate(fmt.format(date), i); } else { MetadataTools.setDefaultCreationDate(store, id, i); } store.setImageName((String) seriesNames.get(i), i); store.setImageDescription((String) seriesDescriptions.get(i), i); store.setDimensionsPhysicalSizeX(new Float(physicalSizes[i][0]), i, 0); store.setDimensionsPhysicalSizeY(new Float(physicalSizes[i][1]), i, 0); store.setDimensionsPhysicalSizeZ(new Float(physicalSizes[i][2]), i, 0); store.setDimensionsWaveIncrement( new Integer((int) physicalSizes[i][3]), i, 0); store.setDimensionsTimeIncrement(new Float(physicalSizes[i][4]), i, 0); for (int j=0; j<core[i].imageCount; j++) { if (timestamps[i] != null && j < timestamps[i].length) { SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS"); Date date = parse.parse(timestamps[i][j], new ParsePosition(0)); float elapsedTime = (float) (date.getTime() - firstPlane) / 1000; store.setPlaneTimingDeltaT(new Float(elapsedTime), i, 0, j); } } } MetadataTools.populatePixels(store, this, true); setSeries(0); } // -- Helper methods -- private void parseInstrumentData(byte[] temp, MetadataStore store, int series) throws IOException { if (temp == null) return; RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); stream.seek(0); // read 24 byte SAFEARRAY stream.skipBytes(4); int cbElements = stream.readInt(); stream.skipBytes(8); int nElements = stream.readInt(); stream.skipBytes(4); for (int j=0; j<nElements; j++) { stream.seek(24 + j * cbElements); String contentID = getString(stream, 128); String description = getString(stream, 64); String data = getString(stream, 64); int dataType = stream.readShort(); stream.skipBytes(6); // read data switch (dataType) { case 2: data = String.valueOf(stream.readShort()); stream.skipBytes(6); break; case 3: data = String.valueOf(stream.readInt()); stream.skipBytes(4); break; case 4: data = String.valueOf(stream.readFloat()); stream.skipBytes(4); break; case 5: data = String.valueOf(stream.readDouble()); break; case 7: case 11: int b = stream.read(); stream.skipBytes(7); data = b == 0 ? "false" : "true"; break; case 17: data = stream.readString(1); stream.skipBytes(7); break; default: stream.skipBytes(8); } String[] tokens = contentID.split("\\|"); if (tokens[0].startsWith("CDetectionUnit")) { // detector information if (tokens[1].startsWith("PMT")) { try { int ndx = tokens[1].lastIndexOf(" ") + 1; int detector = Integer.parseInt(tokens[1].substring(ndx)) - 1; if (tokens[2].equals("VideoOffset")) { store.setDetectorOffset(new Float(data), 0, detector); } else if (tokens[2].equals("HighVoltage")) { store.setDetectorVoltage(new Float(data), 0, detector); } } catch (NumberFormatException e) { if (debug) LogTools.trace(e); } } } else if (tokens[0].startsWith("CTurret")) { // objective information int objective = Integer.parseInt(tokens[3]); if (tokens[2].equals("NumericalAperture")) { store.setObjectiveLensNA(new Float(data), 0, objective); } else if (tokens[2].equals("Objective")) { store.setObjectiveModel(data, 0, objective); } else if (tokens[2].equals("OrderNumber")) { store.setObjectiveSerialNumber(data, 0, objective); } } else if (tokens[0].startsWith("CSpectrophotometerUnit")) { int ndx = tokens[1].lastIndexOf(" ") + 1; int channel = Integer.parseInt(tokens[1].substring(ndx)) - 1; if (tokens[2].equals("Wavelength")) { Integer wavelength = new Integer((int) Float.parseFloat(data)); if (tokens[3].equals("0")) { store.setLogicalChannelEmWave(wavelength, series, channel); } else if (tokens[3].equals("1")) { store.setLogicalChannelExWave(wavelength, series, channel); } } else if (tokens[2].equals("Stain")) { store.setLogicalChannelName(data, series, channel); } } else if (tokens[0].startsWith("CXYZStage")) { if (tokens[2].equals("XPos")) { for (int q=0; q<core[series].imageCount; q++) { store.setStagePositionPositionX(new Float(data), series, 0, q); } } else if (tokens[2].equals("YPos")) { for (int q=0; q<core[series].imageCount; q++) { store.setStagePositionPositionY(new Float(data), series, 0, q); } } else if (tokens[2].equals("ZPos")) { for (int q=0; q<core[series].imageCount; q++) { store.setStagePositionPositionZ(new Float(data), series, 0, q); } } } if (contentID.equals("dblVoxelX")) { physicalSizes[series][0] = Float.parseFloat(data); } else if (contentID.equals("dblVoxelY")) { physicalSizes[series][1] = Float.parseFloat(data); } else if (contentID.equals("dblVoxelZ")) { physicalSizes[series][2] = Float.parseFloat(data); } addMeta("Series " + series + " " + contentID, data); stream.skipBytes(16); } stream.close(); } private boolean usedFile(String s) { if (files == null) return false; for (int i=0; i<files.length; i++) { if (files[i] == null) continue; for (int j=0; j<files[i].size(); j++) { if (((String) files[i].get(j)).endsWith(s)) return true; } } return false; } private String getString(RandomAccessStream stream, int len) throws IOException { return DataTools.stripString(stream.readString(len)); } private boolean containsValue(int[] array, int value) { return indexOf(value, array) != -1; } private int indexOf(int value, int[] array) { for (int i=0; i<array.length; i++) { if (array[i] == value) return i; } return -1; } private static Hashtable makeDimensionTable() { Hashtable table = new Hashtable(); table.put(new Integer(0), "undefined"); table.put(new Integer(120), "x"); table.put(new Integer(121), "y"); table.put(new Integer(122), "z"); table.put(new Integer(116), "t"); table.put(new Integer(6815843), "channel"); table.put(new Integer(6357100), "wave length"); table.put(new Integer(7602290), "rotation"); table.put(new Integer(7798904), "x-wide for the motorized xy-stage"); table.put(new Integer(7798905), "y-wide for the motorized xy-stage"); table.put(new Integer(7798906), "z-wide for the z-stage-drive"); table.put(new Integer(4259957), "user1 - unspecified"); table.put(new Integer(4325493), "user2 - unspecified"); table.put(new Integer(4391029), "user3 - unspecified"); table.put(new Integer(6357095), "graylevel"); table.put(new Integer(6422631), "graylevel1"); table.put(new Integer(6488167), "graylevel2"); table.put(new Integer(6553703), "graylevel3"); table.put(new Integer(7864398), "logical x"); table.put(new Integer(7929934), "logical y"); table.put(new Integer(7995470), "logical z"); table.put(new Integer(7602254), "logical t"); table.put(new Integer(7077966), "logical lambda"); table.put(new Integer(7471182), "logical rotation"); table.put(new Integer(5767246), "logical x-wide"); table.put(new Integer(5832782), "logical y-wide"); table.put(new Integer(5898318), "logical z-wide"); return table; } }
true
true
protected void initFile(String id) throws FormatException, IOException { if (debug) debug("LeicaReader.initFile(" + id + ")"); close(); if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) { // need to find the associated .lei file if (ifds == null) super.initFile(id); in = new RandomAccessStream(id); in.order(TiffTools.checkHeader(in).booleanValue()); in.seek(0); status("Finding companion file name"); // open the TIFF file and look for the "Image Description" field ifds = TiffTools.getIFDs(in); if (ifds == null) throw new FormatException("No IFDs found"); String descr = TiffTools.getComment(ifds[0]); // remove anything of the form "[blah]" descr = descr.replaceAll("\\[.*.\\]\n", ""); // each remaining line in descr is a (key, value) pair, // where '=' separates the key from the value String lei = id.substring(0, id.lastIndexOf(File.separator) + 1); StringTokenizer lines = new StringTokenizer(descr, "\n"); String line = null, key = null, value = null; while (lines.hasMoreTokens()) { line = lines.nextToken(); if (line.indexOf("=") == -1) continue; key = line.substring(0, line.indexOf("=")).trim(); value = line.substring(line.indexOf("=") + 1).trim(); addMeta(key, value); if (key.startsWith("Series Name")) lei += value; } // now open the LEI file Location l = new Location(lei).getAbsoluteFile(); if (l.exists()) { initFile(lei); return; } else { l = l.getParentFile(); String[] list = l.list(); for (int i=0; i<list.length; i++) { if (checkSuffix(list[i], LEI_SUFFIX)) { initFile( new Location(l.getAbsolutePath(), list[i]).getAbsolutePath()); return; } } } throw new FormatException("LEI file not found."); } // parse the LEI file super.initFile(id); leiFilename = new File(id).exists() ? new Location(id).getAbsolutePath() : id; in = new RandomAccessStream(id); seriesNames = new Vector(); byte[] fourBytes = new byte[4]; in.read(fourBytes); core[0].littleEndian = (fourBytes[0] == TiffTools.LITTLE && fourBytes[1] == TiffTools.LITTLE && fourBytes[2] == TiffTools.LITTLE && fourBytes[3] == TiffTools.LITTLE); in.order(isLittleEndian()); status("Reading metadata blocks"); in.skipBytes(8); int addr = in.readInt(); Vector v = new Vector(); Hashtable ifd; while (addr != 0) { ifd = new Hashtable(); v.add(ifd); in.seek(addr + 4); int tag = in.readInt(); while (tag != 0) { // create the IFD structure int offset = in.readInt(); long pos = in.getFilePointer(); in.seek(offset + 12); int size = in.readInt(); byte[] data = new byte[size]; in.read(data); ifd.put(new Integer(tag), data); in.seek(pos); tag = in.readInt(); } addr = in.readInt(); } numSeries = v.size(); core = new CoreMetadata[numSeries]; for (int i=0; i<numSeries; i++) { core[i] = new CoreMetadata(); } channelMap = new int[numSeries][]; files = new Vector[numSeries]; headerIFDs = (Hashtable[]) v.toArray(new Hashtable[0]); // determine the length of a filename int nameLength = 0; int maxPlanes = 0; status("Parsing metadata blocks"); core[0].littleEndian = !isLittleEndian(); int seriesIndex = 0; boolean[] valid = new boolean[numSeries]; for (int i=0; i<headerIFDs.length; i++) { valid[i] = true; if (headerIFDs[i].get(SERIES) != null) { byte[] temp = (byte[]) headerIFDs[i].get(SERIES); nameLength = DataTools.bytesToInt(temp, 8, isLittleEndian()) * 2; } Vector f = new Vector(); byte[] tempData = (byte[]) headerIFDs[i].get(IMAGES); RandomAccessStream data = new RandomAccessStream(tempData); data.order(isLittleEndian()); int tempImages = data.readInt(); if (((long) tempImages * nameLength) > data.length()) { data.order(!isLittleEndian()); tempImages = data.readInt(); data.order(isLittleEndian()); } File dirFile = new File(id).getAbsoluteFile(); String[] listing = null; String dirPrefix = ""; if (dirFile.exists()) { listing = dirFile.getParentFile().list(); dirPrefix = dirFile.getParent(); if (!dirPrefix.endsWith(File.separator)) dirPrefix += File.separator; } else { listing = (String[]) Location.getIdMap().keySet().toArray(new String[0]); } Vector list = new Vector(); for (int k=0; k<listing.length; k++) { if (checkSuffix(listing[k], TiffReader.TIFF_SUFFIXES)) { list.add(listing[k]); } } boolean tiffsExist = true; data.seek(20); String prefix = ""; for (int j=0; j<tempImages; j++) { // read in each filename prefix = getString(data, nameLength); f.add(dirPrefix + prefix); // test to make sure the path is valid Location test = new Location((String) f.get(f.size() - 1)); if (test.exists()) list.remove(prefix); if (tiffsExist) tiffsExist = test.exists(); } data.close(); tempData = null; // at least one of the TIFF files was renamed if (!tiffsExist) { // Strategy for handling renamed files: // 1) Assume that files for each series follow a pattern. // 2) Assign each file group to the first series with the correct count. status("Handling renamed TIFF files"); listing = (String[]) list.toArray(new String[0]); // grab the file patterns Vector filePatterns = new Vector(); for (int q=0; q<listing.length; q++) { Location l = new Location(dirPrefix, listing[q]); l = l.getAbsoluteFile(); FilePattern pattern = new FilePattern(l); AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false); String fp = pattern.getPattern(); if (guess.getAxisCountS() >= 1) { String pre = pattern.getPrefix(guess.getAxisCountS()); Vector fileList = new Vector(); for (int n=0; n<listing.length; n++) { Location p = new Location(dirPrefix, listing[n]); if (p.getAbsolutePath().startsWith(pre)) { fileList.add(listing[n]); } } fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix, (String[]) fileList.toArray(new String[0])); } if (fp != null && !filePatterns.contains(fp)) { filePatterns.add(fp); } } for (int q=0; q<filePatterns.size(); q++) { String[] pattern = new FilePattern((String) filePatterns.get(q)).getFiles(); if (pattern.length == tempImages) { // make sure that this pattern hasn't already been used boolean validPattern = true; for (int n=0; n<i; n++) { if (files[n] == null) continue; if (files[n].contains(pattern[0])) { validPattern = false; break; } } if (validPattern) { files[i] = new Vector(); for (int n=0; n<pattern.length; n++) { files[i].add(pattern[n]); } } } } } else files[i] = f; if (files[i] == null) valid[i] = false; else { core[i].imageCount = files[i].size(); if (core[i].imageCount > maxPlanes) maxPlanes = core[i].imageCount; } } int invalidCount = 0; for (int i=0; i<valid.length; i++) { if (!valid[i]) invalidCount++; } numSeries -= invalidCount; int[] count = new int[core.length]; for (int i=0; i<core.length; i++) { count[i] = core[i].imageCount; } Vector[] tempFiles = files; Hashtable[] tempIFDs = headerIFDs; core = new CoreMetadata[numSeries]; files = new Vector[numSeries]; headerIFDs = new Hashtable[numSeries]; int index = 0; for (int i=0; i<numSeries; i++) { core[i] = new CoreMetadata(); while (!valid[index]) index++; core[i].imageCount = count[index]; files[i] = tempFiles[index]; Object[] sorted = files[i].toArray(); Arrays.sort(sorted); files[i].clear(); for (int q=0; q<sorted.length; q++) { files[i].add(sorted[q]); } headerIFDs[i] = tempIFDs[index]; index++; } tiff = new MinimalTiffReader(); status("Populating metadata"); if (headerIFDs == null) headerIFDs = ifds; int fileLength = 0; int resolution = -1; String[][] timestamps = new String[headerIFDs.length][]; seriesDescriptions = new Vector(); physicalSizes = new float[headerIFDs.length][5]; MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); for (int i=0; i<headerIFDs.length; i++) { String prefix = "Series " + i + " "; byte[] temp = (byte[]) headerIFDs[i].get(SERIES); if (temp != null) { // the series data // ID_SERIES RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); addMeta(prefix + "Version", stream.readInt()); addMeta(prefix + "Number of Series", stream.readInt()); fileLength = stream.readInt(); addMeta(prefix + "Length of filename", fileLength); Integer extLen = new Integer(stream.readInt()); if (extLen.intValue() > fileLength) { stream.seek(0); core[0].littleEndian = !isLittleEndian(); stream.order(isLittleEndian()); fileLength = stream.readInt(); extLen = new Integer(stream.readInt()); } addMeta(prefix + "Length of file extension", extLen); addMeta(prefix + "Image file extension", getString(stream, extLen.intValue())); stream.close(); } temp = (byte[]) headerIFDs[i].get(IMAGES); if (temp != null) { // the image data // ID_IMAGES RandomAccessStream s = new RandomAccessStream(temp); s.order(isLittleEndian()); core[i].imageCount = s.readInt(); core[i].sizeX = s.readInt(); core[i].sizeY = s.readInt(); addMeta(prefix + "Number of images", core[i].imageCount); addMeta(prefix + "Image width", core[i].sizeX); addMeta(prefix + "Image height", core[i].sizeY); addMeta(prefix + "Bits per Sample", s.readInt()); addMeta(prefix + "Samples per pixel", s.readInt()); String p = getString(s, fileLength * 2); s.close(); StringTokenizer st = new StringTokenizer(p, "_"); StringBuffer buf = new StringBuffer(); st.nextToken(); while (st.hasMoreTokens()) { String token = st.nextToken(); String lcase = token.toLowerCase(); if (!checkSuffix(lcase, TiffReader.TIFF_SUFFIXES) && !lcase.startsWith("ch0") && !lcase.startsWith("c0") && !lcase.startsWith("z0")) { if (buf.length() > 0) buf.append("_"); buf.append(token); } } seriesNames.add(buf.toString()); } temp = (byte[]) headerIFDs[i].get(DIMDESCR); if (temp != null) { // dimension description // ID_DIMDESCR RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); addMeta(prefix + "Voxel Version", stream.readInt()); int voxelType = stream.readInt(); core[i].rgb = voxelType == 20; addMeta(prefix + "VoxelType", voxelType == 20 ? "RGB" : "gray"); int bpp = stream.readInt(); addMeta(prefix + "Bytes per pixel", bpp); switch (bpp) { case 1: case 3: core[i].pixelType = FormatTools.UINT8; break; case 2: case 6: core[i].pixelType = FormatTools.UINT16; break; case 4: core[i].pixelType = FormatTools.UINT32; break; default: throw new FormatException("Unsupported bytes per pixel (" + bpp + ")"); } core[i].dimensionOrder = "XY"; resolution = stream.readInt(); addMeta(prefix + "Real world resolution", resolution); int length = stream.readInt() * 2; addMeta(prefix + "Maximum voxel intensity", getString(stream, length)); length = stream.readInt() * 2; addMeta(prefix + "Minimum voxel intensity", getString(stream, length)); length = stream.readInt(); stream.skipBytes(length * 2); stream.skipBytes(4); // version number length = stream.readInt(); for (int j=0; j<length; j++) { int dimId = stream.readInt(); String dimType = (String) dimensionNames.get(new Integer(dimId)); if (dimType == null) dimType = ""; int size = stream.readInt(); int distance = stream.readInt(); int strlen = stream.readInt(); String physicalSize = getString(stream, strlen * 2); String unit = ""; if (physicalSize.indexOf(" ") != -1) { unit = physicalSize.substring(physicalSize.indexOf(" ") + 1); physicalSize = physicalSize.substring(0, physicalSize.indexOf(" ")); } float physical = Float.parseFloat(physicalSize) / size; if (unit.equals("m")) { physical *= 1000000; } if (dimType.equals("x")) { core[i].sizeX = size; physicalSizes[i][0] = physical; } else if (dimType.equals("y")) { core[i].sizeY = size; physicalSizes[i][1] = physical; } else if (dimType.indexOf("z") != -1) { core[i].sizeZ = size; if (core[i].dimensionOrder.indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } physicalSizes[i][2] = physical; } else if (dimType.equals("channel")) { core[i].sizeC = size; if (core[i].dimensionOrder.indexOf("C") == -1) { core[i].dimensionOrder += "C"; } physicalSizes[i][3] = physical; } else { core[i].sizeT = size; if (core[i].dimensionOrder.indexOf("T") == -1) { core[i].dimensionOrder += "T"; } physicalSizes[i][4] = physical; } addMeta(prefix + "Dim" + j + " type", dimType); addMeta(prefix + "Dim" + j + " size", size); addMeta(prefix + "Dim" + j + " distance between sub-dimensions", distance); addMeta(prefix + "Dim" + j + " physical length", physicalSize + " " + unit); int len = stream.readInt(); addMeta(prefix + "Dim" + j + " physical origin", getString(stream, len * 2)); } int len = stream.readInt(); addMeta(prefix + "Series name", getString(stream, len)); len = stream.readInt(); String description = getString(stream, len); seriesDescriptions.add(description); addMeta(prefix + "Series description", description); stream.close(); } parseInstrumentData((byte[]) headerIFDs[i].get(FILTERSET), store, i); temp = (byte[]) headerIFDs[i].get(TIMEINFO); if (temp != null) { // time data // ID_TIMEINFO RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); stream.seek(0); int nDims = stream.readInt(); addMeta(prefix + "Number of time-stamped dimensions", nDims); addMeta(prefix + "Time-stamped dimension", stream.readInt()); for (int j=0; j < nDims; j++) { addMeta(prefix + "Dimension " + j + " ID", stream.readInt()); addMeta(prefix + "Dimension " + j + " size", stream.readInt()); addMeta(prefix + "Dimension " + j + " distance between dimensions", stream.readInt()); } int numStamps = stream.readInt(); addMeta(prefix + "Number of time-stamps", numStamps); timestamps[i] = new String[numStamps]; for (int j=0; j<numStamps; j++) { timestamps[i][j] = getString(stream, 64); addMeta(prefix + "Timestamp " + j, timestamps[i][j]); } if (stream.getFilePointer() < stream.length()) { int numTMs = stream.readInt(); addMeta(prefix + "Number of time-markers", numTMs); for (int j=0; j<numTMs; j++) { int numDims = stream.readInt(); String time = "Time-marker " + j + " Dimension "; for (int k=0; k<numDims; k++) { addMeta(prefix + time + k + " coordinate", stream.readInt()); } addMeta(prefix + "Time-marker " + j, getString(stream, 64)); } } stream.close(); } parseInstrumentData((byte[]) headerIFDs[i].get(SCANNERSET), store, i); temp = (byte[]) headerIFDs[i].get(EXPERIMENT); if (temp != null) { // experiment data // ID_EXPERIMENT RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); stream.seek(8); int len = stream.readInt(); String description = getString(stream, len * 2); addMeta(prefix + "Image Description", description); len = stream.readInt(); addMeta(prefix + "Main file extension", getString(stream, len * 2)); len = stream.readInt(); addMeta(prefix + "Single image format identifier", getString(stream, len * 2)); len = stream.readInt(); addMeta(prefix + "Single image extension", getString(stream, len * 2)); stream.close(); } temp = (byte[]) headerIFDs[i].get(LUTDESC); if (temp != null) { // LUT data // ID_LUTDESC RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); int nChannels = stream.readInt(); if (nChannels > 0) core[i].indexed = true; addMeta(prefix + "Number of LUT channels", nChannels); addMeta(prefix + "ID of colored dimension", stream.readInt()); channelMap[i] = new int[nChannels]; String[] luts = new String[nChannels]; for (int j=0; j<nChannels; j++) { String p = "LUT Channel " + j; addMeta(prefix + p + " version", stream.readInt()); addMeta(prefix + p + " inverted?", stream.read() == 1); int length = stream.readInt(); addMeta(prefix + p + " description", getString(stream, length)); length = stream.readInt(); addMeta(prefix + p + " filename", getString(stream, length)); length = stream.readInt(); luts[j] = getString(stream, length); addMeta(prefix + p + " name", luts[j]); luts[j] = luts[j].toLowerCase(); stream.skipBytes(8); } stream.close(); // finish setting up channel mapping for (int q=0; q<channelMap[i].length; q++) { if (!CHANNEL_PRIORITIES.containsKey(luts[q])) luts[q] = ""; channelMap[i][q] = ((Integer) CHANNEL_PRIORITIES.get(luts[q])).intValue(); } int[] sorted = new int[channelMap[i].length]; Arrays.fill(sorted, -1); for (int q=0; q<sorted.length; q++) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int n=0; n<channelMap[i].length; n++) { if (channelMap[i][n] < min && !containsValue(sorted, n)) { min = channelMap[i][n]; minIndex = n; } } sorted[q] = minIndex; } for (int q=0; q<channelMap[i].length; q++) { channelMap[i][sorted[q]] = q; } } core[i].orderCertain = true; core[i].littleEndian = isLittleEndian(); core[i].falseColor = true; core[i].metadataComplete = true; core[i].interleaved = false; } for (int i=0; i<numSeries; i++) { setSeries(i); if (getSizeZ() == 0) core[i].sizeZ = 1; if (getSizeT() == 0) core[i].sizeT = 1; if (getSizeC() == 0) core[i].sizeC = 1; if (getImageCount() == 0) core[i].imageCount = 1; if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) { core[i].sizeZ = 1; core[i].sizeT = 1; } tiff.setId((String) files[i].get(0)); core[i].sizeX = tiff.getSizeX(); core[i].sizeY = tiff.getSizeY(); core[i].rgb = tiff.isRGB(); core[i].indexed = tiff.isIndexed(); core[i].sizeC *= tiff.getSizeC(); if (getDimensionOrder().indexOf("C") == -1) { core[i].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } if (getDimensionOrder().indexOf("T") == -1) { core[i].dimensionOrder += "T"; } long firstPlane = 0; if (i < timestamps.length && timestamps[i] != null && timestamps[i].length > 0) { SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS"); Date date = parse.parse(timestamps[i][0], new ParsePosition(0)); firstPlane = date.getTime(); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); store.setImageCreationDate(fmt.format(date), i); } else { MetadataTools.setDefaultCreationDate(store, id, i); } store.setImageName((String) seriesNames.get(i), i); store.setImageDescription((String) seriesDescriptions.get(i), i); store.setDimensionsPhysicalSizeX(new Float(physicalSizes[i][0]), i, 0); store.setDimensionsPhysicalSizeY(new Float(physicalSizes[i][1]), i, 0); store.setDimensionsPhysicalSizeZ(new Float(physicalSizes[i][2]), i, 0); store.setDimensionsWaveIncrement( new Integer((int) physicalSizes[i][3]), i, 0); store.setDimensionsTimeIncrement(new Float(physicalSizes[i][4]), i, 0); for (int j=0; j<core[i].imageCount; j++) { if (timestamps[i] != null && j < timestamps[i].length) { SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS"); Date date = parse.parse(timestamps[i][j], new ParsePosition(0)); float elapsedTime = (float) (date.getTime() - firstPlane) / 1000; store.setPlaneTimingDeltaT(new Float(elapsedTime), i, 0, j); } } } MetadataTools.populatePixels(store, this, true); setSeries(0); }
protected void initFile(String id) throws FormatException, IOException { if (debug) debug("LeicaReader.initFile(" + id + ")"); close(); if (checkSuffix(id, TiffReader.TIFF_SUFFIXES)) { // need to find the associated .lei file if (ifds == null) super.initFile(id); in = new RandomAccessStream(id); in.order(TiffTools.checkHeader(in).booleanValue()); in.seek(0); status("Finding companion file name"); // open the TIFF file and look for the "Image Description" field ifds = TiffTools.getIFDs(in); if (ifds == null) throw new FormatException("No IFDs found"); String descr = TiffTools.getComment(ifds[0]); // remove anything of the form "[blah]" descr = descr.replaceAll("\\[.*.\\]\n", ""); // each remaining line in descr is a (key, value) pair, // where '=' separates the key from the value String lei = id.substring(0, id.lastIndexOf(File.separator) + 1); StringTokenizer lines = new StringTokenizer(descr, "\n"); String line = null, key = null, value = null; while (lines.hasMoreTokens()) { line = lines.nextToken(); if (line.indexOf("=") == -1) continue; key = line.substring(0, line.indexOf("=")).trim(); value = line.substring(line.indexOf("=") + 1).trim(); addMeta(key, value); if (key.startsWith("Series Name")) lei += value; } // now open the LEI file Location l = new Location(lei).getAbsoluteFile(); if (l.exists()) { initFile(lei); return; } else { l = l.getParentFile(); String[] list = l.list(); for (int i=0; i<list.length; i++) { if (checkSuffix(list[i], LEI_SUFFIX)) { initFile( new Location(l.getAbsolutePath(), list[i]).getAbsolutePath()); return; } } } throw new FormatException("LEI file not found."); } // parse the LEI file super.initFile(id); leiFilename = new File(id).exists() ? new Location(id).getAbsolutePath() : id; in = new RandomAccessStream(id); seriesNames = new Vector(); byte[] fourBytes = new byte[4]; in.read(fourBytes); core[0].littleEndian = (fourBytes[0] == TiffTools.LITTLE && fourBytes[1] == TiffTools.LITTLE && fourBytes[2] == TiffTools.LITTLE && fourBytes[3] == TiffTools.LITTLE); in.order(isLittleEndian()); status("Reading metadata blocks"); in.skipBytes(8); int addr = in.readInt(); Vector v = new Vector(); Hashtable ifd; while (addr != 0) { ifd = new Hashtable(); v.add(ifd); in.seek(addr + 4); int tag = in.readInt(); while (tag != 0) { // create the IFD structure int offset = in.readInt(); long pos = in.getFilePointer(); in.seek(offset + 12); int size = in.readInt(); byte[] data = new byte[size]; in.read(data); ifd.put(new Integer(tag), data); in.seek(pos); tag = in.readInt(); } addr = in.readInt(); } numSeries = v.size(); core = new CoreMetadata[numSeries]; for (int i=0; i<numSeries; i++) { core[i] = new CoreMetadata(); } channelMap = new int[numSeries][]; files = new Vector[numSeries]; headerIFDs = (Hashtable[]) v.toArray(new Hashtable[0]); // determine the length of a filename int nameLength = 0; int maxPlanes = 0; status("Parsing metadata blocks"); core[0].littleEndian = !isLittleEndian(); int seriesIndex = 0; boolean[] valid = new boolean[numSeries]; for (int i=0; i<headerIFDs.length; i++) { valid[i] = true; if (headerIFDs[i].get(SERIES) != null) { byte[] temp = (byte[]) headerIFDs[i].get(SERIES); nameLength = DataTools.bytesToInt(temp, 8, isLittleEndian()) * 2; } Vector f = new Vector(); byte[] tempData = (byte[]) headerIFDs[i].get(IMAGES); RandomAccessStream data = new RandomAccessStream(tempData); data.order(isLittleEndian()); int tempImages = data.readInt(); if (((long) tempImages * nameLength) > data.length()) { data.order(!isLittleEndian()); tempImages = data.readInt(); data.order(isLittleEndian()); } File dirFile = new File(id).getAbsoluteFile(); String[] listing = null; String dirPrefix = ""; if (dirFile.exists()) { listing = dirFile.getParentFile().list(); dirPrefix = dirFile.getParent(); if (!dirPrefix.endsWith(File.separator)) dirPrefix += File.separator; } else { listing = (String[]) Location.getIdMap().keySet().toArray(new String[0]); } Vector list = new Vector(); for (int k=0; k<listing.length; k++) { if (checkSuffix(listing[k], TiffReader.TIFF_SUFFIXES)) { list.add(listing[k]); } } boolean tiffsExist = true; data.seek(20); String prefix = ""; for (int j=0; j<tempImages; j++) { // read in each filename prefix = getString(data, nameLength); f.add(dirPrefix + prefix); // test to make sure the path is valid Location test = new Location((String) f.get(f.size() - 1)); if (test.exists()) list.remove(prefix); if (tiffsExist) tiffsExist = test.exists(); } data.close(); tempData = null; // at least one of the TIFF files was renamed if (!tiffsExist) { // Strategy for handling renamed files: // 1) Assume that files for each series follow a pattern. // 2) Assign each file group to the first series with the correct count. status("Handling renamed TIFF files"); listing = (String[]) list.toArray(new String[0]); // grab the file patterns Vector filePatterns = new Vector(); for (int q=0; q<listing.length; q++) { Location l = new Location(dirPrefix, listing[q]); l = l.getAbsoluteFile(); FilePattern pattern = new FilePattern(l); AxisGuesser guess = new AxisGuesser(pattern, "XYZCT", 1, 1, 1, false); String fp = pattern.getPattern(); if (guess.getAxisCountS() >= 1) { String pre = pattern.getPrefix(guess.getAxisCountS()); Vector fileList = new Vector(); for (int n=0; n<listing.length; n++) { Location p = new Location(dirPrefix, listing[n]); if (p.getAbsolutePath().startsWith(pre)) { fileList.add(listing[n]); } } fp = FilePattern.findPattern(l.getAbsolutePath(), dirPrefix, (String[]) fileList.toArray(new String[0])); } if (fp != null && !filePatterns.contains(fp)) { filePatterns.add(fp); } } for (int q=0; q<filePatterns.size(); q++) { String[] pattern = new FilePattern((String) filePatterns.get(q)).getFiles(); if (pattern.length == tempImages) { // make sure that this pattern hasn't already been used boolean validPattern = true; for (int n=0; n<i; n++) { if (files[n] == null) continue; if (files[n].contains(pattern[0])) { validPattern = false; break; } } if (validPattern) { files[i] = new Vector(); for (int n=0; n<pattern.length; n++) { files[i].add(pattern[n]); } } } } } else files[i] = f; if (files[i] == null) valid[i] = false; else { core[i].imageCount = files[i].size(); if (core[i].imageCount > maxPlanes) maxPlanes = core[i].imageCount; } } int invalidCount = 0; for (int i=0; i<valid.length; i++) { if (!valid[i]) invalidCount++; } numSeries -= invalidCount; int[] count = new int[core.length]; for (int i=0; i<core.length; i++) { count[i] = core[i].imageCount; } Vector[] tempFiles = files; Hashtable[] tempIFDs = headerIFDs; core = new CoreMetadata[numSeries]; files = new Vector[numSeries]; headerIFDs = new Hashtable[numSeries]; int index = 0; for (int i=0; i<numSeries; i++) { core[i] = new CoreMetadata(); while (!valid[index]) index++; core[i].imageCount = count[index]; files[i] = tempFiles[index]; Object[] sorted = files[i].toArray(); Arrays.sort(sorted); files[i].clear(); for (int q=0; q<sorted.length; q++) { files[i].add(sorted[q]); } headerIFDs[i] = tempIFDs[index]; index++; } tiff = new MinimalTiffReader(); status("Populating metadata"); if (headerIFDs == null) headerIFDs = ifds; int fileLength = 0; int resolution = -1; String[][] timestamps = new String[headerIFDs.length][]; seriesDescriptions = new Vector(); physicalSizes = new float[headerIFDs.length][5]; MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); for (int i=0; i<headerIFDs.length; i++) { String prefix = "Series " + i + " "; byte[] temp = (byte[]) headerIFDs[i].get(SERIES); if (temp != null) { // the series data // ID_SERIES RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); addMeta(prefix + "Version", stream.readInt()); addMeta(prefix + "Number of Series", stream.readInt()); fileLength = stream.readInt(); addMeta(prefix + "Length of filename", fileLength); Integer extLen = new Integer(stream.readInt()); if (extLen.intValue() > fileLength) { stream.seek(8); core[0].littleEndian = !isLittleEndian(); stream.order(isLittleEndian()); fileLength = stream.readInt(); extLen = new Integer(stream.readInt()); } addMeta(prefix + "Length of file extension", extLen); addMeta(prefix + "Image file extension", getString(stream, extLen.intValue())); stream.close(); } temp = (byte[]) headerIFDs[i].get(IMAGES); if (temp != null) { // the image data // ID_IMAGES RandomAccessStream s = new RandomAccessStream(temp); s.order(isLittleEndian()); core[i].imageCount = s.readInt(); core[i].sizeX = s.readInt(); core[i].sizeY = s.readInt(); addMeta(prefix + "Number of images", core[i].imageCount); addMeta(prefix + "Image width", core[i].sizeX); addMeta(prefix + "Image height", core[i].sizeY); addMeta(prefix + "Bits per Sample", s.readInt()); addMeta(prefix + "Samples per pixel", s.readInt()); String p = getString(s, fileLength * 2); s.close(); StringTokenizer st = new StringTokenizer(p, "_"); StringBuffer buf = new StringBuffer(); st.nextToken(); while (st.hasMoreTokens()) { String token = st.nextToken(); String lcase = token.toLowerCase(); if (!checkSuffix(lcase, TiffReader.TIFF_SUFFIXES) && !lcase.startsWith("ch0") && !lcase.startsWith("c0") && !lcase.startsWith("z0")) { if (buf.length() > 0) buf.append("_"); buf.append(token); } } seriesNames.add(buf.toString()); } temp = (byte[]) headerIFDs[i].get(DIMDESCR); if (temp != null) { // dimension description // ID_DIMDESCR RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); addMeta(prefix + "Voxel Version", stream.readInt()); int voxelType = stream.readInt(); core[i].rgb = voxelType == 20; addMeta(prefix + "VoxelType", voxelType == 20 ? "RGB" : "gray"); int bpp = stream.readInt(); addMeta(prefix + "Bytes per pixel", bpp); switch (bpp) { case 1: case 3: core[i].pixelType = FormatTools.UINT8; break; case 2: case 6: core[i].pixelType = FormatTools.UINT16; break; case 4: core[i].pixelType = FormatTools.UINT32; break; default: throw new FormatException("Unsupported bytes per pixel (" + bpp + ")"); } core[i].dimensionOrder = "XY"; resolution = stream.readInt(); addMeta(prefix + "Real world resolution", resolution); int length = stream.readInt() * 2; addMeta(prefix + "Maximum voxel intensity", getString(stream, length)); length = stream.readInt() * 2; addMeta(prefix + "Minimum voxel intensity", getString(stream, length)); length = stream.readInt(); stream.skipBytes(length * 2); stream.skipBytes(4); // version number length = stream.readInt(); for (int j=0; j<length; j++) { int dimId = stream.readInt(); String dimType = (String) dimensionNames.get(new Integer(dimId)); if (dimType == null) dimType = ""; int size = stream.readInt(); int distance = stream.readInt(); int strlen = stream.readInt(); String physicalSize = getString(stream, strlen * 2); String unit = ""; if (physicalSize.indexOf(" ") != -1) { unit = physicalSize.substring(physicalSize.indexOf(" ") + 1); physicalSize = physicalSize.substring(0, physicalSize.indexOf(" ")); } float physical = Float.parseFloat(physicalSize) / size; if (unit.equals("m")) { physical *= 1000000; } if (dimType.equals("x")) { core[i].sizeX = size; physicalSizes[i][0] = physical; } else if (dimType.equals("y")) { core[i].sizeY = size; physicalSizes[i][1] = physical; } else if (dimType.indexOf("z") != -1) { core[i].sizeZ = size; if (core[i].dimensionOrder.indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } physicalSizes[i][2] = physical; } else if (dimType.equals("channel")) { core[i].sizeC = size; if (core[i].dimensionOrder.indexOf("C") == -1) { core[i].dimensionOrder += "C"; } physicalSizes[i][3] = physical; } else { core[i].sizeT = size; if (core[i].dimensionOrder.indexOf("T") == -1) { core[i].dimensionOrder += "T"; } physicalSizes[i][4] = physical; } addMeta(prefix + "Dim" + j + " type", dimType); addMeta(prefix + "Dim" + j + " size", size); addMeta(prefix + "Dim" + j + " distance between sub-dimensions", distance); addMeta(prefix + "Dim" + j + " physical length", physicalSize + " " + unit); int len = stream.readInt(); addMeta(prefix + "Dim" + j + " physical origin", getString(stream, len * 2)); } int len = stream.readInt(); addMeta(prefix + "Series name", getString(stream, len)); len = stream.readInt(); String description = getString(stream, len); seriesDescriptions.add(description); addMeta(prefix + "Series description", description); stream.close(); } parseInstrumentData((byte[]) headerIFDs[i].get(FILTERSET), store, i); temp = (byte[]) headerIFDs[i].get(TIMEINFO); if (temp != null) { // time data // ID_TIMEINFO RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); stream.seek(0); int nDims = stream.readInt(); addMeta(prefix + "Number of time-stamped dimensions", nDims); addMeta(prefix + "Time-stamped dimension", stream.readInt()); for (int j=0; j < nDims; j++) { addMeta(prefix + "Dimension " + j + " ID", stream.readInt()); addMeta(prefix + "Dimension " + j + " size", stream.readInt()); addMeta(prefix + "Dimension " + j + " distance between dimensions", stream.readInt()); } int numStamps = stream.readInt(); addMeta(prefix + "Number of time-stamps", numStamps); timestamps[i] = new String[numStamps]; for (int j=0; j<numStamps; j++) { timestamps[i][j] = getString(stream, 64); addMeta(prefix + "Timestamp " + j, timestamps[i][j]); } if (stream.getFilePointer() < stream.length()) { int numTMs = stream.readInt(); addMeta(prefix + "Number of time-markers", numTMs); for (int j=0; j<numTMs; j++) { int numDims = stream.readInt(); String time = "Time-marker " + j + " Dimension "; for (int k=0; k<numDims; k++) { addMeta(prefix + time + k + " coordinate", stream.readInt()); } addMeta(prefix + "Time-marker " + j, getString(stream, 64)); } } stream.close(); } parseInstrumentData((byte[]) headerIFDs[i].get(SCANNERSET), store, i); temp = (byte[]) headerIFDs[i].get(EXPERIMENT); if (temp != null) { // experiment data // ID_EXPERIMENT RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); stream.seek(8); int len = stream.readInt(); String description = getString(stream, len * 2); addMeta(prefix + "Image Description", description); len = stream.readInt(); addMeta(prefix + "Main file extension", getString(stream, len * 2)); len = stream.readInt(); addMeta(prefix + "Single image format identifier", getString(stream, len * 2)); len = stream.readInt(); addMeta(prefix + "Single image extension", getString(stream, len * 2)); stream.close(); } temp = (byte[]) headerIFDs[i].get(LUTDESC); if (temp != null) { // LUT data // ID_LUTDESC RandomAccessStream stream = new RandomAccessStream(temp); stream.order(isLittleEndian()); int nChannels = stream.readInt(); if (nChannels > 0) core[i].indexed = true; addMeta(prefix + "Number of LUT channels", nChannels); addMeta(prefix + "ID of colored dimension", stream.readInt()); channelMap[i] = new int[nChannels]; String[] luts = new String[nChannels]; for (int j=0; j<nChannels; j++) { String p = "LUT Channel " + j; addMeta(prefix + p + " version", stream.readInt()); addMeta(prefix + p + " inverted?", stream.read() == 1); int length = stream.readInt(); addMeta(prefix + p + " description", getString(stream, length)); length = stream.readInt(); addMeta(prefix + p + " filename", getString(stream, length)); length = stream.readInt(); luts[j] = getString(stream, length); addMeta(prefix + p + " name", luts[j]); luts[j] = luts[j].toLowerCase(); stream.skipBytes(8); } stream.close(); // finish setting up channel mapping for (int q=0; q<channelMap[i].length; q++) { if (!CHANNEL_PRIORITIES.containsKey(luts[q])) luts[q] = ""; channelMap[i][q] = ((Integer) CHANNEL_PRIORITIES.get(luts[q])).intValue(); } int[] sorted = new int[channelMap[i].length]; Arrays.fill(sorted, -1); for (int q=0; q<sorted.length; q++) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int n=0; n<channelMap[i].length; n++) { if (channelMap[i][n] < min && !containsValue(sorted, n)) { min = channelMap[i][n]; minIndex = n; } } sorted[q] = minIndex; } for (int q=0; q<channelMap[i].length; q++) { channelMap[i][sorted[q]] = q; } } core[i].orderCertain = true; core[i].littleEndian = isLittleEndian(); core[i].falseColor = true; core[i].metadataComplete = true; core[i].interleaved = false; } for (int i=0; i<numSeries; i++) { setSeries(i); if (getSizeZ() == 0) core[i].sizeZ = 1; if (getSizeT() == 0) core[i].sizeT = 1; if (getSizeC() == 0) core[i].sizeC = 1; if (getImageCount() == 0) core[i].imageCount = 1; if (getImageCount() == 1 && getSizeZ() * getSizeT() > 1) { core[i].sizeZ = 1; core[i].sizeT = 1; } tiff.setId((String) files[i].get(0)); core[i].sizeX = tiff.getSizeX(); core[i].sizeY = tiff.getSizeY(); core[i].rgb = tiff.isRGB(); core[i].indexed = tiff.isIndexed(); core[i].sizeC *= tiff.getSizeC(); if (getDimensionOrder().indexOf("C") == -1) { core[i].dimensionOrder += "C"; } if (getDimensionOrder().indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } if (getDimensionOrder().indexOf("T") == -1) { core[i].dimensionOrder += "T"; } long firstPlane = 0; if (i < timestamps.length && timestamps[i] != null && timestamps[i].length > 0) { SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS"); Date date = parse.parse(timestamps[i][0], new ParsePosition(0)); firstPlane = date.getTime(); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); store.setImageCreationDate(fmt.format(date), i); } else { MetadataTools.setDefaultCreationDate(store, id, i); } store.setImageName((String) seriesNames.get(i), i); store.setImageDescription((String) seriesDescriptions.get(i), i); store.setDimensionsPhysicalSizeX(new Float(physicalSizes[i][0]), i, 0); store.setDimensionsPhysicalSizeY(new Float(physicalSizes[i][1]), i, 0); store.setDimensionsPhysicalSizeZ(new Float(physicalSizes[i][2]), i, 0); store.setDimensionsWaveIncrement( new Integer((int) physicalSizes[i][3]), i, 0); store.setDimensionsTimeIncrement(new Float(physicalSizes[i][4]), i, 0); for (int j=0; j<core[i].imageCount; j++) { if (timestamps[i] != null && j < timestamps[i].length) { SimpleDateFormat parse = new SimpleDateFormat("yyyy:MM:dd,HH:mm:ss:SSS"); Date date = parse.parse(timestamps[i][j], new ParsePosition(0)); float elapsedTime = (float) (date.getTime() - firstPlane) / 1000; store.setPlaneTimingDeltaT(new Float(elapsedTime), i, 0, j); } } } MetadataTools.populatePixels(store, this, true); setSeries(0); }
diff --git a/edu/wisc/ssec/mcidasv/ViewManagerManager.java b/edu/wisc/ssec/mcidasv/ViewManagerManager.java index f76c1f79c..0cb7221a9 100644 --- a/edu/wisc/ssec/mcidasv/ViewManagerManager.java +++ b/edu/wisc/ssec/mcidasv/ViewManagerManager.java @@ -1,205 +1,208 @@ package edu.wisc.ssec.mcidasv; import java.util.List; import java.util.Stack; import edu.wisc.ssec.mcidasv.ui.UIManager; import ucar.unidata.idv.IntegratedDataViewer; import ucar.unidata.idv.VMManager; import ucar.unidata.idv.ViewDescriptor; import ucar.unidata.idv.ViewManager; import ucar.unidata.idv.control.DisplayControlImpl; import ucar.unidata.util.GuiUtils; /** * <p>McIDAS-V needs to manage ViewManagers in a slightly different way than * the IDV. The key differences between the two are the way previously active * ViewManagers are ordered and a (hopefully) more consistent way of handling * active ViewManagers.</p> * * <p>The IDV only keeps track of the ViewManager used immediately before the * current one. McV keeps track of the previously active ViewManagers in a * stack. This mimics window z-ordering and always returns the user to the most * recently active ViewManager upon removal of the active ViewManager.</p> * * <p>Newly created ViewManagers and their first layer now become the active * ViewManager and layer. If there is only one ViewManager, it is now displayed * as active instead of just implying it. When the active ViewManager is * removed, the last active ViewManager and its first layer become active.</p> * * <p><b>A note to the future</b>: McV/IDV supports two notions of active and * selected ViewManagers. Say you have NxN ViewManagers in a ComponentHolder, * and you want to share views among some of these ViewManagers. When one of * these shared ViewManagers is activated, should all of them become the active * ViewManager? We're going to have to work out how to convey which * ViewManagers are shared and active, and maybe more? Good luck!</p> */ // TODO: should accesses to previousVMs should be synchronized? // TODO: should keep track of the ordering of active layers per VM as well. public class ViewManagerManager extends VMManager { /** Whether or not to display debug messages. */ private final boolean DEBUG = false; /** The stack that stores the order of previously active ViewManagers. */ private Stack<ViewManager> previousVMs = new Stack<ViewManager>(); /** Convenient reference back to the UIManager. */ private UIManager uiManager; /** * Yet another constructor. */ public ViewManagerManager(IntegratedDataViewer idv) { super(idv); uiManager = (UIManager)getIdvUIManager(); } /** * Add the new view manager into the list if we don't have * one with the {@link ViewDescriptor} of the new view manager * already. * * @param newViewManager The new view manager */ @Override public void addViewManager(ViewManager newViewManager) { super.addViewManager(newViewManager); focusLayerControlsOn(newViewManager, false); } /** * @return Reference to the stack of previously active ViewManagers. */ public Stack<ViewManager> getViewManagerOrder() { return previousVMs; } /** * Overridden so that McV can set the active ViewManager even if there is * only ViewManager. This is just a UI nicety. */ @Override public boolean haveMoreThanOneMainViewManager() { return true; } /** * Handles the removal of a ViewManager. McV needs to override this so that * the stack of previously active ViewManagers is ordered properly. McV uses * this method to make the ViewPanel respond immediately to the change. * * @param viewManager The ViewManager being removed. */ @Override public void removeViewManager(ViewManager viewManager) { if (getLastActiveViewManager() != viewManager) { previousVMs.remove(viewManager); inspectStack("removed inactive vm"); } super.removeViewManager(viewManager); // inform UIManager that the VM needs to be dissociated from its // ComponentHolder. uiManager.removeViewManagerHolder(viewManager); // force the layer controls tabs to layout the remaining components, // but we don't want to bring it to the front! uiManager.getViewPanel().getContents().validate(); } /** * <p>This method is a bit strange. If the given ViewManager is null, then * the IDV has removed the active ViewManager. McV will use the stack of * last active ViewManagers to make the last active ViewManager active once * again.</p> * * <p>If the given ViewManager is not null, but cannot be found in the stack * of previously active ViewManagers, the IDV has created a new ViewManager * and McV must push it on the stack.</p> * * <p>If the given ViewManager is not null and has been found in the stack, * then the user has selected an inactive ViewManager. McV must remove the * ViewManager from the stack and then push it back on top.</p> * * <p>These steps allow McV to make the behavior of closing tabs a bit more * user-friendly. The user is always returned to whichever ViewManager was * last active.</p> * * @param vm See above. :( */ // TODO: when you start removing the debug stuff, just convert the messages // to comments. @Override public void setLastActiveViewManager(ViewManager vm) { String debugMsg = "created new vm"; if (vm != null) { if (previousVMs.search(vm) >= 0) { debugMsg = "reset active vm"; previousVMs.remove(vm); focusLayerControlsOn(vm, false); } previousVMs.push(vm); } else { debugMsg = "removed active vm"; ViewManager lastActive = getLastActiveViewManager(); if (lastActive == null) return; lastActive.setLastActive(false); previousVMs.pop(); + if (previousVMs.size() == 0) + return; + lastActive = previousVMs.peek(); lastActive.setLastActive(true); focusLayerControlsOn(lastActive, false); } inspectStack(debugMsg); super.setLastActiveViewManager(previousVMs.peek()); } /** * <p>Overwrite the stack containing the ordering of previously active * ViewManagers.</p> * * <p>Use this if you want to mess with the user's mind a little bit.</p> * * @param newOrder The stack containing the new ordering of ViewManagers. */ public void setViewManagerOrder(Stack<ViewManager> newOrder) { previousVMs = newOrder; } /** * Sets the active tab of the dashboard to the layer controls and makes the * first layer (TODO: fix that!) of the given ViewManager the active layer. * * @param vm The ViewManager to make active. * @param doShow Whether or not focus should be stolen. */ private void focusLayerControlsOn(ViewManager vm, boolean doShow) { List<DisplayControlImpl> controls = vm.getControlsForLegend(); if (controls != null && !controls.isEmpty()) { DisplayControlImpl control = controls.get(0); GuiUtils.showComponentInTabs(control.getOuterContents(), doShow); } } /** * Helper method that'll display the ordering of the stack and a helpful * debug message! */ private void inspectStack(String msg) { if (!DEBUG) return; System.out.print(msg + ": ["); for (ViewManager vm : previousVMs) System.out.print(vm.getName() + ","); System.out.println("] Size=" + previousVMs.size()); } }
true
false
null
null
diff --git a/WEB-INF/src/edu/wustl/catissuecore/bizlogic/NewSpecimenBizLogic.java b/WEB-INF/src/edu/wustl/catissuecore/bizlogic/NewSpecimenBizLogic.java index b234e31dc..08e8db221 100644 --- a/WEB-INF/src/edu/wustl/catissuecore/bizlogic/NewSpecimenBizLogic.java +++ b/WEB-INF/src/edu/wustl/catissuecore/bizlogic/NewSpecimenBizLogic.java @@ -1,1960 +1,1962 @@ /** * <p>Title: NewSpecimenHDAO Class> * <p>Description: NewSpecimenBizLogicHDAO is used to add new specimen information into the database using Hibernate.</p> * Copyright: Copyright (c) year * Company: Washington University, School of Medicine, St. Louis. * @author Aniruddha Phadnis * @version 1.00 * Created on Jul 21, 2005 */ package edu.wustl.catissuecore.bizlogic; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import net.sf.hibernate.HibernateException; import edu.wustl.catissuecore.domain.Address; import edu.wustl.catissuecore.domain.Biohazard; import edu.wustl.catissuecore.domain.CellSpecimen; import edu.wustl.catissuecore.domain.CollectionEventParameters; import edu.wustl.catissuecore.domain.DisposalEventParameters; import edu.wustl.catissuecore.domain.DistributedItem; import edu.wustl.catissuecore.domain.ExternalIdentifier; import edu.wustl.catissuecore.domain.FluidSpecimen; import edu.wustl.catissuecore.domain.MolecularSpecimen; import edu.wustl.catissuecore.domain.QuantityInCount; import edu.wustl.catissuecore.domain.QuantityInGram; import edu.wustl.catissuecore.domain.QuantityInMicrogram; import edu.wustl.catissuecore.domain.QuantityInMilliliter; import edu.wustl.catissuecore.domain.ReceivedEventParameters; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenCharacteristics; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.domain.SpecimenEventParameters; import edu.wustl.catissuecore.domain.StorageContainer; import edu.wustl.catissuecore.domain.TissueSpecimen; import edu.wustl.catissuecore.integration.IntegrationManager; import edu.wustl.catissuecore.integration.IntegrationManagerFactory; import edu.wustl.catissuecore.util.ApiSearchUtil; import edu.wustl.catissuecore.util.StorageContainerUtil; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.dao.DAO; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.security.SecurityManager; import edu.wustl.common.security.exceptions.SMException; import edu.wustl.common.security.exceptions.UserNotAuthorizedException; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.Validator; import edu.wustl.common.util.logger.Logger; /** * NewSpecimenHDAO is used to add new specimen information into the database using Hibernate. * @author aniruddha_phadnis */ public class NewSpecimenBizLogic extends IntegrationBizLogic { /** * Saves the storageType object in the database. * @param obj The storageType object to be saved. * @param session The session in which the object is saved. * @throws DAOException */ protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { if (obj instanceof Map) { insertMultipleSpecimen((Map) obj, dao, sessionDataBean); } else { insertSingleSpecimen((Specimen) obj, dao, sessionDataBean, false); //Inserting authorization data Specimen specimen = (Specimen) obj; Set protectionObjects = new HashSet(); protectionObjects.add(specimen); if (specimen.getSpecimenCharacteristics() != null) { protectionObjects.add(specimen.getSpecimenCharacteristics()); } try { SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, getDynamicGroups(specimen)); } catch (SMException e) { throw handleSMException(e); } } } /** * Insert multiple specimen into the data base. * @param specimenList * @param dao * @param sessionDataBean * @throws DAOException * @throws UserNotAuthorizedException */ private void insertMultipleSpecimen(Map specimenMap, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { List specimenList = new ArrayList(); Iterator specimenIterator = specimenMap.keySet().iterator(); + int count = 0; while (specimenIterator.hasNext()) { + count++; Specimen specimen = (Specimen) specimenIterator.next(); /** * Start: Change for API Search --- Jitendra 06/10/2006 * In Case of Api Search, previoulsy it was failing since there was default class level initialization * on domain object. For example in User object, it was initialized as protected String lastName=""; * So we removed default class level initialization on domain object and are initializing in method * setAllValues() of domain object. But in case of Api Search, default values will not get set * since setAllValues() method of domainObject will not get called. To avoid null pointer exception, * we are setting the default values same as we were setting in setAllValues() method of domainObject. */ ApiSearchUtil.setSpecimenDefault(specimen); //End:- Change for API Search Long parentSpecimenId = specimen.getId(); resetId(specimen); try { insertSingleSpecimen(specimen, dao, sessionDataBean, true); specimenList.add(specimen); } catch (DAOException daoException) { - String message = " (This message is for Specimen number " + parentSpecimenId + ")"; + String message = " (This message is for Specimen number " + count + ")"; daoException.setSupportingMessage(message); throw daoException; } List derivedSpecimens = (List) specimenMap.get(specimen); if (derivedSpecimens == null) { continue; } //insert derived specimens for (int i = 0; i < derivedSpecimens.size(); i++) { Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i); resetId(derivedSpecimen); derivedSpecimen.setParentSpecimen(specimen); derivedSpecimen.setSpecimenCollectionGroup(specimen.getSpecimenCollectionGroup()); try { insertSingleSpecimen(derivedSpecimen, dao, sessionDataBean, true); specimenList.add(derivedSpecimen); } catch (DAOException daoException) { int j = i + 1; - String message = " (This message is for Derived Specimen " + j + " of Parent Specimen number " + parentSpecimenId + ")"; + String message = " (This message is for Derived Specimen " + j + " of Parent Specimen number " + count + ")"; daoException.setSupportingMessage(message); throw daoException; } } } //inserting authorization data Iterator itr = specimenList.iterator(); while(itr.hasNext()) { Specimen specimen = (Specimen)itr.next(); Set protectionObjects = new HashSet(); protectionObjects.add(specimen); if (specimen.getSpecimenCharacteristics() != null) { protectionObjects.add(specimen.getSpecimenCharacteristics()); } try { SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, getDynamicGroups(specimen)); } catch (SMException e) { throw handleSMException(e); } } } /** * By Rahul Ner * @param specimen */ private void resetId(Specimen specimen) { specimen.setId(null); Iterator childItr = null; if(specimen.getSpecimenEventCollection() != null) { childItr = specimen.getSpecimenEventCollection().iterator(); while (childItr.hasNext()) { SpecimenEventParameters eventParams = (SpecimenEventParameters) childItr.next(); eventParams.setSpecimen(specimen); eventParams.setId(null); } } if(specimen.getExternalIdentifierCollection() != null) { childItr = specimen.getExternalIdentifierCollection().iterator(); while (childItr.hasNext()) { ExternalIdentifier externalIdentifier = (ExternalIdentifier) childItr.next(); externalIdentifier.setSpecimen(specimen); externalIdentifier.setId(null); } } if (specimen.getBiohazardCollection() != null) { childItr = specimen.getBiohazardCollection().iterator(); while (childItr.hasNext()) { Biohazard biohazard = (Biohazard) childItr.next(); //biohazard.setId(null); } } } /** * This method gives the error message. * This method is overrided for customizing error message * @param ex - DAOException * @param obj - Object * @return - error message string */ public String getErrorMessage(DAOException daoException, Object obj, String operation) { if (obj instanceof HashMap) { obj = new Specimen(); } String supportingMessage = daoException.getSupportingMessage(); String formatedException = formatException(daoException.getWrapException(), obj, operation); if (supportingMessage != null && formatedException != null) { formatedException += supportingMessage; } if (formatedException == null) { formatedException = daoException.getMessage(); if (supportingMessage != null) formatedException += supportingMessage; } return formatedException; } /** * Insert single specimen into the data base. * @param specimen * @param dao * @param sessionDataBean * @param partOfMulipleSpecimen * @throws DAOException * @throws UserNotAuthorizedException */ private void insertSingleSpecimen(Specimen specimen, DAO dao, SessionDataBean sessionDataBean, boolean partOfMulipleSpecimen) throws DAOException, UserNotAuthorizedException { try { /** * Start: Change for API Search --- Jitendra 06/10/2006 * In Case of Api Search, previoulsy it was failing since there was default class level initialization * on domain object. For example in User object, it was initialized as protected String lastName=""; * So we removed default class level initialization on domain object and are initializing in method * setAllValues() of domain object. But in case of Api Search, default values will not get set * since setAllValues() method of domainObject will not get called. To avoid null pointer exception, * we are setting the default values same as we were setting in setAllValues() method of domainObject. */ ApiSearchUtil.setSpecimenDefault(specimen); //End:- Change for API Search Collection externalIdentifierCollection = specimen.getExternalIdentifierCollection(); if (externalIdentifierCollection != null) { if (externalIdentifierCollection.isEmpty()) //Dummy entry added for query { ExternalIdentifier exId = new ExternalIdentifier(); exId.setName(null); exId.setValue(null); exId.setSpecimen(specimen); externalIdentifierCollection.add(exId); } // Iterator it = externalIdentifierCollection.iterator(); // while (it.hasNext()) // { // ExternalIdentifier exId = (ExternalIdentifier) it.next(); // exId.setSpecimen(specimen); // dao.insert(exId, sessionDataBean, true, true); // } } else { //Dummy entry added for query. externalIdentifierCollection = new HashSet(); ExternalIdentifier exId = new ExternalIdentifier(); exId.setName(null); exId.setValue(null); exId.setSpecimen(specimen); externalIdentifierCollection.add(exId); specimen.setExternalIdentifierCollection(externalIdentifierCollection); } //Set protectionObjects = new HashSet(); specimen.setLineage(Constants.NEW_SPECIMEN); setSpecimenAttributes(dao, specimen, sessionDataBean, partOfMulipleSpecimen); dao.insert(specimen.getSpecimenCharacteristics(), sessionDataBean, true, true); dao.insert(specimen, sessionDataBean, true, true); //protectionObjects.add(specimen); /*if (specimen.getSpecimenCharacteristics() != null) { protectionObjects.add(specimen.getSpecimenCharacteristics()); }*/ //Mandar : 17-july-06 : autoevents start // Collection specimenEventsCollection = specimen.getSpecimenEventCollection(); // Iterator specimenEventsCollectionIterator = specimenEventsCollection.iterator(); // while (specimenEventsCollectionIterator.hasNext()) // { // // Object eventObject = specimenEventsCollectionIterator.next(); // // // if (eventObject instanceof CollectionEventParameters) // { // CollectionEventParameters collectionEventParameters = (CollectionEventParameters) eventObject; // collectionEventParameters.setSpecimen(specimen); // //collectionEventParameters.setId(null); // dao.insert(collectionEventParameters, sessionDataBean, true, true); // // } // else if (eventObject instanceof ReceivedEventParameters) // { // ReceivedEventParameters receivedEventParameters = (ReceivedEventParameters) eventObject; // receivedEventParameters.setSpecimen(specimen); // //receivedEventParameters.setId(null); // dao.insert(receivedEventParameters, sessionDataBean, true, true); // // } // // } //Mandar : 17-july-06 : autoevents end //Inserting data for Authorization //SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, getDynamicGroups(specimen)); } catch (SMException e) { throw handleSMException(e); } } public void postInsert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { Map containerMap = null; try { containerMap = StorageContainerUtil.getContainerMapFromCache(); } catch (Exception e) { e.printStackTrace(); } if (obj instanceof HashMap) { HashMap specimenMap = (HashMap) obj; Iterator specimenIterator = specimenMap.keySet().iterator(); while (specimenIterator.hasNext()) { Specimen specimen = (Specimen) specimenIterator.next(); updateStorageLocations((TreeMap) containerMap, specimen); List derivedSpecimens = (List) specimenMap.get(specimen); if (derivedSpecimens != null) { for (int i = 0; i < derivedSpecimens.size(); i++) { Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i); updateStorageLocations((TreeMap) containerMap, derivedSpecimen); } } } } else { updateStorageLocations((TreeMap) containerMap, (Specimen) obj); } } void updateStorageLocations(TreeMap containerMap,Specimen specimen) { try { if (specimen.getStorageContainer() != null) { StorageContainerUtil.deleteSinglePositionInContainerMap(specimen.getStorageContainer(), containerMap, specimen .getPositionDimensionOne().intValue(), specimen.getPositionDimensionTwo().intValue()); } } catch (Exception e) { } } protected String[] getDynamicGroups(AbstractDomainObject obj) throws SMException { Specimen specimen = (Specimen) obj; String[] dynamicGroups = new String[1]; dynamicGroups[0] = SecurityManager.getInstance(this.getClass()).getProtectionGroupByName(specimen.getSpecimenCollectionGroup(), Constants.getCollectionProtocolPGName(null)); Logger.out.debug("Dynamic Group name: " + dynamicGroups[0]); return dynamicGroups; } protected void chkContainerValidForSpecimen(StorageContainer container, Specimen specimen, DAO dao) throws DAOException { boolean aa = container.getHoldsSpecimenClassCollection().contains(specimen.getClassName()); boolean bb = container.getCollectionProtocolCollection().contains( specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol()); if (!container.getHoldsSpecimenClassCollection().contains(specimen.getClassName()) || (!container.getCollectionProtocolCollection().contains( specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol()) && container .getCollectionProtocolCollection().size() != 0)) { throw new DAOException("This Storage Container not valid for Specimen"); } } private SpecimenCollectionGroup loadSpecimenCollectionGroup(Long specimenID, DAO dao) throws DAOException { //get list of Participant's names String sourceObjectName = Specimen.class.getName(); String[] selectedColumn = {"specimenCollectionGroup." + Constants.SYSTEM_IDENTIFIER}; String whereColumnName[] = {Constants.SYSTEM_IDENTIFIER}; String whereColumnCondition[] = {"="}; Object whereColumnValue[] = {specimenID}; String joinCondition = Constants.AND_JOIN_CONDITION; List list = dao.retrieve(sourceObjectName, selectedColumn, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); if (!list.isEmpty()) { Long specimenCollectionGroupId = (Long) list.get(0); SpecimenCollectionGroup specimenCollectionGroup = new SpecimenCollectionGroup(); specimenCollectionGroup.setId(specimenCollectionGroupId); return specimenCollectionGroup; } return null; } private SpecimenCharacteristics loadSpecimenCharacteristics(Long specimenID, DAO dao) throws DAOException { //get list of Participant's names String sourceObjectName = Specimen.class.getName(); String[] selectedColumn = {"specimenCharacteristics." + Constants.SYSTEM_IDENTIFIER}; String whereColumnName[] = {Constants.SYSTEM_IDENTIFIER}; String whereColumnCondition[] = {"="}; Object whereColumnValue[] = {specimenID}; String joinCondition = Constants.AND_JOIN_CONDITION; List list = dao.retrieve(sourceObjectName, selectedColumn, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); if (!list.isEmpty()) { Long specimenCharacteristicsId = (Long) list.get(0); SpecimenCharacteristics specimenCharacteristics = new SpecimenCharacteristics(); specimenCharacteristics.setId(specimenCharacteristicsId); return specimenCharacteristics; //return (SpecimenCharacteristics)list.get(0); } return null; } private void setAvailableQuantity(Specimen obj, Specimen oldObj) throws DAOException { if (obj instanceof TissueSpecimen) { Logger.out.debug("In TissueSpecimen"); TissueSpecimen tissueSpecimenObj = (TissueSpecimen) obj; TissueSpecimen tissueSpecimenOldObj = (TissueSpecimen) oldObj; // get new qunatity modifed by user double newQty = Double.parseDouble(tissueSpecimenObj.getQuantity().toString());//tissueSpecimenObj.getQuantityInGram().doubleValue(); // get old qunatity from database double oldQty = Double.parseDouble(tissueSpecimenOldObj.getQuantity().toString());//tissueSpecimenOldObj.getQuantityInGram().doubleValue(); Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty); // get Available qty double oldAvailableQty = Double.parseDouble(tissueSpecimenOldObj.getAvailableQuantity().toString());//tissueSpecimenOldObj.getAvailableQuantityInGram().doubleValue(); double distQty = 0; double newAvailableQty = 0; // Distributed Qty = Old_Qty - Old_Available_Qty distQty = oldQty - oldAvailableQty; // New_Available_Qty = New_Qty - Distributed_Qty newAvailableQty = newQty - distQty; Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty); if (newAvailableQty < 0) { throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty + "'"); } else { // set new available quantity tissueSpecimenObj.setAvailableQuantity(new QuantityInGram(newAvailableQty));//tissueSpecimenObj.setAvailableQuantityInGram(new Double(newAvailableQty)); } } else if (obj instanceof MolecularSpecimen) { Logger.out.debug("In MolecularSpecimen"); MolecularSpecimen molecularSpecimenObj = (MolecularSpecimen) obj; MolecularSpecimen molecularSpecimenOldObj = (MolecularSpecimen) oldObj; // get new qunatity modifed by user double newQty = Double.parseDouble(molecularSpecimenObj.getQuantity().toString());//molecularSpecimenObj.getQuantityInMicrogram().doubleValue(); // get old qunatity from database double oldQty = Double.parseDouble(molecularSpecimenOldObj.getQuantity().toString());//molecularSpecimenOldObj.getQuantityInMicrogram().doubleValue(); Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty); // get Available qty double oldAvailableQty = Double.parseDouble(molecularSpecimenOldObj.getAvailableQuantity().toString());//molecularSpecimenOldObj.getAvailableQuantityInMicrogram().doubleValue(); double distQty = 0; double newAvailableQty = 0; // Distributed Qty = Old_Qty - Old_Available_Qty distQty = oldQty - oldAvailableQty; // New_Available_Qty = New_Qty - Distributed_Qty newAvailableQty = newQty - distQty; Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty); if (newAvailableQty < 0) { throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty + "'"); } else { // set new available quantity molecularSpecimenObj.setAvailableQuantity(new QuantityInMicrogram(newAvailableQty));//molecularSpecimenObj.setAvailableQuantityInMicrogram(new Double(newAvailableQty)); } } else if (obj instanceof CellSpecimen) { Logger.out.debug("In CellSpecimen"); CellSpecimen cellSpecimenObj = (CellSpecimen) obj; CellSpecimen cellSpecimenOldObj = (CellSpecimen) oldObj; // get new qunatity modifed by user int newQty = (int) Double.parseDouble(cellSpecimenObj.getQuantity().toString());//cellSpecimenObj.getQuantityInCellCount().intValue(); // get old qunatity from database int oldQty = (int) Double.parseDouble(cellSpecimenOldObj.getQuantity().toString());//cellSpecimenOldObj.getQuantityInCellCount().intValue(); Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty); // get Available qty int oldAvailableQty = (int) Double.parseDouble(cellSpecimenOldObj.getAvailableQuantity().toString());//cellSpecimenOldObj.getAvailableQuantityInCellCount().intValue(); int distQty = 0; int newAvailableQty = 0; // Distributed Qty = Old_Qty - Old_Available_Qty distQty = oldQty - oldAvailableQty; // New_Available_Qty = New_Qty - Distributed_Qty newAvailableQty = newQty - distQty; Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty); if (newAvailableQty < 0) { throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty + "'"); } else { // set new available quantity cellSpecimenObj.setAvailableQuantity(new QuantityInCount(newAvailableQty));//cellSpecimenObj.setAvailableQuantityInCellCount(new Integer(newAvailableQty)); } } else if (obj instanceof FluidSpecimen) { Logger.out.debug("In FluidSpecimen"); FluidSpecimen fluidSpecimenObj = (FluidSpecimen) obj; FluidSpecimen fluidSpecimenOldObj = (FluidSpecimen) oldObj; // get new qunatity modifed by user double newQty = Double.parseDouble(fluidSpecimenObj.getQuantity().toString());//fluidSpecimenObj.getQuantityInMilliliter().doubleValue(); // get old qunatity from database double oldQty = Double.parseDouble(fluidSpecimenOldObj.getQuantity().toString());//fluidSpecimenOldObj.getQuantityInMilliliter().doubleValue(); Logger.out.debug("New Qty: " + newQty + " Old Qty: " + oldQty); // get Available qty double oldAvailableQty = Double.parseDouble(fluidSpecimenOldObj.getAvailableQuantity().toString());//fluidSpecimenOldObj.getAvailableQuantityInMilliliter().doubleValue(); double distQty = 0; double newAvailableQty = 0; // Distributed Qty = Old_Qty - Old_Available_Qty distQty = oldQty - oldAvailableQty; // New_Available_Qty = New_Qty - Distributed_Qty newAvailableQty = newQty - distQty; Logger.out.debug("Dist Qty: " + distQty + " New Available Qty: " + newAvailableQty); if (newAvailableQty < 0) { throw new DAOException("Newly modified Quantity '" + newQty + "' should not be less than current Distributed Quantity '" + distQty + "'"); } else { fluidSpecimenObj.setAvailableQuantity(new QuantityInMilliliter(newAvailableQty));//fluidSpecimenObj.setAvailableQuantityInMilliliter(new Double(newAvailableQty)); } } } /** * Updates the persistent object in the database. * @param obj The object to be updated. * @param session The session in which the object is saved. * @throws DAOException * @throws HibernateException Exception thrown during hibernate operations. */ public void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException { Specimen specimen = (Specimen) obj; Specimen specimenOld = (Specimen) oldObj; /** * Start: Change for API Search --- Jitendra 06/10/2006 * In Case of Api Search, previoulsy it was failing since there was default class level initialization * on domain object. For example in User object, it was initialized as protected String lastName=""; * So we removed default class level initialization on domain object and are initializing in method * setAllValues() of domain object. But in case of Api Search, default values will not get set * since setAllValues() method of domainObject will not get called. To avoid null pointer exception, * we are setting the default values same as we were setting in setAllValues() method of domainObject. */ ApiSearchUtil.setSpecimenDefault(specimen); //Added for api Search if (isStoragePositionChanged(specimenOld, specimen)) { throw new DAOException("Storage Position should not be changed while updating the specimen"); } if (!specimenOld.getLineage().equals(specimen.getLineage())) { throw new DAOException("Lineage should not be changed while updating the specimen"); } if (!specimenOld.getClassName().equals(specimen.getClassName())) { throw new DAOException("Class should not be changed while updating the specimen"); } // if(specimenOld.getAvailableQuantity().getValue().longValue() != specimen.getAvailableQuantity().getValue().longValue()) // { // throw new DAOException("Available Quantity should not be changed while updating the specimen"); // } //End:- Change for API Search setAvailableQuantity(specimen, specimenOld); if (specimen.isParentChanged()) { //Check whether continer is moved to one of its sub container. if (isUnderSubSpecimen(specimen, specimen.getParentSpecimen().getId())) { throw new DAOException(ApplicationProperties.getValue("errors.specimen.under.subspecimen")); } Logger.out.debug("Loading ParentSpecimen: " + specimen.getParentSpecimen().getId()); // check for closed ParentSpecimen checkStatus(dao, specimen.getParentSpecimen(), "Parent Specimen"); SpecimenCollectionGroup scg = loadSpecimenCollectionGroup(specimen.getParentSpecimen().getId(), dao); specimen.setSpecimenCollectionGroup(scg); SpecimenCharacteristics sc = loadSpecimenCharacteristics(specimen.getParentSpecimen().getId(), dao); if (!Constants.ALIQUOT.equals(specimen.getLineage()))//specimen instanceof OriginalSpecimen) { specimen.setSpecimenCharacteristics(sc); } } //check for closed Specimen Collection Group if (!specimen.getSpecimenCollectionGroup().getId().equals(specimenOld.getSpecimenCollectionGroup().getId())) checkStatus(dao, specimen.getSpecimenCollectionGroup(), "Specimen Collection Group"); setSpecimenGroupForSubSpecimen(specimen, specimen.getSpecimenCollectionGroup(), specimen.getSpecimenCharacteristics()); if (!Constants.ALIQUOT.equals(specimen.getLineage()))//specimen instanceof OriginalSpecimen) { dao.update(specimen.getSpecimenCharacteristics(), sessionDataBean, true, true, false); } dao.update(specimen, sessionDataBean, true, false, false);//dao.update(specimen, sessionDataBean, true, true, false); //Audit of Specimen. dao.audit(obj, oldObj, sessionDataBean, true); //Audit of Specimen Characteristics. dao.audit(specimen.getSpecimenCharacteristics(), specimenOld.getSpecimenCharacteristics(), sessionDataBean, true); Collection oldExternalIdentifierCollection = specimenOld.getExternalIdentifierCollection(); Collection externalIdentifierCollection = specimen.getExternalIdentifierCollection(); if (externalIdentifierCollection != null) { Iterator it = externalIdentifierCollection.iterator(); while (it.hasNext()) { ExternalIdentifier exId = (ExternalIdentifier) it.next(); exId.setSpecimen(specimen); dao.update(exId, sessionDataBean, true, true, false); ExternalIdentifier oldExId = (ExternalIdentifier) getCorrespondingOldObject(oldExternalIdentifierCollection, exId.getId()); dao.audit(exId, oldExId, sessionDataBean, true); } } //Disable functionality Logger.out.debug("specimen.getActivityStatus() " + specimen.getActivityStatus()); if (specimen.getActivityStatus().equals(Constants.ACTIVITY_STATUS_DISABLED)) { // check for disabling a specimen boolean disposalEventPresent = false; Collection eventCollection = specimen.getSpecimenEventCollection(); Iterator itr = eventCollection.iterator(); while (itr.hasNext()) { Object eventObject = itr.next(); if (eventObject instanceof DisposalEventParameters) { disposalEventPresent = true; break; } } if (!disposalEventPresent) { throw new DAOException(ApplicationProperties.getValue("errors.specimen.not.disabled.no.disposalevent")); } setDisableToSubSpecimen(specimen); Logger.out.debug("specimen.getActivityStatus() " + specimen.getActivityStatus()); Long specimenIDArr[] = new Long[1]; specimenIDArr[0] = specimen.getId(); disableSubSpecimens(dao, specimenIDArr); } } private boolean isUnderSubSpecimen(Specimen specimen, Long parentSpecimenID) { if (specimen != null) { Iterator iterator = specimen.getChildrenSpecimen().iterator(); while (iterator.hasNext()) { Specimen childSpecimen = (Specimen) iterator.next(); //Logger.out.debug("SUB CONTINER container "+parentContainerID.longValue()+" "+container.getId().longValue()+" "+(parentContainerID.longValue()==container.getId().longValue())); if (parentSpecimenID.longValue() == childSpecimen.getId().longValue()) return true; if (isUnderSubSpecimen(childSpecimen, parentSpecimenID)) return true; } } return false; } private void setSpecimenGroupForSubSpecimen(Specimen specimen, SpecimenCollectionGroup specimenCollectionGroup, SpecimenCharacteristics specimenCharacteristics) { if (specimen != null) { Logger.out.debug("specimen() " + specimen.getId()); Logger.out.debug("specimen.getChildrenContainerCollection() " + specimen.getChildrenSpecimen().size()); Iterator iterator = specimen.getChildrenSpecimen().iterator(); while (iterator.hasNext()) { Specimen childSpecimen = (Specimen) iterator.next(); childSpecimen.setSpecimenCollectionGroup(specimenCollectionGroup); //((OriginalSpecimen)childSpecimen).setSpecimenCharacteristics(specimenCharacteristics); setSpecimenGroupForSubSpecimen(childSpecimen, specimenCollectionGroup, specimenCharacteristics); } } } // TODO TO BE REMOVED private void setDisableToSubSpecimen(Specimen specimen) { if (specimen != null) { Iterator iterator = specimen.getChildrenSpecimen().iterator(); while (iterator.hasNext()) { Specimen childSpecimen = (Specimen) iterator.next(); childSpecimen.setActivityStatus(Constants.ACTIVITY_STATUS_DISABLED); setDisableToSubSpecimen(childSpecimen); } } } private void setSpecimenAttributes(DAO dao, Specimen specimen, SessionDataBean sessionDataBean, boolean partOfMultipleSpecimen) throws DAOException, SMException { specimen.setActivityStatus(Constants.ACTIVITY_STATUS_ACTIVE); // set barcode to null in case it is blank if (specimen.getBarcode() != null && specimen.getBarcode().trim().equals("")) { specimen.setBarcode(null); } // TODO //Load & set Specimen Collection Group if present if (specimen.getSpecimenCollectionGroup() != null) { SpecimenCollectionGroup specimenCollectionGroupObj = null; if (partOfMultipleSpecimen) { /*String sourceObjectName = SpecimenCollectionGroup.class.getName(); String[] selectColumnName = {"id"}; String[] whereColumnName = {"name"}; String[] whereColumnCondition = {"="}; Object[] whereColumnValue = {specimen.getSpecimenCollectionGroup().getName()}; String joinCondition = null; List list = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); specimenCollectionGroupObj = new SpecimenCollectionGroup(); specimenCollectionGroupObj.setId((Long)list.get(0));*/ List spgList = dao.retrieve(SpecimenCollectionGroup.class.getName(), Constants.NAME, specimen.getSpecimenCollectionGroup().getName()); specimenCollectionGroupObj = (SpecimenCollectionGroup)spgList.get(0); } else { specimenCollectionGroupObj = new SpecimenCollectionGroup(); specimenCollectionGroupObj.setId(specimen.getSpecimenCollectionGroup().getId()); } if (specimenCollectionGroupObj != null) { /*if (specimenCollectionGroupObj.getActivityStatus().equals(Constants.ACTIVITY_STATUS_CLOSED)) { throw new DAOException("Specimen Collection Group " + ApplicationProperties.getValue("error.object.closed")); }*/ checkStatus(dao, specimenCollectionGroupObj,"Specimen Collection Group" ); specimen.setSpecimenCollectionGroup(specimenCollectionGroupObj); } } //Load & set Parent Specimen if present if (specimen.getParentSpecimen() != null) { // Object parentSpecimenObj = dao.retrieve(Specimen.class.getName(), specimen.getParentSpecimen().getId()); // if (parentSpecimenObj != null) // { Specimen parentSpecimen = new Specimen(); parentSpecimen.setId(specimen.getParentSpecimen().getId()); // check for closed Parent Specimen checkStatus(dao, parentSpecimen, "Parent Specimen"); specimen.setLineage(Constants.DERIVED_SPECIMEN); // set parent specimen event parameters -- added by Ashwin for bug id# 2476 specimen.setSpecimenEventCollection(populateDeriveSpecimenEventCollection(specimen.getParentSpecimen(),specimen)); // } } //Load & set Storage Container if (specimen.getStorageContainer() != null) { if (specimen.getStorageContainer().getId() != null) { // Object containerObj = dao.retrieve(StorageContainer.class.getName(), specimen.getStorageContainer().getId()); // if (containerObj != null) // { // StorageContainer container = (StorageContainer) containerObj; StorageContainer storageContainerObj = new StorageContainer(); storageContainerObj.setId(specimen.getStorageContainer().getId()); String sourceObjectName = StorageContainer.class.getName(); String[] selectColumnName = {"name"}; String[] whereColumnName = {"id"}; //"storageContainer."+Constants.SYSTEM_IDENTIFIER String[] whereColumnCondition = {"="}; Object[] whereColumnValue = {specimen.getStorageContainer().getId()}; String joinCondition = null; List list = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); if (!list.isEmpty()) { storageContainerObj.setName((String) list.get(0)); } // check for closed Storage Container checkStatus(dao, storageContainerObj, "Storage Container"); StorageContainerBizLogic storageContainerBizLogic = (StorageContainerBizLogic) BizLogicFactory.getInstance().getBizLogic( Constants.STORAGE_CONTAINER_FORM_ID); // --- check for all validations on the storage container. storageContainerBizLogic.checkContainer(dao, storageContainerObj.getId().toString(), specimen.getPositionDimensionOne().toString(), specimen.getPositionDimensionTwo().toString(), sessionDataBean,partOfMultipleSpecimen); - //chkContainerValidForSpecimen(container, specimen,dao); + // chkContainerValidForSpecimen(specimen.getStorageContainer(), specimen,dao); specimen.setStorageContainer(storageContainerObj); // } // else // { // throw new DAOException(ApplicationProperties.getValue("errors.storageContainerExist")); // } } } //Setting the Biohazard Collection Set set = new HashSet(); Collection biohazardCollection = specimen.getBiohazardCollection(); if (biohazardCollection != null) { Iterator it = biohazardCollection.iterator(); while (it.hasNext()) { Biohazard hazard = (Biohazard) it.next(); Logger.out.debug("hazard.getId() " + hazard.getId()); Object bioObj = dao.retrieve(Biohazard.class.getName(), hazard.getId()); if (bioObj != null) { Biohazard hazardObj = (Biohazard) bioObj; set.add(hazardObj); } } } specimen.setBiohazardCollection(set); } public void disableRelatedObjectsForSpecimenCollectionGroup(DAO dao, Long specimenCollectionGroupArr[]) throws DAOException { Logger.out.debug("disableRelatedObjects NewSpecimenBizLogic"); List listOfSpecimenId = super.disableObjects(dao, Specimen.class, "specimenCollectionGroup", "CATISSUE_SPECIMEN", "SPECIMEN_COLLECTION_GROUP_ID", specimenCollectionGroupArr); if (!listOfSpecimenId.isEmpty()) { disableSubSpecimens(dao, Utility.toLongArray(listOfSpecimenId)); } } // public void disableRelatedObjectsForStorageContainer(DAO dao, Long storageContainerIdArr[])throws DAOException // { // Logger.out.debug("disableRelatedObjectsForStorageContainer NewSpecimenBizLogic"); // List listOfSpecimenId = super.disableObjects(dao, Specimen.class, "storageContainer", // "CATISSUE_SPECIMEN", "STORAGE_CONTAINER_IDENTIFIER", storageContainerIdArr); // if(!listOfSpecimenId.isEmpty()) // { // disableSubSpecimens(dao,Utility.toLongArray(listOfSpecimenId)); // } // } private void disableSubSpecimens(DAO dao, Long speIDArr[]) throws DAOException { List listOfSubElement = super.disableObjects(dao, Specimen.class, "parentSpecimen", "CATISSUE_SPECIMEN", "PARENT_SPECIMEN_ID", speIDArr); if (listOfSubElement.isEmpty()) return; disableSubSpecimens(dao, Utility.toLongArray(listOfSubElement)); } /** * @param dao * @param privilegeName * @param longs * @param userId * @throws DAOException * @throws SMException */ public void assignPrivilegeToRelatedObjectsForSCG(DAO dao, String privilegeName, Long[] specimenCollectionGroupArr, Long userId, String roleId, boolean assignToUser, boolean assignOperation) throws SMException, DAOException { Logger.out.debug("assignPrivilegeToRelatedObjectsForSCG NewSpecimenBizLogic"); List listOfSpecimenId = super.getRelatedObjects(dao, Specimen.class, "specimenCollectionGroup", specimenCollectionGroupArr); if (!listOfSpecimenId.isEmpty()) { super.setPrivilege(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSpecimenId), userId, roleId, assignToUser, assignOperation); List specimenCharacteristicsIds = super.getRelatedObjects(dao, Specimen.class, new String[]{"specimenCharacteristics." + Constants.SYSTEM_IDENTIFIER}, new String[]{Constants.SYSTEM_IDENTIFIER}, Utility.toLongArray(listOfSpecimenId)); super.setPrivilege(dao, privilegeName, Address.class, Utility.toLongArray(specimenCharacteristicsIds), userId, roleId, assignToUser, assignOperation); assignPrivilegeToSubSpecimens(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSpecimenId), userId, roleId, assignToUser, assignOperation); } } /** * @param dao * @param privilegeName * @param class1 * @param longs * @param userId * @throws DAOException * @throws SMException */ private void assignPrivilegeToSubSpecimens(DAO dao, String privilegeName, Class class1, Long[] speIDArr, Long userId, String roleId, boolean assignToUser, boolean assignOperation) throws SMException, DAOException { List listOfSubElement = super.getRelatedObjects(dao, Specimen.class, "parentSpecimen", speIDArr); if (listOfSubElement.isEmpty()) return; super.setPrivilege(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSubElement), userId, roleId, assignToUser, assignOperation); List specimenCharacteristicsIds = super.getRelatedObjects(dao, Specimen.class, new String[]{"specimenCharacteristics." + Constants.SYSTEM_IDENTIFIER}, new String[]{Constants.SYSTEM_IDENTIFIER}, Utility.toLongArray(listOfSubElement)); super.setPrivilege(dao, privilegeName, Address.class, Utility.toLongArray(specimenCharacteristicsIds), userId, roleId, assignToUser, assignOperation); assignPrivilegeToSubSpecimens(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSubElement), userId, roleId, assignToUser, assignOperation); } public void setPrivilege(DAO dao, String privilegeName, Class objectType, Long[] objectIds, Long userId, String roleId, boolean assignToUser, boolean assignOperation) throws SMException, DAOException { super.setPrivilege(dao, privilegeName, objectType, objectIds, userId, roleId, assignToUser, assignOperation); List specimenCharacteristicsIds = super.getRelatedObjects(dao, Specimen.class, new String[]{"specimenCharacteristics." + Constants.SYSTEM_IDENTIFIER}, new String[]{Constants.SYSTEM_IDENTIFIER}, objectIds); super.setPrivilege(dao, privilegeName, Address.class, Utility.toLongArray(specimenCharacteristicsIds), userId, roleId, assignToUser, assignOperation); assignPrivilegeToSubSpecimens(dao, privilegeName, Specimen.class, objectIds, userId, roleId, assignToUser, assignOperation); } // validation code here /** * @see edu.wustl.common.bizlogic.IBizLogic#setPrivilege(DAO, String, Class, Long[], Long, String, boolean) * @param dao * @param privilegeName * @param objectIds * @param userId * @param roleId * @param assignToUser * @throws SMException * @throws DAOException */ public void assignPrivilegeToRelatedObjectsForDistributedItem(DAO dao, String privilegeName, Long[] objectIds, Long userId, String roleId, boolean assignToUser, boolean assignOperation) throws SMException, DAOException { String[] selectColumnNames = {"specimen.id"}; String[] whereColumnNames = {"id"}; List listOfSubElement = super.getRelatedObjects(dao, DistributedItem.class, selectColumnNames, whereColumnNames, objectIds); if (!listOfSubElement.isEmpty()) { super.setPrivilege(dao, privilegeName, Specimen.class, Utility.toLongArray(listOfSubElement), userId, roleId, assignToUser, assignOperation); } } /** * Overriding the parent class's method to validate the enumerated attribute values */ protected boolean validate(Object obj, DAO dao, String operation) throws DAOException { boolean result; if (obj instanceof Map) { //validation on multiple specimens are performed in MultipleSpecimenValidationUtil, so dont require to perform the bizlogic validations. return true; //result = validateMultipleSpecimen((Map) obj, dao, operation); } else { result = validateSingleSpecimen((Specimen) obj, dao, operation, false); } return result; } /** * validates single specimen. */ private boolean validateSingleSpecimen(Specimen specimen, DAO dao, String operation, boolean partOfMulipleSpecimen) throws DAOException { //Added by Ashish //Logger.out.debug("Start-Inside validate method of specimen bizlogic"); if (specimen == null) { throw new DAOException(ApplicationProperties.getValue("domain.object.null.err.msg", "Specimen")); } Validator validator = new Validator(); if (specimen.getSpecimenCollectionGroup() == null || specimen.getSpecimenCollectionGroup().getId() == null || specimen.getSpecimenCollectionGroup().getId().equals("-1")) { String message = ApplicationProperties.getValue("specimen.specimenCollectionGroup"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (specimen.getParentSpecimen() != null && (specimen.getParentSpecimen().getId() == null || validator.isEmpty(specimen.getParentSpecimen().getId().toString()))) { String message = ApplicationProperties.getValue("createSpecimen.parent"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (validator.isEmpty(specimen.getLabel())) { String message = ApplicationProperties.getValue("specimen.label"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (validator.isEmpty(specimen.getClassName())) { String message = ApplicationProperties.getValue("specimen.type"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (validator.isEmpty(specimen.getType())) { String message = ApplicationProperties.getValue("specimen.subType"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (specimen.getStorageContainer() != null && (specimen.getStorageContainer().getId() == null && specimen.getStorageContainer().getName() == null)) { String message = ApplicationProperties.getValue("specimen.storageContainer"); throw new DAOException(ApplicationProperties.getValue("errors.invalid", message)); } if (specimen.getStorageContainer() != null && specimen.getStorageContainer().getName() != null) { StorageContainer storageContainerObj = specimen.getStorageContainer(); String sourceObjectName = StorageContainer.class.getName(); String[] selectColumnName = {"id"}; String[] whereColumnName = {"name"}; String[] whereColumnCondition = {"="}; Object[] whereColumnValue = {specimen.getStorageContainer().getName()}; String joinCondition = null; List list = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition); if (!list.isEmpty()) { storageContainerObj.setId((Long) list.get(0)); specimen.setStorageContainer(storageContainerObj); } else { String message = ApplicationProperties.getValue("specimen.storageContainer"); throw new DAOException(ApplicationProperties.getValue("errors.invalid", message)); } } if (specimen.getSpecimenEventCollection() != null) { Iterator specimenEventCollectionIterator = specimen.getSpecimenEventCollection().iterator(); while (specimenEventCollectionIterator.hasNext()) { //CollectionEvent validation. Object eventObject = specimenEventCollectionIterator.next(); if (eventObject instanceof CollectionEventParameters) { CollectionEventParameters collectionEventParameters = (CollectionEventParameters) eventObject; collectionEventParameters.getUser(); if (collectionEventParameters.getUser() == null || collectionEventParameters.getUser().getId() == null) { String message = ApplicationProperties.getValue("specimen.collection.event.user"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (!validator.checkDate(Utility.parseDateToString(collectionEventParameters.getTimestamp(), Constants.DATE_PATTERN_MM_DD_YYYY))) { String message = ApplicationProperties.getValue("specimen.collection.event.date"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } // checks the collectionProcedure if (!validator.isValidOption(collectionEventParameters.getCollectionProcedure())) { String message = ApplicationProperties.getValue("collectioneventparameters.collectionprocedure"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } List procedureList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COLLECTION_PROCEDURE, null); if (!Validator.isEnumeratedValue(procedureList, collectionEventParameters.getCollectionProcedure())) { throw new DAOException(ApplicationProperties.getValue("events.collectionProcedure.errMsg")); } if (!validator.isValidOption(collectionEventParameters.getContainer())) { String message = ApplicationProperties.getValue("collectioneventparameters.container"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } List containerList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CONTAINER, null); if (!Validator.isEnumeratedValue(containerList, collectionEventParameters.getContainer())) { throw new DAOException(ApplicationProperties.getValue("events.container.errMsg")); } } //ReceivedEvent validation else if (eventObject instanceof ReceivedEventParameters) { ReceivedEventParameters receivedEventParameters = (ReceivedEventParameters) eventObject; if (receivedEventParameters.getUser() == null || receivedEventParameters.getUser().getId() == null) { String message = ApplicationProperties.getValue("specimen.recieved.event.user"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (!validator.checkDate(Utility.parseDateToString(receivedEventParameters.getTimestamp(), Constants.DATE_PATTERN_MM_DD_YYYY))) { String message = ApplicationProperties.getValue("specimen.recieved.event.date"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } // checks the collectionProcedure if (!validator.isValidOption(receivedEventParameters.getReceivedQuality())) { String message = ApplicationProperties.getValue("collectioneventparameters.receivedquality"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } List qualityList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_RECEIVED_QUALITY, null); if (!Validator.isEnumeratedValue(qualityList, receivedEventParameters.getReceivedQuality())) { throw new DAOException(ApplicationProperties.getValue("events.receivedQuality.errMsg")); } } } } //Validations for Biohazard Add-More Block Collection bioHazardCollection = specimen.getBiohazardCollection(); Biohazard biohazard = null; if (bioHazardCollection != null && !bioHazardCollection.isEmpty()) { Iterator itr = bioHazardCollection.iterator(); while (itr.hasNext()) { biohazard = (Biohazard) itr.next(); if (!validator.isValidOption(biohazard.getType())) { String message = ApplicationProperties.getValue("newSpecimen.msg"); throw new DAOException(ApplicationProperties.getValue("errors.newSpecimen.biohazard.missing", message)); } if (biohazard.getId() == null) { String message = ApplicationProperties.getValue("newSpecimen.msg"); throw new DAOException(ApplicationProperties.getValue("errors.newSpecimen.biohazard.missing", message)); } } } //validations for external identifiers Collection extIdentifierCollection = specimen.getExternalIdentifierCollection(); ExternalIdentifier extIdentifier = null; if (extIdentifierCollection != null && !extIdentifierCollection.isEmpty()) { Iterator itr = extIdentifierCollection.iterator(); while (itr.hasNext()) { extIdentifier = (ExternalIdentifier) itr.next(); if (validator.isEmpty(extIdentifier.getName())) { String message = ApplicationProperties.getValue("specimen.msg"); throw new DAOException(ApplicationProperties.getValue("errors.specimen.externalIdentifier.missing", message)); } if (validator.isEmpty(extIdentifier.getValue())) { String message = ApplicationProperties.getValue("specimen.msg"); throw new DAOException(ApplicationProperties.getValue("errors.specimen.externalIdentifier.missing", message)); } } } //End Ashish if (Constants.ALIQUOT.equals(specimen.getLineage())) { //return true; } validateFields(specimen, dao, operation, partOfMulipleSpecimen); List specimenClassList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_SPECIMEN_CLASS, null); String specimenClass = Utility.getSpecimenClassName(specimen); if (!Validator.isEnumeratedValue(specimenClassList, specimenClass)) { throw new DAOException(ApplicationProperties.getValue("protocol.class.errMsg")); } if (!Validator.isEnumeratedValue(Utility.getSpecimenTypes(specimenClass), specimen.getType())) { throw new DAOException(ApplicationProperties.getValue("protocol.type.errMsg")); } SpecimenCharacteristics characters = specimen.getSpecimenCharacteristics(); if (characters == null) { throw new DAOException(ApplicationProperties.getValue("specimen.characteristics.errMsg")); } else { if (specimen.getSpecimenCollectionGroup() != null) { // NameValueBean undefinedVal = new NameValueBean(Constants.UNDEFINED,Constants.UNDEFINED); List tissueSiteList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_TISSUE_SITE, null); if (!Validator.isEnumeratedValue(tissueSiteList, characters.getTissueSite())) { throw new DAOException(ApplicationProperties.getValue("protocol.tissueSite.errMsg")); } // NameValueBean unknownVal = new NameValueBean(Constants.UNKNOWN,Constants.UNKNOWN); List tissueSideList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_TISSUE_SIDE, null); if (!Validator.isEnumeratedValue(tissueSideList, characters.getTissueSide())) { throw new DAOException(ApplicationProperties.getValue("specimen.tissueSide.errMsg")); } List pathologicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_PATHOLOGICAL_STATUS, null); if (!Validator.isEnumeratedValue(pathologicalStatusList, specimen.getPathologicalStatus())) { throw new DAOException(ApplicationProperties.getValue("protocol.pathologyStatus.errMsg")); } } } if (operation.equals(Constants.ADD)) { if (!specimen.getAvailable().booleanValue()) { throw new DAOException(ApplicationProperties.getValue("specimen.available.errMsg")); } if (!Constants.ACTIVITY_STATUS_ACTIVE.equals(specimen.getActivityStatus())) { throw new DAOException(ApplicationProperties.getValue("activityStatus.active.errMsg")); } } else { if (!Validator.isEnumeratedValue(Constants.ACTIVITY_STATUS_VALUES, specimen.getActivityStatus())) { throw new DAOException(ApplicationProperties.getValue("activityStatus.errMsg")); } } //Logger.out.debug("End-Inside validate method of specimen bizlogic"); return true; } private void validateFields(Specimen specimen, DAO dao, String operation, boolean partOfMulipleSpecimen) throws DAOException { Validator validator = new Validator(); if (partOfMulipleSpecimen) { if (specimen.getSpecimenCollectionGroup() == null || validator.isEmpty(specimen.getSpecimenCollectionGroup().getName())) { String quantityString = ApplicationProperties.getValue("specimen.specimenCollectionGroup"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", quantityString)); } List spgList = dao.retrieve(SpecimenCollectionGroup.class.getName(), Constants.NAME, specimen.getSpecimenCollectionGroup().getName()); if (spgList.size() == 0) { throw new DAOException(ApplicationProperties.getValue("errors.item.unknown", "Specimen Collection Group " + specimen.getSpecimenCollectionGroup().getName())); } } if (validator.isEmpty(specimen.getLabel())) { String labelString = ApplicationProperties.getValue("specimen.label"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", labelString)); } if (specimen.getQuantity() == null || specimen.getQuantity().getValue() == null) { String quantityString = ApplicationProperties.getValue("specimen.quantity"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", quantityString)); } /** * If specimen is virtually located, then in that case storage container is being set null explicitly in Specimen * domain object.Hence to avoid NullPointerException here check null of container is required. * @author jitendra_agrawal */ if (specimen.getStorageContainer() != null) { //Long storageContainerId = specimen.getStorageContainer().getId(); Integer xPos = specimen.getPositionDimensionOne(); Integer yPos = specimen.getPositionDimensionTwo(); if (xPos == null || yPos == null || xPos.intValue() < 0 || yPos.intValue() < 0) { throw new DAOException(ApplicationProperties.getValue("errors.item.format", ApplicationProperties .getValue("specimen.positionInStorageContainer"))); } } } /** * validates multiple specimen. Internally it for each specimen it innvokes validateSingleSpecimen. * @throws DAOException * @throws DAOException private boolean validateMultipleSpecimen(Map specimenMap, DAO dao, String operation) throws DAOException { populateStorageLocations(dao, specimenMap); Iterator specimenIterator = specimenMap.keySet().iterator(); boolean result = true; while (specimenIterator.hasNext() && result == true) { Specimen specimen = (Specimen) specimenIterator.next(); //validate single specimen */ /* if (specimenCollectionGroup != null) { if (specimenCollectionGroup.getActivityStatus().equals(Constants.ACTIVITY_STATUS_CLOSED)) { throw new DAOException("Specimen Collection Group " + ApplicationProperties.getValue("error.object.closed")); } specimen.setSpecimenCollectionGroup(specimenCollectionGroup); } List spgList = dao.retrieve(SpecimenCollectionGroup.class.getName(), Constants.NAME, specimen.getSpecimenCollectionGroup().getName()); if(spgList!=null && !spgList.isEmpty()) { specimenCollectionGroup = (SpecimenCollectionGroup) spgList.get(0); } else if(specimen.getParentSpecimen()!=null) { List spList = dao.retrieve(Specimen.class.getName(), Constants.SYSTEM_LABEL, specimen.getParentSpecimen().getLabel()); if (spList != null && !spList.isEmpty()) { Specimen sp = (Specimen) spList.get(0); specimenCollectionGroup = sp.getSpecimenCollectionGroup(); } } */ /* // TODO uncomment code for label, performance try { result = validateSingleSpecimen(specimen, dao, operation, true); } catch (DAOException daoException) { String message = daoException.getMessage(); message += " (This message is for Specimen number " + specimen.getId() + ")"; daoException.setMessage(message); throw daoException; } List derivedSpecimens = (List) specimenMap.get(specimen); if (derivedSpecimens == null) { continue; } //validate derived specimens for (int i = 0; i < derivedSpecimens.size(); i++) { Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i); derivedSpecimen.setSpecimenCharacteristics(specimen.getSpecimenCharacteristics()); derivedSpecimen.setSpecimenCollectionGroup(specimen.getSpecimenCollectionGroup()); derivedSpecimen.setPathologicalStatus(specimen.getPathologicalStatus()); try { result = validateSingleSpecimen(derivedSpecimen, dao, operation, false); } catch (DAOException daoException) { int j = i + 1; String message = daoException.getMessage(); message += " (This message is for Derived Specimen " + j + " of Parent Specimen number " + specimen.getId() + ")"; daoException.setMessage(message); throw daoException; } if (!result) { break; } } } return result; } */ /** * * Start --> Code added for auto populating storage locations in case of multiple specimen */ /** * This method populates SCG Id and storage locations for Multiple Specimen * @param dao * @param specimenMap * @throws DAOException private void populateStorageLocations(DAO dao, Map specimenMap) throws DAOException { final String saperator = "$"; Map tempSpecimenMap = new HashMap(); Iterator specimenIterator = specimenMap.keySet().iterator(); while (specimenIterator.hasNext()) { Specimen specimen = (Specimen) specimenIterator.next(); //validate single specimen if (specimen.getSpecimenCollectionGroup() != null) { String[] selectColumnName = {"collectionProtocolRegistration.id"}; String[] whereColumnName = {Constants.NAME}; String[] whereColumnCondition = {"="}; String[] whereColumnValue = {specimen.getSpecimenCollectionGroup().getName()}; List spCollGroupList = dao.retrieve(SpecimenCollectionGroup.class.getName(), selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, null); // TODO saperate calls for SCG - ID and cpid // SCG - ID will be needed before populateStorageLocations // TODO test if (!spCollGroupList.isEmpty()) { //Object idList[] = (Object[]) spCollGroupList.get(0); // Move up + here long cpId = ((Long) spCollGroupList.get(0)).longValue(); //Long scgId = (Long) idList[0]; // Move up //long cpId = ((Long) idList[0]).longValue();//here //specimen.getSpecimenCollectionGroup().setId(scgId); // Move up List tempListOfSpecimen = (ArrayList) tempSpecimenMap.get(cpId + saperator + specimen.getClassName()); if (tempListOfSpecimen == null) { tempListOfSpecimen = new ArrayList(); } int i = 0; for (; i < tempListOfSpecimen.size(); i++) { Specimen sp = (Specimen) tempListOfSpecimen.get(i); if ((sp.getId() != null) && (specimen.getId().longValue() < sp.getId().longValue())) break; } tempListOfSpecimen.add(i, specimen); tempSpecimenMap.put(cpId + saperator + specimen.getClassName(), tempListOfSpecimen); List listOfDerivedSpecimen = (ArrayList) specimenMap.get(specimen); // TODO if (listOfDerivedSpecimen != null) { for (int j = 0; j < listOfDerivedSpecimen.size(); j++) { Specimen tempDerivedSpecimen = (Specimen) listOfDerivedSpecimen.get(j); String derivedKey = cpId + saperator + tempDerivedSpecimen.getClassName(); List listOfSpecimen = (ArrayList) tempSpecimenMap.get(derivedKey); if (listOfSpecimen == null) { listOfSpecimen = new ArrayList(); } listOfSpecimen.add(tempDerivedSpecimen); tempSpecimenMap.put(derivedKey, listOfSpecimen); } } } } } Iterator keyIterator = tempSpecimenMap.keySet().iterator(); while (keyIterator.hasNext()) { String key = (String) keyIterator.next(); StorageContainerBizLogic scbizLogic = (StorageContainerBizLogic) BizLogicFactory.getInstance().getBizLogic( Constants.STORAGE_CONTAINER_FORM_ID); String split[] = key.split("[$]"); // TODO when moved to acion pass true TreeMap containerMap = scbizLogic.getAllocatedContaienrMapForSpecimen((Long.parseLong(split[0])), split[1], 0, "", false); List listOfSpecimens = (ArrayList) tempSpecimenMap.get(key); allocatePositionToSpecimensList(specimenMap, listOfSpecimens, containerMap); } } */ /** * This function gets the default positions for list of specimens * @param specimenMap * @param listOfSpecimens * @param containerMap private void allocatePositionToSpecimensList(Map specimenMap, List listOfSpecimens, Map containerMap) { List newListOfSpecimen = new ArrayList(); */ /* for (int i = 0; i < listOfSpecimens.size(); i++) { Specimen tempSpecimen = (Specimen) listOfSpecimens.get(i); newListOfSpecimen.add(tempSpecimen); List listOfDerivedSpecimen = (ArrayList) specimenMap.get(tempSpecimen); // TODO if (listOfDerivedSpecimen != null) { for (int j = 0; j < listOfDerivedSpecimen.size(); j++) { Specimen tempDerivedSpecimen = (Specimen) listOfDerivedSpecimen.get(j); newListOfSpecimen.add(tempDerivedSpecimen); } } } */ /* Iterator iterator = containerMap.keySet().iterator(); int i = 0; while (iterator.hasNext()) { NameValueBean nvb = (NameValueBean) iterator.next(); Map tempMap = (Map) containerMap.get(nvb); if (tempMap.size() > 0) { boolean result = false; for (; i < newListOfSpecimen.size(); i++) { Specimen tempSpecimen = (Specimen) newListOfSpecimen.get(i); result = allocatePositionToSingleSpecimen(specimenMap, tempSpecimen, tempMap, nvb); if (result == false) // container is exhausted break; } if (result == true) break; } } } */ /** * This function gets the default position specimen,the position should not be used by any other specimen in specimenMap * This is required because we might have given the same position to another specimen. * @param specimenMap * @param tempSpecimen * @param tempMap * @param nvb * @return private boolean allocatePositionToSingleSpecimen(Map specimenMap, Specimen tempSpecimen, Map tempMap, NameValueBean nvbForContainer) { Iterator itr = tempMap.keySet().iterator(); String containerId = nvbForContainer.getValue(), xPos, yPos; while (itr.hasNext()) { NameValueBean nvb = (NameValueBean) itr.next(); xPos = nvb.getValue(); List list = (List) tempMap.get(nvb); for (int i = 0; i < list.size(); i++) { nvb = (NameValueBean) list.get(i); yPos = nvb.getValue(); boolean result = checkPositionValidForSpecimen(containerId, xPos, yPos, specimenMap); if (result == true) { StorageContainer tempStorageContainer = new StorageContainer(); tempStorageContainer.setId(new Long(Long.parseLong(containerId))); tempSpecimen.setPositionDimensionOne(new Integer(Integer.parseInt(xPos))); tempSpecimen.setPositionDimensionTwo(new Integer(Integer.parseInt(yPos))); tempSpecimen.setStorageContainer(tempStorageContainer); return true; } } } return false; } */ /** * This method checks whether the given parameters match with parameters in specimen Map * @param containerId * @param pos * @param pos2 * @param specimenMap * @return private boolean checkPositionValidForSpecimen(String containerId, String xpos, String ypos, Map specimenMap) { // TODO can be optimised by passing list Iterator specimenIterator = specimenMap.keySet().iterator(); while (specimenIterator.hasNext()) { Specimen specimen = (Specimen) specimenIterator.next(); boolean matchFound = checkMatchingPosition(containerId, xpos, ypos, specimen); if (matchFound == true) return false; List derivedSpecimens = (List) specimenMap.get(specimen); if (derivedSpecimens != null) { for (int i = 0; i < derivedSpecimens.size(); i++) { Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i); matchFound = checkMatchingPosition(containerId, xpos, ypos, derivedSpecimen); if (matchFound == true) return false; } } } return true; } */ /** * This method checks whether the given parameters match with parameters of the specimen * @param containerId * @param pos * @param pos2 * @param specimen * @return private boolean checkMatchingPosition(String containerId, String xpos, String ypos, Specimen specimen) { String storageContainerId = ""; if (specimen.getStorageContainer() != null && specimen.getStorageContainer().getId() != null) storageContainerId += specimen.getStorageContainer().getId(); else return false; String pos1 = specimen.getPositionDimensionOne() + ""; String pos2 = specimen.getPositionDimensionTwo() + ""; if (storageContainerId.equals(containerId) && xpos.equals(pos1) && ypos.equals(pos2)) return true; return false; } */ /** * * End --> Code added for auto populating storage locations in case of multiple specimen */ /* This function checks whether the storage position of a specimen is changed or not * & returns the status accordingly. */ private boolean isStoragePositionChanged(Specimen oldSpecimen, Specimen newSpecimen) { StorageContainer oldContainer = oldSpecimen.getStorageContainer(); StorageContainer newContainer = newSpecimen.getStorageContainer(); //Added for api: Jitendra if ((oldContainer == null && newContainer != null) || (oldContainer != null && newContainer == null)) { return true; } if (oldContainer != null && newContainer != null) { if (oldContainer.getId().longValue() == newContainer.getId().longValue()) { if (oldSpecimen.getPositionDimensionOne().intValue() == newSpecimen.getPositionDimensionOne().intValue()) { if (oldSpecimen.getPositionDimensionTwo().intValue() == newSpecimen.getPositionDimensionTwo().intValue()) { return false; } else { return true; } } else { return true; } } else { return true; } } else { return false; } } /** * This method fetches linked data from integrated application i.e. CAE/caTies. */ public List getLinkedAppData(Long id, String applicationID) { Logger.out.debug("In getIntegrationData() of SpecimenBizLogic "); Logger.out.debug("ApplicationName in getIntegrationData() of SCGBizLogic==>" + applicationID); long identifiedPathologyReportId = 0; try { //JDBC call to get matching identifier from database Class.forName("org.gjt.mm.mysql.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/catissuecore", "catissue_core", "catissue_core"); Statement stmt = connection.createStatement(); String specimenCollectionGroupQuery = "select SPECIMEN_COLLECTION_GROUP_ID from CATISSUE_SPECIMEN where IDENTIFIER=" + id; ResultSet specimenCollectionGroupResultSet = stmt.executeQuery(specimenCollectionGroupQuery); long specimenCollectionGroupId = 0; while (specimenCollectionGroupResultSet.next()) { specimenCollectionGroupId = specimenCollectionGroupResultSet.getLong(1); break; } Logger.out.debug("SpecimenCollectionGroupId==>" + specimenCollectionGroupId); if (specimenCollectionGroupId == 0) { List exception = new ArrayList(); exception.add("SpecimenCollectionGroupId is not available for Specimen"); return exception; } String clinicalReportQuery = "select CLINICAL_REPORT_ID from CATISSUE_SPECIMEN_COLL_GROUP where IDENTIFIER=" + specimenCollectionGroupId; ResultSet clinicalReportResultSet = stmt.executeQuery(clinicalReportQuery); long clinicalReportId = 0; while (clinicalReportResultSet.next()) { clinicalReportId = clinicalReportResultSet.getLong(1); break; } Logger.out.debug("ClinicalReportId==>" + clinicalReportId); clinicalReportResultSet.close(); if (clinicalReportId == 0) { List exception = new ArrayList(); exception.add("ClinicalReportId is not available for SpecimenCollectionGroup"); return exception; } String identifiedPathologyReportIdQuery = "select IDENTIFIER from CATISSUE_IDENTIFIED_PATHOLOGY_REPORT where CLINICAL_REPORT_ID=" + clinicalReportId; ResultSet identifiedPathologyReportResultSet = stmt.executeQuery(identifiedPathologyReportIdQuery); while (identifiedPathologyReportResultSet.next()) { identifiedPathologyReportId = identifiedPathologyReportResultSet.getLong(1); break; } Logger.out.debug("IdentifiedPathologyReportId==>" + identifiedPathologyReportId); identifiedPathologyReportResultSet.close(); if (identifiedPathologyReportId == 0) { List exception = new ArrayList(); exception.add("IdentifiedPathologyReportId is not available for linked ClinicalReportId"); return exception; } stmt.close(); connection.close(); } catch (Exception e) { Logger.out.debug("JDBC Exception==>" + e.getMessage()); } IntegrationManager integrationManager = IntegrationManagerFactory.getIntegrationManager(applicationID); return integrationManager.getLinkedAppData(new Specimen(), new Long(identifiedPathologyReportId)); } public String getPageToShow() { return new String(); } public List getMatchingObjects() { return new ArrayList(); } // added by Ashwin for bug id# 2476 /** * Set event parameters from parent specimen to derived specimen * @param parentSpecimen specimen * @return set */ private Set populateDeriveSpecimenEventCollection(Specimen parentSpecimen,Specimen deriveSpecimen) { Set deriveEventCollection = new HashSet(); Set parentSpecimeneventCollection = (Set) parentSpecimen.getSpecimenEventCollection(); SpecimenEventParameters specimenEventParameters = null; SpecimenEventParameters deriveSpecimenEventParameters = null; try { if (parentSpecimeneventCollection != null) { for (Iterator iter = parentSpecimeneventCollection.iterator(); iter.hasNext();) { specimenEventParameters = (SpecimenEventParameters) iter.next(); deriveSpecimenEventParameters = (SpecimenEventParameters) specimenEventParameters.clone(); deriveSpecimenEventParameters.setId(null); deriveSpecimenEventParameters.setSpecimen(deriveSpecimen); deriveEventCollection.add(deriveSpecimenEventParameters); } } } catch (CloneNotSupportedException exception) { exception.printStackTrace(); } return deriveEventCollection; } } \ No newline at end of file diff --git a/WEB-INF/src/edu/wustl/catissuecore/util/MultipleSpecimenValidationUtil.java b/WEB-INF/src/edu/wustl/catissuecore/util/MultipleSpecimenValidationUtil.java index cd84ca116..8afca03c3 100644 --- a/WEB-INF/src/edu/wustl/catissuecore/util/MultipleSpecimenValidationUtil.java +++ b/WEB-INF/src/edu/wustl/catissuecore/util/MultipleSpecimenValidationUtil.java @@ -1,488 +1,490 @@ package edu.wustl.catissuecore.util; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import edu.wustl.catissuecore.domain.Biohazard; import edu.wustl.catissuecore.domain.CollectionEventParameters; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.CollectionProtocolRegistration; import edu.wustl.catissuecore.domain.ExternalIdentifier; import edu.wustl.catissuecore.domain.ReceivedEventParameters; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenCharacteristics; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.catissuecore.util.global.Utility; import edu.wustl.common.bizlogic.IBizLogic; import edu.wustl.common.cde.CDEManager; import edu.wustl.common.util.dbManager.DAOException; import edu.wustl.common.util.global.ApplicationProperties; import edu.wustl.common.util.global.Validator; /** * <p>This class initializes the fields of MultipleSpecimenValidationUtil.java</p> * @author Ashwin Gupta * @version 1.1 */ public final class MultipleSpecimenValidationUtil { /** * validate multiple specimens. * @param specimenMap * @param dao * @param operation * @return * @throws DAOException */ public static boolean validateMultipleSpecimen(Map specimenMap, IBizLogic bizLogic, String operation) throws DAOException { System.out.println("Inside validateMultipleSpecimen() "); boolean result = true; /* IBizLogic bizLogic; try { bizLogic = AbstractBizLogicFactory.getBizLogic(ApplicationProperties.getValue("app.bizLogicFactory"), "getBizLogic", Constants.NEW_SPECIMEN_FORM_ID); } catch (BizLogicException e) { e.printStackTrace(); throw new DAOException(e); } */ setSCGinSpecimen(specimenMap,bizLogic); Iterator specimenIterator = specimenMap.keySet().iterator(); + int count = 0; while (specimenIterator.hasNext() && result == true) { Specimen specimen = (Specimen) specimenIterator.next(); + count++; // TODO uncomment code for label, performance try { result = validateSingleSpecimen(specimen, bizLogic, operation, true); } catch (DAOException daoException) { String message = daoException.getMessage(); - message += " (This message is for Specimen number " + specimen.getId() + ")"; + message += " (This message is for Specimen number " + count + ")"; daoException.setMessage(message); throw daoException; } List derivedSpecimens = (List) specimenMap.get(specimen); if (derivedSpecimens == null) { continue; } //validate derived specimens for (int i = 0; i < derivedSpecimens.size(); i++) { Specimen derivedSpecimen = (Specimen) derivedSpecimens.get(i); derivedSpecimen.setSpecimenCharacteristics(specimen.getSpecimenCharacteristics()); derivedSpecimen.setSpecimenCollectionGroup(specimen.getSpecimenCollectionGroup()); derivedSpecimen.setPathologicalStatus(specimen.getPathologicalStatus()); try { result = validateSingleSpecimen(derivedSpecimen, bizLogic, operation, false); } catch (DAOException daoException) { int j = i + 1; String message = daoException.getMessage(); - message += " (This message is for Derived Specimen " + j + " of Parent Specimen number " + specimen.getId() + ")"; + message += " (This message is for Derived Specimen " + j + " of Parent Specimen number " + count + ")"; daoException.setMessage(message); throw daoException; } if (!result) { break; } } } System.out.println("End Inside validateMultipleSpecimen() " + result); return result; } /** * Sets SCG in Specimen. * @param specimenMap map * @param dao dao * @throws DAOException dao exception */ public static void setSCGinSpecimen(Map specimenMap, IBizLogic bizLogic) throws DAOException { Iterator specimenIterator = specimenMap.keySet().iterator(); while (specimenIterator.hasNext()) { Specimen specimen = (Specimen) specimenIterator.next(); //validate single specimen if (specimen.getSpecimenCollectionGroup() != null) { String[] selectColumnName = {"id","collectionProtocolRegistration.id","collectionProtocolRegistration.collectionProtocol.id"}; String[] whereColumnName = {Constants.NAME}; String[] whereColumnCondition = {"="}; String[] whereColumnValue = {specimen.getSpecimenCollectionGroup().getName()}; List spCollGroupList = bizLogic.retrieve(SpecimenCollectionGroup.class.getName(), selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, null); // TODO saperate calls for SCG - ID and cpid // SCG - ID will be needed before populateStorageLocations // TODO test if (!spCollGroupList.isEmpty()) { Object idList[] = (Object[]) spCollGroupList.get(0); // Move up + here //Long scgId = (Long) spCollGroupList.get(0); //Long scgId = (Long) idList[0]; Long scgId = (Long) idList[0]; // Move up long cprId = ((Long) idList[1]).longValue();//here long cpId = ((Long) idList[2]).longValue();//here specimen.getSpecimenCollectionGroup().setId(scgId); //TODO instantiate associated objects(CPR & CP) & set IDs CollectionProtocol cp = new CollectionProtocol(); cp.setId(new Long(cpId)); CollectionProtocolRegistration cpr = new CollectionProtocolRegistration(); cpr.setId(new Long(cprId)); cpr.setCollectionProtocol(cp); specimen.getSpecimenCollectionGroup().setCollectionProtocolRegistration(cpr); } } } } /** * validates single specimen. * @param specimen * @param dao * @param operation * @param partOfMulipleSpecimen * @return * @throws DAOException */ public static boolean validateSingleSpecimen(Specimen specimen, IBizLogic bizLogic, String operation, boolean partOfMulipleSpecimen) throws DAOException { //Added by Ashish //Logger.out.debug("Start-Inside validate method of specimen bizlogic"); System.out.println("Inside validateSingleSpecimen() "); if (specimen == null) { throw new DAOException(ApplicationProperties.getValue("domain.object.null.err.msg", "Specimen")); } Validator validator = new Validator(); if (specimen.getSpecimenCollectionGroup() == null || specimen.getSpecimenCollectionGroup().getId() == null || specimen.getSpecimenCollectionGroup().getId().equals("-1")) { String message = ApplicationProperties.getValue("specimen.specimenCollectionGroup"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (specimen.getParentSpecimen() != null && (specimen.getParentSpecimen().getId() == null || validator.isEmpty(specimen.getParentSpecimen().getId().toString()))) { String message = ApplicationProperties.getValue("createSpecimen.parent"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (validator.isEmpty(specimen.getLabel())) { String message = ApplicationProperties.getValue("specimen.label"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (validator.isEmpty(specimen.getClassName())) { String message = ApplicationProperties.getValue("specimen.type"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (validator.isEmpty(specimen.getType())) { String message = ApplicationProperties.getValue("specimen.subType"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } /* // commented as storage container has been removed from multiple specimen page - Ashwin if (specimen.getStorageContainer() != null && specimen.getStorageContainer().getId() == null) { String message = ApplicationProperties.getValue("specimen.subType"); throw new DAOException(ApplicationProperties.getValue("errors.invalid", message)); } */ if (specimen.getSpecimenEventCollection() != null) { Iterator specimenEventCollectionIterator = specimen.getSpecimenEventCollection().iterator(); while (specimenEventCollectionIterator.hasNext()) { //CollectionEvent validation. Object eventObject = specimenEventCollectionIterator.next(); if (eventObject instanceof CollectionEventParameters) { CollectionEventParameters collectionEventParameters = (CollectionEventParameters) eventObject; collectionEventParameters.getUser(); if (collectionEventParameters.getUser() == null || collectionEventParameters.getUser().getId() == null) { String message = ApplicationProperties.getValue("specimen.collection.event.user"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (!validator.checkDate(Utility.parseDateToString(collectionEventParameters.getTimestamp(), Constants.DATE_PATTERN_MM_DD_YYYY))) { String message = ApplicationProperties.getValue("specimen.collection.event.date"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } // checks the collectionProcedure if (!validator.isValidOption(collectionEventParameters.getCollectionProcedure())) { String message = ApplicationProperties.getValue("collectioneventparameters.collectionprocedure"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } List procedureList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COLLECTION_PROCEDURE, null); if (!Validator.isEnumeratedValue(procedureList, collectionEventParameters.getCollectionProcedure())) { throw new DAOException(ApplicationProperties.getValue("events.collectionProcedure.errMsg")); } if (!validator.isValidOption(collectionEventParameters.getContainer())) { String message = ApplicationProperties.getValue("collectioneventparameters.container"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } List containerList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CONTAINER, null); if (!Validator.isEnumeratedValue(containerList, collectionEventParameters.getContainer())) { throw new DAOException(ApplicationProperties.getValue("events.container.errMsg")); } } //ReceivedEvent validation else if (eventObject instanceof ReceivedEventParameters) { ReceivedEventParameters receivedEventParameters = (ReceivedEventParameters) eventObject; if (receivedEventParameters.getUser() == null || receivedEventParameters.getUser().getId() == null) { String message = ApplicationProperties.getValue("specimen.recieved.event.user"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } if (!validator.checkDate(Utility.parseDateToString(receivedEventParameters.getTimestamp(), Constants.DATE_PATTERN_MM_DD_YYYY))) { String message = ApplicationProperties.getValue("specimen.recieved.event.date"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } // checks the collectionProcedure if (!validator.isValidOption(receivedEventParameters.getReceivedQuality())) { String message = ApplicationProperties.getValue("collectioneventparameters.receivedquality"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", message)); } List qualityList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_RECEIVED_QUALITY, null); if (!Validator.isEnumeratedValue(qualityList, receivedEventParameters.getReceivedQuality())) { throw new DAOException(ApplicationProperties.getValue("events.receivedQuality.errMsg")); } } } } //Validations for Biohazard Add-More Block Collection bioHazardCollection = specimen.getBiohazardCollection(); Biohazard biohazard = null; if (bioHazardCollection != null && !bioHazardCollection.isEmpty()) { Iterator itr = bioHazardCollection.iterator(); while (itr.hasNext()) { biohazard = (Biohazard) itr.next(); if (!validator.isValidOption(biohazard.getType())) { String message = ApplicationProperties.getValue("newSpecimen.msg"); throw new DAOException(ApplicationProperties.getValue("errors.newSpecimen.biohazard.missing", message)); } if (biohazard.getId() == null || biohazard.getId().toString().equals("-1")) { String message = ApplicationProperties.getValue("newSpecimen.msg"); throw new DAOException(ApplicationProperties.getValue("errors.newSpecimen.biohazard.missing", message)); } } } //validations for external identifiers Collection extIdentifierCollection = specimen.getExternalIdentifierCollection(); ExternalIdentifier extIdentifier = null; if (extIdentifierCollection != null && !extIdentifierCollection.isEmpty()) { Iterator itr = extIdentifierCollection.iterator(); while (itr.hasNext()) { extIdentifier = (ExternalIdentifier) itr.next(); if (validator.isEmpty(extIdentifier.getName())) { String message = ApplicationProperties.getValue("specimen.msg"); throw new DAOException(ApplicationProperties.getValue("errors.specimen.externalIdentifier.missing", message)); } if (validator.isEmpty(extIdentifier.getValue())) { String message = ApplicationProperties.getValue("specimen.msg"); throw new DAOException(ApplicationProperties.getValue("errors.specimen.externalIdentifier.missing", message)); } } } //End Ashish if (Constants.ALIQUOT.equals(specimen.getLineage())) { //return true; } validateFields(specimen, bizLogic, operation, partOfMulipleSpecimen); List specimenClassList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_SPECIMEN_CLASS, null); String specimenClass = Utility.getSpecimenClassName(specimen); if (!Validator.isEnumeratedValue(specimenClassList, specimenClass)) { throw new DAOException(ApplicationProperties.getValue("protocol.class.errMsg")); } if (!Validator.isEnumeratedValue(Utility.getSpecimenTypes(specimenClass), specimen.getType())) { throw new DAOException(ApplicationProperties.getValue("protocol.type.errMsg")); } SpecimenCharacteristics characters = specimen.getSpecimenCharacteristics(); if (characters == null) { throw new DAOException(ApplicationProperties.getValue("specimen.characteristics.errMsg")); } else { if (specimen.getSpecimenCollectionGroup() != null) { // NameValueBean undefinedVal = new NameValueBean(Constants.UNDEFINED,Constants.UNDEFINED); List tissueSiteList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_TISSUE_SITE, null); if (!Validator.isEnumeratedValue(tissueSiteList, characters.getTissueSite())) { throw new DAOException(ApplicationProperties.getValue("protocol.tissueSite.errMsg")); } // NameValueBean unknownVal = new NameValueBean(Constants.UNKNOWN,Constants.UNKNOWN); List tissueSideList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_TISSUE_SIDE, null); if (!Validator.isEnumeratedValue(tissueSideList, characters.getTissueSide())) { throw new DAOException(ApplicationProperties.getValue("specimen.tissueSide.errMsg")); } List pathologicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_PATHOLOGICAL_STATUS, null); if (!Validator.isEnumeratedValue(pathologicalStatusList, specimen.getPathologicalStatus())) { throw new DAOException(ApplicationProperties.getValue("protocol.pathologyStatus.errMsg")); } } } if (operation.equals(Constants.ADD)) { if (!specimen.getAvailable().booleanValue()) { throw new DAOException(ApplicationProperties.getValue("specimen.available.errMsg")); } if (!Constants.ACTIVITY_STATUS_ACTIVE.equals(specimen.getActivityStatus())) { throw new DAOException(ApplicationProperties.getValue("activityStatus.active.errMsg")); } } else { if (!Validator.isEnumeratedValue(Constants.ACTIVITY_STATUS_VALUES, specimen.getActivityStatus())) { throw new DAOException(ApplicationProperties.getValue("activityStatus.errMsg")); } } //Logger.out.debug("End-Inside validate method of specimen bizlogic"); return true; } /** * validate fields * @param specimen specimen * @param dao dao * @param operation string operation * @param partOfMulipleSpecimen * @throws DAOException */ private static void validateFields(Specimen specimen, IBizLogic bizLogic, String operation, boolean partOfMulipleSpecimen) throws DAOException { Validator validator = new Validator(); if (partOfMulipleSpecimen) { if (specimen.getSpecimenCollectionGroup() == null || validator.isEmpty(specimen.getSpecimenCollectionGroup().getName())) { String quantityString = ApplicationProperties.getValue("specimen.specimenCollectionGroup"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", quantityString)); } List spgList = bizLogic.retrieve(SpecimenCollectionGroup.class.getName(), Constants.NAME, specimen.getSpecimenCollectionGroup().getName()); if (spgList.size() == 0) { throw new DAOException(ApplicationProperties.getValue("errors.item.unknown", "Specimen Collection Group " + specimen.getSpecimenCollectionGroup().getName())); } } if (validator.isEmpty(specimen.getLabel())) { String labelString = ApplicationProperties.getValue("specimen.label"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", labelString)); } if (specimen.getQuantity() == null || specimen.getQuantity().getValue() == null) { String quantityString = ApplicationProperties.getValue("specimen.quantity"); throw new DAOException(ApplicationProperties.getValue("errors.item.required", quantityString)); } /** * If specimen is virtually located, then in that case storage container is being set null explicitly in Specimen * domain object.Hence to avoid NullPointerException here check null of container is required. * @author jitendra_agrawal */ /* // commented as storage container has been removed from multiple specimen page - Ashwin if (specimen.getStorageContainer() != null) { Long storageContainerId = specimen.getStorageContainer().getId(); Integer xPos = specimen.getPositionDimensionOne(); Integer yPos = specimen.getPositionDimensionTwo(); if (storageContainerId == null || xPos == null || yPos == null || xPos.intValue() < 0 || yPos.intValue() < 0) { throw new DAOException(ApplicationProperties.getValue("errors.item.format", ApplicationProperties .getValue("specimen.positionInStorageContainer"))); } } */ } }
false
false
null
null
diff --git a/x10.compiler/src/x10/ast/AnnotationNode_c.java b/x10.compiler/src/x10/ast/AnnotationNode_c.java index 522c62ce6..677a7ef32 100644 --- a/x10.compiler/src/x10/ast/AnnotationNode_c.java +++ b/x10.compiler/src/x10/ast/AnnotationNode_c.java @@ -1,112 +1,112 @@ /* * This file is part of the X10 project (http://x10-lang.org). * * This file is licensed to You under the Eclipse Public License (EPL); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.opensource.org/licenses/eclipse-1.0.php * * (C) Copyright IBM Corporation 2006-2010. */ package x10.ast; import polyglot.ast.Node; import polyglot.ast.Node_c; import polyglot.ast.TypeNode; import polyglot.types.Context; import polyglot.types.SemanticException; import polyglot.util.CodeWriter; import polyglot.util.Position; import polyglot.visit.ContextVisitor; import polyglot.visit.NodeVisitor; import polyglot.visit.PrettyPrinter; import polyglot.visit.Translator; import x10.errors.Errors; import x10.types.X10ClassType; import polyglot.types.Context; import polyglot.types.TypeSystem; /** * A node representing an annotation. Every X10 Node has an associated list of AnnotationNodes. * An annotation is simply an interface type. * @author nystrom */ public class AnnotationNode_c extends Node_c implements AnnotationNode { TypeNode tn; /** * */ public AnnotationNode_c(Position pos, TypeNode tn) { super(pos); this.tn = tn; } public TypeNode annotationType() { return tn; } public AnnotationNode annotationType(TypeNode tn) { AnnotationNode_c n = (AnnotationNode_c) copy(); n.tn = tn; return n; } public X10ClassType annotationInterface() { - return (X10ClassType) annotationType().type(); + return (X10ClassType) annotationType().type().toClass(); } @Override public Node visitChildren(NodeVisitor v) { TypeNode tn = (TypeNode) this.visitChild(this.tn, v); if (tn != this.tn) { return annotationType(tn); } return this; } @Override public Context enterChildScope(Node child, Context c) { c = c.pushBlock(); ((Context) c).setAnnotation(); return super.enterChildScope(child, c); } // public Node disambiguateOverride(AmbiguityRemover ar) throws SemanticException { // if (ar.job().extensionInfo().scheduler().currentGoal() instanceof SignaturesDisambiguated) { // return this; // } // if (ar.job().extensionInfo().scheduler().currentGoal() instanceof SupertypesDisambiguated) { // return this; // } // return super.disambiguate(ar); // } @Override public Node typeCheck(ContextVisitor tc) { // System.out.println("Type checking " + this); TypeSystem xts = (TypeSystem) tc.typeSystem(); if (!xts.hasUnknown(tn.type()) && !(tn.type().isClass() && tn.type().toClass().flags().isInterface())) { Errors.issue(tc.job(), new Errors.AnnotationMustBeInterfacetype(position())); } return this; } @Override public void prettyPrint(CodeWriter w, PrettyPrinter pp) { w.write("@"); print(tn, w, pp); } @Override public void translate(CodeWriter w, Translator tr) { /** Do nothing! */ } @Override public String toString() { return "@" + tn.toString(); } } diff --git a/x10.compiler/src/x10/parser/X10SemanticRules.java b/x10.compiler/src/x10/parser/X10SemanticRules.java index a6c2eb610..ae664b55f 100644 --- a/x10.compiler/src/x10/parser/X10SemanticRules.java +++ b/x10.compiler/src/x10/parser/X10SemanticRules.java @@ -1,4259 +1,4259 @@ /* * This file is part of the X10 project (http://x10-lang.org). * * This file is licensed to You under the Eclipse Public License (EPL); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.opensource.org/licenses/eclipse-1.0.php * * (C) Copyright IBM Corporation 2006-2010. */ package x10.parser; import lpg.runtime.*; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.io.File; import polyglot.types.QName; import polyglot.types.Name; import polyglot.ast.AmbTypeNode; import polyglot.ast.AmbExpr; import polyglot.ast.Assign; import polyglot.ast.Binary; import polyglot.ast.Block; import polyglot.ast.Case; import polyglot.ast.Catch; import polyglot.ast.ClassBody; import polyglot.ast.ClassDecl; import polyglot.ast.ClassMember; import polyglot.ast.ConstructorCall; import polyglot.ast.ConstructorDecl; import polyglot.ast.Eval; import polyglot.ast.Expr; import polyglot.ast.Field; import polyglot.ast.FloatLit; import polyglot.ast.ForInit; import polyglot.ast.ForUpdate; import polyglot.ast.Formal; import polyglot.ast.Id; import polyglot.ast.Import; import polyglot.ast.IntLit; import polyglot.ast.LocalDecl; import polyglot.ast.MethodDecl; import polyglot.ast.FieldDecl; import polyglot.ast.Node; import polyglot.ast.NodeFactory; import polyglot.ast.PackageNode; import polyglot.ast.ProcedureDecl; import polyglot.ast.SourceFile; import polyglot.ast.Stmt; import polyglot.ast.SwitchElement; import polyglot.ast.TopLevelDecl; import polyglot.ast.TypeNode; import polyglot.ast.Unary; import polyglot.ast.FlagsNode; import polyglot.parse.ParsedName; import x10.ast.AnnotationNode; import x10.ast.ClosureCall; import x10.ast.SettableAssign; import x10.ast.Here; import x10.ast.DepParameterExpr; import x10.ast.Tuple; import x10.ast.X10Formal; import x10.ast.TypeDecl; import x10.ast.TypeParamNode; import x10.types.ParameterType; import polyglot.types.TypeSystem; import x10.ast.PropertyDecl; import x10.ast.X10Binary_c; import x10.ast.X10Unary_c; import x10.extension.X10Ext; import polyglot.frontend.FileSource; import polyglot.frontend.Parser; import polyglot.lex.BooleanLiteral; import polyglot.lex.CharacterLiteral; import polyglot.lex.DoubleLiteral; import polyglot.lex.FloatLiteral; import polyglot.lex.Identifier; import polyglot.lex.LongLiteral; import polyglot.lex.NullLiteral; import polyglot.lex.Operator; import polyglot.lex.StringLiteral; import polyglot.types.Flags; import x10.types.checker.Converter; import x10.errors.Errors; import polyglot.util.CollectionUtil; import x10.util.CollectionFactory; import polyglot.util.ErrorInfo; import polyglot.util.ErrorQueue; import polyglot.util.Position; import polyglot.util.TypedList; import lpg.runtime.BacktrackingParser; import lpg.runtime.IToken; import lpg.runtime.ParseTable; public class X10SemanticRules implements Parser, ParseErrorCodes { public ParseTable getParseTable() { return p.getParseTable(); } public BacktrackingParser getParser() { return p.getParser(); } public X10Parser getX10Parser() { return p; } public X10Lexer getX10Lexer() { return lexer; } //private Object setResult(Object o) { return o; } // todo: refactor it out private void setResult(Object object) { getParser().setSym1(object); } public Object getRhsSym(int i) { return p.getRhsSym(i); } public int getRhsTokenIndex(int i) { return p.getRhsTokenIndex(i); } public IToken getRhsIToken(int i) { return p.getRhsIToken(i); } public int getRhsFirstTokenIndex(int i) { return p.getRhsFirstTokenIndex(i); } public IToken getRhsFirstIToken(int i) { return p.getRhsFirstIToken(i); } public int getRhsLastTokenIndex(int i) { return p.getRhsLastTokenIndex(i); } public IToken getRhsLastIToken(int i) { return p.getRhsLastIToken(i); } public int getLeftSpan() { return p.getLeftSpan(); } public IToken getLeftIToken() { return p.getLeftIToken(); } public int getRightSpan() { return p.getRightSpan(); } public IToken getRightIToken() { return p.getRightIToken(); } public int getRhsErrorTokenIndex(int i) { return p.getRhsErrorTokenIndex(i); } public ErrorToken getRhsErrorIToken(int i) { return p.getRhsErrorIToken(i); } public polyglot.ast.Node parser() { return p.parser(); } // public void reset(ILexStream lexStream) { return p.(i); } // public int numTokenKinds() { return X10Parsersym.numTokenKinds; } // public String[] orderedTerminalSymbols() { return X10Parsersym.orderedTerminalSymbols; } // public String getTokenKindName(int kind) { return X10Parsersym.orderedTerminalSymbols[kind]; } // public int getEOFTokenKind() { return prsTable.getEoftSymbol(); } public IPrsStream getIPrsStream() { return p.getIPrsStream(); } private final X10Parser p; private final X10Lexer lexer; private IPrsStream prsStream; private ErrorQueue eq; private TypeSystem ts; private NodeFactory nf; private FileSource source; private boolean unrecoverableSyntaxError = false; public void initialize(TypeSystem t, NodeFactory n, FileSource source, ErrorQueue q) { this.ts = (TypeSystem) t; this.nf = (NodeFactory) n; this.source = source; this.eq = q; } public X10SemanticRules(X10Lexer lexer, TypeSystem t, NodeFactory n, FileSource source, ErrorQueue q) { this.lexer = lexer; ILexStream lexStream = this.lexer.getILexStream(); p = new X10Parser(lexStream); p.r = this; initialize((TypeSystem) t, (NodeFactory) n, source, q); prsStream = p.getIPrsStream(); prsStream.setMessageHandler(new MessageHandler(q)); } public static class MessageHandler implements IMessageHandler { ErrorQueue eq; public MessageHandler(ErrorQueue eq) { this.eq = eq; } public static String getErrorMessageFor(int errorCode, String[] errorInfo) { String msg = ""; String info = ""; for (String s : errorInfo) { info += s; } switch (errorCode) { case LEX_ERROR_CODE: msg = "Unexpected character ignored: " + info; break; case ERROR_CODE: msg = "Parse terminated at this token: " + info; break; case BEFORE_CODE: msg = "Token " + info + " expected before this input"; break; case INSERTION_CODE: msg = "Token " + info + " expected after this input"; break; case INVALID_CODE: msg = "Unexpected input discarded: " + info; break; case SUBSTITUTION_CODE: msg = "Token " + info + " expected instead of this input"; break; case DELETION_CODE: msg = "Unexpected input ignored: " + info; break; case MERGE_CODE: msg = "Merging token(s) to recover: " + info; break; case MISPLACED_CODE: msg = "Misplaced constructs(s): " + info; break; case SCOPE_CODE: msg = "Token(s) inserted to complete scope: " + info; break; case EOF_CODE: msg = "Reached after this token: " + info; break; case INVALID_TOKEN_CODE: msg = "Invalid token: " + info; break; case ERROR_RULE_WARNING_CODE: msg = "Ignored token: " + info; break; case NO_MESSAGE_CODE: msg = "Syntax error"; break; } // FIXME: HACK! Prepend "Syntax error: " until we figure out how to // get Polyglot to do it for us. if (errorCode != NO_MESSAGE_CODE) { msg = "Syntax error: " + msg; } return msg; } public void handleMessage(int errorCode, int[] msgLocation, int[] errorLocation, String filename, String[] errorInfo) { File file = new File(filename); int l0 = msgLocation[2]; int c0 = msgLocation[3]; int l1 = msgLocation[4]; int c1 = msgLocation[5]; int o0 = msgLocation[0]; int o1 = msgLocation[0] + msgLocation[1]; Position pos = new JPGPosition("", file.getPath(), l0, c0, l1, c1+1, o0, o1); String msg = getErrorMessageFor(errorCode, errorInfo); eq.enqueue(ErrorInfo.SYNTAX_ERROR, msg, pos); } } public String getErrorLocation(int lefttok, int righttok) { return prsStream.getFileName() + ':' + prsStream.getLine(lefttok) + ":" + prsStream.getColumn(lefttok) + ":" + prsStream.getEndLine(righttok) + ":" + prsStream.getEndColumn(righttok) + ": "; } public Position getErrorPosition(int lefttok, int righttok) { return new JPGPosition(null, prsStream.getFileName(), prsStream.getIToken(lefttok), prsStream.getIToken(righttok)); } // // Temporary classes used to wrap modifiers. // private static class Modifier { } private static class FlagModifier extends Modifier { public static int ABSTRACT = 0; public static int ATOMIC = 1; // public static int EXTERN = 2; public static int FINAL = 3; //public static int GLOBAL = 4; //public static int INCOMPLETE = 5; public static int NATIVE = 6; //public static int NON_BLOCKING = 7; public static int PRIVATE = 8; public static int PROPERTY = 9; public static int PROTECTED = 10; public static int PUBLIC = 11; //public static int SAFE = 12; //public static int SEQUENTIAL = 13; public static int CLOCKED = 14; public static int STATIC = 15; public static int TRANSIENT = 16; public static int NUM_FLAGS = TRANSIENT + 1; private JPGPosition pos; private int flag; public JPGPosition position() { return pos; } public int flag() { return flag; } public Flags flags() { if (flag == ABSTRACT) return Flags.ABSTRACT; if (flag == ATOMIC) return Flags.ATOMIC; // if (flag == EXTERN) return X10Flags.EXTERN; if (flag == FINAL) return Flags.FINAL; // if (flag == GLOBAL) return X10Flags.GLOBAL; //if (flag == INCOMPLETE) return X10Flags.INCOMPLETE; if (flag == NATIVE) return Flags.NATIVE; //if (flag == NON_BLOCKING) return X10Flags.NON_BLOCKING; if (flag == PRIVATE) return Flags.PRIVATE; if (flag == PROPERTY) return Flags.PROPERTY; if (flag == PROTECTED) return Flags.PROTECTED; if (flag == PUBLIC) return Flags.PUBLIC; //if (flag == SAFE) return X10Flags.SAFE; //if (flag == SEQUENTIAL) return X10Flags.SEQUENTIAL; if (flag == CLOCKED) return Flags.CLOCKED; if (flag == TRANSIENT) return Flags.TRANSIENT; if (flag == STATIC) return Flags.STATIC; assert(false); return null; } public String name() { if (flag == ABSTRACT) return "abstract"; if (flag == ATOMIC) return "atomic"; //if (flag == EXTERN) return "extern"; if (flag == FINAL) return "final"; //if (flag == GLOBAL) return "global"; //if (flag == INCOMPLETE) return "incomplete"; if (flag == NATIVE) return "native"; //if (flag == NON_BLOCKING) return "nonblocking"; if (flag == PRIVATE) return "private"; if (flag == PROPERTY) return "property"; if (flag == PROTECTED) return "protected"; if (flag == PUBLIC) return "public"; //if (flag == SAFE) return "safe"; //if (flag == SEQUENTIAL) return "sequential"; if (flag == CLOCKED) return "clocked"; if (flag == STATIC) return "static"; if (flag == TRANSIENT) return "transient"; assert(false); return "?"; } public static boolean classModifiers[] = new boolean[NUM_FLAGS]; static { classModifiers[ABSTRACT] = true; classModifiers[FINAL] = true; classModifiers[PRIVATE] = true; classModifiers[PROTECTED] = true; classModifiers[PUBLIC] = true; //classModifiers[SAFE] = true; classModifiers[STATIC] = true; classModifiers[CLOCKED] = true; // classModifiers[GLOBAL] = true; } public boolean isClassModifier(int flag) { return classModifiers[flag]; } public static boolean typeDefModifiers[] = new boolean[NUM_FLAGS]; static { typeDefModifiers[ABSTRACT] = true; typeDefModifiers[FINAL] = true; typeDefModifiers[PRIVATE] = true; typeDefModifiers[PROTECTED] = true; typeDefModifiers[PUBLIC] = true; typeDefModifiers[STATIC] = true; } public boolean isTypeDefModifier(int flag) { return typeDefModifiers[flag]; } public static boolean fieldModifiers[] = new boolean[NUM_FLAGS]; static { fieldModifiers[TRANSIENT] = true; // fieldModifiers[GLOBAL] = true; fieldModifiers[CLOCKED] = true; fieldModifiers[PRIVATE] = true; fieldModifiers[PROTECTED] = true; fieldModifiers[PROPERTY] = true; fieldModifiers[PUBLIC] = true; fieldModifiers[STATIC] = true; } public boolean isFieldModifier(int flag) { return fieldModifiers[flag]; } public static boolean variableModifiers[] = new boolean[NUM_FLAGS]; static { variableModifiers[CLOCKED] = true; } public boolean isVariableModifier(int flag) { return variableModifiers[flag]; } public static boolean methodModifiers[] = new boolean[NUM_FLAGS]; static { methodModifiers[ABSTRACT] = true; methodModifiers[ATOMIC] = true; // methodModifiers[EXTERN] = true; methodModifiers[FINAL] = true; // methodModifiers[GLOBAL] = true; //methodModifiers[INCOMPLETE] = true; methodModifiers[NATIVE] = true; //methodModifiers[NON_BLOCKING] = true; methodModifiers[PRIVATE] = true; methodModifiers[PROPERTY] = true; methodModifiers[PROTECTED] = true; methodModifiers[PUBLIC] = true; //methodModifiers[SAFE] = true; //methodModifiers[SEQUENTIAL] = true; methodModifiers[STATIC] = true; //methodModifiers[CLOCKED] = true; } public boolean isMethodModifier(int flag) { return methodModifiers[flag]; } public static boolean constructorModifiers[] = new boolean[NUM_FLAGS]; static { constructorModifiers[NATIVE] = true; constructorModifiers[PRIVATE] = true; constructorModifiers[PROTECTED] = true; constructorModifiers[PUBLIC] = true; } public boolean isConstructorModifier(int flag) { return constructorModifiers[flag]; } public static boolean interfaceModifiers[] = new boolean[NUM_FLAGS]; static { interfaceModifiers[ABSTRACT] = true; interfaceModifiers[PRIVATE] = true; interfaceModifiers[PROTECTED] = true; interfaceModifiers[PUBLIC] = true; interfaceModifiers[STATIC] = true; interfaceModifiers[CLOCKED] = true; } public boolean isInterfaceModifier(int flag) { return interfaceModifiers[flag]; } public FlagModifier(JPGPosition pos, int flag) { this.pos = pos; this.flag = flag; } } private static class AnnotationModifier extends Modifier { private AnnotationNode annotation; public AnnotationNode annotation() { return annotation; } public AnnotationModifier(AnnotationNode annotation) { this.annotation = annotation; } } // // TODO: Say something! // private List<Node> checkModifiers(String kind, List<Modifier> modifiers, boolean legal_flags[]) { List<Node> l = new LinkedList<Node>(); assert(modifiers.size() > 0); boolean flags[] = new boolean[FlagModifier.NUM_FLAGS]; // initialized to false for (int i = 0; i < modifiers.size(); i++) { Object element = modifiers.get(i); if (element instanceof FlagModifier) { FlagModifier modifier = (FlagModifier) element; l.addAll(Collections.singletonList(nf.FlagsNode(modifier.position(), modifier.flags()))); if (! flags[modifier.flag()]) { flags[modifier.flag()] = true; } else { syntaxError("Duplicate specification of modifier: " + modifier.name(), modifier.position()); } if (! legal_flags[modifier.flag()]) { syntaxError("\"" + modifier.name() + "\" is not a valid " + kind + " modifier", modifier.position()); } } else { AnnotationModifier modifier = (AnnotationModifier) element; l.addAll(Collections.singletonList(modifier.annotation())); } } return l; } private List<Node> checkClassModifiers(List<Modifier> modifiers) { return (modifiers.size() == 0 ? Collections.<Node>singletonList(nf.FlagsNode(JPGPosition.COMPILER_GENERATED, Flags.NONE)) : checkModifiers("class", modifiers, FlagModifier.classModifiers)); } private List<Node> checkTypeDefModifiers(List<Modifier> modifiers) { return (modifiers.size() == 0 ? Collections.<Node>singletonList(nf.FlagsNode(JPGPosition.COMPILER_GENERATED, Flags.NONE)) : checkModifiers("typedef", modifiers, FlagModifier.typeDefModifiers)); } private List<Node> checkFieldModifiers(List<Modifier> modifiers) { return (modifiers.size() == 0 ? Collections.<Node>emptyList() : checkModifiers("field", modifiers, FlagModifier.fieldModifiers)); } private List<Node> checkVariableModifiers(List<Modifier> modifiers) { return (modifiers.size() == 0 ? Collections.<Node>emptyList() : checkModifiers("variable", modifiers, FlagModifier.variableModifiers)); } private List<Node> checkMethodModifiers(List<Modifier> modifiers) { return (modifiers.size() == 0 ? Collections.<Node>emptyList() : checkModifiers("method", modifiers, FlagModifier.methodModifiers)); } private List<Node> checkConstructorModifiers(List<Modifier> modifiers) { return (modifiers.size() == 0 ? Collections.<Node>emptyList() : checkModifiers("constructor", modifiers, FlagModifier.constructorModifiers)); } private List<Node> checkInterfaceModifiers(List<Modifier> modifiers) { return (modifiers.size() == 0 ? Collections.<Node>emptyList() : checkModifiers("interface", modifiers, FlagModifier.interfaceModifiers)); } // RMF 11/7/2005 - N.B. This class has to be serializable, since it shows up inside Type objects, // which Polyglot serializes to save processing when loading class files generated from source // by Polyglot itself. public static class JPGPosition extends Position { private static final long serialVersionUID= -1593187800129872262L; private final transient IToken leftIToken, rightIToken; public JPGPosition(String path, String filename, IToken leftToken, IToken rightToken) { super(path, filename, leftToken.getLine(), leftToken.getColumn(), rightToken.getEndLine(), rightToken.getEndColumn(), leftToken.getStartOffset(), rightToken.getEndOffset()); this.leftIToken = null; // BRT -- was null, need to keep leftToken for later reference this.rightIToken = null; // BRT -- was null, need to keep rightToken for later reference } public JPGPosition(Position start, Position end) { super(start, end); this.leftIToken = (start instanceof JPGPosition) ? ((JPGPosition)start).leftIToken : null; this.rightIToken = (end instanceof JPGPosition) ? ((JPGPosition)end).rightIToken : null; } JPGPosition(String path, String filename, int line, int column, int endLine, int endColumn, int offset, int endOffset) { super(path, filename, line, column, endLine, endColumn, offset, endOffset); this.leftIToken = null; this.rightIToken = null; } private JPGPosition() { super(null, "Compiler Generated"); this.leftIToken = null; this.rightIToken = null; } public static final JPGPosition COMPILER_GENERATED = (JPGPosition)(new JPGPosition().markCompilerGenerated()); public IToken getLeftIToken() { return leftIToken; } public IToken getRightIToken() { return rightIToken; } public String toText() { if (leftIToken == null) return "..."; IPrsStream prsStream = leftIToken.getIPrsStream(); return new String(prsStream.getInputChars(), offset(), endOffset() - offset() + 1); } } public void syntaxError(String msg, Position pos) { syntaxError(msg, pos, false); } public void syntaxError(String msg, Position pos, boolean unrecoverable) { unrecoverableSyntaxError = unrecoverable; eq.enqueue(ErrorInfo.SYNTAX_ERROR, msg, pos); } public polyglot.ast.Node parse() { try { SourceFile sf = (SourceFile) parser(); if (sf != null) { if (! unrecoverableSyntaxError) return sf.source(source); eq.enqueue(ErrorInfo.SYNTAX_ERROR, "Unable to parse " + source.name() + ".", new JPGPosition(null, file(), 1, 1, 1, 1, 0, 0).markCompilerGenerated()); } } catch (RuntimeException e) { // Let the Compiler catch and report it. throw e; } catch (Exception e) { // Used by cup to indicate a non-recoverable error. eq.enqueue(ErrorInfo.SYNTAX_ERROR, e.getMessage(), new JPGPosition(null, file(), 1, 1, 1, 1, 0, 0).markCompilerGenerated()); } return null; } public String file() { return prsStream.getFileName(); } public JPGPosition pos() { return new JPGPosition("", prsStream.getFileName(), prsStream.getIToken(getLeftSpan()), prsStream.getIToken(getRightSpan())); } public JPGPosition pos(int i) { return new JPGPosition("", prsStream.getFileName(), prsStream.getIToken(i), prsStream.getIToken(i)); } public JPGPosition pos(int i, int j) { return new JPGPosition("", prsStream.getFileName(), prsStream.getIToken(i), prsStream.getIToken(j)); } public JPGPosition pos(JPGPosition start, JPGPosition end) { return new JPGPosition(start.path(), start.file(), start.leftIToken, end.rightIToken); } private void checkTypeName(Id identifier) { String filename = file(); String idname = identifier.id().toString(); int dot = filename.lastIndexOf('.'), slash = filename.lastIndexOf('/', dot); if (slash == -1) slash = filename.lastIndexOf('\\', dot); String clean_filename = (slash >= 0 && dot >= 0 ? filename.substring(slash+1, dot) : ""); if ((! clean_filename.equals(idname)) && clean_filename.equalsIgnoreCase(idname)) eq.enqueue(ErrorInfo.SYNTAX_ERROR, "This type name does not match the name of the containing file: " + filename.substring(slash+1), identifier.position()); } private polyglot.lex.Operator op(int i) { return new Operator(pos(i), prsStream.getName(i), prsStream.getKind(i)); } private polyglot.lex.Identifier id(int i) { return new Identifier(pos(i), prsStream.getName(i), X10Parsersym.TK_IDENTIFIER); } private String comment(int i) { IToken[] adjuncts = prsStream.getTokenAt(i).getPrecedingAdjuncts(); String s = null; for (IToken a : adjuncts) { String c = a.toString(); if (c.startsWith("/**") && c.endsWith("*/")) { s = c; } } return s; } private List<Formal> toFormals(List<Formal> l) { return l; } private List<Expr> toActuals(List<Formal> l) { List<Expr> l2 = new ArrayList<Expr>(); for (Formal f : l) { l2.add(nf.Local(f.position(), f.name())); } return l2; } private List<TypeParamNode> toTypeParams(List<TypeParamNode> l) { return l; } private List<TypeNode> toTypeArgs(List<TypeParamNode> l) { List<TypeNode> l2 = new ArrayList<TypeNode>(); for (TypeParamNode f : l) { l2.add(nf.AmbTypeNode(f.position(), null, f.name())); } return l2; } private List<AnnotationNode> extractAnnotations(List<? extends Node> l) { List<AnnotationNode> l2 = new LinkedList<AnnotationNode>(); for (Node n : l) { if (n instanceof AnnotationNode) { l2.add((AnnotationNode) n); } } return l2; } private FlagsNode extractFlags(List<? extends Node> l, Flags f) { FlagsNode fn = extractFlags(l); fn = fn.flags(fn.flags().set(f)); return fn; } private FlagsNode extractFlags(List<? extends Node> l1, List<? extends Node> l2) { List<Node> l = new ArrayList<Node>(); l.addAll(l1); l.addAll(l2); return extractFlags(l); } private FlagsNode extractFlags(List<? extends Node> l) { Position pos = null; Flags xf = Flags.NONE; for (Node n : l) { if (n instanceof FlagsNode) { FlagsNode fn = (FlagsNode) n; pos = pos == null ? fn.position() : new JPGPosition(pos, fn.position()); Flags f = fn.flags(); xf = xf.set(f); } } return nf.FlagsNode(pos == null ? JPGPosition.COMPILER_GENERATED : pos, xf); } /* Roll our own integer parser. We can't use Long.parseLong because * it doesn't handle numbers greater than 0x7fffffffffffffff correctly. */ private long parseLong(String s, int radix) { long x = 0L; s = s.toLowerCase(); for (int i = 0; i < s.length(); i++) { int c = s.charAt(i); if (c < '0' || c > '9') { c = c - 'a' + 10; } else { c = c - '0'; } x *= radix; x += c; } return x; } private long parseLong(String s) { int radix; int start_index; int end_index; end_index = s.length(); boolean isUnsigned = false; long min = Integer.MIN_VALUE; while (end_index > 0) { char lastCh = s.charAt(end_index - 1); if (lastCh == 'u' || lastCh == 'U') isUnsigned = true; // todo: long need special treatment cause we have overflows if (lastCh == 'l' || lastCh == 'L') isUnsigned = true; // for signed values that start with 0, we need to make them negative if they are above max value if (lastCh == 'y' || lastCh == 'Y') min = Byte.MIN_VALUE; if (lastCh == 's' || lastCh == 'S') min = Short.MIN_VALUE; if (lastCh != 'y' && lastCh != 'Y' && lastCh != 's' && lastCh != 'S' && lastCh != 'l' && lastCh != 'L' && lastCh != 'u' && lastCh != 'U') { break; } end_index--; } long max = -min; if (s.charAt(0) == '0') { if (s.length() > 1 && (s.charAt(1) == 'x' || s.charAt(1) == 'X')) { radix = 16; start_index = 2; } else { radix = 8; start_index = 0; } } else { radix = 10; start_index = 0; } final long res = parseLong(s.substring(start_index, end_index), radix); if (!isUnsigned && radix!=10 && res>=max) { // need to make this value negative // e.g., 0xffUY == 255, 0xffY== 255-256 = -1 , 0xfeYU==254, 0xfeY== 254-256 = -2 return res+min*2; } return res; } private void setIntLit(IntLit.Kind k) { setResult(nf.IntLit(pos(), k, parseLong(prsStream.getName(getRhsFirstTokenIndex(1))))); } private polyglot.lex.FloatLiteral float_lit(int i) { try { String s = prsStream.getName(i); int end_index = (s.charAt(s.length() - 1) == 'f' || s.charAt(s.length() - 1) == 'F' ? s.length() - 1 : s.length()); float x = Float.parseFloat(s.substring(0, end_index)); return new FloatLiteral(pos(i), x, X10Parsersym.TK_FloatingPointLiteral); } catch (NumberFormatException e) { unrecoverableSyntaxError = true; eq.enqueue(ErrorInfo.LEXICAL_ERROR, "Illegal float literal \"" + prsStream.getName(i) + "\"", pos(i)); return null; } } private polyglot.lex.DoubleLiteral double_lit(int i) { try { String s = prsStream.getName(i); int end_index = (s.charAt(s.length() - 1) == 'd' || s.charAt(s.length() - 1) == 'D' ? s.length() - 1 : s.length()); double x = Double.parseDouble(s.substring(0, end_index)); return new DoubleLiteral(pos(i), x, X10Parsersym.TK_DoubleLiteral); } catch (NumberFormatException e) { unrecoverableSyntaxError = true; eq.enqueue(ErrorInfo.LEXICAL_ERROR, "Illegal float literal \"" + prsStream.getName(i) + "\"", pos(i)); return null; } } private polyglot.lex.CharacterLiteral char_lit(int i) { char x; String s = prsStream.getName(i); if (s.charAt(1) == '\\') { switch(s.charAt(2)) { case 'u': x = (char) parseLong(s.substring(3, s.length() - 1), 16); break; case 'b': x = '\b'; break; case 't': x = '\t'; break; case 'n': x = '\n'; break; case 'f': x = '\f'; break; case 'r': x = '\r'; break; case '\"': x = '\"'; break; case '\'': x = '\''; break; case '\\': x = '\\'; break; default: x = (char) parseLong(s.substring(2, s.length() - 1), 8); if (x > 255) { unrecoverableSyntaxError = true; eq.enqueue(ErrorInfo.LEXICAL_ERROR, "Illegal character literal " + s, pos(i)); } } } else { assert(s.length() == 3); x = s.charAt(1); } return new CharacterLiteral(pos(i), x, X10Parsersym.TK_CharacterLiteral); } private polyglot.lex.BooleanLiteral boolean_lit(int i) { return new BooleanLiteral(pos(i), prsStream.getKind(i) == X10Parsersym.TK_true, prsStream.getKind(i)); } private polyglot.lex.StringLiteral string_lit(int i) { String s = prsStream.getName(i); char x[] = new char[s.length()]; int j = 1, k = 0; while(j < s.length() - 1) { if (s.charAt(j) != '\\') x[k++] = s.charAt(j++); else { switch(s.charAt(j + 1)) { case 'u': x[k++] = (char) parseLong(s.substring(j + 2, j + 6), 16); j += 6; break; case 'b': x[k++] = '\b'; j += 2; break; case 't': x[k++] = '\t'; j += 2; break; case 'n': x[k++] = '\n'; j += 2; break; case 'f': x[k++] = '\f'; j += 2; break; case 'r': x[k++] = '\r'; j += 2; break; case '\"': x[k++] = '\"'; j += 2; break; case '\'': x[k++] = '\''; j += 2; break; case '`': x[k++] = '`'; j += 2; break; case '\\': x[k++] = '\\'; j += 2; break; default: { int n = j + 1; for (int l = 0; l < 3 && Character.isDigit(s.charAt(n)); l++) n++; char c = (char) parseLong(s.substring(j + 1, n), 8); if (c > 255) { unrecoverableSyntaxError = true; eq.enqueue(ErrorInfo.LEXICAL_ERROR, "Illegal character (" + s.substring(j, n) + ") in string literal " + s, pos(i)); } x[k++] = c; j = n; } } } } return new StringLiteral(pos(i), new String(x, 0, k), X10Parsersym.TK_StringLiteral); } private polyglot.lex.NullLiteral null_lit(int i) { return new NullLiteral(pos(i), X10Parsersym.TK_null); } // Production: ExpressionStatement ::= StatementExpression ';' void rule_ExpressionStatement0(Object _StatementExpression) { Expr StatementExpression = (Expr) _StatementExpression; setResult(nf.Eval(pos(), StatementExpression)); } // Production: ClosureExpression ::= FormalParameters WhereClauseopt HasResultTypeopt Offersopt '=>' ClosureBody void rule_ClosureExpression0(Object _FormalParameters, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _ClosureBody) { List<Formal> FormalParameters = (List<Formal>) _FormalParameters; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block ClosureBody = (Block) _ClosureBody; setResult(nf.Closure(pos(), FormalParameters, WhereClauseopt, HasResultTypeopt == null ? nf.UnknownTypeNode(pos()) : HasResultTypeopt, ClosureBody)); } // Production: PackageOrTypeName ::= PackageOrTypeName '.' ErrorId void rule_PackageOrTypeName0(Object _PackageOrTypeName) { ParsedName PackageOrTypeName = (ParsedName) _PackageOrTypeName; setResult(new ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), PackageOrTypeName, nf.Id(pos(getRightSpan()), "*"))); } // Production: PackageOrTypeName ::= Identifier void rule_PackageOrTypeName1(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(), Identifier)); } // Production: PackageOrTypeName ::= PackageOrTypeName '.' Identifier void rule_PackageOrTypeName2(Object _PackageOrTypeName, Object _Identifier) { ParsedName PackageOrTypeName = (ParsedName) _PackageOrTypeName; Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), PackageOrTypeName, Identifier)); } // Production: Property ::= Annotationsopt Identifier ResultType void rule_Property0(Object _Annotationsopt, Object _Identifier, Object _ResultType) { List<AnnotationNode> Annotationsopt = (List<AnnotationNode>) _Annotationsopt; Id Identifier = (Id) _Identifier; TypeNode ResultType = (TypeNode) _ResultType; List<AnnotationNode> annotations = extractAnnotations(Annotationsopt); PropertyDecl cd = nf.PropertyDecl(pos(), nf.FlagsNode(pos(), Flags.PUBLIC.Final()), ResultType, Identifier); cd = (PropertyDecl) ((X10Ext) cd.ext()).annotations(annotations); setResult(cd); } // Production: CastExpression ::= ExpressionName void rule_CastExpression1(Object _ExpressionName) { ParsedName ExpressionName = (ParsedName) _ExpressionName; setResult(ExpressionName.toExpr()); } // Production: CastExpression ::= CastExpression as Type void rule_CastExpression2(Object _CastExpression, Object _Type) { Expr CastExpression = (Expr) _CastExpression; TypeNode Type = (TypeNode) _Type; setResult(nf.X10Cast(pos(), Type, CastExpression)); } // Production: TypeParameter ::= Identifier void rule_TypeParameter0(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(nf.TypeParamNode(pos(), Identifier)); } // Production: FieldDeclarator ::= Identifier HasResultType void rule_FieldDeclarator0(Object _Identifier, Object _HasResultType) { Id Identifier = (Id) _Identifier; TypeNode HasResultType = (TypeNode) _HasResultType; setResult(new Object[] { pos(), Identifier, Collections.<Id>emptyList(), HasResultType, null }); } // Production: FieldDeclarator ::= Identifier HasResultTypeopt '=' VariableInitializer void rule_FieldDeclarator1(Object _Identifier, Object _HasResultTypeopt, Object _VariableInitializer) { Id Identifier = (Id) _Identifier; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; Expr VariableInitializer = (Expr) _VariableInitializer; setResult(new Object[] { pos(), Identifier, Collections.<Id>emptyList(), HasResultTypeopt, VariableInitializer }); } // Production: OperatorFunction ::= TypeName '.' '+' void rule_OperatorFunction0(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.ADD, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '-' void rule_OperatorFunction1(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.SUB, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '*' void rule_OperatorFunction2(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.MUL, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '/' void rule_OperatorFunction3(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.DIV, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '%' void rule_OperatorFunction4(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.MOD, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '&' void rule_OperatorFunction5(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.BIT_AND, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '|' void rule_OperatorFunction6(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.BIT_OR, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '^' void rule_OperatorFunction7(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.BIT_XOR, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '<<' void rule_OperatorFunction8(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.SHL, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '>>' void rule_OperatorFunction9(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.SHR, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '>>>' void rule_OperatorFunction10(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.USHR, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '<' void rule_OperatorFunction11(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.CanonicalTypeNode(pos(), ts.Boolean()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.LT, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '<=' void rule_OperatorFunction12(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.CanonicalTypeNode(pos(), ts.Boolean()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.LE, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '>=' void rule_OperatorFunction13(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.CanonicalTypeNode(pos(), ts.Boolean()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.GE, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '>' void rule_OperatorFunction14(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.CanonicalTypeNode(pos(), ts.Boolean()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.GT, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '==' void rule_OperatorFunction15(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.CanonicalTypeNode(pos(), ts.Boolean()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.EQ, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: OperatorFunction ::= TypeName '.' '!=' void rule_OperatorFunction16(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; List<Formal> formals = new ArrayList<Formal>(); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "x"))); formals.add(nf.Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), TypeName.toType(), nf.Id(pos(), "y"))); TypeNode tn = nf.CanonicalTypeNode(pos(), ts.Boolean()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.Binary(pos(), nf.Local(pos(), nf.Id(pos(), "x")), Binary.NE, nf.Local(pos(), nf.Id(pos(), "y"))), true)))); } // Production: AmbiguousName ::= AmbiguousName '.' ErrorId void rule_AmbiguousName0(Object _AmbiguousName) { ParsedName AmbiguousName = (ParsedName) _AmbiguousName; setResult(new ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), AmbiguousName, nf.Id(pos(getRightSpan()), "*"))); } // Production: AmbiguousName ::= Identifier void rule_AmbiguousName1(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(), Identifier)); } // Production: AmbiguousName ::= AmbiguousName '.' Identifier void rule_AmbiguousName2(Object _AmbiguousName, Object _Identifier) { ParsedName AmbiguousName = (ParsedName) _AmbiguousName; Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), AmbiguousName, Identifier)); } // Production: VariableDeclaratorWithType ::= Identifier HasResultType '=' VariableInitializer void rule_VariableDeclaratorWithType0(Object _Identifier, Object _HasResultType, Object _VariableInitializer) { Id Identifier = (Id) _Identifier; TypeNode HasResultType = (TypeNode) _HasResultType; Expr VariableInitializer = (Expr) _VariableInitializer; setResult(new Object[] { pos(), Identifier, Collections.<Id>emptyList(), null, HasResultType, VariableInitializer }); } // Production: VariableDeclaratorWithType ::= '[' IdentifierList ']' HasResultType '=' VariableInitializer void rule_VariableDeclaratorWithType1(Object _IdentifierList, Object _HasResultType, Object _VariableInitializer) { List<Id> IdentifierList = (List<Id>) _IdentifierList; TypeNode HasResultType = (TypeNode) _HasResultType; Expr VariableInitializer = (Expr) _VariableInitializer; setResult(new Object[] { pos(), null, IdentifierList, null, HasResultType, VariableInitializer }); } // Production: VariableDeclaratorWithType ::= Identifier '[' IdentifierList ']' HasResultType '=' VariableInitializer void rule_VariableDeclaratorWithType2(Object _Identifier, Object _IdentifierList, Object _HasResultType, Object _VariableInitializer) { Id Identifier = (Id) _Identifier; List<Id> IdentifierList = (List<Id>) _IdentifierList; TypeNode HasResultType = (TypeNode) _HasResultType; Expr VariableInitializer = (Expr) _VariableInitializer; setResult(new Object[] { pos(), Identifier, IdentifierList, null, HasResultType, VariableInitializer }); } // Production: Finally ::= finally Block void rule_Finally0(Object _Block) { Block Block = (Block) _Block; setResult(Block); } // Production: AnnotationStatement ::= Annotationsopt NonExpressionStatement void rule_AnnotationStatement0(Object _Annotationsopt, Object _NonExpressionStatement) { List<AnnotationNode> Annotationsopt = (List<AnnotationNode>) _Annotationsopt; Stmt NonExpressionStatement = (Stmt) _NonExpressionStatement; if (NonExpressionStatement.ext() instanceof X10Ext) { NonExpressionStatement = (Stmt) ((X10Ext) NonExpressionStatement.ext()).annotations(Annotationsopt); } setResult(NonExpressionStatement.position(pos())); } // Production: TypeDeclarations ::= TypeDeclaration void rule_TypeDeclarations0(Object _TypeDeclaration) { TopLevelDecl TypeDeclaration = (TopLevelDecl) _TypeDeclaration; List<TopLevelDecl> l = new TypedList<TopLevelDecl>(new LinkedList<TopLevelDecl>(), TopLevelDecl.class, false); if (TypeDeclaration != null) l.add(TypeDeclaration); setResult(l); } // Production: TypeDeclarations ::= TypeDeclarations TypeDeclaration void rule_TypeDeclarations1(Object _TypeDeclarations, Object _TypeDeclaration) { List<TopLevelDecl> TypeDeclarations = (List<TopLevelDecl>) _TypeDeclarations; TopLevelDecl TypeDeclaration = (TopLevelDecl) _TypeDeclaration; if (TypeDeclaration != null) TypeDeclarations.add(TypeDeclaration); //setResult(l); } // Production: IdentifierList ::= Identifier void rule_IdentifierList0(Object _Identifier) { Id Identifier = (Id) _Identifier; List<Id> l = new TypedList<Id>(new LinkedList<Id>(), Id.class, false); l.add(Identifier); setResult(l); } // Production: IdentifierList ::= IdentifierList ',' Identifier void rule_IdentifierList1(Object _IdentifierList, Object _Identifier) { List<Id> IdentifierList = (List<Id>) _IdentifierList; Id Identifier = (Id) _Identifier; IdentifierList.add(Identifier); } // Production: TypeImportOnDemandDeclaration ::= import PackageOrTypeName '.' '*' ';' void rule_TypeImportOnDemandDeclaration0(Object _PackageOrTypeName) { ParsedName PackageOrTypeName = (ParsedName) _PackageOrTypeName; setResult(nf.Import(pos(getLeftSpan(), getRightSpan()), Import.PACKAGE, QName.make(PackageOrTypeName.toString()))); } // Production: BreakStatement ::= break Identifieropt ';' void rule_BreakStatement0(Object _Identifieropt) { Id Identifieropt = (Id) _Identifieropt; setResult(nf.Break(pos(), Identifieropt)); } // Production: PlaceExpressionSingleList ::= '(' PlaceExpression ')' void rule_PlaceExpressionSingleList0(Object _PlaceExpression) { Expr PlaceExpression = (Expr) _PlaceExpression; setResult(PlaceExpression); } // Production: ConditionalOrExpression ::= ConditionalOrExpression '||' ConditionalAndExpression void rule_ConditionalOrExpression1(Object _ConditionalOrExpression, Object _ConditionalAndExpression) { Expr ConditionalOrExpression = (Expr) _ConditionalOrExpression; Expr ConditionalAndExpression = (Expr) _ConditionalAndExpression; setResult(nf.Binary(pos(), ConditionalOrExpression, Binary.COND_OR, ConditionalAndExpression)); } // Production: LocalVariableDeclaration ::= Modifiersopt VarKeyword VariableDeclarators void rule_LocalVariableDeclaration0(Object _Modifiersopt, Object _VarKeyword, Object _VariableDeclarators) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; List<FlagsNode> VarKeyword = (List<FlagsNode>) _VarKeyword; List<Object[]> VariableDeclarators = (List<Object[]>) _VariableDeclarators; List<Node> modifiers = checkVariableModifiers(Modifiersopt); FlagsNode fn = VarKeyword==null ? extractFlags(modifiers, Flags.FINAL) : extractFlags(modifiers, VarKeyword); List<LocalDecl> l = new TypedList<LocalDecl>(new LinkedList<LocalDecl>(), LocalDecl.class, false); for (Object[] o : VariableDeclarators) { Position pos = (Position) o[0]; Position compilerGen = pos.markCompilerGenerated(); Id name = (Id) o[1]; if (name == null) name = nf.Id(pos, Name.makeFresh()); List<Id> exploded = (List<Id>) o[2]; DepParameterExpr guard = (DepParameterExpr) o[3]; TypeNode type = (TypeNode) o[4]; if (type == null) type = nf.UnknownTypeNode(name != null ? name.position() : pos); Expr init = (Expr) o[5]; LocalDecl ld = nf.LocalDecl(pos, fn, type, name, init, exploded); ld = (LocalDecl) ((X10Ext) ld.ext()).annotations(extractAnnotations(modifiers)); int index = 0; l.add(ld); if (exploded.size()>0 && init==null) { syntaxError("An exploded point must have an initializer.",pos); } for (Id id : exploded) { TypeNode tni = init==null ? nf.TypeNodeFromQualifiedName(compilerGen,QName.make("x10.lang.Int")) : // we infer the type of the exploded components, however if there is no init, then we just assume Int to avoid cascading errors. explodedType(id.position()); // UnknownType l.add(nf.LocalDecl(id.position(), fn, tni, id, init != null ? nf.ClosureCall(compilerGen, nf.Local(compilerGen, name), Collections.<Expr>singletonList(nf.IntLit(compilerGen, IntLit.INT, index))) : null)); index++; } } setResult(l); } // Production: LocalVariableDeclaration ::= Modifiersopt VariableDeclaratorsWithType void rule_LocalVariableDeclaration1(Object _Modifiersopt, Object _VariableDeclaratorsWithType) { rule_LocalVariableDeclaration0(_Modifiersopt,null, _VariableDeclaratorsWithType); } // Production: LocalVariableDeclaration ::= Modifiersopt VarKeyword FormalDeclarators void rule_LocalVariableDeclaration2(Object _Modifiersopt, Object _VarKeyword, Object _FormalDeclarators) { rule_LocalVariableDeclaration0(_Modifiersopt,_VarKeyword, _FormalDeclarators); } // Production: InterfaceMemberDeclarationsopt ::= %Empty void rule_InterfaceMemberDeclarationsopt0() { setResult(new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false)); } // Production: InterfaceTypeList ::= Type void rule_InterfaceTypeList0(Object _Type) { TypeNode Type = (TypeNode) _Type; List<TypeNode> l = new TypedList<TypeNode>(new LinkedList<TypeNode>(), TypeNode.class, false); l.add(Type); setResult(l); } // Production: InterfaceTypeList ::= InterfaceTypeList ',' Type void rule_InterfaceTypeList1(Object _InterfaceTypeList, Object _Type) { List<TypeNode> InterfaceTypeList = (List<TypeNode>) _InterfaceTypeList; TypeNode Type = (TypeNode) _Type; InterfaceTypeList.add(Type); setResult(InterfaceTypeList); } // Production: AtomicStatement ::= atomic Statement void rule_AtomicStatement0(Object _Statement) { Stmt Statement = (Stmt) _Statement; setResult(nf.Atomic(pos(), nf.Here(pos(getLeftSpan())), Statement)); } // Production: PackageName ::= PackageName '.' ErrorId void rule_PackageName0(Object _PackageName) { ParsedName PackageName = (ParsedName) _PackageName; setResult(new ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), PackageName, nf.Id(pos(getRightSpan()), "*"))); } // Production: PackageName ::= Identifier void rule_PackageName1(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(), Identifier)); } // Production: PackageName ::= PackageName '.' Identifier void rule_PackageName2(Object _PackageName, Object _Identifier) { ParsedName PackageName = (ParsedName) _PackageName; Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), PackageName, Identifier)); } // Production: RelationalExpression ::= RelationalExpression '<' ShiftExpression void rule_RelationalExpression3(Object _RelationalExpression, Object _ShiftExpression) { Expr RelationalExpression = (Expr) _RelationalExpression; Expr ShiftExpression = (Expr) _ShiftExpression; setResult(nf.Binary(pos(), RelationalExpression, Binary.LT, ShiftExpression)); } // Production: RelationalExpression ::= RelationalExpression '>' ShiftExpression void rule_RelationalExpression4(Object _RelationalExpression, Object _ShiftExpression) { Expr RelationalExpression = (Expr) _RelationalExpression; Expr ShiftExpression = (Expr) _ShiftExpression; setResult(nf.Binary(pos(), RelationalExpression, Binary.GT, ShiftExpression)); } // Production: RelationalExpression ::= RelationalExpression '<=' ShiftExpression void rule_RelationalExpression5(Object _RelationalExpression, Object _ShiftExpression) { Expr RelationalExpression = (Expr) _RelationalExpression; Expr ShiftExpression = (Expr) _ShiftExpression; setResult(nf.Binary(pos(), RelationalExpression, Binary.LE, ShiftExpression)); } // Production: RelationalExpression ::= RelationalExpression '>=' ShiftExpression void rule_RelationalExpression6(Object _RelationalExpression, Object _ShiftExpression) { Expr RelationalExpression = (Expr) _RelationalExpression; Expr ShiftExpression = (Expr) _ShiftExpression; setResult(nf.Binary(pos(), RelationalExpression, Binary.GE, ShiftExpression)); } // Production: RelationalExpression ::= RelationalExpression instanceof Type void rule_RelationalExpression7(Object _RelationalExpression, Object _Type) { Expr RelationalExpression = (Expr) _RelationalExpression; TypeNode Type = (TypeNode) _Type; setResult(nf.Instanceof(pos(), RelationalExpression, Type)); } // Production: RelationalExpression ::= RelationalExpression in ShiftExpression void rule_RelationalExpression8(Object _RelationalExpression, Object _ShiftExpression) { Expr RelationalExpression = (Expr) _RelationalExpression; Expr ShiftExpression = (Expr) _ShiftExpression; setResult(nf.Binary(pos(), RelationalExpression, Binary.IN, ShiftExpression)); } // Production: BlockStatement ::= ClassDeclaration void rule_BlockStatement1(Object _ClassDeclaration) { ClassDecl ClassDeclaration = (ClassDecl) _ClassDeclaration; List<Stmt> l = new TypedList<Stmt>(new LinkedList<Stmt>(), Stmt.class, false); l.add(nf.LocalClassDecl(pos(), ClassDeclaration)); setResult(l); } // Production: BlockStatement ::= TypeDefDeclaration void rule_BlockStatement2(Object _TypeDefDeclaration) { TypeDecl TypeDefDeclaration = (TypeDecl) _TypeDefDeclaration; List<Stmt> l = new TypedList<Stmt>(new LinkedList<Stmt>(), Stmt.class, false); l.add(nf.LocalTypeDef(pos(), TypeDefDeclaration)); setResult(l); } // Production: BlockStatement ::= Statement void rule_BlockStatement3(Object _Statement) { Stmt Statement = (Stmt) _Statement; List<Stmt> l = new TypedList<Stmt>(new LinkedList<Stmt>(), Stmt.class, false); l.add(Statement); setResult(l); } // Production: UnaryExpression ::= Annotations UnannotatedUnaryExpression void rule_UnaryExpression1(Object _Annotations, Object _UnannotatedUnaryExpression) { List<AnnotationNode> Annotations = (List<AnnotationNode>) _Annotations; Expr UnannotatedUnaryExpression = (Expr) _UnannotatedUnaryExpression; Expr e = UnannotatedUnaryExpression; e = (Expr) ((X10Ext) e.ext()).annotations(Annotations); setResult(e.position(pos())); } // Production: ExclusiveOrExpression ::= ExclusiveOrExpression '^' AndExpression void rule_ExclusiveOrExpression1(Object _ExclusiveOrExpression, Object _AndExpression) { Expr ExclusiveOrExpression = (Expr) _ExclusiveOrExpression; Expr AndExpression = (Expr) _AndExpression; setResult(nf.Binary(pos(), ExclusiveOrExpression, Binary.BIT_XOR, AndExpression)); } // Production: ClockedClauseopt ::= %Empty void rule_ClockedClauseopt0() { setResult(new TypedList<Expr>(new LinkedList<Expr>(), Expr.class, false)); } // Production: AdditiveExpression ::= AdditiveExpression '+' MultiplicativeExpression void rule_AdditiveExpression1(Object _AdditiveExpression, Object _MultiplicativeExpression) { Expr AdditiveExpression = (Expr) _AdditiveExpression; Expr MultiplicativeExpression = (Expr) _MultiplicativeExpression; setResult(nf.Binary(pos(), AdditiveExpression, Binary.ADD, MultiplicativeExpression)); } // Production: AdditiveExpression ::= AdditiveExpression '-' MultiplicativeExpression void rule_AdditiveExpression2(Object _AdditiveExpression, Object _MultiplicativeExpression) { Expr AdditiveExpression = (Expr) _AdditiveExpression; Expr MultiplicativeExpression = (Expr) _MultiplicativeExpression; setResult(nf.Binary(pos(), AdditiveExpression, Binary.SUB, MultiplicativeExpression)); } // Production: AssignPropertyCall ::= property TypeArgumentsopt '(' ArgumentListopt ')' ';' void rule_AssignPropertyCall0(Object _TypeArgumentsopt, Object _ArgumentListopt) { List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; setResult(nf.AssignPropertyCall(pos(), TypeArgumentsopt, ArgumentListopt)); } // Production: ClosureBody ::= ConditionalExpression void rule_ClosureBody0(Object _ConditionalExpression) { Expr ConditionalExpression = (Expr) _ConditionalExpression; setResult(nf.Block(pos(), nf.X10Return(pos(), ConditionalExpression, true))); } // Production: ClosureBody ::= Annotationsopt '{' BlockStatementsopt LastExpression '}' void rule_ClosureBody1(Object _Annotationsopt, Object _BlockStatementsopt, Object _LastExpression) { List<AnnotationNode> Annotationsopt = (List<AnnotationNode>) _Annotationsopt; List<Stmt> BlockStatementsopt = (List<Stmt>) _BlockStatementsopt; Stmt LastExpression = (Stmt) _LastExpression; List<Stmt> l = new ArrayList<Stmt>(); l.addAll(BlockStatementsopt); l.add(LastExpression); Block b = nf.Block(pos(), l); b = (Block) ((X10Ext) b.ext()).annotations(Annotationsopt); setResult(b); } // Production: ClosureBody ::= Annotationsopt Block void rule_ClosureBody2(Object _Annotationsopt, Object _Block) { List<AnnotationNode> Annotationsopt = (List<AnnotationNode>) _Annotationsopt; Block Block = (Block) _Block; Block b = Block; b = (Block) ((X10Ext) b.ext()).annotations(Annotationsopt); setResult(b.position(pos())); } // Production: MultiplicativeExpression ::= MultiplicativeExpression '*' RangeExpression void rule_MultiplicativeExpression1(Object _MultiplicativeExpression, Object _RangeExpression) { Expr MultiplicativeExpression = (Expr) _MultiplicativeExpression; Expr RangeExpression = (Expr) _RangeExpression; setResult(nf.Binary(pos(), MultiplicativeExpression, Binary.MUL, RangeExpression)); } // Production: MultiplicativeExpression ::= MultiplicativeExpression '/' RangeExpression void rule_MultiplicativeExpression2(Object _MultiplicativeExpression, Object _RangeExpression) { Expr MultiplicativeExpression = (Expr) _MultiplicativeExpression; Expr RangeExpression = (Expr) _RangeExpression; setResult(nf.Binary(pos(), MultiplicativeExpression, Binary.DIV, RangeExpression)); } // Production: MultiplicativeExpression ::= MultiplicativeExpression '%' RangeExpression void rule_MultiplicativeExpression3(Object _MultiplicativeExpression, Object _RangeExpression) { Expr MultiplicativeExpression = (Expr) _MultiplicativeExpression; Expr RangeExpression = (Expr) _RangeExpression; setResult(nf.Binary(pos(), MultiplicativeExpression, Binary.MOD, RangeExpression)); } // Production: TryStatement ::= try Block Catches void rule_TryStatement0(Object _Block, Object _Catches) { Block Block = (Block) _Block; List<Catch> Catches = (List<Catch>) _Catches; setResult(nf.Try(pos(), Block, Catches)); } // Production: TryStatement ::= try Block Catchesopt Finally void rule_TryStatement1(Object _Block, Object _Catchesopt, Object _Finally) { Block Block = (Block) _Block; List<Catch> Catchesopt = (List<Catch>) _Catchesopt; Block Finally = (Block) _Finally; setResult(nf.Try(pos(), Block, Catchesopt, Finally)); } // Production: FormalParameterList ::= FormalParameter void rule_FormalParameterList0(Object _FormalParameter) { X10Formal FormalParameter = (X10Formal) _FormalParameter; List<Formal> l = new TypedList<Formal>(new LinkedList<Formal>(), Formal.class, false); l.add(FormalParameter); setResult(l); } // Production: FormalParameterList ::= FormalParameterList ',' FormalParameter void rule_FormalParameterList1(Object _FormalParameterList, Object _FormalParameter) { List<Formal> FormalParameterList = (List<Formal>) _FormalParameterList; X10Formal FormalParameter = (X10Formal) _FormalParameter; FormalParameterList.add(FormalParameter); } // Production: SwitchBlock ::= '{' SwitchBlockStatementGroupsopt SwitchLabelsopt '}' void rule_SwitchBlock0(Object _SwitchBlockStatementGroupsopt, Object _SwitchLabelsopt) { List<Stmt> SwitchBlockStatementGroupsopt = (List<Stmt>) _SwitchBlockStatementGroupsopt; List<Case> SwitchLabelsopt = (List<Case>) _SwitchLabelsopt; SwitchBlockStatementGroupsopt.addAll(SwitchLabelsopt); setResult(SwitchBlockStatementGroupsopt); } // Production: UnannotatedUnaryExpression ::= '+' UnaryExpressionNotPlusMinus void rule_UnannotatedUnaryExpression2(Object _UnaryExpressionNotPlusMinus) { Expr UnaryExpressionNotPlusMinus = (Expr) _UnaryExpressionNotPlusMinus; setResult(nf.Unary(pos(), Unary.POS, UnaryExpressionNotPlusMinus)); } // Production: UnannotatedUnaryExpression ::= '-' UnaryExpressionNotPlusMinus void rule_UnannotatedUnaryExpression3(Object _UnaryExpressionNotPlusMinus) { Expr UnaryExpressionNotPlusMinus = (Expr) _UnaryExpressionNotPlusMinus; setResult(nf.Unary(pos(), Unary.NEG, UnaryExpressionNotPlusMinus)); } // Production: VariableDeclarator ::= Identifier HasResultTypeopt '=' VariableInitializer void rule_VariableDeclarator0(Object _Identifier, Object _HasResultTypeopt, Object _VariableInitializer) { Id Identifier = (Id) _Identifier; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; Expr VariableInitializer = (Expr) _VariableInitializer; setResult(new Object[] { pos(), Identifier, Collections.<Id>emptyList(), null, HasResultTypeopt, VariableInitializer }); } // Production: VariableDeclarator ::= '[' IdentifierList ']' HasResultTypeopt '=' VariableInitializer void rule_VariableDeclarator1(Object _IdentifierList, Object _HasResultTypeopt, Object _VariableInitializer) { List<Id> IdentifierList = (List<Id>) _IdentifierList; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; Expr VariableInitializer = (Expr) _VariableInitializer; setResult(new Object[] { pos(), null, IdentifierList, null, HasResultTypeopt, VariableInitializer }); } // Production: VariableDeclarator ::= Identifier '[' IdentifierList ']' HasResultTypeopt '=' VariableInitializer void rule_VariableDeclarator2(Object _Identifier, Object _IdentifierList, Object _HasResultTypeopt, Object _VariableInitializer) { Id Identifier = (Id) _Identifier; List<Id> IdentifierList = (List<Id>) _IdentifierList; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; Expr VariableInitializer = (Expr) _VariableInitializer; setResult(new Object[] { pos(), Identifier, IdentifierList, null, HasResultTypeopt, VariableInitializer }); } // Production: TypeParamWithVarianceList ::= TypeParamWithVariance void rule_TypeParamWithVarianceList0(Object _TypeParamWithVariance) { TypeParamNode TypeParamWithVariance = (TypeParamNode) _TypeParamWithVariance; List<TypeParamNode> l = new TypedList<TypeParamNode>(new LinkedList<TypeParamNode>(), TypeParamNode.class, false); l.add(TypeParamWithVariance); setResult(l); } // Production: TypeParamWithVarianceList ::= TypeParamWithVarianceList ',' TypeParamWithVariance void rule_TypeParamWithVarianceList1(Object _TypeParamWithVarianceList, Object _TypeParamWithVariance) { List<TypeParamNode> TypeParamWithVarianceList = (List<TypeParamNode>) _TypeParamWithVarianceList; TypeParamNode TypeParamWithVariance = (TypeParamNode) _TypeParamWithVariance; TypeParamWithVarianceList.add(TypeParamWithVariance); setResult(TypeParamWithVarianceList); } // Production: UnaryExpressionNotPlusMinus ::= '~' UnaryExpression void rule_UnaryExpressionNotPlusMinus1(Object _UnaryExpression) { Expr UnaryExpression = (Expr) _UnaryExpression; setResult(nf.Unary(pos(), Unary.BIT_NOT, UnaryExpression)); } // Production: UnaryExpressionNotPlusMinus ::= '!' UnaryExpression void rule_UnaryExpressionNotPlusMinus2(Object _UnaryExpression) { Expr UnaryExpression = (Expr) _UnaryExpression; setResult(nf.Unary(pos(), Unary.NOT, UnaryExpression)); } // Production: Interfacesopt ::= %Empty void rule_Interfacesopt0() { setResult(new TypedList<TypeNode>(new LinkedList<TypeNode>(), TypeNode.class, false)); } // Production: ConditionalExpression ::= ConditionalOrExpression '?' Expression ':' ConditionalExpression void rule_ConditionalExpression4(Object _ConditionalOrExpression, Object _Expression, Object _ConditionalExpression) { Expr ConditionalOrExpression = (Expr) _ConditionalOrExpression; Expr Expression = (Expr) _Expression; Expr ConditionalExpression = (Expr) _ConditionalExpression; setResult(nf.Conditional(pos(), ConditionalOrExpression, Expression, ConditionalExpression)); } // Production: SwitchLabel ::= case ConstantExpression ':' void rule_SwitchLabel0(Object _ConstantExpression) { Expr ConstantExpression = (Expr) _ConstantExpression; setResult(nf.Case(pos(), ConstantExpression)); } // Production: SwitchLabel ::= default ':' void rule_SwitchLabel1() { setResult(nf.Default(pos())); } // Production: MethodSuperPrefix ::= super '.' ErrorId void rule_MethodSuperPrefix0() { setResult(id(getRhsFirstTokenIndex(3))); } // Production: VariableDeclarators ::= VariableDeclarator void rule_VariableDeclarators0(Object _VariableDeclarator) { Object[] VariableDeclarator = (Object[]) _VariableDeclarator; List<Object[]> l = new TypedList<Object[]>(new LinkedList<Object[]>(), Object[].class, false); l.add(VariableDeclarator); setResult(l); } // Production: VariableDeclarators ::= VariableDeclarators ',' VariableDeclarator void rule_VariableDeclarators1(Object _VariableDeclarators, Object _VariableDeclarator) { List<Object[]> VariableDeclarators = (List<Object[]>) _VariableDeclarators; Object[] VariableDeclarator = (Object[]) _VariableDeclarator; VariableDeclarators.add(VariableDeclarator); // setResult(VariableDeclarators); } // Production: BlockStatementsopt ::= %Empty void rule_BlockStatementsopt0() { setResult(new TypedList<Stmt>(new LinkedList<Stmt>(), Stmt.class, false)); } // Production: BlockStatements ::= BlockStatement void rule_BlockStatements0(Object _BlockStatement) { List<Stmt> BlockStatement = (List<Stmt>) _BlockStatement; List<Stmt> l = new TypedList<Stmt>(new LinkedList<Stmt>(), Stmt.class, false); l.addAll(BlockStatement); setResult(l); } // Production: BlockStatements ::= BlockStatements BlockStatement void rule_BlockStatements1(Object _BlockStatements, Object _BlockStatement) { List<Stmt> BlockStatements = (List<Stmt>) _BlockStatements; List<Stmt> BlockStatement = (List<Stmt>) _BlockStatement; BlockStatements.addAll(BlockStatement); //setResult(l); } // Production: TypeParameterList ::= TypeParameter void rule_TypeParameterList0(Object _TypeParameter) { TypeParamNode TypeParameter = (TypeParamNode) _TypeParameter; List<TypeParamNode> l = new TypedList<TypeParamNode>(new LinkedList<TypeParamNode>(), TypeParamNode.class, false); l.add(TypeParameter); setResult(l); } // Production: TypeParameterList ::= TypeParameterList ',' TypeParameter void rule_TypeParameterList1(Object _TypeParameterList, Object _TypeParameter) { List<TypeParamNode> TypeParameterList = (List<TypeParamNode>) _TypeParameterList; TypeParamNode TypeParameter = (TypeParamNode) _TypeParameter; TypeParameterList.add(TypeParameter); setResult(TypeParameterList); } // Production: TypeParamWithVariance ::= Identifier void rule_TypeParamWithVariance0(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(nf.TypeParamNode(pos(), Identifier, ParameterType.Variance.INVARIANT)); } // Production: TypeParamWithVariance ::= '+' Identifier void rule_TypeParamWithVariance1(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(nf.TypeParamNode(pos(), Identifier, ParameterType.Variance.COVARIANT)); } // Production: TypeParamWithVariance ::= '-' Identifier void rule_TypeParamWithVariance2(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(nf.TypeParamNode(pos(), Identifier, ParameterType.Variance.CONTRAVARIANT)); } // Production: VariableDeclaratorsWithType ::= VariableDeclaratorWithType void rule_VariableDeclaratorsWithType0(Object _VariableDeclaratorWithType) { Object[] VariableDeclaratorWithType = (Object[]) _VariableDeclaratorWithType; List<Object[]> l = new TypedList<Object[]>(new LinkedList<Object[]>(), Object[].class, false); l.add(VariableDeclaratorWithType); setResult(l); } // Production: VariableDeclaratorsWithType ::= VariableDeclaratorsWithType ',' VariableDeclaratorWithType void rule_VariableDeclaratorsWithType1(Object _VariableDeclaratorsWithType, Object _VariableDeclaratorWithType) { List<Object[]> VariableDeclaratorsWithType = (List<Object[]>) _VariableDeclaratorsWithType; Object[] VariableDeclaratorWithType = (Object[]) _VariableDeclaratorWithType; VariableDeclaratorsWithType.add(VariableDeclaratorWithType); // setResult(VariableDeclaratorsWithType); } // Production: Block ::= '{' BlockStatementsopt '}' void rule_Block0(Object _BlockStatementsopt) { List<Stmt> BlockStatementsopt = (List<Stmt>) _BlockStatementsopt; setResult(nf.Block(pos(), BlockStatementsopt)); } // Production: ResultType ::= ':' Type void rule_ResultType0(Object _Type) { TypeNode Type = (TypeNode) _Type; setResult(Type); } // Production: MethodSelection ::= MethodName '.' '(' FormalParameterListopt ')' void rule_MethodSelection0(Object _MethodName, Object _FormalParameterListopt) { ParsedName MethodName = (ParsedName) _MethodName; List<Formal> FormalParameterListopt = (List<Formal>) _FormalParameterListopt; // List<TypeNode> typeArgs = toTypeArgs(TypeParametersopt); // List<TypeParamNode> typeParams = toTypeParams(TypeParametersopt); List<Formal> formals = toFormals(FormalParameterListopt); List<Expr> actuals = toActuals(FormalParameterListopt); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.X10Call(pos(), MethodName.prefix == null ? null : MethodName.prefix.toReceiver(), MethodName.name, Collections.<TypeNode>emptyList(), actuals), true)))); } // Production: MethodSelection ::= Primary '.' Identifier '.' '(' FormalParameterListopt ')' void rule_MethodSelection1(Object _Primary, Object _Identifier, Object _FormalParameterListopt) { Expr Primary = (Expr) _Primary; Id Identifier = (Id) _Identifier; List<Formal> FormalParameterListopt = (List<Formal>) _FormalParameterListopt; // List<TypeNode> typeArgs = toTypeArgs(TypeParametersopt); // List<TypeParamNode> typeParams = toTypeParams(TypeParametersopt); List<Formal> formals = toFormals(FormalParameterListopt); List<Expr> actuals = toActuals(FormalParameterListopt); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.X10Call(pos(), Primary, Identifier, Collections.<TypeNode>emptyList(), actuals), true)))); } // Production: MethodSelection ::= super '.' Identifier '.' '(' FormalParameterListopt ')' void rule_MethodSelection2(Object _Identifier, Object _FormalParameterListopt) { Id Identifier = (Id) _Identifier; List<Formal> FormalParameterListopt = (List<Formal>) _FormalParameterListopt; // List<TypeNode> typeArgs = toTypeArgs(TypeParametersopt); // List<TypeParamNode> typeParams = toTypeParams(TypeParametersopt); List<Formal> formals = toFormals(FormalParameterListopt); List<Expr> actuals = toActuals(FormalParameterListopt); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.X10Call(pos(), nf.Super(pos(getLeftSpan())), Identifier, Collections.<TypeNode>emptyList(), actuals), true)))); } // Production: MethodSelection ::= ClassName '.' super '.' Identifier '.' '(' FormalParameterListopt ')' void rule_MethodSelection3(Object _ClassName, Object _Identifier, Object _FormalParameterListopt) { ParsedName ClassName = (ParsedName) _ClassName; Id Identifier = (Id) _Identifier; List<Formal> FormalParameterListopt = (List<Formal>) _FormalParameterListopt; // List<TypeNode> typeArgs = toTypeArgs(TypeParametersopt); // List<TypeParamNode> typeParams = toTypeParams(TypeParametersopt); List<Formal> formals = toFormals(FormalParameterListopt); List<Expr> actuals = toActuals(FormalParameterListopt); TypeNode tn = nf.UnknownTypeNode(pos()); setResult(nf.Closure(pos(), formals, (DepParameterExpr) null, tn, nf.Block(pos(), nf.X10Return(pos(), nf.X10Call(pos(), nf.Super(pos(getRhsFirstTokenIndex(3)), ClassName.toType()), Identifier, Collections.<TypeNode>emptyList(), actuals), true)))); } // Production: FunctionType ::= TypeParametersopt '(' FormalParameterListopt ')' WhereClauseopt Offersopt '=>' Type void rule_FunctionType0(Object _TypeParametersopt, Object _FormalParameterListopt, Object _WhereClauseopt, Object _Offersopt, Object _Type) { List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; List<Formal> FormalParameterListopt = (List<Formal>) _FormalParameterListopt; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode Offersopt = (TypeNode) _Offersopt; TypeNode Type = (TypeNode) _Type; setResult(nf.FunctionTypeNode(pos(), TypeParametersopt, FormalParameterListopt, WhereClauseopt, Type, Offersopt)); } // Production: Conjunction ::= Expression void rule_Conjunction0(Object _Expression) { Expr Expression = (Expr) _Expression; List<Expr> l = new ArrayList<Expr>(); l.add(Expression); setResult(l); } // Production: Conjunction ::= Conjunction ',' Expression void rule_Conjunction1(Object _Conjunction, Object _Expression) { List<Expr> Conjunction = (List<Expr>) _Conjunction; Expr Expression = (Expr) _Expression; Conjunction.add(Expression); } // Production: TypeParamsWithVariance ::= '[' TypeParamWithVarianceList ']' void rule_TypeParamsWithVariance0(Object _TypeParamWithVarianceList) { List<TypeParamNode> TypeParamWithVarianceList = (List<TypeParamNode>) _TypeParamWithVarianceList; setResult(TypeParamWithVarianceList); } // Production: HasZeroConstraint ::= Type haszero void rule_HasZeroConstraint0(Object _t1) { TypeNode t1 = (TypeNode) _t1; setResult(nf.HasZeroTest(pos(), t1)); } // Production: ExistentialListopt ::= %Empty void rule_ExistentialListopt0() { setResult(new ArrayList<Formal>()); } // Production: ExistentialListopt ::= ExistentialList ';' void rule_ExistentialListopt1(Object _ExistentialList) { List<Formal> ExistentialList = (List<Formal>) _ExistentialList; setResult(ExistentialList); } // Production: Annotation ::= '@' NamedType void rule_Annotation0(Object _NamedType) { TypeNode NamedType = (TypeNode) _NamedType; setResult(nf.AnnotationNode(pos(), NamedType)); } // Production: BinOp ::= '+' void rule_BinOp0() { setResult(Binary.ADD); } // Production: BinOp ::= '-' void rule_BinOp1() { setResult(Binary.SUB); } // Production: BinOp ::= '*' void rule_BinOp2() { setResult(Binary.MUL); } // Production: BinOp ::= '/' void rule_BinOp3() { setResult(Binary.DIV); } // Production: BinOp ::= '%' void rule_BinOp4() { setResult(Binary.MOD); } // Production: BinOp ::= '&' void rule_BinOp5() { setResult(Binary.BIT_AND); } // Production: BinOp ::= '|' void rule_BinOp6() { setResult(Binary.BIT_OR); } // Production: BinOp ::= '^' void rule_BinOp7() { setResult(Binary.BIT_XOR); } // Production: BinOp ::= '&&' void rule_BinOp8() { setResult(Binary.COND_AND); } // Production: BinOp ::= '||' void rule_BinOp9() { setResult(Binary.COND_OR); } // Production: BinOp ::= '<<' void rule_BinOp10() { setResult(Binary.SHL); } // Production: BinOp ::= '>>' void rule_BinOp11() { setResult(Binary.SHR); } // Production: BinOp ::= '>>>' void rule_BinOp12() { setResult(Binary.USHR); } // Production: BinOp ::= '>=' void rule_BinOp13() { setResult(Binary.GE); } // Production: BinOp ::= '<=' void rule_BinOp14() { setResult(Binary.LE); } // Production: BinOp ::= '>' void rule_BinOp15() { setResult(Binary.GT); } // Production: BinOp ::= '<' void rule_BinOp16() { setResult(Binary.LT); } // Production: BinOp ::= '==' void rule_BinOp17() { setResult(Binary.EQ); } // Production: BinOp ::= '!=' void rule_BinOp18() { setResult(Binary.NE); } // Production: BinOp ::= '..' void rule_BinOp19() { setResult(Binary.DOT_DOT); } // Production: BinOp ::= '->' void rule_BinOp20() { setResult(Binary.ARROW); } // Production: BinOp ::= 'in' void rule_BinOp21() { setResult(Binary.IN); } // Production: EqualityExpression ::= EqualityExpression '==' RelationalExpression void rule_EqualityExpression1(Object _EqualityExpression, Object _RelationalExpression) { Expr EqualityExpression = (Expr) _EqualityExpression; Expr RelationalExpression = (Expr) _RelationalExpression; setResult(nf.Binary(pos(), EqualityExpression, Binary.EQ, RelationalExpression)); } // Production: EqualityExpression ::= EqualityExpression '!=' RelationalExpression void rule_EqualityExpression2(Object _EqualityExpression, Object _RelationalExpression) { Expr EqualityExpression = (Expr) _EqualityExpression; Expr RelationalExpression = (Expr) _RelationalExpression; setResult(nf.Binary(pos(), EqualityExpression, Binary.NE, RelationalExpression)); } // Production: EqualityExpression ::= Type '==' Type void rule_EqualityExpression3(Object _t1, Object _t2) { TypeNode t1 = (TypeNode) _t1; TypeNode t2 = (TypeNode) _t2; setResult(nf.SubtypeTest(pos(), t1, t2, true)); } // Production: Modifiersopt ::= %Empty void rule_Modifiersopt0() { setResult(new LinkedList<Modifier>()); } // Production: Modifiersopt ::= Modifiersopt Modifier void rule_Modifiersopt1(Object _Modifiersopt, Object _Modifier) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; Modifier Modifier = (Modifier) _Modifier; Modifiersopt.add(Modifier); } // Production: BooleanLiteral ::= true void rule_BooleanLiteral0() { setResult(boolean_lit(getRhsFirstTokenIndex(1))); } // Production: BooleanLiteral ::= false void rule_BooleanLiteral1() { setResult(boolean_lit(getRhsFirstTokenIndex(1))); } // Production: ArgumentList ::= Expression void rule_ArgumentList0(Object _Expression) { Expr Expression = (Expr) _Expression; List<Expr> l = new TypedList<Expr>(new LinkedList<Expr>(), Expr.class, false); l.add(Expression); setResult(l); } // Production: ArgumentList ::= ArgumentList ',' Expression void rule_ArgumentList1(Object _ArgumentList, Object _Expression) { List<Expr> ArgumentList = (List<Expr>) _ArgumentList; Expr Expression = (Expr) _Expression; ArgumentList.add(Expression); } // Production: FormalParametersopt ::= %Empty void rule_FormalParametersopt0() { setResult(new TypedList<Formal>(new LinkedList<Formal>(), Formal.class, false)); } // Production: ExtendsInterfacesopt ::= %Empty void rule_ExtendsInterfacesopt0() { setResult(new TypedList<TypeNode>(new LinkedList<TypeNode>(), TypeNode.class, false)); } // Production: Primary ::= here void rule_Primary0() { setResult(((NodeFactory) nf).Here(pos())); } // Production: Primary ::= '[' ArgumentListopt ']' void rule_Primary1(Object _ArgumentListopt) { List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; Tuple tuple = nf.Tuple(pos(), ArgumentListopt); setResult(tuple); } // Production: Primary ::= self void rule_Primary3() { setResult(nf.Self(pos())); } // Production: Primary ::= this void rule_Primary4() { setResult(nf.This(pos())); } // Production: Primary ::= ClassName '.' this void rule_Primary5(Object _ClassName) { ParsedName ClassName = (ParsedName) _ClassName; setResult(nf.This(pos(), ClassName.toType())); } // Production: Primary ::= '(' Expression ')' void rule_Primary6(Object _Expression) { Expr Expression = (Expr) _Expression; setResult(nf.ParExpr(pos(), Expression)); } // Production: FormalDeclarators ::= FormalDeclarator void rule_FormalDeclarators0(Object _FormalDeclarator) { Object[] FormalDeclarator = (Object[]) _FormalDeclarator; List<Object[]> l = new TypedList<Object[]>(new LinkedList<Object[]>(), Object[].class, false); l.add(FormalDeclarator); setResult(l); } // Production: FormalDeclarators ::= FormalDeclarators ',' FormalDeclarator void rule_FormalDeclarators1(Object _FormalDeclarators, Object _FormalDeclarator) { List<Object[]> FormalDeclarators = (List<Object[]>) _FormalDeclarators; Object[] FormalDeclarator = (Object[]) _FormalDeclarator; FormalDeclarators.add(FormalDeclarator); } // Production: SingleTypeImportDeclaration ::= import TypeName ';' void rule_SingleTypeImportDeclaration0(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; setResult(nf.Import(pos(getLeftSpan(), getRightSpan()), Import.CLASS, QName.make(TypeName.toString()))); } // Production: RangeExpression ::= RangeExpression '..' UnaryExpression void rule_RangeExpression1(Object _expr1, Object _expr2) { Expr expr1 = (Expr) _expr1; Expr expr2 = (Expr) _expr2; Expr regionCall = nf.Binary(pos(), expr1, Binary.DOT_DOT, expr2); setResult(regionCall); } // Production: DepNamedType ::= SimpleNamedType DepParameters void rule_DepNamedType0(Object _SimpleNamedType, Object _DepParameters) { TypeNode SimpleNamedType = (TypeNode) _SimpleNamedType; DepParameterExpr DepParameters = (DepParameterExpr) _DepParameters; TypeNode type = nf.AmbDepTypeNode(pos(), ((AmbTypeNode) SimpleNamedType).prefix(), ((AmbTypeNode) SimpleNamedType).name(), new TypedList<TypeNode>(new LinkedList<TypeNode>(), TypeNode.class, false), new TypedList<Expr>(new LinkedList<Expr>(), Expr.class, false), DepParameters); setResult(type); } // Production: DepNamedType ::= SimpleNamedType Arguments void rule_DepNamedType1(Object _SimpleNamedType, Object _Arguments) { TypeNode SimpleNamedType = (TypeNode) _SimpleNamedType; List<Expr> Arguments = (List<Expr>) _Arguments; TypeNode type = nf.AmbDepTypeNode(pos(), ((AmbTypeNode) SimpleNamedType).prefix(), ((AmbTypeNode) SimpleNamedType).name(), new TypedList<TypeNode>(new LinkedList<TypeNode>(), TypeNode.class, false), Arguments, null); setResult(type); } // Production: DepNamedType ::= SimpleNamedType Arguments DepParameters void rule_DepNamedType2(Object _SimpleNamedType, Object _Arguments, Object _DepParameters) { TypeNode SimpleNamedType = (TypeNode) _SimpleNamedType; List<Expr> Arguments = (List<Expr>) _Arguments; DepParameterExpr DepParameters = (DepParameterExpr) _DepParameters; TypeNode type = nf.AmbDepTypeNode(pos(), ((AmbTypeNode) SimpleNamedType).prefix(), ((AmbTypeNode) SimpleNamedType).name(), new TypedList<TypeNode>(new LinkedList<TypeNode>(), TypeNode.class, false), Arguments, DepParameters); setResult(type); } // Production: DepNamedType ::= SimpleNamedType TypeArguments void rule_DepNamedType3(Object _SimpleNamedType, Object _TypeArguments) { TypeNode SimpleNamedType = (TypeNode) _SimpleNamedType; List<TypeNode> TypeArguments = (List<TypeNode>) _TypeArguments; TypeNode type = nf.AmbDepTypeNode(pos(), ((AmbTypeNode) SimpleNamedType).prefix(), ((AmbTypeNode) SimpleNamedType).name(), TypeArguments, new TypedList<Expr>(new LinkedList<Expr>(), Expr.class, false), null); setResult(type); } // Production: DepNamedType ::= SimpleNamedType TypeArguments DepParameters void rule_DepNamedType4(Object _SimpleNamedType, Object _TypeArguments, Object _DepParameters) { TypeNode SimpleNamedType = (TypeNode) _SimpleNamedType; List<TypeNode> TypeArguments = (List<TypeNode>) _TypeArguments; DepParameterExpr DepParameters = (DepParameterExpr) _DepParameters; TypeNode type = nf.AmbDepTypeNode(pos(), ((AmbTypeNode) SimpleNamedType).prefix(), ((AmbTypeNode) SimpleNamedType).name(), TypeArguments, new TypedList<Expr>(new LinkedList<Expr>(), Expr.class, false), DepParameters); setResult(type); } // Production: DepNamedType ::= SimpleNamedType TypeArguments Arguments void rule_DepNamedType5(Object _SimpleNamedType, Object _TypeArguments, Object _Arguments) { TypeNode SimpleNamedType = (TypeNode) _SimpleNamedType; List<TypeNode> TypeArguments = (List<TypeNode>) _TypeArguments; List<Expr> Arguments = (List<Expr>) _Arguments; TypeNode type = nf.AmbDepTypeNode(pos(), ((AmbTypeNode) SimpleNamedType).prefix(), ((AmbTypeNode) SimpleNamedType).name(), TypeArguments, Arguments, null); setResult(type); } // Production: DepNamedType ::= SimpleNamedType TypeArguments Arguments DepParameters void rule_DepNamedType6(Object _SimpleNamedType, Object _TypeArguments, Object _Arguments, Object _DepParameters) { TypeNode SimpleNamedType = (TypeNode) _SimpleNamedType; List<TypeNode> TypeArguments = (List<TypeNode>) _TypeArguments; List<Expr> Arguments = (List<Expr>) _Arguments; DepParameterExpr DepParameters = (DepParameterExpr) _DepParameters; TypeNode type = nf.AmbDepTypeNode(pos(), ((AmbTypeNode) SimpleNamedType).prefix(), ((AmbTypeNode) SimpleNamedType).name(), TypeArguments, Arguments, DepParameters); setResult(type); } // Production: ClassBodyDeclaration ::= ConstructorDeclaration void rule_ClassBodyDeclaration1(Object _ConstructorDeclaration) { ConstructorDecl ConstructorDeclaration = (ConstructorDecl) _ConstructorDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(ConstructorDeclaration); setResult(l); } // Production: InterfaceBody ::= '{' InterfaceMemberDeclarationsopt '}' void rule_InterfaceBody0(Object _InterfaceMemberDeclarationsopt) { List<ClassMember> InterfaceMemberDeclarationsopt = (List<ClassMember>) _InterfaceMemberDeclarationsopt; setResult(nf.ClassBody(pos(), InterfaceMemberDeclarationsopt)); } // Production: LabeledStatement ::= Identifier ':' LoopStatement void rule_LabeledStatement0(Object _Identifier, Object _LoopStatement) { Id Identifier = (Id) _Identifier; Stmt LoopStatement = (Stmt) _LoopStatement; setResult(nf.Labeled(pos(), Identifier, LoopStatement)); } // Production: TypeArgumentList ::= Type void rule_TypeArgumentList0(Object _Type) { TypeNode Type = (TypeNode) _Type; List<TypeNode> l = new ArrayList<TypeNode>(); l.add(Type); setResult(l); } // Production: TypeArgumentList ::= TypeArgumentList ',' Type void rule_TypeArgumentList1(Object _TypeArgumentList, Object _Type) { List<TypeNode> TypeArgumentList = (List<TypeNode>) _TypeArgumentList; TypeNode Type = (TypeNode) _Type; TypeArgumentList.add(Type); } // Production: NormalClassDeclaration ::= Modifiersopt class Identifier TypeParamsWithVarianceopt Propertiesopt WhereClauseopt Superopt Interfacesopt ClassBody void rule_NormalClassDeclaration0(Object _Modifiersopt, Object _Identifier, Object _TypeParamsWithVarianceopt, Object _Propertiesopt, Object _WhereClauseopt, Object _Superopt, Object _Interfacesopt, Object _ClassBody) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; Id Identifier = (Id) _Identifier; List<TypeParamNode> TypeParamsWithVarianceopt = (List<TypeParamNode>) _TypeParamsWithVarianceopt; List<PropertyDecl> Propertiesopt = (List<PropertyDecl>) _Propertiesopt; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode Superopt = (TypeNode) _Superopt; List<TypeNode> Interfacesopt = (List<TypeNode>) _Interfacesopt; ClassBody ClassBody = (ClassBody) _ClassBody; List<Node> modifiers = checkClassModifiers(Modifiersopt); checkTypeName(Identifier); List<TypeParamNode> TypeParametersopt = TypeParamsWithVarianceopt; List<PropertyDecl> props = Propertiesopt; DepParameterExpr ci = WhereClauseopt; FlagsNode f = extractFlags(modifiers); List<AnnotationNode> annotations = extractAnnotations(modifiers); ClassDecl cd = nf.X10ClassDecl(pos(), f, Identifier, TypeParametersopt, props, ci, Superopt, Interfacesopt, ClassBody); cd = (ClassDecl) ((X10Ext) cd.ext()).annotations(annotations); setResult(cd); } // Production: SimpleNamedType ::= TypeName void rule_SimpleNamedType0(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; setResult(TypeName.toType()); } // Production: SimpleNamedType ::= Primary '.' Identifier void rule_SimpleNamedType1(Object _Primary, Object _Identifier) { Expr Primary = (Expr) _Primary; Id Identifier = (Id) _Identifier; setResult(nf.AmbTypeNode(pos(), Primary, Identifier)); } // Production: SimpleNamedType ::= DepNamedType '.' Identifier void rule_SimpleNamedType2(Object _DepNamedType, Object _Identifier) { TypeNode DepNamedType = (TypeNode) _DepNamedType; Id Identifier = (Id) _Identifier; setResult(nf.AmbTypeNode(pos(), DepNamedType, Identifier)); } // Production: VoidType ::= void void rule_VoidType0() { setResult(nf.CanonicalTypeNode(pos(), ts.Void())); } // Production: PreIncrementExpression ::= '++' UnaryExpressionNotPlusMinus void rule_PreIncrementExpression0(Object _UnaryExpressionNotPlusMinus) { Expr UnaryExpressionNotPlusMinus = (Expr) _UnaryExpressionNotPlusMinus; setResult(nf.Unary(pos(), Unary.PRE_INC, UnaryExpressionNotPlusMinus)); } TypeNode explodedType(Position p) { return nf.UnknownTypeNode(p);// exploded formals/locals are either Int or T (when exploding Array[T]). nf.TypeNodeFromQualifiedName(p,QName.make("x10.lang.Int")); } List<Formal> createExplodedFormals(List<Id> exploded) { List<Formal> explodedFormals = new ArrayList<Formal>(); for (Id id : exploded) { // exploded formals are always final (VAL) explodedFormals.add(nf.Formal(id.position(), nf.FlagsNode(id.position(), Flags.FINAL), explodedType(id.position()), id)); } return explodedFormals; } // Production: LoopIndex ::= Modifiersopt LoopIndexDeclarator void rule_LoopIndex0(Object _Modifiersopt, Object _LoopIndexDeclarator) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; Object[] LoopIndexDeclarator = (Object[]) _LoopIndexDeclarator; List<Node> modifiers = checkVariableModifiers(Modifiersopt); Formal f; FlagsNode fn = extractFlags(modifiers, Flags.FINAL); Object[] o = LoopIndexDeclarator; Position pos = (Position) o[0]; Id name = (Id) o[1]; boolean unnamed = name == null; if (name == null) name = nf.Id(pos, Name.makeFresh()); List<Id> exploded = (List<Id>) o[2]; DepParameterExpr guard = (DepParameterExpr) o[3]; TypeNode type = (TypeNode) o[4]; if (type == null) type = nf.UnknownTypeNode(name != null ? name.position() : pos); List<Formal> explodedFormals = createExplodedFormals(exploded); f = nf.X10Formal(pos(), fn, type, name, explodedFormals, unnamed); f = (Formal) ((X10Ext) f.ext()).annotations(extractAnnotations(modifiers)); setResult(f); } // Production: LoopIndex ::= Modifiersopt VarKeyword LoopIndexDeclarator void rule_LoopIndex1(Object _Modifiersopt, Object _VarKeyword, Object _LoopIndexDeclarator) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; List<FlagsNode> VarKeyword = (List<FlagsNode>) _VarKeyword; Object[] LoopIndexDeclarator = (Object[]) _LoopIndexDeclarator; List<Node> modifiers = checkVariableModifiers(Modifiersopt); Formal f; FlagsNode fn = extractFlags(modifiers, VarKeyword); Object[] o = LoopIndexDeclarator; Position pos = (Position) o[0]; Id name = (Id) o[1]; boolean unnamed = name == null; if (name == null) name = nf.Id(pos, Name.makeFresh()); List<Id> exploded = (List<Id>) o[2]; DepParameterExpr guard = (DepParameterExpr) o[3]; TypeNode type = (TypeNode) o[4]; if (type == null) type = nf.UnknownTypeNode(name != null ? name.position() : pos); List<Formal> explodedFormals = createExplodedFormals(exploded); f = nf.X10Formal(pos(), fn, type, name, explodedFormals, unnamed); f = (Formal) ((X10Ext) f.ext()).annotations(extractAnnotations(modifiers)); setResult(f); } // Production: Arguments ::= '(' ArgumentListopt ')' void rule_Arguments0(Object _ArgumentListopt) { List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; setResult(ArgumentListopt); } // Production: Literal ::= ByteLiteral void rule_LiteralByte() { setIntLit(IntLit.BYTE); } // Production: Literal ::= UByteLiteral void rule_LiteralUByte() { setIntLit(IntLit.UBYTE); } // Production: Literal ::= ShortLiteral void rule_LiteralShort() { setIntLit(IntLit.SHORT); } // Production: Literal ::= UShortLiteral void rule_LiteralUShort() { setIntLit(IntLit.USHORT); } // Production: Literal ::= IntegerLiteral void rule_Literal0() { setIntLit(IntLit.INT); } // Production: Literal ::= LongLiteral void rule_Literal1() { setIntLit(IntLit.LONG); } // Production: Literal ::= UnsignedIntegerLiteral void rule_Literal2() { setIntLit(IntLit.UINT); } // Production: Literal ::= UnsignedLongLiteral void rule_Literal3() { setIntLit(IntLit.ULONG); } // Production: Literal ::= FloatingPointLiteral void rule_Literal4() { polyglot.lex.FloatLiteral a = float_lit(getRhsFirstTokenIndex(1)); setResult(nf.FloatLit(pos(), FloatLit.FLOAT, a.getValue().floatValue())); } // Production: Literal ::= DoubleLiteral void rule_Literal5() { polyglot.lex.DoubleLiteral a = double_lit(getRhsFirstTokenIndex(1)); setResult(nf.FloatLit(pos(), FloatLit.DOUBLE, a.getValue().doubleValue())); } // Production: Literal ::= BooleanLiteral void rule_Literal6(Object _BooleanLiteral) { polyglot.lex.BooleanLiteral BooleanLiteral = (polyglot.lex.BooleanLiteral) _BooleanLiteral; setResult(nf.BooleanLit(pos(), BooleanLiteral.getValue().booleanValue())); } // Production: Literal ::= CharacterLiteral void rule_Literal7() { polyglot.lex.CharacterLiteral a = char_lit(getRhsFirstTokenIndex(1)); setResult(nf.CharLit(pos(), a.getValue().charValue())); } // Production: Literal ::= StringLiteral void rule_Literal8() { polyglot.lex.StringLiteral a = string_lit(getRhsFirstTokenIndex(1)); setResult(nf.StringLit(pos(), a.getValue())); } // Production: Literal ::= null void rule_Literal9() { setResult(nf.NullLit(pos())); } // Production: ArgumentListopt ::= %Empty void rule_ArgumentListopt0() { setResult(new TypedList<Expr>(new LinkedList<Expr>(), Expr.class, false)); } // Production: TypeDeclaration ::= ';' void rule_TypeDeclaration3() { setResult(null); } // Production: TypeArguments ::= '[' TypeArgumentList ']' void rule_TypeArguments0(Object _TypeArgumentList) { List<TypeNode> TypeArgumentList = (List<TypeNode>) _TypeArgumentList; setResult(TypeArgumentList); } // Production: ClassBodyDeclarationsopt ::= %Empty void rule_ClassBodyDeclarationsopt0() { setResult(new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false)); } // Production: LeftHandSide ::= ExpressionName void rule_LeftHandSide0(Object _ExpressionName) { ParsedName ExpressionName = (ParsedName) _ExpressionName; setResult(ExpressionName.toExpr()); } // Production: TypeName ::= TypeName '.' ErrorId void rule_TypeName0(Object _TypeName) { ParsedName TypeName = (ParsedName) _TypeName; setResult(new ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), TypeName, nf.Id(pos(getRightSpan()), "*"))); } // Production: TypeName ::= Identifier void rule_TypeName1(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(), Identifier)); } // Production: TypeName ::= TypeName '.' Identifier void rule_TypeName2(Object _TypeName, Object _Identifier) { ParsedName TypeName = (ParsedName) _TypeName; Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), TypeName, Identifier)); } // Production: Offers ::= offers Type void rule_Offers0(Object _Type) { TypeNode Type = (TypeNode) _Type; setResult(Type); } // Production: Super ::= extends ClassType void rule_Super0(Object _ClassType) { TypeNode ClassType = (TypeNode) _ClassType; setResult(ClassType); } // Production: NormalInterfaceDeclaration ::= Modifiersopt interface Identifier TypeParamsWithVarianceopt Propertiesopt WhereClauseopt ExtendsInterfacesopt InterfaceBody void rule_NormalInterfaceDeclaration0(Object _Modifiersopt, Object _Identifier, Object _TypeParamsWithVarianceopt, Object _Propertiesopt, Object _WhereClauseopt, Object _ExtendsInterfacesopt, Object _InterfaceBody) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; Id Identifier = (Id) _Identifier; List<TypeParamNode> TypeParamsWithVarianceopt = (List<TypeParamNode>) _TypeParamsWithVarianceopt; List<PropertyDecl> Propertiesopt = (List<PropertyDecl>) _Propertiesopt; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; List<TypeNode> ExtendsInterfacesopt = (List<TypeNode>) _ExtendsInterfacesopt; ClassBody InterfaceBody = (ClassBody) _InterfaceBody; List<Node> modifiers = checkInterfaceModifiers(Modifiersopt); checkTypeName(Identifier); List<TypeParamNode> TypeParametersopt = TypeParamsWithVarianceopt; List<PropertyDecl> props = Propertiesopt; DepParameterExpr ci = WhereClauseopt; FlagsNode fn = extractFlags(modifiers, Flags.INTERFACE); ClassDecl cd = nf.X10ClassDecl(pos(), fn, Identifier, TypeParametersopt, props, ci, null, ExtendsInterfacesopt, InterfaceBody); cd = (ClassDecl) ((X10Ext) cd.ext()).annotations(extractAnnotations(modifiers)); setResult(cd); } // Production: Propertiesopt ::= %Empty void rule_Propertiesopt0() { setResult(new TypedList<PropertyDecl>(new LinkedList<PropertyDecl>(), PropertyDecl.class, false)); } // Production: SwitchLabelsopt ::= %Empty void rule_SwitchLabelsopt0() { setResult(new TypedList<Case>(new LinkedList<Case>(), Case.class, false)); } // Production: MethodClassNameSuperPrefix ::= ClassName '.' super '.' ErrorId void rule_MethodClassNameSuperPrefix0(Object _ClassName) { ParsedName ClassName = (ParsedName) _ClassName; Object[] a = new Object[3]; a[0] = ClassName; a[1] = pos(getRhsFirstTokenIndex(3)); a[2] = id(getRhsFirstTokenIndex(5)); setResult(a); } // Production: MethodName ::= AmbiguousName '.' ErrorId void rule_MethodName0(Object _AmbiguousName) { ParsedName AmbiguousName = (ParsedName) _AmbiguousName; setResult(new ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), AmbiguousName, nf.Id(pos(getRightSpan()), "*"))); } // Production: MethodName ::= Identifier void rule_MethodName1(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(), Identifier)); } // Production: MethodName ::= AmbiguousName '.' Identifier void rule_MethodName2(Object _AmbiguousName, Object _Identifier) { ParsedName AmbiguousName = (ParsedName) _AmbiguousName; Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), AmbiguousName, Identifier)); } // Production: FieldAccess ::= Primary '.' ErrorId void rule_FieldAccess0(Object _Primary) { Expr Primary = (Expr) _Primary; setResult(nf.Field(pos(), Primary, nf.Id(pos(getRightSpan()), "*"))); } // Production: FieldAccess ::= super '.' ErrorId void rule_FieldAccess1() { setResult(nf.Field(pos(getRightSpan()), nf.Super(pos(getLeftSpan())), nf.Id(pos(getRightSpan()), "*"))); } // Production: FieldAccess ::= ClassName '.' super '.' ErrorId void rule_FieldAccess2(Object _ClassName) { ParsedName ClassName = (ParsedName) _ClassName; setResult(nf.Field(pos(getRightSpan()), nf.Super(pos(getRhsFirstTokenIndex(3)), ClassName.toType()), nf.Id(pos(getRightSpan()), "*"))); } // Production: FieldAccess ::= Primary '.' Identifier void rule_FieldAccess3(Object _Primary, Object _Identifier) { Expr Primary = (Expr) _Primary; Id Identifier = (Id) _Identifier; setResult(nf.Field(pos(), Primary, Identifier)); } // Production: FieldAccess ::= super '.' Identifier void rule_FieldAccess4(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(nf.Field(pos(), nf.Super(pos(getLeftSpan())), Identifier)); } // Production: FieldAccess ::= ClassName '.' super '.' Identifier void rule_FieldAccess5(Object _ClassName, Object _Identifier) { ParsedName ClassName = (ParsedName) _ClassName; Id Identifier = (Id) _Identifier; setResult(nf.Field(pos(), nf.Super(pos(getLeftSpan(),getRhsFirstTokenIndex(3)), ClassName.toType()), Identifier)); } // Production: FieldAccess ::= Primary '.' class void rule_FieldAccess6(Object _Primary) { Expr Primary = (Expr) _Primary; setResult(nf.Field(pos(), Primary, nf.Id(pos(getRhsFirstTokenIndex(3)), "class"))); } // Production: FieldAccess ::= super '.' class void rule_FieldAccess7() { setResult(nf.Field(pos(), nf.Super(pos(getLeftSpan())), nf.Id(pos(getRhsFirstTokenIndex(3)), "class"))); } // Production: FieldAccess ::= ClassName '.' super '.' class void rule_FieldAccess8(Object _ClassName) { ParsedName ClassName = (ParsedName) _ClassName; setResult(nf.Field(pos(), nf.Super(pos(getLeftSpan(),getRhsFirstTokenIndex(3)), ClassName.toType()), nf.Id(pos(getRhsFirstTokenIndex(5)), "class"))); } // Production: ForInit ::= LocalVariableDeclaration void rule_ForInit1(Object _LocalVariableDeclaration) { List<LocalDecl> LocalVariableDeclaration = (List<LocalDecl>) _LocalVariableDeclaration; List<ForInit> l = new TypedList<ForInit>(new LinkedList<ForInit>(), ForInit.class, false); l.addAll(LocalVariableDeclaration); //setResult(l); } // Production: OfferStatement ::= offer Expression ';' void rule_OfferStatement0(Object _Expression) { Expr Expression = (Expr) _Expression; setResult(nf.Offer(pos(), Expression)); } // Production: AtEachStatement ::= ateach '(' LoopIndex in Expression ')' ClockedClauseopt Statement void rule_AtEachStatement0(Object _LoopIndex, Object _Expression, Object _ClockedClauseopt, Object _Statement) { X10Formal LoopIndex = (X10Formal) _LoopIndex; Expr Expression = (Expr) _Expression; List<Expr> ClockedClauseopt = (List<Expr>) _ClockedClauseopt; Stmt Statement = (Stmt) _Statement; FlagsNode fn = LoopIndex.flags(); if (! fn.flags().isFinal()) { syntaxError("Enhanced ateach loop may not have var loop index. " + LoopIndex, LoopIndex.position()); fn = fn.flags(fn.flags().Final()); LoopIndex = LoopIndex.flags(fn); } setResult(nf.AtEach(pos(), LoopIndex, Expression, ClockedClauseopt, Statement)); } // Production: AtEachStatement ::= ateach '(' Expression ')' Statement void rule_AtEachStatement1(Object _Expression, Object _Statement) { Expr Expression = (Expr) _Expression; Stmt Statement = (Stmt) _Statement; Id name = nf.Id(pos(), Name.makeFresh()); TypeNode type = nf.UnknownTypeNode(pos()); setResult(nf.AtEach(pos(), nf.X10Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), type, name, null, true), Expression, new TypedList<Expr>(new LinkedList<Expr>(), Expr.class, false), Statement)); } // Production: Offersopt ::= %Empty void rule_Offersopt0() { setResult(null); } // Production: TypeDeclarationsopt ::= %Empty void rule_TypeDeclarationsopt0() { setResult(new TypedList<TopLevelDecl>(new LinkedList<TopLevelDecl>(), TopLevelDecl.class, false)); } // Production: ClassBodyDeclarations ::= ClassBodyDeclarations ClassBodyDeclaration void rule_ClassBodyDeclarations1(Object _ClassBodyDeclarations, Object _ClassBodyDeclaration) { List<ClassMember> ClassBodyDeclarations = (List<ClassMember>) _ClassBodyDeclarations; List<ClassMember> ClassBodyDeclaration = (List<ClassMember>) _ClassBodyDeclaration; ClassBodyDeclarations.addAll(ClassBodyDeclaration); // setResult(a); } // Production: WhereClause ::= DepParameters void rule_WhereClause0(Object _DepParameters) { DepParameterExpr DepParameters = (DepParameterExpr) _DepParameters; setResult(DepParameters); } // Production: InterfaceMemberDeclaration ::= MethodDeclaration void rule_InterfaceMemberDeclaration0(Object _MethodDeclaration) { ClassMember MethodDeclaration = (ClassMember) _MethodDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(MethodDeclaration); setResult(l); } // Production: InterfaceMemberDeclaration ::= PropertyMethodDeclaration void rule_InterfaceMemberDeclaration1(Object _PropertyMethodDeclaration) { ClassMember PropertyMethodDeclaration = (ClassMember) _PropertyMethodDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(PropertyMethodDeclaration); setResult(l); } // Production: InterfaceMemberDeclaration ::= FieldDeclaration void rule_InterfaceMemberDeclaration2(Object _FieldDeclaration) { List<ClassMember> FieldDeclaration = (List<ClassMember>) _FieldDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.addAll(FieldDeclaration); setResult(l); } // Production: InterfaceMemberDeclaration ::= ClassDeclaration void rule_InterfaceMemberDeclaration3(Object _ClassDeclaration) { ClassDecl ClassDeclaration = (ClassDecl) _ClassDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(ClassDeclaration); setResult(l); } // Production: InterfaceMemberDeclaration ::= InterfaceDeclaration void rule_InterfaceMemberDeclaration4(Object _InterfaceDeclaration) { ClassDecl InterfaceDeclaration = (ClassDecl) _InterfaceDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(InterfaceDeclaration); setResult(l); } // Production: InterfaceMemberDeclaration ::= TypeDefDeclaration void rule_InterfaceMemberDeclaration5(Object _TypeDefDeclaration) { TypeDecl TypeDefDeclaration = (TypeDecl) _TypeDefDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(TypeDefDeclaration); setResult(l); } // Production: InterfaceMemberDeclaration ::= ';' void rule_InterfaceMemberDeclaration6() { - setResult(Collections.<ClassMember>emptyList()); + setResult(new LinkedList<ClassMember>()); } // Production: PackageDeclaration ::= Annotationsopt package PackageName ';' void rule_PackageDeclaration0(Object _Annotationsopt, Object _PackageName) { List<AnnotationNode> Annotationsopt = (List<AnnotationNode>) _Annotationsopt; ParsedName PackageName = (ParsedName) _PackageName; PackageNode pn = PackageName.toPackage(); pn = (PackageNode) ((X10Ext) pn.ext()).annotations(Annotationsopt); setResult(pn.position(pos())); } // Production: InterfaceMemberDeclarations ::= InterfaceMemberDeclarations InterfaceMemberDeclaration void rule_InterfaceMemberDeclarations1(Object _InterfaceMemberDeclarations, Object _InterfaceMemberDeclaration) { List<ClassMember> InterfaceMemberDeclarations = (List<ClassMember>) _InterfaceMemberDeclarations; List<ClassMember> InterfaceMemberDeclaration = (List<ClassMember>) _InterfaceMemberDeclaration; InterfaceMemberDeclarations.addAll(InterfaceMemberDeclaration); // setResult(l); } // Production: MethodInvocation ::= MethodPrimaryPrefix '(' ArgumentListopt ')' void rule_MethodInvocation0(Object _MethodPrimaryPrefix, Object _ArgumentListopt) { Object MethodPrimaryPrefix = (Object) _MethodPrimaryPrefix; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; Expr Primary = (Expr) ((Object[]) MethodPrimaryPrefix)[0]; polyglot.lex.Identifier identifier = (polyglot.lex.Identifier) ((Object[]) MethodPrimaryPrefix)[1]; setResult(nf.Call(pos(), Primary, nf.Id(pos(), identifier.getIdentifier()), ArgumentListopt)); } // Production: MethodInvocation ::= MethodSuperPrefix '(' ArgumentListopt ')' void rule_MethodInvocation1(Object _MethodSuperPrefix, Object _ArgumentListopt) { polyglot.lex.Identifier MethodSuperPrefix = (polyglot.lex.Identifier) _MethodSuperPrefix; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; polyglot.lex.Identifier identifier = MethodSuperPrefix; setResult(nf.Call(pos(), nf.Super(pos(getLeftSpan())), nf.Id(pos(), identifier.getIdentifier()), ArgumentListopt)); } // Production: MethodInvocation ::= MethodClassNameSuperPrefix '(' ArgumentListopt ')' void rule_MethodInvocation2(Object _MethodClassNameSuperPrefix, Object _ArgumentListopt) { Object MethodClassNameSuperPrefix = (Object) _MethodClassNameSuperPrefix; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; ParsedName ClassName = (ParsedName) ((Object[]) MethodClassNameSuperPrefix)[0]; JPGPosition super_pos = (JPGPosition) ((Object[]) MethodClassNameSuperPrefix)[1]; polyglot.lex.Identifier identifier = (polyglot.lex.Identifier) ((Object[]) MethodClassNameSuperPrefix)[2]; setResult(nf.Call(pos(), nf.Super(super_pos, ClassName.toType()), nf.Id(pos(), identifier.getIdentifier()), ArgumentListopt)); } // Production: MethodInvocation ::= MethodName TypeArgumentsopt '(' ArgumentListopt ')' void rule_MethodInvocation3(Object _MethodName, Object _TypeArgumentsopt, Object _ArgumentListopt) { ParsedName MethodName = (ParsedName) _MethodName; List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; setResult(nf.X10Call(pos(), MethodName.prefix == null ? null : MethodName.prefix.toReceiver(), MethodName.name, TypeArgumentsopt, ArgumentListopt)); } // Production: MethodInvocation ::= Primary '.' Identifier TypeArgumentsopt '(' ArgumentListopt ')' void rule_MethodInvocation4(Object _Primary, Object _Identifier, Object _TypeArgumentsopt, Object _ArgumentListopt) { Expr Primary = (Expr) _Primary; Id Identifier = (Id) _Identifier; List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; setResult(nf.X10Call(pos(), Primary, Identifier, TypeArgumentsopt, ArgumentListopt)); } // Production: MethodInvocation ::= super '.' Identifier TypeArgumentsopt '(' ArgumentListopt ')' void rule_MethodInvocation5(Object _Identifier, Object _TypeArgumentsopt, Object _ArgumentListopt) { Id Identifier = (Id) _Identifier; List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; setResult(nf.X10Call(pos(), nf.Super(pos(getLeftSpan())), Identifier, TypeArgumentsopt, ArgumentListopt)); } // Production: MethodInvocation ::= ClassName '.' super '.' Identifier TypeArgumentsopt '(' ArgumentListopt ')' void rule_MethodInvocation6(Object _ClassName, Object _Identifier, Object _TypeArgumentsopt, Object _ArgumentListopt) { ParsedName ClassName = (ParsedName) _ClassName; Id Identifier = (Id) _Identifier; List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; setResult(nf.X10Call(pos(), nf.Super(pos(getRhsFirstTokenIndex(3)), ClassName.toType()), Identifier, TypeArgumentsopt, ArgumentListopt)); } // Production: MethodInvocation ::= Primary TypeArgumentsopt '(' ArgumentListopt ')' void rule_MethodInvocation7(Object _Primary, Object _TypeArgumentsopt, Object _ArgumentListopt) { Expr Primary = (Expr) _Primary; List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; if (Primary instanceof Field) { Field f = (Field) Primary; setResult(nf.X10Call(pos(), f.target(), f.name(), TypeArgumentsopt, ArgumentListopt)); } else if (Primary instanceof AmbExpr) { AmbExpr f = (AmbExpr) Primary; setResult(nf.X10Call(pos(), null, f.name(), TypeArgumentsopt, ArgumentListopt)); } else if (Primary instanceof Here) { Here f = (Here) Primary; setResult(nf.X10Call(pos(), null, nf.Id(Primary.position(), Name.make("here")), TypeArgumentsopt, ArgumentListopt)); } else { setResult(nf.ClosureCall(pos(), Primary, TypeArgumentsopt, ArgumentListopt)); } } // Production: PrefixOp ::= '+' void rule_PrefixOp0() { setResult(Unary.POS); } // Production: PrefixOp ::= '-' void rule_PrefixOp1() { setResult(Unary.NEG); } // Production: PrefixOp ::= '!' void rule_PrefixOp2() { setResult(Unary.NOT); } // Production: PrefixOp ::= '~' void rule_PrefixOp3() { setResult(Unary.BIT_NOT); } // Production: ConstrainedType ::= '(' Type ')' void rule_ConstrainedType2(Object _Type) { TypeNode Type = (TypeNode) _Type; setResult(Type); } // Production: PreDecrementExpression ::= '--' UnaryExpressionNotPlusMinus void rule_PreDecrementExpression0(Object _UnaryExpressionNotPlusMinus) { Expr UnaryExpressionNotPlusMinus = (Expr) _UnaryExpressionNotPlusMinus; setResult(nf.Unary(pos(), Unary.PRE_DEC, UnaryExpressionNotPlusMinus)); } // Production: WhileStatement ::= while '(' Expression ')' Statement void rule_WhileStatement0(Object _Expression, Object _Statement) { Expr Expression = (Expr) _Expression; Stmt Statement = (Stmt) _Statement; setResult(nf.While(pos(), Expression, Statement)); } // Production: Modifier ::= abstract void rule_Modifier0() { setResult(new FlagModifier(pos(), FlagModifier.ABSTRACT)); } // Production: Modifier ::= Annotation void rule_Modifier1(Object _Annotation) { AnnotationNode Annotation = (AnnotationNode) _Annotation; setResult(new AnnotationModifier(Annotation)); } // Production: Modifier ::= atomic void rule_Modifier2() { setResult(new FlagModifier(pos(), FlagModifier.ATOMIC)); } // Production: Modifier ::= final void rule_Modifier3() { setResult(new FlagModifier(pos(), FlagModifier.FINAL)); } // Production: Modifier ::= native void rule_Modifier4() { setResult(new FlagModifier(pos(), FlagModifier.NATIVE)); } // Production: Modifier ::= private void rule_Modifier5() { setResult(new FlagModifier(pos(), FlagModifier.PRIVATE)); } // Production: Modifier ::= protected void rule_Modifier6() { setResult(new FlagModifier(pos(), FlagModifier.PROTECTED)); } // Production: Modifier ::= public void rule_Modifier7() { setResult(new FlagModifier(pos(), FlagModifier.PUBLIC)); } // Production: Modifier ::= static void rule_Modifier8() { setResult(new FlagModifier(pos(), FlagModifier.STATIC)); } // Production: Modifier ::= transient void rule_Modifier9() { setResult(new FlagModifier(pos(), FlagModifier.TRANSIENT)); } // Production: Modifier ::= clocked void rule_Modifier10() { setResult(new FlagModifier(pos(), FlagModifier.CLOCKED)); } // Production: Clock ::= Expression void rule_Clock0(Object _Expression) { Expr Expression = (Expr) _Expression; setResult(Expression); } // Production: ExpressionName ::= AmbiguousName '.' ErrorId void rule_ExpressionName0(Object _AmbiguousName) { ParsedName AmbiguousName = (ParsedName) _AmbiguousName; setResult(new ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), AmbiguousName, nf.Id(pos(getRightSpan()), "*"))); } // Production: ExpressionName ::= Identifier void rule_ExpressionName1(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(), Identifier)); } // Production: ExpressionName ::= AmbiguousName '.' Identifier void rule_ExpressionName2(Object _AmbiguousName, Object _Identifier) { ParsedName AmbiguousName = (ParsedName) _AmbiguousName; Id Identifier = (Id) _Identifier; setResult(new X10ParsedName(nf, ts, pos(getLeftSpan(), getRightSpan()), AmbiguousName, Identifier)); } // Production: TypeParamsWithVarianceopt ::= %Empty void rule_TypeParamsWithVarianceopt0() { setResult(new TypedList<TypeParamNode>(new LinkedList<TypeParamNode>(), TypeParamNode.class, false)); } // Production: FormalParameterListopt ::= %Empty void rule_FormalParameterListopt0() { setResult(new TypedList<Formal>(new LinkedList<Formal>(), Formal.class, false)); } // Production: Conjunctionopt ::= %Empty void rule_Conjunctionopt0() { List<Expr> l = new ArrayList<Expr>(); setResult(l); } // Production: Conjunctionopt ::= Conjunction void rule_Conjunctionopt1(Object _Conjunction) { List<Expr> Conjunction = (List<Expr>) _Conjunction; setResult(Conjunction); } // Production: ClassBody ::= '{' ClassBodyDeclarationsopt '}' void rule_ClassBody0(Object _ClassBodyDeclarationsopt) { List<ClassMember> ClassBodyDeclarationsopt = (List<ClassMember>) _ClassBodyDeclarationsopt; setResult(nf.ClassBody(pos(getLeftSpan(), getRightSpan()), ClassBodyDeclarationsopt)); } // Production: Identifier ::= IDENTIFIER void rule_Identifier0() { // TODO: [IP] Transform escape sequences in quoted identifiers setResult( nf.Id(pos(), prsStream.getName(getRhsFirstTokenIndex(1)))); } // Production: AssignmentOperator ::= '=' void rule_AssignmentOperator0() { setResult(Assign.ASSIGN); } // Production: AssignmentOperator ::= '*=' void rule_AssignmentOperator1() { setResult(Assign.MUL_ASSIGN); } // Production: AssignmentOperator ::= '/=' void rule_AssignmentOperator2() { setResult(Assign.DIV_ASSIGN); } // Production: AssignmentOperator ::= '%=' void rule_AssignmentOperator3() { setResult(Assign.MOD_ASSIGN); } // Production: AssignmentOperator ::= '+=' void rule_AssignmentOperator4() { setResult(Assign.ADD_ASSIGN); } // Production: AssignmentOperator ::= '-=' void rule_AssignmentOperator5() { setResult(Assign.SUB_ASSIGN); } // Production: AssignmentOperator ::= '<<=' void rule_AssignmentOperator6() { setResult(Assign.SHL_ASSIGN); } // Production: AssignmentOperator ::= '>>=' void rule_AssignmentOperator7() { setResult(Assign.SHR_ASSIGN); } // Production: AssignmentOperator ::= '>>>=' void rule_AssignmentOperator8() { setResult(Assign.USHR_ASSIGN); } // Production: AssignmentOperator ::= '&=' void rule_AssignmentOperator9() { setResult(Assign.BIT_AND_ASSIGN); } // Production: AssignmentOperator ::= '^=' void rule_AssignmentOperator10() { setResult(Assign.BIT_XOR_ASSIGN); } // Production: AssignmentOperator ::= '|=' void rule_AssignmentOperator11() { setResult(Assign.BIT_OR_ASSIGN); } // Production: ForUpdateopt ::= %Empty void rule_ForUpdateopt0() { setResult(new TypedList<ForUpdate>(new LinkedList<ForUpdate>(), ForUpdate.class, false)); } // Production: AndExpression ::= AndExpression '&' EqualityExpression void rule_AndExpression1(Object _AndExpression, Object _EqualityExpression) { Expr AndExpression = (Expr) _AndExpression; Expr EqualityExpression = (Expr) _EqualityExpression; setResult(nf.Binary(pos(), AndExpression, Binary.BIT_AND, EqualityExpression)); } // Production: FinishExpression ::= finish '(' Expression ')' Block void rule_FinishExpression0(Object _Expression, Object _Block) { Expr Expression = (Expr) _Expression; Block Block = (Block) _Block; setResult(nf.FinishExpr(pos(), Expression, Block)); } // Production: ReturnStatement ::= return Expressionopt ';' void rule_ReturnStatement0(Object _Expressionopt) { Expr Expressionopt = (Expr) _Expressionopt; setResult(nf.Return(pos(), Expressionopt)); } // Production: SubtypeConstraint ::= Type '<:' Type void rule_SubtypeConstraint0(Object _t1, Object _t2) { TypeNode t1 = (TypeNode) _t1; TypeNode t2 = (TypeNode) _t2; setResult(nf.SubtypeTest(pos(), t1, t2, false)); } // Production: SubtypeConstraint ::= Type ':>' Type void rule_SubtypeConstraint1(Object _t1, Object _t2) { TypeNode t1 = (TypeNode) _t1; TypeNode t2 = (TypeNode) _t2; setResult(nf.SubtypeTest(pos(), t2, t1, false)); } // Production: Catchesopt ::= %Empty void rule_Catchesopt0() { setResult(new TypedList<Catch>(new LinkedList<Catch>(), Catch.class, false)); } // Production: MethodDeclaration ::= MethodModifiersopt def Identifier TypeParametersopt FormalParameters WhereClauseopt HasResultTypeopt Offersopt MethodBody void rule_MethodDeclaration0(Object _MethodModifiersopt, Object _Identifier, Object _TypeParametersopt, Object _FormalParameters, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; Id Identifier = (Id) _Identifier; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; List<Formal> FormalParameters = (List<Formal>) _FormalParameters; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); ProcedureDecl pd; if (Identifier.id().toString().equals("this")) { pd = nf.X10ConstructorDecl(pos(), extractFlags(modifiers), Identifier, HasResultTypeopt, TypeParametersopt, FormalParameters, WhereClauseopt, Offersopt, MethodBody); } else { Position bodyStart = MethodBody == null ? pos().endOf() : MethodBody.position().startOf(); pd = nf.X10MethodDecl(pos(), extractFlags(modifiers), HasResultTypeopt == null ? nf.UnknownTypeNode(bodyStart.markCompilerGenerated()) : HasResultTypeopt, Identifier, TypeParametersopt, FormalParameters, WhereClauseopt, Offersopt, MethodBody); } pd = (ProcedureDecl) ((X10Ext) pd.ext()).annotations(extractAnnotations(modifiers)); setResult(pd); } // Production: MethodDeclaration ::= MethodModifiersopt operator TypeParametersopt '(' FormalParameter ')' BinOp '(' FormalParameter ')' WhereClauseopt HasResultTypeopt Offersopt MethodBody void rule_MethodDeclaration1(Object _MethodModifiersopt, Object _TypeParametersopt, Object _fp1, Object _BinOp, Object _fp2, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; X10Formal fp1 = (X10Formal) _fp1; Binary.Operator BinOp = (Binary.Operator) _BinOp; X10Formal fp2 = (X10Formal) _fp2; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); Name opName = X10Binary_c.binaryMethodName(BinOp); if (opName == null) { syntaxError("Cannot override binary operator '"+BinOp+"'.", pos()); opName = Name.make("invalid operator"); } Position bodyStart = MethodBody == null ? pos().endOf() : MethodBody.position().startOf(); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers), HasResultTypeopt == null ? nf.UnknownTypeNode(bodyStart.markCompilerGenerated()) : HasResultTypeopt, nf.Id(pos(getRhsFirstTokenIndex(7)), opName), TypeParametersopt, Arrays.<Formal>asList(fp1, fp2), WhereClauseopt, Offersopt, MethodBody); FlagsNode flags = md.flags(); if (! flags.flags().isStatic()) { syntaxError("Binary operator with two parameters must be static.", md.position()); md = md.flags(flags.flags(flags.flags().Static())); } md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: MethodDeclaration ::= MethodModifiersopt operator TypeParametersopt PrefixOp '(' FormalParameter ')' WhereClauseopt HasResultTypeopt Offersopt MethodBody void rule_MethodDeclaration2(Object _MethodModifiersopt, Object _TypeParametersopt, Object _PrefixOp, Object _fp2, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; Unary.Operator PrefixOp = (Unary.Operator) _PrefixOp; X10Formal fp2 = (X10Formal) _fp2; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); Name opName = X10Unary_c.unaryMethodName(PrefixOp); if (opName == null) { syntaxError("Cannot override unary operator '"+PrefixOp+"'.", pos()); opName = Name.make("invalid operator"); } Position bodyStart = MethodBody == null ? pos().endOf() : MethodBody.position().startOf(); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers), HasResultTypeopt == null ? nf.UnknownTypeNode(bodyStart.markCompilerGenerated()) : HasResultTypeopt, nf.Id(pos(getRhsFirstTokenIndex(4)), opName), TypeParametersopt, Collections.<Formal>singletonList(fp2), WhereClauseopt, Offersopt, MethodBody); FlagsNode flags = md.flags(); if (! flags.flags().isStatic()) { syntaxError("Unary operator with one parameter must be static.", md.position()); md = md.flags(flags.flags(flags.flags().Static())); } md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: MethodDeclaration ::= MethodModifiersopt operator TypeParametersopt this BinOp '(' FormalParameter ')' WhereClauseopt HasResultTypeopt Offersopt MethodBody void rule_MethodDeclaration3(Object _MethodModifiersopt, Object _TypeParametersopt, Object _BinOp, Object _fp2, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; Binary.Operator BinOp = (Binary.Operator) _BinOp; X10Formal fp2 = (X10Formal) _fp2; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); Name opName = X10Binary_c.binaryMethodName(BinOp); if (opName == null) { syntaxError("Cannot override binary operator '"+BinOp+"'.", pos()); opName = Name.make("invalid operator"); } Position bodyStart = MethodBody == null ? pos().endOf() : MethodBody.position().startOf(); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers), HasResultTypeopt == null ? nf.UnknownTypeNode(bodyStart.markCompilerGenerated()) : HasResultTypeopt, nf.Id(pos(getRhsFirstTokenIndex(5)), opName), TypeParametersopt, Collections.<Formal>singletonList(fp2), WhereClauseopt, Offersopt, MethodBody); FlagsNode flags = md.flags(); if (flags.flags().isStatic()) { syntaxError("Binary operator with this parameter cannot be static.", md.position()); md = md.flags(flags.flags(flags.flags().clearStatic())); } md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: MethodDeclaration ::= MethodModifiersopt operator TypeParametersopt '(' FormalParameter ')' BinOp this WhereClauseopt HasResultTypeopt Offersopt MethodBody void rule_MethodDeclaration4(Object _MethodModifiersopt, Object _TypeParametersopt, Object _fp1, Object _BinOp, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; X10Formal fp1 = (X10Formal) _fp1; Binary.Operator BinOp = (Binary.Operator) _BinOp; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); Name opName = X10Binary_c.invBinaryMethodName(BinOp); if (opName == null) { syntaxError("Cannot override binary operator '"+BinOp+"'.", pos()); opName = Name.make("invalid operator"); } Position bodyStart = MethodBody == null ? pos().endOf() : MethodBody.position().startOf(); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers), HasResultTypeopt == null ? nf.UnknownTypeNode(bodyStart.markCompilerGenerated()) : HasResultTypeopt, nf.Id(pos(getRhsFirstTokenIndex(7)), opName), TypeParametersopt, Collections.<Formal>singletonList(fp1), WhereClauseopt, Offersopt, MethodBody); FlagsNode flags = md.flags(); if (flags.flags().isStatic()) { syntaxError("Binary operator with this parameter cannot be static.", md.position()); md = md.flags(flags.flags(flags.flags().clearStatic())); } md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: MethodDeclaration ::= MethodModifiersopt operator TypeParametersopt PrefixOp this WhereClauseopt HasResultTypeopt Offersopt MethodBody void rule_MethodDeclaration5(Object _MethodModifiersopt, Object _TypeParametersopt, Object _PrefixOp, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; Unary.Operator PrefixOp = (Unary.Operator) _PrefixOp; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); Name opName = X10Unary_c.unaryMethodName(PrefixOp); if (opName == null) { syntaxError("Cannot override unary operator '"+PrefixOp+"'.", pos()); opName = Name.make("invalid operator"); } Position bodyStart = MethodBody == null ? pos().endOf() : MethodBody.position().startOf(); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers), HasResultTypeopt == null ? nf.UnknownTypeNode(bodyStart.markCompilerGenerated()) : HasResultTypeopt, nf.Id(pos(getRhsFirstTokenIndex(4)), opName), TypeParametersopt, Collections.<Formal>emptyList(), WhereClauseopt, Offersopt, MethodBody); FlagsNode flags = md.flags(); if (flags.flags().isStatic()) { syntaxError("Unary operator with this parameter cannot be static.", md.position()); md = md.flags(flags.flags(flags.flags().clearStatic())); } md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: MethodDeclaration ::= MethodModifiersopt operator this TypeParametersopt FormalParameters WhereClauseopt HasResultTypeopt Offersopt MethodBody void rule_MethodDeclaration6(Object _MethodModifiersopt, Object _TypeParametersopt, Object _FormalParameters, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; List<Formal> FormalParameters = (List<Formal>) _FormalParameters; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); Position bodyStart = MethodBody == null ? pos().endOf() : MethodBody.position().startOf(); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers), HasResultTypeopt == null ? nf.UnknownTypeNode(bodyStart.markCompilerGenerated()) : HasResultTypeopt, nf.Id(pos(), ClosureCall.APPLY), TypeParametersopt, FormalParameters, WhereClauseopt, Offersopt, MethodBody); FlagsNode flags = md.flags(); if (flags.flags().isStatic()) { syntaxError("operator() cannot be static.", md.position()); md = md.flags(flags.flags(flags.flags().clearStatic())); } md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: MethodDeclaration ::= MethodModifiersopt operator this TypeParametersopt FormalParameters '=' '(' FormalParameter ')' WhereClauseopt HasResultTypeopt Offersopt MethodBody void rule_MethodDeclaration7(Object _MethodModifiersopt, Object _TypeParametersopt, Object _FormalParameters, Object _fp2, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; List<Formal> FormalParameters = (List<Formal>) _FormalParameters; X10Formal fp2 = (X10Formal) _fp2; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); Position bodyStart = MethodBody == null ? pos().endOf() : MethodBody.position().startOf(); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers), HasResultTypeopt == null ? nf.UnknownTypeNode(bodyStart.markCompilerGenerated()) : HasResultTypeopt, nf.Id(pos(), SettableAssign.SET), TypeParametersopt, CollectionUtil.append(Collections.singletonList(fp2), FormalParameters), WhereClauseopt, Offersopt, MethodBody); FlagsNode flags = md.flags(); if (flags.flags().isStatic()) { syntaxError("Set operator cannot be static.", md.position()); md = md.flags(flags.flags(flags.flags().clearStatic())); } md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: MethodDeclaration ::= MethodModifiersopt operator TypeParametersopt '(' FormalParameter ')' as Type WhereClauseopt Offersopt MethodBody void rule_MethodDeclaration8(Object _MethodModifiersopt, Object _TypeParametersopt, Object _fp1, Object _Type, Object _WhereClauseopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; X10Formal fp1 = (X10Formal) _fp1; TypeNode Type = (TypeNode) _Type; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers), Type, nf.Id(pos(), Converter.operator_as), TypeParametersopt, Collections.<Formal>singletonList(fp1), WhereClauseopt, Offersopt, MethodBody); FlagsNode flags = md.flags(); if (! flags.flags().isStatic()) { syntaxError("Conversion operator must be static.", md.position()); md = md.flags(flags.flags(flags.flags().Static())); } md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: MethodDeclaration ::= MethodModifiersopt operator TypeParametersopt '(' FormalParameter ')' as '?' WhereClauseopt HasResultTypeopt Offersopt MethodBody void rule_MethodDeclaration9(Object _MethodModifiersopt, Object _TypeParametersopt, Object _fp1, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; X10Formal fp1 = (X10Formal) _fp1; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); Position bodyStart = MethodBody == null ? pos().endOf() : MethodBody.position().startOf(); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers), HasResultTypeopt == null ? nf.UnknownTypeNode(bodyStart.markCompilerGenerated()) : HasResultTypeopt, nf.Id(pos(), Converter.operator_as), TypeParametersopt, Collections.<Formal>singletonList(fp1), WhereClauseopt, Offersopt, MethodBody); FlagsNode flags = md.flags(); if (! flags.flags().isStatic()) { syntaxError("Conversion operator must be static.", md.position()); md = md.flags(flags.flags(flags.flags().Static())); } md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: MethodDeclaration ::= MethodModifiersopt operator TypeParametersopt '(' FormalParameter ')' WhereClauseopt HasResultTypeopt Offersopt MethodBody void rule_MethodDeclaration10(Object _MethodModifiersopt, Object _TypeParametersopt, Object _fp1, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; X10Formal fp1 = (X10Formal) _fp1; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); Position bodyStart = MethodBody == null ? pos().endOf() : MethodBody.position().startOf(); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers), HasResultTypeopt == null ? nf.UnknownTypeNode(bodyStart.markCompilerGenerated()) : HasResultTypeopt, nf.Id(pos(), Converter.implicit_operator_as), TypeParametersopt, Collections.<Formal>singletonList(fp1), WhereClauseopt, Offersopt, MethodBody); FlagsNode flags = md.flags(); if (! flags.flags().isStatic()) { syntaxError("Conversion operator must be static.", md.position()); md = md.flags(flags.flags(flags.flags().Static())); } md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: AssertStatement ::= assert Expression ';' void rule_AssertStatement0(Object _Expression) { Expr Expression = (Expr) _Expression; setResult(nf.Assert(pos(), Expression)); } // Production: AssertStatement ::= assert Expression ':' Expression ';' void rule_AssertStatement1(Object _expr1, Object _expr2) { Expr expr1 = (Expr) _expr1; Expr expr2 = (Expr) _expr2; setResult(nf.Assert(pos(), expr1, expr2)); } // Production: DepParameters ::= '{' ExistentialListopt Conjunctionopt '}' void rule_DepParameters0(Object _ExistentialListopt, Object _Conjunctionopt) { List<Formal> ExistentialListopt = (List<Formal>) _ExistentialListopt; List<Expr> Conjunctionopt = (List<Expr>) _Conjunctionopt; setResult(nf.DepParameterExpr(pos(), ExistentialListopt, Conjunctionopt)); } // Production: DoStatement ::= do Statement while '(' Expression ')' ';' void rule_DoStatement0(Object _Statement, Object _Expression) { Stmt Statement = (Stmt) _Statement; Expr Expression = (Expr) _Expression; setResult(nf.Do(pos(), Statement, Expression)); } // Production: PostDecrementExpression ::= PostfixExpression '--' void rule_PostDecrementExpression0(Object _PostfixExpression) { Expr PostfixExpression = (Expr) _PostfixExpression; setResult(nf.Unary(pos(), PostfixExpression, Unary.POST_DEC)); } // Production: ShiftExpression ::= ShiftExpression '->' AdditiveExpression void rule_ShiftExpression4(Object _expr1, Object _expr2) { Expr expr1 = (Expr) _expr1; Expr expr2 = (Expr) _expr2; Expr call = nf.Binary(pos(), expr1, Binary.ARROW, expr2); setResult(call); } // Production: ExplicitConstructorInvocation ::= this TypeArgumentsopt '(' ArgumentListopt ')' ';' void rule_ExplicitConstructorInvocation0(Object _TypeArgumentsopt, Object _ArgumentListopt) { List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; setResult(nf.X10ThisCall(pos(), TypeArgumentsopt, ArgumentListopt)); } // Production: ExplicitConstructorInvocation ::= super TypeArgumentsopt '(' ArgumentListopt ')' ';' void rule_ExplicitConstructorInvocation1(Object _TypeArgumentsopt, Object _ArgumentListopt) { List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; setResult(nf.X10SuperCall(pos(), TypeArgumentsopt, ArgumentListopt)); } // Production: ExplicitConstructorInvocation ::= Primary '.' this TypeArgumentsopt '(' ArgumentListopt ')' ';' void rule_ExplicitConstructorInvocation2(Object _Primary, Object _TypeArgumentsopt, Object _ArgumentListopt) { Expr Primary = (Expr) _Primary; List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; setResult(nf.X10ThisCall(pos(), Primary, TypeArgumentsopt, ArgumentListopt)); } // Production: ExplicitConstructorInvocation ::= Primary '.' super TypeArgumentsopt '(' ArgumentListopt ')' ';' void rule_ExplicitConstructorInvocation3(Object _Primary, Object _TypeArgumentsopt, Object _ArgumentListopt) { Expr Primary = (Expr) _Primary; List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; setResult(nf.X10SuperCall(pos(), Primary, TypeArgumentsopt, ArgumentListopt)); } // Production: FormalParameter ::= Modifiersopt FormalDeclarator void rule_FormalParameter0(Object _Modifiersopt, Object _FormalDeclarator) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; Object[] FormalDeclarator = (Object[]) _FormalDeclarator; List<Node> modifiers = checkVariableModifiers(Modifiersopt); Formal f; FlagsNode fn = extractFlags(modifiers, Flags.FINAL); Object[] o = FormalDeclarator; Position pos = (Position) o[0]; Id name = (Id) o[1]; boolean unnamed = name == null; if (name == null) name = nf.Id(pos, Name.makeFresh()); List<Id> exploded = (List<Id>) o[2]; DepParameterExpr guard = (DepParameterExpr) o[3]; TypeNode type = (TypeNode) o[4]; if (type == null) type = nf.UnknownTypeNode(name != null ? name.position() : pos); Expr init = (Expr) o[5]; List<Formal> explodedFormals = createExplodedFormals(exploded); f = nf.X10Formal(pos(), fn, type, name, explodedFormals, unnamed); f = (Formal) ((X10Ext) f.ext()).annotations(extractAnnotations(modifiers)); setResult(f); } // Production: FormalParameter ::= Modifiersopt VarKeyword FormalDeclarator void rule_FormalParameter1(Object _Modifiersopt, Object _VarKeyword, Object _FormalDeclarator) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; List<FlagsNode> VarKeyword = (List<FlagsNode>) _VarKeyword; Object[] FormalDeclarator = (Object[]) _FormalDeclarator; List<Node> modifiers = checkVariableModifiers(Modifiersopt); Formal f; FlagsNode fn = extractFlags(modifiers, VarKeyword); Object[] o = FormalDeclarator; Position pos = (Position) o[0]; Id name = (Id) o[1]; boolean unnamed = name == null; if (name == null) name = nf.Id(pos, Name.makeFresh()); List<Id> exploded = (List<Id>) o[2]; DepParameterExpr guard = (DepParameterExpr) o[3]; TypeNode type = (TypeNode) o[4]; if (type == null) type = nf.UnknownTypeNode(name != null ? name.position() : pos); Expr init = (Expr) o[5]; List<Formal> explodedFormals = createExplodedFormals(exploded); f = nf.X10Formal(pos(), fn, type, name, explodedFormals, unnamed); f = (Formal) ((X10Ext) f.ext()).annotations(extractAnnotations(modifiers)); setResult(f); } // Production: FormalParameter ::= Type void rule_FormalParameter2(Object _Type) { TypeNode Type = (TypeNode) _Type; Formal f; f = nf.X10Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), Type, nf.Id(pos(), Name.makeFresh("id$")), Collections.<Formal>emptyList(), true); setResult(f); } // Production: BasicForStatement ::= for '(' ForInitopt ';' Expressionopt ';' ForUpdateopt ')' Statement void rule_BasicForStatement0(Object _ForInitopt, Object _Expressionopt, Object _ForUpdateopt, Object _Statement) { List<ForInit> ForInitopt = (List<ForInit>) _ForInitopt; Expr Expressionopt = (Expr) _Expressionopt; List<ForUpdate> ForUpdateopt = (List<ForUpdate>) _ForUpdateopt; Stmt Statement = (Stmt) _Statement; setResult(nf.For(pos(), ForInitopt, Expressionopt, ForUpdateopt, Statement)); } // Production: Properties ::= '(' PropertyList ')' void rule_Properties0(Object _PropertyList) { List<PropertyDecl> PropertyList = (List<PropertyDecl>) _PropertyList; setResult(PropertyList); } // Production: ClockList ::= Clock void rule_ClockList0(Object _Clock) { Expr Clock = (Expr) _Clock; List<Expr> l = new TypedList<Expr>(new LinkedList<Expr>(), Expr.class, false); l.add(Clock); setResult(l); } // Production: ClockList ::= ClockList ',' Clock void rule_ClockList1(Object _ClockList, Object _Clock) { List<Expr> ClockList = (List<Expr>) _ClockList; Expr Clock = (Expr) _Clock; ClockList.add(Clock); setResult(ClockList); } // Production: SwitchStatement ::= switch '(' Expression ')' SwitchBlock void rule_SwitchStatement0(Object _Expression, Object _SwitchBlock) { Expr Expression = (Expr) _Expression; List<SwitchElement> SwitchBlock = (List<SwitchElement>) _SwitchBlock; setResult(nf.Switch(pos(), Expression, SwitchBlock)); } // Production: ThrowStatement ::= throw Expression ';' void rule_ThrowStatement0(Object _Expression) { Expr Expression = (Expr) _Expression; setResult(nf.Throw(pos(), Expression)); } // Production: ContinueStatement ::= continue Identifieropt ';' void rule_ContinueStatement0(Object _Identifieropt) { Id Identifieropt = (Id) _Identifieropt; setResult(nf.Continue(pos(), Identifieropt)); } // Production: StatementExpressionList ::= StatementExpression void rule_StatementExpressionList0(Object _StatementExpression) { Expr StatementExpression = (Expr) _StatementExpression; List<Eval> l = new TypedList<Eval>(new LinkedList<Eval>(), Eval.class, false); l.add(nf.Eval(pos(), StatementExpression)); setResult(l); } // Production: StatementExpressionList ::= StatementExpressionList ',' StatementExpression void rule_StatementExpressionList1(Object _StatementExpressionList, Object _StatementExpression) { List<Eval> StatementExpressionList = (List<Eval>) _StatementExpressionList; Expr StatementExpression = (Expr) _StatementExpression; StatementExpressionList.add(nf.Eval(pos(), StatementExpression)); } // Production: SwitchBlockStatementGroups ::= SwitchBlockStatementGroups SwitchBlockStatementGroup void rule_SwitchBlockStatementGroups1(Object _SwitchBlockStatementGroups, Object _SwitchBlockStatementGroup) { List<SwitchElement> SwitchBlockStatementGroups = (List<SwitchElement>) _SwitchBlockStatementGroups; List<SwitchElement> SwitchBlockStatementGroup = (List<SwitchElement>) _SwitchBlockStatementGroup; SwitchBlockStatementGroups.addAll(SwitchBlockStatementGroup); // setResult(SwitchBlockStatementGroups); } // Production: TypeDefDeclaration ::= Modifiersopt type Identifier TypeParametersopt FormalParametersopt WhereClauseopt '=' Type ';' void rule_TypeDefDeclaration0(Object _Modifiersopt, Object _Identifier, Object _TypeParametersopt, Object _FormalParametersopt, Object _WhereClauseopt, Object _Type) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; Id Identifier = (Id) _Identifier; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; List<Formal> FormalParametersopt = (List<Formal>) _FormalParametersopt; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode Type = (TypeNode) _Type; List<Node> modifiers = checkTypeDefModifiers(Modifiersopt); FlagsNode f = extractFlags(modifiers); List<AnnotationNode> annotations = extractAnnotations(modifiers); List<Formal> formals = new ArrayList<Formal>(); for (Formal v : FormalParametersopt) { FlagsNode flags = v.flags(); if (!flags.flags().isFinal()) { syntaxError("Type definition parameters must be final.", v.position()); v = v.flags(flags.flags(flags.flags().Final())); } formals.add(v); } TypeDecl cd = nf.TypeDecl(pos(), f, Identifier, TypeParametersopt, formals, WhereClauseopt, Type); cd = (TypeDecl) ((X10Ext) cd.ext()).annotations(annotations); setResult(cd); } // Production: PropertyMethodDeclaration ::= MethodModifiersopt Identifier TypeParametersopt FormalParameters WhereClauseopt HasResultTypeopt MethodBody void rule_PropertyMethodDeclaration0(Object _MethodModifiersopt, Object _Identifier, Object _TypeParametersopt, Object _FormalParameters, Object _WhereClauseopt, Object _HasResultTypeopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; Id Identifier = (Id) _Identifier; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; List<Formal> FormalParameters = (List<Formal>) _FormalParameters; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers, Flags.PROPERTY), HasResultTypeopt == null ? nf.UnknownTypeNode(pos()) : HasResultTypeopt, Identifier, TypeParametersopt, FormalParameters, WhereClauseopt, null, // offersOpt MethodBody); md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: PropertyMethodDeclaration ::= MethodModifiersopt Identifier WhereClauseopt HasResultTypeopt MethodBody void rule_PropertyMethodDeclaration1(Object _MethodModifiersopt, Object _Identifier, Object _WhereClauseopt, Object _HasResultTypeopt, Object _MethodBody) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; Id Identifier = (Id) _Identifier; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; Block MethodBody = (Block) _MethodBody; List<Node> modifiers = checkMethodModifiers(MethodModifiersopt); MethodDecl md = nf.X10MethodDecl(pos(), extractFlags(modifiers, Flags.PROPERTY), HasResultTypeopt == null ? nf.UnknownTypeNode(pos()) : HasResultTypeopt, Identifier, Collections.<TypeParamNode>emptyList(), Collections.<Formal>emptyList(), WhereClauseopt, null, // offersOpt MethodBody); md = (MethodDecl) ((X10Ext) md.ext()).annotations(extractAnnotations(modifiers)); setResult(md); } // Production: ExtendsInterfaces ::= extends Type void rule_ExtendsInterfaces0(Object _Type) { TypeNode Type = (TypeNode) _Type; List<TypeNode> l = new TypedList<TypeNode>(new LinkedList<TypeNode>(), TypeNode.class, false); l.add(Type); setResult(l); } // Production: ExtendsInterfaces ::= ExtendsInterfaces ',' Type void rule_ExtendsInterfaces1(Object _ExtendsInterfaces, Object _Type) { List<TypeNode> ExtendsInterfaces = (List<TypeNode>) _ExtendsInterfaces; TypeNode Type = (TypeNode) _Type; ExtendsInterfaces.add(Type); } // Production: SwitchBlockStatementGroup ::= SwitchLabels BlockStatements void rule_SwitchBlockStatementGroup0(Object _SwitchLabels, Object _BlockStatements) { List<SwitchElement> SwitchLabels = (List<SwitchElement>) _SwitchLabels; List<Stmt> BlockStatements = (List<Stmt>) _BlockStatements; List<SwitchElement> l = new TypedList<SwitchElement>(new LinkedList<SwitchElement>(), SwitchElement.class, false); l.addAll(SwitchLabels); l.add(nf.SwitchBlock(pos(), BlockStatements)); setResult(l); } // Production: TypeParametersopt ::= %Empty void rule_TypeParametersopt0() { setResult(new TypedList<TypeParamNode>(new LinkedList<TypeParamNode>(), TypeParamNode.class, false)); } // Production: AtStatement ::= at PlaceExpressionSingleList Statement void rule_AtStatement0(Object _PlaceExpressionSingleList, Object _Statement) { Expr PlaceExpressionSingleList = (Expr) _PlaceExpressionSingleList; Stmt Statement = (Stmt) _Statement; setResult(nf.AtStmt(pos(), PlaceExpressionSingleList, Statement)); } // Production: ConstructorBody ::= '=' ConstructorBlock void rule_ConstructorBody0(Object _ConstructorBlock) { Block ConstructorBlock = (Block) _ConstructorBlock; setResult(ConstructorBlock); } // Production: ConstructorBody ::= ConstructorBlock void rule_ConstructorBody1(Object _ConstructorBlock) { Block ConstructorBlock = (Block) _ConstructorBlock; setResult(ConstructorBlock); } // Production: ConstructorBody ::= '=' ExplicitConstructorInvocation void rule_ConstructorBody2(Object _ExplicitConstructorInvocation) { ConstructorCall ExplicitConstructorInvocation = (ConstructorCall) _ExplicitConstructorInvocation; List<Stmt> l = new TypedList<Stmt>(new LinkedList<Stmt>(), Stmt.class, false); l.add(ExplicitConstructorInvocation); setResult(nf.Block(pos(), l)); } // Production: ConstructorBody ::= '=' AssignPropertyCall void rule_ConstructorBody3(Object _AssignPropertyCall) { Stmt AssignPropertyCall = (Stmt) _AssignPropertyCall; List<Stmt> l = new TypedList<Stmt>(new LinkedList<Stmt>(), Stmt.class, false); l.add(AssignPropertyCall); setResult(nf.Block(pos(), l)); } // Production: WhenStatement ::= when '(' Expression ')' Statement void rule_WhenStatement0(Object _Expression, Object _Statement) { Expr Expression = (Expr) _Expression; Stmt Statement = (Stmt) _Statement; setResult(nf.When(pos(), Expression, Statement)); } // Production: AsyncStatement ::= async ClockedClauseopt Statement void rule_AsyncStatement0(Object _ClockedClauseopt, Object _Statement) { List<Expr> ClockedClauseopt = (List<Expr>) _ClockedClauseopt; Stmt Statement = (Stmt) _Statement; setResult(nf.Async(pos(), ClockedClauseopt, Statement)); } // Production: AsyncStatement ::= clocked async Statement void rule_AsyncStatement1(Object _Statement) { Stmt Statement = (Stmt) _Statement; setResult(nf.Async(pos(), Statement, true)); } // Production: MethodBody ::= '=' LastExpression ';' void rule_MethodBody0(Object _LastExpression) { Stmt LastExpression = (Stmt) _LastExpression; setResult(nf.Block(pos(), LastExpression)); } // Production: MethodBody ::= '=' Annotationsopt '{' BlockStatementsopt LastExpression '}' void rule_MethodBody1(Object _Annotationsopt, Object _BlockStatementsopt, Object _LastExpression) { List<AnnotationNode> Annotationsopt = (List<AnnotationNode>) _Annotationsopt; List<Stmt> BlockStatementsopt = (List<Stmt>) _BlockStatementsopt; Stmt LastExpression = (Stmt) _LastExpression; List<Stmt> l = new ArrayList<Stmt>(); l.addAll(BlockStatementsopt); l.add(LastExpression); setResult((Block) ((X10Ext) nf.Block(pos(),l).ext()).annotations(Annotationsopt)); } // Production: MethodBody ::= '=' Annotationsopt Block void rule_MethodBody2(Object _Annotationsopt, Object _Block) { List<AnnotationNode> Annotationsopt = (List<AnnotationNode>) _Annotationsopt; Block Block = (Block) _Block; setResult((Block) ((X10Ext) Block.ext()).annotations(Annotationsopt).position(pos())); } // Production: MethodBody ::= Annotationsopt Block void rule_MethodBody3(Object _Annotationsopt, Object _Block) { rule_MethodBody2(_Annotationsopt,_Block); } // Production: FieldDeclaration ::= Modifiersopt FieldKeyword FieldDeclarators ';' void rule_FieldDeclaration0(Object _Modifiersopt, Object _FieldKeyword, Object _FieldDeclarators) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; List<FlagsNode> FieldKeyword = (List<FlagsNode>) _FieldKeyword; List<Object[]> FieldDeclarators = (List<Object[]>) _FieldDeclarators; List<Node> modifiers = checkFieldModifiers(Modifiersopt); FlagsNode fn = extractFlags(modifiers, FieldKeyword); List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); for (Object[] o : FieldDeclarators) { Position pos = (Position) o[0]; Id name = (Id) o[1]; if (name == null) name = nf.Id(pos, Name.makeFresh()); TypeNode type = (TypeNode) o[3]; if (type == null) type = nf.UnknownTypeNode(name.position()); Expr init = (Expr) o[4]; FieldDecl fd = nf.FieldDecl(pos, fn, type, name, init); fd = (FieldDecl) ((X10Ext) fd.ext()).annotations(extractAnnotations(modifiers)); fd = (FieldDecl) ((X10Ext) fd.ext()).setComment(comment(getRhsFirstTokenIndex(1))); l.add(fd); } setResult(l); } // Production: FieldDeclaration ::= Modifiersopt FieldDeclarators ';' void rule_FieldDeclaration1(Object _Modifiersopt, Object _FieldDeclarators) { rule_FieldDeclaration0(_Modifiersopt,Collections.singletonList(nf.FlagsNode(pos(), Flags.FINAL)),_FieldDeclarators); } // Production: Interfaces ::= implements InterfaceTypeList void rule_Interfaces0(Object _InterfaceTypeList) { List<TypeNode> InterfaceTypeList = (List<TypeNode>) _InterfaceTypeList; setResult(InterfaceTypeList); } // Production: ShiftExpression ::= ShiftExpression '<<' AdditiveExpression void rule_ShiftExpression1(Object _ShiftExpression, Object _AdditiveExpression) { Expr ShiftExpression = (Expr) _ShiftExpression; Expr AdditiveExpression = (Expr) _AdditiveExpression; setResult(nf.Binary(pos(), ShiftExpression, Binary.SHL, AdditiveExpression)); } // Production: ShiftExpression ::= ShiftExpression '>>' AdditiveExpression void rule_ShiftExpression2(Object _ShiftExpression, Object _AdditiveExpression) { Expr ShiftExpression = (Expr) _ShiftExpression; Expr AdditiveExpression = (Expr) _AdditiveExpression; setResult(nf.Binary(pos(), ShiftExpression, Binary.SHR, AdditiveExpression)); } // Production: ShiftExpression ::= ShiftExpression '>>>' AdditiveExpression void rule_ShiftExpression3(Object _ShiftExpression, Object _AdditiveExpression) { Expr ShiftExpression = (Expr) _ShiftExpression; Expr AdditiveExpression = (Expr) _AdditiveExpression; setResult(nf.Binary(pos(), ShiftExpression, Binary.USHR, AdditiveExpression)); } // Production: ClassMemberDeclaration ::= MethodDeclaration void rule_ClassMemberDeclaration1(Object _MethodDeclaration) { ClassMember MethodDeclaration = (ClassMember) _MethodDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(MethodDeclaration); setResult(l); } // Production: ClassMemberDeclaration ::= PropertyMethodDeclaration void rule_ClassMemberDeclaration2(Object _PropertyMethodDeclaration) { ClassMember PropertyMethodDeclaration = (ClassMember) _PropertyMethodDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(PropertyMethodDeclaration); setResult(l); } // Production: ClassMemberDeclaration ::= TypeDefDeclaration void rule_ClassMemberDeclaration3(Object _TypeDefDeclaration) { TypeDecl TypeDefDeclaration = (TypeDecl) _TypeDefDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(TypeDefDeclaration); setResult(l); } // Production: ClassMemberDeclaration ::= ClassDeclaration void rule_ClassMemberDeclaration4(Object _ClassDeclaration) { ClassDecl ClassDeclaration = (ClassDecl) _ClassDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(ClassDeclaration); setResult(l); } // Production: ClassMemberDeclaration ::= InterfaceDeclaration void rule_ClassMemberDeclaration5(Object _InterfaceDeclaration) { ClassDecl InterfaceDeclaration = (ClassDecl) _InterfaceDeclaration; List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); l.add(InterfaceDeclaration); setResult(l); } // Production: ClassMemberDeclaration ::= ';' void rule_ClassMemberDeclaration6() { List<ClassMember> l = new TypedList<ClassMember>(new LinkedList<ClassMember>(), ClassMember.class, false); setResult(l); } // Production: IfThenStatement ::= if '(' Expression ')' Statement void rule_IfThenStatement0(Object _Expression, Object _Statement) { Expr Expression = (Expr) _Expression; Stmt Statement = (Stmt) _Statement; setResult(nf.If(pos(), Expression, Statement)); } // Production: StructDeclaration ::= Modifiersopt struct Identifier TypeParamsWithVarianceopt Propertiesopt WhereClauseopt Interfacesopt ClassBody void rule_StructDeclaration0(Object _Modifiersopt, Object _Identifier, Object _TypeParamsWithVarianceopt, Object _Propertiesopt, Object _WhereClauseopt, Object _Interfacesopt, Object _ClassBody) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; Id Identifier = (Id) _Identifier; List<TypeParamNode> TypeParamsWithVarianceopt = (List<TypeParamNode>) _TypeParamsWithVarianceopt; List<PropertyDecl> Propertiesopt = (List<PropertyDecl>) _Propertiesopt; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; List<TypeNode> Interfacesopt = (List<TypeNode>) _Interfacesopt; ClassBody ClassBody = (ClassBody) _ClassBody; List<Node> modifiers = checkClassModifiers(Modifiersopt); checkTypeName(Identifier); List<TypeParamNode> TypeParametersopt = TypeParamsWithVarianceopt; List<PropertyDecl> props = Propertiesopt; DepParameterExpr ci = WhereClauseopt; ClassDecl cd = nf.X10ClassDecl(pos(getLeftSpan(), getRightSpan()), extractFlags(modifiers, Flags.STRUCT), Identifier, TypeParametersopt, props, ci, null, Interfacesopt, ClassBody); cd = (ClassDecl) ((X10Ext) cd.ext()).annotations(extractAnnotations(modifiers)); setResult(cd); } // Production: ConstructorBlock ::= '{' ExplicitConstructorInvocationopt BlockStatementsopt '}' void rule_ConstructorBlock0(Object _ExplicitConstructorInvocationopt, Object _BlockStatementsopt) { Stmt ExplicitConstructorInvocationopt = (Stmt) _ExplicitConstructorInvocationopt; List<Stmt> BlockStatementsopt = (List<Stmt>) _BlockStatementsopt; List<Stmt> l = new TypedList<Stmt>(new LinkedList<Stmt>(), Stmt.class, false); if (ExplicitConstructorInvocationopt != null) { l.add(ExplicitConstructorInvocationopt); } l.addAll(BlockStatementsopt); setResult(nf.Block(pos(), l)); } // Production: FieldKeyword ::= val void rule_FieldKeyword0() { setResult(Collections.singletonList(nf.FlagsNode(pos(), Flags.FINAL))); } // Production: FieldKeyword ::= var void rule_FieldKeyword1() { setResult(Collections.singletonList(nf.FlagsNode(pos(), Flags.NONE))); } // Production: InclusiveOrExpression ::= InclusiveOrExpression '|' ExclusiveOrExpression void rule_InclusiveOrExpression1(Object _InclusiveOrExpression, Object _ExclusiveOrExpression) { Expr InclusiveOrExpression = (Expr) _InclusiveOrExpression; Expr ExclusiveOrExpression = (Expr) _ExclusiveOrExpression; setResult(nf.Binary(pos(), InclusiveOrExpression, Binary.BIT_OR, ExclusiveOrExpression)); } // Production: HasResultType ::= ':' Type void rule_HasResultType0(Object _Type) { TypeNode Type = (TypeNode) _Type; setResult(Type); } // Production: HasResultType ::= '<:' Type void rule_HasResultType1(Object _Type) { TypeNode Type = (TypeNode) _Type; setResult(nf.HasType(Type)); } // Production: PropertyList ::= Property void rule_PropertyList0(Object _Property) { PropertyDecl Property = (PropertyDecl) _Property; List<PropertyDecl> l = new TypedList<PropertyDecl>(new LinkedList<PropertyDecl>(), PropertyDecl.class, false); l.add(Property); setResult(l); } // Production: PropertyList ::= PropertyList ',' Property void rule_PropertyList1(Object _PropertyList, Object _Property) { List<PropertyDecl> PropertyList = (List<PropertyDecl>) _PropertyList; PropertyDecl Property = (PropertyDecl) _Property; PropertyList.add(Property); } // Production: ConditionalAndExpression ::= ConditionalAndExpression '&&' InclusiveOrExpression void rule_ConditionalAndExpression1(Object _ConditionalAndExpression, Object _InclusiveOrExpression) { Expr ConditionalAndExpression = (Expr) _ConditionalAndExpression; Expr InclusiveOrExpression = (Expr) _InclusiveOrExpression; setResult(nf.Binary(pos(), ConditionalAndExpression, Binary.COND_AND, InclusiveOrExpression)); } // Production: SwitchLabels ::= SwitchLabel void rule_SwitchLabels0(Object _SwitchLabel) { Case SwitchLabel = (Case) _SwitchLabel; List<Case> l = new TypedList<Case>(new LinkedList<Case>(), Case.class, false); l.add(SwitchLabel); setResult(l); } // Production: SwitchLabels ::= SwitchLabels SwitchLabel void rule_SwitchLabels1(Object _SwitchLabels, Object _SwitchLabel) { List<SwitchElement> SwitchLabels = (List<SwitchElement>) _SwitchLabels; Case SwitchLabel = (Case) _SwitchLabel; SwitchLabels.add(SwitchLabel); //setResult(SwitchLabels); } // Production: ImportDeclarationsopt ::= %Empty void rule_ImportDeclarationsopt0() { setResult(new TypedList<Import>(new LinkedList<Import>(), Import.class, false)); } // Production: IfThenElseStatement ::= if '(' Expression ')' Statement else Statement void rule_IfThenElseStatement0(Object _Expression, Object _s1, Object _s2) { Expr Expression = (Expr) _Expression; Stmt s1 = (Stmt) _s1; Stmt s2 = (Stmt) _s2; setResult(nf.If(pos(), Expression, s1, s2)); } // Production: Identifieropt ::= Identifier void rule_Identifieropt1(Object _Identifier) { Id Identifier = (Id) _Identifier; setResult(Identifier); } // Production: MethodPrimaryPrefix ::= Primary '.' ErrorId void rule_MethodPrimaryPrefix0(Object _Primary) { Expr Primary = (Expr) _Primary; Object[] a = new Object[2]; a[0] = Primary; a[1] = id(getRhsFirstTokenIndex(3)); setResult(a); } // Production: AnnotatedType ::= Type Annotations void rule_AnnotatedType0(Object _Type, Object _Annotations) { TypeNode Type = (TypeNode) _Type; List<AnnotationNode> Annotations = (List<AnnotationNode>) _Annotations; TypeNode tn = Type; tn = (TypeNode) ((X10Ext) tn.ext()).annotations((List<AnnotationNode>) Annotations); setResult(tn.position(pos())); } // Production: ConstructorDeclaration ::= Modifiersopt def this TypeParametersopt FormalParameters WhereClauseopt HasResultTypeopt Offersopt ConstructorBody void rule_ConstructorDeclaration0(Object _Modifiersopt, Object _TypeParametersopt, Object _FormalParameters, Object _WhereClauseopt, Object _HasResultTypeopt, Object _Offersopt, Object _ConstructorBody) { List<Modifier> Modifiersopt = (List<Modifier>) _Modifiersopt; List<TypeParamNode> TypeParametersopt = (List<TypeParamNode>) _TypeParametersopt; List<Formal> FormalParameters = (List<Formal>) _FormalParameters; DepParameterExpr WhereClauseopt = (DepParameterExpr) _WhereClauseopt; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; TypeNode Offersopt = (TypeNode) _Offersopt; Block ConstructorBody = (Block) _ConstructorBody; List<Node> modifiers = checkConstructorModifiers(Modifiersopt); ConstructorDecl cd = nf.X10ConstructorDecl(pos(), extractFlags(modifiers), nf.Id(pos(getRhsFirstTokenIndex(3)), "this"), HasResultTypeopt, TypeParametersopt, FormalParameters, WhereClauseopt, Offersopt, ConstructorBody); cd = (ConstructorDecl) ((X10Ext) cd.ext()).annotations(extractAnnotations(modifiers)); setResult(cd); } // Production: PostIncrementExpression ::= PostfixExpression '++' void rule_PostIncrementExpression0(Object _PostfixExpression) { Expr PostfixExpression = (Expr) _PostfixExpression; setResult(nf.Unary(pos(), PostfixExpression, Unary.POST_INC)); } // Production: ResumeStatement ::= resume ';' void rule_ResumeStatement0() { setResult(nf.Resume(pos())); } // Production: SwitchBlockStatementGroupsopt ::= %Empty void rule_SwitchBlockStatementGroupsopt0() { setResult(new TypedList<SwitchElement>(new LinkedList<SwitchElement>(), SwitchElement.class, false)); } // Production: Catches ::= CatchClause void rule_Catches0(Object _CatchClause) { Catch CatchClause = (Catch) _CatchClause; List<Catch> l = new TypedList<Catch>(new LinkedList<Catch>(), Catch.class, false); l.add(CatchClause); setResult(l); } // Production: Catches ::= Catches CatchClause void rule_Catches1(Object _Catches, Object _CatchClause) { List<Catch> Catches = (List<Catch>) _Catches; Catch CatchClause = (Catch) _CatchClause; Catches.add(CatchClause); //setResult(Catches); } // Production: CatchClause ::= catch '(' FormalParameter ')' Block void rule_CatchClause0(Object _FormalParameter, Object _Block) { X10Formal FormalParameter = (X10Formal) _FormalParameter; Block Block = (Block) _Block; setResult(nf.Catch(pos(), FormalParameter, Block)); } // Production: FieldDeclarators ::= FieldDeclarator void rule_FieldDeclarators0(Object _FieldDeclarator) { Object[] FieldDeclarator = (Object[]) _FieldDeclarator; List<Object[]> l = new TypedList<Object[]>(new LinkedList<Object[]>(), Object[].class, false); l.add(FieldDeclarator); setResult(l); } // Production: FieldDeclarators ::= FieldDeclarators ',' FieldDeclarator void rule_FieldDeclarators1(Object _FieldDeclarators, Object _FieldDeclarator) { List<Object[]> FieldDeclarators = (List<Object[]>) _FieldDeclarators; Object[] FieldDeclarator = (Object[]) _FieldDeclarator; FieldDeclarators.add(FieldDeclarator); // setResult(FieldDeclarators); } // Production: FormalParameters ::= '(' FormalParameterListopt ')' void rule_FormalParameters0(Object _FormalParameterListopt) { List<Formal> FormalParameterListopt = (List<Formal>) _FormalParameterListopt; setResult(FormalParameterListopt); } // Production: ClassInstanceCreationExpression ::= new TypeName TypeArgumentsopt '(' ArgumentListopt ')' ClassBodyopt void rule_ClassInstanceCreationExpression0(Object _TypeName, Object _TypeArgumentsopt, Object _ArgumentListopt, Object _ClassBodyopt) { ParsedName TypeName = (ParsedName) _TypeName; List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; ClassBody ClassBodyopt = (ClassBody) _ClassBodyopt; if (ClassBodyopt == null) setResult(nf.X10New(pos(), TypeName.toType(), TypeArgumentsopt, ArgumentListopt)); else setResult(nf.X10New(pos(), TypeName.toType(), TypeArgumentsopt, ArgumentListopt, ClassBodyopt)) ; } // Production: ClassInstanceCreationExpression ::= new TypeName '[' Type ']' '[' ArgumentListopt ']' void rule_ClassInstanceCreationExpression1(Object _TypeName, Object _Type, Object _ArgumentListopt) { ParsedName TypeName = (ParsedName) _TypeName; TypeNode Type = (TypeNode) _Type; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; String arrayTypeName = TypeName.name.id().toString(); if (! (arrayTypeName.equals("x10.array.Array") || arrayTypeName.equals("Array"))) syntaxError(new Errors.ArrayLiteralMustBeOfArrayType(arrayTypeName, TypeName.pos).getMessage(),TypeName.pos); setResult(nf.Tuple(pos(), Type, ArgumentListopt)); } // Production: ClassInstanceCreationExpression ::= Primary '.' new Identifier TypeArgumentsopt '(' ArgumentListopt ')' ClassBodyopt void rule_ClassInstanceCreationExpression2(Object _Primary, Object _Identifier, Object _TypeArgumentsopt, Object _ArgumentListopt, Object _ClassBodyopt) { Expr Primary = (Expr) _Primary; Id Identifier = (Id) _Identifier; List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; ClassBody ClassBodyopt = (ClassBody) _ClassBodyopt; ParsedName b = new X10ParsedName(nf, ts, pos(), Identifier); if (ClassBodyopt == null) setResult(nf.X10New(pos(), Primary, b.toType(), TypeArgumentsopt, ArgumentListopt)); else setResult(nf.X10New(pos(), Primary, b.toType(), TypeArgumentsopt, ArgumentListopt, ClassBodyopt)); } // Production: ClassInstanceCreationExpression ::= AmbiguousName '.' new Identifier TypeArgumentsopt '(' ArgumentListopt ')' ClassBodyopt void rule_ClassInstanceCreationExpression3(Object _AmbiguousName, Object _Identifier, Object _TypeArgumentsopt, Object _ArgumentListopt, Object _ClassBodyopt) { ParsedName AmbiguousName = (ParsedName) _AmbiguousName; Id Identifier = (Id) _Identifier; List<TypeNode> TypeArgumentsopt = (List<TypeNode>) _TypeArgumentsopt; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; ClassBody ClassBodyopt = (ClassBody) _ClassBodyopt; ParsedName b = new X10ParsedName(nf, ts, pos(), Identifier); if (ClassBodyopt == null) setResult(nf.X10New(pos(), AmbiguousName.toExpr(), b.toType(), TypeArgumentsopt, ArgumentListopt)); else setResult(nf.X10New(pos(), AmbiguousName.toExpr(), b.toType(), TypeArgumentsopt, ArgumentListopt, ClassBodyopt)); } // Production: NextStatement ::= next ';' void rule_NextStatement0() { setResult(nf.Next(pos())); } // Production: AtExpression ::= at PlaceExpressionSingleList ClosureBody void rule_AtExpression0(Object _PlaceExpressionSingleList, Object _ClosureBody) { Expr PlaceExpressionSingleList = (Expr) _PlaceExpressionSingleList; Block ClosureBody = (Block) _ClosureBody; setResult(nf.AtExpr(pos(), PlaceExpressionSingleList, nf.UnknownTypeNode(pos()), ClosureBody)); } // Production: CompilationUnit ::= PackageDeclarationopt TypeDeclarationsopt void rule_CompilationUnit0(Object _PackageDeclarationopt, Object _TypeDeclarationsopt) { PackageNode PackageDeclarationopt = (PackageNode) _PackageDeclarationopt; List<TopLevelDecl> TypeDeclarationsopt = (List<TopLevelDecl>) _TypeDeclarationsopt; // Add import x10.lang.* by default. // int token_pos = (ImportDeclarationsopt.size() == 0 // ? TypeDeclarationsopt.size() == 0 // ? prsStream.getSize() - 1 // : prsStream.getPrevious(getRhsFirstTokenIndex(2)) // : getRhsLastTokenIndex($ImportDeclarationsopt) // ); // Import x10LangImport = // nf.Import(pos(token_pos), Import.PACKAGE, QName.make("x10.lang")); // ImportDeclarationsopt.add(x10LangImport); setResult(nf.SourceFile(pos(getLeftSpan(), getRightSpan()), PackageDeclarationopt, new TypedList<Import>(new LinkedList<Import>(), Import.class, false), TypeDeclarationsopt)); } // Production: CompilationUnit ::= PackageDeclarationopt ImportDeclarations TypeDeclarationsopt void rule_CompilationUnit1(Object _PackageDeclarationopt, Object _ImportDeclarations, Object _TypeDeclarationsopt) { PackageNode PackageDeclarationopt = (PackageNode) _PackageDeclarationopt; List<Import> ImportDeclarations = (List<Import>) _ImportDeclarations; List<TopLevelDecl> TypeDeclarationsopt = (List<TopLevelDecl>) _TypeDeclarationsopt; setResult(nf.SourceFile(pos(getLeftSpan(), getRightSpan()), PackageDeclarationopt, ImportDeclarations, TypeDeclarationsopt)); } // Production: CompilationUnit ::= ImportDeclarations PackageDeclaration ImportDeclarationsopt TypeDeclarationsopt void rule_CompilationUnit2(Object _ImportDeclarations, Object _misplacedPackageDeclaration, Object _misplacedImportDeclarations, Object _TypeDeclarationsopt) { List<Import> ImportDeclarations = (List<Import>) _ImportDeclarations; PackageNode misplacedPackageDeclaration = (PackageNode) _misplacedPackageDeclaration; List<Import> misplacedImportDeclarations = (List<Import>) _misplacedImportDeclarations; List<TopLevelDecl> TypeDeclarationsopt = (List<TopLevelDecl>) _TypeDeclarationsopt; syntaxError("Misplaced package declaration", misplacedPackageDeclaration.position()); ImportDeclarations.addAll(misplacedImportDeclarations); // merge the two import lists setResult(nf.SourceFile(pos(getLeftSpan(), getRightSpan()), misplacedPackageDeclaration, ImportDeclarations, TypeDeclarationsopt)); } // Production: CompilationUnit ::= PackageDeclaration ImportDeclarations PackageDeclaration ImportDeclarationsopt TypeDeclarationsopt void rule_CompilationUnit3(Object _PackageDeclaration, Object _ImportDeclarations, Object _misplacedPackageDeclaration, Object _misplacedImportDeclarations, Object _TypeDeclarationsopt) { PackageNode PackageDeclaration = (PackageNode) _PackageDeclaration; List<Import> ImportDeclarations = (List<Import>) _ImportDeclarations; PackageNode misplacedPackageDeclaration = (PackageNode) _misplacedPackageDeclaration; List<Import> misplacedImportDeclarations = (List<Import>) _misplacedImportDeclarations; List<TopLevelDecl> TypeDeclarationsopt = (List<TopLevelDecl>) _TypeDeclarationsopt; syntaxError("Misplaced package declaration, ignoring", misplacedPackageDeclaration.position()); ImportDeclarations.addAll(misplacedImportDeclarations); // merge the two import lists setResult(nf.SourceFile(pos(getLeftSpan(), getRightSpan()), PackageDeclaration, ImportDeclarations, TypeDeclarationsopt)); } // Production: Assignment ::= LeftHandSide AssignmentOperator AssignmentExpression void rule_Assignment0(Object _LeftHandSide, Object _AssignmentOperator, Object _AssignmentExpression) { Expr LeftHandSide = (Expr) _LeftHandSide; Assign.Operator AssignmentOperator = (Assign.Operator) _AssignmentOperator; Expr AssignmentExpression = (Expr) _AssignmentExpression; setResult(nf.Assign(pos(), LeftHandSide, AssignmentOperator, AssignmentExpression)); } // Production: Assignment ::= ExpressionName '(' ArgumentListopt ')' AssignmentOperator AssignmentExpression void rule_Assignment1(Object _e1, Object _ArgumentListopt, Object _AssignmentOperator, Object _AssignmentExpression) { ParsedName e1 = (ParsedName) _e1; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; Assign.Operator AssignmentOperator = (Assign.Operator) _AssignmentOperator; Expr AssignmentExpression = (Expr) _AssignmentExpression; setResult(nf.SettableAssign(pos(), e1.toExpr(), ArgumentListopt, AssignmentOperator, AssignmentExpression)); } // Production: Assignment ::= Primary '(' ArgumentListopt ')' AssignmentOperator AssignmentExpression void rule_Assignment2(Object _e1, Object _ArgumentListopt, Object _AssignmentOperator, Object _AssignmentExpression) { Expr e1 = (Expr) _e1; List<Expr> ArgumentListopt = (List<Expr>) _ArgumentListopt; Assign.Operator AssignmentOperator = (Assign.Operator) _AssignmentOperator; Expr AssignmentExpression = (Expr) _AssignmentExpression; setResult(nf.SettableAssign(pos(), e1, ArgumentListopt, AssignmentOperator, AssignmentExpression)); } // Production: MethodModifiersopt ::= MethodModifiersopt property void rule_MethodModifiersopt1(Object _MethodModifiersopt) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; MethodModifiersopt.add(new FlagModifier(pos(getRhsFirstTokenIndex(2)), FlagModifier.PROPERTY)); } // Production: MethodModifiersopt ::= MethodModifiersopt Modifier void rule_MethodModifiersopt2(Object _MethodModifiersopt, Object _Modifier) { List<Modifier> MethodModifiersopt = (List<Modifier>) _MethodModifiersopt; Modifier Modifier = (Modifier) _Modifier; MethodModifiersopt.add(Modifier); } // Production: LastExpression ::= Expression void rule_LastExpression0(Object _Expression) { Expr Expression = (Expr) _Expression; setResult(nf.X10Return(pos(), Expression, true)); } // Production: VarKeyword ::= val void rule_VarKeyword0() { setResult(Collections.singletonList(nf.FlagsNode(pos(), Flags.FINAL))); } // Production: VarKeyword ::= var void rule_VarKeyword1() { setResult(Collections.singletonList(nf.FlagsNode(pos(), Flags.NONE))); } // Production: TypeArgumentsopt ::= %Empty void rule_TypeArgumentsopt0() { setResult(new TypedList<TypeNode>(new LinkedList<TypeNode>(), TypeNode.class, false)); } // Production: Annotationsopt ::= %Empty void rule_Annotationsopt0() { setResult(new TypedList<AnnotationNode>(new LinkedList<AnnotationNode>(), AnnotationNode.class, false)); } // Production: LoopIndexDeclarator ::= Identifier HasResultTypeopt void rule_LoopIndexDeclarator0(Object _Identifier, Object _HasResultTypeopt) { Id Identifier = (Id) _Identifier; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; setResult(new Object[] { pos(), Identifier, Collections.<Id>emptyList(), null, HasResultTypeopt, null }); } // Production: LoopIndexDeclarator ::= '[' IdentifierList ']' HasResultTypeopt void rule_LoopIndexDeclarator1(Object _IdentifierList, Object _HasResultTypeopt) { List<Id> IdentifierList = (List<Id>) _IdentifierList; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; setResult(new Object[] { pos(), null, IdentifierList, null, HasResultTypeopt, null }); } // Production: LoopIndexDeclarator ::= Identifier '[' IdentifierList ']' HasResultTypeopt void rule_LoopIndexDeclarator2(Object _Identifier, Object _IdentifierList, Object _HasResultTypeopt) { Id Identifier = (Id) _Identifier; List<Id> IdentifierList = (List<Id>) _IdentifierList; TypeNode HasResultTypeopt = (TypeNode) _HasResultTypeopt; setResult(new Object[] { pos(), Identifier, IdentifierList, null, HasResultTypeopt, null }); } // Production: FinishStatement ::= finish Statement void rule_FinishStatement0(Object _Statement) { Stmt Statement = (Stmt) _Statement; setResult(nf.Finish(pos(), Statement, false)); } // Production: FinishStatement ::= clocked finish Statement void rule_FinishStatement1(Object _Statement) { Stmt Statement = (Stmt) _Statement; setResult(nf.Finish(pos(), Statement, true)); } // Production: Annotations ::= Annotation void rule_Annotations0(Object _Annotation) { AnnotationNode Annotation = (AnnotationNode) _Annotation; List<AnnotationNode> l = new TypedList<AnnotationNode>(new LinkedList<AnnotationNode>(), AnnotationNode.class, false); l.add(Annotation); setResult(l); } // Production: Annotations ::= Annotations Annotation void rule_Annotations1(Object _Annotations, Object _Annotation) { List<AnnotationNode> Annotations = (List<AnnotationNode>) _Annotations; AnnotationNode Annotation = (AnnotationNode) _Annotation; Annotations.add(Annotation); } // Production: ImportDeclarations ::= ImportDeclaration void rule_ImportDeclarations0(Object _ImportDeclaration) { Import ImportDeclaration = (Import) _ImportDeclaration; List<Import> l = new TypedList<Import>(new LinkedList<Import>(), Import.class, false); l.add(ImportDeclaration); setResult(l); } // Production: ImportDeclarations ::= ImportDeclarations ImportDeclaration void rule_ImportDeclarations1(Object _ImportDeclarations, Object _ImportDeclaration) { List<Import> ImportDeclarations = (List<Import>) _ImportDeclarations; Import ImportDeclaration = (Import) _ImportDeclaration; if (ImportDeclaration != null) ImportDeclarations.add(ImportDeclaration); //setResult(l); } // Production: TypeParameters ::= '[' TypeParameterList ']' void rule_TypeParameters0(Object _TypeParameterList) { List<TypeParamNode> TypeParameterList = (List<TypeParamNode>) _TypeParameterList; setResult(TypeParameterList); } // Production: EnhancedForStatement ::= for '(' LoopIndex in Expression ')' Statement void rule_EnhancedForStatement0(Object _LoopIndex, Object _Expression, Object _Statement) { X10Formal LoopIndex = (X10Formal) _LoopIndex; Expr Expression = (Expr) _Expression; Stmt Statement = (Stmt) _Statement; FlagsNode fn = LoopIndex.flags(); if (! fn.flags().isFinal()) { syntaxError("Enhanced for loop may not have var loop index. " + LoopIndex, LoopIndex.position()); fn = fn.flags(fn.flags().Final()); LoopIndex = LoopIndex.flags(fn); } setResult(nf.ForLoop(pos(), LoopIndex, Expression, Statement)); } // Production: EnhancedForStatement ::= for '(' Expression ')' Statement void rule_EnhancedForStatement1(Object _Expression, Object _Statement) { Expr Expression = (Expr) _Expression; Stmt Statement = (Stmt) _Statement; Id name = nf.Id(pos(), Name.makeFresh()); TypeNode type = nf.UnknownTypeNode(pos()); setResult(nf.ForLoop(pos(), nf.X10Formal(pos(), nf.FlagsNode(pos(), Flags.FINAL), type, name, null, true), Expression, Statement)); } // Production: EmptyStatement ::= ';' void rule_EmptyStatement0() { setResult(nf.Empty(pos())); } // Production: FormalDeclarator ::= Identifier ResultType void rule_FormalDeclarator0(Object _Identifier, Object _ResultType) { Id Identifier = (Id) _Identifier; TypeNode ResultType = (TypeNode) _ResultType; setResult(new Object[] { pos(), Identifier, Collections.<Id>emptyList(), null, ResultType, null }); } // Production: FormalDeclarator ::= '[' IdentifierList ']' ResultType void rule_FormalDeclarator1(Object _IdentifierList, Object _ResultType) { List<Id> IdentifierList = (List<Id>) _IdentifierList; TypeNode ResultType = (TypeNode) _ResultType; setResult(new Object[] { pos(), null, IdentifierList, null, ResultType, null }); } // Production: FormalDeclarator ::= Identifier '[' IdentifierList ']' ResultType void rule_FormalDeclarator2(Object _Identifier, Object _IdentifierList, Object _ResultType) { Id Identifier = (Id) _Identifier; List<Id> IdentifierList = (List<Id>) _IdentifierList; TypeNode ResultType = (TypeNode) _ResultType; setResult(new Object[] { pos(), Identifier, IdentifierList, null, ResultType, null }); } // Production: ForInitopt ::= %Empty void rule_ForInitopt0() { setResult(new TypedList<ForInit>(new LinkedList<ForInit>(), ForInit.class, false)); } // Production: ExistentialList ::= FormalParameter void rule_ExistentialList0(Object _FormalParameter) { X10Formal FormalParameter = (X10Formal) _FormalParameter; List<Formal> l = new TypedList<Formal>(new LinkedList<Formal>(), Formal.class, false); l.add(FormalParameter.flags(nf.FlagsNode(Position.compilerGenerated(FormalParameter.position()), Flags.FINAL))); setResult(l); } // Production: ExistentialList ::= ExistentialList ';' FormalParameter void rule_ExistentialList1(Object _ExistentialList, Object _FormalParameter) { List<Formal> ExistentialList = (List<Formal>) _ExistentialList; X10Formal FormalParameter = (X10Formal) _FormalParameter; ExistentialList.add(FormalParameter.flags(nf.FlagsNode(Position.compilerGenerated(FormalParameter.position()), Flags.FINAL))); } // Production: ClockedClause ::= clocked '(' ClockList ')' void rule_ClockedClause0(Object _ClockList) { List<Expr> ClockList = (List<Expr>) _ClockList; setResult(ClockList); } }
false
false
null
null
diff --git a/src/main/java/com/github/joukojo/testgame/GameEngine.java b/src/main/java/com/github/joukojo/testgame/GameEngine.java index a668571..14e06e5 100644 --- a/src/main/java/com/github/joukojo/testgame/GameEngine.java +++ b/src/main/java/com/github/joukojo/testgame/GameEngine.java @@ -1,91 +1,89 @@ package com.github.joukojo.testgame; import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.joukojo.testgame.world.core.WorldCore; import com.github.joukojo.testgame.world.core.WorldCoreFactory; import com.github.joukojo.testgame.world.core.WorldCoreTask; import com.github.joukojo.testgame.world.graphics.GraphicEngine; import com.github.joukojo.testgame.world.graphics.GraphicEngineWorker; public class GameEngine { private final static Logger LOG = LoggerFactory.getLogger(GameEngine.class); - private GraphicEngine engine; + private MonsterCreatorTask monsterCreatorTask; private CollisionDetectionWorker collisionDetector; private GraphicEngineWorker graphicEngineWorker; private WorldCoreTask worldCoreTask; private ExecutorService executorService; private static GameEngine INSTANCE; public void init() { - GraphicsEnvironment env = GraphicsEnvironment + final GraphicsEnvironment env = GraphicsEnvironment .getLocalGraphicsEnvironment(); - GraphicsDevice[] devices = env.getScreenDevices(); + final GraphicsDevice[] devices = env.getScreenDevices(); - - - GraphicsConfiguration graphicsEngine = devices[0].getDefaultConfiguration();; - engine = new GraphicEngine(graphicsEngine); + + final GraphicsConfiguration graphicsEngine = devices[0].getDefaultConfiguration(); + + final GraphicEngine engine = new GraphicEngine(graphicsEngine); final WorldCore worldCore = WorldCoreFactory.getWorld(); final Player player = new Player(); player.setPositionX(500); player.setPositionY(100); worldCore.addMoveable(Constants.PLAYER, player); monsterCreatorTask = new MonsterCreatorTask(); collisionDetector = new CollisionDetectionWorker(); graphicEngineWorker = new GraphicEngineWorker(engine); worldCoreTask = new WorldCoreTask(); executorService = Executors.newCachedThreadPool(); } public void startGame() { LOG.debug("starting up the game engine"); executorService.execute(monsterCreatorTask); executorService.execute(collisionDetector); executorService.execute(graphicEngineWorker); executorService.execute(worldCoreTask); } public void stopGame() { monsterCreatorTask.setIsrunning(false); collisionDetector.setRunning(false); graphicEngineWorker.setRunning(false); worldCoreTask.setRunning(false); executorService.shutdownNow(); } - public static synchronized GameEngine getInstance() { + public static GameEngine getInstance() { - if (INSTANCE == null) { - INSTANCE = new GameEngine(); + synchronized (GameEngine.class) { + if (INSTANCE == null) { + INSTANCE = new GameEngine(); + } } return INSTANCE; } - public void reset() { - - } - }
false
false
null
null
diff --git a/src/java/soc/server/SOCGameListAtServer.java b/src/java/soc/server/SOCGameListAtServer.java index a290665d..40e024b2 100644 --- a/src/java/soc/server/SOCGameListAtServer.java +++ b/src/java/soc/server/SOCGameListAtServer.java @@ -1,447 +1,448 @@ /** * Java Settlers - An online multiplayer version of the game Settlers of Catan - * This file Copyright (C) 2009-2012 Jeremy D Monin <[email protected]> + * This file Copyright (C) 2009-2013 Jeremy D Monin <[email protected]> * Portions of this file Copyright (C) 2003 Robert S. Thomas <[email protected]> * Portions of this file Copyright (C) 2012 Paul Bilnoski <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * The maintainer of this program can be reached at [email protected] **/ package soc.server; import java.util.Date; import java.util.Hashtable; import java.util.Vector; import soc.debug.D; import soc.game.SOCGame; import soc.game.SOCGameOption; import soc.server.genericServer.StringConnection; import soc.util.SOCGameBoardReset; import soc.util.SOCGameList; import soc.util.Version; /** * A class for creating and tracking the games; * contains each game's name, {@link SOCGameOption game options}, * {@link SOCGame} object, and clients ({@link StringConnection}s). *<P> * In 1.1.07, parent class SOCGameList was refactored, with * some methods moved to this new subclass, such as {@link #createGame(String, String, Hashtable) createGame}. * * @see SOCBoardLargeAtServer * @author Jeremy D Monin <[email protected]> * @since 1.1.07 */ public class SOCGameListAtServer extends SOCGameList { /** * Number of minutes after which a game (created on the list) is expired. * Default is 90. * * @see #createGame(String, String, Hashtable) * @see SOCServer#checkForExpiredGames(long) */ public static int GAME_EXPIRE_MINUTES = 90; /** map of game names to Vector of game members ({@link StringConnection}s) */ protected Hashtable<String, Vector<StringConnection>> gameMembers; /** * constructor */ public SOCGameListAtServer() { super(); gameMembers = new Hashtable<String, Vector<StringConnection>>(); } /** * does the game have no members? * @param gaName the name of the game * @return true if the game exists and has an empty member list */ public synchronized boolean isGameEmpty(String gaName) { boolean result; Vector<StringConnection> members; members = gameMembers.get(gaName); if ((members != null) && (members.isEmpty())) { result = true; } else { result = false; } return result; } /** * get a game's members (client connections) * @param gaName game name * @return list of members: a Vector of {@link StringConnection}s */ public synchronized Vector<StringConnection> getMembers(String gaName) { return gameMembers.get(gaName); } /** * is this connection a member of the game? * @param gaName the name of the game * @param conn the member's connection * @return true if memName is a member of the game */ public synchronized boolean isMember(StringConnection conn, String gaName) { Vector<StringConnection> members = getMembers(gaName); if ((members != null) && (members.contains(conn))) return true; else return false; } /** * add a member to the game. * Also checks client's version against game's current range of client versions. * Please call {@link #takeMonitorForGame(String)} before calling this. * * @param gaName the name of the game * @param conn the member's connection; version should already be set */ public synchronized void addMember(StringConnection conn, String gaName) { Vector<StringConnection> members = getMembers(gaName); if ((members != null) && (!members.contains(conn))) { System.err.println("L139: game " + gaName + " add " + conn); // JM TEMP final boolean firstMember = members.isEmpty(); members.addElement(conn); // Check version range SOCGame ga = getGameData(gaName); final int cliVers = conn.getVersion(); if (firstMember) { ga.clientVersionLowest = cliVers; ga.clientVersionHighest = cliVers; ga.hasOldClients = (cliVers < Version.versionNumber()); } else { final int cliLowestAlready = ga.clientVersionLowest; final int cliHighestAlready = ga.clientVersionHighest; if (cliVers < cliLowestAlready) { ga.clientVersionLowest = cliVers; if (cliVers < Version.versionNumber()) ga.hasOldClients = true; } if (cliVers > cliHighestAlready) { ga.clientVersionHighest = cliVers; } } } } /** * remove member from the game. * Also updates game's client version range, with remaining connected members. * Please call {@link #takeMonitorForGame(String)} before calling this. * * @param gaName the name of the game * @param conn the member's connection */ public synchronized void removeMember(StringConnection conn, String gaName) { System.err.println("L139: game " + gaName + " remove " + conn); // JM TEMP Vector<StringConnection> members = getMembers(gaName); if ((members != null)) { members.removeElement(conn); // Check version of remaining members if (! members.isEmpty()) { StringConnection c = members.firstElement(); int lowVers = c.getVersion(); int highVers = lowVers; for (int i = members.size() - 1; i > 1; --i) { c = members.elementAt(i); int v = c.getVersion(); if (v < lowVers) lowVers = v; if (v > highVers) highVers = v; } SOCGame ga = getGameData(gaName); ga.clientVersionLowest = lowVers; ga.clientVersionHighest = highVers; ga.hasOldClients = (lowVers < Version.versionNumber()); } } } /** * Replace member from all games, with a new connection with same name (after a network problem). * * @param oldConn the member's old connection * @param oldConn the member's new connection * @throws IllegalArgumentException if oldConn's keyname (via {@link StringConnection#getData() getData()}) * differs from newConn's keyname * * @see #memberGames(StringConnection, String) * @since 1.1.08 */ public synchronized void replaceMemberAllGames(StringConnection oldConn, StringConnection newConn) throws IllegalArgumentException { if (! oldConn.getData().equals(newConn.getData())) throw new IllegalArgumentException("keyname data"); System.err.println("L212: replaceMemberAllGames(" + oldConn + ", " + newConn + ")"); // JM TEMP final boolean sameVersion = (oldConn.getVersion() == newConn.getVersion()); for (String gaName : getGameNames()) { Vector<StringConnection> members = gameMembers.get(gaName); if ((members != null) && members.contains(oldConn)) { System.err.println("L221: for game " + gaName + ":"); // JM TEMP if (sameVersion) { if (members.remove(oldConn)) System.err.println(" OK"); else System.err.println(" ** not found"); members.addElement(newConn); } else { removeMember(oldConn, gaName); addMember(newConn, gaName); } } } } /** * create a new game, and add to the list; game will expire in {@link #GAME_EXPIRE_MINUTES} minutes. * If a game already exists (per {@link #isGame(String)}), do nothing. * * @param gaName the name of the game * @param gaOwner the game owner/creator's player name, or null (added in 1.1.10) * @param gaOpts if game has options, hashtable of {@link SOCGameOption}; otherwise null. * Should already be validated, by calling * {@link SOCGameOption#adjustOptionsToKnown(Hashtable, Hashtable, boolean)} * with <tt>doServerPreadjust</tt> true. * @return new game object, or null if it already existed */ public synchronized SOCGame createGame(final String gaName, final String gaOwner, Hashtable<String, SOCGameOption> gaOpts) { if (isGame(gaName)) return null; - // Make sure server games have SOCBoardLargeAtServer, for makeNewBoard - if (SOCGame.boardFactory == null) + // Make sure server games have SOCBoardLargeAtServer, for makeNewBoard. + // Double-check class in case server is started at client after a client SOCGame. + if ((SOCGame.boardFactory == null) || ! (SOCGame.boardFactory instanceof SOCBoardLargeAtServer)) SOCGame.boardFactory = new SOCBoardLargeAtServer.BoardFactoryAtServer(); Vector<StringConnection> members = new Vector<StringConnection>(); gameMembers.put(gaName, members); SOCGame game = new SOCGame(gaName, gaOpts); if (gaOwner != null) game.setOwner(gaOwner); // set the expiration to 90 min. from now game.setExpiration(game.getStartTime().getTime() + (60 * 1000 * GAME_EXPIRE_MINUTES)); gameInfo.put(gaName, new GameInfo(true, game.getGameOptions())); // also creates MutexFlag gameData.put(gaName, game); return game; } /** * Reset the board of this game, create a new game of same name, * same players, new layout. The new "reset" board takes the place * of the old game in the game list. *<P> * Robots are not copied and * must re-join the game. (They're removed from the list of game members.) * If the game had robots, they must leave the old game before any players can * join the new game; the new game's {@link SOCGame#boardResetOngoingInfo} field * is set to the object returned by this method, and its gameState will be * {@link SOCGame#READY_RESET_WAIT_ROBOT_DISMISS} instead of {@link SOCGame#NEW}. *<P> * <b>Locking:</b> * Takes game monitor. * Copies old game. * Adds reset-copy to gamelist. * Destroys old game. * Releases game monitor. * * @param gaName Name of game - If not found, do nothing. No monitor is taken. * @return New game if gaName was found and copied; null if no game called gaName, * or if a problem occurs during reset * @see soc.game.SOCGame#resetAsCopy() */ public SOCGameBoardReset resetBoard(String gaName) { SOCGame oldGame = gameData.get(gaName); if (oldGame == null) return null; takeMonitorForGame(gaName); // Create reset-copy of game; // also removes robots from game obj and its member list, // and sets boardResetOngoingInfo field/gamestate if there are robots. SOCGameBoardReset reset = null; try { reset = new SOCGameBoardReset(oldGame, getMembers(gaName)); SOCGame rgame = reset.newGame; // As in createGame, set expiration timer to 90 min. from now rgame.setExpiration(new Date().getTime() + (60 * 1000 * GAME_EXPIRE_MINUTES)); // Adjust game-list gameData.remove(gaName); gameData.put(gaName, rgame); // Done. oldGame.destroyGame(); } catch (Throwable e) { D.ebugPrintStackTrace(e, "ERROR -> gamelist.resetBoard"); } finally { releaseMonitorForGame(gaName); } return reset; // null if error during reset } /** * remove the game from the list * and call {@link SOCGame#destroyGame()} via {@link SOCGameList#deleteGame(String)}. * * @param gaName the name of the game */ @Override public synchronized void deleteGame(String gaName) { // delete from super first, to destroy game and set its gameDestroyed flag // (Removes game from list before dealing with members, in case of locks) super.deleteGame(gaName); Vector<StringConnection> members = gameMembers.get(gaName); if (members != null) { members.removeAllElements(); } } /** * For the games this player is in, what's the * minimum required client version? * Checks {@link SOCGame#getClientVersionMinRequired()}. *<P> * This method helps determine if a client's connection can be * "taken over" after a network problem. It synchronizes on <tt>gameData</tt>. * * @param plConn the previous connection of the player, which might be taken over * @return Minimum version, in same format as {@link SOCGame#getClientVersionMinRequired()}, * or 0 if player isn't in any games. * @since 1.1.08 */ public int playerGamesMinVersion(StringConnection plConn) { int minVers = 0; synchronized(gameData) { for (SOCGame ga : getGamesData()) { Vector<StringConnection> members = getMembers(ga.getName()); if ((members == null) || ! members.contains(plConn)) continue; // plConn is a member of this game. int vers = ga.getClientVersionMinRequired(); if (vers > minVers) minVers = vers; } } return minVers; } /** * List of games containing this member. * * @param c Connection * @param firstGameName Game name that should be first element of list * (if <tt>newConn</tt> is a member of it), or null. * @return The games, in no particular order (past firstGameName), * or a 0-length Vector, if member isn't in any game. * * @see #replaceMemberAllGames(StringConnection, StringConnection) * @since 1.1.08 */ public Vector<SOCGame> memberGames(StringConnection c, final String firstGameName) { Vector<SOCGame> cGames = new Vector<SOCGame>(); synchronized(gameData) { SOCGame firstGame = null; if (firstGameName != null) { firstGame = getGameData(firstGameName); if (firstGame != null) { Vector<?> members = getMembers(firstGameName); if ((members != null) && members.contains(c)) cGames.addElement(firstGame); } } for (SOCGame ga : getGamesData()) { if (ga == firstGame) continue; Vector<?> members = getMembers(ga.getName()); if ((members == null) || ! members.contains(c)) continue; cGames.addElement(ga); } } return cGames; } }
false
false
null
null
diff --git a/funwithmusic/src/com/smp/funwithmusic/activities/FlowActivity.java b/funwithmusic/src/com/smp/funwithmusic/activities/FlowActivity.java index 5984e56..d29d68a 100644 --- a/funwithmusic/src/com/smp/funwithmusic/activities/FlowActivity.java +++ b/funwithmusic/src/com/smp/funwithmusic/activities/FlowActivity.java @@ -1,173 +1,173 @@ package com.smp.funwithmusic.activities; import static com.smp.funwithmusic.utilities.Constants.*; import static com.smp.funwithmusic.utilities.UtilityMethods.*; import java.util.ArrayList; import java.util.List; import org.json.JSONObject; import com.afollestad.cardsui.Card; import com.afollestad.cardsui.Card.CardMenuListener; import com.afollestad.cardsui.CardAdapter; import com.afollestad.cardsui.CardBase; import com.afollestad.cardsui.CardHeader; import com.afollestad.cardsui.CardListView; import com.afollestad.silk.images.SilkImageManager; import com.echonest.api.v4.Artist; import com.echonest.api.v4.EchoNestAPI; import com.echonest.api.v4.EchoNestException; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.JsonHttpResponseHandler; import com.smp.funwithmusic.R; import com.smp.funwithmusic.R.id; import com.smp.funwithmusic.R.layout; import com.smp.funwithmusic.adapters.SongCardAdapter; import com.smp.funwithmusic.apiclient.ItunesClient; import com.smp.funwithmusic.dataobjects.Song; import com.smp.funwithmusic.dataobjects.SongCard; import android.annotation.SuppressLint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Toast; public class FlowActivity extends Activity implements CardMenuListener<Card> { ArrayList<String> songs; private IntentFilter filter; private UpdateActivityReceiver receiver; SongCardAdapter<SongCard> cardsAdapter; String lastArtist; private class UpdateActivityReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { addCardsFromList(); getAlbumUrls(); } } @Override protected void onPause() { super.onPause(); unregisterReceiver(receiver); } @Override protected void onResume() { super.onResume(); addCardsFromList(); getAlbumUrls(); registerReceiver(receiver, filter); } //need to make old OS friendly @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_flow); cardsAdapter = new SongCardAdapter<SongCard>(this); cardsAdapter.setAccentColorRes(android.R.color.holo_blue_dark); cardsAdapter.setPopupMenu(R.menu.card_popup, this); // the popup menu // callback is this // activity CardListView cardsList = (CardListView) findViewById(R.id.cardsList); cardsList.setAdapter(cardsAdapter); cardsList.setOnCardClickListener(new CardListView.CardClickListener() { @SuppressWarnings("rawtypes") @Override public void onCardClick(int index, CardBase card, View view) { SongCard songCard = (SongCard) card; Song song = songCard.getSong(); if (song.hasLyrics()) { Intent intent = new Intent(FlowActivity.this, WebActivity.class); intent.putExtra(WEB_URL, song.getFullLyricsUrl()); startActivity(intent); } } }); filter = new IntentFilter(SONG_ACTION); - //filter.addCategory(Intent.CATEGORY_DEFAULT); + filter.addCategory(Intent.CATEGORY_DEFAULT); receiver = new UpdateActivityReceiver(); } private void getAlbumUrls() { } private void addCardsFromList() { ArrayList<Song> songs = getSongList(this); if (this.songs == null || this.songs.size() != songs.size()) { cardsAdapter.clear(); cardsAdapter.notifyDataSetChanged(); for (Song song : songs) { addCard(song); } } } // Adds to same stack if the artist is the same. private void addCard(final Song song) { if (lastArtist != null && lastArtist.equals(song.getArtist())) { cardsAdapter.add(new SongCard(song, this)); return; } lastArtist = song.getArtist(); cardsAdapter.add(new CardHeader(song.getArtist()) .setAction(this, R.string.artist_info, new CardHeader.ActionListener() { @Override public void onClick(CardHeader header) { Toast.makeText(getApplicationContext(), header.getActionTitle(), Toast.LENGTH_SHORT).show(); } })); cardsAdapter.add(new SongCard(song, this)); } @Override public void onMenuItemClick(Card card, MenuItem item) { // TODO Auto-generated method stub } } diff --git a/funwithmusic/src/com/smp/funwithmusic/activities/WebActivity.java b/funwithmusic/src/com/smp/funwithmusic/activities/WebActivity.java index 1da1bd3..00dc151 100644 --- a/funwithmusic/src/com/smp/funwithmusic/activities/WebActivity.java +++ b/funwithmusic/src/com/smp/funwithmusic/activities/WebActivity.java @@ -1,75 +1,75 @@ package com.smp.funwithmusic.activities; import com.smp.funwithmusic.R; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Window; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import static com.smp.funwithmusic.utilities.Constants.*; public class WebActivity extends Activity { WebView webView; String url; @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_PROGRESS); getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); setContentView(R.layout.activity_web); webView = (WebView) findViewById(R.id.webview); Intent intent = getIntent(); url = intent.getStringExtra(WEB_URL); webView.getSettings().setJavaScriptEnabled(true); - //webView.getSettings().setBuiltInZoomControls(true); + webView.getSettings().setBuiltInZoomControls(true); final Activity activity = this; webView.setWebChromeClient(new WebChromeClient() { public void onProgressChanged(WebView view, int progress) { // Activities and WebViews measure progress with different // scales. // The progress meter will automatically disappear when we reach // 100% activity.setProgress(progress * 100); } }); webView.setWebViewClient(new WebViewClient() { public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); } }); webView.loadUrl(url); } } diff --git a/funwithmusic/src/com/smp/funwithmusic/apiclient/ItunesClient.java b/funwithmusic/src/com/smp/funwithmusic/apiclient/ItunesClient.java index f9694d3..f27b30e 100644 --- a/funwithmusic/src/com/smp/funwithmusic/apiclient/ItunesClient.java +++ b/funwithmusic/src/com/smp/funwithmusic/apiclient/ItunesClient.java @@ -1,82 +1,83 @@ package com.smp.funwithmusic.apiclient; import java.util.Locale; +import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.JsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.smp.funwithmusic.utilities.URLParamEncoder; import static com.smp.funwithmusic.utilities.Constants.*; public class ItunesClient { public static final String BASE_URL = "http://itunes.apple.com/search?"; private static AsyncHttpClient client = new AsyncHttpClient(); public static void get(String album, JsonHttpResponseHandler responseHandler) { RequestParams params = new RequestParams(); params.put("term", URLParamEncoder.encode(removeAlbumVariations(album)) .replace(ESCAPED_SPACE, ITUNES_TERMS_CONNECTOR)); params.put("media", "music"); params.put("attribute", "albumTerm"); params.put("entity", "album"); params.put("limit", "200"); client.get(BASE_URL, params, responseHandler); } // This function will remove variations from the album name. For example, // "Violator [Digital Version]" will become "Violator" or Music (US Edition) // becomes "Music". private static String removeAlbumVariations(String album) { return album; } public static String getImageUrl(JSONObject json, String artist) { String result = null; JSONArray results; Locale locale = Locale.getDefault(); try { results = json.getJSONArray("results"); for (int i = 0; i < results.length(); ++i) { JSONObject res = results.getJSONObject(i); String candidate = res.optString("artistName"); // Log.i("URL", candidate); // Log.i("URL", artist); if (artist != null && artist.toUpperCase(locale) .equals(candidate.toUpperCase(locale))) { // Log.i("URL", artist); result = res.optString("artworkUrl100"); if (result == null) result = res.optString("artworkUrl60"); if (result != null) break; } } } catch (JSONException e) { e.printStackTrace(); } return result; } } diff --git a/funwithmusic/src/com/smp/funwithmusic/receivers/SongReceiver.java b/funwithmusic/src/com/smp/funwithmusic/receivers/SongReceiver.java index 169a999..8567099 100644 --- a/funwithmusic/src/com/smp/funwithmusic/receivers/SongReceiver.java +++ b/funwithmusic/src/com/smp/funwithmusic/receivers/SongReceiver.java @@ -1,204 +1,206 @@ package com.smp.funwithmusic.receivers; import java.util.ArrayList; import java.util.Arrays; import com.smp.funwithmusic.dataobjects.Song; import android.content.BroadcastReceiver; import static com.smp.funwithmusic.utilities.Constants.*; import static com.smp.funwithmusic.utilities.UtilityMethods.*; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.provider.MediaStore; import android.util.Log; import android.widget.Toast; public class SongReceiver extends BroadcastReceiver { public String mAlbum; public String mArtist; public Context mContext; public Intent mIntent; public String mTitle; @Override public void onReceive(Context context, Intent intent) { + PendingResult result = goAsync(); setSongInfo(context, intent); if (mAlbum != null && mArtist != null && mTitle != null) { Song song = new Song(mTitle, mArtist, mAlbum); writeNewSong(context, song); Intent send = new Intent(); send.setAction(SONG_ACTION) .addCategory(Intent.CATEGORY_DEFAULT); context.sendBroadcast(send); Log.i("SONG", mArtist + " " + mTitle + " " + mAlbum); } + result.finish(); } private void setSongInfo(Context context, Intent intent) { Log.d("SONG", "BLAH"); mContext = context; mIntent = intent; try { if ((intent.getAction().equals("com.htc.music.playstatechanged")) || (intent.getAction().equals("com.htc.music.metachanged"))) { boolean bool1 = intent.getBooleanExtra("isplaying", false); mArtist = intent.getStringExtra("artist"); mTitle = intent.getStringExtra("track"); mAlbum = intent.getStringExtra("album"); } else if (intent.getAction().equals("com.htc.music.playbackcomplete")) { } else if ((intent.getAction().equals("com.android.music.playstatechanged")) || (intent.getAction().equals("com.android.music.metachanged"))) { boolean bool2 = intent.getBooleanExtra("playing", false); mArtist = intent.getStringExtra("artist"); mTitle = intent.getStringExtra("track"); mAlbum = intent.getStringExtra("album"); } else if (intent.getAction().equals("com.android.music.playbackcomplete")) { } else if (intent.getAction().equals("fm.last.android.metachanged")) { mArtist = intent.getStringExtra("artist"); mTitle = intent.getStringExtra("track"); mAlbum = intent.getStringExtra("album"); } else if ((intent.getAction().equals("fm.last.android.playbackpaused")) || (intent.getAction().equals("fm.last.android.playbackcomplete"))) { } else if ((intent.getAction().equals("com.real.RealPlayer.playstatechanged")) || (intent.getAction().equals("com.real.RealPlayer.metachanged"))) { boolean bool3 = intent.getBooleanExtra("isplaying", false); mArtist = intent.getStringExtra("artist"); mTitle = intent.getStringExtra("track"); mAlbum = intent.getStringExtra("album"); } else if (intent.getAction().equals("com.real.RealPlayer.playbackcomplete")) { } else if ((intent.getAction().equals("com.tbig.playerprotrial.playstatechanged")) || (intent.getAction().equals("com.tbig.playerprotrial.metachanged")) || (intent.getAction().equals("com.tbig.playerpro.playstatechanged")) || (intent.getAction().equals("com.tbig.playerpro.metachanged"))) { boolean bool4 = intent.getBooleanExtra("playing", false); mArtist = intent.getStringExtra("artist"); mTitle = intent.getStringExtra("track"); mAlbum = intent.getStringExtra("album"); } else if ((intent.getAction().equals("com.tbig.playerprotrial.playbackcomplete")) || (intent.getAction().equals("com.tbig.playerpro.playbackcomplete"))) { } /* * else if (intent.getAction().equals( * "com.spotify.mobile.android.playbackstatechanged")) { if * (intent.getBooleanExtra("playing", false)) { * LyricsSettings.putBoolean(context, "spotifyPlaying", true); * mArtist = LyricsSettings.getString(context, "spotifyArtist"); * mTitle = LyricsSettings.getString(context, "spotifyTitle"); * mAlbum = LyricsSettings.getString(context, "spotifyAlbum"); if * ((mArtist != null) && (mTitle != null)) * addNotificationIcon(context); } else { * LyricsSettings.putBoolean(context, "spotifyPlaying", false); * removeNotificationIcon(context); } } else if (intent.getAction * ().equals("com.spotify.mobile.android.metadatachanged")) { * boolean bool6 = LyricsSettings.getBoolean(context, * "spotifyPlaying"); mArtist = intent.getStringExtra("artist"); * mTitle = intent.getStringExtra("track"); mAlbum = * intent.getStringExtra("album"); LyricsSettings.putString(context, * "spotifyArtist", intent.getStringExtra("artist")); * LyricsSettings.putString(context, "spotifyTitle", * intent.getStringExtra("track")); * LyricsSettings.putString(context, "spotifyAlbum", * intent.getStringExtra("album")); if (bool6) * addNotificationIcon(context); else * removeNotificationIcon(context); } */ else if ((intent.getAction().equals("com.adam.aslfms.notify.playstatechanged")) || (intent.getAction().equals("com.adam.aslfms.notify.metachanged"))) { int i = intent.getIntExtra("state", 3); if (i == 0) return; if (i == 1) return; mArtist = intent.getStringExtra("artist"); mTitle = intent.getStringExtra("track"); mAlbum = intent.getStringExtra("album"); } else if (intent.getAction().equals("com.adam.aslfms.notify.playbackcomplete")) { } else if (intent.getAction().equals("net.jjc1138.android.scrobbler.action.MUSIC_STATUS")) { boolean bool5 = intent.getBooleanExtra("playing", false); if (intent.hasExtra("id")) { int k = intent.getIntExtra("id", 1); Cursor localCursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, "_id=" + k, null, null); localCursor.moveToFirst(); mArtist = localCursor.getString(localCursor.getColumnIndexOrThrow("artist")); mTitle = localCursor.getString(localCursor.getColumnIndexOrThrow("title")); mAlbum = localCursor.getString(localCursor.getColumnIndexOrThrow("album")); } } else if (intent.getAction().equals("com.sonyericsson.music.playbackcontrol.ACTION_TRACK_STARTED")) { mArtist = intent.getStringExtra("ARTIST_NAME"); mTitle = intent.getStringExtra("TRACK_NAME"); mAlbum = intent.getStringExtra("ALBUM_NAME"); } else if ((intent.getAction().equals("com.sonyericsson.music.playbackcontrol.ACTION_PAUSED")) || (intent.getAction().equals("com.sonyericsson.music.TRACK_COMPLETED"))) { } else { return; } } catch (Exception e) { e.printStackTrace(); } } private void writeNewSong(Context context, Song song) { ArrayList<Song> songs = getSongList(context); if (song != null && !songs.contains(song)) { songs.add(song); writeObjectToFile(context, SONG_FILE_NAME, songs); } } }
false
false
null
null
diff --git a/src/main/java/edu/gatech/cs2340/risky/model/Lobby.java b/src/main/java/edu/gatech/cs2340/risky/model/Lobby.java index 136f870..de8f048 100644 --- a/src/main/java/edu/gatech/cs2340/risky/model/Lobby.java +++ b/src/main/java/edu/gatech/cs2340/risky/model/Lobby.java @@ -1,41 +1,41 @@ package edu.gatech.cs2340.risky.model; import java.util.ArrayList; public class Lobby { private String name; public ArrayList<Player> players = new ArrayList<Player>(); public Lobby(String name) { this.name = name; } public ArrayList<Player> getPlayers() { return players; } public String getName() { return name; } - public int calculateArmies(int numPlayers) { - switch (numPlayers) { + public int calculateArmies() { + switch (players.size()) { case 3: return 35; case 4: return 30; case 5: return 25; case 6: return 20; } return 0; } public void allocateArmies() { for (Player player : this.players) { - player.armies = this.calculateArmies(this.players.size()); + player.setArmy(this.calculateArmies()); } } } diff --git a/src/main/java/edu/gatech/cs2340/risky/model/Player.java b/src/main/java/edu/gatech/cs2340/risky/model/Player.java index ce8c687..288c1db 100644 --- a/src/main/java/edu/gatech/cs2340/risky/model/Player.java +++ b/src/main/java/edu/gatech/cs2340/risky/model/Player.java @@ -1,25 +1,33 @@ package edu.gatech.cs2340.risky.model; public class Player { public String name; - public int armies; + private int armies; private boolean playing=true; public Player(String name, int armies) { this.name = name; this.armies = armies; } public Player(String name) { this(name, 0); } public void setDead() { playing=false; } public boolean stillAlive() { return playing; } + + public int getArmy() { + return armies; + } + + public void setArmy(int armySize) { + armies = armySize; + } } diff --git a/src/main/java/edu/gatech/cs2340/risky/model/TurnManager.java b/src/main/java/edu/gatech/cs2340/risky/model/TurnManager.java index fe288bb..e881a34 100644 --- a/src/main/java/edu/gatech/cs2340/risky/model/TurnManager.java +++ b/src/main/java/edu/gatech/cs2340/risky/model/TurnManager.java @@ -1,77 +1,78 @@ package edu.gatech.cs2340.risky.model; import java.util.ArrayList; import java.util.Iterator; import java.util.Collections; /** * Class that will act as a reference * to current players and their turns */ public class TurnManager { private static final int MAX_PLAYERS = 6; private ArrayList<Player> turnList; private int playerIndex = 0; private Iterator<Player> currentPlayer; private int round = 0; public TurnManager() { turnList = new ArrayList<Player>(MAX_PLAYERS); currentPlayer = turnList.iterator(); } public boolean addPlayer(Player p) { if (round == 0) { if (turnList.size() <= MAX_PLAYERS) { turnList.add(p); return true; } } return false; } + public void shuffleOrder() { Collections.shuffle(turnList); } public int getRound() { return round; } private Player nextPlayer() { if (playerIndex < turnList.size()) { return turnList.get(playerIndex++); } else { playerIndex = 0; round++; return turnList.get(playerIndex++); } } //this method will only work if there is atleast 1 living player //round will be updated if next/first player is returned //@dare-- do it with iterators... public Player getNextPlayer() { if(round == 0) { round++;//ensures players are only added on game start } Player p = nextPlayer(); while (!p.stillAlive()) { p = nextPlayer(); if (round > 9001){ break;//just in case } } return p; } public String PlayerOrder() { String order = new String(); for (Player p : turnList){ order = order.concat(p.name + ", "); } return order; } }
false
false
null
null
diff --git a/bytecode/src/main/java/org/jboss/capedwarf/bytecode/endpoints/EndPointAnnotator.java b/bytecode/src/main/java/org/jboss/capedwarf/bytecode/endpoints/EndPointAnnotator.java index 5327f12a..901e3da2 100644 --- a/bytecode/src/main/java/org/jboss/capedwarf/bytecode/endpoints/EndPointAnnotator.java +++ b/bytecode/src/main/java/org/jboss/capedwarf/bytecode/endpoints/EndPointAnnotator.java @@ -1,152 +1,152 @@ /* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.capedwarf.bytecode.endpoints; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.inject.Named; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import com.google.api.server.spi.config.Api; import com.google.api.server.spi.config.ApiMethod; import javassist.CtClass; import javassist.CtMethod; import javassist.bytecode.ParameterAnnotationsAttribute; import javassist.bytecode.annotation.Annotation; import javassist.bytecode.annotation.ArrayMemberValue; import javassist.bytecode.annotation.MemberValue; import javassist.bytecode.annotation.StringMemberValue; import org.jboss.capedwarf.bytecode.Annotator; /** * @author <a href="mailto:[email protected]">Marko Luksa</a> */ public class EndPointAnnotator extends Annotator { - public static final String DEFAULT_NAME = "myApi"; + public static final String DEFAULT_NAME = "myapi"; public static final String DEFAULT_VERSION = "v1"; private static Map<String, Class<? extends java.lang.annotation.Annotation>> HTTP_METHODS = new HashMap<>(); static { HTTP_METHODS.put(ApiMethod.HttpMethod.GET, GET.class); HTTP_METHODS.put(ApiMethod.HttpMethod.POST, POST.class); HTTP_METHODS.put(ApiMethod.HttpMethod.PUT, PUT.class); HTTP_METHODS.put(ApiMethod.HttpMethod.DELETE, DELETE.class); } public EndPointAnnotator(CtClass clazz) { super(clazz); } @Override public void addAnnotations() throws Exception { Api api = (Api) getClazz().getAnnotation(Api.class); if (api == null) { return; } addAnnotationsToClass( createPathAnnotation("" // TODO: api.root() + "/" + (api.name().isEmpty() ? DEFAULT_NAME : api.name()) + "/" + (api.version().isEmpty() ? DEFAULT_VERSION : api.version()))); for (CtMethod method : getClazz().getDeclaredMethods()) { ApiMethod apiMethod = (ApiMethod) method.getAnnotation(ApiMethod.class); if (apiMethod != null) { convertApiMethodAnnotation(method, apiMethod); } } } private Annotation createPathAnnotation(String urlPath) { return createAnnotation(Path.class, memberValueOf(urlPath)); } private void convertApiMethodAnnotation(CtMethod method, ApiMethod apiMethod) { Class<? extends java.lang.annotation.Annotation> httpMethod = HTTP_METHODS.get(apiMethod.httpMethod()); if (httpMethod == null) { return; } String path = apiMethod.path(); if (path == null || path.isEmpty()) { path = method.getName(); } addAnnotationsToMethod(method, Arrays.asList( createAnnotation(httpMethod), createProducesAnnotation("application/json"), createPathAnnotation(path) )); convertAnnotationsOnParameters(method, path); } private void convertAnnotationsOnParameters(CtMethod method, String path) { ParameterAnnotationsAttribute attributeInfo = (ParameterAnnotationsAttribute) method.getMethodInfo().getAttribute(ParameterAnnotationsAttribute.visibleTag); if (attributeInfo == null) { return; } Annotation[][] paramArrays = attributeInfo.getAnnotations(); for (int i = 0; i < paramArrays.length; i++) { Annotation[] paramAnnotations = paramArrays[i]; for (Annotation paramAnnotation : paramAnnotations) { if (paramAnnotation.getTypeName().equals(Named.class.getName())) { MemberValue value = paramAnnotation.getMemberValue("value"); String paramName = ((StringMemberValue) value).getValue(); Annotation param = createAnnotation(isPathParam(path, paramName) ? PathParam.class : QueryParam.class, value); paramAnnotations = addToArray(paramAnnotations, param); paramArrays[i] = paramAnnotations; } } } attributeInfo.setAnnotations(paramArrays); } private boolean isPathParam(String path, String paramName) { return path.contains("{" + paramName + "}"); } private Annotation createProducesAnnotation(String value) { StringMemberValue element = memberValueOf(value); ArrayMemberValue array = createSingleElementArrayMemberValue(String.class, element); return createAnnotation(Produces.class, array); } private Annotation[] addToArray(Annotation[] paramAnnotations, Annotation queryParam) { Annotation newParamAnnotations[] = new Annotation[paramAnnotations.length + 1]; System.arraycopy(paramAnnotations, 0, newParamAnnotations, 0, paramAnnotations.length); newParamAnnotations[newParamAnnotations.length - 1] = queryParam; return newParamAnnotations; } }
true
false
null
null
diff --git a/doxia-modules/doxia-module-fo/src/main/java/org/apache/maven/doxia/module/fo/FoAggregateSink.java b/doxia-modules/doxia-module-fo/src/main/java/org/apache/maven/doxia/module/fo/FoAggregateSink.java index 3e262a90..955491a0 100644 --- a/doxia-modules/doxia-module-fo/src/main/java/org/apache/maven/doxia/module/fo/FoAggregateSink.java +++ b/doxia-modules/doxia-module-fo/src/main/java/org/apache/maven/doxia/module/fo/FoAggregateSink.java @@ -1,869 +1,871 @@ package org.apache.maven.doxia.module.fo; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.Writer; +import java.util.Calendar; import java.util.Iterator; import javax.swing.text.html.HTML.Tag; import org.apache.maven.doxia.document.DocumentMeta; import org.apache.maven.doxia.document.DocumentModel; import org.apache.maven.doxia.document.DocumentTOC; import org.apache.maven.doxia.document.DocumentTOCItem; import org.apache.maven.doxia.util.DoxiaUtils; import org.apache.maven.doxia.util.HtmlTools; import org.codehaus.plexus.util.StringUtils; /** * A Doxia Sink that produces an aggregated FO model. * * @author ltheussl * @version $Id$ * @since 1.0 */ public class FoAggregateSink extends FoSink { /** The document model to be used by this sink. */ private DocumentModel docModel; /** Counts the current chapter level. */ private int chapter = 0; /** Name of the source file of the current document, relative to the source root. */ private String docName; /** Title of the chapter, used in the page header. */ private String docTitle = ""; /** Content in head is ignored in aggregated documents. */ private boolean ignoreText; /** * Constructor. * * @param writer The writer for writing the result. */ public FoAggregateSink( Writer writer ) { super( writer ); } /** {@inheritDoc} */ public void head() { ignoreText = true; } /** {@inheritDoc} */ public void head_() { ignoreText = false; writeEOL(); } /** {@inheritDoc} */ public void title() { // ignored } /** {@inheritDoc} */ public void title_() { // ignored } /** {@inheritDoc} */ public void author() { // ignored } /** {@inheritDoc} */ public void author_() { // ignored } /** {@inheritDoc} */ public void date() { // ignored } /** {@inheritDoc} */ public void date_() { // ignored } /** {@inheritDoc} */ public void body() { chapter++; resetSectionCounter(); startPageSequence( getHeaderText(), getFooterText() ); if ( docName == null ) { getLog().warn( "No document root specified, local links will not be resolved correctly!" ); } else { writeStartTag( BLOCK_TAG, "id", docName ); } } /** {@inheritDoc} */ public void body_() { writeEOL(); writeEndTag( BLOCK_TAG ); writeEndTag( FLOW_TAG ); writeEndTag( PAGE_SEQUENCE_TAG ); // reset document name docName = null; } /** * Sets the title of the current document. This is used as a chapter title in the page header. * * @param title the title of the current document. */ public void setDocumentTitle( String title ) { this.docTitle = title; if ( title == null ) { this.docTitle = ""; } } /** * Sets the name of the current source document, relative to the source root. * Used to resolve links to other source documents. * * @param name the name for the current document. */ public void setDocumentName( String name ) { this.docName = getIdName( name ); } /** * Sets the DocumentModel to be used by this sink. The DocumentModel provides all the meta-information * required to render a document, eg settings for the cover page, table of contents, etc. * * @param model the DocumentModel. */ public void setDocumentModel( DocumentModel model ) { this.docModel = model; } /** * Translates the given name to a usable id. * Prepends "./" and strips any extension. * * @param name the name for the current document. * @return String */ private String getIdName( String name ) { if ( StringUtils.isEmpty( name ) ) { getLog().warn( "Empty document reference, links will not be resolved correctly!" ); return ""; } String idName = name; // prepend "./" and strip extension if ( !idName.startsWith( "./" ) ) { idName = "./" + idName; } if ( idName.indexOf( ".", 2 ) != -1 ) { idName = idName.substring( 0, idName.indexOf( ".", 2 ) ); } return idName; } // ----------------------------------------------------------------------- // // ----------------------------------------------------------------------- /** {@inheritDoc} */ public void anchor( String name ) { if ( name == null ) { throw new NullPointerException( "Anchor name cannot be null!" ); } String anchor = name; if ( !DoxiaUtils.isValidId( anchor ) ) { anchor = DoxiaUtils.encodeId( name ); getLog().warn( "[FO Sink] Modified invalid anchor name: " + name ); } anchor = "#" + anchor; if ( docName != null ) { anchor = docName + anchor; } writeStartTag( INLINE_TAG, "id", anchor ); } /** {@inheritDoc} */ public void link( String name ) { if ( name == null ) { throw new NullPointerException( "Link name cannot be null!" ); } if ( DoxiaUtils.isExternalLink( name ) ) { // external links writeStartTag( BASIC_LINK_TAG, "external-destination", HtmlTools.escapeHTML( name ) ); writeStartTag( INLINE_TAG, "href.external" ); } else if ( DoxiaUtils.isInternalLink( name ) ) { // internal link (ie anchor is in the same source document) String anchor = name.substring( 1 ); if ( !DoxiaUtils.isValidId( anchor ) ) { anchor = DoxiaUtils.encodeId( anchor ); getLog().warn( "[FO Sink] Modified invalid link name: " + name ); } if ( docName != null ) { anchor = docName + "#" + anchor; } writeStartTag( BASIC_LINK_TAG, "internal-destination", HtmlTools.escapeHTML( anchor ) ); writeStartTag( INLINE_TAG, "href.internal" ); } else if ( name.startsWith( "../" ) ) { // local link (ie anchor is not in the same source document) String anchor = name; if ( docName == null ) { // can't resolve link without base, fop will issue a warning writeStartTag( BASIC_LINK_TAG, "internal-destination", HtmlTools.escapeHTML( anchor ) ); writeStartTag( INLINE_TAG, "href.internal" ); return; } String base = docName.substring( 0, docName.lastIndexOf( "/" ) ); if ( base.indexOf( "/" ) != -1 ) { while ( anchor.startsWith( "../" ) ) { base = base.substring( 0, base.lastIndexOf( "/" ) ); anchor = anchor.substring( 3 ); } } anchor = base + "/" + chopExtension ( anchor ); writeStartTag( BASIC_LINK_TAG, "internal-destination", HtmlTools.escapeHTML( anchor ) ); writeStartTag( INLINE_TAG, "href.internal" ); } else { // local link (ie anchor is not in the same source document) String anchor = name; if ( anchor.startsWith( "./" ) ) { anchor = anchor.substring( 2 ); } anchor = chopExtension ( anchor ); String base = docName.substring( 0, docName.lastIndexOf( "/" ) ); anchor = base + "/" + anchor; writeStartTag( BASIC_LINK_TAG, "internal-destination", HtmlTools.escapeHTML( anchor ) ); writeStartTag( INLINE_TAG, "href.internal" ); } } private String chopExtension( String anchor ) { int dot = anchor.indexOf( "." ); if ( dot != -1 ) { int hash = anchor.indexOf( "#", dot ); if ( hash != -1 ) { int dot2 = anchor.indexOf( ".", hash ); if ( dot2 != -1 ) { anchor = anchor.substring( 0, dot ) + "#" + HtmlTools.encodeId( anchor.substring( hash + 1, dot2 ) ); } else { anchor = anchor.substring( 0, dot ) + "#" + HtmlTools.encodeId( anchor.substring( hash + 1, anchor.length() ) ); } } else { anchor = anchor.substring( 0, dot ); } } return anchor; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- /** * Writes a start tag, prepending EOL. * * @param tag The tag. * @param attributeId An id identifying the attribute set. */ protected void writeStartTag( Tag tag, String attributeId ) { if ( !ignoreText ) { super.writeStartTag( tag, attributeId ); } } /** * Writes a start tag, prepending EOL. * * @param tag The tag. * @param id An id to add. * @param name The name (value) of the id. */ protected void writeStartTag( Tag tag, String id, String name ) { if ( !ignoreText ) { super.writeStartTag( tag, id, name ); } } /** * Writes an end tag, appending EOL. * * @param tag The tag. */ protected void writeEndTag( Tag tag ) { if ( !ignoreText ) { super.writeEndTag( tag ); } } /** * Writes a simple tag, appending EOL. * * @param tag The tag. * @param attributeId An id identifying the attribute set. */ protected void writeEmptyTag( Tag tag, String attributeId ) { if ( !ignoreText ) { super.writeEmptyTag( tag, attributeId ); } } /** * Writes a text, swallowing any exceptions. * * @param text The text to write. */ protected void write( String text ) { if ( !ignoreText ) { super.write( text ); } } /** * Writes a text, appending EOL. * * @param text The text to write. */ protected void writeln( String text ) { if ( !ignoreText ) { super.writeln( text ); } } /** * Writes content, escaping special characters. * * @param text The text to write. */ protected void content( String text ) { if ( !ignoreText ) { super.content( text ); } } /** Writes EOL. */ protected void newline() { if ( !ignoreText ) { writeEOL(); } } /** * Starts a page sequence, depending on the current chapter. * * @param headerText The text to write in the header, if null, nothing is written. * @param footerText The text to write in the footer, if null, nothing is written. */ protected void startPageSequence( String headerText, String footerText ) { if ( chapter == 1 ) { startPageSequence( "0", headerText, footerText ); } else { startPageSequence( "auto", headerText, footerText ); } } /** * Returns the text to write in the header of each page. * * @return String */ protected String getHeaderText() { return Integer.toString( chapter ) + " " + docTitle; } /** * Returns the text to write in the footer of each page. * * @return String */ protected String getFooterText() { // TODO: year and company have to come from DocumentMeta - return "&#169;2007 The Apache Software Foundation &#8226; ALL RIGHTS RESERVED"; + int actualYear = Calendar.getInstance().get( Calendar.YEAR ); + return "&#169;" + actualYear + " The Apache Software Foundation &#8226; ALL RIGHTS RESERVED"; } /** * Returns the current chapter number as a string. * * @return String */ protected String getChapterString() { return Integer.toString( chapter ) + "."; } /** * Writes a 'xsl-region-before' block. * * @param headerText The text to write in the header, if null, nothing is written. */ protected void regionBefore( String headerText ) { writeStartTag( STATIC_CONTENT_TAG, "flow-name", "xsl-region-before" ); writeln( "<fo:table table-layout=\"fixed\" width=\"100%\" >" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "5.625in" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "0.625in" ); writeStartTag( TABLE_BODY_TAG, "" ); writeStartTag( TABLE_ROW_TAG, "" ); writeStartTag( TABLE_CELL_TAG, "" ); writeStartTag( BLOCK_TAG, "header.style" ); if ( headerText != null ) { write( headerText ); } writeEndTag( BLOCK_TAG ); writeEndTag( TABLE_CELL_TAG ); writeStartTag( TABLE_CELL_TAG, "" ); writeStartTag( BLOCK_TAG, "page.number" ); writeEmptyTag( PAGE_NUMBER_TAG, "" ); writeEndTag( BLOCK_TAG ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); writeEndTag( TABLE_BODY_TAG ); writeEndTag( TABLE_TAG ); writeEndTag( STATIC_CONTENT_TAG ); } /** * Writes a 'xsl-region-after' block. * * @param footerText The text to write in the footer, if null, nothing is written. */ protected void regionAfter( String footerText ) { writeStartTag( STATIC_CONTENT_TAG, "flow-name", "xsl-region-after" ); writeStartTag( BLOCK_TAG, "footer.style" ); if ( footerText != null ) { write( footerText ); } writeEndTag( BLOCK_TAG ); writeEndTag( STATIC_CONTENT_TAG ); } /** * Writes a chapter heading. * * @param headerText The text to write in the header, if null, the current document title is written. * @param chapterNumber True if the chapter number should be written in front of the text. */ protected void chapterHeading( String headerText, boolean chapterNumber ) { writeStartTag( BLOCK_TAG, "" ); writeStartTag( LIST_BLOCK_TAG, "" ); writeStartTag( LIST_ITEM_TAG, "" ); writeln( "<fo:list-item-label end-indent=\"6.375in\" start-indent=\"-1in\">" ); writeStartTag( BLOCK_TAG, "outdented.number.style" ); if ( chapterNumber ) { write( Integer.toString( chapter ) ); } writeEndTag( BLOCK_TAG ); writeEndTag( LIST_ITEM_LABEL_TAG ); writeln( "<fo:list-item-body end-indent=\"1in\" start-indent=\"0in\">" ); writeStartTag( BLOCK_TAG, "chapter.title" ); if ( headerText == null ) { write( docTitle ); } else { write( headerText ); } writeEndTag( BLOCK_TAG ); writeEndTag( LIST_ITEM_BODY_TAG ); writeEndTag( LIST_ITEM_TAG ); writeEndTag( LIST_BLOCK_TAG ); writeEndTag( BLOCK_TAG ); writeStartTag( BLOCK_TAG, "space-after.optimum", "0em" ); writeEmptyTag( LEADER_TAG, "chapter.rule" ); writeEndTag( BLOCK_TAG ); } /** * Writes a table of contents. The DocumentModel has to contain a DocumentTOC for this to work. */ public void toc() { if ( this.docModel == null ) { return; } DocumentTOC toc = docModel.getToc(); if ( toc == null ) { return; } writeln( "<fo:page-sequence master-reference=\"toc\" initial-page-number=\"1\" format=\"i\">" ); regionBefore( toc.getName() ); regionAfter( getFooterText() ); writeStartTag( FLOW_TAG, "flow-name", "xsl-region-body" ); chapterHeading( toc.getName(), false ); writeln( "<fo:table table-layout=\"fixed\" width=\"100%\" >" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "0.45in" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "0.4in" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "0.4in" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "5in" ); // TODO writeStartTag( TABLE_BODY_TAG, "" ); int count = 0; for ( Iterator k = toc.getItems().iterator(); k.hasNext(); ) { DocumentTOCItem tocItem = (DocumentTOCItem) k.next(); count++; String ref = getIdName( tocItem.getRef() ); writeStartTag( TABLE_ROW_TAG, "keep-with-next", "always" ); writeStartTag( TABLE_CELL_TAG, "toc.cell" ); writeStartTag( BLOCK_TAG, "toc.number.style" ); write( Integer.toString( count ) ); writeEndTag( BLOCK_TAG ); writeEndTag( TABLE_CELL_TAG ); writeStartTag( TABLE_CELL_TAG, "number-columns-spanned", "3", "toc.cell" ); // TODO: writeStartTag( BLOCK_TAG, "text-align-last", "justify", "toc.h1.style" ); writeStartTag( BLOCK_TAG, "toc.h1.style" ); writeStartTag( BASIC_LINK_TAG, "internal-destination", ref ); write( tocItem.getName() ); writeEndTag( BASIC_LINK_TAG ); writeEmptyTag( LEADER_TAG, "toc.leader.style" ); writeStartTag( INLINE_TAG, "page.number" ); writeEmptyTag( PAGE_NUMBER_CITATION_TAG, "ref-id", ref ); writeEndTag( INLINE_TAG ); writeEndTag( BLOCK_TAG ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); } writeEndTag( TABLE_BODY_TAG ); writeEndTag( TABLE_TAG ); writeEndTag( FLOW_TAG ); writeEndTag( PAGE_SEQUENCE_TAG ); } /** * Writes a fo:bookmark-tree. The DocumentModel has to contain a DocumentTOC for this to work. */ protected void pdfBookmarks() { if ( this.docModel == null ) { return; } DocumentTOC toc = docModel.getToc(); if ( toc == null ) { return; } writeStartTag( BOOKMARK_TREE_TAG, "" ); for ( Iterator k = toc.getItems().iterator(); k.hasNext(); ) { DocumentTOCItem tocItem = (DocumentTOCItem) k.next(); String ref = getIdName( tocItem.getRef() ); writeStartTag( BOOKMARK_TAG, "internal-destination", ref ); writeStartTag( BOOKMARK_TITLE_TAG, "" ); write( tocItem.getName() ); writeEndTag( BOOKMARK_TITLE_TAG ); writeEndTag( BOOKMARK_TAG ); } writeEndTag( BOOKMARK_TREE_TAG ); } /** * Writes a cover page. The DocumentModel has to contain a DocumentMeta for this to work. */ public void coverPage() { if ( this.docModel == null ) { return; } DocumentMeta meta = docModel.getMeta(); if ( meta == null ) { return; } String title = meta.getTitle(); String author = meta.getAuthor(); // TODO: remove hard-coded settings writeStartTag( PAGE_SEQUENCE_TAG, "master-reference", "cover-page" ); writeStartTag( FLOW_TAG, "flow-name", "xsl-region-body" ); writeStartTag( BLOCK_TAG, "text-align", "center" ); //writeStartTag( TABLE_TAG, "table-layout", "fixed" ); writeln( "<fo:table table-layout=\"fixed\" width=\"100%\" >" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "3.125in" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "3.125in" ); writeStartTag( TABLE_BODY_TAG, "" ); writeStartTag( TABLE_ROW_TAG, "height", "1.5in" ); writeStartTag( TABLE_CELL_TAG, "" ); // TODO: companyLogo writeEmptyTag( BLOCK_TAG, "" ); writeEndTag( TABLE_CELL_TAG ); writeStartTag( TABLE_CELL_TAG, "" ); // TODO: projectLogo writeEmptyTag( BLOCK_TAG, "" ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); writeln( "<fo:table-row keep-with-previous=\"always\" height=\"0.014in\">" ); writeStartTag( TABLE_CELL_TAG, "number-columns-spanned", "2" ); writeStartTag( BLOCK_TAG, "line-height", "0.014in" ); writeEmptyTag( LEADER_TAG, "chapter.rule" ); writeEndTag( BLOCK_TAG ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); writeStartTag( TABLE_ROW_TAG, "height", "7.447in" ); writeStartTag( TABLE_CELL_TAG, "number-columns-spanned", "2" ); //writeStartTag( TABLE_TAG, "table-layout", "fixed" ); writeln( "<fo:table table-layout=\"fixed\" width=\"100%\" >" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "2.083in" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "2.083in" ); writeEmptyTag( TABLE_COLUMN_TAG, "column-width", "2.083in" ); writeStartTag( TABLE_BODY_TAG, "" ); writeStartTag( TABLE_ROW_TAG, "" ); writeStartTag( TABLE_CELL_TAG, "number-columns-spanned", "3" ); writeEmptyTag( BLOCK_TAG, "" ); writeEmptyTag( BLOCK_TAG, "space-before", "3.2235in" ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); writeStartTag( TABLE_ROW_TAG, "" ); writeStartTag( TABLE_CELL_TAG, "" ); writeEmptyTag( BLOCK_TAG, "space-after", "0.5in" ); writeEndTag( TABLE_CELL_TAG ); writeStartTag( TABLE_CELL_TAG, "number-columns-spanned", "2", "cover.border.left" ); writeStartTag( BLOCK_TAG, "cover.title" ); write( title ); // TODO: version writeEndTag( BLOCK_TAG ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); writeStartTag( TABLE_ROW_TAG, "" ); writeStartTag( TABLE_CELL_TAG, "" ); writeEmptyTag( BLOCK_TAG, "" ); writeEndTag( TABLE_CELL_TAG ); writeStartTag( TABLE_CELL_TAG, "number-columns-spanned", "2", "cover.border.left.bottom" ); writeStartTag( BLOCK_TAG, "cover.subtitle" ); // TODO: sub title (cover type) writeEndTag( BLOCK_TAG ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); writeEndTag( TABLE_BODY_TAG ); writeEndTag( TABLE_TAG ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); writeStartTag( TABLE_ROW_TAG, "height", "0.014in" ); writeStartTag( TABLE_CELL_TAG, "number-columns-spanned", "2" ); writeln( "<fo:block space-after=\"0.2in\" line-height=\"0.014in\">" ); writeEmptyTag( LEADER_TAG, "chapter.rule" ); writeEndTag( BLOCK_TAG ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); writeStartTag( TABLE_ROW_TAG, "" ); writeStartTag( TABLE_CELL_TAG, "number-columns-spanned", "2" ); writeEmptyTag( BLOCK_TAG, "" ); writeEmptyTag( BLOCK_TAG, "space-before", "0.2in" ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); writeStartTag( TABLE_ROW_TAG, "height", "0.3in" ); writeStartTag( TABLE_CELL_TAG, "" ); writeStartTag( BLOCK_TAG, "height", "0.3in", "cover.subtitle" ); write( author ); writeEndTag( BLOCK_TAG ); writeEndTag( TABLE_CELL_TAG ); writeStartTag( TABLE_CELL_TAG, "" ); writeStartTag( BLOCK_TAG, "height", "0.3in", "cover.subtitle" ); // TODO: date writeEndTag( BLOCK_TAG ); writeEndTag( TABLE_CELL_TAG ); writeEndTag( TABLE_ROW_TAG ); writeEndTag( TABLE_BODY_TAG ); writeEndTag( TABLE_TAG ); writeEndTag( BLOCK_TAG ); writeEndTag( FLOW_TAG ); writeEndTag( PAGE_SEQUENCE_TAG ); } }
false
false
null
null
diff --git a/src/com/google/javascript/rhino/jstype/FunctionType.java b/src/com/google/javascript/rhino/jstype/FunctionType.java index fb0be075..c3025a88 100644 --- a/src/com/google/javascript/rhino/jstype/FunctionType.java +++ b/src/com/google/javascript/rhino/jstype/FunctionType.java @@ -1,1115 +1,1123 @@ /* * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Bob Jervis * Google Inc. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package com.google.javascript.rhino.jstype; import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE; import static com.google.javascript.rhino.jstype.JSTypeNative.U2U_CONSTRUCTOR_TYPE; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.javascript.rhino.ErrorReporter; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.Collections; import java.util.List; import java.util.Set; /** * This derived type provides extended information about a function, including * its return type and argument types.<p> * * Note: the parameters list is the LP node that is the parent of the * actual NAME node containing the parsed argument list (annotated with * JSDOC_TYPE_PROP's for the compile-time type of each argument. */ public class FunctionType extends PrototypeObjectType { private static final long serialVersionUID = 1L; private enum Kind { ORDINARY, CONSTRUCTOR, INTERFACE } /** * {@code [[Call]]} property. */ private ArrowType call; /** * The {@code prototype} property. This field is lazily initialized by * {@code #getPrototype()}. The most important reason for lazily * initializing this field is that there are cycles in the native types * graph, so some prototypes must temporarily be {@code null} during * the construction of the graph. * * If non-null, the type must be a PrototypeObjectType. */ private Property prototypeSlot; /** * Whether a function is a constructor, an interface, or just an ordinary * function. */ private final Kind kind; /** * The type of {@code this} in the scope of this function. */ private ObjectType typeOfThis; /** * The function node which this type represents. It may be {@code null}. */ private Node source; /** * The interfaces directly implemented by this function (for constructors) * It is only relevant for constructors. May not be {@code null}. */ private List<ObjectType> implementedInterfaces = ImmutableList.of(); /** * The interfaces directly extendeded by this function (for interfaces) * It is only relevant for constructors. May not be {@code null}. */ private List<ObjectType> extendedInterfaces = ImmutableList.of(); /** * The types which are subtypes of this function. It is only relevant for * constructors and may be {@code null}. */ private List<FunctionType> subTypes; /** * The template type name. May be {@code null}. */ private String templateTypeName; /** Creates an instance for a function that might be a constructor. */ FunctionType(JSTypeRegistry registry, String name, Node source, ArrowType arrowType, ObjectType typeOfThis, String templateTypeName, boolean isConstructor, boolean nativeType) { super(registry, name, registry.getNativeObjectType(JSTypeNative.FUNCTION_INSTANCE_TYPE), nativeType); Preconditions.checkArgument(source == null || Token.FUNCTION == source.getType()); Preconditions.checkNotNull(arrowType); this.source = source; this.kind = isConstructor ? Kind.CONSTRUCTOR : Kind.ORDINARY; if (isConstructor) { this.typeOfThis = typeOfThis != null ? typeOfThis : new InstanceObjectType(registry, this, nativeType); } else { this.typeOfThis = typeOfThis != null ? typeOfThis : registry.getNativeObjectType(JSTypeNative.UNKNOWN_TYPE); } this.call = arrowType; this.templateTypeName = templateTypeName; } /** Creates an instance for a function that is an interface. */ private FunctionType(JSTypeRegistry registry, String name, Node source) { super(registry, name, registry.getNativeObjectType(JSTypeNative.FUNCTION_INSTANCE_TYPE)); Preconditions.checkArgument(source == null || Token.FUNCTION == source.getType()); Preconditions.checkArgument(name != null); this.source = source; this.call = new ArrowType(registry, new Node(Token.LP), null); this.kind = Kind.INTERFACE; this.typeOfThis = new InstanceObjectType(registry, this); } /** Creates an instance for a function that is an interface. */ static FunctionType forInterface( JSTypeRegistry registry, String name, Node source) { return new FunctionType(registry, name, source); } @Override public boolean isInstanceType() { // The universal constructor is its own instance, bizarrely. return isEquivalentTo(registry.getNativeType(U2U_CONSTRUCTOR_TYPE)); } @Override public boolean isConstructor() { return kind == Kind.CONSTRUCTOR; } @Override public boolean isInterface() { return kind == Kind.INTERFACE; } @Override public boolean isOrdinaryFunction() { return kind == Kind.ORDINARY; } @Override public FunctionType toMaybeFunctionType() { return this; } @Override public boolean canBeCalled() { return true; } public boolean hasImplementedInterfaces() { if (!implementedInterfaces.isEmpty()){ return true; } FunctionType superCtor = isConstructor() ? getSuperClassConstructor() : null; if (superCtor != null) { return superCtor.hasImplementedInterfaces(); } return false; } public Iterable<Node> getParameters() { Node n = getParametersNode(); if (n != null) { return n.children(); } else { return Collections.emptySet(); } } /** Gets an LP node that contains all params. May be null. */ public Node getParametersNode() { return call.parameters; } /** Gets the minimum number of arguments that this function requires. */ public int getMinArguments() { // NOTE(nicksantos): There are some native functions that have optional // parameters before required parameters. This algorithm finds the position // of the last required parameter. int i = 0; int min = 0; for (Node n : getParameters()) { i++; if (!n.isOptionalArg() && !n.isVarArgs()) { min = i; } } return min; } /** * Gets the maximum number of arguments that this function requires, * or Integer.MAX_VALUE if this is a variable argument function. */ public int getMaxArguments() { Node params = getParametersNode(); if (params != null) { Node lastParam = params.getLastChild(); if (lastParam == null || !lastParam.isVarArgs()) { return params.getChildCount(); } } return Integer.MAX_VALUE; } public JSType getReturnType() { return call.returnType; } public boolean isReturnTypeInferred() { return call.returnTypeInferred; } /** Gets the internal arrow type. For use by subclasses only. */ ArrowType getInternalArrowType() { return call; } @Override public StaticSlot<JSType> getSlot(String name) { if ("prototype".equals(name)) { // Lazy initialization of the prototype field. getPrototype(); return prototypeSlot; } else { return super.getSlot(name); } } /** * Includes the prototype iff someone has created it. We do not want * to expose the prototype for ordinary functions. */ public Set<String> getOwnPropertyNames() { if (prototypeSlot == null) { return super.getOwnPropertyNames(); } else { Set<String> names = Sets.newHashSet("prototype"); names.addAll(super.getOwnPropertyNames()); return names; } } /** * Gets the {@code prototype} property of this function type. This is * equivalent to {@code (ObjectType) getPropertyType("prototype")}. */ public ObjectType getPrototype() { // lazy initialization of the prototype field if (prototypeSlot == null) { setPrototype( new PrototypeObjectType( registry, this.getReferenceName() + ".prototype", registry.getNativeObjectType(OBJECT_TYPE), isNativeObjectType()), null); } return (ObjectType) prototypeSlot.getType(); } /** * Sets the prototype, creating the prototype object from the given * base type. * @param baseType The base type. */ public void setPrototypeBasedOn(ObjectType baseType) { setPrototypeBasedOn(baseType, null); } void setPrototypeBasedOn(ObjectType baseType, Node propertyNode) { // This is a bit weird. We need to successfully handle these // two cases: // Foo.prototype = new Bar(); // and // Foo.prototype = {baz: 3}; // In the first case, we do not want new properties to get // added to Bar. In the second case, we do want new properties // to get added to the type of the anonymous object. // // We handle this by breaking it into two cases: // // In the first case, we create a new PrototypeObjectType and set // its implicit prototype to the type being assigned. This ensures // that Bar will not get any properties of Foo.prototype, but properties // later assigned to Bar will get inherited properly. // // In the second case, we just use the anonymous object as the prototype. if (baseType.hasReferenceName() || isNativeObjectType() || baseType.isFunctionPrototypeType() || !(baseType instanceof PrototypeObjectType)) { baseType = new PrototypeObjectType( registry, this.getReferenceName() + ".prototype", baseType); } setPrototype((PrototypeObjectType) baseType, propertyNode); } /** * Sets the prototype. * @param prototype the prototype. If this value is {@code null} it will * silently be discarded. */ boolean setPrototype(PrototypeObjectType prototype, Node propertyNode) { if (prototype == null) { return false; } // getInstanceType fails if the function is not a constructor if (isConstructor() && prototype == getInstanceType()) { return false; } PrototypeObjectType oldPrototype = prototypeSlot == null ? null : (PrototypeObjectType) prototypeSlot.getType(); boolean replacedPrototype = oldPrototype != null; this.prototypeSlot = new Property("prototype", prototype, true, propertyNode == null ? source : propertyNode); prototype.setOwnerFunction(this); if (oldPrototype != null) { // Disassociating the old prototype makes this easier to debug-- // we don't have to worry about two prototypes running around. oldPrototype.setOwnerFunction(null); } if (isConstructor() || isInterface()) { FunctionType superClass = getSuperClassConstructor(); if (superClass != null) { superClass.addSubType(this); } if (isInterface()) { for (ObjectType interfaceType : getExtendedInterfaces()) { if (interfaceType.getConstructor() != null) { interfaceType.getConstructor().addSubType(this); } } } } if (replacedPrototype) { clearCachedValues(); } return true; } /** * Returns all interfaces implemented by a class or its superclass and any * superclasses for any of those interfaces. If this is called before all * types are resolved, it may return an incomplete set. */ public Iterable<ObjectType> getAllImplementedInterfaces() { // Store them in a linked hash set, so that the compile job is // deterministic. Set<ObjectType> interfaces = Sets.newLinkedHashSet(); for (ObjectType type : getImplementedInterfaces()) { addRelatedInterfaces(type, interfaces); } return interfaces; } private void addRelatedInterfaces(ObjectType instance, Set<ObjectType> set) { FunctionType constructor = instance.getConstructor(); if (constructor != null) { if (!constructor.isInterface()) { return; } set.add(instance); for (ObjectType interfaceType : instance.getCtorExtendedInterfaces()) { addRelatedInterfaces(interfaceType, set); } } } /** Returns interfaces implemented directly by a class or its superclass. */ public Iterable<ObjectType> getImplementedInterfaces() { FunctionType superCtor = isConstructor() ? getSuperClassConstructor() : null; if (superCtor == null) { return implementedInterfaces; } else { return Iterables.concat( implementedInterfaces, superCtor.getImplementedInterfaces()); } } public void setImplementedInterfaces(List<ObjectType> implementedInterfaces) { // Records this type for each implemented interface. for (ObjectType type : implementedInterfaces) { registry.registerTypeImplementingInterface(this, type); } this.implementedInterfaces = ImmutableList.copyOf(implementedInterfaces); } /** * Returns all extended interfaces declared by an interfaces or its super- * interfaces. If this is called before all types are resolved, it may return * an incomplete set. */ public Iterable<ObjectType> getAllExtendedInterfaces() { // Store them in a linked hash set, so that the compile job is // deterministic. Set<ObjectType> extendedInterfaces = Sets.newLinkedHashSet(); for (ObjectType interfaceType : getExtendedInterfaces()) { addRelatedExtendedInterfaces(interfaceType, extendedInterfaces); } return extendedInterfaces; } private void addRelatedExtendedInterfaces(ObjectType instance, Set<ObjectType> set) { FunctionType constructor = instance.getConstructor(); if (constructor != null) { set.add(instance); for (ObjectType interfaceType : constructor.getExtendedInterfaces()) { addRelatedExtendedInterfaces(interfaceType, set); } } } /** Returns interfaces directly extended by an interface */ public Iterable<ObjectType> getExtendedInterfaces() { return extendedInterfaces; } /** Returns the number of interfaces directly extended by an interface */ public int getExtendedInterfacesCount() { return extendedInterfaces.size(); } public void setExtendedInterfaces(List<ObjectType> extendedInterfaces) throws UnsupportedOperationException { if (isInterface()) { this.extendedInterfaces = ImmutableList.copyOf(extendedInterfaces); } else { throw new UnsupportedOperationException(); } } @Override public JSType getPropertyType(String name) { if (!hasOwnProperty(name)) { if ("call".equals(name)) { // Define the "call" function lazily. Node params = getParametersNode(); if (params == null) { // If there's no params array, don't do any type-checking // in this CALL function. defineDeclaredProperty(name, new FunctionBuilder(registry) .withReturnType(getReturnType()) .build(), source); } else { params = params.cloneTree(); Node thisTypeNode = Node.newString(Token.NAME, "thisType"); thisTypeNode.setJSType( registry.createOptionalNullableType(getTypeOfThis())); params.addChildToFront(thisTypeNode); thisTypeNode.setOptionalArg(true); defineDeclaredProperty(name, new FunctionBuilder(registry) .withParamsNode(params) .withReturnType(getReturnType()) .build(), source); } } else if ("apply".equals(name)) { // Define the "apply" function lazily. FunctionParamBuilder builder = new FunctionParamBuilder(registry); // Ecma-262 says that apply's second argument must be an Array // or an arguments object. We don't model the arguments object, // so let's just be forgiving for now. // TODO(nicksantos): Model the Arguments object. builder.addOptionalParams( registry.createNullableType(getTypeOfThis()), registry.createNullableType( registry.getNativeType(JSTypeNative.OBJECT_TYPE))); defineDeclaredProperty(name, new FunctionBuilder(registry) .withParams(builder) .withReturnType(getReturnType()) .build(), source); } } return super.getPropertyType(name); } @Override boolean defineProperty(String name, JSType type, boolean inferred, Node propertyNode) { if ("prototype".equals(name)) { ObjectType objType = type.toObjectType(); if (objType != null) { if (prototypeSlot != null && objType.isEquivalentTo(prototypeSlot.getType())) { return true; } this.setPrototypeBasedOn(objType, propertyNode); return true; } else { return false; } } return super.defineProperty(name, type, inferred, propertyNode); } @Override public JSType getLeastSupertype(JSType that) { return supAndInfHelper(that, true); } @Override public JSType getGreatestSubtype(JSType that) { return supAndInfHelper(that, false); } /** * Computes the supremum or infimum of functions with other types. * Because sup() and inf() share a lot of logic for functions, we use * a single helper. * @param leastSuper If true, compute the supremum of {@code this} with * {@code that}. Otherwise compute the infimum. * @return The least supertype or greatest subtype. */ private JSType supAndInfHelper(JSType that, boolean leastSuper) { // NOTE(nicksantos): When we remove the unknown type, the function types // form a lattice with the universal constructor at the top of the lattice, // and the LEAST_FUNCTION_TYPE type at the bottom of the lattice. // // When we introduce the unknown type, it's much more difficult to make // heads or tails of the partial ordering of types, because there's no // clear hierarchy between the different components (parameter types and // return types) in the ArrowType. // // Rather than make the situation more complicated by introducing new // types (like unions of functions), we just fallback on the simpler // approach of getting things right at the top and the bottom of the // lattice. if (isFunctionType() && that.isFunctionType()) { if (isEquivalentTo(that)) { return this; } FunctionType other = that.toMaybeFunctionType(); // If these are ordinary functions, then merge them. // Don't do this if any of the params/return // values are unknown, because then there will be cycles in // their local lattice and they will merge in weird ways. if (other != null && isOrdinaryFunction() && that.isOrdinaryFunction() && !this.call.hasUnknownParamsOrReturn() && !other.call.hasUnknownParamsOrReturn()) { // Check for the degenerate case, but double check // that there's not a cycle. boolean isSubtypeOfThat = this.isSubtype(that); boolean isSubtypeOfThis = that.isSubtype(this); if (isSubtypeOfThat && !isSubtypeOfThis) { return leastSuper ? that : this; } else if (isSubtypeOfThis && !isSubtypeOfThat) { return leastSuper ? this : that; } // Merge the two functions component-wise. FunctionType merged = tryMergeFunctionPiecewise(other, leastSuper); if (merged != null) { return merged; } } // The function instance type is a special case // that lives above the rest of the lattice. JSType functionInstance = registry.getNativeType( JSTypeNative.FUNCTION_INSTANCE_TYPE); if (functionInstance.isEquivalentTo(that)) { return leastSuper ? that : this; } else if (functionInstance.isEquivalentTo(this)) { return leastSuper ? this : that; } // In theory, we should be using the GREATEST_FUNCTION_TYPE as the // greatest function. In practice, we don't because it's way too // broad. The greatest function takes var_args None parameters, which // means that all parameters register a type warning. // // Instead, we use the U2U ctor type, which has unknown type args. FunctionType greatestFn = registry.getNativeFunctionType(JSTypeNative.U2U_CONSTRUCTOR_TYPE); FunctionType leastFn = registry.getNativeFunctionType(JSTypeNative.LEAST_FUNCTION_TYPE); return leastSuper ? greatestFn : leastFn; } return leastSuper ? super.getLeastSupertype(that) : super.getGreatestSubtype(that); } /** * Try to get the sup/inf of two functions by looking at the * piecewise components. */ private FunctionType tryMergeFunctionPiecewise( FunctionType other, boolean leastSuper) { Node newParamsNode = null; if (call.hasEqualParameters(other.call)) { newParamsNode = call.parameters; } else { // If the parameters are not equal, don't try to merge them. // Someday, we should try to merge the individual params. return null; } JSType newReturnType = leastSuper ? call.returnType.getLeastSupertype(other.call.returnType) : call.returnType.getGreatestSubtype(other.call.returnType); ObjectType newTypeOfThis = null; if (isEquivalent(typeOfThis, other.typeOfThis)) { newTypeOfThis = typeOfThis; } else { JSType maybeNewTypeOfThis = leastSuper ? typeOfThis.getLeastSupertype(other.typeOfThis) : typeOfThis.getGreatestSubtype(other.typeOfThis); if (maybeNewTypeOfThis instanceof ObjectType) { newTypeOfThis = (ObjectType) maybeNewTypeOfThis; } else { newTypeOfThis = leastSuper ? registry.getNativeObjectType(JSTypeNative.OBJECT_TYPE) : registry.getNativeObjectType(JSTypeNative.NO_OBJECT_TYPE); } } boolean newReturnTypeInferred = call.returnTypeInferred || other.call.returnTypeInferred; return new FunctionType( registry, null, null, new ArrowType( registry, newParamsNode, newReturnType, newReturnTypeInferred), newTypeOfThis, null, false, false); } /** * Given a constructor or an interface type, get its superclass constructor * or {@code null} if none exists. */ public FunctionType getSuperClassConstructor() { Preconditions.checkArgument(isConstructor() || isInterface()); ObjectType maybeSuperInstanceType = getPrototype().getImplicitPrototype(); if (maybeSuperInstanceType == null) { return null; } return maybeSuperInstanceType.getConstructor(); } /** * Given an interface and a property, finds the top-most super interface * that has the property defined (including this interface). */ public static ObjectType getTopDefiningInterface(ObjectType type, String propertyName) { ObjectType foundType = null; if (type.hasProperty(propertyName)) { foundType = type; } for (ObjectType interfaceType : type.getCtorExtendedInterfaces()) { if (interfaceType.hasProperty(propertyName)) { foundType = getTopDefiningInterface(interfaceType, propertyName); } } return foundType; } /** * Given a constructor or an interface type and a property, finds the * top-most superclass that has the property defined (including this * constructor). */ public ObjectType getTopMostDefiningType(String propertyName) { Preconditions.checkState(isConstructor() || isInterface()); Preconditions.checkArgument(getPrototype().hasProperty(propertyName)); FunctionType ctor = this; if (isInterface()) { return getTopDefiningInterface(this.getInstanceType(), propertyName); } ObjectType topInstanceType = ctor.getInstanceType(); while (true) { topInstanceType = ctor.getInstanceType(); ctor = ctor.getSuperClassConstructor(); if (ctor == null || !ctor.getPrototype().hasProperty(propertyName)) { break; } } return topInstanceType; } /** * Two function types are equal if their signatures match. Since they don't * have signatures, two interfaces are equal if their names match. */ @Override public boolean isEquivalentTo(JSType otherType) { FunctionType that = JSType.toMaybeFunctionType(otherType); if (that == null) { return false; } if (this.isConstructor()) { if (that.isConstructor()) { return this == that; } return false; } if (this.isInterface()) { if (that.isInterface()) { return this.getReferenceName().equals(that.getReferenceName()); } return false; } if (that.isInterface()) { return false; } return this.typeOfThis.isEquivalentTo(that.typeOfThis) && this.call.isEquivalentTo(that.call); } @Override public int hashCode() { return isInterface() ? getReferenceName().hashCode() : call.hashCode(); } public boolean hasEqualCallType(FunctionType otherType) { return this.call.isEquivalentTo(otherType.call); } /** * Informally, a function is represented by * {@code function (params): returnType} where the {@code params} is a comma * separated list of types, the first one being a special * {@code this:T} if the function expects a known type for {@code this}. */ @Override public String toString() { if (this == registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE)) { return "Function"; } StringBuilder b = new StringBuilder(32); b.append("function ("); int paramNum = call.parameters.getChildCount(); boolean hasKnownTypeOfThis = !typeOfThis.isUnknownType(); if (hasKnownTypeOfThis) { if (isConstructor()) { b.append("new:"); } else { b.append("this:"); } b.append(typeOfThis.toString()); } if (paramNum > 0) { if (hasKnownTypeOfThis) { b.append(", "); } Node p = call.parameters.getFirstChild(); if (p.isVarArgs()) { appendVarArgsString(b, p.getJSType()); } else { b.append(p.getJSType().toString()); } p = p.getNext(); while (p != null) { b.append(", "); if (p.isVarArgs()) { appendVarArgsString(b, p.getJSType()); } else { b.append(p.getJSType().toString()); } p = p.getNext(); } } b.append("): "); b.append(call.returnType); return b.toString(); } /** Gets the string representation of a var args param. */ private void appendVarArgsString(StringBuilder builder, JSType paramType) { if (paramType.isUnionType()) { // Remove the optionalness from the var arg. paramType = paramType.toMaybeUnionType().getRestrictedUnion( registry.getNativeType(JSTypeNative.VOID_TYPE)); } builder.append("...[").append(paramType.toString()).append("]"); } /** * A function is a subtype of another if their call methods are related via * subtyping and {@code this} is a subtype of {@code that} with regard to * the prototype chain. */ @Override public boolean isSubtype(JSType that) { if (JSType.isSubtype(this, that)) { return true; } if (that.isFunctionType()) { FunctionType other = that.toMaybeFunctionType(); if (other.isInterface()) { // Any function can be assigned to an interface function. return true; } if (this.isInterface()) { // An interface function cannot be assigned to anything. return false; } // If functionA is a subtype of functionB, then their "this" types // should be contravariant. However, this causes problems because // of the way we enforce overrides. Because function(this:SubFoo) // is not a subtype of function(this:Foo), our override check treats // this as an error. It also screws up out standard method // for aliasing constructors. Let's punt on all this for now. // TODO(nicksantos): fix this. boolean treatThisTypesAsCovariant = // If either one of these is a ctor, skip 'this' checking. this.isConstructor() || other.isConstructor() || // An interface 'this'-type is non-restrictive. // In practical terms, if C implements I, and I has a method m, // then any m doesn't necessarily have to C#m's 'this' // type doesn't need to match I. (other.typeOfThis.getConstructor() != null && other.typeOfThis.getConstructor().isInterface()) || // If one of the 'this' types is covariant of the other, // then we'll treat them as covariant (see comment above). other.typeOfThis.isSubtype(this.typeOfThis) || this.typeOfThis.isSubtype(other.typeOfThis); return treatThisTypesAsCovariant && this.call.isSubtype(other.call); } return getNativeType(JSTypeNative.FUNCTION_PROTOTYPE).isSubtype(that); } @Override public <T> T visit(Visitor<T> visitor) { return visitor.caseFunctionType(this); } /** * Gets the type of instance of this function. * @throws IllegalStateException if this function is not a constructor * (see {@link #isConstructor()}). */ public ObjectType getInstanceType() { Preconditions.checkState(hasInstanceType()); return typeOfThis; } /** * Sets the instance type. This should only be used for special * native types. */ void setInstanceType(ObjectType instanceType) { typeOfThis = instanceType; } /** * Returns whether this function type has an instance type. */ public boolean hasInstanceType() { return isConstructor() || isInterface(); } /** * Gets the type of {@code this} in this function. */ @Override public ObjectType getTypeOfThis() { return typeOfThis.isNoObjectType() ? registry.getNativeObjectType(JSTypeNative.OBJECT_TYPE) : typeOfThis; } /** * Gets the source node or null if this is an unknown function. */ public Node getSource() { return source; } /** * Sets the source node. */ public void setSource(Node source) { - if (null == source) { - prototypeSlot = null; + if (prototypeSlot != null) { + // NOTE(bashir): On one hand when source is null we want to drop any + // references to old nodes retained in prototypeSlot. On the other hand + // we cannot simply drop prototypeSlot, so we retain all information + // except the propertyNode for which we use an approximation! These + // details mostly matter in hot-swap passes. + if (source == null || prototypeSlot.getNode() == null) { + prototypeSlot = new Property(prototypeSlot.getName(), + prototypeSlot.getType(), prototypeSlot.isTypeInferred(), source); + } } this.source = source; } /** Adds a type to the list of subtypes for this type. */ private void addSubType(FunctionType subType) { if (subTypes == null) { subTypes = Lists.newArrayList(); } subTypes.add(subType); } @Override public void clearCachedValues() { super.clearCachedValues(); if (subTypes != null) { for (FunctionType subType : subTypes) { subType.clearCachedValues(); } } if (!isNativeObjectType()) { if (hasInstanceType()) { getInstanceType().clearCachedValues(); } if (prototypeSlot != null) { ((PrototypeObjectType) prototypeSlot.getType()).clearCachedValues(); } } } /** * Returns a list of types that are subtypes of this type. This is only valid * for constructor functions, and may be null. This allows a downward * traversal of the subtype graph. */ public List<FunctionType> getSubTypes() { return subTypes; } @Override public boolean hasCachedValues() { return prototypeSlot != null || super.hasCachedValues(); } /** * Gets the template type name. */ public String getTemplateTypeName() { return templateTypeName; } @Override JSType resolveInternal(ErrorReporter t, StaticScope<JSType> scope) { setResolvedTypeInternal(this); call = (ArrowType) safeResolve(call, t, scope); if (prototypeSlot != null) { prototypeSlot.setType( safeResolve(prototypeSlot.getType(), t, scope)); } // Warning about typeOfThis if it doesn't resolve to an ObjectType // is handled further upstream. // // TODO(nicksantos): Handle this correctly if we have a UnionType. // // TODO(nicksantos): In ES3, the runtime coerces "null" to the global // activation object. In ES5, it leaves it as null. Just punt on this // issue for now by coercing out null. This is complicated by the // fact that when most people write @this {Foo}, they really don't // mean "nullable Foo". For certain tags (like @extends) we de-nullify // the name for them. JSType maybeTypeOfThis = safeResolve(typeOfThis, t, scope); if (maybeTypeOfThis != null) { maybeTypeOfThis = maybeTypeOfThis.restrictByNotNullOrUndefined(); } if (maybeTypeOfThis instanceof ObjectType) { typeOfThis = (ObjectType) maybeTypeOfThis; } boolean changed = false; ImmutableList.Builder<ObjectType> resolvedInterfaces = ImmutableList.builder(); for (ObjectType iface : implementedInterfaces) { ObjectType resolvedIface = (ObjectType) iface.resolve(t, scope); resolvedInterfaces.add(resolvedIface); changed |= (resolvedIface != iface); } if (changed) { implementedInterfaces = resolvedInterfaces.build(); } if (subTypes != null) { for (int i = 0; i < subTypes.size(); i++) { subTypes.set( i, JSType.toMaybeFunctionType(subTypes.get(i).resolve(t, scope))); } } return super.resolveInternal(t, scope); } @Override public String toDebugHashCodeString() { if (this == registry.getNativeType(JSTypeNative.FUNCTION_INSTANCE_TYPE)) { return super.toDebugHashCodeString(); } StringBuilder b = new StringBuilder(32); b.append("function ("); int paramNum = call.parameters.getChildCount(); boolean hasKnownTypeOfThis = !typeOfThis.isUnknownType(); if (hasKnownTypeOfThis) { b.append("this:"); b.append(getDebugHashCodeStringOf(typeOfThis)); } if (paramNum > 0) { if (hasKnownTypeOfThis) { b.append(", "); } Node p = call.parameters.getFirstChild(); b.append(getDebugHashCodeStringOf(p.getJSType())); p = p.getNext(); while (p != null) { b.append(", "); b.append(getDebugHashCodeStringOf(p.getJSType())); p = p.getNext(); } } b.append(")"); b.append(": "); b.append(getDebugHashCodeStringOf(call.returnType)); return b.toString(); } private String getDebugHashCodeStringOf(JSType type) { if (type == this) { return "me"; } else { return type.toDebugHashCodeString(); } } }
true
false
null
null
diff --git a/apps/omicsconnect/org/molgenis/omicsconnect/minigui/CleanHome.java b/apps/omicsconnect/org/molgenis/omicsconnect/minigui/CleanHome.java index da12aef35..5befe84f7 100644 --- a/apps/omicsconnect/org/molgenis/omicsconnect/minigui/CleanHome.java +++ b/apps/omicsconnect/org/molgenis/omicsconnect/minigui/CleanHome.java @@ -1,222 +1,221 @@ /* Date: October 5, 2010 * Template: PluginScreenJavaTemplateGen.java.ftl * generator: org.molgenis.generators.ui.PluginScreenJavaTemplateGen 3.3.3 * * THIS FILE IS A TEMPLATE. PLEASE EDIT :-) */ package org.molgenis.omicsconnect.minigui; import org.molgenis.framework.db.Database; import org.molgenis.framework.ui.PluginModel; import org.molgenis.framework.ui.ScreenController; import org.molgenis.framework.ui.html.render.LinkoutRenderDecorator; import org.molgenis.framework.ui.html.render.RenderDecorator; +import org.molgenis.omicsconnect.services.StorageHandler; import org.molgenis.util.Entity; import org.molgenis.util.Tuple; -import filehandling.storage.StorageHandler; - public class CleanHome extends PluginModel<Entity> { private static final long serialVersionUID = -5307970595544892186L; private boolean userIsAdminAndDatabaseIsEmpty; private String validpath; private boolean loggedIn; private RenderDecorator linkouter; private StorageHandler sh; public RenderDecorator getLinkouter() { return linkouter; } public boolean isLoggedIn() { return loggedIn; } public void setLoggedIn(boolean loggedIn) { this.loggedIn = loggedIn; } public String getValidpath() { return validpath; } public void setValidpath(String validpath) { this.validpath = validpath; } public boolean isUserIsAdminAndDatabaseIsEmpty() { return userIsAdminAndDatabaseIsEmpty; } public void setUserIsAdminAndDatabaseIsEmpty(boolean userIsAdminAndDatabaseIsEmpty) { this.userIsAdminAndDatabaseIsEmpty = userIsAdminAndDatabaseIsEmpty; } public CleanHome(String name, ScreenController<?> parent) { super(name, parent); } @Override public String getViewName() { return "org_molgenis_omicsconnect_minigui_CleanHome"; } @Override public String getViewTemplate() { return "org/molgenis/omicsconnect/minigui/CleanHome.ftl"; } @Override public void handleRequest(Database db, Tuple request) { } @Override public void reload(Database db) { if (linkouter == null) { linkouter = new LinkoutRenderDecorator(); } sh = new StorageHandler(db); if (this.getLogin().isAuthenticated()) { this.setLoggedIn(true); } else { this.setLoggedIn(false); } // if (this.getLogin() instanceof DatabaseLogin) // { // try // { // // fails when there is no table 'MolgenisUser', or no // // MolgenisUser named 'admin' // // assume database has not been setup yet // db.find(MolgenisUser.class, new QueryRule("name", Operator.EQUALS, // "admin")).get(0); // } // catch (Exception e) // { // // setup database and report back // String report = ResetXgapDb.reset(this.getDatabase(), true); // if (report.endsWith("SUCCESS")) // { // this.setMessages(new ScreenMessage("Database setup success!", true)); // } // else // { // this.setMessages(new // ScreenMessage("Database setup fail! Review report: " + report, // false)); // } // } // // try // { // // show special dataloader box for admin when the database has // // no investigations // if (this.getLogin().getUserName().equals("admin")) // { // List<Investigation> invList = db.find(Investigation.class); // if (invList.size() == 0) // { // // // flip bool to enable box // setUserIsAdminAndDatabaseIsEmpty(true); // // // since we're now showing the special box, // // find out if there is a validated path and save this // // info // if (sh.hasValidFileStorage(db)) // { // this.setValidpath(sh.getFileStorage(true, db).getAbsolutePath()); // } // else // { // this.setValidpath(null); // } // // } // else // { // setUserIsAdminAndDatabaseIsEmpty(false); // } // } // else // { // setUserIsAdminAndDatabaseIsEmpty(false); // } // } // catch (Exception e) // { // // something went wrong, set boolean to false for safety // setUserIsAdminAndDatabaseIsEmpty(false); // } // // } // else // { // // for simplelogin, just check if there are investigations present // try // { // List<Investigation> invList = db.find(Investigation.class); // if (invList.size() == 0) // { // // // flip bool to enable box // setUserIsAdminAndDatabaseIsEmpty(true); // // // since we're now showing the special box, // // find out if there is a validated path and save this info // if (sh.hasValidFileStorage(db)) // { // this.setValidpath(sh.getFileStorage(true, db).getAbsolutePath()); // } // else // { // this.setValidpath(null); // } // } // else // { // setUserIsAdminAndDatabaseIsEmpty(false); // } // // } // catch (Exception e) // { // // something went wrong, set boolean to false for safety // setUserIsAdminAndDatabaseIsEmpty(false); // } // // } } @Override public boolean isVisible() { // you can use this to hide this plugin, e.g. based on user rights. // e.g. // if(!this.getLogin().hasEditPermission(myEntity)) return false; return true; } }
false
false
null
null
diff --git a/webofneeds/won-core/src/main/java/won/protocol/model/BasicNeedType.java b/webofneeds/won-core/src/main/java/won/protocol/model/BasicNeedType.java index 17b41a97d..bb73daebb 100644 --- a/webofneeds/won-core/src/main/java/won/protocol/model/BasicNeedType.java +++ b/webofneeds/won-core/src/main/java/won/protocol/model/BasicNeedType.java @@ -1,65 +1,65 @@ package won.protocol.model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import won.protocol.vocabulary.WON; import java.net.URI; /** * User: Alan Tus * Date: 17.04.13 * Time: 13:38 */ public enum BasicNeedType { DEMAND("Demand"), SUPPLY("Supply"), - DO_TOGETHER("Do together"), + DO_TOGETHER("Do_together"), CRITIQUE("Critique"); private static final Logger logger = LoggerFactory.getLogger(BasicNeedType.class); private String name; private BasicNeedType(String name) { this.name = name; } public URI getURI() { return URI.create(WON.BASE_URI + name); } /** * Tries to match the given string against all enum values. * * @param fragment string to match * @return matched enum, null otherwise */ public static BasicNeedType parseString(final String fragment) { for (BasicNeedType state : values()) if (state.name.equals(fragment)) return state; logger.warn("No enum could be matched for: {}", fragment); return null; } public BasicNeedType getMatchesWith() { switch (this) { case SUPPLY: return DEMAND; case DEMAND: return SUPPLY; case DO_TOGETHER: return DO_TOGETHER; case CRITIQUE: return CRITIQUE; } logger.warn("BasicNeedType could not be matched."); return null; } }
true
false
null
null
diff --git a/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/xfer/ClientImport.java b/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/xfer/ClientImport.java index 455fd4c0..860e9526 100644 --- a/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/xfer/ClientImport.java +++ b/bundles/org.eclipse.orion.server.servlets/src/org/eclipse/orion/internal/server/servlets/xfer/ClientImport.java @@ -1,339 +1,340 @@ /******************************************************************************* * Copyright (c) 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.orion.internal.server.servlets.xfer; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.*; import java.util.zip.*; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileStore; import org.eclipse.core.runtime.*; import org.eclipse.orion.internal.server.core.IOUtilities; import org.eclipse.orion.internal.server.servlets.ProtocolConstants; import org.eclipse.orion.internal.server.servlets.ServletResourceHandler; import org.eclipse.orion.internal.server.servlets.file.NewFileServlet; import org.eclipse.orion.server.core.ServerStatus; import org.eclipse.osgi.util.NLS; import org.osgi.framework.FrameworkUtil; /** * Represents an import from client operation in progress. */ class ClientImport { private static final String FILE_DATA = "xfer.data"; //$NON-NLS-1$ private static final String FILE_INDEX = "xfer.properties"; //$NON-NLS-1$ private static final String KEY_FILE_NAME = "FileName"; //$NON-NLS-1$ private static final String KEY_LENGTH = "Length"; //$NON-NLS-1$ private static final String KEY_OPTIONS = "Options"; //$NON-NLS-1$ private static final String KEY_PATH = "Path"; //$NON-NLS-1$ private static final String KEY_TRANSFERRED = "Transferred"; //$NON-NLS-1$ /** * The UUID of this import operation. */ private final String id; private Properties props = new Properties(); private final ServletResourceHandler<IStatus> statusHandler; /** * Creates a new import. This may represent an import that has not yet started, * or one that is already underway. */ ClientImport(String id, ServletResourceHandler<IStatus> servletResourceHandler) throws IOException { this.id = id; this.statusHandler = servletResourceHandler; restore(); } /** * Completes a move after a file transfer. Returns <code>true</code> if the move was * successful, and <code>false</code> otherwise. In case of failure, this method * handles setting an appropriate response. */ private boolean completeMove(HttpServletRequest req, HttpServletResponse resp) throws ServletException { IPath destPath = new Path(getPath()).append(getFileName()); try { IFileStore source = EFS.getStore(new File(getStorageDirectory(), FILE_DATA).toURI()); IFileStore destination = NewFileServlet.getFileStore(destPath); source.move(destination, EFS.OVERWRITE, null); } catch (CoreException e) { String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString()); statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); return false; } return true; } /** * We have just received the final chunk of data for a file upload. * Complete the transfer by moving the uploaded content into the * workspace. * @throws IOException */ private void completeTransfer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<String> options = getOptions(); boolean success; if (!options.contains("raw")) { //$NON-NLS-1$ success = completeUnzip(req, resp); } else { success = completeMove(req, resp); } if (success) { resp.setHeader(ProtocolConstants.HEADER_LOCATION, "/file" + getPath()); //$NON-NLS-1$ resp.setStatus(HttpServletResponse.SC_CREATED); + resp.setContentType(ProtocolConstants.CONTENT_TYPE_HTML); resp.getOutputStream().write(new String("<head></head><body><textarea>{}</textarea></body>").getBytes()); } } /** * Unzips the transferred file. Returns <code>true</code> if the unzip was * successful, and <code>false</code> otherwise. In case of failure, this method * handles setting an appropriate response. */ private boolean completeUnzip(HttpServletRequest req, HttpServletResponse resp) throws ServletException { IPath destPath = new Path(getPath()); try { ZipFile source = new ZipFile(new File(getStorageDirectory(), FILE_DATA)); IFileStore destinationRoot = NewFileServlet.getFileStore(destPath); Enumeration<? extends ZipEntry> entries = source.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); IFileStore destination = destinationRoot.getChild(entry.getName()); if (entry.isDirectory()) destination.mkdir(EFS.NONE, null); else { destination.getParent().mkdir(EFS.NONE, null); IOUtilities.pipe(source.getInputStream(entry), destination.openOutputStream(EFS.NONE, null), false, true); } } source.close(); } catch (ZipException e) { //zip exception implies client sent us invalid input String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString()); statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, e)); return false; } catch (Exception e) { //other failures should be considered server errors String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString()); statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e)); return false; } return true; } /** * A post operation represents the beginning of an import operation. This method * initializes the import and sets an appropriate response. */ void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { save(); //if the transfer length header is not specified, then the file is being uploaded during the POST if (req.getHeader(ProtocolConstants.HEADER_XFER_LENGTH) == null) { doPut(req, resp); return; } //otherwise the POST is just starting a transfer to be completed later resp.setStatus(HttpServletResponse.SC_OK); setResponseLocationHeader(req, resp); } private void setResponseLocationHeader(HttpServletRequest req, HttpServletResponse resp) throws ServletException { URI requestURI = ServletResourceHandler.getURI(req); String responsePath = "/" + new Path(requestURI.getPath()).segment(0) + "/import/" + id; //$NON-NLS-1$ //$NON-NLS-2$ URI responseURI; try { responseURI = new URI(requestURI.getScheme(), requestURI.getAuthority(), responsePath, null, null); } catch (URISyntaxException e) { //should not be possible throw new ServletException(e); } resp.setHeader(ProtocolConstants.HEADER_LOCATION, responseURI.toString()); } /** * A put is used to send a chunk of a file. */ void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int transferred = getTransferred(); int length = getLength(); int headerLength = Integer.valueOf(req.getHeader(ProtocolConstants.HEADER_CONTENT_LENGTH)); String rangeString = req.getHeader(ProtocolConstants.HEADER_CONTENT_RANGE); if (rangeString == null) rangeString = "bytes 0-" + (length - 1) + '/' + length; ContentRange range = ContentRange.parse(rangeString); if (length != range.getLength()) { fail(req, resp, "Chunk specifies an incorrect document length"); return; } if (range.getStartByte() > transferred) { fail(req, resp, "Chunk missing; Expected start byte: " + transferred); return; } if (range.getEndByte() < range.getStartByte()) { fail(req, resp, "Invalid range: " + rangeString); return; } int chunkSize = 1 + range.getEndByte() - range.getStartByte(); if (chunkSize != headerLength) { fail(req, resp, "Content-Range doesn't agree with Content-Length"); return; } byte[] chunk = readChunk(req, chunkSize); FileOutputStream fout = null; try { fout = new FileOutputStream(new File(getStorageDirectory(), FILE_DATA), true); FileChannel channel = fout.getChannel(); channel.position(range.getStartByte()); channel.write(ByteBuffer.wrap(chunk)); channel.close(); } finally { try { if (fout != null) fout.close(); } catch (IOException e) { //ignore secondary failure } } transferred = range.getEndByte() + 1; setTransferred(transferred); save(); if (transferred >= length) { completeTransfer(req, resp); return; } resp.setStatus(308);//Resume Incomplete resp.setHeader("Range", "bytes 0-" + range.getEndByte()); setResponseLocationHeader(req, resp); } /** * Reads the chunk of data to be imported from the request's input stream. */ private byte[] readChunk(HttpServletRequest req, int chunkSize) throws IOException { ServletInputStream requestStream = req.getInputStream(); String contentType = req.getHeader(ProtocolConstants.HEADER_CONTENT_TYPE); if (contentType.startsWith("multipart")) //$NON-NLS-1$ return readMultiPartChunk(requestStream, contentType); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(chunkSize); IOUtilities.pipe(requestStream, outputStream, false, false); return outputStream.toByteArray(); } private byte[] readMultiPartChunk(ServletInputStream requestStream, String contentType) throws IOException { //fast forward stream past multi-part header int boundaryOff = contentType.indexOf("boundary="); //$NON-NLS-1$ String boundary = contentType.substring(boundaryOff + 9); BufferedReader reader = new BufferedReader(new InputStreamReader(requestStream, "ISO-8859-1")); //$NON-NLS-1$ StringBuffer out = new StringBuffer(); //skip headers up to the first blank line String line = reader.readLine(); while (line != null && line.length() > 0) line = reader.readLine(); //now process the file char[] buf = new char[1000]; int read; while ((read = reader.read(buf)) > 0) { out.append(buf, 0, read); } //remove the boundary from the output (end of input is \r\n--<boundary>--\r\n) out.setLength(out.length() - (boundary.length() + 8)); return out.toString().getBytes("ISO-8859-1"); //$NON-NLS-1$ } private void fail(HttpServletRequest req, HttpServletResponse resp, String msg) throws ServletException { statusHandler.handleRequest(req, resp, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } private String getFileName() { return props.getProperty(KEY_FILE_NAME, ""); //$NON-NLS-1$ } private int getLength() { return Integer.valueOf(props.getProperty(KEY_LENGTH, "0")); //$NON-NLS-1$ } private List<String> getOptions() { return TransferServlet.getOptions(props.getProperty(KEY_OPTIONS, ""));//$NON-NLS-1$ } private String getPath() { return props.getProperty(KEY_PATH, ""); //$NON-NLS-1$ } private File getStorageDirectory() { return FrameworkUtil.getBundle(ClientImport.class).getDataFile("xfer/" + id); //$NON-NLS-1$ } /** * Returns the number of bytes transferred so far. */ private Integer getTransferred() { return Integer.valueOf(props.getProperty(KEY_TRANSFERRED, "0")); //$NON-NLS-1$ } /** * Load any progress information for the import so far. */ void restore() throws IOException { try { File dir = getStorageDirectory(); File index = new File(dir, FILE_INDEX); props.load(new FileInputStream(index)); } catch (FileNotFoundException e) { //ok if file doesn't exist yet } } void save() throws IOException { File dir = getStorageDirectory(); dir.mkdirs(); File index = new File(dir, FILE_INDEX); props.store(new FileOutputStream(index), null); } public void setFileName(String name) { props.put(KEY_FILE_NAME, name == null ? "" : name); //$NON-NLS-1$ } /** * Sets the total length of the file being imported. */ public void setLength(long length) { props.put(KEY_LENGTH, Long.toString(length)); } public void setOptions(String options) { props.put(KEY_OPTIONS, options == null ? "" : options); //$NON-NLS-1$ } /** * Sets the path of the file in the workspace once the import completes. */ public void setPath(IPath path) { props.put(KEY_PATH, path.toString()); } private void setTransferred(int transferred) { props.put(KEY_TRANSFERRED, Integer.toString(transferred)); } } diff --git a/tests/org.eclipse.orion.server.tests/src/org/eclipse/orion/server/tests/servlets/xfer/TransferTest.java b/tests/org.eclipse.orion.server.tests/src/org/eclipse/orion/server/tests/servlets/xfer/TransferTest.java index bdee6bc5..60dcd084 100644 --- a/tests/org.eclipse.orion.server.tests/src/org/eclipse/orion/server/tests/servlets/xfer/TransferTest.java +++ b/tests/org.eclipse.orion.server.tests/src/org/eclipse/orion/server/tests/servlets/xfer/TransferTest.java @@ -1,201 +1,204 @@ /******************************************************************************* * Copyright (c) 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.orion.server.tests.servlets.xfer; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.meterware.httpunit.*; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.FileLocator; import org.eclipse.orion.internal.server.core.IOUtilities; import org.eclipse.orion.server.tests.ServerTestsActivator; import org.eclipse.orion.server.tests.servlets.files.FileSystemTest; import org.junit.*; import org.xml.sax.SAXException; /** * */ public class TransferTest extends FileSystemTest { WebConversation webConversation; @BeforeClass public static void setupWorkspace() { initializeWorkspaceLocation(); } @After public void removeTempDir() throws CoreException { remove("sample"); } @Before public void setUp() throws CoreException { webConversation = new WebConversation(); webConversation.setExceptionsThrownOnErrorStatus(false); setUpAuthorization(); } @Test public void testImportWithPost() throws CoreException, IOException, SAXException { //create a directory to upload to String directoryPath = "sample/testImportWithPost/path" + System.currentTimeMillis(); createDirectory(directoryPath); //start the import URL entry = ServerTestsActivator.getContext().getBundle().getEntry("testData/importTest/client.zip"); File source = new File(FileLocator.toFileURL(entry).getPath()); long length = source.length(); InputStream in = new BufferedInputStream(new FileInputStream(source)); PostMethodWebRequest request = new PostMethodWebRequest(ServerTestsActivator.getServerLocation() + "/xfer/import/" + directoryPath, in, "application/zip"); request.setHeaderField("Content-Length", "" + length); request.setHeaderField("Content-Type", "application/zip"); setAuthentication(request); WebResponse postResponse = webConversation.getResponse(request); assertEquals(201, postResponse.getResponseCode()); String location = postResponse.getHeaderField("Location"); assertNotNull(location); + String type = postResponse.getHeaderField("Content-Type"); + assertNotNull(type); + assertTrue(type.contains("text/html")); //assert the file has been unzipped in the workspace assertTrue(checkFileExists(directoryPath + "/org.eclipse.e4.webide/static/js/navigate-tree/navigate-tree.js")); } @Test public void testImportAndUnzip() throws CoreException, IOException, SAXException { //create a directory to upload to String directoryPath = "sample/directory/path" + System.currentTimeMillis(); createDirectory(directoryPath); //start the import URL entry = ServerTestsActivator.getContext().getBundle().getEntry("testData/importTest/client.zip"); File source = new File(FileLocator.toFileURL(entry).getPath()); long length = source.length(); PostMethodWebRequest request = new PostMethodWebRequest(ServerTestsActivator.getServerLocation() + "/xfer/import/" + directoryPath); request.setHeaderField("X-Xfer-Content-Length", Long.toString(length)); setAuthentication(request); WebResponse postResponse = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, postResponse.getResponseCode()); String location = postResponse.getHeaderField("Location"); assertNotNull(location); doImport(source, length, location); //assert the file has been unzipped in the workspace assertTrue(checkFileExists(directoryPath + "/org.eclipse.e4.webide/static/js/navigate-tree/navigate-tree.js")); } /** * Tests attempting to import and unzip a file that is not a zip file. */ @Test public void testImportUnzipNonZipFile() throws CoreException, IOException, SAXException { //create a directory to upload to String directoryPath = "sample/testImportWithPost/path" + System.currentTimeMillis(); createDirectory(directoryPath); //start the import URL entry = ServerTestsActivator.getContext().getBundle().getEntry("testData/importTest/junk.zip"); File source = new File(FileLocator.toFileURL(entry).getPath()); long length = source.length(); InputStream in = new BufferedInputStream(new FileInputStream(source)); PostMethodWebRequest request = new PostMethodWebRequest(ServerTestsActivator.getServerLocation() + "/xfer/import/" + directoryPath, in, "application/zip"); request.setHeaderField("Content-Length", "" + length); request.setHeaderField("Content-Type", "application/zip"); setAuthentication(request); WebResponse postResponse = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, postResponse.getResponseCode()); } @Test public void testImportFile() throws CoreException, IOException, SAXException { //create a directory to upload to String directoryPath = "sample/directory/path" + System.currentTimeMillis(); createDirectory(directoryPath); //start the import URL entry = ServerTestsActivator.getContext().getBundle().getEntry("testData/importTest/client.zip"); File source = new File(FileLocator.toFileURL(entry).getPath()); long length = source.length(); PostMethodWebRequest request = new PostMethodWebRequest(ServerTestsActivator.getServerLocation() + "/xfer/import/" + directoryPath); request.setHeaderField("X-Xfer-Content-Length", Long.toString(length)); request.setHeaderField("X-Xfer-Options", "raw"); request.setHeaderField("Slug", "client.zip"); setAuthentication(request); WebResponse postResponse = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, postResponse.getResponseCode()); String location = postResponse.getHeaderField("Location"); assertNotNull(location); doImport(source, length, location); //assert the file is present in the workspace assertTrue(checkFileExists(directoryPath + "/client.zip")); } @Test public void testExportProject() throws CoreException, IOException, SAXException { //create content to export String directoryPath = "sample/directory/path" + System.currentTimeMillis(); createDirectory(directoryPath); String fileContents = "This is the file contents"; createFile(directoryPath + "/file.txt", fileContents); GetMethodWebRequest export = new GetMethodWebRequest(ServerTestsActivator.getServerLocation() + "/xfer/export/" + directoryPath + ".zip"); setAuthentication(export); WebResponse response = webConversation.getResponse(export); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); boolean found = false; ZipInputStream in = new ZipInputStream(response.getInputStream()); ZipEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.getName().equals("file.txt")) { found = true; ByteArrayOutputStream bytes = new ByteArrayOutputStream(); IOUtilities.pipe(in, bytes, false, false); assertEquals(fileContents, new String(bytes.toByteArray())); } } assertTrue(found); } private void doImport(File source, long length, String location) throws FileNotFoundException, IOException, SAXException { //repeat putting chunks until done byte[] chunk = new byte[64 * 1024]; InputStream in = new BufferedInputStream(new FileInputStream(source)); int chunkSize = 0; int totalTransferred = 0; while ((chunkSize = in.read(chunk, 0, chunk.length)) > 0) { PutMethodWebRequest put = new PutMethodWebRequest(location, new ByteArrayInputStream(chunk, 0, chunkSize), "application/zip"); put.setHeaderField("Content-Range", "bytes " + totalTransferred + "-" + (totalTransferred + chunkSize - 1) + "/" + length); put.setHeaderField("Content-Length", "" + length); put.setHeaderField("Content-Type", "application/zip"); setAuthentication(put); totalTransferred += chunkSize; WebResponse putResponse = webConversation.getResponse(put); if (totalTransferred == length) { assertEquals(201, putResponse.getResponseCode()); } else { assertEquals(308, putResponse.getResponseCode()); String range = putResponse.getHeaderField("Range"); assertEquals("bytes 0-" + (totalTransferred - 1), range); } } } }
false
false
null
null
diff --git a/src/main/java/com/ning/http/multipart/MultipartBody.java b/src/main/java/com/ning/http/multipart/MultipartBody.java index 83fa17530..cd1b8d2f2 100644 --- a/src/main/java/com/ning/http/multipart/MultipartBody.java +++ b/src/main/java/com/ning/http/multipart/MultipartBody.java @@ -1,560 +1,561 @@ /* * Copyright (c) 2010-2011 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.ning.http.multipart; import com.ning.http.client.RandomAccessBody; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import java.util.ArrayList; import java.util.List; public class MultipartBody implements RandomAccessBody { private byte[] boundary; private long contentLength; private List<com.ning.http.client.Part> parts; private List<RandomAccessFile> files; private int startPart; private final static Logger logger = LoggerFactory.getLogger(MultipartBody.class); ByteArrayInputStream currentStream; int currentStreamPosition; boolean endWritten; boolean doneWritingParts; FileLocation fileLocation; FilePart currentFilePart; FileChannel currentFileChannel; enum FileLocation {NONE, START, MIDDLE, END} public MultipartBody(List<com.ning.http.client.Part> parts, String boundary, String contentLength) { this.boundary = MultipartEncodingUtil.getAsciiBytes(boundary.substring("multipart/form-data; boundary=".length())); this.contentLength = Long.parseLong(contentLength); this.parts = parts; files = new ArrayList<RandomAccessFile>(); startPart = 0; currentStreamPosition = -1; endWritten = false; doneWritingParts = false; fileLocation = FileLocation.NONE; currentFilePart = null; } public void close() throws IOException { for (RandomAccessFile file : files) { file.close(); } } public long getContentLength() { return contentLength; } public long read(ByteBuffer buffer) throws IOException { try { int overallLength = 0; int maxLength = buffer.capacity(); if (startPart == parts.size() && endWritten) { return overallLength; } boolean full = false; while (!full && !doneWritingParts) { com.ning.http.client.Part part = null; if (startPart < parts.size()) { part = parts.get(startPart); } if (currentFileChannel != null) { overallLength += currentFileChannel.read(buffer); if (currentFileChannel.position() == currentFileChannel.size()) { currentFileChannel.close(); currentFileChannel = null; } if (overallLength == maxLength) { full = true; } } else if (currentStreamPosition > -1) { overallLength += writeToBuffer(buffer, maxLength - overallLength); if (overallLength == maxLength) { full = true; } if (startPart == parts.size() && currentStream.available() == 0) { doneWritingParts = true; } } else if (part instanceof StringPart) { StringPart currentPart = (StringPart) part; initializeStringPart(currentPart); startPart++; } else if (part instanceof com.ning.http.client.StringPart) { StringPart currentPart = generateClientStringpart(part); initializeStringPart(currentPart); startPart++; } else if (part instanceof FilePart) { if (fileLocation == FileLocation.NONE) { currentFilePart = (FilePart) part; initializeFilePart(currentFilePart); } else if (fileLocation == FileLocation.START) { initializeFileBody(currentFilePart); } else if (fileLocation == FileLocation.MIDDLE) { initializeFileEnd(currentFilePart); } else if (fileLocation == FileLocation.END) { startPart++; if (startPart == parts.size() && currentStream.available() == 0) { doneWritingParts = true; } } } else if (part instanceof com.ning.http.client.FilePart) { if (fileLocation == FileLocation.NONE) { currentFilePart = generateClientFilePart(part); initializeFilePart(currentFilePart); } else if (fileLocation == FileLocation.START) { initializeFileBody(currentFilePart); } else if (fileLocation == FileLocation.MIDDLE) { initializeFileEnd(currentFilePart); } else if (fileLocation == FileLocation.END) { startPart++; if (startPart == parts.size() && currentStream.available() == 0) { doneWritingParts = true; } } } else if (part instanceof com.ning.http.client.ByteArrayPart) { com.ning.http.client.ByteArrayPart bytePart = (com.ning.http.client.ByteArrayPart) part; if (fileLocation == FileLocation.NONE) { currentFilePart = generateClientByteArrayPart(bytePart); initializeFilePart(currentFilePart); } else if (fileLocation == FileLocation.START) { initializeByteArrayBody(currentFilePart); } else if (fileLocation == FileLocation.MIDDLE) { initializeFileEnd(currentFilePart); } else if (fileLocation == FileLocation.END) { startPart++; if (startPart == parts.size() && currentStream.available() == 0) { doneWritingParts = true; } } } } if (doneWritingParts) { if (currentStreamPosition == -1) { ByteArrayOutputStream endWriter = new ByteArrayOutputStream(); Part.sendMessageEnd(endWriter, boundary); initializeBuffer(endWriter); } if (currentStreamPosition > -1) { overallLength += writeToBuffer(buffer, maxLength - overallLength); if (currentStream.available() == 0) { currentStream.close(); currentStreamPosition = -1; endWritten = true; } } } return overallLength; } catch (Exception e) { logger.info("read exception", e); return 0; } } private void initializeByteArrayBody(FilePart filePart) throws IOException { ByteArrayOutputStream output = generateByteArrayBody(filePart); initializeBuffer(output); fileLocation = FileLocation.MIDDLE; } private void initializeFileEnd(FilePart currentPart) throws IOException { ByteArrayOutputStream output = generateFileEnd(currentPart); initializeBuffer(output); fileLocation = FileLocation.END; } private void initializeFileBody(FilePart currentPart) throws IOException { if (FilePartSource.class.isAssignableFrom(currentPart.getSource().getClass())) { FilePartSource source = (FilePartSource) currentPart.getSource(); File file = source.getFile(); RandomAccessFile raf = new RandomAccessFile(file, "r"); files.add(raf); currentFileChannel = raf.getChannel(); } else { PartSource partSource = currentPart.getSource(); InputStream stream = partSource.createInputStream(); byte[] bytes = new byte[(int) partSource.getLength()]; stream.read(bytes); currentStream = new ByteArrayInputStream(bytes); currentStreamPosition = 0; } fileLocation = FileLocation.MIDDLE; } private void initializeFilePart(FilePart filePart) throws IOException { filePart.setPartBoundary(boundary); ByteArrayOutputStream output = generateFileStart(filePart); initializeBuffer(output); fileLocation = FileLocation.START; } private void initializeStringPart(StringPart currentPart) throws IOException { currentPart.setPartBoundary(boundary); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Part.sendPart(outputStream, currentPart, boundary); initializeBuffer(outputStream); } private int writeToBuffer(ByteBuffer buffer, int length) throws IOException { int available = currentStream.available(); int writeLength = Math.min(available, length); byte[] bytes = new byte[writeLength]; currentStream.read(bytes); buffer.put(bytes); if (available <= length) { currentStream.close(); currentStreamPosition = -1; } else { currentStreamPosition += writeLength; } return writeLength; } private void initializeBuffer(ByteArrayOutputStream outputStream) throws IOException { currentStream = new ByteArrayInputStream(outputStream.toByteArray()); currentStreamPosition = 0; } public long transferTo(long position, long count, WritableByteChannel target) throws IOException { long overallLength = 0; if (startPart == parts.size()) { return contentLength; } int tempPart = startPart; for (com.ning.http.client.Part part : parts) { if (part instanceof Part) { overallLength += handleMultiPart(target, (Part) part); } else { overallLength += handleClientPart(target, part); } tempPart++; } ByteArrayOutputStream endWriter = new ByteArrayOutputStream(); Part.sendMessageEnd(endWriter, boundary); overallLength += writeToTarget(target, endWriter); startPart = tempPart; return overallLength; } private long handleClientPart( WritableByteChannel target, com.ning.http.client.Part part) throws IOException { if (part.getClass().equals(com.ning.http.client.StringPart.class)) { StringPart currentPart = generateClientStringpart(part); return handleStringPart(target, currentPart); } else if (part.getClass().equals(com.ning.http.client.FilePart.class)) { FilePart filePart = generateClientFilePart(part); return handleFilePart(target, filePart); } else if (part.getClass().equals(com.ning.http.client.ByteArrayPart.class)) { com.ning.http.client.ByteArrayPart bytePart = (com.ning.http.client.ByteArrayPart) part; FilePart filePart = generateClientByteArrayPart(bytePart); return handleByteArrayPart(target, filePart, bytePart.getData()); } return 0; } private FilePart generateClientByteArrayPart( com.ning.http.client.ByteArrayPart bytePart) { ByteArrayPartSource source = new ByteArrayPartSource(bytePart.getFileName(), bytePart.getData()); FilePart filePart = new FilePart(bytePart.getName(), source, bytePart.getMimeType(), bytePart.getCharSet()); return filePart; } private FilePart generateClientFilePart(com.ning.http.client.Part part) throws FileNotFoundException { com.ning.http.client.FilePart currentPart = (com.ning.http.client.FilePart) part; FilePart filePart = new FilePart(currentPart.getName(), currentPart.getFile(), currentPart.getMimeType(), currentPart.getCharSet()); return filePart; } private StringPart generateClientStringpart(com.ning.http.client.Part part) { com.ning.http.client.StringPart stringPart = (com.ning.http.client.StringPart) part; StringPart currentPart = new StringPart(stringPart.getName(), stringPart.getValue(), stringPart.getCharset()); return currentPart; } private long handleByteArrayPart(WritableByteChannel target, FilePart filePart, byte[] data) throws IOException { ByteArrayOutputStream output = generateByteArrayBody(filePart); return writeToTarget(target, output); } private ByteArrayOutputStream generateByteArrayBody(FilePart filePart) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); Part.sendPart(output, filePart, boundary); return output; } private long handleFileEnd(WritableByteChannel target, FilePart filePart) throws IOException { ByteArrayOutputStream endOverhead = generateFileEnd(filePart); return this.writeToTarget(target, endOverhead); } private ByteArrayOutputStream generateFileEnd(FilePart filePart) throws IOException { ByteArrayOutputStream endOverhead = new ByteArrayOutputStream(); filePart.sendEnd(endOverhead); return endOverhead; } private long handleFileHeaders(WritableByteChannel target, FilePart filePart) throws IOException { filePart.setPartBoundary(boundary); ByteArrayOutputStream overhead = generateFileStart(filePart); return writeToTarget(target, overhead); } private ByteArrayOutputStream generateFileStart(FilePart filePart) throws IOException { ByteArrayOutputStream overhead = new ByteArrayOutputStream(); filePart.setPartBoundary(boundary); filePart.sendStart(overhead); filePart.sendDispositionHeader(overhead); filePart.sendContentTypeHeader(overhead); filePart.sendTransferEncodingHeader(overhead); filePart.sendEndOfHeader(overhead); return overhead; } private long handleFilePart(WritableByteChannel target, FilePart filePart) throws IOException { if (FilePartSource.class.isAssignableFrom(filePart.getSource().getClass())) { int length = 0; length += handleFileHeaders(target, filePart); FilePartSource source = (FilePartSource) filePart.getSource(); File file = source.getFile(); RandomAccessFile raf = new RandomAccessFile(file, "r"); files.add(raf); FileChannel fc = raf.getChannel(); long l = file.length(); int fileLength = 0; long nWrite = 0; synchronized (fc) { while (fileLength != l) { nWrite = fc.transferTo(fileLength, l, target); if (nWrite == 0 ) { logger.info("Waiting for writing..."); try { fc.wait(1000); } catch (InterruptedException e) { logger.trace(e.getMessage(), e); } } fileLength += nWrite; } } fc.close(); length += handleFileEnd(target, filePart); return length; } else { return handlePartSource(target, filePart); } } private long handlePartSource(WritableByteChannel target, FilePart filePart) throws IOException { int length = 0; length += handleFileHeaders(target, filePart); PartSource partSource = filePart.getSource(); InputStream stream = partSource.createInputStream(); try { int nRead = 0; while (nRead != -1) { // Do not buffer the entire monster in memory. byte[] bytes = new byte[8192]; nRead = stream.read(bytes); if (nRead > 0) { ByteArrayOutputStream bos = new ByteArrayOutputStream(nRead); bos.write(bytes, 0, nRead); writeToTarget(target, bos); } } } finally { stream.close(); } length += handleFileEnd(target, filePart); return length; } private long handleStringPart(WritableByteChannel target, StringPart currentPart) throws IOException { currentPart.setPartBoundary(boundary); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Part.sendPart(outputStream, currentPart, boundary); return writeToTarget(target, outputStream); } private long handleMultiPart(WritableByteChannel target, Part currentPart) throws IOException { currentPart.setPartBoundary(boundary); if (currentPart.getClass().equals(StringPart.class)) { return handleStringPart(target, (StringPart) currentPart); } else if (currentPart.getClass().equals(FilePart.class)) { FilePart filePart = (FilePart) currentPart; return handleFilePart(target, filePart); } return 0; } private long writeToTarget(WritableByteChannel target, ByteArrayOutputStream byteWriter) throws IOException { int written = 0; int maxSpin = 0; synchronized (byteWriter) { ByteBuffer message = ByteBuffer.wrap(byteWriter.toByteArray()); while ((target.isOpen()) && (written < byteWriter.size())) { - written += target.write(message); - if (written == 0 && maxSpin++ < 10) { + long nWrite = target.write(message); + written += nWrite; + if (nWrite == 0 && maxSpin++ < 10) { logger.info("Waiting for writing..."); try { byteWriter.wait(1000); } catch (InterruptedException e) { logger.trace(e.getMessage(), e); } } else { if (maxSpin >= 10) { throw new IOException("Unable to write on channel " + target); } maxSpin = 0; } } } return written; } }
true
false
null
null
diff --git a/src/com/android/calendar/event/EditEventView.java b/src/com/android/calendar/event/EditEventView.java index e025153f..2ec8f674 100644 --- a/src/com/android/calendar/event/EditEventView.java +++ b/src/com/android/calendar/event/EditEventView.java @@ -1,1835 +1,1835 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.calendar.event; import android.app.Activity; import android.app.AlertDialog; import android.app.DialogFragment; import android.app.FragmentManager; import android.app.ProgressDialog; import android.app.Service; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.provider.CalendarContract; import android.provider.CalendarContract.Attendees; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.provider.CalendarContract.Reminders; import android.provider.Settings; import android.text.InputFilter; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.text.util.Rfc822Tokenizer; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityManager; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.MultiAutoCompleteTextView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.ResourceCursorAdapter; import android.widget.ScrollView; import android.widget.Spinner; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.android.calendar.CalendarEventModel; import com.android.calendar.CalendarEventModel.Attendee; import com.android.calendar.CalendarEventModel.ReminderEntry; import com.android.calendar.EmailAddressAdapter; import com.android.calendar.EventInfoFragment; import com.android.calendar.EventRecurrenceFormatter; import com.android.calendar.GeneralPreferences; import com.android.calendar.R; import com.android.calendar.RecipientAdapter; import com.android.calendar.Utils; import com.android.calendar.event.EditEventHelper.EditDoneRunnable; import com.android.calendar.recurrencepicker.RecurrencePickerDialog; import com.android.calendarcommon2.EventRecurrence; import com.android.common.Rfc822InputFilter; import com.android.common.Rfc822Validator; import com.android.datetimepicker.date.DatePickerDialog; import com.android.datetimepicker.date.DatePickerDialog.OnDateSetListener; import com.android.datetimepicker.time.RadialPickerLayout; import com.android.datetimepicker.time.TimePickerDialog; import com.android.datetimepicker.time.TimePickerDialog.OnTimeSetListener; import com.android.ex.chips.AccountSpecifier; import com.android.ex.chips.BaseRecipientAdapter; import com.android.ex.chips.ChipsUtil; import com.android.ex.chips.RecipientEditTextView; import com.android.timezonepicker.TimeZoneInfo; import com.android.timezonepicker.TimeZonePickerDialog; import com.android.timezonepicker.TimeZonePickerUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Formatter; import java.util.HashMap; import java.util.Locale; import java.util.TimeZone; public class EditEventView implements View.OnClickListener, DialogInterface.OnCancelListener, DialogInterface.OnClickListener, OnItemSelectedListener, RecurrencePickerDialog.OnRecurrenceSetListener, TimeZonePickerDialog.OnTimeZoneSetListener { private static final String TAG = "EditEvent"; private static final String GOOGLE_SECONDARY_CALENDAR = "calendar.google.com"; private static final String PERIOD_SPACE = ". "; private static final String FRAG_TAG_DATE_PICKER = "datePickerDialogFragment"; private static final String FRAG_TAG_TIME_PICKER = "timePickerDialogFragment"; private static final String FRAG_TAG_TIME_ZONE_PICKER = "timeZonePickerDialogFragment"; private static final String FRAG_TAG_RECUR_PICKER = "recurrencePickerDialogFragment"; ArrayList<View> mEditOnlyList = new ArrayList<View>(); ArrayList<View> mEditViewList = new ArrayList<View>(); ArrayList<View> mViewOnlyList = new ArrayList<View>(); TextView mLoadingMessage; ScrollView mScrollView; Button mStartDateButton; Button mEndDateButton; Button mStartTimeButton; Button mEndTimeButton; Button mTimezoneButton; View mColorPickerNewEvent; View mColorPickerExistingEvent; OnClickListener mChangeColorOnClickListener; View mTimezoneRow; TextView mStartTimeHome; TextView mStartDateHome; TextView mEndTimeHome; TextView mEndDateHome; CheckBox mAllDayCheckBox; Spinner mCalendarsSpinner; Button mRruleButton; Spinner mAvailabilitySpinner; Spinner mAccessLevelSpinner; RadioGroup mResponseRadioGroup; TextView mTitleTextView; AutoCompleteTextView mLocationTextView; EventLocationAdapter mLocationAdapter; TextView mDescriptionTextView; TextView mWhenView; TextView mTimezoneTextView; TextView mTimezoneLabel; LinearLayout mRemindersContainer; MultiAutoCompleteTextView mAttendeesList; View mCalendarSelectorGroup; View mCalendarSelectorWrapper; View mCalendarStaticGroup; View mLocationGroup; View mDescriptionGroup; View mRemindersGroup; View mResponseGroup; View mOrganizerGroup; View mAttendeesGroup; View mStartHomeGroup; View mEndHomeGroup; private int[] mOriginalPadding = new int[4]; public boolean mIsMultipane; private ProgressDialog mLoadingCalendarsDialog; private AlertDialog mNoCalendarsDialog; private DialogFragment mTimezoneDialog; private Activity mActivity; private EditDoneRunnable mDone; private View mView; private CalendarEventModel mModel; private Cursor mCalendarsCursor; private AccountSpecifier mAddressAdapter; private Rfc822Validator mEmailValidator; public boolean mTimeSelectedWasStartTime; public boolean mDateSelectedWasStartDate; private TimePickerDialog mStartTimePickerDialog; private TimePickerDialog mEndTimePickerDialog; private DatePickerDialog mDatePickerDialog; /** * Contents of the "minutes" spinner. This has default values from the XML file, augmented * with any additional values that were already associated with the event. */ private ArrayList<Integer> mReminderMinuteValues; private ArrayList<String> mReminderMinuteLabels; /** * Contents of the "methods" spinner. The "values" list specifies the method constant * (e.g. {@link Reminders#METHOD_ALERT}) associated with the labels. Any methods that * aren't allowed by the Calendar will be removed. */ private ArrayList<Integer> mReminderMethodValues; private ArrayList<String> mReminderMethodLabels; /** * Contents of the "availability" spinner. The "values" list specifies the * type constant (e.g. {@link Events#AVAILABILITY_BUSY}) associated with the * labels. Any types that aren't allowed by the Calendar will be removed. */ private ArrayList<Integer> mAvailabilityValues; private ArrayList<String> mAvailabilityLabels; private ArrayList<String> mOriginalAvailabilityLabels; private ArrayAdapter<String> mAvailabilityAdapter; private boolean mAvailabilityExplicitlySet; private boolean mAllDayChangingAvailability; private int mAvailabilityCurrentlySelected; private int mDefaultReminderMinutes; private boolean mSaveAfterQueryComplete = false; private TimeZonePickerUtils mTzPickerUtils; private Time mStartTime; private Time mEndTime; private String mTimezone; private boolean mAllDay = false; private int mModification = EditEventHelper.MODIFY_UNINITIALIZED; private EventRecurrence mEventRecurrence = new EventRecurrence(); private ArrayList<LinearLayout> mReminderItems = new ArrayList<LinearLayout>(0); private ArrayList<ReminderEntry> mUnsupportedReminders = new ArrayList<ReminderEntry>(); private String mRrule; private static StringBuilder mSB = new StringBuilder(50); private static Formatter mF = new Formatter(mSB, Locale.getDefault()); /* This class is used to update the time buttons. */ private class TimeListener implements OnTimeSetListener { private View mView; public TimeListener(View view) { mView = view; } @Override public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) { // Cache the member variables locally to avoid inner class overhead. Time startTime = mStartTime; Time endTime = mEndTime; // Cache the start and end millis so that we limit the number // of calls to normalize() and toMillis(), which are fairly // expensive. long startMillis; long endMillis; if (mView == mStartTimeButton) { // The start time was changed. int hourDuration = endTime.hour - startTime.hour; int minuteDuration = endTime.minute - startTime.minute; startTime.hour = hourOfDay; startTime.minute = minute; startMillis = startTime.normalize(true); // Also update the end time to keep the duration constant. endTime.hour = hourOfDay + hourDuration; endTime.minute = minute + minuteDuration; // Update tz in case the start time switched from/to DLS populateTimezone(startMillis); } else { // The end time was changed. startMillis = startTime.toMillis(true); endTime.hour = hourOfDay; endTime.minute = minute; // Move to the start time if the end time is before the start // time. if (endTime.before(startTime)) { endTime.monthDay = startTime.monthDay + 1; } // Call populateTimezone if we support end time zone as well } endMillis = endTime.normalize(true); setDate(mEndDateButton, endMillis); setTime(mStartTimeButton, startMillis); setTime(mEndTimeButton, endMillis); updateHomeTime(); } } private class TimeClickListener implements View.OnClickListener { private Time mTime; public TimeClickListener(Time time) { mTime = time; } @Override public void onClick(View v) { TimePickerDialog dialog; if (v == mStartTimeButton) { mTimeSelectedWasStartTime = true; if (mStartTimePickerDialog == null) { mStartTimePickerDialog = TimePickerDialog.newInstance(new TimeListener(v), mTime.hour, mTime.minute, DateFormat.is24HourFormat(mActivity)); } else { mStartTimePickerDialog.setStartTime(mTime.hour, mTime.minute); } dialog = mStartTimePickerDialog; } else { mTimeSelectedWasStartTime = false; if (mEndTimePickerDialog == null) { mEndTimePickerDialog = TimePickerDialog.newInstance(new TimeListener(v), mTime.hour, mTime.minute, DateFormat.is24HourFormat(mActivity)); } else { mEndTimePickerDialog.setStartTime(mTime.hour, mTime.minute); } dialog = mEndTimePickerDialog; } final FragmentManager fm = mActivity.getFragmentManager(); fm.executePendingTransactions(); if (dialog != null && !dialog.isAdded()) { dialog.show(fm, FRAG_TAG_TIME_PICKER); } } } private class DateListener implements OnDateSetListener { View mView; public DateListener(View view) { mView = view; } @Override public void onDateSet(DatePickerDialog view, int year, int month, int monthDay) { Log.d(TAG, "onDateSet: " + year + " " + month + " " + monthDay); // Cache the member variables locally to avoid inner class overhead. Time startTime = mStartTime; Time endTime = mEndTime; // Cache the start and end millis so that we limit the number // of calls to normalize() and toMillis(), which are fairly // expensive. long startMillis; long endMillis; if (mView == mStartDateButton) { // The start date was changed. int yearDuration = endTime.year - startTime.year; int monthDuration = endTime.month - startTime.month; int monthDayDuration = endTime.monthDay - startTime.monthDay; startTime.year = year; startTime.month = month; startTime.monthDay = monthDay; startMillis = startTime.normalize(true); // Also update the end date to keep the duration constant. endTime.year = year + yearDuration; endTime.month = month + monthDuration; endTime.monthDay = monthDay + monthDayDuration; endMillis = endTime.normalize(true); // If the start date has changed then update the repeats. populateRepeats(); // Update tz in case the start time switched from/to DLS populateTimezone(startMillis); } else { // The end date was changed. startMillis = startTime.toMillis(true); endTime.year = year; endTime.month = month; endTime.monthDay = monthDay; endMillis = endTime.normalize(true); // Do not allow an event to have an end time before the start // time. if (endTime.before(startTime)) { endTime.set(startTime); endMillis = startMillis; } // Call populateTimezone if we support end time zone as well } setDate(mStartDateButton, startMillis); setDate(mEndDateButton, endMillis); setTime(mEndTimeButton, endMillis); // In case end time had to be // reset updateHomeTime(); } } // Fills in the date and time fields private void populateWhen() { long startMillis = mStartTime.toMillis(false /* use isDst */); long endMillis = mEndTime.toMillis(false /* use isDst */); setDate(mStartDateButton, startMillis); setDate(mEndDateButton, endMillis); setTime(mStartTimeButton, startMillis); setTime(mEndTimeButton, endMillis); mStartDateButton.setOnClickListener(new DateClickListener(mStartTime)); mEndDateButton.setOnClickListener(new DateClickListener(mEndTime)); mStartTimeButton.setOnClickListener(new TimeClickListener(mStartTime)); mEndTimeButton.setOnClickListener(new TimeClickListener(mEndTime)); } // Implements OnTimeZoneSetListener @Override public void onTimeZoneSet(TimeZoneInfo tzi) { setTimezone(tzi.mTzId); updateHomeTime(); } private void setTimezone(String timeZone) { mTimezone = timeZone; mStartTime.timezone = mTimezone; long timeMillis = mStartTime.normalize(true); mEndTime.timezone = mTimezone; mEndTime.normalize(true); populateTimezone(timeMillis); } private void populateTimezone(long eventStartTime) { if (mTzPickerUtils == null) { mTzPickerUtils = new TimeZonePickerUtils(mActivity); } CharSequence displayName = mTzPickerUtils.getGmtDisplayName(mActivity, mTimezone, eventStartTime); mTimezoneTextView.setText(displayName); mTimezoneButton.setText(displayName); } private void showTimezoneDialog() { Bundle b = new Bundle(); b.putLong(TimeZonePickerDialog.BUNDLE_START_TIME_MILLIS, mStartTime.toMillis(false)); b.putString(TimeZonePickerDialog.BUNDLE_TIME_ZONE, mTimezone); FragmentManager fm = mActivity.getFragmentManager(); TimeZonePickerDialog tzpd = (TimeZonePickerDialog) fm .findFragmentByTag(FRAG_TAG_TIME_ZONE_PICKER); if (tzpd != null) { tzpd.dismiss(); } tzpd = new TimeZonePickerDialog(); tzpd.setArguments(b); tzpd.setOnTimeZoneSetListener(EditEventView.this); tzpd.show(fm, FRAG_TAG_TIME_ZONE_PICKER); } private void populateRepeats() { Resources r = mActivity.getResources(); String repeatString; boolean enabled; if (!TextUtils.isEmpty(mRrule)) { repeatString = EventRecurrenceFormatter.getRepeatString(mActivity, r, mEventRecurrence, true); if (repeatString == null) { repeatString = r.getString(R.string.custom); Log.e(TAG, "Can't generate display string for " + mRrule); enabled = false; } else { // TODO Should give option to clear/reset rrule enabled = RecurrencePickerDialog.canHandleRecurrenceRule(mEventRecurrence); if (!enabled) { Log.e(TAG, "UI can't handle " + mRrule); } } } else { repeatString = r.getString(R.string.does_not_repeat); enabled = true; } mRruleButton.setText(repeatString); // Don't allow the user to make exceptions recurring events. if (mModel.mOriginalSyncId != null) { enabled = false; } mRruleButton.setOnClickListener(this); mRruleButton.setEnabled(enabled); } private class DateClickListener implements View.OnClickListener { private Time mTime; public DateClickListener(Time time) { mTime = time; } @Override public void onClick(View v) { if (v == mStartDateButton) { mDateSelectedWasStartDate = true; } else { mDateSelectedWasStartDate = false; } final DateListener listener = new DateListener(v); if (mDatePickerDialog != null) { mDatePickerDialog.dismiss(); } mDatePickerDialog = DatePickerDialog.newInstance(listener, mTime.year, mTime.month, mTime.monthDay); mDatePickerDialog.setFirstDayOfWeek(Utils.getFirstDayOfWeekAsCalendar(mActivity)); mDatePickerDialog.setYearRange(Utils.YEAR_MIN, Utils.YEAR_MAX); mDatePickerDialog.show(mActivity.getFragmentManager(), FRAG_TAG_DATE_PICKER); } } public static class CalendarsAdapter extends ResourceCursorAdapter { public CalendarsAdapter(Context context, int resourceId, Cursor c) { super(context, resourceId, c); setDropDownViewResource(R.layout.calendars_dropdown_item); } @Override public void bindView(View view, Context context, Cursor cursor) { View colorBar = view.findViewById(R.id.color); int colorColumn = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR); int nameColumn = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_DISPLAY_NAME); int ownerColumn = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT); if (colorBar != null) { colorBar.setBackgroundColor(Utils.getDisplayColorFromColor(cursor .getInt(colorColumn))); } TextView name = (TextView) view.findViewById(R.id.calendar_name); if (name != null) { String displayName = cursor.getString(nameColumn); name.setText(displayName); TextView accountName = (TextView) view.findViewById(R.id.account_name); if (accountName != null) { accountName.setText(cursor.getString(ownerColumn)); accountName.setVisibility(TextView.VISIBLE); } } } } /** * Does prep steps for saving a calendar event. * * This triggers a parse of the attendees list and checks if the event is * ready to be saved. An event is ready to be saved so long as a model * exists and has a calendar it can be associated with, either because it's * an existing event or we've finished querying. * * @return false if there is no model or no calendar had been loaded yet, * true otherwise. */ public boolean prepareForSave() { if (mModel == null || (mCalendarsCursor == null && mModel.mUri == null)) { return false; } return fillModelFromUI(); } public boolean fillModelFromReadOnlyUi() { if (mModel == null || (mCalendarsCursor == null && mModel.mUri == null)) { return false; } mModel.mReminders = EventViewUtils.reminderItemsToReminders( mReminderItems, mReminderMinuteValues, mReminderMethodValues); mModel.mReminders.addAll(mUnsupportedReminders); mModel.normalizeReminders(); int status = EventInfoFragment.getResponseFromButtonId( mResponseRadioGroup.getCheckedRadioButtonId()); if (status != Attendees.ATTENDEE_STATUS_NONE) { mModel.mSelfAttendeeStatus = status; } return true; } // This is called if the user clicks on one of the buttons: "Save", // "Discard", or "Delete". This is also called if the user clicks // on the "remove reminder" button. @Override public void onClick(View view) { if (view == mRruleButton) { Bundle b = new Bundle(); b.putLong(RecurrencePickerDialog.BUNDLE_START_TIME_MILLIS, mStartTime.toMillis(false)); b.putString(RecurrencePickerDialog.BUNDLE_TIME_ZONE, mStartTime.timezone); // TODO may be more efficient to serialize and pass in EventRecurrence b.putString(RecurrencePickerDialog.BUNDLE_RRULE, mRrule); FragmentManager fm = mActivity.getFragmentManager(); RecurrencePickerDialog rpd = (RecurrencePickerDialog) fm .findFragmentByTag(FRAG_TAG_RECUR_PICKER); if (rpd != null) { rpd.dismiss(); } rpd = new RecurrencePickerDialog(); rpd.setArguments(b); rpd.setOnRecurrenceSetListener(EditEventView.this); rpd.show(fm, FRAG_TAG_RECUR_PICKER); return; } // This must be a click on one of the "remove reminder" buttons LinearLayout reminderItem = (LinearLayout) view.getParent(); LinearLayout parent = (LinearLayout) reminderItem.getParent(); parent.removeView(reminderItem); mReminderItems.remove(reminderItem); updateRemindersVisibility(mReminderItems.size()); EventViewUtils.updateAddReminderButton(mView, mReminderItems, mModel.mCalendarMaxReminders); } @Override public void onRecurrenceSet(String rrule) { Log.d(TAG, "Old rrule:" + mRrule); Log.d(TAG, "New rrule:" + rrule); mRrule = rrule; if (mRrule != null) { mEventRecurrence.parse(mRrule); } populateRepeats(); } // This is called if the user cancels the "No calendars" dialog. // The "No calendars" dialog is shown if there are no syncable calendars. @Override public void onCancel(DialogInterface dialog) { if (dialog == mLoadingCalendarsDialog) { mLoadingCalendarsDialog = null; mSaveAfterQueryComplete = false; } else if (dialog == mNoCalendarsDialog) { mDone.setDoneCode(Utils.DONE_REVERT); mDone.run(); return; } } // This is called if the user clicks on a dialog button. @Override public void onClick(DialogInterface dialog, int which) { if (dialog == mNoCalendarsDialog) { mDone.setDoneCode(Utils.DONE_REVERT); mDone.run(); if (which == DialogInterface.BUTTON_POSITIVE) { Intent nextIntent = new Intent(Settings.ACTION_ADD_ACCOUNT); final String[] array = {"com.android.calendar"}; nextIntent.putExtra(Settings.EXTRA_AUTHORITIES, array); nextIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); mActivity.startActivity(nextIntent); } } } // Goes through the UI elements and updates the model as necessary private boolean fillModelFromUI() { if (mModel == null) { return false; } mModel.mReminders = EventViewUtils.reminderItemsToReminders(mReminderItems, mReminderMinuteValues, mReminderMethodValues); mModel.mReminders.addAll(mUnsupportedReminders); mModel.normalizeReminders(); mModel.mHasAlarm = mReminderItems.size() > 0; mModel.mTitle = mTitleTextView.getText().toString(); mModel.mAllDay = mAllDayCheckBox.isChecked(); mModel.mLocation = mLocationTextView.getText().toString(); mModel.mDescription = mDescriptionTextView.getText().toString(); if (TextUtils.isEmpty(mModel.mLocation)) { mModel.mLocation = null; } if (TextUtils.isEmpty(mModel.mDescription)) { mModel.mDescription = null; } int status = EventInfoFragment.getResponseFromButtonId(mResponseRadioGroup .getCheckedRadioButtonId()); if (status != Attendees.ATTENDEE_STATUS_NONE) { mModel.mSelfAttendeeStatus = status; } if (mAttendeesList != null) { mEmailValidator.setRemoveInvalid(true); mAttendeesList.performValidation(); mModel.mAttendeesList.clear(); mModel.addAttendees(mAttendeesList.getText().toString(), mEmailValidator); mEmailValidator.setRemoveInvalid(false); } // If this was a new event we need to fill in the Calendar information if (mModel.mUri == null) { mModel.mCalendarId = mCalendarsSpinner.getSelectedItemId(); int calendarCursorPosition = mCalendarsSpinner.getSelectedItemPosition(); if (mCalendarsCursor.moveToPosition(calendarCursorPosition)) { String defaultCalendar = mCalendarsCursor.getString( EditEventHelper.CALENDARS_INDEX_OWNER_ACCOUNT); Utils.setSharedPreference( mActivity, GeneralPreferences.KEY_DEFAULT_CALENDAR, defaultCalendar); mModel.mOwnerAccount = defaultCalendar; mModel.mOrganizer = defaultCalendar; mModel.mCalendarId = mCalendarsCursor.getLong(EditEventHelper.CALENDARS_INDEX_ID); } } if (mModel.mAllDay) { // Reset start and end time, increment the monthDay by 1, and set // the timezone to UTC, as required for all-day events. mTimezone = Time.TIMEZONE_UTC; mStartTime.hour = 0; mStartTime.minute = 0; mStartTime.second = 0; mStartTime.timezone = mTimezone; mModel.mStart = mStartTime.normalize(true); mEndTime.hour = 0; mEndTime.minute = 0; mEndTime.second = 0; mEndTime.timezone = mTimezone; // When a user see the event duration as "X - Y" (e.g. Oct. 28 - Oct. 29), end time // should be Y + 1 (Oct.30). final long normalizedEndTimeMillis = mEndTime.normalize(true) + DateUtils.DAY_IN_MILLIS; if (normalizedEndTimeMillis < mModel.mStart) { // mEnd should be midnight of the next day of mStart. mModel.mEnd = mModel.mStart + DateUtils.DAY_IN_MILLIS; } else { mModel.mEnd = normalizedEndTimeMillis; } } else { mStartTime.timezone = mTimezone; mEndTime.timezone = mTimezone; mModel.mStart = mStartTime.toMillis(true); mModel.mEnd = mEndTime.toMillis(true); } mModel.mTimezone = mTimezone; mModel.mAccessLevel = mAccessLevelSpinner.getSelectedItemPosition(); // TODO set correct availability value mModel.mAvailability = mAvailabilityValues.get(mAvailabilitySpinner .getSelectedItemPosition()); // rrrule // If we're making an exception we don't want it to be a repeating // event. if (mModification == EditEventHelper.MODIFY_SELECTED) { mModel.mRrule = null; } else { mModel.mRrule = mRrule; } return true; } public EditEventView(Activity activity, View view, EditDoneRunnable done, boolean timeSelectedWasStartTime, boolean dateSelectedWasStartDate) { mActivity = activity; mView = view; mDone = done; // cache top level view elements mLoadingMessage = (TextView) view.findViewById(R.id.loading_message); mScrollView = (ScrollView) view.findViewById(R.id.scroll_view); // cache all the widgets mCalendarsSpinner = (Spinner) view.findViewById(R.id.calendars_spinner); mTitleTextView = (TextView) view.findViewById(R.id.title); mLocationTextView = (AutoCompleteTextView) view.findViewById(R.id.location); mDescriptionTextView = (TextView) view.findViewById(R.id.description); mTimezoneLabel = (TextView) view.findViewById(R.id.timezone_label); mStartDateButton = (Button) view.findViewById(R.id.start_date); mEndDateButton = (Button) view.findViewById(R.id.end_date); mWhenView = (TextView) mView.findViewById(R.id.when); mTimezoneTextView = (TextView) mView.findViewById(R.id.timezone_textView); mStartTimeButton = (Button) view.findViewById(R.id.start_time); mEndTimeButton = (Button) view.findViewById(R.id.end_time); mTimezoneButton = (Button) view.findViewById(R.id.timezone_button); mTimezoneButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showTimezoneDialog(); } }); mTimezoneRow = view.findViewById(R.id.timezone_button_row); mStartTimeHome = (TextView) view.findViewById(R.id.start_time_home_tz); mStartDateHome = (TextView) view.findViewById(R.id.start_date_home_tz); mEndTimeHome = (TextView) view.findViewById(R.id.end_time_home_tz); mEndDateHome = (TextView) view.findViewById(R.id.end_date_home_tz); mAllDayCheckBox = (CheckBox) view.findViewById(R.id.is_all_day); mRruleButton = (Button) view.findViewById(R.id.rrule); mAvailabilitySpinner = (Spinner) view.findViewById(R.id.availability); mAccessLevelSpinner = (Spinner) view.findViewById(R.id.visibility); mCalendarSelectorGroup = view.findViewById(R.id.calendar_selector_group); mCalendarSelectorWrapper = view.findViewById(R.id.calendar_selector_wrapper); mCalendarStaticGroup = view.findViewById(R.id.calendar_group); mRemindersGroup = view.findViewById(R.id.reminders_row); mResponseGroup = view.findViewById(R.id.response_row); mOrganizerGroup = view.findViewById(R.id.organizer_row); mAttendeesGroup = view.findViewById(R.id.add_attendees_row); mLocationGroup = view.findViewById(R.id.where_row); mDescriptionGroup = view.findViewById(R.id.description_row); mStartHomeGroup = view.findViewById(R.id.from_row_home_tz); mEndHomeGroup = view.findViewById(R.id.to_row_home_tz); mAttendeesList = (MultiAutoCompleteTextView) view.findViewById(R.id.attendees); mColorPickerNewEvent = view.findViewById(R.id.change_color_new_event); mColorPickerExistingEvent = view.findViewById(R.id.change_color_existing_event); mTitleTextView.setTag(mTitleTextView.getBackground()); mLocationTextView.setTag(mLocationTextView.getBackground()); mLocationAdapter = new EventLocationAdapter(activity); mLocationTextView.setAdapter(mLocationAdapter); mLocationTextView.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { // Dismiss the suggestions dropdown. Return false so the other // side effects still occur (soft keyboard going away, etc.). mLocationTextView.dismissDropDown(); } return false; } }); mAvailabilityExplicitlySet = false; mAllDayChangingAvailability = false; mAvailabilityCurrentlySelected = -1; mAvailabilitySpinner.setOnItemSelectedListener( new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // The spinner's onItemSelected gets called while it is being // initialized to the first item, and when we explicitly set it // in the allDay checkbox toggling, so we need these checks to // find out when the spinner is actually being clicked. // Set the initial selection. if (mAvailabilityCurrentlySelected == -1) { mAvailabilityCurrentlySelected = position; } if (mAvailabilityCurrentlySelected != position && !mAllDayChangingAvailability) { mAvailabilityExplicitlySet = true; } else { mAvailabilityCurrentlySelected = position; mAllDayChangingAvailability = false; } } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); mDescriptionTextView.setTag(mDescriptionTextView.getBackground()); mAttendeesList.setTag(mAttendeesList.getBackground()); mOriginalPadding[0] = mLocationTextView.getPaddingLeft(); mOriginalPadding[1] = mLocationTextView.getPaddingTop(); mOriginalPadding[2] = mLocationTextView.getPaddingRight(); mOriginalPadding[3] = mLocationTextView.getPaddingBottom(); mEditViewList.add(mTitleTextView); mEditViewList.add(mLocationTextView); mEditViewList.add(mDescriptionTextView); mEditViewList.add(mAttendeesList); mViewOnlyList.add(view.findViewById(R.id.when_row)); mViewOnlyList.add(view.findViewById(R.id.timezone_textview_row)); mEditOnlyList.add(view.findViewById(R.id.all_day_row)); mEditOnlyList.add(view.findViewById(R.id.availability_row)); mEditOnlyList.add(view.findViewById(R.id.visibility_row)); mEditOnlyList.add(view.findViewById(R.id.from_row)); mEditOnlyList.add(view.findViewById(R.id.to_row)); mEditOnlyList.add(mTimezoneRow); mEditOnlyList.add(mStartHomeGroup); mEditOnlyList.add(mEndHomeGroup); mResponseRadioGroup = (RadioGroup) view.findViewById(R.id.response_value); mRemindersContainer = (LinearLayout) view.findViewById(R.id.reminder_items_container); mTimezone = Utils.getTimeZone(activity, null); mIsMultipane = activity.getResources().getBoolean(R.bool.tablet_config); mStartTime = new Time(mTimezone); mEndTime = new Time(mTimezone); mEmailValidator = new Rfc822Validator(null); initMultiAutoCompleteTextView((RecipientEditTextView) mAttendeesList); // Display loading screen setModel(null); FragmentManager fm = activity.getFragmentManager(); RecurrencePickerDialog rpd = (RecurrencePickerDialog) fm .findFragmentByTag(FRAG_TAG_RECUR_PICKER); if (rpd != null) { rpd.setOnRecurrenceSetListener(this); } TimeZonePickerDialog tzpd = (TimeZonePickerDialog) fm .findFragmentByTag(FRAG_TAG_TIME_ZONE_PICKER); if (tzpd != null) { tzpd.setOnTimeZoneSetListener(this); } TimePickerDialog tpd = (TimePickerDialog) fm.findFragmentByTag(FRAG_TAG_TIME_PICKER); if (tpd != null) { View v; mTimeSelectedWasStartTime = timeSelectedWasStartTime; if (timeSelectedWasStartTime) { v = mStartTimeButton; } else { v = mEndTimeButton; } tpd.setOnTimeSetListener(new TimeListener(v)); } mDatePickerDialog = (DatePickerDialog) fm.findFragmentByTag(FRAG_TAG_DATE_PICKER); if (mDatePickerDialog != null) { View v; mDateSelectedWasStartDate = dateSelectedWasStartDate; if (dateSelectedWasStartDate) { v = mStartDateButton; } else { v = mEndDateButton; } mDatePickerDialog.setOnDateSetListener(new DateListener(v)); } } /** * Loads an integer array asset into a list. */ private static ArrayList<Integer> loadIntegerArray(Resources r, int resNum) { int[] vals = r.getIntArray(resNum); int size = vals.length; ArrayList<Integer> list = new ArrayList<Integer>(size); for (int i = 0; i < size; i++) { list.add(vals[i]); } return list; } /** * Loads a String array asset into a list. */ private static ArrayList<String> loadStringArray(Resources r, int resNum) { String[] labels = r.getStringArray(resNum); ArrayList<String> list = new ArrayList<String>(Arrays.asList(labels)); return list; } private void prepareAvailability() { Resources r = mActivity.getResources(); mAvailabilityValues = loadIntegerArray(r, R.array.availability_values); mAvailabilityLabels = loadStringArray(r, R.array.availability); // Copy the unadulterated availability labels for all-day toggling. mOriginalAvailabilityLabels = new ArrayList<String>(); mOriginalAvailabilityLabels.addAll(mAvailabilityLabels); if (mModel.mCalendarAllowedAvailability != null) { EventViewUtils.reduceMethodList(mAvailabilityValues, mAvailabilityLabels, mModel.mCalendarAllowedAvailability); } mAvailabilityAdapter = new ArrayAdapter<String>(mActivity, android.R.layout.simple_spinner_item, mAvailabilityLabels); mAvailabilityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mAvailabilitySpinner.setAdapter(mAvailabilityAdapter); } /** * Prepares the reminder UI elements. * <p> * (Re-)loads the minutes / methods lists from the XML assets, adds/removes items as * needed for the current set of reminders and calendar properties, and then creates UI * elements. */ private void prepareReminders() { CalendarEventModel model = mModel; Resources r = mActivity.getResources(); // Load the labels and corresponding numeric values for the minutes and methods lists // from the assets. If we're switching calendars, we need to clear and re-populate the // lists (which may have elements added and removed based on calendar properties). This // is mostly relevant for "methods", since we shouldn't have any "minutes" values in a // new event that aren't in the default set. mReminderMinuteValues = loadIntegerArray(r, R.array.reminder_minutes_values); mReminderMinuteLabels = loadStringArray(r, R.array.reminder_minutes_labels); mReminderMethodValues = loadIntegerArray(r, R.array.reminder_methods_values); mReminderMethodLabels = loadStringArray(r, R.array.reminder_methods_labels); // Remove any reminder methods that aren't allowed for this calendar. If this is // a new event, mCalendarAllowedReminders may not be set the first time we're called. if (mModel.mCalendarAllowedReminders != null) { EventViewUtils.reduceMethodList(mReminderMethodValues, mReminderMethodLabels, mModel.mCalendarAllowedReminders); } int numReminders = 0; if (model.mHasAlarm) { ArrayList<ReminderEntry> reminders = model.mReminders; numReminders = reminders.size(); // Insert any minute values that aren't represented in the minutes list. for (ReminderEntry re : reminders) { if (mReminderMethodValues.contains(re.getMethod())) { EventViewUtils.addMinutesToList(mActivity, mReminderMinuteValues, mReminderMinuteLabels, re.getMinutes()); } } // Create a UI element for each reminder. We display all of the reminders we get // from the provider, even if the count exceeds the calendar maximum. (Also, for // a new event, we won't have a maxReminders value available.) mUnsupportedReminders.clear(); for (ReminderEntry re : reminders) { if (mReminderMethodValues.contains(re.getMethod()) || re.getMethod() == Reminders.METHOD_DEFAULT) { EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderItems, mReminderMinuteValues, mReminderMinuteLabels, mReminderMethodValues, mReminderMethodLabels, re, Integer.MAX_VALUE, null); } else { // TODO figure out a way to display unsupported reminders mUnsupportedReminders.add(re); } } } updateRemindersVisibility(numReminders); EventViewUtils.updateAddReminderButton(mView, mReminderItems, mModel.mCalendarMaxReminders); } /** * Fill in the view with the contents of the given event model. This allows * an edit view to be initialized before the event has been loaded. Passing * in null for the model will display a loading screen. A non-null model * will fill in the view's fields with the data contained in the model. * * @param model The event model to pull the data from */ public void setModel(CalendarEventModel model) { mModel = model; // Need to close the autocomplete adapter to prevent leaking cursors. if (mAddressAdapter != null && mAddressAdapter instanceof EmailAddressAdapter) { ((EmailAddressAdapter)mAddressAdapter).close(); mAddressAdapter = null; } if (model == null) { // Display loading screen mLoadingMessage.setVisibility(View.VISIBLE); mScrollView.setVisibility(View.GONE); return; } boolean canRespond = EditEventHelper.canRespond(model); long begin = model.mStart; long end = model.mEnd; mTimezone = model.mTimezone; // this will be UTC for all day events // Set up the starting times if (begin > 0) { mStartTime.timezone = mTimezone; mStartTime.set(begin); mStartTime.normalize(true); } if (end > 0) { mEndTime.timezone = mTimezone; mEndTime.set(end); mEndTime.normalize(true); } mRrule = model.mRrule; if (!TextUtils.isEmpty(mRrule)) { mEventRecurrence.parse(mRrule); } if (mEventRecurrence.startDate == null) { mEventRecurrence.startDate = mStartTime; } // If the user is allowed to change the attendees set up the view and // validator if (!model.mHasAttendeeData) { mAttendeesGroup.setVisibility(View.GONE); } mAllDayCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { setAllDayViewsVisibility(isChecked); } }); boolean prevAllDay = mAllDayCheckBox.isChecked(); mAllDay = false; // default to false. Let setAllDayViewsVisibility update it as needed if (model.mAllDay) { mAllDayCheckBox.setChecked(true); // put things back in local time for all day events mTimezone = Utils.getTimeZone(mActivity, null); mStartTime.timezone = mTimezone; mEndTime.timezone = mTimezone; mEndTime.normalize(true); } else { mAllDayCheckBox.setChecked(false); } // On a rotation we need to update the views but onCheckedChanged // doesn't get called if (prevAllDay == mAllDayCheckBox.isChecked()) { setAllDayViewsVisibility(prevAllDay); } populateTimezone(mStartTime.normalize(true)); SharedPreferences prefs = GeneralPreferences.getSharedPreferences(mActivity); String defaultReminderString = prefs.getString( GeneralPreferences.KEY_DEFAULT_REMINDER, GeneralPreferences.NO_REMINDER_STRING); mDefaultReminderMinutes = Integer.parseInt(defaultReminderString); prepareReminders(); prepareAvailability(); View reminderAddButton = mView.findViewById(R.id.reminder_add); View.OnClickListener addReminderOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { addReminder(); } }; reminderAddButton.setOnClickListener(addReminderOnClickListener); if (!mIsMultipane) { mView.findViewById(R.id.is_all_day_label).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { mAllDayCheckBox.setChecked(!mAllDayCheckBox.isChecked()); } }); } if (model.mTitle != null) { mTitleTextView.setTextKeepState(model.mTitle); } if (model.mIsOrganizer || TextUtils.isEmpty(model.mOrganizer) || model.mOrganizer.endsWith(GOOGLE_SECONDARY_CALENDAR)) { mView.findViewById(R.id.organizer_label).setVisibility(View.GONE); mView.findViewById(R.id.organizer).setVisibility(View.GONE); mOrganizerGroup.setVisibility(View.GONE); } else { ((TextView) mView.findViewById(R.id.organizer)).setText(model.mOrganizerDisplayName); } if (model.mLocation != null) { mLocationTextView.setTextKeepState(model.mLocation); } if (model.mDescription != null) { mDescriptionTextView.setTextKeepState(model.mDescription); } int availIndex = mAvailabilityValues.indexOf(model.mAvailability); if (availIndex != -1) { mAvailabilitySpinner.setSelection(availIndex); } mAccessLevelSpinner.setSelection(model.mAccessLevel); View responseLabel = mView.findViewById(R.id.response_label); if (canRespond) { int buttonToCheck = EventInfoFragment .findButtonIdForResponse(model.mSelfAttendeeStatus); mResponseRadioGroup.check(buttonToCheck); // -1 clear all radio buttons mResponseRadioGroup.setVisibility(View.VISIBLE); responseLabel.setVisibility(View.VISIBLE); } else { responseLabel.setVisibility(View.GONE); mResponseRadioGroup.setVisibility(View.GONE); mResponseGroup.setVisibility(View.GONE); } if (model.mUri != null) { // This is an existing event so hide the calendar spinner // since we can't change the calendar. View calendarGroup = mView.findViewById(R.id.calendar_selector_group); calendarGroup.setVisibility(View.GONE); TextView tv = (TextView) mView.findViewById(R.id.calendar_textview); tv.setText(model.mCalendarDisplayName); tv = (TextView) mView.findViewById(R.id.calendar_textview_secondary); if (tv != null) { tv.setText(model.mOwnerAccount); } } else { View calendarGroup = mView.findViewById(R.id.calendar_group); calendarGroup.setVisibility(View.GONE); } if (model.isEventColorInitialized()) { updateHeadlineColor(model, model.getEventColor()); } populateWhen(); populateRepeats(); updateAttendees(model.mAttendeesList); updateView(); mScrollView.setVisibility(View.VISIBLE); mLoadingMessage.setVisibility(View.GONE); sendAccessibilityEvent(); } public void updateHeadlineColor(CalendarEventModel model, int displayColor) { if (model.mUri != null) { if (mIsMultipane) { mView.findViewById(R.id.calendar_textview_with_colorpicker) .setBackgroundColor(displayColor); } else { mView.findViewById(R.id.calendar_group).setBackgroundColor(displayColor); } } else { setSpinnerBackgroundColor(displayColor); } } private void setSpinnerBackgroundColor(int displayColor) { if (mIsMultipane) { mCalendarSelectorWrapper.setBackgroundColor(displayColor); } else { mCalendarSelectorGroup.setBackgroundColor(displayColor); } } private void sendAccessibilityEvent() { AccessibilityManager am = (AccessibilityManager) mActivity.getSystemService(Service.ACCESSIBILITY_SERVICE); if (!am.isEnabled() || mModel == null) { return; } StringBuilder b = new StringBuilder(); addFieldsRecursive(b, mView); CharSequence msg = b.toString(); AccessibilityEvent event = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_FOCUSED); event.setClassName(getClass().getName()); event.setPackageName(mActivity.getPackageName()); event.getText().add(msg); event.setAddedCount(msg.length()); am.sendAccessibilityEvent(event); } private void addFieldsRecursive(StringBuilder b, View v) { if (v == null || v.getVisibility() != View.VISIBLE) { return; } if (v instanceof TextView) { CharSequence tv = ((TextView) v).getText(); if (!TextUtils.isEmpty(tv.toString().trim())) { b.append(tv + PERIOD_SPACE); } } else if (v instanceof RadioGroup) { RadioGroup rg = (RadioGroup) v; int id = rg.getCheckedRadioButtonId(); if (id != View.NO_ID) { b.append(((RadioButton) (v.findViewById(id))).getText() + PERIOD_SPACE); } } else if (v instanceof Spinner) { Spinner s = (Spinner) v; if (s.getSelectedItem() instanceof String) { String str = ((String) (s.getSelectedItem())).trim(); if (!TextUtils.isEmpty(str)) { b.append(str + PERIOD_SPACE); } } } else if (v instanceof ViewGroup) { ViewGroup vg = (ViewGroup) v; int children = vg.getChildCount(); for (int i = 0; i < children; i++) { addFieldsRecursive(b, vg.getChildAt(i)); } } } /** * Creates a single line string for the time/duration */ protected void setWhenString() { String when; int flags = DateUtils.FORMAT_SHOW_DATE; String tz = mTimezone; if (mModel.mAllDay) { flags |= DateUtils.FORMAT_SHOW_WEEKDAY; tz = Time.TIMEZONE_UTC; } else { flags |= DateUtils.FORMAT_SHOW_TIME; if (DateFormat.is24HourFormat(mActivity)) { flags |= DateUtils.FORMAT_24HOUR; } } long startMillis = mStartTime.normalize(true); long endMillis = mEndTime.normalize(true); mSB.setLength(0); when = DateUtils .formatDateRange(mActivity, mF, startMillis, endMillis, flags, tz).toString(); mWhenView.setText(when); } /** * Configures the Calendars spinner. This is only done for new events, because only new * events allow you to select a calendar while editing an event. * <p> * We tuck a reference to a Cursor with calendar database data into the spinner, so that * we can easily extract calendar-specific values when the value changes (the spinner's * onItemSelected callback is configured). */ public void setCalendarsCursor(Cursor cursor, boolean userVisible, long selectedCalendarId) { // If there are no syncable calendars, then we cannot allow // creating a new event. mCalendarsCursor = cursor; if (cursor == null || cursor.getCount() == 0) { // Cancel the "loading calendars" dialog if it exists if (mSaveAfterQueryComplete) { mLoadingCalendarsDialog.cancel(); } if (!userVisible) { return; } // Create an error message for the user that, when clicked, // will exit this activity without saving the event. AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); builder.setTitle(R.string.no_syncable_calendars).setIconAttribute( android.R.attr.alertDialogIcon).setMessage(R.string.no_calendars_found) .setPositiveButton(R.string.add_account, this) .setNegativeButton(android.R.string.no, this).setOnCancelListener(this); mNoCalendarsDialog = builder.show(); return; } int selection; if (selectedCalendarId != -1) { selection = findSelectedCalendarPosition(cursor, selectedCalendarId); } else { selection = findDefaultCalendarPosition(cursor); } // populate the calendars spinner CalendarsAdapter adapter = new CalendarsAdapter(mActivity, R.layout.calendars_spinner_item, cursor); mCalendarsSpinner.setAdapter(adapter); mCalendarsSpinner.setSelection(selection); mCalendarsSpinner.setOnItemSelectedListener(this); if (mSaveAfterQueryComplete) { mLoadingCalendarsDialog.cancel(); if (prepareForSave() && fillModelFromUI()) { int exit = userVisible ? Utils.DONE_EXIT : 0; mDone.setDoneCode(Utils.DONE_SAVE | exit); mDone.run(); } else if (userVisible) { mDone.setDoneCode(Utils.DONE_EXIT); mDone.run(); } else if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "SetCalendarsCursor:Save failed and unable to exit view"); } return; } } /** * Updates the view based on {@link #mModification} and {@link #mModel} */ public void updateView() { if (mModel == null) { return; } if (EditEventHelper.canModifyEvent(mModel)) { setViewStates(mModification); } else { setViewStates(Utils.MODIFY_UNINITIALIZED); } } private void setViewStates(int mode) { // Extra canModify check just in case if (mode == Utils.MODIFY_UNINITIALIZED || !EditEventHelper.canModifyEvent(mModel)) { setWhenString(); for (View v : mViewOnlyList) { v.setVisibility(View.VISIBLE); } for (View v : mEditOnlyList) { v.setVisibility(View.GONE); } for (View v : mEditViewList) { v.setEnabled(false); v.setBackgroundDrawable(null); } mCalendarSelectorGroup.setVisibility(View.GONE); mCalendarStaticGroup.setVisibility(View.VISIBLE); mRruleButton.setEnabled(false); - mRruleButton.setBackgroundDrawable(null); if (EditEventHelper.canAddReminders(mModel)) { mRemindersGroup.setVisibility(View.VISIBLE); } else { mRemindersGroup.setVisibility(View.GONE); } if (TextUtils.isEmpty(mLocationTextView.getText())) { mLocationGroup.setVisibility(View.GONE); } if (TextUtils.isEmpty(mDescriptionTextView.getText())) { mDescriptionGroup.setVisibility(View.GONE); } } else { for (View v : mViewOnlyList) { v.setVisibility(View.GONE); } for (View v : mEditOnlyList) { v.setVisibility(View.VISIBLE); } for (View v : mEditViewList) { v.setEnabled(true); if (v.getTag() != null) { v.setBackgroundDrawable((Drawable) v.getTag()); v.setPadding(mOriginalPadding[0], mOriginalPadding[1], mOriginalPadding[2], mOriginalPadding[3]); } } if (mModel.mUri == null) { mCalendarSelectorGroup.setVisibility(View.VISIBLE); mCalendarStaticGroup.setVisibility(View.GONE); } else { mCalendarSelectorGroup.setVisibility(View.GONE); mCalendarStaticGroup.setVisibility(View.VISIBLE); } if (mModel.mOriginalSyncId == null) { mRruleButton.setEnabled(true); } else { mRruleButton.setEnabled(false); + mRruleButton.setBackgroundDrawable(null); } mRemindersGroup.setVisibility(View.VISIBLE); mLocationGroup.setVisibility(View.VISIBLE); mDescriptionGroup.setVisibility(View.VISIBLE); } setAllDayViewsVisibility(mAllDayCheckBox.isChecked()); } public void setModification(int modifyWhich) { mModification = modifyWhich; updateView(); updateHomeTime(); } private int findSelectedCalendarPosition(Cursor calendarsCursor, long calendarId) { if (calendarsCursor.getCount() <= 0) { return -1; } int calendarIdColumn = calendarsCursor.getColumnIndexOrThrow(Calendars._ID); int position = 0; calendarsCursor.moveToPosition(-1); while (calendarsCursor.moveToNext()) { if (calendarsCursor.getLong(calendarIdColumn) == calendarId) { return position; } position++; } return 0; } // Find the calendar position in the cursor that matches calendar in // preference private int findDefaultCalendarPosition(Cursor calendarsCursor) { if (calendarsCursor.getCount() <= 0) { return -1; } String defaultCalendar = Utils.getSharedPreference( mActivity, GeneralPreferences.KEY_DEFAULT_CALENDAR, (String) null); int calendarsOwnerIndex = calendarsCursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT); int accountNameIndex = calendarsCursor.getColumnIndexOrThrow(Calendars.ACCOUNT_NAME); int accountTypeIndex = calendarsCursor.getColumnIndexOrThrow(Calendars.ACCOUNT_TYPE); int position = 0; calendarsCursor.moveToPosition(-1); while (calendarsCursor.moveToNext()) { String calendarOwner = calendarsCursor.getString(calendarsOwnerIndex); if (defaultCalendar == null) { // There is no stored default upon the first time running. Use a primary // calendar in this case. if (calendarOwner != null && calendarOwner.equals(calendarsCursor.getString(accountNameIndex)) && !CalendarContract.ACCOUNT_TYPE_LOCAL.equals( calendarsCursor.getString(accountTypeIndex))) { return position; } } else if (defaultCalendar.equals(calendarOwner)) { // Found the default calendar. return position; } position++; } return 0; } private void updateAttendees(HashMap<String, Attendee> attendeesList) { if (attendeesList == null || attendeesList.isEmpty()) { return; } mAttendeesList.setText(null); for (Attendee attendee : attendeesList.values()) { // TODO: Please remove separator when Calendar uses the chips MR2 project // Adding a comma separator between email addresses to prevent a chips MR1.1 bug // in which email addresses are concatenated together with no separator. mAttendeesList.append(attendee.mEmail + ", "); } } private void updateRemindersVisibility(int numReminders) { if (numReminders == 0) { mRemindersContainer.setVisibility(View.GONE); } else { mRemindersContainer.setVisibility(View.VISIBLE); } } /** * Add a new reminder when the user hits the "add reminder" button. We use the default * reminder time and method. */ private void addReminder() { // TODO: when adding a new reminder, make it different from the // last one in the list (if any). if (mDefaultReminderMinutes == GeneralPreferences.NO_REMINDER) { EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderItems, mReminderMinuteValues, mReminderMinuteLabels, mReminderMethodValues, mReminderMethodLabels, ReminderEntry.valueOf(GeneralPreferences.REMINDER_DEFAULT_TIME), mModel.mCalendarMaxReminders, null); } else { EventViewUtils.addReminder(mActivity, mScrollView, this, mReminderItems, mReminderMinuteValues, mReminderMinuteLabels, mReminderMethodValues, mReminderMethodLabels, ReminderEntry.valueOf(mDefaultReminderMinutes), mModel.mCalendarMaxReminders, null); } updateRemindersVisibility(mReminderItems.size()); EventViewUtils.updateAddReminderButton(mView, mReminderItems, mModel.mCalendarMaxReminders); } // From com.google.android.gm.ComposeActivity private MultiAutoCompleteTextView initMultiAutoCompleteTextView(RecipientEditTextView list) { if (ChipsUtil.supportsChipsUi()) { mAddressAdapter = new RecipientAdapter(mActivity); list.setAdapter((BaseRecipientAdapter) mAddressAdapter); list.setOnFocusListShrinkRecipients(false); } else { mAddressAdapter = new EmailAddressAdapter(mActivity); list.setAdapter((EmailAddressAdapter)mAddressAdapter); } list.setTokenizer(new Rfc822Tokenizer()); list.setValidator(mEmailValidator); // NOTE: assumes no other filters are set list.setFilters(sRecipientFilters); return list; } /** * From com.google.android.gm.ComposeActivity Implements special address * cleanup rules: The first space key entry following an "@" symbol that is * followed by any combination of letters and symbols, including one+ dots * and zero commas, should insert an extra comma (followed by the space). */ private static InputFilter[] sRecipientFilters = new InputFilter[] { new Rfc822InputFilter() }; private void setDate(TextView view, long millis) { int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_WEEKDAY; // Unfortunately, DateUtils doesn't support a timezone other than the // default timezone provided by the system, so we have this ugly hack // here to trick it into formatting our time correctly. In order to // prevent all sorts of craziness, we synchronize on the TimeZone class // to prevent other threads from reading an incorrect timezone from // calls to TimeZone#getDefault() // TODO fix this if/when DateUtils allows for passing in a timezone String dateString; synchronized (TimeZone.class) { TimeZone.setDefault(TimeZone.getTimeZone(mTimezone)); dateString = DateUtils.formatDateTime(mActivity, millis, flags); // setting the default back to null restores the correct behavior TimeZone.setDefault(null); } view.setText(dateString); } private void setTime(TextView view, long millis) { int flags = DateUtils.FORMAT_SHOW_TIME; if (DateFormat.is24HourFormat(mActivity)) { flags |= DateUtils.FORMAT_24HOUR; } // Unfortunately, DateUtils doesn't support a timezone other than the // default timezone provided by the system, so we have this ugly hack // here to trick it into formatting our time correctly. In order to // prevent all sorts of craziness, we synchronize on the TimeZone class // to prevent other threads from reading an incorrect timezone from // calls to TimeZone#getDefault() // TODO fix this if/when DateUtils allows for passing in a timezone String timeString; synchronized (TimeZone.class) { TimeZone.setDefault(TimeZone.getTimeZone(mTimezone)); timeString = DateUtils.formatDateTime(mActivity, millis, flags); TimeZone.setDefault(null); } view.setText(timeString); } /** * @param isChecked */ protected void setAllDayViewsVisibility(boolean isChecked) { if (isChecked) { if (mEndTime.hour == 0 && mEndTime.minute == 0) { if (mAllDay != isChecked) { mEndTime.monthDay--; } long endMillis = mEndTime.normalize(true); // Do not allow an event to have an end time // before the // start time. if (mEndTime.before(mStartTime)) { mEndTime.set(mStartTime); endMillis = mEndTime.normalize(true); } setDate(mEndDateButton, endMillis); setTime(mEndTimeButton, endMillis); } mStartTimeButton.setVisibility(View.GONE); mEndTimeButton.setVisibility(View.GONE); mTimezoneRow.setVisibility(View.GONE); } else { if (mEndTime.hour == 0 && mEndTime.minute == 0) { if (mAllDay != isChecked) { mEndTime.monthDay++; } long endMillis = mEndTime.normalize(true); setDate(mEndDateButton, endMillis); setTime(mEndTimeButton, endMillis); } mStartTimeButton.setVisibility(View.VISIBLE); mEndTimeButton.setVisibility(View.VISIBLE); mTimezoneRow.setVisibility(View.VISIBLE); } // If this is a new event, and if availability has not yet been // explicitly set, toggle busy/available as the inverse of all day. if (mModel.mUri == null && !mAvailabilityExplicitlySet) { // Values are from R.arrays.availability_values. // 0 = busy // 1 = available int newAvailabilityValue = isChecked? 1 : 0; if (mAvailabilityAdapter != null && mAvailabilityValues != null && mAvailabilityValues.contains(newAvailabilityValue)) { // We'll need to let the spinner's listener know that we're // explicitly toggling it. mAllDayChangingAvailability = true; String newAvailabilityLabel = mOriginalAvailabilityLabels.get(newAvailabilityValue); int newAvailabilityPos = mAvailabilityAdapter.getPosition(newAvailabilityLabel); mAvailabilitySpinner.setSelection(newAvailabilityPos); } } mAllDay = isChecked; updateHomeTime(); } public void setColorPickerButtonStates(int[] eventColors) { if (eventColors == null || eventColors.length == 0) { mColorPickerNewEvent.setVisibility(View.INVISIBLE); mColorPickerExistingEvent.setVisibility(View.GONE); } else { mColorPickerNewEvent.setVisibility(View.VISIBLE); mColorPickerExistingEvent.setVisibility(View.VISIBLE); } } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // This is only used for the Calendar spinner in new events, and only fires when the // calendar selection changes or on screen rotation Cursor c = (Cursor) parent.getItemAtPosition(position); if (c == null) { // TODO: can this happen? should we drop this check? Log.w(TAG, "Cursor not set on calendar item"); return; } // Do nothing if the selection didn't change so that reminders will not get lost int idColumn = c.getColumnIndexOrThrow(Calendars._ID); long calendarId = c.getLong(idColumn); int colorColumn = c.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR); int color = c.getInt(colorColumn); int displayColor = Utils.getDisplayColorFromColor(color); // Prevents resetting of data (reminders, etc.) on orientation change. if (calendarId == mModel.mCalendarId && mModel.isCalendarColorInitialized() && displayColor == mModel.getCalendarColor()) { return; } setSpinnerBackgroundColor(displayColor); mModel.mCalendarId = calendarId; mModel.setCalendarColor(displayColor); mModel.mCalendarAccountName = c.getString(EditEventHelper.CALENDARS_INDEX_ACCOUNT_NAME); mModel.mCalendarAccountType = c.getString(EditEventHelper.CALENDARS_INDEX_ACCOUNT_TYPE); mModel.setEventColor(mModel.getCalendarColor()); setColorPickerButtonStates(mModel.getCalendarEventColors()); // Update the max/allowed reminders with the new calendar properties. int maxRemindersColumn = c.getColumnIndexOrThrow(Calendars.MAX_REMINDERS); mModel.mCalendarMaxReminders = c.getInt(maxRemindersColumn); int allowedRemindersColumn = c.getColumnIndexOrThrow(Calendars.ALLOWED_REMINDERS); mModel.mCalendarAllowedReminders = c.getString(allowedRemindersColumn); int allowedAttendeeTypesColumn = c.getColumnIndexOrThrow(Calendars.ALLOWED_ATTENDEE_TYPES); mModel.mCalendarAllowedAttendeeTypes = c.getString(allowedAttendeeTypesColumn); int allowedAvailabilityColumn = c.getColumnIndexOrThrow(Calendars.ALLOWED_AVAILABILITY); mModel.mCalendarAllowedAvailability = c.getString(allowedAvailabilityColumn); // Discard the current reminders and replace them with the model's default reminder set. // We could attempt to save & restore the reminders that have been added, but that's // probably more trouble than it's worth. mModel.mReminders.clear(); mModel.mReminders.addAll(mModel.mDefaultReminders); mModel.mHasAlarm = mModel.mReminders.size() != 0; // Update the UI elements. mReminderItems.clear(); LinearLayout reminderLayout = (LinearLayout) mScrollView.findViewById(R.id.reminder_items_container); reminderLayout.removeAllViews(); prepareReminders(); prepareAvailability(); } /** * Checks if the start and end times for this event should be displayed in * the Calendar app's time zone as well and formats and displays them. */ private void updateHomeTime() { String tz = Utils.getTimeZone(mActivity, null); if (!mAllDayCheckBox.isChecked() && !TextUtils.equals(tz, mTimezone) && mModification != EditEventHelper.MODIFY_UNINITIALIZED) { int flags = DateUtils.FORMAT_SHOW_TIME; boolean is24Format = DateFormat.is24HourFormat(mActivity); if (is24Format) { flags |= DateUtils.FORMAT_24HOUR; } long millisStart = mStartTime.toMillis(false); long millisEnd = mEndTime.toMillis(false); boolean isDSTStart = mStartTime.isDst != 0; boolean isDSTEnd = mEndTime.isDst != 0; // First update the start date and times String tzDisplay = TimeZone.getTimeZone(tz).getDisplayName( isDSTStart, TimeZone.SHORT, Locale.getDefault()); StringBuilder time = new StringBuilder(); mSB.setLength(0); time.append(DateUtils .formatDateRange(mActivity, mF, millisStart, millisStart, flags, tz)) .append(" ").append(tzDisplay); mStartTimeHome.setText(time.toString()); flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY; mSB.setLength(0); mStartDateHome .setText(DateUtils.formatDateRange( mActivity, mF, millisStart, millisStart, flags, tz).toString()); // Make any adjustments needed for the end times if (isDSTEnd != isDSTStart) { tzDisplay = TimeZone.getTimeZone(tz).getDisplayName( isDSTEnd, TimeZone.SHORT, Locale.getDefault()); } flags = DateUtils.FORMAT_SHOW_TIME; if (is24Format) { flags |= DateUtils.FORMAT_24HOUR; } // Then update the end times time.setLength(0); mSB.setLength(0); time.append(DateUtils.formatDateRange( mActivity, mF, millisEnd, millisEnd, flags, tz)).append(" ").append(tzDisplay); mEndTimeHome.setText(time.toString()); flags = DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY; mSB.setLength(0); mEndDateHome.setText(DateUtils.formatDateRange( mActivity, mF, millisEnd, millisEnd, flags, tz).toString()); mStartHomeGroup.setVisibility(View.VISIBLE); mEndHomeGroup.setVisibility(View.VISIBLE); } else { mStartHomeGroup.setVisibility(View.GONE); mEndHomeGroup.setVisibility(View.GONE); } } @Override public void onNothingSelected(AdapterView<?> parent) { } } diff --git a/src/com/android/calendar/recurrencepicker/RecurrencePickerDialog.java b/src/com/android/calendar/recurrencepicker/RecurrencePickerDialog.java index 971260ad..6de84390 100644 --- a/src/com/android/calendar/recurrencepicker/RecurrencePickerDialog.java +++ b/src/com/android/calendar/recurrencepicker/RecurrencePickerDialog.java @@ -1,1314 +1,1316 @@ /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.calendar.recurrencepicker; import android.app.Activity; import android.app.DialogFragment; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import android.util.TimeFormatException; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.Switch; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.android.calendar.R; import com.android.calendar.Utils; import com.android.calendar.CalendarController.ViewType; import com.android.calendarcommon2.EventRecurrence; import com.android.datetimepicker.date.DatePickerDialog; import java.text.DateFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; public class RecurrencePickerDialog extends DialogFragment implements OnItemSelectedListener, OnCheckedChangeListener, OnClickListener, android.widget.RadioGroup.OnCheckedChangeListener, DatePickerDialog.OnDateSetListener { private static final String TAG = "RecurrencePickerDialog"; // in dp's private static final int MIN_SCREEN_WIDTH_FOR_SINGLE_ROW_WEEK = 450; // Update android:maxLength in EditText as needed private static final int INTERVAL_MAX = 99; private static final int INTERVAL_DEFAULT = 1; // Update android:maxLength in EditText as needed private static final int COUNT_MAX = 730; private static final int COUNT_DEFAULT = 5; private DatePickerDialog mDatePickerDialog; private class RecurrenceModel implements Parcelable { // Should match EventRecurrence.DAILY, etc static final int FREQ_DAILY = 0; static final int FREQ_WEEKLY = 1; static final int FREQ_MONTHLY = 2; static final int FREQ_YEARLY = 3; static final int END_NEVER = 0; static final int END_BY_DATE = 1; static final int END_BY_COUNT = 2; static final int MONTHLY_BY_DATE = 0; static final int MONTHLY_BY_NTH_DAY_OF_WEEK = 1; static final int STATE_NO_RECURRENCE = 0; static final int STATE_RECURRENCE = 1; int recurrenceState; /** * FREQ: Repeat pattern * * @see FREQ_DAILY * @see FREQ_WEEKLY * @see FREQ_MONTHLY * @see FREQ_YEARLY */ int freq = FREQ_WEEKLY; /** * INTERVAL: Every n days/weeks/months/years. n >= 1 */ int interval = INTERVAL_DEFAULT; /** * UNTIL and COUNT: How does the the event end? * * @see END_NEVER * @see END_BY_DATE * @see END_BY_COUNT * @see untilDate * @see untilCount */ int end; /** * UNTIL: Date of the last recurrence. Used when until == END_BY_DATE */ Time endDate; /** * COUNT: Times to repeat. Use when until == END_BY_COUNT */ int endCount = COUNT_DEFAULT; /** * BYDAY: Days of the week to be repeated. Sun = 0, Mon = 1, etc */ boolean[] weeklyByDayOfWeek = new boolean[7]; /** * BYDAY AND BYMONTHDAY: How to repeat monthly events? Same date of the * month or Same nth day of week. * * @see MONTHLY_BY_DATE * @see MONTHLY_BY_NTH_DAY_OF_WEEK */ int monthlyRepeat; /** * Day of the month to repeat. Used when monthlyRepeat == * MONTHLY_BY_DATE */ int monthlyByMonthDay; /** * Day of the week to repeat. Used when monthlyRepeat == * MONTHLY_BY_NTH_DAY_OF_WEEK */ int monthlyByDayOfWeek; /** * Nth day of the week to repeat. Used when monthlyRepeat == * MONTHLY_BY_NTH_DAY_OF_WEEK 0=undefined, 1=1st, 2=2nd, etc */ int monthlyByNthDayOfWeek; /* * (generated method) */ @Override public String toString() { return "Model [freq=" + freq + ", interval=" + interval + ", end=" + end + ", endDate=" + endDate + ", endCount=" + endCount + ", weeklyByDayOfWeek=" + Arrays.toString(weeklyByDayOfWeek) + ", monthlyRepeat=" + monthlyRepeat + ", monthlyByMonthDay=" + monthlyByMonthDay + ", monthlyByDayOfWeek=" + monthlyByDayOfWeek + ", monthlyByNthDayOfWeek=" + monthlyByNthDayOfWeek + "]"; } @Override public int describeContents() { return 0; } public RecurrenceModel() { } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(freq); dest.writeInt(interval); dest.writeInt(end); dest.writeInt(endDate.year); dest.writeInt(endDate.month); dest.writeInt(endDate.monthDay); dest.writeInt(endCount); dest.writeBooleanArray(weeklyByDayOfWeek); dest.writeInt(monthlyRepeat); dest.writeInt(monthlyByMonthDay); dest.writeInt(monthlyByDayOfWeek); dest.writeInt(monthlyByNthDayOfWeek); dest.writeInt(recurrenceState); } } class minMaxTextWatcher implements TextWatcher { private int mMin; private int mMax; private int mDefault; public minMaxTextWatcher(int min, int defaultInt, int max) { mMin = min; mMax = max; mDefault = defaultInt; } @Override public void afterTextChanged(Editable s) { boolean updated = false; int value; try { value = Integer.parseInt(s.toString()); } catch (NumberFormatException e) { value = mDefault; } if (value < mMin) { value = mMin; updated = true; } else if (value > mMax) { updated = true; value = mMax; } // Update UI if (updated) { s.clear(); s.append(Integer.toString(value)); } updateDoneButtonState(); onChange(value); } /** Override to be called after each key stroke */ void onChange(int value) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } } private Resources mResources; private EventRecurrence mRecurrence = new EventRecurrence(); private Time mTime = new Time(); // TODO timezone? private RecurrenceModel mModel = new RecurrenceModel(); private Toast mToast; private final int[] TIME_DAY_TO_CALENDAR_DAY = new int[] { Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY, }; // Call mStringBuilder.setLength(0) before formatting any string or else the // formatted text will accumulate. // private final StringBuilder mStringBuilder = new StringBuilder(); // private Formatter mFormatter = new Formatter(mStringBuilder); private View mView; private Spinner mFreqSpinner; private static final int[] mFreqModelToEventRecurrence = { EventRecurrence.DAILY, EventRecurrence.WEEKLY, EventRecurrence.MONTHLY, EventRecurrence.YEARLY }; public static final String BUNDLE_START_TIME_MILLIS = "bundle_event_start_time"; public static final String BUNDLE_TIME_ZONE = "bundle_event_time_zone"; public static final String BUNDLE_RRULE = "bundle_event_rrule"; private static final String BUNDLE_MODEL = "bundle_model"; private static final String BUNDLE_END_COUNT_HAS_FOCUS = "bundle_end_count_has_focus"; private static final String FRAG_TAG_DATE_PICKER = "tag_date_picker_frag"; private Switch mRepeatSwitch; private EditText mInterval; private TextView mIntervalPreText; private TextView mIntervalPostText; private int mIntervalResId = -1; private Spinner mEndSpinner; private TextView mEndDateTextView; private EditText mEndCount; private TextView mPostEndCount; private boolean mHidePostEndCount; private ArrayList<CharSequence> mEndSpinnerArray = new ArrayList<CharSequence>(3); private EndSpinnerAdapter mEndSpinnerAdapter; private String mEndNeverStr; private String mEndDateLabel; private String mEndCountLabel; /** Hold toggle buttons in the order per user's first day of week preference */ private LinearLayout mWeekGroup; private LinearLayout mWeekGroup2; // Sun = 0 private ToggleButton[] mWeekByDayButtons = new ToggleButton[7]; private String[] mDayOfWeekString; private String[] mOrdinalArray; private LinearLayout mMonthGroup; private RadioGroup mMonthRepeatByRadioGroup; private RadioButton mRepeatMonthlyByNthDayOfWeek; private RadioButton mRepeatMonthlyByNthDayOfMonth; private String mMonthRepeatByDayOfWeekStr; private Button mDone; private OnRecurrenceSetListener mRecurrenceSetListener; public RecurrencePickerDialog() { } static public boolean canHandleRecurrenceRule(EventRecurrence er) { switch (er.freq) { case EventRecurrence.DAILY: case EventRecurrence.MONTHLY: case EventRecurrence.YEARLY: case EventRecurrence.WEEKLY: break; default: return false; } if (er.count > 0 && !TextUtils.isEmpty(er.until)) { return false; } // Weekly: For "repeat by day of week", the day of week to repeat is in // er.byday[] /* * Monthly: For "repeat by nth day of week" the day of week to repeat is * in er.byday[] and the "nth" is stored in er.bydayNum[]. Currently we * can handle only one and only in monthly */ int numOfByDayNum = 0; for (int i = 0; i < er.bydayCount; i++) { if (er.bydayNum[i] > 0) { ++numOfByDayNum; } } if (numOfByDayNum > 1) { return false; } if (numOfByDayNum > 0 && er.freq != EventRecurrence.MONTHLY) { return false; } // The UI only handle repeat by one day of month i.e. not 9th and 10th // of every month if (er.bymonthdayCount > 1) { return false; } if (er.freq == EventRecurrence.MONTHLY) { if (er.bydayCount > 1) { return false; } if (er.bydayCount > 0 && er.bymonthdayCount > 0) { return false; } } return true; } // TODO don't lose data when getting data that our UI can't handle static private void copyEventRecurrenceToModel(final EventRecurrence er, RecurrenceModel model) { // Freq: switch (er.freq) { case EventRecurrence.DAILY: model.freq = RecurrenceModel.FREQ_DAILY; break; case EventRecurrence.MONTHLY: model.freq = RecurrenceModel.FREQ_MONTHLY; break; case EventRecurrence.YEARLY: model.freq = RecurrenceModel.FREQ_YEARLY; break; case EventRecurrence.WEEKLY: model.freq = RecurrenceModel.FREQ_WEEKLY; break; default: throw new IllegalStateException("freq=" + er.freq); } // Interval: if (er.interval > 0) { model.interval = er.interval; } // End: // End by count: model.endCount = er.count; if (model.endCount > 0) { model.end = RecurrenceModel.END_BY_COUNT; } // End by date: if (!TextUtils.isEmpty(er.until)) { if (model.endDate == null) { model.endDate = new Time(); } try { model.endDate.parse(er.until); } catch (TimeFormatException e) { model.endDate = null; } // LIMITATION: The UI can only handle END_BY_DATE or END_BY_COUNT if (model.end == RecurrenceModel.END_BY_COUNT && model.endDate != null) { throw new IllegalStateException("freq=" + er.freq); } model.end = RecurrenceModel.END_BY_DATE; } // Weekly: repeat by day of week or Monthly: repeat by nth day of week // in the month Arrays.fill(model.weeklyByDayOfWeek, false); if (er.bydayCount > 0) { int count = 0; for (int i = 0; i < er.bydayCount; i++) { int dayOfWeek = EventRecurrence.day2TimeDay(er.byday[i]); model.weeklyByDayOfWeek[dayOfWeek] = true; if (model.freq == RecurrenceModel.FREQ_MONTHLY && er.bydayNum[i] > 0) { // LIMITATION: Can handle only (one) weekDayNum and only // when // monthly model.monthlyByDayOfWeek = dayOfWeek; model.monthlyByNthDayOfWeek = er.bydayNum[i]; model.monthlyRepeat = RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK; count++; } } if (model.freq == RecurrenceModel.FREQ_MONTHLY) { if (er.bydayCount != 1) { // Can't handle 1st Monday and 2nd Wed throw new IllegalStateException("Can handle only 1 byDayOfWeek in monthly"); } if (count != 1) { throw new IllegalStateException( "Didn't specify which nth day of week to repeat for a monthly"); } } } // Monthly by day of month if (model.freq == RecurrenceModel.FREQ_MONTHLY) { if (er.bymonthdayCount == 1) { if (model.monthlyRepeat == RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK) { throw new IllegalStateException( "Can handle only by monthday or by nth day of week, not both"); } model.monthlyByMonthDay = er.bymonthday[0]; model.monthlyRepeat = RecurrenceModel.MONTHLY_BY_DATE; } else if (er.bymonthCount > 1) { // LIMITATION: Can handle only one month day throw new IllegalStateException("Can handle only one bymonthday"); } } } static private void copyModelToEventRecurrence(final RecurrenceModel model, EventRecurrence er) { if (model.recurrenceState == RecurrenceModel.STATE_NO_RECURRENCE) { throw new IllegalStateException("There's no recurrence"); } // Freq er.freq = mFreqModelToEventRecurrence[model.freq]; // Interval if (model.interval <= 1) { er.interval = 0; } else { er.interval = model.interval; } // End switch (model.end) { case RecurrenceModel.END_BY_DATE: if (model.endDate != null) { model.endDate.switchTimezone(Time.TIMEZONE_UTC); model.endDate.normalize(false); er.until = model.endDate.format2445(); er.count = 0; } else { throw new IllegalStateException("end = END_BY_DATE but endDate is null"); } break; case RecurrenceModel.END_BY_COUNT: er.count = model.endCount; er.until = null; if (er.count <= 0) { throw new IllegalStateException("count is " + er.count); } break; default: er.count = 0; er.until = null; break; } // Weekly && monthly repeat patterns er.bydayCount = 0; er.bymonthdayCount = 0; switch (model.freq) { case RecurrenceModel.FREQ_MONTHLY: if (model.monthlyRepeat == RecurrenceModel.MONTHLY_BY_DATE) { if (model.monthlyByMonthDay > 0) { if (er.bymonthday == null || er.bymonthdayCount < 1) { er.bymonthday = new int[1]; } er.bymonthday[0] = model.monthlyByMonthDay; er.bymonthdayCount = 1; } } else if (model.monthlyRepeat == RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK) { if (model.monthlyByNthDayOfWeek <= 0) { throw new IllegalStateException("month repeat by nth week but n is " + model.monthlyByNthDayOfWeek); } int count = 1; if (er.bydayCount < count || er.byday == null || er.bydayNum == null) { er.byday = new int[count]; er.bydayNum = new int[count]; } er.bydayCount = count; er.byday[0] = EventRecurrence.timeDay2Day(model.monthlyByDayOfWeek); er.bydayNum[0] = model.monthlyByNthDayOfWeek; } break; case RecurrenceModel.FREQ_WEEKLY: int count = 0; for (int i = 0; i < 7; i++) { if (model.weeklyByDayOfWeek[i]) { count++; } } if (er.bydayCount < count || er.byday == null || er.bydayNum == null) { er.byday = new int[count]; er.bydayNum = new int[count]; } er.bydayCount = count; for (int i = 6; i >= 0; i--) { if (model.weeklyByDayOfWeek[i]) { er.bydayNum[--count] = 0; er.byday[count] = EventRecurrence.timeDay2Day(i); } } break; } if (!canHandleRecurrenceRule(er)) { throw new IllegalStateException("UI generated recurrence that it can't handle. ER:" + er.toString() + " Model: " + model.toString()); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRecurrence.wkst = EventRecurrence.timeDay2Day(Utils.getFirstDayOfWeek(getActivity())); getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); boolean endCountHasFocus = false; if (savedInstanceState != null) { RecurrenceModel m = (RecurrenceModel) savedInstanceState.get(BUNDLE_MODEL); if (m != null) { mModel = m; } endCountHasFocus = savedInstanceState.getBoolean(BUNDLE_END_COUNT_HAS_FOCUS); } else { Bundle b = getArguments(); if (b != null) { mTime.set(b.getLong(BUNDLE_START_TIME_MILLIS)); String tz = b.getString(BUNDLE_TIME_ZONE); if (!TextUtils.isEmpty(tz)) { mTime.timezone = tz; } mTime.normalize(false); // Time days of week: Sun=0, Mon=1, etc mModel.weeklyByDayOfWeek[mTime.weekDay] = true; String rrule = b.getString(BUNDLE_RRULE); if (!TextUtils.isEmpty(rrule)) { mModel.recurrenceState = RecurrenceModel.STATE_RECURRENCE; mRecurrence.parse(rrule); copyEventRecurrenceToModel(mRecurrence, mModel); // Leave today's day of week as checked by default in weekly view. if (mRecurrence.bydayCount == 0) { mModel.weeklyByDayOfWeek[mTime.weekDay] = true; } } } else { mTime.setToNow(); } } mResources = getResources(); mView = inflater.inflate(R.layout.recurrencepicker, container, true); final Activity activity = getActivity(); final Configuration config = activity.getResources().getConfiguration(); mRepeatSwitch = (Switch) mView.findViewById(R.id.repeat_switch); mRepeatSwitch.setChecked(mModel.recurrenceState == RecurrenceModel.STATE_RECURRENCE); mRepeatSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mModel.recurrenceState = isChecked ? RecurrenceModel.STATE_RECURRENCE : RecurrenceModel.STATE_NO_RECURRENCE; togglePickerOptions(); } }); mFreqSpinner = (Spinner) mView.findViewById(R.id.freqSpinner); mFreqSpinner.setOnItemSelectedListener(this); ArrayAdapter<CharSequence> freqAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.recurrence_freq, R.layout.recurrencepicker_freq_item); freqAdapter.setDropDownViewResource(R.layout.recurrencepicker_freq_item); mFreqSpinner.setAdapter(freqAdapter); mInterval = (EditText) mView.findViewById(R.id.interval); mInterval.addTextChangedListener(new minMaxTextWatcher(1, INTERVAL_DEFAULT, INTERVAL_MAX) { @Override void onChange(int v) { if (mIntervalResId != -1 && mInterval.getText().toString().length() > 0) { mModel.interval = v; updateIntervalText(); mInterval.requestLayout(); } } }); mIntervalPreText = (TextView) mView.findViewById(R.id.intervalPreText); mIntervalPostText = (TextView) mView.findViewById(R.id.intervalPostText); mEndNeverStr = mResources.getString(R.string.recurrence_end_continously); mEndDateLabel = mResources.getString(R.string.recurrence_end_date_label); mEndCountLabel = mResources.getString(R.string.recurrence_end_count_label); mEndSpinnerArray.add(mEndNeverStr); mEndSpinnerArray.add(mEndDateLabel); mEndSpinnerArray.add(mEndCountLabel); mEndSpinner = (Spinner) mView.findViewById(R.id.endSpinner); mEndSpinner.setOnItemSelectedListener(this); mEndSpinnerAdapter = new EndSpinnerAdapter(getActivity(), mEndSpinnerArray, R.layout.recurrencepicker_freq_item, R.layout.recurrencepicker_end_text); mEndSpinnerAdapter.setDropDownViewResource(R.layout.recurrencepicker_freq_item); mEndSpinner.setAdapter(mEndSpinnerAdapter); mEndCount = (EditText) mView.findViewById(R.id.endCount); mEndCount.addTextChangedListener(new minMaxTextWatcher(1, COUNT_DEFAULT, COUNT_MAX) { @Override void onChange(int v) { if (mModel.endCount != v) { mModel.endCount = v; updateEndCountText(); mEndCount.requestLayout(); } } }); mPostEndCount = (TextView) mView.findViewById(R.id.postEndCount); mEndDateTextView = (TextView) mView.findViewById(R.id.endDate); mEndDateTextView.setOnClickListener(this); if (mModel.endDate == null) { mModel.endDate = new Time(mTime); switch (mModel.freq) { case RecurrenceModel.FREQ_DAILY: case RecurrenceModel.FREQ_WEEKLY: mModel.endDate.month += 1; break; case RecurrenceModel.FREQ_MONTHLY: mModel.endDate.month += 3; break; case RecurrenceModel.FREQ_YEARLY: mModel.endDate.year += 3; break; } mModel.endDate.normalize(false); } mWeekGroup = (LinearLayout) mView.findViewById(R.id.weekGroup); mWeekGroup2 = (LinearLayout) mView.findViewById(R.id.weekGroup2); mOrdinalArray = mResources.getStringArray(R.array.ordinal_labels); // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7 String[] dayOfWeekString = new DateFormatSymbols().getWeekdays(); mDayOfWeekString = new String[7]; for (int i = 0; i < 7; i++) { mDayOfWeekString[i] = dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[i]]; } // In Time.java day of week order e.g. Sun = 0 int idx = Utils.getFirstDayOfWeek(getActivity()); // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7 dayOfWeekString = new DateFormatSymbols().getShortWeekdays(); int numOfButtonsInRow1; int numOfButtonsInRow2; if (mResources.getConfiguration().screenWidthDp > MIN_SCREEN_WIDTH_FOR_SINGLE_ROW_WEEK) { numOfButtonsInRow1 = 7; numOfButtonsInRow2 = 0; mWeekGroup2.setVisibility(View.GONE); mWeekGroup2.getChildAt(3).setVisibility(View.GONE); } else { numOfButtonsInRow1 = 4; numOfButtonsInRow2 = 3; mWeekGroup2.setVisibility(View.VISIBLE); // Set rightmost button on the second row invisible so it takes up // space and everything centers properly mWeekGroup2.getChildAt(3).setVisibility(View.INVISIBLE); } /* First row */ for (int i = 0; i < 7; i++) { if (i >= numOfButtonsInRow1) { mWeekGroup.getChildAt(i).setVisibility(View.GONE); continue; } mWeekByDayButtons[idx] = (ToggleButton) mWeekGroup.getChildAt(i); mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setOnCheckedChangeListener(this); if (++idx >= 7) { idx = 0; } } /* 2nd Row */ for (int i = 0; i < 3; i++) { if (i >= numOfButtonsInRow2) { mWeekGroup2.getChildAt(i).setVisibility(View.GONE); continue; } mWeekByDayButtons[idx] = (ToggleButton) mWeekGroup2.getChildAt(i); mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]); mWeekByDayButtons[idx].setOnCheckedChangeListener(this); if (++idx >= 7) { idx = 0; } } mMonthGroup = (LinearLayout) mView.findViewById(R.id.monthGroup); mMonthRepeatByRadioGroup = (RadioGroup) mView.findViewById(R.id.monthGroup); mMonthRepeatByRadioGroup.setOnCheckedChangeListener(this); mRepeatMonthlyByNthDayOfWeek = (RadioButton) mView .findViewById(R.id.repeatMonthlyByNthDayOfTheWeek); mRepeatMonthlyByNthDayOfMonth = (RadioButton) mView .findViewById(R.id.repeatMonthlyByNthDayOfMonth); mDone = (Button) mView.findViewById(R.id.done); mDone.setOnClickListener(this); togglePickerOptions(); updateDialog(); if (endCountHasFocus) { mEndCount.requestFocus(); } return mView; } private void togglePickerOptions() { if (mModel.recurrenceState == RecurrenceModel.STATE_NO_RECURRENCE) { mFreqSpinner.setEnabled(false); mEndSpinner.setEnabled(false); mIntervalPreText.setEnabled(false); mInterval.setEnabled(false); mIntervalPostText.setEnabled(false); mMonthRepeatByRadioGroup.setEnabled(false); mEndCount.setEnabled(false); mPostEndCount.setEnabled(false); mEndDateTextView.setEnabled(false); mRepeatMonthlyByNthDayOfWeek.setEnabled(false); mRepeatMonthlyByNthDayOfMonth.setEnabled(false); for (Button button : mWeekByDayButtons) { button.setEnabled(false); } } else { mView.findViewById(R.id.options).setEnabled(true); mFreqSpinner.setEnabled(true); mEndSpinner.setEnabled(true); mIntervalPreText.setEnabled(true); mInterval.setEnabled(true); mIntervalPostText.setEnabled(true); mMonthRepeatByRadioGroup.setEnabled(true); mEndCount.setEnabled(true); mPostEndCount.setEnabled(true); mEndDateTextView.setEnabled(true); mRepeatMonthlyByNthDayOfWeek.setEnabled(true); mRepeatMonthlyByNthDayOfMonth.setEnabled(true); for (Button button : mWeekByDayButtons) { button.setEnabled(true); } } updateDoneButtonState(); } private void updateDoneButtonState() { if (mModel.recurrenceState == RecurrenceModel.STATE_NO_RECURRENCE) { mDone.setEnabled(true); return; } if (mInterval.getText().toString().length() == 0) { mDone.setEnabled(false); return; } if (mEndCount.getVisibility() == View.VISIBLE && mEndCount.getText().toString().length() == 0) { mDone.setEnabled(false); return; } if (mModel.freq == RecurrenceModel.FREQ_WEEKLY) { for (CompoundButton b : mWeekByDayButtons) { if (b.isChecked()) { mDone.setEnabled(true); return; } } mDone.setEnabled(false); return; } mDone.setEnabled(true); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(BUNDLE_MODEL, mModel); if (mEndCount.hasFocus()) { outState.putBoolean(BUNDLE_END_COUNT_HAS_FOCUS, true); } } public void updateDialog() { // Interval // Checking before setting because this causes infinite recursion // in afterTextWatcher final String intervalStr = Integer.toString(mModel.interval); if (!intervalStr.equals(mInterval.getText().toString())) { mInterval.setText(intervalStr); } mFreqSpinner.setSelection(mModel.freq); mWeekGroup.setVisibility(mModel.freq == RecurrenceModel.FREQ_WEEKLY ? View.VISIBLE : View.GONE); mWeekGroup2.setVisibility(mModel.freq == RecurrenceModel.FREQ_WEEKLY ? View.VISIBLE : View.GONE); mMonthGroup.setVisibility(mModel.freq == RecurrenceModel.FREQ_MONTHLY ? View.VISIBLE : View.GONE); switch (mModel.freq) { case RecurrenceModel.FREQ_DAILY: mIntervalResId = R.plurals.recurrence_interval_daily; break; case RecurrenceModel.FREQ_WEEKLY: mIntervalResId = R.plurals.recurrence_interval_weekly; for (int i = 0; i < 7; i++) { mWeekByDayButtons[i].setChecked(mModel.weeklyByDayOfWeek[i]); } break; case RecurrenceModel.FREQ_MONTHLY: mIntervalResId = R.plurals.recurrence_interval_monthly; if (mModel.monthlyRepeat == RecurrenceModel.MONTHLY_BY_DATE) { mMonthRepeatByRadioGroup.check(R.id.repeatMonthlyByNthDayOfMonth); } else if (mModel.monthlyRepeat == RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK) { mMonthRepeatByRadioGroup.check(R.id.repeatMonthlyByNthDayOfTheWeek); } if (mMonthRepeatByDayOfWeekStr == null) { if (mModel.monthlyByNthDayOfWeek == 0) { mModel.monthlyByNthDayOfWeek = (mTime.monthDay + 6) / 7; mModel.monthlyByDayOfWeek = mTime.weekDay; } mMonthRepeatByDayOfWeekStr = mResources.getString( R.string.recurrence_month_pattern_by_day_of_week, mOrdinalArray[mModel.monthlyByNthDayOfWeek - 1], mDayOfWeekString[mModel.monthlyByDayOfWeek]); mRepeatMonthlyByNthDayOfWeek.setText(mMonthRepeatByDayOfWeekStr); } break; case RecurrenceModel.FREQ_YEARLY: mIntervalResId = R.plurals.recurrence_interval_yearly; break; } updateIntervalText(); updateDoneButtonState(); mEndSpinner.setSelection(mModel.end); if (mModel.end == RecurrenceModel.END_BY_DATE) { final String dateStr = DateUtils.formatDateTime(getActivity(), mModel.endDate.toMillis(false), DateUtils.FORMAT_NUMERIC_DATE); mEndDateTextView.setText(dateStr); } else { if (mModel.end == RecurrenceModel.END_BY_COUNT) { // Checking before setting because this causes infinite // recursion // in afterTextWatcher final String countStr = Integer.toString(mModel.endCount); if (!countStr.equals(mEndCount.getText().toString())) { mEndCount.setText(countStr); } } } } /** * @param endDateString */ private void setEndSpinnerEndDateStr(final String endDateString) { mEndSpinnerArray.set(1, endDateString); mEndSpinnerAdapter.notifyDataSetChanged(); } private void doToast() { Log.e(TAG, "Model = " + mModel.toString()); String rrule; if (mModel.recurrenceState == RecurrenceModel.STATE_NO_RECURRENCE) { rrule = "Not repeating"; } else { copyModelToEventRecurrence(mModel, mRecurrence); rrule = mRecurrence.toString(); } if (mToast != null) { mToast.cancel(); } mToast = Toast.makeText(getActivity(), rrule, Toast.LENGTH_LONG); mToast.show(); } // TODO Test and update for Right-to-Left private void updateIntervalText() { if (mIntervalResId == -1) { return; } final String INTERVAL_COUNT_MARKER = "%d"; String intervalString = mResources.getQuantityString(mIntervalResId, mModel.interval); int markerStart = intervalString.indexOf(INTERVAL_COUNT_MARKER); if (markerStart != -1) { if (markerStart == 0) { mIntervalPreText.setText(""); } else { int postTextStart = markerStart + INTERVAL_COUNT_MARKER.length(); if (postTextStart < intervalString.length() && intervalString.charAt(postTextStart) == ' ') { postTextStart++; } mIntervalPostText.setText(intervalString.subSequence(postTextStart, intervalString.length())); if (intervalString.charAt(markerStart - 1) == ' ') { markerStart--; } mIntervalPreText.setText(intervalString.subSequence(0, markerStart)); } } } /** * Update the "Repeat for N events" end option with the proper string values * based on the value that has been entered for N. */ private void updateEndCountText() { final String END_COUNT_MARKER = "%d"; String endString = mResources.getQuantityString(R.plurals.recurrence_end_count, mModel.endCount); int markerStart = endString.indexOf(END_COUNT_MARKER); if (markerStart != -1) { if (markerStart == 0) { Log.e(TAG, "No text to put in to recurrence's end spinner."); } else { int postTextStart = markerStart + END_COUNT_MARKER.length(); if (postTextStart < endString.length() && endString.charAt(postTextStart) == ' ') { postTextStart++; } mPostEndCount.setText(endString.subSequence(postTextStart, endString.length())); } } } // Implements OnItemSelectedListener interface // Freq spinner // End spinner @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (parent == mFreqSpinner) { mModel.freq = position; } else if (parent == mEndSpinner) { switch (position) { case RecurrenceModel.END_NEVER: mModel.end = RecurrenceModel.END_NEVER; break; case RecurrenceModel.END_BY_DATE: mModel.end = RecurrenceModel.END_BY_DATE; break; case RecurrenceModel.END_BY_COUNT: mModel.end = RecurrenceModel.END_BY_COUNT; if (mModel.endCount <= 1) { mModel.endCount = 1; } else if (mModel.endCount > COUNT_MAX) { mModel.endCount = COUNT_MAX; } updateEndCountText(); break; } mEndCount.setVisibility(mModel.end == RecurrenceModel.END_BY_COUNT ? View.VISIBLE : View.GONE); mEndDateTextView.setVisibility(mModel.end == RecurrenceModel.END_BY_DATE ? View.VISIBLE : View.GONE); mPostEndCount.setVisibility( mModel.end == RecurrenceModel.END_BY_COUNT && !mHidePostEndCount? View.VISIBLE : View.GONE); } updateDialog(); } // Implements OnItemSelectedListener interface @Override public void onNothingSelected(AdapterView<?> arg0) { } @Override public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { if (mModel.endDate == null) { mModel.endDate = new Time(mTime.timezone); mModel.endDate.hour = mModel.endDate.minute = mModel.endDate.second = 0; } mModel.endDate.year = year; mModel.endDate.month = monthOfYear; mModel.endDate.monthDay = dayOfMonth; mModel.endDate.normalize(false); updateDialog(); } // Implements OnCheckedChangeListener interface // Week repeat by day of week @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int itemIdx = -1; for (int i = 0; i < 7; i++) { if (itemIdx == -1 && buttonView == mWeekByDayButtons[i]) { itemIdx = i; mModel.weeklyByDayOfWeek[i] = isChecked; } } updateDialog(); } // Implements android.widget.RadioGroup.OnCheckedChangeListener interface // Month repeat by radio buttons @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.repeatMonthlyByNthDayOfMonth) { mModel.monthlyRepeat = RecurrenceModel.MONTHLY_BY_DATE; } else if (checkedId == R.id.repeatMonthlyByNthDayOfTheWeek) { mModel.monthlyRepeat = RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK; } updateDialog(); } // Implements OnClickListener interface // EndDate button // Done button @Override public void onClick(View v) { if (mEndDateTextView == v) { if (mDatePickerDialog != null) { mDatePickerDialog.dismiss(); } mDatePickerDialog = DatePickerDialog.newInstance(this, mModel.endDate.year, mModel.endDate.month, mModel.endDate.monthDay); mDatePickerDialog.setFirstDayOfWeek(Utils.getFirstDayOfWeekAsCalendar(getActivity())); mDatePickerDialog.setYearRange(Utils.YEAR_MIN, Utils.YEAR_MAX); mDatePickerDialog.show(getFragmentManager(), FRAG_TAG_DATE_PICKER); } else if (mDone == v) { String rrule; if (mModel.recurrenceState == RecurrenceModel.STATE_NO_RECURRENCE) { rrule = null; } else { copyModelToEventRecurrence(mModel, mRecurrence); rrule = mRecurrence.toString(); } mRecurrenceSetListener.onRecurrenceSet(rrule); dismiss(); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mDatePickerDialog = (DatePickerDialog) getFragmentManager() .findFragmentByTag(FRAG_TAG_DATE_PICKER); if (mDatePickerDialog != null) { mDatePickerDialog.setOnDateSetListener(this); } } public interface OnRecurrenceSetListener { void onRecurrenceSet(String rrule); } public void setOnRecurrenceSetListener(OnRecurrenceSetListener l) { mRecurrenceSetListener = l; } private class EndSpinnerAdapter extends ArrayAdapter<CharSequence> { final String END_DATE_MARKER = "%s"; final String END_COUNT_MARKER = "%d"; private LayoutInflater mInflater; private int mItemResourceId; private int mTextResourceId; private ArrayList<CharSequence> mStrings; private String mEndDateString; private boolean mUseFormStrings; /** * @param context * @param textViewResourceId * @param objects */ public EndSpinnerAdapter(Context context, ArrayList<CharSequence> strings, int itemResourceId, int textResourceId) { super(context, itemResourceId, strings); mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mItemResourceId = itemResourceId; mTextResourceId = textResourceId; mStrings = strings; mEndDateString = getResources().getString(R.string.recurrence_end_date); // If either date or count strings don't translate well, such that we aren't assured // to have some text available to be placed in the spinner, then we'll have to use // the more form-like versions of both strings instead. int markerStart = mEndDateString.indexOf(END_DATE_MARKER); if (markerStart <= 0) { // The date string does not have any text before the "%s" so we'll have to use the // more form-like strings instead. mUseFormStrings = true; } else { String countEndStr = getResources().getQuantityString( R.plurals.recurrence_end_count, 1); markerStart = countEndStr.indexOf(END_COUNT_MARKER); if (markerStart <= 0) { // The count string does not have any text before the "%d" so we'll have to use // the more form-like strings instead. mUseFormStrings = true; } } if (mUseFormStrings) { // We'll have to set the layout for the spinner to be weight=0 so it doesn't // take up too much space. mEndSpinner.setLayoutParams( new TableLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f)); } } @Override public View getView(int position, View convertView, ViewGroup parent) { View v; // Check if we can recycle the view if (convertView == null) { v = mInflater.inflate(mTextResourceId, parent, false); } else { v = convertView; } TextView item = (TextView) v.findViewById(R.id.spinner_item); int markerStart; switch (position) { case RecurrenceModel.END_NEVER: item.setText(mStrings.get(RecurrenceModel.END_NEVER)); break; case RecurrenceModel.END_BY_DATE: markerStart = mEndDateString.indexOf(END_DATE_MARKER); if (markerStart != -1) { if (mUseFormStrings || markerStart == 0) { // If we get here, the translation of "Until" doesn't work correctly, // so we'll just set the whole "Until a date" string. item.setText(mEndDateLabel); } else { if (mEndDateString.charAt(markerStart - 1) == ' ') { markerStart--; } item.setText(mEndDateString.subSequence(0, markerStart)); } } break; case RecurrenceModel.END_BY_COUNT: String endString = mResources.getQuantityString(R.plurals.recurrence_end_count, mModel.endCount); markerStart = endString.indexOf(END_COUNT_MARKER); if (markerStart != -1) { if (mUseFormStrings || markerStart == 0) { // If we get here, the translation of "For" doesn't work correctly, // so we'll just set the whole "For a number of events" string. item.setText(mEndCountLabel); // Also, we'll hide the " events" that would have been at the end. mPostEndCount.setVisibility(View.GONE); // Use this flag so the onItemSelected knows whether to show it later. mHidePostEndCount = true; } else { int postTextStart = markerStart + END_COUNT_MARKER.length(); if (endString.charAt(postTextStart) == ' ') { postTextStart++; } mPostEndCount.setText(endString.subSequence(postTextStart, endString.length())); // In case it's a recycled view that wasn't visible. - mPostEndCount.setVisibility(View.VISIBLE); + if (mModel.end == RecurrenceModel.END_BY_COUNT) { + mPostEndCount.setVisibility(View.VISIBLE); + } if (endString.charAt(markerStart - 1) == ' ') { markerStart--; } item.setText(endString.subSequence(0, markerStart)); } } break; default: v = null; break; } return v; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View v; // Check if we can recycle the view if (convertView == null) { v = mInflater.inflate(mItemResourceId, parent, false); } else { v = convertView; } TextView item = (TextView) v.findViewById(R.id.spinner_item); item.setText(mStrings.get(position)); return v; } } }
false
false
null
null
diff --git a/src/com/android/calendar/DayView.java b/src/com/android/calendar/DayView.java index e2dd89d7..2c714a60 100644 --- a/src/com/android/calendar/DayView.java +++ b/src/com/android/calendar/DayView.java @@ -1,3594 +1,3592 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.calendar; import com.android.calendar.CalendarController.EventType; import com.android.calendar.CalendarController.ViewType; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.database.Cursor; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; -import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Handler; import android.provider.Calendar.Attendees; import android.provider.Calendar.Calendars; import android.provider.Calendar.Events; import android.text.Layout.Alignment; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.ViewSwitcher; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * View for multi-day view. So far only 1 and 7 day have been tested. */ public class DayView extends View implements View.OnCreateContextMenuListener, ScaleGestureDetector.OnScaleGestureListener, View.OnClickListener { private static String TAG = "DayView"; private static boolean DEBUG = false; private static float mScale = 0; // Used for supporting different screen densities private static final long INVALID_EVENT_ID = -1; //This is used for remembering a null event private static final long ANIMATION_DURATION = 400; private static final int MENU_AGENDA = 2; private static final int MENU_DAY = 3; private static final int MENU_EVENT_VIEW = 5; private static final int MENU_EVENT_CREATE = 6; private static final int MENU_EVENT_EDIT = 7; private static final int MENU_EVENT_DELETE = 8; private static int DEFAULT_CELL_HEIGHT = 64; private static int MAX_CELL_HEIGHT = 150; private static int MIN_Y_SPAN = 100; private boolean mOnFlingCalled; /** * ID of the last event which was displayed with the toast popup. * * This is used to prevent popping up multiple quick views for the same event, especially * during calendar syncs. This becomes valid when an event is selected, either by default * on starting calendar or by scrolling to an event. It becomes invalid when the user * explicitly scrolls to an empty time slot, changes views, or deletes the event. */ private long mLastPopupEventID; protected Context mContext; private static final String[] CALENDARS_PROJECTION = new String[] { Calendars._ID, // 0 Calendars.ACCESS_LEVEL, // 1 Calendars.OWNER_ACCOUNT, // 2 }; private static final int CALENDARS_INDEX_ACCESS_LEVEL = 1; private static final int CALENDARS_INDEX_OWNER_ACCOUNT = 2; private static final String CALENDARS_WHERE = Calendars._ID + "=%d"; private static final String[] ATTENDEES_PROJECTION = new String[] { Attendees._ID, // 0 Attendees.ATTENDEE_RELATIONSHIP, // 1 }; private static final int ATTENDEES_INDEX_RELATIONSHIP = 1; private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=%d"; private static final int FROM_NONE = 0; private static final int FROM_ABOVE = 1; private static final int FROM_BELOW = 2; private static final int FROM_LEFT = 4; private static final int FROM_RIGHT = 8; private static final int ACCESS_LEVEL_NONE = 0; private static final int ACCESS_LEVEL_DELETE = 1; private static final int ACCESS_LEVEL_EDIT = 2; private static int mHorizontalSnapBackThreshold = 128; private static int HORIZONTAL_FLING_THRESHOLD = 75; private ContinueScroll mContinueScroll = new ContinueScroll(); // Make this visible within the package for more informative debugging Time mBaseDate; private Time mCurrentTime; //Update the current time line every five minutes if the window is left open that long private static final int UPDATE_CURRENT_TIME_DELAY = 300000; private UpdateCurrentTime mUpdateCurrentTime = new UpdateCurrentTime(); private int mTodayJulianDay; private Typeface mBold = Typeface.DEFAULT_BOLD; private int mFirstJulianDay; private int mLastJulianDay; private int mMonthLength; private int mFirstVisibleDate; private int mFirstVisibleDayOfWeek; private int[] mEarliestStartHour; // indexed by the week day offset private boolean[] mHasAllDayEvent; // indexed by the week day offset private Runnable mTZUpdater = new Runnable() { @Override public void run() { String tz = Utils.getTimeZone(mContext, this); mBaseDate.timezone = tz; mBaseDate.normalize(true); mCurrentTime.switchTimezone(tz); invalidate(); } }; /** * This variable helps to avoid unnecessarily reloading events by keeping * track of the start millis parameter used for the most recent loading * of events. If the next reload matches this, then the events are not * reloaded. To force a reload, set this to zero (this is set to zero * in the method clearCachedEvents()). */ private long mLastReloadMillis; private ArrayList<Event> mEvents = new ArrayList<Event>(); private ArrayList<Event> mAllDayEvents = new ArrayList<Event>(); private StaticLayout[] mLayouts = null; private StaticLayout[] mAllDayLayouts = null; private int mSelectionDay; // Julian day private int mSelectionHour; boolean mSelectionAllDay; /** Width of a day or non-conflicting event */ private int mCellWidth; // Pre-allocate these objects and re-use them private Rect mRect = new Rect(); - private RectF mRectF = new RectF(); private Rect mDestRect = new Rect(); private Paint mPaint = new Paint(); private Paint mEventTextPaint = new Paint(); private Paint mSelectionPaint = new Paint(); private float[] mLines; private int mFirstDayOfWeek; // First day of the week private PopupWindow mPopup; private View mPopupView; // The number of milliseconds to show the popup window private static final int POPUP_DISMISS_DELAY = 3000; private DismissPopup mDismissPopup = new DismissPopup(); private boolean mRemeasure = true; private final EventLoader mEventLoader; protected final EventGeometry mEventGeometry; - private static final int GRID_LINE_INNER_WIDTH = 1; - private static final int GRID_LINE_WIDTH = 5; + private static final float GRID_LINE_INNER_WIDTH = 1; + private static final float GRID_LINE_WIDTH = 5; private static final int DAY_GAP = 1; private static final int HOUR_GAP = 1; private static int SINGLE_ALLDAY_HEIGHT = 34; private static int MAX_ALLDAY_HEIGHT = 105; private static int ALLDAY_TOP_MARGIN = 3; private static int MAX_HEIGHT_OF_ONE_ALLDAY_EVENT = 34; private static final int HOURS_LEFT_MARGIN = 2; private static final int HOURS_RIGHT_MARGIN = 4; private static final int HOURS_MARGIN = HOURS_LEFT_MARGIN + HOURS_RIGHT_MARGIN; private static int CURRENT_TIME_LINE_HEIGHT = 2; private static int CURRENT_TIME_LINE_BORDER_WIDTH = 1; private static final int CURRENT_TIME_LINE_SIDE_BUFFER = 2; /* package */ static final int MINUTES_PER_HOUR = 60; /* package */ static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * 24; /* package */ static final int MILLIS_PER_MINUTE = 60 * 1000; /* package */ static final int MILLIS_PER_HOUR = (3600 * 1000); /* package */ static final int MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; private static final int DAY_HEADER_ALPHA = 0x26000000; private static final int DAY_HEADER_TODAY_ALPHA = 0x99000000; private static float DAY_HEADER_ONE_DAY_LEFT_MARGIN = -12; private static float DAY_HEADER_ONE_DAY_RIGHT_MARGIN = 5; private static float DAY_HEADER_ONE_DAY_BOTTOM_MARGIN = 6; private static float DAY_HEADER_LEFT_MARGIN = 5; private static float DAY_HEADER_RIGHT_MARGIN = 7; private static float DAY_HEADER_BOTTOM_MARGIN = 3; private static float DAY_HEADER_FONT_SIZE = 14; private static float DATE_HEADER_FONT_SIZE = 24; private static float NORMAL_FONT_SIZE = 12; private static float EVENT_TEXT_FONT_SIZE = 12; private static float HOURS_FONT_SIZE = 12; private static float AMPM_FONT_SIZE = 9; private static int MIN_CELL_WIDTH_FOR_TEXT = 27; private static final int MAX_EVENT_TEXT_LEN = 500; private static float MIN_EVENT_HEIGHT = 15.0F; // in pixels private static int CALENDAR_COLOR_SQUARE_SIZE = 10; private static int CALENDAR_COLOR_SQUARE_V_OFFSET = -1; private static int CALENDAR_COLOR_SQUARE_H_OFFSET = -3; private static int EVENT_RECT_TOP_MARGIN = -1; private static int EVENT_RECT_BOTTOM_MARGIN = -1; private static int EVENT_RECT_LEFT_MARGIN = -1; private static int EVENT_RECT_RIGHT_MARGIN = -1; private static int EVENT_TEXT_TOP_MARGIN = 2; private static int EVENT_TEXT_BOTTOM_MARGIN = 3; private static int EVENT_TEXT_LEFT_MARGIN = 11; private static int EVENT_TEXT_RIGHT_MARGIN = 4; private static int EVENT_ALL_DAY_TEXT_TOP_MARGIN = EVENT_TEXT_TOP_MARGIN; private static int EVENT_ALL_DAY_TEXT_BOTTOM_MARGIN = EVENT_TEXT_BOTTOM_MARGIN; private static int EVENT_ALL_DAY_TEXT_LEFT_MARGIN = EVENT_TEXT_LEFT_MARGIN; private static int EVENT_ALL_DAY_TEXT_RIGHT_MARGIN = EVENT_TEXT_RIGHT_MARGIN; private static int mSelectionColor; private static int mPressedColor; private static int mSelectedEventTextColor; private static int mEventTextColor; private static int mWeek_saturdayColor; private static int mWeek_sundayColor; private static int mCalendarDateBannerTextColor; // private static int mCalendarAllDayBackground; private static int mCalendarAmPmLabel; // private static int mCalendarDateBannerBackground; // private static int mCalendarDateSelected; // private static int mCalendarGridAreaBackground; private static int mCalendarGridAreaSelected; private static int mCalendarGridLineHorizontalColor; private static int mCalendarGridLineVerticalColor; private static int mCalendarGridLineInnerHorizontalColor; private static int mCalendarGridLineInnerVerticalColor; // private static int mCalendarHourBackground; private static int mCalendarHourLabel; // private static int mCalendarHourSelected; private int mViewStartX; private int mViewStartY; private int mMaxViewStartY; private int mViewHeight; private int mViewWidth; private int mGridAreaHeight; private static int mCellHeight = 0; // shared among all DayViews private static int mMinCellHeight = 32; private int mScrollStartY; private int mPreviousDirection; /** * Vertical distance or span between the two touch points at the start of a * scaling gesture */ private float mStartingSpanY = 0; /** Height of 1 hour in pixels at the start of a scaling gesture */ private int mCellHeightBeforeScaleGesture; /** The hour at the center two touch points */ private float mGestureCenterHour = 0; /** * Flag to decide whether to handle the up event. Cases where up events * should be ignored are 1) right after a scale gesture and 2) finger was * down before app launch */ private boolean mHandleActionUp = true; private int mHoursTextHeight; private int mAllDayHeight; private static int DAY_HEADER_HEIGHT = 45; /** * Max of all day events in a given day in this view. */ private int mMaxAllDayEvents; protected int mNumDays = 7; private int mNumHours = 10; /** Width of the time line (list of hours) to the left. */ private int mHoursWidth; private int mDateStrWidth; private int mFirstCell; private int mFirstHour = -1; private int mFirstHourOffset; private String[] mHourStrs; private String[] mDayStrs; private String[] mDayStrs2Letter; private boolean mIs24HourFormat; private ArrayList<Event> mSelectedEvents = new ArrayList<Event>(); private boolean mComputeSelectedEvents; private Event mSelectedEvent; private Event mPrevSelectedEvent; private Rect mPrevBox = new Rect(); protected final Resources mResources; protected final Drawable mCurrentTimeLine; protected final Drawable mTodayHeaderDrawable; protected final Drawable mEventBoxDrawable; private String mAmString; private String mPmString; private DeleteEventHelper mDeleteEventHelper; private ContextMenuHandler mContextMenuHandler = new ContextMenuHandler(); ScaleGestureDetector mScaleGestureDetector; /** * The initial state of the touch mode when we enter this view. */ private static final int TOUCH_MODE_INITIAL_STATE = 0; /** * Indicates we just received the touch event and we are waiting to see if * it is a tap or a scroll gesture. */ private static final int TOUCH_MODE_DOWN = 1; /** * Indicates the touch gesture is a vertical scroll */ private static final int TOUCH_MODE_VSCROLL = 0x20; /** * Indicates the touch gesture is a horizontal scroll */ private static final int TOUCH_MODE_HSCROLL = 0x40; private int mTouchMode = TOUCH_MODE_INITIAL_STATE; /** * The selection modes are HIDDEN, PRESSED, SELECTED, and LONGPRESS. */ private static final int SELECTION_HIDDEN = 0; private static final int SELECTION_PRESSED = 1; // D-pad down but not up yet private static final int SELECTION_SELECTED = 2; private static final int SELECTION_LONGPRESS = 3; private int mSelectionMode = SELECTION_HIDDEN; private boolean mScrolling = false; private CalendarController mController; private ViewSwitcher mViewSwitcher; private GestureDetector mGestureDetector; public DayView(Context context, CalendarController controller, ViewSwitcher viewSwitcher, EventLoader eventLoader, int numDays) { super(context); if (mScale == 0) { mScale = getContext().getResources().getDisplayMetrics().density; if (mScale != 1) { SINGLE_ALLDAY_HEIGHT *= mScale; ALLDAY_TOP_MARGIN *= mScale; MAX_HEIGHT_OF_ONE_ALLDAY_EVENT *= mScale; NORMAL_FONT_SIZE *= mScale; EVENT_TEXT_FONT_SIZE *= mScale; HOURS_FONT_SIZE *= mScale; AMPM_FONT_SIZE *= mScale; MIN_CELL_WIDTH_FOR_TEXT *= mScale; MIN_EVENT_HEIGHT *= mScale; HORIZONTAL_FLING_THRESHOLD *= mScale; CURRENT_TIME_LINE_HEIGHT *= mScale; CURRENT_TIME_LINE_BORDER_WIDTH *= mScale; MIN_Y_SPAN *= mScale; MAX_CELL_HEIGHT *= mScale; DEFAULT_CELL_HEIGHT *= mScale; DAY_HEADER_HEIGHT *= mScale; DAY_HEADER_LEFT_MARGIN *= mScale; DAY_HEADER_RIGHT_MARGIN *= mScale; DAY_HEADER_BOTTOM_MARGIN *= mScale; DAY_HEADER_ONE_DAY_LEFT_MARGIN *= mScale; DAY_HEADER_ONE_DAY_RIGHT_MARGIN *= mScale; DAY_HEADER_ONE_DAY_BOTTOM_MARGIN *= mScale; DAY_HEADER_FONT_SIZE *= mScale; DATE_HEADER_FONT_SIZE *= mScale; CALENDAR_COLOR_SQUARE_SIZE *= mScale; EVENT_TEXT_TOP_MARGIN *= mScale; EVENT_TEXT_BOTTOM_MARGIN *= mScale; EVENT_TEXT_LEFT_MARGIN *= mScale; EVENT_TEXT_RIGHT_MARGIN *= mScale; EVENT_ALL_DAY_TEXT_TOP_MARGIN *= mScale; EVENT_ALL_DAY_TEXT_BOTTOM_MARGIN *= mScale; EVENT_ALL_DAY_TEXT_LEFT_MARGIN *= mScale; EVENT_ALL_DAY_TEXT_RIGHT_MARGIN *= mScale; EVENT_RECT_TOP_MARGIN *= mScale; EVENT_RECT_BOTTOM_MARGIN *= mScale; EVENT_RECT_LEFT_MARGIN *= mScale; EVENT_RECT_RIGHT_MARGIN *= mScale; } } mResources = context.getResources(); mCurrentTimeLine = mResources.getDrawable(R.drawable.timeline_week_holo_light); mTodayHeaderDrawable = mResources.getDrawable(R.drawable.today_blue_week_holo_light); mEventBoxDrawable = mResources.getDrawable(R.drawable.panel_month_event_holo_light); mEventLoader = eventLoader; mEventGeometry = new EventGeometry(); mEventGeometry.setMinEventHeight(MIN_EVENT_HEIGHT); mEventGeometry.setHourGap(HOUR_GAP); mContext = context; mDeleteEventHelper = new DeleteEventHelper(context, null, false /* don't exit when done */); mLastPopupEventID = INVALID_EVENT_ID; mController = controller; mViewSwitcher = viewSwitcher; mGestureDetector = new GestureDetector(context, new CalendarGestureListener()); mScaleGestureDetector = new ScaleGestureDetector(getContext(), this); mNumDays = numDays; if (mCellHeight == 0) { mCellHeight = Utils.getSharedPreference(mContext, GeneralPreferences.KEY_DEFAULT_CELL_HEIGHT, DEFAULT_CELL_HEIGHT); } init(context); } private void init(Context context) { setFocusable(true); // Allow focus in touch mode so that we can do keyboard shortcuts // even after we've entered touch mode. setFocusableInTouchMode(true); setClickable(true); setOnCreateContextMenuListener(this); mFirstDayOfWeek = Utils.getFirstDayOfWeek(context); mCurrentTime = new Time(Utils.getTimeZone(context, mTZUpdater)); long currentTime = System.currentTimeMillis(); mCurrentTime.set(currentTime); //The % makes it go off at the next increment of 5 minutes. postDelayed(mUpdateCurrentTime, UPDATE_CURRENT_TIME_DELAY - (currentTime % UPDATE_CURRENT_TIME_DELAY)); mTodayJulianDay = Time.getJulianDay(currentTime, mCurrentTime.gmtoff); mWeek_saturdayColor = mResources.getColor(R.color.week_saturday); mWeek_sundayColor = mResources.getColor(R.color.week_sunday); mCalendarDateBannerTextColor = mResources.getColor(R.color.calendar_date_banner_text_color); // mCalendarAllDayBackground = mResources.getColor(R.color.calendar_all_day_background); mCalendarAmPmLabel = mResources.getColor(R.color.calendar_ampm_label); // mCalendarDateBannerBackground = mResources.getColor(R.color.calendar_date_banner_background); // mCalendarDateSelected = mResources.getColor(R.color.calendar_date_selected); // mCalendarGridAreaBackground = mResources.getColor(R.color.calendar_grid_area_background); mCalendarGridAreaSelected = mResources.getColor(R.color.calendar_grid_area_selected); mCalendarGridLineHorizontalColor = mResources.getColor(R.color.calendar_grid_line_horizontal_color); mCalendarGridLineVerticalColor = mResources.getColor(R.color.calendar_grid_line_vertical_color); mCalendarGridLineInnerHorizontalColor = mResources.getColor(R.color.calendar_grid_line_inner_horizontal_color); mCalendarGridLineInnerVerticalColor = mResources.getColor(R.color.calendar_grid_line_inner_vertical_color); // mCalendarHourBackground = mResources.getColor(R.color.calendar_hour_background); mCalendarHourLabel = mResources.getColor(R.color.calendar_hour_label); // mCalendarHourSelected = mResources.getColor(R.color.calendar_hour_selected); mSelectionColor = mResources.getColor(R.color.selection); mPressedColor = mResources.getColor(R.color.pressed); mSelectedEventTextColor = mResources.getColor(R.color.calendar_event_selected_text_color); mEventTextColor = mResources.getColor(R.color.calendar_event_text_color); mEventTextPaint.setColor(mEventTextColor); mEventTextPaint.setTextSize(EVENT_TEXT_FONT_SIZE); mEventTextPaint.setTextAlign(Paint.Align.LEFT); mEventTextPaint.setAntiAlias(true); int gridLineColor = mResources.getColor(R.color.calendar_grid_line_highlight_color); Paint p = mSelectionPaint; p.setColor(gridLineColor); p.setStyle(Style.FILL); p.setAntiAlias(false); p = mPaint; p.setAntiAlias(true); // Allocate space for 2 weeks worth of weekday names so that we can // easily start the week display at any week day. mDayStrs = new String[14]; // Also create an array of 2-letter abbreviations. mDayStrs2Letter = new String[14]; for (int i = Calendar.SUNDAY; i <= Calendar.SATURDAY; i++) { int index = i - Calendar.SUNDAY; // e.g. Tue for Tuesday mDayStrs[index] = DateUtils.getDayOfWeekString(i, DateUtils.LENGTH_MEDIUM); mDayStrs[index + 7] = mDayStrs[index]; // e.g. Tu for Tuesday mDayStrs2Letter[index] = DateUtils.getDayOfWeekString(i, DateUtils.LENGTH_SHORT); // If we don't have 2-letter day strings, fall back to 1-letter. if (mDayStrs2Letter[index].equals(mDayStrs[index])) { mDayStrs2Letter[index] = DateUtils.getDayOfWeekString(i, DateUtils.LENGTH_SHORTEST); } mDayStrs2Letter[index + 7] = mDayStrs2Letter[index]; } // Figure out how much space we need for the 3-letter abbrev names // in the worst case. p.setTextSize(DATE_HEADER_FONT_SIZE); p.setTypeface(mBold); String[] dateStrs = {" 28", " 30"}; mDateStrWidth = computeMaxStringWidth(0, dateStrs, p); p.setTextSize(DAY_HEADER_FONT_SIZE); mDateStrWidth += computeMaxStringWidth(0, mDayStrs, p); p.setTextSize(HOURS_FONT_SIZE); p.setTypeface(null); updateIs24HourFormat(); mAmString = DateUtils.getAMPMString(Calendar.AM); mPmString = DateUtils.getAMPMString(Calendar.PM); String[] ampm = {mAmString, mPmString}; p.setTextSize(AMPM_FONT_SIZE); mHoursWidth = computeMaxStringWidth(mHoursWidth, ampm, p); mHoursWidth += HOURS_MARGIN; LayoutInflater inflater; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mPopupView = inflater.inflate(R.layout.bubble_event, null); mPopupView.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); mPopup = new PopupWindow(context); mPopup.setContentView(mPopupView); Resources.Theme dialogTheme = getResources().newTheme(); dialogTheme.applyStyle(android.R.style.Theme_Dialog, true); TypedArray ta = dialogTheme.obtainStyledAttributes(new int[] { android.R.attr.windowBackground }); mPopup.setBackgroundDrawable(ta.getDrawable(0)); ta.recycle(); // Enable touching the popup window mPopupView.setOnClickListener(this); mBaseDate = new Time(Utils.getTimeZone(context, mTZUpdater)); long millis = System.currentTimeMillis(); mBaseDate.set(millis); mEarliestStartHour = new int[mNumDays]; mHasAllDayEvent = new boolean[mNumDays]; // mLines is the array of points used with Canvas.drawLines() in // drawGridBackground() and drawAllDayEvents(). Its size depends // on the max number of lines that can ever be drawn by any single // drawLines() call in either of those methods. final int maxGridLines = (24 + 1) // max horizontal lines we might draw + (mNumDays + 1); // max vertical lines we might draw mLines = new float[maxGridLines * 4]; } /** * This is called when the popup window is pressed. */ public void onClick(View v) { if (v == mPopupView) { // Pretend it was a trackball click because that will always // jump to the "View event" screen. switchViews(true /* trackball */); } } public void updateIs24HourFormat() { mIs24HourFormat = DateFormat.is24HourFormat(mContext); mHourStrs = mIs24HourFormat ? CalendarData.s24Hours : CalendarData.s12HoursNoAmPm; } /** * Returns the start of the selected time in milliseconds since the epoch. * * @return selected time in UTC milliseconds since the epoch. */ long getSelectedTimeInMillis() { Time time = new Time(mBaseDate); time.setJulianDay(mSelectionDay); time.hour = mSelectionHour; // We ignore the "isDst" field because we want normalize() to figure // out the correct DST value and not adjust the selected time based // on the current setting of DST. return time.normalize(true /* ignore isDst */); } Time getSelectedTime() { Time time = new Time(mBaseDate); time.setJulianDay(mSelectionDay); time.hour = mSelectionHour; // We ignore the "isDst" field because we want normalize() to figure // out the correct DST value and not adjust the selected time based // on the current setting of DST. time.normalize(true /* ignore isDst */); return time; } /** * Returns the start of the selected time in minutes since midnight, * local time. The derived class must ensure that this is consistent * with the return value from getSelectedTimeInMillis(). */ int getSelectedMinutesSinceMidnight() { return mSelectionHour * MINUTES_PER_HOUR; } public void setSelectedDay(Time time) { mBaseDate.set(time); mSelectionHour = mBaseDate.hour; mSelectedEvent = null; mPrevSelectedEvent = null; long millis = mBaseDate.toMillis(false /* use isDst */); mSelectionDay = Time.getJulianDay(millis, mBaseDate.gmtoff); mSelectedEvents.clear(); mComputeSelectedEvents = true; recalc(); // Don't draw the selection box if we are going to the "current" time long currMillis = System.currentTimeMillis(); boolean recent = (currMillis - 10000) < millis && millis < currMillis; mSelectionMode = recent ? SELECTION_HIDDEN : SELECTION_SELECTED; mRemeasure = true; invalidate(); } public Time getSelectedDay() { Time time = new Time(mBaseDate); time.setJulianDay(mSelectionDay); time.hour = mSelectionHour; // We ignore the "isDst" field because we want normalize() to figure // out the correct DST value and not adjust the selected time based // on the current setting of DST. time.normalize(true /* ignore isDst */); return time; } /** * return a negative number if "time" is comes before the visible time * range, a positive number if "time" is after the visible time range, and 0 * if it is in the visible time range. */ public int compareToVisibleTimeRange(Time time) { int savedHour = mBaseDate.hour; int savedMinute = mBaseDate.minute; int savedSec = mBaseDate.second; mBaseDate.hour = 0; mBaseDate.minute = 0; mBaseDate.second = 0; if (DEBUG) { Log.d(TAG, "Begin " + mBaseDate.toString()); Log.d(TAG, "Diff " + time.toString()); } // Compare beginning of range int diff = Time.compare(time, mBaseDate); if (diff > 0) { // Compare end of range mBaseDate.monthDay += mNumDays; mBaseDate.normalize(true); diff = Time.compare(time, mBaseDate); if (DEBUG) Log.d(TAG, "End " + mBaseDate.toString()); mBaseDate.monthDay -= mNumDays; mBaseDate.normalize(true); if (diff < 0) { // in visible time diff = 0; } else if (diff == 0) { // Midnight of following day diff = 1; } } if (DEBUG) Log.d(TAG, "Diff: " + diff); mBaseDate.hour = savedHour; mBaseDate.minute = savedMinute; mBaseDate.second = savedSec; return diff; } private void recalc() { // Set the base date to the beginning of the week if we are displaying // 7 days at a time. if (mNumDays == 7) { int dayOfWeek = mBaseDate.weekDay; int diff = dayOfWeek - mFirstDayOfWeek; if (diff != 0) { if (diff < 0) { diff += 7; } mBaseDate.monthDay -= diff; mBaseDate.normalize(true /* ignore isDst */); } } final long start = mBaseDate.toMillis(false /* use isDst */); mFirstJulianDay = Time.getJulianDay(start, mBaseDate.gmtoff); mLastJulianDay = mFirstJulianDay + mNumDays - 1; mMonthLength = mBaseDate.getActualMaximum(Time.MONTH_DAY); mFirstVisibleDate = mBaseDate.monthDay; mFirstVisibleDayOfWeek = mBaseDate.weekDay; } @Override protected void onSizeChanged(int width, int height, int oldw, int oldh) { mViewWidth = width; mViewHeight = height; int gridAreaWidth = width - mHoursWidth; mCellWidth = (gridAreaWidth - (mNumDays * DAY_GAP)) / mNumDays; // This would be about 1 day worth in a 7 day view mHorizontalSnapBackThreshold = width / 7; Paint p = new Paint(); p.setTextSize(HOURS_FONT_SIZE); mHoursTextHeight = (int) Math.abs(p.ascent()); remeasure(width, height); } /** * Measures the space needed for various parts of the view after * loading new events. This can change if there are all-day events. */ private void remeasure(int width, int height) { // First, clear the array of earliest start times, and the array // indicating presence of an all-day event. for (int day = 0; day < mNumDays; day++) { mEarliestStartHour[day] = 25; // some big number mHasAllDayEvent[day] = false; } // Compute the layout relation between each event before measuring cell // width, as the cell width should be adjusted along with the relation. // // Examples: A (1:00pm - 1:01pm), B (1:02pm - 2:00pm) // We should mark them as "overwapped". Though they are not overwapped logically, but // minimum cell height implicitly expands the cell height of A and it should look like // (1:00pm - 1:15pm) after the cell height adjustment. // Compute the space needed for the all-day events, if any. // Make a pass over all the events, and keep track of the maximum // number of all-day events in any one day. Also, keep track of // the earliest event in each day. int maxAllDayEvents = 0; final ArrayList<Event> events = mEvents; final int len = events.size(); // Num of all-day-events on each day. final int eventsCount[] = new int[mLastJulianDay - mFirstJulianDay + 1]; Arrays.fill(eventsCount, 0); for (int ii = 0; ii < len; ii++) { Event event = events.get(ii); if (event.startDay > mLastJulianDay || event.endDay < mFirstJulianDay) { continue; } if (event.allDay) { final int firstDay = Math.max(event.startDay, mFirstJulianDay); final int lastDay = Math.min(event.endDay, mLastJulianDay); for (int day = firstDay; day <= lastDay; day++) { final int count = ++eventsCount[day - mFirstJulianDay]; if (maxAllDayEvents < count) { maxAllDayEvents = count; } } int daynum = event.startDay - mFirstJulianDay; int durationDays = event.endDay - event.startDay + 1; if (daynum < 0) { durationDays += daynum; daynum = 0; } if (daynum + durationDays > mNumDays) { durationDays = mNumDays - daynum; } for (int day = daynum; durationDays > 0; day++, durationDays--) { mHasAllDayEvent[day] = true; } } else { int daynum = event.startDay - mFirstJulianDay; int hour = event.startTime / 60; if (daynum >= 0 && hour < mEarliestStartHour[daynum]) { mEarliestStartHour[daynum] = hour; } // Also check the end hour in case the event spans more than // one day. daynum = event.endDay - mFirstJulianDay; hour = event.endTime / 60; if (daynum < mNumDays && hour < mEarliestStartHour[daynum]) { mEarliestStartHour[daynum] = hour; } } } mMaxAllDayEvents = maxAllDayEvents; // Calculate mAllDayHeight mFirstCell = DAY_HEADER_HEIGHT; int allDayHeight = 0; if (maxAllDayEvents > 0) { // If there is at most one all-day event per day, then use less // space (but more than the space for a single event). if (maxAllDayEvents == 1) { allDayHeight = SINGLE_ALLDAY_HEIGHT; } else { // Allow the all-day area to grow in height depending on the // number of all-day events we need to show, up to a limit. allDayHeight = maxAllDayEvents * MAX_HEIGHT_OF_ONE_ALLDAY_EVENT; if (allDayHeight > MAX_ALLDAY_HEIGHT) { allDayHeight = MAX_ALLDAY_HEIGHT; } } mFirstCell = DAY_HEADER_HEIGHT + allDayHeight + ALLDAY_TOP_MARGIN; } else { mSelectionAllDay = false; } mAllDayHeight = allDayHeight; mGridAreaHeight = height - mFirstCell; // The min is where 24 hours cover the entire visible area mMinCellHeight = (height - DAY_HEADER_HEIGHT) / 24 - HOUR_GAP; if (mCellHeight < mMinCellHeight) { mCellHeight = mMinCellHeight; } mNumHours = mGridAreaHeight / mCellHeight; mEventGeometry.setHourHeight(mCellHeight); final long minimumDurationMillis = (long) (MIN_EVENT_HEIGHT * DateUtils.MINUTE_IN_MILLIS / (mCellHeight / 60.0f)); Event.computePositions(events, minimumDurationMillis); // Compute the top of our reachable view mMaxViewStartY = HOUR_GAP + 24 * (mCellHeight + HOUR_GAP) - mGridAreaHeight; if (DEBUG) { Log.e(TAG, "mViewStartY: " + mViewStartY); Log.e(TAG, "mMaxViewStartY: " + mMaxViewStartY); } if (mViewStartY > mMaxViewStartY) { mViewStartY = mMaxViewStartY; computeFirstHour(); } if (mFirstHour == -1) { initFirstHour(); mFirstHourOffset = 0; } // When we change the base date, the number of all-day events may // change and that changes the cell height. When we switch dates, // we use the mFirstHourOffset from the previous view, but that may // be too large for the new view if the cell height is smaller. if (mFirstHourOffset >= mCellHeight + HOUR_GAP) { mFirstHourOffset = mCellHeight + HOUR_GAP - 1; } mViewStartY = mFirstHour * (mCellHeight + HOUR_GAP) - mFirstHourOffset; final int eventAreaWidth = mNumDays * (mCellWidth + DAY_GAP); //When we get new events we don't want to dismiss the popup unless the event changes if (mSelectedEvent != null && mLastPopupEventID != mSelectedEvent.id) { mPopup.dismiss(); } mPopup.setWidth(eventAreaWidth - 20); mPopup.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); } /** * Initialize the state for another view. The given view is one that has * its own bitmap and will use an animation to replace the current view. * The current view and new view are either both Week views or both Day * views. They differ in their base date. * * @param view the view to initialize. */ private void initView(DayView view) { view.mSelectionHour = mSelectionHour; view.mSelectedEvents.clear(); view.mComputeSelectedEvents = true; view.mFirstHour = mFirstHour; view.mFirstHourOffset = mFirstHourOffset; view.remeasure(getWidth(), getHeight()); view.mSelectedEvent = null; view.mPrevSelectedEvent = null; view.mFirstDayOfWeek = mFirstDayOfWeek; if (view.mEvents.size() > 0) { view.mSelectionAllDay = mSelectionAllDay; } else { view.mSelectionAllDay = false; } // Redraw the screen so that the selection box will be redrawn. We may // have scrolled to a different part of the day in some other view // so the selection box in this view may no longer be visible. view.recalc(); } /** * Switch to another view based on what was selected (an event or a free * slot) and how it was selected (by touch or by trackball). * * @param trackBallSelection true if the selection was made using the * trackball. */ private void switchViews(boolean trackBallSelection) { Event selectedEvent = mSelectedEvent; mPopup.dismiss(); mLastPopupEventID = INVALID_EVENT_ID; if (mNumDays > 1) { // This is the Week view. // With touch, we always switch to Day/Agenda View // With track ball, if we selected a free slot, then create an event. // If we selected a specific event, switch to EventInfo view. if (trackBallSelection) { if (selectedEvent == null) { // Switch to the EditEvent view long startMillis = getSelectedTimeInMillis(); long endMillis = startMillis + DateUtils.HOUR_IN_MILLIS; mController.sendEventRelatedEvent(this, EventType.CREATE_EVENT, -1, startMillis, endMillis, 0, 0); } else { // Switch to the EventInfo view mController.sendEventRelatedEvent(this, EventType.VIEW_EVENT, selectedEvent.id, selectedEvent.startMillis, selectedEvent.endMillis, 0, 0); } } else { // This was a touch selection. If the touch selected a single // unambiguous event, then view that event. Otherwise go to // Day/Agenda view. if (mSelectedEvents.size() == 1) { mController.sendEventRelatedEvent(this, EventType.VIEW_EVENT, selectedEvent.id, selectedEvent.startMillis, selectedEvent.endMillis, 0, 0); } } } else { // This is the Day view. // If we selected a free slot, then create an event. // If we selected an event, then go to the EventInfo view. if (selectedEvent == null) { // Switch to the EditEvent view long startMillis = getSelectedTimeInMillis(); long endMillis = startMillis + DateUtils.HOUR_IN_MILLIS; mController.sendEventRelatedEvent(this, EventType.CREATE_EVENT, -1, startMillis, endMillis, 0, 0); } else { mController.sendEventRelatedEvent(this, EventType.VIEW_EVENT, selectedEvent.id, selectedEvent.startMillis, selectedEvent.endMillis, 0, 0); } } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { mScrolling = false; long duration = event.getEventTime() - event.getDownTime(); switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: if (mSelectionMode == SELECTION_HIDDEN) { // Don't do anything unless the selection is visible. break; } if (mSelectionMode == SELECTION_PRESSED) { // This was the first press when there was nothing selected. // Change the selection from the "pressed" state to the // the "selected" state. We treat short-press and // long-press the same here because nothing was selected. mSelectionMode = SELECTION_SELECTED; invalidate(); break; } // Check the duration to determine if this was a short press if (duration < ViewConfiguration.getLongPressTimeout()) { switchViews(true /* trackball */); } else { mSelectionMode = SELECTION_LONGPRESS; invalidate(); performLongClick(); } break; // case KeyEvent.KEYCODE_BACK: // if (event.isTracking() && !event.isCanceled()) { // mPopup.dismiss(); // mContext.finish(); // return true; // } // break; } return super.onKeyUp(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mSelectionMode == SELECTION_HIDDEN) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { // Display the selection box but don't move or select it // on this key press. mSelectionMode = SELECTION_SELECTED; invalidate(); return true; } else if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { // Display the selection box but don't select it // on this key press. mSelectionMode = SELECTION_PRESSED; invalidate(); return true; } } mSelectionMode = SELECTION_SELECTED; mScrolling = false; boolean redraw; int selectionDay = mSelectionDay; switch (keyCode) { case KeyEvent.KEYCODE_DEL: // Delete the selected event, if any Event selectedEvent = mSelectedEvent; if (selectedEvent == null) { return false; } mPopup.dismiss(); mLastPopupEventID = INVALID_EVENT_ID; long begin = selectedEvent.startMillis; long end = selectedEvent.endMillis; long id = selectedEvent.id; mDeleteEventHelper.delete(begin, end, id, -1); return true; case KeyEvent.KEYCODE_ENTER: switchViews(true /* trackball or keyboard */); return true; case KeyEvent.KEYCODE_BACK: if (event.getRepeatCount() == 0) { event.startTracking(); return true; } return super.onKeyDown(keyCode, event); case KeyEvent.KEYCODE_DPAD_LEFT: if (mSelectedEvent != null) { mSelectedEvent = mSelectedEvent.nextLeft; } if (mSelectedEvent == null) { mLastPopupEventID = INVALID_EVENT_ID; selectionDay -= 1; } redraw = true; break; case KeyEvent.KEYCODE_DPAD_RIGHT: if (mSelectedEvent != null) { mSelectedEvent = mSelectedEvent.nextRight; } if (mSelectedEvent == null) { mLastPopupEventID = INVALID_EVENT_ID; selectionDay += 1; } redraw = true; break; case KeyEvent.KEYCODE_DPAD_UP: if (mSelectedEvent != null) { mSelectedEvent = mSelectedEvent.nextUp; } if (mSelectedEvent == null) { mLastPopupEventID = INVALID_EVENT_ID; if (!mSelectionAllDay) { mSelectionHour -= 1; adjustHourSelection(); mSelectedEvents.clear(); mComputeSelectedEvents = true; } } redraw = true; break; case KeyEvent.KEYCODE_DPAD_DOWN: if (mSelectedEvent != null) { mSelectedEvent = mSelectedEvent.nextDown; } if (mSelectedEvent == null) { mLastPopupEventID = INVALID_EVENT_ID; if (mSelectionAllDay) { mSelectionAllDay = false; } else { mSelectionHour++; adjustHourSelection(); mSelectedEvents.clear(); mComputeSelectedEvents = true; } } redraw = true; break; default: return super.onKeyDown(keyCode, event); } if ((selectionDay < mFirstJulianDay) || (selectionDay > mLastJulianDay)) { DayView view = (DayView) mViewSwitcher.getNextView(); Time date = view.mBaseDate; date.set(mBaseDate); if (selectionDay < mFirstJulianDay) { date.monthDay -= mNumDays; } else { date.monthDay += mNumDays; } date.normalize(true /* ignore isDst */); view.mSelectionDay = selectionDay; initView(view); Time end = new Time(date); end.monthDay += mNumDays - 1; Log.d(TAG, "onKeyDown"); mController.sendEvent(this, EventType.GO_TO, date, end, -1, ViewType.CURRENT); return true; } mSelectionDay = selectionDay; mSelectedEvents.clear(); mComputeSelectedEvents = true; if (redraw) { invalidate(); return true; } return super.onKeyDown(keyCode, event); } private View switchViews(boolean forward, float xOffSet, float width) { if (DEBUG) Log.d(TAG, "switchViews(" + forward + ")..."); float progress = Math.abs(xOffSet) / width; if (progress > 1.0f) { progress = 1.0f; } float inFromXValue, inToXValue; float outFromXValue, outToXValue; if (forward) { inFromXValue = 1.0f - progress; inToXValue = 0.0f; outFromXValue = -progress; outToXValue = -1.0f; } else { inFromXValue = progress - 1.0f; inToXValue = 0.0f; outFromXValue = progress; outToXValue = 1.0f; } // We have to allocate these animation objects each time we switch views // because that is the only way to set the animation parameters. TranslateAnimation inAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, inFromXValue, Animation.RELATIVE_TO_SELF, inToXValue, Animation.ABSOLUTE, 0.0f, Animation.ABSOLUTE, 0.0f); TranslateAnimation outAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, outFromXValue, Animation.RELATIVE_TO_SELF, outToXValue, Animation.ABSOLUTE, 0.0f, Animation.ABSOLUTE, 0.0f); // Reduce the animation duration based on how far we have already swiped. long duration = (long) (ANIMATION_DURATION * (1.0f - progress)); inAnimation.setDuration(duration); outAnimation.setDuration(duration); mViewSwitcher.setInAnimation(inAnimation); mViewSwitcher.setOutAnimation(outAnimation); DayView view = (DayView) mViewSwitcher.getCurrentView(); view.cleanup(); mViewSwitcher.showNext(); view = (DayView) mViewSwitcher.getCurrentView(); view.requestFocus(); view.reloadEvents(); // Update the mini-month (but defer it until the animation // completes, to avoid stutter.) final Time start = new Time(view.mBaseDate); final Time end = new Time(view.mBaseDate); end.monthDay += mNumDays; end.normalize(true); postDelayed(new Runnable() { public void run() { mController.sendEvent(this, EventType.GO_TO, start, end, -1, ViewType.CURRENT); } }, duration); return view; } // This is called after scrolling stops to move the selected hour // to the visible part of the screen. private void resetSelectedHour() { if (mSelectionHour < mFirstHour + 1) { mSelectionHour = mFirstHour + 1; mSelectedEvent = null; mSelectedEvents.clear(); mComputeSelectedEvents = true; } else if (mSelectionHour > mFirstHour + mNumHours - 3) { mSelectionHour = mFirstHour + mNumHours - 3; mSelectedEvent = null; mSelectedEvents.clear(); mComputeSelectedEvents = true; } } private void initFirstHour() { mFirstHour = mSelectionHour - mNumHours / 5; if (mFirstHour < 0) { mFirstHour = 0; } else if (mFirstHour + mNumHours > 24) { mFirstHour = 24 - mNumHours; } } /** * Recomputes the first full hour that is visible on screen after the * screen is scrolled. */ private void computeFirstHour() { // Compute the first full hour that is visible on screen mFirstHour = (mViewStartY + mCellHeight + HOUR_GAP - 1) / (mCellHeight + HOUR_GAP); mFirstHourOffset = mFirstHour * (mCellHeight + HOUR_GAP) - mViewStartY; } private void adjustHourSelection() { if (mSelectionHour < 0) { mSelectionHour = 0; if (mMaxAllDayEvents > 0) { mPrevSelectedEvent = null; mSelectionAllDay = true; } } if (mSelectionHour > 23) { mSelectionHour = 23; } // If the selected hour is at least 2 time slots from the top and // bottom of the screen, then don't scroll the view. if (mSelectionHour < mFirstHour + 1) { // If there are all-days events for the selected day but there // are no more normal events earlier in the day, then jump to // the all-day event area. // Exception 1: allow the user to scroll to 8am with the trackball // before jumping to the all-day event area. // Exception 2: if 12am is on screen, then allow the user to select // 12am before going up to the all-day event area. int daynum = mSelectionDay - mFirstJulianDay; if (mMaxAllDayEvents > 0 && mEarliestStartHour[daynum] > mSelectionHour && mFirstHour > 0 && mFirstHour < 8) { mPrevSelectedEvent = null; mSelectionAllDay = true; mSelectionHour = mFirstHour + 1; return; } if (mFirstHour > 0) { mFirstHour -= 1; mViewStartY -= (mCellHeight + HOUR_GAP); if (mViewStartY < 0) { mViewStartY = 0; } return; } } if (mSelectionHour > mFirstHour + mNumHours - 3) { if (mFirstHour < 24 - mNumHours) { mFirstHour += 1; mViewStartY += (mCellHeight + HOUR_GAP); if (mViewStartY > mMaxViewStartY) { mViewStartY = mMaxViewStartY; } return; } else if (mFirstHour == 24 - mNumHours && mFirstHourOffset > 0) { mViewStartY = mMaxViewStartY; } } } void clearCachedEvents() { mLastReloadMillis = 0; } private Runnable mCancelCallback = new Runnable() { public void run() { clearCachedEvents(); } }; /* package */ void reloadEvents() { // Protect against this being called before this view has been // initialized. // if (mContext == null) { // return; // } // Make sure our time zones are up to date mTZUpdater.run(); mSelectedEvent = null; mPrevSelectedEvent = null; mSelectedEvents.clear(); // The start date is the beginning of the week at 12am Time weekStart = new Time(Utils.getTimeZone(mContext, mTZUpdater)); weekStart.set(mBaseDate); weekStart.hour = 0; weekStart.minute = 0; weekStart.second = 0; long millis = weekStart.normalize(true /* ignore isDst */); // Avoid reloading events unnecessarily. if (millis == mLastReloadMillis) { return; } mLastReloadMillis = millis; // load events in the background // mContext.startProgressSpinner(); final ArrayList<Event> events = new ArrayList<Event>(); mEventLoader.loadEventsInBackground(mNumDays, events, millis, new Runnable() { public void run() { mEvents = events; if (mAllDayEvents == null) { mAllDayEvents = new ArrayList<Event>(); } else { mAllDayEvents.clear(); } // Create a shorter array for all day events for(Event e : events) { if (e.allDay) { mAllDayEvents.add(e); } } // New events, new layouts if (mLayouts == null || mLayouts.length < events.size()) { mLayouts = new StaticLayout[events.size()]; } else { Arrays.fill(mLayouts, null); } if (mAllDayLayouts == null || mAllDayLayouts.length < mAllDayEvents.size()) { mAllDayLayouts = new StaticLayout[events.size()]; } else { Arrays.fill(mAllDayLayouts, null); } mRemeasure = true; mComputeSelectedEvents = true; recalc(); // mContext.stopProgressSpinner(); invalidate(); } }, mCancelCallback); } @Override protected void onDraw(Canvas canvas) { if (mRemeasure) { remeasure(getWidth(), getHeight()); mRemeasure = false; } canvas.save(); float yTranslate = -mViewStartY + DAY_HEADER_HEIGHT + mAllDayHeight; // offset canvas by the current drag and header position canvas.translate(-mViewStartX, yTranslate); // clip to everything below the allDay area Rect dest = mDestRect; dest.top = (int) (mFirstCell - yTranslate); dest.bottom = (int) (mViewHeight - yTranslate); dest.left = 0; dest.right = mViewWidth; canvas.save(); canvas.clipRect(dest); // Draw the movable part of the view doDraw(canvas); // restore to having no clip canvas.restore(); if ((mTouchMode & TOUCH_MODE_HSCROLL) != 0) { float xTranslate; if (mViewStartX > 0) { xTranslate = mViewWidth; } else { xTranslate = -mViewWidth; } // Move the canvas around to prep it for the next view // specifically, shift it by a screen and undo the // yTranslation which will be redone in the nextView's onDraw(). canvas.translate(xTranslate, -yTranslate); DayView nextView = (DayView) mViewSwitcher.getNextView(); // Prevent infinite recursive calls to onDraw(). nextView.mTouchMode = TOUCH_MODE_INITIAL_STATE; nextView.onDraw(canvas); // Move it back for this view canvas.translate(-xTranslate, 0); } else { // If we drew another view we already translated it back // If we didn't draw another view we should be at the edge of the // screen canvas.translate(mViewStartX, -yTranslate); } // Draw the fixed areas (that don't scroll) directly to the canvas. drawAfterScroll(canvas); mComputeSelectedEvents = false; canvas.restore(); } private void drawAfterScroll(Canvas canvas) { Paint p = mPaint; Rect r = mRect; if (mMaxAllDayEvents != 0) { drawAllDayEvents(mFirstJulianDay, mNumDays, canvas, p); // drawUpperLeftCorner(r, canvas, p); } drawScrollLine(r, canvas, p); drawDayHeaderLoop(r, canvas, p); // Draw the AM and PM indicators if we're in 12 hour mode if (!mIs24HourFormat) { drawAmPm(canvas, p); } // Update the popup window showing the event details, but only if // we are not scrolling and we have focus. if (!mScrolling && isFocused()) { updateEventDetails(); } } // This isn't really the upper-left corner. It's the square area just // below the upper-left corner, above the hours and to the left of the // all-day area. // private void drawUpperLeftCorner(Rect r, Canvas canvas, Paint p) { // p.setColor(mCalendarHourBackground); // r.top = DAY_HEADER_HEIGHT; // r.bottom = r.top + mAllDayHeight + ALLDAY_TOP_MARGIN; // r.left = 0; // r.right = mHoursWidth; // canvas.drawRect(r, p); // } private void drawScrollLine(Rect r, Canvas canvas, Paint p) { p.setColor(mCalendarGridLineInnerHorizontalColor); p.setAntiAlias(false); int y = mFirstCell - 1; canvas.drawLine(0, y, mHoursWidth + (mCellWidth + DAY_GAP) * mNumDays, y, p); p.setAntiAlias(true); } private void drawDayHeaderLoop(Rect r, Canvas canvas, Paint p) { // Draw the horizontal day background banner // p.setColor(mCalendarDateBannerBackground); // r.top = 0; // r.bottom = DAY_HEADER_HEIGHT; // r.left = 0; // r.right = mHoursWidth + mNumDays * (mCellWidth + DAY_GAP); // canvas.drawRect(r, p); // // Fill the extra space on the right side with the default background // r.left = r.right; // r.right = mViewWidth; // p.setColor(mCalendarGridAreaBackground); // canvas.drawRect(r, p); int todayNum = mTodayJulianDay - mFirstJulianDay; if (mNumDays > 1) { r.top = 0; r.bottom = DAY_HEADER_HEIGHT; // Highlight today if (mFirstJulianDay <= mTodayJulianDay && mTodayJulianDay < (mFirstJulianDay + mNumDays)) { r.left = mHoursWidth + todayNum * (mCellWidth + DAY_GAP); r.right = r.left + mCellWidth; mTodayHeaderDrawable.setBounds(r); mTodayHeaderDrawable.draw(canvas); } // Draw a highlight on the selected day (if any), but only if we are // displaying more than one day. // // int selectedDayNum = mSelectionDay - mFirstJulianDay; // if (mSelectionMode != SELECTION_HIDDEN && selectedDayNum >= 0 // && selectedDayNum < mNumDays) { // p.setColor(mCalendarDateSelected); // r.left = mHoursWidth + selectedDayNum * (mCellWidth + DAY_GAP); // r.right = r.left + mCellWidth; // canvas.drawRect(r, p); // } } p.setTypeface(mBold); p.setTextAlign(Paint.Align.RIGHT); float x = mHoursWidth; int deltaX = mCellWidth + DAY_GAP; int cell = mFirstJulianDay; String[] dayNames; if (mDateStrWidth < mCellWidth) { dayNames = mDayStrs; } else { dayNames = mDayStrs2Letter; } p.setAntiAlias(true); for (int day = 0; day < mNumDays; day++, cell++) { int dayOfWeek = day + mFirstVisibleDayOfWeek; if (dayOfWeek >= 14) { dayOfWeek -= 14; } int color = mCalendarDateBannerTextColor; if (mNumDays == 1) { if (dayOfWeek == Time.SATURDAY) { color = mWeek_saturdayColor; } else if (dayOfWeek == Time.SUNDAY) { color = mWeek_sundayColor; } } else { final int column = day % 7; if (Utils.isSaturday(column, mFirstDayOfWeek)) { color = mWeek_saturdayColor; } else if (Utils.isSunday(column, mFirstDayOfWeek)) { color = mWeek_sundayColor; } } color &= 0x00FFFFFF; if (todayNum == day) { color |= DAY_HEADER_TODAY_ALPHA; } else { color |= DAY_HEADER_ALPHA; } p.setColor(color); drawDayHeader(dayNames[dayOfWeek], day, cell, x, canvas, p); x += deltaX; } p.setTypeface(null); } private void drawAmPm(Canvas canvas, Paint p) { p.setColor(mCalendarAmPmLabel); p.setTextSize(AMPM_FONT_SIZE); p.setTypeface(mBold); p.setAntiAlias(true); mPaint.setTextAlign(Paint.Align.RIGHT); String text = mAmString; if (mFirstHour >= 12) { text = mPmString; } int y = mFirstCell + mFirstHourOffset + 2 * mHoursTextHeight + HOUR_GAP; int right = mHoursWidth - HOURS_RIGHT_MARGIN; canvas.drawText(text, right, y, p); if (mFirstHour < 12 && mFirstHour + mNumHours > 12) { // Also draw the "PM" text = mPmString; y = mFirstCell + mFirstHourOffset + (12 - mFirstHour) * (mCellHeight + HOUR_GAP) + 2 * mHoursTextHeight + HOUR_GAP; canvas.drawText(text, right, y, p); } } private void drawCurrentTimeLine(Rect r, final int left, final int top, Canvas canvas, Paint p) { r.left = left - CURRENT_TIME_LINE_SIDE_BUFFER; r.right = left + mCellWidth + DAY_GAP + CURRENT_TIME_LINE_SIDE_BUFFER; r.top = top - mCurrentTimeLine.getIntrinsicHeight() / 2; r.bottom = r.top + mCurrentTimeLine.getIntrinsicHeight(); mCurrentTimeLine.setBounds(r); mCurrentTimeLine.draw(canvas); } private void doDraw(Canvas canvas) { Paint p = mPaint; Rect r = mRect; drawGridBackground(r, canvas, p); drawHours(r, canvas, p); // Draw each day int x = mHoursWidth; int deltaX = mCellWidth + DAY_GAP; int cell = mFirstJulianDay; for (int day = 0; day < mNumDays; day++, cell++) { // TODO Wow, this needs cleanup. drawEvents loop through all the // events on every call. drawEvents(cell, x, HOUR_GAP, canvas, p); //If this is today if(cell == mTodayJulianDay) { int lineY = mCurrentTime.hour * (mCellHeight + HOUR_GAP) + ((mCurrentTime.minute * mCellHeight) / 60) + 1; //And the current time shows up somewhere on the screen if(lineY >= mViewStartY && lineY < mViewStartY + mViewHeight - 2) { drawCurrentTimeLine(r, x, lineY, canvas, p); } } x += deltaX; } } private void drawHours(Rect r, Canvas canvas, Paint p) { // Comment out as the background will be a drawable // Draw the background for the hour labels // p.setColor(mCalendarHourBackground); // r.top = 0; // r.bottom = 24 * (mCellHeight + HOUR_GAP) + HOUR_GAP; // r.left = 0; // r.right = mHoursWidth; // canvas.drawRect(r, p); // Fill the bottom left corner with the default grid background // r.top = r.bottom; // r.bottom = mBitmapHeight; // p.setColor(mCalendarGridAreaBackground); // canvas.drawRect(r, p); // Draw a highlight on the selected hour (if needed) if (mSelectionMode != SELECTION_HIDDEN && !mSelectionAllDay) { // p.setColor(mCalendarHourSelected); int daynum = mSelectionDay - mFirstJulianDay; r.top = mSelectionHour * (mCellHeight + HOUR_GAP); r.bottom = r.top + mCellHeight + HOUR_GAP; r.left = mHoursWidth + daynum * (mCellWidth + DAY_GAP); r.right = r.left + mCellWidth + DAY_GAP; // Draw a border around the highlighted grid hour. // drawEmptyRect(canvas, r, mSelectionPaint.getColor()); saveSelectionPosition(r.left, r.top, r.right, r.bottom); // Also draw the highlight on the grid p.setColor(mCalendarGridAreaSelected); r.top += HOUR_GAP; r.right -= DAY_GAP; canvas.drawRect(r, p); } p.setColor(mCalendarHourLabel); p.setTextSize(HOURS_FONT_SIZE); p.setTypeface(mBold); p.setTextAlign(Paint.Align.RIGHT); p.setAntiAlias(true); int right = mHoursWidth - HOURS_RIGHT_MARGIN; int y = HOUR_GAP + mHoursTextHeight; for (int i = 0; i < 24; i++) { String time = mHourStrs[i]; canvas.drawText(time, right, y, p); y += mCellHeight + HOUR_GAP; } } private void drawDayHeader(String dayStr, int day, int cell, float x, Canvas canvas, Paint p) { int dateNum = mFirstVisibleDate + day; if (dateNum > mMonthLength) { dateNum -= mMonthLength; } // Draw day of the month String dateNumStr = String.valueOf(dateNum); if (mNumDays > 1) { float y = DAY_HEADER_HEIGHT - DAY_HEADER_BOTTOM_MARGIN; // Draw day of the month x += mCellWidth - DAY_HEADER_RIGHT_MARGIN; p.setTextSize(DATE_HEADER_FONT_SIZE); canvas.drawText(dateNumStr, x, y, p); // Draw day of the week x -= p.measureText(dateNumStr) + DAY_HEADER_LEFT_MARGIN; p.setTextSize(DAY_HEADER_FONT_SIZE); canvas.drawText(dayStr, x, y, p); } else { float y = DAY_HEADER_HEIGHT - DAY_HEADER_ONE_DAY_BOTTOM_MARGIN; p.setTextAlign(Paint.Align.LEFT); // Draw day of the week x += DAY_HEADER_ONE_DAY_LEFT_MARGIN; p.setTextSize(DAY_HEADER_FONT_SIZE); canvas.drawText(dayStr, x, y, p); // Draw day of the month x += p.measureText(dayStr) + DAY_HEADER_ONE_DAY_RIGHT_MARGIN; p.setTextSize(DATE_HEADER_FONT_SIZE); canvas.drawText(dateNumStr, x, y, p); } } private void drawGridBackground(Rect r, Canvas canvas, Paint p) { Paint.Style savedStyle = p.getStyle(); // Draw the outer horizontal grid lines p.setColor(mCalendarGridLineHorizontalColor); p.setStyle(Style.FILL); p.setAntiAlias(false); final float startX = 0; final float stopX = mHoursWidth + (mCellWidth + DAY_GAP) * mNumDays; - float y = 1; + float y = 0; final float deltaY = mCellHeight + HOUR_GAP; p.setStrokeWidth(GRID_LINE_WIDTH); int linesIndex = 0; for (int hour = 0; hour <= 24; hour++) { mLines[linesIndex++] = startX; mLines[linesIndex++] = y; mLines[linesIndex++] = stopX; mLines[linesIndex++] = y; y += deltaY; } if (mCalendarGridLineVerticalColor != mCalendarGridLineHorizontalColor) { canvas.drawLines(mLines, 0, linesIndex, p); linesIndex = 0; p.setColor(mCalendarGridLineVerticalColor); } // Draw the outer vertical grid lines final float startY = 0; final float stopY = HOUR_GAP + 24 * (mCellHeight + HOUR_GAP); final float deltaX = mCellWidth + DAY_GAP; float x = mHoursWidth; for (int day = 0; day < mNumDays; day++) { x += deltaX; mLines[linesIndex++] = x; mLines[linesIndex++] = startY; mLines[linesIndex++] = x; mLines[linesIndex++] = stopY; } canvas.drawLines(mLines, 0, linesIndex, p); // Draw the inner horizontal grid lines p.setColor(mCalendarGridLineInnerHorizontalColor); p.setStrokeWidth(GRID_LINE_INNER_WIDTH); y = 0; linesIndex = 0; for (int hour = 0; hour <= 24; hour++) { mLines[linesIndex++] = startX; mLines[linesIndex++] = y; mLines[linesIndex++] = stopX; mLines[linesIndex++] = y; y += deltaY; } if (mCalendarGridLineInnerVerticalColor != mCalendarGridLineInnerHorizontalColor) { canvas.drawLines(mLines, 0, linesIndex, p); linesIndex = 0; p.setColor(mCalendarGridLineInnerVerticalColor); } // Draw the inner vertical grid lines x = mHoursWidth; for (int day = 0; day < mNumDays; day++) { x += deltaX; mLines[linesIndex++] = x; mLines[linesIndex++] = startY; mLines[linesIndex++] = x; mLines[linesIndex++] = stopY; } canvas.drawLines(mLines, 0, linesIndex, p); // Restore the saved style. p.setStyle(savedStyle); p.setAntiAlias(true); } Event getSelectedEvent() { if (mSelectedEvent == null) { // There is no event at the selected hour, so create a new event. return getNewEvent(mSelectionDay, getSelectedTimeInMillis(), getSelectedMinutesSinceMidnight()); } return mSelectedEvent; } boolean isEventSelected() { return (mSelectedEvent != null); } Event getNewEvent() { return getNewEvent(mSelectionDay, getSelectedTimeInMillis(), getSelectedMinutesSinceMidnight()); } static Event getNewEvent(int julianDay, long utcMillis, int minutesSinceMidnight) { Event event = Event.newInstance(); event.startDay = julianDay; event.endDay = julianDay; event.startMillis = utcMillis; event.endMillis = event.startMillis + MILLIS_PER_HOUR; event.startTime = minutesSinceMidnight; event.endTime = event.startTime + MINUTES_PER_HOUR; return event; } private int computeMaxStringWidth(int currentMax, String[] strings, Paint p) { float maxWidthF = 0.0f; int len = strings.length; for (int i = 0; i < len; i++) { float width = p.measureText(strings[i]); maxWidthF = Math.max(width, maxWidthF); } int maxWidth = (int) (maxWidthF + 0.5); if (maxWidth < currentMax) { maxWidth = currentMax; } return maxWidth; } private void saveSelectionPosition(float left, float top, float right, float bottom) { mPrevBox.left = (int) left; mPrevBox.right = (int) right; mPrevBox.top = (int) top; mPrevBox.bottom = (int) bottom; } private Rect getCurrentSelectionPosition() { Rect box = new Rect(); box.top = mSelectionHour * (mCellHeight + HOUR_GAP); box.bottom = box.top + mCellHeight + HOUR_GAP; int daynum = mSelectionDay - mFirstJulianDay; box.left = mHoursWidth + daynum * (mCellWidth + DAY_GAP); box.right = box.left + mCellWidth + DAY_GAP; return box; } private void setupTextRect(Rect r) { if (r.bottom <= r.top || r.right <= r.left) { r.bottom = r.top; r.right = r.left; return; } if (r.bottom - r.top > EVENT_TEXT_TOP_MARGIN + EVENT_TEXT_BOTTOM_MARGIN) { r.top += EVENT_TEXT_TOP_MARGIN; r.bottom -= EVENT_TEXT_BOTTOM_MARGIN; } if (r.right - r.left > EVENT_TEXT_LEFT_MARGIN + EVENT_TEXT_RIGHT_MARGIN) { r.left += EVENT_TEXT_LEFT_MARGIN; r.right -= EVENT_TEXT_RIGHT_MARGIN; } } private void setupAllDayTextRect(Rect r) { if (r.bottom <= r.top || r.right <= r.left) { r.bottom = r.top; r.right = r.left; return; } if (r.bottom - r.top > EVENT_ALL_DAY_TEXT_TOP_MARGIN + EVENT_ALL_DAY_TEXT_BOTTOM_MARGIN) { r.top += EVENT_ALL_DAY_TEXT_TOP_MARGIN; r.bottom -= EVENT_ALL_DAY_TEXT_BOTTOM_MARGIN; } if (r.right - r.left > EVENT_ALL_DAY_TEXT_LEFT_MARGIN + EVENT_ALL_DAY_TEXT_RIGHT_MARGIN) { r.left += EVENT_ALL_DAY_TEXT_LEFT_MARGIN; r.right -= EVENT_ALL_DAY_TEXT_RIGHT_MARGIN; } } /** * Return the layout for a numbered event. Create it if not already existing */ private StaticLayout getEventLayout(StaticLayout[] layouts, int i, Event event, Paint paint, Rect r) { if (i < 0 || i >= layouts.length) { return null; } StaticLayout layout = layouts[i]; // Check if we have already initialized the StaticLayout and that // the width hasn't changed (due to vertical resizing which causes // re-layout of events at min height) if (layout == null || r.width() != layout.getWidth()) { String text = drawTextSanitizer(event.getTitleAndLocation(), MAX_EVENT_TEXT_LEN); // Leave a one pixel boundary on the left and right of the rectangle for the event layout = new StaticLayout(text, 0, text.length(), new TextPaint(paint), r.width(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true, null, r.width()); layouts[i] = layout; } return layout; } private void drawAllDayEvents(int firstDay, int numDays, Canvas canvas, Paint p) { if (mSelectionAllDay) { // Draw the highlight on the selected all-day area mRect.top = DAY_HEADER_HEIGHT + 1; mRect.bottom = mRect.top + mAllDayHeight + ALLDAY_TOP_MARGIN - 2; int daynum = mSelectionDay - mFirstJulianDay; mRect.left = mHoursWidth + daynum * (mCellWidth + DAY_GAP); mRect.right = mRect.left + mCellWidth + DAY_GAP - 1; p.setColor(mCalendarGridAreaSelected); canvas.drawRect(mRect, p); } p.setTextSize(NORMAL_FONT_SIZE); p.setTextAlign(Paint.Align.LEFT); Paint eventTextPaint = mEventTextPaint; // Draw the background for the all-day events area // r.top = DAY_HEADER_HEIGHT; // r.bottom = r.top + mAllDayHeight + ALLDAY_TOP_MARGIN; // r.left = mHoursWidth; // r.right = r.left + mNumDays * (mCellWidth + DAY_GAP); // p.setColor(mCalendarAllDayBackground); // canvas.drawRect(r, p); // Fill the extra space on the right side with the default background // r.left = r.right; // r.right = mViewWidth; // p.setColor(mCalendarGridAreaBackground); // canvas.drawRect(r, p); // Draw the outer vertical grid lines p.setColor(mCalendarGridLineVerticalColor); p.setStyle(Style.FILL); p.setStrokeWidth(GRID_LINE_WIDTH); p.setAntiAlias(false); final float startY = DAY_HEADER_HEIGHT; final float stopY = startY + mAllDayHeight + ALLDAY_TOP_MARGIN; final float deltaX = mCellWidth + DAY_GAP; float x = mHoursWidth; int linesIndex = 0; // Line bounding the top of the all day area mLines[linesIndex++] = 0; mLines[linesIndex++] = startY; mLines[linesIndex++] = mHoursWidth + deltaX * mNumDays; mLines[linesIndex++] = startY; for (int day = 0; day < mNumDays; day++) { x += deltaX; mLines[linesIndex++] = x; mLines[linesIndex++] = startY; mLines[linesIndex++] = x; mLines[linesIndex++] = stopY; } canvas.drawLines(mLines, 0, linesIndex, p); // Draw the inner vertical grid lines p.setColor(mCalendarGridLineInnerVerticalColor); x = mHoursWidth; p.setStrokeWidth(GRID_LINE_INNER_WIDTH); linesIndex = 0; // Line bounding the top of the all day area mLines[linesIndex++] = 0; mLines[linesIndex++] = startY; mLines[linesIndex++] = mHoursWidth + (deltaX) * mNumDays; mLines[linesIndex++] = startY; for (int day = 0; day < mNumDays; day++) { x += deltaX; mLines[linesIndex++] = x; mLines[linesIndex++] = startY; mLines[linesIndex++] = x; mLines[linesIndex++] = stopY; } canvas.drawLines(mLines, 0, linesIndex, p); p.setAntiAlias(true); p.setStyle(Style.FILL); int y = DAY_HEADER_HEIGHT + ALLDAY_TOP_MARGIN; float left = mHoursWidth; int lastDay = firstDay + numDays - 1; final ArrayList<Event> events = mAllDayEvents; int numEvents = events.size(); float drawHeight = mAllDayHeight; float numRectangles = mMaxAllDayEvents; for (int i = 0; i < numEvents; i++) { Event event = events.get(i); int startDay = event.startDay; int endDay = event.endDay; if (startDay > lastDay || endDay < firstDay) { continue; } if (startDay < firstDay) { startDay = firstDay; } if (endDay > lastDay) { endDay = lastDay; } int startIndex = startDay - firstDay; int endIndex = endDay - firstDay; float height = drawHeight / numRectangles; // Prevent a single event from getting too big if (height > MAX_HEIGHT_OF_ONE_ALLDAY_EVENT) { height = MAX_HEIGHT_OF_ONE_ALLDAY_EVENT; } // Leave a one-pixel space between the vertical day lines and the // event rectangle. event.left = left + startIndex * (mCellWidth + DAY_GAP); event.right = left + endIndex * (mCellWidth + DAY_GAP) + mCellWidth; event.top = y + height * event.getColumn(); event.bottom = event.top + height; Rect r = drawEventRect(event, canvas, p, eventTextPaint); setupAllDayTextRect(r); StaticLayout layout = getEventLayout(mAllDayLayouts, i, event, eventTextPaint, r); drawEventText(layout, r, canvas, r.top, r.bottom); // Check if this all-day event intersects the selected day if (mSelectionAllDay && mComputeSelectedEvents) { if (startDay <= mSelectionDay && endDay >= mSelectionDay) { mSelectedEvents.add(event); } } } if (mSelectionAllDay) { // Compute the neighbors for the list of all-day events that // intersect the selected day. computeAllDayNeighbors(); // Set the selection position to zero so that when we move down // to the normal event area, we will highlight the topmost event. saveSelectionPosition(0f, 0f, 0f, 0f); } } private void computeAllDayNeighbors() { int len = mSelectedEvents.size(); if (len == 0 || mSelectedEvent != null) { return; } // First, clear all the links for (int ii = 0; ii < len; ii++) { Event ev = mSelectedEvents.get(ii); ev.nextUp = null; ev.nextDown = null; ev.nextLeft = null; ev.nextRight = null; } // For each event in the selected event list "mSelectedEvents", find // its neighbors in the up and down directions. This could be done // more efficiently by sorting on the Event.getColumn() field, but // the list is expected to be very small. // Find the event in the same row as the previously selected all-day // event, if any. int startPosition = -1; if (mPrevSelectedEvent != null && mPrevSelectedEvent.allDay) { startPosition = mPrevSelectedEvent.getColumn(); } int maxPosition = -1; Event startEvent = null; Event maxPositionEvent = null; for (int ii = 0; ii < len; ii++) { Event ev = mSelectedEvents.get(ii); int position = ev.getColumn(); if (position == startPosition) { startEvent = ev; } else if (position > maxPosition) { maxPositionEvent = ev; maxPosition = position; } for (int jj = 0; jj < len; jj++) { if (jj == ii) { continue; } Event neighbor = mSelectedEvents.get(jj); int neighborPosition = neighbor.getColumn(); if (neighborPosition == position - 1) { ev.nextUp = neighbor; } else if (neighborPosition == position + 1) { ev.nextDown = neighbor; } } } if (startEvent != null) { mSelectedEvent = startEvent; } else { mSelectedEvent = maxPositionEvent; } } private void drawEvents(int date, int left, int top, Canvas canvas, Paint p) { Paint eventTextPaint = mEventTextPaint; int cellWidth = mCellWidth; int cellHeight = mCellHeight; // Use the selected hour as the selection region Rect selectionArea = mRect; selectionArea.top = top + mSelectionHour * (cellHeight + HOUR_GAP); selectionArea.bottom = selectionArea.top + cellHeight; selectionArea.left = left; selectionArea.right = selectionArea.left + cellWidth; final ArrayList<Event> events = mEvents; int numEvents = events.size(); EventGeometry geometry = mEventGeometry; final int viewEndY = mViewStartY + mViewHeight - DAY_HEADER_HEIGHT - mAllDayHeight; for (int i = 0; i < numEvents; i++) { Event event = events.get(i); if (!geometry.computeEventRect(date, left, top, cellWidth, event)) { continue; } // Don't draw it if it is not visible if (event.bottom < mViewStartY || event.top > viewEndY) { continue; } if (date == mSelectionDay && !mSelectionAllDay && mComputeSelectedEvents && geometry.eventIntersectsSelection(event, selectionArea)) { mSelectedEvents.add(event); } Rect r = drawEventRect(event, canvas, p, eventTextPaint); setupTextRect(r); // Don't draw text if it is not visible if (r.top > viewEndY || r.bottom < mViewStartY) { continue; } StaticLayout layout = getEventLayout(mLayouts, i, event, eventTextPaint, r); // TODO: not sure why we are 4 pixels off drawEventText(layout, r, canvas, mViewStartY + 4, mViewStartY + mViewHeight - DAY_HEADER_HEIGHT - mAllDayHeight); } if (date == mSelectionDay && !mSelectionAllDay && isFocused() && mSelectionMode != SELECTION_HIDDEN) { computeNeighbors(); } } // Computes the "nearest" neighbor event in four directions (left, right, // up, down) for each of the events in the mSelectedEvents array. private void computeNeighbors() { int len = mSelectedEvents.size(); if (len == 0 || mSelectedEvent != null) { return; } // First, clear all the links for (int ii = 0; ii < len; ii++) { Event ev = mSelectedEvents.get(ii); ev.nextUp = null; ev.nextDown = null; ev.nextLeft = null; ev.nextRight = null; } Event startEvent = mSelectedEvents.get(0); int startEventDistance1 = 100000; // any large number int startEventDistance2 = 100000; // any large number int prevLocation = FROM_NONE; int prevTop; int prevBottom; int prevLeft; int prevRight; int prevCenter = 0; Rect box = getCurrentSelectionPosition(); if (mPrevSelectedEvent != null) { prevTop = (int) mPrevSelectedEvent.top; prevBottom = (int) mPrevSelectedEvent.bottom; prevLeft = (int) mPrevSelectedEvent.left; prevRight = (int) mPrevSelectedEvent.right; // Check if the previously selected event intersects the previous // selection box. (The previously selected event may be from a // much older selection box.) if (prevTop >= mPrevBox.bottom || prevBottom <= mPrevBox.top || prevRight <= mPrevBox.left || prevLeft >= mPrevBox.right) { mPrevSelectedEvent = null; prevTop = mPrevBox.top; prevBottom = mPrevBox.bottom; prevLeft = mPrevBox.left; prevRight = mPrevBox.right; } else { // Clip the top and bottom to the previous selection box. if (prevTop < mPrevBox.top) { prevTop = mPrevBox.top; } if (prevBottom > mPrevBox.bottom) { prevBottom = mPrevBox.bottom; } } } else { // Just use the previously drawn selection box prevTop = mPrevBox.top; prevBottom = mPrevBox.bottom; prevLeft = mPrevBox.left; prevRight = mPrevBox.right; } // Figure out where we came from and compute the center of that area. if (prevLeft >= box.right) { // The previously selected event was to the right of us. prevLocation = FROM_RIGHT; prevCenter = (prevTop + prevBottom) / 2; } else if (prevRight <= box.left) { // The previously selected event was to the left of us. prevLocation = FROM_LEFT; prevCenter = (prevTop + prevBottom) / 2; } else if (prevBottom <= box.top) { // The previously selected event was above us. prevLocation = FROM_ABOVE; prevCenter = (prevLeft + prevRight) / 2; } else if (prevTop >= box.bottom) { // The previously selected event was below us. prevLocation = FROM_BELOW; prevCenter = (prevLeft + prevRight) / 2; } // For each event in the selected event list "mSelectedEvents", search // all the other events in that list for the nearest neighbor in 4 // directions. for (int ii = 0; ii < len; ii++) { Event ev = mSelectedEvents.get(ii); int startTime = ev.startTime; int endTime = ev.endTime; int left = (int) ev.left; int right = (int) ev.right; int top = (int) ev.top; if (top < box.top) { top = box.top; } int bottom = (int) ev.bottom; if (bottom > box.bottom) { bottom = box.bottom; } if (false) { int flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_CAP_NOON_MIDNIGHT; if (DateFormat.is24HourFormat(mContext)) { flags |= DateUtils.FORMAT_24HOUR; } String timeRange = DateUtils.formatDateRange(mContext, ev.startMillis, ev.endMillis, flags); Log.i("Cal", "left: " + left + " right: " + right + " top: " + top + " bottom: " + bottom + " ev: " + timeRange + " " + ev.title); } int upDistanceMin = 10000; // any large number int downDistanceMin = 10000; // any large number int leftDistanceMin = 10000; // any large number int rightDistanceMin = 10000; // any large number Event upEvent = null; Event downEvent = null; Event leftEvent = null; Event rightEvent = null; // Pick the starting event closest to the previously selected event, // if any. distance1 takes precedence over distance2. int distance1 = 0; int distance2 = 0; if (prevLocation == FROM_ABOVE) { if (left >= prevCenter) { distance1 = left - prevCenter; } else if (right <= prevCenter) { distance1 = prevCenter - right; } distance2 = top - prevBottom; } else if (prevLocation == FROM_BELOW) { if (left >= prevCenter) { distance1 = left - prevCenter; } else if (right <= prevCenter) { distance1 = prevCenter - right; } distance2 = prevTop - bottom; } else if (prevLocation == FROM_LEFT) { if (bottom <= prevCenter) { distance1 = prevCenter - bottom; } else if (top >= prevCenter) { distance1 = top - prevCenter; } distance2 = left - prevRight; } else if (prevLocation == FROM_RIGHT) { if (bottom <= prevCenter) { distance1 = prevCenter - bottom; } else if (top >= prevCenter) { distance1 = top - prevCenter; } distance2 = prevLeft - right; } if (distance1 < startEventDistance1 || (distance1 == startEventDistance1 && distance2 < startEventDistance2)) { startEvent = ev; startEventDistance1 = distance1; startEventDistance2 = distance2; } // For each neighbor, figure out if it is above or below or left // or right of me and compute the distance. for (int jj = 0; jj < len; jj++) { if (jj == ii) { continue; } Event neighbor = mSelectedEvents.get(jj); int neighborLeft = (int) neighbor.left; int neighborRight = (int) neighbor.right; if (neighbor.endTime <= startTime) { // This neighbor is entirely above me. // If we overlap the same column, then compute the distance. if (neighborLeft < right && neighborRight > left) { int distance = startTime - neighbor.endTime; if (distance < upDistanceMin) { upDistanceMin = distance; upEvent = neighbor; } else if (distance == upDistanceMin) { int center = (left + right) / 2; int currentDistance = 0; int currentLeft = (int) upEvent.left; int currentRight = (int) upEvent.right; if (currentRight <= center) { currentDistance = center - currentRight; } else if (currentLeft >= center) { currentDistance = currentLeft - center; } int neighborDistance = 0; if (neighborRight <= center) { neighborDistance = center - neighborRight; } else if (neighborLeft >= center) { neighborDistance = neighborLeft - center; } if (neighborDistance < currentDistance) { upDistanceMin = distance; upEvent = neighbor; } } } } else if (neighbor.startTime >= endTime) { // This neighbor is entirely below me. // If we overlap the same column, then compute the distance. if (neighborLeft < right && neighborRight > left) { int distance = neighbor.startTime - endTime; if (distance < downDistanceMin) { downDistanceMin = distance; downEvent = neighbor; } else if (distance == downDistanceMin) { int center = (left + right) / 2; int currentDistance = 0; int currentLeft = (int) downEvent.left; int currentRight = (int) downEvent.right; if (currentRight <= center) { currentDistance = center - currentRight; } else if (currentLeft >= center) { currentDistance = currentLeft - center; } int neighborDistance = 0; if (neighborRight <= center) { neighborDistance = center - neighborRight; } else if (neighborLeft >= center) { neighborDistance = neighborLeft - center; } if (neighborDistance < currentDistance) { downDistanceMin = distance; downEvent = neighbor; } } } } if (neighborLeft >= right) { // This neighbor is entirely to the right of me. // Take the closest neighbor in the y direction. int center = (top + bottom) / 2; int distance = 0; int neighborBottom = (int) neighbor.bottom; int neighborTop = (int) neighbor.top; if (neighborBottom <= center) { distance = center - neighborBottom; } else if (neighborTop >= center) { distance = neighborTop - center; } if (distance < rightDistanceMin) { rightDistanceMin = distance; rightEvent = neighbor; } else if (distance == rightDistanceMin) { // Pick the closest in the x direction int neighborDistance = neighborLeft - right; int currentDistance = (int) rightEvent.left - right; if (neighborDistance < currentDistance) { rightDistanceMin = distance; rightEvent = neighbor; } } } else if (neighborRight <= left) { // This neighbor is entirely to the left of me. // Take the closest neighbor in the y direction. int center = (top + bottom) / 2; int distance = 0; int neighborBottom = (int) neighbor.bottom; int neighborTop = (int) neighbor.top; if (neighborBottom <= center) { distance = center - neighborBottom; } else if (neighborTop >= center) { distance = neighborTop - center; } if (distance < leftDistanceMin) { leftDistanceMin = distance; leftEvent = neighbor; } else if (distance == leftDistanceMin) { // Pick the closest in the x direction int neighborDistance = left - neighborRight; int currentDistance = left - (int) leftEvent.right; if (neighborDistance < currentDistance) { leftDistanceMin = distance; leftEvent = neighbor; } } } } ev.nextUp = upEvent; ev.nextDown = downEvent; ev.nextLeft = leftEvent; ev.nextRight = rightEvent; } mSelectedEvent = startEvent; } private Rect drawEventRect(Event event, Canvas canvas, Paint p, Paint eventTextPaint) { // Draw the Event Rect Rect r = mRect; r.top = (int) event.top + EVENT_RECT_TOP_MARGIN; r.bottom = (int) event.bottom - EVENT_RECT_BOTTOM_MARGIN; r.left = (int) event.left + EVENT_RECT_LEFT_MARGIN; r.right = (int) event.right - EVENT_RECT_RIGHT_MARGIN; mEventBoxDrawable.setBounds(r); mEventBoxDrawable.draw(canvas); // drawEmptyRect(canvas, r, 0xFF00FF00); // for debugging int eventTextColor = mEventTextColor; p.setStyle(Style.FILL); // If this event is selected, then use the selection color if (mSelectedEvent == event) { boolean paintIt = false; int color = 0; if (mSelectionMode == SELECTION_PRESSED) { // Also, remember the last selected event that we drew mPrevSelectedEvent = event; // box = mBoxPressed; color = mPressedColor; eventTextColor = mSelectedEventTextColor; paintIt = true; } else if (mSelectionMode == SELECTION_SELECTED) { // Also, remember the last selected event that we drew mPrevSelectedEvent = event; // box = mBoxSelected; color = mPressedColor; eventTextColor = mSelectedEventTextColor; paintIt = true; } else if (mSelectionMode == SELECTION_LONGPRESS) { // box = mBoxLongPressed; color = mPressedColor; eventTextColor = mSelectedEventTextColor; paintIt = true; } if (paintIt) { p.setColor(color); canvas.drawRect(r, p); } } eventTextPaint.setColor(eventTextColor); // Draw cal color square border r.top = (int) event.top + CALENDAR_COLOR_SQUARE_V_OFFSET; r.left = (int) event.left + CALENDAR_COLOR_SQUARE_H_OFFSET; r.bottom = r.top + CALENDAR_COLOR_SQUARE_SIZE + 1; r.right = r.left + CALENDAR_COLOR_SQUARE_SIZE + 1; p.setColor(0xFFFFFFFF); canvas.drawRect(r, p); // Draw cal color r.top++; r.left++; r.bottom--; r.right--; p.setColor(event.color); canvas.drawRect(r, p); boolean declined = (event.selfAttendeeStatus == Attendees.ATTENDEE_STATUS_DECLINED); if (declined) { boolean aa = p.isAntiAlias(); if (!aa) { p.setAntiAlias(true); } // Temp behavior p.setColor(0x88FFFFFF); canvas.drawLine(r.right, r.top, r.left, r.bottom, p); if (!aa) { p.setAntiAlias(false); } } // Setup rect for drawEventText which follows r.top = (int) event.top + EVENT_RECT_TOP_MARGIN; r.bottom = (int) event.bottom - EVENT_RECT_BOTTOM_MARGIN; r.left = (int) event.left + EVENT_RECT_LEFT_MARGIN; r.right = (int) event.right - EVENT_RECT_RIGHT_MARGIN; return r; } private Pattern drawTextSanitizerFilter = Pattern.compile("[\t\n],"); // Sanitize a string before passing it to drawText or else we get little // squares. For newlines and tabs before a comma, delete the character. // Otherwise, just replace them with a space. private String drawTextSanitizer(String string, int maxEventTextLen) { Matcher m = drawTextSanitizerFilter.matcher(string); string = m.replaceAll(","); int len = string.length(); if (len > maxEventTextLen) { string = string.substring(0, maxEventTextLen); len = maxEventTextLen; } return string.replace('\n', ' '); } private void drawEventText(StaticLayout eventLayout, Rect rect, Canvas canvas, int top, int bottom) { // drawEmptyRect(canvas, rect, 0xFFFF00FF); // for debugging int width = rect.right - rect.left; int height = rect.bottom - rect.top; // If the rectangle is too small for text, then return if (eventLayout == null || width < MIN_CELL_WIDTH_FOR_TEXT) { return; } int totalLineHeight = 0; int lineCount = eventLayout.getLineCount(); for (int i = 0; i < lineCount; i++) { int lineBottom = eventLayout.getLineBottom(i); if (lineBottom <= height) { totalLineHeight = lineBottom; } else { break; } } if (totalLineHeight == 0 || rect.top > bottom || rect.top + totalLineHeight < top) { return; } // Use a StaticLayout to format the string. canvas.save(); canvas.translate(rect.left, rect.top); rect.left = 0; rect.right = width; rect.top = 0; rect.bottom = totalLineHeight; // There's a bug somewhere. If this rect is outside of a previous // cliprect, this becomes a no-op. What happens is that the text draw // past the event rect. The current fix is to not draw the staticLayout // at all if it is completely out of bound. canvas.clipRect(rect); eventLayout.draw(canvas); canvas.restore(); } // This is to replace p.setStyle(Style.STROKE); canvas.drawRect() since it // doesn't work well with hardware acceleration private void drawEmptyRect(Canvas canvas, Rect r, int color) { int linesIndex = 0; mLines[linesIndex++] = r.left; mLines[linesIndex++] = r.top; mLines[linesIndex++] = r.right; mLines[linesIndex++] = r.top; mLines[linesIndex++] = r.left; mLines[linesIndex++] = r.bottom; mLines[linesIndex++] = r.right; mLines[linesIndex++] = r.bottom; mLines[linesIndex++] = r.left; mLines[linesIndex++] = r.top; mLines[linesIndex++] = r.left; mLines[linesIndex++] = r.bottom; mLines[linesIndex++] = r.right; mLines[linesIndex++] = r.top; mLines[linesIndex++] = r.right; mLines[linesIndex++] = r.bottom; mPaint.setColor(color); canvas.drawLines(mLines, 0, linesIndex, mPaint); } private void updateEventDetails() { if (mSelectedEvent == null || mSelectionMode == SELECTION_HIDDEN || mSelectionMode == SELECTION_LONGPRESS) { mPopup.dismiss(); return; } if (mLastPopupEventID == mSelectedEvent.id) { return; } mLastPopupEventID = mSelectedEvent.id; // Remove any outstanding callbacks to dismiss the popup. getHandler().removeCallbacks(mDismissPopup); Event event = mSelectedEvent; TextView titleView = (TextView) mPopupView.findViewById(R.id.event_title); titleView.setText(event.title); ImageView imageView = (ImageView) mPopupView.findViewById(R.id.reminder_icon); imageView.setVisibility(event.hasAlarm ? View.VISIBLE : View.GONE); imageView = (ImageView) mPopupView.findViewById(R.id.repeat_icon); imageView.setVisibility(event.isRepeating ? View.VISIBLE : View.GONE); int flags; if (event.allDay) { flags = DateUtils.FORMAT_UTC | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_ALL; } else { flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_CAP_NOON_MIDNIGHT; } if (DateFormat.is24HourFormat(mContext)) { flags |= DateUtils.FORMAT_24HOUR; } String timeRange = Utils.formatDateRange(mContext, event.startMillis, event.endMillis, flags); TextView timeView = (TextView) mPopupView.findViewById(R.id.time); timeView.setText(timeRange); TextView whereView = (TextView) mPopupView.findViewById(R.id.where); final boolean empty = TextUtils.isEmpty(event.location); whereView.setVisibility(empty ? View.GONE : View.VISIBLE); if (!empty) whereView.setText(event.location); mPopup.showAtLocation(this, Gravity.BOTTOM | Gravity.LEFT, mHoursWidth, 5); postDelayed(mDismissPopup, POPUP_DISMISS_DELAY); } // The following routines are called from the parent activity when certain // touch events occur. private void doDown(MotionEvent ev) { mTouchMode = TOUCH_MODE_DOWN; mViewStartX = 0; mOnFlingCalled = false; getHandler().removeCallbacks(mContinueScroll); } private void doSingleTapUp(MotionEvent ev) { if (!mHandleActionUp) { return; } int x = (int) ev.getX(); int y = (int) ev.getY(); int selectedDay = mSelectionDay; int selectedHour = mSelectionHour; boolean validPosition = setSelectionFromPosition(x, y); if (!validPosition) { // return if the touch wasn't on an area of concern return; } mSelectionMode = SELECTION_SELECTED; invalidate(); if (mSelectedEvent != null) { // If the tap is on an event, launch the "View event" view mController.sendEventRelatedEvent(this, EventType.VIEW_EVENT, mSelectedEvent.id, mSelectedEvent.startMillis, mSelectedEvent.endMillis, (int) ev.getRawX(), (int) ev.getRawY()); } else if (selectedDay == mSelectionDay && selectedHour == mSelectionHour) { // If the tap is on an already selected hour slot, then create a new // event mController.sendEventRelatedEvent(this, EventType.CREATE_EVENT, -1, getSelectedTimeInMillis(), 0, (int) ev.getRawX(), (int) ev.getRawY()); } else { Time startTime = new Time(mBaseDate); startTime.setJulianDay(mSelectionDay); startTime.hour = mSelectionHour; startTime.normalize(true /* ignore isDst */); Time endTime = new Time(startTime); endTime.hour++; mController.sendEvent(this, EventType.GO_TO, startTime, endTime, -1, ViewType.CURRENT); } } private void doLongPress(MotionEvent ev) { // Scale gesture in progress if (mStartingSpanY != 0) { return; } int x = (int) ev.getX(); int y = (int) ev.getY(); boolean validPosition = setSelectionFromPosition(x, y); if (!validPosition) { // return if the touch wasn't on an area of concern return; } mSelectionMode = SELECTION_LONGPRESS; invalidate(); performLongClick(); } private void doScroll(MotionEvent e1, MotionEvent e2, float deltaX, float deltaY) { // Use the distance from the current point to the initial touch instead // of deltaX and deltaY to avoid accumulating floating-point rounding // errors. Also, we don't need floats, we can use ints. int distanceX = (int) e1.getX() - (int) e2.getX(); int distanceY = (int) e1.getY() - (int) e2.getY(); // If we haven't figured out the predominant scroll direction yet, // then do it now. if (mTouchMode == TOUCH_MODE_DOWN) { int absDistanceX = Math.abs(distanceX); int absDistanceY = Math.abs(distanceY); mScrollStartY = mViewStartY; mPreviousDirection = 0; // If the x distance is at least twice the y distance, then lock // the scroll horizontally. Otherwise scroll vertically. if (absDistanceX >= 2 * absDistanceY) { mTouchMode = TOUCH_MODE_HSCROLL; mViewStartX = distanceX; initNextView(-mViewStartX); } else { mTouchMode = TOUCH_MODE_VSCROLL; } } else if ((mTouchMode & TOUCH_MODE_HSCROLL) != 0) { // We are already scrolling horizontally, so check if we // changed the direction of scrolling so that the other week // is now visible. mViewStartX = distanceX; if (distanceX != 0) { int direction = (distanceX > 0) ? 1 : -1; if (direction != mPreviousDirection) { // The user has switched the direction of scrolling // so re-init the next view initNextView(-mViewStartX); mPreviousDirection = direction; } } } if ((mTouchMode & TOUCH_MODE_VSCROLL) != 0) { mViewStartY = mScrollStartY + distanceY; if (mViewStartY < 0) { mViewStartY = 0; } else if (mViewStartY > mMaxViewStartY) { mViewStartY = mMaxViewStartY; } computeFirstHour(); } mScrolling = true; mSelectionMode = SELECTION_HIDDEN; invalidate(); } private void doFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { mTouchMode = TOUCH_MODE_INITIAL_STATE; mSelectionMode = SELECTION_HIDDEN; mOnFlingCalled = true; int deltaX = (int) e2.getX() - (int) e1.getX(); int distanceX = Math.abs(deltaX); int deltaY = (int) e2.getY() - (int) e1.getY(); int distanceY = Math.abs(deltaY); if (DEBUG) Log.d(TAG, "doFling: distanceX " + distanceX + ", HORIZONTAL_FLING_THRESHOLD " + HORIZONTAL_FLING_THRESHOLD); if ((distanceX >= HORIZONTAL_FLING_THRESHOLD) && (distanceX > distanceY)) { // Horizontal fling. // initNextView(deltaX); switchViews(deltaX < 0, mViewStartX, mViewWidth); mViewStartX = 0; return; } // Vertical fling. mViewStartX = 0; // Continue scrolling vertically mContinueScroll.init((int) velocityY / 20); post(mContinueScroll); } private boolean initNextView(int deltaX) { // Change the view to the previous day or week DayView view = (DayView) mViewSwitcher.getNextView(); Time date = view.mBaseDate; date.set(mBaseDate); boolean switchForward; if (deltaX > 0) { date.monthDay -= mNumDays; view.mSelectionDay = mSelectionDay - mNumDays; switchForward = false; } else { date.monthDay += mNumDays; view.mSelectionDay = mSelectionDay + mNumDays; switchForward = true; } date.normalize(true /* ignore isDst */); initView(view); view.layout(getLeft(), getTop(), getRight(), getBottom()); view.reloadEvents(); return switchForward; } // ScaleGestureDetector.OnScaleGestureListener public boolean onScaleBegin(ScaleGestureDetector detector) { mHandleActionUp = false; float gestureCenterInPixels = detector.getFocusY() - DAY_HEADER_HEIGHT - mAllDayHeight; mGestureCenterHour = (mViewStartY + gestureCenterInPixels) / (mCellHeight + DAY_GAP); mStartingSpanY = Math.max(MIN_Y_SPAN, Math.abs(detector.getCurrentSpanY())); mCellHeightBeforeScaleGesture = mCellHeight; if (DEBUG) { float ViewStartHour = mViewStartY / (float) (mCellHeight + DAY_GAP); Log.d(TAG, "mGestureCenterHour:" + mGestureCenterHour + "\tViewStartHour: " + ViewStartHour + "\tmViewStartY:" + mViewStartY + "\tmCellHeight:" + mCellHeight); } return true; } // ScaleGestureDetector.OnScaleGestureListener public boolean onScale(ScaleGestureDetector detector) { float spanY = Math.abs(detector.getCurrentSpanY()); mCellHeight = (int) (mCellHeightBeforeScaleGesture * spanY / mStartingSpanY); if (mCellHeight < mMinCellHeight) { // If mStartingSpanY is too small, even a small increase in the // gesture can bump the mCellHeight beyond MAX_CELL_HEIGHT mStartingSpanY = Math.max(MIN_Y_SPAN, spanY); mCellHeight = mMinCellHeight; mCellHeightBeforeScaleGesture = mMinCellHeight; } else if (mCellHeight > MAX_CELL_HEIGHT) { mStartingSpanY = spanY; mCellHeight = MAX_CELL_HEIGHT; mCellHeightBeforeScaleGesture = MAX_CELL_HEIGHT; } int gestureCenterInPixels = (int) detector.getFocusY() - DAY_HEADER_HEIGHT - mAllDayHeight; mViewStartY = (int) (mGestureCenterHour * (mCellHeight + DAY_GAP)) - gestureCenterInPixels; mMaxViewStartY = HOUR_GAP + 24 * (mCellHeight + HOUR_GAP) - mGridAreaHeight; if (DEBUG) { float ViewStartHour = mViewStartY / (float) (mCellHeight + DAY_GAP); Log.d(TAG, " mGestureCenterHour:" + mGestureCenterHour + "\tViewStartHour: " + ViewStartHour + "\tmViewStartY:" + mViewStartY + "\tmCellHeight:" + mCellHeight + " SpanY:" + detector.getCurrentSpanY()); } if (mViewStartY < 0) { mViewStartY = 0; mGestureCenterHour = (mViewStartY + gestureCenterInPixels) / (float) (mCellHeight + DAY_GAP); } else if (mViewStartY > mMaxViewStartY) { mViewStartY = mMaxViewStartY; mGestureCenterHour = (mViewStartY + gestureCenterInPixels) / (float) (mCellHeight + DAY_GAP); } computeFirstHour(); mRemeasure = true; invalidate(); return true; } // ScaleGestureDetector.OnScaleGestureListener public void onScaleEnd(ScaleGestureDetector detector) { mStartingSpanY = 0; } @Override public boolean onTouchEvent(MotionEvent ev) { int action = ev.getAction(); if ((mTouchMode & TOUCH_MODE_HSCROLL) == 0) { mScaleGestureDetector.onTouchEvent(ev); if (mScaleGestureDetector.isInProgress()) { return true; } } switch (action) { case MotionEvent.ACTION_DOWN: if (DEBUG) Log.e(TAG, "ACTION_DOWN"); mHandleActionUp = true; mGestureDetector.onTouchEvent(ev); return true; case MotionEvent.ACTION_MOVE: if (DEBUG) Log.e(TAG, "ACTION_MOVE"); mGestureDetector.onTouchEvent(ev); return true; case MotionEvent.ACTION_UP: if (DEBUG) Log.e(TAG, "ACTION_UP " + mHandleActionUp); mGestureDetector.onTouchEvent(ev); if (!mHandleActionUp) { mHandleActionUp = true; return true; } if (mOnFlingCalled) { return true; } if ((mTouchMode & TOUCH_MODE_HSCROLL) != 0) { mTouchMode = TOUCH_MODE_INITIAL_STATE; if (Math.abs(mViewStartX) > mHorizontalSnapBackThreshold) { // The user has gone beyond the threshold so switch views if (DEBUG) Log.d(TAG, "- horizontal scroll: switch views"); switchViews(mViewStartX > 0, mViewStartX, mViewWidth); mViewStartX = 0; return true; } else { // Not beyond the threshold so invalidate which will cause // the view to snap back. Also call recalc() to ensure // that we have the correct starting date and title. if (DEBUG) Log.d(TAG, "- horizontal scroll: snap back"); recalc(); invalidate(); mViewStartX = 0; } } // If we were scrolling, then reset the selected hour so that it // is visible. if (mScrolling) { mScrolling = false; resetSelectedHour(); invalidate(); } return true; // This case isn't expected to happen. case MotionEvent.ACTION_CANCEL: if (DEBUG) Log.e(TAG, "ACTION_CANCEL"); mGestureDetector.onTouchEvent(ev); mScrolling = false; resetSelectedHour(); return true; default: if (DEBUG) Log.e(TAG, "Not MotionEvent"); if (mGestureDetector.onTouchEvent(ev)) { return true; } return super.onTouchEvent(ev); } } public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) { MenuItem item; // If the trackball is held down, then the context menu pops up and // we never get onKeyUp() for the long-press. So check for it here // and change the selection to the long-press state. if (mSelectionMode != SELECTION_LONGPRESS) { mSelectionMode = SELECTION_LONGPRESS; invalidate(); } final long startMillis = getSelectedTimeInMillis(); int flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_CAP_NOON_MIDNIGHT | DateUtils.FORMAT_SHOW_WEEKDAY; final String title = Utils.formatDateRange(mContext, startMillis, startMillis, flags); menu.setHeaderTitle(title); int numSelectedEvents = mSelectedEvents.size(); if (mNumDays == 1) { // Day view. // If there is a selected event, then allow it to be viewed and // edited. if (numSelectedEvents >= 1) { item = menu.add(0, MENU_EVENT_VIEW, 0, R.string.event_view); item.setOnMenuItemClickListener(mContextMenuHandler); item.setIcon(android.R.drawable.ic_menu_info_details); int accessLevel = getEventAccessLevel(mContext, mSelectedEvent); if (accessLevel == ACCESS_LEVEL_EDIT) { item = menu.add(0, MENU_EVENT_EDIT, 0, R.string.event_edit); item.setOnMenuItemClickListener(mContextMenuHandler); item.setIcon(android.R.drawable.ic_menu_edit); item.setAlphabeticShortcut('e'); } if (accessLevel >= ACCESS_LEVEL_DELETE) { item = menu.add(0, MENU_EVENT_DELETE, 0, R.string.event_delete); item.setOnMenuItemClickListener(mContextMenuHandler); item.setIcon(android.R.drawable.ic_menu_delete); } item = menu.add(0, MENU_EVENT_CREATE, 0, R.string.event_create); item.setOnMenuItemClickListener(mContextMenuHandler); item.setIcon(android.R.drawable.ic_menu_add); item.setAlphabeticShortcut('n'); } else { // Otherwise, if the user long-pressed on a blank hour, allow // them to create an event. They can also do this by tapping. item = menu.add(0, MENU_EVENT_CREATE, 0, R.string.event_create); item.setOnMenuItemClickListener(mContextMenuHandler); item.setIcon(android.R.drawable.ic_menu_add); item.setAlphabeticShortcut('n'); } } else { // Week view. // If there is a selected event, then allow it to be viewed and // edited. if (numSelectedEvents >= 1) { item = menu.add(0, MENU_EVENT_VIEW, 0, R.string.event_view); item.setOnMenuItemClickListener(mContextMenuHandler); item.setIcon(android.R.drawable.ic_menu_info_details); int accessLevel = getEventAccessLevel(mContext, mSelectedEvent); if (accessLevel == ACCESS_LEVEL_EDIT) { item = menu.add(0, MENU_EVENT_EDIT, 0, R.string.event_edit); item.setOnMenuItemClickListener(mContextMenuHandler); item.setIcon(android.R.drawable.ic_menu_edit); item.setAlphabeticShortcut('e'); } if (accessLevel >= ACCESS_LEVEL_DELETE) { item = menu.add(0, MENU_EVENT_DELETE, 0, R.string.event_delete); item.setOnMenuItemClickListener(mContextMenuHandler); item.setIcon(android.R.drawable.ic_menu_delete); } } item = menu.add(0, MENU_EVENT_CREATE, 0, R.string.event_create); item.setOnMenuItemClickListener(mContextMenuHandler); item.setIcon(android.R.drawable.ic_menu_add); item.setAlphabeticShortcut('n'); item = menu.add(0, MENU_DAY, 0, R.string.show_day_view); item.setOnMenuItemClickListener(mContextMenuHandler); item.setIcon(android.R.drawable.ic_menu_day); item.setAlphabeticShortcut('d'); } mPopup.dismiss(); } private class ContextMenuHandler implements MenuItem.OnMenuItemClickListener { public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case MENU_EVENT_VIEW: { if (mSelectedEvent != null) { mController.sendEventRelatedEvent(this, EventType.VIEW_EVENT_DETAILS, mSelectedEvent.id, mSelectedEvent.startMillis, mSelectedEvent.endMillis, 0, 0); } break; } case MENU_EVENT_EDIT: { if (mSelectedEvent != null) { mController.sendEventRelatedEvent(this, EventType.EDIT_EVENT, mSelectedEvent.id, mSelectedEvent.startMillis, mSelectedEvent.endMillis, 0, 0); } break; } case MENU_DAY: { mController.sendEvent(this, EventType.GO_TO, getSelectedTime(), null, -1, ViewType.DAY); break; } case MENU_AGENDA: { mController.sendEvent(this, EventType.GO_TO, getSelectedTime(), null, -1, ViewType.AGENDA); break; } case MENU_EVENT_CREATE: { long startMillis = getSelectedTimeInMillis(); long endMillis = startMillis + DateUtils.HOUR_IN_MILLIS; mController.sendEventRelatedEvent(this, EventType.CREATE_EVENT, -1, startMillis, endMillis, 0, 0); break; } case MENU_EVENT_DELETE: { if (mSelectedEvent != null) { Event selectedEvent = mSelectedEvent; long begin = selectedEvent.startMillis; long end = selectedEvent.endMillis; long id = selectedEvent.id; mController.sendEventRelatedEvent(this, EventType.DELETE_EVENT, id, begin, end, 0, 0); } break; } default: { return false; } } return true; } } private static int getEventAccessLevel(Context context, Event e) { ContentResolver cr = context.getContentResolver(); int visibility = Calendars.NO_ACCESS; // Get the calendar id for this event Cursor cursor = cr.query(ContentUris.withAppendedId(Events.CONTENT_URI, e.id), new String[] { Events.CALENDAR_ID }, null /* selection */, null /* selectionArgs */, null /* sort */); if (cursor == null) { return ACCESS_LEVEL_NONE; } if (cursor.getCount() == 0) { cursor.close(); return ACCESS_LEVEL_NONE; } cursor.moveToFirst(); long calId = cursor.getLong(0); cursor.close(); Uri uri = Calendars.CONTENT_URI; String where = String.format(CALENDARS_WHERE, calId); cursor = cr.query(uri, CALENDARS_PROJECTION, where, null, null); String calendarOwnerAccount = null; if (cursor != null) { cursor.moveToFirst(); visibility = cursor.getInt(CALENDARS_INDEX_ACCESS_LEVEL); calendarOwnerAccount = cursor.getString(CALENDARS_INDEX_OWNER_ACCOUNT); cursor.close(); } if (visibility < Calendars.CONTRIBUTOR_ACCESS) { return ACCESS_LEVEL_NONE; } if (e.guestsCanModify) { return ACCESS_LEVEL_EDIT; } if (!TextUtils.isEmpty(calendarOwnerAccount) && calendarOwnerAccount.equalsIgnoreCase(e.organizer)) { return ACCESS_LEVEL_EDIT; } return ACCESS_LEVEL_DELETE; } /** * Sets mSelectionDay and mSelectionHour based on the (x,y) touch position. * If the touch position is not within the displayed grid, then this * method returns false. * * @param x the x position of the touch * @param y the y position of the touch * @return true if the touch position is valid */ private boolean setSelectionFromPosition(int x, int y) { if (x < mHoursWidth) { return false; } int day = (x - mHoursWidth) / (mCellWidth + DAY_GAP); if (day >= mNumDays) { day = mNumDays - 1; } day += mFirstJulianDay; int hour; if (y < mFirstCell + mFirstHourOffset) { mSelectionAllDay = true; } else { hour = (y - mFirstCell - mFirstHourOffset) / (mCellHeight + HOUR_GAP); hour += mFirstHour; mSelectionHour = hour; mSelectionAllDay = false; } mSelectionDay = day; findSelectedEvent(x, y); // Log.i("Cal", "setSelectionFromPosition( " + x + ", " + y + " ) day: " + day // + " hour: " + hour // + " mFirstCell: " + mFirstCell + " mFirstHourOffset: " + mFirstHourOffset); // if (mSelectedEvent != null) { // Log.i("Cal", " num events: " + mSelectedEvents.size() + " event: " + mSelectedEvent.title); // for (Event ev : mSelectedEvents) { // int flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL // | DateUtils.FORMAT_CAP_NOON_MIDNIGHT; // String timeRange = formatDateRange(mContext, // ev.startMillis, ev.endMillis, flags); // // Log.i("Cal", " " + timeRange + " " + ev.title); // } // } return true; } private void findSelectedEvent(int x, int y) { int date = mSelectionDay; int cellWidth = mCellWidth; final ArrayList<Event> events = mEvents; int numEvents = events.size(); int left = mHoursWidth + (mSelectionDay - mFirstJulianDay) * (cellWidth + DAY_GAP); int top = 0; mSelectedEvent = null; mSelectedEvents.clear(); if (mSelectionAllDay) { float yDistance; float minYdistance = 10000.0f; // any large number Event closestEvent = null; float drawHeight = mAllDayHeight; int yOffset = DAY_HEADER_HEIGHT + ALLDAY_TOP_MARGIN; for (int i = 0; i < numEvents; i++) { Event event = events.get(i); if (!event.allDay) { continue; } if (event.startDay <= mSelectionDay && event.endDay >= mSelectionDay) { float numRectangles = event.getMaxColumns(); float height = drawHeight / numRectangles; if (height > MAX_HEIGHT_OF_ONE_ALLDAY_EVENT) { height = MAX_HEIGHT_OF_ONE_ALLDAY_EVENT; } float eventTop = yOffset + height * event.getColumn(); float eventBottom = eventTop + height; if (eventTop < y && eventBottom > y) { // If the touch is inside the event rectangle, then // add the event. mSelectedEvents.add(event); closestEvent = event; break; } else { // Find the closest event if (eventTop >= y) { yDistance = eventTop - y; } else { yDistance = y - eventBottom; } if (yDistance < minYdistance) { minYdistance = yDistance; closestEvent = event; } } } } mSelectedEvent = closestEvent; return; } // Adjust y for the scrollable bitmap y += mViewStartY - mFirstCell; // Use a region around (x,y) for the selection region Rect region = mRect; region.left = x - 10; region.right = x + 10; region.top = y - 10; region.bottom = y + 10; EventGeometry geometry = mEventGeometry; for (int i = 0; i < numEvents; i++) { Event event = events.get(i); // Compute the event rectangle. if (!geometry.computeEventRect(date, left, top, cellWidth, event)) { continue; } // If the event intersects the selection region, then add it to // mSelectedEvents. if (geometry.eventIntersectsSelection(event, region)) { mSelectedEvents.add(event); } } // If there are any events in the selected region, then assign the // closest one to mSelectedEvent. if (mSelectedEvents.size() > 0) { int len = mSelectedEvents.size(); Event closestEvent = null; float minDist = mViewWidth + mViewHeight; // some large distance for (int index = 0; index < len; index++) { Event ev = mSelectedEvents.get(index); float dist = geometry.pointToEvent(x, y, ev); if (dist < minDist) { minDist = dist; closestEvent = ev; } } mSelectedEvent = closestEvent; // Keep the selected hour and day consistent with the selected // event. They could be different if we touched on an empty hour // slot very close to an event in the previous hour slot. In // that case we will select the nearby event. int startDay = mSelectedEvent.startDay; int endDay = mSelectedEvent.endDay; if (mSelectionDay < startDay) { mSelectionDay = startDay; } else if (mSelectionDay > endDay) { mSelectionDay = endDay; } int startHour = mSelectedEvent.startTime / 60; int endHour; if (mSelectedEvent.startTime < mSelectedEvent.endTime) { endHour = (mSelectedEvent.endTime - 1) / 60; } else { endHour = mSelectedEvent.endTime / 60; } if (mSelectionHour < startHour) { mSelectionHour = startHour; } else if (mSelectionHour > endHour) { mSelectionHour = endHour; } } } // Encapsulates the code to continue the scrolling after the // finger is lifted. Instead of stopping the scroll immediately, // the scroll continues to "free spin" and gradually slows down. private class ContinueScroll implements Runnable { int mSignDeltaY; int mAbsDeltaY; float mFloatDeltaY; long mFreeSpinTime; private static final float FRICTION_COEF = 0.7F; private static final long FREE_SPIN_MILLIS = 180; private static final int MAX_DELTA = 60; private static final int SCROLL_REPEAT_INTERVAL = 30; public void init(int deltaY) { mSignDeltaY = 0; if (deltaY > 0) { mSignDeltaY = 1; } else if (deltaY < 0) { mSignDeltaY = -1; } mAbsDeltaY = Math.abs(deltaY); // Limit the maximum speed if (mAbsDeltaY > MAX_DELTA) { mAbsDeltaY = MAX_DELTA; } mFloatDeltaY = mAbsDeltaY; mFreeSpinTime = System.currentTimeMillis() + FREE_SPIN_MILLIS; // Log.i("Cal", "init scroll: mAbsDeltaY: " + mAbsDeltaY // + " mViewStartY: " + mViewStartY); } public void run() { long time = System.currentTimeMillis(); // Start out with a frictionless "free spin" if (time > mFreeSpinTime) { // If the delta is small, then apply a fixed deceleration. // Otherwise if (mAbsDeltaY <= 10) { mAbsDeltaY -= 2; } else { mFloatDeltaY *= FRICTION_COEF; mAbsDeltaY = (int) mFloatDeltaY; } if (mAbsDeltaY < 0) { mAbsDeltaY = 0; } } if (mSignDeltaY == 1) { mViewStartY -= mAbsDeltaY; } else { mViewStartY += mAbsDeltaY; } // Log.i("Cal", " scroll: mAbsDeltaY: " + mAbsDeltaY // + " mViewStartY: " + mViewStartY); if (mViewStartY < 0) { mViewStartY = 0; mAbsDeltaY = 0; } else if (mViewStartY > mMaxViewStartY) { mViewStartY = mMaxViewStartY; mAbsDeltaY = 0; } computeFirstHour(); if (mAbsDeltaY > 0) { postDelayed(this, SCROLL_REPEAT_INTERVAL); } else { // Done scrolling. mScrolling = false; resetSelectedHour(); } invalidate(); } } /** * Cleanup the pop-up and timers. */ public void cleanup() { // Protect against null-pointer exceptions if (mPopup != null) { mPopup.dismiss(); } mLastPopupEventID = INVALID_EVENT_ID; Handler handler = getHandler(); if (handler != null) { handler.removeCallbacks(mDismissPopup); handler.removeCallbacks(mUpdateCurrentTime); } Utils.setSharedPreference(mContext, GeneralPreferences.KEY_DEFAULT_CELL_HEIGHT, mCellHeight); // Turn off redraw mRemeasure = false; } /** * Restart the update timer */ public void restartCurrentTimeUpdates() { post(mUpdateCurrentTime); } @Override protected void onDetachedFromWindow() { cleanup(); super.onDetachedFromWindow(); } class DismissPopup implements Runnable { public void run() { // Protect against null-pointer exceptions if (mPopup != null) { mPopup.dismiss(); } } } class UpdateCurrentTime implements Runnable { public void run() { long currentTime = System.currentTimeMillis(); mCurrentTime.set(currentTime); //% causes update to occur on 5 minute marks (11:10, 11:15, 11:20, etc.) postDelayed(mUpdateCurrentTime, UPDATE_CURRENT_TIME_DELAY - (currentTime % UPDATE_CURRENT_TIME_DELAY)); mTodayJulianDay = Time.getJulianDay(currentTime, mCurrentTime.gmtoff); invalidate(); } } class CalendarGestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapUp(MotionEvent ev) { DayView.this.doSingleTapUp(ev); return true; } @Override public void onLongPress(MotionEvent ev) { DayView.this.doLongPress(ev); } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { DayView.this.doScroll(e1, e2, distanceX, distanceY); return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { DayView.this.doFling(e1, e2, velocityX, velocityY); return true; } @Override public boolean onDown(MotionEvent ev) { DayView.this.doDown(ev); return true; } } }
false
false
null
null
diff --git a/src/main/java/com/wolvereness/overmapped/MembersSubRoutine.java b/src/main/java/com/wolvereness/overmapped/MembersSubRoutine.java index 901ca32..0c20f0f 100644 --- a/src/main/java/com/wolvereness/overmapped/MembersSubRoutine.java +++ b/src/main/java/com/wolvereness/overmapped/MembersSubRoutine.java @@ -1,595 +1,595 @@ /* * This file is part of OverMapped. * * OverMapped is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OverMapped is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with OverMapped. If not, see <http://www.gnu.org/licenses/>. */ package com.wolvereness.overmapped; import static com.google.common.collect.Lists.*; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.maven.plugin.MojoFailureException; import org.objectweb.asm.commons.Remapper; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.wolvereness.overmapped.asm.ByteClass; import com.wolvereness.overmapped.asm.Signature; import com.wolvereness.overmapped.asm.Signature.MutableSignature; class MembersSubRoutine extends SubRoutine { static class Store { String newName; String oldName; String description; String originalDescription; final Set<String> searchCache; final Set<String> parents; Map<String, Signature> classFieldsCache; final OverMapped instance; Store( final Set<String> searchCache, final Set<String> parents, final OverMapped instance ) { this.searchCache = searchCache; this.parents = parents; this.instance = instance; } } MembersSubRoutine() { super("members"); } @Override public void invoke( final OverMapped instance, final Map<String, ByteClass> classes, final Multimap<String, String> depends, final Multimap<String, String> rdepends, final BiMap<String, String> nameMaps, final BiMap<String, String> inverseNameMaps, final BiMap<Signature, Signature> signatureMaps, final BiMap<Signature, Signature> inverseSignatureMaps, final Remapper inverseMapper, final MutableSignature mutableSignature, final Set<String> searchCache, final Map<Signature, Integer> flags, final Map<?,?> map ) throws ClassCastException, NullPointerException, MojoFailureException { final Object memberMaps = map.get(tag); if (!(memberMaps instanceof Map)) return; final Store store = new Store( searchCache, instance.isFindParents() ? new HashSet<String>() : null, instance ); for (final Map.Entry<?, ?> memberMap : ((Map<?,?>) memberMaps).entrySet()) { final Map<?,?> maps = asType( memberMap.getValue(), "`%4$s' points to a %2$s `%1$s', expected a %5$s, in `%3$s'", false, memberMaps, memberMap, Map.class ); if (memberMap.getKey() instanceof Collection<?> && ((Collection<?>) memberMap.getKey()).size() > 1) { final Iterable<String> classNames; { final ImmutableCollection.Builder<String> containingClassNames = ImmutableList.builder(); for (final Object clazz : (Collection<?>) memberMap.getKey()) { final String unresolvedClassName = asType( clazz, "`%4$s' contains a %2$s `%1$s', expected a %5$s, from `%3$s'", false, memberMaps, memberMap.getKey(), String.class ); final String className = inverseNameMaps.get(unresolvedClassName); if (className == null) { instance.missingAction.actMemberClass(instance.getLog(), unresolvedClassName, memberMap.getKey(), inverseNameMaps); continue; } containingClassNames.add(className); } classNames = containingClassNames.build(); } for (final Map.Entry<?, ?> entry : maps.entrySet()) { parseMapping( store, inverseMapper, mutableSignature, maps, entry, false ); final String newName = store.newName, oldName = store.oldName, description = store.description, originalDescription = store.originalDescription; if (!mutableSignature.update("", "", description).isMethod()) throw new MojoFailureException(String.format( "Malformed mapping %s for %s; can only map methods.", entry, memberMap )); for (final String className : classNames) { updateMember(store, signatureMaps, inverseSignatureMaps, mutableSignature, oldName, newName, description, className, nameMaps, originalDescription, nameMaps.get(className)); if (mutableSignature.isMethod() && !mutableSignature.isConstructor()) { final Set<String> parents = store.parents; if (parents != null) { parents.addAll(depends.get(className)); } for (final String inherited : rdepends.get(className)) { if (!updateMember(store, signatureMaps, inverseSignatureMaps, mutableSignature, oldName, newName, description, inherited, nameMaps, originalDescription, nameMaps.get(inherited))) continue; if (parents != null) { parents.addAll(depends.get(inherited)); } } } } performParentChecks(store, nameMaps, inverseSignatureMaps, mutableSignature, classNames, newName, oldName, description, originalDescription); store.searchCache.clear(); } continue; } if (memberMap.getKey() instanceof Collection<?> && ((Collection<?>) memberMap.getKey()).size() < 1) throw new MojoFailureException(String.format( "Malformed mapping %s -> %s", memberMap.getKey(), maps )); final String unresolvedClassName = asType( memberMap.getKey() instanceof Collection<?> ? ((Collection<?>) memberMap.getKey()).iterator().next() : memberMap.getKey(), "`%4$s' points from a %2$s `%1$s', expected a %5$s, in `%3$s'", false, memberMaps, memberMap, String.class ); final String className = inverseNameMaps.get(unresolvedClassName); if (className == null) { instance.missingAction.actMemberClass(instance.getLog(), unresolvedClassName, memberMap.getKey(), inverseNameMaps); continue; } for (final Map.Entry<?, ?> entry : maps.entrySet()) { processSingleClassMappings( store, classes, depends, rdepends, nameMaps, signatureMaps, inverseSignatureMaps, inverseMapper, mutableSignature, maps, className, unresolvedClassName, entry ); } } } private static void processSingleClassMappings( final Store store, final Map<String, ByteClass> classes, final Multimap<String, String> depends, final Multimap<String, String> rdepends, final BiMap<String, String> nameMaps, final BiMap<Signature, Signature> signatureMaps, final BiMap<Signature, Signature> inverseSignatureMaps, final Remapper inverseMapper, final MutableSignature mutableSignature, final Map<?, ?> maps, final String className, final String originalClassName, final Map.Entry<?, ?> entry ) throws MojoFailureException { if (entry.getValue() instanceof String) { parseMapping(store, inverseMapper, mutableSignature, maps, entry, true); final String newName = store.newName, oldName = store.oldName, description = store.description, originalDescription = store.originalDescription; if (description == null) { final Map<String, Signature> classFieldsCache = buildFieldsCache(store, classes.get(className).getLocalSignatures(), signatureMaps); final Signature signature = getClassField(store, classFieldsCache, oldName, originalClassName); if (signature == null) return; attemptFieldMap(signatureMaps, signature, mutableSignature, oldName, newName, className); return; } updateMember(store, signatureMaps, inverseSignatureMaps, mutableSignature, oldName, newName, description, className, nameMaps, originalDescription, originalClassName); if (mutableSignature.isMethod() && !mutableSignature.isConstructor()) { final Set<String> parents = store.parents; if (parents != null) { parents.addAll(depends.get(className)); } for (final String inherited : rdepends.get(className)) { if (!updateMember(store, signatureMaps, inverseSignatureMaps, mutableSignature, oldName, newName, description, inherited, nameMaps, originalDescription, nameMaps.get(inherited))) continue; if (parents != null) { parents.addAll(depends.get(inherited)); } } performParentChecks(store, nameMaps, inverseSignatureMaps, mutableSignature, className, newName, oldName, description, originalDescription); } store.searchCache.clear(); } else if (entry.getValue() instanceof Iterable) { final Map<String, Signature> classFieldsCache = buildFieldsCache(store, classes.get(className).getLocalSignatures(), signatureMaps); final Iterable<?> names = (Iterable<?>) entry.getValue(); final List<?> oldNames; final int start; { final Map<?, ?> entryMap = asType( entry.getKey(), "`%4$s' points from a %2$s `%1$s', expected a %5$s, in `%3$s'", false, maps, entry, Map.class ); if (entryMap.size() != 1) throw new MojoFailureException(String.format( "Malformed mapping `%s' to `%s' in `%s'", entryMap, entry.getValue(), maps )); final Map.Entry<?, ?> pair = entryMap.entrySet().iterator().next(); oldNames = asType( pair.getKey(), "`%4$s' points from a %2$s `%1$s', expected a %5$s, in `%3$s'", false, entry, pair, List.class ); final String startToken = asType( pair.getValue(), "`%4$s' points to a %2$s `%1$s', expected a %5$s, in `%3$s'", false, entry, pair, String.class ); start = oldNames.indexOf(startToken); if (start == -1) throw new MojoFailureException(String.format( "Cannot find value `%s' in `%s'", startToken, oldNames )); } int i = start; for (final Object name : names) { if (i >= oldNames.size()) throw new MojoFailureException(String.format( "Insuffient sequence length %n in `%s' for `%s' at `%s'", i, oldNames, name, names, name )); final String newName = asType( name, - "`%4$s' contains a %2$2 `%1$s', expected a %5$s, in `%3$s'", + "`%4$s' contains a %2$s `%1$s', expected a %5$s, in `%3$s'", false, entry, names, String.class ); final String oldName = asType( oldNames.get(i++), - "`%4$s' contains a %2$2 `%1$s', expected a %5$s, in `%3$s'", + "`%4$s' contains a %2$s `%1$s', expected a %5$s, in `%3$s'", false, entry, oldNames, String.class ); final Signature signature = getClassField(store, classFieldsCache, oldName, originalClassName); if (signature == null) { continue; } attemptFieldMap(signatureMaps, signature, mutableSignature, oldName, newName, className); updateFieldCacheEntry(classFieldsCache, signature, newName); } } else throw new MojoFailureException(String.format( "Malformed mapping `%s' from `%s' in `%s'", entry.getValue(), entry.getKey(), maps )); } private static void updateFieldCacheEntry( final Map<String, Signature> cache, final Signature signature, final String newName ) { final int size = cache.size(); if (cache.put(newName, signature) != null || size == cache.size()) { // (put() != null) is redundant to (size==cache.size()), but who cares? cache.put(newName, null); } } private static Signature getClassField( final Store store, final Map<String, Signature> classFieldsCache, final String oldName, final String originalClassName ) throws MojoFailureException { final int size = classFieldsCache.size(); final Signature signature = classFieldsCache.remove(oldName); if (signature != null) return signature; if (size != classFieldsCache.size()) throw new MojoFailureException(String.format( "Ambiguous field name %s", oldName )); store.instance.missingAction.actField(store.instance.getLog(), classFieldsCache, oldName, originalClassName); return null; } private static void parseMapping( final Store store, final Remapper inverseMapper, final MutableSignature mutableSignature, final Map<?, ?> maps, final Map.Entry<?, ?> entry, boolean nullDescription ) throws MojoFailureException { store.newName = asType( entry.getValue(), "`%4$s' points to a %2$s `%1$s', expected a %5$s, in `%3$s'", false, maps, entry, String.class ); if (entry.getKey() instanceof Map && ((Map<?, ?>) entry.getKey()).size() == 1) { final Map.Entry<?, ?> mapKey = ((Map<?, ?>) entry.getKey()).entrySet().iterator().next(); store.oldName = asType( mapKey.getKey(), "`%4$s' points from a %2$s `%1$s', expected a %5$s, in `%3$s'", false, entry.getKey(), mapKey, String.class ); final String unresolvedDescription = store.originalDescription = asType( mapKey.getValue(), "`%4$s' points to a %2$s `%1$s', expected a %5$s, in `%3$s'", nullDescription, entry.getKey(), mapKey, String.class ); store.description = parseDescription(inverseMapper, mutableSignature, unresolvedDescription); } else if (entry.getKey() instanceof String) { final String fullToken = (String) entry.getKey(); final int split = fullToken.indexOf(' '); final String unresolvedDescription; if (nullDescription & (nullDescription = (split == -1))) { unresolvedDescription = null; store.oldName = fullToken; } else if (nullDescription || split != fullToken.lastIndexOf(' ')) throw new MojoFailureException(String.format( "Malformed mapping %s", fullToken )); else { unresolvedDescription = store.originalDescription = fullToken.substring(split + 1, fullToken.length()); store.oldName = fullToken.substring(0, split); } store.description = parseDescription(inverseMapper, mutableSignature, unresolvedDescription); } else throw new MojoFailureException(String.format( "Malformed mapping `%s' to `%s' in `%s'", entry.getKey(), store.newName, maps )); } private static void performParentChecks( final Store store, final BiMap<String, String> nameMaps, final BiMap<Signature, Signature> inverseSignatureMaps, final MutableSignature mutableSignature, Object className_s, final String newName, final String oldName, final String description, final String originalDescription ) { final Set<String> parents = store.parents; if (parents != null) { parents.removeAll(store.searchCache); if (parents.isEmpty()) return; if (className_s instanceof String) { className_s = nameMaps.get(className_s); } else { final Collection<String> originalClassNames = newArrayList(); for (final Object className : (Iterable<?>) className_s) { originalClassNames.add(nameMaps.get(className)); } className_s = originalClassNames; } for (final String parent : parents) { if (inverseSignatureMaps.containsKey(mutableSignature.update(parent, oldName, description))) { store.instance.getLog().info(String.format( "Expected parent method mapping for `%s'->`%s' from mappings in %s", mutableSignature.update(nameMaps.get(parent), oldName, originalDescription), mutableSignature.forElementName(newName), className_s )); } } parents.clear(); } } private static void attemptFieldMap( final BiMap<Signature, Signature> signatureMaps, final Signature signature, final MutableSignature mutableSignature, final String oldName, final String newName, final String className ) throws MojoFailureException { try { signatureMaps.put(signature, signature.forElementName(newName)); } catch (final IllegalArgumentException ex) { final MojoFailureException mojoEx = new MojoFailureException(String.format( "Cannot map %s (currently %s) to pre-existing member %s (in class %s)", signature, mutableSignature.update(className, oldName, signature.getDescriptor()), signature.forElementName(newName), className )); mojoEx.initCause(ex); throw mojoEx; } } private static String parseDescription( final Remapper inverseMapper, final MutableSignature mutableSignature, final String unresolvedDescription ) { return unresolvedDescription != null ? mutableSignature.update("", "", unresolvedDescription).isMethod() ? inverseMapper.mapMethodDesc(unresolvedDescription) : inverseMapper.mapDesc(unresolvedDescription) : null; } private static Map<String, Signature> buildFieldsCache(final Store store, final List<Signature> localSignatures, final Map<Signature, Signature> signatures) { Map<String, Signature> classFieldsCache = store.classFieldsCache; if (classFieldsCache == null) { classFieldsCache = store.classFieldsCache = new HashMap<String, Signature>(localSignatures.size()); } else { classFieldsCache.clear(); } int size = 0; for (final Signature signature : localSignatures) { if (signature.isMethod()) { continue; } final String mappedName = signatures.get(signature).getElementName(); if ( classFieldsCache.put(mappedName, signature) != null || size == (size = classFieldsCache.size()) ) { // Remove the mapping we accidentally put in... classFieldsCache.put(mappedName, null); } } return classFieldsCache; } /** * * @return true if cache does not contain original (or similarly interpreted as attempted to update as it has not attempted to do so thus far) */ private static boolean updateMember( final Store store, final BiMap<Signature, Signature> signatureMaps, final BiMap<Signature, Signature> inverseSignatureMaps, final Signature.MutableSignature signature, final String oldName, final String newName, final String description, final String clazz, final Map<String, String> classes, final String originalDescription, final String originalClass ) throws MojoFailureException { if (!store.searchCache.add(clazz)) return false; signature.update(clazz, oldName, description); final Signature originalSignature = inverseSignatureMaps.get(signature); if (originalSignature != null) { try { signatureMaps.put(originalSignature, signature.forElementName(newName)); } catch (final IllegalArgumentException ex) { final MojoFailureException mojoEx = new MojoFailureException(String.format( "Cannot map %s (currently %s) to pre-existing member %s (in class %s)", originalSignature, signature, signature.forElementName(newName), classes.get(clazz) )); mojoEx.initCause(ex); throw mojoEx; } } else { store.instance.missingAction.actMember(store.instance.getLog(), originalClass, oldName, newName, originalDescription, inverseSignatureMaps); } return true; } }
false
false
null
null
diff --git a/nuxeo-core-schema/src/main/java/org/nuxeo/ecm/core/schema/types/CompositeTypeImpl.java b/nuxeo-core-schema/src/main/java/org/nuxeo/ecm/core/schema/types/CompositeTypeImpl.java index 558cdb222..3afe6d404 100644 --- a/nuxeo-core-schema/src/main/java/org/nuxeo/ecm/core/schema/types/CompositeTypeImpl.java +++ b/nuxeo-core-schema/src/main/java/org/nuxeo/ecm/core/schema/types/CompositeTypeImpl.java @@ -1,209 +1,213 @@ /* * Copyright (c) 2006-2012 Nuxeo SA (http://nuxeo.com/) and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Bogdan Stefanescu * Florent Guillaume */ package org.nuxeo.ecm.core.schema.types; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.nuxeo.ecm.core.schema.SchemaNames; import org.nuxeo.ecm.core.schema.TypeRef; /** * A Composite Type resolves fields for several schemas. */ public class CompositeTypeImpl extends ComplexTypeImpl implements CompositeType { private static final long serialVersionUID = 1L; /** The schemas (refs) for this composite type. */ protected final Map<String, TypeRef<Schema>> schemas = new HashMap<String, TypeRef<Schema>>(); /** The precomputed schema names. */ protected String[] schemaNames = new String[0]; /** Does some stuff need to be recomputed lazily. */ protected volatile boolean dirty; /** The lazily precomputed map of prefix to schema. */ protected volatile Map<String, Schema> prefix2schemas = Collections.emptyMap(); // also fieldsByName public CompositeTypeImpl(CompositeType superType, String schema, String name, String[] schemas) { this (superType == null ? null : superType.getRef(), schema, name, schemas); } public CompositeTypeImpl(TypeRef<? extends CompositeType> superType, String schema, String name, String[] schemas) { super(superType, schema, name); CompositeType stype = (CompositeType) this.superType.get(); if (stype != null) { for (String sname : stype.getSchemaNames()) { addSchema(sname); } } if (schemas != null) { for (String sname : schemas) { addSchema(sname); } } } @Override public final boolean hasSchemas() { return !schemas.isEmpty(); } @Override public final void addSchema(String schema) { schemas.put(schema, new TypeRef<Schema>(SchemaNames.SCHEMAS, schema)); updated(); } @Override public final void addSchema(Schema schema) { schemas.put(schema.getName(), schema.getRef()); updated(); } /** Update non-lazy stuff. The rest will be done by checkDirty. */ protected void updated() { schemaNames = schemas.keySet().toArray(new String[schemas.size()]); dirty = true; } protected void checkDirty() { // double-checked locking works because fields are volatile if (!dirty) { return; } synchronized(this) { if (!dirty) { return; } recompute(); dirty = false; } } /** Do not call this directly, go through checkDirty. */ protected void recompute() { - Map<String,Schema> prefix2schema = new HashMap<String, Schema>(); - Map<String,Field> name2field = new HashMap<String, Field>(); - List<Field> fields = new ArrayList<Field>(); + fields.clear(); + prefix2schemas = new HashMap<String, Schema>(); + fieldsByName = new HashMap<String, Field>(); for (TypeRef<Schema> ref : schemas.values()) { Schema schema = ref.get(); if (schema == null) { continue; } - prefix2schema.put(schema.getNamespace().prefix, schema); + prefix2schemas.put(schema.getNamespace().prefix, schema); for (Field field : schema.getFields()) { QName name = field.getName(); - name2field.put(name.getLocalName(), field); - name2field.put(name.getPrefixedName(), field); - fields.add(field); + fields.put(name, field); + fieldsByName.put(name.getLocalName(), field); + fieldsByName.put(name.getPrefixedName(), field); } } - prefix2schemas = prefix2schema; - fieldsByName = name2field; - fieldsCollection = Collections.unmodifiableCollection(fields); + fieldsCollection = Collections.unmodifiableCollection(fields.values()); } @Override public final Schema getSchema(String name) { TypeRef<Schema> ref = schemas.get(name); return ref == null ? null : ref.get(); } @Override public final Schema getSchemaByPrefix(String prefix) { checkDirty(); return prefix2schemas.get(prefix); } @Override public final boolean hasSchema(String name) { return schemas.containsKey(name); } @Override public final String[] getSchemaNames() { return schemaNames.clone(); } @Override public final Collection<Schema> getSchemas() { List<Schema> list = new ArrayList<Schema>(schemas.size()); for (TypeRef<Schema> ref : schemas.values()) { list.add(ref.get()); } return Collections.unmodifiableCollection(list); } @Override public final Field addField(QName name, TypeRef<? extends Type> type) { throw new UnsupportedOperationException( "Cannot add fields to a composite type since it is a composition of other complex types"); } @Override public final Field getField(String name) { checkDirty(); return fieldsByName.get(name); } @Override public final Field getField(QName name) { checkDirty(); return fieldsByName.get(name.getPrefixedName()); } @Override + public final boolean hasField(String name) { + checkDirty(); + return fieldsByName.containsKey(name); + } + + @Override public final boolean hasField(QName name) { checkDirty(); - return fieldsByName.containsKey(name.getPrefixedName()); + return fields.containsKey(name); } @Override public final Collection<Field> getFields() { checkDirty(); return fieldsCollection; } @Override public final boolean isComplexType() { return false; } @Override public final boolean isCompositeType() { return true; } @Override public final boolean validate(Object object) { return true; } @Override public TypeRef<? extends CompositeType> getRef() { return new TypeRef<CompositeType>(schema, name, this); } }
false
false
null
null
diff --git a/billrive-service/src/main/java/com/uhsarp/billrive/domain/BillSimpleEntry.java b/billrive-service/src/main/java/com/uhsarp/billrive/domain/BillSimpleEntry.java index 660ddc8..5876d38 100644 --- a/billrive-service/src/main/java/com/uhsarp/billrive/domain/BillSimpleEntry.java +++ b/billrive-service/src/main/java/com/uhsarp/billrive/domain/BillSimpleEntry.java @@ -1,132 +1,132 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.uhsarp.billrive.domain; import java.util.ArrayList; import java.util.List; import javax.persistence.*; /** * * @author uhsarp */ @Entity @Table(name="billsimpleentry") public class BillSimpleEntry implements GenericObject{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long billId; @Column(columnDefinition="TEXT") private String itemDescription;//napkin // private Long billId; // @OneToMany(fetch=FetchType.EAGER,targetEntity = SimpleUserIdAndLiableCost.class, cascade = CascadeType.ALL,mappedBy="billSimpleEntryId") // @JoinColumn(name = "billId", referencedColumnName = "billSimpleEntryId") // @Transient @OneToMany(cascade=CascadeType.ALL,mappedBy="billSimpleEntryId",fetch = FetchType.EAGER) private List<SimpleUserIdAndLiableCost> simpleUserIdAndLiableCost = new ArrayList<SimpleUserIdAndLiableCost>(); // private BillFinances iteamEntryBillFinances; //should be set not list // ArrayList<SimpleUserIdAndLiableCost> simpleUserIdAndLiableCost = new ArrayList<SimpleUserIdAndLiableCost>();//2->3, 3->3, 4->3 public BillSimpleEntry(){ } public BillSimpleEntry(Long itemDescriptionId, String itemDescription, List<SimpleUserIdAndLiableCost> userIdAndLiableCost) { this.billId = itemDescriptionId; this.itemDescription = itemDescription; this.simpleUserIdAndLiableCost = userIdAndLiableCost; } public Long getItemDescriptionId() { return billId; } public void setItemDescriptionId(Long itemDescriptionId) { this.billId = itemDescriptionId; } public String getItemDescription() { return itemDescription; } public void setItemDescription(String itemDescription) { this.itemDescription = itemDescription; } // public Long getBillFinancesId() { // return billFinancesId; // } // // public void setBillFinancesId(Long billFinancesId) { // this.billFinancesId = billFinancesId; // } // // public ArrayList<SimpleUserIdAndLiableCost> getUserIdAndLiableCost() { // return simpleUserIdAndLiableCost; // } // // public void setUserIdAndLiableCost(ArrayList<SimpleUserIdAndLiableCost> simpleUserIdAndLiableCost) { // this.simpleUserIdAndLiableCost = simpleUserIdAndLiableCost; // } // // @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="billiteamEntryLiab") // public List<SimpleUserIdAndLiableCost> getIteamEntryUserIdAndLiableCost() { // return iteamEntryUserIdAndLiableCost; // } // // public void setIteamEntryUserIdAndLiableCost( // List<SimpleUserIdAndLiableCost> iteamEntryUserIdAndLiableCost) { // this.iteamEntryUserIdAndLiableCost = iteamEntryUserIdAndLiableCost; // } // @ManyToOne(fetch=FetchType.LAZY) //BiDirectional Mapping // @JoinColumn(name="billFinanceiteamEntry_id") // public BillFinances getIteamEntryBillFinances() { // return iteamEntryBillFinances; // } // // public void setIteamEntryBillFinances(BillFinances iteamEntryBillFinances) { // this.iteamEntryBillFinances = iteamEntryBillFinances; // } - public List<SimpleUserIdAndLiableCost> getUserIdAndLiableCost() { - return simpleUserIdAndLiableCost; - } - - public void setUserIdAndLiableCost(List<SimpleUserIdAndLiableCost> userIdAndLiableCost) { - this.simpleUserIdAndLiableCost = userIdAndLiableCost; - } - - - // public Long getBillId() { // return billId; // } // // public void setBillId(Long billId) { // this.billId = billId; // } // public Long getBillId() { return billId; } public void setBillId(Long billId) { this.billId = billId; } + + public List<SimpleUserIdAndLiableCost> getSimpleUserIdAndLiableCost() { + return simpleUserIdAndLiableCost; + } + + public void setSimpleUserIdAndLiableCost(List<SimpleUserIdAndLiableCost> simpleUserIdAndLiableCost) { + this.simpleUserIdAndLiableCost = simpleUserIdAndLiableCost; + } + + }
false
false
null
null
diff --git a/src/frontend/org/voltdb/compiler/DDLCompiler.java b/src/frontend/org/voltdb/compiler/DDLCompiler.java index 8cd866092..37822fd4e 100644 --- a/src/frontend/org/voltdb/compiler/DDLCompiler.java +++ b/src/frontend/org/voltdb/compiler/DDLCompiler.java @@ -1,979 +1,980 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2012 VoltDB Inc. * * VoltDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VoltDB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.compiler; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.hsqldb_voltpatches.HSQLInterface; import org.hsqldb_voltpatches.HSQLInterface.HSQLParseException; import org.hsqldb_voltpatches.VoltXMLElement; import org.voltdb.VoltType; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.Column; import org.voltdb.catalog.ColumnRef; import org.voltdb.catalog.Constraint; import org.voltdb.catalog.Database; import org.voltdb.catalog.Index; import org.voltdb.catalog.MaterializedViewInfo; import org.voltdb.catalog.Table; import org.voltdb.compiler.VoltCompiler.VoltCompilerException; import org.voltdb.expressions.AbstractExpression; import org.voltdb.expressions.TupleValueExpression; import org.voltdb.planner.AbstractParsedStmt; import org.voltdb.planner.ParsedSelectStmt; import org.voltdb.types.ConstraintType; import org.voltdb.types.ExpressionType; import org.voltdb.types.IndexType; import org.voltdb.utils.BuildDirectoryUtils; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.Encoder; import org.voltdb.utils.VoltTypeUtil; /** * Compiles schema (SQL DDL) text files and stores the results in a given catalog. * */ public class DDLCompiler { static final int MAX_COLUMNS = 1024; static final int MAX_ROW_SIZE = 1024 * 1024 * 2; HSQLInterface m_hsql; VoltCompiler m_compiler; String m_fullDDL = ""; int m_currLineNo = 1; /// Partition descriptors parsed from DDL PARTITION or REPLICATE statements. final TablePartitionMap m_partitionMap; HashMap<String, Column> columnMap = new HashMap<String, Column>(); HashMap<String, Index> indexMap = new HashMap<String, Index>(); HashMap<Table, String> matViewMap = new HashMap<Table, String>(); private class DDLStatement { public DDLStatement() { } String statement = ""; int lineNo; } public DDLCompiler(VoltCompiler compiler, HSQLInterface hsql, TablePartitionMap partitionMap) { assert(compiler != null); assert(hsql != null); assert(partitionMap != null); this.m_hsql = hsql; this.m_compiler = compiler; this.m_partitionMap = partitionMap; } /** * Compile a DDL schema from a file on disk * @param path * @throws VoltCompiler.VoltCompilerException */ public void loadSchema(String path) throws VoltCompiler.VoltCompilerException { File inputFile = new File(path); FileReader reader = null; try { reader = new FileReader(inputFile); } catch (FileNotFoundException e) { throw m_compiler.new VoltCompilerException("Unable to open schema file for reading"); } m_currLineNo = 1; this.loadSchema(path, reader); } /** * Compile a file from an open input stream * @param path * @param reader * @throws VoltCompiler.VoltCompilerException */ public void loadSchema(String path, FileReader reader) throws VoltCompiler.VoltCompilerException { DDLStatement stmt = getNextStatement(reader, m_compiler); while (stmt != null) { // Some statements are processed by VoltDB and the rest are handled by HSQL. boolean processed = false; try { processed = processVoltDBStatement(stmt.statement); } catch (VoltCompilerException e) { // Reformat the message thrown by VoltDB DDL processing to have a line number. String msg = "VoltDB DDL Error: \"" + e.getMessage() + "\" in statement starting on lineno: " + stmt.lineNo; throw m_compiler.new VoltCompilerException(msg); } if (!processed) { try { // kind of ugly. We hex-encode each statement so we can // avoid embedded newlines so we can delimit statements // with newline. m_fullDDL += Encoder.hexEncode(stmt.statement) + "\n"; m_hsql.runDDLCommand(stmt.statement); } catch (HSQLParseException e) { String msg = "DDL Error: \"" + e.getMessage() + "\" in statement starting on lineno: " + stmt.lineNo; throw m_compiler.new VoltCompilerException(msg, stmt.lineNo); } } stmt = getNextStatement(reader, m_compiler); } try { reader.close(); } catch (IOException e) { throw m_compiler.new VoltCompilerException("Error closing schema file"); } } /** * Process a VoltDB-specific DDL statement, like PARTITION and REPLICATE. * @param statement DDL statement string * @return true if statement was handled, otherwise it should be passed to HSQL * @throws VoltCompilerException */ private boolean processVoltDBStatement(String statement) throws VoltCompilerException { if (statement == null) { return false; } // Split the statement on whitespace. For now the supported statements // don't have quoted strings or anything else more than simple tokens. String[] tokens = statement.trim().split("\\s+"); if (tokens.length == 0) { return false; } // Handle PARTITION statement. if (tokens[0].equalsIgnoreCase("PARTITION")) { // Check and strip semi-colon terminator. tokens = cleanupVoltDBDDLTerminator("PARTITION", tokens); // Validate tokens. if ( tokens.length != 6 || !tokens[1].equalsIgnoreCase("table") || !tokens[3].equalsIgnoreCase("on") || !tokens[4].equalsIgnoreCase("column")) { throw m_compiler.new VoltCompilerException(String.format( "Bad PARTITION DDL statement: \"%s\", " + "expected syntax: PARTITION TABLE <table> ON COLUMN <column>", StringUtils.join(tokens, ' '))); } m_partitionMap.put(tokens[2], tokens[5]); return true; } // Handle REPLICATE statement. else if (tokens[0].equalsIgnoreCase("REPLICATE")) { // Check and strip semi-colon terminator. tokens = cleanupVoltDBDDLTerminator("REPLICATE", tokens); // Validate tokens. if ( tokens.length != 3 || !tokens[1].equalsIgnoreCase("table")) { throw m_compiler.new VoltCompilerException(String.format( "Bad REPLICATE DDL statement: \"%s\", " + "expected syntax: REPLICATE TABLE <table>", StringUtils.join(tokens, ' '))); } m_partitionMap.put(tokens[2], null); return true; } // Not a VoltDB-specific DDL statement. return false; } /** * Strip trailing semi-colon, either as it's own token or at the end * of the last token. Throw exception if there is no semi-colon. * @param tokens * @return processed tokens * @throws VoltCompilerException */ private String[] cleanupVoltDBDDLTerminator(final String statementName, final String[] tokens) throws VoltCompilerException { assert(tokens.length > 0); String[] startTokens = ArrayUtils.subarray(tokens, 0, tokens.length-1); String endToken = tokens[tokens.length-1]; if (!endToken.endsWith(";")) { throw m_compiler.new VoltCompilerException(String.format( "%s DDL statement is not terminated by a semi-colon: \"%s\".", StringUtils.join(tokens, ' '))); } if (endToken.equals(";")) { return startTokens; } return ArrayUtils.add(startTokens, endToken.substring(0, endToken.length()-1)); } public void compileToCatalog(Catalog catalog, Database db) throws VoltCompilerException { String hexDDL = Encoder.hexEncode(m_fullDDL); catalog.execute("set " + db.getPath() + " schema \"" + hexDDL + "\""); VoltXMLElement xmlCatalog; try { xmlCatalog = m_hsql.getXMLFromCatalog(); } catch (HSQLParseException e) { String msg = "DDL Error: " + e.getMessage(); throw m_compiler.new VoltCompilerException(msg); } // output the xml catalog to disk BuildDirectoryUtils.writeFile("schema-xml", "hsql-catalog-output.xml", xmlCatalog.toString()); // build the local catalog from the xml catalog fillCatalogFromXML(catalog, db, xmlCatalog); } /** * Read until the next newline * @throws IOException */ String readToEndOfLine(FileReader reader) throws IOException { LineNumberReader lnr = new LineNumberReader(reader); String retval = lnr.readLine(); m_currLineNo++; return retval; } // Parsing states. Start in kStateInvalid private static int kStateInvalid = 0; // have not yet found start of statement private static int kStateReading = 1; // normal reading state private static int kStateReadingCommentDelim = 2; // dealing with first - private static int kStateReadingComment = 3; // parsing after -- for a newline private static int kStateReadingStringLiteralSpecialChar = 4; // dealing with one or more single quotes private static int kStateReadingStringLiteral = 5; // in the middle of a string literal private static int kStateCompleteStatement = 6; // found end of statement private int readingState(char[] nchar, DDLStatement retval) { if (nchar[0] == '-') { // remember that a possible '--' is being examined return kStateReadingCommentDelim; } else if (nchar[0] == '\n') { // normalize newlines to spaces m_currLineNo += 1; retval.statement += " "; } else if (nchar[0] == '\r') { // ignore carriage returns } else if (nchar[0] == ';') { // end of the statement retval.statement += nchar[0]; return kStateCompleteStatement; } else if (nchar[0] == '\'') { retval.statement += nchar[0]; return kStateReadingStringLiteral; } else { // accumulate and continue retval.statement += nchar[0]; } return kStateReading; } private int readingStringLiteralState(char[] nchar, DDLStatement retval) { // all characters in the literal are accumulated. keep track of // newlines for error messages. retval.statement += nchar[0]; if (nchar[0] == '\n') { m_currLineNo += 1; } // if we see a SINGLE_QUOTE, change states to check for terminating literal if (nchar[0] != '\'') { return kStateReadingStringLiteral; } else { return kStateReadingStringLiteralSpecialChar; } } private int readingStringLiteralSpecialChar(char[] nchar, DDLStatement retval) { // if this is an escaped quote, return kReadingStringLiteral. // otherwise, the string is complete. Parse nchar as a non-literal if (nchar[0] == '\'') { retval.statement += nchar[0]; return kStateReadingStringLiteral; } else { return readingState(nchar, retval); } } private int readingCommentDelimState(char[] nchar, DDLStatement retval) { if (nchar[0] == '-') { // confirmed that a comment is being read return kStateReadingComment; } else { // need to append the previously skipped '-' to the statement // and process the current character retval.statement += '-'; return readingState(nchar, retval); } } private int readingCommentState(char[] nchar, DDLStatement retval) { if (nchar[0] == '\n') { // a comment is continued until a newline is found. m_currLineNo += 1; return kStateReading; } return kStateReadingComment; } DDLStatement getNextStatement(FileReader reader, VoltCompiler compiler) throws VoltCompiler.VoltCompilerException { int state = kStateInvalid; char[] nchar = new char[1]; @SuppressWarnings("synthetic-access") DDLStatement retval = new DDLStatement(); retval.lineNo = m_currLineNo; try { // find the start of a statement and break out of the loop // or return null if there is no next statement to be found do { if (reader.read(nchar) == -1) { return null; } // trim leading whitespace outside of a statement if (nchar[0] == '\n') { m_currLineNo++; } else if (nchar[0] == '\r') { } else if (nchar[0] == ' ') { } // trim leading comments outside of a statement else if (nchar[0] == '-') { // The next character must be a comment because no valid // statement will start with "-<foo>". If a comment was // found, read until the next newline. if (reader.read(nchar) == -1) { // garbage at the end of a file but easy to tolerable? return null; } if (nchar[0] != '-') { String msg = "Invalid content before or between DDL statements."; throw compiler.new VoltCompilerException(msg, m_currLineNo); } else { do { if (reader.read(nchar) == -1) { // a comment extending to EOF means no statement return null; } } while (nchar[0] != '\n'); // process the newline and loop m_currLineNo++; } } // not whitespace or comment: start of a statement. else { retval.statement += nchar[0]; state = kStateReading; // Set the line number to the start of the real statement. retval.lineNo = m_currLineNo; break; } } while (true); while (state != kStateCompleteStatement) { if (reader.read(nchar) == -1) { String msg = "Schema file ended mid-statement (no semicolon found)."; throw compiler.new VoltCompilerException(msg, retval.lineNo); } if (state == kStateReading) { state = readingState(nchar, retval); } else if (state == kStateReadingCommentDelim) { state = readingCommentDelimState(nchar, retval); } else if (state == kStateReadingComment) { state = readingCommentState(nchar, retval); } else if (state == kStateReadingStringLiteral) { state = readingStringLiteralState(nchar, retval); } else if (state == kStateReadingStringLiteralSpecialChar) { state = readingStringLiteralSpecialChar(nchar, retval); } else { throw compiler.new VoltCompilerException("Unrecoverable error parsing DDL."); } } return retval; } catch (IOException e) { throw compiler.new VoltCompilerException("Unable to read from file"); } } public void fillCatalogFromXML(Catalog catalog, Database db, VoltXMLElement xml) throws VoltCompiler.VoltCompilerException { if (xml == null) throw m_compiler.new VoltCompilerException("Unable to parse catalog xml file from hsqldb"); assert xml.name.equals("databaseschema"); for (VoltXMLElement node : xml.children) { if (node.name.equals("table")) addTableToCatalog(catalog, db, node); } processMaterializedViews(db); } void addTableToCatalog(Catalog catalog, Database db, VoltXMLElement node) throws VoltCompilerException { assert node.name.equals("table"); // clear these maps, as they're table specific columnMap.clear(); indexMap.clear(); String name = node.attributes.get("name"); Table table = db.getTables().add(name); // handle the case where this is a materialized view String query = node.attributes.get("query"); if (query != null) { assert(query.length() > 0); matViewMap.put(table, query); } // all tables start replicated // if a partition is found in the project file later, // then this is reversed table.setIsreplicated(true); ArrayList<VoltType> columnTypes = new ArrayList<VoltType>(); for (VoltXMLElement subNode : node.children) { if (subNode.name.equals("columns")) { int colIndex = 0; for (VoltXMLElement columnNode : subNode.children) { if (columnNode.name.equals("column")) addColumnToCatalog(table, columnNode, colIndex++, columnTypes); } // limit the total number of columns in a table if (colIndex > MAX_COLUMNS) { String msg = "Table " + name + " has " + colIndex + " columns (max is " + MAX_COLUMNS + ")"; throw m_compiler.new VoltCompilerException(msg); } } if (subNode.name.equals("indexes")) { for (VoltXMLElement indexNode : subNode.children) { if (indexNode.name.equals("index")) addIndexToCatalog(table, indexNode); } } if (subNode.name.equals("constraints")) { for (VoltXMLElement constraintNode : subNode.children) { if (constraintNode.name.equals("constraint")) addConstraintToCatalog(table, constraintNode); } } } table.setSignature(VoltTypeUtil.getSignatureForTable(name, columnTypes)); /* * Validate that the total size */ int maxRowSize = 0; for (Column c : columnMap.values()) { VoltType t = VoltType.get((byte)c.getType()); if ((t == VoltType.STRING) || (t == VoltType.VARBINARY)) { if (c.getSize() > VoltType.MAX_VALUE_LENGTH) { throw m_compiler.new VoltCompilerException("Table name " + name + " column " + c.getName() + " has a maximum size of " + c.getSize() + " bytes" + " but the maximum supported size is " + VoltType.MAX_VALUE_LENGTH_STR); } maxRowSize += 4 + c.getSize(); } else { maxRowSize += t.getLengthInBytesForFixedTypes(); } } if (maxRowSize > MAX_ROW_SIZE) { throw m_compiler.new VoltCompilerException("Table name " + name + " has a maximum row size of " + maxRowSize + " but the maximum supported row size is " + MAX_ROW_SIZE); } } void addColumnToCatalog(Table table, VoltXMLElement node, int index, ArrayList<VoltType> columnTypes) throws VoltCompilerException { assert node.name.equals("column"); String name = node.attributes.get("name"); String typename = node.attributes.get("type"); String nullable = node.attributes.get("nullable"); String sizeString = node.attributes.get("size"); String defaultvalue = null; String defaulttype = null; // throws an exception if string isn't an int (i think) Integer.parseInt(sizeString); // Default Value for (VoltXMLElement child : node.children) { if (child.name.equals("default")) { for (VoltXMLElement inner_child : child.children) { // Value if (inner_child.name.equals("value")) { defaultvalue = inner_child.attributes.get("value"); defaulttype = inner_child.attributes.get("type"); } // Function /*else if (inner_child.name.equals("function")) { defaultvalue = inner_child.attributes.get("name"); defaulttype = VoltType.VOLTFUNCTION.name(); }*/ if (defaultvalue != null) break; } } } if (defaultvalue != null && defaultvalue.equals("NULL")) defaultvalue = null; if (defaulttype != null) { // fyi: Historically, VoltType class initialization errors get reported on this line (?). defaulttype = Integer.toString(VoltType.typeFromString(defaulttype).getValue()); } // replace newlines in default values if (defaultvalue != null) { defaultvalue = defaultvalue.replace('\n', ' '); defaultvalue = defaultvalue.replace('\r', ' '); } // fyi: Historically, VoltType class initialization errors get reported on this line (?). VoltType type = VoltType.typeFromString(typename); columnTypes.add(type); int size = Integer.parseInt(sizeString); // check valid length if varchar if (type == VoltType.STRING) { if ((size == 0) || (size > VoltType.MAX_VALUE_LENGTH)) { String msg = "VARCHAR Column " + name + " in table " + table.getTypeName() + " has unsupported length " + sizeString; throw m_compiler.new VoltCompilerException(msg); } } if (defaultvalue != null && (type == VoltType.DECIMAL || type == VoltType.NUMERIC)) { // Until we support deserializing scientific notation in the EE, we'll // coerce default values to plain notation here. See ENG-952 for more info. BigDecimal temp = new BigDecimal(defaultvalue); defaultvalue = temp.toPlainString(); } Column column = table.getColumns().add(name); // need to set other column data here (default, nullable, etc) column.setName(name); column.setIndex(index); column.setType(type.getValue()); column.setNullable(nullable.toLowerCase().startsWith("t") ? true : false); column.setSize(size); column.setDefaultvalue(defaultvalue); if (defaulttype != null) column.setDefaulttype(Integer.parseInt(defaulttype)); columnMap.put(name, column); } void addIndexToCatalog(Table table, VoltXMLElement node) throws VoltCompilerException { assert node.name.equals("index"); String name = node.attributes.get("name"); boolean unique = Boolean.parseBoolean(node.attributes.get("unique")); // this won't work for multi-column indices // XXX not sure what 'this' is above, perhaps stale comment --izzy String colList = node.attributes.get("columns"); String[] colNames = colList.split(","); Column[] columns = new Column[colNames.length]; boolean has_nonint_col = false; String nonint_col_name = null; for (int i = 0; i < colNames.length; i++) { columns[i] = columnMap.get(colNames[i]); if (columns[i] == null) { return; } VoltType colType = VoltType.get((byte)columns[i].getType()); if (colType == VoltType.DECIMAL || colType == VoltType.FLOAT || colType == VoltType.STRING) { has_nonint_col = true; nonint_col_name = colNames[i]; } // disallow columns from VARBINARYs if (colType == VoltType.VARBINARY) { String msg = "VARBINARY values are not currently supported as index keys: '" + colNames[i] + "'"; throw this.m_compiler.new VoltCompilerException(msg); } } Index index = table.getIndexes().add(name); index.setCountable(false); // set the type of the index based on the index name and column types // Currently, only int types can use hash or array indexes String indexNameNoCase = name.toLowerCase(); if (indexNameNoCase.contains("tree")) { index.setType(IndexType.BALANCED_TREE.getValue()); index.setCountable(true); } else if (indexNameNoCase.contains("hash")) { if (!has_nonint_col) { index.setType(IndexType.HASH_TABLE.getValue()); } else { String msg = "Index " + name + " in table " + table.getTypeName() + " uses a non-hashable column" + nonint_col_name; throw m_compiler.new VoltCompilerException(msg); } } else { index.setType(IndexType.BALANCED_TREE.getValue()); index.setCountable(true); } - if (indexNameNoCase.contains("NoCounter")) { - index.setType(IndexType.BALANCED_TREE.getValue()); - index.setCountable(false); - } + // Countable is always on right now. Fix it when VoltDB can pack memory for TreeNode. +// if (indexNameNoCase.contains("NoCounter")) { +// index.setType(IndexType.BALANCED_TREE.getValue()); +// index.setCountable(false); +// } // need to set other index data here (column, etc) for (int i = 0; i < columns.length; i++) { ColumnRef cref = index.getColumns().add(columns[i].getTypeName()); cref.setColumn(columns[i]); cref.setIndex(i); } index.setUnique(unique); String msg = "Created index: " + name + " on table: " + table.getTypeName() + " of type: " + IndexType.get(index.getType()).name(); m_compiler.addInfo(msg); indexMap.put(name, index); } /** * Add a constraint on a given table to the catalog * @param table * @param node * @throws VoltCompilerException */ void addConstraintToCatalog(Table table, VoltXMLElement node) throws VoltCompilerException { assert node.name.equals("constraint"); String name = node.attributes.get("name"); String typeName = node.attributes.get("type"); ConstraintType type = ConstraintType.valueOf(typeName); if (type == null) { throw m_compiler.new VoltCompilerException("Invalid constraint type '" + typeName + "'"); } if (type == ConstraintType.CHECK) { String msg = "VoltDB does not enforce check constraints. "; msg += "Constraint on table " + table.getTypeName() + " will be ignored."; m_compiler.addWarn(msg); return; } else if (type == ConstraintType.FOREIGN_KEY) { String msg = "VoltDB does not enforce foreign key references and constraints. "; msg += "Constraint on table " + table.getTypeName() + " will be ignored."; m_compiler.addWarn(msg); return; } else if (type == ConstraintType.PRIMARY_KEY) { // create the unique index below // primary key code is in other places as well } else if (type == ConstraintType.UNIQUE) { // just create the unique index below } else if (type == ConstraintType.MAIN) { // should never see these assert(false); } else if (type == ConstraintType.NOT_NULL) { // these get handled by table metadata inspection return; } // The constraint is backed by an index, therefore we need to create it // TODO: We need to be able to use indexes for foreign keys. I am purposely // leaving those out right now because HSQLDB just makes too many of them. Constraint catalog_const = null; if (node.attributes.get("index") != null) { String indexName = node.attributes.get("index"); Index catalog_index = indexMap.get(indexName); // if the constraint name contains index type hints, exercise them (giant hack) if (catalog_index != null) { String constraintNameNoCase = name.toLowerCase(); if (constraintNameNoCase.contains("tree")) catalog_index.setType(IndexType.BALANCED_TREE.getValue()); if (constraintNameNoCase.contains("hash")) catalog_index.setType(IndexType.HASH_TABLE.getValue()); } catalog_const = table.getConstraints().add(name); if (catalog_index != null) { catalog_const.setIndex(catalog_index); catalog_index.setUnique(type == ConstraintType.UNIQUE || type == ConstraintType.PRIMARY_KEY); } } else { catalog_const = table.getConstraints().add(name); } catalog_const.setType(type.getValue()); // NO ADDITIONAL WORK // since we only really support unique constraints, setting up a // unique index above is all we need to do to make that work return; } /** * Add materialized view info to the catalog for the tables that are * materialized views. */ void processMaterializedViews(Database db) throws VoltCompiler.VoltCompilerException { for (Entry<Table, String> entry : matViewMap.entrySet()) { Table destTable = entry.getKey(); String query = entry.getValue(); // get the xml for the query VoltXMLElement xmlquery = null; try { xmlquery = m_hsql.getXMLCompiledStatement(query); } catch (HSQLParseException e) { e.printStackTrace(); } assert(xmlquery != null); // parse the xml like any other sql statement ParsedSelectStmt stmt = null; try { stmt = (ParsedSelectStmt) AbstractParsedStmt.parse(query, xmlquery, db, null); } catch (Exception e) { throw m_compiler.new VoltCompilerException(e.getMessage()); } assert(stmt != null); // throw an error if the view isn't withing voltdb's limited worldview checkViewMeetsSpec(destTable.getTypeName(), stmt); // create the materializedviewinfo catalog node for the source table Table srcTable = stmt.tableList.get(0); MaterializedViewInfo matviewinfo = srcTable.getViews().add(destTable.getTypeName()); matviewinfo.setDest(destTable); if (stmt.where == null) matviewinfo.setPredicate(""); else { String hex = Encoder.hexEncode(stmt.where.toJSONString()); matviewinfo.setPredicate(hex); } destTable.setMaterializer(srcTable); List<Column> srcColumnArray = CatalogUtil.getSortedCatalogItems(srcTable.getColumns(), "index"); List<Column> destColumnArray = CatalogUtil.getSortedCatalogItems(destTable.getColumns(), "index"); // add the group by columns from the src table for (int i = 0; i < stmt.groupByColumns.size(); i++) { ParsedSelectStmt.ParsedColInfo gbcol = stmt.groupByColumns.get(i); Column srcCol = srcColumnArray.get(gbcol.index); ColumnRef cref = matviewinfo.getGroupbycols().add(srcCol.getTypeName()); // groupByColumns is iterating in order of groups. Store that grouping order // in the column ref index. When the catalog is serialized, it will, naturally, // scramble this order like a two year playing dominos, presenting the data // in a meaningless sequence. cref.setIndex(i); // the column offset in the view's grouping order cref.setColumn(srcCol); // the source column from the base (non-view) table } ParsedSelectStmt.ParsedColInfo countCol = stmt.displayColumns.get(stmt.groupByColumns.size()); assert(countCol.expression.getExpressionType() == ExpressionType.AGGREGATE_COUNT); assert(countCol.expression.getLeft() == null); processMaterializedViewColumn(matviewinfo, srcTable, destTable, destColumnArray.get(stmt.groupByColumns.size()), ExpressionType.AGGREGATE_COUNT, null); // create an index and constraint for the table Index pkIndex = destTable.getIndexes().add("MATVIEW_PK_INDEX"); pkIndex.setType(IndexType.BALANCED_TREE.getValue()); pkIndex.setUnique(true); // add the group by columns from the src table // assume index 1 throuh #grpByCols + 1 are the cols for (int i = 0; i < stmt.groupByColumns.size(); i++) { ColumnRef c = pkIndex.getColumns().add(String.valueOf(i)); c.setColumn(destColumnArray.get(i)); c.setIndex(i); } Constraint pkConstraint = destTable.getConstraints().add("MATVIEW_PK_CONSTRAINT"); pkConstraint.setType(ConstraintType.PRIMARY_KEY.getValue()); pkConstraint.setIndex(pkIndex); // parse out the group by columns into the dest table for (int i = 0; i < stmt.groupByColumns.size(); i++) { ParsedSelectStmt.ParsedColInfo col = stmt.displayColumns.get(i); Column destColumn = destColumnArray.get(i); processMaterializedViewColumn(matviewinfo, srcTable, destTable, destColumn, ExpressionType.VALUE_TUPLE, (TupleValueExpression)col.expression); } // parse out the aggregation columns into the dest table for (int i = stmt.groupByColumns.size() + 1; i < stmt.displayColumns.size(); i++) { ParsedSelectStmt.ParsedColInfo col = stmt.displayColumns.get(i); Column destColumn = destColumnArray.get(i); AbstractExpression colExpr = col.expression.getLeft(); assert(colExpr.getExpressionType() == ExpressionType.VALUE_TUPLE); processMaterializedViewColumn(matviewinfo, srcTable, destTable, destColumn, col.expression.getExpressionType(), (TupleValueExpression)colExpr); // Correctly set the type of the column so that it's consistent. // Otherwise HSQLDB might promote types differently than Volt. destColumn.setType(col.expression.getValueType().getValue()); } } } /** * Verify the materialized view meets our arcane rules about what can and can't * go in a materialized view. Throw hopefully helpful error messages when these * rules are inevitably borked. * * @param viewName The name of the view being checked. * @param stmt The output from the parser describing the select statement that creates the view. * @throws VoltCompilerException */ private void checkViewMeetsSpec(String viewName, ParsedSelectStmt stmt) throws VoltCompilerException { int groupColCount = stmt.groupByColumns.size(); int displayColCount = stmt.displayColumns.size(); String msg = "Materialized view \"" + viewName + "\" "; if (stmt.tableList.size() != 1) { msg += "has " + String.valueOf(stmt.tableList.size()) + " sources. " + "Only one source view or source table is allowed."; throw m_compiler.new VoltCompilerException(msg); } if (displayColCount <= groupColCount) { msg += "has too few columns."; throw m_compiler.new VoltCompilerException(msg); } int i; for (i = 0; i < groupColCount; i++) { ParsedSelectStmt.ParsedColInfo gbcol = stmt.groupByColumns.get(i); ParsedSelectStmt.ParsedColInfo outcol = stmt.displayColumns.get(i); if (outcol.expression.getExpressionType() != ExpressionType.VALUE_TUPLE) { msg += "must have column at index " + String.valueOf(i) + " be " + gbcol.alias; throw m_compiler.new VoltCompilerException(msg); } TupleValueExpression expr = (TupleValueExpression) outcol.expression; if (expr.getColumnIndex() != gbcol.index) { msg += "must have column at index " + String.valueOf(i) + " be " + gbcol.alias; throw m_compiler.new VoltCompilerException(msg); } } AbstractExpression coli = stmt.displayColumns.get(i).expression; if ((coli.getExpressionType() != ExpressionType.AGGREGATE_COUNT) || (coli.getLeft() != null) || (coli.getRight() != null)) { msg += "is missing count(*) as the column after the group by columns, a materialized view requirement."; throw m_compiler.new VoltCompilerException(msg); } for (i++; i < displayColCount; i++) { ParsedSelectStmt.ParsedColInfo outcol = stmt.displayColumns.get(i); if ((outcol.expression.getExpressionType() != ExpressionType.AGGREGATE_COUNT) && (outcol.expression.getExpressionType() != ExpressionType.AGGREGATE_SUM)) { msg += "must have non-group by columns aggregated by sum or count."; throw m_compiler.new VoltCompilerException(msg); } if (outcol.expression.getLeft().getExpressionType() != ExpressionType.VALUE_TUPLE) { msg += "must have non-group by columns use only one level of aggregation."; throw m_compiler.new VoltCompilerException(msg); } } } void processMaterializedViewColumn(MaterializedViewInfo info, Table srcTable, Table destTable, Column destColumn, ExpressionType type, TupleValueExpression colExpr) throws VoltCompiler.VoltCompilerException { if (colExpr != null) { assert(colExpr.getTableName().equalsIgnoreCase(srcTable.getTypeName())); String srcColName = colExpr.getColumnName(); Column srcColumn = srcTable.getColumns().getIgnoreCase(srcColName); destColumn.setMatviewsource(srcColumn); } destColumn.setMatview(info); destColumn.setAggregatetype(type.getValue()); } }
true
false
null
null
diff --git a/src/java/org/jivesoftware/spark/component/tabbedPane/TabPanelUI.java b/src/java/org/jivesoftware/spark/component/tabbedPane/TabPanelUI.java index 59a6eaa2..4a484f13 100644 --- a/src/java/org/jivesoftware/spark/component/tabbedPane/TabPanelUI.java +++ b/src/java/org/jivesoftware/spark/component/tabbedPane/TabPanelUI.java @@ -1,193 +1,195 @@ /** * $Revision: $ * $Date: $ * * Copyright (C) 2006 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Lesser Public License (LGPL), * a copy of which is included in this distribution. */ package org.jivesoftware.spark.component.tabbedPane; import org.jivesoftware.Spark; import org.jivesoftware.resource.Default; import org.jivesoftware.spark.util.log.Log; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.RoundRectangle2D; import java.util.StringTokenizer; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.UIManager; import javax.swing.plaf.basic.BasicPanelUI; /** * Represents a single instance of a Tab Paint Component. * * @author Derek DeMoro */ public class TabPanelUI extends BasicPanelUI { private Color backgroundColor1 = new Color(0, 0, 0, 0); private Color backgroundColor2 = new Color(0, 0, 0, 0); private Color borderColor = new Color(86, 88, 72); private Color borderColorAlpha1 = new Color(86, 88, 72, 100); private Color borderColorAlpha2 = new Color(86, 88, 72, 50); private Color borderHighlight = new Color(225, 224, 224); private boolean selected; private boolean hideBorder; private int placement = JTabbedPane.TOP; // ------------------------------------------------------------------------------------------------------------------ // Custom installation methods // ------------------------------------------------------------------------------------------------------------------ protected void installDefaults(JPanel p) { p.setOpaque(false); } public void setSelected(boolean selected) { if (selected) { backgroundColor1 = getSelectedStartColor(); backgroundColor2 = getSelectedEndColor(); } else { backgroundColor1 = new Color(0, 0, 0, 0); backgroundColor2 = new Color(0, 0, 0, 0); } this.selected = selected; } // ------------------------------------------------------------------------------------------------------------------ // Custom painting methods // ------------------------------------------------------------------------------------------------------------------ public void paint(Graphics g, JComponent c) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Insets vInsets = c.getInsets(); int w = c.getWidth() - (vInsets.left + vInsets.right); int h = c.getHeight() - (vInsets.top + vInsets.bottom); int x = vInsets.left; int y = vInsets.top; int arc = 8; Shape vButtonShape = new RoundRectangle2D.Double((double)x, (double)y, (double)w, (double)h, (double)arc, (double)arc); Shape vOldClip = g.getClip(); - g2d.setClip(vButtonShape); + if(!Spark.isMac()){ + g2d.setClip(vButtonShape); + } g2d.setColor(backgroundColor2); g2d.fillRect(x, y, w, h); g2d.setClip(vOldClip); GradientPaint vPaint = new GradientPaint(x, y, borderColor, x, y + h, borderHighlight); g2d.setPaint(vPaint); // Handle custom actions. if (placement == JTabbedPane.TOP) { if (selected) { g2d.setColor(Color.lightGray); g2d.drawRoundRect(x, y, w, h, arc, arc); } g2d.clipRect(x, y, w + 1, h - arc / 4); g2d.setColor(borderColorAlpha1); g2d.setClip(vOldClip); g2d.setColor(borderColorAlpha2); g2d.setColor(backgroundColor2); g2d.fillRect(x, h - 5, w, h); } else { // Make straight line. g2d.setColor(backgroundColor2); g2d.fillRect(x, y, w, 4); } if (selected) { } else if (!hideBorder) { // Draw border on right side. g2d.setColor(Color.lightGray); g2d.drawLine(w - 1, 4, w - 1, h - 4); } } public void setHideBorder(boolean hide) { hideBorder = hide; } private Color getSelectedStartColor() { Color uiStartColor = (Color)UIManager.get("SparkTabbedPane.startColor"); if (uiStartColor != null) { return uiStartColor; } if (Spark.isCustomBuild()) { String end = Default.getString(Default.CONTACT_GROUP_END_COLOR); return getColor(end); } else { return new Color(193, 216, 248); } } private Color getSelectedEndColor() { Color uiEndColor = (Color)UIManager.get("SparkTabbedPane.endColor"); if (uiEndColor != null) { return uiEndColor; } if (Spark.isCustomBuild()) { String end = Default.getString(Default.CONTACT_GROUP_END_COLOR); return getColor(end); } else { return new Color(180, 207, 247); } } private static Color getColor(String commaColorString) { Color color = null; try { color = null; StringTokenizer tkn = new StringTokenizer(commaColorString, ","); color = new Color(Integer.parseInt(tkn.nextToken()), Integer.parseInt(tkn.nextToken()), Integer.parseInt(tkn.nextToken())); } catch (NumberFormatException e1) { Log.error(e1); return Color.white; } return color; } public void setPlacement(int placement) { this.placement = placement; } }
true
true
public void paint(Graphics g, JComponent c) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Insets vInsets = c.getInsets(); int w = c.getWidth() - (vInsets.left + vInsets.right); int h = c.getHeight() - (vInsets.top + vInsets.bottom); int x = vInsets.left; int y = vInsets.top; int arc = 8; Shape vButtonShape = new RoundRectangle2D.Double((double)x, (double)y, (double)w, (double)h, (double)arc, (double)arc); Shape vOldClip = g.getClip(); g2d.setClip(vButtonShape); g2d.setColor(backgroundColor2); g2d.fillRect(x, y, w, h); g2d.setClip(vOldClip); GradientPaint vPaint = new GradientPaint(x, y, borderColor, x, y + h, borderHighlight); g2d.setPaint(vPaint); // Handle custom actions. if (placement == JTabbedPane.TOP) { if (selected) { g2d.setColor(Color.lightGray); g2d.drawRoundRect(x, y, w, h, arc, arc); } g2d.clipRect(x, y, w + 1, h - arc / 4); g2d.setColor(borderColorAlpha1); g2d.setClip(vOldClip); g2d.setColor(borderColorAlpha2); g2d.setColor(backgroundColor2); g2d.fillRect(x, h - 5, w, h); } else { // Make straight line. g2d.setColor(backgroundColor2); g2d.fillRect(x, y, w, 4); } if (selected) { } else if (!hideBorder) { // Draw border on right side. g2d.setColor(Color.lightGray); g2d.drawLine(w - 1, 4, w - 1, h - 4); } }
public void paint(Graphics g, JComponent c) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Insets vInsets = c.getInsets(); int w = c.getWidth() - (vInsets.left + vInsets.right); int h = c.getHeight() - (vInsets.top + vInsets.bottom); int x = vInsets.left; int y = vInsets.top; int arc = 8; Shape vButtonShape = new RoundRectangle2D.Double((double)x, (double)y, (double)w, (double)h, (double)arc, (double)arc); Shape vOldClip = g.getClip(); if(!Spark.isMac()){ g2d.setClip(vButtonShape); } g2d.setColor(backgroundColor2); g2d.fillRect(x, y, w, h); g2d.setClip(vOldClip); GradientPaint vPaint = new GradientPaint(x, y, borderColor, x, y + h, borderHighlight); g2d.setPaint(vPaint); // Handle custom actions. if (placement == JTabbedPane.TOP) { if (selected) { g2d.setColor(Color.lightGray); g2d.drawRoundRect(x, y, w, h, arc, arc); } g2d.clipRect(x, y, w + 1, h - arc / 4); g2d.setColor(borderColorAlpha1); g2d.setClip(vOldClip); g2d.setColor(borderColorAlpha2); g2d.setColor(backgroundColor2); g2d.fillRect(x, h - 5, w, h); } else { // Make straight line. g2d.setColor(backgroundColor2); g2d.fillRect(x, y, w, 4); } if (selected) { } else if (!hideBorder) { // Draw border on right side. g2d.setColor(Color.lightGray); g2d.drawLine(w - 1, 4, w - 1, h - 4); } }
diff --git a/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/PDAHandler.java b/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/PDAHandler.java index 60b724c6..4f5529a3 100644 --- a/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/PDAHandler.java +++ b/portal-impl/impl/src/java/org/sakaiproject/portal/charon/handlers/PDAHandler.java @@ -1,341 +1,342 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2007 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.portal.charon.handlers; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.portal.api.Portal; import org.sakaiproject.portal.api.PortalHandlerException; import org.sakaiproject.portal.api.PortalRenderContext; import org.sakaiproject.portal.util.ByteArrayServletResponse; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.site.cover.SiteService; import org.sakaiproject.tool.api.ActiveTool; import org.sakaiproject.tool.api.Session; import org.sakaiproject.tool.api.Tool; import org.sakaiproject.tool.api.ToolException; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.ActiveToolManager; import org.sakaiproject.tool.cover.SessionManager; +import org.sakaiproject.util.Validator; import org.sakaiproject.util.Web; /** * * @author csev * @since Sakai 2.4 * @version $Rev$ * */ public class PDAHandler extends PageHandler { /** * Key in the ThreadLocalManager for access to the current http response * object. */ public final static String CURRENT_HTTP_RESPONSE = "org.sakaiproject.util.RequestFilter.http_response"; private ToolHandler toolHandler = new ToolHandler(); private static final Log log = LogFactory.getLog(PDAHandler.class); private static final String URL_FRAGMENT = "pda"; public PDAHandler() { setUrlFragment(PDAHandler.URL_FRAGMENT); } @Override public int doGet(String[] parts, HttpServletRequest req, HttpServletResponse res, Session session) throws PortalHandlerException { if ((parts.length >= 2) && (parts[1].equals("pda"))) { // Indicate that we are the controlling portal session.setAttribute("sakai-controlling-portal",PDAHandler.URL_FRAGMENT); try { // /portal/pda/site-id String siteId = null; if (parts.length >= 3) { siteId = parts[2]; } // This is a pop-up page - it does exactly the same as // /portal/page // /portal/pda/site-id/page/page-id // 1 2 3 4 String pageId = null; if ((parts.length == 5) && (parts[3].equals("page"))) { doPage(req, res, session, parts[4], req.getContextPath() + req.getServletPath()); return END; } // Tool resetting URL - clear state and forward to the real tool // URL // /portal/pda/site-id/tool-reset/toolId // 0 1 2 3 4 String toolId = null; if ((siteId != null) && (parts.length == 5) && (parts[3].equals("tool-reset"))) { toolId = parts[4]; String toolUrl = req.getContextPath() + "/pda/" + siteId + "/tool" + Web.makePath(parts, 4, parts.length); - String queryString = req.getQueryString(); + String queryString = Validator.generateQueryString(req); if (queryString != null) { toolUrl = toolUrl + "?" + queryString; } portalService.setResetState("true"); res.sendRedirect(toolUrl); return RESET_DONE; } // Tool after the reset // /portal/pda/site-id/tool/toolId if ((parts.length > 4) && (parts[3].equals("tool"))) { toolId = parts[4]; } String forceLogout = req.getParameter(Portal.PARAM_FORCE_LOGOUT); if ("yes".equalsIgnoreCase(forceLogout) || "true".equalsIgnoreCase(forceLogout)) { portal.doLogout(req, res, session, "/pda"); return END; } if (session.getUserId() == null) { String forceLogin = req.getParameter(Portal.PARAM_FORCE_LOGIN); if ("yes".equalsIgnoreCase(forceLogin) || "true".equalsIgnoreCase(forceLogin)) { portal.doLogin(req, res, session, req.getPathInfo(), false); return END; } } PortalRenderContext rcontext = portal.includePortal(req, res, session, siteId, toolId, req.getContextPath() + req.getServletPath(), "pda", /* doPages */false, /* resetTools */true, /* includeSummary */false, /* expandSite */false); // TODO: Should this be a property? Probably because it does cause an // uncached SQL query portal.includeSubSites(rcontext, req, session, siteId, req.getContextPath() + req.getServletPath(), "pda", /* resetTools */ true ); // Add any device specific information to the context portal.setupMobileDevice(req, rcontext); // Optionally buffer tool content to eliminate iFrames bufferContent(req, res, session, parts, toolId, rcontext); portal.sendResponse(rcontext, res, "pda", null); return END; } catch (Exception ex) { throw new PortalHandlerException(ex); } } else { return NEXT; } } /* * Optionally actually grab the tool's output and include it in the same * frame */ public void bufferContent(HttpServletRequest req, HttpServletResponse res, Session session, String[] parts, String toolId, PortalRenderContext rcontext) { if (toolId == null) return; String tidAllow = ServerConfigurationService .getString("portal.pda.iframesuppress"); if (tidAllow.indexOf(":none:") >= 0) return; ToolConfiguration siteTool = SiteService.findTool(toolId); if (siteTool == null) return; // If the property is set and :all: is not specified, then the // tools in the list are the ones that we accept if (tidAllow.trim().length() > 0 && tidAllow.indexOf(":all:") < 0) { if (tidAllow.indexOf(siteTool.getToolId()) < 0) return; } // If the property is set and :all: is specified, then the // tools in the list are the ones that we render the old way if (tidAllow.indexOf(":all:") >= 0) { if (tidAllow.indexOf(siteTool.getToolId()) >= 0) return; } // Produce the buffered response ByteArrayServletResponse bufferedResponse = new ByteArrayServletResponse(res); try { boolean retval = doToolBuffer(req, bufferedResponse, session, parts[4], req.getContextPath() + req.getServletPath() + Web.makePath(parts, 1, 5), Web.makePath(parts, 5, parts.length)); if ( ! retval ) return; } catch (Exception e) { return; } String responseStr = bufferedResponse.getInternalBuffer(); if (responseStr == null || responseStr.length() < 1) return; String responseStrLower = responseStr.toLowerCase(); int headStart = responseStrLower.indexOf("<head"); headStart = findEndOfTag(responseStrLower, headStart); int headEnd = responseStrLower.indexOf("</head"); int bodyStart = responseStrLower.indexOf("<body"); bodyStart = findEndOfTag(responseStrLower, bodyStart); // Some tools (Blogger for example) have multiple // head-body pairs - browsers seem to not care much about // this so we will do the same - so that we can be // somewhat clean - we search for the "last" end // body tag - for the normal case there will only be one int bodyEnd = responseStrLower.lastIndexOf("</body"); // If there is no body end at all or it is before the body // start tag we simply - take the rest of the response if ( bodyEnd < bodyStart ) bodyEnd = responseStrLower.length() - 1; if( tidAllow.indexOf(":debug:") >= 0 ) log.info("Frameless HS="+headStart+" HE="+headEnd+" BS="+bodyStart+" BE="+bodyEnd); if (bodyEnd > bodyStart && bodyStart > headEnd && headEnd > headStart && headStart > 1) { String headString = responseStr.substring(headStart + 1, headEnd); String bodyString = responseStr.substring(bodyStart + 1, bodyEnd); if (tidAllow.indexOf(":debug:") >= 0) { System.out.println(" ---- Head --- "); System.out.println(headString); System.out.println(" ---- Body --- "); System.out.println(bodyString); } rcontext.put("bufferedResponse", Boolean.TRUE); rcontext.put("responseHead", headString); rcontext.put("responseBody", bodyString); } } private int findEndOfTag(String string, int startPos) { if (startPos < 1) return -1; for (int i = startPos; i < string.length(); i++) { if (string.charAt(i) == '>') return i; } return -1; } public boolean doToolBuffer(HttpServletRequest req, HttpServletResponse res, Session session, String placementId, String toolContextPath, String toolPathInfo) throws ToolException, IOException { if (portal.redirectIfLoggedOut(res)) return false; // find the tool from some site ToolConfiguration siteTool = SiteService.findTool(placementId); if (siteTool == null) { return false; } // Reset the tool state if requested if ("true".equals(req.getParameter(portalService.getResetStateParam())) || "true".equals(portalService.getResetState())) { Session s = SessionManager.getCurrentSession(); ToolSession ts = s.getToolSession(placementId); ts.clearAttributes(); } // find the tool registered for this ActiveTool tool = ActiveToolManager.getActiveTool(siteTool.getToolId()); if (tool == null) { return false; } // permission check - visit the site (unless the tool is configured to // bypass) if (tool.getAccessSecurity() == Tool.AccessSecurity.PORTAL) { Site site = null; try { site = SiteService.getSiteVisit(siteTool.getSiteId()); } catch (IdUnusedException e) { portal.doError(req, res, session, Portal.ERROR_WORKSITE); return false; } catch (PermissionException e) { return false; } } // System.out.println("portal.forwardTool siteTool="+siteTool+" // TCP="+toolContextPath+" TPI="+toolPathInfo); portal.forwardTool(tool, req, res, siteTool, siteTool.getSkin(), toolContextPath, toolPathInfo); return true; } }
false
false
null
null
diff --git a/src/main/java/libshapedraw/internal/Controller.java b/src/main/java/libshapedraw/internal/Controller.java index 2873127..693c62f 100644 --- a/src/main/java/libshapedraw/internal/Controller.java +++ b/src/main/java/libshapedraw/internal/Controller.java @@ -1,226 +1,225 @@ package libshapedraw.internal; import java.util.LinkedHashSet; import java.util.logging.Level; import java.util.logging.Logger; import libshapedraw.ApiInfo; import libshapedraw.LibShapeDraw; import libshapedraw.MinecraftAccess; import libshapedraw.animation.trident.TridentConfig; import libshapedraw.event.LSDEventListener; import libshapedraw.event.LSDGameTickEvent; import libshapedraw.event.LSDPreRenderEvent; import libshapedraw.event.LSDRespawnEvent; import libshapedraw.internal.Util.FileLogger; import libshapedraw.internal.Util.NullLogger; import libshapedraw.primitive.ReadonlyVector3; import libshapedraw.shape.Shape; import org.lwjgl.opengl.GL11; /** * Internal singleton controller class, lazily instantiated. * Relies on a bootstrapper (mod_LibShapeDraw) to feed it Minecraft game events. */ public class Controller { private static Controller instance; private final Logger log; private final LinkedHashSet<LibShapeDraw> apiInstances; private int topApiInstanceId; private MinecraftAccess minecraftAccess; private boolean initialized; private long lastDump; private Controller() { if (GlobalSettings.isLoggingEnabled()) { log = new FileLogger(ModDirectory.DIRECTORY, ApiInfo.getName(), GlobalSettings.isLoggingAppend()); } else { log = new NullLogger(); } apiInstances = new LinkedHashSet<LibShapeDraw>(); topApiInstanceId = 0; TridentConfig trident = TridentConfig.getInstance(); trident.addPropertyInterpolator(new ReadonlyColorPropertyInterpolator()); trident.addPropertyInterpolator(new ReadonlyVector3PropertyInterpolator()); trident.addPropertyInterpolator(new ReadonlyLineStylePropertyInterpolator()); log.info(ApiInfo.getName() + " v" + ApiInfo.getVersion() + " by " + ApiInfo.getAuthors()); log.info(ApiInfo.getUrl()); log.info(getClass().getName() + " instantiated"); } public static Controller getInstance() { if (instance == null) { instance = new Controller(); } return instance; } public static Logger getLog() { return getInstance().log; } public static MinecraftAccess getMinecraftAccess() { return getInstance().minecraftAccess; } /** * @return true if the bootstrapper has been instantiated and is linked up to the controller */ public static boolean isInitialized() { return getInstance().initialized; } /** * Called by the bootstrapper. */ public void initialize(MinecraftAccess minecraftAccess) { if (isInitialized()) { throw new IllegalStateException("multiple initializations of controller"); } this.minecraftAccess = minecraftAccess; initialized = true; log.info(getClass().getName() + " initialized"); } /** * Called by LibShapeDraw's constructor. */ public String registerApiInstance(LibShapeDraw apiInstance, String ownerId) { if (apiInstances.contains(apiInstance)) { throw new IllegalStateException("already registered"); } topApiInstanceId++; String apiInstanceId = apiInstance.getClass().getSimpleName() + "#" + topApiInstanceId + ":" + ownerId; apiInstances.add(apiInstance); log.info("registered API instance " + apiInstanceId); return apiInstanceId; } /** * Called by LibShapeDraw.unregister. */ public boolean unregisterApiInstance(LibShapeDraw apiInstance) { boolean result = apiInstances.remove(apiInstance); if (result) { log.info("unregistered API instance " + apiInstance.getInstanceId()); } return result; } /** * Called by the bootstrapper. * Dispatch the respawn event. */ public void respawn(ReadonlyVector3 playerCoords, boolean isNewServer, boolean isNewDimension) { log.finer("respawn"); for (LibShapeDraw apiInstance : apiInstances) { if (!apiInstance.getEventListeners().isEmpty()) { LSDRespawnEvent event = new LSDRespawnEvent(apiInstance, playerCoords, isNewServer, isNewDimension); for (LSDEventListener listener : apiInstance.getEventListeners()) { listener.onRespawn(event); } } } } /** * Called by the bootstrapper. * Periodically dump API state to log if configured to do so. * Dispatch gameTick events. */ public void gameTick(ReadonlyVector3 playerCoords) { log.finer("gameTick"); if (GlobalSettings.getLoggingDebugDumpInterval() > 0) { long now = System.currentTimeMillis(); if (now > lastDump + GlobalSettings.getLoggingDebugDumpInterval()) { dump(); lastDump = now; } } for (LibShapeDraw apiInstance : apiInstances) { if (!apiInstance.getEventListeners().isEmpty()) { LSDGameTickEvent event = new LSDGameTickEvent(apiInstance, playerCoords); for (LSDEventListener listener : apiInstance.getEventListeners()) { if (listener != null) { listener.onGameTick(event); } } } } } /** * Called by the bootstrapper. * Dispatch preRender events. * Render all registered shapes. */ public void render(ReadonlyVector3 playerCoords, boolean isGuiHidden) { log.finer("render"); int origDepthFunc = GL11.glGetInteger(GL11.GL_DEPTH_FUNC); GL11.glPushMatrix(); GL11.glTranslated(-playerCoords.getX(), -playerCoords.getY(), -playerCoords.getZ()); for (LibShapeDraw apiInstance : apiInstances) { if (!apiInstance.getEventListeners().isEmpty()) { LSDPreRenderEvent event = new LSDPreRenderEvent(apiInstance, playerCoords, minecraftAccess.getPartialTick(), isGuiHidden); for (LSDEventListener listener : apiInstance.getEventListeners()) { if (listener != null) { listener.onPreRender(event); } } } if (apiInstance.isVisible() && (!isGuiHidden || apiInstance.isVisibleWhenHidingGui())) { for (Shape shape : apiInstance.getShapes()) { if (shape != null) { shape.render(minecraftAccess); } } } } GL11.glPopMatrix(); GL11.glDepthMask(true); GL11.glDepthFunc(origDepthFunc); - GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); } /** * Log all the things. */ public boolean dump() { if (!log.isLoggable(Level.INFO)) { return false; } final String INDENT = " "; StringBuilder line = new StringBuilder().append(this).append(":\n"); for (LibShapeDraw apiInstance : apiInstances) { line.append(INDENT).append(apiInstance).append(":\n"); line.append(INDENT).append(INDENT).append("visible="); line.append(apiInstance.isVisible()).append('\n'); line.append(INDENT).append(INDENT).append("visibleWhenHidingGui="); line.append(apiInstance.isVisibleWhenHidingGui()).append('\n'); line.append(INDENT).append(INDENT).append("shapes="); line.append(apiInstance.getShapes().size()).append(":\n"); for (Shape shape : apiInstance.getShapes()) { line.append(INDENT).append(INDENT).append(INDENT).append(shape).append('\n'); } line.append(INDENT).append(INDENT).append("eventListeners="); line.append(apiInstance.getEventListeners().size()).append(":\n"); for (LSDEventListener listener : apiInstance.getEventListeners()) { line.append(INDENT).append(INDENT).append(INDENT).append(listener).append('\n'); } } log.info(line.toString()); return true; } }
true
true
public void render(ReadonlyVector3 playerCoords, boolean isGuiHidden) { log.finer("render"); int origDepthFunc = GL11.glGetInteger(GL11.GL_DEPTH_FUNC); GL11.glPushMatrix(); GL11.glTranslated(-playerCoords.getX(), -playerCoords.getY(), -playerCoords.getZ()); for (LibShapeDraw apiInstance : apiInstances) { if (!apiInstance.getEventListeners().isEmpty()) { LSDPreRenderEvent event = new LSDPreRenderEvent(apiInstance, playerCoords, minecraftAccess.getPartialTick(), isGuiHidden); for (LSDEventListener listener : apiInstance.getEventListeners()) { if (listener != null) { listener.onPreRender(event); } } } if (apiInstance.isVisible() && (!isGuiHidden || apiInstance.isVisibleWhenHidingGui())) { for (Shape shape : apiInstance.getShapes()) { if (shape != null) { shape.render(minecraftAccess); } } } } GL11.glPopMatrix(); GL11.glDepthMask(true); GL11.glDepthFunc(origDepthFunc); GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); }
public void render(ReadonlyVector3 playerCoords, boolean isGuiHidden) { log.finer("render"); int origDepthFunc = GL11.glGetInteger(GL11.GL_DEPTH_FUNC); GL11.glPushMatrix(); GL11.glTranslated(-playerCoords.getX(), -playerCoords.getY(), -playerCoords.getZ()); for (LibShapeDraw apiInstance : apiInstances) { if (!apiInstance.getEventListeners().isEmpty()) { LSDPreRenderEvent event = new LSDPreRenderEvent(apiInstance, playerCoords, minecraftAccess.getPartialTick(), isGuiHidden); for (LSDEventListener listener : apiInstance.getEventListeners()) { if (listener != null) { listener.onPreRender(event); } } } if (apiInstance.isVisible() && (!isGuiHidden || apiInstance.isVisibleWhenHidingGui())) { for (Shape shape : apiInstance.getShapes()) { if (shape != null) { shape.render(minecraftAccess); } } } } GL11.glPopMatrix(); GL11.glDepthMask(true); GL11.glDepthFunc(origDepthFunc); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); }
diff --git a/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/project/MarkerUtils.java b/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/project/MarkerUtils.java index 1481c4f..b78cbe4 100644 --- a/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/project/MarkerUtils.java +++ b/org.eclipse.m2e.core/src/org/eclipse/m2e/core/internal/project/MarkerUtils.java @@ -1,68 +1,68 @@ /******************************************************************************* * Copyright (c) 2010 Sonatype, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Sonatype, Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.m2e.core.internal.project; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.apache.maven.project.MavenProject; import org.eclipse.m2e.core.MavenPlugin; import org.eclipse.m2e.core.project.IEditorMarkerService; import org.eclipse.m2e.core.project.IMarkerLocationService; import org.eclipse.m2e.core.project.IMavenMarkerManager; /** * MarkerUtils * * @author mkleint */ public class MarkerUtils { public static void decorateMarker(IMarker marker) { BundleContext context = MavenPlugin.getDefault().getBundleContext(); - ServiceReference<IMarkerLocationService> ref = context.getServiceReference(IMarkerLocationService.class); - IMarkerLocationService service = context.getService(ref); + ServiceReference ref = context.getServiceReference(IMarkerLocationService.class); + IMarkerLocationService service = (IMarkerLocationService)context.getService(ref); if (service != null) { try { service.findLocationForMarker(marker); } finally { context.ungetService(ref); } } } /** * @param markerManager * @param pom * @param mavenProject * @param markerPomLoadingId */ public static void addEditorHintMarkers(IMavenMarkerManager markerManager, IFile pom, MavenProject mavenProject, String type) { BundleContext context = MavenPlugin.getDefault().getBundleContext(); - ServiceReference<IEditorMarkerService> ref = context.getServiceReference(IEditorMarkerService.class); - IEditorMarkerService service = context.getService(ref); + ServiceReference ref = context.getServiceReference(IEditorMarkerService.class); + IEditorMarkerService service = (IEditorMarkerService)context.getService(ref); if (service != null) { try { service.addEditorHintMarkers(markerManager, pom, mavenProject, type); } finally { context.ungetService(ref); } } } }
false
false
null
null
diff --git a/app/Global.java b/app/Global.java index 679ec6e..4a02522 100644 --- a/app/Global.java +++ b/app/Global.java @@ -1,22 +1,23 @@ import models.ContactDB; import play.Application; import play.GlobalSettings; import views.formdata.ContactFormData; /** * Initializes activity upon startup. * @author Alvin Wang * */ public class Global extends GlobalSettings { /** * Initialize system with sample contacts. + * @param app The application. */ public void onStart(Application app) { ContactDB.addContact(new ContactFormData("Bruce", "Wayne", "123-456-7890", "Home")); ContactDB.addContact(new ContactFormData("Clark", "Kent", "123-456-7890", "Work")); ContactDB.addContact(new ContactFormData("Tony", "Stark", "123-456-7890", "Mobile")); ContactDB.addContact(new ContactFormData("Bruce", "Banner", "123-456-7890", "Work")); } }
true
false
null
null
diff --git a/build/source/r/debug/edu/dartmouth/mhb/R.java b/build/source/r/debug/edu/dartmouth/mhb/R.java index caeede7..19dd21e 100644 --- a/build/source/r/debug/edu/dartmouth/mhb/R.java +++ b/build/source/r/debug/edu/dartmouth/mhb/R.java @@ -1,143 +1,144 @@ /* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package edu.dartmouth.mhb; public final class R { public static final class array { /** From: file:/Users/Junior/workspace/mhb/res/values/strings.xml */ public static final int drawer_menu_array=0x7f050000; } public static final class attr { } public static final class dimen { /** From: file:/Users/Junior/workspace/mhb/res/values/dimens.xml From: file:/Users/Junior/workspace/mhb/res/values-sw720dp-land/dimens.xml */ public static final int activity_horizontal_margin=0x7f060000; public static final int activity_vertical_margin=0x7f060001; public static final int author_size=0x7f060002; public static final int lyrics_size=0x7f060003; public static final int number_size=0x7f060004; public static final int title_size=0x7f060005; } public static final class drawable { public static final int action_background=0x7f020000; public static final int drawer_shadow=0x7f020001; public static final int ic_action_back=0x7f020002; public static final int ic_action_browse=0x7f020003; public static final int ic_action_delete=0x7f020004; public static final int ic_action_done=0x7f020005; public static final int ic_action_edit=0x7f020006; public static final int ic_action_format=0x7f020007; public static final int ic_action_forward=0x7f020008; public static final int ic_action_locate=0x7f020009; public static final int ic_action_mail=0x7f02000a; public static final int ic_action_mail_add=0x7f02000b; public static final int ic_action_microphone=0x7f02000c; public static final int ic_action_overflow=0x7f02000d; public static final int ic_action_paste=0x7f02000e; public static final int ic_action_photo=0x7f02000f; public static final int ic_action_refresh=0x7f020010; public static final int ic_action_search=0x7f020011; public static final int ic_action_select_all=0x7f020012; public static final int ic_action_send=0x7f020013; public static final int ic_action_share=0x7f020014; public static final int ic_action_star=0x7f020015; public static final int ic_action_user=0x7f020016; public static final int ic_action_user_add=0x7f020017; public static final int ic_action_video=0x7f020018; public static final int ic_drawer=0x7f020019; public static final int ic_launcher=0x7f02001a; public static final int paper_texture=0x7f02001b; public static final int splash=0x7f02001c; } public static final class id { public static final int action_back=0x7f0a0013; public static final int action_browse=0x7f0a0011; public static final int action_format=0x7f0a0012; public static final int action_forward=0x7f0a0014; public static final int content_frame=0x7f0a0001; public static final int drawer_layout=0x7f0a0000; public static final int image=0x7f0a0008; public static final int inner_content=0x7f0a0006; public static final int left_drawer=0x7f0a0002; public static final int list=0x7f0a0003; public static final int menu_search=0x7f0a0010; public static final int pager=0x7f0a0007; public static final int sauthor=0x7f0a000f; public static final int snumber=0x7f0a000e; public static final int splashscreen=0x7f0a0004; public static final int stitle=0x7f0a000d; public static final int textAuthor=0x7f0a000b; public static final int textLyrics=0x7f0a000c; public static final int textNumber=0x7f0a0009; public static final int textTitle=0x7f0a000a; public static final int textView1=0x7f0a0005; } public static final class layout { public static final int activity_main=0x7f030000; public static final int activity_search_view=0x7f030001; public static final int activity_splashscreen=0x7f030002; public static final int drawer_list_item=0x7f030003; public static final int fragment_menu_about=0x7f030004; public static final int fragment_menu_canticles=0x7f030005; public static final int fragment_menu_creeds=0x7f030006; public static final int fragment_menu_favorites=0x7f030007; public static final int fragment_menu_hymns=0x7f030008; public static final int fragment_menu_today=0x7f030009; public static final int fragment_planet=0x7f03000a; public static final int fragment_slide_page=0x7f03000b; public static final int hymnresult=0x7f03000c; } public static final class menu { public static final int main=0x7f090000; } public static final class string { /** From: file:/Users/Junior/workspace/mhb/res/values/strings.xml */ public static final int action_back=0x7f070000; public static final int action_browse=0x7f070001; public static final int action_format=0x7f070002; public static final int action_forward=0x7f070003; public static final int action_search=0x7f070004; public static final int action_settings=0x7f070005; public static final int app_name=0x7f070006; public static final int drawer_close=0x7f070007; public static final int drawer_open=0x7f070008; public static final int hymn_text=0x7f070009; public static final int search_hint=0x7f07000a; public static final int search_label=0x7f07000b; public static final int ui_author_title=0x7f07000c; public static final int ui_number_title=0x7f07000d; public static final int ui_title_title=0x7f07000e; } public static final class style { /** From: file:/Users/Junior/workspace/mhb/res/values/styles.xml Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. From: file:/Users/Junior/workspace/mhb/res/values-v11/styles.xml API 11 theme customizations can go here. From: file:/Users/Junior/workspace/mhb/res/values-v14/styles.xml API 14 theme customizations can go here. */ public static final int AppBaseTheme=0x7f080000; /** All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f080001; public static final int MainTheme=0x7f080002; public static final int MyActionBar=0x7f080003; - public static final int SplashTheme=0x7f080004; + public static final int MyActionBar_TitleTextStyle=0x7f080004; + public static final int SplashTheme=0x7f080005; } public static final class xml { public static final int searchable=0x7f040000; } }
true
false
null
null
diff --git a/src/se/team05/dialog/AlertDialogFactory.java b/src/se/team05/dialog/AlertDialogFactory.java index f93e1c3..fffdd41 100644 --- a/src/se/team05/dialog/AlertDialogFactory.java +++ b/src/se/team05/dialog/AlertDialogFactory.java @@ -1,134 +1,140 @@ /** This file is part of Personal Trainer. Personal Trainer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Personal Trainer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Personal Trainer. If not, see <http://www.gnu.org/licenses/>. (C) Copyright 2012: Daniel Kvist, Henrik Hugo, Gustaf Werlinder, Patrik Thitusson, Markus Schutzer */ package se.team05.dialog; import se.team05.R; +import se.team05.activity.MainActivity; import se.team05.content.Result; import se.team05.content.Route; import se.team05.data.DatabaseHandler; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; +import android.content.Intent; import android.widget.Toast; /** * This factory class is used to create alert dialog instances for the save * result dialog, confirm back press dialog and others. It always returns a * created instance so remember to call show() on the alert dialog that is * returned. * * @author Daniel Kvist, Patrik Thitusson * */ public class AlertDialogFactory { /** * Creates a new "save result?" dialog. It needs a context, route and result * to be displayed. If the user saves the result a toast is shown as * confirmation. If the result is not saved the dialog is simply cancelled. * * @param context * the context to operate in * @param route * the route which was executed * @param result * the result of the route * @return a new alert dialog */ public static AlertDialog newSaveResultDialog(final Context context, final Route route, final Result result) { String giveUserDistanceString = context.getString(R.string.distance_of_run) + String.valueOf((int) route.getTotalDistance()) + context.getString(R.string.km) + "\n"; String giveUserTimeString = context.getString(R.string.time_) + route.getTimePassedAsString() + "\n\n"; String giveUserResultData = giveUserDistanceString + giveUserTimeString; return new AlertDialog.Builder(context).setTitle(R.string.save_result_) .setMessage(giveUserResultData + context.getString(R.string.do_you_want_to_save_this_result_)) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DatabaseHandler databaseHandler = new DatabaseHandler(context); databaseHandler.saveResult(result); Toast.makeText(context, context.getString(R.string.result_saved) + " " + route.getName(), Toast.LENGTH_LONG).show(); + Intent intent = new Intent(context, MainActivity.class); + context.startActivity(intent); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); + Intent intent = new Intent(context, MainActivity.class); + context.startActivity(intent); } }).create(); } /** * Creates a new "confirm back" dialog that can be shown to the user when * he/she presses the back button. A good use is for example when a route is * being executed and the back button is mistakenly pressed. If the user * presses the positive button the activity (context) is finished. * * @param context * the context to operate in and finish if positive answer * @return a new alert dialog */ public static AlertDialog newConfirmBackDialog(final Context context) { return new AlertDialog.Builder(context).setTitle(R.string.discard_route_) .setMessage(R.string.do_you_really_want_to_discard_your_route_) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { ((Activity) context).finish(); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); } /** * Alerts the user that they need to do something that is specified in the * message to do something. * * @param context * the context to operate in and finish if positive answer * @param title * the title of the dialog * @param message * the message of the dialog * @return a new alert dialog */ public static AlertDialog newAlertMessageDialog(final Context context, String title, String message) { return new AlertDialog.Builder(context).setTitle(title).setMessage(message) .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); } } diff --git a/src/se/team05/dialog/SaveRouteDialog.java b/src/se/team05/dialog/SaveRouteDialog.java index 33641a0..6e7cf70 100644 --- a/src/se/team05/dialog/SaveRouteDialog.java +++ b/src/se/team05/dialog/SaveRouteDialog.java @@ -1,248 +1,249 @@ /** This file is part of Personal Trainer. Personal Trainer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Personal Trainer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Personal Trainer. If not, see <http://www.gnu.org/licenses/>. (C) Copyright 2012: Daniel Kvist, Henrik Hugo, Gustaf Werlinder, Patrik Thitusson, Markus Schutzer */ package se.team05.dialog; import se.team05.R; import se.team05.content.Route; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckedTextView; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; /** * This Dialog class is shown to the user when the user has recorded a new route * and wishes to finish recording it. It has inputs for the name and description * of the route and it also has a checkbox which is connected to a boolean value * which decides if the results that the user had (time, length) should also be * saved with the route. * * @author Daniel Kvist, Patrik Thitusson, Markus Schutzer * */ public class SaveRouteDialog extends Dialog implements View.OnClickListener { /** * This interface must be implemented by the calling Activity to be able to * receive callbacks. * */ public interface Callbacks { public void onSaveRoute(Route route, boolean saveResult); public void onDismissRoute(); public void onResumeTimer(); } private Context context; private Callbacks callbacks; private EditText nameEditTextView; private EditText descriptionEditTextView; private CheckedTextView checkedSaveResult; private Route route; /** * The constructor of the dialog takes a Context and a Callbacks as a * parameter and saves it as instances of both the Context class and as a * Callbacks instance. * * @param context * the context to run the dialog in * @param callbacks * an instance of the class that implements this class's * Callbacks interface * @param result * the results from the route including speed, distance, time */ public SaveRouteDialog(Context context, Callbacks callbacks, Route route) { super(context); this.context = context; this.callbacks = callbacks; this.route = route; } /** * This method is called by the system and sets the content view that should * be connected with this class and also the title of the dialog.It also * sets the result attributes, speed, distance and time of the route, and * adds click listeners to the buttons. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dialog_save_route); setTitle(context.getString(R.string.save_route)); this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); ((Button) findViewById(R.id.discard_button)).setOnClickListener(this); ((Button) findViewById(R.id.save_button)).setOnClickListener(this); TextView timeTextView = (TextView) findViewById(R.id.time); timeTextView.setText(route.getTimePassedAsString()); TextView distanceTextView = (TextView) findViewById(R.id.runneddistance); int routeDistance = (int) route.getTotalDistance(); String distanceText = String.valueOf(routeDistance); distanceTextView.setText(distanceText + context.getString(R.string.km)); TextView speedTextView = (TextView) findViewById(R.id.speed); double speed = (routeDistance / route.getTimePassed()) * 3.6; String speedText = String.valueOf(speed); speedTextView.setText(speedText + context.getString(R.string.km) + "/" + context.getString(R.string.h)); TextView calorieTextView = (TextView) findViewById(R.id.calories); int calories = (int) route.getCalories(); String calorieText = String.valueOf(calories); calorieTextView.setText(calorieText); nameEditTextView = ((EditText) findViewById(R.id.name)); nameEditTextView.setText(route.getName()); descriptionEditTextView = ((EditText) findViewById(R.id.description)); descriptionEditTextView.setText(route.getDescription()); checkedSaveResult = (CheckedTextView) findViewById(R.id.save_result); checkedSaveResult.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ((CheckedTextView) v).toggle(); } }); setCanceledOnTouchOutside(false); } /** * This is called when a button is clicked and decides which action to take * next. If the discard button is clicked, an alert dialog is created to * prompt the user to confirm that the route really should be discarded. If, * however, the save button was clicked we get the name, description and the * checked value and pass that on through the callback. */ @Override public void onClick(View v) { switch (v.getId()) { case R.id.discard_button: AlertDialog alertDialog = new AlertDialog.Builder(context).setTitle(R.string.discard_route_) .setMessage(R.string.do_you_really_want_to_discard_your_route_) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { callbacks.onDismissRoute(); dismiss(); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); alertDialog.show(); break; case R.id.save_button: String name = nameEditTextView.getText().toString(); if (isValidName(name)) { String description = descriptionEditTextView.getText().toString(); boolean saveResult = isSaveResultChecked(); route.setName(name); route.setDescription(description); callbacks.onSaveRoute(route, saveResult); dismiss(); } break; } } /** * Help method for testing that a string is neither empty nor null. In case * the string is empty a toast message will appear prompting the user to * choose a name. * * @param name * the string to be tested * @return true if string has some character in it, otherwise false */ private boolean isValidName(String name) { if (name.equals("") || name == null) { Toast.makeText(context, getContext().getString(R.string.must_use_a_valid_name), Toast.LENGTH_SHORT).show(); return false; } else { return true; } } - @Override - public void onBackPressed() - { - callbacks.onResumeTimer(); - } +// @Override +// public void onBackPressed() +// { +// dismiss(); +// callbacks.onResumeTimer(); +// } /** * * @return true if saveResult checkbox is checked */ public boolean isSaveResultChecked() { return checkedSaveResult.isChecked(); } /** * * @param check * sets the checkbox to true or false */ public void setSaveResultChecked(boolean check) { checkedSaveResult.setChecked(check); } /** * Gets the route * * @return the route */ public Route getRoute() { route.setName(nameEditTextView.getText().toString()); route.setDescription(descriptionEditTextView.getText().toString()); return route; } }
false
false
null
null
diff --git a/trunk/AntToMaven/src/main/java/org/cruxframework/anttomaven/Main.java b/trunk/AntToMaven/src/main/java/org/cruxframework/anttomaven/Main.java index aea49ac37..56f0d22f4 100644 --- a/trunk/AntToMaven/src/main/java/org/cruxframework/anttomaven/Main.java +++ b/trunk/AntToMaven/src/main/java/org/cruxframework/anttomaven/Main.java @@ -1,334 +1,334 @@ package org.cruxframework.anttomaven; import java.io.File; import java.io.FileFilter; import java.io.FileWriter; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.logging.Logger; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.maven.shared.invoker.DefaultInvocationRequest; import org.apache.maven.shared.invoker.DefaultInvoker; import org.apache.maven.shared.invoker.InvocationRequest; import org.apache.maven.shared.invoker.Invoker; import org.apache.maven.shared.invoker.MavenInvocationException; import org.codehaus.plexus.util.StringUtils; import org.cruxframework.anttomaven.utils.CruxFileUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { private static Logger LOG = Logger.getLogger(Main.class.getName()); private static final String JAVA_FILES = ".java"; private static final String RESOURCES_FILES = ".css .js .png .jpg .gif .jpeg"; private static final String GWT_CRUX_FILES = ".gwt.xml .module.xml .view.xml .crux.xml .template.xml .xdevice.xml"; public static void main(String[] args) { String file = (args != null) && (args.length > 0) ? args[0] : null; if(StringUtils.isEmpty(file)) { //throw new RuntimeException("Please inform a config file!"); file = "sampleInput.txt"; } String mavenHome = null; String workingDirectory = null; String targetDirectory = null; String archetypeGroupId = null; String archetypeJARArtifactId = null; String archetypeWARArtifactId = null; String archetypeCatalog = null; try { File fXmlFile = new File(file); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); NodeList globalConfigurations = doc.getElementsByTagName("globalConfigurations"); for (int temp = 0; temp < globalConfigurations.getLength(); temp++) { Node nNode = globalConfigurations.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; mavenHome = CruxFileUtils.ensureDirNoLastBars(eElement.getElementsByTagName("mavenHome").item(0).getTextContent()); workingDirectory = CruxFileUtils.ensureDirNoLastBars(eElement.getElementsByTagName("workingDirectory").item(0).getTextContent()); targetDirectory = CruxFileUtils.ensureDirNoLastBars(eElement.getElementsByTagName("targetDirectory").item(0).getTextContent()); archetypeGroupId = eElement.getElementsByTagName("archetypeGroupId").item(0).getTextContent(); archetypeJARArtifactId = eElement.getElementsByTagName("archetypeJARArtifactId").item(0).getTextContent(); archetypeWARArtifactId = eElement.getElementsByTagName("archetypeWARArtifactId").item(0).getTextContent(); archetypeCatalog = eElement.getElementsByTagName("archetypeCatalog").item(0).getTextContent(); } } NodeList nList = doc.getElementsByTagName("project"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; LOG.info("Generating project" + eElement.getAttribute("projectName")); boolean typeWAR; String groupId = null; String artifactId = null; String version = null; String packageStr = null; String moduleName = null; String resourcesFolder = "resources"; String moduleShortName = null; String moduleDescription = null; try { LOG.info("Reading params..."); typeWAR = Boolean.valueOf(eElement.getElementsByTagName("typeWAR").item(0).getTextContent()); groupId = eElement.getElementsByTagName("groupId").item(0).getTextContent(); artifactId = eElement.getElementsByTagName("artifactId").item(0).getTextContent(); version = eElement.getElementsByTagName("version").item(0).getTextContent(); packageStr = eElement.getElementsByTagName("package").item(0).getTextContent(); try{ resourcesFolder = eElement.getElementsByTagName("resourcesFolder").item(0).getTextContent(); } catch (Exception e) { LOG.info("Using default resources folder."); } moduleName = eElement.getElementsByTagName("moduleName").item(0).getTextContent(); moduleShortName = eElement.getElementsByTagName("moduleShortName").item(0).getTextContent(); moduleDescription = eElement.getElementsByTagName("moduleDescription").item(0).getTextContent(); } catch (Exception e) { throw new RuntimeException("Argument parse error.", e); } LOG.info(">>> Removing target <<<<"); try { CruxFileUtils.cleanDirectory(targetDirectory + "\\" + artifactId); } catch (Exception e) { - e.printStackTrace(); + LOG.info("Unable to clean directory: " + targetDirectory + "\\" + artifactId); } LOG.info("Generating..."); InvocationRequest request = new DefaultInvocationRequest(); List<String> params = Collections.singletonList( "archetype:generate" + " -DgroupId=" + groupId + " -DartifactId=" + artifactId + " -DarchetypeGroupId=" + archetypeGroupId + " -DarchetypeArtifactId=" + (typeWAR ? archetypeJARArtifactId : archetypeWARArtifactId) + " -DarchetypeCatalog=" + archetypeCatalog + " -Dversion=" + version + " -Dpackage=" + packageStr + " -Dmodule-name=" + moduleName + " -Dmodule-short-name=" + moduleShortName + " -Dmodule-description='" + moduleDescription + "'" + " -DinteractiveMode=false" ); request.setGoals(params); LOG.info(">>> mvn: " + params.toString()); Invoker invoker = new DefaultInvoker(); invoker.setMavenHome(new File(mavenHome)); invoker.setWorkingDirectory(new File(targetDirectory)); try { invoker.execute( request ); } catch (MavenInvocationException e) { throw new RuntimeException("Error running mvn task.", e); } LOG.info("Project created."); LOG.info("Copying files..."); copyFiles(workingDirectory, targetDirectory, packageStr.replace(".", "\\"), moduleName, artifactId, typeWAR, resourcesFolder); LOG.info("OK"); } } } catch (Exception e) { throw new RuntimeException("Global exception thrown.", e); } } private static void copyFiles(String workingDirectory, String targetDirectory, String packageStr, String moduleName, String artifactId, boolean typeWAR, String resourcesFolder) { LOG.info(">>> Copying web.xml <<<<"); //from: war\\WEB-INF\\web.xml String srcWAR = null; if(typeWAR) { srcWAR = workingDirectory + "\\" + artifactId + "\\war\\WEB-INF\\web.xml"; } else { srcWAR = workingDirectory + "\\" + artifactId + "\\war\\web.xml"; } //to: src\\main\\webapp\\WEB-INF\\web.xml String destWAR = targetDirectory + "\\" + artifactId + "\\src\\main\\webapp\\WEB-INF\\web.xml"; try { CruxFileUtils.copyFile(new File(srcWAR), new File(destWAR)); } catch (IOException e) { throw new RuntimeException("Error to copy web.xml.", e); } LOG.info(">>> Copying public folder <<<<"); //from: src\*\public String srcPublic = workingDirectory + "\\" + artifactId + "\\" + "src" + "\\" + packageStr + "\\public"; //to: src\main\resources\*\public String destPublic = targetDirectory + "\\" + artifactId + "\\" + "src\\main\\resources" + "\\" + packageStr + "\\public"; try { CruxFileUtils.copyDirectoryStructure(new File(srcPublic), new File(destPublic)); } catch (IOException e) { throw new RuntimeException("Error to copy public folder.", e); } LOG.info(">>> Copying build folder <<<<"); //from: build\* String srcBuild = workingDirectory + "\\" + artifactId + "\\" + "build"; //to: build\* String destBuild = targetDirectory + "\\" + artifactId + "\\" + "build"; try { CruxFileUtils.copyDirectoryStructure(new File(srcBuild), new File(destBuild)); } catch (IOException e) { throw new RuntimeException("Error to copy build folder.", e); } LOG.info(">>> Copying resources folder <<<<"); //from: src\*\resources\* File workingResourcesDir = CruxFileUtils.search(new File(workingDirectory + "\\" + artifactId), resourcesFolder, true); if(workingResourcesDir != null) { //Copy resources //to: src\main\resources\* try { String destResources = targetDirectory + "\\" + artifactId + "\\src\\main\\" + resourcesFolder; CruxFileUtils.copyDirectory(workingResourcesDir, new File(destResources), new FileFilter() { public boolean accept(File pathname) { return CruxFileUtils.checkExtensionFile(pathname, RESOURCES_FILES); } }, true); String destJavaResources = targetDirectory + "\\" + artifactId + "\\src\\main\\java\\" + resourcesFolder; CruxFileUtils.copyDirectory(workingResourcesDir, new File(destJavaResources), new FileFilter() { public boolean accept(File pathname) { return CruxFileUtils.checkExtensionFile(pathname, JAVA_FILES); } }, true); } catch (IOException e) { throw new RuntimeException("Error to copy resources folder.", e); } } LOG.info(">>> Copying Client and Server folders <<<<"); //Skip: //-> public folder //-> *.gwt.xml //-> *.module.xml //-> Resources: *.jpg, png, gif, ... //from: src\* String workingJavaSrc = workingDirectory + "\\" + artifactId + "\\" + "src"; //to: src\main\java\ String destJavaSrc = targetDirectory + "\\" + artifactId + "\\src\\main\\java"; try { CruxFileUtils.copyDirectory(new File(workingJavaSrc), new File(destJavaSrc), new FileFilter() { public boolean accept(File pathname) { return CruxFileUtils.checkExtensionFile(pathname, JAVA_FILES); } }, true); } catch (IOException e) { throw new RuntimeException("Error to copy Client and Server folders.", e); } LOG.info(">>> Copying *.gwt.xml *.module.xml files <<<<"); //from: src\*\*.gwt.xml String workingGWTFiles = workingDirectory + "\\" + artifactId + "\\" + "src" + "\\"; //to: src\main\resources\*\*.gwt.xml String destGWTFiles = targetDirectory + "\\" + artifactId + "\\src\\main\\resources\\"; try { CruxFileUtils.copyDirectory(new File(workingGWTFiles), new File(destGWTFiles), new FileFilter() { public boolean accept(File pathname) { return CruxFileUtils.checkExtensionFile(pathname, GWT_CRUX_FILES); } }, true); } catch (IOException e) { throw new RuntimeException("Error to copy GWT files.", e); } LOG.info(">>> Copying properties files <<<<"); //from: src\*.properties String workingPropertiesFiles = workingDirectory + "\\" + artifactId + "\\src"; //to: src\main\resources\*.properties String destPropertiesFiles = targetDirectory + "\\" + artifactId + "\\src\\main\\resources\\"; try { CruxFileUtils.copyDirectory(new File(workingPropertiesFiles), new File(destPropertiesFiles), new FileFilter() { public boolean accept(File pathname) { return CruxFileUtils.checkExtensionFile(pathname, ".properties"); } }, true); } catch (IOException e) { throw new RuntimeException("Error to copy Properties files.", e); } LOG.info(">>> Copying dependencies at pom file <<<<"); //from: build\ivy\pom.xml String workingPomFile = workingDirectory + "\\" + artifactId + "\\" + "build\\ivy\\pom.xml"; //to: pom.xml String destPomFile = targetDirectory + "\\" + artifactId + "\\" + "pom.xml"; //---->>> <dependencies>*</dependencies> try { String pomOrigContent = CruxFileUtils.readFileContent(new File(workingPomFile)); String pomDestContent = CruxFileUtils.readFileContent(new File(destPomFile)); String newDependencies = pomOrigContent.substring( pomOrigContent.indexOf("<dependencies>") + "<dependencies>".length(), pomOrigContent.lastIndexOf("</dependencies>")); StringBuffer newPom = new StringBuffer(); newPom.append(pomDestContent.substring(0, pomDestContent.indexOf("<dependencies>"))); newPom.append("<dependencies>"); newPom.append(newDependencies); newPom.append(pomDestContent.substring(pomDestContent.lastIndexOf("<dependencies>") + "</dependencies>".length(), pomDestContent.length())); FileWriter writer = new FileWriter(destPomFile); writer.write(newPom.toString()); writer.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } }
true
false
null
null
diff --git a/android/src/com/aj3/kiss/DatabaseHelper.java b/android/src/com/aj3/kiss/DatabaseHelper.java index 57af027..e75399e 100644 --- a/android/src/com/aj3/kiss/DatabaseHelper.java +++ b/android/src/com/aj3/kiss/DatabaseHelper.java @@ -1,304 +1,304 @@ package com.aj3.kiss; import java.util.Vector; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.content.ContentValues; import android.content.Context; public class DatabaseHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "KissDB"; private static final String TABLE_ITEM = "item"; private static final String TABLE_INVENTORY = "inventory"; private static final String TABLE_GROCERY = "grocery"; private static final String TABLE_CATEGORY = "category"; private static final String TABLE_UNIT = "unit"; private static final String KEY_ITEM_ID = "item_id"; private static final String KEY_CATEGORY_ID = "category_id"; private static final String KEY_UNIT_ID = "unit_id"; private static final String KEY_UPC = "upc"; private static final String KEY_ITEM_NAME = "item_name"; private static final String KEY_CATEGORY_NAME = "category_name"; private static final String KEY_UNIT_NAME = "unit_name"; private static final String KEY_QUANTITY = "quantity"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String createItemTableQuery = "CREATE TABLE IF NOT EXISTS " + TABLE_ITEM + " ( " + KEY_ITEM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_ITEM_NAME + " TEXT UNIQUE, " + KEY_CATEGORY_ID + " INTEGER, " + KEY_UNIT_ID + " TEXT, " + KEY_UPC + " TEXT )"; String createInventoryTableQuery = "CREATE TABLE IF NOT EXISTS " + TABLE_INVENTORY + " ( " + KEY_ITEM_ID + " INTEGER, " + KEY_QUANTITY + " REAL )"; String createGroceryTableQuery = "CREATE TABLE IF NOT EXISTS " + TABLE_GROCERY + " ( " + KEY_ITEM_ID + " INTEGER, " + KEY_QUANTITY + " REAL )"; String createCategoryTableQuery = "CREATE TABLE IF NOT EXISTS " + TABLE_CATEGORY + " ( " + KEY_CATEGORY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_CATEGORY_NAME + " TEXT UNIQUE )"; String createUnitTableQuery = "CREATE TABLE IF NOT EXISTS " + TABLE_UNIT + " ( " + KEY_UNIT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_UNIT_NAME + " TEXT UNIQUE )"; db.execSQL(createItemTableQuery); db.execSQL(createInventoryTableQuery); db.execSQL(createGroceryTableQuery); db.execSQL(createCategoryTableQuery); db.execSQL(createUnitTableQuery); } private void dropTables(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEM); db.execSQL("DROP TABLE IF EXISTS " + TABLE_INVENTORY); db.execSQL("DROP TABLE IF EXISTS " + TABLE_GROCERY); db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORY); db.execSQL("DROP TABLE IF EXISTS " + TABLE_UNIT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { dropTables(db); this.onCreate(db); } public void resetDatabase() { SQLiteDatabase db = this.getWritableDatabase(); dropTables(db); this.onCreate(db); } public void closeDB() { SQLiteDatabase db = this.getReadableDatabase(); if (db != null && db.isOpen()) db.close(); } public int addCategory(Category category) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_CATEGORY_NAME, category.getName()); return (int) db.insert(TABLE_CATEGORY, null, values); } public int addUnit(Unit unit) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_UNIT_NAME, unit.getName()); return (int) db.insert(TABLE_UNIT, null, values); } public int addItem(Item item) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_ITEM_NAME, item.getName()); values.put(KEY_CATEGORY_ID, item.getCategory().getId()); values.put(KEY_UNIT_ID, item.getUnit().getId()); values.put(KEY_UPC, item.getUpc()); return (int) db.insert(TABLE_ITEM, null, values); } public void addInventoryItem(ListItem item) { addTableItem(TABLE_INVENTORY, item); } public void addGroceryItem(ListItem item) { addTableItem(TABLE_GROCERY, item); } private void addTableItem(String tableName, ListItem listItem) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_ITEM_ID, listItem.getItem().getId()); values.put(KEY_QUANTITY, listItem.getQuantity()); db.insert(tableName, null, values); } public int getCategoryId(String categoryName) { String query = "SELECT " + KEY_CATEGORY_ID + " FROM " + TABLE_CATEGORY + " WHERE " + KEY_CATEGORY_NAME + " = '" + categoryName + "'"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor == null || cursor.getCount() == 0) { return -1; } cursor.moveToFirst(); return cursor.getInt(cursor.getColumnIndex(KEY_CATEGORY_ID)); } public int getUnitId(String unitName) { String query = "SELECT " + KEY_UNIT_ID + " FROM " + TABLE_UNIT + " WHERE " + KEY_UNIT_NAME + " = '" + unitName.replace("'", "\'\'") + "'"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor == null || cursor.getCount() == 0) { return -1; } cursor.moveToFirst(); return cursor.getInt(cursor.getColumnIndex(KEY_UNIT_ID)); } public int getItemId(String itemName) { String query = "SELECT " + KEY_ITEM_ID + " FROM " + TABLE_ITEM + " WHERE " + KEY_ITEM_NAME + " = '" + itemName.replace("'", "\'\'") + "'"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor == null || cursor.getCount() == 0) { return -1; } cursor.moveToFirst(); return cursor.getInt(cursor.getColumnIndex(KEY_ITEM_ID)); } private Item getItem(Cursor cursor) { Item item = new Item(); item.setId(cursor.getInt(cursor.getColumnIndex(KEY_ITEM_ID))); item.setName(cursor.getString(cursor.getColumnIndex(KEY_ITEM_NAME))); Category category = new Category(); category.setId(cursor.getInt(cursor.getColumnIndex(KEY_CATEGORY_ID))); category.setName(cursor.getString(cursor.getColumnIndex(KEY_CATEGORY_NAME))); item.setCategory(category); Unit unit = new Unit(); unit.setId(cursor.getInt(cursor.getColumnIndex(KEY_UNIT_ID))); unit.setName(cursor.getString(cursor.getColumnIndex(KEY_UNIT_NAME))); item.setUnit(unit); item.setUpc(cursor.getString(cursor.getColumnIndex(KEY_UPC))); return item; } public Item getItemByUpc(String upc) { String query = "SELECT * FROM " + TABLE_ITEM + " WHERE " + KEY_UPC + " = '" + upc + "'"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor == null || cursor.getCount() == 0) { return null; } cursor.moveToFirst(); return getItem(cursor); } public Item getItemByName(String itemName) { - String query = "SELECT * FROM " + TABLE_ITEM + " WHERE " + KEY_ITEM_NAME + " + '" + itemName.replace("'", "\'\'") + "'"; + String query = "SELECT * FROM " + TABLE_ITEM + " WHERE " + KEY_ITEM_NAME + " = '" + itemName.replace("'", "\'\'") + "'"; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); if (cursor == null || cursor.getCount() == 0) { return null; } cursor.moveToFirst(); return getItem(cursor); } public Vector<ListItem> getGrocery() { return getList(TABLE_GROCERY); } public Vector<ListItem> getInventory() { return getList(TABLE_INVENTORY); } private Vector<ListItem> getList(String tableName) { Vector<ListItem> list = new Vector<ListItem>(); SQLiteDatabase db = this.getReadableDatabase(); String query = "SELECT * FROM " + tableName + " JOIN " + TABLE_ITEM + " JOIN " + TABLE_CATEGORY + " JOIN " + TABLE_UNIT + " ON " + tableName + "." + KEY_ITEM_ID + " = " + TABLE_ITEM + "." + KEY_ITEM_ID + " AND " + TABLE_ITEM + "." + KEY_CATEGORY_ID + " = " + TABLE_CATEGORY + "." + KEY_CATEGORY_ID + " AND " + TABLE_ITEM + "." + KEY_UNIT_ID + " = " + TABLE_UNIT + "." + KEY_UNIT_ID; Cursor cursor = db.rawQuery(query, null); if (cursor.moveToFirst()) { do { ListItem listItem = new ListItem(); listItem.setItem(getItem(cursor)); listItem.setQuantity(cursor.getDouble(cursor.getColumnIndex(KEY_QUANTITY))); list.add(listItem); } while (cursor.moveToNext()); } return list; } public int updateItem(Item item) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_ITEM_NAME, item.getName()); values.put(KEY_CATEGORY_ID, item.getCategory().getId()); values.put(KEY_UNIT_ID, item.getUnit().getId()); values.put(KEY_UPC, item.getUpc()); return db.update(TABLE_ITEM, values, KEY_ITEM_ID + " = ?", new String[] { String.valueOf(item.getId()) }); } public int updateGroceryItem(ListItem listItem) { return updateListItem(TABLE_GROCERY, listItem); } public int updateInventoryItem(ListItem listItem) { return updateListItem(TABLE_INVENTORY, listItem); } private int updateListItem(String tableName, ListItem listItem) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_QUANTITY, listItem.getQuantity()); return db.update(tableName, values, KEY_ITEM_ID + " = ?", new String[] { String.valueOf(listItem.getItem().getId()) }); } public void deleteGroceryItem(ListItem listItem) { deleteListItem(TABLE_GROCERY, listItem); } public void deleteInventoryItem(ListItem listItem) { deleteListItem(TABLE_INVENTORY, listItem); } private void deleteListItem(String tableName, ListItem listItem) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(tableName, KEY_ITEM_ID + " = ?", new String[] {String.valueOf(listItem.getItem().getId()) }); } }
true
false
null
null
diff --git a/src/main/java/de/fhb/twitalyse/spout/TwitterStreamSpout.java b/src/main/java/de/fhb/twitalyse/spout/TwitterStreamSpout.java index f45fc09..7dd9928 100644 --- a/src/main/java/de/fhb/twitalyse/spout/TwitterStreamSpout.java +++ b/src/main/java/de/fhb/twitalyse/spout/TwitterStreamSpout.java @@ -1,244 +1,244 @@ /* * Copyright (C) 2012 Michael Koppen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.fhb.twitalyse.spout; import backtype.storm.spout.SpoutOutputCollector; import backtype.storm.task.TopologyContext; import backtype.storm.testing.AckFailDelegate; import backtype.storm.topology.IRichSpout; import backtype.storm.topology.OutputFieldsDeclarer; import backtype.storm.tuple.Fields; import backtype.storm.tuple.Values; import backtype.storm.utils.InprocMessaging; import backtype.storm.utils.Utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import redis.clients.jedis.Jedis; import redis.clients.jedis.exceptions.JedisException; import twitter4j.Status; import twitter4j.StatusDeletionNotice; import twitter4j.StatusListener; import twitter4j.TwitterException; import twitter4j.TwitterStream; import twitter4j.TwitterStreamFactory; import twitter4j.auth.AccessToken; import twitter4j.conf.ConfigurationBuilder; import twitter4j.json.DataObjectFactory; /** * This Spout connects to the Twitter API and opens up a Stream. The Spout * listens for new Twitter Stati posted on the public Twitter Channel and push * it in the System. * * @author Michael Koppen <[email protected]> */ public class TwitterStreamSpout implements IRichSpout, StatusListener { private final static Logger LOGGER = Logger.getLogger(TwitterStreamSpout.class.getName()); //Keys die die App identifizieren private final String CONSUMER_KEY; private final String CONSUMER_KEY_SECURE; //Keys die den Account des Users identifizieren private final String TOKEN; private final String TOKEN_SECRET; private int id; private AckFailDelegate ackFailDelegate; private transient SpoutOutputCollector collector; private transient TwitterStream twitterStream; private String host; private int port; public TwitterStreamSpout(String consumerKey, String consumerKeySecure, String token, String tokenSecret, String host, int port) { id = InprocMessaging.acquireNewPort(); this.CONSUMER_KEY = consumerKey; this.CONSUMER_KEY_SECURE = consumerKeySecure; this.TOKEN = token; this.TOKEN_SECRET = tokenSecret; this.host = host; this.port = port; } public void setAckFailDelegate(AckFailDelegate d) { ackFailDelegate = d; } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { declarer.declare(new Fields("id", "json")); } @Override public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) { this.collector = collector; //enable JSONStore ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setJSONStoreEnabled(true); TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(cb.build()); twitterStream = twitterStreamFactory.getInstance(); AccessToken givenAccessToken = new AccessToken(TOKEN, TOKEN_SECRET); twitterStream.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECURE); twitterStream.setOAuthAccessToken(givenAccessToken); twitterStream.addListener(this); twitterStream.sample(); } @Override public void onStatus(Status status) { String json = DataObjectFactory.getRawJSON(status); + id = InprocMessaging.acquireNewPort(); InprocMessaging.sendMessage(id, new Values(status.getId(), json)); } @Override public void nextTuple() { List<Object> value = (List<Object>) InprocMessaging.pollMessage(id); if (value == null) { Utils.sleep(50); } else { try { Jedis jedis = new Jedis(host, port); jedis.getClient().setTimeout(9999); Date today = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("dd_MM_yyyy"); // Saves # of all stati jedis.incr("#stati"); // Saves # of stati today jedis.incr("#stati_" + sdf.format(today)); // Status ID + Status-JSON - collector.emit(new Values(value.get(0), value.get(1))); + collector.emit(new Values(value.get(0), value.get(1)), id); jedis.disconnect(); } catch (JedisException e) { LOGGER.log(Level.SEVERE, "Exception: {0}", e); } } } @Override public void close() { twitterStream.shutdown(); - } @Override public void ack(Object msgId) { if (ackFailDelegate != null) { ackFailDelegate.ack(msgId); } } @Override public void fail(Object msgId) { if (ackFailDelegate != null) { ackFailDelegate.fail(msgId); } } @Override public void onException(Exception ex) { TwitterException tex = (TwitterException) ex; if (400 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "Rate limit texceeded. Clients may not make more than {0} requests per hour. \nThe ntext reset is {1}", new Object[]{tex.getRateLimitStatus().getHourlyLimit(), tex.getRateLimitStatus().getResetTime()}); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } else if (401 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "Authentication credentials were missing or incorrect."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } else if (403 == tex.getStatusCode()) { LOGGER.log(Level.SEVERE, "Duplicated status."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } else if (404 == tex.getStatusCode()) { LOGGER.log(Level.SEVERE, "The URI requested is invalid or the resource requested, such as a user, does not exists."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } else if (406 == tex.getStatusCode()) { LOGGER.log(Level.SEVERE, "Request returned - invalid format is specified in the request."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } else if (420 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "Too many logins with your account in a short time."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } else if (500 == tex.getStatusCode()) { LOGGER.log(Level.SEVERE, "Something is broken. Please post to the group so the Twitter team can investigate."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } else if (502 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "Twitter is down or being upgraded."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } else if (503 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "The Twitter servers are up, but overloaded with requests. Try again later."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } else if (-1 == tex.getStatusCode()) { close(); LOGGER.log(Level.SEVERE, "Can not connect to the internet or the host is down."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } else { close(); LOGGER.log(Level.SEVERE, "Unknown twitter-error occured."); LOGGER.log(Level.SEVERE, "Exception: {0},\nMessage: {1},\nCause: {2}", new Object[]{tex, tex.getMessage(), tex.getCause()}); } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } @Override public void onScrubGeo(long userId, long upToStatusId) { } @Override public void activate() { } @Override public void deactivate() { } @Override public Map<String, Object> getComponentConfiguration() { return new HashMap<String, Object>(); } }
false
false
null
null
diff --git a/source/java/src/main/java/cmf/bus/support/InMemoryEnvelopeBus.java b/source/java/src/main/java/cmf/bus/support/InMemoryEnvelopeBus.java index c0e63bd..18a28cb 100644 --- a/source/java/src/main/java/cmf/bus/support/InMemoryEnvelopeBus.java +++ b/source/java/src/main/java/cmf/bus/support/InMemoryEnvelopeBus.java @@ -1,70 +1,71 @@ package cmf.bus.support; import java.util.LinkedList; import java.util.List; import cmf.bus.Envelope; import cmf.bus.IEnvelopeBus; import cmf.bus.IRegistration; public class InMemoryEnvelopeBus implements IEnvelopeBus { protected List<IRegistration> registrationList; public InMemoryEnvelopeBus() { registrationList = new LinkedList<IRegistration>(); } protected void dispatch( final Envelope envelope, final List<IRegistration> registrationList) { new Thread() { @Override public void run() { for (IRegistration registration : registrationList) { try { registration.handle(envelope); } catch (Exception e) { try { registration.handleFailed(envelope, e); } catch (Exception failedToFail) { failedToFail.printStackTrace(); } } } } }.run(); } @Override public synchronized void register(IRegistration registration) { registrationList.add(registration); } @Override public synchronized void send(Envelope envelope) { List<IRegistration> registrations = new LinkedList<IRegistration>(); for (IRegistration registration : registrationList) { if (null != registration.getFilterPredicate() - && registration.getFilterPredicate().filter(envelope)){ + && !registration.getFilterPredicate().filter(envelope)){ + registrations.add(registration); } else { registrations.add(registration); } } dispatch(envelope, registrations); } @Override public synchronized void unregister(IRegistration registration) { registrationList.remove(registration); } @Override public void dispose() { // TODO Auto-generated method stub } }
true
false
null
null
diff --git a/service/src/com/chaman/dao/Dao.java b/service/src/com/chaman/dao/Dao.java index 4bac40a2..9a12491f 100644 --- a/service/src/com/chaman/dao/Dao.java +++ b/service/src/com/chaman/dao/Dao.java @@ -1,40 +1,51 @@ package com.chaman.dao; import com.chaman.model.EventLocationCapable; import com.chaman.model.Following; import com.chaman.model.User; import com.chaman.model.Vote; import com.googlecode.objectify.ObjectifyService; import com.googlecode.objectify.util.DAOBase; public class Dao extends DAOBase { static { try { ObjectifyService.register(Following.class); ObjectifyService.register(EventLocationCapable.class); ObjectifyService.register(User.class); ObjectifyService.register(Vote.class); } catch (Exception ex) { System.out.println(ex.toString()); } } public Dao() { super(); + // TODO find the best way to register the classes + try { + + ObjectifyService.register(Following.class); + ObjectifyService.register(EventLocationCapable.class); + ObjectifyService.register(User.class); + ObjectifyService.register(Vote.class); + } catch (Exception ex) { + + System.out.println(ex.toString()); + } } /** Your DAO can have your own useful methods */ // public MyThing getOrCreateMyThing(long id) // { // MyThing found = ofy().find(clazz, id); // if (found == null) // return new MyThing(id); // else // return found; // } }
true
false
null
null
diff --git a/src/com/delin/speedlogger/Activities/DevPrefsActivity.java b/src/com/delin/speedlogger/Activities/DevPrefsActivity.java index 68093fa..f743f03 100644 --- a/src/com/delin/speedlogger/Activities/DevPrefsActivity.java +++ b/src/com/delin/speedlogger/Activities/DevPrefsActivity.java @@ -1,43 +1,47 @@ package com.delin.speedlogger.Activities; import java.io.File; import com.delin.speedlogger.R; import android.os.Bundle; import android.os.Environment; import android.preference.ListPreference; import android.preference.PreferenceActivity; public class DevPrefsActivity extends PreferenceActivity { static final String CREATOR_VALUE = "SpeedLogger"; static final String STORAGE_DIR = Environment.getExternalStorageDirectory().getPath() +"/"+CREATOR_VALUE; static final String GPS_DIR_NAME = "FileGPS"; static final String GPS_DIR_PATH = STORAGE_DIR + "/" + GPS_DIR_NAME; ListPreference gpxFiles; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); String prefsName = getString(R.string.DevPrefs); getPreferenceManager().setSharedPreferencesName(prefsName); addPreferencesFromResource(R.xml.dev_preferences); gpxFiles = (ListPreference) findPreference(getString(R.string.FileWithGPS)); FindGPX(); } // adds all filenames from GPS folder into the gpx list private void FindGPX() { File dir = new File(GPS_DIR_PATH); try{ if(!dir.exists()) dir.mkdirs();} catch(Exception e){return;} - String[] filenames = dir.list(); - if (filenames.length > 0) { - gpxFiles.setEntries(filenames); - for(int i=0; i<filenames.length; ++i) { - filenames[i] = GPS_DIR_NAME + "/" + filenames[i]; + String[] filenameEntries = dir.list(); + String[] filenameValues; + if (filenameEntries.length > 0) { + // list entries + gpxFiles.setEntries(filenameEntries); + // list values + filenameValues = filenameEntries.clone(); + for(int i=0; i<filenameValues.length; ++i) { + filenameValues[i] = GPS_DIR_NAME + "/" + filenameValues[i]; } - gpxFiles.setEntryValues(filenames); + gpxFiles.setEntryValues(filenameValues); if (gpxFiles.getValue() == null) gpxFiles.setValueIndex(0); } } }
false
true
private void FindGPX() { File dir = new File(GPS_DIR_PATH); try{ if(!dir.exists()) dir.mkdirs();} catch(Exception e){return;} String[] filenames = dir.list(); if (filenames.length > 0) { gpxFiles.setEntries(filenames); for(int i=0; i<filenames.length; ++i) { filenames[i] = GPS_DIR_NAME + "/" + filenames[i]; } gpxFiles.setEntryValues(filenames); if (gpxFiles.getValue() == null) gpxFiles.setValueIndex(0); } }
private void FindGPX() { File dir = new File(GPS_DIR_PATH); try{ if(!dir.exists()) dir.mkdirs();} catch(Exception e){return;} String[] filenameEntries = dir.list(); String[] filenameValues; if (filenameEntries.length > 0) { // list entries gpxFiles.setEntries(filenameEntries); // list values filenameValues = filenameEntries.clone(); for(int i=0; i<filenameValues.length; ++i) { filenameValues[i] = GPS_DIR_NAME + "/" + filenameValues[i]; } gpxFiles.setEntryValues(filenameValues); if (gpxFiles.getValue() == null) gpxFiles.setValueIndex(0); } }
diff --git a/src/fr/iutvalence/java/mp/thelasttyper/client/data/Word.java b/src/fr/iutvalence/java/mp/thelasttyper/client/data/Word.java index 8c417bb..e5b5b90 100644 --- a/src/fr/iutvalence/java/mp/thelasttyper/client/data/Word.java +++ b/src/fr/iutvalence/java/mp/thelasttyper/client/data/Word.java @@ -1,113 +1,112 @@ package fr.iutvalence.java.mp.thelasttyper.client.data; /** * This class contains all the informations about a word. The word have to be * destroyed in the game. * * @author culasb */ public class Word { /** * Word score value. When the this word is killed by a player, this value is * added to the player's score this value cannot be changed * */ private final int value; /** * Word's level * * this value cannot be changed */ private final int difficulty; /** * Word's content (string) this value cannot be changed */ private final String content; /** * Instantiation of new word with a given value, a given level, and a given * content. * * @param value * Default score Value for this word * @param difficulty * Word level * @param content * the string */ public Word(int value, int difficulty, String content) { this.value = value; this.difficulty = difficulty; this.content = content; } /** * static method to get the difficulty of a given string * @param s the string which need to be tested * @return the difficulty */ public static int getDifficulty(String s) { int i = s.length(); - if (i ==0) - //TODO throw exception EmptyStringException + if (i ==0) return 0; if (i < 4) return 1; else if (i< 5) return 2; else if (i< 6) return 3; else if (i <8) return 4; //else return 5; } /** * this static method return the value of a string. * @param s the given which need to be tested * @return its value. */ public static int getValue (String s){ return (Word.getDifficulty(s) * 100); } /** * get the score value of the Word * * @return score value */ public int getValue() { return this.value; } /** * get the level of the Word * * @return word's level */ public int getDifficulty() { return this.difficulty; } /** * get the content of the Word * * @return word's content. */ public String getContent() { return this.content; } }
true
true
public static int getDifficulty(String s) { int i = s.length(); if (i ==0) //TODO throw exception EmptyStringException if (i < 4) return 1; else if (i< 5) return 2; else if (i< 6) return 3; else if (i <8) return 4; //else return 5; }
public static int getDifficulty(String s) { int i = s.length(); if (i ==0) return 0; if (i < 4) return 1; else if (i< 5) return 2; else if (i< 6) return 3; else if (i <8) return 4; //else return 5; }
diff --git a/src/com/flaptor/util/Statistics.java b/src/com/flaptor/util/Statistics.java index 1cc54bb..8ceed68 100644 --- a/src/com/flaptor/util/Statistics.java +++ b/src/com/flaptor/util/Statistics.java @@ -1,198 +1,206 @@ /* Copyright 2008 Flaptor (flaptor.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.flaptor.util; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import org.apache.log4j.Logger; import com.flaptor.hist4j.AdaptiveHistogram; /** * class for keeping statistics of events. Events can be registered and kept track of. * Event data is collected in periods. You can get the accumulated data from start, the data from the * last period and the data gathered in this (unfinished) period. * * There is a singleton instance configured in either common.properties (statistics.period) * or 1 minute if thats missing * * @author Martin Massera */ public class Statistics { private static final Logger logger = Logger.getLogger(com.flaptor.util.Execute.whoAmI()); private static final Statistics instance; static { int time; try{ time = Config.getConfig("common.properties").getInt("statistics.period"); } catch (IllegalStateException e) { time = 60000; logger.warn("statistics.period not found in common.properties"); } instance = new Statistics(time); } //returns a static instance that updates every minute public static Statistics getStatistics() { return instance; } //map of event -> AccumulatedStats, thisPeriodStats, lastPeriodStats private Map<String, EventStats[]> eventStatistics = new HashMap<String, EventStats[]>(); private int periodLength; Statistics(int periodLength) { this.periodLength = periodLength; new Timer(true).schedule(new StatisticsTask(), 0, periodLength); } /** * notifies the value of an event * @param eventName * @param value */ public void notifyEventValue(String eventName, float value) { EventStats[] eventStats = getOrCreateStats(eventName); eventStats[0].addSample(value); eventStats[1].addSample(value); } /** * notifies an error of an event * @param eventName */ public void notifyEventError(String eventName) { EventStats[] eventStats = getOrCreateStats(eventName); eventStats[0].addError(); eventStats[1].addError(); } private EventStats[] getOrCreateStats(String eventName) { EventStats[] eventStats = eventStatistics.get(eventName); if (eventStats == null) { eventStats = new EventStats[] {new EventStats(), new EventStats(), new EventStats()}; eventStatistics.put(eventName, eventStats); } return eventStats; } public Set<String> getEvents() { return eventStatistics.keySet(); } /** * * @param eventName * @return the statistics in form <accumulatedStats, thisPeriodStats, lastPeriodStats> */ public Triad<EventStats,EventStats,EventStats> getStats(String eventName) { EventStats[] eventStats = eventStatistics.get(eventName); if (eventStats == null) return null; return new Triad<EventStats,EventStats,EventStats>(eventStats[0],eventStats[1],eventStats[2]); } public EventStats getAccumulatedStats(String eventName) { return eventStatistics.get(eventName)[0]; } public EventStats getThisPeriodStats(String eventName) { return eventStatistics.get(eventName)[1]; } public EventStats getLastPeriodStats(String eventName) { return eventStatistics.get(eventName)[2]; } public void clearAccumulatedStats(String eventName) { eventStatistics.get(eventName)[0].clear(); } public int getPeriodLength() { return periodLength; } public static class EventStats implements Serializable { public long numCorrectSamples; public long numErrors; public float errorRatio; - public float sampleAverage; + private float sampleSum; public float maximum; public float minimum; AdaptiveHistogram histogram = new AdaptiveHistogram(); public EventStats() { clear(); } private synchronized void clear() { numErrors = 0; numCorrectSamples = 0; errorRatio = 0; - sampleAverage = 0; + sampleSum = 0; maximum= -100000000000000.0f; minimum= 100000000000000.0f; histogram.reset(); } private synchronized void addSample(float value) { numCorrectSamples++; - sampleAverage = (numCorrectSamples * sampleAverage + value) / numCorrectSamples ; + sampleSum += value; if (value < minimum) minimum = value; if (value > maximum) maximum = value; histogram.addValue(value); errorRatio = numErrors / (numErrors + numCorrectSamples); } private synchronized void addError() { numErrors++; errorRatio = numErrors / (numErrors + numCorrectSamples); } + public AdaptiveHistogram getHistogram() { + return histogram; + } + + public float getSampleAverage() { + return sampleSum / numCorrectSamples; + } + public String toString() { return " correct samples: " + numCorrectSamples + " \n" + " error samples: " + numErrors +" \n" + " total samples: " + (numCorrectSamples + numErrors) + "\n" + " error ratio: " + errorRatio + "\n" + " ------------------------ \n" + " max sample: " + histogram.getValueForPercentile(100) + "\n" + " min sample: " + histogram.getValueForPercentile(0) + "\n" + - " median sample: " + histogram.getValueForPercentile(50); + " median sample: " + histogram.getValueForPercentile(50) + "\n"; } } private class StatisticsTask extends TimerTask { public void run() { for (EventStats[] stats : eventStatistics.values()) { synchronized(stats) { stats[2] = stats[1]; stats[1] = new EventStats(); } } } } }
false
false
null
null
diff --git a/PullToRefreshLibrary/src/au/com/jtribe/pulltorefreshlib/PullToRefreshAnimation.java b/PullToRefreshLibrary/src/au/com/jtribe/pulltorefreshlib/PullToRefreshAnimation.java index 01c5508..fcd78f7 100644 --- a/PullToRefreshLibrary/src/au/com/jtribe/pulltorefreshlib/PullToRefreshAnimation.java +++ b/PullToRefreshLibrary/src/au/com/jtribe/pulltorefreshlib/PullToRefreshAnimation.java @@ -1,197 +1,201 @@ package au.com.jtribe.pulltorefreshlib; import android.content.Context; import android.content.res.Resources; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; /** * Created by tosa on 8/14/13. */ public abstract class PullToRefreshAnimation { private static final int IDLE_DISTANCE = 5; private static final float PULL_RESISTANCE = 1.1f; protected final ImageView mAnimationView; protected final Context mContext; protected final PullToRefreshCallback mRefreshCallback; private final float mDensityFactor; protected int mCurrentIndex; protected PullToRefreshAnimationCallback mAnimationCallback; protected final View mHeaderView; private boolean mRefreshStarted; private State state = State.PULL_TO_REFRESH; private float mTotalDistance; private float mPreviousY; private float mScrollStartY; + private float mPreviousX; protected abstract void loadAnimation(); protected abstract void setMarginForAnimationView(int i); protected abstract void setAnimationForFrame(int mCurrentIndex); protected abstract float getMarginStart(); protected abstract float getAnimationHeight(); protected abstract float getAnimationEndHeight(); protected abstract int getAnimationFrames(); protected abstract float getAnimationStart(); protected abstract void animateRefresh(); protected abstract void animateBackAndReset(); protected abstract void resetHeader(); public abstract boolean onDown(MotionEvent event); public PullToRefreshAnimation(Context context, int layoutId, int animationViewId, int offset, PullToRefreshCallback callback) { this.mContext = context; LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mHeaderView = inflater.inflate(layoutId, null, false); mAnimationView = (ImageView) mHeaderView.findViewById(animationViewId); Resources r = context.getResources(); mDensityFactor = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, r.getDisplayMetrics()); mRefreshCallback = callback; } public View getHeader() { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mAnimationView .getLayoutParams(); params.setMargins(0, (int) -getAnimationEndHeight(), 0, 0); mAnimationView.setLayoutParams(params); return mHeaderView; } public void setPullToRefreshAnimationCallback(PullToRefreshAnimationCallback callback) { mAnimationCallback = callback; } public boolean onDownIntercept(MotionEvent event) { boolean intercept = false; mTotalDistance = 0; if (mAnimationCallback.getFirstVisiblePosition() == 0) { mPreviousY = event.getY(); + mPreviousX = event.getX(); } else { mPreviousY = -1; } // Remember where have we started mScrollStartY = event.getY(); return intercept; } public boolean onMoveIntercept(MotionEvent event) { + float yMovment = event.getY() - mPreviousY; + float xMovment = event.getX() - mPreviousX; if ((mPreviousY != -1 - && mAnimationCallback.getFirstVisiblePosition() == 0 - && event.getY() - mScrollStartY > IDLE_DISTANCE)) { + && mAnimationCallback.getFirstVisiblePosition() == 0 && + event.getY() - mScrollStartY > IDLE_DISTANCE) && Math.abs(yMovment) > Math.abs(xMovment)) { return true; // intercept this so we can do the animation } return false; } public boolean onMove(MotionEvent event) { if ((mPreviousY != -1 && mAnimationCallback.getFirstVisiblePosition() == 0 && event.getY() - mScrollStartY > IDLE_DISTANCE) || mRefreshStarted) { float y = event.getY(); float diff = y - mPreviousY; if (diff > 0) diff /= PULL_RESISTANCE; float newTotalDistance = mTotalDistance + diff; if (newTotalDistance != mTotalDistance) { mRefreshStarted = true; if (mTotalDistance <= getAnimationStart()) { mTotalDistance += (y - mPreviousY) * (4.2/mDensityFactor); } else { mTotalDistance = newTotalDistance; } if (mTotalDistance <= getAnimationEndHeight() + getMarginStart()) { setMarginForAnimationView((int) (mTotalDistance - getAnimationEndHeight())); } Log.d("PULLTOREFRESH", "TOTAL: " + mTotalDistance); if (mTotalDistance <= getAnimationEndHeight()) { float range = (getAnimationEndHeight() - getAnimationStart() - getMarginStart()) / getAnimationFrames(); int image_index = (int) ((mTotalDistance - getAnimationStart() - getMarginStart()) / range); int chosen_index = image_index; if (image_index >= 0 && image_index < getAnimationFrames()) { mCurrentIndex = chosen_index; setAnimationForFrame(mCurrentIndex); } else if (image_index > 0) { setAnimationForFrame(getAnimationFrames() - 1); } else { setAnimationForFrame(0); } if (chosen_index > getAnimationFrames() * 0.75 && state != State.REFRESHING) { state = State.RELEASE_TO_REFRESH; } else { state = State.PULL_TO_REFRESH; } } } mPreviousY = y; return true; } return false; } public boolean onUp(MotionEvent event) { boolean intercept = false; if (mPreviousY != -1 && (state == State.RELEASE_TO_REFRESH || (mAnimationCallback.getFirstVisiblePosition() == 0))) { switch (state) { case RELEASE_TO_REFRESH: state = State.REFRESHING; animateRefresh(); break; case PULL_TO_REFRESH: animateBackAndReset(); break; } } if (mRefreshStarted) { mRefreshStarted = false; intercept = true; } return intercept; } public boolean onCancel(MotionEvent event) { resetHeader(); return false; } public void refreshComplete() { state = State.PULL_TO_REFRESH; resetHeader(); } private static enum State { PULL_TO_REFRESH, RELEASE_TO_REFRESH, REFRESHING } }
false
false
null
null
diff --git a/server-enterprise/src/main/java/org/neo4j/server/enterprise/EnterpriseDatabase.java b/server-enterprise/src/main/java/org/neo4j/server/enterprise/EnterpriseDatabase.java index d42d43c8..4b5e1f7a 100644 --- a/server-enterprise/src/main/java/org/neo4j/server/enterprise/EnterpriseDatabase.java +++ b/server-enterprise/src/main/java/org/neo4j/server/enterprise/EnterpriseDatabase.java @@ -1,84 +1,84 @@ /** * Copyright (c) 2002-2012 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * GNU Affero General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.server.enterprise; import java.util.Map; import org.apache.commons.configuration.Configuration; import org.neo4j.kernel.EmbeddedGraphDatabase; import org.neo4j.kernel.GraphDatabaseAPI; import org.neo4j.kernel.HighlyAvailableGraphDatabase; import org.neo4j.server.configuration.Configurator; import org.neo4j.server.database.CommunityDatabase; import org.neo4j.server.database.GraphDatabaseFactory; public class EnterpriseDatabase extends CommunityDatabase { enum DatabaseMode implements GraphDatabaseFactory { SINGLE { @Override public GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ) { return new EmbeddedGraphDatabase( databaseStoreDirectory, databaseProperties ); } }, HA { @Override public GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ) { return new HighlyAvailableGraphDatabase( databaseStoreDirectory, databaseProperties ); } }; @Override public abstract GraphDatabaseAPI createDatabase( String databaseStoreDirectory, Map<String, String> databaseProperties ); } public EnterpriseDatabase(Configuration serverConfig) { super(serverConfig); } @Override @SuppressWarnings("deprecation") public void start() throws Throwable { try { GraphDatabaseFactory factory = DatabaseMode.valueOf( serverConfig.getString( Configurator.DB_MODE_KEY, DatabaseMode.SINGLE.name() ).toUpperCase() ); this.graph = factory.createDatabase( serverConfig.getString(Configurator.DATABASE_LOCATION_PROPERTY_KEY, Configurator.DEFAULT_DATABASE_LOCATION_PROPERTY_KEY), loadNeo4jProperties()); log.info( "Successfully started database" ); } catch(Exception e) { log.error( "Failed to start database.", e); throw e; } } } diff --git a/server-enterprise/src/main/java/org/neo4j/server/enterprise/EnterpriseNeoServer.java b/server-enterprise/src/main/java/org/neo4j/server/enterprise/EnterpriseNeoServer.java index 60188e36..1c145125 100644 --- a/server-enterprise/src/main/java/org/neo4j/server/enterprise/EnterpriseNeoServer.java +++ b/server-enterprise/src/main/java/org/neo4j/server/enterprise/EnterpriseNeoServer.java @@ -1,46 +1,46 @@ /** * Copyright (c) 2002-2012 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * GNU Affero General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.server.enterprise; import org.neo4j.server.advanced.AdvancedNeoServer; import org.neo4j.server.configuration.Configurator; import org.neo4j.server.startup.healthcheck.StartupHealthCheck; public class EnterpriseNeoServer extends AdvancedNeoServer { public EnterpriseNeoServer( Configurator configurator ) { this.configurator = configurator; init(); } @Override protected StartupHealthCheck createHealthCheck() { final StartupHealthCheck parentCheck = super.createHealthCheck(); return new StartupHealthCheck( new Neo4jHAPropertiesMustExistRule() ){ @Override public boolean run(){ return parentCheck.run() && super.run(); } }; } }
false
false
null
null
diff --git a/src/husacct/define/domain/services/DomainGateway.java b/src/husacct/define/domain/services/DomainGateway.java index f44ebeb2..01720dde 100644 --- a/src/husacct/define/domain/services/DomainGateway.java +++ b/src/husacct/define/domain/services/DomainGateway.java @@ -1,128 +1,129 @@ package husacct.define.domain.services; import husacct.define.domain.SoftwareArchitecture; import husacct.define.domain.services.stateservice.StateService; import husacct.define.task.AppliedRuleController; import husacct.define.task.DefinitionController; import husacct.define.task.JtreeController; import husacct.define.task.SoftwareUnitController; import husacct.define.task.components.AnalyzedModuleComponent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class DomainGateway { private static DomainGateway instance = null; private SoftwareUnitController unitController; private AppliedRuleController appliedRuleController; public static DomainGateway getInstance() { if (instance == null) { return instance = new DomainGateway(); } else { return instance; } } public boolean addModule(String name, String description, String type) { DefinitionController.getInstance().addModule(name, description, type); return true; } public void moveLayerUp(long layerId) { DefinitionController.getInstance().moveLayerUp(layerId); StateService.instance().layerUp(layerId); } public void moveLayerDown(long layerId) { DefinitionController.getInstance().moveLayerDown(layerId); StateService.instance().layerDown(layerId); } public void updateModule(String moduleName, String moduleDescription, String type) { DefinitionController.getInstance().updateModule(moduleName, moduleDescription, type); } public boolean saveAnalzedModule(ArrayList<AnalyzedModuleComponent> units) { long id = DefinitionController.getInstance().getSelectedModuleId(); SoftwareUnitController softwareUnitController = new SoftwareUnitController( id); softwareUnitController.save(units); return true; } public AnalyzedModuleComponent getRootModel() { AnalyzedModuleComponent root = StateService.instance().getRootModel(); JtreeController.instance().setTreeModel(root); return root; } public void removeSoftwareUnits(List<String> selectedModules, List<String> types) { DefinitionController.getInstance().removeSoftwareUnits(selectedModules, types); StateService.instance().removeSoftwareUnit(selectedModules); } public void removeModuleById(long moduleId) { DefinitionController.getInstance().removeModuleById(moduleId); } public void selectModule(long id) { DefinitionController.getInstance().setSelectedModuleId(id); } public void saveRegEx(ArrayList<AnalyzedModuleComponent> components, String enteredRegEx) { unitController = new SoftwareUnitController(getSelectedModuleId()); unitController.saveRegEx(components, enteredRegEx); } public long getSelectedModuleId() { return DefinitionController.getInstance().getSelectedModuleId(); } public void updateModule(String moduleName, String moduleDescription) { DefinitionController.getInstance().updateModule(moduleName, moduleDescription); } public void updateFacade(String moduleName) { DefinitionController.getInstance().updateFacade(moduleName); } public void addException(HashMap<String, Object> ruleDetails) { long moduleId = (long) ruleDetails.get("moduleFromId"); // appliedruleController = new // AppliedRuleController(ruleDetails.get("rule"), moduleId); } public void removeRules(List<Long> selectedRules) { + SoftwareArchitecture.getInstance().removeAppliedRule(selectedRules); } public AnalyzedModuleComponent treeModel() { return JtreeController.instance().getRootOfModel(); } public void editRegEx(ArrayList<AnalyzedModuleComponent> components, String editingRegEx) { new SoftwareUnitController(getSelectedModuleId()).editRegEx(components, editingRegEx); } } diff --git a/src/husacct/define/task/DefinitionController.java b/src/husacct/define/task/DefinitionController.java index b0c302c9..f5413e8f 100644 --- a/src/husacct/define/task/DefinitionController.java +++ b/src/husacct/define/task/DefinitionController.java @@ -1,456 +1,458 @@ package husacct.define.task; import husacct.ServiceProvider; import husacct.define.domain.appliedrule.AppliedRuleStrategy; import husacct.define.domain.module.ModuleStrategy; import husacct.define.domain.module.modules.Component; import husacct.define.domain.module.modules.Facade; import husacct.define.domain.services.AppliedRuleDomainService; import husacct.define.domain.services.DefaultRuleDomainService; import husacct.define.domain.services.ModuleDomainService; import husacct.define.domain.services.SoftwareUnitDefinitionDomainService; import husacct.define.domain.services.WarningMessageService; +import husacct.define.domain.services.stateservice.StateService; import husacct.define.presentation.jpanel.DefinitionJPanel; import husacct.define.presentation.utils.JPanelStatus; import husacct.define.presentation.utils.UiDialogs; import husacct.define.task.components.AbstractDefineComponent; import husacct.define.task.components.DefineComponentFactory; import husacct.define.task.components.SoftwareArchitectureComponent; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Observable; import java.util.Observer; import javax.swing.JPanel; import org.apache.log4j.Logger; public class DefinitionController extends Observable implements Observer { private static DefinitionController instance; public static DefinitionController getInstance() { return instance == null ? (instance = new DefinitionController()) : instance; } public static void setInstance(DefinitionController dC) { instance = dC; } private AppliedRuleDomainService appliedRuleService; private DefaultRuleDomainService defaultRuleService; private DefinitionJPanel definitionJPanel; private Logger logger; private ModuleDomainService moduleService; private List<Observer> observers; private long selectedModuleId = -1; private SoftwareUnitDefinitionDomainService softwareUnitDefinitionDomainService; public DefinitionController() { observers = new ArrayList<Observer>(); logger = Logger.getLogger(DefinitionController.class); moduleService = new ModuleDomainService(); appliedRuleService = new AppliedRuleDomainService(); softwareUnitDefinitionDomainService = new SoftwareUnitDefinitionDomainService(); defaultRuleService = new DefaultRuleDomainService(); } private void addChildComponents(AbstractDefineComponent parentComponent, ModuleStrategy module) { AbstractDefineComponent childComponent = DefineComponentFactory.getDefineComponent(module); for (ModuleStrategy subModule : module.getSubModules()) { logger.debug(module.getName() + " ]" + module.getType()); addChildComponents(childComponent, subModule); } parentComponent.addChild(childComponent); } @Override public void addObserver(Observer o) { if (!observers.contains(o)) { observers.add(o); } } public ArrayList<Long> getAppliedRuleIdsBySelectedModule() { return appliedRuleService.getAppliedRulesIdsByModuleFromId(getSelectedModuleId()); } /** * This function will return a hash map with the details of the requested * module. */ public HashMap<String, Object> getModuleDetails(long moduleId) { HashMap<String, Object> moduleDetails = new HashMap<String, Object>(); if (moduleId != -1) { try { ModuleStrategy module = moduleService.getModuleById(moduleId); moduleDetails.put("id", module.getId()); moduleDetails.put("name", module.getName()); moduleDetails.put("description", module.getDescription()); moduleDetails.put("type", module.getType()); } catch (Exception e) { logger.error("getModuleDetails() - exception: " + e.getMessage()); UiDialogs.errorDialog(definitionJPanel, e.getMessage()); } } return moduleDetails; } public String getModuleName(long moduleId) { String moduleName = "Root"; if (getSelectedModuleId() != -1) { moduleName = moduleService.getModuleNameById(getSelectedModuleId()); } return moduleName; } public AbstractDefineComponent getModuleTreeComponents() { JPanelStatus.getInstance("Updating Modules").start(); SoftwareArchitectureComponent rootComponent = new SoftwareArchitectureComponent(); ArrayList<ModuleStrategy> modules = moduleService.getSortedModules(); for (ModuleStrategy module : modules) { addChildComponents(rootComponent, module); } JPanelStatus.getInstance().stop(); return rootComponent; } public ArrayList<String> getRegExSoftwareUnitNamesBySelectedModule() { return softwareUnitDefinitionDomainService .getRegExSoftwareUnitNames(getSelectedModuleId()); } public HashMap<String, Object> getRuleDetailsByAppliedRuleId( long appliedRuleId) { AppliedRuleStrategy rule = appliedRuleService.getAppliedRuleById(appliedRuleId); HashMap<String, Object> ruleDetails = new HashMap<String, Object>(); ruleDetails.put("id", rule.getId()); ruleDetails.put("description", rule.getDescription()); ruleDetails.put("dependencies", rule.getDependencies()); ruleDetails.put("moduleFromName", rule.getModuleFrom().getName()); ruleDetails.put("moduleToName", rule.getModuleTo().getName()); ruleDetails.put("enabled", rule.isEnabled()); ruleDetails.put("regex", rule.getRegex()); ruleDetails.put("ruleTypeKey", rule.getRuleType()); ruleDetails.put("numberofexceptions", rule.getExceptions().size()); return ruleDetails; } public long getSelectedModuleId() { return selectedModuleId; } public ArrayList<String> getSoftwareUnitNamesBySelectedModule() { return softwareUnitDefinitionDomainService.getSoftwareUnitNames(getSelectedModuleId()); } public String getSoftwareUnitTypeBySoftwareUnitName(String softwareUnitName) { return softwareUnitDefinitionDomainService .getSoftwareUnitType(softwareUnitName); } public void initSettings() { observers.clear(); definitionJPanel = new DefinitionJPanel(); } /** * Init the user interface for creating/editting the definition. * * @return JPanel The jpanel */ public JPanel initUi() { return definitionJPanel; } public boolean isAnalysed() { return ServiceProvider.getInstance().getAnalyseService().isAnalysed(); } public void moveLayerDown(long layerId) { logger.info("Moving layer down"); try { if (layerId != -1) { JPanelStatus.getInstance("Moving layer down").start(); moduleService.moveLayerDown(layerId); this.notifyObservers(); } } catch (Exception e) { logger.error("moveLayerDown() - exception: " + e.getMessage()); UiDialogs.errorDialog(definitionJPanel, e.getMessage()); } finally { JPanelStatus.getInstance().stop(); } } public void moveLayerUp(long layerId) { logger.info("Moving layer up"); try { if (layerId != -1) { JPanelStatus.getInstance("Moving layer up").start(); moduleService.moveLayerUp(layerId); this.notifyObservers(); } } catch (Exception e) { logger.error("moveLayerUp() - exception: " + e.getMessage()); UiDialogs.errorDialog(definitionJPanel, e.getMessage()); } finally { JPanelStatus.getInstance().stop(); } } @Override public void notifyObservers() { long moduleId = getSelectedModuleId(); for (Observer o : observers) { o.update(this, moduleId); } } /** * This function will load notify all to update their data */ public void notifyObservers(long moduleId) { for (Observer o : observers) { o.update(this, moduleId); } } public void passModuleToService(long selectedModuleId, ModuleStrategy module) { String ExceptionMessage = ""; + StateService.instance().addModule(module); if (selectedModuleId == -1) { moduleService.addModuleToRoot(module); } else { logger.debug("Adding child"); ExceptionMessage = moduleService.addNewModuleToParent( selectedModuleId, module); } this.notifyObservers(); if (!ExceptionMessage.isEmpty()) { UiDialogs.errorDialog(definitionJPanel, ExceptionMessage); } } /** * Remove a module by Id */ public void removeModuleById(long moduleId) { logger.info("Removing module by Id " + moduleId); try { JPanelStatus.getInstance("Removing ModuleStrategy").start(); moduleService.removeModuleById(moduleId); setSelectedModuleId(0); this.notifyObservers(); } catch (Exception e) { logger.error("removeModuleById(" + moduleId + ") - exception: " + e.getMessage()); UiDialogs.errorDialog(definitionJPanel, e.getMessage()); e.printStackTrace(); } finally { JPanelStatus.getInstance().stop(); } } public void removeObserver(Observer o) { if (observers.contains(o)) { observers.remove(o); } } public void removeRules(List<Long> appliedRuleIds) { boolean mandatory = false; try { if (getSelectedModuleId() != -1L && !appliedRuleIds.isEmpty()) { for (long appliedRuleID : appliedRuleIds) { AppliedRuleStrategy rule = appliedRuleService .getAppliedRuleById(appliedRuleID); if (defaultRuleService.isMandatoryRule(rule)) { mandatory = true; UiDialogs.errorDialog(definitionJPanel, ServiceProvider .getInstance().getLocaleService() .getTranslatedString("DefaultRule") + "\n- " + rule.getRuleType()); break; } } if (!mandatory) { boolean confirm = UiDialogs.confirmDialog( definitionJPanel, ServiceProvider .getInstance() .getLocaleService() .getTranslatedString( "ConfirmRemoveAppliedRule"), "Remove?"); if (confirm) { for (long appliedRuleID : appliedRuleIds) { logger.info("Removing rule " + appliedRuleID); JPanelStatus.getInstance("Removing applied rule") .start(); appliedRuleService.removeAppliedRule(appliedRuleID); } this.notifyObservers(); } } } } catch (Exception e) { logger.error("removeRule() - exception: " + e.getMessage()); UiDialogs.errorDialog(definitionJPanel, e.getMessage()); } finally { JPanelStatus.getInstance().stop(); } } /** * Remove the selected software unit */ public void removeSoftwareUnits(List<String> softwareUnitNames, List<String> types) { try { long moduleId = getSelectedModuleId(); int location = 0; boolean confirm = UiDialogs.confirmDialog(definitionJPanel, ServiceProvider.getInstance().getLocaleService() .getTranslatedString("ConfirmRemoveSoftwareUnit"), "Remove?"); for (String softwareUnit : softwareUnitNames) { String type = types.get(location); logger.info("Removing software unit " + softwareUnit); if (moduleId != -1 && softwareUnit != null && !softwareUnit.equals("")) { if (confirm) { logger.info("getting type:" + type); JtreeController.instance().restoreTreeItemm(softwareUnitNames, types); JPanelStatus.getInstance("Removing software unit") .start(); boolean chekHasCodelevelWarning = WarningMessageService .getInstance().isCodeLevelWarning( softwareUnit); if (chekHasCodelevelWarning) { boolean confirm2 = UiDialogs .confirmDialog( definitionJPanel, "Your about to remove an software unit that does exist at code level", "Remove?"); if (confirm2) { softwareUnitDefinitionDomainService .removeSoftwareUnit(moduleId, softwareUnit); } } else { softwareUnitDefinitionDomainService .removeSoftwareUnit(moduleId, softwareUnit); } this.notifyObservers(); } } location++; } } catch (Exception e) { logger.error("removeSoftwareUnit() - exception: " + e.getMessage()); e.printStackTrace(); UiDialogs.errorDialog(definitionJPanel, e.getMessage()); } finally { JPanelStatus.getInstance().stop(); } } public void setSelectedModuleId(long moduleId) { selectedModuleId = moduleId; notifyObservers(moduleId); } @Override public void update(Observable o, Object arg) { logger.info("update(" + o + ", " + arg + ")"); long moduleId = getSelectedModuleId(); notifyObservers(moduleId); } /** * Function which will save the name and description changes to the module */ public void updateModule(String moduleName, String moduleDescription) { logger.info("Updating module " + moduleName); try { JPanelStatus.getInstance("Updating module").start(); long moduleId = getSelectedModuleId(); if (moduleId != -1) { moduleService.updateModule(moduleId, moduleName, moduleDescription); } this.notifyObservers(); } catch (Exception e) { logger.error("updateModule() - exception: " + e.getMessage()); UiDialogs.errorDialog(definitionJPanel, e.getMessage()); } finally { JPanelStatus.getInstance().stop(); } } public void updateFacade(String moduleName){ logger.info("Updating facade " + moduleName +"Facade"); try { JPanelStatus.getInstance("Updating facade").start(); long moduleId = getSelectedModuleId(); if (moduleId != -1) { moduleService.updateFacade(moduleId, moduleName); } this.notifyObservers(); } catch (Exception e) { logger.error("updateFacade() - exception: " + e.getMessage()); UiDialogs.errorDialog(definitionJPanel, e.getMessage()); } finally { JPanelStatus.getInstance().stop(); } } public void updateModule(String moduleName, String moduleDescription, String type) { moduleService.updateModule(getSelectedModuleId(), moduleName, moduleDescription, type); this.notifyObservers(); } public void addModule(String name, String description, String type) { ModuleStrategy module= moduleService.createNewModule(type); module.set(name, description); if (module instanceof Component) { ModuleStrategy facade= moduleService.createNewModule("facade"); facade.set("Facade<"+name+">", "this is the Facade of your Component"); module.addSubModule(facade); } this.passModuleToService(getSelectedModuleId(), module); } } diff --git a/src/husacct/define/task/JtreeController.java b/src/husacct/define/task/JtreeController.java index ecc64c64..9adce655 100644 --- a/src/husacct/define/task/JtreeController.java +++ b/src/husacct/define/task/JtreeController.java @@ -1,344 +1,344 @@ package husacct.define.task; import husacct.define.domain.module.ModuleStrategy; import husacct.define.domain.seperatedinterfaces.ISofwareUnitSeperatedInterface; import husacct.define.domain.services.SoftwareUnitDefinitionDomainService; import husacct.define.domain.services.UndoRedoService; import husacct.define.domain.services.stateservice.StateService; import husacct.define.domain.softwareunit.ExpressionUnitDefinition; import husacct.define.domain.softwareunit.SoftwareUnitDefinition; import husacct.define.presentation.moduletree.AnalyzedModuleTree; import husacct.define.presentation.moduletree.CombinedModuleTreeModel; import husacct.define.presentation.moduletree.ModuleTree; import husacct.define.presentation.moduletree.SearchModuleCellRenderer; import husacct.define.task.components.AbstractCombinedComponent; import husacct.define.task.components.AnalyzedModuleComponent; import husacct.define.task.components.RegexComponent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.tree.TreePath; public class JtreeController implements ISofwareUnitSeperatedInterface{ private AnalyzedModuleTree tree; private static JtreeController instance; private AnalyzedModuleTree resultTree; private ModuleTree moduleTree; private AnalyzedModuleTree editTree; private boolean isLoaded=false; public JtreeController() { UndoRedoService.getInstance().registerObserver(this); } public static JtreeController instance() { if(instance==null) { return instance= new JtreeController(); }else{ return instance; } } public void registerTreeRemoval(ModuleStrategy module) { removeSoftWareUnits(module); for (ModuleStrategy m : module.getSubModules()) { registerTreeRemoval(m); } } private void removeSoftWareUnits(ModuleStrategy module) { for (SoftwareUnitDefinition unit : module.getUnits()) { AnalyzedModuleComponent softwareUnit= StateService.instance().getAnalyzedSoftWareUnit(unit); restoreTreeItem(softwareUnit); } } public void setCurrentTree(AnalyzedModuleTree instanceoftree) { tree=instanceoftree; } public boolean isLoaded() { return isLoaded; } public void setLoadState(boolean value) { isLoaded=value; } public AnalyzedModuleTree getTree() { return tree; } public AnalyzedModuleComponent getRootOfModel () { return (AnalyzedModuleComponent)instance.getTree().getModel().getRoot(); } public AnalyzedModuleTree getResultTree() { RegexComponent root = new RegexComponent("Found results:","Nothing found","SEARCH","public"); resultTree= new AnalyzedModuleTree(root); return resultTree; } public void additemgetResultTree(AnalyzedModuleComponent analyzedModule) { analyzedModule.detach(); AnalyzedModuleComponent rootOfResultTree = (AnalyzedModuleComponent)resultTree.getModel().getRoot(); rootOfResultTree.detach(); rootOfResultTree.addChild(analyzedModule); resultTree.setModel(new CombinedModuleTreeModel(rootOfResultTree)); resultTree.setCellRenderer(new SearchModuleCellRenderer()); } public ModuleTree getModuleTree() { return moduleTree; } public void setModuleTree(ModuleTree moduleTree) { this.moduleTree = moduleTree; } public RegexComponent registerRegix(String regExName) { RegexComponent regixwrapper = new RegexComponent(); TreePath[] paths = instance.resultTree.getSelectionPaths(); for (TreePath treePath : paths) { AnalyzedModuleComponent op = (AnalyzedModuleComponent)treePath.getLastPathComponent(); removeTreeItem(StateService.instance().getAnalyzedSoftWareUnit(op.getUniqueName().toLowerCase())); regixwrapper.addChild(op); } regixwrapper.setName(regExName); regixwrapper.setType("regex"); regixwrapper.setUniqueName(regExName); regixwrapper.setVisibility("public"); return regixwrapper; } public AnalyzedModuleTree getRegixTree(String editingRegEx) { RegexComponent result = new RegexComponent("root","editRegex","SEARCH","public"); result.setRegex(new SoftwareUnitDefinitionDomainService().getExpressionByName(DefinitionController.getInstance().getSelectedModuleId(),editingRegEx)); editTree = new AnalyzedModuleTree(result); return editTree; } public void restoreRegexWrapper(ExpressionUnitDefinition unit) { for (SoftwareUnitDefinition result : unit.getExpressionValues()) { AnalyzedModuleComponent unitToBeRestored= StateService.instance().getAnalyzedSoftWareUnit(result); unitToBeRestored.unfreeze(); } } public AbstractCombinedComponent getMappedunits() { return (AbstractCombinedComponent) instance.getTree().getModel().getRoot(); } public void restoreTreeItem(AnalyzedModuleComponent analyzeModuleTobeRestored) { tree.restoreTreeItem(analyzeModuleTobeRestored); tree.repaint(); } public void removeTreeItem(AnalyzedModuleComponent unitToBeinserted) { if (unitToBeinserted instanceof RegexComponent) { restoreRegex((RegexComponent) unitToBeinserted); }else{ tree.removeTreeItem(unitToBeinserted); tree.repaint(); } } public void setTreeModel(AnalyzedModuleComponent root) { if(tree==null) { tree= new AnalyzedModuleTree(root); }else { tree.setModel(new CombinedModuleTreeModel(root)); } } public void restoreTreeItems(ModuleStrategy module) { for (SoftwareUnitDefinition unit : module.getUnits()) { AnalyzedModuleComponent anal = StateService.instance().getAnalyzedSoftWareUnit(unit); restoreTreeItem(anal); } } public void restoreTreeItemm(List<String> softwareUnitNames, List<String> types) { for (String uniqname : softwareUnitNames) { AnalyzedModuleComponent tobeRestored= StateService.instance().getAnalyzedSoftWareUnit(uniqname); if (tobeRestored instanceof RegexComponent) { restoreRegex((RegexComponent)tobeRestored); }else{ tree.restoreTreeItem(tobeRestored); tree.repaint(); } } } private void restoreRegex(RegexComponent tobeRestored) { for (AbstractCombinedComponent unit : tobeRestored.getChildren()) { AnalyzedModuleComponent referenceditem = StateService.instance().getAnalyzedSoftWareUnit(unit.getUniqueName().toLowerCase()); - tree.removeTreeItem(referenceditem); + tree.restoreTreeItem(referenceditem); tree.repaint(); } } @Override public void addSeperatedSoftwareUnit(List<SoftwareUnitDefinition> units, long moduleID) { for (SoftwareUnitDefinition softwareUnitDefinition : units) { AnalyzedModuleComponent unitToBeinserted= StateService.instance().getAnalyzedSoftWareUnit(softwareUnitDefinition); removeTreeItem(unitToBeinserted); } } @Override public void removeSeperatedSoftwareUnit(List<SoftwareUnitDefinition> units, long moduleId) { for (SoftwareUnitDefinition softwareUnitDefinition : units) { AnalyzedModuleComponent unitToBeinserted= StateService.instance().getAnalyzedSoftWareUnit(softwareUnitDefinition); restoreTreeItem(unitToBeinserted); } } public List<AbstractCombinedComponent> getRootprojectsModules() { List<AbstractCombinedComponent> returnList = new ArrayList<AbstractCombinedComponent>(); for (AbstractCombinedComponent result : getRootOfModel().getChildren()) { if (result.getType().toLowerCase().equals("root")) { returnList.addAll(result.getChildren()); } } return returnList; } public RegexComponent createRegexRepresentation(String editingRegEx, ArrayList<AnalyzedModuleComponent> components) { RegexComponent expresion = new RegexComponent(editingRegEx,"root","REGEX","public"); for (AnalyzedModuleComponent unit : components) { expresion.addChild(unit); } return expresion; } @Override public void addExpression(long moduleId, ExpressionUnitDefinition expression) { for (SoftwareUnitDefinition unit : expression.getExpressionValues()) { AnalyzedModuleComponent result = StateService.instance().getAnalyzedSoftWareUnit(unit); tree.removeTreeItem(result); } tree.repaint(); } @Override public void removeExpression(long moduleId, ExpressionUnitDefinition expression) { for (SoftwareUnitDefinition unit : expression.getExpressionValues()) { AnalyzedModuleComponent result = StateService.instance().getAnalyzedSoftWareUnit(unit); tree.restoreTreeItem(result); } tree.repaint(); } @Override public void editExpression(long moduleId, ExpressionUnitDefinition oldExpresion, ExpressionUnitDefinition newExpression) { // TODO Auto-generated method stub } public void removeRegexTreeItem(RegexComponent softwareunit) { for (AbstractCombinedComponent unit : softwareunit.getChildren()) { removeTreeItem((AnalyzedModuleComponent)unit); } } @Override public void switchSoftwareUnitLocation(long fromModule, long toModule, List<String> uniqNames) { // TODO Auto-generated method stub } } \ No newline at end of file diff --git a/src/husacct/define/task/JtreeStateEngine.java b/src/husacct/define/task/JtreeStateEngine.java index 9ce9521a..74058287 100644 --- a/src/husacct/define/task/JtreeStateEngine.java +++ b/src/husacct/define/task/JtreeStateEngine.java @@ -1,212 +1,217 @@ package husacct.define.task; import husacct.define.analyzer.AnalyzedUnitComparator; import husacct.define.domain.SoftwareArchitecture; import husacct.define.domain.appliedrule.AppliedRuleStrategy; import husacct.define.domain.module.ModuleStrategy; import husacct.define.domain.services.UndoRedoService; import husacct.define.domain.services.WarningMessageService; import husacct.define.domain.services.stateservice.StateService; import husacct.define.domain.services.stateservice.state.StateDefineController; import husacct.define.domain.services.stateservice.state.appliedrule.AppliedRuleAddCommand; import husacct.define.domain.services.stateservice.state.appliedrule.ExceptionAddRuleCommand; import husacct.define.domain.services.stateservice.state.appliedrule.RemoveAppliedRuleCommand; import husacct.define.domain.services.stateservice.state.module.LayerDownCommand; import husacct.define.domain.services.stateservice.state.module.LayerUpCommand; import husacct.define.domain.services.stateservice.state.module.ModuleAddCommand; import husacct.define.domain.services.stateservice.state.module.ModuleRemoveCommand; import husacct.define.domain.services.stateservice.state.module.UpdateModuleCommand; import husacct.define.domain.services.stateservice.state.module.UpdateModuleTypeCommand; import husacct.define.domain.services.stateservice.state.softwareunit.SoftwareUnitAddCommand; import husacct.define.domain.services.stateservice.state.softwareunit.SoftwareUnitRemoveCommand; import husacct.define.domain.softwareunit.SoftwareUnitDefinition; import husacct.define.domain.warningmessages.WarningMessageContainer; import husacct.define.presentation.registry.AnalyzedUnitRegistry; import husacct.define.task.components.AnalyzedModuleComponent; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; public abstract class JtreeStateEngine { private Logger logger; private StateDefineController stateController = new StateDefineController(); private AnalyzedUnitComparator analyzerComparator = new AnalyzedUnitComparator(); private AnalyzedUnitRegistry allUnitsRegistry = new AnalyzedUnitRegistry(); public JtreeStateEngine() { logger = Logger.getLogger(JtreeStateEngine.class); UndoRedoService.getInstance().registerObserver(SoftwareArchitecture.getInstance()); } public boolean undo() { boolean res =stateController.undo(); DefinitionController.getInstance().notifyObservers(); return res; } public boolean redo() { boolean res =stateController.redo();; DefinitionController.getInstance().notifyObservers(); return res; } public void removeModule(ArrayList<Object[]> data) { stateController.insertCommand(new ModuleRemoveCommand(data)); } public void addUpdateModule(long moduleId, String[] moduleold, String[] modulenew) { stateController.insertCommand(new UpdateModuleCommand(moduleId, modulenew, moduleold)); } public void addUpdateModule(ModuleStrategy module, ModuleStrategy updatedModule) { stateController.insertCommand(new UpdateModuleTypeCommand(module, updatedModule)); } public void layerUp(long moduleId) { stateController.insertCommand(new LayerUpCommand(moduleId)); DefinitionController.getInstance().notifyObservers(); } public void layerDown(long moduleId) { stateController.insertCommand(new LayerDownCommand(moduleId)); DefinitionController.getInstance().notifyObservers(); } public void removeSoftwareUnit(ModuleStrategy module, SoftwareUnitDefinition unit) { AnalyzedModuleComponent analyzeModuleTobeRestored = allUnitsRegistry.getAnalyzedUnit(unit); ArrayList<AnalyzedModuleComponent> data = new ArrayList<AnalyzedModuleComponent>(); data.add(analyzeModuleTobeRestored); StateService.instance().allUnitsRegistry .registerAnalyzedUnit(analyzeModuleTobeRestored); } public void addSoftwareUnit(ModuleStrategy module, ArrayList<AnalyzedModuleComponent> unitToBeinserted) { stateController.insertCommand(new SoftwareUnitAddCommand(module, unitToBeinserted)); for (AnalyzedModuleComponent analyzedModuleComponent : unitToBeinserted) { JtreeController.instance().removeTreeItem(analyzedModuleComponent); WarningMessageService.getInstance().updateWarnings(); } } public AnalyzedModuleComponent getRootModel() { return analyzerComparator.getRootModel(); } public void analyze() { getRootModel(); } public void registerAnalyzedUnit(AnalyzedModuleComponent unit) { allUnitsRegistry.registerAnalyzedUnit(unit); } public AnalyzedUnitRegistry getAnalzedModuleRegistry() { return allUnitsRegistry; } public void reset() { allUnitsRegistry.reset(); } public boolean[] getRedoAndUndoStates() { return stateController.getStatesStatus(); } public void removeRules(ArrayList<AppliedRuleStrategy> selectedRules) { stateController.insertCommand(new RemoveAppliedRuleCommand( selectedRules)); } public void addRules(ArrayList<AppliedRuleStrategy> rules) { stateController.insertCommand(new AppliedRuleAddCommand(rules)); } public void addExceptionRule(AppliedRuleStrategy parent, ArrayList<AppliedRuleStrategy> rules) { stateController .insertCommand(new ExceptionAddRuleCommand(parent, rules)); } public void removeSoftwareUnit(List<String> selectedModules) { stateController.insertCommand(new SoftwareUnitRemoveCommand(DefinitionController.getInstance().getSelectedModuleId(), selectedModules)); } public AnalyzedModuleComponent getAnalyzedSoftWareUnit(SoftwareUnitDefinition unit) { return allUnitsRegistry.getAnalyzedUnit(unit); } public void addModule(ModuleStrategy subModule) { stateController.insertCommand(new ModuleAddCommand(subModule)); } public ModuleStrategy getModulebySoftwareUnitUniqName(String uniqueName) { return SoftwareArchitecture.getInstance().getModuleBySoftwareUnit(uniqueName); } public WarningMessageContainer getNotMappedUnits() { return allUnitsRegistry.getNotMappedUnits(); } public AnalyzedModuleComponent getAnalyzedSoftWareUnit(String uniqueName) { return allUnitsRegistry.getAnalyzedUnit(uniqueName); } public ArrayList<AnalyzedModuleComponent> getAnalyzedSoftWareUnit( List<String> data) { return allUnitsRegistry.getAnalyzedUnit(data); } + public void removeRules(List<Long> selectedRules) { + + + } + }
false
false
null
null
diff --git a/java/src/com/centaurean/clmax/schema/mem/CLMapType.java b/java/src/com/centaurean/clmax/schema/mem/CLMapType.java index 3edb208..1fc17b8 100644 --- a/java/src/com/centaurean/clmax/schema/mem/CLMapType.java +++ b/java/src/com/centaurean/clmax/schema/mem/CLMapType.java @@ -1,65 +1,65 @@ package com.centaurean.clmax.schema.mem; import com.centaurean.clmax.schema.versions.CLVersion; import com.centaurean.clmax.schema.versions.CLVersionMatcher; import static com.centaurean.clmax.schema.versions.CLVersion.OPENCL_1_0; import static com.centaurean.clmax.schema.versions.CLVersion.OPENCL_1_2; /* * Copyright (c) 2013, Centaurean * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Centaurean nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Centaurean BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * jetFlow + * CLmax * * 17/04/13 03:23 * @author gpnuma */ public enum CLMapType implements CLVersionMatcher { READ(1), WRITE(1 << 1), WRITE_INVALIDATE_REGION(1 << 2, OPENCL_1_2); private int value; private CLVersion minimumVersion; private CLMapType(int value, CLVersion minimumVersion) { this.value = value; this.minimumVersion = minimumVersion; } private CLMapType(int value) { this(value, OPENCL_1_0); } public int getValue() { return value; } @Override public CLVersion getMinimumCLVersion() { return minimumVersion; } } diff --git a/java/src/com/centaurean/clmax/schema/mem/CLMem.java b/java/src/com/centaurean/clmax/schema/mem/CLMem.java index e6b93da..7554da3 100644 --- a/java/src/com/centaurean/clmax/schema/mem/CLMem.java +++ b/java/src/com/centaurean/clmax/schema/mem/CLMem.java @@ -1,45 +1,45 @@ package com.centaurean.clmax.schema.mem; import com.centaurean.clmax.schema.CLObject; /* * Copyright (c) 2013, Centaurean * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Centaurean nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Centaurean BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * jetFlow + * CLmax * * 15/04/13 02:25 * @author gpnuma */ public class CLMem extends CLObject { public CLMem(long pointer) { super(pointer); } @Override public String toString() { return super.toString(); } } diff --git a/java/src/com/centaurean/clmax/schema/mem/buffers/CLBuffer.java b/java/src/com/centaurean/clmax/schema/mem/buffers/CLBuffer.java index 7ebb810..a9903dd 100644 --- a/java/src/com/centaurean/clmax/schema/mem/buffers/CLBuffer.java +++ b/java/src/com/centaurean/clmax/schema/mem/buffers/CLBuffer.java @@ -1,74 +1,74 @@ package com.centaurean.clmax.schema.mem.buffers; import com.centaurean.clmax.schema.CL; import com.centaurean.clmax.schema.exceptions.CLException; import com.centaurean.clmax.schema.mem.CLMapType; import com.centaurean.clmax.schema.mem.CLMem; import com.centaurean.clmax.schema.queues.CLCommandQueue; import java.nio.ByteBuffer; /* * Copyright (c) 2013, Centaurean * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Centaurean nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Centaurean BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * jetFlow + * CLmax * * 14/04/13 02:53 * @author gpnuma */ public class CLBuffer extends CLMem { private ByteBuffer hostBuffer; public CLBuffer(long pointerBuffer, ByteBuffer hostBuffer) { super(pointerBuffer); this.hostBuffer = hostBuffer; } public void map(CLCommandQueue commandQueue, CLMapType mapType) { if(commandQueue.getDevice().getVersion().compareTo(mapType.getMinimumCLVersion()) < 0) throw new CLException("Map type " + mapType.name() + " requires an " + mapType.getMinimumCLVersion().majorMinor() + " compatible device !"); CL.mapBufferNative(commandQueue.getPointer(), getPointer(), mapType.getValue(), getHostBuffer().capacity()); } public void unmap(CLCommandQueue commandQueue) { CL.unmapMemObjectNative(commandQueue.getPointer(), getPointer(), getHostBuffer()); } public void release() { CL.releaseMemObjectNative(getPointer()); } public ByteBuffer getHostBuffer() { return hostBuffer; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(super.toString()).append(" {").append(getHostBuffer()).append("}"); return stringBuilder.toString(); } } diff --git a/java/src/com/centaurean/clmax/schema/mem/buffers/CLBufferType.java b/java/src/com/centaurean/clmax/schema/mem/buffers/CLBufferType.java index 989e3de..60d073b 100644 --- a/java/src/com/centaurean/clmax/schema/mem/buffers/CLBufferType.java +++ b/java/src/com/centaurean/clmax/schema/mem/buffers/CLBufferType.java @@ -1,48 +1,48 @@ package com.centaurean.clmax.schema.mem.buffers; /* * Copyright (c) 2013, Centaurean * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Centaurean nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Centaurean BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * jetFlow + * CLmax * * 16/04/13 22:22 * @author gpnuma */ public enum CLBufferType { READ_WRITE(1), WRITE_ONLY(1 << 1), READ_ONLY(1 << 2); private int value; private CLBufferType(int value) { this.value = value; } public int getValue() { return value; } } diff --git a/java/src/com/centaurean/clmax/schema/queues/CLCommandQueue.java b/java/src/com/centaurean/clmax/schema/queues/CLCommandQueue.java index d956311..4e361b2 100644 --- a/java/src/com/centaurean/clmax/schema/queues/CLCommandQueue.java +++ b/java/src/com/centaurean/clmax/schema/queues/CLCommandQueue.java @@ -1,60 +1,60 @@ package com.centaurean.clmax.schema.queues; import com.centaurean.clmax.schema.CL; import com.centaurean.clmax.schema.CLObject; import com.centaurean.clmax.schema.contexts.CLContext; import com.centaurean.clmax.schema.devices.CLDevice; /* * Copyright (c) 2013, Centaurean * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Centaurean nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Centaurean BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * - * jetFlow + * CLmax * * 16/04/13 22:32 * @author gpnuma */ public class CLCommandQueue extends CLObject { private CLContext context; private CLDevice device; public CLCommandQueue(long pointer, CLContext context, CLDevice device) { super(pointer); this.context = context; this.device = device; } public void release() { CL.releaseCommandQueueNative(getPointer()); } public CLContext getContext() { return context; } public CLDevice getDevice() { return device; } }
false
false
null
null
diff --git a/src/jp/ac/osaka_u/ist/sdl/ectec/ast/ASTCreator.java b/src/jp/ac/osaka_u/ist/sdl/ectec/ast/ASTCreator.java index afc67bd..cb2ca50 100644 --- a/src/jp/ac/osaka_u/ist/sdl/ectec/ast/ASTCreator.java +++ b/src/jp/ac/osaka_u/ist/sdl/ectec/ast/ASTCreator.java @@ -1,58 +1,58 @@ package jp.ac.osaka_u.ist.sdl.ectec.ast; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; /** * A class to create ASTs from the given source files * * @author k-hotta * */ public class ASTCreator { public static CompilationUnit createAST(final String sourceCode) { final ASTParser parser = ASTParser.newParser(AST.JLS4); parser.setSource(sourceCode.toCharArray()); return (CompilationUnit) parser.createAST(new NullProgressMonitor()); } - public static CompilationUnit creatAST(final File file) { + public static CompilationUnit createAST(final File file) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); final StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } return createAST(builder.toString()); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
true
true
public static CompilationUnit creatAST(final File file) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); final StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } return createAST(builder.toString()); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public static CompilationUnit createAST(final File file) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file)); final StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } return createAST(builder.toString()); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } }
diff --git a/src/main/java/org/apache/maven/plugin/swig/SwigMojo.java b/src/main/java/org/apache/maven/plugin/swig/SwigMojo.java index 968206d..6f6299a 100644 --- a/src/main/java/org/apache/maven/plugin/swig/SwigMojo.java +++ b/src/main/java/org/apache/maven/plugin/swig/SwigMojo.java @@ -1,787 +1,796 @@ package org.apache.maven.plugin.swig; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.nar.AbstractNarLayout; import org.apache.maven.plugin.nar.Linker; import org.apache.maven.plugin.nar.NarArtifact; import org.apache.maven.plugin.nar.NarInfo; import org.apache.maven.plugin.nar.NarLayout; import org.apache.maven.plugin.nar.NarManager; import org.apache.maven.plugin.nar.NarUtil; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.codehaus.plexus.compiler.util.scan.InclusionScanException; import org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner; import org.codehaus.plexus.compiler.util.scan.StaleSourceScanner; import org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; /** * Compiles swg files using the swig compiler. * * @goal generate * @description Compiles swg files using the swig compiler. * @phase generate-sources * @requiresDependencyResolution compile * @author Mark Donszelmann */ public class SwigMojo extends AbstractMojo { /** * Skip the running of SWIG * * @parameter expression="${swig.skip}" default-value="false" */ private boolean skip; /** * Force the running of SWIG * * @parameter expression="${swig.force}" default-value="false" */ private boolean force; /** * Define symbol for conditional compilation, same as -D option for swig. * * @parameter */ private List defines; /** * Sets a fake version number, same as -fakeversion for swig. * * @parameter */ private String fakeVersion; /** * Enable C++ processing, same as -c++ option for swig. * * @parameter expression="${swig.cpp}" default-value="false" */ private boolean cpp; /** * Add include paths. By default the current directory is scanned. * * @parameter */ private List includePaths; /** * List of warning numbers to be suppressed, same as -w option for swig. * * @parameter expression="${swig.noWarn}" */ private String noWarn; /** * Enable all warnings, same as -Wall * * @parameter expression="${swig.warnAll}" default-value="false" */ private boolean warnAll; /** * Treat warnings as errors, same as -Werror * * @parameter expression="${swig.warnError}" default-value="false" */ private boolean warnError; /** * The target directory into which to generate the output. * * @parameter expression="${project.build.directory}/swig" */ private File targetDirectory; /** * The unpack directory into which to unpack the swig executable. * * @parameter expression="${project.build.directory}/nar/dependencies" */ private File unpackDirectory; /** * The package name for the generated java files (fully qualified ex: org.apache.maven.jni). * * @parameter expression="${swig.packageName}" */ private String packageName; /** * The output filename. Defaults to ${source}.cpp or .c depending on cpp option. * * @parameter */ private String outFile; /** * The target directory into which to generate the java output, becomes -outdir option for swig. * * @parameter expression="${project.build.directory}/swig/java" */ private String javaTargetDirectory; /** * Remove all *.java files from the output directory. The output directory is formed by * ${javaTargetDirectory}/${packageName}. This setting is ignored (false) if no packageName is supplied. All *.java * are deleted from the output directory just before the swig command is run. This allows the user to configure to * have the java files of the swig command in the src directory tree. * * @parameter expression="false" */ private boolean cleanOutputDirectory; /** * The directory to look for swig files and swig include files. Also added to -I flag when swig is run. * * @parameter expression="${basedir}/src/main/swig" * @required */ private String sourceDirectory; /** * The swig file to process, normally in source directory set by swigDirectory. * * @parameter * @required */ private String source; /** * The Architecture for picking up swig, Some choices are: "x86", "i386", "amd64", "ppc", "sparc", ... Defaults to a * derived value from ${os.arch} * * @parameter expression="${os.arch}" * @required */ private String architecture; /** * The Operating System for picking up swig. Some choices are: "Windows", "Linux", "MacOSX", "SunOS", ... Defaults * to a derived value from ${os.name} * * @parameter expression="" */ private String os; /** * The granularity in milliseconds of the last modification date for testing whether a source needs recompilation * * @parameter expression="${idlj.staleMillis}" default-value="0" * @required */ private int staleMillis; /** * Swig Executable (overrides built-in or user configured reference to NAR) * * @parameter expression="${swig.exec}" */ private String exec; /** * GroupId for the swig NAR * * @parameter expression="${swig.groupId}" default-value="org.swig" */ private String groupId; /** * ArtifactId for the swig NAR * * @parameter expression="${swig.artifactId}" default-value="nar-swig" */ private String artifactId; /** * Version for the swig NAR * * @parameter expression="${swig.version}" */ private String version; /** * Layout to be used for building and unpacking artifacts * * @parameter expression="${nar.layout}" default-value="org.apache.maven.plugin.nar.NarLayout21" * @required */ private String layout; /** * Adds system libraries to the linker. Will work in combination with &lt;sysLibs&gt;. The format is comma * separated, colon-delimited values (name:type), like "dl:shared, pthread:shared". * * @parameter expression="" */ private String sysLibSet; /** * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * @parameter expression="${localRepository}" * @required * @readonly */ private ArtifactRepository localRepository; /** * Artifact handler * * @component role="org.apache.maven.artifact.handler.ArtifactHandler" * @required * @readonly */ private ArtifactHandler artifactHandler; /** * Artifact resolver, needed to download source jars for inclusion in classpath. * * @component role="org.apache.maven.artifact.resolver.ArtifactResolver" * @required * @readonly */ private ArtifactResolver artifactResolver; /** * @component role="org.apache.maven.artifact.factory.ArtifactFactory" * @required * @readonly */ private ArtifactFactory artifactFactory; /** * Remote repositories which will be searched for source attachments. * * @parameter expression="${project.remoteArtifactRepositories}" * @required * @readonly */ private List remoteArtifactRepositories; /** * To look up Archiver/UnArchiver implementations * * @component role="org.codehaus.plexus.archiver.manager.ArchiverManager" * @required */ private ArchiverManager archiverManager; private NarManager narManager; public final void execute() throws MojoExecutionException, MojoFailureException { if ( skip ) { getLog().warn( "SKIPPED Running SWIG compiler on " + source + " ..." ); return; } configureNarPlugin(); if ( !sourceDirectory.endsWith( "/" ) ) { sourceDirectory = sourceDirectory + "/"; } File sourceDir = new File( sourceDirectory ); File sourceFile = new File( sourceDir, source ); if ( !sourceDir.exists() || !sourceFile.exists() ) { getLog().info( "No SWIG sources found" ); return; } os = NarUtil.getOS( os ); Linker linker = new Linker( NarUtil.getLinkerName( architecture, os, null ) ); narManager = new NarManager( getLog(), localRepository, project, architecture, os, linker ); targetDirectory = new File( targetDirectory, cpp ? "c++" : "c" ); if ( !targetDirectory.exists() ) { targetDirectory.mkdirs(); } if ( project != null ) { project.addCompileSourceRoot( javaTargetDirectory ); project.addCompileSourceRoot( targetDirectory.getPath() ); } if ( packageName != null ) { if ( !javaTargetDirectory.endsWith( "/" ) ) { javaTargetDirectory = javaTargetDirectory + "/"; } javaTargetDirectory += packageName.replace( '.', File.separatorChar ); } if ( !FileUtils.fileExists( javaTargetDirectory ) ) { FileUtils.mkdir( javaTargetDirectory ); } // make sure all NAR dependencies are downloaded and unpacked // even if packaging is NOT nar // in nar packaging, downloading happens in generate-sources phase and // thus may be too late // unpacking happens in process-sources which is definitely too late // so we need to handle this here ourselves. NarLayout narLayout = AbstractNarLayout.getLayout( layout, getLog() ); List narArtifacts = narManager.getNarDependencies( "compile" ); narManager.downloadAttachedNars( narArtifacts, remoteArtifactRepositories, artifactResolver, null ); narManager.unpackAttachedNars( narArtifacts, archiverManager, null, os, narLayout, unpackDirectory ); File swig, swigInclude, swigJavaInclude; if ( exec == null ) { // NOTE, since a project will just load this as a plugin, there is // no way to look up the org.swig:nar-swig dependency, so we hardcode // that in here, but it is configurable in the configuration part of this plugin. // if version not specified use maven-swig-plugin version if ( version == null ) { Plugin swigPlugin = (Plugin) project.getBuild().getPluginsAsMap().get( "org.apache.maven.plugins:maven-swig-plugin" ); version = swigPlugin.getVersion(); } Artifact swigJar = artifactFactory.createArtifactWithClassifier( groupId, artifactId, version, "nar", ""); // new DefaultArtifact( groupId, artifactId, VersionRange.createFromVersion( version ), "compile", "nar", // "", artifactHandler ); // download jar file try { getLog().debug( "maven-swig-plugin: Resolving " + swigJar ); artifactResolver.resolve( swigJar, remoteArtifactRepositories, localRepository ); } catch ( ArtifactNotFoundException e ) { String message = "Jar not found " + swigJar; throw new MojoExecutionException( message, e ); } catch ( ArtifactResolutionException e ) { String message = "Jar cannot be resolved " + swigJar; throw new MojoExecutionException( message, e ); } NarInfo info = narManager.getNarInfo( swigJar ); getLog().debug( info.toString() ); NarArtifact swigNar = new NarArtifact( swigJar, info ); // download attached nars, in which the executable and the include files sit List swigNarArtifacts = new ArrayList(); swigNarArtifacts.add( swigNar ); narManager.downloadAttachedNars( swigNarArtifacts, remoteArtifactRepositories, artifactResolver, null ); narManager.unpackAttachedNars( swigNarArtifacts, archiverManager, null, os, narLayout, unpackDirectory ); swigInclude = narLayout.getIncludeDirectory( unpackDirectory, swigJar.getArtifactId(), swigJar.getVersion() ); swigJavaInclude = new File( swigInclude, "java" ); swig = new File( narLayout.getBinDirectory( unpackDirectory, swigJar.getArtifactId(), swigJar.getVersion(), NarUtil.getAOL( architecture, os, linker, null ).toString() ), "swig" ); } else { swig = new File( exec ); swigInclude = null; swigJavaInclude = null; } File targetFile = targetDirectory; SourceInclusionScanner scanner = new StaleSourceScanner( staleMillis, Collections.singleton( source ), Collections.EMPTY_SET ); String extension = "." + FileUtils.getExtension( source ); SuffixMapping mapping = new SuffixMapping( extension, extension + ".flag" ); scanner.addSourceMapping( mapping ); try { Set files = scanner.getIncludedSources( sourceDir, targetFile ); if ( !files.isEmpty() || force ) { if ( cleanOutputDirectory && ( packageName != null ) && FileUtils.fileExists( javaTargetDirectory ) ) { getLog().info( "Cleaning " + javaTargetDirectory ); String[] filesToRemove = FileUtils.getFilesFromExtension( javaTargetDirectory, new String[] { "java" } ); for ( int i = 0; i < filesToRemove.length; i++ ) { File f = new File( filesToRemove[i] ); f.delete(); } } getLog().info( ( force ? "FORCE " : "" ) + "Running SWIG compiler on " + source + " ..." ); int error = runCommand( generateCommandLine( swig, swigInclude, swigJavaInclude ) ); if ( error != 0 ) { throw new MojoFailureException( "SWIG returned error code " + error ); } File flagFile = new File( targetDirectory, source + ".flag" ); FileUtils.fileDelete( flagFile.getPath() ); FileUtils.fileWrite( flagFile.getPath(), "" ); } else { getLog().info( "Nothing to swig - all classes are up to date" ); } } catch ( InclusionScanException e ) { throw new MojoExecutionException( "IDLJ: Source scanning failed", e ); } catch ( IOException e ) { throw new MojoExecutionException( "SWIG: Creation of timestamp flag file failed", e ); } } private void configureNarPlugin() throws MojoExecutionException, MojoFailureException { // configure NAR plugin Plugin narPlugin = (Plugin) project.getBuild().getPluginsAsMap().get( "org.apache.maven.plugins:maven-nar-plugin" ); if ( narPlugin == null ) { return; } if ( narPlugin.getConfiguration() != null ) { throw new MojoExecutionException( "Please configure maven-nar-plugin without <configuration> element, so that the maven-swig-plugin can configure it" ); } getLog().info( "Configuring maven-nar-plugin to create jni library" ); Xpp3Dom narConfig = new Xpp3Dom( "configuration" ); narPlugin.setConfiguration( narConfig ); // set type to jni and generate NarSystem Xpp3Dom libraries = new Xpp3Dom( "libraries" ); narConfig.addChild( libraries ); Xpp3Dom library = new Xpp3Dom( "library" ); libraries.addChild( library ); Xpp3Dom type = new Xpp3Dom( "type" ); type.setValue( "jni" ); library.addChild( type ); Xpp3Dom narSystemPackage = new Xpp3Dom( "narSystemPackage" ); narSystemPackage.setValue( packageName ); library.addChild( narSystemPackage ); // include and link with java Xpp3Dom java = new Xpp3Dom( "java" ); narConfig.addChild( java ); Xpp3Dom include = new Xpp3Dom( "include" ); include.setValue( "true" ); java.addChild( include ); Xpp3Dom link = new Xpp3Dom( "link" ); link.setValue( "true" ); java.addChild( link ); Xpp3Dom javah = new Xpp3Dom( "javah" ); narConfig.addChild( javah ); // do not run javah Xpp3Dom excludes = new Xpp3Dom( "excludes" ); javah.addChild( excludes ); Xpp3Dom exclude = new Xpp3Dom( "exclude" ); exclude.setValue( packageName.replace( '.', File.separatorChar ) + File.separatorChar + "*.class" ); excludes.addChild( exclude ); if( sysLibSet != null && !sysLibSet.isEmpty() ) { Xpp3Dom linker = new Xpp3Dom( "linker" ); narConfig.addChild( linker ); Xpp3Dom sysLibSetNode = new Xpp3Dom( "sysLibSet" ); sysLibSetNode.setValue( sysLibSet ); linker.addChild( sysLibSetNode ); } if (includePaths != null && !includePaths.isEmpty()) { final String compilerName = cpp ? "cpp" : "c"; Xpp3Dom compilerConfig = new Xpp3Dom( compilerName ); narConfig.addChild( compilerConfig ); Xpp3Dom options = new Xpp3Dom( "options" ); compilerConfig.addChild( options ); for ( Iterator i = includePaths.iterator(); i.hasNext(); ) { Xpp3Dom includePath = new Xpp3Dom( "option" ); includePath.setValue( "-I" + i.next() ); options.addChild( includePath ); } Xpp3Dom standardIncludePath = new Xpp3Dom( "option" ); standardIncludePath.setValue( "-I" + "src/main/include" ); options.addChild( standardIncludePath ); Xpp3Dom rootIncludePath = new Xpp3Dom( "option" ); rootIncludePath.setValue( "-I" + sourceDirectory ); options.addChild( rootIncludePath ); } } private String[] generateCommandLine( File swig, File swigInclude, File swigJavaInclude ) throws MojoExecutionException, MojoFailureException { List cmdLine = new ArrayList(); cmdLine.add( swig.toString() ); if ( fakeVersion != null ) { cmdLine.add( "-fakeversion" ); cmdLine.add( fakeVersion ); } if ( getLog().isDebugEnabled() ) { cmdLine.add( "-v" ); } // FIXME hardcoded cmdLine.add( "-java" ); if ( cpp ) { cmdLine.add( "-c++" ); } // defines if ( defines != null ) { for ( Iterator i = defines.iterator(); i.hasNext(); ) { cmdLine.add( "-D" + i.next() ); } } // warnings if ( noWarn != null ) { String noWarns[] = noWarn.split( ",| " ); for ( int i = 0; i < noWarns.length; i++ ) { cmdLine.add( "-w" + noWarns[i] ); } } if ( warnAll ) { cmdLine.add( "-Wall" ); } if ( warnError ) { cmdLine.add( "-Werror" ); } // output file String baseName = FileUtils.basename( source ); cmdLine.add( "-o" ); File outputFile = outFile != null ? new File( targetDirectory, outFile ) : new File( targetDirectory, baseName + ( cpp ? "cxx" : "c" ) ); cmdLine.add( outputFile.toString() ); // package for java code if ( packageName != null ) { cmdLine.add( "-package" ); cmdLine.add( packageName ); } // output dir for java code cmdLine.add( "-outdir" ); cmdLine.add( javaTargetDirectory ); // user added include dirs if ( includePaths != null ) { for ( Iterator i = includePaths.iterator(); i.hasNext(); ) { cmdLine.add( "-I" + i.next() ); } } // default include dirs cmdLine.add( "-I" + "src/main/include" ); cmdLine.add( "-I" + sourceDirectory ); // NAR dependency include dirs NarLayout narLayout = AbstractNarLayout.getLayout( layout, getLog() ); List narIncludes = narManager.getNarDependencies( "compile" ); for ( Iterator i = narIncludes.iterator(); i.hasNext(); ) { Artifact narInclude = (Artifact) i.next(); File narIncludeDir = narLayout.getIncludeDirectory( unpackDirectory, narInclude.getArtifactId(), narInclude.getVersion() ); if ( narIncludeDir.isDirectory() ) { cmdLine.add( "-I" + narIncludeDir ); } } // system swig include dirs if ( swigJavaInclude != null ) { cmdLine.add( "-I" + swigJavaInclude.toString() ); } if ( swigInclude != null ) { cmdLine.add( "-I" + swigInclude.toString() ); } + // custom include paths + if (includePaths != null && !includePaths.isEmpty()) + { + for ( Iterator i = includePaths.iterator(); i.hasNext(); ) + { + cmdLine.add( "-I" + i.next() ); + } + } + // swig file cmdLine.add( sourceDirectory + source ); StringBuffer b = new StringBuffer(); for ( Iterator i = cmdLine.iterator(); i.hasNext(); ) { b.append( (String) i.next() ); if ( i.hasNext() ) { b.append( ' ' ); } } getLog().info( b.toString() ); return (String[]) cmdLine.toArray( new String[cmdLine.size()] ); } private int runCommand( String[] cmdLine ) throws MojoExecutionException { try { final int timeout = 5000; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec( cmdLine ); StreamGobbler errorGobbler = new StreamGobbler( process.getErrorStream(), true ); StreamGobbler outputGobbler = new StreamGobbler( process.getInputStream(), false ); errorGobbler.start(); outputGobbler.start(); process.waitFor(); errorGobbler.join( timeout ); outputGobbler.join( timeout ); return process.exitValue(); } catch ( Exception e ) { throw new MojoExecutionException( "Could not launch " + cmdLine[0], e ); } } private class StreamGobbler extends Thread { private InputStream is; private boolean error; StreamGobbler( InputStream is, boolean error ) { this.is = is; this.error = error; } public void run() { try { BufferedReader reader = new BufferedReader( new InputStreamReader( is ) ); String line = null; while ( ( line = reader.readLine() ) != null ) { if ( error ) { getLog().error( line ); } else { getLog().debug( line ); } } reader.close(); } catch ( IOException e ) { getLog().error( e ); } } } }
true
false
null
null
diff --git a/src/test/java/herbstJennrichLehmannRitter/tests/model/DataTests.java b/src/test/java/herbstJennrichLehmannRitter/tests/model/DataTests.java index 73791f8..434e5b3 100644 --- a/src/test/java/herbstJennrichLehmannRitter/tests/model/DataTests.java +++ b/src/test/java/herbstJennrichLehmannRitter/tests/model/DataTests.java @@ -1,34 +1,34 @@ package herbstJennrichLehmannRitter.tests.model; import static org.junit.Assert.assertEquals; import herbstJennrichLehmannRitter.engine.model.Player; import herbstJennrichLehmannRitter.engine.model.impl.DataImpl; import herbstJennrichLehmannRitter.engine.model.impl.PlayerImpl; import org.junit.Before; import org.junit.Test; public class DataTests { private Player player = new PlayerImpl(); private DataImpl data = new DataImpl(); @Before public void before() { this.player = new PlayerImpl(); this.data = new DataImpl(); } @Test public void testOwnPlayer() { this.data.setOwnPlayer(this.player); - assertEquals(data.getOwnPlayer(), this.player); + assertEquals(this.data.getOwnPlayer(), this.player); } @Test public void testEnemyPlayer() { - data.setEnemyPlayer(this.player); - assertEquals(data.getEnemyPlayer(), this.player); + this.data.setEnemyPlayer(this.player); + assertEquals(this.data.getEnemyPlayer(), this.player); } }
false
false
null
null