diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/server/ServerThread.java b/server/ServerThread.java index 4db644e..051335d 100644 --- a/server/ServerThread.java +++ b/server/ServerThread.java @@ -1,176 +1,176 @@ package server; import game.ClientMessage; import game.GameWorld; import game.WorldDelta; import game.things.Player; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.io.*; import java.net.*; import data.Database; import serialization.Tree; import util.*; //new ClientMessage(mygid, new ClientMessage.Interaction(thatgid, foo)).apply(game); /** * A Server thread receives xml formatted-instructions from a client connection via a socket. * These intructions are registered with the game model. The Server connection is also * responsible for transmitting information to the client about the updates to the game * state. */ public final class ServerThread { private final GameWorld model; private int usrNo; private long usrGID; private String usrName; private final Socket socket; private LinkedBlockingQueue<String> outqueue = new LinkedBlockingQueue<String>(); boolean exit=false; private Listener listener = new Listener(this); private Talker talker = new Talker(this); private Server server; private static class Listener extends Thread { private ServerThread parent; public Listener(ServerThread parent) { this.parent = parent; } public void run() { Player plyr = null; try { InputStreamReader input = new InputStreamReader(parent.socket.getInputStream()); BufferedReader rd = new BufferedReader(input); while(!parent.exit) { String temp; temp = rd.readLine(); if(temp == null) { // End of stream break; } try { if((temp.startsWith("uid"))) { String name = temp.substring(4); if(parent.model.checkPlayer(parent.usrName)){ plyr = parent.model.getPlayer(parent.usrName, null); plyr.login(); System.err.println("plyr logged in"); // parent.model.level(0).location(new Position((int)(Math.random()*10 - 5), (int)(Math.random()*10 - 5)), Direction.NORTH).put(plyr); parent.usrGID = plyr.gid(); parent.queueMessage("uid " + parent.usrGID + "\n"); } else{ parent.queueMessage("noid"); } } else if(temp.startsWith("cid")){ String character = temp.substring(4); plyr = parent.model.getPlayer(parent.usrName, character); plyr.login(); System.err.println("plyr logged in"); parent.usrGID = plyr.gid(); - parent.queueMessage("uid " + parent.usrGID + "\n"); + parent.queueMessage("uid " + parent.usrGID + "::::" + character + "\n"); } else if(temp.startsWith("cmg")){ String action = temp.substring(4); action = Database.unescapeNewLines(action); ClientMessage msg = (ClientMessage.serializer(parent.model, parent.usrGID)).read(Tree.fromString(action)); msg.apply(parent.model); } else if(temp.startsWith("cts")) { String chat = temp.substring(4); final String msg = "ctc "+chat+"\n"; parent.server.toAllPlayers(new Server.ClientMessenger() { @Override public void doTo(ServerThread client) { client.queueMessage(msg); } }); } } catch (Exception e) { // Catch everything while processing message System.err.println("Exception handling message from client..."); e.printStackTrace(); } } } catch(IOException e) { System.err.println("PLAYER " + parent.usrNo +"/" + "usrName" + " DISCONNECTED"); } finally{ parent.exit = true; if(plyr != null){ plyr.logout(); System.err.println("plyr logedout"); } } } } private static class Talker extends Thread { private ServerThread parent; public Talker(ServerThread parent) { this.parent = parent; } public void run() { try { OutputStreamWriter output = new OutputStreamWriter(parent.socket.getOutputStream()); BufferedWriter bw = new BufferedWriter(output); while(!parent.exit) { String msg = null; try { msg = parent.outqueue.poll(2, TimeUnit.SECONDS); } catch (InterruptedException e) {} if(msg != null) { bw.write(msg); bw.flush(); } } } catch(IOException e) { System.err.println("PLAYER " + parent.usrNo +"/" + "usrName" + " DISCONNECTED"); } parent.exit = true; } } public ServerThread(Socket socket, int usrNo, GameWorld model, Server server) { this.model = model; this.socket = socket; this.usrNo = usrNo; this.server = server; } public void addDelta(WorldDelta d){ String deltaupdate = Database.escapeNewLines(Database.treeToString(WorldDelta.SERIALIZER.write(d))); this.queueMessage("upd " + deltaupdate + "\n"); } private void queueMessage(String msg) { outqueue.add(msg); } public void start() { listener.start(); talker.start(); } public boolean isAlive(){ return !exit; } public String name() { return usrName; } }
true
true
public void run() { Player plyr = null; try { InputStreamReader input = new InputStreamReader(parent.socket.getInputStream()); BufferedReader rd = new BufferedReader(input); while(!parent.exit) { String temp; temp = rd.readLine(); if(temp == null) { // End of stream break; } try { if((temp.startsWith("uid"))) { String name = temp.substring(4); if(parent.model.checkPlayer(parent.usrName)){ plyr = parent.model.getPlayer(parent.usrName, null); plyr.login(); System.err.println("plyr logged in"); // parent.model.level(0).location(new Position((int)(Math.random()*10 - 5), (int)(Math.random()*10 - 5)), Direction.NORTH).put(plyr); parent.usrGID = plyr.gid(); parent.queueMessage("uid " + parent.usrGID + "\n"); } else{ parent.queueMessage("noid"); } } else if(temp.startsWith("cid")){ String character = temp.substring(4); plyr = parent.model.getPlayer(parent.usrName, character); plyr.login(); System.err.println("plyr logged in"); parent.usrGID = plyr.gid(); parent.queueMessage("uid " + parent.usrGID + "\n"); } else if(temp.startsWith("cmg")){ String action = temp.substring(4); action = Database.unescapeNewLines(action); ClientMessage msg = (ClientMessage.serializer(parent.model, parent.usrGID)).read(Tree.fromString(action)); msg.apply(parent.model); } else if(temp.startsWith("cts")) { String chat = temp.substring(4); final String msg = "ctc "+chat+"\n"; parent.server.toAllPlayers(new Server.ClientMessenger() { @Override public void doTo(ServerThread client) { client.queueMessage(msg); } }); } } catch (Exception e) { // Catch everything while processing message System.err.println("Exception handling message from client..."); e.printStackTrace(); } } } catch(IOException e) { System.err.println("PLAYER " + parent.usrNo +"/" + "usrName" + " DISCONNECTED"); } finally{ parent.exit = true; if(plyr != null){ plyr.logout(); System.err.println("plyr logedout"); } } }
public void run() { Player plyr = null; try { InputStreamReader input = new InputStreamReader(parent.socket.getInputStream()); BufferedReader rd = new BufferedReader(input); while(!parent.exit) { String temp; temp = rd.readLine(); if(temp == null) { // End of stream break; } try { if((temp.startsWith("uid"))) { String name = temp.substring(4); if(parent.model.checkPlayer(parent.usrName)){ plyr = parent.model.getPlayer(parent.usrName, null); plyr.login(); System.err.println("plyr logged in"); // parent.model.level(0).location(new Position((int)(Math.random()*10 - 5), (int)(Math.random()*10 - 5)), Direction.NORTH).put(plyr); parent.usrGID = plyr.gid(); parent.queueMessage("uid " + parent.usrGID + "\n"); } else{ parent.queueMessage("noid"); } } else if(temp.startsWith("cid")){ String character = temp.substring(4); plyr = parent.model.getPlayer(parent.usrName, character); plyr.login(); System.err.println("plyr logged in"); parent.usrGID = plyr.gid(); parent.queueMessage("uid " + parent.usrGID + "::::" + character + "\n"); } else if(temp.startsWith("cmg")){ String action = temp.substring(4); action = Database.unescapeNewLines(action); ClientMessage msg = (ClientMessage.serializer(parent.model, parent.usrGID)).read(Tree.fromString(action)); msg.apply(parent.model); } else if(temp.startsWith("cts")) { String chat = temp.substring(4); final String msg = "ctc "+chat+"\n"; parent.server.toAllPlayers(new Server.ClientMessenger() { @Override public void doTo(ServerThread client) { client.queueMessage(msg); } }); } } catch (Exception e) { // Catch everything while processing message System.err.println("Exception handling message from client..."); e.printStackTrace(); } } } catch(IOException e) { System.err.println("PLAYER " + parent.usrNo +"/" + "usrName" + " DISCONNECTED"); } finally{ parent.exit = true; if(plyr != null){ plyr.logout(); System.err.println("plyr logedout"); } } }
diff --git a/src/org/python/antlr/PythonTokenSource.java b/src/org/python/antlr/PythonTokenSource.java index 3e0ed69b..35f86f88 100644 --- a/src/org/python/antlr/PythonTokenSource.java +++ b/src/org/python/antlr/PythonTokenSource.java @@ -1,379 +1,386 @@ package org.python.antlr; import org.python.core.Py; /* [The "BSD licence"] Copyright (c) 2004 Terence Parr and Loring Craymer 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 name of the author may not 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. */ import org.antlr.runtime.*; import java.util.*; /** Python does not explicitly provide begin and end nesting signals. Rather, the indentation level indicates when you begin and end. This is an interesting lexical problem because multiple DEDENT tokens should be sent to the parser sometimes without a corresponding input symbol! Consider the following example: a=1 if a>1: print a b=3 Here the "b" token on the left edge signals that a DEDENT is needed after the "print a \n" and before the "b". The sequence should be ... 1 COLON NEWLINE INDENT PRINT a NEWLINE DEDENT b ASSIGN 3 ... For more examples, see the big comment at the bottom of this file. This TokenStream normally just passes tokens through to the parser. Upon NEWLINE token from the lexer, however, an INDENT or DEDENT token may need to be sent to the parser. The NEWLINE is the trigger for this class to do it's job. NEWLINE is saved and then the first token of the next line is examined. If non-leading-whitespace token, then check against stack for indent vs dedent. If LEADING_WS, then the column of the next non-whitespace token will dictate indent vs dedent. The column of the next real token is number of spaces in the LEADING_WS token + 1 (to move past the whitespace). The lexer grammar must set the text of the LEADING_WS token to be the proper number of spaces (and do tab conversion etc...). A stack of column numbers is tracked and used to detect changes in indent level from one token to the next. A queue of tokens is built up to hold multiple DEDENT tokens that are generated. Before asking the lexer for another token via nextToken(), the queue is flushed first one token at a time. Terence Parr and Loring Craymer February 2004 */ public class PythonTokenSource implements TokenSource { public static final int MAX_INDENTS = 100; public static final int FIRST_CHAR_POSITION = 0; /** The stack of indent levels (column numbers) */ int[] indentStack = new int[MAX_INDENTS]; /** stack pointer */ int sp=-1; // grow upwards /** The queue of tokens */ Vector tokens = new Vector(); /** We pull real tokens from this lexer */ CommonTokenStream stream; int lastTokenAddedIndex = -1; String filename; boolean inSingle; public PythonTokenSource(PythonLexer lexer) { } public PythonTokenSource(CommonTokenStream stream, String filename) { this(stream, filename, false); } public PythonTokenSource(CommonTokenStream stream, String filename, boolean single) { this.stream = stream; this.filename = filename; this.inSingle = single; // "state" of indent level is FIRST_CHAR_POSITION push(FIRST_CHAR_POSITION); } /** From http://www.python.org/doc/2.2.3/ref/indentation.html "Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line's indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero." I use char position in line 0..n-1 instead. The DEDENTS possibly needed at EOF are gracefully handled by forcing EOF to have char pos 0 even though with UNIX it's hard to get EOF at a non left edge. */ public Token nextToken() { // if something in queue, just remove and return it if (tokens.size() > 0) { Token t = (Token)tokens.firstElement(); tokens.removeElementAt(0); //System.out.println(filename + t); return t; } insertImaginaryIndentDedentTokens(); return nextToken(); } private void generateNewline(Token t) { CommonToken newline = new CommonToken(PythonLexer.NEWLINE, "\n"); newline.setLine(t.getLine()); newline.setCharPositionInLine(t.getCharPositionInLine()); tokens.addElement(newline); } private void handleEOF(CommonToken eof, CommonToken prev) { if (prev != null) { eof.setStartIndex(prev.getStopIndex()); eof.setStopIndex(prev.getStopIndex()); } } protected void insertImaginaryIndentDedentTokens() { Token t = stream.LT(1); stream.consume(); if (t.getType() == Token.EOF) { Token prev = stream.LT(-1); handleEOF((CommonToken)t, (CommonToken)prev); if (!inSingle) { - if (prev == null || prev.getType() != PythonLexer.NEWLINE) { + if (prev == null) { generateNewline(t); + } else if (prev.getType() == PythonLexer.LEADING_WS) { + handleDedents(-1, (CommonToken)t); + generateNewline(t); + } else if (prev.getType() != PythonLexer.NEWLINE) { + generateNewline(t); + handleDedents(-1, (CommonToken)t); } + } else { + handleDedents(-1, (CommonToken)t); } - handleDedents(-1, (CommonToken)t); enqueue(t); } else if (t.getType() == PythonLexer.NEWLINE) { // save NEWLINE in the queue //System.out.println("found newline: "+t+" stack is "+stackString()); enqueueHiddens(t); tokens.addElement(t); Token newline = t; // grab first token of next line t = stream.LT(1); stream.consume(); enqueueHiddens(t); // compute cpos as the char pos of next non-WS token in line int cpos = t.getCharPositionInLine(); // column dictates indent/dedent if (t.getType() == Token.EOF) { handleEOF((CommonToken)t, (CommonToken)newline); cpos = -1; // pretend EOF always happens at left edge } else if (t.getType() == PythonLexer.LEADING_WS) { Token next = stream.LT(1); if (next != null && next.getType() == Token.EOF) { stream.consume(); return; } else { cpos = t.getText().length(); } } //System.out.println("next token is: "+t); // compare to last indent level int lastIndent = peek(); //System.out.println("cpos, lastIndent = "+cpos+", "+lastIndent); if (cpos > lastIndent) { // they indented; track and gen INDENT handleIndents(cpos, (CommonToken)t); } else if (cpos < lastIndent) { // they dedented handleDedents(cpos, (CommonToken)t); } if (t.getType() == Token.EOF && inSingle) { String newlines = newline.getText(); for(int i=1;i<newlines.length();i++) { generateNewline(newline); } } if (t.getType() != PythonLexer.LEADING_WS) { // discard WS tokens.addElement(t); } } else { enqueue(t); } } private void enqueue(Token t) { enqueueHiddens(t); tokens.addElement(t); } private void enqueueHiddens(Token t) { if (inSingle && t.getType() == Token.EOF) { if (stream.size() > lastTokenAddedIndex + 1) { Token hidden = stream.get(lastTokenAddedIndex + 1); if (hidden.getType() == PythonLexer.COMMENT) { String text = hidden.getText(); int i = text.indexOf("\n"); while(i != -1) { generateNewline(hidden); i = text.indexOf("\n", i + 1); } } } } List hiddenTokens = stream.getTokens(lastTokenAddedIndex + 1,t.getTokenIndex() - 1); if (hiddenTokens != null) { tokens.addAll(hiddenTokens); } lastTokenAddedIndex = t.getTokenIndex(); } private void handleIndents(int cpos, CommonToken t) { push(cpos); //System.out.println("push("+cpos+"): "+stackString()); CommonToken indent = new CommonToken(PythonParser.INDENT,""); indent.setCharPositionInLine(t.getCharPositionInLine()); indent.setLine(t.getLine()); indent.setStartIndex(t.getStartIndex() - 1); indent.setStopIndex(t.getStartIndex() - 1); tokens.addElement(indent); } private void handleDedents(int cpos, CommonToken t) { // how far back did we dedent? int prevIndex = findPreviousIndent(cpos, t); //System.out.println("dedented; prevIndex of cpos="+cpos+" is "+prevIndex); // generate DEDENTs for each indent level we backed up over for (int d = sp - 1; d >= prevIndex; d--) { CommonToken dedent = new CommonToken(PythonParser.DEDENT,""); dedent.setCharPositionInLine(t.getCharPositionInLine()); dedent.setLine(t.getLine()); dedent.setStartIndex(t.getStartIndex() - 1); dedent.setStopIndex(t.getStartIndex() - 1); tokens.addElement(dedent); } sp = prevIndex; // pop those off indent level } // T O K E N S T A C K M E T H O D S protected void push(int i) { if (sp >= MAX_INDENTS) { throw new IllegalStateException("stack overflow"); } sp++; indentStack[sp] = i; } protected int pop() { if (sp<0) { throw new IllegalStateException("stack underflow"); } int top = indentStack[sp]; sp--; return top; } protected int peek() { return indentStack[sp]; } /** Return the index on stack of previous indent level == i else -1 */ protected int findPreviousIndent(int i, Token t) { for (int j = sp - 1; j >= 0; j--) { if (indentStack[j] == i) { return j; } } //The -2 is for the special case of getCharPositionInLine in multiline str nodes. if (i == -1 || i == -2) { return FIRST_CHAR_POSITION; } ParseException p = new ParseException("unindent does not match any outer indentation level", t.getLine(), t.getCharPositionInLine()); p.setType(Py.IndentationError); throw p; } public String stackString() { StringBuffer buf = new StringBuffer(); for (int j = sp; j >= 0; j--) { buf.append(" "); buf.append(indentStack[j]); } return buf.toString(); } public String getSourceName() { return filename; } } /* More example input / output pairs with code simplified to single chars ------- t1 ------- a a b b c d a a \n INDENT b b \n c \n DEDENT d \n EOF ------- t2 ------- a c b c a c \n INDENT b \n DEDENT c \n EOF ------- t3 ------- a b c d a \n INDENT b \n INDENT c \n DEDENT DEDENT d \n EOF ------- t4 ------- a c d e f g h i j k a \n INDENT c \n INDENT d \n DEDENT e \n f \n INDENT g \n h \n i \n INDENT j \n DEDENT DEDENT k \n DEDENT EOF ------- t5 ------- a b c d e a \n INDENT b \n c \n INDENT d \n e \n DEDENT DEDENT EOF */
false
true
protected void insertImaginaryIndentDedentTokens() { Token t = stream.LT(1); stream.consume(); if (t.getType() == Token.EOF) { Token prev = stream.LT(-1); handleEOF((CommonToken)t, (CommonToken)prev); if (!inSingle) { if (prev == null || prev.getType() != PythonLexer.NEWLINE) { generateNewline(t); } } handleDedents(-1, (CommonToken)t); enqueue(t); } else if (t.getType() == PythonLexer.NEWLINE) { // save NEWLINE in the queue //System.out.println("found newline: "+t+" stack is "+stackString()); enqueueHiddens(t); tokens.addElement(t); Token newline = t; // grab first token of next line t = stream.LT(1); stream.consume(); enqueueHiddens(t); // compute cpos as the char pos of next non-WS token in line int cpos = t.getCharPositionInLine(); // column dictates indent/dedent if (t.getType() == Token.EOF) { handleEOF((CommonToken)t, (CommonToken)newline); cpos = -1; // pretend EOF always happens at left edge } else if (t.getType() == PythonLexer.LEADING_WS) { Token next = stream.LT(1); if (next != null && next.getType() == Token.EOF) { stream.consume(); return; } else { cpos = t.getText().length(); } } //System.out.println("next token is: "+t); // compare to last indent level int lastIndent = peek(); //System.out.println("cpos, lastIndent = "+cpos+", "+lastIndent); if (cpos > lastIndent) { // they indented; track and gen INDENT handleIndents(cpos, (CommonToken)t); } else if (cpos < lastIndent) { // they dedented handleDedents(cpos, (CommonToken)t); } if (t.getType() == Token.EOF && inSingle) { String newlines = newline.getText(); for(int i=1;i<newlines.length();i++) { generateNewline(newline); } } if (t.getType() != PythonLexer.LEADING_WS) { // discard WS tokens.addElement(t); } } else { enqueue(t); } }
protected void insertImaginaryIndentDedentTokens() { Token t = stream.LT(1); stream.consume(); if (t.getType() == Token.EOF) { Token prev = stream.LT(-1); handleEOF((CommonToken)t, (CommonToken)prev); if (!inSingle) { if (prev == null) { generateNewline(t); } else if (prev.getType() == PythonLexer.LEADING_WS) { handleDedents(-1, (CommonToken)t); generateNewline(t); } else if (prev.getType() != PythonLexer.NEWLINE) { generateNewline(t); handleDedents(-1, (CommonToken)t); } } else { handleDedents(-1, (CommonToken)t); } enqueue(t); } else if (t.getType() == PythonLexer.NEWLINE) { // save NEWLINE in the queue //System.out.println("found newline: "+t+" stack is "+stackString()); enqueueHiddens(t); tokens.addElement(t); Token newline = t; // grab first token of next line t = stream.LT(1); stream.consume(); enqueueHiddens(t); // compute cpos as the char pos of next non-WS token in line int cpos = t.getCharPositionInLine(); // column dictates indent/dedent if (t.getType() == Token.EOF) { handleEOF((CommonToken)t, (CommonToken)newline); cpos = -1; // pretend EOF always happens at left edge } else if (t.getType() == PythonLexer.LEADING_WS) { Token next = stream.LT(1); if (next != null && next.getType() == Token.EOF) { stream.consume(); return; } else { cpos = t.getText().length(); } } //System.out.println("next token is: "+t); // compare to last indent level int lastIndent = peek(); //System.out.println("cpos, lastIndent = "+cpos+", "+lastIndent); if (cpos > lastIndent) { // they indented; track and gen INDENT handleIndents(cpos, (CommonToken)t); } else if (cpos < lastIndent) { // they dedented handleDedents(cpos, (CommonToken)t); } if (t.getType() == Token.EOF && inSingle) { String newlines = newline.getText(); for(int i=1;i<newlines.length();i++) { generateNewline(newline); } } if (t.getType() != PythonLexer.LEADING_WS) { // discard WS tokens.addElement(t); } } else { enqueue(t); } }
diff --git a/src/com/legit2/Demigods/Listeners/DDivineBlockListener.java b/src/com/legit2/Demigods/Listeners/DDivineBlockListener.java index 14eebaea..a24fd8db 100644 --- a/src/com/legit2/Demigods/Listeners/DDivineBlockListener.java +++ b/src/com/legit2/Demigods/Listeners/DDivineBlockListener.java @@ -1,366 +1,367 @@ package com.legit2.Demigods.Listeners; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockBurnEvent; import org.bukkit.event.block.BlockDamageEvent; import org.bukkit.event.block.BlockIgniteEvent; import org.bukkit.event.block.BlockPistonExtendEvent; import org.bukkit.event.block.BlockPistonRetractEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import com.legit2.Demigods.DConfig; import com.legit2.Demigods.DDivineBlocks; import com.legit2.Demigods.Demigods; import com.legit2.Demigods.DTributeValue; import com.legit2.Demigods.Utilities.DCharUtil; import com.legit2.Demigods.Utilities.DDataUtil; import com.legit2.Demigods.Utilities.DPlayerUtil; import com.legit2.Demigods.Utilities.DMiscUtil; public class DDivineBlockListener implements Listener { static Demigods plugin; public static double FAVORMULTIPLIER = DConfig.getSettingDouble("global_favor_multiplier"); public static int RADIUS = 8; public DDivineBlockListener(Demigods instance) { plugin = instance; } /* -------------------------------------------- * Handle DivineBlock Interactions * -------------------------------------------- */ @EventHandler (priority = EventPriority.HIGH) public void shrineInteract(PlayerInteractEvent event) { // Exit method if it isn't a block of gold or if the player is mortal if(!DCharUtil.isImmortal(event.getPlayer())) return; if(event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; // Define variables Location location = event.getClickedBlock().getLocation(); Player player = event.getPlayer(); int charID = DPlayerUtil.getCurrentChar(player); String charAlliance = DCharUtil.getAlliance(charID); String charDeity = DCharUtil.getDeity(charID); if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getPlayer().getItemInHand().getType() == Material.BOOK) { try { // Shrine created! ArrayList<Location> locations = new ArrayList<Location>(); locations.add(location); DDivineBlocks.createShrine(charID, locations); location.getWorld().getBlockAt(location).setType(Material.BEDROCK); location.getWorld().spawnEntity(location.add(0.5, 0.0, 0.5), EntityType.ENDER_CRYSTAL); location.getWorld().strikeLightningEffect(location); player.sendMessage(ChatColor.GRAY + "The " + ChatColor.YELLOW + charAlliance + "s" + ChatColor.GRAY + " are pleased..."); player.sendMessage(ChatColor.GRAY + "A shrine has been created in honor of " + ChatColor.YELLOW + charDeity + ChatColor.GRAY + "!"); } catch(Exception e) { // Creation of shrine failed... e.printStackTrace(); } } try { // Check if block is divine int shrineOwner = DDivineBlocks.getShrineOwner(location); + OfflinePlayer charOwner = DCharUtil.getOwner(shrineOwner); String shrineDeity = DDivineBlocks.getShrineDeity(location); if(shrineDeity == null) return; - if(DDivineBlocks.isDivineBlock(location)) + if(DDivineBlocks.isDivineBlock(location) || DDivineBlocks.isDivineBlock(location.subtract(0.5, 0, 0.5))) { // Check if character has deity if(DCharUtil.hasDeity(charID, shrineDeity)) { // Open the tribute inventory - Inventory ii = DMiscUtil.getPlugin().getServer().createInventory(player, 27, DCharUtil.getName(shrineOwner) + "'s Shrine"); + Inventory ii = DMiscUtil.getPlugin().getServer().createInventory(player, 27, charOwner.getName() + "'s Shrine to " + shrineDeity); player.openInventory(ii); DDataUtil.saveCharData(charID, "temp_tributing", DDivineBlocks.getShrineOwner(event.getClickedBlock().getLocation())); event.setCancelled(true); return; } player.sendMessage(ChatColor.YELLOW + "You must be allied to " + shrineDeity + " in order to tribute here."); } } catch(Exception e) {} } /* -------------------------------------------- * Handle Player Tributing * -------------------------------------------- */ @EventHandler (priority = EventPriority.MONITOR) public void playerTribute(InventoryCloseEvent event) { try { if(!(event.getPlayer() instanceof Player)) return; Player player = (Player)event.getPlayer(); int charID = DPlayerUtil.getCurrentChar(player); if(!DCharUtil.isImmortal(player)) return; // If it isn't a tribute chest then break the method if(!event.getInventory().getName().equals("Tributes")) return; // Get the creator of the shrine //int shrineCreator = DDivineBlocks.getOwnerOfShrine((Location) DDataUtil.getCharData(charID, "tributing_temp")); DDataUtil.removeCharData(charID, "temp_tributing"); //calculate value of chest int tirbuteValue = 0; int items = 0; for(ItemStack ii : event.getInventory().getContents()) { if(ii != null) { tirbuteValue += DTributeValue.getTributeValue(ii); items ++; } } tirbuteValue *= FAVORMULTIPLIER; // Give devotion int devotionBefore = DCharUtil.getDevotion(charID); DCharUtil.giveDevotion(charID, tirbuteValue); DCharUtil.giveDevotion(charID, tirbuteValue / 7); // Give favor int favorBefore = DCharUtil.getMaxFavor(charID); //DUtil.setFavorCap(player, DUtil.getFavorCap(username)+value/5); TODO // Devotion lock TODO String charName = DCharUtil.getName(charID); if(devotionBefore < DCharUtil.getDevotion(charID)) player.sendMessage(ChatColor.YELLOW + "Your devotion to " + charName + " has increased to " + DCharUtil.getDevotion(charID) + "."); if(favorBefore < DCharUtil.getMaxFavor(charID)) player.sendMessage(ChatColor.YELLOW + "Your favor cap has increased to " + DCharUtil.getMaxFavor(charID) + "."); if((favorBefore == DCharUtil.getMaxFavor(charID)) && (devotionBefore == DCharUtil.getDevotion(charID)) && (items > 0)) player.sendMessage(ChatColor.YELLOW + "Your tributes were insufficient for " + charName + "'s blessings."); // Clear the tribute case event.getInventory().clear(); } catch(Exception e) {} } /* -------------------------------------------- * Handle Miscellaneous Divine Block Events * -------------------------------------------- */ @EventHandler(priority = EventPriority.HIGH) public void divineBlockAlerts(PlayerMoveEvent event) { if(event.getFrom().distance(event.getTo()) < 0.1) return; // Define variables for(Location divineBlock : DDivineBlocks.getAllShrines()) { OfflinePlayer charOwner = DCharUtil.getOwner(DDivineBlocks.getShrineOwner(divineBlock)); // Check for world errors if(!divineBlock.getWorld().equals(event.getPlayer().getWorld())) return; if(event.getFrom().getWorld() != divineBlock.getWorld()) return; /* * Entering */ if(event.getFrom().distance(divineBlock) > RADIUS) { if(divineBlock.distance(event.getTo()) <= RADIUS) { event.getPlayer().sendMessage(ChatColor.GRAY + "You have entered " + charOwner.getName() + "'s shrine to " + ChatColor.YELLOW + DDivineBlocks.getShrineDeity(divineBlock) + ChatColor.GRAY + "."); return; } } /* * Leaving */ else if(event.getFrom().distance(divineBlock) <= RADIUS) { if(divineBlock.distance(event.getTo()) > RADIUS) { event.getPlayer().sendMessage(ChatColor.GRAY + "You have left a holy area."); return; } } } } @EventHandler(priority = EventPriority.HIGHEST) public static void stopDestroyEnderCrystal(EntityDamageEvent event) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(event.getEntity().getLocation().subtract(0.5, 0, 0.5).equals(divineBlock)) { event.setDamage(0); event.setCancelled(true); return; } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public static void stopDestroyDivineBlock(BlockBreakEvent event) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(event.getBlock().getLocation().equals(divineBlock)) { event.getPlayer().sendMessage(ChatColor.YELLOW + "Divine blocks cannot be broken by hand."); event.setCancelled(true); return; } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public void stopDivineBlockDamage(BlockDamageEvent event) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(event.getBlock().getLocation().equals(divineBlock)) { event.setCancelled(true); } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public void stopDivineBlockIgnite(BlockIgniteEvent event) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(event.getBlock().getLocation().equals(divineBlock)) { event.setCancelled(true); } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public void stopDivineBlockBurn(BlockBurnEvent event) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(event.getBlock().getLocation().equals(divineBlock)) { event.setCancelled(true); } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public void stopDivineBlockPistonExtend(BlockPistonExtendEvent event) { List<Block> blocks = event.getBlocks(); CHECKBLOCKS: for(Block block : blocks) { try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(block.getLocation().equals(divineBlock)) { event.setCancelled(true); break CHECKBLOCKS; } } } catch(Exception e) { e.printStackTrace(); } } } @EventHandler(priority = EventPriority.HIGHEST) public void stopDivineBlockPistonRetract(BlockPistonRetractEvent event) { // Define variables final Block block = event.getBlock().getRelative(event.getDirection(), 2); try { for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(block.getLocation().equals((divineBlock)) && event.isSticky()) { event.setCancelled(true); } } } catch(Exception e) {} } @EventHandler(priority = EventPriority.HIGHEST) public void divineBlockExplode(final EntityExplodeEvent event) { try { // Remove divineBlock blocks from explosions Iterator<Block> i = event.blockList().iterator(); while(i.hasNext()) { Block block = i.next(); if(!DMiscUtil.canLocationPVP(block.getLocation())) i.remove(); for(Location divineBlock : DDivineBlocks.getAllDivineBlocks()) { if(block.getLocation().equals(divineBlock)) i.remove(); } } } catch (Exception er) {} } }
false
true
public void shrineInteract(PlayerInteractEvent event) { // Exit method if it isn't a block of gold or if the player is mortal if(!DCharUtil.isImmortal(event.getPlayer())) return; if(event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; // Define variables Location location = event.getClickedBlock().getLocation(); Player player = event.getPlayer(); int charID = DPlayerUtil.getCurrentChar(player); String charAlliance = DCharUtil.getAlliance(charID); String charDeity = DCharUtil.getDeity(charID); if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getPlayer().getItemInHand().getType() == Material.BOOK) { try { // Shrine created! ArrayList<Location> locations = new ArrayList<Location>(); locations.add(location); DDivineBlocks.createShrine(charID, locations); location.getWorld().getBlockAt(location).setType(Material.BEDROCK); location.getWorld().spawnEntity(location.add(0.5, 0.0, 0.5), EntityType.ENDER_CRYSTAL); location.getWorld().strikeLightningEffect(location); player.sendMessage(ChatColor.GRAY + "The " + ChatColor.YELLOW + charAlliance + "s" + ChatColor.GRAY + " are pleased..."); player.sendMessage(ChatColor.GRAY + "A shrine has been created in honor of " + ChatColor.YELLOW + charDeity + ChatColor.GRAY + "!"); } catch(Exception e) { // Creation of shrine failed... e.printStackTrace(); } } try { // Check if block is divine int shrineOwner = DDivineBlocks.getShrineOwner(location); String shrineDeity = DDivineBlocks.getShrineDeity(location); if(shrineDeity == null) return; if(DDivineBlocks.isDivineBlock(location)) { // Check if character has deity if(DCharUtil.hasDeity(charID, shrineDeity)) { // Open the tribute inventory Inventory ii = DMiscUtil.getPlugin().getServer().createInventory(player, 27, DCharUtil.getName(shrineOwner) + "'s Shrine"); player.openInventory(ii); DDataUtil.saveCharData(charID, "temp_tributing", DDivineBlocks.getShrineOwner(event.getClickedBlock().getLocation())); event.setCancelled(true); return; } player.sendMessage(ChatColor.YELLOW + "You must be allied to " + shrineDeity + " in order to tribute here."); } } catch(Exception e) {} }
public void shrineInteract(PlayerInteractEvent event) { // Exit method if it isn't a block of gold or if the player is mortal if(!DCharUtil.isImmortal(event.getPlayer())) return; if(event.getAction() != Action.LEFT_CLICK_BLOCK && event.getAction() != Action.RIGHT_CLICK_BLOCK) return; // Define variables Location location = event.getClickedBlock().getLocation(); Player player = event.getPlayer(); int charID = DPlayerUtil.getCurrentChar(player); String charAlliance = DCharUtil.getAlliance(charID); String charDeity = DCharUtil.getDeity(charID); if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getPlayer().getItemInHand().getType() == Material.BOOK) { try { // Shrine created! ArrayList<Location> locations = new ArrayList<Location>(); locations.add(location); DDivineBlocks.createShrine(charID, locations); location.getWorld().getBlockAt(location).setType(Material.BEDROCK); location.getWorld().spawnEntity(location.add(0.5, 0.0, 0.5), EntityType.ENDER_CRYSTAL); location.getWorld().strikeLightningEffect(location); player.sendMessage(ChatColor.GRAY + "The " + ChatColor.YELLOW + charAlliance + "s" + ChatColor.GRAY + " are pleased..."); player.sendMessage(ChatColor.GRAY + "A shrine has been created in honor of " + ChatColor.YELLOW + charDeity + ChatColor.GRAY + "!"); } catch(Exception e) { // Creation of shrine failed... e.printStackTrace(); } } try { // Check if block is divine int shrineOwner = DDivineBlocks.getShrineOwner(location); OfflinePlayer charOwner = DCharUtil.getOwner(shrineOwner); String shrineDeity = DDivineBlocks.getShrineDeity(location); if(shrineDeity == null) return; if(DDivineBlocks.isDivineBlock(location) || DDivineBlocks.isDivineBlock(location.subtract(0.5, 0, 0.5))) { // Check if character has deity if(DCharUtil.hasDeity(charID, shrineDeity)) { // Open the tribute inventory Inventory ii = DMiscUtil.getPlugin().getServer().createInventory(player, 27, charOwner.getName() + "'s Shrine to " + shrineDeity); player.openInventory(ii); DDataUtil.saveCharData(charID, "temp_tributing", DDivineBlocks.getShrineOwner(event.getClickedBlock().getLocation())); event.setCancelled(true); return; } player.sendMessage(ChatColor.YELLOW + "You must be allied to " + shrineDeity + " in order to tribute here."); } } catch(Exception e) {} }
diff --git a/src/api/org/openmrs/validator/ConceptValidator.java b/src/api/org/openmrs/validator/ConceptValidator.java index 01f76954..8ee9dde4 100644 --- a/src/api/org/openmrs/validator/ConceptValidator.java +++ b/src/api/org/openmrs/validator/ConceptValidator.java @@ -1,124 +1,124 @@ /** * The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org * * 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. * * Copyright (C) OpenMRS, LLC. All Rights Reserved. */ package org.openmrs.validator; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.Concept; import org.openmrs.annotation.Handler; import org.openmrs.api.APIException; import org.openmrs.api.DuplicateConceptNameException; import org.openmrs.api.context.Context; import org.springframework.validation.Errors; import org.springframework.validation.Validator; /** * Validates methods of the {@link Concept} object. */ @Handler(supports = { Concept.class }, order = 50) public class ConceptValidator implements Validator { /** Log for this class and subclasses */ protected final Log log = LogFactory.getLog(getClass()); /** * Determines if the command object being submitted is a valid type * * @see org.springframework.validation.Validator#supports(java.lang.Class) */ @SuppressWarnings("unchecked") public boolean supports(Class c) { return c.equals(Concept.class); } /** * Checks that a given concept object has a unique name or preferred name across the entire * unretired and preferred concept name space in a given locale(should be the default * application locale set in the openmrs context). Currently this method is called just before * the concept is persisted in the database * * @should fail if there is a duplicate unretired concept name in the locale * @should fail if the preferred name is an empty string * @should fail if the object parameter is null * @should pass if the found duplicate concept is actually retired * @should pass if the concept is being updated with no name change */ public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException { if (obj == null || !(obj instanceof Concept)) { if (log.isErrorEnabled()) log.error("The parameter obj should not be null and must be of type" + Concept.class); throw new IllegalArgumentException("Concept name is null or of invalid class"); } else { Concept newConcept = (Concept) obj; String newName = null; //no name to validate, but why is this the case? if (newConcept.getName() == null) return; //if the new concept name is in a different locale other than openmrs' default one if (newConcept.getName().getLocale() != null && !newConcept.getName().getLocale().equals(Context.getLocale())) newName = newConcept.getName().getName(); else newName = newConcept.getPreferredName(Context.getLocale()).getName(); if (StringUtils.isBlank(newName)) { if (log.isErrorEnabled()) log.error("No preferred name specified for the concept to be validated"); throw new APIException("Concept name cannot be an empty String"); } if (log.isDebugEnabled()) log.debug("Looking up concept names matching " + newName); List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName); Set<Concept> duplicates = new HashSet<Concept>(); for (Concept c : matchingConcepts) { //If updating a concept, read past the concept being updated - if (newConcept.getConceptId() != null && c.getConceptId().intValue() == newConcept.getConceptId()) + if (newConcept.getConceptId() != null && c.getConceptId().equals(newConcept.getConceptId())) continue; //get only duplicates that are not retired if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) { duplicates.add(c); } } if (duplicates.size() > 0) { for (Concept duplicate : duplicates) { if (log.isErrorEnabled()) log.error("The name '" + newName + "' is already being used by concept with Id: " + duplicate.getConceptId()); throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'"); } } } } }
true
true
public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException { if (obj == null || !(obj instanceof Concept)) { if (log.isErrorEnabled()) log.error("The parameter obj should not be null and must be of type" + Concept.class); throw new IllegalArgumentException("Concept name is null or of invalid class"); } else { Concept newConcept = (Concept) obj; String newName = null; //no name to validate, but why is this the case? if (newConcept.getName() == null) return; //if the new concept name is in a different locale other than openmrs' default one if (newConcept.getName().getLocale() != null && !newConcept.getName().getLocale().equals(Context.getLocale())) newName = newConcept.getName().getName(); else newName = newConcept.getPreferredName(Context.getLocale()).getName(); if (StringUtils.isBlank(newName)) { if (log.isErrorEnabled()) log.error("No preferred name specified for the concept to be validated"); throw new APIException("Concept name cannot be an empty String"); } if (log.isDebugEnabled()) log.debug("Looking up concept names matching " + newName); List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName); Set<Concept> duplicates = new HashSet<Concept>(); for (Concept c : matchingConcepts) { //If updating a concept, read past the concept being updated if (newConcept.getConceptId() != null && c.getConceptId().intValue() == newConcept.getConceptId()) continue; //get only duplicates that are not retired if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) { duplicates.add(c); } } if (duplicates.size() > 0) { for (Concept duplicate : duplicates) { if (log.isErrorEnabled()) log.error("The name '" + newName + "' is already being used by concept with Id: " + duplicate.getConceptId()); throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'"); } } } }
public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException { if (obj == null || !(obj instanceof Concept)) { if (log.isErrorEnabled()) log.error("The parameter obj should not be null and must be of type" + Concept.class); throw new IllegalArgumentException("Concept name is null or of invalid class"); } else { Concept newConcept = (Concept) obj; String newName = null; //no name to validate, but why is this the case? if (newConcept.getName() == null) return; //if the new concept name is in a different locale other than openmrs' default one if (newConcept.getName().getLocale() != null && !newConcept.getName().getLocale().equals(Context.getLocale())) newName = newConcept.getName().getName(); else newName = newConcept.getPreferredName(Context.getLocale()).getName(); if (StringUtils.isBlank(newName)) { if (log.isErrorEnabled()) log.error("No preferred name specified for the concept to be validated"); throw new APIException("Concept name cannot be an empty String"); } if (log.isDebugEnabled()) log.debug("Looking up concept names matching " + newName); List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName); Set<Concept> duplicates = new HashSet<Concept>(); for (Concept c : matchingConcepts) { //If updating a concept, read past the concept being updated if (newConcept.getConceptId() != null && c.getConceptId().equals(newConcept.getConceptId())) continue; //get only duplicates that are not retired if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) { duplicates.add(c); } } if (duplicates.size() > 0) { for (Concept duplicate : duplicates) { if (log.isErrorEnabled()) log.error("The name '" + newName + "' is already being used by concept with Id: " + duplicate.getConceptId()); throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'"); } } } }
diff --git a/src/com/android/music/MediaPlaybackService.java b/src/com/android/music/MediaPlaybackService.java index 608b3ff..4a87d45 100644 --- a/src/com/android/music/MediaPlaybackService.java +++ b/src/com/android/music/MediaPlaybackService.java @@ -1,1992 +1,1992 @@ /* * 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.music; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.BroadcastReceiver; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.database.sqlite.SQLiteException; import android.media.audiofx.AudioEffect; import android.media.AudioManager; import android.media.AudioManager.OnAudioFocusChangeListener; import android.media.MediaPlayer; import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.SystemClock; import android.os.PowerManager.WakeLock; import android.provider.MediaStore; import android.util.Log; import android.widget.RemoteViews; import android.widget.Toast; import java.io.FileDescriptor; import java.io.IOException; import java.io.PrintWriter; import java.lang.ref.WeakReference; import java.util.Random; import java.util.Vector; /** * Provides "background" audio playback capabilities, allowing the * user to switch between activities without stopping playback. */ public class MediaPlaybackService extends Service { /** used to specify whether enqueue() should start playing * the new list of files right away, next or once all the currently * queued files have been played */ public static final int NOW = 1; public static final int NEXT = 2; public static final int LAST = 3; public static final int PLAYBACKSERVICE_STATUS = 1; public static final int SHUFFLE_NONE = 0; public static final int SHUFFLE_NORMAL = 1; public static final int SHUFFLE_AUTO = 2; public static final int REPEAT_NONE = 0; public static final int REPEAT_CURRENT = 1; public static final int REPEAT_ALL = 2; public static final String PLAYSTATE_CHANGED = "com.android.music.playstatechanged"; public static final String META_CHANGED = "com.android.music.metachanged"; public static final String QUEUE_CHANGED = "com.android.music.queuechanged"; public static final String SERVICECMD = "com.android.music.musicservicecommand"; public static final String CMDNAME = "command"; public static final String CMDTOGGLEPAUSE = "togglepause"; public static final String CMDSTOP = "stop"; public static final String CMDPAUSE = "pause"; public static final String CMDPLAY = "play"; public static final String CMDPREVIOUS = "previous"; public static final String CMDNEXT = "next"; public static final String TOGGLEPAUSE_ACTION = "com.android.music.musicservicecommand.togglepause"; public static final String PAUSE_ACTION = "com.android.music.musicservicecommand.pause"; public static final String PREVIOUS_ACTION = "com.android.music.musicservicecommand.previous"; public static final String NEXT_ACTION = "com.android.music.musicservicecommand.next"; private static final int TRACK_ENDED = 1; private static final int RELEASE_WAKELOCK = 2; private static final int SERVER_DIED = 3; private static final int FADEINFROMSTART = 4; private static final int FADEDOWN = 5; private static final int FADEUP = 6; private static final int MAX_HISTORY_SIZE = 100; private MultiPlayer mPlayer; private String mFileToPlay; private int mShuffleMode = SHUFFLE_NONE; private int mRepeatMode = REPEAT_NONE; private int mMediaMountedCount = 0; private long [] mAutoShuffleList = null; private long [] mPlayList = null; private int mPlayListLen = 0; private Vector<Integer> mHistory = new Vector<Integer>(MAX_HISTORY_SIZE); private Cursor mCursor; private int mPlayPos = -1; private static final String LOGTAG = "MediaPlaybackService"; private final Shuffler mRand = new Shuffler(); private int mOpenFailedCounter = 0; String[] mCursorCols = new String[] { "audio._id AS _id", // index must match IDCOLIDX below MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.MIME_TYPE, MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.IS_PODCAST, // index must match PODCASTCOLIDX below MediaStore.Audio.Media.BOOKMARK // index must match BOOKMARKCOLIDX below }; private final static int IDCOLIDX = 0; private final static int PODCASTCOLIDX = 8; private final static int BOOKMARKCOLIDX = 9; private BroadcastReceiver mUnmountReceiver = null; private WakeLock mWakeLock; private int mServiceStartId = -1; private boolean mServiceInUse = false; private boolean mIsSupposedToBePlaying = false; private boolean mQuietMode = false; private AudioManager mAudioManager; private boolean mQueueIsSaveable = true; // used to track what type of audio focus loss caused the playback to pause private boolean mPausedByTransientLossOfFocus = false; private SharedPreferences mPreferences; // We use this to distinguish between different cards when saving/restoring playlists. // This will have to change if we want to support multiple simultaneous cards. private int mCardId; private MediaAppWidgetProvider mAppWidgetProvider = MediaAppWidgetProvider.getInstance(); // interval after which we stop the service when idle private static final int IDLE_DELAY = 60000; private void startAndFadeIn() { mMediaplayerHandler.sendEmptyMessageDelayed(FADEINFROMSTART, 10); } private Handler mMediaplayerHandler = new Handler() { float mCurrentVolume = 1.0f; @Override public void handleMessage(Message msg) { MusicUtils.debugLog("mMediaplayerHandler.handleMessage " + msg.what); switch (msg.what) { case FADEINFROMSTART: if (!isPlaying()) { mCurrentVolume = 0f; mPlayer.setVolume(mCurrentVolume); play(); } mMediaplayerHandler.sendEmptyMessageDelayed(FADEUP, 10); break; case FADEDOWN: mCurrentVolume -= .05f; if (mCurrentVolume > .2f) { mMediaplayerHandler.sendEmptyMessageDelayed(FADEDOWN, 10); } else { mCurrentVolume = .2f; } mPlayer.setVolume(mCurrentVolume); break; case FADEUP: mCurrentVolume += .01f; if (mCurrentVolume < 1.0f) { mMediaplayerHandler.sendEmptyMessageDelayed(FADEUP, 10); } else { mCurrentVolume = 1.0f; } mPlayer.setVolume(mCurrentVolume); break; case SERVER_DIED: if (mIsSupposedToBePlaying) { next(true); } else { // the server died when we were idle, so just // reopen the same song (it will start again // from the beginning though when the user // restarts) openCurrent(); } break; case TRACK_ENDED: if (mRepeatMode == REPEAT_CURRENT) { seek(0); play(); } else { next(false); } break; case RELEASE_WAKELOCK: mWakeLock.release(); break; default: break; } } }; private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); String cmd = intent.getStringExtra("command"); MusicUtils.debugLog("mIntentReceiver.onReceive " + action + " / " + cmd); if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) { next(true); } else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) { prev(); } else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) { if (isPlaying()) { pause(); mPausedByTransientLossOfFocus = false; } else { play(); } } else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) { pause(); mPausedByTransientLossOfFocus = false; } else if (CMDPLAY.equals(cmd)) { play(); } else if (CMDSTOP.equals(cmd)) { pause(); mPausedByTransientLossOfFocus = false; seek(0); } else if (MediaAppWidgetProvider.CMDAPPWIDGETUPDATE.equals(cmd)) { // Someone asked us to refresh a set of specific widgets, probably // because they were just added. int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); mAppWidgetProvider.performUpdate(MediaPlaybackService.this, appWidgetIds); } } }; private OnAudioFocusChangeListener mAudioFocusListener = new OnAudioFocusChangeListener() { public void onAudioFocusChange(int focusChange) { // AudioFocus is a new feature: focus updates are made verbose on purpose switch (focusChange) { case AudioManager.AUDIOFOCUS_LOSS: Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS"); if(isPlaying()) { mPausedByTransientLossOfFocus = false; pause(); } break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: mMediaplayerHandler.sendEmptyMessage(FADEDOWN); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT"); if(isPlaying()) { mPausedByTransientLossOfFocus = true; pause(); } break; case AudioManager.AUDIOFOCUS_GAIN: Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_GAIN"); if(!isPlaying() && mPausedByTransientLossOfFocus) { mPausedByTransientLossOfFocus = false; startAndFadeIn(); } else { mMediaplayerHandler.sendEmptyMessage(FADEUP); } break; default: Log.e(LOGTAG, "Unknown audio focus change code"); } } }; public MediaPlaybackService() { } @Override public void onCreate() { super.onCreate(); mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mAudioManager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName())); mPreferences = getSharedPreferences("Music", MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE); mCardId = MusicUtils.getCardId(this); registerExternalStorageListener(); // Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes. mPlayer = new MultiPlayer(); mPlayer.setHandler(mMediaplayerHandler); reloadQueue(); IntentFilter commandFilter = new IntentFilter(); commandFilter.addAction(SERVICECMD); commandFilter.addAction(TOGGLEPAUSE_ACTION); commandFilter.addAction(PAUSE_ACTION); commandFilter.addAction(NEXT_ACTION); commandFilter.addAction(PREVIOUS_ACTION); registerReceiver(mIntentReceiver, commandFilter); PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName()); mWakeLock.setReferenceCounted(false); // If the service was idle, but got killed before it stopped itself, the // system will relaunch it. Make sure it gets stopped again in that case. Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); } @Override public void onDestroy() { // Check that we're not being destroyed while something is still playing. if (isPlaying()) { Log.e(LOGTAG, "Service being destroyed while still playing."); } // release all MediaPlayer resources, including the native player and wakelocks Intent i = new Intent(AudioEffect.ACTION_CLOSE_AUDIO_EFFECT_CONTROL_SESSION); i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId()); i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName()); sendBroadcast(i); mPlayer.release(); mPlayer = null; mAudioManager.abandonAudioFocus(mAudioFocusListener); // make sure there aren't any other messages coming mDelayedStopHandler.removeCallbacksAndMessages(null); mMediaplayerHandler.removeCallbacksAndMessages(null); if (mCursor != null) { mCursor.close(); mCursor = null; } unregisterReceiver(mIntentReceiver); if (mUnmountReceiver != null) { unregisterReceiver(mUnmountReceiver); mUnmountReceiver = null; } mWakeLock.release(); super.onDestroy(); } private final char hexdigits [] = new char [] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private void saveQueue(boolean full) { if (!mQueueIsSaveable) { return; } Editor ed = mPreferences.edit(); //long start = System.currentTimeMillis(); if (full) { StringBuilder q = new StringBuilder(); // The current playlist is saved as a list of "reverse hexadecimal" // numbers, which we can generate faster than normal decimal or // hexadecimal numbers, which in turn allows us to save the playlist // more often without worrying too much about performance. // (saving the full state takes about 40 ms under no-load conditions // on the phone) int len = mPlayListLen; for (int i = 0; i < len; i++) { long n = mPlayList[i]; if (n < 0) { continue; } else if (n == 0) { q.append("0;"); } else { while (n != 0) { int digit = (int)(n & 0xf); n >>>= 4; q.append(hexdigits[digit]); } q.append(";"); } } //Log.i("@@@@ service", "created queue string in " + (System.currentTimeMillis() - start) + " ms"); ed.putString("queue", q.toString()); ed.putInt("cardid", mCardId); if (mShuffleMode != SHUFFLE_NONE) { // In shuffle mode we need to save the history too len = mHistory.size(); q.setLength(0); for (int i = 0; i < len; i++) { int n = mHistory.get(i); if (n == 0) { q.append("0;"); } else { while (n != 0) { int digit = (n & 0xf); n >>>= 4; q.append(hexdigits[digit]); } q.append(";"); } } ed.putString("history", q.toString()); } } ed.putInt("curpos", mPlayPos); if (mPlayer.isInitialized()) { ed.putLong("seekpos", mPlayer.position()); } ed.putInt("repeatmode", mRepeatMode); ed.putInt("shufflemode", mShuffleMode); SharedPreferencesCompat.apply(ed); //Log.i("@@@@ service", "saved state in " + (System.currentTimeMillis() - start) + " ms"); } private void reloadQueue() { String q = null; boolean newstyle = false; int id = mCardId; if (mPreferences.contains("cardid")) { newstyle = true; id = mPreferences.getInt("cardid", ~mCardId); } if (id == mCardId) { // Only restore the saved playlist if the card is still // the same one as when the playlist was saved q = mPreferences.getString("queue", ""); } int qlen = q != null ? q.length() : 0; if (qlen > 1) { //Log.i("@@@@ service", "loaded queue: " + q); int plen = 0; int n = 0; int shift = 0; for (int i = 0; i < qlen; i++) { char c = q.charAt(i); if (c == ';') { ensurePlayListCapacity(plen + 1); mPlayList[plen] = n; plen++; n = 0; shift = 0; } else { if (c >= '0' && c <= '9') { n += ((c - '0') << shift); } else if (c >= 'a' && c <= 'f') { n += ((10 + c - 'a') << shift); } else { // bogus playlist data plen = 0; break; } shift += 4; } } mPlayListLen = plen; int pos = mPreferences.getInt("curpos", 0); if (pos < 0 || pos >= mPlayListLen) { // The saved playlist is bogus, discard it mPlayListLen = 0; return; } mPlayPos = pos; // When reloadQueue is called in response to a card-insertion, // we might not be able to query the media provider right away. // To deal with this, try querying for the current file, and if // that fails, wait a while and try again. If that too fails, // assume there is a problem and don't restore the state. Cursor crsr = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null); if (crsr == null || crsr.getCount() == 0) { // wait a bit and try again SystemClock.sleep(3000); crsr = getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null); } if (crsr != null) { crsr.close(); } // Make sure we don't auto-skip to the next song, since that // also starts playback. What could happen in that case is: // - music is paused // - go to UMS and delete some files, including the currently playing one // - come back from UMS // (time passes) // - music app is killed for some reason (out of memory) // - music service is restarted, service restores state, doesn't find // the "current" file, goes to the next and: playback starts on its // own, potentially at some random inconvenient time. mOpenFailedCounter = 20; mQuietMode = true; openCurrent(); mQuietMode = false; if (!mPlayer.isInitialized()) { // couldn't restore the saved state mPlayListLen = 0; return; } long seekpos = mPreferences.getLong("seekpos", 0); seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0); Log.d(LOGTAG, "restored queue, currently at position " + position() + "/" + duration() + " (requested " + seekpos + ")"); int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE); if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) { repmode = REPEAT_NONE; } mRepeatMode = repmode; int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE); if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) { shufmode = SHUFFLE_NONE; } if (shufmode != SHUFFLE_NONE) { // in shuffle mode we need to restore the history too q = mPreferences.getString("history", ""); qlen = q != null ? q.length() : 0; if (qlen > 1) { plen = 0; n = 0; shift = 0; mHistory.clear(); for (int i = 0; i < qlen; i++) { char c = q.charAt(i); if (c == ';') { if (n >= mPlayListLen) { // bogus history data mHistory.clear(); break; } mHistory.add(n); n = 0; shift = 0; } else { if (c >= '0' && c <= '9') { n += ((c - '0') << shift); } else if (c >= 'a' && c <= 'f') { n += ((10 + c - 'a') << shift); } else { // bogus history data mHistory.clear(); break; } shift += 4; } } } } if (shufmode == SHUFFLE_AUTO) { if (! makeAutoShuffleList()) { shufmode = SHUFFLE_NONE; } } mShuffleMode = shufmode; } } @Override public IBinder onBind(Intent intent) { mDelayedStopHandler.removeCallbacksAndMessages(null); mServiceInUse = true; return mBinder; } @Override public void onRebind(Intent intent) { mDelayedStopHandler.removeCallbacksAndMessages(null); mServiceInUse = true; } @Override public int onStartCommand(Intent intent, int flags, int startId) { mServiceStartId = startId; mDelayedStopHandler.removeCallbacksAndMessages(null); if (intent != null) { String action = intent.getAction(); String cmd = intent.getStringExtra("command"); MusicUtils.debugLog("onStartCommand " + action + " / " + cmd); if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) { next(true); } else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) { if (position() < 2000) { prev(); } else { seek(0); play(); } } else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) { if (isPlaying()) { pause(); mPausedByTransientLossOfFocus = false; } else { play(); } } else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) { pause(); mPausedByTransientLossOfFocus = false; } else if (CMDSTOP.equals(cmd)) { pause(); mPausedByTransientLossOfFocus = false; seek(0); } } // make sure the service will shut down on its own if it was // just started but not bound to and nothing is playing mDelayedStopHandler.removeCallbacksAndMessages(null); Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); return START_STICKY; } @Override public boolean onUnbind(Intent intent) { mServiceInUse = false; // Take a snapshot of the current playlist saveQueue(true); if (isPlaying() || mPausedByTransientLossOfFocus) { // something is currently playing, or will be playing once // an in-progress action requesting audio focus ends, so don't stop the service now. return true; } // If there is a playlist but playback is paused, then wait a while // before stopping the service, so that pause/resume isn't slow. // Also delay stopping the service if we're transitioning between tracks. if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) { Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); return true; } // No active playlist, OK to stop the service right now stopSelf(mServiceStartId); return true; } private Handler mDelayedStopHandler = new Handler() { @Override public void handleMessage(Message msg) { // Check again to make sure nothing is playing right now if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse || mMediaplayerHandler.hasMessages(TRACK_ENDED)) { return; } // save the queue again, because it might have changed // since the user exited the music app (because of // party-shuffle or because the play-position changed) saveQueue(true); stopSelf(mServiceStartId); } }; /** * Called when we receive a ACTION_MEDIA_EJECT notification. * * @param storagePath path to mount point for the removed media */ public void closeExternalStorageFiles(String storagePath) { // stop playback and clean up if the SD card is going to be unmounted. stop(true); notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); } /** * Registers an intent to listen for ACTION_MEDIA_EJECT notifications. * The intent will call closeExternalStorageFiles() if the external media * is going to be ejected, so applications can clean up any files they have open. */ public void registerExternalStorageListener() { if (mUnmountReceiver == null) { mUnmountReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { saveQueue(true); mQueueIsSaveable = false; closeExternalStorageFiles(intent.getData().getPath()); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { mMediaMountedCount++; mCardId = MusicUtils.getCardId(MediaPlaybackService.this); reloadQueue(); mQueueIsSaveable = true; notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); } } }; IntentFilter iFilter = new IntentFilter(); iFilter.addAction(Intent.ACTION_MEDIA_EJECT); iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); iFilter.addDataScheme("file"); registerReceiver(mUnmountReceiver, iFilter); } } /** * Notify the change-receivers that something has changed. * The intent that is sent contains the following data * for the currently playing track: * "id" - Integer: the database row ID * "artist" - String: the name of the artist * "album" - String: the name of the album * "track" - String: the name of the track * The intent has an action that is one of * "com.android.music.metachanged" * "com.android.music.queuechanged", * "com.android.music.playbackcomplete" * "com.android.music.playstatechanged" * respectively indicating that a new track has * started playing, that the playback queue has * changed, that playback has stopped because * the last file in the list has been played, * or that the play-state changed (paused/resumed). */ private void notifyChange(String what) { Intent i = new Intent(what); i.putExtra("id", Long.valueOf(getAudioId())); i.putExtra("artist", getArtistName()); i.putExtra("album",getAlbumName()); i.putExtra("track", getTrackName()); i.putExtra("playing", isPlaying()); sendStickyBroadcast(i); if (what.equals(QUEUE_CHANGED)) { saveQueue(true); } else { saveQueue(false); } // Share this notification directly with our widgets mAppWidgetProvider.notifyChange(this, what); } private void ensurePlayListCapacity(int size) { if (mPlayList == null || size > mPlayList.length) { // reallocate at 2x requested size so we don't // need to grow and copy the array for every // insert long [] newlist = new long[size * 2]; int len = mPlayList != null ? mPlayList.length : mPlayListLen; for (int i = 0; i < len; i++) { newlist[i] = mPlayList[i]; } mPlayList = newlist; } // FIXME: shrink the array when the needed size is much smaller // than the allocated size } // insert the list of songs at the specified position in the playlist private void addToPlayList(long [] list, int position) { int addlen = list.length; if (position < 0) { // overwrite mPlayListLen = 0; position = 0; } ensurePlayListCapacity(mPlayListLen + addlen); if (position > mPlayListLen) { position = mPlayListLen; } // move part of list after insertion point int tailsize = mPlayListLen - position; for (int i = tailsize ; i > 0 ; i--) { mPlayList[position + i] = mPlayList[position + i - addlen]; } // copy list into playlist for (int i = 0; i < addlen; i++) { mPlayList[position + i] = list[i]; } mPlayListLen += addlen; if (mPlayListLen == 0) { mCursor.close(); mCursor = null; notifyChange(META_CHANGED); } } /** * Appends a list of tracks to the current playlist. * If nothing is playing currently, playback will be started at * the first track. * If the action is NOW, playback will switch to the first of * the new tracks immediately. * @param list The list of tracks to append. * @param action NOW, NEXT or LAST */ public void enqueue(long [] list, int action) { synchronized(this) { if (action == NEXT && mPlayPos + 1 < mPlayListLen) { addToPlayList(list, mPlayPos + 1); notifyChange(QUEUE_CHANGED); } else { // action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen addToPlayList(list, Integer.MAX_VALUE); notifyChange(QUEUE_CHANGED); if (action == NOW) { mPlayPos = mPlayListLen - list.length; openCurrent(); play(); notifyChange(META_CHANGED); return; } } if (mPlayPos < 0) { mPlayPos = 0; openCurrent(); play(); notifyChange(META_CHANGED); } } } /** * Replaces the current playlist with a new list, * and prepares for starting playback at the specified * position in the list, or a random position if the * specified position is 0. * @param list The new list of tracks. */ public void open(long [] list, int position) { synchronized (this) { if (mShuffleMode == SHUFFLE_AUTO) { mShuffleMode = SHUFFLE_NORMAL; } long oldId = getAudioId(); int listlength = list.length; boolean newlist = true; if (mPlayListLen == listlength) { // possible fast path: list might be the same newlist = false; for (int i = 0; i < listlength; i++) { if (list[i] != mPlayList[i]) { newlist = true; break; } } } if (newlist) { addToPlayList(list, -1); notifyChange(QUEUE_CHANGED); } int oldpos = mPlayPos; if (position >= 0) { mPlayPos = position; } else { mPlayPos = mRand.nextInt(mPlayListLen); } mHistory.clear(); saveBookmarkIfNeeded(); openCurrent(); if (oldId != getAudioId()) { notifyChange(META_CHANGED); } } } /** * Moves the item at index1 to index2. * @param index1 * @param index2 */ public void moveQueueItem(int index1, int index2) { synchronized (this) { if (index1 >= mPlayListLen) { index1 = mPlayListLen - 1; } if (index2 >= mPlayListLen) { index2 = mPlayListLen - 1; } if (index1 < index2) { long tmp = mPlayList[index1]; for (int i = index1; i < index2; i++) { mPlayList[i] = mPlayList[i+1]; } mPlayList[index2] = tmp; if (mPlayPos == index1) { mPlayPos = index2; } else if (mPlayPos >= index1 && mPlayPos <= index2) { mPlayPos--; } } else if (index2 < index1) { long tmp = mPlayList[index1]; for (int i = index1; i > index2; i--) { mPlayList[i] = mPlayList[i-1]; } mPlayList[index2] = tmp; if (mPlayPos == index1) { mPlayPos = index2; } else if (mPlayPos >= index2 && mPlayPos <= index1) { mPlayPos++; } } notifyChange(QUEUE_CHANGED); } } /** * Returns the current play list * @return An array of integers containing the IDs of the tracks in the play list */ public long [] getQueue() { synchronized (this) { int len = mPlayListLen; long [] list = new long[len]; for (int i = 0; i < len; i++) { list[i] = mPlayList[i]; } return list; } } private void openCurrent() { synchronized (this) { if (mCursor != null) { mCursor.close(); mCursor = null; } if (mPlayListLen == 0) { return; } stop(false); String id = String.valueOf(mPlayList[mPlayPos]); mCursor = getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursorCols, "_id=" + id , null, null); if (mCursor != null) { mCursor.moveToFirst(); open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id); // go to bookmark if needed if (isPodcast()) { long bookmark = getBookmark(); // Start playing a little bit before the bookmark, // so it's easier to get back in to the narrative. seek(bookmark - 5000); } } } } /** * Opens the specified file and readies it for playback. * * @param path The full path of the file to be opened. */ public void open(String path) { synchronized (this) { if (path == null) { return; } // if mCursor is null, try to associate path with a database cursor if (mCursor == null) { ContentResolver resolver = getContentResolver(); Uri uri; String where; String selectionArgs[]; if (path.startsWith("content://media/")) { uri = Uri.parse(path); where = null; selectionArgs = null; } else { uri = MediaStore.Audio.Media.getContentUriForPath(path); where = MediaStore.Audio.Media.DATA + "=?"; selectionArgs = new String[] { path }; } try { mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null); if (mCursor != null) { if (mCursor.getCount() == 0) { mCursor.close(); mCursor = null; } else { mCursor.moveToNext(); ensurePlayListCapacity(1); mPlayListLen = 1; mPlayList[0] = mCursor.getLong(IDCOLIDX); mPlayPos = 0; } } } catch (UnsupportedOperationException ex) { } } mFileToPlay = path; mPlayer.setDataSource(mFileToPlay); if (! mPlayer.isInitialized()) { stop(true); if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) { // beware: this ends up being recursive because next() calls open() again. next(false); } if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) { // need to make sure we only shows this once mOpenFailedCounter = 0; if (!mQuietMode) { Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show(); } Log.d(LOGTAG, "Failed to open file for playback"); } } else { mOpenFailedCounter = 0; } } } /** * Starts playback of a previously opened file. */ public void play() { mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(), MediaButtonIntentReceiver.class.getName())); if (mPlayer.isInitialized()) { // if we are at the end of the song, go to the next song first long duration = mPlayer.duration(); if (mRepeatMode != REPEAT_CURRENT && duration > 2000 && mPlayer.position() >= duration - 2000) { next(true); } mPlayer.start(); RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar); views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer); if (getAudioId() < 0) { // streaming views.setTextViewText(R.id.trackname, getPath()); views.setTextViewText(R.id.artistalbum, null); } else { String artist = getArtistName(); views.setTextViewText(R.id.trackname, getTrackName()); if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) { artist = getString(R.string.unknown_artist_name); } String album = getAlbumName(); if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) { album = getString(R.string.unknown_album_name); } views.setTextViewText(R.id.artistalbum, getString(R.string.notification_artist_album, artist, album) ); } Notification status = new Notification(); status.contentView = views; status.flags |= Notification.FLAG_ONGOING_EVENT; status.icon = R.drawable.stat_notify_musicplayer; status.contentIntent = PendingIntent.getActivity(this, 0, new Intent("com.android.music.PLAYBACK_VIEWER") .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0); startForeground(PLAYBACKSERVICE_STATUS, status); if (!mIsSupposedToBePlaying) { mIsSupposedToBePlaying = true; notifyChange(PLAYSTATE_CHANGED); } } else if (mPlayListLen <= 0) { // This is mostly so that if you press 'play' on a bluetooth headset // without every having played anything before, it will still play // something. setShuffleMode(SHUFFLE_AUTO); } } private void stop(boolean remove_status_icon) { if (mPlayer.isInitialized()) { mPlayer.stop(); } mFileToPlay = null; if (mCursor != null) { mCursor.close(); mCursor = null; } if (remove_status_icon) { gotoIdleState(); } else { stopForeground(false); } if (remove_status_icon) { mIsSupposedToBePlaying = false; } } /** * Stops playback. */ public void stop() { stop(true); } /** * Pauses playback (call play() to resume) */ public void pause() { synchronized(this) { if (isPlaying()) { - mMediaplayerHandler.removeMessages(FADEIN); + mMediaplayerHandler.removeMessages(FADEINFROMSTART); mPlayer.pause(); gotoIdleState(); mIsSupposedToBePlaying = false; notifyChange(PLAYSTATE_CHANGED); saveBookmarkIfNeeded(); } } } /** Returns whether something is currently playing * * @return true if something is playing (or will be playing shortly, in case * we're currently transitioning between tracks), false if not. */ public boolean isPlaying() { return mIsSupposedToBePlaying; } /* Desired behavior for prev/next/shuffle: - NEXT will move to the next track in the list when not shuffling, and to a track randomly picked from the not-yet-played tracks when shuffling. If all tracks have already been played, pick from the full set, but avoid picking the previously played track if possible. - when shuffling, PREV will go to the previously played track. Hitting PREV again will go to the track played before that, etc. When the start of the history has been reached, PREV is a no-op. When not shuffling, PREV will go to the sequentially previous track (the difference with the shuffle-case is mainly that when not shuffling, the user can back up to tracks that are not in the history). Example: When playing an album with 10 tracks from the start, and enabling shuffle while playing track 5, the remaining tracks (6-10) will be shuffled, e.g. the final play order might be 1-2-3-4-5-8-10-6-9-7. When hitting 'prev' 8 times while playing track 7 in this example, the user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next', a random track will be picked again. If at any time user disables shuffling the next/previous track will be picked in sequential order again. */ public void prev() { synchronized (this) { if (mShuffleMode == SHUFFLE_NORMAL) { // go to previously-played track and remove it from the history int histsize = mHistory.size(); if (histsize == 0) { // prev is a no-op return; } Integer pos = mHistory.remove(histsize - 1); mPlayPos = pos.intValue(); } else { if (mPlayPos > 0) { mPlayPos--; } else { mPlayPos = mPlayListLen - 1; } } saveBookmarkIfNeeded(); stop(false); openCurrent(); play(); notifyChange(META_CHANGED); } } public void next(boolean force) { synchronized (this) { if (mPlayListLen <= 0) { Log.d(LOGTAG, "No play queue"); return; } if (mShuffleMode == SHUFFLE_NORMAL) { // Pick random next track from the not-yet-played ones // TODO: make it work right after adding/removing items in the queue. // Store the current file in the history, but keep the history at a // reasonable size if (mPlayPos >= 0) { mHistory.add(mPlayPos); } if (mHistory.size() > MAX_HISTORY_SIZE) { mHistory.removeElementAt(0); } int numTracks = mPlayListLen; int[] tracks = new int[numTracks]; for (int i=0;i < numTracks; i++) { tracks[i] = i; } int numHistory = mHistory.size(); int numUnplayed = numTracks; for (int i=0;i < numHistory; i++) { int idx = mHistory.get(i).intValue(); if (idx < numTracks && tracks[idx] >= 0) { numUnplayed--; tracks[idx] = -1; } } // 'numUnplayed' now indicates how many tracks have not yet // been played, and 'tracks' contains the indices of those // tracks. if (numUnplayed <=0) { // everything's already been played if (mRepeatMode == REPEAT_ALL || force) { //pick from full set numUnplayed = numTracks; for (int i=0;i < numTracks; i++) { tracks[i] = i; } } else { // all done gotoIdleState(); if (mIsSupposedToBePlaying) { mIsSupposedToBePlaying = false; notifyChange(PLAYSTATE_CHANGED); } return; } } int skip = mRand.nextInt(numUnplayed); int cnt = -1; while (true) { while (tracks[++cnt] < 0) ; skip--; if (skip < 0) { break; } } mPlayPos = cnt; } else if (mShuffleMode == SHUFFLE_AUTO) { doAutoShuffleUpdate(); mPlayPos++; } else { if (mPlayPos >= mPlayListLen - 1) { // we're at the end of the list if (mRepeatMode == REPEAT_NONE && !force) { // all done gotoIdleState(); mIsSupposedToBePlaying = false; notifyChange(PLAYSTATE_CHANGED); return; } else if (mRepeatMode == REPEAT_ALL || force) { mPlayPos = 0; } } else { mPlayPos++; } } saveBookmarkIfNeeded(); stop(false); openCurrent(); play(); notifyChange(META_CHANGED); } } private void gotoIdleState() { mDelayedStopHandler.removeCallbacksAndMessages(null); Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); stopForeground(true); } private void saveBookmarkIfNeeded() { try { if (isPodcast()) { long pos = position(); long bookmark = getBookmark(); long duration = duration(); if ((pos < bookmark && (pos + 10000) > bookmark) || (pos > bookmark && (pos - 10000) < bookmark)) { // The existing bookmark is close to the current // position, so don't update it. return; } if (pos < 15000 || (pos + 10000) > duration) { // if we're near the start or end, clear the bookmark pos = 0; } // write 'pos' to the bookmark field ContentValues values = new ContentValues(); values.put(MediaStore.Audio.Media.BOOKMARK, pos); Uri uri = ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX)); getContentResolver().update(uri, values, null, null); } } catch (SQLiteException ex) { } } // Make sure there are at least 5 items after the currently playing item // and no more than 10 items before. private void doAutoShuffleUpdate() { boolean notify = false; // remove old entries if (mPlayPos > 10) { removeTracks(0, mPlayPos - 9); notify = true; } // add new entries if needed int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos)); for (int i = 0; i < to_add; i++) { // pick something at random from the list int lookback = mHistory.size(); int idx = -1; while(true) { idx = mRand.nextInt(mAutoShuffleList.length); if (!wasRecentlyUsed(idx, lookback)) { break; } lookback /= 2; } mHistory.add(idx); if (mHistory.size() > MAX_HISTORY_SIZE) { mHistory.remove(0); } ensurePlayListCapacity(mPlayListLen + 1); mPlayList[mPlayListLen++] = mAutoShuffleList[idx]; notify = true; } if (notify) { notifyChange(QUEUE_CHANGED); } } // check that the specified idx is not in the history (but only look at at // most lookbacksize entries in the history) private boolean wasRecentlyUsed(int idx, int lookbacksize) { // early exit to prevent infinite loops in case idx == mPlayPos if (lookbacksize == 0) { return false; } int histsize = mHistory.size(); if (histsize < lookbacksize) { Log.d(LOGTAG, "lookback too big"); lookbacksize = histsize; } int maxidx = histsize - 1; for (int i = 0; i < lookbacksize; i++) { long entry = mHistory.get(maxidx - i); if (entry == idx) { return true; } } return false; } // A simple variation of Random that makes sure that the // value it returns is not equal to the value it returned // previously, unless the interval is 1. private static class Shuffler { private int mPrevious; private Random mRandom = new Random(); public int nextInt(int interval) { int ret; do { ret = mRandom.nextInt(interval); } while (ret == mPrevious && interval > 1); mPrevious = ret; return ret; } }; private boolean makeAutoShuffleList() { ContentResolver res = getContentResolver(); Cursor c = null; try { c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1", null, null); if (c == null || c.getCount() == 0) { return false; } int len = c.getCount(); long [] list = new long[len]; for (int i = 0; i < len; i++) { c.moveToNext(); list[i] = c.getLong(0); } mAutoShuffleList = list; return true; } catch (RuntimeException ex) { } finally { if (c != null) { c.close(); } } return false; } /** * Removes the range of tracks specified from the play list. If a file within the range is * the file currently being played, playback will move to the next file after the * range. * @param first The first file to be removed * @param last The last file to be removed * @return the number of tracks deleted */ public int removeTracks(int first, int last) { int numremoved = removeTracksInternal(first, last); if (numremoved > 0) { notifyChange(QUEUE_CHANGED); } return numremoved; } private int removeTracksInternal(int first, int last) { synchronized (this) { if (last < first) return 0; if (first < 0) first = 0; if (last >= mPlayListLen) last = mPlayListLen - 1; boolean gotonext = false; if (first <= mPlayPos && mPlayPos <= last) { mPlayPos = first; gotonext = true; } else if (mPlayPos > last) { mPlayPos -= (last - first + 1); } int num = mPlayListLen - last - 1; for (int i = 0; i < num; i++) { mPlayList[first + i] = mPlayList[last + 1 + i]; } mPlayListLen -= last - first + 1; if (gotonext) { if (mPlayListLen == 0) { stop(true); mPlayPos = -1; if (mCursor != null) { mCursor.close(); mCursor = null; } } else { if (mPlayPos >= mPlayListLen) { mPlayPos = 0; } boolean wasPlaying = isPlaying(); stop(false); openCurrent(); if (wasPlaying) { play(); } } notifyChange(META_CHANGED); } return last - first + 1; } } /** * Removes all instances of the track with the given id * from the playlist. * @param id The id to be removed * @return how many instances of the track were removed */ public int removeTrack(long id) { int numremoved = 0; synchronized (this) { for (int i = 0; i < mPlayListLen; i++) { if (mPlayList[i] == id) { numremoved += removeTracksInternal(i, i); i--; } } } if (numremoved > 0) { notifyChange(QUEUE_CHANGED); } return numremoved; } public void setShuffleMode(int shufflemode) { synchronized(this) { if (mShuffleMode == shufflemode && mPlayListLen > 0) { return; } mShuffleMode = shufflemode; if (mShuffleMode == SHUFFLE_AUTO) { if (makeAutoShuffleList()) { mPlayListLen = 0; doAutoShuffleUpdate(); mPlayPos = 0; openCurrent(); play(); notifyChange(META_CHANGED); return; } else { // failed to build a list of files to shuffle mShuffleMode = SHUFFLE_NONE; } } saveQueue(false); } } public int getShuffleMode() { return mShuffleMode; } public void setRepeatMode(int repeatmode) { synchronized(this) { mRepeatMode = repeatmode; saveQueue(false); } } public int getRepeatMode() { return mRepeatMode; } public int getMediaMountedCount() { return mMediaMountedCount; } /** * Returns the path of the currently playing file, or null if * no file is currently playing. */ public String getPath() { return mFileToPlay; } /** * Returns the rowid of the currently playing file, or -1 if * no file is currently playing. */ public long getAudioId() { synchronized (this) { if (mPlayPos >= 0 && mPlayer.isInitialized()) { return mPlayList[mPlayPos]; } } return -1; } /** * Returns the position in the queue * @return the position in the queue */ public int getQueuePosition() { synchronized(this) { return mPlayPos; } } /** * Starts playing the track at the given position in the queue. * @param pos The position in the queue of the track that will be played. */ public void setQueuePosition(int pos) { synchronized(this) { stop(false); mPlayPos = pos; openCurrent(); play(); notifyChange(META_CHANGED); if (mShuffleMode == SHUFFLE_AUTO) { doAutoShuffleUpdate(); } } } public String getArtistName() { synchronized(this) { if (mCursor == null) { return null; } return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)); } } public long getArtistId() { synchronized (this) { if (mCursor == null) { return -1; } return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID)); } } public String getAlbumName() { synchronized (this) { if (mCursor == null) { return null; } return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)); } } public long getAlbumId() { synchronized (this) { if (mCursor == null) { return -1; } return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)); } } public String getTrackName() { synchronized (this) { if (mCursor == null) { return null; } return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); } } private boolean isPodcast() { synchronized (this) { if (mCursor == null) { return false; } return (mCursor.getInt(PODCASTCOLIDX) > 0); } } private long getBookmark() { synchronized (this) { if (mCursor == null) { return 0; } return mCursor.getLong(BOOKMARKCOLIDX); } } /** * Returns the duration of the file in milliseconds. * Currently this method returns -1 for the duration of MIDI files. */ public long duration() { if (mPlayer.isInitialized()) { return mPlayer.duration(); } return -1; } /** * Returns the current playback position in milliseconds */ public long position() { if (mPlayer.isInitialized()) { return mPlayer.position(); } return -1; } /** * Seeks to the position specified. * * @param pos The position to seek to, in milliseconds */ public long seek(long pos) { if (mPlayer.isInitialized()) { if (pos < 0) pos = 0; if (pos > mPlayer.duration()) pos = mPlayer.duration(); return mPlayer.seek(pos); } return -1; } /** * Sets the audio session ID. * * @param sessionId: the audio session ID. */ public void setAudioSessionId(int sessionId) { synchronized (this) { mPlayer.setAudioSessionId(sessionId); } } /** * Returns the audio session ID. */ public int getAudioSessionId() { synchronized (this) { return mPlayer.getAudioSessionId(); } } /** * Provides a unified interface for dealing with midi files and * other media files. */ private class MultiPlayer { private MediaPlayer mMediaPlayer = new MediaPlayer(); private Handler mHandler; private boolean mIsInitialized = false; public MultiPlayer() { mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK); } public void setDataSource(String path) { try { mMediaPlayer.reset(); mMediaPlayer.setOnPreparedListener(null); if (path.startsWith("content://")) { mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path)); } else { mMediaPlayer.setDataSource(path); } mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.prepare(); } catch (IOException ex) { // TODO: notify the user why the file couldn't be opened mIsInitialized = false; return; } catch (IllegalArgumentException ex) { // TODO: notify the user why the file couldn't be opened mIsInitialized = false; return; } mMediaPlayer.setOnCompletionListener(listener); mMediaPlayer.setOnErrorListener(errorListener); Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION); i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId()); i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName()); sendBroadcast(i); mIsInitialized = true; } public boolean isInitialized() { return mIsInitialized; } public void start() { MusicUtils.debugLog(new Exception("MultiPlayer.start called")); mMediaPlayer.start(); } public void stop() { mMediaPlayer.reset(); mIsInitialized = false; } /** * You CANNOT use this player anymore after calling release() */ public void release() { stop(); mMediaPlayer.release(); } public void pause() { mMediaPlayer.pause(); } public void setHandler(Handler handler) { mHandler = handler; } MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // Acquire a temporary wakelock, since when we return from // this callback the MediaPlayer will release its wakelock // and allow the device to go to sleep. // This temporary wakelock is released when the RELEASE_WAKELOCK // message is processed, but just in case, put a timeout on it. mWakeLock.acquire(30000); mHandler.sendEmptyMessage(TRACK_ENDED); mHandler.sendEmptyMessage(RELEASE_WAKELOCK); } }; MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() { public boolean onError(MediaPlayer mp, int what, int extra) { switch (what) { case MediaPlayer.MEDIA_ERROR_SERVER_DIED: mIsInitialized = false; mMediaPlayer.release(); // Creating a new MediaPlayer and settings its wakemode does not // require the media service, so it's OK to do this now, while the // service is still being restarted mMediaPlayer = new MediaPlayer(); mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK); mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000); return true; default: Log.d("MultiPlayer", "Error: " + what + "," + extra); break; } return false; } }; public long duration() { return mMediaPlayer.getDuration(); } public long position() { return mMediaPlayer.getCurrentPosition(); } public long seek(long whereto) { mMediaPlayer.seekTo((int) whereto); return whereto; } public void setVolume(float vol) { mMediaPlayer.setVolume(vol, vol); } public void setAudioSessionId(int sessionId) { mMediaPlayer.setAudioSessionId(sessionId); } public int getAudioSessionId() { return mMediaPlayer.getAudioSessionId(); } } /* * By making this a static class with a WeakReference to the Service, we * ensure that the Service can be GCd even when the system process still * has a remote reference to the stub. */ static class ServiceStub extends IMediaPlaybackService.Stub { WeakReference<MediaPlaybackService> mService; ServiceStub(MediaPlaybackService service) { mService = new WeakReference<MediaPlaybackService>(service); } public void openFile(String path) { mService.get().open(path); } public void open(long [] list, int position) { mService.get().open(list, position); } public int getQueuePosition() { return mService.get().getQueuePosition(); } public void setQueuePosition(int index) { mService.get().setQueuePosition(index); } public boolean isPlaying() { return mService.get().isPlaying(); } public void stop() { mService.get().stop(); } public void pause() { mService.get().pause(); } public void play() { mService.get().play(); } public void prev() { mService.get().prev(); } public void next() { mService.get().next(true); } public String getTrackName() { return mService.get().getTrackName(); } public String getAlbumName() { return mService.get().getAlbumName(); } public long getAlbumId() { return mService.get().getAlbumId(); } public String getArtistName() { return mService.get().getArtistName(); } public long getArtistId() { return mService.get().getArtistId(); } public void enqueue(long [] list , int action) { mService.get().enqueue(list, action); } public long [] getQueue() { return mService.get().getQueue(); } public void moveQueueItem(int from, int to) { mService.get().moveQueueItem(from, to); } public String getPath() { return mService.get().getPath(); } public long getAudioId() { return mService.get().getAudioId(); } public long position() { return mService.get().position(); } public long duration() { return mService.get().duration(); } public long seek(long pos) { return mService.get().seek(pos); } public void setShuffleMode(int shufflemode) { mService.get().setShuffleMode(shufflemode); } public int getShuffleMode() { return mService.get().getShuffleMode(); } public int removeTracks(int first, int last) { return mService.get().removeTracks(first, last); } public int removeTrack(long id) { return mService.get().removeTrack(id); } public void setRepeatMode(int repeatmode) { mService.get().setRepeatMode(repeatmode); } public int getRepeatMode() { return mService.get().getRepeatMode(); } public int getMediaMountedCount() { return mService.get().getMediaMountedCount(); } public int getAudioSessionId() { return mService.get().getAudioSessionId(); } } @Override protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { writer.println("" + mPlayListLen + " items in queue, currently at index " + mPlayPos); writer.println("Currently loaded:"); writer.println(getArtistName()); writer.println(getAlbumName()); writer.println(getTrackName()); writer.println(getPath()); writer.println("playing: " + mIsSupposedToBePlaying); writer.println("actual: " + mPlayer.mMediaPlayer.isPlaying()); writer.println("shuffle mode: " + mShuffleMode); MusicUtils.debugDump(writer); } private final IBinder mBinder = new ServiceStub(this); }
true
true
private void reloadQueue() { String q = null; boolean newstyle = false; int id = mCardId; if (mPreferences.contains("cardid")) { newstyle = true; id = mPreferences.getInt("cardid", ~mCardId); } if (id == mCardId) { // Only restore the saved playlist if the card is still // the same one as when the playlist was saved q = mPreferences.getString("queue", ""); } int qlen = q != null ? q.length() : 0; if (qlen > 1) { //Log.i("@@@@ service", "loaded queue: " + q); int plen = 0; int n = 0; int shift = 0; for (int i = 0; i < qlen; i++) { char c = q.charAt(i); if (c == ';') { ensurePlayListCapacity(plen + 1); mPlayList[plen] = n; plen++; n = 0; shift = 0; } else { if (c >= '0' && c <= '9') { n += ((c - '0') << shift); } else if (c >= 'a' && c <= 'f') { n += ((10 + c - 'a') << shift); } else { // bogus playlist data plen = 0; break; } shift += 4; } } mPlayListLen = plen; int pos = mPreferences.getInt("curpos", 0); if (pos < 0 || pos >= mPlayListLen) { // The saved playlist is bogus, discard it mPlayListLen = 0; return; } mPlayPos = pos; // When reloadQueue is called in response to a card-insertion, // we might not be able to query the media provider right away. // To deal with this, try querying for the current file, and if // that fails, wait a while and try again. If that too fails, // assume there is a problem and don't restore the state. Cursor crsr = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null); if (crsr == null || crsr.getCount() == 0) { // wait a bit and try again SystemClock.sleep(3000); crsr = getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null); } if (crsr != null) { crsr.close(); } // Make sure we don't auto-skip to the next song, since that // also starts playback. What could happen in that case is: // - music is paused // - go to UMS and delete some files, including the currently playing one // - come back from UMS // (time passes) // - music app is killed for some reason (out of memory) // - music service is restarted, service restores state, doesn't find // the "current" file, goes to the next and: playback starts on its // own, potentially at some random inconvenient time. mOpenFailedCounter = 20; mQuietMode = true; openCurrent(); mQuietMode = false; if (!mPlayer.isInitialized()) { // couldn't restore the saved state mPlayListLen = 0; return; } long seekpos = mPreferences.getLong("seekpos", 0); seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0); Log.d(LOGTAG, "restored queue, currently at position " + position() + "/" + duration() + " (requested " + seekpos + ")"); int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE); if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) { repmode = REPEAT_NONE; } mRepeatMode = repmode; int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE); if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) { shufmode = SHUFFLE_NONE; } if (shufmode != SHUFFLE_NONE) { // in shuffle mode we need to restore the history too q = mPreferences.getString("history", ""); qlen = q != null ? q.length() : 0; if (qlen > 1) { plen = 0; n = 0; shift = 0; mHistory.clear(); for (int i = 0; i < qlen; i++) { char c = q.charAt(i); if (c == ';') { if (n >= mPlayListLen) { // bogus history data mHistory.clear(); break; } mHistory.add(n); n = 0; shift = 0; } else { if (c >= '0' && c <= '9') { n += ((c - '0') << shift); } else if (c >= 'a' && c <= 'f') { n += ((10 + c - 'a') << shift); } else { // bogus history data mHistory.clear(); break; } shift += 4; } } } } if (shufmode == SHUFFLE_AUTO) { if (! makeAutoShuffleList()) { shufmode = SHUFFLE_NONE; } } mShuffleMode = shufmode; } } @Override public IBinder onBind(Intent intent) { mDelayedStopHandler.removeCallbacksAndMessages(null); mServiceInUse = true; return mBinder; } @Override public void onRebind(Intent intent) { mDelayedStopHandler.removeCallbacksAndMessages(null); mServiceInUse = true; } @Override public int onStartCommand(Intent intent, int flags, int startId) { mServiceStartId = startId; mDelayedStopHandler.removeCallbacksAndMessages(null); if (intent != null) { String action = intent.getAction(); String cmd = intent.getStringExtra("command"); MusicUtils.debugLog("onStartCommand " + action + " / " + cmd); if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) { next(true); } else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) { if (position() < 2000) { prev(); } else { seek(0); play(); } } else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) { if (isPlaying()) { pause(); mPausedByTransientLossOfFocus = false; } else { play(); } } else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) { pause(); mPausedByTransientLossOfFocus = false; } else if (CMDSTOP.equals(cmd)) { pause(); mPausedByTransientLossOfFocus = false; seek(0); } } // make sure the service will shut down on its own if it was // just started but not bound to and nothing is playing mDelayedStopHandler.removeCallbacksAndMessages(null); Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); return START_STICKY; } @Override public boolean onUnbind(Intent intent) { mServiceInUse = false; // Take a snapshot of the current playlist saveQueue(true); if (isPlaying() || mPausedByTransientLossOfFocus) { // something is currently playing, or will be playing once // an in-progress action requesting audio focus ends, so don't stop the service now. return true; } // If there is a playlist but playback is paused, then wait a while // before stopping the service, so that pause/resume isn't slow. // Also delay stopping the service if we're transitioning between tracks. if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) { Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); return true; } // No active playlist, OK to stop the service right now stopSelf(mServiceStartId); return true; } private Handler mDelayedStopHandler = new Handler() { @Override public void handleMessage(Message msg) { // Check again to make sure nothing is playing right now if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse || mMediaplayerHandler.hasMessages(TRACK_ENDED)) { return; } // save the queue again, because it might have changed // since the user exited the music app (because of // party-shuffle or because the play-position changed) saveQueue(true); stopSelf(mServiceStartId); } }; /** * Called when we receive a ACTION_MEDIA_EJECT notification. * * @param storagePath path to mount point for the removed media */ public void closeExternalStorageFiles(String storagePath) { // stop playback and clean up if the SD card is going to be unmounted. stop(true); notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); } /** * Registers an intent to listen for ACTION_MEDIA_EJECT notifications. * The intent will call closeExternalStorageFiles() if the external media * is going to be ejected, so applications can clean up any files they have open. */ public void registerExternalStorageListener() { if (mUnmountReceiver == null) { mUnmountReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { saveQueue(true); mQueueIsSaveable = false; closeExternalStorageFiles(intent.getData().getPath()); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { mMediaMountedCount++; mCardId = MusicUtils.getCardId(MediaPlaybackService.this); reloadQueue(); mQueueIsSaveable = true; notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); } } }; IntentFilter iFilter = new IntentFilter(); iFilter.addAction(Intent.ACTION_MEDIA_EJECT); iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); iFilter.addDataScheme("file"); registerReceiver(mUnmountReceiver, iFilter); } } /** * Notify the change-receivers that something has changed. * The intent that is sent contains the following data * for the currently playing track: * "id" - Integer: the database row ID * "artist" - String: the name of the artist * "album" - String: the name of the album * "track" - String: the name of the track * The intent has an action that is one of * "com.android.music.metachanged" * "com.android.music.queuechanged", * "com.android.music.playbackcomplete" * "com.android.music.playstatechanged" * respectively indicating that a new track has * started playing, that the playback queue has * changed, that playback has stopped because * the last file in the list has been played, * or that the play-state changed (paused/resumed). */ private void notifyChange(String what) { Intent i = new Intent(what); i.putExtra("id", Long.valueOf(getAudioId())); i.putExtra("artist", getArtistName()); i.putExtra("album",getAlbumName()); i.putExtra("track", getTrackName()); i.putExtra("playing", isPlaying()); sendStickyBroadcast(i); if (what.equals(QUEUE_CHANGED)) { saveQueue(true); } else { saveQueue(false); } // Share this notification directly with our widgets mAppWidgetProvider.notifyChange(this, what); } private void ensurePlayListCapacity(int size) { if (mPlayList == null || size > mPlayList.length) { // reallocate at 2x requested size so we don't // need to grow and copy the array for every // insert long [] newlist = new long[size * 2]; int len = mPlayList != null ? mPlayList.length : mPlayListLen; for (int i = 0; i < len; i++) { newlist[i] = mPlayList[i]; } mPlayList = newlist; } // FIXME: shrink the array when the needed size is much smaller // than the allocated size } // insert the list of songs at the specified position in the playlist private void addToPlayList(long [] list, int position) { int addlen = list.length; if (position < 0) { // overwrite mPlayListLen = 0; position = 0; } ensurePlayListCapacity(mPlayListLen + addlen); if (position > mPlayListLen) { position = mPlayListLen; } // move part of list after insertion point int tailsize = mPlayListLen - position; for (int i = tailsize ; i > 0 ; i--) { mPlayList[position + i] = mPlayList[position + i - addlen]; } // copy list into playlist for (int i = 0; i < addlen; i++) { mPlayList[position + i] = list[i]; } mPlayListLen += addlen; if (mPlayListLen == 0) { mCursor.close(); mCursor = null; notifyChange(META_CHANGED); } } /** * Appends a list of tracks to the current playlist. * If nothing is playing currently, playback will be started at * the first track. * If the action is NOW, playback will switch to the first of * the new tracks immediately. * @param list The list of tracks to append. * @param action NOW, NEXT or LAST */ public void enqueue(long [] list, int action) { synchronized(this) { if (action == NEXT && mPlayPos + 1 < mPlayListLen) { addToPlayList(list, mPlayPos + 1); notifyChange(QUEUE_CHANGED); } else { // action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen addToPlayList(list, Integer.MAX_VALUE); notifyChange(QUEUE_CHANGED); if (action == NOW) { mPlayPos = mPlayListLen - list.length; openCurrent(); play(); notifyChange(META_CHANGED); return; } } if (mPlayPos < 0) { mPlayPos = 0; openCurrent(); play(); notifyChange(META_CHANGED); } } } /** * Replaces the current playlist with a new list, * and prepares for starting playback at the specified * position in the list, or a random position if the * specified position is 0. * @param list The new list of tracks. */ public void open(long [] list, int position) { synchronized (this) { if (mShuffleMode == SHUFFLE_AUTO) { mShuffleMode = SHUFFLE_NORMAL; } long oldId = getAudioId(); int listlength = list.length; boolean newlist = true; if (mPlayListLen == listlength) { // possible fast path: list might be the same newlist = false; for (int i = 0; i < listlength; i++) { if (list[i] != mPlayList[i]) { newlist = true; break; } } } if (newlist) { addToPlayList(list, -1); notifyChange(QUEUE_CHANGED); } int oldpos = mPlayPos; if (position >= 0) { mPlayPos = position; } else { mPlayPos = mRand.nextInt(mPlayListLen); } mHistory.clear(); saveBookmarkIfNeeded(); openCurrent(); if (oldId != getAudioId()) { notifyChange(META_CHANGED); } } } /** * Moves the item at index1 to index2. * @param index1 * @param index2 */ public void moveQueueItem(int index1, int index2) { synchronized (this) { if (index1 >= mPlayListLen) { index1 = mPlayListLen - 1; } if (index2 >= mPlayListLen) { index2 = mPlayListLen - 1; } if (index1 < index2) { long tmp = mPlayList[index1]; for (int i = index1; i < index2; i++) { mPlayList[i] = mPlayList[i+1]; } mPlayList[index2] = tmp; if (mPlayPos == index1) { mPlayPos = index2; } else if (mPlayPos >= index1 && mPlayPos <= index2) { mPlayPos--; } } else if (index2 < index1) { long tmp = mPlayList[index1]; for (int i = index1; i > index2; i--) { mPlayList[i] = mPlayList[i-1]; } mPlayList[index2] = tmp; if (mPlayPos == index1) { mPlayPos = index2; } else if (mPlayPos >= index2 && mPlayPos <= index1) { mPlayPos++; } } notifyChange(QUEUE_CHANGED); } } /** * Returns the current play list * @return An array of integers containing the IDs of the tracks in the play list */ public long [] getQueue() { synchronized (this) { int len = mPlayListLen; long [] list = new long[len]; for (int i = 0; i < len; i++) { list[i] = mPlayList[i]; } return list; } } private void openCurrent() { synchronized (this) { if (mCursor != null) { mCursor.close(); mCursor = null; } if (mPlayListLen == 0) { return; } stop(false); String id = String.valueOf(mPlayList[mPlayPos]); mCursor = getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursorCols, "_id=" + id , null, null); if (mCursor != null) { mCursor.moveToFirst(); open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id); // go to bookmark if needed if (isPodcast()) { long bookmark = getBookmark(); // Start playing a little bit before the bookmark, // so it's easier to get back in to the narrative. seek(bookmark - 5000); } } } } /** * Opens the specified file and readies it for playback. * * @param path The full path of the file to be opened. */ public void open(String path) { synchronized (this) { if (path == null) { return; } // if mCursor is null, try to associate path with a database cursor if (mCursor == null) { ContentResolver resolver = getContentResolver(); Uri uri; String where; String selectionArgs[]; if (path.startsWith("content://media/")) { uri = Uri.parse(path); where = null; selectionArgs = null; } else { uri = MediaStore.Audio.Media.getContentUriForPath(path); where = MediaStore.Audio.Media.DATA + "=?"; selectionArgs = new String[] { path }; } try { mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null); if (mCursor != null) { if (mCursor.getCount() == 0) { mCursor.close(); mCursor = null; } else { mCursor.moveToNext(); ensurePlayListCapacity(1); mPlayListLen = 1; mPlayList[0] = mCursor.getLong(IDCOLIDX); mPlayPos = 0; } } } catch (UnsupportedOperationException ex) { } } mFileToPlay = path; mPlayer.setDataSource(mFileToPlay); if (! mPlayer.isInitialized()) { stop(true); if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) { // beware: this ends up being recursive because next() calls open() again. next(false); } if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) { // need to make sure we only shows this once mOpenFailedCounter = 0; if (!mQuietMode) { Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show(); } Log.d(LOGTAG, "Failed to open file for playback"); } } else { mOpenFailedCounter = 0; } } } /** * Starts playback of a previously opened file. */ public void play() { mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(), MediaButtonIntentReceiver.class.getName())); if (mPlayer.isInitialized()) { // if we are at the end of the song, go to the next song first long duration = mPlayer.duration(); if (mRepeatMode != REPEAT_CURRENT && duration > 2000 && mPlayer.position() >= duration - 2000) { next(true); } mPlayer.start(); RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar); views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer); if (getAudioId() < 0) { // streaming views.setTextViewText(R.id.trackname, getPath()); views.setTextViewText(R.id.artistalbum, null); } else { String artist = getArtistName(); views.setTextViewText(R.id.trackname, getTrackName()); if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) { artist = getString(R.string.unknown_artist_name); } String album = getAlbumName(); if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) { album = getString(R.string.unknown_album_name); } views.setTextViewText(R.id.artistalbum, getString(R.string.notification_artist_album, artist, album) ); } Notification status = new Notification(); status.contentView = views; status.flags |= Notification.FLAG_ONGOING_EVENT; status.icon = R.drawable.stat_notify_musicplayer; status.contentIntent = PendingIntent.getActivity(this, 0, new Intent("com.android.music.PLAYBACK_VIEWER") .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0); startForeground(PLAYBACKSERVICE_STATUS, status); if (!mIsSupposedToBePlaying) { mIsSupposedToBePlaying = true; notifyChange(PLAYSTATE_CHANGED); } } else if (mPlayListLen <= 0) { // This is mostly so that if you press 'play' on a bluetooth headset // without every having played anything before, it will still play // something. setShuffleMode(SHUFFLE_AUTO); } } private void stop(boolean remove_status_icon) { if (mPlayer.isInitialized()) { mPlayer.stop(); } mFileToPlay = null; if (mCursor != null) { mCursor.close(); mCursor = null; } if (remove_status_icon) { gotoIdleState(); } else { stopForeground(false); } if (remove_status_icon) { mIsSupposedToBePlaying = false; } } /** * Stops playback. */ public void stop() { stop(true); } /** * Pauses playback (call play() to resume) */ public void pause() { synchronized(this) { if (isPlaying()) { mMediaplayerHandler.removeMessages(FADEIN); mPlayer.pause(); gotoIdleState(); mIsSupposedToBePlaying = false; notifyChange(PLAYSTATE_CHANGED); saveBookmarkIfNeeded(); } } } /** Returns whether something is currently playing * * @return true if something is playing (or will be playing shortly, in case * we're currently transitioning between tracks), false if not. */ public boolean isPlaying() { return mIsSupposedToBePlaying; } /* Desired behavior for prev/next/shuffle: - NEXT will move to the next track in the list when not shuffling, and to a track randomly picked from the not-yet-played tracks when shuffling. If all tracks have already been played, pick from the full set, but avoid picking the previously played track if possible. - when shuffling, PREV will go to the previously played track. Hitting PREV again will go to the track played before that, etc. When the start of the history has been reached, PREV is a no-op. When not shuffling, PREV will go to the sequentially previous track (the difference with the shuffle-case is mainly that when not shuffling, the user can back up to tracks that are not in the history). Example: When playing an album with 10 tracks from the start, and enabling shuffle while playing track 5, the remaining tracks (6-10) will be shuffled, e.g. the final play order might be 1-2-3-4-5-8-10-6-9-7. When hitting 'prev' 8 times while playing track 7 in this example, the user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next', a random track will be picked again. If at any time user disables shuffling the next/previous track will be picked in sequential order again. */ public void prev() { synchronized (this) { if (mShuffleMode == SHUFFLE_NORMAL) { // go to previously-played track and remove it from the history int histsize = mHistory.size(); if (histsize == 0) { // prev is a no-op return; } Integer pos = mHistory.remove(histsize - 1); mPlayPos = pos.intValue(); } else { if (mPlayPos > 0) { mPlayPos--; } else { mPlayPos = mPlayListLen - 1; } } saveBookmarkIfNeeded(); stop(false); openCurrent(); play(); notifyChange(META_CHANGED); } } public void next(boolean force) { synchronized (this) { if (mPlayListLen <= 0) { Log.d(LOGTAG, "No play queue"); return; } if (mShuffleMode == SHUFFLE_NORMAL) { // Pick random next track from the not-yet-played ones // TODO: make it work right after adding/removing items in the queue. // Store the current file in the history, but keep the history at a // reasonable size if (mPlayPos >= 0) { mHistory.add(mPlayPos); } if (mHistory.size() > MAX_HISTORY_SIZE) { mHistory.removeElementAt(0); } int numTracks = mPlayListLen; int[] tracks = new int[numTracks]; for (int i=0;i < numTracks; i++) { tracks[i] = i; } int numHistory = mHistory.size(); int numUnplayed = numTracks; for (int i=0;i < numHistory; i++) { int idx = mHistory.get(i).intValue(); if (idx < numTracks && tracks[idx] >= 0) { numUnplayed--; tracks[idx] = -1; } } // 'numUnplayed' now indicates how many tracks have not yet // been played, and 'tracks' contains the indices of those // tracks. if (numUnplayed <=0) { // everything's already been played if (mRepeatMode == REPEAT_ALL || force) { //pick from full set numUnplayed = numTracks; for (int i=0;i < numTracks; i++) { tracks[i] = i; } } else { // all done gotoIdleState(); if (mIsSupposedToBePlaying) { mIsSupposedToBePlaying = false; notifyChange(PLAYSTATE_CHANGED); } return; } } int skip = mRand.nextInt(numUnplayed); int cnt = -1; while (true) { while (tracks[++cnt] < 0) ; skip--; if (skip < 0) { break; } } mPlayPos = cnt; } else if (mShuffleMode == SHUFFLE_AUTO) { doAutoShuffleUpdate(); mPlayPos++; } else { if (mPlayPos >= mPlayListLen - 1) { // we're at the end of the list if (mRepeatMode == REPEAT_NONE && !force) { // all done gotoIdleState(); mIsSupposedToBePlaying = false; notifyChange(PLAYSTATE_CHANGED); return; } else if (mRepeatMode == REPEAT_ALL || force) { mPlayPos = 0; } } else { mPlayPos++; } } saveBookmarkIfNeeded(); stop(false); openCurrent(); play(); notifyChange(META_CHANGED); } } private void gotoIdleState() { mDelayedStopHandler.removeCallbacksAndMessages(null); Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); stopForeground(true); } private void saveBookmarkIfNeeded() { try { if (isPodcast()) { long pos = position(); long bookmark = getBookmark(); long duration = duration(); if ((pos < bookmark && (pos + 10000) > bookmark) || (pos > bookmark && (pos - 10000) < bookmark)) { // The existing bookmark is close to the current // position, so don't update it. return; } if (pos < 15000 || (pos + 10000) > duration) { // if we're near the start or end, clear the bookmark pos = 0; } // write 'pos' to the bookmark field ContentValues values = new ContentValues(); values.put(MediaStore.Audio.Media.BOOKMARK, pos); Uri uri = ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX)); getContentResolver().update(uri, values, null, null); } } catch (SQLiteException ex) { } } // Make sure there are at least 5 items after the currently playing item // and no more than 10 items before. private void doAutoShuffleUpdate() { boolean notify = false; // remove old entries if (mPlayPos > 10) { removeTracks(0, mPlayPos - 9); notify = true; } // add new entries if needed int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos)); for (int i = 0; i < to_add; i++) { // pick something at random from the list int lookback = mHistory.size(); int idx = -1; while(true) { idx = mRand.nextInt(mAutoShuffleList.length); if (!wasRecentlyUsed(idx, lookback)) { break; } lookback /= 2; } mHistory.add(idx); if (mHistory.size() > MAX_HISTORY_SIZE) { mHistory.remove(0); } ensurePlayListCapacity(mPlayListLen + 1); mPlayList[mPlayListLen++] = mAutoShuffleList[idx]; notify = true; } if (notify) { notifyChange(QUEUE_CHANGED); } } // check that the specified idx is not in the history (but only look at at // most lookbacksize entries in the history) private boolean wasRecentlyUsed(int idx, int lookbacksize) { // early exit to prevent infinite loops in case idx == mPlayPos if (lookbacksize == 0) { return false; } int histsize = mHistory.size(); if (histsize < lookbacksize) { Log.d(LOGTAG, "lookback too big"); lookbacksize = histsize; } int maxidx = histsize - 1; for (int i = 0; i < lookbacksize; i++) { long entry = mHistory.get(maxidx - i); if (entry == idx) { return true; } } return false; } // A simple variation of Random that makes sure that the // value it returns is not equal to the value it returned // previously, unless the interval is 1. private static class Shuffler { private int mPrevious; private Random mRandom = new Random(); public int nextInt(int interval) { int ret; do { ret = mRandom.nextInt(interval); } while (ret == mPrevious && interval > 1); mPrevious = ret; return ret; } }; private boolean makeAutoShuffleList() { ContentResolver res = getContentResolver(); Cursor c = null; try { c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1", null, null); if (c == null || c.getCount() == 0) { return false; } int len = c.getCount(); long [] list = new long[len]; for (int i = 0; i < len; i++) { c.moveToNext(); list[i] = c.getLong(0); } mAutoShuffleList = list; return true; } catch (RuntimeException ex) { } finally { if (c != null) { c.close(); } } return false; } /** * Removes the range of tracks specified from the play list. If a file within the range is * the file currently being played, playback will move to the next file after the * range. * @param first The first file to be removed * @param last The last file to be removed * @return the number of tracks deleted */ public int removeTracks(int first, int last) { int numremoved = removeTracksInternal(first, last); if (numremoved > 0) { notifyChange(QUEUE_CHANGED); } return numremoved; } private int removeTracksInternal(int first, int last) { synchronized (this) { if (last < first) return 0; if (first < 0) first = 0; if (last >= mPlayListLen) last = mPlayListLen - 1; boolean gotonext = false; if (first <= mPlayPos && mPlayPos <= last) { mPlayPos = first; gotonext = true; } else if (mPlayPos > last) { mPlayPos -= (last - first + 1); } int num = mPlayListLen - last - 1; for (int i = 0; i < num; i++) { mPlayList[first + i] = mPlayList[last + 1 + i]; } mPlayListLen -= last - first + 1; if (gotonext) { if (mPlayListLen == 0) { stop(true); mPlayPos = -1; if (mCursor != null) { mCursor.close(); mCursor = null; } } else { if (mPlayPos >= mPlayListLen) { mPlayPos = 0; } boolean wasPlaying = isPlaying(); stop(false); openCurrent(); if (wasPlaying) { play(); } } notifyChange(META_CHANGED); } return last - first + 1; } } /** * Removes all instances of the track with the given id * from the playlist. * @param id The id to be removed * @return how many instances of the track were removed */ public int removeTrack(long id) { int numremoved = 0; synchronized (this) { for (int i = 0; i < mPlayListLen; i++) { if (mPlayList[i] == id) { numremoved += removeTracksInternal(i, i); i--; } } } if (numremoved > 0) { notifyChange(QUEUE_CHANGED); } return numremoved; } public void setShuffleMode(int shufflemode) { synchronized(this) { if (mShuffleMode == shufflemode && mPlayListLen > 0) { return; } mShuffleMode = shufflemode; if (mShuffleMode == SHUFFLE_AUTO) { if (makeAutoShuffleList()) { mPlayListLen = 0; doAutoShuffleUpdate(); mPlayPos = 0; openCurrent(); play(); notifyChange(META_CHANGED); return; } else { // failed to build a list of files to shuffle mShuffleMode = SHUFFLE_NONE; } } saveQueue(false); } } public int getShuffleMode() { return mShuffleMode; } public void setRepeatMode(int repeatmode) { synchronized(this) { mRepeatMode = repeatmode; saveQueue(false); } } public int getRepeatMode() { return mRepeatMode; } public int getMediaMountedCount() { return mMediaMountedCount; } /** * Returns the path of the currently playing file, or null if * no file is currently playing. */ public String getPath() { return mFileToPlay; } /** * Returns the rowid of the currently playing file, or -1 if * no file is currently playing. */ public long getAudioId() { synchronized (this) { if (mPlayPos >= 0 && mPlayer.isInitialized()) { return mPlayList[mPlayPos]; } } return -1; } /** * Returns the position in the queue * @return the position in the queue */ public int getQueuePosition() { synchronized(this) { return mPlayPos; } } /** * Starts playing the track at the given position in the queue. * @param pos The position in the queue of the track that will be played. */ public void setQueuePosition(int pos) { synchronized(this) { stop(false); mPlayPos = pos; openCurrent(); play(); notifyChange(META_CHANGED); if (mShuffleMode == SHUFFLE_AUTO) { doAutoShuffleUpdate(); } } } public String getArtistName() { synchronized(this) { if (mCursor == null) { return null; } return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)); } } public long getArtistId() { synchronized (this) { if (mCursor == null) { return -1; } return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID)); } } public String getAlbumName() { synchronized (this) { if (mCursor == null) { return null; } return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)); } } public long getAlbumId() { synchronized (this) { if (mCursor == null) { return -1; } return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)); } } public String getTrackName() { synchronized (this) { if (mCursor == null) { return null; } return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); } } private boolean isPodcast() { synchronized (this) { if (mCursor == null) { return false; } return (mCursor.getInt(PODCASTCOLIDX) > 0); } } private long getBookmark() { synchronized (this) { if (mCursor == null) { return 0; } return mCursor.getLong(BOOKMARKCOLIDX); } } /** * Returns the duration of the file in milliseconds. * Currently this method returns -1 for the duration of MIDI files. */ public long duration() { if (mPlayer.isInitialized()) { return mPlayer.duration(); } return -1; } /** * Returns the current playback position in milliseconds */ public long position() { if (mPlayer.isInitialized()) { return mPlayer.position(); } return -1; } /** * Seeks to the position specified. * * @param pos The position to seek to, in milliseconds */ public long seek(long pos) { if (mPlayer.isInitialized()) { if (pos < 0) pos = 0; if (pos > mPlayer.duration()) pos = mPlayer.duration(); return mPlayer.seek(pos); } return -1; } /** * Sets the audio session ID. * * @param sessionId: the audio session ID. */ public void setAudioSessionId(int sessionId) { synchronized (this) { mPlayer.setAudioSessionId(sessionId); } } /** * Returns the audio session ID. */ public int getAudioSessionId() { synchronized (this) { return mPlayer.getAudioSessionId(); } } /** * Provides a unified interface for dealing with midi files and * other media files. */ private class MultiPlayer { private MediaPlayer mMediaPlayer = new MediaPlayer(); private Handler mHandler; private boolean mIsInitialized = false; public MultiPlayer() { mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK); } public void setDataSource(String path) { try { mMediaPlayer.reset(); mMediaPlayer.setOnPreparedListener(null); if (path.startsWith("content://")) { mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path)); } else { mMediaPlayer.setDataSource(path); } mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.prepare(); } catch (IOException ex) { // TODO: notify the user why the file couldn't be opened mIsInitialized = false; return; } catch (IllegalArgumentException ex) { // TODO: notify the user why the file couldn't be opened mIsInitialized = false; return; } mMediaPlayer.setOnCompletionListener(listener); mMediaPlayer.setOnErrorListener(errorListener); Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION); i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId()); i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName()); sendBroadcast(i); mIsInitialized = true; } public boolean isInitialized() { return mIsInitialized; } public void start() { MusicUtils.debugLog(new Exception("MultiPlayer.start called")); mMediaPlayer.start(); } public void stop() { mMediaPlayer.reset(); mIsInitialized = false; } /** * You CANNOT use this player anymore after calling release() */ public void release() { stop(); mMediaPlayer.release(); } public void pause() { mMediaPlayer.pause(); } public void setHandler(Handler handler) { mHandler = handler; } MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // Acquire a temporary wakelock, since when we return from // this callback the MediaPlayer will release its wakelock // and allow the device to go to sleep. // This temporary wakelock is released when the RELEASE_WAKELOCK // message is processed, but just in case, put a timeout on it. mWakeLock.acquire(30000); mHandler.sendEmptyMessage(TRACK_ENDED); mHandler.sendEmptyMessage(RELEASE_WAKELOCK); } }; MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() { public boolean onError(MediaPlayer mp, int what, int extra) { switch (what) { case MediaPlayer.MEDIA_ERROR_SERVER_DIED: mIsInitialized = false; mMediaPlayer.release(); // Creating a new MediaPlayer and settings its wakemode does not // require the media service, so it's OK to do this now, while the // service is still being restarted mMediaPlayer = new MediaPlayer(); mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK); mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000); return true; default: Log.d("MultiPlayer", "Error: " + what + "," + extra); break; } return false; } }; public long duration() { return mMediaPlayer.getDuration(); } public long position() { return mMediaPlayer.getCurrentPosition(); } public long seek(long whereto) { mMediaPlayer.seekTo((int) whereto); return whereto; } public void setVolume(float vol) { mMediaPlayer.setVolume(vol, vol); } public void setAudioSessionId(int sessionId) { mMediaPlayer.setAudioSessionId(sessionId); } public int getAudioSessionId() { return mMediaPlayer.getAudioSessionId(); } } /* * By making this a static class with a WeakReference to the Service, we * ensure that the Service can be GCd even when the system process still * has a remote reference to the stub. */ static class ServiceStub extends IMediaPlaybackService.Stub { WeakReference<MediaPlaybackService> mService; ServiceStub(MediaPlaybackService service) { mService = new WeakReference<MediaPlaybackService>(service); } public void openFile(String path) { mService.get().open(path); } public void open(long [] list, int position) { mService.get().open(list, position); } public int getQueuePosition() { return mService.get().getQueuePosition(); } public void setQueuePosition(int index) { mService.get().setQueuePosition(index); } public boolean isPlaying() { return mService.get().isPlaying(); } public void stop() { mService.get().stop(); } public void pause() { mService.get().pause(); } public void play() { mService.get().play(); } public void prev() { mService.get().prev(); } public void next() { mService.get().next(true); } public String getTrackName() { return mService.get().getTrackName(); } public String getAlbumName() { return mService.get().getAlbumName(); } public long getAlbumId() { return mService.get().getAlbumId(); } public String getArtistName() { return mService.get().getArtistName(); } public long getArtistId() { return mService.get().getArtistId(); } public void enqueue(long [] list , int action) { mService.get().enqueue(list, action); } public long [] getQueue() { return mService.get().getQueue(); } public void moveQueueItem(int from, int to) { mService.get().moveQueueItem(from, to); } public String getPath() { return mService.get().getPath(); } public long getAudioId() { return mService.get().getAudioId(); } public long position() { return mService.get().position(); } public long duration() { return mService.get().duration(); } public long seek(long pos) { return mService.get().seek(pos); } public void setShuffleMode(int shufflemode) { mService.get().setShuffleMode(shufflemode); } public int getShuffleMode() { return mService.get().getShuffleMode(); } public int removeTracks(int first, int last) { return mService.get().removeTracks(first, last); } public int removeTrack(long id) { return mService.get().removeTrack(id); } public void setRepeatMode(int repeatmode) { mService.get().setRepeatMode(repeatmode); } public int getRepeatMode() { return mService.get().getRepeatMode(); } public int getMediaMountedCount() { return mService.get().getMediaMountedCount(); } public int getAudioSessionId() { return mService.get().getAudioSessionId(); } } @Override protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { writer.println("" + mPlayListLen + " items in queue, currently at index " + mPlayPos); writer.println("Currently loaded:"); writer.println(getArtistName()); writer.println(getAlbumName()); writer.println(getTrackName()); writer.println(getPath()); writer.println("playing: " + mIsSupposedToBePlaying); writer.println("actual: " + mPlayer.mMediaPlayer.isPlaying()); writer.println("shuffle mode: " + mShuffleMode); MusicUtils.debugDump(writer); } private final IBinder mBinder = new ServiceStub(this); }
private void reloadQueue() { String q = null; boolean newstyle = false; int id = mCardId; if (mPreferences.contains("cardid")) { newstyle = true; id = mPreferences.getInt("cardid", ~mCardId); } if (id == mCardId) { // Only restore the saved playlist if the card is still // the same one as when the playlist was saved q = mPreferences.getString("queue", ""); } int qlen = q != null ? q.length() : 0; if (qlen > 1) { //Log.i("@@@@ service", "loaded queue: " + q); int plen = 0; int n = 0; int shift = 0; for (int i = 0; i < qlen; i++) { char c = q.charAt(i); if (c == ';') { ensurePlayListCapacity(plen + 1); mPlayList[plen] = n; plen++; n = 0; shift = 0; } else { if (c >= '0' && c <= '9') { n += ((c - '0') << shift); } else if (c >= 'a' && c <= 'f') { n += ((10 + c - 'a') << shift); } else { // bogus playlist data plen = 0; break; } shift += 4; } } mPlayListLen = plen; int pos = mPreferences.getInt("curpos", 0); if (pos < 0 || pos >= mPlayListLen) { // The saved playlist is bogus, discard it mPlayListLen = 0; return; } mPlayPos = pos; // When reloadQueue is called in response to a card-insertion, // we might not be able to query the media provider right away. // To deal with this, try querying for the current file, and if // that fails, wait a while and try again. If that too fails, // assume there is a problem and don't restore the state. Cursor crsr = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String [] {"_id"}, "_id=" + mPlayList[mPlayPos] , null, null); if (crsr == null || crsr.getCount() == 0) { // wait a bit and try again SystemClock.sleep(3000); crsr = getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursorCols, "_id=" + mPlayList[mPlayPos] , null, null); } if (crsr != null) { crsr.close(); } // Make sure we don't auto-skip to the next song, since that // also starts playback. What could happen in that case is: // - music is paused // - go to UMS and delete some files, including the currently playing one // - come back from UMS // (time passes) // - music app is killed for some reason (out of memory) // - music service is restarted, service restores state, doesn't find // the "current" file, goes to the next and: playback starts on its // own, potentially at some random inconvenient time. mOpenFailedCounter = 20; mQuietMode = true; openCurrent(); mQuietMode = false; if (!mPlayer.isInitialized()) { // couldn't restore the saved state mPlayListLen = 0; return; } long seekpos = mPreferences.getLong("seekpos", 0); seek(seekpos >= 0 && seekpos < duration() ? seekpos : 0); Log.d(LOGTAG, "restored queue, currently at position " + position() + "/" + duration() + " (requested " + seekpos + ")"); int repmode = mPreferences.getInt("repeatmode", REPEAT_NONE); if (repmode != REPEAT_ALL && repmode != REPEAT_CURRENT) { repmode = REPEAT_NONE; } mRepeatMode = repmode; int shufmode = mPreferences.getInt("shufflemode", SHUFFLE_NONE); if (shufmode != SHUFFLE_AUTO && shufmode != SHUFFLE_NORMAL) { shufmode = SHUFFLE_NONE; } if (shufmode != SHUFFLE_NONE) { // in shuffle mode we need to restore the history too q = mPreferences.getString("history", ""); qlen = q != null ? q.length() : 0; if (qlen > 1) { plen = 0; n = 0; shift = 0; mHistory.clear(); for (int i = 0; i < qlen; i++) { char c = q.charAt(i); if (c == ';') { if (n >= mPlayListLen) { // bogus history data mHistory.clear(); break; } mHistory.add(n); n = 0; shift = 0; } else { if (c >= '0' && c <= '9') { n += ((c - '0') << shift); } else if (c >= 'a' && c <= 'f') { n += ((10 + c - 'a') << shift); } else { // bogus history data mHistory.clear(); break; } shift += 4; } } } } if (shufmode == SHUFFLE_AUTO) { if (! makeAutoShuffleList()) { shufmode = SHUFFLE_NONE; } } mShuffleMode = shufmode; } } @Override public IBinder onBind(Intent intent) { mDelayedStopHandler.removeCallbacksAndMessages(null); mServiceInUse = true; return mBinder; } @Override public void onRebind(Intent intent) { mDelayedStopHandler.removeCallbacksAndMessages(null); mServiceInUse = true; } @Override public int onStartCommand(Intent intent, int flags, int startId) { mServiceStartId = startId; mDelayedStopHandler.removeCallbacksAndMessages(null); if (intent != null) { String action = intent.getAction(); String cmd = intent.getStringExtra("command"); MusicUtils.debugLog("onStartCommand " + action + " / " + cmd); if (CMDNEXT.equals(cmd) || NEXT_ACTION.equals(action)) { next(true); } else if (CMDPREVIOUS.equals(cmd) || PREVIOUS_ACTION.equals(action)) { if (position() < 2000) { prev(); } else { seek(0); play(); } } else if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) { if (isPlaying()) { pause(); mPausedByTransientLossOfFocus = false; } else { play(); } } else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) { pause(); mPausedByTransientLossOfFocus = false; } else if (CMDSTOP.equals(cmd)) { pause(); mPausedByTransientLossOfFocus = false; seek(0); } } // make sure the service will shut down on its own if it was // just started but not bound to and nothing is playing mDelayedStopHandler.removeCallbacksAndMessages(null); Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); return START_STICKY; } @Override public boolean onUnbind(Intent intent) { mServiceInUse = false; // Take a snapshot of the current playlist saveQueue(true); if (isPlaying() || mPausedByTransientLossOfFocus) { // something is currently playing, or will be playing once // an in-progress action requesting audio focus ends, so don't stop the service now. return true; } // If there is a playlist but playback is paused, then wait a while // before stopping the service, so that pause/resume isn't slow. // Also delay stopping the service if we're transitioning between tracks. if (mPlayListLen > 0 || mMediaplayerHandler.hasMessages(TRACK_ENDED)) { Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); return true; } // No active playlist, OK to stop the service right now stopSelf(mServiceStartId); return true; } private Handler mDelayedStopHandler = new Handler() { @Override public void handleMessage(Message msg) { // Check again to make sure nothing is playing right now if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse || mMediaplayerHandler.hasMessages(TRACK_ENDED)) { return; } // save the queue again, because it might have changed // since the user exited the music app (because of // party-shuffle or because the play-position changed) saveQueue(true); stopSelf(mServiceStartId); } }; /** * Called when we receive a ACTION_MEDIA_EJECT notification. * * @param storagePath path to mount point for the removed media */ public void closeExternalStorageFiles(String storagePath) { // stop playback and clean up if the SD card is going to be unmounted. stop(true); notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); } /** * Registers an intent to listen for ACTION_MEDIA_EJECT notifications. * The intent will call closeExternalStorageFiles() if the external media * is going to be ejected, so applications can clean up any files they have open. */ public void registerExternalStorageListener() { if (mUnmountReceiver == null) { mUnmountReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_EJECT)) { saveQueue(true); mQueueIsSaveable = false; closeExternalStorageFiles(intent.getData().getPath()); } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) { mMediaMountedCount++; mCardId = MusicUtils.getCardId(MediaPlaybackService.this); reloadQueue(); mQueueIsSaveable = true; notifyChange(QUEUE_CHANGED); notifyChange(META_CHANGED); } } }; IntentFilter iFilter = new IntentFilter(); iFilter.addAction(Intent.ACTION_MEDIA_EJECT); iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED); iFilter.addDataScheme("file"); registerReceiver(mUnmountReceiver, iFilter); } } /** * Notify the change-receivers that something has changed. * The intent that is sent contains the following data * for the currently playing track: * "id" - Integer: the database row ID * "artist" - String: the name of the artist * "album" - String: the name of the album * "track" - String: the name of the track * The intent has an action that is one of * "com.android.music.metachanged" * "com.android.music.queuechanged", * "com.android.music.playbackcomplete" * "com.android.music.playstatechanged" * respectively indicating that a new track has * started playing, that the playback queue has * changed, that playback has stopped because * the last file in the list has been played, * or that the play-state changed (paused/resumed). */ private void notifyChange(String what) { Intent i = new Intent(what); i.putExtra("id", Long.valueOf(getAudioId())); i.putExtra("artist", getArtistName()); i.putExtra("album",getAlbumName()); i.putExtra("track", getTrackName()); i.putExtra("playing", isPlaying()); sendStickyBroadcast(i); if (what.equals(QUEUE_CHANGED)) { saveQueue(true); } else { saveQueue(false); } // Share this notification directly with our widgets mAppWidgetProvider.notifyChange(this, what); } private void ensurePlayListCapacity(int size) { if (mPlayList == null || size > mPlayList.length) { // reallocate at 2x requested size so we don't // need to grow and copy the array for every // insert long [] newlist = new long[size * 2]; int len = mPlayList != null ? mPlayList.length : mPlayListLen; for (int i = 0; i < len; i++) { newlist[i] = mPlayList[i]; } mPlayList = newlist; } // FIXME: shrink the array when the needed size is much smaller // than the allocated size } // insert the list of songs at the specified position in the playlist private void addToPlayList(long [] list, int position) { int addlen = list.length; if (position < 0) { // overwrite mPlayListLen = 0; position = 0; } ensurePlayListCapacity(mPlayListLen + addlen); if (position > mPlayListLen) { position = mPlayListLen; } // move part of list after insertion point int tailsize = mPlayListLen - position; for (int i = tailsize ; i > 0 ; i--) { mPlayList[position + i] = mPlayList[position + i - addlen]; } // copy list into playlist for (int i = 0; i < addlen; i++) { mPlayList[position + i] = list[i]; } mPlayListLen += addlen; if (mPlayListLen == 0) { mCursor.close(); mCursor = null; notifyChange(META_CHANGED); } } /** * Appends a list of tracks to the current playlist. * If nothing is playing currently, playback will be started at * the first track. * If the action is NOW, playback will switch to the first of * the new tracks immediately. * @param list The list of tracks to append. * @param action NOW, NEXT or LAST */ public void enqueue(long [] list, int action) { synchronized(this) { if (action == NEXT && mPlayPos + 1 < mPlayListLen) { addToPlayList(list, mPlayPos + 1); notifyChange(QUEUE_CHANGED); } else { // action == LAST || action == NOW || mPlayPos + 1 == mPlayListLen addToPlayList(list, Integer.MAX_VALUE); notifyChange(QUEUE_CHANGED); if (action == NOW) { mPlayPos = mPlayListLen - list.length; openCurrent(); play(); notifyChange(META_CHANGED); return; } } if (mPlayPos < 0) { mPlayPos = 0; openCurrent(); play(); notifyChange(META_CHANGED); } } } /** * Replaces the current playlist with a new list, * and prepares for starting playback at the specified * position in the list, or a random position if the * specified position is 0. * @param list The new list of tracks. */ public void open(long [] list, int position) { synchronized (this) { if (mShuffleMode == SHUFFLE_AUTO) { mShuffleMode = SHUFFLE_NORMAL; } long oldId = getAudioId(); int listlength = list.length; boolean newlist = true; if (mPlayListLen == listlength) { // possible fast path: list might be the same newlist = false; for (int i = 0; i < listlength; i++) { if (list[i] != mPlayList[i]) { newlist = true; break; } } } if (newlist) { addToPlayList(list, -1); notifyChange(QUEUE_CHANGED); } int oldpos = mPlayPos; if (position >= 0) { mPlayPos = position; } else { mPlayPos = mRand.nextInt(mPlayListLen); } mHistory.clear(); saveBookmarkIfNeeded(); openCurrent(); if (oldId != getAudioId()) { notifyChange(META_CHANGED); } } } /** * Moves the item at index1 to index2. * @param index1 * @param index2 */ public void moveQueueItem(int index1, int index2) { synchronized (this) { if (index1 >= mPlayListLen) { index1 = mPlayListLen - 1; } if (index2 >= mPlayListLen) { index2 = mPlayListLen - 1; } if (index1 < index2) { long tmp = mPlayList[index1]; for (int i = index1; i < index2; i++) { mPlayList[i] = mPlayList[i+1]; } mPlayList[index2] = tmp; if (mPlayPos == index1) { mPlayPos = index2; } else if (mPlayPos >= index1 && mPlayPos <= index2) { mPlayPos--; } } else if (index2 < index1) { long tmp = mPlayList[index1]; for (int i = index1; i > index2; i--) { mPlayList[i] = mPlayList[i-1]; } mPlayList[index2] = tmp; if (mPlayPos == index1) { mPlayPos = index2; } else if (mPlayPos >= index2 && mPlayPos <= index1) { mPlayPos++; } } notifyChange(QUEUE_CHANGED); } } /** * Returns the current play list * @return An array of integers containing the IDs of the tracks in the play list */ public long [] getQueue() { synchronized (this) { int len = mPlayListLen; long [] list = new long[len]; for (int i = 0; i < len; i++) { list[i] = mPlayList[i]; } return list; } } private void openCurrent() { synchronized (this) { if (mCursor != null) { mCursor.close(); mCursor = null; } if (mPlayListLen == 0) { return; } stop(false); String id = String.valueOf(mPlayList[mPlayPos]); mCursor = getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursorCols, "_id=" + id , null, null); if (mCursor != null) { mCursor.moveToFirst(); open(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + id); // go to bookmark if needed if (isPodcast()) { long bookmark = getBookmark(); // Start playing a little bit before the bookmark, // so it's easier to get back in to the narrative. seek(bookmark - 5000); } } } } /** * Opens the specified file and readies it for playback. * * @param path The full path of the file to be opened. */ public void open(String path) { synchronized (this) { if (path == null) { return; } // if mCursor is null, try to associate path with a database cursor if (mCursor == null) { ContentResolver resolver = getContentResolver(); Uri uri; String where; String selectionArgs[]; if (path.startsWith("content://media/")) { uri = Uri.parse(path); where = null; selectionArgs = null; } else { uri = MediaStore.Audio.Media.getContentUriForPath(path); where = MediaStore.Audio.Media.DATA + "=?"; selectionArgs = new String[] { path }; } try { mCursor = resolver.query(uri, mCursorCols, where, selectionArgs, null); if (mCursor != null) { if (mCursor.getCount() == 0) { mCursor.close(); mCursor = null; } else { mCursor.moveToNext(); ensurePlayListCapacity(1); mPlayListLen = 1; mPlayList[0] = mCursor.getLong(IDCOLIDX); mPlayPos = 0; } } } catch (UnsupportedOperationException ex) { } } mFileToPlay = path; mPlayer.setDataSource(mFileToPlay); if (! mPlayer.isInitialized()) { stop(true); if (mOpenFailedCounter++ < 10 && mPlayListLen > 1) { // beware: this ends up being recursive because next() calls open() again. next(false); } if (! mPlayer.isInitialized() && mOpenFailedCounter != 0) { // need to make sure we only shows this once mOpenFailedCounter = 0; if (!mQuietMode) { Toast.makeText(this, R.string.playback_failed, Toast.LENGTH_SHORT).show(); } Log.d(LOGTAG, "Failed to open file for playback"); } } else { mOpenFailedCounter = 0; } } } /** * Starts playback of a previously opened file. */ public void play() { mAudioManager.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(), MediaButtonIntentReceiver.class.getName())); if (mPlayer.isInitialized()) { // if we are at the end of the song, go to the next song first long duration = mPlayer.duration(); if (mRepeatMode != REPEAT_CURRENT && duration > 2000 && mPlayer.position() >= duration - 2000) { next(true); } mPlayer.start(); RemoteViews views = new RemoteViews(getPackageName(), R.layout.statusbar); views.setImageViewResource(R.id.icon, R.drawable.stat_notify_musicplayer); if (getAudioId() < 0) { // streaming views.setTextViewText(R.id.trackname, getPath()); views.setTextViewText(R.id.artistalbum, null); } else { String artist = getArtistName(); views.setTextViewText(R.id.trackname, getTrackName()); if (artist == null || artist.equals(MediaStore.UNKNOWN_STRING)) { artist = getString(R.string.unknown_artist_name); } String album = getAlbumName(); if (album == null || album.equals(MediaStore.UNKNOWN_STRING)) { album = getString(R.string.unknown_album_name); } views.setTextViewText(R.id.artistalbum, getString(R.string.notification_artist_album, artist, album) ); } Notification status = new Notification(); status.contentView = views; status.flags |= Notification.FLAG_ONGOING_EVENT; status.icon = R.drawable.stat_notify_musicplayer; status.contentIntent = PendingIntent.getActivity(this, 0, new Intent("com.android.music.PLAYBACK_VIEWER") .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0); startForeground(PLAYBACKSERVICE_STATUS, status); if (!mIsSupposedToBePlaying) { mIsSupposedToBePlaying = true; notifyChange(PLAYSTATE_CHANGED); } } else if (mPlayListLen <= 0) { // This is mostly so that if you press 'play' on a bluetooth headset // without every having played anything before, it will still play // something. setShuffleMode(SHUFFLE_AUTO); } } private void stop(boolean remove_status_icon) { if (mPlayer.isInitialized()) { mPlayer.stop(); } mFileToPlay = null; if (mCursor != null) { mCursor.close(); mCursor = null; } if (remove_status_icon) { gotoIdleState(); } else { stopForeground(false); } if (remove_status_icon) { mIsSupposedToBePlaying = false; } } /** * Stops playback. */ public void stop() { stop(true); } /** * Pauses playback (call play() to resume) */ public void pause() { synchronized(this) { if (isPlaying()) { mMediaplayerHandler.removeMessages(FADEINFROMSTART); mPlayer.pause(); gotoIdleState(); mIsSupposedToBePlaying = false; notifyChange(PLAYSTATE_CHANGED); saveBookmarkIfNeeded(); } } } /** Returns whether something is currently playing * * @return true if something is playing (or will be playing shortly, in case * we're currently transitioning between tracks), false if not. */ public boolean isPlaying() { return mIsSupposedToBePlaying; } /* Desired behavior for prev/next/shuffle: - NEXT will move to the next track in the list when not shuffling, and to a track randomly picked from the not-yet-played tracks when shuffling. If all tracks have already been played, pick from the full set, but avoid picking the previously played track if possible. - when shuffling, PREV will go to the previously played track. Hitting PREV again will go to the track played before that, etc. When the start of the history has been reached, PREV is a no-op. When not shuffling, PREV will go to the sequentially previous track (the difference with the shuffle-case is mainly that when not shuffling, the user can back up to tracks that are not in the history). Example: When playing an album with 10 tracks from the start, and enabling shuffle while playing track 5, the remaining tracks (6-10) will be shuffled, e.g. the final play order might be 1-2-3-4-5-8-10-6-9-7. When hitting 'prev' 8 times while playing track 7 in this example, the user will go to tracks 9-6-10-8-5-4-3-2. If the user then hits 'next', a random track will be picked again. If at any time user disables shuffling the next/previous track will be picked in sequential order again. */ public void prev() { synchronized (this) { if (mShuffleMode == SHUFFLE_NORMAL) { // go to previously-played track and remove it from the history int histsize = mHistory.size(); if (histsize == 0) { // prev is a no-op return; } Integer pos = mHistory.remove(histsize - 1); mPlayPos = pos.intValue(); } else { if (mPlayPos > 0) { mPlayPos--; } else { mPlayPos = mPlayListLen - 1; } } saveBookmarkIfNeeded(); stop(false); openCurrent(); play(); notifyChange(META_CHANGED); } } public void next(boolean force) { synchronized (this) { if (mPlayListLen <= 0) { Log.d(LOGTAG, "No play queue"); return; } if (mShuffleMode == SHUFFLE_NORMAL) { // Pick random next track from the not-yet-played ones // TODO: make it work right after adding/removing items in the queue. // Store the current file in the history, but keep the history at a // reasonable size if (mPlayPos >= 0) { mHistory.add(mPlayPos); } if (mHistory.size() > MAX_HISTORY_SIZE) { mHistory.removeElementAt(0); } int numTracks = mPlayListLen; int[] tracks = new int[numTracks]; for (int i=0;i < numTracks; i++) { tracks[i] = i; } int numHistory = mHistory.size(); int numUnplayed = numTracks; for (int i=0;i < numHistory; i++) { int idx = mHistory.get(i).intValue(); if (idx < numTracks && tracks[idx] >= 0) { numUnplayed--; tracks[idx] = -1; } } // 'numUnplayed' now indicates how many tracks have not yet // been played, and 'tracks' contains the indices of those // tracks. if (numUnplayed <=0) { // everything's already been played if (mRepeatMode == REPEAT_ALL || force) { //pick from full set numUnplayed = numTracks; for (int i=0;i < numTracks; i++) { tracks[i] = i; } } else { // all done gotoIdleState(); if (mIsSupposedToBePlaying) { mIsSupposedToBePlaying = false; notifyChange(PLAYSTATE_CHANGED); } return; } } int skip = mRand.nextInt(numUnplayed); int cnt = -1; while (true) { while (tracks[++cnt] < 0) ; skip--; if (skip < 0) { break; } } mPlayPos = cnt; } else if (mShuffleMode == SHUFFLE_AUTO) { doAutoShuffleUpdate(); mPlayPos++; } else { if (mPlayPos >= mPlayListLen - 1) { // we're at the end of the list if (mRepeatMode == REPEAT_NONE && !force) { // all done gotoIdleState(); mIsSupposedToBePlaying = false; notifyChange(PLAYSTATE_CHANGED); return; } else if (mRepeatMode == REPEAT_ALL || force) { mPlayPos = 0; } } else { mPlayPos++; } } saveBookmarkIfNeeded(); stop(false); openCurrent(); play(); notifyChange(META_CHANGED); } } private void gotoIdleState() { mDelayedStopHandler.removeCallbacksAndMessages(null); Message msg = mDelayedStopHandler.obtainMessage(); mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY); stopForeground(true); } private void saveBookmarkIfNeeded() { try { if (isPodcast()) { long pos = position(); long bookmark = getBookmark(); long duration = duration(); if ((pos < bookmark && (pos + 10000) > bookmark) || (pos > bookmark && (pos - 10000) < bookmark)) { // The existing bookmark is close to the current // position, so don't update it. return; } if (pos < 15000 || (pos + 10000) > duration) { // if we're near the start or end, clear the bookmark pos = 0; } // write 'pos' to the bookmark field ContentValues values = new ContentValues(); values.put(MediaStore.Audio.Media.BOOKMARK, pos); Uri uri = ContentUris.withAppendedId( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, mCursor.getLong(IDCOLIDX)); getContentResolver().update(uri, values, null, null); } } catch (SQLiteException ex) { } } // Make sure there are at least 5 items after the currently playing item // and no more than 10 items before. private void doAutoShuffleUpdate() { boolean notify = false; // remove old entries if (mPlayPos > 10) { removeTracks(0, mPlayPos - 9); notify = true; } // add new entries if needed int to_add = 7 - (mPlayListLen - (mPlayPos < 0 ? -1 : mPlayPos)); for (int i = 0; i < to_add; i++) { // pick something at random from the list int lookback = mHistory.size(); int idx = -1; while(true) { idx = mRand.nextInt(mAutoShuffleList.length); if (!wasRecentlyUsed(idx, lookback)) { break; } lookback /= 2; } mHistory.add(idx); if (mHistory.size() > MAX_HISTORY_SIZE) { mHistory.remove(0); } ensurePlayListCapacity(mPlayListLen + 1); mPlayList[mPlayListLen++] = mAutoShuffleList[idx]; notify = true; } if (notify) { notifyChange(QUEUE_CHANGED); } } // check that the specified idx is not in the history (but only look at at // most lookbacksize entries in the history) private boolean wasRecentlyUsed(int idx, int lookbacksize) { // early exit to prevent infinite loops in case idx == mPlayPos if (lookbacksize == 0) { return false; } int histsize = mHistory.size(); if (histsize < lookbacksize) { Log.d(LOGTAG, "lookback too big"); lookbacksize = histsize; } int maxidx = histsize - 1; for (int i = 0; i < lookbacksize; i++) { long entry = mHistory.get(maxidx - i); if (entry == idx) { return true; } } return false; } // A simple variation of Random that makes sure that the // value it returns is not equal to the value it returned // previously, unless the interval is 1. private static class Shuffler { private int mPrevious; private Random mRandom = new Random(); public int nextInt(int interval) { int ret; do { ret = mRandom.nextInt(interval); } while (ret == mPrevious && interval > 1); mPrevious = ret; return ret; } }; private boolean makeAutoShuffleList() { ContentResolver res = getContentResolver(); Cursor c = null; try { c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1", null, null); if (c == null || c.getCount() == 0) { return false; } int len = c.getCount(); long [] list = new long[len]; for (int i = 0; i < len; i++) { c.moveToNext(); list[i] = c.getLong(0); } mAutoShuffleList = list; return true; } catch (RuntimeException ex) { } finally { if (c != null) { c.close(); } } return false; } /** * Removes the range of tracks specified from the play list. If a file within the range is * the file currently being played, playback will move to the next file after the * range. * @param first The first file to be removed * @param last The last file to be removed * @return the number of tracks deleted */ public int removeTracks(int first, int last) { int numremoved = removeTracksInternal(first, last); if (numremoved > 0) { notifyChange(QUEUE_CHANGED); } return numremoved; } private int removeTracksInternal(int first, int last) { synchronized (this) { if (last < first) return 0; if (first < 0) first = 0; if (last >= mPlayListLen) last = mPlayListLen - 1; boolean gotonext = false; if (first <= mPlayPos && mPlayPos <= last) { mPlayPos = first; gotonext = true; } else if (mPlayPos > last) { mPlayPos -= (last - first + 1); } int num = mPlayListLen - last - 1; for (int i = 0; i < num; i++) { mPlayList[first + i] = mPlayList[last + 1 + i]; } mPlayListLen -= last - first + 1; if (gotonext) { if (mPlayListLen == 0) { stop(true); mPlayPos = -1; if (mCursor != null) { mCursor.close(); mCursor = null; } } else { if (mPlayPos >= mPlayListLen) { mPlayPos = 0; } boolean wasPlaying = isPlaying(); stop(false); openCurrent(); if (wasPlaying) { play(); } } notifyChange(META_CHANGED); } return last - first + 1; } } /** * Removes all instances of the track with the given id * from the playlist. * @param id The id to be removed * @return how many instances of the track were removed */ public int removeTrack(long id) { int numremoved = 0; synchronized (this) { for (int i = 0; i < mPlayListLen; i++) { if (mPlayList[i] == id) { numremoved += removeTracksInternal(i, i); i--; } } } if (numremoved > 0) { notifyChange(QUEUE_CHANGED); } return numremoved; } public void setShuffleMode(int shufflemode) { synchronized(this) { if (mShuffleMode == shufflemode && mPlayListLen > 0) { return; } mShuffleMode = shufflemode; if (mShuffleMode == SHUFFLE_AUTO) { if (makeAutoShuffleList()) { mPlayListLen = 0; doAutoShuffleUpdate(); mPlayPos = 0; openCurrent(); play(); notifyChange(META_CHANGED); return; } else { // failed to build a list of files to shuffle mShuffleMode = SHUFFLE_NONE; } } saveQueue(false); } } public int getShuffleMode() { return mShuffleMode; } public void setRepeatMode(int repeatmode) { synchronized(this) { mRepeatMode = repeatmode; saveQueue(false); } } public int getRepeatMode() { return mRepeatMode; } public int getMediaMountedCount() { return mMediaMountedCount; } /** * Returns the path of the currently playing file, or null if * no file is currently playing. */ public String getPath() { return mFileToPlay; } /** * Returns the rowid of the currently playing file, or -1 if * no file is currently playing. */ public long getAudioId() { synchronized (this) { if (mPlayPos >= 0 && mPlayer.isInitialized()) { return mPlayList[mPlayPos]; } } return -1; } /** * Returns the position in the queue * @return the position in the queue */ public int getQueuePosition() { synchronized(this) { return mPlayPos; } } /** * Starts playing the track at the given position in the queue. * @param pos The position in the queue of the track that will be played. */ public void setQueuePosition(int pos) { synchronized(this) { stop(false); mPlayPos = pos; openCurrent(); play(); notifyChange(META_CHANGED); if (mShuffleMode == SHUFFLE_AUTO) { doAutoShuffleUpdate(); } } } public String getArtistName() { synchronized(this) { if (mCursor == null) { return null; } return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)); } } public long getArtistId() { synchronized (this) { if (mCursor == null) { return -1; } return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID)); } } public String getAlbumName() { synchronized (this) { if (mCursor == null) { return null; } return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM)); } } public long getAlbumId() { synchronized (this) { if (mCursor == null) { return -1; } return mCursor.getLong(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID)); } } public String getTrackName() { synchronized (this) { if (mCursor == null) { return null; } return mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); } } private boolean isPodcast() { synchronized (this) { if (mCursor == null) { return false; } return (mCursor.getInt(PODCASTCOLIDX) > 0); } } private long getBookmark() { synchronized (this) { if (mCursor == null) { return 0; } return mCursor.getLong(BOOKMARKCOLIDX); } } /** * Returns the duration of the file in milliseconds. * Currently this method returns -1 for the duration of MIDI files. */ public long duration() { if (mPlayer.isInitialized()) { return mPlayer.duration(); } return -1; } /** * Returns the current playback position in milliseconds */ public long position() { if (mPlayer.isInitialized()) { return mPlayer.position(); } return -1; } /** * Seeks to the position specified. * * @param pos The position to seek to, in milliseconds */ public long seek(long pos) { if (mPlayer.isInitialized()) { if (pos < 0) pos = 0; if (pos > mPlayer.duration()) pos = mPlayer.duration(); return mPlayer.seek(pos); } return -1; } /** * Sets the audio session ID. * * @param sessionId: the audio session ID. */ public void setAudioSessionId(int sessionId) { synchronized (this) { mPlayer.setAudioSessionId(sessionId); } } /** * Returns the audio session ID. */ public int getAudioSessionId() { synchronized (this) { return mPlayer.getAudioSessionId(); } } /** * Provides a unified interface for dealing with midi files and * other media files. */ private class MultiPlayer { private MediaPlayer mMediaPlayer = new MediaPlayer(); private Handler mHandler; private boolean mIsInitialized = false; public MultiPlayer() { mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK); } public void setDataSource(String path) { try { mMediaPlayer.reset(); mMediaPlayer.setOnPreparedListener(null); if (path.startsWith("content://")) { mMediaPlayer.setDataSource(MediaPlaybackService.this, Uri.parse(path)); } else { mMediaPlayer.setDataSource(path); } mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.prepare(); } catch (IOException ex) { // TODO: notify the user why the file couldn't be opened mIsInitialized = false; return; } catch (IllegalArgumentException ex) { // TODO: notify the user why the file couldn't be opened mIsInitialized = false; return; } mMediaPlayer.setOnCompletionListener(listener); mMediaPlayer.setOnErrorListener(errorListener); Intent i = new Intent(AudioEffect.ACTION_OPEN_AUDIO_EFFECT_CONTROL_SESSION); i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, getAudioSessionId()); i.putExtra(AudioEffect.EXTRA_PACKAGE_NAME, getPackageName()); sendBroadcast(i); mIsInitialized = true; } public boolean isInitialized() { return mIsInitialized; } public void start() { MusicUtils.debugLog(new Exception("MultiPlayer.start called")); mMediaPlayer.start(); } public void stop() { mMediaPlayer.reset(); mIsInitialized = false; } /** * You CANNOT use this player anymore after calling release() */ public void release() { stop(); mMediaPlayer.release(); } public void pause() { mMediaPlayer.pause(); } public void setHandler(Handler handler) { mHandler = handler; } MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mp) { // Acquire a temporary wakelock, since when we return from // this callback the MediaPlayer will release its wakelock // and allow the device to go to sleep. // This temporary wakelock is released when the RELEASE_WAKELOCK // message is processed, but just in case, put a timeout on it. mWakeLock.acquire(30000); mHandler.sendEmptyMessage(TRACK_ENDED); mHandler.sendEmptyMessage(RELEASE_WAKELOCK); } }; MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() { public boolean onError(MediaPlayer mp, int what, int extra) { switch (what) { case MediaPlayer.MEDIA_ERROR_SERVER_DIED: mIsInitialized = false; mMediaPlayer.release(); // Creating a new MediaPlayer and settings its wakemode does not // require the media service, so it's OK to do this now, while the // service is still being restarted mMediaPlayer = new MediaPlayer(); mMediaPlayer.setWakeMode(MediaPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK); mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000); return true; default: Log.d("MultiPlayer", "Error: " + what + "," + extra); break; } return false; } }; public long duration() { return mMediaPlayer.getDuration(); } public long position() { return mMediaPlayer.getCurrentPosition(); } public long seek(long whereto) { mMediaPlayer.seekTo((int) whereto); return whereto; } public void setVolume(float vol) { mMediaPlayer.setVolume(vol, vol); } public void setAudioSessionId(int sessionId) { mMediaPlayer.setAudioSessionId(sessionId); } public int getAudioSessionId() { return mMediaPlayer.getAudioSessionId(); } } /* * By making this a static class with a WeakReference to the Service, we * ensure that the Service can be GCd even when the system process still * has a remote reference to the stub. */ static class ServiceStub extends IMediaPlaybackService.Stub { WeakReference<MediaPlaybackService> mService; ServiceStub(MediaPlaybackService service) { mService = new WeakReference<MediaPlaybackService>(service); } public void openFile(String path) { mService.get().open(path); } public void open(long [] list, int position) { mService.get().open(list, position); } public int getQueuePosition() { return mService.get().getQueuePosition(); } public void setQueuePosition(int index) { mService.get().setQueuePosition(index); } public boolean isPlaying() { return mService.get().isPlaying(); } public void stop() { mService.get().stop(); } public void pause() { mService.get().pause(); } public void play() { mService.get().play(); } public void prev() { mService.get().prev(); } public void next() { mService.get().next(true); } public String getTrackName() { return mService.get().getTrackName(); } public String getAlbumName() { return mService.get().getAlbumName(); } public long getAlbumId() { return mService.get().getAlbumId(); } public String getArtistName() { return mService.get().getArtistName(); } public long getArtistId() { return mService.get().getArtistId(); } public void enqueue(long [] list , int action) { mService.get().enqueue(list, action); } public long [] getQueue() { return mService.get().getQueue(); } public void moveQueueItem(int from, int to) { mService.get().moveQueueItem(from, to); } public String getPath() { return mService.get().getPath(); } public long getAudioId() { return mService.get().getAudioId(); } public long position() { return mService.get().position(); } public long duration() { return mService.get().duration(); } public long seek(long pos) { return mService.get().seek(pos); } public void setShuffleMode(int shufflemode) { mService.get().setShuffleMode(shufflemode); } public int getShuffleMode() { return mService.get().getShuffleMode(); } public int removeTracks(int first, int last) { return mService.get().removeTracks(first, last); } public int removeTrack(long id) { return mService.get().removeTrack(id); } public void setRepeatMode(int repeatmode) { mService.get().setRepeatMode(repeatmode); } public int getRepeatMode() { return mService.get().getRepeatMode(); } public int getMediaMountedCount() { return mService.get().getMediaMountedCount(); } public int getAudioSessionId() { return mService.get().getAudioSessionId(); } } @Override protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { writer.println("" + mPlayListLen + " items in queue, currently at index " + mPlayPos); writer.println("Currently loaded:"); writer.println(getArtistName()); writer.println(getAlbumName()); writer.println(getTrackName()); writer.println(getPath()); writer.println("playing: " + mIsSupposedToBePlaying); writer.println("actual: " + mPlayer.mMediaPlayer.isPlaying()); writer.println("shuffle mode: " + mShuffleMode); MusicUtils.debugDump(writer); } private final IBinder mBinder = new ServiceStub(this); }
diff --git a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnBlameHandler.java b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnBlameHandler.java index d3fd69463..0e3e1bbce 100644 --- a/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnBlameHandler.java +++ b/scm-plugins/scm-svn-plugin/src/main/java/sonia/scm/repository/SvnBlameHandler.java @@ -1,164 +1,164 @@ /** * Copyright (c) 2010, Sebastian Sdorra * 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 SCM-Manager; nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://bitbucket.org/sdorra/scm-manager * */ package sonia.scm.repository; //~--- non-JDK imports -------------------------------------------------------- import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.wc.ISVNAnnotateHandler; import sonia.scm.util.Util; //~--- JDK imports ------------------------------------------------------------ import java.io.File; import java.util.Date; import java.util.List; /** * * @author Sebastian Sdorra */ public class SvnBlameHandler implements ISVNAnnotateHandler { /** * Constructs ... * * * @param blameLines */ public SvnBlameHandler(List<BlameLine> blameLines) { this.blameLines = blameLines; } //~--- methods -------------------------------------------------------------- /** * Method description * */ @Override public void handleEOF() { // do nothing } /** * Method description * * * @param date * @param revision * @param author * @param line * * @throws SVNException */ @Override public void handleLine(Date date, long revision, String author, String line) throws SVNException { handleLine(date, revision, author, line, null, -1, null, null, 0); } /** * Method description * * * @param date * @param revision * @param author * @param line * @param mergedDate * @param mergedRevision * @param mergedAuthor * @param mergedPath * @param lineNumber * * @throws SVNException */ @Override public void handleLine(Date date, long revision, String author, String line, Date mergedDate, long mergedRevision, String mergedAuthor, String mergedPath, int lineNumber) throws SVNException { Person authorPerson = null; if (Util.isNotEmpty(author)) { authorPerson = Person.toPerson(author); } Long when = null; if (date != null) { when = date.getTime(); } blameLines.add(new BlameLine(authorPerson, when, String.valueOf(revision), - line, lineNumber)); + line, lineNumber + 1)); } /** * Method description * * * @param date * @param revision * @param author * @param contents * * @return * * @throws SVNException */ @Override public boolean handleRevision(Date date, long revision, String author, File contents) throws SVNException { return false; } //~--- fields --------------------------------------------------------------- /** Field description */ private List<BlameLine> blameLines; }
true
true
public void handleLine(Date date, long revision, String author, String line, Date mergedDate, long mergedRevision, String mergedAuthor, String mergedPath, int lineNumber) throws SVNException { Person authorPerson = null; if (Util.isNotEmpty(author)) { authorPerson = Person.toPerson(author); } Long when = null; if (date != null) { when = date.getTime(); } blameLines.add(new BlameLine(authorPerson, when, String.valueOf(revision), line, lineNumber)); }
public void handleLine(Date date, long revision, String author, String line, Date mergedDate, long mergedRevision, String mergedAuthor, String mergedPath, int lineNumber) throws SVNException { Person authorPerson = null; if (Util.isNotEmpty(author)) { authorPerson = Person.toPerson(author); } Long when = null; if (date != null) { when = date.getTime(); } blameLines.add(new BlameLine(authorPerson, when, String.valueOf(revision), line, lineNumber + 1)); }
diff --git a/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java b/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java index eb53562..398b483 100644 --- a/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java +++ b/PureJava/org.csstudio.swt.xygraph/src/org/csstudio/swt/xygraph/linearscale/TickFactory.java @@ -1,603 +1,603 @@ /* * Copyright 2012 Diamond Light Source Ltd. * * 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.csstudio.swt.xygraph.linearscale; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; /** * Tick factory produces the different axis ticks. When specifying a format and * given the screen size parameters and range it will return a list of Ticks */ public class TickFactory { public enum TickFormatting { /** * Plain mode no rounding no chopping maximum 6 figures before the * fraction point and four after */ plainMode, /** * Rounded or chopped to the nearest decimal */ roundAndChopMode, /** * Use Exponent */ useExponent, /** * Use SI units (k,M,G,etc.) */ useSIunits, /** * Use external scale provider */ useCustom; } private TickFormatting formatOfTicks; private final static BigDecimal EPSILON = new BigDecimal("1.0E-20"); private static final int DIGITS_UPPER_LIMIT = 6; // limit for number of digits to display left of decimal point private static final int DIGITS_LOWER_LIMIT = -6; // limit for number of zeros to display right of decimal point private static final double ROUND_FRACTION = 2e-6; // fraction of denominator to round to private static final BigDecimal BREL_ERROR = new BigDecimal("1e-15"); private static final double REL_ERROR = BREL_ERROR.doubleValue(); private double graphMin; private double graphMax; private String tickFormat; private IScaleProvider scale; private int intervals; // number of intervals private boolean isReversed; /** * @param format */ public TickFactory(IScaleProvider scale) { this(TickFormatting.useCustom, scale); } /** * @param format */ public TickFactory(TickFormatting format, IScaleProvider scale) { formatOfTicks = format; this.scale = scale; } private String getTickString(double value) { if (scale!=null) value = scale.getLabel(value); String returnString = ""; if (Double.isNaN(value)) return returnString; switch (formatOfTicks) { case plainMode: returnString = String.format(tickFormat, value); break; case useExponent: returnString = String.format(tickFormat, value); break; case roundAndChopMode: returnString = String.format("%d", Math.round(value)); break; case useSIunits: double absValue = Math.abs(value); if (absValue == 0.0) { returnString = String.format("%6.2f", value); } else if (absValue <= 1E-15) { returnString = String.format("%6.2ff", value * 1E15); } else if (absValue <= 1E-12) { returnString = String.format("%6.2fp", value * 1E12); } else if (absValue <= 1E-9) { returnString = String.format("%6.2fn", value * 1E9); } else if (absValue <= 1E-6) { returnString = String.format("%6.2fµ", value * 1E6); } else if (absValue <= 1E-3) { returnString = String.format("%6.2fm", value * 1E3); } else if (absValue < 1E3) { returnString = String.format("%6.2f", value); } else if (absValue < 1E6) { returnString = String.format("%6.2fk", value * 1E-3); } else if (absValue < 1E9) { returnString = String.format("%6.2fM", value * 1E-6); } else if (absValue < 1E12) { returnString = String.format("%6.2fG", value * 1E-9); } else if (absValue < 1E15) { returnString = String.format("%6.2fT", value * 1E-12); } else if (absValue < 1E18) returnString = String.format("%6.2fP", value * 1E-15); break; case useCustom: returnString = scale.format(value); break; } return returnString; } private void createFormatString(final int precision, final boolean b) { switch (formatOfTicks) { case plainMode: tickFormat = b ? String.format("%%.%de", precision) : String.format("%%.%df", precision); break; case useExponent: tickFormat = String.format("%%.%de", precision); break; default: tickFormat = null; break; } } /** * Round numerator down to multiples of denominators * @param n numerator * @param d denominator * @return */ protected static double roundDown(BigDecimal n, BigDecimal d) { final int ns = n.signum(); if (ns == 0) return 0; final int ds = d.signum(); if (ds == 0) throw new IllegalArgumentException("Zero denominator is not allowed"); n = n.abs(); d = d.abs(); final BigDecimal[] x = n.divideAndRemainder(d); double rx = x[1].doubleValue(); if (rx > (1-ROUND_FRACTION)*d.doubleValue()) { // trim up if close to denominator x[1] = BigDecimal.ZERO; x[0] = x[0].add(BigDecimal.ONE); } else if (rx < ROUND_FRACTION*d.doubleValue()) { x[1] = BigDecimal.ZERO; } final int xs = x[1].signum(); if (xs == 0) { return ns != ds ? -x[0].multiply(d).doubleValue() : x[0].multiply(d).doubleValue(); } else if (xs < 0) { throw new IllegalStateException("Cannot happen!"); } if (ns != ds) return x[0].signum() == 0 ? -d.doubleValue() : -x[0].add(BigDecimal.ONE).multiply(d).doubleValue(); return x[0].multiply(d).doubleValue(); } /** * Round numerator up to multiples of denominators * @param n numerator * @param d denominator * @return */ protected static double roundUp(BigDecimal n, BigDecimal d) { final int ns = n.signum(); if (ns == 0) return 0; final int ds = d.signum(); if (ds == 0) throw new IllegalArgumentException("Zero denominator is not allowed"); n = n.abs(); d = d.abs(); final BigDecimal[] x = n.divideAndRemainder(d); double rx = x[1].doubleValue(); if (rx != 0) { if (rx < ROUND_FRACTION*d.doubleValue()) { // trim down if close to zero x[1] = BigDecimal.ZERO; } else if (rx > (1-ROUND_FRACTION)*d.doubleValue()) { x[1] = BigDecimal.ZERO; x[0] = x[0].add(BigDecimal.ONE); } } final int xs = x[1].signum(); if (xs == 0) { return ns != ds ? -x[0].multiply(d).doubleValue() : x[0].multiply(d).doubleValue(); } else if (xs < 0) { throw new IllegalStateException("Cannot happen!"); } if (ns != ds) return x[0].signum() == 0 ? 0 : -x[0].multiply(d).doubleValue(); return x[0].add(BigDecimal.ONE).multiply(d).doubleValue(); } /** * @param x * @return floor of log 10 */ private static int log10(BigDecimal x) { int c = x.compareTo(BigDecimal.ONE); int e = 0; while (c < 0) { e--; x = x.scaleByPowerOfTen(1); c = x.compareTo(BigDecimal.ONE); } c = x.compareTo(BigDecimal.TEN); while (c >= 0) { e++; x = x.scaleByPowerOfTen(-1); c = x.compareTo(BigDecimal.TEN); } return e; } /** * @param x * @param round if true, then round else take ceiling * @return a nice number */ protected static BigDecimal nicenum(BigDecimal x, boolean round) { int expv; /* exponent of x */ double f; /* fractional part of x */ double nf; /* nice, rounded number */ BigDecimal bf; expv = log10(x); bf = x.scaleByPowerOfTen(-expv); f = bf.doubleValue(); /* between 1 and 10 */ if (round) { if (f < 1.5) nf = 1; else if (f < 2.25) nf = 2; else if (f < 3.25) nf = 2.5; else if (f < 7.5) nf = 5; else nf = 10; } else if (f <= 1.) nf = 1; else if (f <= 2.) nf = 2; else if (f <= 5.) nf = 5; else nf = 10; return BigDecimal.valueOf(BigDecimal.valueOf(nf).scaleByPowerOfTen(expv).doubleValue()); } private double determineNumTicks(int size, double min, double max, int maxTicks, boolean allowMinMaxOver, boolean isIndexBased) { BigDecimal bMin = BigDecimal.valueOf(min); BigDecimal bMax = BigDecimal.valueOf(max); BigDecimal bRange = bMax.subtract(bMin); if (bRange.signum() < 0) { BigDecimal bt = bMin; bMin = bMax; bMax = bt; bRange = bRange.negate(); isReversed = true; } else { isReversed = false; } BigDecimal magnitude = BigDecimal.valueOf(Math.max(Math.abs(min), Math.abs(max))); // tick points too dense to do anything if (bRange.compareTo(EPSILON.multiply(magnitude)) < 0) { return 0; } bRange = nicenum(bRange, false); BigDecimal bUnit; int nTicks = maxTicks - 1; if (Math.signum(min)*Math.signum(max) < 0) { // straddle case nTicks++; } do { long n; do { // ensure number of ticks is less or equal to number requested bUnit = nicenum(BigDecimal.valueOf(bRange.doubleValue() / nTicks), true); n = bRange.divideToIntegralValue(bUnit).longValue(); } while (n > maxTicks && --nTicks > 0); if (allowMinMaxOver) { graphMin = roundDown(bMin, bUnit); if (graphMin == 0) // ensure positive zero graphMin = 0; graphMax = roundUp(bMax, bUnit); if (graphMax == 0) graphMax = 0; } else { graphMin = min; graphMax = max; } if (bUnit.compareTo(BREL_ERROR.multiply(magnitude)) <= 0) { intervals = -1; // signal that we hit the limit of precision } else { intervals = (int) Math.round((graphMax - graphMin) / bUnit.doubleValue()); } } while (intervals > maxTicks && --nTicks > 0); if (isReversed) { double t = graphMin; graphMin = graphMax; graphMax = t; } double tickUnit = isReversed ? -bUnit.doubleValue() : bUnit.doubleValue(); if (isIndexBased) { switch (formatOfTicks) { case plainMode: tickFormat = "%g"; break; case useExponent: tickFormat = "%e"; break; default: tickFormat = null; break; } } else { /** * We get the labelled max and min for determining the precision * which the ticks should be shown at. */ int d = bUnit.scale() == bUnit.precision() ? -bUnit.scale() : bUnit.precision() - bUnit.scale() - 1; int p = (int) Math.max(Math.floor(Math.log10(Math.abs(graphMin))), Math.floor(Math.log10(Math.abs(graphMax)))); // System.err.println("P: " + bUnit.precision() + ", S: " + // bUnit.scale() + " => " + d + ", " + p); if (p <= DIGITS_LOWER_LIMIT || p >= DIGITS_UPPER_LIMIT) { createFormatString(Math.max(p - d, 0), true); } else { createFormatString(Math.max(-d, 0), false); } } return tickUnit; } private boolean inRange(double x, double min, double max) { if (isReversed) { return x >= max && x <= min; } return x >= min && x <= max; } private static final DecimalFormat INDEX_FORMAT = new DecimalFormat("#####0.###"); /** * Generate a list of ticks that span range given by min and max. The maximum number of * ticks is exceed by one in the case where the range straddles zero. * @param displaySize * @param min * @param max * @param maxTicks * @param allowMinMaxOver allow min/maximum overwrite * @param tight if true then remove ticks outside range * @return a list of the ticks for the axis */ public List<Tick> generateTicks(int displaySize, double min, double max, int maxTicks, boolean allowMinMaxOver, final boolean tight, final boolean isIndexBased) { List<Tick> ticks = new ArrayList<Tick>(); double tickUnit = determineNumTicks(displaySize, min, max, maxTicks, allowMinMaxOver, isIndexBased); if (tickUnit == 0) return ticks; for (int i = 0; i <= intervals; i++) { double p = graphMin + i * tickUnit; if (Math.abs(p/tickUnit) < REL_ERROR) p = 0; // ensure positive zero boolean r = inRange(p, min, max); if (!tight || r) { Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); ticks.add(newTick); } } int imax = ticks.size(); if (imax > 1) { if (!tight && allowMinMaxOver) { Tick t = ticks.get(imax - 1); - if (tickUnit > 0 && t.getValue() < max) { // last is >= max + if (!isReversed && t.getValue() < max) { // last is >= max t.setValue(graphMax); t.setText(getTickString(graphMax)); } } double lo = tight ? min : ticks.get(0).getValue(); double hi = tight ? max : ticks.get(imax - 1).getValue(); double range = hi - lo; - if (tickUnit > 0) { + if (isReversed) { for (Tick t : ticks) { - t.setPosition((t.getValue() - lo) / range); + t.setPosition(1 - (t.getValue() - lo) / range); } } else { for (Tick t : ticks) { - t.setPosition(1 - (t.getValue() - lo) / range); + t.setPosition((t.getValue() - lo) / range); } } } else if (maxTicks > 1) { if (imax == 0) { imax++; Tick newTick = new Tick(); newTick.setValue(graphMin); newTick.setText(getTickString(graphMin)); - if (tickUnit < 0) { + if (isReversed) { newTick.setPosition(1); } else { newTick.setPosition(0); } ticks.add(newTick); } if (imax == 1) { Tick t = ticks.get(0); Tick newTick = new Tick(); if (t.getText().equals(getTickString(graphMax))) { newTick.setValue(graphMin); newTick.setText(getTickString(graphMin)); ticks.add(0, newTick); } else { newTick.setValue(graphMax); newTick.setText(getTickString(graphMax)); ticks.add(newTick); } - if (tickUnit < 0) { + if (isReversed) { ticks.get(0).setPosition(1); ticks.get(1).setPosition(0); } else { ticks.get(0).setPosition(1); ticks.get(1).setPosition(0); } } } if (isIndexBased && formatOfTicks == TickFormatting.plainMode) { double vmin = Double.POSITIVE_INFINITY; double vmax = Double.NEGATIVE_INFINITY; for (Tick t : ticks) { double v = Math.abs(scale.getLabel(t.getValue())); if (v < vmin && v > 0) vmin = v; if (v > vmax) vmax = v; } - if (Math.log10(vmin) < DIGITS_LOWER_LIMIT || Math.log10(vmax) > DIGITS_UPPER_LIMIT) { + if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) { // override labels for (Tick t : ticks) { double v = scale.getLabel(t.getValue()); t.setText(INDEX_FORMAT.format(v)); } } } return ticks; } private double determineNumLogTicks(int size, double min, double max, int maxTicks, boolean allowMinMaxOver) { final boolean isReverse = min > max; final int loDecade; // lowest decade (or power of ten) final int hiDecade; if (isReverse) { loDecade = (int) Math.floor(Math.log10(max)); hiDecade = (int) Math.ceil(Math.log10(min)); } else { loDecade = (int) Math.floor(Math.log10(min)); hiDecade = (int) Math.ceil(Math.log10(max)); } int decades = hiDecade - loDecade; int unit = 0; int n; do { n = decades/++unit; } while (n > maxTicks); double tickUnit = isReverse ? Math.pow(10, -unit) : Math.pow(10, unit); if (allowMinMaxOver) { graphMin = Math.pow(10, loDecade); graphMax = Math.pow(10, hiDecade); } else { graphMin = min; graphMax = max; } if (isReverse) { double t = graphMin; graphMin = graphMax; graphMax = t; } createFormatString((int) Math.max(-Math.floor(loDecade), 0), false); return tickUnit; } /** * @param displaySize * @param min * @param max * @param maxTicks * @param allowMinMaxOver allow min/maximum overwrite * @param tight if true then remove ticks outside range * @return a list of the ticks for the axis */ public List<Tick> generateLogTicks(int displaySize, double min, double max, int maxTicks, boolean allowMinMaxOver, final boolean tight) { List<Tick> ticks = new ArrayList<Tick>(); double tickUnit = determineNumLogTicks(displaySize, min, max, maxTicks, allowMinMaxOver); double p = graphMin; if (tickUnit > 1) { final double pmax = graphMax * Math.sqrt(tickUnit); while (p < pmax) { if (!tight || (p >= min && p <= max)) if (allowMinMaxOver || p <= max) { Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); ticks.add(newTick); } double newTickValue = p * tickUnit; if (p == newTickValue) break; p = newTickValue; } final int imax = ticks.size(); if (imax == 1) { ticks.get(0).setPosition(0.5); } else if (imax > 1) { double lo = Math.log(tight ? min : ticks.get(0).getValue()); double hi = Math.log(tight ? max : ticks.get(imax - 1).getValue()); double range = hi - lo; for (Tick t : ticks) { t.setPosition((Math.log(t.getValue()) - lo) / range); } } } else { final double pmin = graphMax * Math.sqrt(tickUnit); while (p > pmin) { if (!tight || (p >= max && p <= min)) if (allowMinMaxOver || p <= max) { Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); } double newTickValue = p * tickUnit; if (p == newTickValue) break; p = newTickValue; } final int imax = ticks.size(); if (imax == 1) { ticks.get(0).setPosition(0.5); } else if (imax > 1) { double lo = Math.log(tight ? max : ticks.get(0).getValue()); double hi = Math.log(tight ? min : ticks.get(imax - 1).getValue()); double range = hi - lo; for (Tick t : ticks) { t.setPosition(1 - (Math.log(t.getValue()) - lo) / range); } } } return ticks; } }
false
true
public List<Tick> generateTicks(int displaySize, double min, double max, int maxTicks, boolean allowMinMaxOver, final boolean tight, final boolean isIndexBased) { List<Tick> ticks = new ArrayList<Tick>(); double tickUnit = determineNumTicks(displaySize, min, max, maxTicks, allowMinMaxOver, isIndexBased); if (tickUnit == 0) return ticks; for (int i = 0; i <= intervals; i++) { double p = graphMin + i * tickUnit; if (Math.abs(p/tickUnit) < REL_ERROR) p = 0; // ensure positive zero boolean r = inRange(p, min, max); if (!tight || r) { Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); ticks.add(newTick); } } int imax = ticks.size(); if (imax > 1) { if (!tight && allowMinMaxOver) { Tick t = ticks.get(imax - 1); if (tickUnit > 0 && t.getValue() < max) { // last is >= max t.setValue(graphMax); t.setText(getTickString(graphMax)); } } double lo = tight ? min : ticks.get(0).getValue(); double hi = tight ? max : ticks.get(imax - 1).getValue(); double range = hi - lo; if (tickUnit > 0) { for (Tick t : ticks) { t.setPosition((t.getValue() - lo) / range); } } else { for (Tick t : ticks) { t.setPosition(1 - (t.getValue() - lo) / range); } } } else if (maxTicks > 1) { if (imax == 0) { imax++; Tick newTick = new Tick(); newTick.setValue(graphMin); newTick.setText(getTickString(graphMin)); if (tickUnit < 0) { newTick.setPosition(1); } else { newTick.setPosition(0); } ticks.add(newTick); } if (imax == 1) { Tick t = ticks.get(0); Tick newTick = new Tick(); if (t.getText().equals(getTickString(graphMax))) { newTick.setValue(graphMin); newTick.setText(getTickString(graphMin)); ticks.add(0, newTick); } else { newTick.setValue(graphMax); newTick.setText(getTickString(graphMax)); ticks.add(newTick); } if (tickUnit < 0) { ticks.get(0).setPosition(1); ticks.get(1).setPosition(0); } else { ticks.get(0).setPosition(1); ticks.get(1).setPosition(0); } } } if (isIndexBased && formatOfTicks == TickFormatting.plainMode) { double vmin = Double.POSITIVE_INFINITY; double vmax = Double.NEGATIVE_INFINITY; for (Tick t : ticks) { double v = Math.abs(scale.getLabel(t.getValue())); if (v < vmin && v > 0) vmin = v; if (v > vmax) vmax = v; } if (Math.log10(vmin) < DIGITS_LOWER_LIMIT || Math.log10(vmax) > DIGITS_UPPER_LIMIT) { // override labels for (Tick t : ticks) { double v = scale.getLabel(t.getValue()); t.setText(INDEX_FORMAT.format(v)); } } } return ticks; }
public List<Tick> generateTicks(int displaySize, double min, double max, int maxTicks, boolean allowMinMaxOver, final boolean tight, final boolean isIndexBased) { List<Tick> ticks = new ArrayList<Tick>(); double tickUnit = determineNumTicks(displaySize, min, max, maxTicks, allowMinMaxOver, isIndexBased); if (tickUnit == 0) return ticks; for (int i = 0; i <= intervals; i++) { double p = graphMin + i * tickUnit; if (Math.abs(p/tickUnit) < REL_ERROR) p = 0; // ensure positive zero boolean r = inRange(p, min, max); if (!tight || r) { Tick newTick = new Tick(); newTick.setValue(p); newTick.setText(getTickString(p)); ticks.add(newTick); } } int imax = ticks.size(); if (imax > 1) { if (!tight && allowMinMaxOver) { Tick t = ticks.get(imax - 1); if (!isReversed && t.getValue() < max) { // last is >= max t.setValue(graphMax); t.setText(getTickString(graphMax)); } } double lo = tight ? min : ticks.get(0).getValue(); double hi = tight ? max : ticks.get(imax - 1).getValue(); double range = hi - lo; if (isReversed) { for (Tick t : ticks) { t.setPosition(1 - (t.getValue() - lo) / range); } } else { for (Tick t : ticks) { t.setPosition((t.getValue() - lo) / range); } } } else if (maxTicks > 1) { if (imax == 0) { imax++; Tick newTick = new Tick(); newTick.setValue(graphMin); newTick.setText(getTickString(graphMin)); if (isReversed) { newTick.setPosition(1); } else { newTick.setPosition(0); } ticks.add(newTick); } if (imax == 1) { Tick t = ticks.get(0); Tick newTick = new Tick(); if (t.getText().equals(getTickString(graphMax))) { newTick.setValue(graphMin); newTick.setText(getTickString(graphMin)); ticks.add(0, newTick); } else { newTick.setValue(graphMax); newTick.setText(getTickString(graphMax)); ticks.add(newTick); } if (isReversed) { ticks.get(0).setPosition(1); ticks.get(1).setPosition(0); } else { ticks.get(0).setPosition(1); ticks.get(1).setPosition(0); } } } if (isIndexBased && formatOfTicks == TickFormatting.plainMode) { double vmin = Double.POSITIVE_INFINITY; double vmax = Double.NEGATIVE_INFINITY; for (Tick t : ticks) { double v = Math.abs(scale.getLabel(t.getValue())); if (v < vmin && v > 0) vmin = v; if (v > vmax) vmax = v; } if (Math.log10(vmin) >= DIGITS_LOWER_LIMIT || Math.log10(vmax) <= DIGITS_UPPER_LIMIT) { // override labels for (Tick t : ticks) { double v = scale.getLabel(t.getValue()); t.setText(INDEX_FORMAT.format(v)); } } } return ticks; }
diff --git a/tregmine/src/info/tregmine/Tregmine.java b/tregmine/src/info/tregmine/Tregmine.java index 398e9d9..b81b468 100644 --- a/tregmine/src/info/tregmine/Tregmine.java +++ b/tregmine/src/info/tregmine/Tregmine.java @@ -1,312 +1,314 @@ package info.tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.listeners.TregmineBlockListener; import info.tregmine.listeners.TregmineEntityListener; import info.tregmine.listeners.TregminePlayerListener; import info.tregmine.listeners.TregmineWeatherListener; import info.tregmine.stats.BlockStats; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.WorldCreator; import org.bukkit.World.Environment; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.plugin.java.JavaPlugin; import java.util.HashMap; import java.util.Map; /** * @author Ein Andersson - www.tregmine.info * @version 0.8 */ public class Tregmine extends JavaPlugin { public final Logger log = Logger.getLogger("Minecraft"); public final BlockStats blockStats = new BlockStats(this); public Map<String, TregminePlayer> tregminePlayer = new HashMap<String, TregminePlayer>(); public int version = 0; public int amount = 0; @Override public void onEnable() { WorldCreator citadelCreator = new WorldCreator("citadel"); citadelCreator.environment(Environment.NORMAL); citadelCreator.createWorld(); WorldCreator world = new WorldCreator("world"); world.environment(Environment.NORMAL); world.createWorld(); WorldCreator NETHER = new WorldCreator("world_nether"); NETHER.environment(Environment.NETHER); NETHER.createWorld(); getServer().getPluginManager().registerEvents(new info.tregmine.lookup.LookupPlayer(this), this); getServer().getPluginManager().registerEvents(new TregminePlayerListener(this), this); getServer().getPluginManager().registerEvents(new TregmineBlockListener(this), this); getServer().getPluginManager().registerEvents(new TregmineEntityListener(this), this); getServer().getPluginManager().registerEvents(new TregmineWeatherListener(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.invis.InvisPlayer(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.death.DeathEntity(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.death.DeathPlayer(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.chat.Chat(this), this); getServer().getPluginManager().registerEvents(new info.tregmine.sign.Color(), this); } @Override public void onDisable() { //run when plugin is disabled this.getServer().getScheduler().cancelTasks(this); Player[] players = this.getServer().getOnlinePlayers(); for (Player player : players) { player.sendMessage(ChatColor.AQUA + "Tregmine successfully unloaded build: " + this.getDescription().getVersion() ); } } @Override public void onLoad() { Player[] players = this.getServer().getOnlinePlayers(); this.getServer().getWorld("world_the_end").setPVP(true); for (Player player : players) { String onlineName = player.getName(); TregminePlayer tregPlayer = new TregminePlayer(player, onlineName); tregPlayer.load(); this.tregminePlayer.put(onlineName, tregPlayer); player.sendMessage(ChatColor.GRAY + "Tregmine successfully loaded to build: " + this.getDescription().getVersion() ); player.sendMessage(ChatColor.GRAY + "Version explanation: X.Y.Z.G"); player.sendMessage(ChatColor.GRAY + "X new stuff added, When i make a brand new thing"); player.sendMessage(ChatColor.GRAY + "Y new function added, when i extend what current stuff can do"); player.sendMessage(ChatColor.GRAY + "Z bugfix that may change how function and stuff works"); player.sendMessage(ChatColor.GRAY + "G small bugfix like spelling errors"); } } public TregminePlayer getPlayer(String name) { return tregminePlayer.get(name); } public TregminePlayer getPlayer(Player player) { return tregminePlayer.get(player.getName()); } public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); Player from = null; TregminePlayer player = null; if(!(sender instanceof Player)) { if(commandName.equals("say")) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); this.getServer().broadcastMessage("<" + ChatColor.BLUE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); this.log.info("CONSOLE: <GOD> " + buffMsg); return true; } return false; } else { from = (Player) sender; player = this.getPlayer(from); } if("invis".matches(commandName) && player.isOp()) { if ("off".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { - p.canSee(player); + p.showPlayer(player); } + player.sendMessage(ChatColor.YELLOW + "You can now be seen!"); } else if ("on".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { if (!p.isOp()) { p.hidePlayer(player); } else { - p.canSee(player); + p.showPlayer(player); } + player.sendMessage(ChatColor.YELLOW + "*poof* no one knows where you are!"); } } else { player.sendMessage("Try /invis [on|off]"); } } if(commandName.equals("text") && player.isAdmin()) { Player[] players = this.getServer().getOnlinePlayers(); // player.setTexturePack(args[0]); for (Player p : players) { p.setTexturePack(args[0]); } } if(commandName.equals("head") && player.isAdmin()) { ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); SkullMeta meta = (SkullMeta) item.getItemMeta(); meta.setOwner(args[0]); meta.setDisplayName(ChatColor.YELLOW + "Head of " + args[0]); item.setItemMeta(meta); PlayerInventory inv = player.getInventory(); inv.addItem(item); player.updateInventory(); player.sendMessage("Skull of " + args[0]); } if(commandName.equals("say") && player.isAdmin()) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if(from.getName().matches("BlackX")) { this.getServer().broadcastMessage("<" + ChatColor.BLACK + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("mejjad")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("einand")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("LilKiw")){ this.getServer().broadcastMessage("<" + ChatColor.AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Camrenn")){ this.getServer().broadcastMessage("<" + ChatColor.LIGHT_PURPLE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Mksen")){ this.getServer().broadcastMessage("<" + ChatColor.YELLOW + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("josh121297")){ this.getServer().broadcastMessage("<" + ChatColor.GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("rweiand")){ this.getServer().broadcastMessage("<" + ChatColor.GOLD + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else { this.getServer().broadcastMessage("<" + ChatColor.RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } this.log.info(from.getName() + ": <GOD> " + buffMsg); Player[] players = this.getServer().getOnlinePlayers(); for (Player p : players) { info.tregmine.api.TregminePlayer locTregminePlayer = this.getPlayer((p.getName())); if (locTregminePlayer.isAdmin()) { p.sendMessage(ChatColor.DARK_AQUA + "/say used by: " + player.getChatName()); } } return true; } if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){ info.tregmine.commands.Who.run(this, player, args); return true; } if(commandName.equals("tp")){ info.tregmine.commands.Tp.run(this, player, args); return true; } if(commandName.equals("channel")){ if (args.length != 1) { return false; } from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + "."); from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." ); player.setChatChannel(args[0]); return true; } if(commandName.equals("force") && args.length == 2 ){ player.setChatChannel(args[1]); Player to = getServer().matchPlayer(args[0]).get(0); info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); toPlayer.setChatChannel(args[1]); to.sendMessage(ChatColor.YELLOW + player.getChatName() + " forced you into channel " + args[1].toUpperCase() + "."); to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." ); from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + "."); this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase()); return true; } if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) { Player to = getServer().getPlayer(args[0]); if (to != null) { info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); StringBuffer buf = new StringBuffer(); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if (!toPlayer.getMetaBoolean("invis")) { from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg); } to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg); log.info(from.getName() + " => " + to.getName() + buffMsg); return true; } } if(commandName.equals("me") && args.length > 0 ){ StringBuffer buf = new StringBuffer(); Player[] players = getServer().getOnlinePlayers(); for (int i = 0; i < args.length; ++i) { buf.append(" " + args[i]); } for (Player tp : players) { TregminePlayer to = this.getPlayer(tp); if (player.getChatChannel().equals(to.getChatChannel())) { to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() ); } } return true; } return false; } }
false
true
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); Player from = null; TregminePlayer player = null; if(!(sender instanceof Player)) { if(commandName.equals("say")) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); this.getServer().broadcastMessage("<" + ChatColor.BLUE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); this.log.info("CONSOLE: <GOD> " + buffMsg); return true; } return false; } else { from = (Player) sender; player = this.getPlayer(from); } if("invis".matches(commandName) && player.isOp()) { if ("off".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { p.canSee(player); } } else if ("on".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { if (!p.isOp()) { p.hidePlayer(player); } else { p.canSee(player); } } } else { player.sendMessage("Try /invis [on|off]"); } } if(commandName.equals("text") && player.isAdmin()) { Player[] players = this.getServer().getOnlinePlayers(); // player.setTexturePack(args[0]); for (Player p : players) { p.setTexturePack(args[0]); } } if(commandName.equals("head") && player.isAdmin()) { ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); SkullMeta meta = (SkullMeta) item.getItemMeta(); meta.setOwner(args[0]); meta.setDisplayName(ChatColor.YELLOW + "Head of " + args[0]); item.setItemMeta(meta); PlayerInventory inv = player.getInventory(); inv.addItem(item); player.updateInventory(); player.sendMessage("Skull of " + args[0]); } if(commandName.equals("say") && player.isAdmin()) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if(from.getName().matches("BlackX")) { this.getServer().broadcastMessage("<" + ChatColor.BLACK + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("mejjad")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("einand")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("LilKiw")){ this.getServer().broadcastMessage("<" + ChatColor.AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Camrenn")){ this.getServer().broadcastMessage("<" + ChatColor.LIGHT_PURPLE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Mksen")){ this.getServer().broadcastMessage("<" + ChatColor.YELLOW + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("josh121297")){ this.getServer().broadcastMessage("<" + ChatColor.GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("rweiand")){ this.getServer().broadcastMessage("<" + ChatColor.GOLD + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else { this.getServer().broadcastMessage("<" + ChatColor.RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } this.log.info(from.getName() + ": <GOD> " + buffMsg); Player[] players = this.getServer().getOnlinePlayers(); for (Player p : players) { info.tregmine.api.TregminePlayer locTregminePlayer = this.getPlayer((p.getName())); if (locTregminePlayer.isAdmin()) { p.sendMessage(ChatColor.DARK_AQUA + "/say used by: " + player.getChatName()); } } return true; } if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){ info.tregmine.commands.Who.run(this, player, args); return true; } if(commandName.equals("tp")){ info.tregmine.commands.Tp.run(this, player, args); return true; } if(commandName.equals("channel")){ if (args.length != 1) { return false; } from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + "."); from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." ); player.setChatChannel(args[0]); return true; } if(commandName.equals("force") && args.length == 2 ){ player.setChatChannel(args[1]); Player to = getServer().matchPlayer(args[0]).get(0); info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); toPlayer.setChatChannel(args[1]); to.sendMessage(ChatColor.YELLOW + player.getChatName() + " forced you into channel " + args[1].toUpperCase() + "."); to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." ); from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + "."); this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase()); return true; } if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) { Player to = getServer().getPlayer(args[0]); if (to != null) { info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); StringBuffer buf = new StringBuffer(); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if (!toPlayer.getMetaBoolean("invis")) { from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg); } to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg); log.info(from.getName() + " => " + to.getName() + buffMsg); return true; } } if(commandName.equals("me") && args.length > 0 ){ StringBuffer buf = new StringBuffer(); Player[] players = getServer().getOnlinePlayers(); for (int i = 0; i < args.length; ++i) { buf.append(" " + args[i]); } for (Player tp : players) { TregminePlayer to = this.getPlayer(tp); if (player.getChatChannel().equals(to.getChatChannel())) { to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() ); } } return true; } return false; }
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { String commandName = command.getName().toLowerCase(); Player from = null; TregminePlayer player = null; if(!(sender instanceof Player)) { if(commandName.equals("say")) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); this.getServer().broadcastMessage("<" + ChatColor.BLUE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); this.log.info("CONSOLE: <GOD> " + buffMsg); return true; } return false; } else { from = (Player) sender; player = this.getPlayer(from); } if("invis".matches(commandName) && player.isOp()) { if ("off".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { p.showPlayer(player); } player.sendMessage(ChatColor.YELLOW + "You can now be seen!"); } else if ("on".matches(args[0])) { for (Player p : this.getServer().getOnlinePlayers()) { if (!p.isOp()) { p.hidePlayer(player); } else { p.showPlayer(player); } player.sendMessage(ChatColor.YELLOW + "*poof* no one knows where you are!"); } } else { player.sendMessage("Try /invis [on|off]"); } } if(commandName.equals("text") && player.isAdmin()) { Player[] players = this.getServer().getOnlinePlayers(); // player.setTexturePack(args[0]); for (Player p : players) { p.setTexturePack(args[0]); } } if(commandName.equals("head") && player.isAdmin()) { ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3); SkullMeta meta = (SkullMeta) item.getItemMeta(); meta.setOwner(args[0]); meta.setDisplayName(ChatColor.YELLOW + "Head of " + args[0]); item.setItemMeta(meta); PlayerInventory inv = player.getInventory(); inv.addItem(item); player.updateInventory(); player.sendMessage("Skull of " + args[0]); } if(commandName.equals("say") && player.isAdmin()) { StringBuffer buf = new StringBuffer(); buf.append(args[0]); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if(from.getName().matches("BlackX")) { this.getServer().broadcastMessage("<" + ChatColor.BLACK + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("mejjad")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("einand")){ this.getServer().broadcastMessage("<" + ChatColor.DARK_GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("LilKiw")){ this.getServer().broadcastMessage("<" + ChatColor.AQUA + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Camrenn")){ this.getServer().broadcastMessage("<" + ChatColor.LIGHT_PURPLE + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("Mksen")){ this.getServer().broadcastMessage("<" + ChatColor.YELLOW + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("josh121297")){ this.getServer().broadcastMessage("<" + ChatColor.GREEN + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else if (from.getName().matches("rweiand")){ this.getServer().broadcastMessage("<" + ChatColor.GOLD + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } else { this.getServer().broadcastMessage("<" + ChatColor.RED + "GOD" + ChatColor.WHITE + "> " + ChatColor.LIGHT_PURPLE + buffMsg); } this.log.info(from.getName() + ": <GOD> " + buffMsg); Player[] players = this.getServer().getOnlinePlayers(); for (Player p : players) { info.tregmine.api.TregminePlayer locTregminePlayer = this.getPlayer((p.getName())); if (locTregminePlayer.isAdmin()) { p.sendMessage(ChatColor.DARK_AQUA + "/say used by: " + player.getChatName()); } } return true; } if(commandName.equals("who") || commandName.equals("playerlist") || commandName.equals("list")){ info.tregmine.commands.Who.run(this, player, args); return true; } if(commandName.equals("tp")){ info.tregmine.commands.Tp.run(this, player, args); return true; } if(commandName.equals("channel")){ if (args.length != 1) { return false; } from.sendMessage(ChatColor.YELLOW + "You are now talking in channel " + args[0] + "."); from.sendMessage(ChatColor.YELLOW + "Write /channel global to switch to the global chat." ); player.setChatChannel(args[0]); return true; } if(commandName.equals("force") && args.length == 2 ){ player.setChatChannel(args[1]); Player to = getServer().matchPlayer(args[0]).get(0); info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); toPlayer.setChatChannel(args[1]); to.sendMessage(ChatColor.YELLOW + player.getChatName() + " forced you into channel " + args[1].toUpperCase() + "."); to.sendMessage(ChatColor.YELLOW + "Write /channel global to switch back to the global chat." ); from.sendMessage(ChatColor.YELLOW + "You are now in a forced chat " + args[1].toUpperCase()+ " with " + to.getDisplayName() + "."); this.log.info(from.getName() + " FORCED CHAT WITH " + to.getDisplayName() + " IN CHANNEL " + args[1].toUpperCase()); return true; } if(commandName.equals("msg") || commandName.equals("m") || commandName.equals("tell")) { Player to = getServer().getPlayer(args[0]); if (to != null) { info.tregmine.api.TregminePlayer toPlayer = this.tregminePlayer.get(to.getName()); StringBuffer buf = new StringBuffer(); for (int i = 1; i < args.length; ++i) { buf.append(" " + args[i]); } String buffMsg = buf.toString(); if (!toPlayer.getMetaBoolean("invis")) { from.sendMessage(ChatColor.GREEN + "(to) " + toPlayer.getChatName() + ChatColor.GREEN + ": " + buffMsg); } to.sendMessage(ChatColor.GREEN + "(msg) " + player.getChatName() + ChatColor.GREEN + ": " + buffMsg); log.info(from.getName() + " => " + to.getName() + buffMsg); return true; } } if(commandName.equals("me") && args.length > 0 ){ StringBuffer buf = new StringBuffer(); Player[] players = getServer().getOnlinePlayers(); for (int i = 0; i < args.length; ++i) { buf.append(" " + args[i]); } for (Player tp : players) { TregminePlayer to = this.getPlayer(tp); if (player.getChatChannel().equals(to.getChatChannel())) { to.sendMessage("* " + player.getChatName() + ChatColor.WHITE + buf.toString() ); } } return true; } return false; }
diff --git a/com.github.fhd.eclipsecolortheme/src/com/github/fhd/eclipsecolortheme/ColorThemeCollection.java b/com.github.fhd.eclipsecolortheme/src/com/github/fhd/eclipsecolortheme/ColorThemeCollection.java index 1bc3826..331fdf9 100644 --- a/com.github.fhd.eclipsecolortheme/src/com/github/fhd/eclipsecolortheme/ColorThemeCollection.java +++ b/com.github.fhd.eclipsecolortheme/src/com/github/fhd/eclipsecolortheme/ColorThemeCollection.java @@ -1,114 +1,114 @@ package com.github.fhd.eclipsecolortheme; import java.util.*; /** * A collection of color themes. * TODO: The keys are Java specific right now. Generalise them. * XXX: One class per theme would be more flexible. */ public class ColorThemeCollection { private Map<String, Map<String, String>> themes; /** Creates a new color theme collection. */ public ColorThemeCollection() { themes = new HashMap<String, Map<String, String>>(); themes.put("Inkpot", createInkpotTheme()); themes.put("Zenburn", createZenburnTheme()); } private static Map<String, String> createInkpotTheme() { Map<String, String> theme = new HashMap<String, String>(); theme.put("foreground", color(207, 191, 173)); theme.put("background", color(31, 31, 39)); theme.put("selectionForeground", color(64, 64, 64)); theme.put("selectionBackground", color(139, 139, 255)); theme.put("currentLine", color(45, 45, 68)); theme.put("lineNumber", color(43, 145, 175)); theme.put("contentAssistProposalsForeground", color(0, 0, 0)); theme.put("contentAssistProposalsBackground", color(255, 255, 255)); theme.put("singleLineComment", color(205, 139, 0)); theme.put("multiLineComment", color(205, 139, 0)); theme.put("commentTaskTag", color(255, 139, 255)); theme.put("sourceHoverBackground", color(255, 255, 255));; theme.put("number", color(255, 205, 139)); theme.put("string", color(255, 205, 139)); theme.put("bracket", color(207, 191, 173)); theme.put("operator", color(207, 191, 173)); theme.put("keyword", color(128, 139, 237)); theme.put("class", color(135, 206, 250)); theme.put("interface", color(135, 250, 196)); theme.put("method", color(135, 206, 250)); theme.put("methodDeclarationName", color(207, 191, 173)); return theme; } private static Map<String, String> createZenburnTheme() { Map<String, String> theme = new HashMap<String, String>(); theme.put("foreground", color(246, 243, 232)); theme.put("background", color(64, 64, 64)); theme.put("selectionForeground", color(0, 0, 0)); theme.put("selectionBackground", color(137, 137, 65)); theme.put("currentLine", color(80, 80, 80)); theme.put("lineNumber", color(192, 192, 192)); theme.put("filteredSearchResultIndication", color(63, 63, 106)); theme.put("occurrenceIndication", color(97, 97, 97)); theme.put("findScope", color(188, 173, 173)); theme.put("secondaryIP", color(26, 89, 26)); theme.put("writeOccurrenceIndication", color(148, 133, 103)); theme.put("currentIP", color(26, 89, 26)); theme.put("searchResultIndication", color(70, 68, 103)); theme.put("contentAssistProposalsForeground", color(0, 0, 0)); theme.put("contentAssistProposalsBackground", color(255, 255, 255)); theme.put("commentTaskTag", color(172, 193, 172)); theme.put("javadoc", color(179, 181, 175)); theme.put("javadocLink", color(168, 147, 204)); theme.put("javadocSingleLineComment", color(127, 159, 127)); theme.put("localVariable", color(212, 196, 169)); theme.put("staticFinalField", color(83, 220, 205)); theme.put("bracket", color(255, 255, 255)); theme.put("field", color(179, 183, 132)); theme.put("staticMethodInvocation", color(196, 196, 183)); theme.put("contentAssistParametersForeground", color(246, 243, 232)); theme.put("contentAssistParametersBackground", color(36, 36, 36)); - theme.put("number", color(138, 04, 07)); - theme.put("sourceHoverBackground", color(161, 52, 21)); - theme.put("deprecatedMember", color(255, 55, 55)); - theme.put("class", color(202, 30, 30)); - theme.put("operator", color(240, 39, 208)); - theme.put("method", color(223, 90, 49)); - theme.put("methodDeclarationName", color(223, 90, 49)); - theme.put("autoboxing", color(255, 87, 87)); - theme.put("keyword", color(239, 39, 75)); - theme.put("string", color(204, 47, 47)); - theme.put("localVariableDeclaration", color(212, 96, 69)); - theme.put("javadocKeyword", color(204, 47, 47)); - theme.put("annotation", color(128, 28, 28)); - theme.put("staticField", color(147, 62, 04)); - theme.put("multiLineComment", color(127, 59, 27)); - theme.put("javadocTag", color(147, 47, 04)); + theme.put("number", color(138, 204, 207)); + theme.put("sourceHoverBackground", color(161, 152, 121)); + theme.put("deprecatedMember", color(255, 255, 255)); + theme.put("class", color(202, 230, 130)); + theme.put("operator", color(240, 239, 208)); + theme.put("method", color(223, 190, 149)); + theme.put("methodDeclarationName", color(223, 190, 149)); + theme.put("autoboxing", color(255, 187, 187)); + theme.put("keyword", color(239, 239, 175)); + theme.put("string", color(204, 147, 147)); + theme.put("localVariableDeclaration", color(212, 196, 169)); + theme.put("javadocKeyword", color(204, 147, 147)); + theme.put("annotation", color(128, 128, 128)); + theme.put("staticField", color(147, 162, 204)); + theme.put("multiLineComment", color(127, 159, 127)); + theme.put("javadocTag", color(147, 147, 204)); return theme; } private static String color(int r, int g, int b) { return r + "," + g + "," + b; } /** * Returns the names of all available color themes. * @return the names of all available color themes. */ public Set<String> getThemeNames() { return themes.keySet(); } /** * Returns the theme stored under @a name. * @param name The theme to return. * @return The requested theme or <code>null</code> if none with that name * exists. */ public Map<String, String> getTheme(String name) { return themes.get(name); } }
true
true
private static Map<String, String> createZenburnTheme() { Map<String, String> theme = new HashMap<String, String>(); theme.put("foreground", color(246, 243, 232)); theme.put("background", color(64, 64, 64)); theme.put("selectionForeground", color(0, 0, 0)); theme.put("selectionBackground", color(137, 137, 65)); theme.put("currentLine", color(80, 80, 80)); theme.put("lineNumber", color(192, 192, 192)); theme.put("filteredSearchResultIndication", color(63, 63, 106)); theme.put("occurrenceIndication", color(97, 97, 97)); theme.put("findScope", color(188, 173, 173)); theme.put("secondaryIP", color(26, 89, 26)); theme.put("writeOccurrenceIndication", color(148, 133, 103)); theme.put("currentIP", color(26, 89, 26)); theme.put("searchResultIndication", color(70, 68, 103)); theme.put("contentAssistProposalsForeground", color(0, 0, 0)); theme.put("contentAssistProposalsBackground", color(255, 255, 255)); theme.put("commentTaskTag", color(172, 193, 172)); theme.put("javadoc", color(179, 181, 175)); theme.put("javadocLink", color(168, 147, 204)); theme.put("javadocSingleLineComment", color(127, 159, 127)); theme.put("localVariable", color(212, 196, 169)); theme.put("staticFinalField", color(83, 220, 205)); theme.put("bracket", color(255, 255, 255)); theme.put("field", color(179, 183, 132)); theme.put("staticMethodInvocation", color(196, 196, 183)); theme.put("contentAssistParametersForeground", color(246, 243, 232)); theme.put("contentAssistParametersBackground", color(36, 36, 36)); theme.put("number", color(138, 04, 07)); theme.put("sourceHoverBackground", color(161, 52, 21)); theme.put("deprecatedMember", color(255, 55, 55)); theme.put("class", color(202, 30, 30)); theme.put("operator", color(240, 39, 208)); theme.put("method", color(223, 90, 49)); theme.put("methodDeclarationName", color(223, 90, 49)); theme.put("autoboxing", color(255, 87, 87)); theme.put("keyword", color(239, 39, 75)); theme.put("string", color(204, 47, 47)); theme.put("localVariableDeclaration", color(212, 96, 69)); theme.put("javadocKeyword", color(204, 47, 47)); theme.put("annotation", color(128, 28, 28)); theme.put("staticField", color(147, 62, 04)); theme.put("multiLineComment", color(127, 59, 27)); theme.put("javadocTag", color(147, 47, 04)); return theme; }
private static Map<String, String> createZenburnTheme() { Map<String, String> theme = new HashMap<String, String>(); theme.put("foreground", color(246, 243, 232)); theme.put("background", color(64, 64, 64)); theme.put("selectionForeground", color(0, 0, 0)); theme.put("selectionBackground", color(137, 137, 65)); theme.put("currentLine", color(80, 80, 80)); theme.put("lineNumber", color(192, 192, 192)); theme.put("filteredSearchResultIndication", color(63, 63, 106)); theme.put("occurrenceIndication", color(97, 97, 97)); theme.put("findScope", color(188, 173, 173)); theme.put("secondaryIP", color(26, 89, 26)); theme.put("writeOccurrenceIndication", color(148, 133, 103)); theme.put("currentIP", color(26, 89, 26)); theme.put("searchResultIndication", color(70, 68, 103)); theme.put("contentAssistProposalsForeground", color(0, 0, 0)); theme.put("contentAssistProposalsBackground", color(255, 255, 255)); theme.put("commentTaskTag", color(172, 193, 172)); theme.put("javadoc", color(179, 181, 175)); theme.put("javadocLink", color(168, 147, 204)); theme.put("javadocSingleLineComment", color(127, 159, 127)); theme.put("localVariable", color(212, 196, 169)); theme.put("staticFinalField", color(83, 220, 205)); theme.put("bracket", color(255, 255, 255)); theme.put("field", color(179, 183, 132)); theme.put("staticMethodInvocation", color(196, 196, 183)); theme.put("contentAssistParametersForeground", color(246, 243, 232)); theme.put("contentAssistParametersBackground", color(36, 36, 36)); theme.put("number", color(138, 204, 207)); theme.put("sourceHoverBackground", color(161, 152, 121)); theme.put("deprecatedMember", color(255, 255, 255)); theme.put("class", color(202, 230, 130)); theme.put("operator", color(240, 239, 208)); theme.put("method", color(223, 190, 149)); theme.put("methodDeclarationName", color(223, 190, 149)); theme.put("autoboxing", color(255, 187, 187)); theme.put("keyword", color(239, 239, 175)); theme.put("string", color(204, 147, 147)); theme.put("localVariableDeclaration", color(212, 196, 169)); theme.put("javadocKeyword", color(204, 147, 147)); theme.put("annotation", color(128, 128, 128)); theme.put("staticField", color(147, 162, 204)); theme.put("multiLineComment", color(127, 159, 127)); theme.put("javadocTag", color(147, 147, 204)); return theme; }
diff --git a/src/com/fixedd/AndroidTrimet/schemas/Arrivals/ResultSet.java b/src/com/fixedd/AndroidTrimet/schemas/Arrivals/ResultSet.java index 86e3738..9387c4c 100644 --- a/src/com/fixedd/AndroidTrimet/schemas/Arrivals/ResultSet.java +++ b/src/com/fixedd/AndroidTrimet/schemas/Arrivals/ResultSet.java @@ -1,210 +1,210 @@ package com.fixedd.AndroidTrimet.schemas.Arrivals; import java.util.ArrayList; import java.util.List; import android.os.Parcel; import android.os.Parcelable; /** * <p> * This class holds information on a returned result set. This is basically * the wrapper for all of the other information returned by an Arrivals or Nearby * API call. */ public class ResultSet implements Parcelable { protected String mErrorMessage; protected List<LocationType > mLocation; protected List<ArrivalType > mArrival; protected List<RouteStatusType> mRouteStatus; protected Long mQueryTime = -9223372036854775808l; public ResultSet() {} /** * Gets all of the Arrivals which belong to a certain Location. * @param locationId The location id you want arrivals for. This is usually a stop id. * @return all of the arrivals for a location. */ public List<ArrivalType> getArrivalsForLocation(int locationId) { ArrayList<ArrivalType> toReturn = new ArrayList<ArrivalType>(); int len = mArrival.size(); for (int i=0; i<len; i++) { ArrivalType arr = mArrival.get(i); if (arr.mLocid == locationId) toReturn.add(arr); } return toReturn; } /** * Gets an error message. * @return A {@link String} containing an error message or null if there wasn't an error. * */ public String getErrorMessage() { return mErrorMessage; } /** * Sets the error message. * @param The {@link String} that contains the error message. * */ public void setErrorMessage(String message) { mErrorMessage = message; } /** * Gets the locations for the ResultSet. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned * list will be present inside the locations list. This is why there * is not a <CODE>set</CODE> method for the location property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLocations().add(newItem); * </pre> * @return List<LocationType> All of the locations. */ public List<LocationType> getLocations() { if (mLocation == null) { mLocation = new ArrayList<LocationType>(); } return mLocation; } /** * Gets the arrivals for the ResultSet. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list * will be present inside the arrival list. This is why there is not * a <CODE>set</CODE> method for the arrival property. * * <p> * For example, to add a new item, do as follows: * <pre> * getArrivals().add(newItem); * </pre> * @return List<ArrivalType> All of the arrivals. */ public List<ArrivalType> getArrivals() { if (mArrival == null) { mArrival = new ArrayList<ArrivalType>(); } return mArrival; } /** * Gets the routeStatuses for the ResultSet. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list * will be present inside the RouteStatus list. This is why there is not * a <CODE>set</CODE> method for the routeStatus property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRouteStatuses().add(newItem); * </pre> * @return List<RouteStatusType> All of the route statuses. * */ public List<RouteStatusType> getRouteStatuses() { if (mRouteStatus == null) { mRouteStatus = new ArrayList<RouteStatusType>(); } return mRouteStatus; } /** * Gets the time that the query was made (according to Trimet's servers). * @return the time that the query was made in milliseconds since epoch or -9223372036854775808 if the time wasn't set correctly. */ public long getQueryTime() { return mQueryTime; } /** * Sets the time the query was made. * @param time The milliseconds since epoch that the query was made. */ public void setQueryTime(long time) { mQueryTime = time; } // ********************************************** // for implementing Parcelable // ********************************************** @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { if (mErrorMessage == null) dest.writeInt(0); else { dest.writeInt(1); dest.writeString(mErrorMessage); } - if (mLocation == null && mLocation.size() > 0) + if (mLocation == null || mLocation.size() > 0) dest.writeInt(0); else { dest.writeInt(1); dest.writeTypedList(mLocation); } - if (mArrival == null && mArrival.size() > 0) + if (mArrival == null || mArrival.size() > 0) dest.writeInt(0); else { dest.writeInt(1); dest.writeTypedList(mArrival); } - if (mRouteStatus == null && mRouteStatus.size() > 0) + if (mRouteStatus == null || mRouteStatus.size() > 0) dest.writeInt(0); else { dest.writeInt(1); dest.writeTypedList(mRouteStatus ); } dest.writeLong(mQueryTime); } public static final Parcelable.Creator<ResultSet> CREATOR = new Parcelable.Creator<ResultSet>() { public ResultSet createFromParcel(Parcel in) { return new ResultSet(in); } public ResultSet[] newArray(int size) { return new ResultSet[size]; } }; private ResultSet(Parcel dest) { if (dest.readInt() == 1) mErrorMessage = dest.readString(); if (dest.readInt() == 1) dest.readTypedList(mLocation , LocationType .CREATOR); if (dest.readInt() == 1) dest.readTypedList(mArrival , ArrivalType .CREATOR); if (dest.readInt() == 1) dest.readTypedList(mRouteStatus, RouteStatusType.CREATOR); mQueryTime = dest.readLong(); } }
false
true
public void writeToParcel(Parcel dest, int flags) { if (mErrorMessage == null) dest.writeInt(0); else { dest.writeInt(1); dest.writeString(mErrorMessage); } if (mLocation == null && mLocation.size() > 0) dest.writeInt(0); else { dest.writeInt(1); dest.writeTypedList(mLocation); } if (mArrival == null && mArrival.size() > 0) dest.writeInt(0); else { dest.writeInt(1); dest.writeTypedList(mArrival); } if (mRouteStatus == null && mRouteStatus.size() > 0) dest.writeInt(0); else { dest.writeInt(1); dest.writeTypedList(mRouteStatus ); } dest.writeLong(mQueryTime); }
public void writeToParcel(Parcel dest, int flags) { if (mErrorMessage == null) dest.writeInt(0); else { dest.writeInt(1); dest.writeString(mErrorMessage); } if (mLocation == null || mLocation.size() > 0) dest.writeInt(0); else { dest.writeInt(1); dest.writeTypedList(mLocation); } if (mArrival == null || mArrival.size() > 0) dest.writeInt(0); else { dest.writeInt(1); dest.writeTypedList(mArrival); } if (mRouteStatus == null || mRouteStatus.size() > 0) dest.writeInt(0); else { dest.writeInt(1); dest.writeTypedList(mRouteStatus ); } dest.writeLong(mQueryTime); }
diff --git a/x10.compiler/src/x10cuda/types/X10CUDAContext_c.java b/x10.compiler/src/x10cuda/types/X10CUDAContext_c.java index 9d6b91f7c..accf23b08 100644 --- a/x10.compiler/src/x10cuda/types/X10CUDAContext_c.java +++ b/x10.compiler/src/x10cuda/types/X10CUDAContext_c.java @@ -1,129 +1,129 @@ /* * 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 x10cuda.types; /** * This class extends the X10 notion of Context to keep track of * the translation state for the C++ backend. * * @author Dave Cunningham */ import java.util.ArrayList; import polyglot.ast.Expr; import polyglot.ast.Formal; import polyglot.ast.LocalDecl; import polyglot.frontend.Job; import x10.ast.Closure_c; import x10cpp.X10CPPCompilerOptions; import x10cpp.types.X10CPPContext_c; import polyglot.types.Name; import polyglot.types.TypeSystem; import polyglot.types.VarInstance; import x10.util.ClassifiedStream; import x10.util.StreamWrapper; public class X10CUDAContext_c extends X10CPPContext_c { public X10CUDAContext_c(TypeSystem ts) { super(ts); } private String wrappingClosure; public String wrappingClosure() { return wrappingClosure; } public void wrappingClosure(String v) { wrappingClosure = v; } private String wrappingClass; public String wrappingClass() { return wrappingClass; } public void wrappingClass(String v) { wrappingClass = v; } private boolean generatingKernel; public boolean generatingKernel() { return generatingKernel; } public void generatingKernel(boolean v) { generatingKernel = v; } private Expr blocks; public Expr blocks() { return blocks; } private Expr threads; public Expr threads() { return threads; } private Name blocksVar; public Name blocksVar() { return blocksVar; } private Name threadsVar; public Name threadsVar() { return threadsVar; } private SharedMem shm; public SharedMem shm() { return shm; } private SharedMem cmem; public SharedMem cmem() { return cmem; } private boolean directParams; public boolean directParams() { return directParams; } private ArrayList<VarInstance<?>> kernelParams; public ArrayList<VarInstance<?>> kernelParams() { return kernelParams; } public void setCUDAKernelCFG(Expr blocks, Name blocksVar, Expr threads, Name threadsVar, SharedMem shm, SharedMem cmem, boolean directParams) { this.blocks = blocks; this.blocksVar = blocksVar; this.threads = threads; this.threadsVar = threadsVar; this.shm = shm; this.cmem = cmem; this.kernelParams = variables(); this.directParams = directParams; if (autoBlocks!=null) this.kernelParams.add(autoBlocks.localDef().asInstance()); if (autoThreads!=null) this.kernelParams.add(autoThreads.localDef().asInstance()); } public boolean isKernelParam(Name n) { for (VarInstance<?> i : kernelParams) { if (i.name()==n) return true; } return false; } private ClassifiedStream cudaStream = null; public ClassifiedStream cudaStream (StreamWrapper sw, Job j) { if (firstKernel()) { ClassifiedStream cudaStream = sw.getNewStream("cu" ); firstKernel(false); j.compiler().outputFiles().add(wrappingClass()+".cu"); ((X10CPPCompilerOptions)j.extensionInfo().getOptions()).compilationUnits().add(wrappingClass()+".cu"); cudaStream.write("#include <x10aux/config.h>"); cudaStream.newline(); cudaStream.write("#include <x10aux/cuda_kernel.cuh>"); cudaStream.newline(); cudaStream.forceNewline(); - cudaStream.write("extern __shared__ char __shm[];"); cudaStream.newline(); + cudaStream.write("extern __shared__ int __shm[];"); cudaStream.newline(); cudaStream.write("extern __constant__ char __cmem[64*1024];"); cudaStream.newline(); cudaStream.forceNewline(); } if (cudaStream==null) { cudaStream = sw.getNewStream("cu", false); } return cudaStream; } X10CUDAContext_c established; public void establishClosure() { established = this; } public X10CUDAContext_c established() { return established; } LocalDecl autoBlocks; public void autoBlocks(LocalDecl v) { autoBlocks = v; } public LocalDecl autoBlocks() { return autoBlocks; } LocalDecl autoThreads; public void autoThreads(LocalDecl v) { autoThreads = v; } public LocalDecl autoThreads() { return autoThreads; } Name shmIterationVar; public void shmIterationVar(Name v) { shmIterationVar = v; } public Name shmIterationVar() { return shmIterationVar; } boolean firstKernel[] = new boolean[]{false}; public void firstKernel(boolean b) { firstKernel[0] = b; } public boolean firstKernel() { return firstKernel[0]; } } //vim:tabstop=4:shiftwidth=4:expandtab
true
true
public ClassifiedStream cudaStream (StreamWrapper sw, Job j) { if (firstKernel()) { ClassifiedStream cudaStream = sw.getNewStream("cu" ); firstKernel(false); j.compiler().outputFiles().add(wrappingClass()+".cu"); ((X10CPPCompilerOptions)j.extensionInfo().getOptions()).compilationUnits().add(wrappingClass()+".cu"); cudaStream.write("#include <x10aux/config.h>"); cudaStream.newline(); cudaStream.write("#include <x10aux/cuda_kernel.cuh>"); cudaStream.newline(); cudaStream.forceNewline(); cudaStream.write("extern __shared__ char __shm[];"); cudaStream.newline(); cudaStream.write("extern __constant__ char __cmem[64*1024];"); cudaStream.newline(); cudaStream.forceNewline(); } if (cudaStream==null) { cudaStream = sw.getNewStream("cu", false); } return cudaStream; }
public ClassifiedStream cudaStream (StreamWrapper sw, Job j) { if (firstKernel()) { ClassifiedStream cudaStream = sw.getNewStream("cu" ); firstKernel(false); j.compiler().outputFiles().add(wrappingClass()+".cu"); ((X10CPPCompilerOptions)j.extensionInfo().getOptions()).compilationUnits().add(wrappingClass()+".cu"); cudaStream.write("#include <x10aux/config.h>"); cudaStream.newline(); cudaStream.write("#include <x10aux/cuda_kernel.cuh>"); cudaStream.newline(); cudaStream.forceNewline(); cudaStream.write("extern __shared__ int __shm[];"); cudaStream.newline(); cudaStream.write("extern __constant__ char __cmem[64*1024];"); cudaStream.newline(); cudaStream.forceNewline(); } if (cudaStream==null) { cudaStream = sw.getNewStream("cu", false); } return cudaStream; }
diff --git a/src/uk/org/ownage/dmdirc/parser/callbacks/CallbackOnChannelKick.java b/src/uk/org/ownage/dmdirc/parser/callbacks/CallbackOnChannelKick.java index 311fede5b..c9764d945 100644 --- a/src/uk/org/ownage/dmdirc/parser/callbacks/CallbackOnChannelKick.java +++ b/src/uk/org/ownage/dmdirc/parser/callbacks/CallbackOnChannelKick.java @@ -1,81 +1,84 @@ /* * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * SVN: $Id$ */ package uk.org.ownage.dmdirc.parser.callbacks; import uk.org.ownage.dmdirc.parser.ChannelClientInfo; import uk.org.ownage.dmdirc.parser.ChannelInfo; import uk.org.ownage.dmdirc.parser.IRCParser; import uk.org.ownage.dmdirc.parser.ParserError; import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IChannelKick; /** * Callback to all objects implementing the IChannelKick Interface. */ public final class CallbackOnChannelKick extends CallbackObjectSpecific { /** * Create a new instance of the Callback Object. * * @param parser IRCParser That owns this callback * @param manager CallbackManager that is in charge of this callback */ public CallbackOnChannelKick(final IRCParser parser, final CallbackManager manager) { super(parser, manager); } /** * Callback to all objects implementing the IChannelKick Interface. * * @see IChannelKick * @param cChannel Channel where the kick took place * @param cKickedClient ChannelClient that got kicked * @param cKickedByClient ChannelClient that did the kicking (may be null if server) * @param sReason Reason for kick (may be "") * @param sKickedByHost Hostname of Kicker (or servername) * @return true if a callback was called, else false */ - public boolean call(final ChannelInfo cChannel, final ChannelClientInfo cKickedClient, final ChannelClientInfo cKickedByClient, final String sReason, final String sKickedByHost) { + public boolean call(final ChannelInfo cChannel, final ChannelClientInfo cKickedClient, ChannelClientInfo cKickedByClient, final String sReason, final String sKickedByHost) { + if (cKickedByClient == null && myParser.getCreateFake()) { + cKickedByClient = new ChannelClientInfo(cChannel.getParser(), new ClientInfo(cChannel.getParser(), sHost).setFake(true) ,cChannel); + } boolean bResult = false; IChannelKick eMethod = null; for (int i = 0; i < callbackInfo.size(); i++) { eMethod = (IChannelKick) callbackInfo.get(i); if (!this.isValidChan(eMethod, cChannel)) { continue; } try { eMethod.onChannelKick(myParser, cChannel, cKickedClient, cKickedByClient, sReason, sKickedByHost); } catch (Exception e) { final ParserError ei = new ParserError(ParserError.ERROR_ERROR, "Exception in onChannelKick"); ei.setException(e); callErrorInfo(ei); } bResult = true; } return bResult; } /** * Get SVN Version information. * * @return SVN Version String */ public static String getSvnInfo() { return "$Id$"; } }
true
true
public boolean call(final ChannelInfo cChannel, final ChannelClientInfo cKickedClient, final ChannelClientInfo cKickedByClient, final String sReason, final String sKickedByHost) { boolean bResult = false; IChannelKick eMethod = null; for (int i = 0; i < callbackInfo.size(); i++) { eMethod = (IChannelKick) callbackInfo.get(i); if (!this.isValidChan(eMethod, cChannel)) { continue; } try { eMethod.onChannelKick(myParser, cChannel, cKickedClient, cKickedByClient, sReason, sKickedByHost); } catch (Exception e) { final ParserError ei = new ParserError(ParserError.ERROR_ERROR, "Exception in onChannelKick"); ei.setException(e); callErrorInfo(ei); } bResult = true; } return bResult; }
public boolean call(final ChannelInfo cChannel, final ChannelClientInfo cKickedClient, ChannelClientInfo cKickedByClient, final String sReason, final String sKickedByHost) { if (cKickedByClient == null && myParser.getCreateFake()) { cKickedByClient = new ChannelClientInfo(cChannel.getParser(), new ClientInfo(cChannel.getParser(), sHost).setFake(true) ,cChannel); } boolean bResult = false; IChannelKick eMethod = null; for (int i = 0; i < callbackInfo.size(); i++) { eMethod = (IChannelKick) callbackInfo.get(i); if (!this.isValidChan(eMethod, cChannel)) { continue; } try { eMethod.onChannelKick(myParser, cChannel, cKickedClient, cKickedByClient, sReason, sKickedByHost); } catch (Exception e) { final ParserError ei = new ParserError(ParserError.ERROR_ERROR, "Exception in onChannelKick"); ei.setException(e); callErrorInfo(ei); } bResult = true; } return bResult; }
diff --git a/beam-gpf/src/main/java/org/esa/beam/framework/gpf/main/Main.java b/beam-gpf/src/main/java/org/esa/beam/framework/gpf/main/Main.java index dc1e8d1e3..2c9a64fec 100644 --- a/beam-gpf/src/main/java/org/esa/beam/framework/gpf/main/Main.java +++ b/beam-gpf/src/main/java/org/esa/beam/framework/gpf/main/Main.java @@ -1,18 +1,19 @@ package org.esa.beam.framework.gpf.main; /** * The entry point for the GPF command-line tool. * For usage, see {@link org/esa/beam/framework/gpf/main/CommandLineUsage.txt} * or use the option "-h". */ public class Main { public static void main(String[] args) { try { new CommandLineTool().run(args); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); + e.printStackTrace(); } } }
true
true
public static void main(String[] args) { try { new CommandLineTool().run(args); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } }
public static void main(String[] args) { try { new CommandLineTool().run(args); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(); } }
diff --git a/src/be/ibridge/kettle/pan/Pan.java b/src/be/ibridge/kettle/pan/Pan.java index 84a45cf9..7bc34e87 100644 --- a/src/be/ibridge/kettle/pan/Pan.java +++ b/src/be/ibridge/kettle/pan/Pan.java @@ -1,343 +1,344 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ /** * Kettle was (re-)started in March 2003 */ package be.ibridge.kettle.pan; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.LogWriter; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.repository.RepositoriesMeta; import be.ibridge.kettle.repository.Repository; import be.ibridge.kettle.repository.RepositoryDirectory; import be.ibridge.kettle.repository.RepositoryMeta; import be.ibridge.kettle.repository.UserInfo; import be.ibridge.kettle.trans.StepLoader; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; public class Pan { - public static void main(String[] a) + public static int main(String[] a) { ArrayList args = new ArrayList(); for (int i=0;i<a.length;i++) { if (a[i].length()>0) { args.add(a[i]); } } RepositoryMeta repinfo = null; UserInfo userinfo = null; Trans trans = null; if (args.size()==0 ) { System.out.println("Options:"); System.out.println(" -rep : Repository name"); System.out.println(" -user : Repository username"); System.out.println(" -pass : Repository password"); System.out.println(" -trans : The name of the transformation to launch"); System.out.println(" -dir : The directory (don't forget the leading / or \\)"); System.out.println(" -file : The filename (Transformation in XML) to launch"); System.out.println(" -level : The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)"); System.out.println(" -logfile : The logging file to write to"); System.out.println(" -listdir : List the directories in the repository"); System.out.println(" -listtrans : List the transformations in the specified directory"); System.out.println(" -exprep : Export all repository objects to one XML file"); System.out.println(" -norep : do not log into the repository"); System.out.println(""); - return; + return 9; } String repname = Const.getCommandlineOption(args, "rep"); String username = Const.getCommandlineOption(args, "user"); String password = Const.getCommandlineOption(args, "pass"); String transname = Const.getCommandlineOption(args, "trans"); String dirname = Const.getCommandlineOption(args, "dir"); String filename = Const.getCommandlineOption(args, "file"); String loglevel = Const.getCommandlineOption(args, "level"); String logfile = Const.getCommandlineOption(args, "log"); String listdir = Const.getCommandlineOption(args, "listdir"); String listtrans = Const.getCommandlineOption(args, "listtrans"); String listrep = Const.getCommandlineOption(args, "listrep"); String exprep = Const.getCommandlineOption(args, "exprep"); String norep = Const.getCommandlineOption(args, "norep"); String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null); String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null); String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null); if (kettleRepname !=null && kettleRepname .length()>0) repname = kettleRepname; if (kettleUsername!=null && kettleUsername.length()>0) username = kettleUsername; if (kettlePassword!=null && kettlePassword.length()>0) password = kettlePassword; /** System.out.println("Options:"); System.out.println("-------------"); if (repname!=null) System.out.println("repository name : "+repname); if (username!=null) System.out.println("username : "+username); if (password!=null) System.out.println("password is set"); if (dirname!=null) System.out.println("directory : "+dirname); if (loglevel!=null) System.out.println("logging level : "+loglevel); if (listdir!=null) System.out.println("list directories"); if (listtrans!=null) System.out.println("list transformations"); if (exprep!=null) System.out.println("export repository to: "+exprep); */ LogWriter log; if (logfile==null) { log=LogWriter.getInstance( LogWriter.LOG_LEVEL_BASIC ); } else { log=LogWriter.getInstance( logfile, true, LogWriter.LOG_LEVEL_BASIC ); } if (loglevel!=null) { log.setLogLevel(loglevel); log.logBasic("Pan", "Logging is at level : "+log.getLogLevelDesc()); } log.logBasic("Pan", "Start of run."); /* Load the plugins etc.*/ StepLoader steploader = StepLoader.getInstance(); if (!steploader.read()) { log.logError("Spoon", "Error loading steps... halting Pan!"); - return; + return 8; } Date start, stop; Calendar cal; SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); cal=Calendar.getInstance(); start=cal.getTime(); log.logDebug("Pan", "Allocate new transformation."); TransMeta transMeta = new TransMeta(); try { // Read kettle transformation specified on command-line? if (repname!=null || filename!=null) { log.logDebug("Pan", "Parsing command line options."); if (repname!=null && !"Y".equalsIgnoreCase(norep)) { log.logDebug("Pan", "Loading available repositories."); RepositoriesMeta repsinfo = new RepositoriesMeta(log); if (repsinfo.readData()) { log.logDebug("Pan", "Finding repository ["+repname+"]"); repinfo = repsinfo.findRepository(repname); if (repinfo!=null) { // Define and connect to the repository... log.logDebug("Pan", "Allocate & connect to repository."); Repository rep = new Repository(log, repinfo, userinfo); if (rep.connect("Pan commandline")) { RepositoryDirectory directory = rep.getDirectoryTree(); // Default = root // Find the directory name if one is specified... if (dirname!=null) { directory = rep.getDirectoryTree().findDirectory(dirname); } if (directory!=null) { // Check username, password log.logDebug("Pan", "Check supplied username and password."); userinfo = new UserInfo(rep, username, password); if (userinfo.getID()>0) { // Load a transformation if (transname!=null && transname.length()>0) { log.logDebug("Pan", "Load the transformation info..."); transMeta = new TransMeta(rep, transname, directory); log.logDebug("Pan", "Allocate transformation..."); trans = new Trans(log, transMeta); } else // List the transformations in the repository if ("Y".equalsIgnoreCase(listtrans)) { log.logDebug("Pan", "Getting list of transformations in directory: "+directory); String transnames[] = rep.getTransformationNames(directory.getID()); for (int i=0;i<transnames.length;i++) { System.out.println(transnames[i]); } } else // List the directories in the repository if ("Y".equalsIgnoreCase(listdir)) { String dirnames[] = rep.getDirectoryNames(directory.getID()); for (int i=0;i<dirnames.length;i++) { System.out.println(dirnames[i]); } } else // Export the repository if (exprep!=null && exprep.length()>0) { System.out.println("Exporting all objects in the repository to file ["+exprep+"]"); rep.exportAllObjects(null, exprep); System.out.println("Finished exporting all objects in the repository to file ["+exprep+"]"); } else { System.out.println("ERROR: No transformation name supplied: which one should be run?"); } } else { System.out.println("ERROR: Can't verify username and password."); userinfo=null; repinfo=null; } } else { System.out.println("ERROR: Can't find the specified directory ["+dirname+"]"); userinfo=null; repinfo=null; } rep.disconnect(); } else { System.out.println("ERROR: Can't connect to the repository."); } } else { System.out.println("ERROR: No repository provided, can't load transformation."); } } else { System.out.println("ERROR: No repositories defined on this system."); } } else if ("Y".equalsIgnoreCase(listrep)) { RepositoriesMeta ri = new RepositoriesMeta(log); if (ri.readData()) { System.out.println("List of repositories:"); for (int i=0;i<ri.nrRepositories();i++) { RepositoryMeta rinfo = ri.getRepository(i); System.out.println("#"+(i+1)+" : "+rinfo.getName()+" ["+rinfo.getDescription()+"] "); } } else { System.out.println("ERROR: Unable to read/parse the repositories XML file."); } } // Try to load the transformation from file, even if it failed to load from the repository // You could implement some failover mechanism this way. // if (trans==null && filename!=null) { log.logDetailed("Pan", "Loading transformation from XML file ["+filename+"]"); transMeta = new TransMeta(filename); trans = new Trans(log, transMeta); } else { System.out.println("ERROR: No file or transformation name specified."); trans=null; } } } catch(KettleException e) { trans=null; transMeta=null; System.out.println("Processing has stopped because of an error: "+e.getMessage()); } if (trans==null) { if (!"Y".equalsIgnoreCase(listtrans) && !"Y".equalsIgnoreCase(listdir) && !"Y".equalsIgnoreCase(listrep) && ( exprep==null || exprep.length()==0 ) ) { System.out.println("ERROR: Pan can't continue because the transformation couldn't be loaded."); } - return; + return 7; } try { // allocate & run the required sub-threads boolean ok = trans.execute((String[])args.toArray(new String[args.size()])); trans.waitUntilFinished(); trans.endProcessing("end"); log.logBasic("Pan", "Finished!"); cal=Calendar.getInstance(); stop=cal.getTime(); String begin=df.format(start).toString(); String end =df.format(stop).toString(); log.logBasic("Pan", "Start="+begin+", Stop="+end); long millis=stop.getTime()-start.getTime(); log.logBasic("Pan", "Processing ended after "+(millis/1000)+" seconds."); if (ok) { trans.printStats((int)millis/1000); - return; + return 0; } else { - return; + return 1; } } catch(KettleException ke) { System.out.println("ERROR occurred: "+ke.getMessage()); + return 2; } } }
false
true
public static void main(String[] a) { ArrayList args = new ArrayList(); for (int i=0;i<a.length;i++) { if (a[i].length()>0) { args.add(a[i]); } } RepositoryMeta repinfo = null; UserInfo userinfo = null; Trans trans = null; if (args.size()==0 ) { System.out.println("Options:"); System.out.println(" -rep : Repository name"); System.out.println(" -user : Repository username"); System.out.println(" -pass : Repository password"); System.out.println(" -trans : The name of the transformation to launch"); System.out.println(" -dir : The directory (don't forget the leading / or \\)"); System.out.println(" -file : The filename (Transformation in XML) to launch"); System.out.println(" -level : The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)"); System.out.println(" -logfile : The logging file to write to"); System.out.println(" -listdir : List the directories in the repository"); System.out.println(" -listtrans : List the transformations in the specified directory"); System.out.println(" -exprep : Export all repository objects to one XML file"); System.out.println(" -norep : do not log into the repository"); System.out.println(""); return; } String repname = Const.getCommandlineOption(args, "rep"); String username = Const.getCommandlineOption(args, "user"); String password = Const.getCommandlineOption(args, "pass"); String transname = Const.getCommandlineOption(args, "trans"); String dirname = Const.getCommandlineOption(args, "dir"); String filename = Const.getCommandlineOption(args, "file"); String loglevel = Const.getCommandlineOption(args, "level"); String logfile = Const.getCommandlineOption(args, "log"); String listdir = Const.getCommandlineOption(args, "listdir"); String listtrans = Const.getCommandlineOption(args, "listtrans"); String listrep = Const.getCommandlineOption(args, "listrep"); String exprep = Const.getCommandlineOption(args, "exprep"); String norep = Const.getCommandlineOption(args, "norep"); String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null); String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null); String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null); if (kettleRepname !=null && kettleRepname .length()>0) repname = kettleRepname; if (kettleUsername!=null && kettleUsername.length()>0) username = kettleUsername; if (kettlePassword!=null && kettlePassword.length()>0) password = kettlePassword; /** System.out.println("Options:"); System.out.println("-------------"); if (repname!=null) System.out.println("repository name : "+repname); if (username!=null) System.out.println("username : "+username); if (password!=null) System.out.println("password is set"); if (dirname!=null) System.out.println("directory : "+dirname); if (loglevel!=null) System.out.println("logging level : "+loglevel); if (listdir!=null) System.out.println("list directories"); if (listtrans!=null) System.out.println("list transformations"); if (exprep!=null) System.out.println("export repository to: "+exprep); */ LogWriter log; if (logfile==null) { log=LogWriter.getInstance( LogWriter.LOG_LEVEL_BASIC ); } else { log=LogWriter.getInstance( logfile, true, LogWriter.LOG_LEVEL_BASIC ); } if (loglevel!=null) { log.setLogLevel(loglevel); log.logBasic("Pan", "Logging is at level : "+log.getLogLevelDesc()); } log.logBasic("Pan", "Start of run."); /* Load the plugins etc.*/ StepLoader steploader = StepLoader.getInstance(); if (!steploader.read()) { log.logError("Spoon", "Error loading steps... halting Pan!"); return; } Date start, stop; Calendar cal; SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); cal=Calendar.getInstance(); start=cal.getTime(); log.logDebug("Pan", "Allocate new transformation."); TransMeta transMeta = new TransMeta(); try { // Read kettle transformation specified on command-line? if (repname!=null || filename!=null) { log.logDebug("Pan", "Parsing command line options."); if (repname!=null && !"Y".equalsIgnoreCase(norep)) { log.logDebug("Pan", "Loading available repositories."); RepositoriesMeta repsinfo = new RepositoriesMeta(log); if (repsinfo.readData()) { log.logDebug("Pan", "Finding repository ["+repname+"]"); repinfo = repsinfo.findRepository(repname); if (repinfo!=null) { // Define and connect to the repository... log.logDebug("Pan", "Allocate & connect to repository."); Repository rep = new Repository(log, repinfo, userinfo); if (rep.connect("Pan commandline")) { RepositoryDirectory directory = rep.getDirectoryTree(); // Default = root // Find the directory name if one is specified... if (dirname!=null) { directory = rep.getDirectoryTree().findDirectory(dirname); } if (directory!=null) { // Check username, password log.logDebug("Pan", "Check supplied username and password."); userinfo = new UserInfo(rep, username, password); if (userinfo.getID()>0) { // Load a transformation if (transname!=null && transname.length()>0) { log.logDebug("Pan", "Load the transformation info..."); transMeta = new TransMeta(rep, transname, directory); log.logDebug("Pan", "Allocate transformation..."); trans = new Trans(log, transMeta); } else // List the transformations in the repository if ("Y".equalsIgnoreCase(listtrans)) { log.logDebug("Pan", "Getting list of transformations in directory: "+directory); String transnames[] = rep.getTransformationNames(directory.getID()); for (int i=0;i<transnames.length;i++) { System.out.println(transnames[i]); } } else // List the directories in the repository if ("Y".equalsIgnoreCase(listdir)) { String dirnames[] = rep.getDirectoryNames(directory.getID()); for (int i=0;i<dirnames.length;i++) { System.out.println(dirnames[i]); } } else // Export the repository if (exprep!=null && exprep.length()>0) { System.out.println("Exporting all objects in the repository to file ["+exprep+"]"); rep.exportAllObjects(null, exprep); System.out.println("Finished exporting all objects in the repository to file ["+exprep+"]"); } else { System.out.println("ERROR: No transformation name supplied: which one should be run?"); } } else { System.out.println("ERROR: Can't verify username and password."); userinfo=null; repinfo=null; } } else { System.out.println("ERROR: Can't find the specified directory ["+dirname+"]"); userinfo=null; repinfo=null; } rep.disconnect(); } else { System.out.println("ERROR: Can't connect to the repository."); } } else { System.out.println("ERROR: No repository provided, can't load transformation."); } } else { System.out.println("ERROR: No repositories defined on this system."); } } else if ("Y".equalsIgnoreCase(listrep)) { RepositoriesMeta ri = new RepositoriesMeta(log); if (ri.readData()) { System.out.println("List of repositories:"); for (int i=0;i<ri.nrRepositories();i++) { RepositoryMeta rinfo = ri.getRepository(i); System.out.println("#"+(i+1)+" : "+rinfo.getName()+" ["+rinfo.getDescription()+"] "); } } else { System.out.println("ERROR: Unable to read/parse the repositories XML file."); } } // Try to load the transformation from file, even if it failed to load from the repository // You could implement some failover mechanism this way. // if (trans==null && filename!=null) { log.logDetailed("Pan", "Loading transformation from XML file ["+filename+"]"); transMeta = new TransMeta(filename); trans = new Trans(log, transMeta); } else { System.out.println("ERROR: No file or transformation name specified."); trans=null; } } } catch(KettleException e) { trans=null; transMeta=null; System.out.println("Processing has stopped because of an error: "+e.getMessage()); } if (trans==null) { if (!"Y".equalsIgnoreCase(listtrans) && !"Y".equalsIgnoreCase(listdir) && !"Y".equalsIgnoreCase(listrep) && ( exprep==null || exprep.length()==0 ) ) { System.out.println("ERROR: Pan can't continue because the transformation couldn't be loaded."); } return; } try { // allocate & run the required sub-threads boolean ok = trans.execute((String[])args.toArray(new String[args.size()])); trans.waitUntilFinished(); trans.endProcessing("end"); log.logBasic("Pan", "Finished!"); cal=Calendar.getInstance(); stop=cal.getTime(); String begin=df.format(start).toString(); String end =df.format(stop).toString(); log.logBasic("Pan", "Start="+begin+", Stop="+end); long millis=stop.getTime()-start.getTime(); log.logBasic("Pan", "Processing ended after "+(millis/1000)+" seconds."); if (ok) { trans.printStats((int)millis/1000); return; } else { return; } } catch(KettleException ke) { System.out.println("ERROR occurred: "+ke.getMessage()); } }
public static int main(String[] a) { ArrayList args = new ArrayList(); for (int i=0;i<a.length;i++) { if (a[i].length()>0) { args.add(a[i]); } } RepositoryMeta repinfo = null; UserInfo userinfo = null; Trans trans = null; if (args.size()==0 ) { System.out.println("Options:"); System.out.println(" -rep : Repository name"); System.out.println(" -user : Repository username"); System.out.println(" -pass : Repository password"); System.out.println(" -trans : The name of the transformation to launch"); System.out.println(" -dir : The directory (don't forget the leading / or \\)"); System.out.println(" -file : The filename (Transformation in XML) to launch"); System.out.println(" -level : The logging level (Basic, Detailed, Debug, Rowlevel, Error, Nothing)"); System.out.println(" -logfile : The logging file to write to"); System.out.println(" -listdir : List the directories in the repository"); System.out.println(" -listtrans : List the transformations in the specified directory"); System.out.println(" -exprep : Export all repository objects to one XML file"); System.out.println(" -norep : do not log into the repository"); System.out.println(""); return 9; } String repname = Const.getCommandlineOption(args, "rep"); String username = Const.getCommandlineOption(args, "user"); String password = Const.getCommandlineOption(args, "pass"); String transname = Const.getCommandlineOption(args, "trans"); String dirname = Const.getCommandlineOption(args, "dir"); String filename = Const.getCommandlineOption(args, "file"); String loglevel = Const.getCommandlineOption(args, "level"); String logfile = Const.getCommandlineOption(args, "log"); String listdir = Const.getCommandlineOption(args, "listdir"); String listtrans = Const.getCommandlineOption(args, "listtrans"); String listrep = Const.getCommandlineOption(args, "listrep"); String exprep = Const.getCommandlineOption(args, "exprep"); String norep = Const.getCommandlineOption(args, "norep"); String kettleRepname = Const.getEnvironmentVariable("KETTLE_REPOSITORY", null); String kettleUsername = Const.getEnvironmentVariable("KETTLE_USER", null); String kettlePassword = Const.getEnvironmentVariable("KETTLE_PASSWORD", null); if (kettleRepname !=null && kettleRepname .length()>0) repname = kettleRepname; if (kettleUsername!=null && kettleUsername.length()>0) username = kettleUsername; if (kettlePassword!=null && kettlePassword.length()>0) password = kettlePassword; /** System.out.println("Options:"); System.out.println("-------------"); if (repname!=null) System.out.println("repository name : "+repname); if (username!=null) System.out.println("username : "+username); if (password!=null) System.out.println("password is set"); if (dirname!=null) System.out.println("directory : "+dirname); if (loglevel!=null) System.out.println("logging level : "+loglevel); if (listdir!=null) System.out.println("list directories"); if (listtrans!=null) System.out.println("list transformations"); if (exprep!=null) System.out.println("export repository to: "+exprep); */ LogWriter log; if (logfile==null) { log=LogWriter.getInstance( LogWriter.LOG_LEVEL_BASIC ); } else { log=LogWriter.getInstance( logfile, true, LogWriter.LOG_LEVEL_BASIC ); } if (loglevel!=null) { log.setLogLevel(loglevel); log.logBasic("Pan", "Logging is at level : "+log.getLogLevelDesc()); } log.logBasic("Pan", "Start of run."); /* Load the plugins etc.*/ StepLoader steploader = StepLoader.getInstance(); if (!steploader.read()) { log.logError("Spoon", "Error loading steps... halting Pan!"); return 8; } Date start, stop; Calendar cal; SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); cal=Calendar.getInstance(); start=cal.getTime(); log.logDebug("Pan", "Allocate new transformation."); TransMeta transMeta = new TransMeta(); try { // Read kettle transformation specified on command-line? if (repname!=null || filename!=null) { log.logDebug("Pan", "Parsing command line options."); if (repname!=null && !"Y".equalsIgnoreCase(norep)) { log.logDebug("Pan", "Loading available repositories."); RepositoriesMeta repsinfo = new RepositoriesMeta(log); if (repsinfo.readData()) { log.logDebug("Pan", "Finding repository ["+repname+"]"); repinfo = repsinfo.findRepository(repname); if (repinfo!=null) { // Define and connect to the repository... log.logDebug("Pan", "Allocate & connect to repository."); Repository rep = new Repository(log, repinfo, userinfo); if (rep.connect("Pan commandline")) { RepositoryDirectory directory = rep.getDirectoryTree(); // Default = root // Find the directory name if one is specified... if (dirname!=null) { directory = rep.getDirectoryTree().findDirectory(dirname); } if (directory!=null) { // Check username, password log.logDebug("Pan", "Check supplied username and password."); userinfo = new UserInfo(rep, username, password); if (userinfo.getID()>0) { // Load a transformation if (transname!=null && transname.length()>0) { log.logDebug("Pan", "Load the transformation info..."); transMeta = new TransMeta(rep, transname, directory); log.logDebug("Pan", "Allocate transformation..."); trans = new Trans(log, transMeta); } else // List the transformations in the repository if ("Y".equalsIgnoreCase(listtrans)) { log.logDebug("Pan", "Getting list of transformations in directory: "+directory); String transnames[] = rep.getTransformationNames(directory.getID()); for (int i=0;i<transnames.length;i++) { System.out.println(transnames[i]); } } else // List the directories in the repository if ("Y".equalsIgnoreCase(listdir)) { String dirnames[] = rep.getDirectoryNames(directory.getID()); for (int i=0;i<dirnames.length;i++) { System.out.println(dirnames[i]); } } else // Export the repository if (exprep!=null && exprep.length()>0) { System.out.println("Exporting all objects in the repository to file ["+exprep+"]"); rep.exportAllObjects(null, exprep); System.out.println("Finished exporting all objects in the repository to file ["+exprep+"]"); } else { System.out.println("ERROR: No transformation name supplied: which one should be run?"); } } else { System.out.println("ERROR: Can't verify username and password."); userinfo=null; repinfo=null; } } else { System.out.println("ERROR: Can't find the specified directory ["+dirname+"]"); userinfo=null; repinfo=null; } rep.disconnect(); } else { System.out.println("ERROR: Can't connect to the repository."); } } else { System.out.println("ERROR: No repository provided, can't load transformation."); } } else { System.out.println("ERROR: No repositories defined on this system."); } } else if ("Y".equalsIgnoreCase(listrep)) { RepositoriesMeta ri = new RepositoriesMeta(log); if (ri.readData()) { System.out.println("List of repositories:"); for (int i=0;i<ri.nrRepositories();i++) { RepositoryMeta rinfo = ri.getRepository(i); System.out.println("#"+(i+1)+" : "+rinfo.getName()+" ["+rinfo.getDescription()+"] "); } } else { System.out.println("ERROR: Unable to read/parse the repositories XML file."); } } // Try to load the transformation from file, even if it failed to load from the repository // You could implement some failover mechanism this way. // if (trans==null && filename!=null) { log.logDetailed("Pan", "Loading transformation from XML file ["+filename+"]"); transMeta = new TransMeta(filename); trans = new Trans(log, transMeta); } else { System.out.println("ERROR: No file or transformation name specified."); trans=null; } } } catch(KettleException e) { trans=null; transMeta=null; System.out.println("Processing has stopped because of an error: "+e.getMessage()); } if (trans==null) { if (!"Y".equalsIgnoreCase(listtrans) && !"Y".equalsIgnoreCase(listdir) && !"Y".equalsIgnoreCase(listrep) && ( exprep==null || exprep.length()==0 ) ) { System.out.println("ERROR: Pan can't continue because the transformation couldn't be loaded."); } return 7; } try { // allocate & run the required sub-threads boolean ok = trans.execute((String[])args.toArray(new String[args.size()])); trans.waitUntilFinished(); trans.endProcessing("end"); log.logBasic("Pan", "Finished!"); cal=Calendar.getInstance(); stop=cal.getTime(); String begin=df.format(start).toString(); String end =df.format(stop).toString(); log.logBasic("Pan", "Start="+begin+", Stop="+end); long millis=stop.getTime()-start.getTime(); log.logBasic("Pan", "Processing ended after "+(millis/1000)+" seconds."); if (ok) { trans.printStats((int)millis/1000); return 0; } else { return 1; } } catch(KettleException ke) { System.out.println("ERROR occurred: "+ke.getMessage()); return 2; } }
diff --git a/src/com/android/phone/BluetoothHeadsetService.java b/src/com/android/phone/BluetoothHeadsetService.java index 40724f70..0226280d 100644 --- a/src/com/android/phone/BluetoothHeadsetService.java +++ b/src/com/android/phone/BluetoothHeadsetService.java @@ -1,839 +1,828 @@ /* * Copyright (C) 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, * 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.phone; import android.app.Service; import android.bluetooth.BluetoothAudioGateway; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothUuid; import android.bluetooth.HeadsetBase; import android.bluetooth.IBluetoothHeadset; import android.os.ParcelUuid; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.AudioManager; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.RemoteException; import android.os.SystemProperties; import android.provider.Settings; import android.util.Log; import com.android.internal.telephony.Call; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.ListIterator; import java.util.Set; /** * Provides Bluetooth Headset and Handsfree profile, as a service in * the Phone application. * @hide */ public class BluetoothHeadsetService extends Service { private static final String TAG = "BT HSHFP"; private static final boolean DBG = true; private static final String PREF_NAME = BluetoothHeadsetService.class.getSimpleName(); private static final String PREF_LAST_HEADSET = "lastHeadsetAddress"; private static final int PHONE_STATE_CHANGED = 1; private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN; private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH; private static boolean sHasStarted = false; private BluetoothDevice mDeviceSdpQuery; private BluetoothAdapter mAdapter; private PowerManager mPowerManager; private BluetoothAudioGateway mAg; private HeadsetBase mHeadset; private int mState; private int mHeadsetType; private BluetoothHandsfree mBtHandsfree; private BluetoothDevice mRemoteDevice; private LinkedList<BluetoothDevice> mAutoConnectQueue; private Call mForegroundCall; private Call mRingingCall; private Phone mPhone; private final HeadsetPriority mHeadsetPriority = new HeadsetPriority(); public BluetoothHeadsetService() { mState = BluetoothHeadset.STATE_DISCONNECTED; mHeadsetType = BluetoothHandsfree.TYPE_UNKNOWN; } @Override public void onCreate() { super.onCreate(); mAdapter = BluetoothAdapter.getDefaultAdapter(); mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); mBtHandsfree = PhoneApp.getInstance().getBluetoothHandsfree(); mAg = new BluetoothAudioGateway(mAdapter); mPhone = PhoneFactory.getDefaultPhone(); mRingingCall = mPhone.getRingingCall(); mForegroundCall = mPhone.getForegroundCall(); if (mAdapter.isEnabled()) { mHeadsetPriority.load(); } IntentFilter filter = new IntentFilter( BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); filter.addAction(AudioManager.VOLUME_CHANGED_ACTION); filter.addAction(BluetoothDevice.ACTION_UUID); registerReceiver(mBluetoothReceiver, filter); mPhone.registerForPreciseCallStateChanged(mStateChangeHandler, PHONE_STATE_CHANGED, null); } @Override public void onStart(Intent intent, int startId) { if (mAdapter == null) { Log.w(TAG, "Stopping BluetoothHeadsetService: device does not have BT"); stopSelf(); } else { if (!sHasStarted) { if (DBG) log("Starting BluetoothHeadsetService"); if (mAdapter.isEnabled()) { mAg.start(mIncomingConnectionHandler); mBtHandsfree.onBluetoothEnabled(); // BT might have only just started, wait 6 seconds until // SDP records are registered before reconnecting headset mHandler.sendMessageDelayed(mHandler.obtainMessage(RECONNECT_LAST_HEADSET), 6000); } sHasStarted = true; } } } private final Handler mIncomingConnectionHandler = new Handler() { @Override public void handleMessage(Message msg) { BluetoothAudioGateway.IncomingConnectionInfo info = (BluetoothAudioGateway.IncomingConnectionInfo)msg.obj; int type = BluetoothHandsfree.TYPE_UNKNOWN; switch(msg.what) { case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION: type = BluetoothHandsfree.TYPE_HEADSET; break; case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION: type = BluetoothHandsfree.TYPE_HANDSFREE; break; } Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) + ") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan); int priority = BluetoothHeadset.PRIORITY_OFF; HeadsetBase headset; try { priority = mBinder.getPriority(info.mRemoteDevice); } catch (RemoteException e) {} if (priority <= BluetoothHeadset.PRIORITY_OFF) { Log.i(TAG, "Rejecting incoming connection because priority = " + priority); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); return; } switch (mState) { case BluetoothHeadset.STATE_DISCONNECTED: // headset connecting us, lets join mRemoteDevice = info.mRemoteDevice; setState(BluetoothHeadset.STATE_CONNECTING); headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget(); break; case BluetoothHeadset.STATE_CONNECTING: if (!info.mRemoteDevice.equals(mRemoteDevice)) { // different headset, ignoring Log.i(TAG, "Already attempting connect to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); } // If we are here, we are in danger of a race condition // incoming rfcomm connection, but we are also attempting an // outgoing connection. Lets try and interrupt the outgoing // connection. Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice + ". Cancel outgoing connection."); if (mConnectThread != null) { mConnectThread.interrupt(); + mConnectThread = null; } // Now continue with new connection, including calling callback mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS); mBtHandsfree.connectHeadset(mHeadset, mHeadsetType); - // Make sure that old outgoing connect thread is dead. - if (mConnectThread != null) { - try { - // TODO: Don't block in the main thread - Log.w(TAG, "Block in main thread to join stale outgoing connection thread"); - mConnectThread.join(); - } catch (InterruptedException e) { - Log.e(TAG, "Connection cancelled twice eh?", e); - } - mConnectThread = null; - } - if (DBG) log("Successfully used incoming connection, and cancelled outgoing " + - " connection"); + if (DBG) log("Successfully used incoming connection"); break; case BluetoothHeadset.STATE_CONNECTED: Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); break; } } }; private final Handler mStateChangeHandler = new Handler() { @Override public void handleMessage(Message msg) { switch(msg.what) { case PHONE_STATE_CHANGED: switch(mForegroundCall.getState()) { case DIALING: case ALERTING: synchronized(this) { if (mState == BluetoothHeadset.STATE_DISCONNECTED) { autoConnectHeadset(); } } } switch(mRingingCall.getState()) { case INCOMING: case WAITING: synchronized(this) { if (mState == BluetoothHeadset.STATE_DISCONNECTED) { autoConnectHeadset(); } } break; } } } }; private synchronized void autoConnectHeadset() { if (DBG && debugDontReconnect()) { return; } if (mAdapter.isEnabled()) { try { mBinder.connectHeadset(null); } catch (RemoteException e) {} } } private final BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if ((mState == BluetoothHeadset.STATE_CONNECTED || mState == BluetoothHeadset.STATE_CONNECTING) && action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED) && device.equals(mRemoteDevice)) { try { mBinder.disconnectHeadset(); } catch (RemoteException e) {} } else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { switch (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) { case BluetoothAdapter.STATE_ON: mHeadsetPriority.load(); mHandler.sendMessageDelayed(mHandler.obtainMessage(RECONNECT_LAST_HEADSET), 8000); mAg.start(mIncomingConnectionHandler); mBtHandsfree.onBluetoothEnabled(); break; case BluetoothAdapter.STATE_TURNING_OFF: mBtHandsfree.onBluetoothDisabled(); mAg.stop(); setState(BluetoothHeadset.STATE_DISCONNECTED, BluetoothHeadset.RESULT_FAILURE); break; } } else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) { int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); switch(bondState) { case BluetoothDevice.BOND_BONDED: if (mHeadsetPriority.get(device) == BluetoothHeadset.PRIORITY_UNDEFINED) { mHeadsetPriority.set(device, BluetoothHeadset.PRIORITY_ON); } break; case BluetoothDevice.BOND_NONE: mHeadsetPriority.set(device, BluetoothHeadset.PRIORITY_UNDEFINED); break; } } else if (action.equals(AudioManager.VOLUME_CHANGED_ACTION)) { int streamType = intent.getIntExtra(AudioManager.EXTRA_VOLUME_STREAM_TYPE, -1); if (streamType == AudioManager.STREAM_BLUETOOTH_SCO) { mBtHandsfree.sendScoGainUpdate(intent.getIntExtra( AudioManager.EXTRA_VOLUME_STREAM_VALUE, 0)); } } else if (action.equals(BluetoothDevice.ACTION_UUID)) { if (device.equals(mDeviceSdpQuery)) { // We have got SDP records for the device we are interested in. getSdpRecordsAndConnect(); } } } }; private static final int RECONNECT_LAST_HEADSET = 1; private static final int CONNECT_HEADSET_DELAYED = 2; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case RECONNECT_LAST_HEADSET: autoConnectHeadset(); break; case CONNECT_HEADSET_DELAYED: getSdpRecordsAndConnect(); break; } } }; @Override public IBinder onBind(Intent intent) { return mBinder; } // ------------------------------------------------------------------ // Bluetooth Headset Connect // ------------------------------------------------------------------ private static final int RFCOMM_CONNECTED = 1; private static final int RFCOMM_ERROR = 2; private long mTimestamp; /** * Thread for RFCOMM connection * Messages are sent to mConnectingStatusHandler as connection progresses. */ private RfcommConnectThread mConnectThread; private class RfcommConnectThread extends Thread { private BluetoothDevice device; private int channel; private int type; private static final int EINTERRUPT = -1000; private static final int ECONNREFUSED = -111; public RfcommConnectThread(BluetoothDevice device, int channel, int type) { super(); this.device = device; this.channel = channel; this.type = type; } private int waitForConnect(HeadsetBase headset) { // Try to connect for 20 seconds int result = 0; for (int i=0; i < 40 && result == 0; i++) { // waitForAsyncConnect returns 0 on timeout, 1 on success, < 0 on error. result = headset.waitForAsyncConnect(500, mConnectedStatusHandler); if (isInterrupted()) { headset.disconnect(); return EINTERRUPT; } } return result; } @Override public void run() { long timestamp; timestamp = System.currentTimeMillis(); HeadsetBase headset = new HeadsetBase(mPowerManager, mAdapter, device, channel); int result = waitForConnect(headset); if (result != EINTERRUPT && result != 1) { if (result == ECONNREFUSED && mDeviceSdpQuery == null) { // The rfcomm channel number might have changed, do SDP // query and try to connect again. mDeviceSdpQuery = mRemoteDevice; device.fetchUuidsWithSdp(); mConnectThread = null; return; } else { Log.i(TAG, "Trying to connect to rfcomm socket again after 1 sec"); try { sleep(1000); // 1 second } catch (InterruptedException e) {} } result = waitForConnect(headset); } mDeviceSdpQuery = null; if (result == EINTERRUPT) return; if (DBG) log("RFCOMM connection attempt took " + (System.currentTimeMillis() - timestamp) + " ms"); if (isInterrupted()) { headset.disconnect(); return; } if (result < 0) { Log.w(TAG, "headset.waitForAsyncConnect() error: " + result); mConnectingStatusHandler.obtainMessage(RFCOMM_ERROR).sendToTarget(); return; } else if (result == 0) { mConnectingStatusHandler.obtainMessage(RFCOMM_ERROR).sendToTarget(); Log.w(TAG, "mHeadset.waitForAsyncConnect() error: " + result + "(timeout)"); return; } else { mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget(); } } } /** * Receives events from mConnectThread back in the main thread. */ private final Handler mConnectingStatusHandler = new Handler() { @Override public void handleMessage(Message msg) { if (mState != BluetoothHeadset.STATE_CONNECTING) { return; // stale events } switch (msg.what) { case RFCOMM_ERROR: if (DBG) log("Rfcomm error"); mConnectThread = null; setState(BluetoothHeadset.STATE_DISCONNECTED, BluetoothHeadset.RESULT_FAILURE); break; case RFCOMM_CONNECTED: if (DBG) log("Rfcomm connected"); mConnectThread = null; mHeadset = (HeadsetBase)msg.obj; setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS); mBtHandsfree.connectHeadset(mHeadset, mHeadsetType); break; } } }; /** * Receives events from a connected RFCOMM socket back in the main thread. */ private final Handler mConnectedStatusHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case HeadsetBase.RFCOMM_DISCONNECTED: setState(BluetoothHeadset.STATE_DISCONNECTED, BluetoothHeadset.RESULT_FAILURE); break; } } }; private void setState(int state) { setState(state, BluetoothHeadset.RESULT_SUCCESS); } private synchronized void setState(int state, int result) { if (state != mState) { if (DBG) log("Headset state " + mState + " -> " + state + ", result = " + result); if (mState == BluetoothHeadset.STATE_CONNECTED) { mBtHandsfree.disconnectHeadset(); // no longer connected - make sure BT audio is taken down mBtHandsfree.audioOff(); } Intent intent = new Intent(BluetoothHeadset.ACTION_STATE_CHANGED); intent.putExtra(BluetoothHeadset.EXTRA_PREVIOUS_STATE, mState); mState = state; intent.putExtra(BluetoothHeadset.EXTRA_STATE, mState); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mRemoteDevice); sendBroadcast(intent, BLUETOOTH_PERM); if (mState == BluetoothHeadset.STATE_DISCONNECTED) { mHeadset = null; mRemoteDevice = null; mHeadsetType = BluetoothHandsfree.TYPE_UNKNOWN; if (mAutoConnectQueue != null) { doNextAutoConnect(); } } else if (mState == BluetoothHeadset.STATE_CONNECTING) { // Set the priority to AUTO_CONNECT mHeadsetPriority.set(mRemoteDevice, BluetoothHeadset.PRIORITY_AUTO_CONNECT); } else if (mState == BluetoothHeadset.STATE_CONNECTED) { mAutoConnectQueue = null; // cancel further auto-connection mHeadsetPriority.bump(mRemoteDevice); } } } private void getSdpRecordsAndConnect() { ParcelUuid[] uuids = mRemoteDevice.getUuids(); if (uuids != null) { if (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.Handsfree)) { log("SDP UUID: TYPE_HANDSFREE"); mHeadsetType = BluetoothHandsfree.TYPE_HANDSFREE; int channel = mRemoteDevice.getServiceChannel(BluetoothUuid.Handsfree); mConnectThread = new RfcommConnectThread(mRemoteDevice, channel, mHeadsetType); mConnectThread.start(); return; } else if (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.HSP)) { log("SDP UUID: TYPE_HEADSET"); mHeadsetType = BluetoothHandsfree.TYPE_HEADSET; int channel = mRemoteDevice.getServiceChannel(BluetoothUuid.HSP); mConnectThread = new RfcommConnectThread(mRemoteDevice, channel, mHeadsetType); mConnectThread.start(); return; } } log("SDP UUID: TYPE_UNKNOWN"); mHeadsetType = BluetoothHandsfree.TYPE_UNKNOWN; setState(BluetoothHeadset.STATE_DISCONNECTED, BluetoothHeadset.RESULT_FAILURE); return; } private synchronized boolean doNextAutoConnect() { if (mAutoConnectQueue == null || mAutoConnectQueue.size() == 0) { mAutoConnectQueue = null; return false; } mRemoteDevice = mAutoConnectQueue.removeFirst(); // Don't auto connect with docks if we are docked with the dock. if (isPhoneDocked(mRemoteDevice)) return doNextAutoConnect(); if (DBG) log("pulled " + mRemoteDevice + " off auto-connect queue"); setState(BluetoothHeadset.STATE_CONNECTING); getSdpRecordsAndConnect(); return true; } private boolean isPhoneDocked(BluetoothDevice autoConnectDevice) { // This works only because these broadcast intents are "sticky" Intent i = registerReceiver(null, new IntentFilter(Intent.ACTION_DOCK_EVENT)); if (i != null) { int state = i.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED); if (state != Intent.EXTRA_DOCK_STATE_UNDOCKED) { BluetoothDevice device = i.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device != null && autoConnectDevice.equals(device)) { return true; } } } return false; } /** * Handlers for incoming service calls */ private final IBluetoothHeadset.Stub mBinder = new IBluetoothHeadset.Stub() { public int getState() { enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); return mState; } public BluetoothDevice getCurrentHeadset() { enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); if (mState == BluetoothHeadset.STATE_DISCONNECTED) { return null; } return mRemoteDevice; } public boolean connectHeadset(BluetoothDevice device) { enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); synchronized (BluetoothHeadsetService.this) { if (mState == BluetoothHeadset.STATE_CONNECTED || mState == BluetoothHeadset.STATE_CONNECTING) { Log.w(TAG, "connectHeadset(" + device + "): failed: already in state " + mState + " with headset " + mRemoteDevice); return false; } if (device == null) { mAutoConnectQueue = mHeadsetPriority.getSorted(); return doNextAutoConnect(); } mRemoteDevice = device; setState(BluetoothHeadset.STATE_CONNECTING); if (mRemoteDevice.getUuids() == null) { // We might not have got the UUID change notification from // Bluez yet, if we have just paired. Try after 1.5 secs. mHandler.sendMessageDelayed( mHandler.obtainMessage(CONNECT_HEADSET_DELAYED), 1500); } else { getSdpRecordsAndConnect(); } } return true; } public boolean isConnected(BluetoothDevice device) { enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); return mState == BluetoothHeadset.STATE_CONNECTED && mRemoteDevice.equals(device); } public void disconnectHeadset() { enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); synchronized (BluetoothHeadsetService.this) { switch (mState) { case BluetoothHeadset.STATE_CONNECTING: if (mConnectThread != null) { // cancel the connection thread mConnectThread.interrupt(); try { mConnectThread.join(); } catch (InterruptedException e) { Log.e(TAG, "Connection cancelled twice?", e); } mConnectThread = null; } if (mHeadset != null) { mHeadset.disconnect(); mHeadset = null; } setState(BluetoothHeadset.STATE_DISCONNECTED, BluetoothHeadset.RESULT_CANCELED); break; case BluetoothHeadset.STATE_CONNECTED: // Send a dummy battery level message to force headset // out of sniff mode so that it will immediately notice // the disconnection. We are currently sending it for // handsfree only. // TODO: Call hci_conn_enter_active_mode() from // rfcomm_send_disc() in the kernel instead. // See http://b/1716887 if (mHeadsetType == BluetoothHandsfree.TYPE_HANDSFREE) { mHeadset.sendURC("+CIEV: 7,3"); } if (mHeadset != null) { mHeadset.disconnect(); mHeadset = null; } setState(BluetoothHeadset.STATE_DISCONNECTED, BluetoothHeadset.RESULT_CANCELED); break; } } } public boolean startVoiceRecognition() { enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); synchronized (BluetoothHeadsetService.this) { if (mState != BluetoothHeadset.STATE_CONNECTED) { return false; } return mBtHandsfree.startVoiceRecognition(); } } public boolean stopVoiceRecognition() { enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); synchronized (BluetoothHeadsetService.this) { if (mState != BluetoothHeadset.STATE_CONNECTED) { return false; } return mBtHandsfree.stopVoiceRecognition(); } } public boolean setPriority(BluetoothDevice device, int priority) { enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); if (priority < BluetoothHeadset.PRIORITY_OFF) { return false; } mHeadsetPriority.set(device, priority); return true; } public int getPriority(BluetoothDevice device) { enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); return mHeadsetPriority.get(device); } public int getBatteryUsageHint() { enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); return HeadsetBase.getAtInputCount(); } }; @Override public void onDestroy() { super.onDestroy(); if (DBG) log("Stopping BluetoothHeadsetService"); unregisterReceiver(mBluetoothReceiver); mBtHandsfree.onBluetoothDisabled(); mAg.stop(); sHasStarted = false; setState(BluetoothHeadset.STATE_DISCONNECTED, BluetoothHeadset.RESULT_CANCELED); mHeadsetType = BluetoothHandsfree.TYPE_UNKNOWN; } private class HeadsetPriority { private HashMap<BluetoothDevice, Integer> mPriority = new HashMap<BluetoothDevice, Integer>(); public synchronized boolean load() { Set<BluetoothDevice> devices = mAdapter.getBondedDevices(); if (devices == null) { return false; // for example, bluetooth is off } for (BluetoothDevice device : devices) { load(device); } return true; } private synchronized int load(BluetoothDevice device) { int priority = Settings.Secure.getInt(getContentResolver(), Settings.Secure.getBluetoothHeadsetPriorityKey(device.getAddress()), BluetoothHeadset.PRIORITY_UNDEFINED); mPriority.put(device, new Integer(priority)); if (DBG) log("Loaded priority " + device + " = " + priority); return priority; } public synchronized int get(BluetoothDevice device) { Integer priority = mPriority.get(device); if (priority == null) { return load(device); } return priority.intValue(); } public synchronized void set(BluetoothDevice device, int priority) { int oldPriority = get(device); if (oldPriority == priority) { return; } mPriority.put(device, new Integer(priority)); Settings.Secure.putInt(getContentResolver(), Settings.Secure.getBluetoothHeadsetPriorityKey(device.getAddress()), priority); if (DBG) log("Saved priority " + device + " = " + priority); } /** Mark this headset as highest priority */ public synchronized void bump(BluetoothDevice device) { int oldPriority = get(device); int maxPriority = BluetoothHeadset.PRIORITY_AUTO_CONNECT; // Find max, not including given address for (BluetoothDevice d : mPriority.keySet()) { if (device.equals(d)) continue; int p = mPriority.get(d).intValue(); if (p > maxPriority) { maxPriority = p; } } if (maxPriority >= oldPriority) { int p = maxPriority + 1; set(device, p); if (p >= Integer.MAX_VALUE) { rebalance(); } } } /** shifts all non-zero priorities to be monotonically increasing from * PRIORITY_AUTO_CONNECT */ private synchronized void rebalance() { LinkedList<BluetoothDevice> sorted = getSorted(); if (DBG) log("Rebalancing " + sorted.size() + " headset priorities"); ListIterator<BluetoothDevice> li = sorted.listIterator(sorted.size()); int priority = BluetoothHeadset.PRIORITY_AUTO_CONNECT; while (li.hasPrevious()) { BluetoothDevice device = li.previous(); set(device, priority); priority++; } } /** Get list of headsets sorted by decreasing priority. * Headsets with priority less than AUTO_CONNECT are not included */ public synchronized LinkedList<BluetoothDevice> getSorted() { LinkedList<BluetoothDevice> sorted = new LinkedList<BluetoothDevice>(); HashMap<BluetoothDevice, Integer> toSort = new HashMap<BluetoothDevice, Integer>(mPriority); // add in sorted order. this could be more efficient. while (true) { BluetoothDevice maxDevice = null; int maxPriority = BluetoothHeadset.PRIORITY_AUTO_CONNECT; for (BluetoothDevice device : toSort.keySet()) { int priority = toSort.get(device).intValue(); if (priority >= maxPriority) { maxDevice = device; maxPriority = priority; } } if (maxDevice == null) { break; } sorted.addLast(maxDevice); toSort.remove(maxDevice); } return sorted; } } /** If this property is false, then don't auto-reconnect BT headset */ private static final String DEBUG_AUTO_RECONNECT = "debug.bt.hshfp.auto_reconnect"; private boolean debugDontReconnect() { return (!SystemProperties.getBoolean(DEBUG_AUTO_RECONNECT, true)); } private static void log(String msg) { Log.d(TAG, msg); } }
false
true
public void handleMessage(Message msg) { BluetoothAudioGateway.IncomingConnectionInfo info = (BluetoothAudioGateway.IncomingConnectionInfo)msg.obj; int type = BluetoothHandsfree.TYPE_UNKNOWN; switch(msg.what) { case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION: type = BluetoothHandsfree.TYPE_HEADSET; break; case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION: type = BluetoothHandsfree.TYPE_HANDSFREE; break; } Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) + ") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan); int priority = BluetoothHeadset.PRIORITY_OFF; HeadsetBase headset; try { priority = mBinder.getPriority(info.mRemoteDevice); } catch (RemoteException e) {} if (priority <= BluetoothHeadset.PRIORITY_OFF) { Log.i(TAG, "Rejecting incoming connection because priority = " + priority); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); return; } switch (mState) { case BluetoothHeadset.STATE_DISCONNECTED: // headset connecting us, lets join mRemoteDevice = info.mRemoteDevice; setState(BluetoothHeadset.STATE_CONNECTING); headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget(); break; case BluetoothHeadset.STATE_CONNECTING: if (!info.mRemoteDevice.equals(mRemoteDevice)) { // different headset, ignoring Log.i(TAG, "Already attempting connect to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); } // If we are here, we are in danger of a race condition // incoming rfcomm connection, but we are also attempting an // outgoing connection. Lets try and interrupt the outgoing // connection. Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice + ". Cancel outgoing connection."); if (mConnectThread != null) { mConnectThread.interrupt(); } // Now continue with new connection, including calling callback mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS); mBtHandsfree.connectHeadset(mHeadset, mHeadsetType); // Make sure that old outgoing connect thread is dead. if (mConnectThread != null) { try { // TODO: Don't block in the main thread Log.w(TAG, "Block in main thread to join stale outgoing connection thread"); mConnectThread.join(); } catch (InterruptedException e) { Log.e(TAG, "Connection cancelled twice eh?", e); } mConnectThread = null; } if (DBG) log("Successfully used incoming connection, and cancelled outgoing " + " connection"); break; case BluetoothHeadset.STATE_CONNECTED: Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); break; } }
public void handleMessage(Message msg) { BluetoothAudioGateway.IncomingConnectionInfo info = (BluetoothAudioGateway.IncomingConnectionInfo)msg.obj; int type = BluetoothHandsfree.TYPE_UNKNOWN; switch(msg.what) { case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION: type = BluetoothHandsfree.TYPE_HEADSET; break; case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION: type = BluetoothHandsfree.TYPE_HANDSFREE; break; } Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) + ") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan); int priority = BluetoothHeadset.PRIORITY_OFF; HeadsetBase headset; try { priority = mBinder.getPriority(info.mRemoteDevice); } catch (RemoteException e) {} if (priority <= BluetoothHeadset.PRIORITY_OFF) { Log.i(TAG, "Rejecting incoming connection because priority = " + priority); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); return; } switch (mState) { case BluetoothHeadset.STATE_DISCONNECTED: // headset connecting us, lets join mRemoteDevice = info.mRemoteDevice; setState(BluetoothHeadset.STATE_CONNECTING); headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget(); break; case BluetoothHeadset.STATE_CONNECTING: if (!info.mRemoteDevice.equals(mRemoteDevice)) { // different headset, ignoring Log.i(TAG, "Already attempting connect to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); } // If we are here, we are in danger of a race condition // incoming rfcomm connection, but we are also attempting an // outgoing connection. Lets try and interrupt the outgoing // connection. Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice + ". Cancel outgoing connection."); if (mConnectThread != null) { mConnectThread.interrupt(); mConnectThread = null; } // Now continue with new connection, including calling callback mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler); mHeadsetType = type; setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS); mBtHandsfree.connectHeadset(mHeadset, mHeadsetType); if (DBG) log("Successfully used incoming connection"); break; case BluetoothHeadset.STATE_CONNECTED: Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " + info.mRemoteDevice); headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice, info.mSocketFd, info.mRfcommChan, null); headset.disconnect(); break; } }
diff --git a/src/main/java/freemarker/core/IfBlock.java b/src/main/java/freemarker/core/IfBlock.java index e6ed14d1..7a465a7c 100644 --- a/src/main/java/freemarker/core/IfBlock.java +++ b/src/main/java/freemarker/core/IfBlock.java @@ -1,139 +1,139 @@ /* * Copyright (c) 2003 The Visigoth Software Society. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowledgement: * "This product includes software developed by the * Visigoth Software Society (http://www.visigoths.org/)." * Alternately, this acknowledgement may appear in the software itself, * if and wherever such third-party acknowledgements normally appear. * * 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the * project contributors may 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 "FreeMarker" or "Visigoth" * nor may "FreeMarker" or "Visigoth" appear in their names * without prior written permission of the Visigoth Software Society. * * 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 VISIGOTH SOFTWARE SOCIETY 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 Visigoth Software Society. For more * information on the Visigoth Software Society, please see * http://www.visigoths.org/ */ package freemarker.core; import java.io.IOException; import java.util.ArrayList; import freemarker.template.TemplateException; /** * Container for a group of related #if, #elseif and #else elements. * Each such block is a nested {@link ConditionalBlock}. Note that if an #if has no #else of #elseif, * {@link ConditionalBlock} doesn't need this parent element. */ final class IfBlock extends TemplateElement { IfBlock(ConditionalBlock block) { nestedElements = new ArrayList(); addBlock(block); } void addBlock(ConditionalBlock block) { nestedElements.add(block); } void accept(Environment env) throws TemplateException, IOException { for (int i = 0; i<nestedElements.size(); i++) { ConditionalBlock cblock = (ConditionalBlock) nestedElements.get(i); Expression condition = cblock.condition; env.replaceElemetStackTop(cblock); if (condition == null || condition.evalToBoolean(env)) { if (cblock.nestedBlock != null) { - env.visit(cblock.nestedBlock); + env.visitByHiddingParent(cblock.nestedBlock); } return; } } } TemplateElement postParseCleanup(boolean stripWhitespace) throws ParseException { if (nestedElements.size() == 1) { ConditionalBlock cblock = (ConditionalBlock) nestedElements.get(0); cblock.isLonelyIf = true; cblock.setLocation(getTemplate(), cblock, this); return cblock.postParseCleanup(stripWhitespace); } else { return super.postParseCleanup(stripWhitespace); } } protected String dump(boolean canonical) { if (canonical) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < nestedElements.size(); i++) { ConditionalBlock cblock = (ConditionalBlock) nestedElements.get(i); buf.append(cblock.dump(canonical)); } buf.append("</#if>"); return buf.toString(); } else { return getNodeTypeSymbol(); } } String getNodeTypeSymbol() { return "#if-#elseif-#else-container"; } int getParameterCount() { return 0; } Object getParameterValue(int idx) { throw new IndexOutOfBoundsException(); } ParameterRole getParameterRole(int idx) { throw new IndexOutOfBoundsException(); } boolean isShownInStackTrace() { return false; } }
true
true
void accept(Environment env) throws TemplateException, IOException { for (int i = 0; i<nestedElements.size(); i++) { ConditionalBlock cblock = (ConditionalBlock) nestedElements.get(i); Expression condition = cblock.condition; env.replaceElemetStackTop(cblock); if (condition == null || condition.evalToBoolean(env)) { if (cblock.nestedBlock != null) { env.visit(cblock.nestedBlock); } return; } } }
void accept(Environment env) throws TemplateException, IOException { for (int i = 0; i<nestedElements.size(); i++) { ConditionalBlock cblock = (ConditionalBlock) nestedElements.get(i); Expression condition = cblock.condition; env.replaceElemetStackTop(cblock); if (condition == null || condition.evalToBoolean(env)) { if (cblock.nestedBlock != null) { env.visitByHiddingParent(cblock.nestedBlock); } return; } } }
diff --git a/app/KjcApplet.java b/app/KjcApplet.java index 2b0dc3f87..18b2cad53 100644 --- a/app/KjcApplet.java +++ b/app/KjcApplet.java @@ -1,97 +1,97 @@ // special subclass only used inside the pde environment // while the kjc engine is in use. takes care of error handling. public class KjcApplet extends BApplet { KjcEngine engine; public void setEngine(KjcEngine engine) { this.engine = engine; } public void run() { try { super.run(); } catch (Exception e) { - System.out.println("ex found in run"); - //e.printStackTrace(); + //System.out.println("ex found in run"); + e.printStackTrace(); //engine.error(e); engine.newMessage = true; e.printStackTrace(engine.leechErr); } } } /* public class BAppletViewer implements Runnable { BApplet applet; Thread killer; //int portnum; //Socket umbilical; //OutputStream umbilicalOut; //InputStream umbilicalIn; static public void main(String args[]) { try { //portnum = Integer.parseInt(args[1]); //umbilical = new Socket("localhost", portnum); new BAppletViewer(args[0], Integer.parseInt(args[1]), Integer.parseInt(args[2])); } catch (Exception e) { e.printStackTrace(); } } public BAppletViewer(String name, int x1, int y1) throws Exception { Class c = Class.forName(name); applet = (BApplet) c.newInstance(); applet.init(); applet.start(); Window window = new Window(new Frame()); window.setBounds(x1 - applet.width, y1, applet.width, applet.height); window.add(applet); applet.setBounds(0, 0, applet.width, applet.height); window.show(); applet.requestFocus(); // necessary for key events //umbilical = new Socket("localhost", portnum); //umbilicalOut = umbilical.getOutputStream(); //umbilicalIn = umbilical.getInputStream(); killer = new Thread(this); killer.start(); } File deathNotice = new File("die"); public void run() { //while (Thread.currentThread() == killer) { while (true) { if (deathNotice.exists()) { deathNotice.delete(); System.exit(0); } //try { //System.out.println("testing"); //umbilicalOut.write(100); //umbilicalIn.read(); //} catch (Exception e) { //e.printStackTrace(); //System.exit(0); //} try { Thread.sleep(100); } catch (InterruptedException e) { } } } } */
true
true
public void run() { try { super.run(); } catch (Exception e) { System.out.println("ex found in run"); //e.printStackTrace(); //engine.error(e); engine.newMessage = true; e.printStackTrace(engine.leechErr); } }
public void run() { try { super.run(); } catch (Exception e) { //System.out.println("ex found in run"); e.printStackTrace(); //engine.error(e); engine.newMessage = true; e.printStackTrace(engine.leechErr); } }
diff --git a/tests/dom/dom3/Test.java b/tests/dom/dom3/Test.java index 2fe5196c..c40f24e3 100644 --- a/tests/dom/dom3/Test.java +++ b/tests/dom/dom3/Test.java @@ -1,723 +1,723 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 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 "Xerces" 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, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package dom.dom3; import java.io.Reader; import java.io.StringReader; import org.apache.xerces.dom.CoreDocumentImpl; import org.apache.xerces.dom.DocumentImpl; import org.apache.xerces.dom.NodeImpl; import org.apache.xerces.dom.TextImpl; import org.apache.xerces.dom3.DOMConfiguration; import org.apache.xerces.dom3.DOMError; import org.apache.xerces.dom3.DOMErrorHandler; import org.apache.xerces.dom3.bootstrap.DOMImplementationRegistry; import org.apache.xerces.dom3.DOMLocator; import org.apache.xerces.xs.ElementPSVI; import org.w3c.dom.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.DocumentType; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.w3c.dom.ls.LSParser; import org.w3c.dom.ls.LSResourceResolver; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSSerializer; import dom.util.Assertion; /** * The program tests vacarious DOM Level 3 functionality */ public class Test implements DOMErrorHandler, LSResourceResolver{ static int errorCounter = 0; static DOMErrorHandler errorHandler = new Test(); static LSResourceResolver resolver = new Test(); public static void main( String[] argv) { try { boolean namespaces = true; System.out.println("Running dom.dom3.Test..."); System.setProperty(DOMImplementationRegistry.PROPERTY,"org.apache.xerces.dom.DOMImplementationSourceImpl org.apache.xerces.dom.DOMXSImplementationSourceImpl"); DOMImplementationLS impl = (DOMImplementationLS)DOMImplementationRegistry.newInstance().getDOMImplementation("LS"); Assertion.verify(impl!=null, "domImplementation != null"); LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); LSSerializer writer = impl.createLSSerializer(); - DOMConfiguration config = writer.getConfig(); + DOMConfiguration config = writer.getDomConfig(); config.setParameter("namespaces",(namespaces)?Boolean.TRUE:Boolean.FALSE); config.setParameter("validate",Boolean.FALSE); //---------------------------- // TEST: lookupPrefix // isDefaultNamespace // lookupNamespaceURI //---------------------------- //System.out.println("TEST #1: lookupPrefix, isDefaultNamespace, lookupNamespaceURI, input: tests/dom/dom3/input.xml"); { Document doc = builder.parseURI("tests/dom/dom3/input.xml"); NodeList ls = doc.getElementsByTagName("a:elem_a"); NodeImpl elem = (NodeImpl)ls.item(0); if (namespaces) { //System.out.println("[a:elem_a].lookupPrefix('http://www.example.com', true) == null"); Assertion.verify(elem.lookupPrefix("http://www.example.com").equals("ns1"), "[a:elem_a].lookupPrefix(http://www.example.com)==null"); //System.out.println("[a:elem_a].isDefaultNamespace('http://www.example.com') == true"); Assertion.verify(elem.isDefaultNamespace("http://www.example.com") == true, "[a:elem_a].isDefaultNamespace(http://www.example.com)==true"); //System.out.println("[a:elem_a].lookupPrefix('http://www.example.com', false) == ns1"); Assertion.verify(elem.lookupPrefix("http://www.example.com").equals("ns1"), "[a:elem_a].lookupPrefix(http://www.example.com)==ns1"); Assertion.verify(elem.lookupNamespaceURI("xsi").equals("http://www.w3.org/2001/XMLSchema-instance"), "[a:elem_a].lookupNamespaceURI('xsi') == 'http://www.w3.org/2001/XMLSchema-instance'" ); } else { Assertion.verify( elem.lookupPrefix("http://www.example.com") == null,"lookupPrefix(http://www.example.com)==null"); } ls = doc.getElementsByTagName("bar:leaf"); elem = (NodeImpl)ls.item(0); Assertion.verify(elem.lookupPrefix("url1:").equals("foo"), "[bar:leaf].lookupPrefix('url1:', false) == foo"); //System.out.println("[bar:leaf].lookupPrefix('url1:', false) == "+ ); //System.out.println("==>Create b:baz with namespace 'b:' and xmlns:x='b:'"); ls = doc.getElementsByTagName("baz"); elem = (NodeImpl)ls.item(0); ls = doc.getElementsByTagName("elem8"); elem = (NodeImpl)ls.item(0); Element e1 = doc.createElementNS("b:","p:baz"); e1.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:x", "b:"); elem.appendChild(e1); Assertion.verify(((NodeImpl)e1).lookupPrefix("b:").equals("p"), "[p:baz].lookupPrefix('b:', false) == p"); //System.out.println("[p:baz].lookupPrefix('b:', false) == "+ ((NodeImpl)e1).lookupPrefix("b:",false)); Assertion.verify(elem.lookupNamespaceURI("xsi").equals("http://www.w3.org/2001/XMLSchema-instance"), "[bar:leaf].lookupNamespaceURI('xsi') == 'http://www.w3.org/2001/XMLSchema-instance'" ); } //************************ //* Test normalizeDocument() //************************ //System.out.println("TEST #2: normalizeDocumention() - 3 errors, input: tests/dom/dom3/schema.xml"); { errorCounter = 0; - config = builder.getConfig(); + config = builder.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); DocumentImpl core = (DocumentImpl)builder.parseURI("tests/dom/dom3/schema.xml"); Assertion.verify(errorCounter == 0, "No errors should be reported"); errorCounter = 0; NodeList ls2 = core.getElementsByTagName("decVal"); Element testElem = (Element)ls2.item(0); testElem.removeAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns"); ls2 = core.getElementsByTagName("v02:decVal"); testElem = (Element)ls2.item(0); testElem.setPrefix("myPrefix"); Element root = core.getDocumentElement(); Element newElem = core.createElementNS(null, "decVal"); String data="4.5"; if (true) { data = "string"; } newElem.appendChild(core.createTextNode(data)); root.insertBefore(newElem, testElem); newElem = core.createElementNS(null, "notInSchema"); newElem.appendChild(core.createTextNode("added new element")); root.insertBefore(newElem, testElem); root.appendChild(core.createElementNS("UndefinedNamespace", "NS1:foo")); config = core.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); core.normalizeDocument(); Assertion.verify(errorCounter == 3, "3 errors should be reported"); errorCounter = 0; config.setParameter("validate", Boolean.FALSE); config.setParameter("comments", Boolean.FALSE); core.normalizeDocument(); Assertion.verify(errorCounter == 0, "No errors should be reported"); - config = builder.getConfig(); + config = builder.getDomConfig(); config.setParameter("validate", Boolean.FALSE); } //************************ //* Test normalizeDocument() //************************ // System.out.println("TEST #3: normalizeDocumention() + psvi, input: data/personal-schema.xml"); { errorCounter = 0; - config = builder.getConfig(); + config = builder.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); config.setParameter("psvi", Boolean.TRUE); DocumentImpl core = (DocumentImpl)builder.parseURI("data/personal-schema.xml"); Assertion.verify(errorCounter == 0, "No errors should be reported"); NodeList ls2 = core.getElementsByTagName("person"); Element testElem = (Element)ls2.item(0); Assertion.verify(((ElementPSVI)testElem).getElementDeclaration().getName().equals("person"), "testElem decl"); Element e1 = core.createElementNS(null, "person"); core.getDocumentElement().appendChild(e1); e1.setAttributeNS(null, "id", "newEmp"); Element e2 = core.createElementNS(null, "name"); e2.appendChild(core.createElementNS(null, "family")); e2.appendChild(core.createElementNS(null, "given")); e1.appendChild(e2); e1.appendChild(core.createElementNS(null, "email")); Element e3 = core.createElementNS(null, "link"); e3.setAttributeNS(null, "manager", "Big.Boss"); e1.appendChild(e3); testElem.removeAttributeNode(testElem.getAttributeNodeNS(null, "contr")); NamedNodeMap map = testElem.getAttributes(); config = core.getDomConfig(); errorCounter = 0; config.setParameter("psvi", Boolean.TRUE); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); core.normalizeDocument(); Assertion.verify(errorCounter == 0, "No errors should be reported"); Assertion.verify(((ElementPSVI)e1).getElementDeclaration().getName().equals("person"), "e1 decl"); - config = builder.getConfig(); + config = builder.getDomConfig(); config.setParameter("validate", Boolean.FALSE); } //************************ //* Test normalizeDocument(): core tests //************************ // System.out.println("TEST #4: normalizeDocument() core"); { // check that namespace normalization algorithm works correctly Document doc= new DocumentImpl(); Element root = doc.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:stylesheet"); doc.appendChild(root); root.setAttributeNS("http://attr1", "xsl:attr1",""); Element child1 = doc.createElementNS("http://child1", "NS2:child1"); child1.setAttributeNS("http://attr2", "NS2:attr2",""); root.appendChild(child1); Element child2 = doc.createElementNS("http://child2","NS4:child2"); child2.setAttributeNS("http://attr3","attr3", ""); root.appendChild(child2); Element child3 = doc.createElementNS("http://www.w3.org/1999/XSL/Transform","xsl:child3"); child3.setAttributeNS("http://a1","attr1", ""); child3.setAttributeNS("http://a2","xsl:attr2", ""); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:a1", "http://a1"); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", "http://a2"); Element child4 = doc.createElementNS(null, "child4"); child4.setAttributeNS("http://a1", "xsl:attr1", ""); child4.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "default"); child3.appendChild(child4); root.appendChild(child3); ((CoreDocumentImpl)doc).normalizeDocument(); // // assertions // // xsl:stylesheet should include 2 namespace declarations String name = root.getNodeName(); Assertion.verify(name.equals("xsl:stylesheet"), "xsl:stylesheet"); String value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null, "xmlns:xsl != null"); Assertion.verify(value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr1"), "xmlns:NS1="+value); // child includes 2 namespace decls Assertion.verify(child1.getNodeName().equals("NS2:child1"), "NS2:child1"); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS2"); Assertion.verify(value!=null && value.equals("http://child1"), "xmlns:NS2="+value); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr2"), "xmlns:NS1="+value); // child3 Assertion.verify(child3.getNodeName().equals("xsl:child3"), "xsl:child3"); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://a2"), "xmlns:NS1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "a1"); Assertion.verify(value!=null && value.equals("http://a1"), "xmlns:a1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null && value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); Attr attr = child3.getAttributeNodeNS("http://a2", "attr2"); Assertion.verify(attr != null, "NS1:attr2 !=null"); Assertion.verify(child3.getAttributes().getLength() == 5, "xsl:child3 has 5 attrs"); // child 4 Attr temp = child4.getAttributeNodeNS("http://www.w3.org/2000/xmlns/", "xmlns"); Assertion.verify(temp.getNodeName().equals("xmlns"), "attribute name is xmlns"); Assertion.verify(temp.getNodeValue().length() == 0, "xmlns=''"); /* OutputFormat format = new OutputFormat((Document)doc); format.setLineSeparator(LineSeparator.Windows); format.setIndenting(true); format.setLineWidth(0); format.setPreserveSpace(true); XMLSerializer serializer = new XMLSerializer(System.out, format); serializer.serialize(doc); */ } //************************ //* Test normalizeDocument(): core tests //************************ //System.out.println("TEST #4: namespace fixup during serialization"); { Document doc= new DocumentImpl(); Element root = doc.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:stylesheet"); doc.appendChild(root); root.setAttributeNS("http://attr1", "xsl:attr1",""); Element child1 = doc.createElementNS("http://child1", "NS2:child1"); child1.setAttributeNS("http://attr2", "NS2:attr2",""); root.appendChild(child1); Element child2 = doc.createElementNS("http://child2","NS4:child2"); child2.setAttributeNS("http://attr3","attr3", ""); root.appendChild(child2); Element child3 = doc.createElementNS("http://www.w3.org/1999/XSL/Transform","xsl:child3"); child3.setAttributeNS("http://a1","attr1", ""); child3.setAttributeNS("http://a2","xsl:attr2", ""); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:a1", "http://a1"); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", "http://a2"); Element child4 = doc.createElementNS(null, "child4"); child4.setAttributeNS("http://a1", "xsl:attr1", ""); child4.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "default"); child3.appendChild(child4); root.appendChild(child3); // serialize data - writer.getConfig().setParameter("namespaces", Boolean.TRUE); + writer.getDomConfig().setParameter("namespaces", Boolean.TRUE); String xmlData = writer.writeToString(doc); Reader r = new StringReader(xmlData); LSInput in = impl.createLSInput(); in.setCharacterStream(r); doc = builder.parse(in); // // make sure algorithm works correctly // root = doc.getDocumentElement(); child1 = (Element)root.getFirstChild(); child2 = (Element)child1.getNextSibling(); child3 = (Element)child2.getNextSibling(); // xsl:stylesheet should include 2 namespace declarations String name = root.getNodeName(); Assertion.verify(name.equals("xsl:stylesheet"), "xsl:stylesheet"); String value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null, "xmlns:xsl != null"); Assertion.verify(value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr1"), "xmlns:NS1="+value); // child includes 2 namespace decls Assertion.verify(child1.getNodeName().equals("NS2:child1"), "NS2:child1"); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS2"); Assertion.verify(value!=null && value.equals("http://child1"), "xmlns:NS2="+value); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr2"), "xmlns:NS1="+value); // child3 Assertion.verify(child3.getNodeName().equals("xsl:child3"), "xsl:child3"); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://a2"), "xmlns:NS1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "a1"); Assertion.verify(value!=null && value.equals("http://a1"), "xmlns:a1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null && value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); Attr attr = child3.getAttributeNodeNS("http://a2", "attr2"); Assertion.verify(attr != null, "NS6:attr2 !=null"); Assertion.verify(child3.getAttributes().getLength() == 5, "xsl:child3 has 5 attrs"); //OutputFormat format = new OutputFormat((Document)doc); //format.setLineSeparator(LineSeparator.Windows); //format.setIndenting(true); //format.setLineWidth(0); //format.setPreserveSpace(true); //XMLSerializer serializer = new XMLSerializer(System.out, format); //serializer.serialize(doc); } //************************ // TEST: replaceWholeText() // getWholeText() // //************************ //System.out.println("TEST #5: wholeText, input: tests/dom/dom3/wholeText.xml"); { - config = builder.getConfig(); + config = builder.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.FALSE); config.setParameter("entities", Boolean.TRUE); DocumentImpl doc = (DocumentImpl)builder.parseURI("tests/dom/dom3/wholeText.xml"); Element root = doc.getDocumentElement(); Element test = (Element)doc.getElementsByTagName("elem").item(0); test.appendChild(doc.createTextNode("Address: ")); test.appendChild(doc.createEntityReference("ent2")); test.appendChild(doc.createTextNode("City: ")); test.appendChild(doc.createEntityReference("ent1")); DocumentType doctype = doc.getDoctype(); Node entity = doctype.getEntities().getNamedItem("ent3"); NodeList ls = test.getChildNodes(); Assertion.verify(ls.getLength()==5, "List length"); String compare1 = "Home Address: 1900 Dallas Road (East) City: Dallas. California. USA PO #5668"; Assertion.verify(((TextImpl)ls.item(0)).getWholeText().equals(compare1), "Compare1"); String compare2 = "Address: 1900 Dallas Road (East) City: Dallas. California. USA PO #5668"; Assertion.verify(((TextImpl)ls.item(1)).getWholeText().equals(compare2), "Compare2"); //TEST replaceWholeText() ((NodeImpl)ls.item(0)).setReadOnly(true, true); TextImpl original = (TextImpl)ls.item(0); Node newNode = original.replaceWholeText("Replace with this text"); ls = test.getChildNodes(); Assertion.verify(ls.getLength() == 1, "Length == 1"); Assertion.verify(ls.item(0).getNodeValue().equals("Replace with this text"), "Replacement works"); Assertion.verify(newNode != original, "New node created"); // replace text for node which is not yet attached to the tree Text text = doc.createTextNode("readonly"); ((NodeImpl)text).setReadOnly(true, true); text = ((TextImpl)text).replaceWholeText("Data"); Assertion.verify(text.getNodeValue().equals("Data"), "New value 'Data'"); // test with second child that does not have any content test = (Element)doc.getElementsByTagName("elem").item(1); try { ((TextImpl)test.getFirstChild()).replaceWholeText("can't replace"); } catch (DOMException e){ Assertion.verify(e !=null); } String compare3 = "Test: The Content ends here. "; //Assertion.assert(((Text)test.getFirstChild()).getWholeText().equals(compare3), "Compare3"); } //************************ // TEST: schema-type // schema-location // //************************ { errorCounter = 0; - config = builder.getConfig(); + config = builder.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("resource-resolver",resolver); config.setParameter("validate", Boolean.TRUE); config.setParameter("psvi", Boolean.TRUE); // schema-type is not set validate against both grammars errorCounter = 0; DocumentImpl core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both-error.xml"); Assertion.verify(errorCounter == 4, "4 errors should be reported"); errorCounter = 0; // set schema-type to be XML Schema config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema"); // test parsing a file that has both XML schema and DTD core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both.xml"); Assertion.verify(errorCounter == 0, "No errors should be reported"); // parse a file with XML schema and DTD but validate against DTD only errorCounter = 0; config.setParameter("schema-type","http://www.w3.org/TR/REC-xml"); core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both-error.xml"); Assertion.verify(errorCounter == 3, "3 errors should be reported"); // parse a file with DTD only but set schema-location and // validate against XML Schema // set schema location core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both-error.xml"); // normalize document errorCounter = 0; Element root = core2.getDocumentElement(); root.removeAttributeNS("http://www.w3.org/2001/XMLSchema", "xsi"); root.removeAttributeNS("http://www.w3.org/2001/XMLSchema", "noNamespaceSchemaLocation"); config = core2.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema"); config.setParameter("schema-location","personal.xsd"); config.setParameter("resource-resolver",resolver); config.setParameter("validate", Boolean.TRUE); core2.normalizeDocument(); Assertion.verify(errorCounter == 1, "1 error should be reported: "+errorCounter); } // baseURI tests { LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); Document doc = parser.parseURI("tests/dom/dom3/baseURI.xml"); Element root = doc.getDocumentElement(); NodeList ls = doc.getElementsByTagNameNS(null, "streetNum"); Node e = ls.item(0); Assertion.verify(((NodeImpl)e).getBaseURI().endsWith("tests/dom/dom3/baseURI.xml"), "baseURI=tests/dom/dom3/baseURI.xml"); ls = root.getElementsByTagNameNS(null, "header"); Node p2 = ls.item(0); Assertion.verify(((NodeImpl)p2).getBaseURI().equals("http://paragraph.com"), "baseURI=http://paragraph.com"); p2 = ls.item(1); Assertion.verify(((NodeImpl)p2).getBaseURI().equals("http://paragraph.com2"), "baseURI=http://paragraph.com2"); } } catch ( Exception ex ) { ex.printStackTrace(); } System.out.println("done!"); } StringBuffer fError = new StringBuffer(); public boolean handleError(DOMError error){ fError.setLength(0); short severity = error.getSeverity(); if (severity == error.SEVERITY_ERROR) { errorCounter++; fError.append("[Error]"); } if (severity == error.SEVERITY_FATAL_ERROR) { fError.append("[FatalError]"); } if (severity == error.SEVERITY_WARNING) { fError.append("[Warning]"); } DOMLocator locator = error.getLocation(); if (locator != null) { // line:colon:offset fError.append(locator.getLineNumber()); fError.append(":"); fError.append(locator.getColumnNumber()); fError.append(":"); fError.append(locator.getByteOffset()); Node node = locator.getRelatedNode(); if (node != null) { fError.append("["); fError.append(locator.getRelatedNode().getNodeName()); fError.append("]"); } String systemId = locator.getUri(); if (systemId != null) { int index = systemId.lastIndexOf('/'); if (index != -1) systemId = systemId.substring(index + 1); fError.append(":"); fError.append(systemId); } fError.append(": "); fError.append(error.getMessage()); } //System.out.println(fError.toString()); return true; } /** * @see org.w3c.dom.ls.DOMEntityResolver#resolveEntity(String, String, String, String, String) */ public LSInput resolveResource(String type, String namespace, String publicId, String systemId, String baseURI) { try { DOMImplementationLS impl = (DOMImplementationLS) DOMImplementationRegistry.newInstance().getDOMImplementation( "LS"); LSInput source = impl.createLSInput(); if (systemId.equals("personal.xsd")) { source.setSystemId("data/personal.xsd"); } else { source.setSystemId("data/personal.dtd"); } return source; } catch (Exception e) { return null; } } }
false
true
public static void main( String[] argv) { try { boolean namespaces = true; System.out.println("Running dom.dom3.Test..."); System.setProperty(DOMImplementationRegistry.PROPERTY,"org.apache.xerces.dom.DOMImplementationSourceImpl org.apache.xerces.dom.DOMXSImplementationSourceImpl"); DOMImplementationLS impl = (DOMImplementationLS)DOMImplementationRegistry.newInstance().getDOMImplementation("LS"); Assertion.verify(impl!=null, "domImplementation != null"); LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); LSSerializer writer = impl.createLSSerializer(); DOMConfiguration config = writer.getConfig(); config.setParameter("namespaces",(namespaces)?Boolean.TRUE:Boolean.FALSE); config.setParameter("validate",Boolean.FALSE); //---------------------------- // TEST: lookupPrefix // isDefaultNamespace // lookupNamespaceURI //---------------------------- //System.out.println("TEST #1: lookupPrefix, isDefaultNamespace, lookupNamespaceURI, input: tests/dom/dom3/input.xml"); { Document doc = builder.parseURI("tests/dom/dom3/input.xml"); NodeList ls = doc.getElementsByTagName("a:elem_a"); NodeImpl elem = (NodeImpl)ls.item(0); if (namespaces) { //System.out.println("[a:elem_a].lookupPrefix('http://www.example.com', true) == null"); Assertion.verify(elem.lookupPrefix("http://www.example.com").equals("ns1"), "[a:elem_a].lookupPrefix(http://www.example.com)==null"); //System.out.println("[a:elem_a].isDefaultNamespace('http://www.example.com') == true"); Assertion.verify(elem.isDefaultNamespace("http://www.example.com") == true, "[a:elem_a].isDefaultNamespace(http://www.example.com)==true"); //System.out.println("[a:elem_a].lookupPrefix('http://www.example.com', false) == ns1"); Assertion.verify(elem.lookupPrefix("http://www.example.com").equals("ns1"), "[a:elem_a].lookupPrefix(http://www.example.com)==ns1"); Assertion.verify(elem.lookupNamespaceURI("xsi").equals("http://www.w3.org/2001/XMLSchema-instance"), "[a:elem_a].lookupNamespaceURI('xsi') == 'http://www.w3.org/2001/XMLSchema-instance'" ); } else { Assertion.verify( elem.lookupPrefix("http://www.example.com") == null,"lookupPrefix(http://www.example.com)==null"); } ls = doc.getElementsByTagName("bar:leaf"); elem = (NodeImpl)ls.item(0); Assertion.verify(elem.lookupPrefix("url1:").equals("foo"), "[bar:leaf].lookupPrefix('url1:', false) == foo"); //System.out.println("[bar:leaf].lookupPrefix('url1:', false) == "+ ); //System.out.println("==>Create b:baz with namespace 'b:' and xmlns:x='b:'"); ls = doc.getElementsByTagName("baz"); elem = (NodeImpl)ls.item(0); ls = doc.getElementsByTagName("elem8"); elem = (NodeImpl)ls.item(0); Element e1 = doc.createElementNS("b:","p:baz"); e1.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:x", "b:"); elem.appendChild(e1); Assertion.verify(((NodeImpl)e1).lookupPrefix("b:").equals("p"), "[p:baz].lookupPrefix('b:', false) == p"); //System.out.println("[p:baz].lookupPrefix('b:', false) == "+ ((NodeImpl)e1).lookupPrefix("b:",false)); Assertion.verify(elem.lookupNamespaceURI("xsi").equals("http://www.w3.org/2001/XMLSchema-instance"), "[bar:leaf].lookupNamespaceURI('xsi') == 'http://www.w3.org/2001/XMLSchema-instance'" ); } //************************ //* Test normalizeDocument() //************************ //System.out.println("TEST #2: normalizeDocumention() - 3 errors, input: tests/dom/dom3/schema.xml"); { errorCounter = 0; config = builder.getConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); DocumentImpl core = (DocumentImpl)builder.parseURI("tests/dom/dom3/schema.xml"); Assertion.verify(errorCounter == 0, "No errors should be reported"); errorCounter = 0; NodeList ls2 = core.getElementsByTagName("decVal"); Element testElem = (Element)ls2.item(0); testElem.removeAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns"); ls2 = core.getElementsByTagName("v02:decVal"); testElem = (Element)ls2.item(0); testElem.setPrefix("myPrefix"); Element root = core.getDocumentElement(); Element newElem = core.createElementNS(null, "decVal"); String data="4.5"; if (true) { data = "string"; } newElem.appendChild(core.createTextNode(data)); root.insertBefore(newElem, testElem); newElem = core.createElementNS(null, "notInSchema"); newElem.appendChild(core.createTextNode("added new element")); root.insertBefore(newElem, testElem); root.appendChild(core.createElementNS("UndefinedNamespace", "NS1:foo")); config = core.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); core.normalizeDocument(); Assertion.verify(errorCounter == 3, "3 errors should be reported"); errorCounter = 0; config.setParameter("validate", Boolean.FALSE); config.setParameter("comments", Boolean.FALSE); core.normalizeDocument(); Assertion.verify(errorCounter == 0, "No errors should be reported"); config = builder.getConfig(); config.setParameter("validate", Boolean.FALSE); } //************************ //* Test normalizeDocument() //************************ // System.out.println("TEST #3: normalizeDocumention() + psvi, input: data/personal-schema.xml"); { errorCounter = 0; config = builder.getConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); config.setParameter("psvi", Boolean.TRUE); DocumentImpl core = (DocumentImpl)builder.parseURI("data/personal-schema.xml"); Assertion.verify(errorCounter == 0, "No errors should be reported"); NodeList ls2 = core.getElementsByTagName("person"); Element testElem = (Element)ls2.item(0); Assertion.verify(((ElementPSVI)testElem).getElementDeclaration().getName().equals("person"), "testElem decl"); Element e1 = core.createElementNS(null, "person"); core.getDocumentElement().appendChild(e1); e1.setAttributeNS(null, "id", "newEmp"); Element e2 = core.createElementNS(null, "name"); e2.appendChild(core.createElementNS(null, "family")); e2.appendChild(core.createElementNS(null, "given")); e1.appendChild(e2); e1.appendChild(core.createElementNS(null, "email")); Element e3 = core.createElementNS(null, "link"); e3.setAttributeNS(null, "manager", "Big.Boss"); e1.appendChild(e3); testElem.removeAttributeNode(testElem.getAttributeNodeNS(null, "contr")); NamedNodeMap map = testElem.getAttributes(); config = core.getDomConfig(); errorCounter = 0; config.setParameter("psvi", Boolean.TRUE); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); core.normalizeDocument(); Assertion.verify(errorCounter == 0, "No errors should be reported"); Assertion.verify(((ElementPSVI)e1).getElementDeclaration().getName().equals("person"), "e1 decl"); config = builder.getConfig(); config.setParameter("validate", Boolean.FALSE); } //************************ //* Test normalizeDocument(): core tests //************************ // System.out.println("TEST #4: normalizeDocument() core"); { // check that namespace normalization algorithm works correctly Document doc= new DocumentImpl(); Element root = doc.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:stylesheet"); doc.appendChild(root); root.setAttributeNS("http://attr1", "xsl:attr1",""); Element child1 = doc.createElementNS("http://child1", "NS2:child1"); child1.setAttributeNS("http://attr2", "NS2:attr2",""); root.appendChild(child1); Element child2 = doc.createElementNS("http://child2","NS4:child2"); child2.setAttributeNS("http://attr3","attr3", ""); root.appendChild(child2); Element child3 = doc.createElementNS("http://www.w3.org/1999/XSL/Transform","xsl:child3"); child3.setAttributeNS("http://a1","attr1", ""); child3.setAttributeNS("http://a2","xsl:attr2", ""); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:a1", "http://a1"); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", "http://a2"); Element child4 = doc.createElementNS(null, "child4"); child4.setAttributeNS("http://a1", "xsl:attr1", ""); child4.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "default"); child3.appendChild(child4); root.appendChild(child3); ((CoreDocumentImpl)doc).normalizeDocument(); // // assertions // // xsl:stylesheet should include 2 namespace declarations String name = root.getNodeName(); Assertion.verify(name.equals("xsl:stylesheet"), "xsl:stylesheet"); String value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null, "xmlns:xsl != null"); Assertion.verify(value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr1"), "xmlns:NS1="+value); // child includes 2 namespace decls Assertion.verify(child1.getNodeName().equals("NS2:child1"), "NS2:child1"); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS2"); Assertion.verify(value!=null && value.equals("http://child1"), "xmlns:NS2="+value); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr2"), "xmlns:NS1="+value); // child3 Assertion.verify(child3.getNodeName().equals("xsl:child3"), "xsl:child3"); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://a2"), "xmlns:NS1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "a1"); Assertion.verify(value!=null && value.equals("http://a1"), "xmlns:a1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null && value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); Attr attr = child3.getAttributeNodeNS("http://a2", "attr2"); Assertion.verify(attr != null, "NS1:attr2 !=null"); Assertion.verify(child3.getAttributes().getLength() == 5, "xsl:child3 has 5 attrs"); // child 4 Attr temp = child4.getAttributeNodeNS("http://www.w3.org/2000/xmlns/", "xmlns"); Assertion.verify(temp.getNodeName().equals("xmlns"), "attribute name is xmlns"); Assertion.verify(temp.getNodeValue().length() == 0, "xmlns=''"); /* OutputFormat format = new OutputFormat((Document)doc); format.setLineSeparator(LineSeparator.Windows); format.setIndenting(true); format.setLineWidth(0); format.setPreserveSpace(true); XMLSerializer serializer = new XMLSerializer(System.out, format); serializer.serialize(doc); */ } //************************ //* Test normalizeDocument(): core tests //************************ //System.out.println("TEST #4: namespace fixup during serialization"); { Document doc= new DocumentImpl(); Element root = doc.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:stylesheet"); doc.appendChild(root); root.setAttributeNS("http://attr1", "xsl:attr1",""); Element child1 = doc.createElementNS("http://child1", "NS2:child1"); child1.setAttributeNS("http://attr2", "NS2:attr2",""); root.appendChild(child1); Element child2 = doc.createElementNS("http://child2","NS4:child2"); child2.setAttributeNS("http://attr3","attr3", ""); root.appendChild(child2); Element child3 = doc.createElementNS("http://www.w3.org/1999/XSL/Transform","xsl:child3"); child3.setAttributeNS("http://a1","attr1", ""); child3.setAttributeNS("http://a2","xsl:attr2", ""); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:a1", "http://a1"); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", "http://a2"); Element child4 = doc.createElementNS(null, "child4"); child4.setAttributeNS("http://a1", "xsl:attr1", ""); child4.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "default"); child3.appendChild(child4); root.appendChild(child3); // serialize data writer.getConfig().setParameter("namespaces", Boolean.TRUE); String xmlData = writer.writeToString(doc); Reader r = new StringReader(xmlData); LSInput in = impl.createLSInput(); in.setCharacterStream(r); doc = builder.parse(in); // // make sure algorithm works correctly // root = doc.getDocumentElement(); child1 = (Element)root.getFirstChild(); child2 = (Element)child1.getNextSibling(); child3 = (Element)child2.getNextSibling(); // xsl:stylesheet should include 2 namespace declarations String name = root.getNodeName(); Assertion.verify(name.equals("xsl:stylesheet"), "xsl:stylesheet"); String value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null, "xmlns:xsl != null"); Assertion.verify(value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr1"), "xmlns:NS1="+value); // child includes 2 namespace decls Assertion.verify(child1.getNodeName().equals("NS2:child1"), "NS2:child1"); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS2"); Assertion.verify(value!=null && value.equals("http://child1"), "xmlns:NS2="+value); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr2"), "xmlns:NS1="+value); // child3 Assertion.verify(child3.getNodeName().equals("xsl:child3"), "xsl:child3"); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://a2"), "xmlns:NS1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "a1"); Assertion.verify(value!=null && value.equals("http://a1"), "xmlns:a1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null && value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); Attr attr = child3.getAttributeNodeNS("http://a2", "attr2"); Assertion.verify(attr != null, "NS6:attr2 !=null"); Assertion.verify(child3.getAttributes().getLength() == 5, "xsl:child3 has 5 attrs"); //OutputFormat format = new OutputFormat((Document)doc); //format.setLineSeparator(LineSeparator.Windows); //format.setIndenting(true); //format.setLineWidth(0); //format.setPreserveSpace(true); //XMLSerializer serializer = new XMLSerializer(System.out, format); //serializer.serialize(doc); } //************************ // TEST: replaceWholeText() // getWholeText() // //************************ //System.out.println("TEST #5: wholeText, input: tests/dom/dom3/wholeText.xml"); { config = builder.getConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.FALSE); config.setParameter("entities", Boolean.TRUE); DocumentImpl doc = (DocumentImpl)builder.parseURI("tests/dom/dom3/wholeText.xml"); Element root = doc.getDocumentElement(); Element test = (Element)doc.getElementsByTagName("elem").item(0); test.appendChild(doc.createTextNode("Address: ")); test.appendChild(doc.createEntityReference("ent2")); test.appendChild(doc.createTextNode("City: ")); test.appendChild(doc.createEntityReference("ent1")); DocumentType doctype = doc.getDoctype(); Node entity = doctype.getEntities().getNamedItem("ent3"); NodeList ls = test.getChildNodes(); Assertion.verify(ls.getLength()==5, "List length"); String compare1 = "Home Address: 1900 Dallas Road (East) City: Dallas. California. USA PO #5668"; Assertion.verify(((TextImpl)ls.item(0)).getWholeText().equals(compare1), "Compare1"); String compare2 = "Address: 1900 Dallas Road (East) City: Dallas. California. USA PO #5668"; Assertion.verify(((TextImpl)ls.item(1)).getWholeText().equals(compare2), "Compare2"); //TEST replaceWholeText() ((NodeImpl)ls.item(0)).setReadOnly(true, true); TextImpl original = (TextImpl)ls.item(0); Node newNode = original.replaceWholeText("Replace with this text"); ls = test.getChildNodes(); Assertion.verify(ls.getLength() == 1, "Length == 1"); Assertion.verify(ls.item(0).getNodeValue().equals("Replace with this text"), "Replacement works"); Assertion.verify(newNode != original, "New node created"); // replace text for node which is not yet attached to the tree Text text = doc.createTextNode("readonly"); ((NodeImpl)text).setReadOnly(true, true); text = ((TextImpl)text).replaceWholeText("Data"); Assertion.verify(text.getNodeValue().equals("Data"), "New value 'Data'"); // test with second child that does not have any content test = (Element)doc.getElementsByTagName("elem").item(1); try { ((TextImpl)test.getFirstChild()).replaceWholeText("can't replace"); } catch (DOMException e){ Assertion.verify(e !=null); } String compare3 = "Test: The Content ends here. "; //Assertion.assert(((Text)test.getFirstChild()).getWholeText().equals(compare3), "Compare3"); } //************************ // TEST: schema-type // schema-location // //************************ { errorCounter = 0; config = builder.getConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("resource-resolver",resolver); config.setParameter("validate", Boolean.TRUE); config.setParameter("psvi", Boolean.TRUE); // schema-type is not set validate against both grammars errorCounter = 0; DocumentImpl core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both-error.xml"); Assertion.verify(errorCounter == 4, "4 errors should be reported"); errorCounter = 0; // set schema-type to be XML Schema config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema"); // test parsing a file that has both XML schema and DTD core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both.xml"); Assertion.verify(errorCounter == 0, "No errors should be reported"); // parse a file with XML schema and DTD but validate against DTD only errorCounter = 0; config.setParameter("schema-type","http://www.w3.org/TR/REC-xml"); core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both-error.xml"); Assertion.verify(errorCounter == 3, "3 errors should be reported"); // parse a file with DTD only but set schema-location and // validate against XML Schema // set schema location core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both-error.xml"); // normalize document errorCounter = 0; Element root = core2.getDocumentElement(); root.removeAttributeNS("http://www.w3.org/2001/XMLSchema", "xsi"); root.removeAttributeNS("http://www.w3.org/2001/XMLSchema", "noNamespaceSchemaLocation"); config = core2.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema"); config.setParameter("schema-location","personal.xsd"); config.setParameter("resource-resolver",resolver); config.setParameter("validate", Boolean.TRUE); core2.normalizeDocument(); Assertion.verify(errorCounter == 1, "1 error should be reported: "+errorCounter); } // baseURI tests { LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); Document doc = parser.parseURI("tests/dom/dom3/baseURI.xml"); Element root = doc.getDocumentElement(); NodeList ls = doc.getElementsByTagNameNS(null, "streetNum"); Node e = ls.item(0); Assertion.verify(((NodeImpl)e).getBaseURI().endsWith("tests/dom/dom3/baseURI.xml"), "baseURI=tests/dom/dom3/baseURI.xml"); ls = root.getElementsByTagNameNS(null, "header"); Node p2 = ls.item(0); Assertion.verify(((NodeImpl)p2).getBaseURI().equals("http://paragraph.com"), "baseURI=http://paragraph.com"); p2 = ls.item(1); Assertion.verify(((NodeImpl)p2).getBaseURI().equals("http://paragraph.com2"), "baseURI=http://paragraph.com2"); } } catch ( Exception ex ) { ex.printStackTrace(); } System.out.println("done!"); }
public static void main( String[] argv) { try { boolean namespaces = true; System.out.println("Running dom.dom3.Test..."); System.setProperty(DOMImplementationRegistry.PROPERTY,"org.apache.xerces.dom.DOMImplementationSourceImpl org.apache.xerces.dom.DOMXSImplementationSourceImpl"); DOMImplementationLS impl = (DOMImplementationLS)DOMImplementationRegistry.newInstance().getDOMImplementation("LS"); Assertion.verify(impl!=null, "domImplementation != null"); LSParser builder = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); LSSerializer writer = impl.createLSSerializer(); DOMConfiguration config = writer.getDomConfig(); config.setParameter("namespaces",(namespaces)?Boolean.TRUE:Boolean.FALSE); config.setParameter("validate",Boolean.FALSE); //---------------------------- // TEST: lookupPrefix // isDefaultNamespace // lookupNamespaceURI //---------------------------- //System.out.println("TEST #1: lookupPrefix, isDefaultNamespace, lookupNamespaceURI, input: tests/dom/dom3/input.xml"); { Document doc = builder.parseURI("tests/dom/dom3/input.xml"); NodeList ls = doc.getElementsByTagName("a:elem_a"); NodeImpl elem = (NodeImpl)ls.item(0); if (namespaces) { //System.out.println("[a:elem_a].lookupPrefix('http://www.example.com', true) == null"); Assertion.verify(elem.lookupPrefix("http://www.example.com").equals("ns1"), "[a:elem_a].lookupPrefix(http://www.example.com)==null"); //System.out.println("[a:elem_a].isDefaultNamespace('http://www.example.com') == true"); Assertion.verify(elem.isDefaultNamespace("http://www.example.com") == true, "[a:elem_a].isDefaultNamespace(http://www.example.com)==true"); //System.out.println("[a:elem_a].lookupPrefix('http://www.example.com', false) == ns1"); Assertion.verify(elem.lookupPrefix("http://www.example.com").equals("ns1"), "[a:elem_a].lookupPrefix(http://www.example.com)==ns1"); Assertion.verify(elem.lookupNamespaceURI("xsi").equals("http://www.w3.org/2001/XMLSchema-instance"), "[a:elem_a].lookupNamespaceURI('xsi') == 'http://www.w3.org/2001/XMLSchema-instance'" ); } else { Assertion.verify( elem.lookupPrefix("http://www.example.com") == null,"lookupPrefix(http://www.example.com)==null"); } ls = doc.getElementsByTagName("bar:leaf"); elem = (NodeImpl)ls.item(0); Assertion.verify(elem.lookupPrefix("url1:").equals("foo"), "[bar:leaf].lookupPrefix('url1:', false) == foo"); //System.out.println("[bar:leaf].lookupPrefix('url1:', false) == "+ ); //System.out.println("==>Create b:baz with namespace 'b:' and xmlns:x='b:'"); ls = doc.getElementsByTagName("baz"); elem = (NodeImpl)ls.item(0); ls = doc.getElementsByTagName("elem8"); elem = (NodeImpl)ls.item(0); Element e1 = doc.createElementNS("b:","p:baz"); e1.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:x", "b:"); elem.appendChild(e1); Assertion.verify(((NodeImpl)e1).lookupPrefix("b:").equals("p"), "[p:baz].lookupPrefix('b:', false) == p"); //System.out.println("[p:baz].lookupPrefix('b:', false) == "+ ((NodeImpl)e1).lookupPrefix("b:",false)); Assertion.verify(elem.lookupNamespaceURI("xsi").equals("http://www.w3.org/2001/XMLSchema-instance"), "[bar:leaf].lookupNamespaceURI('xsi') == 'http://www.w3.org/2001/XMLSchema-instance'" ); } //************************ //* Test normalizeDocument() //************************ //System.out.println("TEST #2: normalizeDocumention() - 3 errors, input: tests/dom/dom3/schema.xml"); { errorCounter = 0; config = builder.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); DocumentImpl core = (DocumentImpl)builder.parseURI("tests/dom/dom3/schema.xml"); Assertion.verify(errorCounter == 0, "No errors should be reported"); errorCounter = 0; NodeList ls2 = core.getElementsByTagName("decVal"); Element testElem = (Element)ls2.item(0); testElem.removeAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns"); ls2 = core.getElementsByTagName("v02:decVal"); testElem = (Element)ls2.item(0); testElem.setPrefix("myPrefix"); Element root = core.getDocumentElement(); Element newElem = core.createElementNS(null, "decVal"); String data="4.5"; if (true) { data = "string"; } newElem.appendChild(core.createTextNode(data)); root.insertBefore(newElem, testElem); newElem = core.createElementNS(null, "notInSchema"); newElem.appendChild(core.createTextNode("added new element")); root.insertBefore(newElem, testElem); root.appendChild(core.createElementNS("UndefinedNamespace", "NS1:foo")); config = core.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); core.normalizeDocument(); Assertion.verify(errorCounter == 3, "3 errors should be reported"); errorCounter = 0; config.setParameter("validate", Boolean.FALSE); config.setParameter("comments", Boolean.FALSE); core.normalizeDocument(); Assertion.verify(errorCounter == 0, "No errors should be reported"); config = builder.getDomConfig(); config.setParameter("validate", Boolean.FALSE); } //************************ //* Test normalizeDocument() //************************ // System.out.println("TEST #3: normalizeDocumention() + psvi, input: data/personal-schema.xml"); { errorCounter = 0; config = builder.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); config.setParameter("psvi", Boolean.TRUE); DocumentImpl core = (DocumentImpl)builder.parseURI("data/personal-schema.xml"); Assertion.verify(errorCounter == 0, "No errors should be reported"); NodeList ls2 = core.getElementsByTagName("person"); Element testElem = (Element)ls2.item(0); Assertion.verify(((ElementPSVI)testElem).getElementDeclaration().getName().equals("person"), "testElem decl"); Element e1 = core.createElementNS(null, "person"); core.getDocumentElement().appendChild(e1); e1.setAttributeNS(null, "id", "newEmp"); Element e2 = core.createElementNS(null, "name"); e2.appendChild(core.createElementNS(null, "family")); e2.appendChild(core.createElementNS(null, "given")); e1.appendChild(e2); e1.appendChild(core.createElementNS(null, "email")); Element e3 = core.createElementNS(null, "link"); e3.setAttributeNS(null, "manager", "Big.Boss"); e1.appendChild(e3); testElem.removeAttributeNode(testElem.getAttributeNodeNS(null, "contr")); NamedNodeMap map = testElem.getAttributes(); config = core.getDomConfig(); errorCounter = 0; config.setParameter("psvi", Boolean.TRUE); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.TRUE); core.normalizeDocument(); Assertion.verify(errorCounter == 0, "No errors should be reported"); Assertion.verify(((ElementPSVI)e1).getElementDeclaration().getName().equals("person"), "e1 decl"); config = builder.getDomConfig(); config.setParameter("validate", Boolean.FALSE); } //************************ //* Test normalizeDocument(): core tests //************************ // System.out.println("TEST #4: normalizeDocument() core"); { // check that namespace normalization algorithm works correctly Document doc= new DocumentImpl(); Element root = doc.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:stylesheet"); doc.appendChild(root); root.setAttributeNS("http://attr1", "xsl:attr1",""); Element child1 = doc.createElementNS("http://child1", "NS2:child1"); child1.setAttributeNS("http://attr2", "NS2:attr2",""); root.appendChild(child1); Element child2 = doc.createElementNS("http://child2","NS4:child2"); child2.setAttributeNS("http://attr3","attr3", ""); root.appendChild(child2); Element child3 = doc.createElementNS("http://www.w3.org/1999/XSL/Transform","xsl:child3"); child3.setAttributeNS("http://a1","attr1", ""); child3.setAttributeNS("http://a2","xsl:attr2", ""); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:a1", "http://a1"); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", "http://a2"); Element child4 = doc.createElementNS(null, "child4"); child4.setAttributeNS("http://a1", "xsl:attr1", ""); child4.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "default"); child3.appendChild(child4); root.appendChild(child3); ((CoreDocumentImpl)doc).normalizeDocument(); // // assertions // // xsl:stylesheet should include 2 namespace declarations String name = root.getNodeName(); Assertion.verify(name.equals("xsl:stylesheet"), "xsl:stylesheet"); String value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null, "xmlns:xsl != null"); Assertion.verify(value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr1"), "xmlns:NS1="+value); // child includes 2 namespace decls Assertion.verify(child1.getNodeName().equals("NS2:child1"), "NS2:child1"); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS2"); Assertion.verify(value!=null && value.equals("http://child1"), "xmlns:NS2="+value); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr2"), "xmlns:NS1="+value); // child3 Assertion.verify(child3.getNodeName().equals("xsl:child3"), "xsl:child3"); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://a2"), "xmlns:NS1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "a1"); Assertion.verify(value!=null && value.equals("http://a1"), "xmlns:a1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null && value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); Attr attr = child3.getAttributeNodeNS("http://a2", "attr2"); Assertion.verify(attr != null, "NS1:attr2 !=null"); Assertion.verify(child3.getAttributes().getLength() == 5, "xsl:child3 has 5 attrs"); // child 4 Attr temp = child4.getAttributeNodeNS("http://www.w3.org/2000/xmlns/", "xmlns"); Assertion.verify(temp.getNodeName().equals("xmlns"), "attribute name is xmlns"); Assertion.verify(temp.getNodeValue().length() == 0, "xmlns=''"); /* OutputFormat format = new OutputFormat((Document)doc); format.setLineSeparator(LineSeparator.Windows); format.setIndenting(true); format.setLineWidth(0); format.setPreserveSpace(true); XMLSerializer serializer = new XMLSerializer(System.out, format); serializer.serialize(doc); */ } //************************ //* Test normalizeDocument(): core tests //************************ //System.out.println("TEST #4: namespace fixup during serialization"); { Document doc= new DocumentImpl(); Element root = doc.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:stylesheet"); doc.appendChild(root); root.setAttributeNS("http://attr1", "xsl:attr1",""); Element child1 = doc.createElementNS("http://child1", "NS2:child1"); child1.setAttributeNS("http://attr2", "NS2:attr2",""); root.appendChild(child1); Element child2 = doc.createElementNS("http://child2","NS4:child2"); child2.setAttributeNS("http://attr3","attr3", ""); root.appendChild(child2); Element child3 = doc.createElementNS("http://www.w3.org/1999/XSL/Transform","xsl:child3"); child3.setAttributeNS("http://a1","attr1", ""); child3.setAttributeNS("http://a2","xsl:attr2", ""); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:a1", "http://a1"); child3.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", "http://a2"); Element child4 = doc.createElementNS(null, "child4"); child4.setAttributeNS("http://a1", "xsl:attr1", ""); child4.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "default"); child3.appendChild(child4); root.appendChild(child3); // serialize data writer.getDomConfig().setParameter("namespaces", Boolean.TRUE); String xmlData = writer.writeToString(doc); Reader r = new StringReader(xmlData); LSInput in = impl.createLSInput(); in.setCharacterStream(r); doc = builder.parse(in); // // make sure algorithm works correctly // root = doc.getDocumentElement(); child1 = (Element)root.getFirstChild(); child2 = (Element)child1.getNextSibling(); child3 = (Element)child2.getNextSibling(); // xsl:stylesheet should include 2 namespace declarations String name = root.getNodeName(); Assertion.verify(name.equals("xsl:stylesheet"), "xsl:stylesheet"); String value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null, "xmlns:xsl != null"); Assertion.verify(value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); value = root.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr1"), "xmlns:NS1="+value); // child includes 2 namespace decls Assertion.verify(child1.getNodeName().equals("NS2:child1"), "NS2:child1"); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS2"); Assertion.verify(value!=null && value.equals("http://child1"), "xmlns:NS2="+value); value = child1.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://attr2"), "xmlns:NS1="+value); // child3 Assertion.verify(child3.getNodeName().equals("xsl:child3"), "xsl:child3"); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "NS1"); Assertion.verify(value!=null && value.equals("http://a2"), "xmlns:NS1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "a1"); Assertion.verify(value!=null && value.equals("http://a1"), "xmlns:a1="+value); value = child3.getAttributeNS("http://www.w3.org/2000/xmlns/", "xsl"); Assertion.verify(value!=null && value.equals("http://www.w3.org/1999/XSL/Transform"), "xmlns:xsl="+value); Attr attr = child3.getAttributeNodeNS("http://a2", "attr2"); Assertion.verify(attr != null, "NS6:attr2 !=null"); Assertion.verify(child3.getAttributes().getLength() == 5, "xsl:child3 has 5 attrs"); //OutputFormat format = new OutputFormat((Document)doc); //format.setLineSeparator(LineSeparator.Windows); //format.setIndenting(true); //format.setLineWidth(0); //format.setPreserveSpace(true); //XMLSerializer serializer = new XMLSerializer(System.out, format); //serializer.serialize(doc); } //************************ // TEST: replaceWholeText() // getWholeText() // //************************ //System.out.println("TEST #5: wholeText, input: tests/dom/dom3/wholeText.xml"); { config = builder.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("validate", Boolean.FALSE); config.setParameter("entities", Boolean.TRUE); DocumentImpl doc = (DocumentImpl)builder.parseURI("tests/dom/dom3/wholeText.xml"); Element root = doc.getDocumentElement(); Element test = (Element)doc.getElementsByTagName("elem").item(0); test.appendChild(doc.createTextNode("Address: ")); test.appendChild(doc.createEntityReference("ent2")); test.appendChild(doc.createTextNode("City: ")); test.appendChild(doc.createEntityReference("ent1")); DocumentType doctype = doc.getDoctype(); Node entity = doctype.getEntities().getNamedItem("ent3"); NodeList ls = test.getChildNodes(); Assertion.verify(ls.getLength()==5, "List length"); String compare1 = "Home Address: 1900 Dallas Road (East) City: Dallas. California. USA PO #5668"; Assertion.verify(((TextImpl)ls.item(0)).getWholeText().equals(compare1), "Compare1"); String compare2 = "Address: 1900 Dallas Road (East) City: Dallas. California. USA PO #5668"; Assertion.verify(((TextImpl)ls.item(1)).getWholeText().equals(compare2), "Compare2"); //TEST replaceWholeText() ((NodeImpl)ls.item(0)).setReadOnly(true, true); TextImpl original = (TextImpl)ls.item(0); Node newNode = original.replaceWholeText("Replace with this text"); ls = test.getChildNodes(); Assertion.verify(ls.getLength() == 1, "Length == 1"); Assertion.verify(ls.item(0).getNodeValue().equals("Replace with this text"), "Replacement works"); Assertion.verify(newNode != original, "New node created"); // replace text for node which is not yet attached to the tree Text text = doc.createTextNode("readonly"); ((NodeImpl)text).setReadOnly(true, true); text = ((TextImpl)text).replaceWholeText("Data"); Assertion.verify(text.getNodeValue().equals("Data"), "New value 'Data'"); // test with second child that does not have any content test = (Element)doc.getElementsByTagName("elem").item(1); try { ((TextImpl)test.getFirstChild()).replaceWholeText("can't replace"); } catch (DOMException e){ Assertion.verify(e !=null); } String compare3 = "Test: The Content ends here. "; //Assertion.assert(((Text)test.getFirstChild()).getWholeText().equals(compare3), "Compare3"); } //************************ // TEST: schema-type // schema-location // //************************ { errorCounter = 0; config = builder.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("resource-resolver",resolver); config.setParameter("validate", Boolean.TRUE); config.setParameter("psvi", Boolean.TRUE); // schema-type is not set validate against both grammars errorCounter = 0; DocumentImpl core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both-error.xml"); Assertion.verify(errorCounter == 4, "4 errors should be reported"); errorCounter = 0; // set schema-type to be XML Schema config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema"); // test parsing a file that has both XML schema and DTD core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both.xml"); Assertion.verify(errorCounter == 0, "No errors should be reported"); // parse a file with XML schema and DTD but validate against DTD only errorCounter = 0; config.setParameter("schema-type","http://www.w3.org/TR/REC-xml"); core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both-error.xml"); Assertion.verify(errorCounter == 3, "3 errors should be reported"); // parse a file with DTD only but set schema-location and // validate against XML Schema // set schema location core2 = (DocumentImpl)builder.parseURI("tests/dom/dom3/both-error.xml"); // normalize document errorCounter = 0; Element root = core2.getDocumentElement(); root.removeAttributeNS("http://www.w3.org/2001/XMLSchema", "xsi"); root.removeAttributeNS("http://www.w3.org/2001/XMLSchema", "noNamespaceSchemaLocation"); config = core2.getDomConfig(); config.setParameter("error-handler",errorHandler); config.setParameter("schema-type", "http://www.w3.org/2001/XMLSchema"); config.setParameter("schema-location","personal.xsd"); config.setParameter("resource-resolver",resolver); config.setParameter("validate", Boolean.TRUE); core2.normalizeDocument(); Assertion.verify(errorCounter == 1, "1 error should be reported: "+errorCounter); } // baseURI tests { LSParser parser = impl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null); Document doc = parser.parseURI("tests/dom/dom3/baseURI.xml"); Element root = doc.getDocumentElement(); NodeList ls = doc.getElementsByTagNameNS(null, "streetNum"); Node e = ls.item(0); Assertion.verify(((NodeImpl)e).getBaseURI().endsWith("tests/dom/dom3/baseURI.xml"), "baseURI=tests/dom/dom3/baseURI.xml"); ls = root.getElementsByTagNameNS(null, "header"); Node p2 = ls.item(0); Assertion.verify(((NodeImpl)p2).getBaseURI().equals("http://paragraph.com"), "baseURI=http://paragraph.com"); p2 = ls.item(1); Assertion.verify(((NodeImpl)p2).getBaseURI().equals("http://paragraph.com2"), "baseURI=http://paragraph.com2"); } } catch ( Exception ex ) { ex.printStackTrace(); } System.out.println("done!"); }
diff --git a/src/org/mockito/Matchers.java b/src/org/mockito/Matchers.java index cf6ddf046..e1313d9ac 100644 --- a/src/org/mockito/Matchers.java +++ b/src/org/mockito/Matchers.java @@ -1,347 +1,348 @@ /* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito; import org.mockito.internal.matchers.Any; import org.mockito.internal.matchers.Contains; import org.mockito.internal.matchers.EndsWith; import org.mockito.internal.matchers.Equals; import org.mockito.internal.matchers.InstanceOf; import org.mockito.internal.matchers.Matches; import org.mockito.internal.matchers.NotNull; import org.mockito.internal.matchers.Null; import org.mockito.internal.matchers.Same; import org.mockito.internal.matchers.StartsWith; import org.mockito.internal.progress.LastArguments; /** * Allow less constrained verification or stubbing. See also {@link AdditionalMatchers}. * <pre> * //stubbing using anyInt() argument matcher * stub(mockedList.get(anyInt())).toReturn("element"); * * //following prints "element" * System.out.println(mockedList.get(999)); * * //you can also verify using argument matcher * verify(mockedList).get(anyInt()); * </pre> * <b>Warning:</b> * <p> * When multiple arguments are combined with matchers, all arguments have to be provided by matchers, e.g: * <pre> * verify(mock).someMethod(anyInt(), anyString(), <b>eq("third argument")</b>); * //above is correct - eq() is also an argument matcher * * verify(mock).someMethod(anyInt(), anyString(), <b>"third argument"</b>); * //above is incorrect - exception will be thrown because third argument is given without argument matcher. * </pre> */ public class Matchers { /** * any boolean argument. * * @return <code>false</code>. */ public static boolean anyBoolean() { + //TODO every matcher should have a link to documentation about matchers LastArguments.instance().reportMatcher(Any.ANY); return false; } /** * any byte argument. * * @return <code>0</code>. */ public static byte anyByte() { LastArguments.instance().reportMatcher(Any.ANY); return 0; } /** * any char argument. * * @return <code>0</code>. */ public static char anyChar() { LastArguments.instance().reportMatcher(Any.ANY); return 0; } /** * any int argument. * * @return <code>0</code>. */ public static int anyInt() { LastArguments.instance().reportMatcher(Any.ANY); return 0; } /** * any long argument. * * @return <code>0</code>. */ public static long anyLong() { LastArguments.instance().reportMatcher(Any.ANY); return 0; } /** * any float argument. * * @return <code>0</code>. */ public static float anyFloat() { LastArguments.instance().reportMatcher(Any.ANY); return 0; } /** * any double argument. * * @return <code>0</code>. */ public static double anyDouble() { LastArguments.instance().reportMatcher(Any.ANY); return 0; } /** * any short argument. * * @return <code>0</code>. */ public static short anyShort() { LastArguments.instance().reportMatcher(Any.ANY); return 0; } /** * any Object argument. * * @return <code>null</code>. */ public static Object anyObject() { LastArguments.instance().reportMatcher(Any.ANY); return null; } /** * any String argument. * * @return <code>null</code>. */ public static String anyString() { isA(String.class); return null; } /** * Object argument that implements the given class. * * @param <T> * the accepted type. * @param clazz * the class of the accepted type. * @return <code>null</code>. */ public static <T> T isA(Class<T> clazz) { LastArguments.instance().reportMatcher(new InstanceOf(clazz)); return null; } /** * boolean argument that is equal to the given value. * * @param value * the given value. * @return <code>0</code>. */ public static boolean eq(boolean value) { LastArguments.instance().reportMatcher(new Equals(value)); return false; } /** * byte argument that is equal to the given value. * * @param value * the given value. * @return <code>0</code>. */ public static byte eq(byte value) { LastArguments.instance().reportMatcher(new Equals(value)); return 0; } /** * char argument that is equal to the given value. * * @param value * the given value. * @return <code>0</code>. */ public static char eq(char value) { LastArguments.instance().reportMatcher(new Equals(value)); return 0; } /** * double argument that is equal to the given value. * * @param value * the given value. * @return <code>0</code>. */ public static double eq(double value) { LastArguments.instance().reportMatcher(new Equals(value)); return 0; } /** * float argument that is equal to the given value. * * @param value * the given value. * @return <code>0</code>. */ public static float eq(float value) { LastArguments.instance().reportMatcher(new Equals(value)); return 0; } /** * int argument that is equal to the given value. * * @param value * the given value. * @return <code>0</code>. */ public static int eq(int value) { LastArguments.instance().reportMatcher(new Equals(value)); return 0; } /** * long argument that is equal to the given value. * * @param value * the given value. * @return <code>0</code>. */ public static long eq(long value) { LastArguments.instance().reportMatcher(new Equals(value)); return 0; } /** * short argument that is equal to the given value. * * @param value * the given value. * @return <code>0</code>. */ public static short eq(short value) { LastArguments.instance().reportMatcher(new Equals(value)); return 0; } /** * Object argument that is equal to the given value. * * @param value * the given value. * @return <code>null</code>. */ public static <T> T eq(T value) { LastArguments.instance().reportMatcher(new Equals(value)); return null; } /** * Object argument that is the same as the given value. * * @param <T> * the type of the object, it is passed through to prevent casts. * @param value * the given value. * @return <code>null</code>. */ public static <T> T same(T value) { LastArguments.instance().reportMatcher(new Same(value)); return null; } /** * null argument. * * @return <code>null</code>. */ public static Object isNull() { LastArguments.instance().reportMatcher(Null.NULL); return null; } /** * not null argument. * * @return <code>null</code>. */ public static Object notNull() { LastArguments.instance().reportMatcher(NotNull.NOT_NULL); return null; } /** * String argument that contains the given substring. * * @param substring * the substring. * @return <code>null</code>. */ public static String contains(String substring) { LastArguments.instance().reportMatcher(new Contains(substring)); return null; } /** * String argument that matches the given regular expression. * * @param regex * the regular expression. * @return <code>null</code>. */ public static String matches(String regex) { LastArguments.instance().reportMatcher(new Matches(regex)); return null; } /** * String argument that ends with the given suffix. * * @param suffix * the suffix. * @return <code>null</code>. */ public static String endsWith(String suffix) { LastArguments.instance().reportMatcher(new EndsWith(suffix)); return null; } /** * String argument that starts with the given prefix. * * @param prefix * the prefix. * @return <code>null</code>. */ public static String startsWith(String prefix) { LastArguments.instance().reportMatcher(new StartsWith(prefix)); return null; } }
true
true
public static boolean anyBoolean() { LastArguments.instance().reportMatcher(Any.ANY); return false; }
public static boolean anyBoolean() { //TODO every matcher should have a link to documentation about matchers LastArguments.instance().reportMatcher(Any.ANY); return false; }
diff --git a/RalexBot/src/main/java/net/ae97/ralexbot/permissions/PermissionManager.java b/RalexBot/src/main/java/net/ae97/ralexbot/permissions/PermissionManager.java index 35df396..5c7a545 100644 --- a/RalexBot/src/main/java/net/ae97/ralexbot/permissions/PermissionManager.java +++ b/RalexBot/src/main/java/net/ae97/ralexbot/permissions/PermissionManager.java @@ -1,68 +1,66 @@ /* * Copyright (C) 2013 Lord_Ralex * * 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 net.ae97.ralexbot.permissions; import net.ae97.ralexbot.RalexBot; import net.ae97.ralexbot.api.events.PermissionEvent; import net.ae97.ralexbot.api.users.User; import net.ae97.ralexbot.settings.Settings; import java.io.File; import java.util.List; import java.util.Map; import java.util.Set; /** * @version 1.0 * @author Lord_Ralex */ public class PermissionManager { private final Settings permFile; public PermissionManager() { permFile = new Settings(new File("permissions", "permFile.yml")); } public void reloadFile() { permFile.load(); } public void runPermissionEvent(PermissionEvent event) { User user = event.getUser(); - RalexBot.log("Updating perms for " + user.getNick()); String ver = user.isVerified(); - RalexBot.log("Is verified: " + ver); if (ver == null || ver.isEmpty()) { return; } Map<String, Set<Permission>> existing = user.getPermissions(); - for (String key : existing.keySet()) { - for (Permission perm : existing.get(key)) { + for (String key : existing.keySet().toArray(new String[0])) { + for (Permission perm : existing.get(key).toArray(new Permission[0])) { user.removePermission(key, perm.getName()); } } List<String> list = permFile.getStringList(ver); for (String line : list) { String chan = line.split("\\|")[0]; String perm = line.split("\\|")[1]; if (chan.isEmpty()) { chan = null; } user.addPermission(chan, perm); } } }
false
true
public void runPermissionEvent(PermissionEvent event) { User user = event.getUser(); RalexBot.log("Updating perms for " + user.getNick()); String ver = user.isVerified(); RalexBot.log("Is verified: " + ver); if (ver == null || ver.isEmpty()) { return; } Map<String, Set<Permission>> existing = user.getPermissions(); for (String key : existing.keySet()) { for (Permission perm : existing.get(key)) { user.removePermission(key, perm.getName()); } } List<String> list = permFile.getStringList(ver); for (String line : list) { String chan = line.split("\\|")[0]; String perm = line.split("\\|")[1]; if (chan.isEmpty()) { chan = null; } user.addPermission(chan, perm); } }
public void runPermissionEvent(PermissionEvent event) { User user = event.getUser(); String ver = user.isVerified(); if (ver == null || ver.isEmpty()) { return; } Map<String, Set<Permission>> existing = user.getPermissions(); for (String key : existing.keySet().toArray(new String[0])) { for (Permission perm : existing.get(key).toArray(new Permission[0])) { user.removePermission(key, perm.getName()); } } List<String> list = permFile.getStringList(ver); for (String line : list) { String chan = line.split("\\|")[0]; String perm = line.split("\\|")[1]; if (chan.isEmpty()) { chan = null; } user.addPermission(chan, perm); } }
diff --git a/src/main/java/au/com/postnewspapers/postupload/common/FileHandlerBase.java b/src/main/java/au/com/postnewspapers/postupload/common/FileHandlerBase.java index 8bbb768..249f516 100644 --- a/src/main/java/au/com/postnewspapers/postupload/common/FileHandlerBase.java +++ b/src/main/java/au/com/postnewspapers/postupload/common/FileHandlerBase.java @@ -1,298 +1,298 @@ package au.com.postnewspapers.postupload.common; import au.com.postnewspapers.postupload.config.FileHandlerConfig; import com.sun.jersey.core.header.FormDataContentDisposition; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.enterprise.event.Event; import javax.inject.Inject; import javax.servlet.http.HttpSession; import org.apache.commons.io.IOUtils; import org.codehaus.jackson.map.AnnotationIntrospector; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.xc.JaxbAnnotationIntrospector; /** * Shared code between ajax/rest based and form-based upload handlers * @author Craig */ public abstract class FileHandlerBase { @Inject protected FileHandlerConfig config; @Inject protected Event<UploadSummary> uploadEvent; protected File sessionTempFolder; private UploadSummary uploadSummary; private final List<UploadSummary.FileInfo> fileList = new ArrayList<UploadSummary.FileInfo>(); protected UploadSummary getUploadSummary() { return uploadSummary; } /** * Gain access to the file list. While this list is read/write, it should * not be modified. * * @return */ protected List<UploadSummary.FileInfo> getFileList() { return fileList; } /** * Clear state and make ready for another upload. Must be called by subclass * before starting work. * * This method is safe to call repeatedly, without intervening file uploads * or finishUploadAndSetSummary() calls. */ protected void clearAndInit(HttpSession session) { createOrClearSessionTempFolder(session); fileList.clear(); uploadSummary = null; } // TODO: handle duplicate files /** * Accept a file upload and record it in the file list. * May only be called after clearAndInit() and before * finishUploadAndSetSummary(). * * @param file File data stream to write to session temp folder * @param fileInfo Info about uploaded file * @throws IOException */ protected void uploadFile( InputStream file, FormDataContentDisposition fileInfo) throws IOException { try { final File outFile = new File(sessionTempFolder, fileInfo.getFileName()); final FileOutputStream os = new FileOutputStream(outFile); try { IOUtils.copy(file, os); } finally { os.close(); } recordFileInfo(fileInfo.getFileName(), outFile.length()); } finally { file.close(); } } /** * As uploadFile(InputStream file, FormDataContentDisposition fileInfo) * * @param file Local temp file to read and copy to working location * @param fileInfo Details about uploaded file * @throws IOException */ protected void uploadFile( File file, FormDataContentDisposition fileInfo) throws IOException { final File outFile = new File(sessionTempFolder, fileInfo.getFileName()); final FileOutputStream os = new FileOutputStream(outFile); final FileInputStream is = new FileInputStream(file); try { try { IOUtils.copy(is, os); } finally { os.close(); } } finally { is.close(); } recordFileInfo(fileInfo.getFileName(), file.length()); } /** * Remove an already-uploaded file from the temporary files folder * and the uploaded files list. * * @param fileName Name of file to delete */ protected void deleteFile(String fileName) { for (UploadSummary.FileInfo f : fileList) { if (f.getName().equals(fileName)) { (new File(sessionTempFolder, f.getName())).delete(); fileList.remove(f); break; } } } /** * Call finishUploadAndSetSummary() after your addUploadedFile() calls are * all done and you're ready to show a status report to the user, send notifications * etc. * * If summary.okFiles is empty, it'll be populated with the contents of the * file list created by addSuccessfullyUploadedFile() calls. * * @param summary Data about this upload * @throws IOException */ protected void finishUploadAndSetSummary(UploadSummary summary) throws IOException { if (this.uploadSummary != null) throw new IllegalStateException("Upload summary is set; previous upload not cleared yet!"); if (summary == null) throw new IllegalArgumentException("Cannot set a null upload summary."); uploadSummary = summary; if (uploadSummary.okFiles.isEmpty()) { uploadSummary.okFiles.addAll(fileList); } moveTempsToFinal(uploadSummary, sessionTempFolder); // Notify listeners who are interested in uploads // Exceptions fired by listeners will propagate up and be // thrown from this app, so make sure to write your listeners to // capture and log non-critical exceptions. Listeners may throw // WebApplicationException to indicate failure to the client. uploadEvent.fire(uploadSummary); } /** * Work to be done before session is destroyed. Must be * called by subclass. */ protected void beforeSessionDestroyed() { clearAndDeleteSessionTempFolder(); } /** * use JAXB annotations to transform an object to a JSON serialized * representation. This is just a handy helper method. */ protected static String toJson(Object o) { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); mapper.getSerializationConfig().setAnnotationIntrospector(introspector); try { return mapper.writeValueAsString(o); } catch (IOException ex) { // Dodgy, but in debug code we don't care throw new RuntimeException(ex); } } // Implementation detail // /** * Record information about an uploaded file * * @param fileInfo * @param outFileLength */ private void recordFileInfo(String fileName, long outFileLength) { UploadSummary.FileInfo savedFileInfo = new UploadSummary.FileInfo(); savedFileInfo.setName(fileName); savedFileInfo.setSize((int)outFileLength); fileList.add(savedFileInfo); } /** * Ensure that at the end of this call, the session temp folder is empty * and exists. */ private void createOrClearSessionTempFolder(HttpSession session) { if (sessionTempFolder == null) { sessionTempFolder = new File(config.getTempOutputDir(), session.getId()); } if (sessionTempFolder != null) { if (sessionTempFolder.exists()) { for (File f : sessionTempFolder.listFiles()) { f.delete(); } } else { sessionTempFolder.mkdir(); } } } /** * Ensure that at the end of this call the session temp folder does * NOT exist. No error is thrown if it didn't exist before the call was made. */ private void clearAndDeleteSessionTempFolder() { if (sessionTempFolder != null && sessionTempFolder.exists()) { // This session involved an upload. If the session tempdir exists // we know the files haven't been moved to their final destination. // As the session is being destroyed, these files are abandoned and // should be removed. for (File f : sessionTempFolder.listFiles()) { f.delete(); } sessionTempFolder.delete(); } } private void moveTempsToFinal(UploadSummary uploadSummary, File sessionTempFolder) throws IOException { // Move uploaded files to final destination and write a report // to the directory. if (sessionTempFolder != null && sessionTempFolder.exists()) { File finalOutDir = makeFinalOutputDirectoryPath(uploadSummary, sessionTempFolder); File uploadInfoFile = new File(finalOutDir, ".info.json"); sessionTempFolder.renameTo(finalOutDir); FileWriter w = new FileWriter(uploadInfoFile); try { w.write(toJson(uploadSummary)); } finally { w.close(); } } } /** * Contruct the path for a directory to put the final files in, * creating any parent directories but not the directory its self. * @return */ private File makeFinalOutputDirectoryPath(UploadSummary uploadSummary, File sessionTempFolder) throws IOException { final File outDirParent = config.getFinalOutputDir(); // Create a directory for today if one doesn't already exist final Date now = Calendar.getInstance().getTime(); final String dateDirName = (new SimpleDateFormat("yyyy-MM-dd")).format(now); final File dateDir = new File(outDirParent, dateDirName); - // Try to create then check for existence, to avoid race of test-create-fail - dateDir.mkdirs(); - if (!dateDir.exists()) { - throw new IOException("Unable to create final output folder " + dateDir); - } // then generate a path within today's directory for the uploaded // files to be moved to. StringBuilder b = new StringBuilder(); b.append(dateDirName) .append(File.separatorChar) .append(uploadSummary.senderAddress.getPersonal()) .append(" (").append(uploadSummary.senderAddress.getAddress()).append(") "); if (uploadSummary.customerCode != null && !uploadSummary.customerCode.isEmpty()) { b.append("(C: ").append(uploadSummary.customerCode).append(')'); } if (uploadSummary.bookingNumber != null && !uploadSummary.bookingNumber.isEmpty()) { b.append("(B: ").append(uploadSummary.bookingNumber).append(')'); } // Add a timestamp suffix to handle multiple uploads from one person in a day. // Second resolution should be more than good enough. b.append(' ').append((new SimpleDateFormat("hh-mm-ss").format(now))); uploadSummary.outputDirectory = new File(outDirParent, b.toString()); + uploadSummary.outputDirectory.mkdirs(); + // Try to create then check for existence, to avoid race of test-create-fail + if (!uploadSummary.outputDirectory.exists()) { + throw new IOException("Unable to create final output folder " + uploadSummary.outputDirectory); + } return uploadSummary.outputDirectory; } }
false
true
private File makeFinalOutputDirectoryPath(UploadSummary uploadSummary, File sessionTempFolder) throws IOException { final File outDirParent = config.getFinalOutputDir(); // Create a directory for today if one doesn't already exist final Date now = Calendar.getInstance().getTime(); final String dateDirName = (new SimpleDateFormat("yyyy-MM-dd")).format(now); final File dateDir = new File(outDirParent, dateDirName); // Try to create then check for existence, to avoid race of test-create-fail dateDir.mkdirs(); if (!dateDir.exists()) { throw new IOException("Unable to create final output folder " + dateDir); } // then generate a path within today's directory for the uploaded // files to be moved to. StringBuilder b = new StringBuilder(); b.append(dateDirName) .append(File.separatorChar) .append(uploadSummary.senderAddress.getPersonal()) .append(" (").append(uploadSummary.senderAddress.getAddress()).append(") "); if (uploadSummary.customerCode != null && !uploadSummary.customerCode.isEmpty()) { b.append("(C: ").append(uploadSummary.customerCode).append(')'); } if (uploadSummary.bookingNumber != null && !uploadSummary.bookingNumber.isEmpty()) { b.append("(B: ").append(uploadSummary.bookingNumber).append(')'); } // Add a timestamp suffix to handle multiple uploads from one person in a day. // Second resolution should be more than good enough. b.append(' ').append((new SimpleDateFormat("hh-mm-ss").format(now))); uploadSummary.outputDirectory = new File(outDirParent, b.toString()); return uploadSummary.outputDirectory; }
private File makeFinalOutputDirectoryPath(UploadSummary uploadSummary, File sessionTempFolder) throws IOException { final File outDirParent = config.getFinalOutputDir(); // Create a directory for today if one doesn't already exist final Date now = Calendar.getInstance().getTime(); final String dateDirName = (new SimpleDateFormat("yyyy-MM-dd")).format(now); final File dateDir = new File(outDirParent, dateDirName); // then generate a path within today's directory for the uploaded // files to be moved to. StringBuilder b = new StringBuilder(); b.append(dateDirName) .append(File.separatorChar) .append(uploadSummary.senderAddress.getPersonal()) .append(" (").append(uploadSummary.senderAddress.getAddress()).append(") "); if (uploadSummary.customerCode != null && !uploadSummary.customerCode.isEmpty()) { b.append("(C: ").append(uploadSummary.customerCode).append(')'); } if (uploadSummary.bookingNumber != null && !uploadSummary.bookingNumber.isEmpty()) { b.append("(B: ").append(uploadSummary.bookingNumber).append(')'); } // Add a timestamp suffix to handle multiple uploads from one person in a day. // Second resolution should be more than good enough. b.append(' ').append((new SimpleDateFormat("hh-mm-ss").format(now))); uploadSummary.outputDirectory = new File(outDirParent, b.toString()); uploadSummary.outputDirectory.mkdirs(); // Try to create then check for existence, to avoid race of test-create-fail if (!uploadSummary.outputDirectory.exists()) { throw new IOException("Unable to create final output folder " + uploadSummary.outputDirectory); } return uploadSummary.outputDirectory; }
diff --git a/ngrinder-core/src/main/java/org/ngrinder/common/util/ReflectionUtil.java b/ngrinder-core/src/main/java/org/ngrinder/common/util/ReflectionUtil.java index 0791c357..724b2290 100644 --- a/ngrinder-core/src/main/java/org/ngrinder/common/util/ReflectionUtil.java +++ b/ngrinder-core/src/main/java/org/ngrinder/common/util/ReflectionUtil.java @@ -1,146 +1,146 @@ /* * Copyright (C) 2012 - 2012 NHN Corporation * All rights reserved. * * This file is part of The nGrinder software distribution. Refer to * the file LICENSE which is part of The nGrinder distribution for * licensing details. The nGrinder distribution is available on the * Internet at http://nhnopensource.org/ngrinder * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.ngrinder.common.util; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import static org.ngrinder.common.util.Preconditions.checkNotNull; import static org.ngrinder.common.util.Preconditions.checkArgument; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Reflection Utility functions. * * @author JunHo Yoon * @since 3.0 */ public final class ReflectionUtil { private static final Logger LOG = LoggerFactory.getLogger(ReflectionUtil.class); /** * get object field value, bypassing getter method. * * @param object * object * @param fieldName * field Name * @return fileValue */ public static Object getFieldValue(final Object object, final String fieldName) { Field field = getDeclaredField(object, fieldName); checkNotNull(field, "Could not find field [" + fieldName + "] on target [" + object + "]"); makeAccessible(field); try { return field.get(object); } catch (IllegalAccessException e) { LOG.error(e.getMessage(), e); } return null; } private static Field getDeclaredField(final Object object, final String fieldName) { checkNotNull(object); checkArgument(StringUtils.isBlank(fieldName)); // CHECKSTYLE:OFF for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass .getSuperclass()) { try { return superClass.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { // Fall through } } return null; } private static void makeAccessible(final Field field) { if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) { field.setAccessible(true); } } /** * Invoke private method * * @param object * object * @param methodName * private method name * @param parameters * private method parameter * @return return value */ public static Object invokePrivateMethod(Object object, String methodName, Object[] parameters) { checkNotNull(object); - checkArgument(StringUtils.isBlank(methodName)); + checkArgument(!StringUtils.isBlank(methodName)); Class<?>[] newClassParam = new Class[parameters.length]; for (int i = 0; i < parameters.length; i++) { newClassParam[i] = parameters[i].getClass(); } try { Method declaredMethod = getDeclaredMethod(object.getClass(), methodName, newClassParam); if (declaredMethod == null) { LOG.error("No method {} found in {}", methodName, object.getClass()); return null; } declaredMethod.setAccessible(true); return declaredMethod.invoke(object, parameters); } catch (Exception e) { LOG.error(e.getMessage(), e); return null; } } /** * Get Method object. * * @param clazz * clazz to be inspected * @param methodName * method name * @param parameters * parameter list * @return {@link Method} instance. otherwise null. */ private static Method getDeclaredMethod(final Class<?> clazz, final String methodName, final Class<?>[] parameters) { checkNotNull(clazz); checkArgument(StringUtils.isBlank(methodName)); for (Class<?> superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) { try { return superClass.getDeclaredMethod(methodName, parameters); } catch (Exception e) { } } return null; } }
true
true
public static Object invokePrivateMethod(Object object, String methodName, Object[] parameters) { checkNotNull(object); checkArgument(StringUtils.isBlank(methodName)); Class<?>[] newClassParam = new Class[parameters.length]; for (int i = 0; i < parameters.length; i++) { newClassParam[i] = parameters[i].getClass(); } try { Method declaredMethod = getDeclaredMethod(object.getClass(), methodName, newClassParam); if (declaredMethod == null) { LOG.error("No method {} found in {}", methodName, object.getClass()); return null; } declaredMethod.setAccessible(true); return declaredMethod.invoke(object, parameters); } catch (Exception e) { LOG.error(e.getMessage(), e); return null; } }
public static Object invokePrivateMethod(Object object, String methodName, Object[] parameters) { checkNotNull(object); checkArgument(!StringUtils.isBlank(methodName)); Class<?>[] newClassParam = new Class[parameters.length]; for (int i = 0; i < parameters.length; i++) { newClassParam[i] = parameters[i].getClass(); } try { Method declaredMethod = getDeclaredMethod(object.getClass(), methodName, newClassParam); if (declaredMethod == null) { LOG.error("No method {} found in {}", methodName, object.getClass()); return null; } declaredMethod.setAccessible(true); return declaredMethod.invoke(object, parameters); } catch (Exception e) { LOG.error(e.getMessage(), e); return null; } }
diff --git a/src/com/olympuspvp/tp/olyTP.java b/src/com/olympuspvp/tp/olyTP.java index 07b6f1b..9652c25 100644 --- a/src/com/olympuspvp/tp/olyTP.java +++ b/src/com/olympuspvp/tp/olyTP.java @@ -1,68 +1,72 @@ package com.olympuspvp.tp; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import org.bukkit.plugin.java.JavaPlugin; public class olyTP extends JavaPlugin{ final String tag = ChatColor.GOLD + "[" + ChatColor.YELLOW + "olyTP" + ChatColor.GOLD+"] " + ChatColor.YELLOW; @Override public void onEnable(){ System.out.println("[olyTP] olyTP by willno123 (badass coderleetzors) has been enabled!"); } public boolean onCommand(CommandSender s, Command cmd, String c, String[] args){ if(s instanceof Player == false){ System.out.println("[olyTP] Go home console, you're drunk."); return true; }Player p = (Player)s; if((p.isOp()==false)&&(p.hasPermission("olyTP.use")==false)){ p.sendMessage(tag+"You do not have permission to use this command."); } if(args.length==1){ String to = args[0]; List<Player> matches = Bukkit.matchPlayer(to); if(matches.size() !=1){ p.sendMessage(tag+"The player could not be found."); return true; }Player pto=matches.get(0); if(p==pto){ p.sendMessage(tag+"You cannot teleport to yourself."); return true; - }p.teleport(pto, TeleportCause.PLUGIN); - p.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName()); - if(p.isOp() || p.hasPermission("olyTP.use")) pto.sendMessage(tag+ ChatColor.GOLD + p.getName() + ChatColor.YELLOW + " teleported to you."); + }boolean success = p.teleport(pto, TeleportCause.PLUGIN); + if(success){ + p.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName()); + if(p.isOp() || p.hasPermission("olyTP.use")) pto.sendMessage(tag+ ChatColor.GOLD + p.getName() + ChatColor.YELLOW + " teleported to you."); + }else p.sendMessage(tag + "Teleport failed. Is the player dead?"); }else if(args.length == 2){ String to = args[1]; String from = args[0]; List<Player> matches = Bukkit.matchPlayer(to); if(matches.size() !=1){ p.sendMessage(tag + to + " could not be found."); return true; } Player pto = matches.get(0); matches = Bukkit.matchPlayer(from); if(matches.size() !=1){ p.sendMessage(tag + from + " could not be found."); return true; } Player pfrom = matches.get(0); - pfrom.teleport(pto, TeleportCause.PLUGIN); - pfrom.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName()); - if(!p.equals(pfrom) && !(p.equals(pto))) p.sendMessage(tag + "Teleporting " + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " to " + ChatColor.GOLD + pto.getName()); - pto.sendMessage(tag + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " has been teleported to you."); + boolean success = pfrom.teleport(pto, TeleportCause.PLUGIN); + if(success){ + pfrom.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName()); + if(!p.equals(pfrom) && !(p.equals(pto))) p.sendMessage(tag + "Teleporting " + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " to " + ChatColor.GOLD + pto.getName()); + pto.sendMessage(tag + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " has been teleported to you."); + }else p.sendMessage(tag + "Teleport failed. Is the player dead?"); return true; }else{ p.sendMessage(tag + "Incorrect usage. /tp {player} {player}"); return true; }return true; } }
false
true
public boolean onCommand(CommandSender s, Command cmd, String c, String[] args){ if(s instanceof Player == false){ System.out.println("[olyTP] Go home console, you're drunk."); return true; }Player p = (Player)s; if((p.isOp()==false)&&(p.hasPermission("olyTP.use")==false)){ p.sendMessage(tag+"You do not have permission to use this command."); } if(args.length==1){ String to = args[0]; List<Player> matches = Bukkit.matchPlayer(to); if(matches.size() !=1){ p.sendMessage(tag+"The player could not be found."); return true; }Player pto=matches.get(0); if(p==pto){ p.sendMessage(tag+"You cannot teleport to yourself."); return true; }p.teleport(pto, TeleportCause.PLUGIN); p.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName()); if(p.isOp() || p.hasPermission("olyTP.use")) pto.sendMessage(tag+ ChatColor.GOLD + p.getName() + ChatColor.YELLOW + " teleported to you."); }else if(args.length == 2){ String to = args[1]; String from = args[0]; List<Player> matches = Bukkit.matchPlayer(to); if(matches.size() !=1){ p.sendMessage(tag + to + " could not be found."); return true; } Player pto = matches.get(0); matches = Bukkit.matchPlayer(from); if(matches.size() !=1){ p.sendMessage(tag + from + " could not be found."); return true; } Player pfrom = matches.get(0); pfrom.teleport(pto, TeleportCause.PLUGIN); pfrom.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName()); if(!p.equals(pfrom) && !(p.equals(pto))) p.sendMessage(tag + "Teleporting " + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " to " + ChatColor.GOLD + pto.getName()); pto.sendMessage(tag + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " has been teleported to you."); return true; }else{ p.sendMessage(tag + "Incorrect usage. /tp {player} {player}"); return true; }return true; }
public boolean onCommand(CommandSender s, Command cmd, String c, String[] args){ if(s instanceof Player == false){ System.out.println("[olyTP] Go home console, you're drunk."); return true; }Player p = (Player)s; if((p.isOp()==false)&&(p.hasPermission("olyTP.use")==false)){ p.sendMessage(tag+"You do not have permission to use this command."); } if(args.length==1){ String to = args[0]; List<Player> matches = Bukkit.matchPlayer(to); if(matches.size() !=1){ p.sendMessage(tag+"The player could not be found."); return true; }Player pto=matches.get(0); if(p==pto){ p.sendMessage(tag+"You cannot teleport to yourself."); return true; }boolean success = p.teleport(pto, TeleportCause.PLUGIN); if(success){ p.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName()); if(p.isOp() || p.hasPermission("olyTP.use")) pto.sendMessage(tag+ ChatColor.GOLD + p.getName() + ChatColor.YELLOW + " teleported to you."); }else p.sendMessage(tag + "Teleport failed. Is the player dead?"); }else if(args.length == 2){ String to = args[1]; String from = args[0]; List<Player> matches = Bukkit.matchPlayer(to); if(matches.size() !=1){ p.sendMessage(tag + to + " could not be found."); return true; } Player pto = matches.get(0); matches = Bukkit.matchPlayer(from); if(matches.size() !=1){ p.sendMessage(tag + from + " could not be found."); return true; } Player pfrom = matches.get(0); boolean success = pfrom.teleport(pto, TeleportCause.PLUGIN); if(success){ pfrom.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName()); if(!p.equals(pfrom) && !(p.equals(pto))) p.sendMessage(tag + "Teleporting " + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " to " + ChatColor.GOLD + pto.getName()); pto.sendMessage(tag + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " has been teleported to you."); }else p.sendMessage(tag + "Teleport failed. Is the player dead?"); return true; }else{ p.sendMessage(tag + "Incorrect usage. /tp {player} {player}"); return true; }return true; }
diff --git a/src/com/mojang/mojam/MojamComponent.java b/src/com/mojang/mojam/MojamComponent.java index b2f21ff9..76a1d53b 100644 --- a/src/com/mojang/mojam/MojamComponent.java +++ b/src/com/mojang/mojam/MojamComponent.java @@ -1,1124 +1,1127 @@ package com.mojang.mojam; import java.awt.AWTException; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GraphicsDevice; import java.awt.Point; import java.awt.Robot; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Locale; import java.util.Random; import java.util.Stack; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import com.mojang.mojam.entity.Player; import com.mojang.mojam.entity.building.Base; import com.mojang.mojam.entity.mob.Team; import com.mojang.mojam.gui.Button; import com.mojang.mojam.gui.ButtonListener; import com.mojang.mojam.gui.CharacterSelectionMenu; import com.mojang.mojam.gui.ClickableComponent; import com.mojang.mojam.gui.CreditsScreen; import com.mojang.mojam.gui.DifficultySelect; import com.mojang.mojam.gui.Font; import com.mojang.mojam.gui.GuiError; import com.mojang.mojam.gui.GuiMenu; import com.mojang.mojam.gui.HostingWaitMenu; import com.mojang.mojam.gui.HowToPlayMenu; import com.mojang.mojam.gui.JoinGameMenu; import com.mojang.mojam.gui.KeyBindingsMenu; import com.mojang.mojam.gui.LevelEditorMenu; import com.mojang.mojam.gui.LevelSelect; import com.mojang.mojam.gui.OptionsMenu; import com.mojang.mojam.gui.PauseMenu; import com.mojang.mojam.gui.TitleMenu; import com.mojang.mojam.gui.WinMenu; import com.mojang.mojam.level.DifficultyList; import com.mojang.mojam.level.Level; import com.mojang.mojam.level.LevelInformation; import com.mojang.mojam.level.LevelList; import com.mojang.mojam.level.gamemode.GameMode; import com.mojang.mojam.level.tile.Tile; import com.mojang.mojam.mc.EnumOS2; import com.mojang.mojam.mc.EnumOSMappingHelper; import com.mojang.mojam.network.ClientSidePacketLink; import com.mojang.mojam.network.CommandListener; import com.mojang.mojam.network.NetworkCommand; import com.mojang.mojam.network.NetworkPacketLink; import com.mojang.mojam.network.Packet; import com.mojang.mojam.network.PacketLink; import com.mojang.mojam.network.PacketListener; import com.mojang.mojam.network.PauseCommand; import com.mojang.mojam.network.TurnSynchronizer; import com.mojang.mojam.network.packet.ChangeKeyCommand; import com.mojang.mojam.network.packet.ChangeMouseButtonCommand; import com.mojang.mojam.network.packet.ChangeMouseCoordinateCommand; import com.mojang.mojam.network.packet.ChatCommand; import com.mojang.mojam.network.packet.PingPacket; import com.mojang.mojam.network.packet.StartGamePacket; import com.mojang.mojam.network.packet.StartGamePacketCustom; import com.mojang.mojam.network.packet.TurnPacket; import com.mojang.mojam.resources.Texts; import com.mojang.mojam.screen.Art; import com.mojang.mojam.screen.Bitmap; import com.mojang.mojam.screen.Screen; import com.mojang.mojam.sound.ISoundPlayer; import com.mojang.mojam.sound.NoSoundPlayer; import com.mojang.mojam.sound.SoundPlayer; public class MojamComponent extends Canvas implements Runnable, MouseMotionListener, CommandListener, PacketListener, MouseListener, ButtonListener, KeyListener { public static final String GAME_TITLE = "Catacomb Snatch"; public static final String GAME_VERSION = "1.0.0-SNAPSHOT"; public static MojamComponent instance; public static Locale locale; public static Texts texts; private static final long serialVersionUID = 1L; public static final int GAME_WIDTH = 512; public static final int GAME_HEIGHT = GAME_WIDTH * 3 / 4; public static final int SCALE = 2; private static JFrame guiFrame; private boolean running = true; private boolean paused; private Cursor emptyCursor; private double framerate = 60; private int fps; public static Screen screen = new Screen(GAME_WIDTH, GAME_HEIGHT); private Level level; private Chat chat = new Chat(); // Latency counter private static final int CACHE_EMPTY=0, CACHE_PRIMING=1, CACHE_PRIMED=2; private static final int CACHE_SIZE = 5; private int latencyCacheState = CACHE_EMPTY; private int nextLatencyCacheIdx = 0; private int[] latencyCache = new int[CACHE_SIZE]; private Stack<GuiMenu> menuStack = new Stack<GuiMenu>(); private InputHandler inputHandler; private boolean mouseMoved = false; private int mouseHideTime = 0; public MouseButtons mouseButtons = new MouseButtons(); public Keys keys = new Keys(); public Keys[] synchedKeys = { new Keys(), new Keys() }; public MouseButtons[] synchedMouseButtons = {new MouseButtons(), new MouseButtons() }; public Player[] players = new Player[2]; public Player player; public TurnSynchronizer synchronizer; private PacketLink packetLink; private ServerSocket serverSocket; private boolean isMultiplayer; private boolean isServer; private int localId; public static int localTeam; //local team is the team of the client. This can be used to check if something should be only rendered on one person's screen public int playerCharacter; public int opponentCharacter; private Thread hostThread; private static boolean fullscreen = false; public static ISoundPlayer soundPlayer; private long nextMusicInterval = 0; private byte sShotCounter = 0; private int createServerState = 0; private static File mojamDir = null; public MojamComponent() { String localeString = Options.get(Options.LOCALE, "en"); setLocale(new Locale(localeString)); this.setPreferredSize(new Dimension(GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE)); this.setMinimumSize(new Dimension(GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE)); this.setMaximumSize(new Dimension(GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE)); this.addMouseMotionListener(this); this.addMouseListener(this); TitleMenu menu = new TitleMenu(GAME_WIDTH, GAME_HEIGHT); addMenu(menu); addKeyListener(this); addKeyListener(chat); instance = this; LevelList.createLevelList(); } public void setLocale(Locale locale) { MojamComponent.locale = locale; MojamComponent.texts = new Texts(locale); Locale.setDefault(locale); } @Override public void mouseDragged(MouseEvent arg0) { mouseMoved = true; } @Override public void mouseMoved(MouseEvent arg0) { mouseMoved = true; } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { mouseButtons.releaseAll(); } @Override public void mousePressed(MouseEvent e) { mouseButtons.setNextState(e.getButton(), true); } @Override public void mouseReleased(MouseEvent e) { mouseButtons.setNextState(e.getButton(), false); } @Override public void paint(Graphics g) { } @Override public void update(Graphics g) { } public void start() { running = true; Thread thread = new Thread(this); thread.start(); } public void stop() { running = false; soundPlayer.stopBackgroundMusic(); soundPlayer.shutdown(); } private void init() { initInput(); initCharacters(); soundPlayer = new SoundPlayer(); if (soundPlayer.getSoundSystem() == null) soundPlayer = new NoSoundPlayer(); soundPlayer.startTitleMusic(); try { emptyCursor = Toolkit.getDefaultToolkit().createCustomCursor( new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB), new Point(0, 0), "empty"); } catch (RuntimeException e) { e.printStackTrace(); } setFocusTraversalKeysEnabled(false); requestFocus(); // hide cursor, since we're drawing our own one setCursor(emptyCursor); } private void initInput(){ inputHandler = new InputHandler(keys); addKeyListener(inputHandler); } private void initCharacters(){ opponentCharacter = Art.HERR_VON_SPECK; if(!Options.isCharacterIDset()){ addMenu(new CharacterSelectionMenu()); } playerCharacter = Options.getCharacterID(); } public void showError(String s) { handleAction(TitleMenu.RETURN_TO_TITLESCREEN); addMenu(new GuiError(s)); } private synchronized void createLevel(String levelPath, GameMode mode) { LevelInformation li = LevelInformation.getInfoForPath(levelPath); if (li != null) { createLevel(li, mode); return; } else if (!isMultiplayer) { showError("Missing map."); } showError("Missing map - Multiplayer"); } private synchronized void createLevel(LevelInformation li, GameMode mode) { if (!isMultiplayer) opponentCharacter = Art.NO_OPPONENT; try { //level = Level.fromFile(li); level = mode.generateLevel(li, playerCharacter, opponentCharacter); } catch (Exception ex) { ex.printStackTrace(); showError("Unable to load map."); return; } initLevel(); paused = false; } private synchronized void initLevel() { if (level == null) return; //level.init(); players[0] = new Player(synchedKeys[0], synchedMouseButtons[0], level.width * Tile.WIDTH / 2 - 16, (level.height - 5 - 1) * Tile.HEIGHT - 16, Team.Team1, playerCharacter); players[0].setFacing(4); level.addEntity(players[0]); level.addEntity(new Base(34 * Tile.WIDTH, 7 * Tile.WIDTH, Team.Team1)); if (isMultiplayer) { players[1] = new Player(synchedKeys[1], synchedMouseButtons[1], level.width * Tile.WIDTH / 2 - 16, 7 * Tile.HEIGHT - 16, Team.Team2, opponentCharacter); level.addEntity(players[1]); level.addEntity(new Base(32 * Tile.WIDTH - 20, 32 * Tile.WIDTH - 20, Team.Team2)); } player = players[localId]; player.setCanSee(true); } @Override public void run() { long lastTime = System.nanoTime(); double unprocessed = 0; int frames = 0; long lastTimer1 = System.currentTimeMillis(); try { init(); } catch (Exception e) { e.printStackTrace(); return; } // if (!isMultiplayer) { // createLevel(); // } int toTick = 0; long lastRenderTime = System.nanoTime(); int min = 999999999; int max = 0; while (running) { if (!this.hasFocus()) { keys.release(); } double nsPerTick = 1000000000.0 / framerate; boolean shouldRender = false; while (unprocessed >= 1) { toTick++; unprocessed -= 1; } int tickCount = toTick; if (toTick > 0 && toTick < 3) { tickCount = 1; } if (toTick > 20) { toTick = 20; } for (int i = 0; i < tickCount; i++) { toTick--; // long before = System.nanoTime(); tick(); // long after = System.nanoTime(); // System.out.println("Tick time took " + (after - before) * // 100.0 / nsPerTick + "% of the max time"); shouldRender = true; } // shouldRender = true; BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); continue; } if (shouldRender) { frames++; Graphics g = bs.getDrawGraphics(); Random lastRandom = TurnSynchronizer.synchedRandom; TurnSynchronizer.synchedRandom = null; render(g); TurnSynchronizer.synchedRandom = lastRandom; long renderTime = System.nanoTime(); int timePassed = (int) (renderTime - lastRenderTime); if (timePassed < min) { min = timePassed; } if (timePassed > max) { max = timePassed; } lastRenderTime = renderTime; } long now = System.nanoTime(); unprocessed += (now - lastTime) / nsPerTick; lastTime = now; try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } if (shouldRender) { if (bs != null) { bs.show(); } } if (System.currentTimeMillis() - lastTimer1 > 1000) { lastTimer1 += 1000; fps = frames; frames = 0; } } } private synchronized void render(Graphics g) { if (level != null) { int xScroll = (int) (player.pos.x - screen.w / 2); int yScroll = (int) (player.pos.y - (screen.h - 24) / 2); soundPlayer.setListenerPosition((float) player.pos.x, (float) player.pos.y); level.render(screen, xScroll, yScroll); } if (!menuStack.isEmpty()) { menuStack.peek().render(screen); } if (Options.getAsBoolean(Options.DRAW_FPS, Options.VALUE_FALSE)) { Font.defaultFont().draw(screen, texts.FPS(fps), 10, 10); } if (player != null && menuStack.size() == 0) { addHealthBar(screen); addXpBar(screen); addScore(screen); Font font = Font.defaultFont(); if (isMultiplayer) { font.draw(screen, texts.latency(latencyCacheReady()?""+avgLatency():"-"), 10, 20); } } if (isMultiplayer && menuStack.isEmpty()) { chat.render(screen); } g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.translate((getWidth() - GAME_WIDTH * SCALE) / 2, (getHeight() - GAME_HEIGHT * SCALE) / 2); g.clipRect(0, 0, GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE); if (!menuStack.isEmpty() || level != null) { // render mouse renderMouse(screen, mouseButtons); g.drawImage(screen.image, 0, 0, GAME_WIDTH * SCALE, GAME_HEIGHT * SCALE, null); } } private void addHealthBar(Screen screen){ int maxIndex = Art.panel_healthBar[0].length - 1; int index = maxIndex - Math.round(player.health * maxIndex / player.maxHealth); if (index < 0) index = 0; else if (index > maxIndex) index = maxIndex; screen.blit(Art.panel_healthBar[0][index], 311, screen.h - 17); screen.blit(Art.panel_heart, 314, screen.h - 24); Font font = Font.defaultFont(); font.draw(screen, texts.health(player.health, player.maxHealth), 335, screen.h - 21); } private void addXpBar(Screen screen){ int xpSinceLastLevelUp = (int)(player.xpSinceLastLevelUp()); int xpNeededForNextLevel = (int)(player.nettoXpNeededForLevel(player.plevel+1)); int maxIndex = Art.panel_xpBar[0].length - 1; int index = maxIndex - Math.round(xpSinceLastLevelUp * maxIndex / xpNeededForNextLevel); if (index < 0) index = 0; else if (index > maxIndex) index = maxIndex; screen.blit(Art.panel_xpBar[0][index], 311, screen.h - 32); screen.blit(Art.panel_star, 314, screen.h - 40); Font font = Font.defaultFont(); font.draw(screen, texts.playerLevel(player.plevel+1), 335, screen.h - 36); } private void addScore(Screen screen){ screen.blit(Art.panel_coin, 314, screen.h - 55); Font font = Font.defaultFont(); font.draw(screen, texts.money(player.score), 335, screen.h - 52); } private void renderMouse(Screen screen, MouseButtons mouseButtons) { if (mouseButtons.mouseHidden) return; int crosshairSize = 15; int crosshairSizeHalf = crosshairSize / 2; Bitmap marker = new Bitmap(crosshairSize, crosshairSize); // horizontal line for (int i = 0; i < crosshairSize; i++) { if (i >= crosshairSizeHalf - 1 && i <= crosshairSizeHalf + 1) continue; marker.pixels[crosshairSizeHalf + i * crosshairSize] = 0xffffffff; marker.pixels[i + crosshairSizeHalf * crosshairSize] = 0xffffffff; } screen.blit(marker, mouseButtons.getX() / SCALE - crosshairSizeHalf - 2, mouseButtons.getY() / SCALE - crosshairSizeHalf - 2); } private void tick() { //Not-In-Focus-Pause if (level != null && !isMultiplayer && !paused && !this.isFocusOwner()) { keys.release(); mouseButtons.releaseAll(); PauseCommand pauseCommand = new PauseCommand(true); synchronizer.addCommand(pauseCommand); paused = true; } if (requestToggleFullscreen || keys.fullscreen.wasPressed()) { requestToggleFullscreen = false; setFullscreen(!fullscreen); } if (level != null && level.victoryConditions != null) { if(level.victoryConditions.isVictoryConditionAchieved()) { int winner = level.victoryConditions.playerVictorious(); int characterID = winner == MojamComponent.localTeam ? playerCharacter : opponentCharacter; addMenu(new WinMenu(GAME_WIDTH, GAME_HEIGHT, winner, characterID)); level = null; return; } } if (packetLink != null) { packetLink.tick(); } mouseButtons.setPosition(getMousePosition()); if (!menuStack.isEmpty()) { menuStack.peek().tick(mouseButtons); } if (mouseMoved) { mouseMoved = false; mouseHideTime = 0; if (mouseButtons.mouseHidden) { mouseButtons.mouseHidden = false; } } if (mouseHideTime < 60) { mouseHideTime++; if (mouseHideTime == 60) { mouseButtons.mouseHidden = true; } } if(level == null) { mouseButtons.tick(); } else if (level != null) { if (synchronizer.preTurn()) { synchronizer.postTurn(); for (int index = 0; index < mouseButtons.currentState.length; index++) { boolean nextState = mouseButtons.nextState[index]; if (mouseButtons.isDown(index) != nextState) { synchronizer.addCommand(new ChangeMouseButtonCommand(index,nextState)); } } synchronizer.addCommand(new ChangeMouseCoordinateCommand(mouseButtons.getX(), mouseButtons.getY(), mouseButtons.mouseHidden)); mouseButtons.tick(); for (MouseButtons sMouseButtons : synchedMouseButtons) { sMouseButtons.tick(); } if (!paused) { for (int index = 0; index < keys.getAll().size(); index++) { Keys.Key key = keys.getAll().get(index); boolean nextState = key.nextState; if (key.isDown != nextState) { synchronizer.addCommand(new ChangeKeyCommand(index, nextState)); } } keys.tick(); for (Keys skeys : synchedKeys) { skeys.tick(); } if (keys.pause.wasPressed()) { keys.release(); mouseButtons.releaseAll(); synchronizer.addCommand(new PauseCommand(true)); } level.tick(); if (isMultiplayer) { tickChat(); } } // every 4 minutes, start new background music :) if (System.currentTimeMillis() / 1000 > nextMusicInterval) { nextMusicInterval = (System.currentTimeMillis() / 1000) + 4 * 60; soundPlayer.startBackgroundMusic(); } if (keys.screenShot.isDown) { takeScreenShot(); } } } if (createServerState == 1) { createServerState = 2; synchronizer = new TurnSynchronizer(MojamComponent.this, packetLink, localId, 2); clearMenus(); createLevel(TitleMenu.level, TitleMenu.defaultGameMode); synchronizer.setStarted(true); if (TitleMenu.level.vanilla) { packetLink.sendPacket(new StartGamePacket( TurnSynchronizer.synchedSeed, TitleMenu.level.getUniversalPath(),DifficultyList.getDifficultyID(TitleMenu.difficulty))); } else { packetLink.sendPacket(new StartGamePacketCustom( TurnSynchronizer.synchedSeed, level, DifficultyList.getDifficultyID(TitleMenu.difficulty), playerCharacter, opponentCharacter)); } packetLink.setPacketListener(MojamComponent.this); } } private void tickChat() { if (chat.isOpen()) { keys.release(); } if (keys.chat.wasReleased()) { chat.open(); } chat.tick(); String msg = chat.getWaitingMessage(); if (msg != null) { synchronizer .addCommand(new ChatCommand(texts.playerNameCharacter(playerCharacter) + ": " + msg)); } } public static void main(String[] args) { MojamComponent mc = new MojamComponent(); guiFrame = new JFrame(GAME_TITLE); JPanel panel = new JPanel(new BorderLayout()); panel.add(mc); guiFrame.setContentPane(panel); guiFrame.pack(); guiFrame.setResizable(false); guiFrame.setLocationRelativeTo(null); guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ArrayList<BufferedImage> icoList = new ArrayList<BufferedImage>(); icoList.add(Art.icon32); icoList.add(Art.icon64); guiFrame.setIconImages(icoList); guiFrame.setVisible(true); Options.loadProperties(); setFullscreen(Boolean.parseBoolean(Options.get(Options.FULLSCREEN, Options.VALUE_FALSE))); mc.start(); } private static void setFullscreen(boolean fs) { if (fs != fullscreen) { GraphicsDevice device = guiFrame.getGraphicsConfiguration().getDevice(); // hide window guiFrame.setVisible(false); guiFrame.dispose(); // change options guiFrame.setUndecorated(fs); device.setFullScreenWindow(fs ? guiFrame : null); // display window guiFrame.setLocationRelativeTo(null); guiFrame.setVisible(true); instance.requestFocusInWindow(); fullscreen = fs; } Options.set(Options.FULLSCREEN, fullscreen); } private static volatile boolean requestToggleFullscreen = false; public static void toggleFullscreen() { requestToggleFullscreen = true; // only toggle fullscreen in the tick() loop } public static boolean isFullscreen() { return fullscreen; } @Override public void handle(int playerId, NetworkCommand packet) { if (packet instanceof ChangeKeyCommand) { ChangeKeyCommand ckc = (ChangeKeyCommand) packet; synchedKeys[playerId].getAll().get(ckc.getKey()).nextState = ckc .getNextState(); } if (packet instanceof ChangeMouseButtonCommand) { ChangeMouseButtonCommand ckc = (ChangeMouseButtonCommand) packet; synchedMouseButtons[playerId].nextState[ckc.getButton()] = ckc.getNextState(); } if (packet instanceof ChangeMouseCoordinateCommand) { ChangeMouseCoordinateCommand ccc = (ChangeMouseCoordinateCommand) packet; synchedMouseButtons[playerId].setPosition(new Point(ccc.getX(), ccc.getY())); synchedMouseButtons[playerId].mouseHidden = ccc.isMouseHidden(); } if (packet instanceof ChatCommand) { ChatCommand cc = (ChatCommand) packet; chat.addMessage(cc.getMessage()); } if (packet instanceof PauseCommand) { PauseCommand pc = (PauseCommand) packet; paused = pc.isPause(); if (paused) { addMenu(new PauseMenu(GAME_WIDTH, GAME_HEIGHT)); } else { popMenu(); } } } @Override public void handle(Packet packet) { if (packet instanceof StartGamePacket) { if (!isServer) { StartGamePacket sgPacker = (StartGamePacket) packet; synchronizer.onStartGamePacket(sgPacker); TitleMenu.difficulty = DifficultyList.getDifficulties().get(sgPacker.getDifficulty()); createLevel(sgPacker.getLevelFile(), TitleMenu.defaultGameMode); } } else if (packet instanceof TurnPacket) { synchronizer.onTurnPacket((TurnPacket) packet); } else if (packet instanceof StartGamePacketCustom) { if (!isServer) { StartGamePacketCustom sgPacker = (StartGamePacketCustom) packet; synchronizer.onStartGamePacket((StartGamePacket)packet); TitleMenu.difficulty = DifficultyList.getDifficulties().get(sgPacker.getDifficulty()); level = sgPacker.getLevel(); paused = false; initLevel(); } } else if (packet instanceof PingPacket) { PingPacket pp = (PingPacket)packet; synchronizer.onPingPacket(pp); if (pp.getType() == PingPacket.TYPE_ACK) { addToLatencyCache(pp.getLatency()); } } } private void addToLatencyCache(int latency) { if (nextLatencyCacheIdx >= latencyCache.length) nextLatencyCacheIdx=0; if (latencyCacheState != CACHE_PRIMED) { if (nextLatencyCacheIdx == 0 && latencyCacheState == CACHE_PRIMING) latencyCacheState = CACHE_PRIMED; if (latencyCacheState == CACHE_EMPTY) latencyCacheState = CACHE_PRIMING; } latencyCache[nextLatencyCacheIdx++] = latency; } private boolean latencyCacheReady() { return latencyCacheState == CACHE_PRIMED; } private int avgLatency() { int total = 0; for (int latency : latencyCache) { total += latency; } return total / latencyCache.length; // rounds down } @Override public void buttonPressed(ClickableComponent component) { if (component instanceof Button) { final Button button = (Button) component; handleAction(button.getId()); } } public void handleAction(int id) { switch (id) { case TitleMenu.RETURN_TO_TITLESCREEN: clearMenus(); level = null; TitleMenu menu = new TitleMenu(GAME_WIDTH, GAME_HEIGHT); addMenu(menu); + this.nextMusicInterval = 0; + soundPlayer.stopBackgroundMusic(); + soundPlayer.startTitleMusic(); break; case TitleMenu.START_GAME_ID: clearMenus(); isMultiplayer = false; chat.clear(); localId = 0; MojamComponent.localTeam = Team.Team1; synchronizer = new TurnSynchronizer(this, null, 0, 1); synchronizer.setStarted(true); createLevel(TitleMenu.level, TitleMenu.defaultGameMode); soundPlayer.stopBackgroundMusic(); break; case TitleMenu.SELECT_LEVEL_ID: addMenu(new LevelSelect(false)); break; case TitleMenu.SELECT_HOST_LEVEL_ID: addMenu(new LevelSelect(true)); break; /* * case TitleMenu.UPDATE_LEVELS: * GuiMenu menu = menuStack.pop(); * if (menu instanceof LevelSelect) { addMenu(new * LevelSelect(((LevelSelect) menu).bHosting)); } else { addMenu(new * LevelSelect(false)); } } */ case TitleMenu.HOST_GAME_ID: addMenu(new HostingWaitMenu()); isMultiplayer = true; isServer = true; chat.clear(); try { if (isServer) { localId = 0; MojamComponent.localTeam = Team.Team1; serverSocket = new ServerSocket(Options.getAsInteger(Options.MP_PORT, 3000)); serverSocket.setSoTimeout(1000); hostThread = new Thread() { @Override public void run() { boolean fail = true; try { while (!isInterrupted()) { Socket socket = null; try { socket = serverSocket.accept(); } catch (SocketTimeoutException e) { } if (socket == null) { System.out.println("Waiting for player to connect"); continue; } fail = false; packetLink = new NetworkPacketLink(socket); createServerState = 1; break; } } catch (Exception e) { e.printStackTrace(); } if (fail) { try { serverSocket.close(); } catch (IOException e) { } } }; }; hostThread.start(); } } catch (Exception e) { e.printStackTrace(); } break; case TitleMenu.JOIN_GAME_ID: addMenu(new JoinGameMenu()); break; case TitleMenu.CANCEL_JOIN_ID: popMenu(); if (hostThread != null) { hostThread.interrupt(); hostThread = null; } break; case TitleMenu.PERFORM_JOIN_ID: menuStack.clear(); isMultiplayer = true; isServer = false; chat.clear(); String[] data = TitleMenu.ip.trim().split(":"); String ip = data[0]; Integer port = (data.length > 1) ? Integer.parseInt(data[1]) : Options.getAsInteger(Options.MP_PORT, 3000); try { localId = 1; MojamComponent.localTeam = Team.Team2; packetLink = new ClientSidePacketLink(ip, port); synchronizer = new TurnSynchronizer(this, packetLink, localId, 2); packetLink.setPacketListener(this); } catch (Exception e) { e.printStackTrace(); // System.exit(1); addMenu(new TitleMenu(GAME_WIDTH, GAME_HEIGHT)); } break; case TitleMenu.HOW_TO_PLAY: addMenu(new HowToPlayMenu(level != null)); break; case TitleMenu.OPTIONS_ID: addMenu(new OptionsMenu(level != null)); break; case TitleMenu.SELECT_DIFFICULTY_ID: addMenu(new DifficultySelect(false)); break; case TitleMenu.SELECT_DIFFICULTY_HOSTING_ID: addMenu(new DifficultySelect(true)); break; case TitleMenu.KEY_BINDINGS_ID: addMenu(new KeyBindingsMenu(keys, inputHandler)); break; case TitleMenu.LEVEL_EDITOR_ID: addMenu(new LevelEditorMenu()); break; case TitleMenu.EXIT_GAME_ID: System.exit(0); break; case TitleMenu.RETURN_ID: synchronizer.addCommand(new PauseCommand(false)); keys.tick(); break; case TitleMenu.BACK_ID: popMenu(); break; case TitleMenu.CREDITS_ID: addMenu(new CreditsScreen(GAME_WIDTH, GAME_HEIGHT)); break; case TitleMenu.CHARACTER_ID: addMenu(new CharacterSelectionMenu()); break; } } private void clearMenus() { while (!menuStack.isEmpty()) { menuStack.pop(); } } private void addMenu(GuiMenu menu) { menuStack.add(menu); menu.addButtonListener(this); } private void popMenu() { if (!menuStack.isEmpty()) { menuStack.pop(); } } @Override public void keyPressed(KeyEvent e) { if (!menuStack.isEmpty()) { menuStack.peek().keyPressed(e); } } @Override public void keyReleased(KeyEvent e) { if (!menuStack.isEmpty()) { menuStack.peek().keyReleased(e); } } @Override public void keyTyped(KeyEvent e) { if (!menuStack.isEmpty()) { menuStack.peek().keyTyped(e); } } public static File getMojamDir() { if (mojamDir == null) { mojamDir = getAppDir("mojam"); } return mojamDir; } public static EnumOS2 getOs() { String s = System.getProperty("os.name").toLowerCase(); if (s.contains("win")) { return EnumOS2.windows; } if (s.contains("mac")) { return EnumOS2.macos; } if (s.contains("solaris")) { return EnumOS2.solaris; } if (s.contains("sunos")) { return EnumOS2.solaris; } if (s.contains("linux")) { return EnumOS2.linux; } if (s.contains("unix")) { return EnumOS2.linux; } else { return EnumOS2.unknown; } } public static File getAppDir(String s) { String s1 = System.getProperty("user.home", "."); File file; switch (EnumOSMappingHelper.enumOSMappingArray[getOs().ordinal()]) { case 1: // '\001' case 2: // '\002' file = new File(s1, (new StringBuilder()).append('.').append(s) .append('/').toString()); break; case 3: // '\003' String s2 = System.getenv("APPDATA"); if (s2 != null) { file = new File(s2, (new StringBuilder()).append(".").append(s) .append('/').toString()); } else { file = new File(s1, (new StringBuilder()).append('.').append(s) .append('/').toString()); } break; case 4: // '\004' file = new File(s1, (new StringBuilder()) .append("Library/Application Support/").append(s) .toString()); break; default: file = new File(s1, (new StringBuilder()).append(s).append('/') .toString()); break; } if (!file.exists() && !file.mkdirs()) { throw new RuntimeException((new StringBuilder()) .append("The working directory could not be created: ") .append(file).toString()); } else { return file; } } public void takeScreenShot() { BufferedImage screencapture; try { screencapture = new Robot().createScreenCapture(guiFrame .getBounds()); File file = new File(getMojamDir()+"/"+"screenShot" + sShotCounter++ + ".png"); while(file.exists()) { file = new File(getMojamDir()+"/"+"screenShot" + sShotCounter++ + ".png"); } ImageIO.write(screencapture, "png", file); } catch (AWTException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
true
true
public void handleAction(int id) { switch (id) { case TitleMenu.RETURN_TO_TITLESCREEN: clearMenus(); level = null; TitleMenu menu = new TitleMenu(GAME_WIDTH, GAME_HEIGHT); addMenu(menu); break; case TitleMenu.START_GAME_ID: clearMenus(); isMultiplayer = false; chat.clear(); localId = 0; MojamComponent.localTeam = Team.Team1; synchronizer = new TurnSynchronizer(this, null, 0, 1); synchronizer.setStarted(true); createLevel(TitleMenu.level, TitleMenu.defaultGameMode); soundPlayer.stopBackgroundMusic(); break; case TitleMenu.SELECT_LEVEL_ID: addMenu(new LevelSelect(false)); break; case TitleMenu.SELECT_HOST_LEVEL_ID: addMenu(new LevelSelect(true)); break; /* * case TitleMenu.UPDATE_LEVELS: * GuiMenu menu = menuStack.pop(); * if (menu instanceof LevelSelect) { addMenu(new * LevelSelect(((LevelSelect) menu).bHosting)); } else { addMenu(new * LevelSelect(false)); } } */ case TitleMenu.HOST_GAME_ID: addMenu(new HostingWaitMenu()); isMultiplayer = true; isServer = true; chat.clear(); try { if (isServer) { localId = 0; MojamComponent.localTeam = Team.Team1; serverSocket = new ServerSocket(Options.getAsInteger(Options.MP_PORT, 3000)); serverSocket.setSoTimeout(1000); hostThread = new Thread() { @Override public void run() { boolean fail = true; try { while (!isInterrupted()) { Socket socket = null; try { socket = serverSocket.accept(); } catch (SocketTimeoutException e) { } if (socket == null) { System.out.println("Waiting for player to connect"); continue; } fail = false; packetLink = new NetworkPacketLink(socket); createServerState = 1; break; } } catch (Exception e) { e.printStackTrace(); } if (fail) { try { serverSocket.close(); } catch (IOException e) { } } }; }; hostThread.start(); } } catch (Exception e) { e.printStackTrace(); } break; case TitleMenu.JOIN_GAME_ID: addMenu(new JoinGameMenu()); break; case TitleMenu.CANCEL_JOIN_ID: popMenu(); if (hostThread != null) { hostThread.interrupt(); hostThread = null; } break; case TitleMenu.PERFORM_JOIN_ID: menuStack.clear(); isMultiplayer = true; isServer = false; chat.clear(); String[] data = TitleMenu.ip.trim().split(":"); String ip = data[0]; Integer port = (data.length > 1) ? Integer.parseInt(data[1]) : Options.getAsInteger(Options.MP_PORT, 3000); try { localId = 1; MojamComponent.localTeam = Team.Team2; packetLink = new ClientSidePacketLink(ip, port); synchronizer = new TurnSynchronizer(this, packetLink, localId, 2); packetLink.setPacketListener(this); } catch (Exception e) { e.printStackTrace(); // System.exit(1); addMenu(new TitleMenu(GAME_WIDTH, GAME_HEIGHT)); } break; case TitleMenu.HOW_TO_PLAY: addMenu(new HowToPlayMenu(level != null)); break; case TitleMenu.OPTIONS_ID: addMenu(new OptionsMenu(level != null)); break; case TitleMenu.SELECT_DIFFICULTY_ID: addMenu(new DifficultySelect(false)); break; case TitleMenu.SELECT_DIFFICULTY_HOSTING_ID: addMenu(new DifficultySelect(true)); break; case TitleMenu.KEY_BINDINGS_ID: addMenu(new KeyBindingsMenu(keys, inputHandler)); break; case TitleMenu.LEVEL_EDITOR_ID: addMenu(new LevelEditorMenu()); break; case TitleMenu.EXIT_GAME_ID: System.exit(0); break; case TitleMenu.RETURN_ID: synchronizer.addCommand(new PauseCommand(false)); keys.tick(); break; case TitleMenu.BACK_ID: popMenu(); break; case TitleMenu.CREDITS_ID: addMenu(new CreditsScreen(GAME_WIDTH, GAME_HEIGHT)); break; case TitleMenu.CHARACTER_ID: addMenu(new CharacterSelectionMenu()); break; } }
public void handleAction(int id) { switch (id) { case TitleMenu.RETURN_TO_TITLESCREEN: clearMenus(); level = null; TitleMenu menu = new TitleMenu(GAME_WIDTH, GAME_HEIGHT); addMenu(menu); this.nextMusicInterval = 0; soundPlayer.stopBackgroundMusic(); soundPlayer.startTitleMusic(); break; case TitleMenu.START_GAME_ID: clearMenus(); isMultiplayer = false; chat.clear(); localId = 0; MojamComponent.localTeam = Team.Team1; synchronizer = new TurnSynchronizer(this, null, 0, 1); synchronizer.setStarted(true); createLevel(TitleMenu.level, TitleMenu.defaultGameMode); soundPlayer.stopBackgroundMusic(); break; case TitleMenu.SELECT_LEVEL_ID: addMenu(new LevelSelect(false)); break; case TitleMenu.SELECT_HOST_LEVEL_ID: addMenu(new LevelSelect(true)); break; /* * case TitleMenu.UPDATE_LEVELS: * GuiMenu menu = menuStack.pop(); * if (menu instanceof LevelSelect) { addMenu(new * LevelSelect(((LevelSelect) menu).bHosting)); } else { addMenu(new * LevelSelect(false)); } } */ case TitleMenu.HOST_GAME_ID: addMenu(new HostingWaitMenu()); isMultiplayer = true; isServer = true; chat.clear(); try { if (isServer) { localId = 0; MojamComponent.localTeam = Team.Team1; serverSocket = new ServerSocket(Options.getAsInteger(Options.MP_PORT, 3000)); serverSocket.setSoTimeout(1000); hostThread = new Thread() { @Override public void run() { boolean fail = true; try { while (!isInterrupted()) { Socket socket = null; try { socket = serverSocket.accept(); } catch (SocketTimeoutException e) { } if (socket == null) { System.out.println("Waiting for player to connect"); continue; } fail = false; packetLink = new NetworkPacketLink(socket); createServerState = 1; break; } } catch (Exception e) { e.printStackTrace(); } if (fail) { try { serverSocket.close(); } catch (IOException e) { } } }; }; hostThread.start(); } } catch (Exception e) { e.printStackTrace(); } break; case TitleMenu.JOIN_GAME_ID: addMenu(new JoinGameMenu()); break; case TitleMenu.CANCEL_JOIN_ID: popMenu(); if (hostThread != null) { hostThread.interrupt(); hostThread = null; } break; case TitleMenu.PERFORM_JOIN_ID: menuStack.clear(); isMultiplayer = true; isServer = false; chat.clear(); String[] data = TitleMenu.ip.trim().split(":"); String ip = data[0]; Integer port = (data.length > 1) ? Integer.parseInt(data[1]) : Options.getAsInteger(Options.MP_PORT, 3000); try { localId = 1; MojamComponent.localTeam = Team.Team2; packetLink = new ClientSidePacketLink(ip, port); synchronizer = new TurnSynchronizer(this, packetLink, localId, 2); packetLink.setPacketListener(this); } catch (Exception e) { e.printStackTrace(); // System.exit(1); addMenu(new TitleMenu(GAME_WIDTH, GAME_HEIGHT)); } break; case TitleMenu.HOW_TO_PLAY: addMenu(new HowToPlayMenu(level != null)); break; case TitleMenu.OPTIONS_ID: addMenu(new OptionsMenu(level != null)); break; case TitleMenu.SELECT_DIFFICULTY_ID: addMenu(new DifficultySelect(false)); break; case TitleMenu.SELECT_DIFFICULTY_HOSTING_ID: addMenu(new DifficultySelect(true)); break; case TitleMenu.KEY_BINDINGS_ID: addMenu(new KeyBindingsMenu(keys, inputHandler)); break; case TitleMenu.LEVEL_EDITOR_ID: addMenu(new LevelEditorMenu()); break; case TitleMenu.EXIT_GAME_ID: System.exit(0); break; case TitleMenu.RETURN_ID: synchronizer.addCommand(new PauseCommand(false)); keys.tick(); break; case TitleMenu.BACK_ID: popMenu(); break; case TitleMenu.CREDITS_ID: addMenu(new CreditsScreen(GAME_WIDTH, GAME_HEIGHT)); break; case TitleMenu.CHARACTER_ID: addMenu(new CharacterSelectionMenu()); break; } }
diff --git a/blocksworld/Algorithm.java b/blocksworld/Algorithm.java index 15d2950..5b2544e 100644 --- a/blocksworld/Algorithm.java +++ b/blocksworld/Algorithm.java @@ -1,268 +1,267 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package blocksworld; import java.util.ArrayList; import operators.*; import predicates.*; import predicates.PredicateUsedColsNum; /** * * @author gaspercat */ public class Algorithm { private ArrayList<State> states; // List of states transited private ArrayList<Operator> operators; // List of operators applied private ArrayList<Object> stack; // Stack of the algorithm private ArrayList<Predicate> solve_stack; // Stack of preconditions being solved private State init_state; // Initial state private State goal_state; // Goal state private State curr_state; // Current state private boolean is_valid; // Has the algorithm found a valid solution? public Algorithm(){ this.init_state = null; this.goal_state = null; this.is_valid = true; this.states = new ArrayList<State>(); this.operators = new ArrayList<Operator>(); this.stack = new ArrayList<Object>(); this.solve_stack = new ArrayList<Predicate>(); } // * ** CONTROL METHODS // * ****************************************** // Execute a complete problem public void run(State initial, State goal){ this.init_state = initial; this.goal_state = goal; this.curr_state = initial; this.states.add(this.curr_state); this.stack.add(new Preconditions(goal.getPredicates())); this.stack.addAll(goal.getPredicates()); execute(); // Add goal state to plan this.states.add(goal); } // Execute a partial problem public void run(State initial, Operator op, ArrayList<Predicate> solve_stack){ this.init_state = initial; this.goal_state = null; this.curr_state = initial; this.states.add(this.curr_state); this.stack.add(op); this.stack.add(op.getPreconditions()); this.stack.addAll(op.getPreconditions().getPredicates()); this.solve_stack = solve_stack; execute(); } public boolean isValid(){ return this.is_valid; } public ArrayList<Operator> getOperators(){ ArrayList<Operator> ret = new ArrayList<Operator>(); for(int i=0;i<this.operators.size();i++){ ret.add(this.operators.get(i).clone()); } return ret; } public ArrayList<State> getStates(){ ArrayList<State> ret = new ArrayList<State>(); for(int i=0;i<this.states.size();i++){ ret.add(this.states.get(i).clone()); } return ret; } public void clear(){ this.states.clear(); this.operators.clear(); this.stack.clear(); } // * ** ALGORITHM // * ****************************************** public void execute(){ while(this.stack.size() > 0){ Object c = this.stack.remove(this.stack.size()-1); // If c is an operator if(c instanceof Operator){ // Update current state System.out.println("Applying operator: " + c.toString()); - this.operators.add((Operator)c); this.curr_state = new State(this.curr_state, (Operator)c); // Add new state & operator to plan this.states.add(this.curr_state); this.operators.add((Operator)c); // If c is a condition not fully instanced }else if((c instanceof Predicate) && !((Predicate)c).isInstanced()){ System.out.println("Instantiating condition: " + c); heuristicInstanceCondition((Predicate)c); this.stack.add(c); // If c is a condition fully instanced }else if((c instanceof Predicate) && ((Predicate)c).isInstanced()){ System.out.println("Checking condition: " + c); Predicate pred = (Predicate)c; if(!this.curr_state.hasPredicate(pred)){ // If predicate already being solved, we're in a loop! if(isPredicateBeingSolved(pred)){ this.is_valid = false; return; } //Add predicate to list of predicates being solved this.solve_stack.add(pred); // Run a branch for each possible operator boolean found = false; ArrayList<Operator> ops = heuristicSelectOperators(pred); for(Operator op: ops){ System.out.println("Adding new operator to the stack: " + op); Algorithm alg = new Algorithm(); alg.run(this.curr_state, op, this.solve_stack); if(alg.isValid()){ ArrayList<State> tstates = alg.getStates(); ArrayList<Operator> toperators = alg.getOperators(); tstates.remove(0); this.states.addAll(tstates); this.operators.addAll(toperators); System.out.println("Operators added to plan: "+toperators); this.curr_state = this.states.get(this.states.size()-1); found = true; break; }else{ System.out.println("Operator discarted: "+op.toString()); } } // Remove predicate from list of predicates being solved this.solve_stack.remove(pred); // If no valid operator found, we've got a problemo! if(found == false){ this.is_valid = false; return; } } // If c is a list of conditions }else if(c instanceof Preconditions){ System.out.println("Checking list of conditions: " + c); ArrayList<Predicate> unmet = this.curr_state.getUnmetConditions((Preconditions)c); if(unmet.size() > 0){ this.stack.add(c); this.stack.addAll(unmet); } } } } // * ** HEURISTIC METHODS // * ****************************************** private void heuristicInstanceCondition(Predicate pred){ // Get related operator Operator op = null; for(int i=this.stack.size()-1;;i--){ if(this.stack.get(i) instanceof Operator){ op = (Operator)this.stack.get(i); break; } } // Define value at operator op.instanceValues(pred, this.curr_state); } private ArrayList<Operator> heuristicSelectOperators(Predicate pred){ // TODO: Finish this heuristic ArrayList<Operator> op = new ArrayList<Operator>(); switch(pred.getType()){ // If piece must be free but it isn't case Predicate.FREE: op.add(new OperatorUnstack((Block)null, pred.getA())); break; // If free arm needed but is currently used case Predicate.FREE_ARM: Predicate tp = this.curr_state.getPredicate(Predicate.PICKED_UP); op.add(new OperatorLeave(tp.getA())); op.add(new OperatorStack(tp.getA(), null)); break; // If free stack needed but 3 already used case Predicate.FREE_STACK: op.add(new OperatorPickUp((Block)null)); break; // If a block must be over another case Predicate.ON: op.add(new OperatorStack(pred.getA(), pred.getB())); break; // If a block must be on the table case Predicate.ON_TABLE: op.add(new OperatorLeave(pred.getA())); break; // If a block must be picked up case Predicate.PICKED_UP: op.add(new OperatorPickUp(pred.getA())); op.add(new OperatorUnstack(pred.getA(), null)); break; } return op; } // * ** HELPER METHODS // * ****************************************** private boolean isStateVisited(State s){ for(State ts: this.states){ if(ts.equals(s)) return true; } return false; } private boolean isPredicateBeingSolved(Predicate pred){ for(Predicate p: this.solve_stack){ if(p.equals(pred)) return true; } return false; } }
true
true
public void execute(){ while(this.stack.size() > 0){ Object c = this.stack.remove(this.stack.size()-1); // If c is an operator if(c instanceof Operator){ // Update current state System.out.println("Applying operator: " + c.toString()); this.operators.add((Operator)c); this.curr_state = new State(this.curr_state, (Operator)c); // Add new state & operator to plan this.states.add(this.curr_state); this.operators.add((Operator)c); // If c is a condition not fully instanced }else if((c instanceof Predicate) && !((Predicate)c).isInstanced()){ System.out.println("Instantiating condition: " + c); heuristicInstanceCondition((Predicate)c); this.stack.add(c); // If c is a condition fully instanced }else if((c instanceof Predicate) && ((Predicate)c).isInstanced()){ System.out.println("Checking condition: " + c); Predicate pred = (Predicate)c; if(!this.curr_state.hasPredicate(pred)){ // If predicate already being solved, we're in a loop! if(isPredicateBeingSolved(pred)){ this.is_valid = false; return; } //Add predicate to list of predicates being solved this.solve_stack.add(pred); // Run a branch for each possible operator boolean found = false; ArrayList<Operator> ops = heuristicSelectOperators(pred); for(Operator op: ops){ System.out.println("Adding new operator to the stack: " + op); Algorithm alg = new Algorithm(); alg.run(this.curr_state, op, this.solve_stack); if(alg.isValid()){ ArrayList<State> tstates = alg.getStates(); ArrayList<Operator> toperators = alg.getOperators(); tstates.remove(0); this.states.addAll(tstates); this.operators.addAll(toperators); System.out.println("Operators added to plan: "+toperators); this.curr_state = this.states.get(this.states.size()-1); found = true; break; }else{ System.out.println("Operator discarted: "+op.toString()); } } // Remove predicate from list of predicates being solved this.solve_stack.remove(pred); // If no valid operator found, we've got a problemo! if(found == false){ this.is_valid = false; return; } } // If c is a list of conditions }else if(c instanceof Preconditions){ System.out.println("Checking list of conditions: " + c); ArrayList<Predicate> unmet = this.curr_state.getUnmetConditions((Preconditions)c); if(unmet.size() > 0){ this.stack.add(c); this.stack.addAll(unmet); } } } }
public void execute(){ while(this.stack.size() > 0){ Object c = this.stack.remove(this.stack.size()-1); // If c is an operator if(c instanceof Operator){ // Update current state System.out.println("Applying operator: " + c.toString()); this.curr_state = new State(this.curr_state, (Operator)c); // Add new state & operator to plan this.states.add(this.curr_state); this.operators.add((Operator)c); // If c is a condition not fully instanced }else if((c instanceof Predicate) && !((Predicate)c).isInstanced()){ System.out.println("Instantiating condition: " + c); heuristicInstanceCondition((Predicate)c); this.stack.add(c); // If c is a condition fully instanced }else if((c instanceof Predicate) && ((Predicate)c).isInstanced()){ System.out.println("Checking condition: " + c); Predicate pred = (Predicate)c; if(!this.curr_state.hasPredicate(pred)){ // If predicate already being solved, we're in a loop! if(isPredicateBeingSolved(pred)){ this.is_valid = false; return; } //Add predicate to list of predicates being solved this.solve_stack.add(pred); // Run a branch for each possible operator boolean found = false; ArrayList<Operator> ops = heuristicSelectOperators(pred); for(Operator op: ops){ System.out.println("Adding new operator to the stack: " + op); Algorithm alg = new Algorithm(); alg.run(this.curr_state, op, this.solve_stack); if(alg.isValid()){ ArrayList<State> tstates = alg.getStates(); ArrayList<Operator> toperators = alg.getOperators(); tstates.remove(0); this.states.addAll(tstates); this.operators.addAll(toperators); System.out.println("Operators added to plan: "+toperators); this.curr_state = this.states.get(this.states.size()-1); found = true; break; }else{ System.out.println("Operator discarted: "+op.toString()); } } // Remove predicate from list of predicates being solved this.solve_stack.remove(pred); // If no valid operator found, we've got a problemo! if(found == false){ this.is_valid = false; return; } } // If c is a list of conditions }else if(c instanceof Preconditions){ System.out.println("Checking list of conditions: " + c); ArrayList<Predicate> unmet = this.curr_state.getUnmetConditions((Preconditions)c); if(unmet.size() > 0){ this.stack.add(c); this.stack.addAll(unmet); } } } }
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestPendingDataNodeMessages.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestPendingDataNodeMessages.java index c84c8d1d03..f73245860a 100644 --- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestPendingDataNodeMessages.java +++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestPendingDataNodeMessages.java @@ -1,68 +1,68 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.blockmanagement; import static org.junit.Assert.*; import java.util.Queue; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.protocol.DatanodeID; import org.apache.hadoop.hdfs.server.blockmanagement.PendingDataNodeMessages.ReportedBlockInfo; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.ReplicaState; import org.junit.Test; import com.google.common.base.Joiner; public class TestPendingDataNodeMessages { PendingDataNodeMessages msgs = new PendingDataNodeMessages(); private final Block block1Gs1 = new Block(1, 0, 1); private final Block block1Gs2 = new Block(1, 0, 2); private final Block block1Gs2DifferentInstance = new Block(1, 0, 2); private final Block block2Gs1 = new Block(2, 0, 1); private final DatanodeDescriptor fakeDN = new DatanodeDescriptor( new DatanodeID("fake", 100)); @Test public void testQueues() { msgs.enqueueReportedBlock(fakeDN, block1Gs1, ReplicaState.FINALIZED); msgs.enqueueReportedBlock(fakeDN, block1Gs2, ReplicaState.FINALIZED); assertEquals(2, msgs.count()); // Nothing queued yet for block 2 assertNull(msgs.takeBlockQueue(block2Gs1)); assertEquals(2, msgs.count()); Queue<ReportedBlockInfo> q = msgs.takeBlockQueue(block1Gs2DifferentInstance); assertEquals( - "ReportedBlockInfo [block=blk_1_1, dn=fake, reportedState=FINALIZED]," + - "ReportedBlockInfo [block=blk_1_2, dn=fake, reportedState=FINALIZED]", + "ReportedBlockInfo [block=blk_1_1, dn=fake:100, reportedState=FINALIZED]," + + "ReportedBlockInfo [block=blk_1_2, dn=fake:100, reportedState=FINALIZED]", Joiner.on(",").join(q)); assertEquals(0, msgs.count()); // Should be null if we pull again assertNull(msgs.takeBlockQueue(block1Gs1)); assertEquals(0, msgs.count()); } }
true
true
public void testQueues() { msgs.enqueueReportedBlock(fakeDN, block1Gs1, ReplicaState.FINALIZED); msgs.enqueueReportedBlock(fakeDN, block1Gs2, ReplicaState.FINALIZED); assertEquals(2, msgs.count()); // Nothing queued yet for block 2 assertNull(msgs.takeBlockQueue(block2Gs1)); assertEquals(2, msgs.count()); Queue<ReportedBlockInfo> q = msgs.takeBlockQueue(block1Gs2DifferentInstance); assertEquals( "ReportedBlockInfo [block=blk_1_1, dn=fake, reportedState=FINALIZED]," + "ReportedBlockInfo [block=blk_1_2, dn=fake, reportedState=FINALIZED]", Joiner.on(",").join(q)); assertEquals(0, msgs.count()); // Should be null if we pull again assertNull(msgs.takeBlockQueue(block1Gs1)); assertEquals(0, msgs.count()); }
public void testQueues() { msgs.enqueueReportedBlock(fakeDN, block1Gs1, ReplicaState.FINALIZED); msgs.enqueueReportedBlock(fakeDN, block1Gs2, ReplicaState.FINALIZED); assertEquals(2, msgs.count()); // Nothing queued yet for block 2 assertNull(msgs.takeBlockQueue(block2Gs1)); assertEquals(2, msgs.count()); Queue<ReportedBlockInfo> q = msgs.takeBlockQueue(block1Gs2DifferentInstance); assertEquals( "ReportedBlockInfo [block=blk_1_1, dn=fake:100, reportedState=FINALIZED]," + "ReportedBlockInfo [block=blk_1_2, dn=fake:100, reportedState=FINALIZED]", Joiner.on(",").join(q)); assertEquals(0, msgs.count()); // Should be null if we pull again assertNull(msgs.takeBlockQueue(block1Gs1)); assertEquals(0, msgs.count()); }
diff --git a/curator-framework/src/main/java/com/netflix/curator/framework/listen/ListenerContainer.java b/curator-framework/src/main/java/com/netflix/curator/framework/listen/ListenerContainer.java index 1dc41806..af89528a 100644 --- a/curator-framework/src/main/java/com/netflix/curator/framework/listen/ListenerContainer.java +++ b/curator-framework/src/main/java/com/netflix/curator/framework/listen/ListenerContainer.java @@ -1,93 +1,103 @@ /* * * Copyright 2011 Netflix, 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 com.netflix.curator.framework.listen; import com.google.common.base.Function; import com.google.common.collect.Maps; import com.google.common.util.concurrent.MoreExecutors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import java.util.concurrent.Executor; /** * Abstracts an object that has listeners */ public class ListenerContainer<T> implements Listenable<T> { private final Logger log = LoggerFactory.getLogger(getClass()); private final Map<T, ListenerEntry<T>> listeners = Maps.newConcurrentMap(); @Override public void addListener(T listener) { addListener(listener, MoreExecutors.sameThreadExecutor()); } @Override public void addListener(T listener, Executor executor) { listeners.put(listener, new ListenerEntry<T>(listener, executor)); } @Override public void removeListener(T listener) { listeners.remove(listener); } /** * Remove all listeners */ public void clear() { listeners.clear(); } /** * Return the number of listeners * * @return number */ public int size() { return listeners.size(); } /** * Utility - apply the given function to each listener. The function receives * the listener as an argument. * * @param function function to call for each listener */ - public void forEach(Function<T, Void> function) + public void forEach(final Function<T, Void> function) { for ( final ListenerEntry<T> entry : listeners.values() ) { - try - { - function.apply(entry.listener); - } - catch ( Throwable e ) - { - log.error(String.format("Listener (%s) threw an exception", entry.listener), e); - } + entry.executor.execute + ( + new Runnable() + { + @Override + public void run() + { + try + { + function.apply(entry.listener); + } + catch ( Throwable e ) + { + log.error(String.format("Listener (%s) threw an exception", entry.listener), e); + } + } + } + ); } } }
false
true
public void forEach(Function<T, Void> function) { for ( final ListenerEntry<T> entry : listeners.values() ) { try { function.apply(entry.listener); } catch ( Throwable e ) { log.error(String.format("Listener (%s) threw an exception", entry.listener), e); } } }
public void forEach(final Function<T, Void> function) { for ( final ListenerEntry<T> entry : listeners.values() ) { entry.executor.execute ( new Runnable() { @Override public void run() { try { function.apply(entry.listener); } catch ( Throwable e ) { log.error(String.format("Listener (%s) threw an exception", entry.listener), e); } } } ); } }
diff --git a/cli/src/main/java/com/vmware/bdd/cli/commands/ResourcePoolCommands.java b/cli/src/main/java/com/vmware/bdd/cli/commands/ResourcePoolCommands.java index e7bcecf7..655cf5ec 100644 --- a/cli/src/main/java/com/vmware/bdd/cli/commands/ResourcePoolCommands.java +++ b/cli/src/main/java/com/vmware/bdd/cli/commands/ResourcePoolCommands.java @@ -1,174 +1,174 @@ /***************************************************************************** * Copyright (c) 2012-2013 VMware, Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ package com.vmware.bdd.cli.commands; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliAvailabilityIndicator; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.stereotype.Component; import com.vmware.bdd.apitypes.NodeRead; import com.vmware.bdd.apitypes.ResourcePoolAdd; import com.vmware.bdd.apitypes.ResourcePoolRead; import com.vmware.bdd.cli.rest.CliRestException; import com.vmware.bdd.cli.rest.ResourcePoolRestClient; @Component public class ResourcePoolCommands implements CommandMarker { @Autowired private ResourcePoolRestClient restClient; @CliAvailabilityIndicator({ "resourcepool help" }) public boolean isCommandAvailable() { return true; } @CliCommand(value = "resourcepool add", help = "Add a new resource pool") public void addResourcePool( @CliOption(key = { "name" }, mandatory = true, help = "The resource pool name") final String name, @CliOption(key = { "vcrp" }, mandatory = false, help = "The vc rp name") final String vcrp, @CliOption(key = { "vccluster" }, mandatory = true, help = "The vc cluster name") final String vccluster) { //build ResourcePoolAdd object ResourcePoolAdd rpAdd = new ResourcePoolAdd(); rpAdd.setName(name); rpAdd.setResourcePoolName(CommandsUtils.notNull(vcrp, "")); rpAdd.setVcClusterName(vccluster); //rest invocation try { restClient.add(rpAdd); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_RESULT_ADD); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "resourcepool delete", help = "Delete an unused resource pool") public void deleteResourcePool( @CliOption(key = { "name" }, mandatory = true, help = "The resource pool name") final String name) { //rest invocation try { restClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_RESULT_DELETE); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "resourcepool list", help = "Get resource pool information") public void getResourcePool( @CliOption(key = { "name" }, mandatory = false, help = "The resource pool name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { try { if (name == null) { ResourcePoolRead[] rps = restClient.getAll(); if (rps != null) { prettyOutputResourcePoolsInfo(rps, detail); } } else { ResourcePoolRead rp = restClient.get(name); if (rp != null) { prettyOutputResourcePoolInfo(rp, detail); } } }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private void prettyOutputResourcePoolInfo(ResourcePoolRead rp, boolean detail) { if (rp != null) prettyOutputResourcePoolsInfo(new ResourcePoolRead[] { rp }, detail); } private void prettyOutputResourcePoolsInfo(ResourcePoolRead[] rps, boolean detail) { if (rps != null) { LinkedHashMap<String, List<String>> rpColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); rpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getRpName")); rpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_PATH, Arrays.asList("findPath")); //TODO when backend support it, we can remove the comment. // rpColumnNamesWithGetMethodNames.put( // Constants.FORMAT_TABLE_COLUMN_RAM_MB, // Arrays.asList("getTotalRAMInMB")); // rpColumnNamesWithGetMethodNames.put( // Constants.FORMAT_TABLE_COLUMN_CPU_MHZ, // Arrays.asList("getTotalCPUInMHz")); try { if (detail) { LinkedHashMap<String, List<String>> nodeColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); nodeColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); nodeColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, - Arrays.asList("getIp")); + Arrays.asList("fetchMgtIp")); nodeColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles")); for (ResourcePoolRead rp : rps) { if (rp != null) { CommandsUtils.printInTableFormat( rpColumnNamesWithGetMethodNames, new ResourcePoolRead[] { rp }, Constants.OUTPUT_INDENT); NodeRead[] nodes = rp.getNodes(); if (nodes != null) { System.out.println(); CommandsUtils .printInTableFormat( nodeColumnNamesWithGetMethodNames, nodes, new StringBuilder() .append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT) .toString()); } } System.out.println(); } } else { CommandsUtils.printInTableFormat( rpColumnNamesWithGetMethodNames, rps, Constants.OUTPUT_INDENT); } } catch (Exception e) { System.err.println(e.getMessage()); } } } }
true
true
public void addResourcePool( @CliOption(key = { "name" }, mandatory = true, help = "The resource pool name") final String name, @CliOption(key = { "vcrp" }, mandatory = false, help = "The vc rp name") final String vcrp, @CliOption(key = { "vccluster" }, mandatory = true, help = "The vc cluster name") final String vccluster) { //build ResourcePoolAdd object ResourcePoolAdd rpAdd = new ResourcePoolAdd(); rpAdd.setName(name); rpAdd.setResourcePoolName(CommandsUtils.notNull(vcrp, "")); rpAdd.setVcClusterName(vccluster); //rest invocation try { restClient.add(rpAdd); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_RESULT_ADD); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "resourcepool delete", help = "Delete an unused resource pool") public void deleteResourcePool( @CliOption(key = { "name" }, mandatory = true, help = "The resource pool name") final String name) { //rest invocation try { restClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_RESULT_DELETE); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "resourcepool list", help = "Get resource pool information") public void getResourcePool( @CliOption(key = { "name" }, mandatory = false, help = "The resource pool name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { try { if (name == null) { ResourcePoolRead[] rps = restClient.getAll(); if (rps != null) { prettyOutputResourcePoolsInfo(rps, detail); } } else { ResourcePoolRead rp = restClient.get(name); if (rp != null) { prettyOutputResourcePoolInfo(rp, detail); } } }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private void prettyOutputResourcePoolInfo(ResourcePoolRead rp, boolean detail) { if (rp != null) prettyOutputResourcePoolsInfo(new ResourcePoolRead[] { rp }, detail); } private void prettyOutputResourcePoolsInfo(ResourcePoolRead[] rps, boolean detail) { if (rps != null) { LinkedHashMap<String, List<String>> rpColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); rpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getRpName")); rpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_PATH, Arrays.asList("findPath")); //TODO when backend support it, we can remove the comment. // rpColumnNamesWithGetMethodNames.put( // Constants.FORMAT_TABLE_COLUMN_RAM_MB, // Arrays.asList("getTotalRAMInMB")); // rpColumnNamesWithGetMethodNames.put( // Constants.FORMAT_TABLE_COLUMN_CPU_MHZ, // Arrays.asList("getTotalCPUInMHz")); try { if (detail) { LinkedHashMap<String, List<String>> nodeColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); nodeColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); nodeColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("getIp")); nodeColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles")); for (ResourcePoolRead rp : rps) { if (rp != null) { CommandsUtils.printInTableFormat( rpColumnNamesWithGetMethodNames, new ResourcePoolRead[] { rp }, Constants.OUTPUT_INDENT); NodeRead[] nodes = rp.getNodes(); if (nodes != null) { System.out.println(); CommandsUtils .printInTableFormat( nodeColumnNamesWithGetMethodNames, nodes, new StringBuilder() .append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT) .toString()); } } System.out.println(); } } else { CommandsUtils.printInTableFormat( rpColumnNamesWithGetMethodNames, rps, Constants.OUTPUT_INDENT); } } catch (Exception e) { System.err.println(e.getMessage()); } } } }
public void addResourcePool( @CliOption(key = { "name" }, mandatory = true, help = "The resource pool name") final String name, @CliOption(key = { "vcrp" }, mandatory = false, help = "The vc rp name") final String vcrp, @CliOption(key = { "vccluster" }, mandatory = true, help = "The vc cluster name") final String vccluster) { //build ResourcePoolAdd object ResourcePoolAdd rpAdd = new ResourcePoolAdd(); rpAdd.setName(name); rpAdd.setResourcePoolName(CommandsUtils.notNull(vcrp, "")); rpAdd.setVcClusterName(vccluster); //rest invocation try { restClient.add(rpAdd); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_RESULT_ADD); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_ADD, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "resourcepool delete", help = "Delete an unused resource pool") public void deleteResourcePool( @CliOption(key = { "name" }, mandatory = true, help = "The resource pool name") final String name) { //rest invocation try { restClient.delete(name); CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_RESULT_DELETE); }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_DELETE, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } @CliCommand(value = "resourcepool list", help = "Get resource pool information") public void getResourcePool( @CliOption(key = { "name" }, mandatory = false, help = "The resource pool name") final String name, @CliOption(key = { "detail" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to show node information") final boolean detail) { try { if (name == null) { ResourcePoolRead[] rps = restClient.getAll(); if (rps != null) { prettyOutputResourcePoolsInfo(rps, detail); } } else { ResourcePoolRead rp = restClient.get(name); if (rp != null) { prettyOutputResourcePoolInfo(rp, detail); } } }catch (CliRestException e) { CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_RESOURCEPOOL, name, Constants.OUTPUT_OP_LIST, Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage()); } } private void prettyOutputResourcePoolInfo(ResourcePoolRead rp, boolean detail) { if (rp != null) prettyOutputResourcePoolsInfo(new ResourcePoolRead[] { rp }, detail); } private void prettyOutputResourcePoolsInfo(ResourcePoolRead[] rps, boolean detail) { if (rps != null) { LinkedHashMap<String, List<String>> rpColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); rpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getRpName")); rpColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_PATH, Arrays.asList("findPath")); //TODO when backend support it, we can remove the comment. // rpColumnNamesWithGetMethodNames.put( // Constants.FORMAT_TABLE_COLUMN_RAM_MB, // Arrays.asList("getTotalRAMInMB")); // rpColumnNamesWithGetMethodNames.put( // Constants.FORMAT_TABLE_COLUMN_CPU_MHZ, // Arrays.asList("getTotalCPUInMHz")); try { if (detail) { LinkedHashMap<String, List<String>> nodeColumnNamesWithGetMethodNames = new LinkedHashMap<String, List<String>>(); nodeColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_NAME, Arrays.asList("getName")); nodeColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_IP, Arrays.asList("fetchMgtIp")); nodeColumnNamesWithGetMethodNames.put( Constants.FORMAT_TABLE_COLUMN_ROLES, Arrays.asList("getRoles")); for (ResourcePoolRead rp : rps) { if (rp != null) { CommandsUtils.printInTableFormat( rpColumnNamesWithGetMethodNames, new ResourcePoolRead[] { rp }, Constants.OUTPUT_INDENT); NodeRead[] nodes = rp.getNodes(); if (nodes != null) { System.out.println(); CommandsUtils .printInTableFormat( nodeColumnNamesWithGetMethodNames, nodes, new StringBuilder() .append(Constants.OUTPUT_INDENT) .append(Constants.OUTPUT_INDENT) .toString()); } } System.out.println(); } } else { CommandsUtils.printInTableFormat( rpColumnNamesWithGetMethodNames, rps, Constants.OUTPUT_INDENT); } } catch (Exception e) { System.err.println(e.getMessage()); } } } }
diff --git a/src/org/eclipse/jface/viewers/OwnerDrawLabelProvider.java b/src/org/eclipse/jface/viewers/OwnerDrawLabelProvider.java index 4ba78263..639a1348 100644 --- a/src/org/eclipse/jface/viewers/OwnerDrawLabelProvider.java +++ b/src/org/eclipse/jface/viewers/OwnerDrawLabelProvider.java @@ -1,243 +1,243 @@ /******************************************************************************* * Copyright (c) 2006, 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.viewers; import java.util.HashSet; import java.util.Set; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; /** * OwnerDrawLabelProvider is an abstract implementation of a label provider that * handles custom draw. * * <p> * <b>This class is intended to be subclassed by implementors.</b> * </p> * * @since 3.3 * */ public abstract class OwnerDrawLabelProvider extends CellLabelProvider { static class OwnerDrawListener implements Listener { Set enabledColumns = new HashSet(); int enabledGlobally = 0; private ColumnViewer viewer; OwnerDrawListener(ColumnViewer viewer) { this.viewer = viewer; } public void handleEvent(Event event) { CellLabelProvider provider = viewer.getViewerColumn(event.index) .getLabelProvider(); ViewerColumn column = viewer.getViewerColumn(event.index); if (enabledGlobally > 0 || enabledColumns.contains(column)) { if (provider instanceof OwnerDrawLabelProvider) { Object element = event.item.getData(); OwnerDrawLabelProvider ownerDrawProvider = (OwnerDrawLabelProvider) provider; switch (event.type) { case SWT.MeasureItem: ownerDrawProvider.measure(event, element); break; case SWT.PaintItem: ownerDrawProvider.paint(event, element); break; case SWT.EraseItem: ownerDrawProvider.erase(event, element); break; } } } } } private static final String OWNER_DRAW_LABEL_PROVIDER_LISTENER = "owner_draw_label_provider_listener"; //$NON-NLS-1$ /** * Set up the owner draw callbacks for the viewer. * * @param viewer * the viewer the owner draw is set up * * @deprecated Since 3.4, the default implementation of * {@link CellLabelProvider#initialize(ColumnViewer, ViewerColumn)} * in this class will set up the necessary owner draw callbacks * automatically. Calls to this method can be removed. */ public static void setUpOwnerDraw(final ColumnViewer viewer) { getOrCreateOwnerDrawListener(viewer).enabledGlobally++; } /** * @param viewer * @param control * @return */ private static OwnerDrawListener getOrCreateOwnerDrawListener( final ColumnViewer viewer) { Control control = viewer.getControl(); OwnerDrawListener listener = (OwnerDrawListener) control .getData(OWNER_DRAW_LABEL_PROVIDER_LISTENER); if (listener == null) { listener = new OwnerDrawListener(viewer); control.setData(OWNER_DRAW_LABEL_PROVIDER_LISTENER, listener); control.addListener(SWT.MeasureItem, listener); control.addListener(SWT.EraseItem, listener); control.addListener(SWT.PaintItem, listener); } return listener; } /** * Create a new instance of the receiver based on a column viewer. * */ public OwnerDrawLabelProvider() { } public void dispose(ColumnViewer viewer, ViewerColumn column) { if (!viewer.getControl().isDisposed()) { setOwnerDrawEnabled(viewer, column, false); } super.dispose(viewer, column); } public void initialize(ColumnViewer viewer, ViewerColumn column) { super.initialize(viewer, column); setOwnerDrawEnabled(viewer, column, true); } public void update(ViewerCell cell) { // Force a redraw Rectangle cellBounds = cell.getBounds(); cell.getControl().redraw(cellBounds.x, cellBounds.y, cellBounds.width, cellBounds.height, true); } /** * Handle the erase event. The default implementation colors the background * of selected areas with {@link SWT#COLOR_LIST_SELECTION} and foregrounds * with {@link SWT#COLOR_LIST_SELECTION_TEXT}. Note that this implementation * causes non-native behavior on some platforms. Subclasses should override * this method and <b>not</b> call the super implementation. * * @param event * the erase event * @param element * the model object * @see SWT#EraseItem * @see SWT#COLOR_LIST_SELECTION * @see SWT#COLOR_LIST_SELECTION_TEXT */ protected void erase(Event event, Object element) { Rectangle bounds = event.getBounds(); if ((event.detail & SWT.SELECTED) != 0) { Color oldForeground = event.gc.getForeground(); Color oldBackground = event.gc.getBackground(); event.gc.setBackground(event.item.getDisplay().getSystemColor( SWT.COLOR_LIST_SELECTION)); event.gc.setForeground(event.item.getDisplay().getSystemColor( SWT.COLOR_LIST_SELECTION_TEXT)); event.gc.fillRectangle(bounds); /* restore the old GC colors */ event.gc.setForeground(oldForeground); event.gc.setBackground(oldBackground); /* ensure that default selection is not drawn */ event.detail &= ~SWT.SELECTED; } } /** * Handle the measure event. * * @param event * the measure event * @param element * the model element * @see SWT#MeasureItem */ protected abstract void measure(Event event, Object element); /** * Handle the paint event. * * @param event * the paint event * @param element * the model element * @see SWT#PaintItem */ protected abstract void paint(Event event, Object element); /** * Enables or disables owner draw for the given viewer and column. This * method will attach or remove a listener to the underlying control as * necessary. This method is called from * {@link #initialize(ColumnViewer, ViewerColumn)} and * {@link #dispose(ColumnViewer, ViewerColumn)} but may be called from * subclasses to enable or disable owner draw dynamically. * * @param viewer * the viewer * @param column * the column * @param enabled * <code>true</code> if owner draw should be enabled, * <code>false</code> otherwise * * @since 3.4 */ protected void setOwnerDrawEnabled(ColumnViewer viewer, ViewerColumn column, boolean enabled) { if (enabled) { OwnerDrawListener listener = getOrCreateOwnerDrawListener(viewer); if (column == null) { listener.enabledGlobally++; } else { listener.enabledColumns.add(column); } } else { OwnerDrawListener listener = (OwnerDrawListener) viewer - .getData(OWNER_DRAW_LABEL_PROVIDER_LISTENER); + .getControl().getData(OWNER_DRAW_LABEL_PROVIDER_LISTENER); if (listener != null) { if (column == null) { listener.enabledGlobally--; } else { listener.enabledColumns.remove(column); } if (listener.enabledColumns.isEmpty() && listener.enabledGlobally <= 0) { viewer.getControl().removeListener(SWT.MeasureItem, listener); viewer.getControl().removeListener(SWT.EraseItem, listener); viewer.getControl().removeListener(SWT.PaintItem, listener); viewer.getControl().setData(OWNER_DRAW_LABEL_PROVIDER_LISTENER, null); } } } } }
true
true
protected void setOwnerDrawEnabled(ColumnViewer viewer, ViewerColumn column, boolean enabled) { if (enabled) { OwnerDrawListener listener = getOrCreateOwnerDrawListener(viewer); if (column == null) { listener.enabledGlobally++; } else { listener.enabledColumns.add(column); } } else { OwnerDrawListener listener = (OwnerDrawListener) viewer .getData(OWNER_DRAW_LABEL_PROVIDER_LISTENER); if (listener != null) { if (column == null) { listener.enabledGlobally--; } else { listener.enabledColumns.remove(column); } if (listener.enabledColumns.isEmpty() && listener.enabledGlobally <= 0) { viewer.getControl().removeListener(SWT.MeasureItem, listener); viewer.getControl().removeListener(SWT.EraseItem, listener); viewer.getControl().removeListener(SWT.PaintItem, listener); viewer.getControl().setData(OWNER_DRAW_LABEL_PROVIDER_LISTENER, null); } } } }
protected void setOwnerDrawEnabled(ColumnViewer viewer, ViewerColumn column, boolean enabled) { if (enabled) { OwnerDrawListener listener = getOrCreateOwnerDrawListener(viewer); if (column == null) { listener.enabledGlobally++; } else { listener.enabledColumns.add(column); } } else { OwnerDrawListener listener = (OwnerDrawListener) viewer .getControl().getData(OWNER_DRAW_LABEL_PROVIDER_LISTENER); if (listener != null) { if (column == null) { listener.enabledGlobally--; } else { listener.enabledColumns.remove(column); } if (listener.enabledColumns.isEmpty() && listener.enabledGlobally <= 0) { viewer.getControl().removeListener(SWT.MeasureItem, listener); viewer.getControl().removeListener(SWT.EraseItem, listener); viewer.getControl().removeListener(SWT.PaintItem, listener); viewer.getControl().setData(OWNER_DRAW_LABEL_PROVIDER_LISTENER, null); } } } }
diff --git a/BitcoinJKit/java/bitcoinkit/src/main/java/com/hive/bitcoinkit/BitcoinManager.java b/BitcoinJKit/java/bitcoinkit/src/main/java/com/hive/bitcoinkit/BitcoinManager.java index 669d78e..a09aacb 100644 --- a/BitcoinJKit/java/bitcoinkit/src/main/java/com/hive/bitcoinkit/BitcoinManager.java +++ b/BitcoinJKit/java/bitcoinkit/src/main/java/com/hive/bitcoinkit/BitcoinManager.java @@ -1,406 +1,406 @@ package com.hive.bitcoinkit; import static com.google.bitcoin.core.Utils.bytesToHexString; import com.google.bitcoin.core.*; import com.google.bitcoin.crypto.KeyCrypterException; import com.google.bitcoin.discovery.DnsDiscovery; import com.google.bitcoin.params.MainNetParams; import com.google.bitcoin.params.RegTestParams; import com.google.bitcoin.params.TestNet3Params; import com.google.bitcoin.script.Script; import com.google.bitcoin.store.BlockStore; import com.google.bitcoin.store.SPVBlockStore; import com.google.bitcoin.store.UnreadableWalletException; import com.google.bitcoin.utils.BriefLogFormatter; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.math.BigInteger; import java.net.InetAddress; import java.util.List; import java.util.concurrent.TimeUnit; public class BitcoinManager implements PeerEventListener { private NetworkParameters networkParams; private Wallet wallet; private String dataDirectory; private PeerGroup peerGroup; private BlockStore blockStore; private File walletFile; private int blocksToDownload; public void setTestingNetwork(boolean testing) { if (testing) { this.networkParams = TestNet3Params.get(); } else { this.networkParams = MainNetParams.get(); } } public void setDataDirectory(String path) { dataDirectory = path; } public String getWalletAddres() { ECKey ecKey = wallet.getKeys().get(0); return ecKey.toAddress(networkParams).toString(); } public BigInteger getBalance() { return wallet.getBalance(); } public String getBalanceString() { if (wallet != null) return getBalance().toString(); return null; } private String getJSONFromTransaction(Transaction tx) { if (tx != null) { try { String confidence = "building"; StringBuffer conns = new StringBuffer(); int connCount = 0; if (tx.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.PENDING) confidence = "pending"; // if (tx.isCoinBase()) // tType = "generated"; conns.append("["); if (tx.getInputs().size() > 0 && tx.getValue(wallet).compareTo(BigInteger.ZERO) > 0) { TransactionInput in = tx.getInput(0); if (connCount > 0) conns.append(", "); conns.append("{ "); try { Script scriptSig = in.getScriptSig(); if (scriptSig.getChunks().size() == 2) conns.append("\"address\": \"" + scriptSig.getFromAddress(networkParams).toString() + "\""); conns.append(" ,\"category\": \"received\" }"); connCount++; } catch (Exception e) { } } if (tx.getOutputs().size() > 0 && tx.getValue(wallet).compareTo(BigInteger.ZERO) < 0) { TransactionOutput out = tx.getOutput(0); if (connCount > 0) conns.append(", "); conns.append("{ "); try { Script scriptPubKey = out.getScriptPubKey(); if (scriptPubKey.isSentToAddress()) conns.append(" \"address\": \"" + scriptPubKey.getToAddress(networkParams).toString() + "\""); conns.append(" ,\"category\": \"sent\" }"); connCount++; } catch (Exception e) { } } conns.append("]"); //else if (tx.get) return "{ \"amount\": " + tx.getValue(wallet) + ", \"txid\": \"" + tx.getHashAsString() + "\"" + ", \"time\": \"" + tx.getUpdateTime() + "\"" + ", \"confidence\": \"" +confidence + "\"" + ", \"details\": " + conns.toString() + "}"; } catch (ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } public int getTransactionCount() { return wallet.getTransactionsByTime().size(); } public String getAllTransactions() { return getTransactions(0, getTransactionCount()); } public String getTransaction(String tx) { Sha256Hash hash = new Sha256Hash(tx); return getJSONFromTransaction(wallet.getTransaction(hash)); } public String getTransaction(int idx) { return getJSONFromTransaction(wallet.getTransactionsByTime().get(idx)); } public String getTransactions(int from, int count) { List<Transaction> transactions = wallet.getTransactionsByTime(); if (from >= transactions.size()) return null; int to = (from + count < transactions.size()) ? from + count : transactions.size(); StringBuffer txs = new StringBuffer(); txs.append("[\n"); boolean first = true; for (; from < to; from++) { if (first) first = false; else txs.append("\n,"); txs.append(getJSONFromTransaction(transactions.get(from))); } txs.append("]\n"); return txs.toString(); } public void sendCoins(String amount, final String sendToAddressString) { try { BigInteger aToSend = new BigInteger(amount); aToSend = aToSend.subtract(Transaction.REFERENCE_DEFAULT_MIN_TX_FEE); Address sendToAddress = new Address(networkParams, sendToAddressString); final Wallet.SendResult sendResult = wallet.sendCoins(peerGroup, sendToAddress, aToSend); Futures.addCallback(sendResult.broadcastComplete, new FutureCallback<Transaction>() { public void onSuccess(Transaction transaction) { onTransactionSuccess(sendResult.tx.getHashAsString()); onTransactionChanged(sendResult.tx.getHashAsString()); } public void onFailure(Throwable throwable) { onTransactionFailed(); throwable.printStackTrace(); } }); } catch (Exception e) { onTransactionFailed(); } } public boolean isAddressValid(String address) { try { Address addr = new Address(networkParams, address); return (addr != null); } catch (Exception e) { return false; } } public void start() throws Exception { + if (networkParams == null) + { + setTestingNetwork(false); + } File chainFile = new File(dataDirectory + "/bitcoinkit.spvchain"); // Try to read the wallet from storage, create a new one if not possible. wallet = null; walletFile = new File(dataDirectory + "/bitcoinkit.wallet"); try { // Wipe the wallet if the chain file was deleted. if (walletFile.exists() && chainFile.exists()) wallet = Wallet.loadFromFile(walletFile); } catch (UnreadableWalletException e) { // System.err.println("Couldn't load wallet: " + e); // Fall through. } if (wallet == null) { - if (networkParams == null) - { - setTestingNetwork(false); - } wallet = new Wallet(networkParams); wallet.addKey(new ECKey()); wallet.saveToFile(walletFile); } //make wallet autosave wallet.autosaveToFile(walletFile, 1, TimeUnit.SECONDS, null); // Fetch the first key in the wallet (should be the only key). ECKey key = wallet.getKeys().iterator().next(); // Load the block chain, if there is one stored locally. If it's going to be freshly created, checkpoint it. // System.out.println("Reading block store from disk"); boolean chainExistedAlready = chainFile.exists(); blockStore = new SPVBlockStore(networkParams, chainFile); if (!chainExistedAlready) { File checkpointsFile = new File(dataDirectory + "/bitcoinkit.checkpoints"); if (checkpointsFile.exists()) { FileInputStream stream = new FileInputStream(checkpointsFile); CheckpointManager.checkpoint(networkParams, stream, blockStore, key.getCreationTimeSeconds()); } } BlockChain chain = new BlockChain(networkParams, wallet, blockStore); // Connect to the localhost node. One minute timeout since we won't try any other peers // System.out.println("Connecting ..."); peerGroup = new PeerGroup(networkParams, chain); // peerGroup.setUserAgent("BitcoinKit", "1.0"); if (networkParams == RegTestParams.get()) { peerGroup.addAddress(InetAddress.getLocalHost()); } else { peerGroup.addPeerDiscovery(new DnsDiscovery(networkParams)); } peerGroup.addWallet(wallet); // We want to know when the balance changes. wallet.addEventListener(new AbstractWalletEventListener() { @Override public void onCoinsReceived(Wallet w, Transaction tx, BigInteger prevBalance, BigInteger newBalance) { assert !newBalance.equals(BigInteger.ZERO); if (!tx.isPending()) return; // It was broadcast, but we can't really verify it's valid until it appears in a block. BigInteger value = tx.getValueSentToMe(w); // System.out.println("Received pending tx for " + Utils.bitcoinValueToFriendlyString(value) + // ": " + tx); onTransactionChanged(tx.getHashAsString()); tx.getConfidence().addEventListener(new TransactionConfidence.Listener() { public void onConfidenceChanged(final Transaction tx2, TransactionConfidence.Listener.ChangeReason reason) { if (tx2.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) { // Coins were confirmed (appeared in a block). tx2.getConfidence().removeEventListener(this); // System.out.println("We get " + tx2); } else { // System.out.println(String.format("Confidence of %s changed, is now: %s", // tx2.getHashAsString(), tx2.getConfidence().toString())); } onTransactionChanged(tx2.getHashAsString()); } }); } }); peerGroup.startAndWait(); peerGroup.start(); onBalanceChanged(); peerGroup.startBlockChainDownload(this); } public void stop() { try { System.out.print("Shutting down ... "); peerGroup.stopAndWait(); wallet.saveToFile(walletFile); blockStore.close(); System.out.print("done "); } catch (Exception e) { throw new RuntimeException(e); } } public void walletExport(String path) { } /* Implementing native callbacks here */ public native void onTransactionChanged(String txid); public native void onTransactionFailed(); public native void onTransactionSuccess(String txid); public native void onSynchronizationUpdate(int percent); public void onPeerCountChange(int peersConnected) { // System.out.println("Peers " + peersConnected); } public native void onBalanceChanged(); /* Implementing peer listener */ public void onBlocksDownloaded(Peer peer, Block block, int blocksLeft) { int downloadedSoFar = blocksToDownload - blocksLeft; if (blocksToDownload == 0) onSynchronizationUpdate(10000); else onSynchronizationUpdate(10000*downloadedSoFar / blocksToDownload); } public void onChainDownloadStarted(Peer peer, int blocksLeft) { blocksToDownload = blocksLeft; if (blocksToDownload == 0) onSynchronizationUpdate(10000); else onSynchronizationUpdate(0); } public void onPeerConnected(Peer peer, int peerCount) { onPeerCountChange(peerCount); } public void onPeerDisconnected(Peer peer, int peerCount) { onPeerCountChange(peerCount); } public Message onPreMessageReceived(Peer peer, Message m) { return m; } public void onTransaction(Peer peer, Transaction t) { } public List<Message> getData(Peer peer, GetDataMessage m) { return null; } }
false
true
public void start() throws Exception { File chainFile = new File(dataDirectory + "/bitcoinkit.spvchain"); // Try to read the wallet from storage, create a new one if not possible. wallet = null; walletFile = new File(dataDirectory + "/bitcoinkit.wallet"); try { // Wipe the wallet if the chain file was deleted. if (walletFile.exists() && chainFile.exists()) wallet = Wallet.loadFromFile(walletFile); } catch (UnreadableWalletException e) { // System.err.println("Couldn't load wallet: " + e); // Fall through. } if (wallet == null) { if (networkParams == null) { setTestingNetwork(false); } wallet = new Wallet(networkParams); wallet.addKey(new ECKey()); wallet.saveToFile(walletFile); } //make wallet autosave wallet.autosaveToFile(walletFile, 1, TimeUnit.SECONDS, null); // Fetch the first key in the wallet (should be the only key). ECKey key = wallet.getKeys().iterator().next(); // Load the block chain, if there is one stored locally. If it's going to be freshly created, checkpoint it. // System.out.println("Reading block store from disk"); boolean chainExistedAlready = chainFile.exists(); blockStore = new SPVBlockStore(networkParams, chainFile); if (!chainExistedAlready) { File checkpointsFile = new File(dataDirectory + "/bitcoinkit.checkpoints"); if (checkpointsFile.exists()) { FileInputStream stream = new FileInputStream(checkpointsFile); CheckpointManager.checkpoint(networkParams, stream, blockStore, key.getCreationTimeSeconds()); } } BlockChain chain = new BlockChain(networkParams, wallet, blockStore); // Connect to the localhost node. One minute timeout since we won't try any other peers // System.out.println("Connecting ..."); peerGroup = new PeerGroup(networkParams, chain); // peerGroup.setUserAgent("BitcoinKit", "1.0"); if (networkParams == RegTestParams.get()) { peerGroup.addAddress(InetAddress.getLocalHost()); } else { peerGroup.addPeerDiscovery(new DnsDiscovery(networkParams)); } peerGroup.addWallet(wallet); // We want to know when the balance changes. wallet.addEventListener(new AbstractWalletEventListener() { @Override public void onCoinsReceived(Wallet w, Transaction tx, BigInteger prevBalance, BigInteger newBalance) { assert !newBalance.equals(BigInteger.ZERO); if (!tx.isPending()) return; // It was broadcast, but we can't really verify it's valid until it appears in a block. BigInteger value = tx.getValueSentToMe(w); // System.out.println("Received pending tx for " + Utils.bitcoinValueToFriendlyString(value) + // ": " + tx); onTransactionChanged(tx.getHashAsString()); tx.getConfidence().addEventListener(new TransactionConfidence.Listener() { public void onConfidenceChanged(final Transaction tx2, TransactionConfidence.Listener.ChangeReason reason) { if (tx2.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) { // Coins were confirmed (appeared in a block). tx2.getConfidence().removeEventListener(this); // System.out.println("We get " + tx2); } else { // System.out.println(String.format("Confidence of %s changed, is now: %s", // tx2.getHashAsString(), tx2.getConfidence().toString())); } onTransactionChanged(tx2.getHashAsString()); } }); } }); peerGroup.startAndWait(); peerGroup.start(); onBalanceChanged(); peerGroup.startBlockChainDownload(this); }
public void start() throws Exception { if (networkParams == null) { setTestingNetwork(false); } File chainFile = new File(dataDirectory + "/bitcoinkit.spvchain"); // Try to read the wallet from storage, create a new one if not possible. wallet = null; walletFile = new File(dataDirectory + "/bitcoinkit.wallet"); try { // Wipe the wallet if the chain file was deleted. if (walletFile.exists() && chainFile.exists()) wallet = Wallet.loadFromFile(walletFile); } catch (UnreadableWalletException e) { // System.err.println("Couldn't load wallet: " + e); // Fall through. } if (wallet == null) { wallet = new Wallet(networkParams); wallet.addKey(new ECKey()); wallet.saveToFile(walletFile); } //make wallet autosave wallet.autosaveToFile(walletFile, 1, TimeUnit.SECONDS, null); // Fetch the first key in the wallet (should be the only key). ECKey key = wallet.getKeys().iterator().next(); // Load the block chain, if there is one stored locally. If it's going to be freshly created, checkpoint it. // System.out.println("Reading block store from disk"); boolean chainExistedAlready = chainFile.exists(); blockStore = new SPVBlockStore(networkParams, chainFile); if (!chainExistedAlready) { File checkpointsFile = new File(dataDirectory + "/bitcoinkit.checkpoints"); if (checkpointsFile.exists()) { FileInputStream stream = new FileInputStream(checkpointsFile); CheckpointManager.checkpoint(networkParams, stream, blockStore, key.getCreationTimeSeconds()); } } BlockChain chain = new BlockChain(networkParams, wallet, blockStore); // Connect to the localhost node. One minute timeout since we won't try any other peers // System.out.println("Connecting ..."); peerGroup = new PeerGroup(networkParams, chain); // peerGroup.setUserAgent("BitcoinKit", "1.0"); if (networkParams == RegTestParams.get()) { peerGroup.addAddress(InetAddress.getLocalHost()); } else { peerGroup.addPeerDiscovery(new DnsDiscovery(networkParams)); } peerGroup.addWallet(wallet); // We want to know when the balance changes. wallet.addEventListener(new AbstractWalletEventListener() { @Override public void onCoinsReceived(Wallet w, Transaction tx, BigInteger prevBalance, BigInteger newBalance) { assert !newBalance.equals(BigInteger.ZERO); if (!tx.isPending()) return; // It was broadcast, but we can't really verify it's valid until it appears in a block. BigInteger value = tx.getValueSentToMe(w); // System.out.println("Received pending tx for " + Utils.bitcoinValueToFriendlyString(value) + // ": " + tx); onTransactionChanged(tx.getHashAsString()); tx.getConfidence().addEventListener(new TransactionConfidence.Listener() { public void onConfidenceChanged(final Transaction tx2, TransactionConfidence.Listener.ChangeReason reason) { if (tx2.getConfidence().getConfidenceType() == TransactionConfidence.ConfidenceType.BUILDING) { // Coins were confirmed (appeared in a block). tx2.getConfidence().removeEventListener(this); // System.out.println("We get " + tx2); } else { // System.out.println(String.format("Confidence of %s changed, is now: %s", // tx2.getHashAsString(), tx2.getConfidence().toString())); } onTransactionChanged(tx2.getHashAsString()); } }); } }); peerGroup.startAndWait(); peerGroup.start(); onBalanceChanged(); peerGroup.startBlockChainDownload(this); }
diff --git a/src/main/java/edu/wm/werewolf/dao/MongoUserDao.java b/src/main/java/edu/wm/werewolf/dao/MongoUserDao.java index 1ee075a..193f31a 100644 --- a/src/main/java/edu/wm/werewolf/dao/MongoUserDao.java +++ b/src/main/java/edu/wm/werewolf/dao/MongoUserDao.java @@ -1,99 +1,101 @@ package edu.wm.werewolf.dao; import java.util.ArrayList; import java.util.List; import edu.wm.werewolf.domain.Player; import edu.wm.werewolf.domain.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; //@Document(collection = "users") public class MongoUserDao implements IUserDAO{ private static final Logger logger = LoggerFactory.getLogger(MongoUserDao.class); @Autowired DB db; @Override public void createUser(User user) { DBCollection table = db.getCollection("user"); table.drop(); + table = db.getCollection("players"); + table.drop(); // DBCollection table = db.getCollection("user"); // BasicDBObject documentDetail = new BasicDBObject(); // documentDetail.put("firstName", user.getFirstName()); // documentDetail.put("lastName", user.getLastName()); // documentDetail.put("password", user.getHashedPassword()); // documentDetail.put("id", user.getId()); // documentDetail.put("score", user.getScore()); // documentDetail.put("image", user.getImageURL()); // documentDetail.put("username", user.getUsername()); // documentDetail.put("isAdmin", user.isAdmin()); // table.insert(documentDetail); } @Override public User getUserbyID (String id) { DBCollection table = db.getCollection("user"); BasicDBObject query = new BasicDBObject("id", id); DBCursor cursor = table.find(query); User user = null; while (cursor.hasNext()) { DBObject userObject = cursor.next(); user = new User((String)userObject.get("id"), (String)userObject.get("firstName"), (String)userObject.get("lastName"), (String)userObject.get("username"), (String)userObject.get("password"), (String)userObject.get("image"), (boolean)userObject.get("isAdmin")); } return user; } @Override public User getUserByName (String name) { DBCollection table = db.getCollection("user"); BasicDBObject query = new BasicDBObject("firstName", name); DBCursor cursor = table.find(query); User user = null; while (cursor.hasNext()) { DBObject userObject = cursor.next(); user = new User((String)userObject.get("id"), (String)userObject.get("firstName"), (String)userObject.get("lastName"), (String)userObject.get("username"), (String)userObject.get("password"), (String)userObject.get("image"), (boolean)userObject.get("isAdmin")); } return user; } @Override public List<User> getAllUsers() { DBCollection table = db.getCollection("user"); DBCursor cursor = table.find(); List <User> users = new ArrayList<>(); while (cursor.hasNext()) { DBObject userObject = cursor.next(); User user = new User((String)userObject.get("id"), (String)userObject.get("firstName"), (String)userObject.get("lastName"), (String)userObject.get("username"), (String)userObject.get("password"), (String)userObject.get("image"), (boolean)userObject.get("isAdmin")); users.add(user); } return users; } }
true
true
public void createUser(User user) { DBCollection table = db.getCollection("user"); table.drop(); // DBCollection table = db.getCollection("user"); // BasicDBObject documentDetail = new BasicDBObject(); // documentDetail.put("firstName", user.getFirstName()); // documentDetail.put("lastName", user.getLastName()); // documentDetail.put("password", user.getHashedPassword()); // documentDetail.put("id", user.getId()); // documentDetail.put("score", user.getScore()); // documentDetail.put("image", user.getImageURL()); // documentDetail.put("username", user.getUsername()); // documentDetail.put("isAdmin", user.isAdmin()); // table.insert(documentDetail); }
public void createUser(User user) { DBCollection table = db.getCollection("user"); table.drop(); table = db.getCollection("players"); table.drop(); // DBCollection table = db.getCollection("user"); // BasicDBObject documentDetail = new BasicDBObject(); // documentDetail.put("firstName", user.getFirstName()); // documentDetail.put("lastName", user.getLastName()); // documentDetail.put("password", user.getHashedPassword()); // documentDetail.put("id", user.getId()); // documentDetail.put("score", user.getScore()); // documentDetail.put("image", user.getImageURL()); // documentDetail.put("username", user.getUsername()); // documentDetail.put("isAdmin", user.isAdmin()); // table.insert(documentDetail); }
diff --git a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java index 75d1f334..194888c6 100644 --- a/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java +++ b/jetty-security/src/main/java/org/eclipse/jetty/security/authentication/FormAuthenticator.java @@ -1,369 +1,369 @@ // ======================================================================== // Copyright (c) 2008-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.security.authentication; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import javax.servlet.http.HttpSession; import org.eclipse.jetty.http.HttpHeaders; import org.eclipse.jetty.http.security.Constraint; import org.eclipse.jetty.security.Authenticator; import org.eclipse.jetty.security.UserAuthentication; import org.eclipse.jetty.security.ServerAuthException; import org.eclipse.jetty.server.Authentication; import org.eclipse.jetty.server.UserIdentity; import org.eclipse.jetty.server.Authentication.User; import org.eclipse.jetty.util.StringUtil; import org.eclipse.jetty.util.URIUtil; import org.eclipse.jetty.util.log.Log; /** * FORM Authenticator. * * The form authenticator redirects unauthenticated requests to a log page * which should use a form to gather username/password from the user and send them * to the /j_security_check URI within the context. FormAuthentication is intended * to be used together with the {@link SessionCachingAuthenticator} so that the * auth results may be associated with the session. * * This authenticator implements form authentication using dispatchers unless * the {@link #__FORM_DISPATCH} init parameters is set to false. * */ public class FormAuthenticator extends LoginAuthenticator { public final static String __FORM_LOGIN_PAGE="org.eclipse.jetty.security.form_login_page"; public final static String __FORM_ERROR_PAGE="org.eclipse.jetty.security.form_error_page"; public final static String __FORM_DISPATCH="org.eclipse.jetty.security.dispatch"; public final static String __J_URI = "org.eclipse.jetty.util.URI"; public final static String __J_AUTHENTICATED = "org.eclipse.jetty.server.Auth"; public final static String __J_SECURITY_CHECK = "/j_security_check"; public final static String __J_USERNAME = "j_username"; public final static String __J_PASSWORD = "j_password"; private String _formErrorPage; private String _formErrorPath; private String _formLoginPage; private String _formLoginPath; private boolean _dispatch; public FormAuthenticator() { } /* ------------------------------------------------------------ */ public FormAuthenticator(String login,String error) { if (login!=null) setLoginPage(login); if (error!=null) setErrorPage(error); } /* ------------------------------------------------------------ */ /** * @see org.eclipse.jetty.security.authentication.LoginAuthenticator#setConfiguration(org.eclipse.jetty.security.Authenticator.Configuration) */ @Override public void setConfiguration(Configuration configuration) { super.setConfiguration(configuration); String login=configuration.getInitParameter(FormAuthenticator.__FORM_LOGIN_PAGE); if (login!=null) setLoginPage(login); String error=configuration.getInitParameter(FormAuthenticator.__FORM_ERROR_PAGE); if (error!=null) setErrorPage(error); String dispatch=configuration.getInitParameter(FormAuthenticator.__FORM_DISPATCH); _dispatch=dispatch==null || Boolean.getBoolean(dispatch); } /* ------------------------------------------------------------ */ public String getAuthMethod() { return Constraint.__FORM_AUTH; } /* ------------------------------------------------------------ */ private void setLoginPage(String path) { if (!path.startsWith("/")) { Log.warn("form-login-page must start with /"); path = "/" + path; } _formLoginPage = path; _formLoginPath = path; if (_formLoginPath.indexOf('?') > 0) _formLoginPath = _formLoginPath.substring(0, _formLoginPath.indexOf('?')); } /* ------------------------------------------------------------ */ private void setErrorPage(String path) { if (path == null || path.trim().length() == 0) { _formErrorPath = null; _formErrorPage = null; } else { if (!path.startsWith("/")) { Log.warn("form-error-page must start with /"); path = "/" + path; } _formErrorPage = path; _formErrorPath = path; if (_formErrorPath.indexOf('?') > 0) _formErrorPath = _formErrorPath.substring(0, _formErrorPath.indexOf('?')); } } /* ------------------------------------------------------------ */ public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; HttpSession session = request.getSession(mandatory); - String uri = request.getPathInfo(); + String uri = request.getRequestURL().toString();//getPathInfo(); // not mandatory or not authenticated if (session == null || isLoginOrErrorPage(uri)) { return Authentication.NOT_CHECKED; } try { // Handle a request for authentication. if (uri==null) uri=URIUtil.SLASH; else if (uri.endsWith(__J_SECURITY_CHECK)) { final String username = request.getParameter(__J_USERNAME); final String password = request.getParameter(__J_PASSWORD); UserIdentity user = _loginService.login(username,password); if (user!=null) { // Redirect to original request String nuri; synchronized(session) { nuri = (String) session.getAttribute(__J_URI); session.removeAttribute(__J_URI); } if (nuri == null || nuri.length() == 0) { nuri = request.getContextPath(); if (nuri.length() == 0) nuri = URIUtil.SLASH; } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(nuri)); return new FormAuthentication(this,user); } // not authenticated if (Log.isDebugEnabled()) Log.debug("Form authentication FAILED for " + StringUtil.printable(username)); if (_formErrorPage == null) { if (response != null) response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formErrorPage)); } return Authentication.SEND_FAILURE; } if (mandatory) { // redirect to login page synchronized (session) { if (session.getAttribute(__J_URI)==null) { StringBuffer buf = request.getRequestURL(); if (request.getQueryString() != null) buf.append("?").append(request.getQueryString()); session.setAttribute(__J_URI, buf.toString()); } } if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formLoginPage)); } return Authentication.SEND_CONTINUE; } return Authentication.UNAUTHENTICATED; } catch (IOException e) { throw new ServerAuthException(e); } catch (ServletException e) { throw new ServerAuthException(e); } } /* ------------------------------------------------------------ */ public boolean isLoginOrErrorPage(String pathInContext) { return pathInContext != null && (pathInContext.equals(_formErrorPath) || pathInContext.equals(_formLoginPath)); } /* ------------------------------------------------------------ */ public boolean secureResponse(ServletRequest req, ServletResponse res, boolean mandatory, User validatedUser) throws ServerAuthException { return true; } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ protected static class FormRequest extends HttpServletRequestWrapper { public FormRequest(HttpServletRequest request) { super(request); } @Override public long getDateHeader(String name) { if (name.toLowerCase().startsWith("if-")) return -1; return super.getDateHeader(name); } @Override public String getHeader(String name) { if (name.toLowerCase().startsWith("if-")) return null; return super.getHeader(name); } @Override public Enumeration getHeaderNames() { return Collections.enumeration(Collections.list(super.getHeaderNames())); } @Override public Enumeration getHeaders(String name) { if (name.toLowerCase().startsWith("if-")) return Collections.enumeration(Collections.EMPTY_LIST); return super.getHeaders(name); } } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ protected static class FormResponse extends HttpServletResponseWrapper { public FormResponse(HttpServletResponse response) { super(response); } @Override public void addDateHeader(String name, long date) { if (notIgnored(name)) super.addDateHeader(name,date); } @Override public void addHeader(String name, String value) { if (notIgnored(name)) super.addHeader(name,value); } @Override public void setDateHeader(String name, long date) { if (notIgnored(name)) super.setDateHeader(name,date); } @Override public void setHeader(String name, String value) { if (notIgnored(name)) super.setHeader(name,value); } private boolean notIgnored(String name) { if (HttpHeaders.CACHE_CONTROL.equalsIgnoreCase(name) || HttpHeaders.PRAGMA.equalsIgnoreCase(name) || HttpHeaders.ETAG.equalsIgnoreCase(name) || HttpHeaders.EXPIRES.equalsIgnoreCase(name) || HttpHeaders.LAST_MODIFIED.equalsIgnoreCase(name) || HttpHeaders.AGE.equalsIgnoreCase(name)) return false; return true; } } public static class FormAuthentication extends UserAuthentication implements Authentication.ResponseSent { public FormAuthentication(Authenticator authenticator, UserIdentity userIdentity) { super(authenticator,userIdentity); } public String toString() { return "Form"+super.toString(); } } }
true
true
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; HttpSession session = request.getSession(mandatory); String uri = request.getPathInfo(); // not mandatory or not authenticated if (session == null || isLoginOrErrorPage(uri)) { return Authentication.NOT_CHECKED; } try { // Handle a request for authentication. if (uri==null) uri=URIUtil.SLASH; else if (uri.endsWith(__J_SECURITY_CHECK)) { final String username = request.getParameter(__J_USERNAME); final String password = request.getParameter(__J_PASSWORD); UserIdentity user = _loginService.login(username,password); if (user!=null) { // Redirect to original request String nuri; synchronized(session) { nuri = (String) session.getAttribute(__J_URI); session.removeAttribute(__J_URI); } if (nuri == null || nuri.length() == 0) { nuri = request.getContextPath(); if (nuri.length() == 0) nuri = URIUtil.SLASH; } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(nuri)); return new FormAuthentication(this,user); } // not authenticated if (Log.isDebugEnabled()) Log.debug("Form authentication FAILED for " + StringUtil.printable(username)); if (_formErrorPage == null) { if (response != null) response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formErrorPage)); } return Authentication.SEND_FAILURE; } if (mandatory) { // redirect to login page synchronized (session) { if (session.getAttribute(__J_URI)==null) { StringBuffer buf = request.getRequestURL(); if (request.getQueryString() != null) buf.append("?").append(request.getQueryString()); session.setAttribute(__J_URI, buf.toString()); } } if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formLoginPage)); } return Authentication.SEND_CONTINUE; } return Authentication.UNAUTHENTICATED; } catch (IOException e) { throw new ServerAuthException(e); } catch (ServletException e) { throw new ServerAuthException(e); } }
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; HttpSession session = request.getSession(mandatory); String uri = request.getRequestURL().toString();//getPathInfo(); // not mandatory or not authenticated if (session == null || isLoginOrErrorPage(uri)) { return Authentication.NOT_CHECKED; } try { // Handle a request for authentication. if (uri==null) uri=URIUtil.SLASH; else if (uri.endsWith(__J_SECURITY_CHECK)) { final String username = request.getParameter(__J_USERNAME); final String password = request.getParameter(__J_PASSWORD); UserIdentity user = _loginService.login(username,password); if (user!=null) { // Redirect to original request String nuri; synchronized(session) { nuri = (String) session.getAttribute(__J_URI); session.removeAttribute(__J_URI); } if (nuri == null || nuri.length() == 0) { nuri = request.getContextPath(); if (nuri.length() == 0) nuri = URIUtil.SLASH; } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(nuri)); return new FormAuthentication(this,user); } // not authenticated if (Log.isDebugEnabled()) Log.debug("Form authentication FAILED for " + StringUtil.printable(username)); if (_formErrorPage == null) { if (response != null) response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formErrorPage)); } return Authentication.SEND_FAILURE; } if (mandatory) { // redirect to login page synchronized (session) { if (session.getAttribute(__J_URI)==null) { StringBuffer buf = request.getRequestURL(); if (request.getQueryString() != null) buf.append("?").append(request.getQueryString()); session.setAttribute(__J_URI, buf.toString()); } } if (_dispatch) { RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage); response.setHeader(HttpHeaders.CACHE_CONTROL,"No-cache"); response.setDateHeader(HttpHeaders.EXPIRES,1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); } else { response.sendRedirect(URIUtil.addPaths(request.getContextPath(),_formLoginPage)); } return Authentication.SEND_CONTINUE; } return Authentication.UNAUTHENTICATED; } catch (IOException e) { throw new ServerAuthException(e); } catch (ServletException e) { throw new ServerAuthException(e); } }
diff --git a/plugins/org.eclipse.dltk.ruby.core/src/org/eclipse/dltk/ruby/typeinference/RubyTypeInferencingUtils.java b/plugins/org.eclipse.dltk.ruby.core/src/org/eclipse/dltk/ruby/typeinference/RubyTypeInferencingUtils.java index 92878d86..8fceb46c 100644 --- a/plugins/org.eclipse.dltk.ruby.core/src/org/eclipse/dltk/ruby/typeinference/RubyTypeInferencingUtils.java +++ b/plugins/org.eclipse.dltk.ruby.core/src/org/eclipse/dltk/ruby/typeinference/RubyTypeInferencingUtils.java @@ -1,544 +1,543 @@ package org.eclipse.dltk.ruby.typeinference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.dltk.ast.ASTNode; import org.eclipse.dltk.ast.ASTVisitor; import org.eclipse.dltk.ast.declarations.MethodDeclaration; import org.eclipse.dltk.ast.declarations.ModuleDeclaration; import org.eclipse.dltk.ast.declarations.TypeDeclaration; import org.eclipse.dltk.ast.expressions.Assignment; import org.eclipse.dltk.ast.expressions.Expression; import org.eclipse.dltk.ast.references.ConstantReference; import org.eclipse.dltk.ast.references.VariableReference; import org.eclipse.dltk.ast.statements.Statement; import org.eclipse.dltk.core.DLTKModelUtil; import org.eclipse.dltk.core.ISourceModule; import org.eclipse.dltk.core.IType; import org.eclipse.dltk.core.mixin.IMixinElement; import org.eclipse.dltk.core.mixin.IMixinRequestor; import org.eclipse.dltk.core.mixin.MixinModel; import org.eclipse.dltk.core.search.TypeNameMatch; import org.eclipse.dltk.core.search.TypeNameMatchRequestor; import org.eclipse.dltk.evaluation.types.AmbiguousType; import org.eclipse.dltk.evaluation.types.UnknownType; import org.eclipse.dltk.ruby.ast.ColonExpression; import org.eclipse.dltk.ruby.core.RubyPlugin; import org.eclipse.dltk.ruby.internal.parser.RubySourceElementParser; import org.eclipse.dltk.ruby.internal.parser.mixin.IRubyMixinElement; import org.eclipse.dltk.ruby.internal.parser.mixin.RubyMixinBuildVisitor; import org.eclipse.dltk.ruby.internal.parser.mixin.RubyMixinClass; import org.eclipse.dltk.ruby.internal.parser.mixin.RubyMixinMethod; import org.eclipse.dltk.ruby.internal.parser.mixin.RubyMixinModel; import org.eclipse.dltk.ti.IContext; import org.eclipse.dltk.ti.IInstanceContext; import org.eclipse.dltk.ti.ISourceModuleContext; import org.eclipse.dltk.ti.types.IEvaluatedType; import org.eclipse.dltk.ti.types.RecursionTypeCall; public class RubyTypeInferencingUtils { /** * Searches all top level types, which starts with prefix */ public static IType[] getAllTypes( org.eclipse.dltk.core.ISourceModule module, String prefix) { final List types = new ArrayList(); TypeNameMatchRequestor requestor = new TypeNameMatchRequestor() { public void acceptTypeNameMatch(TypeNameMatch match) { IType type = (IType) match.getType(); if (type.getParent() instanceof ISourceModule) { types.add(type); } } }; DLTKModelUtil.searchTypeDeclarations(module.getScriptProject(), prefix + "*", requestor); return (IType[]) types.toArray(new IType[types.size()]); } public static ASTNode[] getAllStaticScopes(ModuleDeclaration rootNode, final int requestedOffset) { final Collection scopes = new ArrayList(); ASTVisitor visitor = new OffsetTargetedASTVisitor(requestedOffset) { public boolean visitInteresting(MethodDeclaration s) { scopes.add(s); return true; } public boolean visitInteresting(ModuleDeclaration s) { scopes.add(s); return true; } public boolean visitInteresting(TypeDeclaration s) { scopes.add(s); return true; } // TODO: handle Ruby blocks here // XXX: what for? }; try { rootNode.traverse(visitor); } catch (Exception e) { RubyPlugin.log(e); } if (scopes.size() == 0) scopes.add(rootNode); return (ASTNode[]) scopes.toArray(new ASTNode[scopes.size()]); } public static IMixinElement[] getModelStaticScopes(MixinModel model, ModuleDeclaration rootNode, final int requestedOffset) { String[] modelStaticScopesKeys = getModelStaticScopesKeys(model, rootNode, requestedOffset); IMixinElement[] result = new IMixinElement[modelStaticScopesKeys.length]; for (int i = 0; i < modelStaticScopesKeys.length; i++) { result[i] = model.get(modelStaticScopesKeys[i]); if (result[i] == null) throw new RuntimeException("getModelStaticScopes(): Failed to get element from mixin-model: " + modelStaticScopesKeys[i]); } return result; } public static String[] getModelStaticScopesKeys(MixinModel model, ModuleDeclaration rootNode, final int requestedOffset) { ASTNode[] allStaticScopes = RubyTypeInferencingUtils .getAllStaticScopes(rootNode, requestedOffset); return RubyMixinBuildVisitor.restoreScopesByNodes(allStaticScopes); } private static String evaluateClassKey(Statement expr, List topScopes, MixinModel model) { if (expr instanceof ColonExpression) { ColonExpression colonExpression = (ColonExpression) expr; if (colonExpression.isFull()) { return colonExpression.getName(); } else { String key = evaluateClassKey(colonExpression.getLeft(), topScopes, model); if (key != null) { return key + MixinModel.SEPARATOR + colonExpression.getName(); } } } else if (expr instanceof ConstantReference) { ConstantReference constantReference = (ConstantReference) expr; String name = constantReference.getName(); String[] top = (String[]) topScopes.toArray(new String[topScopes .size()]); for (int i = top.length - 1; i >= 0; i--) { String pk = top[i] + MixinModel.SEPARATOR + name; String[] findKeys = model.findKeys(pk); if (findKeys != null && findKeys.length > 0) return pk; } String[] findKeys = model.findKeys(name); if (findKeys != null && findKeys.length > 0) return name; } return null; } public static LocalVariableInfo findLocalVariable( ModuleDeclaration rootNode, final int requestedOffset, String varName) { ASTNode[] staticScopes = getAllStaticScopes(rootNode, requestedOffset); int end = staticScopes.length; for (int start = end - 1; start >= 0; start--) { ASTNode currentScope = staticScopes[start]; if (!isRootLocalScope(currentScope)) continue; ASTNode nextScope = (end < staticScopes.length ? staticScopes[end] : null); Assignment[] assignments = findLocalVariableAssignments( currentScope, nextScope, varName); if (assignments.length > 0) { return new LocalVariableInfo(currentScope, assignments); } } return null; } public static IEvaluatedType determineSelfClass(IContext context, int keyOffset) { if (context instanceof IInstanceContext) { IInstanceContext instanceContext = (IInstanceContext) context; return instanceContext.getInstanceType(); } else { ISourceModuleContext basicContext = (ISourceModuleContext) context; return determineSelfClass(basicContext.getSourceModule(), basicContext.getRootNode(), keyOffset); } } /** * Determines a fully-qualified names of the class scope that the given * offset is statically enclosed in. * * @param sourceModule * a module containing the given offsets * @param rootNode * the root of AST corresponding to the given source module * @param keyOffset * the offset * @return The type of <code>self</code> at the given offset (never null) */ public static RubyClassType determineSelfClass( final ISourceModule sourceModule, ModuleDeclaration rootNode, final int keyOffset) { RubyMixinModel rubyModel = RubyMixinModel.getInstance(); String[] keys = getModelStaticScopesKeys(rubyModel.getRawModel(), rootNode, keyOffset); if (keys != null && keys.length > 0) { String inner = keys[keys.length - 1]; IRubyMixinElement rubyElement = rubyModel.createRubyElement(inner); - System.out.println(); if (rubyElement instanceof RubyMixinMethod) { RubyMixinMethod method = (RubyMixinMethod) rubyElement; return new RubyClassType(method.getSelfType().getKey()); } else if (rubyElement instanceof RubyMixinClass) { RubyMixinClass rubyMixinClass = (RubyMixinClass) rubyElement; return new RubyClassType(rubyMixinClass.getKey()); } } return null; // ClassInfo[] infos = resolveClassScopes(sourceModule, rootNode, new // int[] { keyOffset }); // RubyClassType result; // if (infos.length == 0) // result = RubyClassType.OBJECT_CLASS; // else // result = (RubyClassType) infos[infos.length - 1].getEvaluatedType(); // ASTNode[] staticScopes = getAllStaticScopes(rootNode, keyOffset); // MethodDeclaration method = null; // for (int i = staticScopes.length - 1; i >= 0; i--) // if (staticScopes[i] instanceof MethodDeclaration) { // method = (MethodDeclaration) staticScopes[i]; // break; // } else if (staticScopes[i] instanceof TypeDeclaration) // break; // RubyClassType metaType = getMetaType(result); // if (method != null) { // if (method instanceof RubySingletonMethodDeclaration) { // RubySingletonMethodDeclaration declaration = // (RubySingletonMethodDeclaration) method; // Expression receiver = declaration.getReceiver(); // if (receiver instanceof SelfReference) // return metaType; // static method // if (receiver instanceof SimpleReference) // if (((SimpleReference) // receiver).getName().equals(result.getUnqualifiedName())) // return metaType; // singleton method of our metaclass // // TODO: handle singleton method of another class // //return RubyMetaClassType.OBJECT_METATYPE; // return new RubyClassType("Object%"); // } // return result; // } // return metaType; } public static Assignment[] findLocalVariableAssignments( final ASTNode scope, final ASTNode nextScope, final String varName) { final Collection assignments = new ArrayList(); ASTVisitor visitor = new ASTVisitor() { public boolean visit(Expression s) throws Exception { if (s instanceof Assignment) { Assignment assignment = (Assignment) s; Expression lhs = assignment.getLeft(); if (lhs instanceof VariableReference) { VariableReference varRef = (VariableReference) lhs; if (varName.equals(varRef.getName())) { assignments.add(assignment); } } } return true; } public boolean visit(MethodDeclaration s) throws Exception { if (s == scope) return true; return false; } public boolean visit(TypeDeclaration s) throws Exception { if (s == scope) return true; return false; } public boolean visitGeneral(ASTNode node) throws Exception { if (node == nextScope) return false; return true; } }; try { scope.traverse(visitor); } catch (Exception e) { RubyPlugin.log(e); } return (Assignment[]) assignments.toArray(new Assignment[assignments .size()]); } public static boolean isRootLocalScope(ASTNode node) { return node instanceof ModuleDeclaration || node instanceof TypeDeclaration || node instanceof MethodDeclaration; } public static IEvaluatedType combineTypes(Collection evaluaedTypes) { Set types = new HashSet(evaluaedTypes); types.remove(null); if (types.size() > 1 && types.contains(RecursionTypeCall.INSTANCE)) types.remove(RecursionTypeCall.INSTANCE); return combineUniqueTypes((IEvaluatedType[]) types .toArray(new IEvaluatedType[types.size()])); } private static IEvaluatedType combineUniqueTypes(IEvaluatedType[] types) { if (types.length == 0) return UnknownType.INSTANCE; if (types.length == 1) return types[0]; return new AmbiguousType(types); } public static IEvaluatedType combineTypes(IEvaluatedType[] evaluaedTypes) { return combineTypes(Arrays.asList(evaluaedTypes)); } public static ModuleDeclaration parseSource(ISourceModule module) { // JRubySourceParser parser = new JRubySourceParser(null); // try { // return parser.parse(module.getSource()); // } catch (ModelException e) { // RubyPlugin.log(e); // return null; // } return RubySourceElementParser.parseModule(module); } public static RubyClassType getMetaType(RubyClassType type) { // TODO return type; } public static IEvaluatedType getAmbiguousMetaType(IEvaluatedType receiver) { if (receiver instanceof AmbiguousType) { Set possibleReturns = new HashSet(); AmbiguousType ambiguousType = (AmbiguousType) receiver; IEvaluatedType[] possibleTypes = ambiguousType.getPossibleTypes(); for (int i = 0; i < possibleTypes.length; i++) { IEvaluatedType type = possibleTypes[i]; IEvaluatedType possibleReturn = getAmbiguousMetaType(type); possibleReturns.add(possibleReturn); } return RubyTypeInferencingUtils.combineTypes(possibleReturns); } return null; } // public static RubyMetaClassType resolveMethods(ISourceModule module, // RubyMetaClassType type) { // if (type.getMethods() == null) { // List result = new UniqueNamesList(); // if (type.getInstanceType() != null) { // RubyClassType instanceType = (RubyClassType) type // .getInstanceType(); // // if (instanceType.getFQN()[0].equals("Object")) { // IMethod[] topLevelMethods = RubyModelUtils // .findTopLevelMethods(module, ""); // for (int i = 0; i < topLevelMethods.length; i++) { // result.add(topLevelMethods[i]); // } // } // // IType[] types = resolveTypeDeclarations(module // .getScriptProject(), instanceType); // for (int i = 0; i < types.length; i++) { // try { // IMethod[] methods = types[i].getMethods(); // IType[] subtypes = types[i].getTypes(); // // for (int j = 0; j < methods.length; j++) { // if (methods[j].getElementName().startsWith("self.")) { // result.add(methods[j]); // } // } // // for (int j = 0; j < subtypes.length; j++) { // if (!subtypes[j].getElementName().equals("<< self")) // continue; // IMethod[] methods2 = subtypes[j].getMethods(); // for (int k = 0; k < methods2.length; k++) { // int flags = methods2[k].getFlags(); // if ((flags & Modifiers.AccStatic) == 0) { // result.add(methods2[k]); // } // } // } // // if (!type.getInstanceType().getTypeName().equals( // "Object")) { // RubyMetaClassType superType = null;// // /getMetaType(RubyModelUtils.getSuperType(types[i])); // if (superType != null) { // superType = resolveMethods(module, superType); // IMethod[] allMethods = superType.getMethods(); // for (int j = 0; j < allMethods.length; j++) { // result.add(allMethods[j]); // } // } // } // } catch (ModelException e) { // e.printStackTrace(); // } // } // } // // FakeMethod[] metaMethods = RubyModelUtils.getFakeMetaMethods( // (ModelElement) module.getScriptProject(), "Object"); // for (int j = 0; j < metaMethods.length; j++) { // result.add(metaMethods[j]); // } // if (metaMethods != null) { // return new RubyMetaClassType(type.getInstanceType(), // (IMethod[]) result.toArray(new IMethod[result.size()])); // } // } // return type; // } // public static IType[] resolveTypeDeclarations(IDLTKProject project, // RubyClassType type) { // String modelKey = type.getModelKey(); // IMixinElement mixinElement = RubyTypeInferencer.getModel() // .get(modelKey); // if (mixinElement == null) // return new IType[0]; // Object[] allObjects2 = mixinElement.getAllObjects(); // IType[] allObjects = new IType[allObjects2.length]; // for (int i = 0; i < allObjects2.length; i++) { // allObjects[i] = (IType) allObjects2[i]; // } // return allObjects; // } // // // FIXME should be in RubyClassType itself! // public static RubyClassType resolveMethods(IDLTKProject project, // RubyClassType type) { // if (type.getAllMethods() != null) // return type; // String[] fqn = type.getFQN(); // IType[] allTypes = resolveTypeDeclarations(project, type); // List methods = new UniqueNamesList(); // for (int i = 0; i < allTypes.length; i++) { // try { // // IMethod[] methods2 = allTypes[i].getMethods(); // for (int j = 0; j < methods2.length; j++) { // if (!((methods2[j].getFlags() & Modifiers.AccStatic) > 0)) { // methods.add(methods2[j]); // } // } // RubyClassType superType = RubyModelUtils // .getSuperType(allTypes[i]); // if (superType != null) { // superType = resolveMethods(project, superType); // IMethod[] allMethods = superType.getAllMethods(); // for (int j = 0; j < allMethods.length; j++) { // methods.add(allMethods[j]); // } // } // } catch (ModelException e) { // } // } // if (allTypes.length == 0) { // FakeMethod[] fakeMethods = RubyModelUtils.getFakeMethods( // (ModelElement) project, "Object"); // for (int j = 0; j < fakeMethods.length; j++) { // methods.add(fakeMethods[j]); // } // } // return new RubyClassType(fqn, allTypes, (IMethod[]) methods // .toArray(new IMethod[methods.size()])); // } // public static IType[] findSubtypes(ISourceModule module, // RubyClassType type, String namePrefix) { // List result = new UniqueNamesList(); // type = resolveMethods(module.getScriptProject(), type); // IType[] declarations = type.getTypeDeclarations(); // for (int i = 0; i < declarations.length; i++) { // IType[] subtypes; // try { // subtypes = declarations[i].getTypes(); // } catch (ModelException e) { // e.printStackTrace(); // continue; // } // for (int j = 0; j < subtypes.length; j++) { // String elementName = subtypes[j].getElementName(); // if (elementName.startsWith("<<")) // skip singletons // continue; // result.add(subtypes[j]); // } // } // if (type.getFQN()[0].equals("Object")) { // // get all top level types too // IType[] top = RubyModelUtils.findTopLevelTypes(module, namePrefix); // for (int j = 0; j < top.length; j++) { // result.add(top[j]); // } // } // return (IType[]) result.toArray(new IType[result.size()]); // } public static String searchConstantElement(ModuleDeclaration module, int calculationOffset, String constantName) { MixinModel model = RubyMixinModel.getRawInstance(); String[] modelStaticScopes = getModelStaticScopesKeys(model, module, calculationOffset); String resultKey = null; for (int i = modelStaticScopes.length - 1; i >= 0; i--) { String possibleKey = modelStaticScopes[i] + IMixinRequestor.MIXIN_NAME_SEPARATOR + constantName; String[] keys = model.findKeys(possibleKey); if (keys != null && keys.length > 0) { resultKey = possibleKey; break; } } // check top-most scope if (resultKey == null) { // constantElement = model.get(constantName); String[] keys = model.findKeys(constantName); if (keys != null && keys.length > 0) { resultKey = constantName; } } return resultKey; } }
true
true
public static RubyClassType determineSelfClass( final ISourceModule sourceModule, ModuleDeclaration rootNode, final int keyOffset) { RubyMixinModel rubyModel = RubyMixinModel.getInstance(); String[] keys = getModelStaticScopesKeys(rubyModel.getRawModel(), rootNode, keyOffset); if (keys != null && keys.length > 0) { String inner = keys[keys.length - 1]; IRubyMixinElement rubyElement = rubyModel.createRubyElement(inner); System.out.println(); if (rubyElement instanceof RubyMixinMethod) { RubyMixinMethod method = (RubyMixinMethod) rubyElement; return new RubyClassType(method.getSelfType().getKey()); } else if (rubyElement instanceof RubyMixinClass) { RubyMixinClass rubyMixinClass = (RubyMixinClass) rubyElement; return new RubyClassType(rubyMixinClass.getKey()); } } return null; // ClassInfo[] infos = resolveClassScopes(sourceModule, rootNode, new // int[] { keyOffset }); // RubyClassType result; // if (infos.length == 0) // result = RubyClassType.OBJECT_CLASS; // else // result = (RubyClassType) infos[infos.length - 1].getEvaluatedType(); // ASTNode[] staticScopes = getAllStaticScopes(rootNode, keyOffset); // MethodDeclaration method = null; // for (int i = staticScopes.length - 1; i >= 0; i--) // if (staticScopes[i] instanceof MethodDeclaration) { // method = (MethodDeclaration) staticScopes[i]; // break; // } else if (staticScopes[i] instanceof TypeDeclaration) // break; // RubyClassType metaType = getMetaType(result); // if (method != null) { // if (method instanceof RubySingletonMethodDeclaration) { // RubySingletonMethodDeclaration declaration = // (RubySingletonMethodDeclaration) method; // Expression receiver = declaration.getReceiver(); // if (receiver instanceof SelfReference) // return metaType; // static method // if (receiver instanceof SimpleReference) // if (((SimpleReference) // receiver).getName().equals(result.getUnqualifiedName())) // return metaType; // singleton method of our metaclass // // TODO: handle singleton method of another class // //return RubyMetaClassType.OBJECT_METATYPE; // return new RubyClassType("Object%"); // } // return result; // } // return metaType; }
public static RubyClassType determineSelfClass( final ISourceModule sourceModule, ModuleDeclaration rootNode, final int keyOffset) { RubyMixinModel rubyModel = RubyMixinModel.getInstance(); String[] keys = getModelStaticScopesKeys(rubyModel.getRawModel(), rootNode, keyOffset); if (keys != null && keys.length > 0) { String inner = keys[keys.length - 1]; IRubyMixinElement rubyElement = rubyModel.createRubyElement(inner); if (rubyElement instanceof RubyMixinMethod) { RubyMixinMethod method = (RubyMixinMethod) rubyElement; return new RubyClassType(method.getSelfType().getKey()); } else if (rubyElement instanceof RubyMixinClass) { RubyMixinClass rubyMixinClass = (RubyMixinClass) rubyElement; return new RubyClassType(rubyMixinClass.getKey()); } } return null; // ClassInfo[] infos = resolveClassScopes(sourceModule, rootNode, new // int[] { keyOffset }); // RubyClassType result; // if (infos.length == 0) // result = RubyClassType.OBJECT_CLASS; // else // result = (RubyClassType) infos[infos.length - 1].getEvaluatedType(); // ASTNode[] staticScopes = getAllStaticScopes(rootNode, keyOffset); // MethodDeclaration method = null; // for (int i = staticScopes.length - 1; i >= 0; i--) // if (staticScopes[i] instanceof MethodDeclaration) { // method = (MethodDeclaration) staticScopes[i]; // break; // } else if (staticScopes[i] instanceof TypeDeclaration) // break; // RubyClassType metaType = getMetaType(result); // if (method != null) { // if (method instanceof RubySingletonMethodDeclaration) { // RubySingletonMethodDeclaration declaration = // (RubySingletonMethodDeclaration) method; // Expression receiver = declaration.getReceiver(); // if (receiver instanceof SelfReference) // return metaType; // static method // if (receiver instanceof SimpleReference) // if (((SimpleReference) // receiver).getName().equals(result.getUnqualifiedName())) // return metaType; // singleton method of our metaclass // // TODO: handle singleton method of another class // //return RubyMetaClassType.OBJECT_METATYPE; // return new RubyClassType("Object%"); // } // return result; // } // return metaType; }
diff --git a/src/main/java/org/devtcg/five/server/AbstractHttpServer.java b/src/main/java/org/devtcg/five/server/AbstractHttpServer.java index d0c2b8a..9b529b3 100644 --- a/src/main/java/org/devtcg/five/server/AbstractHttpServer.java +++ b/src/main/java/org/devtcg/five/server/AbstractHttpServer.java @@ -1,217 +1,219 @@ /* * Copyright (C) 2009 Josh Guilfoyle <[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 2, 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. */ package org.devtcg.five.server; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.HashSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpServerConnection; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.DefaultHttpServerConnection; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.protocol.HttpRequestHandlerRegistry; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.devtcg.five.util.CancelableThread; public abstract class AbstractHttpServer extends CancelableThread { /* package */ static final Log LOG = LogFactory.getLog("HttpServer"); protected final HashSet<WorkerThread> mWorkers = new HashSet<WorkerThread>(); private final ServerSocket mSocket; protected final HttpParams mParams; private HttpRequestHandler mReqHandler; public AbstractHttpServer() throws IOException { mSocket = new ServerSocket(); mParams = new BasicHttpParams(); mParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000); setDaemon(true); setPriority(MIN_PRIORITY); } public AbstractHttpServer(int port) throws IOException { this(); bind(port); } public void bind(int port) throws IOException { try { mSocket.bind(new InetSocketAddress(port)); } catch (UnknownHostException e) { throw new RuntimeException(e); } } public void setRequestHandler(HttpRequestHandler handler) { mReqHandler = handler; } private void reset() { WorkerThread[] workersCopy; synchronized(mWorkers) { /* Copied because shutdown() will try to access mWorkers. */ workersCopy = mWorkers.toArray(new WorkerThread[mWorkers.size()]); } for (WorkerThread t: workersCopy) t.requestCancelAndWait(); } @Override protected void onRequestCancel() { reset(); interrupt(); try { mSocket.close(); } catch (IOException e) { if (LOG.isErrorEnabled()) LOG.error("Error shutting down HTTP server", e); } } public void shutdown() { requestCancel(); } public void run() { if (mReqHandler == null) throw new IllegalStateException("Request handler not set."); while (Thread.interrupted() == false) { try { Socket sock = mSocket.accept(); DefaultHttpServerConnection conn = new DefaultHttpServerConnection(); conn.bind(sock, mParams); BasicHttpProcessor proc = new BasicHttpProcessor(); proc.addInterceptor(new ResponseContent()); proc.addInterceptor(new ResponseConnControl()); HttpRequestHandlerRegistry reg = new HttpRequestHandlerRegistry(); reg.register("*", mReqHandler); HttpService svc = new HttpService(proc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); svc.setParams(mParams); svc.setHandlerResolver(reg); WorkerThread t; synchronized(mWorkers) { t = new WorkerThread(svc, conn); mWorkers.add(t); } t.start(); } catch (IOException e) { - if (LOG.isErrorEnabled()) { - LOG.error("I/O error initializing connection thread", e); + if (!hasCanceled()) + { + if (LOG.isErrorEnabled()) + LOG.error("I/O error initializing connection thread", e); } break; } } } private class WorkerThread extends CancelableThread { private HttpService mService; private HttpServerConnection mConn; public WorkerThread(HttpService svc, HttpServerConnection conn) { super(); setName("WorkerThread"); setDaemon(true); setPriority(MIN_PRIORITY); mService = svc; mConn = conn; } public void run() { HttpContext ctx = new BasicHttpContext(null); try { while (isInterrupted() == false && mConn.isOpen()) mService.handleRequest(mConn, ctx); } catch (Exception e) { e.printStackTrace(); if (LOG.isDebugEnabled()) LOG.debug("HTTP client worker disrupted", e); } finally { if (hasCanceled() == false) { try { mConn.shutdown(); } catch (IOException e) {} } synchronized(mWorkers) { mWorkers.remove(this); } } } public void onRequestCancel() { interrupt(); try { mConn.shutdown(); } catch (IOException e) {} } } }
true
true
public void run() { if (mReqHandler == null) throw new IllegalStateException("Request handler not set."); while (Thread.interrupted() == false) { try { Socket sock = mSocket.accept(); DefaultHttpServerConnection conn = new DefaultHttpServerConnection(); conn.bind(sock, mParams); BasicHttpProcessor proc = new BasicHttpProcessor(); proc.addInterceptor(new ResponseContent()); proc.addInterceptor(new ResponseConnControl()); HttpRequestHandlerRegistry reg = new HttpRequestHandlerRegistry(); reg.register("*", mReqHandler); HttpService svc = new HttpService(proc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); svc.setParams(mParams); svc.setHandlerResolver(reg); WorkerThread t; synchronized(mWorkers) { t = new WorkerThread(svc, conn); mWorkers.add(t); } t.start(); } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error("I/O error initializing connection thread", e); } break; } } }
public void run() { if (mReqHandler == null) throw new IllegalStateException("Request handler not set."); while (Thread.interrupted() == false) { try { Socket sock = mSocket.accept(); DefaultHttpServerConnection conn = new DefaultHttpServerConnection(); conn.bind(sock, mParams); BasicHttpProcessor proc = new BasicHttpProcessor(); proc.addInterceptor(new ResponseContent()); proc.addInterceptor(new ResponseConnControl()); HttpRequestHandlerRegistry reg = new HttpRequestHandlerRegistry(); reg.register("*", mReqHandler); HttpService svc = new HttpService(proc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); svc.setParams(mParams); svc.setHandlerResolver(reg); WorkerThread t; synchronized(mWorkers) { t = new WorkerThread(svc, conn); mWorkers.add(t); } t.start(); } catch (IOException e) { if (!hasCanceled()) { if (LOG.isErrorEnabled()) LOG.error("I/O error initializing connection thread", e); } break; } } }
diff --git a/src/org/jruby/libraries/RbConfigLibrary.java b/src/org/jruby/libraries/RbConfigLibrary.java index 892990947..119b17b61 100644 --- a/src/org/jruby/libraries/RbConfigLibrary.java +++ b/src/org/jruby/libraries/RbConfigLibrary.java @@ -1,156 +1,156 @@ /***** BEGIN LICENSE BLOCK ***** * Version: CPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Common Public * 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.eclipse.org/legal/cpl-v10.html * * 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. * * Copyright (C) 2002-2004 Anders Bengtsson <[email protected]> * Copyright (C) 2004 Stefan Matthias Aust <[email protected]> * Copyright (C) 2005 Charles O Nutter * Copyright (C) 2006 Nick Sieger * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the CPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the CPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby.libraries; import java.io.IOException; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jruby.Ruby; import org.jruby.RubyHash; import org.jruby.RubyModule; import org.jruby.runtime.Constants; import org.jruby.runtime.load.Library; import org.jruby.util.NormalizedFile; public class RbConfigLibrary implements Library { /** * Just enough configuration settings (most don't make sense in Java) to run the rubytests * unit tests. The tests use <code>bindir</code>, <code>RUBY_INSTALL_NAME</code> and * <code>EXEEXT</code>. */ public void load(Ruby runtime, boolean wrap) { RubyModule configModule = runtime.defineModule("Config"); RubyHash configHash = RubyHash.newHash(runtime); configModule.defineConstant("CONFIG", configHash); runtime.getObject().defineConstant("RbConfig", configModule); String[] versionParts = Constants.RUBY_VERSION.split("\\."); setConfig(configHash, "MAJOR", versionParts[0]); setConfig(configHash, "MINOR", versionParts[1]); setConfig(configHash, "TEENY", versionParts[2]); setConfig(configHash, "ruby_version", versionParts[0] + '.' + versionParts[1]); - setConfig(configHash, "arch", System.getProperty("os.arch") + "-java" + System.getProperty("java.specification.version")); + // Rubygems is too specific on host cpu so until we have real need lets default to universal + //setConfig(configHash, "arch", System.getProperty("os.arch") + "-java" + System.getProperty("java.specification.version")); + setConfig(configHash, "arch", "universal-java" + System.getProperty("java.specification.version")); String normalizedHome; if (Ruby.isSecurityRestricted()) { normalizedHome = "SECURITY RESTRICTED"; } else { normalizedHome = new NormalizedFile(runtime.getJRubyHome()).getAbsolutePath(); } setConfig(configHash, "bindir", new NormalizedFile(normalizedHome, "bin").getAbsolutePath()); setConfig(configHash, "RUBY_INSTALL_NAME", jruby_script()); setConfig(configHash, "ruby_install_name", jruby_script()); setConfig(configHash, "SHELL", jruby_shell()); setConfig(configHash, "prefix", normalizedHome); setConfig(configHash, "exec_prefix", normalizedHome); setConfig(configHash, "host_os", System.getProperty("os.name")); setConfig(configHash, "host_vendor", System.getProperty("java.vendor")); setConfig(configHash, "host_cpu", System.getProperty("os.arch")); String target_os = System.getProperty("os.name"); if (target_os.compareTo("Mac OS X") == 0) { target_os = "darwin"; } setConfig(configHash, "target_os", target_os); - // Rubygems is too specific on host cpu so until we have real need lets default to universal - //setConfig(configHash, "target_cpu", System.getProperty("os.arch")); - setConfig(configHash, "target_cpu", "universal"); + setConfig(configHash, "target_cpu", System.getProperty("os.arch")); String jrubyJarFile = "jruby.jar"; URL jrubyPropertiesUrl = Ruby.class.getClassLoader().getResource("jruby.properties"); if (jrubyPropertiesUrl != null) { Pattern jarFile = Pattern.compile("jar:file:.*?([a-zA-Z0-9.\\-]+\\.jar)!/jruby.properties"); Matcher jarMatcher = jarFile.matcher(jrubyPropertiesUrl.toString()); jarMatcher.find(); if (jarMatcher.matches()) { jrubyJarFile = jarMatcher.group(1); } } setConfig(configHash, "LIBRUBY", jrubyJarFile); setConfig(configHash, "LIBRUBY_SO", jrubyJarFile); setConfig(configHash, "build", Constants.BUILD); setConfig(configHash, "target", Constants.TARGET); String libdir = System.getProperty("jruby.lib"); if (libdir == null) { libdir = new NormalizedFile(normalizedHome, "lib").getAbsolutePath(); } else { try { // Our shell scripts pass in non-canonicalized paths, but even if we didn't // anyone who did would become unhappy because Ruby apps expect no relative // operators in the pathname (rubygems, for example). libdir = new NormalizedFile(libdir).getCanonicalPath(); } catch (IOException e) { libdir = new NormalizedFile(libdir).getAbsolutePath(); } } setConfig(configHash, "libdir", libdir); setConfig(configHash, "rubylibdir", new NormalizedFile(libdir, "ruby/1.8").getAbsolutePath()); setConfig(configHash, "sitedir", new NormalizedFile(libdir, "ruby/site_ruby").getAbsolutePath()); setConfig(configHash, "sitelibdir", new NormalizedFile(libdir, "ruby/site_ruby/1.8").getAbsolutePath()); setConfig(configHash, "sitearchdir", new NormalizedFile(libdir, "ruby/site_ruby/1.8/java").getAbsolutePath()); setConfig(configHash, "archdir", new NormalizedFile(libdir, "ruby/site_ruby/1.8/java").getAbsolutePath()); setConfig(configHash, "configure_args", ""); setConfig(configHash, "datadir", new NormalizedFile(normalizedHome, "share").getAbsolutePath()); setConfig(configHash, "mandir", new NormalizedFile(normalizedHome, "man").getAbsolutePath()); setConfig(configHash, "sysconfdir", new NormalizedFile(normalizedHome, "etc").getAbsolutePath()); setConfig(configHash, "DLEXT", "jar"); if (isWindows()) { setConfig(configHash, "EXEEXT", ".exe"); } else { setConfig(configHash, "EXEEXT", ""); } } private static void setConfig(RubyHash configHash, String key, String value) { Ruby runtime = configHash.getRuntime(); configHash.op_aset(runtime.newString(key), runtime.newString(value)); } private static boolean isWindows() { return System.getProperty("os.name", "").startsWith("Windows"); } private String jruby_script() { return System.getProperty("jruby.script", isWindows() ? "jruby.bat" : "jruby").replace('\\', '/'); } private String jruby_shell() { return System.getProperty("jruby.shell", isWindows() ? "cmd.exe" : "/bin/sh").replace('\\', '/'); } }
false
true
public void load(Ruby runtime, boolean wrap) { RubyModule configModule = runtime.defineModule("Config"); RubyHash configHash = RubyHash.newHash(runtime); configModule.defineConstant("CONFIG", configHash); runtime.getObject().defineConstant("RbConfig", configModule); String[] versionParts = Constants.RUBY_VERSION.split("\\."); setConfig(configHash, "MAJOR", versionParts[0]); setConfig(configHash, "MINOR", versionParts[1]); setConfig(configHash, "TEENY", versionParts[2]); setConfig(configHash, "ruby_version", versionParts[0] + '.' + versionParts[1]); setConfig(configHash, "arch", System.getProperty("os.arch") + "-java" + System.getProperty("java.specification.version")); String normalizedHome; if (Ruby.isSecurityRestricted()) { normalizedHome = "SECURITY RESTRICTED"; } else { normalizedHome = new NormalizedFile(runtime.getJRubyHome()).getAbsolutePath(); } setConfig(configHash, "bindir", new NormalizedFile(normalizedHome, "bin").getAbsolutePath()); setConfig(configHash, "RUBY_INSTALL_NAME", jruby_script()); setConfig(configHash, "ruby_install_name", jruby_script()); setConfig(configHash, "SHELL", jruby_shell()); setConfig(configHash, "prefix", normalizedHome); setConfig(configHash, "exec_prefix", normalizedHome); setConfig(configHash, "host_os", System.getProperty("os.name")); setConfig(configHash, "host_vendor", System.getProperty("java.vendor")); setConfig(configHash, "host_cpu", System.getProperty("os.arch")); String target_os = System.getProperty("os.name"); if (target_os.compareTo("Mac OS X") == 0) { target_os = "darwin"; } setConfig(configHash, "target_os", target_os); // Rubygems is too specific on host cpu so until we have real need lets default to universal //setConfig(configHash, "target_cpu", System.getProperty("os.arch")); setConfig(configHash, "target_cpu", "universal"); String jrubyJarFile = "jruby.jar"; URL jrubyPropertiesUrl = Ruby.class.getClassLoader().getResource("jruby.properties"); if (jrubyPropertiesUrl != null) { Pattern jarFile = Pattern.compile("jar:file:.*?([a-zA-Z0-9.\\-]+\\.jar)!/jruby.properties"); Matcher jarMatcher = jarFile.matcher(jrubyPropertiesUrl.toString()); jarMatcher.find(); if (jarMatcher.matches()) { jrubyJarFile = jarMatcher.group(1); } } setConfig(configHash, "LIBRUBY", jrubyJarFile); setConfig(configHash, "LIBRUBY_SO", jrubyJarFile); setConfig(configHash, "build", Constants.BUILD); setConfig(configHash, "target", Constants.TARGET); String libdir = System.getProperty("jruby.lib"); if (libdir == null) { libdir = new NormalizedFile(normalizedHome, "lib").getAbsolutePath(); } else { try { // Our shell scripts pass in non-canonicalized paths, but even if we didn't // anyone who did would become unhappy because Ruby apps expect no relative // operators in the pathname (rubygems, for example). libdir = new NormalizedFile(libdir).getCanonicalPath(); } catch (IOException e) { libdir = new NormalizedFile(libdir).getAbsolutePath(); } } setConfig(configHash, "libdir", libdir); setConfig(configHash, "rubylibdir", new NormalizedFile(libdir, "ruby/1.8").getAbsolutePath()); setConfig(configHash, "sitedir", new NormalizedFile(libdir, "ruby/site_ruby").getAbsolutePath()); setConfig(configHash, "sitelibdir", new NormalizedFile(libdir, "ruby/site_ruby/1.8").getAbsolutePath()); setConfig(configHash, "sitearchdir", new NormalizedFile(libdir, "ruby/site_ruby/1.8/java").getAbsolutePath()); setConfig(configHash, "archdir", new NormalizedFile(libdir, "ruby/site_ruby/1.8/java").getAbsolutePath()); setConfig(configHash, "configure_args", ""); setConfig(configHash, "datadir", new NormalizedFile(normalizedHome, "share").getAbsolutePath()); setConfig(configHash, "mandir", new NormalizedFile(normalizedHome, "man").getAbsolutePath()); setConfig(configHash, "sysconfdir", new NormalizedFile(normalizedHome, "etc").getAbsolutePath()); setConfig(configHash, "DLEXT", "jar"); if (isWindows()) { setConfig(configHash, "EXEEXT", ".exe"); } else { setConfig(configHash, "EXEEXT", ""); } }
public void load(Ruby runtime, boolean wrap) { RubyModule configModule = runtime.defineModule("Config"); RubyHash configHash = RubyHash.newHash(runtime); configModule.defineConstant("CONFIG", configHash); runtime.getObject().defineConstant("RbConfig", configModule); String[] versionParts = Constants.RUBY_VERSION.split("\\."); setConfig(configHash, "MAJOR", versionParts[0]); setConfig(configHash, "MINOR", versionParts[1]); setConfig(configHash, "TEENY", versionParts[2]); setConfig(configHash, "ruby_version", versionParts[0] + '.' + versionParts[1]); // Rubygems is too specific on host cpu so until we have real need lets default to universal //setConfig(configHash, "arch", System.getProperty("os.arch") + "-java" + System.getProperty("java.specification.version")); setConfig(configHash, "arch", "universal-java" + System.getProperty("java.specification.version")); String normalizedHome; if (Ruby.isSecurityRestricted()) { normalizedHome = "SECURITY RESTRICTED"; } else { normalizedHome = new NormalizedFile(runtime.getJRubyHome()).getAbsolutePath(); } setConfig(configHash, "bindir", new NormalizedFile(normalizedHome, "bin").getAbsolutePath()); setConfig(configHash, "RUBY_INSTALL_NAME", jruby_script()); setConfig(configHash, "ruby_install_name", jruby_script()); setConfig(configHash, "SHELL", jruby_shell()); setConfig(configHash, "prefix", normalizedHome); setConfig(configHash, "exec_prefix", normalizedHome); setConfig(configHash, "host_os", System.getProperty("os.name")); setConfig(configHash, "host_vendor", System.getProperty("java.vendor")); setConfig(configHash, "host_cpu", System.getProperty("os.arch")); String target_os = System.getProperty("os.name"); if (target_os.compareTo("Mac OS X") == 0) { target_os = "darwin"; } setConfig(configHash, "target_os", target_os); setConfig(configHash, "target_cpu", System.getProperty("os.arch")); String jrubyJarFile = "jruby.jar"; URL jrubyPropertiesUrl = Ruby.class.getClassLoader().getResource("jruby.properties"); if (jrubyPropertiesUrl != null) { Pattern jarFile = Pattern.compile("jar:file:.*?([a-zA-Z0-9.\\-]+\\.jar)!/jruby.properties"); Matcher jarMatcher = jarFile.matcher(jrubyPropertiesUrl.toString()); jarMatcher.find(); if (jarMatcher.matches()) { jrubyJarFile = jarMatcher.group(1); } } setConfig(configHash, "LIBRUBY", jrubyJarFile); setConfig(configHash, "LIBRUBY_SO", jrubyJarFile); setConfig(configHash, "build", Constants.BUILD); setConfig(configHash, "target", Constants.TARGET); String libdir = System.getProperty("jruby.lib"); if (libdir == null) { libdir = new NormalizedFile(normalizedHome, "lib").getAbsolutePath(); } else { try { // Our shell scripts pass in non-canonicalized paths, but even if we didn't // anyone who did would become unhappy because Ruby apps expect no relative // operators in the pathname (rubygems, for example). libdir = new NormalizedFile(libdir).getCanonicalPath(); } catch (IOException e) { libdir = new NormalizedFile(libdir).getAbsolutePath(); } } setConfig(configHash, "libdir", libdir); setConfig(configHash, "rubylibdir", new NormalizedFile(libdir, "ruby/1.8").getAbsolutePath()); setConfig(configHash, "sitedir", new NormalizedFile(libdir, "ruby/site_ruby").getAbsolutePath()); setConfig(configHash, "sitelibdir", new NormalizedFile(libdir, "ruby/site_ruby/1.8").getAbsolutePath()); setConfig(configHash, "sitearchdir", new NormalizedFile(libdir, "ruby/site_ruby/1.8/java").getAbsolutePath()); setConfig(configHash, "archdir", new NormalizedFile(libdir, "ruby/site_ruby/1.8/java").getAbsolutePath()); setConfig(configHash, "configure_args", ""); setConfig(configHash, "datadir", new NormalizedFile(normalizedHome, "share").getAbsolutePath()); setConfig(configHash, "mandir", new NormalizedFile(normalizedHome, "man").getAbsolutePath()); setConfig(configHash, "sysconfdir", new NormalizedFile(normalizedHome, "etc").getAbsolutePath()); setConfig(configHash, "DLEXT", "jar"); if (isWindows()) { setConfig(configHash, "EXEEXT", ".exe"); } else { setConfig(configHash, "EXEEXT", ""); } }
diff --git a/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/AbstractIdentifierAssigner.java b/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/AbstractIdentifierAssigner.java index ae778e37..6042eeec 100644 --- a/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/AbstractIdentifierAssigner.java +++ b/openregistry-service-impl/src/main/java/org/openregistry/core/service/identifier/AbstractIdentifierAssigner.java @@ -1,21 +1,23 @@ package org.openregistry.core.service.identifier; import java.util.Deque; import org.openregistry.core.domain.Identifier; import org.openregistry.core.domain.Person; public abstract class AbstractIdentifierAssigner implements IdentifierAssigner { protected final Identifier findPrimaryIdentifier(Person person, String identifierType) { Identifier identifier = null; final Deque<Identifier> identifiersForThisType = person.getIdentifiersByType().get(identifierType); - for (final Identifier id : identifiersForThisType) { - if (id.isPrimary() && ! id.isDeleted()) { - identifier = id; + if (identifiersForThisType != null) { + for (final Identifier id : identifiersForThisType) { + if (id.isPrimary() && ! id.isDeleted()) { + identifier = id; + } } } return identifier; } }
true
true
protected final Identifier findPrimaryIdentifier(Person person, String identifierType) { Identifier identifier = null; final Deque<Identifier> identifiersForThisType = person.getIdentifiersByType().get(identifierType); for (final Identifier id : identifiersForThisType) { if (id.isPrimary() && ! id.isDeleted()) { identifier = id; } } return identifier; }
protected final Identifier findPrimaryIdentifier(Person person, String identifierType) { Identifier identifier = null; final Deque<Identifier> identifiersForThisType = person.getIdentifiersByType().get(identifierType); if (identifiersForThisType != null) { for (final Identifier id : identifiersForThisType) { if (id.isPrimary() && ! id.isDeleted()) { identifier = id; } } } return identifier; }
diff --git a/config/src/main/java/com/typesafe/config/impl/SimpleConfigObject.java b/config/src/main/java/com/typesafe/config/impl/SimpleConfigObject.java index fb3ac60..1977bd1 100644 --- a/config/src/main/java/com/typesafe/config/impl/SimpleConfigObject.java +++ b/config/src/main/java/com/typesafe/config/impl/SimpleConfigObject.java @@ -1,553 +1,555 @@ /** * Copyright (C) 2011-2012 Typesafe Inc. <http://typesafe.com> */ package com.typesafe.config.impl; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigOrigin; import com.typesafe.config.ConfigRenderOptions; import com.typesafe.config.ConfigValue; final class SimpleConfigObject extends AbstractConfigObject implements Serializable { private static final long serialVersionUID = 2L; // this map should never be modified - assume immutable final private Map<String, AbstractConfigValue> value; final private boolean resolved; final private boolean ignoresFallbacks; SimpleConfigObject(ConfigOrigin origin, Map<String, AbstractConfigValue> value, ResolveStatus status, boolean ignoresFallbacks) { super(origin); if (value == null) throw new ConfigException.BugOrBroken( "creating config object with null map"); this.value = value; this.resolved = status == ResolveStatus.RESOLVED; this.ignoresFallbacks = ignoresFallbacks; // Kind of an expensive debug check. Comment out? if (status != ResolveStatus.fromValues(value.values())) throw new ConfigException.BugOrBroken("Wrong resolved status on " + this); } SimpleConfigObject(ConfigOrigin origin, Map<String, AbstractConfigValue> value) { this(origin, value, ResolveStatus.fromValues(value.values()), false /* ignoresFallbacks */); } @Override public SimpleConfigObject withOnlyKey(String key) { return withOnlyPath(Path.newKey(key)); } @Override public SimpleConfigObject withoutKey(String key) { return withoutPath(Path.newKey(key)); } // gets the object with only the path if the path // exists, otherwise null if it doesn't. this ensures // that if we have { a : { b : 42 } } and do // withOnlyPath("a.b.c") that we don't keep an empty // "a" object. @Override protected SimpleConfigObject withOnlyPathOrNull(Path path) { String key = path.first(); Path next = path.remainder(); AbstractConfigValue v = value.get(key); if (next != null) { if (v != null && (v instanceof AbstractConfigObject)) { v = ((AbstractConfigObject) v).withOnlyPathOrNull(next); } else { // if the path has more elements but we don't have an object, // then the rest of the path does not exist. v = null; } } if (v == null) { return null; } else { return new SimpleConfigObject(origin(), Collections.singletonMap(key, v), v.resolveStatus(), ignoresFallbacks); } } @Override SimpleConfigObject withOnlyPath(Path path) { SimpleConfigObject o = withOnlyPathOrNull(path); if (o == null) { return new SimpleConfigObject(origin(), Collections.<String, AbstractConfigValue> emptyMap(), ResolveStatus.RESOLVED, ignoresFallbacks); } else { return o; } } @Override SimpleConfigObject withoutPath(Path path) { String key = path.first(); Path next = path.remainder(); AbstractConfigValue v = value.get(key); if (v != null && next != null && v instanceof AbstractConfigObject) { v = ((AbstractConfigObject) v).withoutPath(next); Map<String, AbstractConfigValue> updated = new HashMap<String, AbstractConfigValue>( value); updated.put(key, v); return new SimpleConfigObject(origin(), updated, ResolveStatus.fromValues(updated .values()), ignoresFallbacks); } else if (next != null || v == null) { // can't descend, nothing to remove return this; } else { Map<String, AbstractConfigValue> smaller = new HashMap<String, AbstractConfigValue>( value.size() - 1); for (Map.Entry<String, AbstractConfigValue> old : value.entrySet()) { if (!old.getKey().equals(key)) smaller.put(old.getKey(), old.getValue()); } return new SimpleConfigObject(origin(), smaller, ResolveStatus.fromValues(smaller .values()), ignoresFallbacks); } } @Override public SimpleConfigObject withValue(String key, ConfigValue v) { if (v == null) throw new ConfigException.BugOrBroken( "Trying to store null ConfigValue in a ConfigObject"); Map<String, AbstractConfigValue> newMap; if (value.isEmpty()) { newMap = Collections.singletonMap(key, (AbstractConfigValue) v); } else { newMap = new HashMap<String, AbstractConfigValue>(value); newMap.put(key, (AbstractConfigValue) v); } return new SimpleConfigObject(origin(), newMap, ResolveStatus.fromValues(newMap.values()), ignoresFallbacks); } @Override SimpleConfigObject withValue(Path path, ConfigValue v) { String key = path.first(); Path next = path.remainder(); if (next == null) { return withValue(key, v); } else { AbstractConfigValue child = value.get(key); if (child != null && child instanceof AbstractConfigObject) { // if we have an object, add to it return withValue(key, ((AbstractConfigObject) child).withValue(next, v)); } else { // as soon as we have a non-object, replace it entirely SimpleConfig subtree = ((AbstractConfigValue) v).atPath( SimpleConfigOrigin.newSimple("withValue(" + next.render() + ")"), next); return withValue(key, subtree.root()); } } } @Override protected AbstractConfigValue attemptPeekWithPartialResolve(String key) { return value.get(key); } private SimpleConfigObject newCopy(ResolveStatus newStatus, ConfigOrigin newOrigin, boolean newIgnoresFallbacks) { return new SimpleConfigObject(newOrigin, value, newStatus, newIgnoresFallbacks); } @Override protected SimpleConfigObject newCopy(ResolveStatus newStatus, ConfigOrigin newOrigin) { return newCopy(newStatus, newOrigin, ignoresFallbacks); } @Override protected SimpleConfigObject withFallbacksIgnored() { if (ignoresFallbacks) return this; else return newCopy(resolveStatus(), origin(), true /* ignoresFallbacks */); } @Override ResolveStatus resolveStatus() { return ResolveStatus.fromBoolean(resolved); } @Override protected boolean ignoresFallbacks() { return ignoresFallbacks; } @Override public Map<String, Object> unwrapped() { Map<String, Object> m = new HashMap<String, Object>(); for (Map.Entry<String, AbstractConfigValue> e : value.entrySet()) { m.put(e.getKey(), e.getValue().unwrapped()); } return m; } @Override protected SimpleConfigObject mergedWithObject(AbstractConfigObject abstractFallback) { requireNotIgnoringFallbacks(); if (!(abstractFallback instanceof SimpleConfigObject)) { throw new ConfigException.BugOrBroken( "should not be reached (merging non-SimpleConfigObject)"); } SimpleConfigObject fallback = (SimpleConfigObject) abstractFallback; boolean changed = false; boolean allResolved = true; Map<String, AbstractConfigValue> merged = new HashMap<String, AbstractConfigValue>(); Set<String> allKeys = new HashSet<String>(); allKeys.addAll(this.keySet()); allKeys.addAll(fallback.keySet()); for (String key : allKeys) { AbstractConfigValue first = this.value.get(key); AbstractConfigValue second = fallback.value.get(key); AbstractConfigValue kept; if (first == null) kept = second; else if (second == null) kept = first; else kept = first.withFallback(second); merged.put(key, kept); if (first != kept) changed = true; if (kept.resolveStatus() == ResolveStatus.UNRESOLVED) allResolved = false; } ResolveStatus newResolveStatus = ResolveStatus.fromBoolean(allResolved); boolean newIgnoresFallbacks = fallback.ignoresFallbacks(); if (changed) return new SimpleConfigObject(mergeOrigins(this, fallback), merged, newResolveStatus, newIgnoresFallbacks); else if (newResolveStatus != resolveStatus() || newIgnoresFallbacks != ignoresFallbacks()) return newCopy(newResolveStatus, origin(), newIgnoresFallbacks); else return this; } private SimpleConfigObject modify(NoExceptionsModifier modifier) { try { return modifyMayThrow(modifier); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ConfigException.BugOrBroken("unexpected checked exception", e); } } private SimpleConfigObject modifyMayThrow(Modifier modifier) throws Exception { Map<String, AbstractConfigValue> changes = null; for (String k : keySet()) { AbstractConfigValue v = value.get(k); // "modified" may be null, which means remove the child; // to do that we put null in the "changes" map. AbstractConfigValue modified = modifier.modifyChildMayThrow(k, v); if (modified != v) { if (changes == null) changes = new HashMap<String, AbstractConfigValue>(); changes.put(k, modified); } } if (changes == null) { return this; } else { Map<String, AbstractConfigValue> modified = new HashMap<String, AbstractConfigValue>(); boolean sawUnresolved = false; for (String k : keySet()) { if (changes.containsKey(k)) { AbstractConfigValue newValue = changes.get(k); if (newValue != null) { modified.put(k, newValue); if (newValue.resolveStatus() == ResolveStatus.UNRESOLVED) sawUnresolved = true; } else { // remove this child; don't put it in the new map. } } else { AbstractConfigValue newValue = value.get(k); modified.put(k, newValue); if (newValue.resolveStatus() == ResolveStatus.UNRESOLVED) sawUnresolved = true; } } return new SimpleConfigObject(origin(), modified, sawUnresolved ? ResolveStatus.UNRESOLVED : ResolveStatus.RESOLVED, ignoresFallbacks()); } } @Override AbstractConfigObject resolveSubstitutions(final ResolveContext context) throws NotPossibleToResolve { if (resolveStatus() == ResolveStatus.RESOLVED) return this; try { return modifyMayThrow(new Modifier() { @Override public AbstractConfigValue modifyChildMayThrow(String key, AbstractConfigValue v) throws NotPossibleToResolve { if (context.isRestrictedToChild()) { if (key.equals(context.restrictToChild().first())) { Path remainder = context.restrictToChild().remainder(); if (remainder != null) { return context.restrict(remainder).resolve(v); } else { // we don't want to resolve the leaf child. return v; } } else { // not in the restrictToChild path return v; } } else { // no restrictToChild, resolve everything return context.unrestricted().resolve(v); } } }); } catch (NotPossibleToResolve e) { throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new ConfigException.BugOrBroken("unexpected checked exception", e); } } @Override SimpleConfigObject relativized(final Path prefix) { return modify(new NoExceptionsModifier() { @Override public AbstractConfigValue modifyChild(String key, AbstractConfigValue v) { return v.relativized(prefix); } }); } @Override protected void render(StringBuilder sb, int indent, ConfigRenderOptions options) { if (isEmpty()) { sb.append("{}"); } else { boolean outerBraces = indent > 0 || options.getJson(); if (outerBraces) sb.append("{"); if (options.getFormatted()) sb.append('\n'); int separatorCount = 0; for (String k : keySet()) { AbstractConfigValue v; v = value.get(k); if (options.getOriginComments()) { indent(sb, indent + 1, options); sb.append("# "); sb.append(v.origin().description()); sb.append("\n"); } if (options.getComments()) { for (String comment : v.origin().comments()) { indent(sb, indent + 1, options); - sb.append("# "); + sb.append("#"); + if (!comment.startsWith(" ")) + sb.append(' '); sb.append(comment); sb.append("\n"); } } indent(sb, indent + 1, options); v.render(sb, indent + 1, k, options); if (options.getFormatted()) { if (options.getJson()) { sb.append(","); separatorCount = 2; } else { separatorCount = 1; } sb.append('\n'); } else { sb.append(","); separatorCount = 1; } } // chop last commas/newlines sb.setLength(sb.length() - separatorCount); if (options.getFormatted()) { sb.append("\n"); // put a newline back indent(sb, indent, options); } if (outerBraces) sb.append("}"); } } @Override public AbstractConfigValue get(Object key) { return value.get(key); } private static boolean mapEquals(Map<String, ConfigValue> a, Map<String, ConfigValue> b) { Set<String> aKeys = a.keySet(); Set<String> bKeys = b.keySet(); if (!aKeys.equals(bKeys)) return false; for (String key : aKeys) { if (!a.get(key).equals(b.get(key))) return false; } return true; } private static int mapHash(Map<String, ConfigValue> m) { // the keys have to be sorted, otherwise we could be equal // to another map but have a different hashcode. List<String> keys = new ArrayList<String>(); keys.addAll(m.keySet()); Collections.sort(keys); int valuesHash = 0; for (String k : keys) { valuesHash += m.get(k).hashCode(); } return 41 * (41 + keys.hashCode()) + valuesHash; } @Override protected boolean canEqual(Object other) { return other instanceof ConfigObject; } @Override public boolean equals(Object other) { // note that "origin" is deliberately NOT part of equality. // neither are other "extras" like ignoresFallbacks or resolve status. if (other instanceof ConfigObject) { // optimization to avoid unwrapped() for two ConfigObject, // which is what AbstractConfigValue does. return canEqual(other) && mapEquals(this, ((ConfigObject) other)); } else { return false; } } @Override public int hashCode() { // note that "origin" is deliberately NOT part of equality // neither are other "extras" like ignoresFallbacks or resolve status. return mapHash(this); } @Override public boolean containsKey(Object key) { return value.containsKey(key); } @Override public Set<String> keySet() { return value.keySet(); } @Override public boolean containsValue(Object v) { return value.containsValue(v); } @Override public Set<Map.Entry<String, ConfigValue>> entrySet() { // total bloat just to work around lack of type variance HashSet<java.util.Map.Entry<String, ConfigValue>> entries = new HashSet<Map.Entry<String, ConfigValue>>(); for (Map.Entry<String, AbstractConfigValue> e : value.entrySet()) { entries.add(new AbstractMap.SimpleImmutableEntry<String, ConfigValue>( e.getKey(), e .getValue())); } return entries; } @Override public boolean isEmpty() { return value.isEmpty(); } @Override public int size() { return value.size(); } @Override public Collection<ConfigValue> values() { return new HashSet<ConfigValue>(value.values()); } final private static String EMPTY_NAME = "empty config"; final private static SimpleConfigObject emptyInstance = empty(SimpleConfigOrigin .newSimple(EMPTY_NAME)); final static SimpleConfigObject empty() { return emptyInstance; } final static SimpleConfigObject empty(ConfigOrigin origin) { if (origin == null) return empty(); else return new SimpleConfigObject(origin, Collections.<String, AbstractConfigValue> emptyMap()); } final static SimpleConfigObject emptyMissing(ConfigOrigin baseOrigin) { return new SimpleConfigObject(SimpleConfigOrigin.newSimple( baseOrigin.description() + " (not found)"), Collections.<String, AbstractConfigValue> emptyMap()); } // serialization all goes through SerializedConfigValue private Object writeReplace() throws ObjectStreamException { return new SerializedConfigValue(this); } }
true
true
protected void render(StringBuilder sb, int indent, ConfigRenderOptions options) { if (isEmpty()) { sb.append("{}"); } else { boolean outerBraces = indent > 0 || options.getJson(); if (outerBraces) sb.append("{"); if (options.getFormatted()) sb.append('\n'); int separatorCount = 0; for (String k : keySet()) { AbstractConfigValue v; v = value.get(k); if (options.getOriginComments()) { indent(sb, indent + 1, options); sb.append("# "); sb.append(v.origin().description()); sb.append("\n"); } if (options.getComments()) { for (String comment : v.origin().comments()) { indent(sb, indent + 1, options); sb.append("# "); sb.append(comment); sb.append("\n"); } } indent(sb, indent + 1, options); v.render(sb, indent + 1, k, options); if (options.getFormatted()) { if (options.getJson()) { sb.append(","); separatorCount = 2; } else { separatorCount = 1; } sb.append('\n'); } else { sb.append(","); separatorCount = 1; } } // chop last commas/newlines sb.setLength(sb.length() - separatorCount); if (options.getFormatted()) { sb.append("\n"); // put a newline back indent(sb, indent, options); } if (outerBraces) sb.append("}"); } }
protected void render(StringBuilder sb, int indent, ConfigRenderOptions options) { if (isEmpty()) { sb.append("{}"); } else { boolean outerBraces = indent > 0 || options.getJson(); if (outerBraces) sb.append("{"); if (options.getFormatted()) sb.append('\n'); int separatorCount = 0; for (String k : keySet()) { AbstractConfigValue v; v = value.get(k); if (options.getOriginComments()) { indent(sb, indent + 1, options); sb.append("# "); sb.append(v.origin().description()); sb.append("\n"); } if (options.getComments()) { for (String comment : v.origin().comments()) { indent(sb, indent + 1, options); sb.append("#"); if (!comment.startsWith(" ")) sb.append(' '); sb.append(comment); sb.append("\n"); } } indent(sb, indent + 1, options); v.render(sb, indent + 1, k, options); if (options.getFormatted()) { if (options.getJson()) { sb.append(","); separatorCount = 2; } else { separatorCount = 1; } sb.append('\n'); } else { sb.append(","); separatorCount = 1; } } // chop last commas/newlines sb.setLength(sb.length() - separatorCount); if (options.getFormatted()) { sb.append("\n"); // put a newline back indent(sb, indent, options); } if (outerBraces) sb.append("}"); } }
diff --git a/src/net/sf/gogui/game/BoardUpdater.java b/src/net/sf/gogui/game/BoardUpdater.java index 465e76d4..9eae4224 100644 --- a/src/net/sf/gogui/game/BoardUpdater.java +++ b/src/net/sf/gogui/game/BoardUpdater.java @@ -1,60 +1,60 @@ //---------------------------------------------------------------------------- // $Id$ // $Source$ //---------------------------------------------------------------------------- package net.sf.gogui.game; import java.util.ArrayList; import net.sf.gogui.go.Board; import net.sf.gogui.go.GoColor; import net.sf.gogui.go.Move; //---------------------------------------------------------------------------- /** Updates a go.Board to a node in a GameTree. */ public class BoardUpdater { public BoardUpdater() { m_nodes = new ArrayList(400); m_moves = new ArrayList(400); } public void update(GameTree tree, Node currentNode, Board board) { int size = tree.getGameInformation().m_boardSize; assert(board.getSize() == size); m_nodes.clear(); NodeUtil.getPathToRoot(currentNode, m_nodes); board.init(size); for (int i = m_nodes.size() - 1; i >= 0; --i) { Node node = (Node)m_nodes.get(i); for (int j = 0; j < node.getNumberAddBlack(); ++j) - board.setup(node.getAddBlack(i), GoColor.BLACK); + board.setup(node.getAddBlack(j), GoColor.BLACK); for (int j = 0; j < node.getNumberAddWhite(); ++j) - board.setup(node.getAddWhite(i), GoColor.WHITE); + board.setup(node.getAddWhite(j), GoColor.WHITE); for (int j = 0; j < node.getNumberAddEmpty(); ++j) - board.setup(node.getAddEmpty(i), GoColor.EMPTY); + board.setup(node.getAddEmpty(j), GoColor.EMPTY); Move move = node.getMove(); if (move != null) board.play(move); GoColor toMove = node.getToMove(); if (toMove != GoColor.EMPTY) board.setToMove(toMove); } } /** Local variable used in update. Member variable for avoiding frequent new memory allocations. */ private ArrayList m_moves; /** Local variable used in update. Member variable for avoiding frequent new memory allocations. */ private ArrayList m_nodes; } //----------------------------------------------------------------------------
false
true
public void update(GameTree tree, Node currentNode, Board board) { int size = tree.getGameInformation().m_boardSize; assert(board.getSize() == size); m_nodes.clear(); NodeUtil.getPathToRoot(currentNode, m_nodes); board.init(size); for (int i = m_nodes.size() - 1; i >= 0; --i) { Node node = (Node)m_nodes.get(i); for (int j = 0; j < node.getNumberAddBlack(); ++j) board.setup(node.getAddBlack(i), GoColor.BLACK); for (int j = 0; j < node.getNumberAddWhite(); ++j) board.setup(node.getAddWhite(i), GoColor.WHITE); for (int j = 0; j < node.getNumberAddEmpty(); ++j) board.setup(node.getAddEmpty(i), GoColor.EMPTY); Move move = node.getMove(); if (move != null) board.play(move); GoColor toMove = node.getToMove(); if (toMove != GoColor.EMPTY) board.setToMove(toMove); } }
public void update(GameTree tree, Node currentNode, Board board) { int size = tree.getGameInformation().m_boardSize; assert(board.getSize() == size); m_nodes.clear(); NodeUtil.getPathToRoot(currentNode, m_nodes); board.init(size); for (int i = m_nodes.size() - 1; i >= 0; --i) { Node node = (Node)m_nodes.get(i); for (int j = 0; j < node.getNumberAddBlack(); ++j) board.setup(node.getAddBlack(j), GoColor.BLACK); for (int j = 0; j < node.getNumberAddWhite(); ++j) board.setup(node.getAddWhite(j), GoColor.WHITE); for (int j = 0; j < node.getNumberAddEmpty(); ++j) board.setup(node.getAddEmpty(j), GoColor.EMPTY); Move move = node.getMove(); if (move != null) board.play(move); GoColor toMove = node.getToMove(); if (toMove != GoColor.EMPTY) board.setToMove(toMove); } }
diff --git a/timerecoder/timerecoder-app/src/main/java/jp/ddo/haselab/timerecoder/RecodeListAdapter.java b/timerecoder/timerecoder-app/src/main/java/jp/ddo/haselab/timerecoder/RecodeListAdapter.java index a31bae1..12594f2 100644 --- a/timerecoder/timerecoder-app/src/main/java/jp/ddo/haselab/timerecoder/RecodeListAdapter.java +++ b/timerecoder/timerecoder-app/src/main/java/jp/ddo/haselab/timerecoder/RecodeListAdapter.java @@ -1,83 +1,84 @@ package jp.ddo.haselab.timerecoder; import java.util.List; import android.widget.BaseAdapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.TextView; import jp.ddo.haselab.timerecoder.util.RecodeDateTime; import jp.ddo.haselab.timerecoder.dataaccess.Recode; import jp.ddo.haselab.timerecoder.util.MyLog; /** * * @author T.Hasegawa */ final class RecodeListAdapter extends BaseAdapter { private List<Recode> data; private final Context context; public RecodeListAdapter(final Context argContext, final List<Recode> argData){ MyLog.getInstance().verbose("start"); context = argContext; data = argData; } public void addData(final Recode argData){ data.add(argData); notifyDataSetChanged(); } @Override public int getCount() { MyLog.getInstance().verbose("called.result["+ data.size() + "]"); return data.size(); } @Override public long getItemId(final int argPosition) { MyLog.getInstance().verbose("argPosition["+ argPosition + "]"); return argPosition; } @Override public Object getItem(final int argPosition) { MyLog.getInstance().verbose("argPosition["+ argPosition + "]"); MyLog.getInstance().verbose("result["+ data.get(argPosition) + "]"); return data.get(argPosition); } @Override public View getView(final int position, final View convertView, final ViewGroup parentViewGroup) { View resultView = convertView; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); resultView = inflater.inflate(R.layout.recode_item, - null); + parentViewGroup, + false); } Recode rec = (Recode)this.getItem(position); TextView number = (TextView)resultView.findViewById(R.id.number); number.setText(position + ""); TextView dateTime = (TextView)resultView.findViewById(R.id.datetime); dateTime.setText(rec.getDateTime().toString()); TextView event = (TextView)resultView.findViewById(R.id.eventid); event.setText(rec.getEventToString()); TextView memo = (TextView)resultView.findViewById(R.id.memo); memo.setText(rec.getMemo()); return resultView; } }
true
true
public View getView(final int position, final View convertView, final ViewGroup parentViewGroup) { View resultView = convertView; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); resultView = inflater.inflate(R.layout.recode_item, null); } Recode rec = (Recode)this.getItem(position); TextView number = (TextView)resultView.findViewById(R.id.number); number.setText(position + ""); TextView dateTime = (TextView)resultView.findViewById(R.id.datetime); dateTime.setText(rec.getDateTime().toString()); TextView event = (TextView)resultView.findViewById(R.id.eventid); event.setText(rec.getEventToString()); TextView memo = (TextView)resultView.findViewById(R.id.memo); memo.setText(rec.getMemo()); return resultView; }
public View getView(final int position, final View convertView, final ViewGroup parentViewGroup) { View resultView = convertView; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); resultView = inflater.inflate(R.layout.recode_item, parentViewGroup, false); } Recode rec = (Recode)this.getItem(position); TextView number = (TextView)resultView.findViewById(R.id.number); number.setText(position + ""); TextView dateTime = (TextView)resultView.findViewById(R.id.datetime); dateTime.setText(rec.getDateTime().toString()); TextView event = (TextView)resultView.findViewById(R.id.eventid); event.setText(rec.getEventToString()); TextView memo = (TextView)resultView.findViewById(R.id.memo); memo.setText(rec.getMemo()); return resultView; }
diff --git a/app/src/me/openphoto/android/app/MainActivity.java b/app/src/me/openphoto/android/app/MainActivity.java index 1e99cb4..55e6efa 100644 --- a/app/src/me/openphoto/android/app/MainActivity.java +++ b/app/src/me/openphoto/android/app/MainActivity.java @@ -1,146 +1,148 @@ package me.openphoto.android.app; import me.openphoto.android.app.service.UploaderService; import me.openphoto.android.app.ui.widget.ActionBar; import me.openphoto.android.app.ui.widget.ActionBar.ActionClickListener; import android.app.Activity; import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TabHost.TabSpec; import android.widget.TextView; import com.bugsense.trace.BugSenseHandler; /** * The Main screen of OpenPhoto * * @author pas, pboos */ public class MainActivity extends TabActivity implements ActionClickListener { public static final String TAG = MainActivity.class.getSimpleName(); private static final String BUG_SENSE_API_KEY = null; private ActionBar mActionBar; /** * Called when Main Activity is first loaded * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mActionBar = (ActionBar) findViewById(R.id.actionbar); mActionBar.setOnActionClickListener(this); // To make sure the service is initialized startService(new Intent(this, UploaderService.class)); setUpTabs(); if (BUG_SENSE_API_KEY != null) { BugSenseHandler.setup(this, BUG_SENSE_API_KEY); } } private void setUpTabs() { TabSpec tabSpec = getTabHost() .newTabSpec("home") .setIndicator( - newTabIndicator(R.drawable.tab_home, R.string.tab_home)) + newTabIndicator(R.drawable.tab_home_2states, + R.string.tab_home)) .setContent(new Intent(this, HomeActivity.class)); getTabHost().addTab(tabSpec); tabSpec = getTabHost() .newTabSpec("gallery") .setIndicator( - newTabIndicator(R.drawable.tab_gallery, + newTabIndicator(R.drawable.tab_gallery_2states, R.string.tab_gallery)) .setContent(new Intent(this, GalleryActivity.class)); getTabHost().addTab(tabSpec); tabSpec = getTabHost() .newTabSpec("tags") .setIndicator( - newTabIndicator(R.drawable.tab_tags, R.string.tab_tags)) + newTabIndicator(R.drawable.tab_tags_2states, + R.string.tab_tags)) .setContent(new Intent(this, TagsActivity.class)); getTabHost().addTab(tabSpec); - getTabHost().setCurrentTabByTag("gallery"); + getTabHost().setCurrentTabByTag("gallery"); } private View newTabIndicator(int drawableResId, int textResId) { View view = getLayoutInflater().inflate(R.layout.tab, null); ((ImageView) view.findViewById(R.id.image)) .setImageResource(drawableResId); ((TextView) view.findViewById(R.id.text)).setText(textResId); return view; } private Activity getCurrentTabActivity() { String currentTab = getTabHost().getCurrentTabTag(); Activity tabActivity = getLocalActivityManager() .getActivity(currentTab); return tabActivity; } @Override protected void onResume() { super.onResume(); mActionBar.removeAction(R.id.action_add); if (Preferences.isLoggedIn(this)) { mActionBar.addAction(R.drawable.action_add, 0, R.id.action_add); } if (!Preferences.isLoggedIn(this)) { startActivity(new Intent(this, SetupActivity.class)); finish(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { Activity tabActivity = getCurrentTabActivity(); boolean showRefresh = tabActivity instanceof Refreshable; menu.findItem(R.id.menu_refresh).setVisible(showRefresh); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_settings: Intent i = new Intent(this, SettingsActivity.class); startActivity(i); return true; case R.id.menu_refresh: ((Refreshable) getCurrentActivity()).refresh(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onActionClick(int id) { Intent i = new Intent(this, UploadActivity.class); startActivity(i); } }
false
true
private void setUpTabs() { TabSpec tabSpec = getTabHost() .newTabSpec("home") .setIndicator( newTabIndicator(R.drawable.tab_home, R.string.tab_home)) .setContent(new Intent(this, HomeActivity.class)); getTabHost().addTab(tabSpec); tabSpec = getTabHost() .newTabSpec("gallery") .setIndicator( newTabIndicator(R.drawable.tab_gallery, R.string.tab_gallery)) .setContent(new Intent(this, GalleryActivity.class)); getTabHost().addTab(tabSpec); tabSpec = getTabHost() .newTabSpec("tags") .setIndicator( newTabIndicator(R.drawable.tab_tags, R.string.tab_tags)) .setContent(new Intent(this, TagsActivity.class)); getTabHost().addTab(tabSpec); getTabHost().setCurrentTabByTag("gallery"); }
private void setUpTabs() { TabSpec tabSpec = getTabHost() .newTabSpec("home") .setIndicator( newTabIndicator(R.drawable.tab_home_2states, R.string.tab_home)) .setContent(new Intent(this, HomeActivity.class)); getTabHost().addTab(tabSpec); tabSpec = getTabHost() .newTabSpec("gallery") .setIndicator( newTabIndicator(R.drawable.tab_gallery_2states, R.string.tab_gallery)) .setContent(new Intent(this, GalleryActivity.class)); getTabHost().addTab(tabSpec); tabSpec = getTabHost() .newTabSpec("tags") .setIndicator( newTabIndicator(R.drawable.tab_tags_2states, R.string.tab_tags)) .setContent(new Intent(this, TagsActivity.class)); getTabHost().addTab(tabSpec); getTabHost().setCurrentTabByTag("gallery"); }
diff --git a/Character_Equipment_Impl/src/net/sf/anathema/character/equipment/impl/character/view/EquipmentObjectView.java b/Character_Equipment_Impl/src/net/sf/anathema/character/equipment/impl/character/view/EquipmentObjectView.java index 7b76ef00d0..837d3f6c65 100644 --- a/Character_Equipment_Impl/src/net/sf/anathema/character/equipment/impl/character/view/EquipmentObjectView.java +++ b/Character_Equipment_Impl/src/net/sf/anathema/character/equipment/impl/character/view/EquipmentObjectView.java @@ -1,95 +1,95 @@ package net.sf.anathema.character.equipment.impl.character.view; import net.disy.commons.core.model.BooleanModel; import net.disy.commons.swing.action.ActionWidgetFactory; import net.disy.commons.swing.action.SmartToggleAction; import net.disy.commons.swing.layout.grid.GridDialogLayout; import net.sf.anathema.character.equipment.character.view.IEquipmentObjectView; import net.sf.anathema.character.library.taskpane.ITaskPaneGroupView; import net.sf.anathema.lib.gui.GuiUtilities; import org.jdesktop.swingx.JXTaskPane; import javax.swing.Action; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import java.util.HashMap; import java.util.Map; public class EquipmentObjectView implements IEquipmentObjectView, ITaskPaneGroupView { private final JXTaskPane taskGroup = new JXTaskPane(); private final JLabel descriptionLabel = new JLabel(); private final Map<BooleanModel, JCheckBox> boxes = new HashMap<BooleanModel, JCheckBox>(); private final Map<BooleanModel, JPanel> boxPanels = new HashMap<BooleanModel, JPanel>(); public EquipmentObjectView() { taskGroup.add(descriptionLabel); } public void setItemTitle(String title) { taskGroup.setTitle(title); } public void setItemDescription(String text) { descriptionLabel.setText(text); GuiUtilities.revalidate(taskGroup); } public void clearContents() { taskGroup.removeAll(); boxes.clear(); boxPanels.clear(); taskGroup.add(descriptionLabel); } public BooleanModel addStats(String description) { BooleanModel isSelectedModel = new BooleanModel(); - JCheckBox box = ActionWidgetFactory.createCheckBox(new SmartToggleAction(isSelectedModel, description)); + JCheckBox box = ActionWidgetFactory.createCheckBox(new SmartToggleAction(isSelectedModel, description.replaceAll( "&", "&&" ))); boxes.put(isSelectedModel, box); GridDialogLayout layout = new GridDialogLayout(1, false); layout.setVerticalSpacing(0); JPanel panel = new JPanel(layout); panel.add(box); taskGroup.add(panel); boxPanels.put(isSelectedModel, panel); return isSelectedModel; } public BooleanModel addOptionFlag(BooleanModel base, String description) { BooleanModel isSelectedModel = new BooleanModel(); JPanel basePanel = boxPanels.get(base); if (basePanel != null) { JPanel optionPanel = new JPanel(new GridDialogLayout(2, false)); optionPanel.add(new JLabel(" ...")); JCheckBox box = ActionWidgetFactory.createCheckBox(new SmartToggleAction(isSelectedModel, description)); boxes.put(isSelectedModel, box); optionPanel.add(box); basePanel.add(optionPanel); } return isSelectedModel; } public void updateStatText(BooleanModel model, String newText) { boxes.get(model).setText(newText); } public void setEnabled(BooleanModel model, boolean enabled) { boxes.get(model).setEnabled(enabled); } public JXTaskPane getTaskGroup() { return taskGroup; } public void addAction(Action action) { taskGroup.add(action); } }
true
true
public BooleanModel addStats(String description) { BooleanModel isSelectedModel = new BooleanModel(); JCheckBox box = ActionWidgetFactory.createCheckBox(new SmartToggleAction(isSelectedModel, description)); boxes.put(isSelectedModel, box); GridDialogLayout layout = new GridDialogLayout(1, false); layout.setVerticalSpacing(0); JPanel panel = new JPanel(layout); panel.add(box); taskGroup.add(panel); boxPanels.put(isSelectedModel, panel); return isSelectedModel; }
public BooleanModel addStats(String description) { BooleanModel isSelectedModel = new BooleanModel(); JCheckBox box = ActionWidgetFactory.createCheckBox(new SmartToggleAction(isSelectedModel, description.replaceAll( "&", "&&" ))); boxes.put(isSelectedModel, box); GridDialogLayout layout = new GridDialogLayout(1, false); layout.setVerticalSpacing(0); JPanel panel = new JPanel(layout); panel.add(box); taskGroup.add(panel); boxPanels.put(isSelectedModel, panel); return isSelectedModel; }
diff --git a/src/dblike/client/service/ServerListenerClient.java b/src/dblike/client/service/ServerListenerClient.java index fa44cb8..12f2511 100644 --- a/src/dblike/client/service/ServerListenerClient.java +++ b/src/dblike/client/service/ServerListenerClient.java @@ -1,79 +1,79 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dblike.client.service; import dblike.api.ServerAPI; import dblike.client.ActiveServer; import dblike.client.Client; import dblike.client.ClientStart; import dblike.service.InternetUtil; import java.rmi.AccessException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author wenhanwu */ public class ServerListenerClient implements Runnable { private boolean runningFlag = true; public void setRunningFlag(boolean flag) { this.runningFlag = flag; } private Vector<ActiveServer> ActiveServerList; public ServerListenerClient() { this.ActiveServerList = ActiveServerListClient.getActiveServerList(); } public boolean checkCurrentServer() { boolean flag = true; int currentIndex = ClientConfig.getCurrentServerIndex(); flag = true; ActiveServer aServer = ActiveServerList.get(currentIndex); if (aServer.getStatus() == InternetUtil.getOK()) { aServer.setStatus(aServer.getStatus() - 1); } else { aServer.setStatus(aServer.getStatus() - 1); if (aServer.getStatus() == 0) { - ActiveServerListClient.removeServer(aServer.getServerIP(), aServer.getPort()); + //ActiveServerListClient.removeServer(aServer.getServerIP(), aServer.getPort()); System.out.println("Server down!!!-- " + aServer.getServerIP() + ":" + aServer.getPort()); ClientStart.aClient.pickupNewServer(); flag = false; } else { //System.out.println("Connection problem, wait to see..."+ aServer.getServerIP() + ":" + aServer.getPort()); } } return flag; } public void waitForAWhile(int timeOut) { try { Thread.sleep(timeOut * 1000); } catch (InterruptedException ex) { Logger.getLogger(ServerListenerClient.class .getName()).log(Level.SEVERE, null, ex); } } public void run() { while (runningFlag) { checkCurrentServer(); waitForAWhile(InternetUtil.getTIMEOUT()); } } }
true
true
public boolean checkCurrentServer() { boolean flag = true; int currentIndex = ClientConfig.getCurrentServerIndex(); flag = true; ActiveServer aServer = ActiveServerList.get(currentIndex); if (aServer.getStatus() == InternetUtil.getOK()) { aServer.setStatus(aServer.getStatus() - 1); } else { aServer.setStatus(aServer.getStatus() - 1); if (aServer.getStatus() == 0) { ActiveServerListClient.removeServer(aServer.getServerIP(), aServer.getPort()); System.out.println("Server down!!!-- " + aServer.getServerIP() + ":" + aServer.getPort()); ClientStart.aClient.pickupNewServer(); flag = false; } else { //System.out.println("Connection problem, wait to see..."+ aServer.getServerIP() + ":" + aServer.getPort()); } } return flag; }
public boolean checkCurrentServer() { boolean flag = true; int currentIndex = ClientConfig.getCurrentServerIndex(); flag = true; ActiveServer aServer = ActiveServerList.get(currentIndex); if (aServer.getStatus() == InternetUtil.getOK()) { aServer.setStatus(aServer.getStatus() - 1); } else { aServer.setStatus(aServer.getStatus() - 1); if (aServer.getStatus() == 0) { //ActiveServerListClient.removeServer(aServer.getServerIP(), aServer.getPort()); System.out.println("Server down!!!-- " + aServer.getServerIP() + ":" + aServer.getPort()); ClientStart.aClient.pickupNewServer(); flag = false; } else { //System.out.println("Connection problem, wait to see..."+ aServer.getServerIP() + ":" + aServer.getPort()); } } return flag; }
diff --git a/src/com/reddit/worddit/FriendList.java b/src/com/reddit/worddit/FriendList.java index 9e837a1..ea928ca 100755 --- a/src/com/reddit/worddit/FriendList.java +++ b/src/com/reddit/worddit/FriendList.java @@ -1,108 +1,108 @@ package com.reddit.worddit; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; import com.reddit.worddit.adapters.FriendListAdapter; import com.reddit.worddit.api.APICall; import com.reddit.worddit.api.APICallback; import com.reddit.worddit.api.Session; import com.reddit.worddit.api.response.Friend; public class FriendList extends ListActivity implements APICallback { public static final String TAG = "FriendList"; protected Friend[] mFriends; protected Session mSession; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.friends_options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.friend_add: //TODO: add friend return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.worddit_friend_list); registerForContextMenu(getListView()); Intent i = getIntent(); mSession = (Session) i.getParcelableExtra(Constants.EXTRA_SESSION); fetchFriends(); } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); menu.setHeaderTitle(mFriends[((AdapterContextMenuInfo) menuInfo).position].email); if(mFriends[((AdapterContextMenuInfo) menuInfo).position].isRequested()) { inflater.inflate(R.menu.friend_request_menu, menu); } else if (mFriends[((AdapterContextMenuInfo) menuInfo).position].isActive()) { inflater.inflate(R.menu.friend_active_menu, menu); } } public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.friend_accept: - new APICall(this, mSession).acceptFriend(new String[]{mFriends[info.position].id}); + new APICall(this, mSession).acceptFriend(mFriends[info.position].id); return true; case R.id.friend_reject: - new APICall(this, mSession).rejectFriend(new String[]{mFriends[info.position].id}); + new APICall(this, mSession).rejectFriend(mFriends[info.position].id); return true; case R.id.friend_game_request: // TODO: Request game return true; case R.id.friend_message: //TODO: Message friend return true; default: return super.onContextItemSelected(item); } } private void fetchFriends() { new APICall(this, mSession).getFriends(); } @Override public void onCallComplete(boolean success, APICall task) { if(success) { if(task.getCall() == APICall.USER_FRIENDS) { mFriends = (Friend[]) task.getPayload(); setListAdapter(new FriendListAdapter(this, mFriends, R.id.item_friend_email, R.id.item_friend_status)); } else if(task.getCall() == APICall.USER_ACCEPTFRIEND || task.getCall() == APICall.USER_DEFRIEND) { new APICall(this, mSession).getFriends(); // Way too inefficient, but temporarily gets the job done. } } } }
false
true
public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.friend_accept: new APICall(this, mSession).acceptFriend(new String[]{mFriends[info.position].id}); return true; case R.id.friend_reject: new APICall(this, mSession).rejectFriend(new String[]{mFriends[info.position].id}); return true; case R.id.friend_game_request: // TODO: Request game return true; case R.id.friend_message: //TODO: Message friend return true; default: return super.onContextItemSelected(item); } }
public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.friend_accept: new APICall(this, mSession).acceptFriend(mFriends[info.position].id); return true; case R.id.friend_reject: new APICall(this, mSession).rejectFriend(mFriends[info.position].id); return true; case R.id.friend_game_request: // TODO: Request game return true; case R.id.friend_message: //TODO: Message friend return true; default: return super.onContextItemSelected(item); } }
diff --git a/CCProbe/source/LObjGraphProp.java b/CCProbe/source/LObjGraphProp.java index 999d457..a8171ad 100644 --- a/CCProbe/source/LObjGraphProp.java +++ b/CCProbe/source/LObjGraphProp.java @@ -1,213 +1,213 @@ package org.concord.CCProbe; import waba.util.*; import waba.ui.*; import extra.io.*; import extra.util.*; import org.concord.LabBook.*; import graph.*; import org.concord.waba.extra.event.*; import org.concord.waba.extra.ui.*; import org.concord.waba.extra.util.*; import extra.util.*; public class LObjGraphProp extends LabObjectView implements ActionListener { PropContainer propsGraph = null; PropContainer propsXAxis = null; PropContainer propsYAxis = null; PropObject propDataSources; PropObject propVisibleSources = null; PropObject propTitle; LObjGraph graph; Label graphSummary = new Label(""); Axis visYAxis = null; Axis visXAxis = null; PropertyView propView = null; int index=0; String [] testList = {"test1", "test2"}; public LObjGraphProp(ViewContainer vc, LObjGraph g, int index) { super(vc); graph = g; lObj = g; this.index = index; setupProperties(); } public void layout(boolean sDone) { if(didLayout) return; didLayout = true; propView = new PropertyView(this); PropertyPane graphPane = new PropertyPane(propsGraph, propView); graphPane.addTopLabel(graphSummary); graphPane.setAlignment(PropertyView.ALIGN_TOP); propView.addPane(graphPane); propView.addContainer(propsYAxis); propView.addContainer(propsXAxis); propView.setCurTab(index); add(propView); } public void setRect(int x, int y, int width, int height) { super.setRect(x,y,width,height); if(!didLayout) layout(false); propView.setRect(0,0,width,height); } String [] dsStrings = null; public void setupProperties() { int id = 0; GraphSettings curGS = graph.getCurGraphSettings(); if(curGS == null) return; if(propsGraph == null){ propsGraph = new PropContainer("Graph"); visYAxis = curGS.getYAxis(); visXAxis = curGS.getXAxis(); if(visYAxis == null || visXAxis == null) return; propsYAxis = visYAxis.getPropContainer(); propsYAxis.setName("YAxis"); propsXAxis = visXAxis.getPropContainer(); propsXAxis.setName("XAxis"); propTitle = new PropObject("Title", "Title", id++, graph.getTitleNoSummary()); propTitle.prefWidth = 120; - if(propDataSources != null) propsGraph.addProperty(propDataSources); - if(propVisibleSources != null) propsGraph.addProperty(propVisibleSources); propsGraph.addProperty(propTitle); String summary = graph.getSummary(); if(summary == null) summary = ""; graphSummary.setText(summary); dsStrings = new String [graph.numDataSources]; for(int i=0; i<graph.numDataSources; i++){ DataSource ds = graph.getDataSource(i); dsStrings[i] = ds.getQuantityMeasured(); } if(graph.getMaxLines() != 1){ int defIndex = graph.getCurGraphSettings().dsIndex; propDataSources = new PropObject("Data", "Data", id++, dsStrings, defIndex); propDataSources.prefWidth = 120; propDataSources.setType(PropObject.CHOICE_SETTINGS); propDataSources.setSettingsButtonName("Setup"); } if(dsStrings.length > 1){ propVisibleSources = new PropObject("Visible", "Visible", id++, dsStrings); propVisibleSources.prefWidth = 120; propVisibleSources.setType(PropObject.MULTIPLE_SEL_LIST); if(graph.getMaxLines() == 1) propVisibleSources.setRadio(true); for(int i=0; i<dsStrings.length; i++){ propVisibleSources.setCheckedValue(i, graph.getVisible(i)); } } + if(propDataSources != null) propsGraph.addProperty(propDataSources); + if(propVisibleSources != null) propsGraph.addProperty(propVisibleSources); } else { propTitle.setValue(graph.getTitleNoSummary()); String summary = graph.getSummary(); if(summary == null) summary = ""; graphSummary.setText(summary); if(propDataSources != null){ propDataSources.setValue(dsStrings[graph.getCurGraphSettings().dsIndex]); } if(propVisibleSources != null){ if(graph.getMaxLines() == 1) propVisibleSources.setRadio(true); for(int i=0; i<dsStrings.length; i++){ propVisibleSources.setCheckedValue(i, graph.getVisible(i)); } } visYAxis = curGS.getYAxis(); visXAxis = curGS.getXAxis(); if(visYAxis == null || visXAxis == null) return; propsYAxis = visYAxis.getPropContainer(); propsYAxis.setName("YAxis"); propsXAxis = visXAxis.getPropContainer(); propsXAxis.setName("XAxis"); } } public void actionPerformed(ActionEvent e) { GraphSettings curGS = graph.getCurGraphSettings(); if(e.getActionCommand().equals("Apply")){ int firstDS = -1; if(propVisibleSources != null){ String [] dsNames = propVisibleSources.getPossibleValues(); for(int i=0; i<dsNames.length; i++){ graph.setVisible(i, propVisibleSources.getCheckedValue(i)); if(propVisibleSources.getCheckedValue(i)){ firstDS = i; } } } GraphSettings newGS; if(propDataSources == null){ newGS = graph.getCurGraphSettings(); } else { int dsIndex = propDataSources.getIndex(); graph.setCurGSIndex(dsIndex); newGS = graph.getCurGraphSettings(); } if(newGS == null || visXAxis == null || visYAxis == null) return; visXAxis.applyProperties(); visYAxis.applyProperties(); newGS.updateAxis(); // This should be cleaned up String newTitle = propTitle.getValue(); if(newTitle != null && newTitle.length() <= 0){ newTitle = null; } graph.setTitle(newTitle); graph.notifyObjListeners(new LabObjEvent(graph, 0)); } else if(e.getActionCommand().equals("Setup")){ // This should be an index for safety String dataSourceName = propDataSources.getValue(); if(dsStrings != null){ for(int i=0; i<dsStrings.length; i++){ if(dsStrings[i].equals(dataSourceName)){ DataSource selDS = graph.getDataSource(i); if(selDS instanceof LObjProbeDataSource){ LObjProbeDataSource pds = (LObjProbeDataSource)selDS; pds.showProp(); } return; } } } } else if(e.getActionCommand().equals("Close")){ // this is a cancel or close if(container != null){ container.done(this); } } } }
false
true
public void setupProperties() { int id = 0; GraphSettings curGS = graph.getCurGraphSettings(); if(curGS == null) return; if(propsGraph == null){ propsGraph = new PropContainer("Graph"); visYAxis = curGS.getYAxis(); visXAxis = curGS.getXAxis(); if(visYAxis == null || visXAxis == null) return; propsYAxis = visYAxis.getPropContainer(); propsYAxis.setName("YAxis"); propsXAxis = visXAxis.getPropContainer(); propsXAxis.setName("XAxis"); propTitle = new PropObject("Title", "Title", id++, graph.getTitleNoSummary()); propTitle.prefWidth = 120; if(propDataSources != null) propsGraph.addProperty(propDataSources); if(propVisibleSources != null) propsGraph.addProperty(propVisibleSources); propsGraph.addProperty(propTitle); String summary = graph.getSummary(); if(summary == null) summary = ""; graphSummary.setText(summary); dsStrings = new String [graph.numDataSources]; for(int i=0; i<graph.numDataSources; i++){ DataSource ds = graph.getDataSource(i); dsStrings[i] = ds.getQuantityMeasured(); } if(graph.getMaxLines() != 1){ int defIndex = graph.getCurGraphSettings().dsIndex; propDataSources = new PropObject("Data", "Data", id++, dsStrings, defIndex); propDataSources.prefWidth = 120; propDataSources.setType(PropObject.CHOICE_SETTINGS); propDataSources.setSettingsButtonName("Setup"); } if(dsStrings.length > 1){ propVisibleSources = new PropObject("Visible", "Visible", id++, dsStrings); propVisibleSources.prefWidth = 120; propVisibleSources.setType(PropObject.MULTIPLE_SEL_LIST); if(graph.getMaxLines() == 1) propVisibleSources.setRadio(true); for(int i=0; i<dsStrings.length; i++){ propVisibleSources.setCheckedValue(i, graph.getVisible(i)); } } } else { propTitle.setValue(graph.getTitleNoSummary()); String summary = graph.getSummary(); if(summary == null) summary = ""; graphSummary.setText(summary); if(propDataSources != null){ propDataSources.setValue(dsStrings[graph.getCurGraphSettings().dsIndex]); } if(propVisibleSources != null){ if(graph.getMaxLines() == 1) propVisibleSources.setRadio(true); for(int i=0; i<dsStrings.length; i++){ propVisibleSources.setCheckedValue(i, graph.getVisible(i)); } } visYAxis = curGS.getYAxis(); visXAxis = curGS.getXAxis(); if(visYAxis == null || visXAxis == null) return; propsYAxis = visYAxis.getPropContainer(); propsYAxis.setName("YAxis"); propsXAxis = visXAxis.getPropContainer(); propsXAxis.setName("XAxis"); } }
public void setupProperties() { int id = 0; GraphSettings curGS = graph.getCurGraphSettings(); if(curGS == null) return; if(propsGraph == null){ propsGraph = new PropContainer("Graph"); visYAxis = curGS.getYAxis(); visXAxis = curGS.getXAxis(); if(visYAxis == null || visXAxis == null) return; propsYAxis = visYAxis.getPropContainer(); propsYAxis.setName("YAxis"); propsXAxis = visXAxis.getPropContainer(); propsXAxis.setName("XAxis"); propTitle = new PropObject("Title", "Title", id++, graph.getTitleNoSummary()); propTitle.prefWidth = 120; propsGraph.addProperty(propTitle); String summary = graph.getSummary(); if(summary == null) summary = ""; graphSummary.setText(summary); dsStrings = new String [graph.numDataSources]; for(int i=0; i<graph.numDataSources; i++){ DataSource ds = graph.getDataSource(i); dsStrings[i] = ds.getQuantityMeasured(); } if(graph.getMaxLines() != 1){ int defIndex = graph.getCurGraphSettings().dsIndex; propDataSources = new PropObject("Data", "Data", id++, dsStrings, defIndex); propDataSources.prefWidth = 120; propDataSources.setType(PropObject.CHOICE_SETTINGS); propDataSources.setSettingsButtonName("Setup"); } if(dsStrings.length > 1){ propVisibleSources = new PropObject("Visible", "Visible", id++, dsStrings); propVisibleSources.prefWidth = 120; propVisibleSources.setType(PropObject.MULTIPLE_SEL_LIST); if(graph.getMaxLines() == 1) propVisibleSources.setRadio(true); for(int i=0; i<dsStrings.length; i++){ propVisibleSources.setCheckedValue(i, graph.getVisible(i)); } } if(propDataSources != null) propsGraph.addProperty(propDataSources); if(propVisibleSources != null) propsGraph.addProperty(propVisibleSources); } else { propTitle.setValue(graph.getTitleNoSummary()); String summary = graph.getSummary(); if(summary == null) summary = ""; graphSummary.setText(summary); if(propDataSources != null){ propDataSources.setValue(dsStrings[graph.getCurGraphSettings().dsIndex]); } if(propVisibleSources != null){ if(graph.getMaxLines() == 1) propVisibleSources.setRadio(true); for(int i=0; i<dsStrings.length; i++){ propVisibleSources.setCheckedValue(i, graph.getVisible(i)); } } visYAxis = curGS.getYAxis(); visXAxis = curGS.getXAxis(); if(visYAxis == null || visXAxis == null) return; propsYAxis = visYAxis.getPropContainer(); propsYAxis.setName("YAxis"); propsXAxis = visXAxis.getPropContainer(); propsXAxis.setName("XAxis"); } }
diff --git a/src/main/java/jenkins/plugins/svnmerge/IntegratableProjectAction.java b/src/main/java/jenkins/plugins/svnmerge/IntegratableProjectAction.java index aca6caa..0b30b7e 100644 --- a/src/main/java/jenkins/plugins/svnmerge/IntegratableProjectAction.java +++ b/src/main/java/jenkins/plugins/svnmerge/IntegratableProjectAction.java @@ -1,167 +1,168 @@ package jenkins.plugins.svnmerge; import hudson.BulkChange; import hudson.Util; import hudson.model.AbstractModelObject; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.scm.SCM; import hudson.scm.SubversionSCM; import hudson.scm.SubversionSCM.ModuleLocation; import jenkins.model.Jenkins; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNNodeKind; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.wc.SVNClientManager; import org.tmatesoft.svn.core.wc.SVNInfo; import org.tmatesoft.svn.core.wc.SVNRevision; import javax.servlet.ServletException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Project-level {@link Action} that shows the feature branches. * * <p> * This is attached to the upstream job. * * @author Kohsuke Kawaguchi */ public class IntegratableProjectAction extends AbstractModelObject implements Action { public final AbstractProject<?,?> project; private final IntegratableProject ip; /*package*/ IntegratableProjectAction(IntegratableProject ip) { this.ip = ip; this.project = ip.getOwner(); } public String getIconFileName() { return "/plugin/svnmerge/24x24/sync.gif"; } public String getDisplayName() { return "Feature Branches"; } public String getSearchUrl() { return getDisplayName(); } public String getUrlName() { return "featureBranches"; } /** * Gets feature branches for this project. */ public List<AbstractProject<?,?>> getBranches() { String n = project.getName(); List<AbstractProject<?,?>> r = new ArrayList<AbstractProject<?,?>>(); for (AbstractProject<?,?> p : Jenkins.getInstance().getItems(AbstractProject.class)) { FeatureBranchProperty fbp = p.getProperty(FeatureBranchProperty.class); if(fbp!=null && fbp.getUpstream().equals(n)) r.add(p); } return r; } public void doNewBranch(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name, @QueryParameter boolean attach, @QueryParameter String commitMessage) throws ServletException, IOException { requirePOST(); name = Util.fixEmptyAndTrim(name); if (name==null) { sendError("Name is required"); return; } commitMessage = Util.fixEmptyAndTrim(commitMessage); if (commitMessage==null) { commitMessage = "Created a feature branch from Jenkins"; } SCM scm = project.getScm(); if (!(scm instanceof SubversionSCM)) { sendError("This project doesn't use Subversion as SCM"); return; } // TODO: check for multiple locations SubversionSCM svn = (SubversionSCM) scm; - String url = svn.getLocations()[0].getURL(); + ModuleLocation firstLocation = svn.getLocations()[0]; + String url = firstLocation.getURL(); Matcher m = KEYWORD.matcher(url); if(!m.find()) { sendError("Unable to infer the new branch name from "+url); return; } url = url.substring(0,m.start())+"/branches/"+name; if(!attach) { SVNClientManager svnm = SubversionSCM.createSvnClientManager(project); try { SVNURL dst = SVNURL.parseURIEncoded(url); // check if the branch already exists try { SVNInfo info = svnm.getWCClient().doInfo(dst, SVNRevision.HEAD, SVNRevision.HEAD); if(info.getKind()== SVNNodeKind.DIR) { // ask the user if we should attach req.getView(this,"_attach.jelly").forward(req,rsp); return; } else { sendError(info.getURL()+" already exists."); return; } } catch (SVNException e) { // path doesn't exist, which is good } // create a branch svnm.getCopyClient().doCopy( - svn.getLocations()[0].getSVNURL(), SVNRevision.HEAD, + firstLocation.getSVNURL(), SVNRevision.HEAD, dst, false, true, commitMessage); } catch (SVNException e) { sendError(e); return; } } // copy a job, and adjust its properties for integration AbstractProject<?,?> copy = Jenkins.getInstance().copy(project, project.getName() + "-" + name.replaceAll("/", "-")); BulkChange bc = new BulkChange(copy); try { copy.removeProperty(IntegratableProject.class); ((AbstractProject)copy).addProperty(new FeatureBranchProperty(project.getName())); // pointless cast for working around javac bug as of JDK1.6.0_02 // update the SCM config to point to the branch SubversionSCM svnScm = (SubversionSCM)copy.getScm(); copy.setScm( new SubversionSCM( - Arrays.asList(new ModuleLocation(url,null)), + Arrays.asList(new ModuleLocation(url,firstLocation.getLocalDir())), svnScm.getWorkspaceUpdater(), svnScm.getBrowser(), svnScm.getExcludedRegions(), svnScm.getExcludedUsers(), svnScm.getExcludedRevprop(), svnScm.getExcludedCommitMessages(), svnScm.getIncludedRegions() )); } finally { bc.commit(); } rsp.sendRedirect2(req.getContextPath()+"/"+copy.getUrl()); } private static final Pattern KEYWORD = Pattern.compile("/(trunk(/|$)|branches/)"); }
false
true
public void doNewBranch(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name, @QueryParameter boolean attach, @QueryParameter String commitMessage) throws ServletException, IOException { requirePOST(); name = Util.fixEmptyAndTrim(name); if (name==null) { sendError("Name is required"); return; } commitMessage = Util.fixEmptyAndTrim(commitMessage); if (commitMessage==null) { commitMessage = "Created a feature branch from Jenkins"; } SCM scm = project.getScm(); if (!(scm instanceof SubversionSCM)) { sendError("This project doesn't use Subversion as SCM"); return; } // TODO: check for multiple locations SubversionSCM svn = (SubversionSCM) scm; String url = svn.getLocations()[0].getURL(); Matcher m = KEYWORD.matcher(url); if(!m.find()) { sendError("Unable to infer the new branch name from "+url); return; } url = url.substring(0,m.start())+"/branches/"+name; if(!attach) { SVNClientManager svnm = SubversionSCM.createSvnClientManager(project); try { SVNURL dst = SVNURL.parseURIEncoded(url); // check if the branch already exists try { SVNInfo info = svnm.getWCClient().doInfo(dst, SVNRevision.HEAD, SVNRevision.HEAD); if(info.getKind()== SVNNodeKind.DIR) { // ask the user if we should attach req.getView(this,"_attach.jelly").forward(req,rsp); return; } else { sendError(info.getURL()+" already exists."); return; } } catch (SVNException e) { // path doesn't exist, which is good } // create a branch svnm.getCopyClient().doCopy( svn.getLocations()[0].getSVNURL(), SVNRevision.HEAD, dst, false, true, commitMessage); } catch (SVNException e) { sendError(e); return; } } // copy a job, and adjust its properties for integration AbstractProject<?,?> copy = Jenkins.getInstance().copy(project, project.getName() + "-" + name.replaceAll("/", "-")); BulkChange bc = new BulkChange(copy); try { copy.removeProperty(IntegratableProject.class); ((AbstractProject)copy).addProperty(new FeatureBranchProperty(project.getName())); // pointless cast for working around javac bug as of JDK1.6.0_02 // update the SCM config to point to the branch SubversionSCM svnScm = (SubversionSCM)copy.getScm(); copy.setScm( new SubversionSCM( Arrays.asList(new ModuleLocation(url,null)), svnScm.getWorkspaceUpdater(), svnScm.getBrowser(), svnScm.getExcludedRegions(), svnScm.getExcludedUsers(), svnScm.getExcludedRevprop(), svnScm.getExcludedCommitMessages(), svnScm.getIncludedRegions() )); } finally { bc.commit(); } rsp.sendRedirect2(req.getContextPath()+"/"+copy.getUrl()); }
public void doNewBranch(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name, @QueryParameter boolean attach, @QueryParameter String commitMessage) throws ServletException, IOException { requirePOST(); name = Util.fixEmptyAndTrim(name); if (name==null) { sendError("Name is required"); return; } commitMessage = Util.fixEmptyAndTrim(commitMessage); if (commitMessage==null) { commitMessage = "Created a feature branch from Jenkins"; } SCM scm = project.getScm(); if (!(scm instanceof SubversionSCM)) { sendError("This project doesn't use Subversion as SCM"); return; } // TODO: check for multiple locations SubversionSCM svn = (SubversionSCM) scm; ModuleLocation firstLocation = svn.getLocations()[0]; String url = firstLocation.getURL(); Matcher m = KEYWORD.matcher(url); if(!m.find()) { sendError("Unable to infer the new branch name from "+url); return; } url = url.substring(0,m.start())+"/branches/"+name; if(!attach) { SVNClientManager svnm = SubversionSCM.createSvnClientManager(project); try { SVNURL dst = SVNURL.parseURIEncoded(url); // check if the branch already exists try { SVNInfo info = svnm.getWCClient().doInfo(dst, SVNRevision.HEAD, SVNRevision.HEAD); if(info.getKind()== SVNNodeKind.DIR) { // ask the user if we should attach req.getView(this,"_attach.jelly").forward(req,rsp); return; } else { sendError(info.getURL()+" already exists."); return; } } catch (SVNException e) { // path doesn't exist, which is good } // create a branch svnm.getCopyClient().doCopy( firstLocation.getSVNURL(), SVNRevision.HEAD, dst, false, true, commitMessage); } catch (SVNException e) { sendError(e); return; } } // copy a job, and adjust its properties for integration AbstractProject<?,?> copy = Jenkins.getInstance().copy(project, project.getName() + "-" + name.replaceAll("/", "-")); BulkChange bc = new BulkChange(copy); try { copy.removeProperty(IntegratableProject.class); ((AbstractProject)copy).addProperty(new FeatureBranchProperty(project.getName())); // pointless cast for working around javac bug as of JDK1.6.0_02 // update the SCM config to point to the branch SubversionSCM svnScm = (SubversionSCM)copy.getScm(); copy.setScm( new SubversionSCM( Arrays.asList(new ModuleLocation(url,firstLocation.getLocalDir())), svnScm.getWorkspaceUpdater(), svnScm.getBrowser(), svnScm.getExcludedRegions(), svnScm.getExcludedUsers(), svnScm.getExcludedRevprop(), svnScm.getExcludedCommitMessages(), svnScm.getIncludedRegions() )); } finally { bc.commit(); } rsp.sendRedirect2(req.getContextPath()+"/"+copy.getUrl()); }
diff --git a/examples/org.eclipse.rap.demo.controls/src/org/eclipse/rap/demo/controls/ListTab.java b/examples/org.eclipse.rap.demo.controls/src/org/eclipse/rap/demo/controls/ListTab.java index bb29af30c..cc249c524 100644 --- a/examples/org.eclipse.rap.demo.controls/src/org/eclipse/rap/demo/controls/ListTab.java +++ b/examples/org.eclipse.rap.demo.controls/src/org/eclipse/rap/demo/controls/ListTab.java @@ -1,392 +1,403 @@ /******************************************************************************* * Copyright (c) 2007, 2013 Innoopract Informationssysteme GmbH 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: * Innoopract Informationssysteme GmbH - initial API and implementation * EclipseSource - ongoing development ******************************************************************************/ package org.eclipse.rap.demo.controls; import java.util.ArrayList; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.rap.rwt.RWT; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MenuAdapter; import org.eclipse.swt.events.MenuEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; 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.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class ListTab extends ExampleTab { private static final java.util.List<String> ELEMENTS; static { ELEMENTS = new ArrayList<String>(); String text = "A very long item that demonstrates horizontal scrolling in a List"; ELEMENTS.add( text ); text = "An item with a linebreak\n(converted to a whitespace)"; ELEMENTS.add( text ); text = "...and other control chars: \u0003 \t \u0004 \u000F"; ELEMENTS.add( text ); for( int i = 1; i <= 25; i++ ) { ELEMENTS.add( "Item " + i ); } } private List list; private List list2; private ListViewer listViewer; private boolean markup; public ListTab() { super( "List" ); } @Override protected void createStyleControls( Composite parent ) { createStyleButton( "BORDER", SWT.BORDER ); createStyleButton( "SINGLE", SWT.SINGLE ); createStyleButton( "MULTI", SWT.MULTI ); createStyleButton( "H_SCROLL", SWT.H_SCROLL ); createStyleButton( "V_SCROLL", SWT.V_SCROLL ); createVisibilityButton(); createEnablementButton(); createMarkupButton(); createFgColorButton(); createBgColorButton(); createBgImageButton(); createFontChooser(); createCursorCombo(); createSelectionButton(); Group group = new Group( parent, SWT.NONE ); group.setText( "Manipulate Right List" ); group.setLayout( new GridLayout() ); createAddItemsControls( group ); createSetTopIndexControls( group ); createGetTopIndexControls( group ); createShowSelectionControls( group ); createRemoveFirstItemButton( group ); createSelectAllButton( group ); createDeselectAllButton( group ); createSelectButton( group ); createDeselectButton( group ); createSetSelectionButton( group ); } @Override protected void createExampleControls( final Composite parent ) { parent.setLayout( new GridLayout( 2, true ) ); int style = getStyle(); list = new List( parent, style ); list.setLayoutData( new GridData( GridData.FILL_BOTH ) ); Menu menu = new Menu( list ); MenuItem menuItem = new MenuItem( menu, SWT.PUSH ); menuItem.setText( "Context menu item" ); list.setMenu( menu ); listViewer = new ListViewer( list ); listViewer.setContentProvider( new ArrayContentProvider() ); listViewer.setLabelProvider( new LabelProvider() ); listViewer.setInput( ELEMENTS ); list.addListener( SWT.DefaultSelection, new Listener() { public void handleEvent( Event event ) { String item = list.getItem( list.getSelectionIndex() ); String message = "Selected Item: " + item; MessageDialog.openInformation( getShell(), "Selection", message ); } } ); registerControl( list ); // List 2 list2 = new List( parent, style ); list2.setData( RWT.MARKUP_ENABLED, new Boolean( markup ) ); list2.add( "Item 0" ); list2.add( "Item 1" ); list2.add( "Item 2" ); if( markup ) { list2.setData( RWT.CUSTOM_ITEM_HEIGHT, new Integer( 60 ) ); list2.add( "<b>Some Markup Text</b><br/><i>This is italic</i>" ); + list2.add( "A real <a href='http://eclipse.org/rap'>link</a>" ); + list2.add( "This one opens <a href='http://eclipse.org/rap' target='_blank'>a new tab</a>" ); + list2.add( "This is a special <a href='value_of_href' target='_rwt'>RWT Hyperlink</a>" ); + list2.addListener( SWT.Selection, new Listener() { + public void handleEvent( Event event ) { + if( event.detail == RWT.HYPERLINK ) { + log( "Clicked link \"" + event.text + "\"" ); + } + } + } ); + } else { + createPopupMenu( parent.getShell(), list2 ); } list2.setLayoutData( new GridData( GridData.FILL_BOTH ) ); registerControl( list2 ); - createPopupMenu( parent.getShell(), list2 ); // Code int separatorStyle = SWT.SEPARATOR | SWT.HORIZONTAL | SWT.SHADOW_OUT; Label separator = new Label( parent, separatorStyle ); separator.setLayoutData( createGridDataWithSpan() ); Label codeLabel = new Label( parent, SWT.WRAP ); String codeLabelText = "Please note that the content of the left List is provided by a " + "ListViewer with JFace API."; codeLabel.setText( codeLabelText ); codeLabel.setLayoutData( createGridDataWithSpan() ); Link link = new Link( parent, SWT.NONE ); link.setText( "See <a>example code</a>" ); link.setLayoutData( createGridDataWithSpan() ); link.addSelectionListener( new SelectionAdapter() { private final String code = getExampleCode(); @Override public void widgetSelected( final SelectionEvent event ) { String title = "ListViewer Example Code"; HtmlDialog dialog = new HtmlDialog( parent.getShell(), title, code ); dialog.setSize( 550, 400 ); dialog.open(); } } ); } private GridData createGridDataWithSpan() { GridData gridData = new GridData( GridData.FILL_HORIZONTAL ); gridData.horizontalSpan = 2; return gridData; } private void createPopupMenu( final Shell parent, final List list ) { final Menu menu = new Menu( parent, SWT.POP_UP ); String[] listItems = list.getItems(); for( int i = 0; i < listItems.length; i++ ) { MenuItem item = new MenuItem( menu, SWT.PUSH ); item.setText( listItems[ i ] ); } menu.addMenuListener( new MenuAdapter() { @Override public void menuShown( MenuEvent e ) { MenuItem[] items = menu.getItems(); for( int i = 0; i < items.length; i++ ) { MenuItem item = items[ i ]; item.setEnabled( list.isSelected( i ) ); } } } ); list.setMenu( menu ); } private void createSelectionButton() { Button button = new Button( styleComp, SWT.PUSH ); button.setText( "Select first" ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent e ) { listViewer.setSelection( new StructuredSelection( ELEMENTS.get( 0 ) ) ); } } ); } protected Button createMarkupButton( ) { final Button button = new Button( styleComp, SWT.CHECK ); button.setText( "Markup" ); button.setSelection( markup ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent event ) { markup = button.getSelection(); createNew(); } } ); return button; } private void createAddItemsControls( Composite parent ) { Composite composite = new Composite( parent, SWT.NONE ); composite.setLayout( new GridLayout( 3, false ) ); Label lblAddItem = new Label( composite, SWT.NONE ); lblAddItem.setText( "Add" ); final Text txtAddItem = new Text( composite, SWT.BORDER ); txtAddItem.setLayoutData( new GridData( 50, SWT.DEFAULT) ); Button btnAddItem = new Button( composite, SWT.PUSH ); btnAddItem.setText( "Item(s)" ); btnAddItem.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( final SelectionEvent event ) { int count = -1; String[] listItems = list2.getItems(); int existingItems = listItems.length; try { count = Integer.parseInt( txtAddItem.getText() ); } catch( NumberFormatException e ) { // } if( count < 0 ) { String msg = "Invalid number of ListItems: " + txtAddItem.getText(); MessageDialog.openInformation( getShell(), "Information", msg ); } else { for( int i = 0; i < count; i++ ) { list2.add( "Item " + ( existingItems + i ) ); } } } } ); } private void createSetTopIndexControls( Composite parent ) { Composite composite = new Composite( parent, SWT.NONE ); composite.setLayout( new GridLayout( 2, false ) ); final Text txtTopIndex = new Text( composite, SWT.BORDER ); txtTopIndex.setLayoutData( new GridData( 50, SWT.DEFAULT) ); Button button = new Button( composite, SWT.PUSH ); button.setText( "setTopIndex" ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( final SelectionEvent event ) { try { int topIndex = Integer.parseInt( txtTopIndex.getText() ); list2.setTopIndex( topIndex ); } catch( NumberFormatException e ) { String msg = "Invalid number of topIndex: " + txtTopIndex.getText(); MessageDialog.openInformation( getShell(), "Information", msg ); } } } ); } private void createGetTopIndexControls( Composite parent ) { Composite composite = new Composite( parent, SWT.NONE ); composite.setLayout( new GridLayout( 2, false ) ); final Text txtTopIndex = new Text( composite, SWT.BORDER ); txtTopIndex.setLayoutData( new GridData( 50, SWT.DEFAULT) ); txtTopIndex.setEditable( false ); Button button = new Button( composite, SWT.PUSH ); button.setText( "getTopIndex" ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( final SelectionEvent event ) { int topIndex = list2.getTopIndex(); txtTopIndex.setText( String.valueOf( topIndex ) ); } } ); } private void createShowSelectionControls( Composite parent ) { Composite composite = new Composite( parent, SWT.NONE ); composite.setLayout( new GridLayout( 2, false ) ); Button button = new Button( composite, SWT.PUSH ); button.setText( "showSelection" ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( final SelectionEvent event ) { list2.showSelection(); } } ); } private void createRemoveFirstItemButton( Composite parent ) { Button button = new Button( parent , SWT.PUSH ); button.setText( "Remove First Item" ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent event ) { if( list2.getItemCount() > 0 ) { list2.remove( 0 ); } } } ); } private void createSelectAllButton( Composite parent ) { Button button = new Button( parent, SWT.PUSH ); button.setText( "Select All" ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( final SelectionEvent event ) { list2.selectAll(); } } ); } private void createDeselectAllButton( Composite parent ) { Button button = new Button( parent, SWT.PUSH ); button.setText( "Deselect All" ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( final SelectionEvent event ) { list2.deselectAll(); } } ); } private void createSelectButton( Composite parent ) { Button button = new Button( parent, SWT.PUSH ); button.setText( "Select 100th item" ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( final SelectionEvent event ) { if( list2.getItemCount() > 100 ) { list2.select( 100 ); } } } ); } private void createDeselectButton( Composite parent ) { Button button = new Button( parent, SWT.PUSH ); button.setText( "Deselect second item" ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( final SelectionEvent event ) { if( list2.getItemCount() > 1 ) { list2.deselect( 1 ); } } } ); } private void createSetSelectionButton( Composite parent ) { Button button = new Button( parent, SWT.PUSH ); button.setText( "Set selection to first item" ); button.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( final SelectionEvent event ) { if( list2.getItemCount() > 0 ) { list2.setSelection( new int[] { 0 } ); } } } ); } private String getExampleCode() { String result = "<html><head></head></body>" + "<pre>" + "class ListContentProvider implements IStructuredContentProvider {\n" + " public Object[] getElements( final Object inputElement ) {\n" + " return ( ( java.util.List )inputElement ).toArray();\n" + " }\n" + "}\n" + "...\n" + "java.util.List elements = ...\n" + "...\n" + "ListViewer viewer = new ListViewer( parent );\n" + "viewer.setContentProvider( new ListContentProvider() );\n" + "viewer.setLabelProvider( new LabelProvider() );\n" + "java.util.List input = new ArrayList();\n" + "... // populate list\n" + "viewer.setInput( input );\n" + "</pre>" + "</body>"; return result; } }
false
true
protected void createExampleControls( final Composite parent ) { parent.setLayout( new GridLayout( 2, true ) ); int style = getStyle(); list = new List( parent, style ); list.setLayoutData( new GridData( GridData.FILL_BOTH ) ); Menu menu = new Menu( list ); MenuItem menuItem = new MenuItem( menu, SWT.PUSH ); menuItem.setText( "Context menu item" ); list.setMenu( menu ); listViewer = new ListViewer( list ); listViewer.setContentProvider( new ArrayContentProvider() ); listViewer.setLabelProvider( new LabelProvider() ); listViewer.setInput( ELEMENTS ); list.addListener( SWT.DefaultSelection, new Listener() { public void handleEvent( Event event ) { String item = list.getItem( list.getSelectionIndex() ); String message = "Selected Item: " + item; MessageDialog.openInformation( getShell(), "Selection", message ); } } ); registerControl( list ); // List 2 list2 = new List( parent, style ); list2.setData( RWT.MARKUP_ENABLED, new Boolean( markup ) ); list2.add( "Item 0" ); list2.add( "Item 1" ); list2.add( "Item 2" ); if( markup ) { list2.setData( RWT.CUSTOM_ITEM_HEIGHT, new Integer( 60 ) ); list2.add( "<b>Some Markup Text</b><br/><i>This is italic</i>" ); } list2.setLayoutData( new GridData( GridData.FILL_BOTH ) ); registerControl( list2 ); createPopupMenu( parent.getShell(), list2 ); // Code int separatorStyle = SWT.SEPARATOR | SWT.HORIZONTAL | SWT.SHADOW_OUT; Label separator = new Label( parent, separatorStyle ); separator.setLayoutData( createGridDataWithSpan() ); Label codeLabel = new Label( parent, SWT.WRAP ); String codeLabelText = "Please note that the content of the left List is provided by a " + "ListViewer with JFace API."; codeLabel.setText( codeLabelText ); codeLabel.setLayoutData( createGridDataWithSpan() ); Link link = new Link( parent, SWT.NONE ); link.setText( "See <a>example code</a>" ); link.setLayoutData( createGridDataWithSpan() ); link.addSelectionListener( new SelectionAdapter() { private final String code = getExampleCode(); @Override public void widgetSelected( final SelectionEvent event ) { String title = "ListViewer Example Code"; HtmlDialog dialog = new HtmlDialog( parent.getShell(), title, code ); dialog.setSize( 550, 400 ); dialog.open(); } } ); }
protected void createExampleControls( final Composite parent ) { parent.setLayout( new GridLayout( 2, true ) ); int style = getStyle(); list = new List( parent, style ); list.setLayoutData( new GridData( GridData.FILL_BOTH ) ); Menu menu = new Menu( list ); MenuItem menuItem = new MenuItem( menu, SWT.PUSH ); menuItem.setText( "Context menu item" ); list.setMenu( menu ); listViewer = new ListViewer( list ); listViewer.setContentProvider( new ArrayContentProvider() ); listViewer.setLabelProvider( new LabelProvider() ); listViewer.setInput( ELEMENTS ); list.addListener( SWT.DefaultSelection, new Listener() { public void handleEvent( Event event ) { String item = list.getItem( list.getSelectionIndex() ); String message = "Selected Item: " + item; MessageDialog.openInformation( getShell(), "Selection", message ); } } ); registerControl( list ); // List 2 list2 = new List( parent, style ); list2.setData( RWT.MARKUP_ENABLED, new Boolean( markup ) ); list2.add( "Item 0" ); list2.add( "Item 1" ); list2.add( "Item 2" ); if( markup ) { list2.setData( RWT.CUSTOM_ITEM_HEIGHT, new Integer( 60 ) ); list2.add( "<b>Some Markup Text</b><br/><i>This is italic</i>" ); list2.add( "A real <a href='http://eclipse.org/rap'>link</a>" ); list2.add( "This one opens <a href='http://eclipse.org/rap' target='_blank'>a new tab</a>" ); list2.add( "This is a special <a href='value_of_href' target='_rwt'>RWT Hyperlink</a>" ); list2.addListener( SWT.Selection, new Listener() { public void handleEvent( Event event ) { if( event.detail == RWT.HYPERLINK ) { log( "Clicked link \"" + event.text + "\"" ); } } } ); } else { createPopupMenu( parent.getShell(), list2 ); } list2.setLayoutData( new GridData( GridData.FILL_BOTH ) ); registerControl( list2 ); // Code int separatorStyle = SWT.SEPARATOR | SWT.HORIZONTAL | SWT.SHADOW_OUT; Label separator = new Label( parent, separatorStyle ); separator.setLayoutData( createGridDataWithSpan() ); Label codeLabel = new Label( parent, SWT.WRAP ); String codeLabelText = "Please note that the content of the left List is provided by a " + "ListViewer with JFace API."; codeLabel.setText( codeLabelText ); codeLabel.setLayoutData( createGridDataWithSpan() ); Link link = new Link( parent, SWT.NONE ); link.setText( "See <a>example code</a>" ); link.setLayoutData( createGridDataWithSpan() ); link.addSelectionListener( new SelectionAdapter() { private final String code = getExampleCode(); @Override public void widgetSelected( final SelectionEvent event ) { String title = "ListViewer Example Code"; HtmlDialog dialog = new HtmlDialog( parent.getShell(), title, code ); dialog.setSize( 550, 400 ); dialog.open(); } } ); }
diff --git a/consumer/src/main/java/org/gatein/wsrp/services/SOAPServiceFactory.java b/consumer/src/main/java/org/gatein/wsrp/services/SOAPServiceFactory.java index fbdc7689..a32f6bac 100644 --- a/consumer/src/main/java/org/gatein/wsrp/services/SOAPServiceFactory.java +++ b/consumer/src/main/java/org/gatein/wsrp/services/SOAPServiceFactory.java @@ -1,666 +1,666 @@ /* * JBoss, a division of Red Hat * Copyright 2011, Red Hat Middleware, LLC, and individual * contributors as indicated by the @authors tag. See the * copyright.txt 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.gatein.wsrp.services; import org.gatein.common.util.ParameterValidation; import org.gatein.common.util.Version; import org.gatein.wsrp.handler.RequestHeaderClientHandler; import org.gatein.wsrp.services.v1.V1MarkupService; import org.gatein.wsrp.services.v1.V1PortletManagementService; import org.gatein.wsrp.services.v1.V1RegistrationService; import org.gatein.wsrp.services.v1.V1ServiceDescriptionService; import org.gatein.wsrp.services.v2.V2MarkupService; import org.gatein.wsrp.services.v2.V2PortletManagementService; import org.gatein.wsrp.services.v2.V2RegistrationService; import org.gatein.wsrp.services.v2.V2ServiceDescriptionService; import org.gatein.wsrp.wss.WebServiceSecurityFactory; import org.oasis.wsrp.v1.WSRPV1MarkupPortType; import org.oasis.wsrp.v1.WSRPV1PortletManagementPortType; import org.oasis.wsrp.v1.WSRPV1RegistrationPortType; import org.oasis.wsrp.v1.WSRPV1ServiceDescriptionPortType; import org.oasis.wsrp.v2.WSRPV2MarkupPortType; import org.oasis.wsrp.v2.WSRPV2PortletManagementPortType; import org.oasis.wsrp.v2.WSRPV2RegistrationPortType; import org.oasis.wsrp.v2.WSRPV2ServiceDescriptionPortType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.wsdl.Definition; import javax.wsdl.Port; import javax.wsdl.WSDLException; import javax.wsdl.factory.WSDLFactory; import javax.wsdl.xml.WSDLReader; import javax.xml.namespace.QName; import javax.xml.ws.Binding; import javax.xml.ws.BindingProvider; import javax.xml.ws.Service; import javax.xml.ws.handler.Handler; import javax.xml.ws.handler.soap.SOAPHandler; import javax.xml.ws.handler.soap.SOAPMessageContext; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author <a href="mailto:[email protected]">Chris Laprun</a> * @version $Revision$ */ public class SOAPServiceFactory implements ManageableServiceFactory { /** * HTTP request timeout property. JAX-WS doesn't standardize that value, so needs to be adapted per used * implementation */ static final String JBOSS_WS_TIMEOUT = "org.jboss.ws.timeout"; static final String SUN_WS_TIMEOUT = "com.sun.xml.ws.request.timeout"; static final String IBM_WS_TIMEOUT = "com.ibm.SOAP.requestTimeout"; static final RequestHeaderClientHandler REQUEST_HEADER_CLIENT_HANDLER = new RequestHeaderClientHandler(); static final String JBOSS_WS_STUBEXT_PROPERTY_CHUNKED_ENCODING_SIZE = "http://org.jboss.ws/http#chunksize"; private static final Logger log = LoggerFactory.getLogger(SOAPServiceFactory.class); private String wsdlDefinitionURL; private boolean isV2 = false; private Service wsService; private static final String WSRP_V1_BINDING = "urn:oasis:names:tc:wsrp:v1:bind"; private static final String WSRP_V2_BINDING = "urn:oasis:names:tc:wsrp:v2:bind"; private String markupURL; private String serviceDescriptionURL; private String portletManagementURL; private String registrationURL; private boolean failed; private boolean available; private int msBeforeTimeOut = DEFAULT_TIMEOUT_MS; private boolean wssEnabled; private void setTimeout(Map<String, Object> requestContext) { int timeout = getWSOperationTimeOut(); requestContext.put(JBOSS_WS_TIMEOUT, timeout); requestContext.put(SUN_WS_TIMEOUT, timeout); requestContext.put(IBM_WS_TIMEOUT, timeout); } private <T> T customizePort(Class<T> expectedServiceInterface, Object service, String portAddress) { BindingProvider bindingProvider = (BindingProvider)service; Map<String, Object> requestContext = bindingProvider.getRequestContext(); // set timeout setTimeout(requestContext); // set port address requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portAddress); // Set org.jboss.ws.core.StubExt.PROPERTY_CHUNKED_ENCODING_SIZE to 0 to deactive chunked encoding for // better interoperability as Oracle's producer doesn't support it, for example. // See https://jira.jboss.org/jira/browse/JBWS-2884 and // http://community.jboss.org/wiki/JBossWS-NativeUserGuide#Chunked_encoding_setup requestContext.put(JBOSS_WS_STUBEXT_PROPERTY_CHUNKED_ENCODING_SIZE, "0"); // Add client side handler via JAX-WS API Binding binding = bindingProvider.getBinding(); List<Handler> handlerChain = binding.getHandlerChain(); if (handlerChain != null) { //We need to make sure the WSS handlers are added before the REQUEST_HEADER_CLIENT_HANDLER otherwise the session information is lost addWSSHandlers(handlerChain); // if we already have a handler chain, just add the request hearder handler if it's not already in there if (!handlerChain.contains(REQUEST_HEADER_CLIENT_HANDLER)) { handlerChain.add(REQUEST_HEADER_CLIENT_HANDLER); } } else { // otherwise, create a handler chain and add our handler to it handlerChain = new ArrayList<Handler>(1); //We need to make sure the WSS handlers are added before the REQUEST_HEADER_CLIENT_HANDLER otherwise the session information is lost addWSSHandlers(handlerChain); handlerChain.add(REQUEST_HEADER_CLIENT_HANDLER); } binding.setHandlerChain(handlerChain); return expectedServiceInterface.cast(service); } public <T> T getService(Class<T> clazz) throws Exception { // todo: clean up! if (log.isDebugEnabled()) { log.debug("Getting service for class " + clazz); } refresh(false); Object service = null; try { service = wsService.getPort(clazz); } catch (Exception e) { log.debug("No port available for " + clazz, e); } // String portAddress = null; boolean isMandatoryInterface = false; if (WSRPV2ServiceDescriptionPortType.class.isAssignableFrom(clazz) || WSRPV1ServiceDescriptionPortType.class.isAssignableFrom(clazz)) { portAddress = serviceDescriptionURL; isMandatoryInterface = true; } else if (WSRPV2MarkupPortType.class.isAssignableFrom(clazz) || WSRPV1MarkupPortType.class.isAssignableFrom(clazz)) { portAddress = markupURL; isMandatoryInterface = true; } else if (WSRPV2RegistrationPortType.class.isAssignableFrom(clazz) || WSRPV1RegistrationPortType.class.isAssignableFrom(clazz)) { portAddress = registrationURL; } else if (WSRPV2PortletManagementPortType.class.isAssignableFrom(clazz) || WSRPV1PortletManagementPortType.class.isAssignableFrom(clazz)) { portAddress = portletManagementURL; } // Get the stub from the service, remember that the stub itself is not threadsafe // and must be customized for every request to this method. if (service != null) { if (portAddress != null) { if (log.isDebugEnabled()) { log.debug("Setting the end point to: " + portAddress); } T result = customizePort(clazz, service, portAddress); // if we managed to retrieve a service, we're probably available setFailed(false); setAvailable(true); return result; } else { if (isMandatoryInterface) { setFailed(true); throw new IllegalStateException("Mandatory interface URLs were not properly initialized: no proper service URL for " + clazz.getName()); } else { throw new IllegalStateException("No URL was provided for optional interface " + clazz.getName()); } } } else { return null; } } public boolean isAvailable() { return available; } public boolean isFailed() { return failed; } public void stop() { // todo: implement as needed } public void setFailed(boolean failed) { this.failed = failed; } public void setAvailable(boolean available) { this.available = available; } public void setWSOperationTimeOut(int msBeforeTimeOut) { if (msBeforeTimeOut < 0) { msBeforeTimeOut = DEFAULT_TIMEOUT_MS; } this.msBeforeTimeOut = msBeforeTimeOut; } public int getWSOperationTimeOut() { return msBeforeTimeOut; } public String getWsdlDefinitionURL() { return wsdlDefinitionURL; } public void setWsdlDefinitionURL(String wsdlDefinitionURL) { this.wsdlDefinitionURL = wsdlDefinitionURL; // we need a refresh so mark as not available but not failed setAvailable(false); setFailed(false); } public void start() throws Exception { try { ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(wsdlDefinitionURL, "WSDL URL", "SOAPServiceFactory"); URL wsdlURL = new URI(wsdlDefinitionURL).toURL(); WSDLInfo wsdlInfo = new WSDLInfo(wsdlDefinitionURL); // try to get v2 of service if possible, first QName wsrp2 = wsdlInfo.getWSRP2ServiceQName(); QName wsrp1 = wsdlInfo.getWSRP1ServiceQName(); if (wsrp2 != null) { wsService = Service.create(wsdlURL, wsrp2); Class portTypeClass = null; try { portTypeClass = WSRPV2MarkupPortType.class; WSRPV2MarkupPortType markupPortType = wsService.getPort(WSRPV2MarkupPortType.class); markupURL = (String)((BindingProvider)markupPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); portTypeClass = WSRPV2ServiceDescriptionPortType.class; WSRPV2ServiceDescriptionPortType sdPort = wsService.getPort(WSRPV2ServiceDescriptionPortType.class); serviceDescriptionURL = (String)((BindingProvider)sdPort).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { setFailed(true); throw new IllegalArgumentException("Mandatory WSRP 2 port " + portTypeClass.getName() + " was not found for WSDL at " + wsdlDefinitionURL, e); } try { WSRPV2PortletManagementPortType managementPortType = wsService.getPort(WSRPV2PortletManagementPortType.class); portletManagementURL = (String)((BindingProvider)managementPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { log.debug("PortletManagement port was not available for WSDL at " + wsdlDefinitionURL, e); portletManagementURL = null; } try { WSRPV2RegistrationPortType registrationPortType = wsService.getPort(WSRPV2RegistrationPortType.class); registrationURL = (String)((BindingProvider)registrationPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { log.debug("Registration port was not available for WSDL at " + wsdlDefinitionURL, e); registrationURL = null; } setFailed(false); setAvailable(true); isV2 = true; } else if (wsrp1 != null) { wsService = Service.create(wsdlURL, wsrp1); Class portTypeClass = null; try { portTypeClass = WSRPV1MarkupPortType.class; WSRPV1MarkupPortType markupPortType = wsService.getPort(WSRPV1MarkupPortType.class); markupURL = (String)((BindingProvider)markupPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); portTypeClass = WSRPV1ServiceDescriptionPortType.class; WSRPV1ServiceDescriptionPortType sdPort = wsService.getPort(WSRPV1ServiceDescriptionPortType.class); serviceDescriptionURL = (String)((BindingProvider)sdPort).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { setFailed(true); throw new IllegalArgumentException("Mandatory WSRP 1 port " + portTypeClass.getName() + " was not found for WSDL at " + wsdlDefinitionURL, e); } try { WSRPV1PortletManagementPortType managementPortType = wsService.getPort(WSRPV1PortletManagementPortType.class); portletManagementURL = (String)((BindingProvider)managementPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { - log.debug("PortletManagement port was not available for WSDL at: " + wsdlDefinitionURL, e); + log.debug("PortletManagement port was not available for WSDL at " + wsdlDefinitionURL, e); portletManagementURL = null; } try { WSRPV1RegistrationPortType registrationPortType = wsService.getPort(WSRPV1RegistrationPortType.class); registrationURL = (String)((BindingProvider)registrationPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { - log.debug("Registration port was not available for WSDL at: " + wsdlDefinitionURL, e); + log.debug("Registration port was not available for WSDL at " + wsdlDefinitionURL, e); registrationURL = null; } setFailed(false); setAvailable(true); isV2 = false; } else { throw new IllegalArgumentException("Couldn't find any WSRP service in specified WSDL: " + wsdlDefinitionURL); } } catch (MalformedURLException e) { setFailed(true); throw new IllegalArgumentException(wsdlDefinitionURL + " is not a well-formed URL specifying where to find the WSRP services definition.", e); } catch (Exception e) { - log.info("Couldn't access WSDL information at" + wsdlDefinitionURL + ". Service won't be available", e); + log.info("Couldn't access WSDL information at " + wsdlDefinitionURL + ". Service won't be available", e); setAvailable(false); setFailed(true); throw e; } } public ServiceDescriptionService getServiceDescriptionService() throws Exception { if (isV2) { WSRPV2ServiceDescriptionPortType port = getService(WSRPV2ServiceDescriptionPortType.class); return new V2ServiceDescriptionService(port); } else { WSRPV1ServiceDescriptionPortType port = getService(WSRPV1ServiceDescriptionPortType.class); return new V1ServiceDescriptionService(port); } } public MarkupService getMarkupService() throws Exception { if (isV2) { WSRPV2MarkupPortType port = getService(WSRPV2MarkupPortType.class); return new V2MarkupService(port); } else { WSRPV1MarkupPortType port = getService(WSRPV1MarkupPortType.class); return new V1MarkupService(port); } } public PortletManagementService getPortletManagementService() throws Exception { if (isV2) { WSRPV2PortletManagementPortType port = getService(WSRPV2PortletManagementPortType.class); return new V2PortletManagementService(port); } else { WSRPV1PortletManagementPortType port = getService(WSRPV1PortletManagementPortType.class); return new V1PortletManagementService(port); } } public RegistrationService getRegistrationService() throws Exception { if (isV2) { WSRPV2RegistrationPortType port = getService(WSRPV2RegistrationPortType.class); return new V2RegistrationService(port); } else { WSRPV1RegistrationPortType port = getService(WSRPV1RegistrationPortType.class); return new V1RegistrationService(port); } } public Version getWSRPVersion() { if (isAvailable()) { if (isV2) { return WSRP2; } else { return WSRP1; } } else { return null; } } public boolean refresh(boolean force) throws Exception { // if we need a refresh, reload information from WSDL if (force || (!isAvailable() && !isFailed())) { start(); return true; } return false; } public void enableWSS(boolean enable) { this.wssEnabled = enable; } public boolean isWSSEnabled() { return this.wssEnabled; } public boolean isWSSAvailable() { WebServiceSecurityFactory wssFactory = WebServiceSecurityFactory.getInstance(); if (wssFactory != null && wssFactory.getHandlers() != null && !wssFactory.getHandlers().isEmpty()) { return true; } else { return false; } } protected void addWSSHandlers(List<Handler> handlerChain) { if (wssEnabled) { WebServiceSecurityFactory wssFactory = WebServiceSecurityFactory.getInstance(); if (wssFactory.getHandlers() != null) { for (SOAPHandler<SOAPMessageContext> wssHandler : wssFactory.getHandlers()) { if (!handlerChain.contains(wssHandler)) { handlerChain.add(wssHandler); } } } else { log.debug("WSS enabled, but no handlers provided. WSS will not be able to work properly."); } } else { log.debug("WSS disabled."); } } protected static class WSDLInfo { private final QName wsrp2ServiceQName; private final QName wsrp1ServiceQName; private final static WSDLFactory wsdlFactory; static { try { wsdlFactory = WSDLFactory.newInstance(); } catch (WSDLException e) { throw new RuntimeException(e); } } public WSDLInfo(String wsdlURL) throws WSDLException { WSDLReader wsdlReader = wsdlFactory.newWSDLReader(); wsdlReader.setFeature("javax.wsdl.verbose", false); wsdlReader.setFeature("javax.wsdl.importDocuments", false); Definition definition = wsdlReader.readWSDL(wsdlURL); Map<QName, javax.wsdl.Service> services = definition.getServices(); int serviceNb = services.size(); if (serviceNb > 2) { throw new WSDLException(WSDLException.OTHER_ERROR, "The specified WSDL contains more than 2 services definitions when we expected at most 2: one for WSRP 1 and one for WSRP 2."); } QName wsrp1 = null, wsrp2 = null; String ns = definition.getTargetNamespace(); for (QName name : services.keySet()) { javax.wsdl.Service service = services.get(name); // if the namespace is using one of the WSRP-defined ones, we have a potential candidate // but we need to check that the port namespaces to really know which version of the service we've found // this is needed for http://www.netunitysoftware.com/wsrp2interop/WsrpProducer.asmx?Operation=WSDL&WsrpVersion=All // where the WSRP1 service name has the WSRP2 global target namespace so we need more processing :( Map<String, Port> ports = service.getPorts(); String bindingNSURI = null; for (Port port : ports.values()) { QName bindingName = port.getBinding().getQName(); String newBindingNS = bindingName.getNamespaceURI(); if (WSRP_V1_BINDING.equals(newBindingNS) || WSRP_V2_BINDING.equals(newBindingNS)) { if (bindingNSURI != null && !bindingNSURI.equals(newBindingNS)) { throw new WSDLException(WSDLException.OTHER_ERROR, "Inconsistent NS in port bindings. Aborting."); } bindingNSURI = newBindingNS; } else { log.debug("Unknown binding namespace: " + newBindingNS + ". Ignoring binding: " + bindingName); } } if (WSRP_V1_BINDING.equals(bindingNSURI)) { wsrp1 = checkPotentialServiceName(wsrp1, name, ns); } else if (WSRP_V2_BINDING.equals(bindingNSURI)) { wsrp2 = checkPotentialServiceName(wsrp2, name, ns); } } wsrp2ServiceQName = wsrp2; wsrp1ServiceQName = wsrp1; if (wsrp1 == null && wsrp2 == null) { throw new WSDLException(WSDLException.INVALID_WSDL, "Found no service definition with WSRP specification namespaces."); } } public QName getWSRP2ServiceQName() { return wsrp2ServiceQName; } public QName getWSRP1ServiceQName() { return wsrp1ServiceQName; } private QName checkPotentialServiceName(QName potentiallyExisting, QName candidate, String namespace) throws WSDLException { if (potentiallyExisting != null) { throw new WSDLException(WSDLException.OTHER_ERROR, "Found 2 different services using the " + namespace + " namespace. Cannot decide which one to use for service so aborting."); } return candidate; } } }
false
true
public void start() throws Exception { try { ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(wsdlDefinitionURL, "WSDL URL", "SOAPServiceFactory"); URL wsdlURL = new URI(wsdlDefinitionURL).toURL(); WSDLInfo wsdlInfo = new WSDLInfo(wsdlDefinitionURL); // try to get v2 of service if possible, first QName wsrp2 = wsdlInfo.getWSRP2ServiceQName(); QName wsrp1 = wsdlInfo.getWSRP1ServiceQName(); if (wsrp2 != null) { wsService = Service.create(wsdlURL, wsrp2); Class portTypeClass = null; try { portTypeClass = WSRPV2MarkupPortType.class; WSRPV2MarkupPortType markupPortType = wsService.getPort(WSRPV2MarkupPortType.class); markupURL = (String)((BindingProvider)markupPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); portTypeClass = WSRPV2ServiceDescriptionPortType.class; WSRPV2ServiceDescriptionPortType sdPort = wsService.getPort(WSRPV2ServiceDescriptionPortType.class); serviceDescriptionURL = (String)((BindingProvider)sdPort).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { setFailed(true); throw new IllegalArgumentException("Mandatory WSRP 2 port " + portTypeClass.getName() + " was not found for WSDL at " + wsdlDefinitionURL, e); } try { WSRPV2PortletManagementPortType managementPortType = wsService.getPort(WSRPV2PortletManagementPortType.class); portletManagementURL = (String)((BindingProvider)managementPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { log.debug("PortletManagement port was not available for WSDL at " + wsdlDefinitionURL, e); portletManagementURL = null; } try { WSRPV2RegistrationPortType registrationPortType = wsService.getPort(WSRPV2RegistrationPortType.class); registrationURL = (String)((BindingProvider)registrationPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { log.debug("Registration port was not available for WSDL at " + wsdlDefinitionURL, e); registrationURL = null; } setFailed(false); setAvailable(true); isV2 = true; } else if (wsrp1 != null) { wsService = Service.create(wsdlURL, wsrp1); Class portTypeClass = null; try { portTypeClass = WSRPV1MarkupPortType.class; WSRPV1MarkupPortType markupPortType = wsService.getPort(WSRPV1MarkupPortType.class); markupURL = (String)((BindingProvider)markupPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); portTypeClass = WSRPV1ServiceDescriptionPortType.class; WSRPV1ServiceDescriptionPortType sdPort = wsService.getPort(WSRPV1ServiceDescriptionPortType.class); serviceDescriptionURL = (String)((BindingProvider)sdPort).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { setFailed(true); throw new IllegalArgumentException("Mandatory WSRP 1 port " + portTypeClass.getName() + " was not found for WSDL at " + wsdlDefinitionURL, e); } try { WSRPV1PortletManagementPortType managementPortType = wsService.getPort(WSRPV1PortletManagementPortType.class); portletManagementURL = (String)((BindingProvider)managementPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { log.debug("PortletManagement port was not available for WSDL at: " + wsdlDefinitionURL, e); portletManagementURL = null; } try { WSRPV1RegistrationPortType registrationPortType = wsService.getPort(WSRPV1RegistrationPortType.class); registrationURL = (String)((BindingProvider)registrationPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { log.debug("Registration port was not available for WSDL at: " + wsdlDefinitionURL, e); registrationURL = null; } setFailed(false); setAvailable(true); isV2 = false; } else { throw new IllegalArgumentException("Couldn't find any WSRP service in specified WSDL: " + wsdlDefinitionURL); } } catch (MalformedURLException e) { setFailed(true); throw new IllegalArgumentException(wsdlDefinitionURL + " is not a well-formed URL specifying where to find the WSRP services definition.", e); } catch (Exception e) { log.info("Couldn't access WSDL information at" + wsdlDefinitionURL + ". Service won't be available", e); setAvailable(false); setFailed(true); throw e; } }
public void start() throws Exception { try { ParameterValidation.throwIllegalArgExceptionIfNullOrEmpty(wsdlDefinitionURL, "WSDL URL", "SOAPServiceFactory"); URL wsdlURL = new URI(wsdlDefinitionURL).toURL(); WSDLInfo wsdlInfo = new WSDLInfo(wsdlDefinitionURL); // try to get v2 of service if possible, first QName wsrp2 = wsdlInfo.getWSRP2ServiceQName(); QName wsrp1 = wsdlInfo.getWSRP1ServiceQName(); if (wsrp2 != null) { wsService = Service.create(wsdlURL, wsrp2); Class portTypeClass = null; try { portTypeClass = WSRPV2MarkupPortType.class; WSRPV2MarkupPortType markupPortType = wsService.getPort(WSRPV2MarkupPortType.class); markupURL = (String)((BindingProvider)markupPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); portTypeClass = WSRPV2ServiceDescriptionPortType.class; WSRPV2ServiceDescriptionPortType sdPort = wsService.getPort(WSRPV2ServiceDescriptionPortType.class); serviceDescriptionURL = (String)((BindingProvider)sdPort).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { setFailed(true); throw new IllegalArgumentException("Mandatory WSRP 2 port " + portTypeClass.getName() + " was not found for WSDL at " + wsdlDefinitionURL, e); } try { WSRPV2PortletManagementPortType managementPortType = wsService.getPort(WSRPV2PortletManagementPortType.class); portletManagementURL = (String)((BindingProvider)managementPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { log.debug("PortletManagement port was not available for WSDL at " + wsdlDefinitionURL, e); portletManagementURL = null; } try { WSRPV2RegistrationPortType registrationPortType = wsService.getPort(WSRPV2RegistrationPortType.class); registrationURL = (String)((BindingProvider)registrationPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { log.debug("Registration port was not available for WSDL at " + wsdlDefinitionURL, e); registrationURL = null; } setFailed(false); setAvailable(true); isV2 = true; } else if (wsrp1 != null) { wsService = Service.create(wsdlURL, wsrp1); Class portTypeClass = null; try { portTypeClass = WSRPV1MarkupPortType.class; WSRPV1MarkupPortType markupPortType = wsService.getPort(WSRPV1MarkupPortType.class); markupURL = (String)((BindingProvider)markupPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); portTypeClass = WSRPV1ServiceDescriptionPortType.class; WSRPV1ServiceDescriptionPortType sdPort = wsService.getPort(WSRPV1ServiceDescriptionPortType.class); serviceDescriptionURL = (String)((BindingProvider)sdPort).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { setFailed(true); throw new IllegalArgumentException("Mandatory WSRP 1 port " + portTypeClass.getName() + " was not found for WSDL at " + wsdlDefinitionURL, e); } try { WSRPV1PortletManagementPortType managementPortType = wsService.getPort(WSRPV1PortletManagementPortType.class); portletManagementURL = (String)((BindingProvider)managementPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { log.debug("PortletManagement port was not available for WSDL at " + wsdlDefinitionURL, e); portletManagementURL = null; } try { WSRPV1RegistrationPortType registrationPortType = wsService.getPort(WSRPV1RegistrationPortType.class); registrationURL = (String)((BindingProvider)registrationPortType).getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY); } catch (Exception e) { log.debug("Registration port was not available for WSDL at " + wsdlDefinitionURL, e); registrationURL = null; } setFailed(false); setAvailable(true); isV2 = false; } else { throw new IllegalArgumentException("Couldn't find any WSRP service in specified WSDL: " + wsdlDefinitionURL); } } catch (MalformedURLException e) { setFailed(true); throw new IllegalArgumentException(wsdlDefinitionURL + " is not a well-formed URL specifying where to find the WSRP services definition.", e); } catch (Exception e) { log.info("Couldn't access WSDL information at " + wsdlDefinitionURL + ". Service won't be available", e); setAvailable(false); setFailed(true); throw e; } }
diff --git a/opengl/tools/glgen/src/JniCodeEmitter.java b/opengl/tools/glgen/src/JniCodeEmitter.java index b0997b15..73403575 100644 --- a/opengl/tools/glgen/src/JniCodeEmitter.java +++ b/opengl/tools/glgen/src/JniCodeEmitter.java @@ -1,1042 +1,1036 @@ import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; public class JniCodeEmitter { static final boolean mUseCPlusPlus = true; protected boolean mUseContextPointer = true; protected boolean mUseStaticMethods = false; protected String mClassPathName; protected ParameterChecker mChecker; protected List<String> nativeRegistrations = new ArrayList<String>(); boolean needsExit; protected static String indent = " "; HashSet<String> mFunctionsEmitted = new HashSet<String>(); public static String getJniName(JType jType) { String jniName = ""; if (jType.isClass()) { return "L" + jType.getBaseType() + ";"; } else if (jType.isArray()) { jniName = "["; } String baseType = jType.getBaseType(); if (baseType.equals("int")) { jniName += "I"; } else if (baseType.equals("float")) { jniName += "F"; } else if (baseType.equals("boolean")) { jniName += "Z"; } else if (baseType.equals("short")) { jniName += "S"; } else if (baseType.equals("long")) { jniName += "L"; } else if (baseType.equals("byte")) { jniName += "B"; } return jniName; } public void emitCode(CFunc cfunc, String original, PrintStream javaInterfaceStream, PrintStream javaImplStream, PrintStream cStream) { JFunc jfunc; String signature; boolean duplicate; if (cfunc.hasTypedPointerArg()) { jfunc = JFunc.convert(cfunc, true); // Don't emit duplicate functions // These may appear because they are defined in multiple // Java interfaces (e.g., GL11/GL11ExtensionPack) signature = jfunc.toString(); duplicate = false; if (mFunctionsEmitted.contains(signature)) { duplicate = true; } else { mFunctionsEmitted.add(signature); } if (!duplicate) { emitNativeDeclaration(jfunc, javaImplStream); emitJavaCode(jfunc, javaImplStream); } if (javaInterfaceStream != null) { emitJavaInterfaceCode(jfunc, javaInterfaceStream); } if (!duplicate) { emitJniCode(jfunc, cStream); } } jfunc = JFunc.convert(cfunc, false); signature = jfunc.toString(); duplicate = false; if (mFunctionsEmitted.contains(signature)) { duplicate = true; } else { mFunctionsEmitted.add(signature); } if (!duplicate) { emitNativeDeclaration(jfunc, javaImplStream); } if (javaInterfaceStream != null) { emitJavaInterfaceCode(jfunc, javaInterfaceStream); } if (!duplicate) { emitJavaCode(jfunc, javaImplStream); emitJniCode(jfunc, cStream); } } public void emitNativeDeclaration(JFunc jfunc, PrintStream out) { out.println(" // C function " + jfunc.getCFunc().getOriginal()); out.println(); emitFunction(jfunc, out, true, false); } public void emitJavaInterfaceCode(JFunc jfunc, PrintStream out) { emitFunction(jfunc, out, false, true); } public void emitJavaCode(JFunc jfunc, PrintStream out) { emitFunction(jfunc, out, false, false); } void emitFunctionCall(JFunc jfunc, PrintStream out, String iii, boolean grabArray) { boolean isVoid = jfunc.getType().isVoid(); boolean isPointerFunc = jfunc.getName().endsWith("Pointer") && jfunc.getCFunc().hasPointerArg(); if (!isVoid) { out.println(iii + jfunc.getType() + " _returnValue;"); } out.println(iii + (isVoid ? "" : "_returnValue = ") + jfunc.getName() + (isPointerFunc ? "Bounds" : "" ) + "("); int numArgs = jfunc.getNumArgs(); for (int i = 0; i < numArgs; i++) { String argName = jfunc.getArgName(i); JType argType = jfunc.getArgType(i); if (grabArray && argType.isTypedBuffer()) { String typeName = argType.getBaseType(); typeName = typeName.substring(9, typeName.length() - 6); out.println(iii + indent + "get" + typeName + "Array(" + argName + "),"); out.print(iii + indent + "getOffset(" + argName + ")"); } else { out.print(iii + indent + argName); } if (i == numArgs - 1) { if (isPointerFunc) { out.println(","); out.println(iii + indent + argName + ".remaining()"); } else { out.println(); } } else { out.println(","); } } out.println(iii + ");"); } void printIfcheckPostamble(PrintStream out, boolean isBuffer, boolean emitExceptionCheck, String iii) { printIfcheckPostamble(out, isBuffer, emitExceptionCheck, "offset", "_remaining", iii); } void printIfcheckPostamble(PrintStream out, boolean isBuffer, boolean emitExceptionCheck, String offset, String remaining, String iii) { out.println(iii + " default:"); out.println(iii + " _needed = 0;"); out.println(iii + " break;"); out.println(iii + "}"); out.println(iii + "if (" + remaining + " < _needed) {"); if (emitExceptionCheck) { out.println(iii + indent + "_exception = 1;"); } out.println(iii + indent + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ThrowNew(" + (mUseCPlusPlus ? "" : "_env, ") + "IAEClass, " + "\"" + (isBuffer ? "remaining()" : "length - " + offset) + " < needed\");"); out.println(iii + indent + "goto exit;"); needsExit = true; out.println(iii + "}"); } boolean isNullAllowed(CFunc cfunc) { String[] checks = mChecker.getChecks(cfunc.getName()); int index = 1; if (checks != null) { while (index < checks.length) { if (checks[index].equals("return")) { index += 2; } else if (checks[index].startsWith("check")) { index += 3; } else if (checks[index].equals("ifcheck")) { index += 5; } else if (checks[index].equals("unsupported")) { index += 1; } else if (checks[index].equals("nullAllowed")) { return true; } else { System.out.println("Error: unknown keyword \"" + checks[index] + "\""); System.exit(0); } } } return false; } String getErrorReturnValue(CFunc cfunc) { CType returnType = cfunc.getType(); boolean isVoid = returnType.isVoid(); if (isVoid) { return null; } String[] checks = mChecker.getChecks(cfunc.getName()); int index = 1; if (checks != null) { while (index < checks.length) { if (checks[index].equals("return")) { return checks[index + 1]; } else if (checks[index].startsWith("check")) { index += 3; } else if (checks[index].equals("ifcheck")) { index += 5; } else if (checks[index].equals("unsupported")) { index += 1; } else if (checks[index].equals("nullAllowed")) { index += 1; } else { System.out.println("Error: unknown keyword \"" + checks[index] + "\""); System.exit(0); } } } return null; } boolean isUnsupportedFunc(CFunc cfunc) { String[] checks = mChecker.getChecks(cfunc.getName()); int index = 1; if (checks != null) { while (index < checks.length) { if (checks[index].equals("unsupported")) { return true; } else if (checks[index].equals("return")) { index += 2; } else if (checks[index].startsWith("check")) { index += 3; } else if (checks[index].equals("ifcheck")) { index += 5; } else if (checks[index].equals("nullAllowed")) { index += 1; } else { System.out.println("Error: unknown keyword \"" + checks[index] + "\""); System.exit(0); } } } return false; } void emitNativeBoundsChecks(CFunc cfunc, String cname, PrintStream out, boolean isBuffer, boolean emitExceptionCheck, String offset, String remaining, String iii) { String[] checks = mChecker.getChecks(cfunc.getName()); boolean lastWasIfcheck = false; int index = 1; if (checks != null) { while (index < checks.length) { if (checks[index].startsWith("check")) { if (lastWasIfcheck) { printIfcheckPostamble(out, isBuffer, emitExceptionCheck, offset, remaining, iii); } lastWasIfcheck = false; if (cname != null && !cname.equals(checks[index + 1])) { index += 3; continue; } out.println(iii + "if (" + remaining + " < " + checks[index + 2] + ") {"); if (emitExceptionCheck) { out.println(iii + indent + "_exception = 1;"); } String exceptionClassName = "IAEClass"; // If the "check" keyword was of the form // "check_<class name>", use the class name in the // exception to be thrown int underscore = checks[index].indexOf('_'); if (underscore >= 0) { exceptionClassName = checks[index].substring(underscore + 1) + "Class"; } out.println(iii + indent + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ThrowNew(" + (mUseCPlusPlus ? "" : "_env, ") + exceptionClassName + ", " + "\"" + (isBuffer ? "remaining()" : "length - " + offset) + " < " + checks[index + 2] + "\");"); out.println(iii + indent + "goto exit;"); needsExit = true; out.println(iii + "}"); index += 3; } else if (checks[index].equals("ifcheck")) { String[] matches = checks[index + 4].split(","); if (!lastWasIfcheck) { out.println(iii + "int _needed;"); out.println(iii + "switch (" + checks[index + 3] + ") {"); } for (int i = 0; i < matches.length; i++) { out.println("#if defined(" + matches[i] + ")"); out.println(iii + " case " + matches[i] + ":"); out.println("#endif // defined(" + matches[i] + ")"); } out.println(iii + " _needed = " + checks[index + 2] + ";"); out.println(iii + " break;"); lastWasIfcheck = true; index += 5; } else if (checks[index].equals("return")) { // ignore index += 2; } else if (checks[index].equals("unsupported")) { // ignore index += 1; } else if (checks[index].equals("nullAllowed")) { // ignore index += 1; } else { System.out.println("Error: unknown keyword \"" + checks[index] + "\""); System.exit(0); } } } if (lastWasIfcheck) { printIfcheckPostamble(out, isBuffer, emitExceptionCheck, iii); } } boolean hasNonConstArg(JFunc jfunc, CFunc cfunc, List<Integer> nonPrimitiveArgs) { if (nonPrimitiveArgs.size() > 0) { for (int i = nonPrimitiveArgs.size() - 1; i >= 0; i--) { int idx = nonPrimitiveArgs.get(i).intValue(); int cIndex = jfunc.getArgCIndex(idx); if (jfunc.getArgType(idx).isArray()) { if (!cfunc.getArgType(cIndex).isConst()) { return true; } } else if (jfunc.getArgType(idx).isBuffer()) { if (!cfunc.getArgType(cIndex).isConst()) { return true; } } } } return false; } /** * Emit a function in several variants: * * if nativeDecl: public native <returntype> func(args); * * if !nativeDecl: * if interfaceDecl: public <returntype> func(args); * if !interfaceDecl: public <returntype> func(args) { body } */ void emitFunction(JFunc jfunc, PrintStream out, boolean nativeDecl, boolean interfaceDecl) { boolean isPointerFunc = jfunc.getName().endsWith("Pointer") && jfunc.getCFunc().hasPointerArg(); if (!nativeDecl && !interfaceDecl && !isPointerFunc) { // If it's not a pointer function, we've already emitted it // with nativeDecl == true return; } String maybeStatic = mUseStaticMethods ? "static " : ""; if (isPointerFunc) { out.println(indent + (nativeDecl ? "private " + maybeStatic +"native " : (interfaceDecl ? "" : "public ") + maybeStatic) + jfunc.getType() + " " + jfunc.getName() + (nativeDecl ? "Bounds" : "") + "("); } else { out.println(indent + (nativeDecl ? "public " + maybeStatic +"native " : (interfaceDecl ? "" : "public ") + maybeStatic) + jfunc.getType() + " " + jfunc.getName() + "("); } int numArgs = jfunc.getNumArgs(); for (int i = 0; i < numArgs; i++) { String argName = jfunc.getArgName(i); JType argType = jfunc.getArgType(i); out.print(indent + indent + argType + " " + argName); if (i == numArgs - 1) { if (isPointerFunc && nativeDecl) { out.println(","); out.println(indent + indent + "int remaining"); } else { out.println(); } } else { out.println(","); } } if (nativeDecl || interfaceDecl) { out.println(indent + ");"); } else { out.println(indent + ") {"); String iii = indent + indent; // emitBoundsChecks(jfunc, out, iii); emitFunctionCall(jfunc, out, iii, false); // Set the pointer after we call the native code, so that if // the native code throws an exception we don't modify the // pointer. We assume that the native code is written so that // if an exception is thrown, then the underlying glXXXPointer // function will not have been called. String fname = jfunc.getName(); if (isPointerFunc) { // TODO - deal with VBO variants if (fname.equals("glColorPointer")) { out.println(iii + "if ((size == 4) &&"); out.println(iii + " ((type == GL_FLOAT) ||"); out.println(iii + " (type == GL_UNSIGNED_BYTE) ||"); out.println(iii + " (type == GL_FIXED)) &&"); out.println(iii + " (stride >= 0)) {"); out.println(iii + indent + "_colorPointer = pointer;"); out.println(iii + "}"); } else if (fname.equals("glNormalPointer")) { out.println(iii + "if (((type == GL_FLOAT) ||"); out.println(iii + " (type == GL_BYTE) ||"); out.println(iii + " (type == GL_SHORT) ||"); out.println(iii + " (type == GL_FIXED)) &&"); out.println(iii + " (stride >= 0)) {"); out.println(iii + indent + "_normalPointer = pointer;"); out.println(iii + "}"); } else if (fname.equals("glTexCoordPointer")) { out.println(iii + "if (((size == 2) ||"); out.println(iii + " (size == 3) ||"); out.println(iii + " (size == 4)) &&"); out.println(iii + " ((type == GL_FLOAT) ||"); out.println(iii + " (type == GL_BYTE) ||"); out.println(iii + " (type == GL_SHORT) ||"); out.println(iii + " (type == GL_FIXED)) &&"); out.println(iii + " (stride >= 0)) {"); out.println(iii + indent + "_texCoordPointer = pointer;"); out.println(iii + "}"); } else if (fname.equals("glVertexPointer")) { out.println(iii + "if (((size == 2) ||"); out.println(iii + " (size == 3) ||"); out.println(iii + " (size == 4)) &&"); out.println(iii + " ((type == GL_FLOAT) ||"); out.println(iii + " (type == GL_BYTE) ||"); out.println(iii + " (type == GL_SHORT) ||"); out.println(iii + " (type == GL_FIXED)) &&"); out.println(iii + " (stride >= 0)) {"); out.println(iii + indent + "_vertexPointer = pointer;"); out.println(iii + "}"); } } boolean isVoid = jfunc.getType().isVoid(); if (!isVoid) { out.println(indent + indent + "return _returnValue;"); } out.println(indent + "}"); } out.println(); } public void addNativeRegistration(String s) { nativeRegistrations.add(s); } public void emitNativeRegistration(String registrationFunctionName, PrintStream cStream) { cStream.println("static const char *classPathName = \"" + mClassPathName + "\";"); cStream.println(); cStream.println("static JNINativeMethod methods[] = {"); cStream.println("{\"_nativeClassInit\", \"()V\", (void*)nativeClassInit },"); Iterator<String> i = nativeRegistrations.iterator(); while (i.hasNext()) { cStream.println(i.next()); } cStream.println("};"); cStream.println(); cStream.println("int " + registrationFunctionName + "(JNIEnv *_env)"); cStream.println("{"); cStream.println(indent + "int err;"); cStream.println(indent + "err = android::AndroidRuntime::registerNativeMethods(_env, classPathName, methods, NELEM(methods));"); cStream.println(indent + "return err;"); cStream.println("}"); } public JniCodeEmitter() { super(); } String getJniType(JType jType) { if (jType.isVoid()) { return "void"; } String baseType = jType.getBaseType(); if (jType.isPrimitive()) { if (baseType.equals("String")) { return "jstring"; } else { return "j" + baseType; } } else if (jType.isArray()) { return "j" + baseType + "Array"; } else { return "jobject"; } } String getJniMangledName(String name) { name = name.replaceAll("_", "_1"); name = name.replaceAll(";", "_2"); name = name.replaceAll("\\[", "_3"); return name; } public void emitJniCode(JFunc jfunc, PrintStream out) { CFunc cfunc = jfunc.getCFunc(); // Emit comment identifying original C function // // Example: // // /* void glClipPlanef ( GLenum plane, const GLfloat *equation ) */ // out.println("/* " + cfunc.getOriginal() + " */"); // Emit JNI signature (name) // // Example: // // void // android_glClipPlanef__I_3FI // String outName = "android_" + jfunc.getName(); boolean isPointerFunc = outName.endsWith("Pointer") && jfunc.getCFunc().hasPointerArg(); boolean isVBOPointerFunc = (outName.endsWith("Pointer") || outName.endsWith("DrawElements")) && !jfunc.getCFunc().hasPointerArg(); if (isPointerFunc) { outName += "Bounds"; } out.print("static "); out.println(getJniType(jfunc.getType())); out.print(outName); String rsignature = getJniName(jfunc.getType()); String signature = ""; int numArgs = jfunc.getNumArgs(); for (int i = 0; i < numArgs; i++) { JType argType = jfunc.getArgType(i); signature += getJniName(argType); } if (isPointerFunc) { signature += "I"; } // Append signature to function name String sig = getJniMangledName(signature).replace('.', '_'); out.print("__" + sig); outName += "__" + sig; signature = signature.replace('.', '/'); rsignature = rsignature.replace('.', '/'); out.println(); if (rsignature.length() == 0) { rsignature = "V"; } String s = "{\"" + jfunc.getName() + (isPointerFunc ? "Bounds" : "") + "\", \"(" + signature +")" + rsignature + "\", (void *) " + outName + " },"; nativeRegistrations.add(s); List<Integer> nonPrimitiveArgs = new ArrayList<Integer>(); int numBufferArgs = 0; List<String> bufferArgNames = new ArrayList<String>(); // Emit JNI signature (arguments) // // Example: // // (JNIEnv *_env, jobject this, jint plane, jfloatArray equation_ref, jint offset) { // out.print(" (JNIEnv *_env, jobject _this"); for (int i = 0; i < numArgs; i++) { out.print(", "); JType argType = jfunc.getArgType(i); String suffix; if (!argType.isPrimitive()) { if (argType.isArray()) { suffix = "_ref"; } else { suffix = "_buf"; } nonPrimitiveArgs.add(new Integer(i)); if (jfunc.getArgType(i).isBuffer()) { int cIndex = jfunc.getArgCIndex(i); String cname = cfunc.getArgName(cIndex); bufferArgNames.add(cname); numBufferArgs++; } } else { suffix = ""; } out.print(getJniType(argType) + " " + jfunc.getArgName(i) + suffix); } if (isPointerFunc) { out.print(", jint remaining"); } out.println(") {"); int numArrays = 0; int numBuffers = 0; for (int i = 0; i < nonPrimitiveArgs.size(); i++) { int idx = nonPrimitiveArgs.get(i).intValue(); if (jfunc.getArgType(idx).isArray()) { ++numArrays; } if (jfunc.getArgType(idx).isBuffer()) { ++numBuffers; } } // Emit method body // Emit local variable declarations for _exception and _returnValue // // Example: // // android::gl::ogles_context_t *ctx; // // jint _exception; // GLenum _returnValue; // CType returnType = cfunc.getType(); boolean isVoid = returnType.isVoid(); boolean isUnsupported = isUnsupportedFunc(cfunc); if (isUnsupported) { out.println(indent + "_env->ThrowNew(UOEClass,"); out.println(indent + " \"" + cfunc.getName() + "\");"); if (!isVoid) { String retval = getErrorReturnValue(cfunc); out.println(indent + "return " + retval + ";"); } out.println("}"); out.println(); return; } if (mUseContextPointer) { out.println(indent + "android::gl::ogles_context_t *ctx = getContext(_env, _this);"); } boolean emitExceptionCheck = (numArrays > 0 || numBuffers > 0) && hasNonConstArg(jfunc, cfunc, nonPrimitiveArgs); // mChecker.getChecks(cfunc.getName()) != null // Emit an _exeption variable if there will be error checks if (emitExceptionCheck) { out.println(indent + "jint _exception = 0;"); } // Emit a single _array or multiple _XXXArray variables if (numBufferArgs == 1) { out.println(indent + "jarray _array = (jarray) 0;"); } else { for (int i = 0; i < numBufferArgs; i++) { out.println(indent + "jarray _" + bufferArgNames.get(i) + "Array = (jarray) 0;"); } } if (!isVoid) { String retval = getErrorReturnValue(cfunc); if (retval != null) { out.println(indent + returnType.getDeclaration() + " _returnValue = " + retval + ";"); } else { out.println(indent + returnType.getDeclaration() + " _returnValue;"); } } // Emit local variable declarations for pointer arguments // // Example: // // GLfixed *eqn_base; // GLfixed *eqn; // String offset = "offset"; String remaining = "_remaining"; if (nonPrimitiveArgs.size() > 0) { for (int i = 0; i < nonPrimitiveArgs.size(); i++) { int idx = nonPrimitiveArgs.get(i).intValue(); int cIndex = jfunc.getArgCIndex(idx); String cname = cfunc.getArgName(cIndex); CType type = cfunc.getArgType(jfunc.getArgCIndex(idx)); String decl = type.getDeclaration(); if (jfunc.getArgType(idx).isArray()) { out.println(indent + decl + (decl.endsWith("*") ? "" : " ") + jfunc.getArgName(idx) + "_base = (" + decl + ") 0;"); } remaining = (numArrays <= 1 && numBuffers <= 1) ? "_remaining" : "_" + cname + "Remaining"; out.println(indent + "jint " + remaining + ";"); out.println(indent + decl + (decl.endsWith("*") ? "" : " ") + jfunc.getArgName(idx) + " = (" + decl + ") 0;"); } out.println(); } // Emit 'GetPrimitiveArrayCritical' for arrays // Emit 'GetPointer' calls for Buffer pointers int bufArgIdx = 0; if (nonPrimitiveArgs.size() > 0) { for (int i = 0; i < nonPrimitiveArgs.size(); i++) { int idx = nonPrimitiveArgs.get(i).intValue(); int cIndex = jfunc.getArgCIndex(idx); String cname = cfunc.getArgName(cIndex); offset = numArrays <= 1 ? "offset" : cname + "Offset"; remaining = (numArrays <= 1 && numBuffers <= 1) ? "_remaining" : "_" + cname + "Remaining"; if (jfunc.getArgType(idx).isArray()) { out.println(indent + "if (!" + cname + "_ref) {"); if (emitExceptionCheck) { out.println(indent + indent + "_exception = 1;"); } out.println(indent + " " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ThrowNew(" + (mUseCPlusPlus ? "" : "_env, ") + "IAEClass, " + "\"" + cname + " == null\");"); out.println(indent + " goto exit;"); needsExit = true; out.println(indent + "}"); out.println(indent + "if (" + offset + " < 0) {"); if (emitExceptionCheck) { out.println(indent + indent + "_exception = 1;"); } out.println(indent + " " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ThrowNew(" + (mUseCPlusPlus ? "" : "_env, ") + "IAEClass, " + "\"" + offset + " < 0\");"); out.println(indent + " goto exit;"); needsExit = true; out.println(indent + "}"); out.println(indent + remaining + " = " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->GetArrayLength(" + (mUseCPlusPlus ? "" : "_env, ") + cname + "_ref) - " + offset + ";"); emitNativeBoundsChecks(cfunc, cname, out, false, emitExceptionCheck, offset, remaining, " "); out.println(indent + cname + "_base = (" + cfunc.getArgType(cIndex).getDeclaration() + ")"); out.println(indent + " " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->GetPrimitiveArrayCritical(" + (mUseCPlusPlus ? "" : "_env, ") + jfunc.getArgName(idx) + "_ref, (jboolean *)0);"); out.println(indent + cname + " = " + cname + "_base + " + offset + ";"); out.println(); } else { String array = numBufferArgs <= 1 ? "_array" : "_" + bufferArgNames.get(bufArgIdx++) + "Array"; boolean nullAllowed = isNullAllowed(cfunc) || isPointerFunc; if (nullAllowed) { out.println(indent + "if (" + cname + "_buf) {"); out.print(indent); } if (isPointerFunc) { out.println(indent + cname + " = (" + cfunc.getArgType(cIndex).getDeclaration() + - ") _env->GetDirectBufferAddress(" + - (mUseCPlusPlus ? "" : "_env, ") + + ") getDirectBufferPointer(_env, " + cname + "_buf);"); String iii = " "; - out.println(iii + indent + "if ( ! " + cname + " ) {"); - out.println(iii + iii + indent + - (mUseCPlusPlus ? "_env" : "(*_env)") + - "->ThrowNew(" + - (mUseCPlusPlus ? "" : "_env, ") + - "IAEClass, \"Must use a native order direct Buffer\");"); + out.println(iii + indent + "if ( ! " + cname + " ) {"); out.println(iii + iii + indent + "return;"); out.println(iii + indent + "}"); } else { out.println(indent + cname + " = (" + cfunc.getArgType(cIndex).getDeclaration() + ")getPointer(_env, " + cname + "_buf, &" + array + ", &" + remaining + ");"); } if (nullAllowed) { out.println(indent + "}"); } emitNativeBoundsChecks(cfunc, cname, out, true, emitExceptionCheck, offset, remaining, " "); } } } if (!isVoid) { out.print(indent + "_returnValue = "); } else { out.print(indent); } String name = cfunc.getName(); if (mUseContextPointer) { name = name.substring(2, name.length()); // Strip off 'gl' prefix name = name.substring(0, 1).toLowerCase() + name.substring(1, name.length()); out.print("ctx->procs."); } out.print(name + (isPointerFunc ? "Bounds" : "") + "("); numArgs = cfunc.getNumArgs(); if (numArgs == 0) { if (mUseContextPointer) { out.println("ctx);"); } else { out.println(");"); } } else { if (mUseContextPointer) { out.println("ctx,"); } else { out.println(); } for (int i = 0; i < numArgs; i++) { String typecast; if (i == numArgs - 1 && isVBOPointerFunc) { typecast = "const GLvoid *"; } else { typecast = cfunc.getArgType(i).getDeclaration(); } out.print(indent + indent + "(" + typecast + ")" + cfunc.getArgName(i)); if (i == numArgs - 1) { if (isPointerFunc) { out.println(","); out.println(indent + indent + "(GLsizei)remaining"); } else { out.println(); } } else { out.println(","); } } out.println(indent + ");"); } if (needsExit) { out.println(); out.println("exit:"); needsExit = false; } bufArgIdx = 0; if (nonPrimitiveArgs.size() > 0) { for (int i = nonPrimitiveArgs.size() - 1; i >= 0; i--) { int idx = nonPrimitiveArgs.get(i).intValue(); int cIndex = jfunc.getArgCIndex(idx); if (jfunc.getArgType(idx).isArray()) { // If the argument is 'const', GL will not write to it. // In this case, we can use the 'JNI_ABORT' flag to avoid // the need to write back to the Java array out.println(indent + "if (" + jfunc.getArgName(idx) + "_base) {"); out.println(indent + indent + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ReleasePrimitiveArrayCritical(" + (mUseCPlusPlus ? "" : "_env, ") + jfunc.getArgName(idx) + "_ref, " + cfunc.getArgName(cIndex) + "_base,"); out.println(indent + indent + indent + (cfunc.getArgType(cIndex).isConst() ? "JNI_ABORT" : "_exception ? JNI_ABORT: 0") + ");"); out.println(indent + "}"); } else if (jfunc.getArgType(idx).isBuffer()) { if (! isPointerFunc) { String array = numBufferArgs <= 1 ? "_array" : "_" + bufferArgNames.get(bufArgIdx++) + "Array"; out.println(indent + "if (" + array + ") {"); out.println(indent + indent + "releasePointer(_env, " + array + ", " + cfunc.getArgName(cIndex) + ", " + (cfunc.getArgType(cIndex).isConst() ? "JNI_FALSE" : "_exception ? JNI_FALSE :" + " JNI_TRUE") + ");"); out.println(indent + "}"); } } } } if (!isVoid) { out.println(indent + "return _returnValue;"); } out.println("}"); out.println(); } }
false
true
public void emitJniCode(JFunc jfunc, PrintStream out) { CFunc cfunc = jfunc.getCFunc(); // Emit comment identifying original C function // // Example: // // /* void glClipPlanef ( GLenum plane, const GLfloat *equation ) */ // out.println("/* " + cfunc.getOriginal() + " */"); // Emit JNI signature (name) // // Example: // // void // android_glClipPlanef__I_3FI // String outName = "android_" + jfunc.getName(); boolean isPointerFunc = outName.endsWith("Pointer") && jfunc.getCFunc().hasPointerArg(); boolean isVBOPointerFunc = (outName.endsWith("Pointer") || outName.endsWith("DrawElements")) && !jfunc.getCFunc().hasPointerArg(); if (isPointerFunc) { outName += "Bounds"; } out.print("static "); out.println(getJniType(jfunc.getType())); out.print(outName); String rsignature = getJniName(jfunc.getType()); String signature = ""; int numArgs = jfunc.getNumArgs(); for (int i = 0; i < numArgs; i++) { JType argType = jfunc.getArgType(i); signature += getJniName(argType); } if (isPointerFunc) { signature += "I"; } // Append signature to function name String sig = getJniMangledName(signature).replace('.', '_'); out.print("__" + sig); outName += "__" + sig; signature = signature.replace('.', '/'); rsignature = rsignature.replace('.', '/'); out.println(); if (rsignature.length() == 0) { rsignature = "V"; } String s = "{\"" + jfunc.getName() + (isPointerFunc ? "Bounds" : "") + "\", \"(" + signature +")" + rsignature + "\", (void *) " + outName + " },"; nativeRegistrations.add(s); List<Integer> nonPrimitiveArgs = new ArrayList<Integer>(); int numBufferArgs = 0; List<String> bufferArgNames = new ArrayList<String>(); // Emit JNI signature (arguments) // // Example: // // (JNIEnv *_env, jobject this, jint plane, jfloatArray equation_ref, jint offset) { // out.print(" (JNIEnv *_env, jobject _this"); for (int i = 0; i < numArgs; i++) { out.print(", "); JType argType = jfunc.getArgType(i); String suffix; if (!argType.isPrimitive()) { if (argType.isArray()) { suffix = "_ref"; } else { suffix = "_buf"; } nonPrimitiveArgs.add(new Integer(i)); if (jfunc.getArgType(i).isBuffer()) { int cIndex = jfunc.getArgCIndex(i); String cname = cfunc.getArgName(cIndex); bufferArgNames.add(cname); numBufferArgs++; } } else { suffix = ""; } out.print(getJniType(argType) + " " + jfunc.getArgName(i) + suffix); } if (isPointerFunc) { out.print(", jint remaining"); } out.println(") {"); int numArrays = 0; int numBuffers = 0; for (int i = 0; i < nonPrimitiveArgs.size(); i++) { int idx = nonPrimitiveArgs.get(i).intValue(); if (jfunc.getArgType(idx).isArray()) { ++numArrays; } if (jfunc.getArgType(idx).isBuffer()) { ++numBuffers; } } // Emit method body // Emit local variable declarations for _exception and _returnValue // // Example: // // android::gl::ogles_context_t *ctx; // // jint _exception; // GLenum _returnValue; // CType returnType = cfunc.getType(); boolean isVoid = returnType.isVoid(); boolean isUnsupported = isUnsupportedFunc(cfunc); if (isUnsupported) { out.println(indent + "_env->ThrowNew(UOEClass,"); out.println(indent + " \"" + cfunc.getName() + "\");"); if (!isVoid) { String retval = getErrorReturnValue(cfunc); out.println(indent + "return " + retval + ";"); } out.println("}"); out.println(); return; } if (mUseContextPointer) { out.println(indent + "android::gl::ogles_context_t *ctx = getContext(_env, _this);"); } boolean emitExceptionCheck = (numArrays > 0 || numBuffers > 0) && hasNonConstArg(jfunc, cfunc, nonPrimitiveArgs); // mChecker.getChecks(cfunc.getName()) != null // Emit an _exeption variable if there will be error checks if (emitExceptionCheck) { out.println(indent + "jint _exception = 0;"); } // Emit a single _array or multiple _XXXArray variables if (numBufferArgs == 1) { out.println(indent + "jarray _array = (jarray) 0;"); } else { for (int i = 0; i < numBufferArgs; i++) { out.println(indent + "jarray _" + bufferArgNames.get(i) + "Array = (jarray) 0;"); } } if (!isVoid) { String retval = getErrorReturnValue(cfunc); if (retval != null) { out.println(indent + returnType.getDeclaration() + " _returnValue = " + retval + ";"); } else { out.println(indent + returnType.getDeclaration() + " _returnValue;"); } } // Emit local variable declarations for pointer arguments // // Example: // // GLfixed *eqn_base; // GLfixed *eqn; // String offset = "offset"; String remaining = "_remaining"; if (nonPrimitiveArgs.size() > 0) { for (int i = 0; i < nonPrimitiveArgs.size(); i++) { int idx = nonPrimitiveArgs.get(i).intValue(); int cIndex = jfunc.getArgCIndex(idx); String cname = cfunc.getArgName(cIndex); CType type = cfunc.getArgType(jfunc.getArgCIndex(idx)); String decl = type.getDeclaration(); if (jfunc.getArgType(idx).isArray()) { out.println(indent + decl + (decl.endsWith("*") ? "" : " ") + jfunc.getArgName(idx) + "_base = (" + decl + ") 0;"); } remaining = (numArrays <= 1 && numBuffers <= 1) ? "_remaining" : "_" + cname + "Remaining"; out.println(indent + "jint " + remaining + ";"); out.println(indent + decl + (decl.endsWith("*") ? "" : " ") + jfunc.getArgName(idx) + " = (" + decl + ") 0;"); } out.println(); } // Emit 'GetPrimitiveArrayCritical' for arrays // Emit 'GetPointer' calls for Buffer pointers int bufArgIdx = 0; if (nonPrimitiveArgs.size() > 0) { for (int i = 0; i < nonPrimitiveArgs.size(); i++) { int idx = nonPrimitiveArgs.get(i).intValue(); int cIndex = jfunc.getArgCIndex(idx); String cname = cfunc.getArgName(cIndex); offset = numArrays <= 1 ? "offset" : cname + "Offset"; remaining = (numArrays <= 1 && numBuffers <= 1) ? "_remaining" : "_" + cname + "Remaining"; if (jfunc.getArgType(idx).isArray()) { out.println(indent + "if (!" + cname + "_ref) {"); if (emitExceptionCheck) { out.println(indent + indent + "_exception = 1;"); } out.println(indent + " " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ThrowNew(" + (mUseCPlusPlus ? "" : "_env, ") + "IAEClass, " + "\"" + cname + " == null\");"); out.println(indent + " goto exit;"); needsExit = true; out.println(indent + "}"); out.println(indent + "if (" + offset + " < 0) {"); if (emitExceptionCheck) { out.println(indent + indent + "_exception = 1;"); } out.println(indent + " " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ThrowNew(" + (mUseCPlusPlus ? "" : "_env, ") + "IAEClass, " + "\"" + offset + " < 0\");"); out.println(indent + " goto exit;"); needsExit = true; out.println(indent + "}"); out.println(indent + remaining + " = " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->GetArrayLength(" + (mUseCPlusPlus ? "" : "_env, ") + cname + "_ref) - " + offset + ";"); emitNativeBoundsChecks(cfunc, cname, out, false, emitExceptionCheck, offset, remaining, " "); out.println(indent + cname + "_base = (" + cfunc.getArgType(cIndex).getDeclaration() + ")"); out.println(indent + " " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->GetPrimitiveArrayCritical(" + (mUseCPlusPlus ? "" : "_env, ") + jfunc.getArgName(idx) + "_ref, (jboolean *)0);"); out.println(indent + cname + " = " + cname + "_base + " + offset + ";"); out.println(); } else { String array = numBufferArgs <= 1 ? "_array" : "_" + bufferArgNames.get(bufArgIdx++) + "Array"; boolean nullAllowed = isNullAllowed(cfunc) || isPointerFunc; if (nullAllowed) { out.println(indent + "if (" + cname + "_buf) {"); out.print(indent); } if (isPointerFunc) { out.println(indent + cname + " = (" + cfunc.getArgType(cIndex).getDeclaration() + ") _env->GetDirectBufferAddress(" + (mUseCPlusPlus ? "" : "_env, ") + cname + "_buf);"); String iii = " "; out.println(iii + indent + "if ( ! " + cname + " ) {"); out.println(iii + iii + indent + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ThrowNew(" + (mUseCPlusPlus ? "" : "_env, ") + "IAEClass, \"Must use a native order direct Buffer\");"); out.println(iii + iii + indent + "return;"); out.println(iii + indent + "}"); } else { out.println(indent + cname + " = (" + cfunc.getArgType(cIndex).getDeclaration() + ")getPointer(_env, " + cname + "_buf, &" + array + ", &" + remaining + ");"); } if (nullAllowed) { out.println(indent + "}"); } emitNativeBoundsChecks(cfunc, cname, out, true, emitExceptionCheck, offset, remaining, " "); } } } if (!isVoid) { out.print(indent + "_returnValue = "); } else { out.print(indent); } String name = cfunc.getName(); if (mUseContextPointer) { name = name.substring(2, name.length()); // Strip off 'gl' prefix name = name.substring(0, 1).toLowerCase() + name.substring(1, name.length()); out.print("ctx->procs."); } out.print(name + (isPointerFunc ? "Bounds" : "") + "("); numArgs = cfunc.getNumArgs(); if (numArgs == 0) { if (mUseContextPointer) { out.println("ctx);"); } else { out.println(");"); } } else { if (mUseContextPointer) { out.println("ctx,"); } else { out.println(); } for (int i = 0; i < numArgs; i++) { String typecast; if (i == numArgs - 1 && isVBOPointerFunc) { typecast = "const GLvoid *"; } else { typecast = cfunc.getArgType(i).getDeclaration(); } out.print(indent + indent + "(" + typecast + ")" + cfunc.getArgName(i)); if (i == numArgs - 1) { if (isPointerFunc) { out.println(","); out.println(indent + indent + "(GLsizei)remaining"); } else { out.println(); } } else { out.println(","); } } out.println(indent + ");"); } if (needsExit) { out.println(); out.println("exit:"); needsExit = false; } bufArgIdx = 0; if (nonPrimitiveArgs.size() > 0) { for (int i = nonPrimitiveArgs.size() - 1; i >= 0; i--) { int idx = nonPrimitiveArgs.get(i).intValue(); int cIndex = jfunc.getArgCIndex(idx); if (jfunc.getArgType(idx).isArray()) { // If the argument is 'const', GL will not write to it. // In this case, we can use the 'JNI_ABORT' flag to avoid // the need to write back to the Java array out.println(indent + "if (" + jfunc.getArgName(idx) + "_base) {"); out.println(indent + indent + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ReleasePrimitiveArrayCritical(" + (mUseCPlusPlus ? "" : "_env, ") + jfunc.getArgName(idx) + "_ref, " + cfunc.getArgName(cIndex) + "_base,"); out.println(indent + indent + indent + (cfunc.getArgType(cIndex).isConst() ? "JNI_ABORT" : "_exception ? JNI_ABORT: 0") + ");"); out.println(indent + "}"); } else if (jfunc.getArgType(idx).isBuffer()) { if (! isPointerFunc) { String array = numBufferArgs <= 1 ? "_array" : "_" + bufferArgNames.get(bufArgIdx++) + "Array"; out.println(indent + "if (" + array + ") {"); out.println(indent + indent + "releasePointer(_env, " + array + ", " + cfunc.getArgName(cIndex) + ", " + (cfunc.getArgType(cIndex).isConst() ? "JNI_FALSE" : "_exception ? JNI_FALSE :" + " JNI_TRUE") + ");"); out.println(indent + "}"); } } } } if (!isVoid) { out.println(indent + "return _returnValue;"); } out.println("}"); out.println(); }
public void emitJniCode(JFunc jfunc, PrintStream out) { CFunc cfunc = jfunc.getCFunc(); // Emit comment identifying original C function // // Example: // // /* void glClipPlanef ( GLenum plane, const GLfloat *equation ) */ // out.println("/* " + cfunc.getOriginal() + " */"); // Emit JNI signature (name) // // Example: // // void // android_glClipPlanef__I_3FI // String outName = "android_" + jfunc.getName(); boolean isPointerFunc = outName.endsWith("Pointer") && jfunc.getCFunc().hasPointerArg(); boolean isVBOPointerFunc = (outName.endsWith("Pointer") || outName.endsWith("DrawElements")) && !jfunc.getCFunc().hasPointerArg(); if (isPointerFunc) { outName += "Bounds"; } out.print("static "); out.println(getJniType(jfunc.getType())); out.print(outName); String rsignature = getJniName(jfunc.getType()); String signature = ""; int numArgs = jfunc.getNumArgs(); for (int i = 0; i < numArgs; i++) { JType argType = jfunc.getArgType(i); signature += getJniName(argType); } if (isPointerFunc) { signature += "I"; } // Append signature to function name String sig = getJniMangledName(signature).replace('.', '_'); out.print("__" + sig); outName += "__" + sig; signature = signature.replace('.', '/'); rsignature = rsignature.replace('.', '/'); out.println(); if (rsignature.length() == 0) { rsignature = "V"; } String s = "{\"" + jfunc.getName() + (isPointerFunc ? "Bounds" : "") + "\", \"(" + signature +")" + rsignature + "\", (void *) " + outName + " },"; nativeRegistrations.add(s); List<Integer> nonPrimitiveArgs = new ArrayList<Integer>(); int numBufferArgs = 0; List<String> bufferArgNames = new ArrayList<String>(); // Emit JNI signature (arguments) // // Example: // // (JNIEnv *_env, jobject this, jint plane, jfloatArray equation_ref, jint offset) { // out.print(" (JNIEnv *_env, jobject _this"); for (int i = 0; i < numArgs; i++) { out.print(", "); JType argType = jfunc.getArgType(i); String suffix; if (!argType.isPrimitive()) { if (argType.isArray()) { suffix = "_ref"; } else { suffix = "_buf"; } nonPrimitiveArgs.add(new Integer(i)); if (jfunc.getArgType(i).isBuffer()) { int cIndex = jfunc.getArgCIndex(i); String cname = cfunc.getArgName(cIndex); bufferArgNames.add(cname); numBufferArgs++; } } else { suffix = ""; } out.print(getJniType(argType) + " " + jfunc.getArgName(i) + suffix); } if (isPointerFunc) { out.print(", jint remaining"); } out.println(") {"); int numArrays = 0; int numBuffers = 0; for (int i = 0; i < nonPrimitiveArgs.size(); i++) { int idx = nonPrimitiveArgs.get(i).intValue(); if (jfunc.getArgType(idx).isArray()) { ++numArrays; } if (jfunc.getArgType(idx).isBuffer()) { ++numBuffers; } } // Emit method body // Emit local variable declarations for _exception and _returnValue // // Example: // // android::gl::ogles_context_t *ctx; // // jint _exception; // GLenum _returnValue; // CType returnType = cfunc.getType(); boolean isVoid = returnType.isVoid(); boolean isUnsupported = isUnsupportedFunc(cfunc); if (isUnsupported) { out.println(indent + "_env->ThrowNew(UOEClass,"); out.println(indent + " \"" + cfunc.getName() + "\");"); if (!isVoid) { String retval = getErrorReturnValue(cfunc); out.println(indent + "return " + retval + ";"); } out.println("}"); out.println(); return; } if (mUseContextPointer) { out.println(indent + "android::gl::ogles_context_t *ctx = getContext(_env, _this);"); } boolean emitExceptionCheck = (numArrays > 0 || numBuffers > 0) && hasNonConstArg(jfunc, cfunc, nonPrimitiveArgs); // mChecker.getChecks(cfunc.getName()) != null // Emit an _exeption variable if there will be error checks if (emitExceptionCheck) { out.println(indent + "jint _exception = 0;"); } // Emit a single _array or multiple _XXXArray variables if (numBufferArgs == 1) { out.println(indent + "jarray _array = (jarray) 0;"); } else { for (int i = 0; i < numBufferArgs; i++) { out.println(indent + "jarray _" + bufferArgNames.get(i) + "Array = (jarray) 0;"); } } if (!isVoid) { String retval = getErrorReturnValue(cfunc); if (retval != null) { out.println(indent + returnType.getDeclaration() + " _returnValue = " + retval + ";"); } else { out.println(indent + returnType.getDeclaration() + " _returnValue;"); } } // Emit local variable declarations for pointer arguments // // Example: // // GLfixed *eqn_base; // GLfixed *eqn; // String offset = "offset"; String remaining = "_remaining"; if (nonPrimitiveArgs.size() > 0) { for (int i = 0; i < nonPrimitiveArgs.size(); i++) { int idx = nonPrimitiveArgs.get(i).intValue(); int cIndex = jfunc.getArgCIndex(idx); String cname = cfunc.getArgName(cIndex); CType type = cfunc.getArgType(jfunc.getArgCIndex(idx)); String decl = type.getDeclaration(); if (jfunc.getArgType(idx).isArray()) { out.println(indent + decl + (decl.endsWith("*") ? "" : " ") + jfunc.getArgName(idx) + "_base = (" + decl + ") 0;"); } remaining = (numArrays <= 1 && numBuffers <= 1) ? "_remaining" : "_" + cname + "Remaining"; out.println(indent + "jint " + remaining + ";"); out.println(indent + decl + (decl.endsWith("*") ? "" : " ") + jfunc.getArgName(idx) + " = (" + decl + ") 0;"); } out.println(); } // Emit 'GetPrimitiveArrayCritical' for arrays // Emit 'GetPointer' calls for Buffer pointers int bufArgIdx = 0; if (nonPrimitiveArgs.size() > 0) { for (int i = 0; i < nonPrimitiveArgs.size(); i++) { int idx = nonPrimitiveArgs.get(i).intValue(); int cIndex = jfunc.getArgCIndex(idx); String cname = cfunc.getArgName(cIndex); offset = numArrays <= 1 ? "offset" : cname + "Offset"; remaining = (numArrays <= 1 && numBuffers <= 1) ? "_remaining" : "_" + cname + "Remaining"; if (jfunc.getArgType(idx).isArray()) { out.println(indent + "if (!" + cname + "_ref) {"); if (emitExceptionCheck) { out.println(indent + indent + "_exception = 1;"); } out.println(indent + " " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ThrowNew(" + (mUseCPlusPlus ? "" : "_env, ") + "IAEClass, " + "\"" + cname + " == null\");"); out.println(indent + " goto exit;"); needsExit = true; out.println(indent + "}"); out.println(indent + "if (" + offset + " < 0) {"); if (emitExceptionCheck) { out.println(indent + indent + "_exception = 1;"); } out.println(indent + " " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ThrowNew(" + (mUseCPlusPlus ? "" : "_env, ") + "IAEClass, " + "\"" + offset + " < 0\");"); out.println(indent + " goto exit;"); needsExit = true; out.println(indent + "}"); out.println(indent + remaining + " = " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->GetArrayLength(" + (mUseCPlusPlus ? "" : "_env, ") + cname + "_ref) - " + offset + ";"); emitNativeBoundsChecks(cfunc, cname, out, false, emitExceptionCheck, offset, remaining, " "); out.println(indent + cname + "_base = (" + cfunc.getArgType(cIndex).getDeclaration() + ")"); out.println(indent + " " + (mUseCPlusPlus ? "_env" : "(*_env)") + "->GetPrimitiveArrayCritical(" + (mUseCPlusPlus ? "" : "_env, ") + jfunc.getArgName(idx) + "_ref, (jboolean *)0);"); out.println(indent + cname + " = " + cname + "_base + " + offset + ";"); out.println(); } else { String array = numBufferArgs <= 1 ? "_array" : "_" + bufferArgNames.get(bufArgIdx++) + "Array"; boolean nullAllowed = isNullAllowed(cfunc) || isPointerFunc; if (nullAllowed) { out.println(indent + "if (" + cname + "_buf) {"); out.print(indent); } if (isPointerFunc) { out.println(indent + cname + " = (" + cfunc.getArgType(cIndex).getDeclaration() + ") getDirectBufferPointer(_env, " + cname + "_buf);"); String iii = " "; out.println(iii + indent + "if ( ! " + cname + " ) {"); out.println(iii + iii + indent + "return;"); out.println(iii + indent + "}"); } else { out.println(indent + cname + " = (" + cfunc.getArgType(cIndex).getDeclaration() + ")getPointer(_env, " + cname + "_buf, &" + array + ", &" + remaining + ");"); } if (nullAllowed) { out.println(indent + "}"); } emitNativeBoundsChecks(cfunc, cname, out, true, emitExceptionCheck, offset, remaining, " "); } } } if (!isVoid) { out.print(indent + "_returnValue = "); } else { out.print(indent); } String name = cfunc.getName(); if (mUseContextPointer) { name = name.substring(2, name.length()); // Strip off 'gl' prefix name = name.substring(0, 1).toLowerCase() + name.substring(1, name.length()); out.print("ctx->procs."); } out.print(name + (isPointerFunc ? "Bounds" : "") + "("); numArgs = cfunc.getNumArgs(); if (numArgs == 0) { if (mUseContextPointer) { out.println("ctx);"); } else { out.println(");"); } } else { if (mUseContextPointer) { out.println("ctx,"); } else { out.println(); } for (int i = 0; i < numArgs; i++) { String typecast; if (i == numArgs - 1 && isVBOPointerFunc) { typecast = "const GLvoid *"; } else { typecast = cfunc.getArgType(i).getDeclaration(); } out.print(indent + indent + "(" + typecast + ")" + cfunc.getArgName(i)); if (i == numArgs - 1) { if (isPointerFunc) { out.println(","); out.println(indent + indent + "(GLsizei)remaining"); } else { out.println(); } } else { out.println(","); } } out.println(indent + ");"); } if (needsExit) { out.println(); out.println("exit:"); needsExit = false; } bufArgIdx = 0; if (nonPrimitiveArgs.size() > 0) { for (int i = nonPrimitiveArgs.size() - 1; i >= 0; i--) { int idx = nonPrimitiveArgs.get(i).intValue(); int cIndex = jfunc.getArgCIndex(idx); if (jfunc.getArgType(idx).isArray()) { // If the argument is 'const', GL will not write to it. // In this case, we can use the 'JNI_ABORT' flag to avoid // the need to write back to the Java array out.println(indent + "if (" + jfunc.getArgName(idx) + "_base) {"); out.println(indent + indent + (mUseCPlusPlus ? "_env" : "(*_env)") + "->ReleasePrimitiveArrayCritical(" + (mUseCPlusPlus ? "" : "_env, ") + jfunc.getArgName(idx) + "_ref, " + cfunc.getArgName(cIndex) + "_base,"); out.println(indent + indent + indent + (cfunc.getArgType(cIndex).isConst() ? "JNI_ABORT" : "_exception ? JNI_ABORT: 0") + ");"); out.println(indent + "}"); } else if (jfunc.getArgType(idx).isBuffer()) { if (! isPointerFunc) { String array = numBufferArgs <= 1 ? "_array" : "_" + bufferArgNames.get(bufArgIdx++) + "Array"; out.println(indent + "if (" + array + ") {"); out.println(indent + indent + "releasePointer(_env, " + array + ", " + cfunc.getArgName(cIndex) + ", " + (cfunc.getArgType(cIndex).isConst() ? "JNI_FALSE" : "_exception ? JNI_FALSE :" + " JNI_TRUE") + ");"); out.println(indent + "}"); } } } } if (!isVoid) { out.println(indent + "return _returnValue;"); } out.println("}"); out.println(); }
diff --git a/src/main/java/org/basex/tests/w3c/W3CTS.java b/src/main/java/org/basex/tests/w3c/W3CTS.java index a2f747274..218c21fef 100644 --- a/src/main/java/org/basex/tests/w3c/W3CTS.java +++ b/src/main/java/org/basex/tests/w3c/W3CTS.java @@ -1,845 +1,843 @@ package org.basex.tests.w3c; import static org.basex.core.Text.*; import static org.basex.util.Token.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.regex.Pattern; import org.basex.core.Context; import org.basex.core.Prop; import org.basex.core.cmd.Check; import org.basex.core.cmd.Close; import org.basex.core.cmd.CreateDB; import org.basex.core.cmd.DropDB; import org.basex.data.Data; import org.basex.data.DataText; import org.basex.data.Nodes; import org.basex.io.IO; import org.basex.io.IOFile; import org.basex.io.in.TextInput; import org.basex.io.out.ArrayOutput; import org.basex.io.out.PrintOutput; import org.basex.io.serial.Serializer; import org.basex.io.serial.SerializerProp; import org.basex.query.QueryException; import org.basex.query.QueryProcessor; import org.basex.query.expr.Expr; import org.basex.query.func.FNSimple; import org.basex.query.func.Function; import org.basex.query.item.DBNode; import org.basex.query.item.Item; import org.basex.query.item.Str; import org.basex.query.item.Uri; import org.basex.query.item.Value; import org.basex.query.iter.ItemCache; import org.basex.util.Args; import org.basex.util.Performance; import org.basex.util.TokenBuilder; import org.basex.util.Util; import org.basex.util.list.TokenList; /** * XQuery Test Suite wrapper. * * @author BaseX Team 2005-11, BSD License * @author Christian Gruen */ public abstract class W3CTS { // Try "ulimit -n 65536" if Linux tells you "Too many open files." /** Inspect flag. */ private static final byte[] INSPECT = token("Inspect"); /** Fragment flag. */ private static final byte[] FRAGMENT = token("Fragment"); /** XML flag. */ private static final byte[] XML = token("XML"); /** XML flag. */ private static final byte[] IGNORE = token("Ignore"); /** Replacement pattern. */ private static final Pattern SLASH = Pattern.compile("/", Pattern.LITERAL); /** Database context. */ protected final Context context = new Context(); /** Path to the XQuery Test Suite. */ protected String path = ""; /** Data reference. */ protected Data data; /** Log file. */ private final String pathlog; /** Test suite input. */ private final String input; /** Test suite id. */ private final String testid; /** Query path. */ private String queries; /** Expected results. */ private String expected; /** Reported results. */ private String results; /** Reports. */ private String report; /** Test sources. */ private String sources; /** Maximum length of result output. */ private int maxout = 500; /** Query filter string. */ private String single; /** Flag for printing current time functions into log file. */ private boolean currTime; /** Flag for creating report files. */ private boolean reporting; /** Verbose flag. */ private boolean verbose; /** Minimum time in ms to include query in performance statistics. */ private int timer = Integer.MAX_VALUE; /** Minimum conformance. */ private boolean minimum; /** Print compilation steps. */ private boolean compile; /** test-group to use. */ private String group; /** Cached source files. */ private final HashMap<String, String> srcs = new HashMap<String, String>(); /** Cached module files. */ private final HashMap<String, String> mods = new HashMap<String, String>(); /** Cached collections. */ private final HashMap<String, byte[][]> colls = new HashMap<String, byte[][]>(); /** OK log. */ private final StringBuilder logOK = new StringBuilder(); /** OK log. */ private final StringBuilder logOK2 = new StringBuilder(); /** Error log. */ private final StringBuilder logErr = new StringBuilder(); /** Error log. */ private final StringBuilder logErr2 = new StringBuilder(); /** File log. */ private final StringBuilder logReport = new StringBuilder(); /** Error counter. */ private int err; /** Error2 counter. */ private int err2; /** OK counter. */ private int ok; /** OK2 counter. */ private int ok2; /** * Constructor. * @param nm name of test */ public W3CTS(final String nm) { input = nm + "Catalog" + IO.XMLSUFFIX; testid = nm.substring(0, 4); pathlog = testid.toLowerCase() + ".log"; } /** * Runs the test suite. * @param args command-line arguments * @throws Exception exception */ void run(final String[] args) throws Exception { try { parseArguments(args); } catch(final IOException ex) { Util.errln(ex); System.exit(1); } queries = path + "Queries/XQuery/"; expected = path + "ExpectedTestResults/"; results = path + "ReportingResults/Results/"; report = path + "ReportingResults/"; sources = path + "TestSources/"; final Performance perf = new Performance(); context.prop.set(Prop.CHOP, false); //new Check(path + input).execute(context); data = CreateDB.xml(new IOFile(path + input), context); final Nodes root = new Nodes(0, data); Util.outln(NL + Util.name(this) + " Test Suite " + text("/*:test-suite/@version", root)); Util.outln(NL + "Caching Sources..."); for(final int s : nodes("//*:source", root).list) { final Nodes srcRoot = new Nodes(s, data); final String val = (path + text("@FileName", srcRoot)).replace('\\', '/'); srcs.put(text("@ID", srcRoot), val); } Util.outln("Caching Modules..."); for(final int s : nodes("//*:module", root).list) { final Nodes srcRoot = new Nodes(s, data); final String val = (path + text("@FileName", srcRoot)).replace('\\', '/'); mods.put(text("@ID", srcRoot), val); } Util.outln("Caching Collections..."); for(final int c : nodes("//*:collection", root).list) { final Nodes nodes = new Nodes(c, data); final String cname = text("@ID", nodes); final TokenList dl = new TokenList(); final Nodes doc = nodes("*:input-document", nodes); for(int d = 0; d < doc.size(); ++d) { dl.add(token(sources + string(data.atom(doc.list[d])) + IO.XMLSUFFIX)); } colls.put(cname, dl.toArray()); } init(root); if(reporting) { Util.outln("Delete old results..."); new IOFile(results).delete(); } if(verbose) Util.outln(); final Nodes nodes = minimum ? nodes("//*:test-group[starts-with(@name, 'Minim')]//*:test-case", root) : group != null ? nodes("//*:test-group[@name eq '" + group + "']//*:test-case", root) : nodes("//*:test-case", root); long total = nodes.size(); Util.out("Parsing " + total + " Queries"); for(int t = 0; t < total; ++t) { if(!parse(new Nodes(nodes.list[t], data))) break; if(!verbose && t % 500 == 0) Util.out("."); } Util.outln(); total = ok + ok2 + err + err2; final String time = perf.getTimer(); Util.outln("Writing log file..." + NL); PrintOutput po = new PrintOutput(path + pathlog); po.println("TEST RESULTS ________________________________________________"); po.println(NL + "Total #Queries: " + total); po.println("Correct / Empty Results: " + ok + " / " + ok2); po.print("Conformance (w/Empty Results): "); po.println(pc(ok, total) + " / " + pc(ok + ok2, total)); po.println("Wrong Results / Errors: " + err + " / " + err2 + NL); po.println("WRONG _______________________________________________________"); po.print(NL + logErr); po.println("WRONG (ERRORS) ______________________________________________"); po.print(NL + logErr2); po.println("CORRECT? (EMPTY) ____________________________________________"); po.print(NL + logOK2); po.println("CORRECT _____________________________________________________"); po.print(NL + logOK); po.println("_____________________________________________________________"); po.close(); if(reporting) { po = new PrintOutput(report + NAME + IO.XMLSUFFIX); print(po, report + NAME + "Pre" + IO.XMLSUFFIX); po.print(logReport.toString()); print(po, report + NAME + "Pos" + IO.XMLSUFFIX); po.close(); } Util.outln("Total #Queries: " + total); Util.outln("Correct / Empty results: " + ok + " / " + ok2); Util.out("Conformance (w/empty results): "); Util.outln(pc(ok, total) + " / " + pc(ok + ok2, total)); Util.outln("Total Time: " + time); context.close(); } /** * Calculates the percentage of correct queries. * @param v value * @param t total value * @return percentage */ private String pc(final int v, final long t) { return (t == 0 ? 100 : v * 10000 / t / 100d) + "%"; } /** * Parses the specified test case. * @param root root node * @throws Exception exception * @return true if the query, specified by {@link #single}, was evaluated */ private boolean parse(final Nodes root) throws Exception { final String pth = text("@FilePath", root); final String outname = text("@name", root); if(single != null && !outname.startsWith(single)) return true; final Performance perf = new Performance(); if(verbose) Util.out("- " + outname); boolean inspect = false; boolean correct = true; final Nodes nodes = states(root); for(int n = 0; n < nodes.size(); ++n) { final Nodes state = new Nodes(nodes.list[n], nodes.data); final String inname = text("*:query/@name", state); context.query = new IOFile(queries + pth + inname + IO.XQSUFFIX); final String in = read(context.query); String er = null; ItemCache iter = null; final Nodes cont = nodes("*:contextItem", state); Nodes curr = null; if(cont.size() != 0) { final Data d = Check.check(context, srcs.get(string(data.atom(cont.list[0])))); curr = new Nodes(d.docs().toArray(), d); curr.root = true; } context.prop.set(Prop.QUERYINFO, compile); final QueryProcessor xq = new QueryProcessor(in, curr, context); context.prop.set(Prop.QUERYINFO, false); // limit result sizes to 1MB final ArrayOutput ao = new ArrayOutput(); final TokenBuilder files = new TokenBuilder(); try { files.add(file(nodes("*:input-file", state), nodes("*:input-file/@variable", state), xq, n == 0)); files.add(file(nodes("*:defaultCollection", state), null, xq, n == 0)); var(nodes("*:input-URI", state), nodes("*:input-URI/@variable", state), xq); eval(nodes("*:input-query/@name", state), nodes("*:input-query/@variable", state), pth, xq); parse(xq, state); for(final int p : nodes("*:module", root).list) { final String uri = text("@namespace", new Nodes(p, data)); final String file = mods.get(string(data.atom(p))) + IO.XQSUFFIX; xq.module(file, uri); } // evaluate and serialize query final SerializerProp sp = new SerializerProp(); sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ? DataText.YES : DataText.NO); final Serializer ser = Serializer.get(ao, sp); iter = xq.value().cache(); for(Item it; (it = iter.next()) != null;) it.serialize(ser); ser.close(); } catch(final Exception ex) { if(!(ex instanceof QueryException || ex instanceof IOException)) { System.err.println("\n*** " + outname + " ***"); System.err.println(in + "\n"); ex.printStackTrace(); } er = ex.getMessage(); if(er.startsWith(STOPPED)) er = er.substring(er.indexOf('\n') + 1); if(er.startsWith("[")) er = er.replaceAll("\\[(.*?)\\] (.*)", "$1 $2"); // unexpected error - dump stack trace } // print compilation steps if(compile) { Util.errln("---------------------------------------------------------"); Util.err(xq.info()); Util.errln(in); } final Nodes expOut = nodes("*:output-file/text()", state); final TokenList result = new TokenList(); for(int o = 0; o < expOut.size(); ++o) { final String resFile = string(data.atom(expOut.list[o])); final IOFile exp = new IOFile(expected + pth + resFile); - result.add(read(exp)); + result.add(read(exp).replaceAll("\r\n|\r|\n", Prop.NL)); } final Nodes cmpFiles = nodes("*:output-file/@compare", state); boolean xml = false; boolean frag = false; boolean ignore = false; for(int o = 0; o < cmpFiles.size(); ++o) { final byte[] type = data.atom(cmpFiles.list[o]); xml |= eq(type, XML); frag |= eq(type, FRAGMENT); ignore |= eq(type, IGNORE); } String expError = text("*:expected-error/text()", state); final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX); if(files.size() != 0) { log.append(" ["); log.append(files); log.append("]"); } log.append(NL); /** Remove comments. */ log.append(norm(in)); log.append(NL); final String logStr = log.toString(); // skip queries with variable results final boolean print = currTime || !logStr.contains("current-"); boolean correctError = false; if(er != null && (expOut.size() == 0 || !expError.isEmpty())) { expError = error(pth + outname, expError); final String code = er.substring(0, Math.min(8, er.length())); for(final String e : SLASH.split(expError)) { if(code.equals(e)) { correctError = true; break; } } } if(correctError) { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(er)); logOK.append(NL); logOK.append(NL); addLog(pth, outname + ".log", er); } ++ok; } else if(er == null) { int s = -1; final int rs = result.size(); while(!ignore && ++s < rs) { inspect |= s < cmpFiles.list.length && eq(data.atom(cmpFiles.list[s]), INSPECT); - // normalize newlines - final String expect = - string(result.get(s)).replaceAll("\r\n|\r|\n", Prop.NL); + final String expect = string(result.get(s)); final String actual = ao.toString(); if(expect.equals(actual)) break; if(xml || frag) { iter.reset(); try { final ItemCache ic = toIter(expect.replaceAll( "^<\\?xml.*?\\?>", "").trim(), frag); if(FNSimple.deep(null, iter, ic)) break; ic.reset(); final ItemCache ia = toIter(actual, frag); if(FNSimple.deep(null, ia, ic)) break; } catch(final Throwable ex) { System.err.println("\n" + outname + ":"); ex.printStackTrace(); } } } if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) { if(print) { if(expOut.size() == 0) result.add(error(pth + outname, expError)); logErr.append(logStr); logErr.append("[" + testid + " ] "); logErr.append(norm(string(result.get(0)))); logErr.append(NL); logErr.append("[Wrong] "); logErr.append(norm(ao.toString())); logErr.append(NL); logErr.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } correct = false; ++err; } else { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(ao.toString())); logOK.append(NL); logOK.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } ++ok; } } else { if(expOut.size() == 0 || !expError.isEmpty()) { if(print) { logOK2.append(logStr); logOK2.append("[" + testid + " ] "); logOK2.append(norm(expError)); logOK2.append(NL); logOK2.append("[Rght?] "); logOK2.append(norm(er)); logOK2.append(NL); logOK2.append(NL); addLog(pth, outname + ".log", er); } ++ok2; } else { if(print) { logErr2.append(logStr); logErr2.append("[" + testid + " ] "); logErr2.append(norm(string(result.get(0)))); logErr2.append(NL); logErr2.append("[Wrong] "); logErr2.append(norm(er)); logErr2.append(NL); logErr2.append(NL); addLog(pth, outname + ".log", er); } correct = false; ++err2; } } if(curr != null) Close.close(curr.data, context); xq.close(); } if(reporting) { logReport.append(" <test-case name=\""); logReport.append(outname); logReport.append("\" result='"); logReport.append(correct ? "pass" : "fail"); if(inspect) logReport.append("' todo='inspect"); logReport.append("'/>"); logReport.append(NL); } // print verbose/timing information final long nano = perf.getTime(); final boolean slow = nano / 1000000 > timer; if(verbose) { if(slow) Util.out(": " + Performance.getTimer(nano, 1)); Util.outln(); } else if(slow) { Util.out(NL + "- " + outname + ": " + Performance.getTimer(nano, 1)); } return single == null || !outname.equals(single); } /** * Creates an item iterator for the given XML fragment. * @param xml fragment * @param frag fragment flag * @return iterator */ private ItemCache toIter(final String xml, final boolean frag) { final ItemCache it = new ItemCache(); try { final String str = frag ? "<X>" + xml + "</X>" : xml; final Data d = CreateDB.xml(IO.get(str), context); for(int p = frag ? 2 : 0; p < d.meta.size; p += d.size(p, d.kind(p))) it.add(new DBNode(d, p)); } catch(final IOException ex) { return new ItemCache(new Item[] { Str.get(Long.toString(System.nanoTime())) }, 1); } return it; } /** * Removes comments from the specified string. * @param in input string * @return result */ private String norm(final String in) { return QueryProcessor.removeComments(in, maxout); } /** * Initializes the input files, specified by the context nodes. * @param nod variables * @param var documents * @param qp query processor * @param first call * @return string with input files * @throws Exception exception */ private byte[] file(final Nodes nod, final Nodes var, final QueryProcessor qp, final boolean first) throws Exception { final TokenBuilder tb = new TokenBuilder(); for(int c = 0; c < nod.size(); ++c) { final byte[] nm = data.atom(nod.list[c]); String src = srcs.get(string(nm)); if(tb.size() != 0) tb.add(", "); tb.add(nm); Expr expr = null; if(src == null) { // assign collection expr = coll(nm, qp); } else { // assign document final String dbname = new IOFile(src).dbname(); Function def = Function.DOC; // updates: drop updated document or open updated database if(updating()) { if(first) { new DropDB(dbname).execute(context); } else { def = Function.DBOPEN; src = dbname; } } expr = def.get(null, Str.get(src)); } if(var != null) qp.bind(string(data.atom(var.list[c])), expr); } return tb.finish(); } /** * Assigns the nodes to the specified variables. * @param nod nodes * @param var variables * @param qp query processor * @throws QueryException query exception */ private void var(final Nodes nod, final Nodes var, final QueryProcessor qp) throws QueryException { for(int c = 0; c < nod.size(); ++c) { final byte[] nm = data.atom(nod.list[c]); final String src = srcs.get(string(nm)); final Item it = src == null ? coll(nm, qp) : Str.get(src); qp.bind(string(data.atom(var.list[c])), it); } } /** * Assigns a collection. * @param name collection name * @param qp query processor * @return expression * @throws QueryException query exception */ private Uri coll(final byte[] name, final QueryProcessor qp) throws QueryException { qp.ctx.resource.addCollection(name, colls.get(string(name))); return Uri.uri(name); } /** * Evaluates the the input files and assigns the result to the specified * variables. * @param nod variables * @param var documents * @param pth file path * @param qp query processor * @throws Exception exception */ private void eval(final Nodes nod, final Nodes var, final String pth, final QueryProcessor qp) throws Exception { for(int c = 0; c < nod.size(); ++c) { final String file = pth + string(data.atom(nod.list[c])) + IO.XQSUFFIX; final String in = read(new IOFile(queries + file)); final QueryProcessor xq = new QueryProcessor(in, context); final Value val = xq.value(); qp.bind(string(data.atom(var.list[c])), val); xq.close(); } } /** * Adds a log file. * @param pth file path * @param nm file name * @param msg message * @throws Exception exception */ private void addLog(final String pth, final String nm, final String msg) throws Exception { if(reporting) { final File file = new File(results + pth); if(!file.exists()) file.mkdirs(); final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(results + pth + nm), UTF8)); bw.write(msg); bw.close(); } } /** * Returns an error message. * @param nm test name * @param error XQTS error * @return error message */ private String error(final String nm, final String error) { final String error2 = expected + nm + ".log"; final IO file = new IOFile(error2); return file.exists() ? error + "/" + read(file) : error; } /** * Returns the resulting query text (text node or attribute value). * @param qu query * @param root root node * @return attribute value * @throws Exception exception */ protected String text(final String qu, final Nodes root) throws Exception { final Nodes n = nodes(qu, root); final TokenBuilder tb = new TokenBuilder(); for(int i = 0; i < n.size(); ++i) { if(i != 0) tb.add('/'); tb.add(data.atom(n.list[i])); } return tb.toString(); } /** * Returns the resulting auxiliary uri in multiple strings. * @param role role * @param root root node * @return attribute value * @throws Exception exception */ protected String[] aux(final String role, final Nodes root) throws Exception { return text("*:aux-URI[@role = '" + role + "']", root).split("/"); } /** * Returns the resulting query nodes. * @param qu query * @param root root node * @return attribute value * @throws Exception exception */ protected Nodes nodes(final String qu, final Nodes root) throws Exception { return new QueryProcessor(qu, root, context).queryNodes(); } /** * Adds the specified file to the writer. * @param po writer * @param f file path * @throws Exception exception */ private void print(final PrintOutput po, final String f) throws Exception { final BufferedReader br = new BufferedReader(new FileReader(f)); for(String line; (line = br.readLine()) != null;) po.println(line); br.close(); } /** * Returns the contents of the specified file. * @param f file to be read * @return content */ private String read(final IO f) { try { return TextInput.content(f).toString(); } catch(final IOException ex) { Util.errln(ex); return ""; } } /** * Initializes the test. * @param root root nodes reference * @throws Exception exception */ @SuppressWarnings("unused") protected void init(final Nodes root) throws Exception { } /** * Performs test specific parsings. * @param qp query processor * @param root root nodes reference * @throws Exception exception */ @SuppressWarnings("unused") protected void parse(final QueryProcessor qp, final Nodes root) throws Exception { } /** * Returns all query states. * @param root root node * @return states * @throws Exception exception */ @SuppressWarnings("unused") protected Nodes states(final Nodes root) throws Exception { return root; } /** * Updating flag. * @return flag */ protected boolean updating() { return false; } /** * Parses the command-line arguments, specified by the user. * @param args command-line arguments * @throws IOException I/O exception */ protected final void parseArguments(final String[] args) throws IOException { final Args arg = new Args(args, this, " [options] [pat]" + NL + " [pat] perform only tests with the specified pattern" + NL + " -c print compilation steps" + NL + " -C run tests depending on current time" + NL + " -g <test-group> test group to test" + NL + " -h show this help" + NL + " -m minimum conformance" + NL + " -p change path" + NL + " -r create report" + NL + " -t[ms] list slowest queries" + NL + " -v verbose output", Util.info(CONSOLE, Util.name(this))); while(arg.more()) { if(arg.dash()) { final char c = arg.next(); if(c == 'r') { reporting = true; currTime = true; } else if(c == 'C') { currTime = true; } else if(c == 'c') { compile = true; } else if(c == 'm') { minimum = true; } else if(c == 'g') { group = arg.string(); } else if(c == 'p') { path = arg.string() + "/"; } else if(c == 't') { timer = arg.num(); } else if(c == 'v') { verbose = true; } else { arg.usage(); } } else { single = arg.string(); maxout = Integer.MAX_VALUE; } } } }
false
true
private boolean parse(final Nodes root) throws Exception { final String pth = text("@FilePath", root); final String outname = text("@name", root); if(single != null && !outname.startsWith(single)) return true; final Performance perf = new Performance(); if(verbose) Util.out("- " + outname); boolean inspect = false; boolean correct = true; final Nodes nodes = states(root); for(int n = 0; n < nodes.size(); ++n) { final Nodes state = new Nodes(nodes.list[n], nodes.data); final String inname = text("*:query/@name", state); context.query = new IOFile(queries + pth + inname + IO.XQSUFFIX); final String in = read(context.query); String er = null; ItemCache iter = null; final Nodes cont = nodes("*:contextItem", state); Nodes curr = null; if(cont.size() != 0) { final Data d = Check.check(context, srcs.get(string(data.atom(cont.list[0])))); curr = new Nodes(d.docs().toArray(), d); curr.root = true; } context.prop.set(Prop.QUERYINFO, compile); final QueryProcessor xq = new QueryProcessor(in, curr, context); context.prop.set(Prop.QUERYINFO, false); // limit result sizes to 1MB final ArrayOutput ao = new ArrayOutput(); final TokenBuilder files = new TokenBuilder(); try { files.add(file(nodes("*:input-file", state), nodes("*:input-file/@variable", state), xq, n == 0)); files.add(file(nodes("*:defaultCollection", state), null, xq, n == 0)); var(nodes("*:input-URI", state), nodes("*:input-URI/@variable", state), xq); eval(nodes("*:input-query/@name", state), nodes("*:input-query/@variable", state), pth, xq); parse(xq, state); for(final int p : nodes("*:module", root).list) { final String uri = text("@namespace", new Nodes(p, data)); final String file = mods.get(string(data.atom(p))) + IO.XQSUFFIX; xq.module(file, uri); } // evaluate and serialize query final SerializerProp sp = new SerializerProp(); sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ? DataText.YES : DataText.NO); final Serializer ser = Serializer.get(ao, sp); iter = xq.value().cache(); for(Item it; (it = iter.next()) != null;) it.serialize(ser); ser.close(); } catch(final Exception ex) { if(!(ex instanceof QueryException || ex instanceof IOException)) { System.err.println("\n*** " + outname + " ***"); System.err.println(in + "\n"); ex.printStackTrace(); } er = ex.getMessage(); if(er.startsWith(STOPPED)) er = er.substring(er.indexOf('\n') + 1); if(er.startsWith("[")) er = er.replaceAll("\\[(.*?)\\] (.*)", "$1 $2"); // unexpected error - dump stack trace } // print compilation steps if(compile) { Util.errln("---------------------------------------------------------"); Util.err(xq.info()); Util.errln(in); } final Nodes expOut = nodes("*:output-file/text()", state); final TokenList result = new TokenList(); for(int o = 0; o < expOut.size(); ++o) { final String resFile = string(data.atom(expOut.list[o])); final IOFile exp = new IOFile(expected + pth + resFile); result.add(read(exp)); } final Nodes cmpFiles = nodes("*:output-file/@compare", state); boolean xml = false; boolean frag = false; boolean ignore = false; for(int o = 0; o < cmpFiles.size(); ++o) { final byte[] type = data.atom(cmpFiles.list[o]); xml |= eq(type, XML); frag |= eq(type, FRAGMENT); ignore |= eq(type, IGNORE); } String expError = text("*:expected-error/text()", state); final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX); if(files.size() != 0) { log.append(" ["); log.append(files); log.append("]"); } log.append(NL); /** Remove comments. */ log.append(norm(in)); log.append(NL); final String logStr = log.toString(); // skip queries with variable results final boolean print = currTime || !logStr.contains("current-"); boolean correctError = false; if(er != null && (expOut.size() == 0 || !expError.isEmpty())) { expError = error(pth + outname, expError); final String code = er.substring(0, Math.min(8, er.length())); for(final String e : SLASH.split(expError)) { if(code.equals(e)) { correctError = true; break; } } } if(correctError) { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(er)); logOK.append(NL); logOK.append(NL); addLog(pth, outname + ".log", er); } ++ok; } else if(er == null) { int s = -1; final int rs = result.size(); while(!ignore && ++s < rs) { inspect |= s < cmpFiles.list.length && eq(data.atom(cmpFiles.list[s]), INSPECT); // normalize newlines final String expect = string(result.get(s)).replaceAll("\r\n|\r|\n", Prop.NL); final String actual = ao.toString(); if(expect.equals(actual)) break; if(xml || frag) { iter.reset(); try { final ItemCache ic = toIter(expect.replaceAll( "^<\\?xml.*?\\?>", "").trim(), frag); if(FNSimple.deep(null, iter, ic)) break; ic.reset(); final ItemCache ia = toIter(actual, frag); if(FNSimple.deep(null, ia, ic)) break; } catch(final Throwable ex) { System.err.println("\n" + outname + ":"); ex.printStackTrace(); } } } if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) { if(print) { if(expOut.size() == 0) result.add(error(pth + outname, expError)); logErr.append(logStr); logErr.append("[" + testid + " ] "); logErr.append(norm(string(result.get(0)))); logErr.append(NL); logErr.append("[Wrong] "); logErr.append(norm(ao.toString())); logErr.append(NL); logErr.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } correct = false; ++err; } else { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(ao.toString())); logOK.append(NL); logOK.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } ++ok; } } else { if(expOut.size() == 0 || !expError.isEmpty()) { if(print) { logOK2.append(logStr); logOK2.append("[" + testid + " ] "); logOK2.append(norm(expError)); logOK2.append(NL); logOK2.append("[Rght?] "); logOK2.append(norm(er)); logOK2.append(NL); logOK2.append(NL); addLog(pth, outname + ".log", er); } ++ok2; } else { if(print) { logErr2.append(logStr); logErr2.append("[" + testid + " ] "); logErr2.append(norm(string(result.get(0)))); logErr2.append(NL); logErr2.append("[Wrong] "); logErr2.append(norm(er)); logErr2.append(NL); logErr2.append(NL); addLog(pth, outname + ".log", er); } correct = false; ++err2; } } if(curr != null) Close.close(curr.data, context); xq.close(); } if(reporting) { logReport.append(" <test-case name=\""); logReport.append(outname); logReport.append("\" result='"); logReport.append(correct ? "pass" : "fail"); if(inspect) logReport.append("' todo='inspect"); logReport.append("'/>"); logReport.append(NL); } // print verbose/timing information final long nano = perf.getTime(); final boolean slow = nano / 1000000 > timer; if(verbose) { if(slow) Util.out(": " + Performance.getTimer(nano, 1)); Util.outln(); } else if(slow) { Util.out(NL + "- " + outname + ": " + Performance.getTimer(nano, 1)); } return single == null || !outname.equals(single); }
private boolean parse(final Nodes root) throws Exception { final String pth = text("@FilePath", root); final String outname = text("@name", root); if(single != null && !outname.startsWith(single)) return true; final Performance perf = new Performance(); if(verbose) Util.out("- " + outname); boolean inspect = false; boolean correct = true; final Nodes nodes = states(root); for(int n = 0; n < nodes.size(); ++n) { final Nodes state = new Nodes(nodes.list[n], nodes.data); final String inname = text("*:query/@name", state); context.query = new IOFile(queries + pth + inname + IO.XQSUFFIX); final String in = read(context.query); String er = null; ItemCache iter = null; final Nodes cont = nodes("*:contextItem", state); Nodes curr = null; if(cont.size() != 0) { final Data d = Check.check(context, srcs.get(string(data.atom(cont.list[0])))); curr = new Nodes(d.docs().toArray(), d); curr.root = true; } context.prop.set(Prop.QUERYINFO, compile); final QueryProcessor xq = new QueryProcessor(in, curr, context); context.prop.set(Prop.QUERYINFO, false); // limit result sizes to 1MB final ArrayOutput ao = new ArrayOutput(); final TokenBuilder files = new TokenBuilder(); try { files.add(file(nodes("*:input-file", state), nodes("*:input-file/@variable", state), xq, n == 0)); files.add(file(nodes("*:defaultCollection", state), null, xq, n == 0)); var(nodes("*:input-URI", state), nodes("*:input-URI/@variable", state), xq); eval(nodes("*:input-query/@name", state), nodes("*:input-query/@variable", state), pth, xq); parse(xq, state); for(final int p : nodes("*:module", root).list) { final String uri = text("@namespace", new Nodes(p, data)); final String file = mods.get(string(data.atom(p))) + IO.XQSUFFIX; xq.module(file, uri); } // evaluate and serialize query final SerializerProp sp = new SerializerProp(); sp.set(SerializerProp.S_INDENT, context.prop.is(Prop.CHOP) ? DataText.YES : DataText.NO); final Serializer ser = Serializer.get(ao, sp); iter = xq.value().cache(); for(Item it; (it = iter.next()) != null;) it.serialize(ser); ser.close(); } catch(final Exception ex) { if(!(ex instanceof QueryException || ex instanceof IOException)) { System.err.println("\n*** " + outname + " ***"); System.err.println(in + "\n"); ex.printStackTrace(); } er = ex.getMessage(); if(er.startsWith(STOPPED)) er = er.substring(er.indexOf('\n') + 1); if(er.startsWith("[")) er = er.replaceAll("\\[(.*?)\\] (.*)", "$1 $2"); // unexpected error - dump stack trace } // print compilation steps if(compile) { Util.errln("---------------------------------------------------------"); Util.err(xq.info()); Util.errln(in); } final Nodes expOut = nodes("*:output-file/text()", state); final TokenList result = new TokenList(); for(int o = 0; o < expOut.size(); ++o) { final String resFile = string(data.atom(expOut.list[o])); final IOFile exp = new IOFile(expected + pth + resFile); result.add(read(exp).replaceAll("\r\n|\r|\n", Prop.NL)); } final Nodes cmpFiles = nodes("*:output-file/@compare", state); boolean xml = false; boolean frag = false; boolean ignore = false; for(int o = 0; o < cmpFiles.size(); ++o) { final byte[] type = data.atom(cmpFiles.list[o]); xml |= eq(type, XML); frag |= eq(type, FRAGMENT); ignore |= eq(type, IGNORE); } String expError = text("*:expected-error/text()", state); final StringBuilder log = new StringBuilder(pth + inname + IO.XQSUFFIX); if(files.size() != 0) { log.append(" ["); log.append(files); log.append("]"); } log.append(NL); /** Remove comments. */ log.append(norm(in)); log.append(NL); final String logStr = log.toString(); // skip queries with variable results final boolean print = currTime || !logStr.contains("current-"); boolean correctError = false; if(er != null && (expOut.size() == 0 || !expError.isEmpty())) { expError = error(pth + outname, expError); final String code = er.substring(0, Math.min(8, er.length())); for(final String e : SLASH.split(expError)) { if(code.equals(e)) { correctError = true; break; } } } if(correctError) { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(er)); logOK.append(NL); logOK.append(NL); addLog(pth, outname + ".log", er); } ++ok; } else if(er == null) { int s = -1; final int rs = result.size(); while(!ignore && ++s < rs) { inspect |= s < cmpFiles.list.length && eq(data.atom(cmpFiles.list[s]), INSPECT); final String expect = string(result.get(s)); final String actual = ao.toString(); if(expect.equals(actual)) break; if(xml || frag) { iter.reset(); try { final ItemCache ic = toIter(expect.replaceAll( "^<\\?xml.*?\\?>", "").trim(), frag); if(FNSimple.deep(null, iter, ic)) break; ic.reset(); final ItemCache ia = toIter(actual, frag); if(FNSimple.deep(null, ia, ic)) break; } catch(final Throwable ex) { System.err.println("\n" + outname + ":"); ex.printStackTrace(); } } } if((rs > 0 || !expError.isEmpty()) && s == rs && !inspect) { if(print) { if(expOut.size() == 0) result.add(error(pth + outname, expError)); logErr.append(logStr); logErr.append("[" + testid + " ] "); logErr.append(norm(string(result.get(0)))); logErr.append(NL); logErr.append("[Wrong] "); logErr.append(norm(ao.toString())); logErr.append(NL); logErr.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } correct = false; ++err; } else { if(print) { logOK.append(logStr); logOK.append("[Right] "); logOK.append(norm(ao.toString())); logOK.append(NL); logOK.append(NL); addLog(pth, outname + (xml ? IO.XMLSUFFIX : ".txt"), ao.toString()); } ++ok; } } else { if(expOut.size() == 0 || !expError.isEmpty()) { if(print) { logOK2.append(logStr); logOK2.append("[" + testid + " ] "); logOK2.append(norm(expError)); logOK2.append(NL); logOK2.append("[Rght?] "); logOK2.append(norm(er)); logOK2.append(NL); logOK2.append(NL); addLog(pth, outname + ".log", er); } ++ok2; } else { if(print) { logErr2.append(logStr); logErr2.append("[" + testid + " ] "); logErr2.append(norm(string(result.get(0)))); logErr2.append(NL); logErr2.append("[Wrong] "); logErr2.append(norm(er)); logErr2.append(NL); logErr2.append(NL); addLog(pth, outname + ".log", er); } correct = false; ++err2; } } if(curr != null) Close.close(curr.data, context); xq.close(); } if(reporting) { logReport.append(" <test-case name=\""); logReport.append(outname); logReport.append("\" result='"); logReport.append(correct ? "pass" : "fail"); if(inspect) logReport.append("' todo='inspect"); logReport.append("'/>"); logReport.append(NL); } // print verbose/timing information final long nano = perf.getTime(); final boolean slow = nano / 1000000 > timer; if(verbose) { if(slow) Util.out(": " + Performance.getTimer(nano, 1)); Util.outln(); } else if(slow) { Util.out(NL + "- " + outname + ": " + Performance.getTimer(nano, 1)); } return single == null || !outname.equals(single); }
diff --git a/fabric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/internal/ZKServerFactoryBean.java b/fabric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/internal/ZKServerFactoryBean.java index c1a739a14..4a81e105b 100644 --- a/fabric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/internal/ZKServerFactoryBean.java +++ b/fabric/fabric-zookeeper/src/main/java/org/fusesource/fabric/zookeeper/internal/ZKServerFactoryBean.java @@ -1,198 +1,200 @@ /** * Copyright (C) FuseSource, Inc. * http://fusesource.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fusesource.fabric.zookeeper.internal; import java.io.File; import java.io.FileOutputStream; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.zookeeper.server.NIOServerCnxnFactory; import org.apache.zookeeper.server.ServerConfig; import org.apache.zookeeper.server.ServerStats; import org.apache.zookeeper.server.ZKDatabase; import org.apache.zookeeper.server.ZooKeeperServer; import org.apache.zookeeper.server.persistence.FileTxnSnapLog; import org.apache.zookeeper.server.quorum.QuorumPeer; import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import org.apache.zookeeper.server.quorum.QuorumStats; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedServiceFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ZKServerFactoryBean implements ManagedServiceFactory { private static final transient Logger LOG = LoggerFactory.getLogger(ZKServerFactoryBean.class); private BundleContext bundleContext; private Map<String, Object> servers = new HashMap<String, Object>(); private Map<String, ServiceRegistration> services = new HashMap<String, ServiceRegistration>(); public BundleContext getBundleContext() { return bundleContext; } public void setBundleContext(BundleContext bundleContext) { this.bundleContext = bundleContext; } public String getName() { return "ZooKeeper Server"; } // TODO - replace this eventually... public void debug(String str, Object ... args) { if (LOG.isDebugEnabled()) { LOG.debug(String.format(str, args)); } } public synchronized void updated(String pid, Dictionary properties) throws ConfigurationException { try { deleted(pid); Properties props = new Properties(); for (Enumeration ek = properties.keys(); ek.hasMoreElements();) { Object key = ek.nextElement(); Object val = properties.get(key); props.put(key.toString(), val != null ? val.toString() : ""); } // Create myid file String serverId = props.getProperty("server.id"); if (serverId != null) { props.remove("server.id"); File myId = new File(props.getProperty("dataDir"), "myid"); if (myId.exists()) { myId.delete(); } - myId.getParentFile().mkdirs(); + if (myId.getParentFile() != null) { + myId.getParentFile().mkdirs(); + } FileOutputStream fos = new FileOutputStream(myId); try { fos.write((serverId + "\n").getBytes()); } finally { fos.close(); } } // Load properties QuorumPeerConfig config = new QuorumPeerConfig(); config.parseProperties(props); if (!config.getServers().isEmpty()) { NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory(); cnxnFactory.configure(config.getClientPortAddress(), config.getMaxClientCnxns()); QuorumPeer quorumPeer = new QuorumPeer(); quorumPeer.setClientPortAddress(config.getClientPortAddress()); quorumPeer.setTxnFactory(new FileTxnSnapLog( new File(config.getDataLogDir()), new File(config.getDataDir()))); quorumPeer.setQuorumPeers(config.getServers()); quorumPeer.setElectionType(config.getElectionAlg()); quorumPeer.setMyid(config.getServerId()); quorumPeer.setTickTime(config.getTickTime()); quorumPeer.setMinSessionTimeout(config.getMinSessionTimeout()); quorumPeer.setMaxSessionTimeout(config.getMaxSessionTimeout()); quorumPeer.setInitLimit(config.getInitLimit()); quorumPeer.setSyncLimit(config.getSyncLimit()); quorumPeer.setQuorumVerifier(config.getQuorumVerifier()); quorumPeer.setCnxnFactory(cnxnFactory); quorumPeer.setZKDatabase(new ZKDatabase(quorumPeer.getTxnFactory())); quorumPeer.setLearnerType(config.getPeerType()); try { debug("Starting quorum peer \"%s\" on address %s", quorumPeer.getMyid(), config.getClientPortAddress()); quorumPeer.start(); debug("Started quorum peer \"%s\"", quorumPeer.getMyid()); } catch (Exception e) { LOG.warn(String.format("Failed to start quorum peer \"%s\", reason : ", quorumPeer.getMyid(), e)); quorumPeer.shutdown(); throw e; } servers.put(pid, quorumPeer); services.put(pid, bundleContext.registerService(QuorumStats.Provider.class.getName(), quorumPeer, properties)); } else { ServerConfig cfg = new ServerConfig(); cfg.readFrom(config); ZooKeeperServer zkServer = new ZooKeeperServer(); FileTxnSnapLog ftxn = new FileTxnSnapLog(new File(cfg.getDataLogDir()), new File(cfg.getDataDir())); zkServer.setTxnLogFactory(ftxn); zkServer.setTickTime(cfg.getTickTime()); zkServer.setMinSessionTimeout(cfg.getMinSessionTimeout()); zkServer.setMaxSessionTimeout(cfg.getMaxSessionTimeout()); NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory(); cnxnFactory.configure(cfg.getClientPortAddress(), cfg.getMaxClientCnxns()); try { debug("Starting ZooKeeper server on address %s", config.getClientPortAddress()); cnxnFactory.startup(zkServer); LOG.debug("Started ZooKeeper server"); } catch (Exception e) { LOG.warn(String.format("Failed to start ZooKeeper server, reason : %s", e)); cnxnFactory.shutdown(); throw e; } servers.put(pid, cnxnFactory); services.put(pid, bundleContext.registerService(ServerStats.Provider.class.getName(), zkServer, properties)); } } catch (Exception e) { throw (ConfigurationException) new ConfigurationException(null, "Unable to parse ZooKeeper configuration: " + e.getMessage()).initCause(e); } } public synchronized void deleted(String pid) { debug("Shutting down ZK server %s", pid); Object obj = servers.remove(pid); ServiceRegistration reg = services.remove(pid); try { if (obj instanceof QuorumPeer) { ((QuorumPeer) obj).shutdown(); ((QuorumPeer) obj).join(); } else if (obj instanceof NIOServerCnxnFactory) { ((NIOServerCnxnFactory) obj).shutdown(); ((NIOServerCnxnFactory) obj).join(); } } catch (Throwable t) { debug("Caught and am ignoring exception %s while shutting down ZK server %s", t, obj); // ignore } if (reg != null) { try { reg.unregister(); } catch (Throwable t) { debug("Caught and am ignoring exception %s while unregistering %s", t, pid); // ignore } } } public void destroy() throws Exception { while (!servers.isEmpty()) { String pid = servers.keySet().iterator().next(); deleted(pid); } } }
true
true
public synchronized void updated(String pid, Dictionary properties) throws ConfigurationException { try { deleted(pid); Properties props = new Properties(); for (Enumeration ek = properties.keys(); ek.hasMoreElements();) { Object key = ek.nextElement(); Object val = properties.get(key); props.put(key.toString(), val != null ? val.toString() : ""); } // Create myid file String serverId = props.getProperty("server.id"); if (serverId != null) { props.remove("server.id"); File myId = new File(props.getProperty("dataDir"), "myid"); if (myId.exists()) { myId.delete(); } myId.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(myId); try { fos.write((serverId + "\n").getBytes()); } finally { fos.close(); } } // Load properties QuorumPeerConfig config = new QuorumPeerConfig(); config.parseProperties(props); if (!config.getServers().isEmpty()) { NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory(); cnxnFactory.configure(config.getClientPortAddress(), config.getMaxClientCnxns()); QuorumPeer quorumPeer = new QuorumPeer(); quorumPeer.setClientPortAddress(config.getClientPortAddress()); quorumPeer.setTxnFactory(new FileTxnSnapLog( new File(config.getDataLogDir()), new File(config.getDataDir()))); quorumPeer.setQuorumPeers(config.getServers()); quorumPeer.setElectionType(config.getElectionAlg()); quorumPeer.setMyid(config.getServerId()); quorumPeer.setTickTime(config.getTickTime()); quorumPeer.setMinSessionTimeout(config.getMinSessionTimeout()); quorumPeer.setMaxSessionTimeout(config.getMaxSessionTimeout()); quorumPeer.setInitLimit(config.getInitLimit()); quorumPeer.setSyncLimit(config.getSyncLimit()); quorumPeer.setQuorumVerifier(config.getQuorumVerifier()); quorumPeer.setCnxnFactory(cnxnFactory); quorumPeer.setZKDatabase(new ZKDatabase(quorumPeer.getTxnFactory())); quorumPeer.setLearnerType(config.getPeerType()); try { debug("Starting quorum peer \"%s\" on address %s", quorumPeer.getMyid(), config.getClientPortAddress()); quorumPeer.start(); debug("Started quorum peer \"%s\"", quorumPeer.getMyid()); } catch (Exception e) { LOG.warn(String.format("Failed to start quorum peer \"%s\", reason : ", quorumPeer.getMyid(), e)); quorumPeer.shutdown(); throw e; } servers.put(pid, quorumPeer); services.put(pid, bundleContext.registerService(QuorumStats.Provider.class.getName(), quorumPeer, properties)); } else { ServerConfig cfg = new ServerConfig(); cfg.readFrom(config); ZooKeeperServer zkServer = new ZooKeeperServer(); FileTxnSnapLog ftxn = new FileTxnSnapLog(new File(cfg.getDataLogDir()), new File(cfg.getDataDir())); zkServer.setTxnLogFactory(ftxn); zkServer.setTickTime(cfg.getTickTime()); zkServer.setMinSessionTimeout(cfg.getMinSessionTimeout()); zkServer.setMaxSessionTimeout(cfg.getMaxSessionTimeout()); NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory(); cnxnFactory.configure(cfg.getClientPortAddress(), cfg.getMaxClientCnxns()); try { debug("Starting ZooKeeper server on address %s", config.getClientPortAddress()); cnxnFactory.startup(zkServer); LOG.debug("Started ZooKeeper server"); } catch (Exception e) { LOG.warn(String.format("Failed to start ZooKeeper server, reason : %s", e)); cnxnFactory.shutdown(); throw e; } servers.put(pid, cnxnFactory); services.put(pid, bundleContext.registerService(ServerStats.Provider.class.getName(), zkServer, properties)); } } catch (Exception e) { throw (ConfigurationException) new ConfigurationException(null, "Unable to parse ZooKeeper configuration: " + e.getMessage()).initCause(e); } }
public synchronized void updated(String pid, Dictionary properties) throws ConfigurationException { try { deleted(pid); Properties props = new Properties(); for (Enumeration ek = properties.keys(); ek.hasMoreElements();) { Object key = ek.nextElement(); Object val = properties.get(key); props.put(key.toString(), val != null ? val.toString() : ""); } // Create myid file String serverId = props.getProperty("server.id"); if (serverId != null) { props.remove("server.id"); File myId = new File(props.getProperty("dataDir"), "myid"); if (myId.exists()) { myId.delete(); } if (myId.getParentFile() != null) { myId.getParentFile().mkdirs(); } FileOutputStream fos = new FileOutputStream(myId); try { fos.write((serverId + "\n").getBytes()); } finally { fos.close(); } } // Load properties QuorumPeerConfig config = new QuorumPeerConfig(); config.parseProperties(props); if (!config.getServers().isEmpty()) { NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory(); cnxnFactory.configure(config.getClientPortAddress(), config.getMaxClientCnxns()); QuorumPeer quorumPeer = new QuorumPeer(); quorumPeer.setClientPortAddress(config.getClientPortAddress()); quorumPeer.setTxnFactory(new FileTxnSnapLog( new File(config.getDataLogDir()), new File(config.getDataDir()))); quorumPeer.setQuorumPeers(config.getServers()); quorumPeer.setElectionType(config.getElectionAlg()); quorumPeer.setMyid(config.getServerId()); quorumPeer.setTickTime(config.getTickTime()); quorumPeer.setMinSessionTimeout(config.getMinSessionTimeout()); quorumPeer.setMaxSessionTimeout(config.getMaxSessionTimeout()); quorumPeer.setInitLimit(config.getInitLimit()); quorumPeer.setSyncLimit(config.getSyncLimit()); quorumPeer.setQuorumVerifier(config.getQuorumVerifier()); quorumPeer.setCnxnFactory(cnxnFactory); quorumPeer.setZKDatabase(new ZKDatabase(quorumPeer.getTxnFactory())); quorumPeer.setLearnerType(config.getPeerType()); try { debug("Starting quorum peer \"%s\" on address %s", quorumPeer.getMyid(), config.getClientPortAddress()); quorumPeer.start(); debug("Started quorum peer \"%s\"", quorumPeer.getMyid()); } catch (Exception e) { LOG.warn(String.format("Failed to start quorum peer \"%s\", reason : ", quorumPeer.getMyid(), e)); quorumPeer.shutdown(); throw e; } servers.put(pid, quorumPeer); services.put(pid, bundleContext.registerService(QuorumStats.Provider.class.getName(), quorumPeer, properties)); } else { ServerConfig cfg = new ServerConfig(); cfg.readFrom(config); ZooKeeperServer zkServer = new ZooKeeperServer(); FileTxnSnapLog ftxn = new FileTxnSnapLog(new File(cfg.getDataLogDir()), new File(cfg.getDataDir())); zkServer.setTxnLogFactory(ftxn); zkServer.setTickTime(cfg.getTickTime()); zkServer.setMinSessionTimeout(cfg.getMinSessionTimeout()); zkServer.setMaxSessionTimeout(cfg.getMaxSessionTimeout()); NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory(); cnxnFactory.configure(cfg.getClientPortAddress(), cfg.getMaxClientCnxns()); try { debug("Starting ZooKeeper server on address %s", config.getClientPortAddress()); cnxnFactory.startup(zkServer); LOG.debug("Started ZooKeeper server"); } catch (Exception e) { LOG.warn(String.format("Failed to start ZooKeeper server, reason : %s", e)); cnxnFactory.shutdown(); throw e; } servers.put(pid, cnxnFactory); services.put(pid, bundleContext.registerService(ServerStats.Provider.class.getName(), zkServer, properties)); } } catch (Exception e) { throw (ConfigurationException) new ConfigurationException(null, "Unable to parse ZooKeeper configuration: " + e.getMessage()).initCause(e); } }
diff --git a/src/pleocmd/itfc/gui/dgr/Diagram.java b/src/pleocmd/itfc/gui/dgr/Diagram.java index f094fc3..7b45adf 100644 --- a/src/pleocmd/itfc/gui/dgr/Diagram.java +++ b/src/pleocmd/itfc/gui/dgr/Diagram.java @@ -1,462 +1,463 @@ // This file is part of PleoCommand: // Interactively control Pleo with psychobiological parameters // // Copyright (C) 2010 Oliver Hoffmann - [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 2 // 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., 51 Franklin Street, Boston, USA. package pleocmd.itfc.gui.dgr; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.ToolTipManager; public final class Diagram extends JPanel { static final double MIN_GRID_DELTA = 2.0; private static final double SCALE_SPEED_MOUSE = 0.01; private static final double MOVE_SPEED_MOUSE = 0.05; private static final long serialVersionUID = -8245547025738665255L; private static final int BORDER = 4; private static final DefaultColor[] DEFAULT_COLORS = new DefaultColor[] { new DefaultColor(0xFF, 0x45, 0x00, "orange red"), new DefaultColor(0x7F, 0xFF, 0x00, "chartreuse"), new DefaultColor(0x63, 0xB8, 0xFF, "steel blue"), new DefaultColor(0xFF, 0xD7, 0x00, "gold"), new DefaultColor(0xFF, 0x6A, 0x6A, "indian red"), new DefaultColor(0x00, 0xFF, 0xFF, "cyan"), new DefaultColor(0xFF, 0xF6, 0x8F, "khaki"), new DefaultColor(0x7F, 0xFF, 0xD4, "aqua marine"), new DefaultColor(0xFF, 0x69, 0xB4, "hot pink"), new DefaultColor(0xC1, 0xFF, 0xC1, "dark sea green"), new DefaultColor(0xFF, 0xFF, 0xF0, "ivory"), new DefaultColor(0x83, 0x6F, 0xFF, "slate blue"), new DefaultColor(0xC0, 0xFF, 0x3E, "olive drab"), new DefaultColor(0xFF, 0x83, 0xFA, "orchid"), new DefaultColor(0xFF, 0xE7, 0xBA, "wheat"), new DefaultColor(0xFF, 0xC1, 0xC1, "rosy brown") }; private final List<DiagramDataSet> dataSets = new ArrayList<DiagramDataSet>(); private Color backgroundColor = Color.WHITE; private Pen axisPen = new Pen(Color.BLACK); private Pen unitPen = new Pen(Color.GRAY); private Pen subUnitPen = new Pen(Color.LIGHT_GRAY); private final DiagramAxis xAxis = new DiagramAxis(this, "X"); private final DiagramAxis yAxis = new DiagramAxis(this, "Y"); private double zoom = 1.0; private AffineTransform originalTransform; private enum AlignH { Left, Center, Right; } private enum AlignV { Top, Center, Bottom; } public Diagram() { addMouseMotionListener(new MouseMotionListener() { private int oldx; private int oldy; @Override public void mouseMoved(final MouseEvent e) { oldx = e.getX(); oldy = e.getY(); } @Override public void mouseDragged(final MouseEvent e) { final int newx = e.getX(); final int newy = e.getY(); getXAxis().setOffset( getXAxis().getOffset() - (newx - oldx) * MOVE_SPEED_MOUSE / getZoom()); getYAxis().setOffset( getYAxis().getOffset() + (newy - oldy) * MOVE_SPEED_MOUSE / getZoom()); oldx = newx; oldy = newy; } }); addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(final MouseWheelEvent e) { final int clicks = -e.getWheelRotation(); if (clicks > 0) setZoom(getZoom() * (1 + SCALE_SPEED_MOUSE * clicks)); if (clicks < 0) setZoom(getZoom() / (1 - SCALE_SPEED_MOUSE * clicks)); } }); ToolTipManager.sharedInstance().registerComponent(this); } synchronized void addDataSet(final DiagramDataSet dataSet) { dataSets.add(dataSet); } public List<DiagramDataSet> getDataSets() { return Collections.unmodifiableList(dataSets); } public synchronized Color getBackgroundColor() { return backgroundColor; } public synchronized void setBackgroundColor(final Color backgroundColor) { this.backgroundColor = backgroundColor; } public synchronized Pen getAxisPen() { return axisPen; } public synchronized void setAxisPen(final Pen axisPen) { this.axisPen = axisPen; } public synchronized Pen getUnitPen() { return unitPen; } public synchronized void setUnitPen(final Pen unitPen) { this.unitPen = unitPen; } public synchronized Pen getSubUnitPen() { return subUnitPen; } public synchronized void setSubUnitPen(final Pen subUnitPen) { this.subUnitPen = subUnitPen; } public DiagramAxis getXAxis() { return xAxis; } public DiagramAxis getYAxis() { return yAxis; } public synchronized double getZoom() { return zoom; } public synchronized void setZoom(final double zoom) { this.zoom = zoom; repaint(); } @Override protected synchronized void paintComponent(final Graphics g) { - final Rectangle clip = g.getClipBounds(); - final BufferedImage img = new BufferedImage(clip.width, clip.height, + final int areaWidth = getWidth(); + final int areaHeight = getHeight(); + final BufferedImage img = new BufferedImage(areaWidth, areaHeight, BufferedImage.TYPE_INT_RGB); final Graphics2D g2 = img.createGraphics(); originalTransform = g2.getTransform(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2.setClip(0, 0, clip.width, clip.height); + g2.setClip(0, 0, areaWidth, areaHeight); g2.setColor(backgroundColor); - g2.fillRect(0, 0, clip.width, clip.height); + g2.fillRect(0, 0, areaWidth, areaHeight); g2.setFont(getFont().deriveFont(10f)); // cache y-axis dimension final int unitHeight = g2.getFontMetrics().getHeight(); - final int h = getHeight() - 1 - unitHeight - BORDER; + final int h = areaHeight - 1 - unitHeight - BORDER; yAxis.updateCache(h); // cache x-axis dimension final int unitWidth1 = g2.getFontMetrics().stringWidth( String.format("%.2f %s", yAxis.getCachedMinVisUnit(), yAxis .getUnitName())); final int unitWidth2 = g2.getFontMetrics().stringWidth( String.format("%.2f %s", yAxis.getCachedMaxVisUnit(), yAxis .getUnitName())); final int unitWidth = Math.max(unitWidth1, unitWidth2); - final int w = getWidth() - 1 - unitWidth - BORDER; + final int w = areaWidth - 1 - unitWidth - BORDER; xAxis.updateCache(w); - g2.translate(unitWidth, getHeight() - unitHeight); + g2.translate(unitWidth, areaHeight - unitHeight); g2.scale(1, -1); // draw x and y axis drawAxis(g2, yAxis, true, w, unitWidth); drawAxis(g2, xAxis, false, h, unitHeight); axisPen.assignTo(g2); g2.drawLine(0, 0, w, 0); g2.drawLine(0, 0, 0, h); // draw data-sets g2.clipRect(0, 0, w + BORDER, h + BORDER); int idx = 0; for (final DiagramDataSet ds : dataSets) { if (!ds.isValid()) continue; ds.prepare(); ds.updateCache(); double xold = 0; double yold = 0; boolean first = true; final Pen pen = ds.isPenAutomatic() ? detectPen(idx) : ds.getPen(); pen.assignTo(g2); final int y0pos = (int) ds.valueToPixelY(0); for (final Point2D.Double pt : ds.getPoints()) { final double xpix = ds.valueToPixelX(pt.x); final double ypix = ds.valueToPixelY(pt.y); final double xpos = xAxis.isReversed() ? w - xpix : xpix; final double ypos = yAxis.isReversed() ? h - ypix : ypix; switch (ds.getType()) { case LineDiagram: if (!first) g2.drawLine((int) xold, (int) yold, (int) xpos, (int) ypos); break; case BarDiagram: g2.fillRect((int) xpos - 1, y0pos, 3, (int) (ypos - y0pos)); break; case ScatterPlotDiagram: g2.drawOval((int) xpos - 1, (int) ypos - 1, 2, 2); break; case IntersectionDiagram: g2.fillRect((int) xpos - 1, 0, 3, h); final int xp = (int) (xpos + pen.getStroke().getLineWidth() + 3); final String str = String.format("%f", pt.y); final Rectangle bounds = new Rectangle(xp, 2, w - xp, h - 4); drawText(g2, bounds, AlignH.Left, AlignV.Center, str); if (h >= 200) { drawText(g2, bounds, AlignH.Left, AlignV.Top, str); drawText(g2, bounds, AlignH.Left, AlignV.Bottom, str); } break; } xold = xpos; yold = ypos; first = false; } ++idx; } // draw legend g2.setFont(getFont().deriveFont(18f)); final int fh = Math.abs(g2.getFontMetrics().getHeight()); final int legendHeight = fh * dataSets.size() + 2; int legendWidth = 0; for (final DiagramDataSet ds : dataSets) legendWidth = Math.max(legendWidth, g2.getFontMetrics() .stringWidth(ds.getLabel())); legendWidth += 4; g2.setTransform(originalTransform); - g2.translate(getWidth() - BORDER - legendWidth + 1, BORDER + 1); + g2.translate(areaWidth - BORDER - legendWidth + 1, BORDER + 1); final Rectangle legendRect = new Rectangle(0, 0, legendWidth, legendHeight); g2.setPaint(new Color(backgroundColor.getRed(), backgroundColor .getGreen(), backgroundColor.getBlue(), 128)); g2.fill(legendRect); g2.setColor(Color.BLACK); g2.setStroke(new BasicStroke(2.0f)); g2.draw(legendRect); g2.clip(legendRect); idx = 0; legendRect.width -= 2; for (final DiagramDataSet ds : dataSets) { (ds.isPenAutomatic() ? detectPen(idx) : ds.getPen()).assignTo(g2); legendRect.y += fh; legendRect.height -= fh; drawText(g2, legendRect, AlignH.Right, AlignV.Bottom, ds.getLabel()); ++idx; } - g.drawImage(img, clip.x, clip.y, null); + g.drawImage(img, 0, 0, null); } private void drawText(final Graphics2D g2, final Rectangle bounds, final AlignH alignH, final AlignV alignV, final String str) { final float w; final float h; if (alignH == AlignH.Left && alignV == AlignV.Bottom) { w = 0; h = 0; } else { final Rectangle2D sb = g2.getFontMetrics().getStringBounds(str, g2); w = (float) sb.getWidth(); h = Math.abs(g2.getFontMetrics().getAscent()); // must be absolute because of possible negative scaling } final float x; final float y; switch (alignH) { case Left: x = bounds.x; break; case Center: x = bounds.x + (bounds.width - w) / 2; break; case Right: x = bounds.x + bounds.width - w; break; default: throw new IllegalArgumentException("AlignH constant unknown"); } switch (alignV) { case Top: y = bounds.y + bounds.height - h; break; case Center: y = bounds.y + (bounds.height - h) / 2; break; case Bottom: y = bounds.y; break; default: throw new IllegalArgumentException("AlignV constant unknown"); } final AffineTransform at = g2.getTransform(); final Point2D.Float p = (Point2D.Float) at.transform(new Point2D.Float( x, y), new Point2D.Float()); g2.setTransform(originalTransform); g2.drawString(str, p.x, p.y); g2.setTransform(at); } private void drawAxisLine(final Graphics2D g2, final boolean vertical, final double pos, final int len) { if (vertical) g2.drawLine(1, (int) pos, len - 1, (int) pos); else g2.drawLine((int) pos, 1, (int) pos, len - 1); } private void drawAxisText(final Graphics2D g2, final boolean vertical, final double pos, final int unitSpace, final double unitSize, final double val, final String unitName) { final double begin = pos - unitSize / 2; drawText(g2, vertical ? new Rectangle(-unitSpace, (int) begin, unitSpace, (int) unitSize) : new Rectangle((int) begin, -unitSpace, (int) unitSize, unitSpace), vertical ? AlignH.Right : AlignH.Center, vertical ? AlignV.Center : AlignV.Top, String .format("%.2f %s", val, unitName)); } private void drawAxis(final Graphics2D g2, final DiagramAxis axis, final boolean vertical, final int axisThickness, final int unitSpace) { final int spu = axis.getSubsPerUnit(); final int upg = axis.getCachedUnitsPerGrid(); final double ppg = axis.getCachedPixelPerGrid(); final double ppsg = axis.getCachedPixelPerSubGrid(); final boolean rev = axis.isReversed(); for (double u = axis.getCachedMinVisUnit(); u <= axis .getCachedMaxVisUnit(); u += upg) { unitPen.assignTo(g2); final double pos = axis.unitToPixel(u); drawAxisLine(g2, vertical, pos, axisThickness); drawAxisText(g2, vertical, pos, unitSpace, ppg, u, axis .getUnitName()); if (ppsg >= MIN_GRID_DELTA) { subUnitPen.assignTo(g2); for (int s = 1; s < spu; ++s) drawAxisLine(g2, vertical, rev ? pos - s * ppsg : pos + s * ppsg, axisThickness); } } } public Pen detectPen(final int idx) { final Color bc = backgroundColor; int v = (bc.getRed() + bc.getGreen() + bc.getBlue()) / 3; if (idx >= DEFAULT_COLORS.length) { v = v < 64 || v > 192 ? 255 - v : v < 128 ? 255 : 0; return new Pen(new Color(v, v, v), 2.0f); } return new Pen(v > 128 ? DEFAULT_COLORS[idx].makeDarker() : DEFAULT_COLORS[idx], 2.0f); } static int getDefaultColorCount() { return DEFAULT_COLORS.length; } static DefaultColor getDefaultColor(final int index) { return DEFAULT_COLORS[index]; } @Override public String getToolTipText(final MouseEvent event) { return null; } public JPopupMenu getMenu() { final JPopupMenu menu = new JPopupMenu(); JMenuItem item = new JMenuItem("Reset Zoom"); menu.add(item); item.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { setZoom(1.0); } }); item = new JMenuItem("Reset Scrolling"); menu.add(item); item.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { getXAxis().setOffset(0); getYAxis().setOffset(0); } }); xAxis.createMenu(menu); yAxis.createMenu(menu); for (final DiagramDataSet ds : dataSets) ds.createMenu(menu); return menu; } }
false
true
protected synchronized void paintComponent(final Graphics g) { final Rectangle clip = g.getClipBounds(); final BufferedImage img = new BufferedImage(clip.width, clip.height, BufferedImage.TYPE_INT_RGB); final Graphics2D g2 = img.createGraphics(); originalTransform = g2.getTransform(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setClip(0, 0, clip.width, clip.height); g2.setColor(backgroundColor); g2.fillRect(0, 0, clip.width, clip.height); g2.setFont(getFont().deriveFont(10f)); // cache y-axis dimension final int unitHeight = g2.getFontMetrics().getHeight(); final int h = getHeight() - 1 - unitHeight - BORDER; yAxis.updateCache(h); // cache x-axis dimension final int unitWidth1 = g2.getFontMetrics().stringWidth( String.format("%.2f %s", yAxis.getCachedMinVisUnit(), yAxis .getUnitName())); final int unitWidth2 = g2.getFontMetrics().stringWidth( String.format("%.2f %s", yAxis.getCachedMaxVisUnit(), yAxis .getUnitName())); final int unitWidth = Math.max(unitWidth1, unitWidth2); final int w = getWidth() - 1 - unitWidth - BORDER; xAxis.updateCache(w); g2.translate(unitWidth, getHeight() - unitHeight); g2.scale(1, -1); // draw x and y axis drawAxis(g2, yAxis, true, w, unitWidth); drawAxis(g2, xAxis, false, h, unitHeight); axisPen.assignTo(g2); g2.drawLine(0, 0, w, 0); g2.drawLine(0, 0, 0, h); // draw data-sets g2.clipRect(0, 0, w + BORDER, h + BORDER); int idx = 0; for (final DiagramDataSet ds : dataSets) { if (!ds.isValid()) continue; ds.prepare(); ds.updateCache(); double xold = 0; double yold = 0; boolean first = true; final Pen pen = ds.isPenAutomatic() ? detectPen(idx) : ds.getPen(); pen.assignTo(g2); final int y0pos = (int) ds.valueToPixelY(0); for (final Point2D.Double pt : ds.getPoints()) { final double xpix = ds.valueToPixelX(pt.x); final double ypix = ds.valueToPixelY(pt.y); final double xpos = xAxis.isReversed() ? w - xpix : xpix; final double ypos = yAxis.isReversed() ? h - ypix : ypix; switch (ds.getType()) { case LineDiagram: if (!first) g2.drawLine((int) xold, (int) yold, (int) xpos, (int) ypos); break; case BarDiagram: g2.fillRect((int) xpos - 1, y0pos, 3, (int) (ypos - y0pos)); break; case ScatterPlotDiagram: g2.drawOval((int) xpos - 1, (int) ypos - 1, 2, 2); break; case IntersectionDiagram: g2.fillRect((int) xpos - 1, 0, 3, h); final int xp = (int) (xpos + pen.getStroke().getLineWidth() + 3); final String str = String.format("%f", pt.y); final Rectangle bounds = new Rectangle(xp, 2, w - xp, h - 4); drawText(g2, bounds, AlignH.Left, AlignV.Center, str); if (h >= 200) { drawText(g2, bounds, AlignH.Left, AlignV.Top, str); drawText(g2, bounds, AlignH.Left, AlignV.Bottom, str); } break; } xold = xpos; yold = ypos; first = false; } ++idx; } // draw legend g2.setFont(getFont().deriveFont(18f)); final int fh = Math.abs(g2.getFontMetrics().getHeight()); final int legendHeight = fh * dataSets.size() + 2; int legendWidth = 0; for (final DiagramDataSet ds : dataSets) legendWidth = Math.max(legendWidth, g2.getFontMetrics() .stringWidth(ds.getLabel())); legendWidth += 4; g2.setTransform(originalTransform); g2.translate(getWidth() - BORDER - legendWidth + 1, BORDER + 1); final Rectangle legendRect = new Rectangle(0, 0, legendWidth, legendHeight); g2.setPaint(new Color(backgroundColor.getRed(), backgroundColor .getGreen(), backgroundColor.getBlue(), 128)); g2.fill(legendRect); g2.setColor(Color.BLACK); g2.setStroke(new BasicStroke(2.0f)); g2.draw(legendRect); g2.clip(legendRect); idx = 0; legendRect.width -= 2; for (final DiagramDataSet ds : dataSets) { (ds.isPenAutomatic() ? detectPen(idx) : ds.getPen()).assignTo(g2); legendRect.y += fh; legendRect.height -= fh; drawText(g2, legendRect, AlignH.Right, AlignV.Bottom, ds.getLabel()); ++idx; } g.drawImage(img, clip.x, clip.y, null); }
protected synchronized void paintComponent(final Graphics g) { final int areaWidth = getWidth(); final int areaHeight = getHeight(); final BufferedImage img = new BufferedImage(areaWidth, areaHeight, BufferedImage.TYPE_INT_RGB); final Graphics2D g2 = img.createGraphics(); originalTransform = g2.getTransform(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setClip(0, 0, areaWidth, areaHeight); g2.setColor(backgroundColor); g2.fillRect(0, 0, areaWidth, areaHeight); g2.setFont(getFont().deriveFont(10f)); // cache y-axis dimension final int unitHeight = g2.getFontMetrics().getHeight(); final int h = areaHeight - 1 - unitHeight - BORDER; yAxis.updateCache(h); // cache x-axis dimension final int unitWidth1 = g2.getFontMetrics().stringWidth( String.format("%.2f %s", yAxis.getCachedMinVisUnit(), yAxis .getUnitName())); final int unitWidth2 = g2.getFontMetrics().stringWidth( String.format("%.2f %s", yAxis.getCachedMaxVisUnit(), yAxis .getUnitName())); final int unitWidth = Math.max(unitWidth1, unitWidth2); final int w = areaWidth - 1 - unitWidth - BORDER; xAxis.updateCache(w); g2.translate(unitWidth, areaHeight - unitHeight); g2.scale(1, -1); // draw x and y axis drawAxis(g2, yAxis, true, w, unitWidth); drawAxis(g2, xAxis, false, h, unitHeight); axisPen.assignTo(g2); g2.drawLine(0, 0, w, 0); g2.drawLine(0, 0, 0, h); // draw data-sets g2.clipRect(0, 0, w + BORDER, h + BORDER); int idx = 0; for (final DiagramDataSet ds : dataSets) { if (!ds.isValid()) continue; ds.prepare(); ds.updateCache(); double xold = 0; double yold = 0; boolean first = true; final Pen pen = ds.isPenAutomatic() ? detectPen(idx) : ds.getPen(); pen.assignTo(g2); final int y0pos = (int) ds.valueToPixelY(0); for (final Point2D.Double pt : ds.getPoints()) { final double xpix = ds.valueToPixelX(pt.x); final double ypix = ds.valueToPixelY(pt.y); final double xpos = xAxis.isReversed() ? w - xpix : xpix; final double ypos = yAxis.isReversed() ? h - ypix : ypix; switch (ds.getType()) { case LineDiagram: if (!first) g2.drawLine((int) xold, (int) yold, (int) xpos, (int) ypos); break; case BarDiagram: g2.fillRect((int) xpos - 1, y0pos, 3, (int) (ypos - y0pos)); break; case ScatterPlotDiagram: g2.drawOval((int) xpos - 1, (int) ypos - 1, 2, 2); break; case IntersectionDiagram: g2.fillRect((int) xpos - 1, 0, 3, h); final int xp = (int) (xpos + pen.getStroke().getLineWidth() + 3); final String str = String.format("%f", pt.y); final Rectangle bounds = new Rectangle(xp, 2, w - xp, h - 4); drawText(g2, bounds, AlignH.Left, AlignV.Center, str); if (h >= 200) { drawText(g2, bounds, AlignH.Left, AlignV.Top, str); drawText(g2, bounds, AlignH.Left, AlignV.Bottom, str); } break; } xold = xpos; yold = ypos; first = false; } ++idx; } // draw legend g2.setFont(getFont().deriveFont(18f)); final int fh = Math.abs(g2.getFontMetrics().getHeight()); final int legendHeight = fh * dataSets.size() + 2; int legendWidth = 0; for (final DiagramDataSet ds : dataSets) legendWidth = Math.max(legendWidth, g2.getFontMetrics() .stringWidth(ds.getLabel())); legendWidth += 4; g2.setTransform(originalTransform); g2.translate(areaWidth - BORDER - legendWidth + 1, BORDER + 1); final Rectangle legendRect = new Rectangle(0, 0, legendWidth, legendHeight); g2.setPaint(new Color(backgroundColor.getRed(), backgroundColor .getGreen(), backgroundColor.getBlue(), 128)); g2.fill(legendRect); g2.setColor(Color.BLACK); g2.setStroke(new BasicStroke(2.0f)); g2.draw(legendRect); g2.clip(legendRect); idx = 0; legendRect.width -= 2; for (final DiagramDataSet ds : dataSets) { (ds.isPenAutomatic() ? detectPen(idx) : ds.getPen()).assignTo(g2); legendRect.y += fh; legendRect.height -= fh; drawText(g2, legendRect, AlignH.Right, AlignV.Bottom, ds.getLabel()); ++idx; } g.drawImage(img, 0, 0, null); }
diff --git a/org.emftext.sdk.ui/src/org/emftext/sdk/ui/jobs/CreateNewEMFTextProjectJob.java b/org.emftext.sdk.ui/src/org/emftext/sdk/ui/jobs/CreateNewEMFTextProjectJob.java index aea140044..0cf6b64b2 100644 --- a/org.emftext.sdk.ui/src/org/emftext/sdk/ui/jobs/CreateNewEMFTextProjectJob.java +++ b/org.emftext.sdk.ui/src/org/emftext/sdk/ui/jobs/CreateNewEMFTextProjectJob.java @@ -1,131 +1,131 @@ /******************************************************************************* * Copyright (c) 2006-2011 * Software Technology Group, Dresden University of Technology * * 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: * Software Technology Group - TU Dresden, Germany * - initial API and implementation ******************************************************************************/ package org.emftext.sdk.ui.jobs; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.jdt.core.JavaCore; import org.emftext.sdk.EMFTextSDKPlugin; import org.emftext.sdk.IPluginDescriptor; import org.emftext.sdk.codegen.AbstractCreatePluginJob; import org.emftext.sdk.codegen.GenerationProblem; import org.emftext.sdk.codegen.IProblemCollector; import org.emftext.sdk.codegen.IResourceMarker; import org.emftext.sdk.codegen.newproject.NewProjectGenerationContext; import org.emftext.sdk.codegen.newproject.NewProjectParameters; import org.emftext.sdk.codegen.newproject.creators.NewProjectContentsCreator; import org.emftext.sdk.codegen.resource.GenerationContext; /** * An Eclipse job that create a new EMFText project. This job runs when using the * EMFText New Project Wizard. */ public class CreateNewEMFTextProjectJob extends AbstractCreatePluginJob { private NewProjectParameters parameters; private IResourceMarker resourceMarker; public CreateNewEMFTextProjectJob(NewProjectParameters parameters, IResourceMarker resourceMarker) { super(); this.parameters = parameters; this.resourceMarker = resourceMarker; } public void run(IProgressMonitor monitor2) throws Exception { SubMonitor progress = SubMonitor.convert(monitor2, 100); final List<GenerationProblem> problems = new ArrayList<GenerationProblem>(); final IProblemCollector problemCollector = new IProblemCollector() { public void addProblem(GenerationProblem problem) { problems.add(problem); } }; final String newProjectName = parameters.getProjectName(); IPluginDescriptor newProjectPlugin = new IPluginDescriptor() { public String getName() { return newProjectName; } }; IProject project = createProject(progress.newChild(2), newProjectPlugin, parameters.getProjectName()); NewProjectGenerationContext context = new NewProjectGenerationContext(new WorkspaceConnector(), problemCollector, project, newProjectPlugin, parameters); context.setMonitor(progress.newChild(92)); context.setResourceMarker(resourceMarker); new NewProjectContentsCreator().create(newProjectPlugin, context, null, null); refresh(progress.newChild(2), project, "new project"); GenerationContext generationContext = context.getGenerationContext(); String resourcePluginName = generationContext.getResourcePlugin().getName(); if (resourcePluginName != null) { refresh(progress.newChild(2), getProject(resourcePluginName), "resource plug-in"); } String resourceUIPluginName = generationContext.getResourceUIPlugin().getName(); if (resourceUIPluginName != null) { refresh(progress.newChild(2), getProject(resourceUIPluginName), "resource UI plug-in"); } String antrlPluginName = generationContext.getAntlrPlugin().getName(); - if (resourceUIPluginName != null) { + if (antrlPluginName != null) { refresh(progress.newChild(2), getProject(antrlPluginName), "ANTLR plug-in"); } // write problems to error log for (GenerationProblem problem : problems) { int severity = problem.getSeverity() == GenerationProblem.Severity.WARNING ? IStatus.WARNING : IStatus.ERROR; String message = problem.getMessage(); EMFTextSDKPlugin.logProblem(severity, message, null); } } public IProject createProject(IProgressMonitor progress, IPluginDescriptor plugin, String pluginName) throws Exception { progress.beginTask("Creating project", 2); IProject getProject = getProject(pluginName); IProject project = getProject; if (!project.exists()) { project.create(new NullProgressMonitor()); } project.open(new NullProgressMonitor()); if (!project.hasNature(JavaCore.NATURE_ID)) { try { IProjectDescription descriptions = project.getDescription(); String[] oldIds = descriptions.getNatureIds(); String[] newIds = new String[oldIds.length + 1]; System.arraycopy(oldIds, 0, newIds, 0, oldIds.length); newIds[oldIds.length] = JavaCore.NATURE_ID; descriptions.setNatureIds(newIds); project.setDescription(descriptions, null); } catch (CoreException e) { EMFTextSDKPlugin.logWarning("Could not add Java nature to project " + project, e); } } progress.worked(1); JavaCore.create(project); progress.worked(1); return project; } private IProject getProject(String pluginName) { return ResourcesPlugin.getWorkspace().getRoot().getProject(pluginName); } }
true
true
public void run(IProgressMonitor monitor2) throws Exception { SubMonitor progress = SubMonitor.convert(monitor2, 100); final List<GenerationProblem> problems = new ArrayList<GenerationProblem>(); final IProblemCollector problemCollector = new IProblemCollector() { public void addProblem(GenerationProblem problem) { problems.add(problem); } }; final String newProjectName = parameters.getProjectName(); IPluginDescriptor newProjectPlugin = new IPluginDescriptor() { public String getName() { return newProjectName; } }; IProject project = createProject(progress.newChild(2), newProjectPlugin, parameters.getProjectName()); NewProjectGenerationContext context = new NewProjectGenerationContext(new WorkspaceConnector(), problemCollector, project, newProjectPlugin, parameters); context.setMonitor(progress.newChild(92)); context.setResourceMarker(resourceMarker); new NewProjectContentsCreator().create(newProjectPlugin, context, null, null); refresh(progress.newChild(2), project, "new project"); GenerationContext generationContext = context.getGenerationContext(); String resourcePluginName = generationContext.getResourcePlugin().getName(); if (resourcePluginName != null) { refresh(progress.newChild(2), getProject(resourcePluginName), "resource plug-in"); } String resourceUIPluginName = generationContext.getResourceUIPlugin().getName(); if (resourceUIPluginName != null) { refresh(progress.newChild(2), getProject(resourceUIPluginName), "resource UI plug-in"); } String antrlPluginName = generationContext.getAntlrPlugin().getName(); if (resourceUIPluginName != null) { refresh(progress.newChild(2), getProject(antrlPluginName), "ANTLR plug-in"); } // write problems to error log for (GenerationProblem problem : problems) { int severity = problem.getSeverity() == GenerationProblem.Severity.WARNING ? IStatus.WARNING : IStatus.ERROR; String message = problem.getMessage(); EMFTextSDKPlugin.logProblem(severity, message, null); } }
public void run(IProgressMonitor monitor2) throws Exception { SubMonitor progress = SubMonitor.convert(monitor2, 100); final List<GenerationProblem> problems = new ArrayList<GenerationProblem>(); final IProblemCollector problemCollector = new IProblemCollector() { public void addProblem(GenerationProblem problem) { problems.add(problem); } }; final String newProjectName = parameters.getProjectName(); IPluginDescriptor newProjectPlugin = new IPluginDescriptor() { public String getName() { return newProjectName; } }; IProject project = createProject(progress.newChild(2), newProjectPlugin, parameters.getProjectName()); NewProjectGenerationContext context = new NewProjectGenerationContext(new WorkspaceConnector(), problemCollector, project, newProjectPlugin, parameters); context.setMonitor(progress.newChild(92)); context.setResourceMarker(resourceMarker); new NewProjectContentsCreator().create(newProjectPlugin, context, null, null); refresh(progress.newChild(2), project, "new project"); GenerationContext generationContext = context.getGenerationContext(); String resourcePluginName = generationContext.getResourcePlugin().getName(); if (resourcePluginName != null) { refresh(progress.newChild(2), getProject(resourcePluginName), "resource plug-in"); } String resourceUIPluginName = generationContext.getResourceUIPlugin().getName(); if (resourceUIPluginName != null) { refresh(progress.newChild(2), getProject(resourceUIPluginName), "resource UI plug-in"); } String antrlPluginName = generationContext.getAntlrPlugin().getName(); if (antrlPluginName != null) { refresh(progress.newChild(2), getProject(antrlPluginName), "ANTLR plug-in"); } // write problems to error log for (GenerationProblem problem : problems) { int severity = problem.getSeverity() == GenerationProblem.Severity.WARNING ? IStatus.WARNING : IStatus.ERROR; String message = problem.getMessage(); EMFTextSDKPlugin.logProblem(severity, message, null); } }
diff --git a/src/pg13/presentation/LoginScreen.java b/src/pg13/presentation/LoginScreen.java index 8e5594b..fe2a6b7 100644 --- a/src/pg13/presentation/LoginScreen.java +++ b/src/pg13/presentation/LoginScreen.java @@ -1,157 +1,157 @@ package pg13.presentation; import java.util.ArrayList; import org.eclipse.jface.fieldassist.ControlDecoration; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import pg13.org.eclipse.wb.swt.SWTResourceManager; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import pg13.business.UserManager; import pg13.models.User; public class LoginScreen extends Composite { private UserManager userManager; private Combo cmbUsernames; private Label lblInvalidUser; private ControlDecoration invalidUserDecor; /** * Create and populates the login screen. * @param parent * @param style */ public LoginScreen(Composite parent, int style) { super(parent, style); userManager = new UserManager(); setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); setLayout(new FormLayout()); cmbUsernames = new Combo(this, SWT.READ_ONLY); cmbUsernames.setFont(SWTResourceManager.getFont("Segoe UI", 14, SWT.NORMAL)); populateUserList(); FormData fd_cmbUsernames = new FormData(); fd_cmbUsernames.top = new FormAttachment(0, 200); fd_cmbUsernames.left = new FormAttachment(50, -100); fd_cmbUsernames.bottom = new FormAttachment(100, -69); fd_cmbUsernames.right = new FormAttachment(50, 100); cmbUsernames.setLayoutData(fd_cmbUsernames); lblInvalidUser = new Label(this, SWT.WRAP); lblInvalidUser.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED)); lblInvalidUser.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); lblInvalidUser.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL)); FormData fd_lblInvalidUser = new FormData(); fd_lblInvalidUser.right = new FormAttachment(50, 100); fd_lblInvalidUser.left = new FormAttachment(50, -100); fd_lblInvalidUser.top = new FormAttachment(0, 250); lblInvalidUser.setLayoutData(fd_lblInvalidUser); lblInvalidUser.setText(MessageConstants.BLANK_USERNAME); lblInvalidUser.setVisible(false); Label lblLoginInfo = new Label(this, SWT.WRAP | SWT.SHADOW_IN); lblLoginInfo.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL)); lblLoginInfo.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); FormData fd_lblLoginInfo = new FormData(); fd_lblLoginInfo.top = new FormAttachment(0, 75); fd_lblLoginInfo.bottom = new FormAttachment(0, 175); fd_lblLoginInfo.left = new FormAttachment(0, 162); fd_lblLoginInfo.right = new FormAttachment(100, -162); lblLoginInfo.setLayoutData(fd_lblLoginInfo); lblLoginInfo.setText(MessageConstants.LOGIN_INFO); Button btnLogMeIn = new Button(this, SWT.NONE); FormData fd_btnLogMeIn = new FormData(); fd_btnLogMeIn.left = new FormAttachment(50, -100); fd_btnLogMeIn.top = new FormAttachment(0, 300); btnLogMeIn.setLayoutData(fd_btnLogMeIn); invalidUserDecor = new ControlDecoration(lblInvalidUser, SWT.LEFT | SWT.TOP); invalidUserDecor.setMarginWidth(10); - invalidUserDecor.setImage(org.eclipse.wb.swt.SWTResourceManager.getImage(LoginScreen.class, "/javax/swing/plaf/metal/icons/Error.gif")); + invalidUserDecor.setImage(SWTResourceManager.getImage(SignUpScreen.class, "/javax/swing/plaf/metal/icons/Error.gif")); invalidUserDecor.setDescriptionText("Some description"); btnLogMeIn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { loginPressed(); } }); btnLogMeIn.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); btnLogMeIn.setText(Constants.LOGIN_BUTTON); Button btnCancel = new Button(this, SWT.NONE); FormData fd_btnCancel = new FormData(); fd_btnCancel.right = new FormAttachment(50, 100); fd_btnCancel.top = new FormAttachment(0, 300); btnCancel.setLayoutData(fd_btnCancel); btnCancel.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clearScreen(); MainWindow.getInstance().switchToWelcomeScreen(); } }); btnCancel.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); btnCancel.setText(Constants.CANCEL_BUTTON); } private void populateUserList() { //convert arraylist of users from db to an array of strings String [] users = new String [userManager.getNamesOfAllUsers().size()]; userManager.getNamesOfAllUsers().toArray(users); cmbUsernames.setItems(users); } public void refresh() { populateUserList(); } private void loginPressed() { ArrayList<User> allUsers = userManager.getAllUsers(); int selected = this.cmbUsernames.getSelectionIndex(); if(selected >= 0) { clearScreen(); MainWindow.getInstance().login(allUsers.get(selected)); MainWindow.getInstance().switchToWelcomeScreen(); } else //-1 it's blank, lets show an error message { lblInvalidUser.setVisible(true); this.redraw(); } } private void clearScreen() { lblInvalidUser.setVisible(false); } @Override protected void checkSubclass() { // Disable the check that prevents subclassing of SWT components } }
true
true
public LoginScreen(Composite parent, int style) { super(parent, style); userManager = new UserManager(); setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); setLayout(new FormLayout()); cmbUsernames = new Combo(this, SWT.READ_ONLY); cmbUsernames.setFont(SWTResourceManager.getFont("Segoe UI", 14, SWT.NORMAL)); populateUserList(); FormData fd_cmbUsernames = new FormData(); fd_cmbUsernames.top = new FormAttachment(0, 200); fd_cmbUsernames.left = new FormAttachment(50, -100); fd_cmbUsernames.bottom = new FormAttachment(100, -69); fd_cmbUsernames.right = new FormAttachment(50, 100); cmbUsernames.setLayoutData(fd_cmbUsernames); lblInvalidUser = new Label(this, SWT.WRAP); lblInvalidUser.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED)); lblInvalidUser.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); lblInvalidUser.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL)); FormData fd_lblInvalidUser = new FormData(); fd_lblInvalidUser.right = new FormAttachment(50, 100); fd_lblInvalidUser.left = new FormAttachment(50, -100); fd_lblInvalidUser.top = new FormAttachment(0, 250); lblInvalidUser.setLayoutData(fd_lblInvalidUser); lblInvalidUser.setText(MessageConstants.BLANK_USERNAME); lblInvalidUser.setVisible(false); Label lblLoginInfo = new Label(this, SWT.WRAP | SWT.SHADOW_IN); lblLoginInfo.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL)); lblLoginInfo.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); FormData fd_lblLoginInfo = new FormData(); fd_lblLoginInfo.top = new FormAttachment(0, 75); fd_lblLoginInfo.bottom = new FormAttachment(0, 175); fd_lblLoginInfo.left = new FormAttachment(0, 162); fd_lblLoginInfo.right = new FormAttachment(100, -162); lblLoginInfo.setLayoutData(fd_lblLoginInfo); lblLoginInfo.setText(MessageConstants.LOGIN_INFO); Button btnLogMeIn = new Button(this, SWT.NONE); FormData fd_btnLogMeIn = new FormData(); fd_btnLogMeIn.left = new FormAttachment(50, -100); fd_btnLogMeIn.top = new FormAttachment(0, 300); btnLogMeIn.setLayoutData(fd_btnLogMeIn); invalidUserDecor = new ControlDecoration(lblInvalidUser, SWT.LEFT | SWT.TOP); invalidUserDecor.setMarginWidth(10); invalidUserDecor.setImage(org.eclipse.wb.swt.SWTResourceManager.getImage(LoginScreen.class, "/javax/swing/plaf/metal/icons/Error.gif")); invalidUserDecor.setDescriptionText("Some description"); btnLogMeIn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { loginPressed(); } }); btnLogMeIn.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); btnLogMeIn.setText(Constants.LOGIN_BUTTON); Button btnCancel = new Button(this, SWT.NONE); FormData fd_btnCancel = new FormData(); fd_btnCancel.right = new FormAttachment(50, 100); fd_btnCancel.top = new FormAttachment(0, 300); btnCancel.setLayoutData(fd_btnCancel); btnCancel.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clearScreen(); MainWindow.getInstance().switchToWelcomeScreen(); } }); btnCancel.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); btnCancel.setText(Constants.CANCEL_BUTTON); }
public LoginScreen(Composite parent, int style) { super(parent, style); userManager = new UserManager(); setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); setLayout(new FormLayout()); cmbUsernames = new Combo(this, SWT.READ_ONLY); cmbUsernames.setFont(SWTResourceManager.getFont("Segoe UI", 14, SWT.NORMAL)); populateUserList(); FormData fd_cmbUsernames = new FormData(); fd_cmbUsernames.top = new FormAttachment(0, 200); fd_cmbUsernames.left = new FormAttachment(50, -100); fd_cmbUsernames.bottom = new FormAttachment(100, -69); fd_cmbUsernames.right = new FormAttachment(50, 100); cmbUsernames.setLayoutData(fd_cmbUsernames); lblInvalidUser = new Label(this, SWT.WRAP); lblInvalidUser.setForeground(SWTResourceManager.getColor(SWT.COLOR_RED)); lblInvalidUser.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); lblInvalidUser.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL)); FormData fd_lblInvalidUser = new FormData(); fd_lblInvalidUser.right = new FormAttachment(50, 100); fd_lblInvalidUser.left = new FormAttachment(50, -100); fd_lblInvalidUser.top = new FormAttachment(0, 250); lblInvalidUser.setLayoutData(fd_lblInvalidUser); lblInvalidUser.setText(MessageConstants.BLANK_USERNAME); lblInvalidUser.setVisible(false); Label lblLoginInfo = new Label(this, SWT.WRAP | SWT.SHADOW_IN); lblLoginInfo.setFont(SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL)); lblLoginInfo.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE)); FormData fd_lblLoginInfo = new FormData(); fd_lblLoginInfo.top = new FormAttachment(0, 75); fd_lblLoginInfo.bottom = new FormAttachment(0, 175); fd_lblLoginInfo.left = new FormAttachment(0, 162); fd_lblLoginInfo.right = new FormAttachment(100, -162); lblLoginInfo.setLayoutData(fd_lblLoginInfo); lblLoginInfo.setText(MessageConstants.LOGIN_INFO); Button btnLogMeIn = new Button(this, SWT.NONE); FormData fd_btnLogMeIn = new FormData(); fd_btnLogMeIn.left = new FormAttachment(50, -100); fd_btnLogMeIn.top = new FormAttachment(0, 300); btnLogMeIn.setLayoutData(fd_btnLogMeIn); invalidUserDecor = new ControlDecoration(lblInvalidUser, SWT.LEFT | SWT.TOP); invalidUserDecor.setMarginWidth(10); invalidUserDecor.setImage(SWTResourceManager.getImage(SignUpScreen.class, "/javax/swing/plaf/metal/icons/Error.gif")); invalidUserDecor.setDescriptionText("Some description"); btnLogMeIn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { loginPressed(); } }); btnLogMeIn.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); btnLogMeIn.setText(Constants.LOGIN_BUTTON); Button btnCancel = new Button(this, SWT.NONE); FormData fd_btnCancel = new FormData(); fd_btnCancel.right = new FormAttachment(50, 100); fd_btnCancel.top = new FormAttachment(0, 300); btnCancel.setLayoutData(fd_btnCancel); btnCancel.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { clearScreen(); MainWindow.getInstance().switchToWelcomeScreen(); } }); btnCancel.setFont(SWTResourceManager.getFont("Segoe UI", 11, SWT.NORMAL)); btnCancel.setText(Constants.CANCEL_BUTTON); }
diff --git a/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/tests/InteractionEventExternalizationTest.java b/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/tests/InteractionEventExternalizationTest.java index 087fb0c5..53278467 100644 --- a/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/tests/InteractionEventExternalizationTest.java +++ b/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/tests/InteractionEventExternalizationTest.java @@ -1,77 +1,78 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 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.monitor.tests; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.eclipse.mylar.context.tests.AbstractContextTest; import org.eclipse.mylar.internal.core.util.XmlStringConverter; import org.eclipse.mylar.internal.monitor.usage.InteractionEventLogger; import org.eclipse.mylar.internal.monitor.usage.MylarMonitorPreferenceConstants; import org.eclipse.mylar.internal.monitor.usage.MylarUsageMonitorPlugin; import org.eclipse.mylar.monitor.core.InteractionEvent; /** * @author Mik Kersten */ public class InteractionEventExternalizationTest extends AbstractContextTest { private static final String PATH = "test-log.xml"; public void testXmlStringConversion() { String testStrings[] = { "single", "simple string with spaces", "<embedded-xml>", "<more complicated=\"xml\"><example with='comp:licated'/></more>", "<embedded>\rcarriage-returns\nnewlines\tand tabs" }; for(String s : testStrings) { assertEquals(s, XmlStringConverter.convertXmlToString(XmlStringConverter.convertToXmlString(s))); } } public void testManualExternalization() throws IOException { MylarUsageMonitorPlugin.getPrefs().setValue(MylarMonitorPreferenceConstants.PREF_MONITORING_OBFUSCATE, false); List<InteractionEvent> events = new ArrayList<InteractionEvent>(); File f = new File(PATH); if (f.exists()) { f.delete(); } InteractionEventLogger logger = new InteractionEventLogger(f); logger.clearInteractionHistory(); logger.startMonitoring(); String handle = ""; for (int i = 0; i < 100; i++) { handle += "1"; InteractionEvent event = new InteractionEvent(InteractionEvent.Kind.SELECTION, "structureKind", handle, "originId", "navigatedRelation", "delta", 2f, new Date(), new Date()); events.add(event); logger.interactionObserved(event); } logger.stopMonitoring(); - File infile = new File(PATH); + File infile = new File(PATH); List<InteractionEvent> readEvents = logger.getHistoryFromFile(infile); for (int i = 0; i < events.size(); i++) { // NOTE: shouldn't use toString(), but get timezone failures assertEquals(events.get(i), readEvents.get(i)); // assertEquals(events.get(i), readEvents.get(i)); } + infile.delete(); MylarUsageMonitorPlugin.getPrefs().setValue(MylarMonitorPreferenceConstants.PREF_MONITORING_OBFUSCATE, true); } }
false
true
public void testManualExternalization() throws IOException { MylarUsageMonitorPlugin.getPrefs().setValue(MylarMonitorPreferenceConstants.PREF_MONITORING_OBFUSCATE, false); List<InteractionEvent> events = new ArrayList<InteractionEvent>(); File f = new File(PATH); if (f.exists()) { f.delete(); } InteractionEventLogger logger = new InteractionEventLogger(f); logger.clearInteractionHistory(); logger.startMonitoring(); String handle = ""; for (int i = 0; i < 100; i++) { handle += "1"; InteractionEvent event = new InteractionEvent(InteractionEvent.Kind.SELECTION, "structureKind", handle, "originId", "navigatedRelation", "delta", 2f, new Date(), new Date()); events.add(event); logger.interactionObserved(event); } logger.stopMonitoring(); File infile = new File(PATH); List<InteractionEvent> readEvents = logger.getHistoryFromFile(infile); for (int i = 0; i < events.size(); i++) { // NOTE: shouldn't use toString(), but get timezone failures assertEquals(events.get(i), readEvents.get(i)); // assertEquals(events.get(i), readEvents.get(i)); } MylarUsageMonitorPlugin.getPrefs().setValue(MylarMonitorPreferenceConstants.PREF_MONITORING_OBFUSCATE, true); }
public void testManualExternalization() throws IOException { MylarUsageMonitorPlugin.getPrefs().setValue(MylarMonitorPreferenceConstants.PREF_MONITORING_OBFUSCATE, false); List<InteractionEvent> events = new ArrayList<InteractionEvent>(); File f = new File(PATH); if (f.exists()) { f.delete(); } InteractionEventLogger logger = new InteractionEventLogger(f); logger.clearInteractionHistory(); logger.startMonitoring(); String handle = ""; for (int i = 0; i < 100; i++) { handle += "1"; InteractionEvent event = new InteractionEvent(InteractionEvent.Kind.SELECTION, "structureKind", handle, "originId", "navigatedRelation", "delta", 2f, new Date(), new Date()); events.add(event); logger.interactionObserved(event); } logger.stopMonitoring(); File infile = new File(PATH); List<InteractionEvent> readEvents = logger.getHistoryFromFile(infile); for (int i = 0; i < events.size(); i++) { // NOTE: shouldn't use toString(), but get timezone failures assertEquals(events.get(i), readEvents.get(i)); // assertEquals(events.get(i), readEvents.get(i)); } infile.delete(); MylarUsageMonitorPlugin.getPrefs().setValue(MylarMonitorPreferenceConstants.PREF_MONITORING_OBFUSCATE, true); }
diff --git a/src/org/oscim/theme/MatchingCacheKey.java b/src/org/oscim/theme/MatchingCacheKey.java index 24e2b1b4..a73d056a 100644 --- a/src/org/oscim/theme/MatchingCacheKey.java +++ b/src/org/oscim/theme/MatchingCacheKey.java @@ -1,89 +1,89 @@ /* * Copyright 2010, 2011, 2012 mapsforge.org * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package org.oscim.theme; import org.oscim.core.Tag; class MatchingCacheKey { int mHash; Tag[] mTags; MatchingCacheKey() { } MatchingCacheKey(MatchingCacheKey key) { // need to clone tags as they belong to MapDatabase mTags = key.mTags.clone(); mHash = key.mHash; } // set temporary values for comparison boolean set(Tag[] tags, MatchingCacheKey compare) { int length = tags.length; - if (compare != null && length == mTags.length) { + if (compare != null && length == compare.mTags.length) { int i = 0; for (; i < length; i++) { Tag t1 = tags[i]; Tag t2 = compare.mTags[i]; if (!(t1 == t2 || (t1.key == t2.key && t1.value == t2.value))) break; } if (i == length) return true; } int result = 7; for (int i = 0; i < length; i++) result = 31 * result + tags[i].hashCode(); mHash = 31 * result; mTags = tags; return false; } @Override public boolean equals(Object obj) { if (this == obj) return true; MatchingCacheKey other = (MatchingCacheKey) obj; // if (mTags == null) { // return (other.mTags == null); // } else if (other.mTags == null) // return false; int length = mTags.length; if (length != other.mTags.length) return false; for (int i = 0; i < length; i++) { Tag t1 = mTags[i]; Tag t2 = other.mTags[i]; if (!(t1 == t2 || (t1.key == t2.key && t1.value == t2.value))) return false; } return true; } @Override public int hashCode() { return mHash; } }
true
true
boolean set(Tag[] tags, MatchingCacheKey compare) { int length = tags.length; if (compare != null && length == mTags.length) { int i = 0; for (; i < length; i++) { Tag t1 = tags[i]; Tag t2 = compare.mTags[i]; if (!(t1 == t2 || (t1.key == t2.key && t1.value == t2.value))) break; } if (i == length) return true; } int result = 7; for (int i = 0; i < length; i++) result = 31 * result + tags[i].hashCode(); mHash = 31 * result; mTags = tags; return false; }
boolean set(Tag[] tags, MatchingCacheKey compare) { int length = tags.length; if (compare != null && length == compare.mTags.length) { int i = 0; for (; i < length; i++) { Tag t1 = tags[i]; Tag t2 = compare.mTags[i]; if (!(t1 == t2 || (t1.key == t2.key && t1.value == t2.value))) break; } if (i == length) return true; } int result = 7; for (int i = 0; i < length; i++) result = 31 * result + tags[i].hashCode(); mHash = 31 * result; mTags = tags; return false; }
diff --git a/src/net/gumbercules/loot/RepeatSchedule.java b/src/net/gumbercules/loot/RepeatSchedule.java index b512525..a1e8879 100644 --- a/src/net/gumbercules/loot/RepeatSchedule.java +++ b/src/net/gumbercules/loot/RepeatSchedule.java @@ -1,851 +1,853 @@ package net.gumbercules.loot; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.ArrayList; import android.content.ContentValues; import android.database.*; import android.database.sqlite.*; public class RepeatSchedule implements Cloneable { public static final String KEY_ID = "rs_id"; public static final String KEY_ITER = "key_iter"; public static final String KEY_FREQ = "key_freq"; public static final String KEY_CUSTOM = "key_custom"; public static final String KEY_DATE = "key_date"; // repetition iterator type public static final int NO_REPEAT = 0; public static final int DAILY = 1; public static final int WEEKLY = 2; public static final int MONTHLY = 3; public static final int YEARLY = 4; // custom weekly repetition public static final int SUNDAY = 1 << 0; public static final int MONDAY = 1 << 1; public static final int TUESDAY = 1 << 2; public static final int WEDNESDAY = 1 << 3; public static final int THURSDAY = 1 << 4; public static final int FRIDAY = 1 << 5; public static final int SATURDAY = 1 << 6; // custom monthly repetition public static final int DAY = 0; public static final int DATE = 1; int iter; // repetition iterator type int freq; // number between repetitions int custom; // used only for custom types Date start; // start date Date end; // end date private Date due; // date of the next repetition private int id; // id of the database repeat_pattern, if available public RepeatSchedule() { this.id = -1; this.due = null; this.start = null; this.end = null; this.iter = NO_REPEAT; this.freq = -1; this.custom = -1; } public RepeatSchedule( int it, int fr, int cu, Date st, Date en ) { this.id = -1; this.due = null; this.iter = it; this.freq = fr; this.custom = cu; this.start = st; this.end = en; } public int id() { return id; } protected Object clone() throws CloneNotSupportedException { return super.clone(); } public int write(int trans_id) { this.due = this.calculateDueDate(); if (this.due == null || this.start == null) { if (this.id > 0) this.erase(true); return -1; } if (this.id == -1) return newRepeat(trans_id); else return updateRepeat(trans_id); } private int newRepeat(int trans_id) { // check the database to make sure that we don't get stuck in an infinite loop // of constantly writing a new repeat schedule for the transfer links int repeat_id = RepeatSchedule.getRepeatId(trans_id); if (repeat_id != -1) return repeat_id; long start_time = this.start.getTime(), end_time = 0; try { end_time = this.end.getTime(); } catch (Exception e) { } String insert = "insert into repeat_pattern (start_date,end_date,iterator,frequency," + "custom,due) values (" + start_time + "," + end_time + "," + this.iter + "," + this.freq + "," + this.custom + "," + this.due.getTime() + ")"; SQLiteDatabase lootDB = Database.getDatabase(); lootDB.beginTransaction(); try { lootDB.execSQL(insert); } catch (SQLException e) { lootDB.endTransaction(); return -1; } String[] columns = {"max(id)"}; Cursor cur = lootDB.query("repeat_pattern", columns, null, null, null, null, null); if (!cur.moveToFirst()) { cur.close(); lootDB.endTransaction(); return -1; } this.id = cur.getInt(0); cur.close(); if (!this.writeTransactionToRepeatTable(trans_id)) { lootDB.endTransaction(); return -1; } Transaction trans = Transaction.getTransactionById(trans_id, true); int trans_id2 = trans.getTransferId(); if (trans_id2 > 0) { try { RepeatSchedule repeat2 = (RepeatSchedule) this.clone(); repeat2.id = -1; if (repeat2.write(trans_id2) == -1) { lootDB.endTransaction(); return -1; } } catch (CloneNotSupportedException e) { lootDB.endTransaction(); return -1; } } lootDB.setTransactionSuccessful(); lootDB.endTransaction(); return this.id; } private int updateRepeat(int trans_id) { if (this.iter == NO_REPEAT) { this.erase(true); return -1; } long end_time = 0; try { end_time = this.end.getTime(); } catch (Exception e) { } Transaction trans = Transaction.getTransactionById(trans_id, true); int trans_id2 = trans.getTransferId(); int repeat_id2 = -1; if (trans_id2 > 0) repeat_id2 = RepeatSchedule.getRepeatId(trans_id2); String update = "update repeat_pattern set start_date = " + this.start.getTime() + ", end_date = " + end_time + ", iterator = " + this.iter + ", frequency = " + this.freq + ", custom = " + this.custom + ", due = " + this.due.getTime() + " where id = " + this.id; if (repeat_id2 != -1) update += " or id = " + repeat_id2; SQLiteDatabase lootDB = Database.getDatabase(); lootDB.beginTransaction(); try { lootDB.execSQL(update); } catch (SQLException e) { lootDB.endTransaction(); return -1; } // instead of trying to update the row, delete it and copy over the updated transaction if (!this.eraseTransactionFromRepeatTable(repeat_id2)) { lootDB.endTransaction(); } if (trans_id2 != -1) { RepeatSchedule repeat2 = RepeatSchedule.getSchedule(repeat_id2); if (!this.writeTransactionToRepeatTable(trans_id) || !repeat2.writeTransactionToRepeatTable(trans_id2)) { lootDB.endTransaction(); return -1; } } else { if (!this.writeTransactionToRepeatTable(trans_id)) { lootDB.endTransaction(); return -1; } } lootDB.setTransactionSuccessful(); lootDB.endTransaction(); return this.id; } public boolean erase(boolean eraseTransfers) { Transaction trans = Transaction.getTransactionById(this.getTransactionId(), true); int repeat_id2 = -1; if (eraseTransfers) { int trans_id2 = trans.getTransferId(); if (trans_id2 != -1) repeat_id2 = RepeatSchedule.getRepeatId(trans_id2); } SQLiteDatabase lootDB = Database.getDatabase(); lootDB.beginTransaction(); boolean ret = false; if (this.erasePattern(repeat_id2) && this.eraseTransactionFromRepeatTable(repeat_id2)) { ret = true; lootDB.setTransactionSuccessful(); } lootDB.endTransaction(); return ret; } private boolean erasePattern(int repeat_id2) { String del = "delete from repeat_pattern where id = " + this.id; if (repeat_id2 != -1) del += " or id = " + repeat_id2; SQLiteDatabase lootDB = Database.getDatabase(); lootDB.beginTransaction(); try { lootDB.execSQL(del); lootDB.setTransactionSuccessful(); } catch (SQLException e) { return false; } finally { lootDB.endTransaction(); } return true; } public boolean load(int repeat_id) { String[] columns = {"start_date", "end_date", "iterator", "frequency", "custom", "due"}; SQLiteDatabase lootDB = Database.getDatabase(); Cursor cur = lootDB.query("repeat_pattern", columns, "id = " + repeat_id, null, null, null, null); boolean ret = false; if (cur.moveToFirst()) { double end = cur.getLong(1); this.start = new Date(cur.getLong(0)); if (end > 0) this.end = new Date(cur.getLong(1)); else this.end = null; this.iter = cur.getInt(2); this.freq = cur.getInt(3); this.custom = cur.getInt(4); this.due = new Date(cur.getLong(5)); this.id = repeat_id; ret = true; } cur.close(); return ret; } private static int getId(String column, String where, String[] wArgs) { SQLiteDatabase lootDB = Database.getDatabase(); String[] columns = {column}; Cursor cur = lootDB.query("repeat_transactions", columns, where, wArgs, null, null, null); int ret = -1; if (cur.moveToFirst()) ret = cur.getInt(0); cur.close(); return ret; } public static int getRepeatId(int trans_id) { return getId("repeat_id", "trans_id = " + trans_id, null); } public static RepeatSchedule getSchedule(int repeat_id) { RepeatSchedule rs = new RepeatSchedule(); if (rs.load(repeat_id)) return rs; return null; } public int getTransactionId() { return getId("trans_id", "repeat_id = " + this.id, null); } public int getTransferId() { return getId("transfer_id", "repeat_id = " + this.id, null); } public Transaction getTransaction() { String[] columns = {"account", "date", "party", "amount", "check_num", "budget", "tags"}; SQLiteDatabase lootDB = Database.getDatabase(); Cursor cur = lootDB.query("repeat_transactions", columns, "repeat_id = " + this.id, null, null, null, null); Transaction trans = null; if (cur.moveToFirst()) { int type, check_num = cur.getInt(4); double amount = cur.getInt(3); boolean budget = Database.getBoolean(cur.getInt(5)); Date date = new Date(cur.getLong(1)); if (check_num > 0) { amount = -amount; type = Transaction.CHECK; } else if (amount < 0.0) { amount = -amount; type = Transaction.WITHDRAW; } else type = Transaction.DEPOSIT; trans = new Transaction(false, budget, date, type, cur.getString(2), amount, check_num); trans.account = cur.getInt(0); trans.addTags(cur.getString(6)); } cur.close(); return trans; } public String[] getTags() { SQLiteDatabase lootDB = Database.getDatabase(); String[] columns = {"tags"}; Cursor cur = lootDB.query("repeat_transactions", columns, "repeat_id = " + this.id, null, null, null, null); if (!cur.moveToFirst()) { cur.close(); return null; } String tag_str = cur.getString(0); cur.close(); String[] tags = null; if (tag_str != null) tags = tag_str.split(" "); if (tags == null || tags.length == 0) return null; return tags; } private static int[] getIds(String where, String[] wArgs) { SQLiteDatabase lootDB = Database.getDatabase(); String[] columns = {"id"}; Cursor cur = lootDB.query("repeat_pattern", columns, where, wArgs, null, null, null); if (!cur.moveToFirst()) { cur.close(); return null; } int[] ids = new int[cur.getCount()]; int i = 0; do { // get the id and increment i when done ids[i++] = cur.getInt(0); } while (cur.moveToNext()); cur.close(); // if there are no ids, return null instead of a zero-length list if (ids.length == 0) ids = null; return ids; } public static int[] getRepeatIds() { return getIds(null, null); } public static int[] getDueRepeatIds(Date date) { String[] wArgs = {Double.toString(date.getTime())}; return getIds("due <= ?", wArgs); } public static int[] processDueRepetitions(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); // if we post repetitions early, set the date passed in the future int early_days = (int)Database.getOptionInt("post_repeats_early"); if (early_days >= 0) cal.add(Calendar.DAY_OF_YEAR, early_days); int[] ids = getDueRepeatIds(cal.getTime()); if (ids == null) return null; ArrayList<Integer> new_trans_ids = new ArrayList<Integer>(); ArrayList<Integer> ret_list = null; RepeatSchedule pattern = new RepeatSchedule(); ArrayList<Integer> new_ids = new ArrayList<Integer>(); int i, id; for (i = 0; i < ids.length; ++i) { id = ids[i]; pattern.load(id); // write the transaction int trans_id = pattern.writeTransaction(pattern.due); if (trans_id != -1) { new_trans_ids.add(trans_id); int transfer_id = pattern.getTransferId(); if (transfer_id != -1) { Transaction transfer = Transaction.getTransactionById(transfer_id, true); if (transfer == null) { transfer = Transaction.getTransactionById(trans_id); transfer.linkTransfer(trans_id, transfer_id); } else if (transfer.getTransferId() == transfer_id) transfer.linkTransfer(trans_id, transfer_id); } } try { // clone this schedule, then delete it RepeatSchedule new_repeat = (RepeatSchedule) pattern.clone(); pattern.erase(false); // change the start date and write a new repeat pattern new_repeat.start = (Date)new_repeat.due.clone(); new_repeat.id = -1; int repeat_id = new_repeat.write(trans_id); // if the write was successful, add it to the list of newly created ids if (repeat_id != -1) new_ids.add(repeat_id); } catch (Exception e) { e.printStackTrace(); } } // if there were new ids in this run, add them to the list of ids to return if (new_ids.size() != 0) { int[] more_trans_ids = processDueRepetitions(date); if (more_trans_ids != null) { // make a new list out of new_trans_ids and more_trans_ids ret_list = new ArrayList<Integer>(); ret_list.addAll(new_trans_ids); for ( Integer val : more_trans_ids ) ret_list.add(val); } else // if there were no new ids while processing more repetitions, // set the ret_list to the new ids gained from this run ret_list = new_trans_ids; } else { ret_list = new_trans_ids; } if (ret_list == null) return null; // convert ret_list to int[] int[] arr = new int[ret_list.size()]; i = 0; for ( int val : ret_list ) arr[i++] = val; Arrays.sort(arr); return arr; } public int writeTransaction(Date date) { if (date == null) return -1; int trans_id = this.getTransactionId(); // have to retrieve the next check num first because android sqlite api // doesn't allow for the creation of sqlite functions Transaction trans = this.getTransaction(); int next_check_num = 0; if (trans.check_num > 0) { Account acct = Account.getAccountById(trans.account); next_check_num = acct.getNextCheckNum(); } // insert the transaction into the transactions table String insert = "insert into transactions (account,date,party,amount,check_num,budget,timestamp) " + "select account," + date.getTime() + ",party,amount," + next_check_num + ",budget,strftime('%%s','now') from repeat_transactions where repeat_id = " + this.id; SQLiteDatabase lootDB = Database.getDatabase(); lootDB.beginTransaction(); try { lootDB.execSQL(insert); } catch (SQLException e) { lootDB.endTransaction(); return -1; } // retrieve the new id for this row String[] columns = {"max(id)"}; Cursor cur = lootDB.query("transactions", columns, null, null, null, null, null); if (!cur.moveToFirst()) { cur.close(); return -1; } int max = cur.getInt(0); cur.close(); // update any repeat_transactions rows that refer to this transaction as the transfer_id ContentValues cv = new ContentValues(); cv.put("transfer_id", max); int updated = 0; try { updated = lootDB.update("repeat_transactions", cv, "transfer_id = " + trans_id, null); } catch (SQLException e) { lootDB.endTransaction(); return -1; } // link transaction to itself if rows are updated if (updated > 0) { Transaction tmp = Transaction.getTransactionById(max, true); tmp.linkTransfer(max, max); } // write the tags to the tags table for the new transaction trans = Transaction.getTransactionById(max, true); trans.addTags(this.getTags()); int ret = trans.write(trans.account); if (ret != -1) lootDB.setTransactionSuccessful(); lootDB.endTransaction(); return ret; } public boolean writeTransactionToRepeatTable(int trans_id) { Transaction trans = Transaction.getTransactionById(trans_id, true); if (trans == null) return false; int transfer_id = trans.getTransferId(); // verify that both the transaction and repeat pattern exist String query = "select t.id, r.id from transactions as t, repeat_pattern as r where " + "t.id = " + trans_id + " and r.id = " + this.id; SQLiteDatabase lootDB = Database.getDatabase(); Cursor cur = lootDB.rawQuery(query, null); // no rows exist with those IDs if (!cur.moveToFirst()) { cur.close(); return false; } cur.close(); String insert = "insert into repeat_transactions (trans_id,repeat_id,account,date,party,amount," + "check_num,budget,transfer_id) select id," + this.id + ",account,date,party," + "amount,check_num,budget," + transfer_id + " from transactions where id = " + trans_id; lootDB.beginTransaction(); try { lootDB.execSQL(insert); } catch (SQLException e) { lootDB.endTransaction(); return false; } // copy the tags over to the new row insert = "update repeat_transactions set tags = ? where trans_id = " + trans_id + " and repeat_id = " + this.id; Object[] bindArgs = {trans.tagListToString()}; try { lootDB.execSQL(insert, bindArgs); lootDB.setTransactionSuccessful(); } catch (SQLException e) { return false; } finally { lootDB.endTransaction(); } return true; } public boolean eraseTransactionFromRepeatTable(int repeat_id2) { String del = "delete from repeat_transactions where repeat_id = " + this.id; if (repeat_id2 != -1) del += " or repeat_id = " + repeat_id2; SQLiteDatabase lootDB = Database.getDatabase(); lootDB.beginTransaction(); try { lootDB.execSQL(del); lootDB.setTransactionSuccessful(); } catch (SQLException e) { return false; } finally { lootDB.endTransaction(); } return true; } public Date calculateDueDate() { + // if frequency is 0, or the iterator is NO_REPEAT + // or the start time is after the end time, return null if (this.freq == 0 || this.iter == NO_REPEAT || ((this.end != null && this.end.getTime() > 0) && this.start.after(this.end))) return null; Calendar cal = Calendar.getInstance(); cal.setTime(this.start); if ( this.iter == DAILY ) { cal.add(Calendar.DAY_OF_MONTH, this.freq); } else if ( this.iter == WEEKLY ) { if (this.custom == -1) { // standard weekly repetition cal.add(Calendar.DAY_OF_MONTH, this.freq * 7); } else { // go to next day in the pattern int start_day = cal.get(Calendar.DAY_OF_WEEK); int first_day = cal.getFirstDayOfWeek(); int weekday; boolean keep_going = true; while (keep_going) { cal.add(Calendar.DAY_OF_MONTH, 1); weekday = cal.get(Calendar.DAY_OF_WEEK); if (weekday == start_day) { keep_going = false; break; } // if we reached the end of the week, add this.freq - 1 weeks if (weekday == first_day) cal.add(Calendar.DAY_OF_MONTH, 7 * (this.freq - 1)); switch (weekday) { case Calendar.MONDAY: if ((this.custom & RepeatSchedule.MONDAY) > 0) keep_going = false; break; case Calendar.TUESDAY: if ((this.custom & RepeatSchedule.TUESDAY) > 0) keep_going = false; break; case Calendar.WEDNESDAY: if ((this.custom & RepeatSchedule.WEDNESDAY) > 0) keep_going = false; break; case Calendar.THURSDAY: if ((this.custom & RepeatSchedule.THURSDAY) > 0) keep_going = false; break; case Calendar.FRIDAY: if ((this.custom & RepeatSchedule.FRIDAY) > 0) keep_going = false; break; case Calendar.SATURDAY: if ((this.custom & RepeatSchedule.SATURDAY) > 0) keep_going = false; break; case Calendar.SUNDAY: if ((this.custom & RepeatSchedule.SUNDAY) > 0) keep_going = false; break; default: keep_going = false; break; } } } } else if (this.iter == MONTHLY) { if (this.custom == DATE) { cal.add(Calendar.MONTH, this.freq); } else if (this.custom == DAY) { int day_of_week = cal.get(Calendar.DAY_OF_WEEK); int day_of_week_in_month = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH); cal.add(Calendar.MONTH, this.freq); cal.set(Calendar.DAY_OF_WEEK, day_of_week); cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, day_of_week_in_month); } } else if (this.iter == YEARLY) { cal.add(Calendar.YEAR, this.freq); } Date due = cal.getTime(); - if (due.before(this.start) || (this.end != null && due.after(this.end))) + if (due.before(this.start) || ((this.end != null && this.end.getTime() > 0) && due.after(this.end))) return null; else return due; } }
false
true
public Date calculateDueDate() { if (this.freq == 0 || this.iter == NO_REPEAT || ((this.end != null && this.end.getTime() > 0) && this.start.after(this.end))) return null; Calendar cal = Calendar.getInstance(); cal.setTime(this.start); if ( this.iter == DAILY ) { cal.add(Calendar.DAY_OF_MONTH, this.freq); } else if ( this.iter == WEEKLY ) { if (this.custom == -1) { // standard weekly repetition cal.add(Calendar.DAY_OF_MONTH, this.freq * 7); } else { // go to next day in the pattern int start_day = cal.get(Calendar.DAY_OF_WEEK); int first_day = cal.getFirstDayOfWeek(); int weekday; boolean keep_going = true; while (keep_going) { cal.add(Calendar.DAY_OF_MONTH, 1); weekday = cal.get(Calendar.DAY_OF_WEEK); if (weekday == start_day) { keep_going = false; break; } // if we reached the end of the week, add this.freq - 1 weeks if (weekday == first_day) cal.add(Calendar.DAY_OF_MONTH, 7 * (this.freq - 1)); switch (weekday) { case Calendar.MONDAY: if ((this.custom & RepeatSchedule.MONDAY) > 0) keep_going = false; break; case Calendar.TUESDAY: if ((this.custom & RepeatSchedule.TUESDAY) > 0) keep_going = false; break; case Calendar.WEDNESDAY: if ((this.custom & RepeatSchedule.WEDNESDAY) > 0) keep_going = false; break; case Calendar.THURSDAY: if ((this.custom & RepeatSchedule.THURSDAY) > 0) keep_going = false; break; case Calendar.FRIDAY: if ((this.custom & RepeatSchedule.FRIDAY) > 0) keep_going = false; break; case Calendar.SATURDAY: if ((this.custom & RepeatSchedule.SATURDAY) > 0) keep_going = false; break; case Calendar.SUNDAY: if ((this.custom & RepeatSchedule.SUNDAY) > 0) keep_going = false; break; default: keep_going = false; break; } } } } else if (this.iter == MONTHLY) { if (this.custom == DATE) { cal.add(Calendar.MONTH, this.freq); } else if (this.custom == DAY) { int day_of_week = cal.get(Calendar.DAY_OF_WEEK); int day_of_week_in_month = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH); cal.add(Calendar.MONTH, this.freq); cal.set(Calendar.DAY_OF_WEEK, day_of_week); cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, day_of_week_in_month); } } else if (this.iter == YEARLY) { cal.add(Calendar.YEAR, this.freq); } Date due = cal.getTime(); if (due.before(this.start) || (this.end != null && due.after(this.end))) return null; else return due; }
public Date calculateDueDate() { // if frequency is 0, or the iterator is NO_REPEAT // or the start time is after the end time, return null if (this.freq == 0 || this.iter == NO_REPEAT || ((this.end != null && this.end.getTime() > 0) && this.start.after(this.end))) return null; Calendar cal = Calendar.getInstance(); cal.setTime(this.start); if ( this.iter == DAILY ) { cal.add(Calendar.DAY_OF_MONTH, this.freq); } else if ( this.iter == WEEKLY ) { if (this.custom == -1) { // standard weekly repetition cal.add(Calendar.DAY_OF_MONTH, this.freq * 7); } else { // go to next day in the pattern int start_day = cal.get(Calendar.DAY_OF_WEEK); int first_day = cal.getFirstDayOfWeek(); int weekday; boolean keep_going = true; while (keep_going) { cal.add(Calendar.DAY_OF_MONTH, 1); weekday = cal.get(Calendar.DAY_OF_WEEK); if (weekday == start_day) { keep_going = false; break; } // if we reached the end of the week, add this.freq - 1 weeks if (weekday == first_day) cal.add(Calendar.DAY_OF_MONTH, 7 * (this.freq - 1)); switch (weekday) { case Calendar.MONDAY: if ((this.custom & RepeatSchedule.MONDAY) > 0) keep_going = false; break; case Calendar.TUESDAY: if ((this.custom & RepeatSchedule.TUESDAY) > 0) keep_going = false; break; case Calendar.WEDNESDAY: if ((this.custom & RepeatSchedule.WEDNESDAY) > 0) keep_going = false; break; case Calendar.THURSDAY: if ((this.custom & RepeatSchedule.THURSDAY) > 0) keep_going = false; break; case Calendar.FRIDAY: if ((this.custom & RepeatSchedule.FRIDAY) > 0) keep_going = false; break; case Calendar.SATURDAY: if ((this.custom & RepeatSchedule.SATURDAY) > 0) keep_going = false; break; case Calendar.SUNDAY: if ((this.custom & RepeatSchedule.SUNDAY) > 0) keep_going = false; break; default: keep_going = false; break; } } } } else if (this.iter == MONTHLY) { if (this.custom == DATE) { cal.add(Calendar.MONTH, this.freq); } else if (this.custom == DAY) { int day_of_week = cal.get(Calendar.DAY_OF_WEEK); int day_of_week_in_month = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH); cal.add(Calendar.MONTH, this.freq); cal.set(Calendar.DAY_OF_WEEK, day_of_week); cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, day_of_week_in_month); } } else if (this.iter == YEARLY) { cal.add(Calendar.YEAR, this.freq); } Date due = cal.getTime(); if (due.before(this.start) || ((this.end != null && this.end.getTime() > 0) && due.after(this.end))) return null; else return due; }
diff --git a/src/com/reddit/worddit/adapters/GameListAdapter.java b/src/com/reddit/worddit/adapters/GameListAdapter.java index 5e2e930..44f1693 100755 --- a/src/com/reddit/worddit/adapters/GameListAdapter.java +++ b/src/com/reddit/worddit/adapters/GameListAdapter.java @@ -1,76 +1,80 @@ package com.reddit.worddit.adapters; import com.reddit.worddit.R; import com.reddit.worddit.api.response.Game; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class GameListAdapter extends BaseAdapter { protected Game[] mGames; protected LayoutInflater mInflater; private int mStatusField, mNextPlayerField, mLastMoveField; public GameListAdapter(Context ctx, Game[] games) { mGames = games; mInflater = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mNextPlayerField = R.id.item_game_nextup; mLastMoveField = R.id.item_game_lastplay; } public GameListAdapter(Context ctx, Game[] games, int statusField, int nextPlayerField, int lastMoveField) { this(ctx, games); mStatusField = statusField; mNextPlayerField = nextPlayerField; mLastMoveField = lastMoveField; } @Override public int getCount() { return mGames.length; } @Override public Game getItem(int n) { return mGames[n]; } @Override public long getItemId(int n) { Game g = mGames[n]; return Long.parseLong(g.id, 16); } @Override public View getView(int position, View convertView, ViewGroup parent) { View gameItem; Game gameForView = mGames[position]; if(convertView == null) { gameItem = mInflater.inflate(R.layout.item_gameitem, null); } else { gameItem = convertView; } TextView nextUp = (TextView) gameItem.findViewById(mNextPlayerField); TextView lastPlay = (TextView) gameItem.findViewById(mLastMoveField); if(gameForView.current_player != null) { - nextUp.setText(gameForView.players[Integer.parseInt(gameForView.current_player) + 1].id); + nextUp.setText("Next Player: " + gameForView.players[Integer.parseInt(gameForView.current_player) + 1].id); } else { - nextUp.setText(""); + nextUp.setText("Next Player: "); } - lastPlay.setText("YAHTZEE"); + if(gameForView.last_move_utc != null) { + lastPlay.setText("Last Move: " + gameForView.last_move_utc); + } else { + lastPlay.setText("Last Move: "); + } // I figure we'll switch to labels, but I wanted something to print if they were null for testing. return gameItem; } }
false
true
public View getView(int position, View convertView, ViewGroup parent) { View gameItem; Game gameForView = mGames[position]; if(convertView == null) { gameItem = mInflater.inflate(R.layout.item_gameitem, null); } else { gameItem = convertView; } TextView nextUp = (TextView) gameItem.findViewById(mNextPlayerField); TextView lastPlay = (TextView) gameItem.findViewById(mLastMoveField); if(gameForView.current_player != null) { nextUp.setText(gameForView.players[Integer.parseInt(gameForView.current_player) + 1].id); } else { nextUp.setText(""); } lastPlay.setText("YAHTZEE"); return gameItem; }
public View getView(int position, View convertView, ViewGroup parent) { View gameItem; Game gameForView = mGames[position]; if(convertView == null) { gameItem = mInflater.inflate(R.layout.item_gameitem, null); } else { gameItem = convertView; } TextView nextUp = (TextView) gameItem.findViewById(mNextPlayerField); TextView lastPlay = (TextView) gameItem.findViewById(mLastMoveField); if(gameForView.current_player != null) { nextUp.setText("Next Player: " + gameForView.players[Integer.parseInt(gameForView.current_player) + 1].id); } else { nextUp.setText("Next Player: "); } if(gameForView.last_move_utc != null) { lastPlay.setText("Last Move: " + gameForView.last_move_utc); } else { lastPlay.setText("Last Move: "); } // I figure we'll switch to labels, but I wanted something to print if they were null for testing. return gameItem; }
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java index cf10d6a7d..3c86b9e99 100644 --- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java +++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java @@ -1,570 +1,570 @@ package org.apache.lucene.index; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.codecs.LiveDocsFormat; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.TextField; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.store.MockDirectoryWrapper; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util._TestUtil; import static org.apache.lucene.index.TestIndexWriter.assertNoUnreferencedFiles; /** * Tests for IndexWriter when the disk runs out of space */ public class TestIndexWriterOnDiskFull extends LuceneTestCase { /* * Make sure IndexWriter cleans up on hitting a disk * full exception in addDocument. * TODO: how to do this on windows with FSDirectory? */ public void testAddDocumentOnDiskFull() throws IOException { for(int pass=0;pass<2;pass++) { if (VERBOSE) { System.out.println("TEST: pass=" + pass); } boolean doAbort = pass == 1; long diskFree = _TestUtil.nextInt(random(), 100, 300); while(true) { if (VERBOSE) { System.out.println("TEST: cycle: diskFree=" + diskFree); } MockDirectoryWrapper dir = new MockDirectoryWrapper(random(), new RAMDirectory()); dir.setMaxSizeInBytes(diskFree); IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))); MergeScheduler ms = writer.getConfig().getMergeScheduler(); if (ms instanceof ConcurrentMergeScheduler) { // This test intentionally produces exceptions // in the threads that CMS launches; we don't // want to pollute test output with these. ((ConcurrentMergeScheduler) ms).setSuppressExceptions(); } boolean hitError = false; try { for(int i=0;i<200;i++) { addDoc(writer); } if (VERBOSE) { System.out.println("TEST: done adding docs; now commit"); } writer.commit(); } catch (IOException e) { if (VERBOSE) { System.out.println("TEST: exception on addDoc"); e.printStackTrace(System.out); } hitError = true; } if (hitError) { if (doAbort) { if (VERBOSE) { System.out.println("TEST: now rollback"); } writer.rollback(); } else { try { if (VERBOSE) { System.out.println("TEST: now close"); } writer.close(); } catch (IOException e) { if (VERBOSE) { System.out.println("TEST: exception on close; retry w/ no disk space limit"); e.printStackTrace(System.out); } dir.setMaxSizeInBytes(0); writer.close(); } } //_TestUtil.syncConcurrentMerges(ms); if (_TestUtil.anyFilesExceptWriteLock(dir)) { assertNoUnreferencedFiles(dir, "after disk full during addDocument"); // Make sure reader can open the index: DirectoryReader.open(dir).close(); } dir.close(); // Now try again w/ more space: diskFree += TEST_NIGHTLY ? _TestUtil.nextInt(random(), 400, 600) : _TestUtil.nextInt(random(), 3000, 5000); } else { //_TestUtil.syncConcurrentMerges(writer); dir.setMaxSizeInBytes(0); writer.close(); dir.close(); break; } } } } // TODO: make @Nightly variant that provokes more disk // fulls // TODO: have test fail if on any given top // iter there was not a single IOE hit /* Test: make sure when we run out of disk space or hit random IOExceptions in any of the addIndexes(*) calls that 1) index is not corrupt (searcher can open/search it) and 2) transactional semantics are followed: either all or none of the incoming documents were in fact added. */ public void testAddIndexOnDiskFull() throws IOException { // MemoryCodec, since it uses FST, is not necessarily // "additive", ie if you add up N small FSTs, then merge // them, the merged result can easily be larger than the // sum because the merged FST may use array encoding for // some arcs (which uses more space): final String idFormat = _TestUtil.getPostingsFormat("id"); final String contentFormat = _TestUtil.getPostingsFormat("content"); assumeFalse("This test cannot run with Memory codec", idFormat.equals("Memory") || contentFormat.equals("Memory")); int START_COUNT = 57; int NUM_DIR = TEST_NIGHTLY ? 50 : 5; int END_COUNT = START_COUNT + NUM_DIR* (TEST_NIGHTLY ? 25 : 5); // Build up a bunch of dirs that have indexes which we // will then merge together by calling addIndexes(*): Directory[] dirs = new Directory[NUM_DIR]; long inputDiskUsage = 0; for(int i=0;i<NUM_DIR;i++) { dirs[i] = newDirectory(); IndexWriter writer = new IndexWriter(dirs[i], newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))); for(int j=0;j<25;j++) { addDocWithIndex(writer, 25*i+j); } writer.close(); String[] files = dirs[i].listAll(); for(int j=0;j<files.length;j++) { inputDiskUsage += dirs[i].fileLength(files[j]); } } // Now, build a starting index that has START_COUNT docs. We // will then try to addIndexes into a copy of this: MockDirectoryWrapper startDir = newMockDirectory(); IndexWriter writer = new IndexWriter(startDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))); for(int j=0;j<START_COUNT;j++) { addDocWithIndex(writer, j); } writer.close(); // Make sure starting index seems to be working properly: Term searchTerm = new Term("content", "aaa"); IndexReader reader = DirectoryReader.open(startDir); assertEquals("first docFreq", 57, reader.docFreq(searchTerm)); IndexSearcher searcher = newSearcher(reader); ScoreDoc[] hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs; assertEquals("first number of hits", 57, hits.length); reader.close(); // Iterate with larger and larger amounts of free // disk space. With little free disk space, // addIndexes will certainly run out of space & // fail. Verify that when this happens, index is // not corrupt and index in fact has added no // documents. Then, we increase disk space by 2000 // bytes each iteration. At some point there is // enough free disk space and addIndexes should // succeed and index should show all documents were // added. // String[] files = startDir.listAll(); long diskUsage = startDir.sizeInBytes(); long startDiskUsage = 0; String[] files = startDir.listAll(); for(int i=0;i<files.length;i++) { startDiskUsage += startDir.fileLength(files[i]); } for(int iter=0;iter<3;iter++) { if (VERBOSE) { System.out.println("TEST: iter=" + iter); } // Start with 100 bytes more than we are currently using: long diskFree = diskUsage+_TestUtil.nextInt(random(), 50, 200); int method = iter; boolean success = false; boolean done = false; String methodName; if (0 == method) { methodName = "addIndexes(Directory[]) + forceMerge(1)"; } else if (1 == method) { methodName = "addIndexes(IndexReader[])"; } else { methodName = "addIndexes(Directory[])"; } while(!done) { if (VERBOSE) { System.out.println("TEST: cycle..."); } // Make a new dir that will enforce disk usage: MockDirectoryWrapper dir = new MockDirectoryWrapper(random(), new RAMDirectory(startDir, newIOContext(random()))); - writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND).setMergePolicy(newLogMergePolicy())); + writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND).setMergePolicy(newLogMergePolicy(false))); IOException err = null; MergeScheduler ms = writer.getConfig().getMergeScheduler(); for(int x=0;x<2;x++) { if (ms instanceof ConcurrentMergeScheduler) // This test intentionally produces exceptions // in the threads that CMS launches; we don't // want to pollute test output with these. if (0 == x) ((ConcurrentMergeScheduler) ms).setSuppressExceptions(); else ((ConcurrentMergeScheduler) ms).clearSuppressExceptions(); // Two loops: first time, limit disk space & // throw random IOExceptions; second time, no // disk space limit: double rate = 0.05; double diskRatio = ((double) diskFree)/diskUsage; long thisDiskFree; String testName = null; if (0 == x) { thisDiskFree = diskFree; if (diskRatio >= 2.0) { rate /= 2; } if (diskRatio >= 4.0) { rate /= 2; } if (diskRatio >= 6.0) { rate = 0.0; } if (VERBOSE) testName = "disk full test " + methodName + " with disk full at " + diskFree + " bytes"; } else { thisDiskFree = 0; rate = 0.0; if (VERBOSE) testName = "disk full test " + methodName + " with unlimited disk space"; } if (VERBOSE) System.out.println("\ncycle: " + testName); dir.setTrackDiskUsage(true); dir.setMaxSizeInBytes(thisDiskFree); dir.setRandomIOExceptionRate(rate); try { if (0 == method) { if (VERBOSE) { System.out.println("TEST: now addIndexes count=" + dirs.length); } writer.addIndexes(dirs); if (VERBOSE) { System.out.println("TEST: now forceMerge"); } writer.forceMerge(1); } else if (1 == method) { IndexReader readers[] = new IndexReader[dirs.length]; for(int i=0;i<dirs.length;i++) { readers[i] = DirectoryReader.open(dirs[i]); } try { writer.addIndexes(readers); } finally { for(int i=0;i<dirs.length;i++) { readers[i].close(); } } } else { writer.addIndexes(dirs); } success = true; if (VERBOSE) { System.out.println(" success!"); } if (0 == x) { done = true; } } catch (IOException e) { success = false; err = e; if (VERBOSE) { System.out.println(" hit IOException: " + e); e.printStackTrace(System.out); } if (1 == x) { e.printStackTrace(System.out); fail(methodName + " hit IOException after disk space was freed up"); } } // Make sure all threads from // ConcurrentMergeScheduler are done _TestUtil.syncConcurrentMerges(writer); if (VERBOSE) { System.out.println(" now test readers"); } // Finally, verify index is not corrupt, and, if // we succeeded, we see all docs added, and if we // failed, we see either all docs or no docs added // (transactional semantics): try { reader = DirectoryReader.open(dir); } catch (IOException e) { e.printStackTrace(System.out); fail(testName + ": exception when creating IndexReader: " + e); } int result = reader.docFreq(searchTerm); if (success) { if (result != START_COUNT) { fail(testName + ": method did not throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT); } } else { // On hitting exception we still may have added // all docs: if (result != START_COUNT && result != END_COUNT) { err.printStackTrace(System.out); fail(testName + ": method did throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT + " or " + END_COUNT); } } searcher = newSearcher(reader); try { hits = searcher.search(new TermQuery(searchTerm), null, END_COUNT).scoreDocs; } catch (IOException e) { e.printStackTrace(System.out); fail(testName + ": exception when searching: " + e); } int result2 = hits.length; if (success) { if (result2 != result) { fail(testName + ": method did not throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + result); } } else { // On hitting exception we still may have added // all docs: if (result2 != result) { err.printStackTrace(System.out); fail(testName + ": method did throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + result); } } reader.close(); if (VERBOSE) { System.out.println(" count is " + result); } if (done || result == END_COUNT) { break; } } if (VERBOSE) { System.out.println(" start disk = " + startDiskUsage + "; input disk = " + inputDiskUsage + "; max used = " + dir.getMaxUsedSizeInBytes()); } if (done) { // Javadocs state that temp free Directory space // required is at most 2X total input size of // indices so let's make sure: assertTrue("max free Directory space required exceeded 1X the total input index sizes during " + methodName + ": max temp usage = " + (dir.getMaxUsedSizeInBytes()-startDiskUsage) + " bytes vs limit=" + (2*(startDiskUsage + inputDiskUsage)) + "; starting disk usage = " + startDiskUsage + " bytes; " + "input index disk usage = " + inputDiskUsage + " bytes", (dir.getMaxUsedSizeInBytes()-startDiskUsage) < 2*(startDiskUsage + inputDiskUsage)); } // Make sure we don't hit disk full during close below: dir.setMaxSizeInBytes(0); dir.setRandomIOExceptionRate(0.0); writer.close(); // Wait for all BG threads to finish else // dir.close() will throw IOException because // there are still open files _TestUtil.syncConcurrentMerges(ms); dir.close(); // Try again with more free space: diskFree += TEST_NIGHTLY ? _TestUtil.nextInt(random(), 4000, 8000) : _TestUtil.nextInt(random(), 40000, 80000); } } startDir.close(); for (Directory dir : dirs) dir.close(); } private static class FailTwiceDuringMerge extends MockDirectoryWrapper.Failure { public boolean didFail1; public boolean didFail2; @Override public void eval(MockDirectoryWrapper dir) throws IOException { if (!doFail) { return; } StackTraceElement[] trace = new Exception().getStackTrace(); for (int i = 0; i < trace.length; i++) { if (SegmentMerger.class.getName().equals(trace[i].getClassName()) && "mergeTerms".equals(trace[i].getMethodName()) && !didFail1) { didFail1 = true; throw new IOException("fake disk full during mergeTerms"); } if (LiveDocsFormat.class.getName().equals(trace[i].getClassName()) && "writeLiveDocs".equals(trace[i].getMethodName()) && !didFail2) { didFail2 = true; throw new IOException("fake disk full while writing LiveDocs"); } } } } // LUCENE-2593 public void testCorruptionAfterDiskFullDuringMerge() throws IOException { MockDirectoryWrapper dir = newMockDirectory(); //IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setReaderPooling(true)); IndexWriter w = new IndexWriter( dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())). setMergeScheduler(new SerialMergeScheduler()). setReaderPooling(true). setMergePolicy(newLogMergePolicy(2)) ); _TestUtil.keepFullyDeletedSegments(w); Document doc = new Document(); doc.add(newTextField("f", "doctor who", Field.Store.NO)); w.addDocument(doc); w.commit(); w.deleteDocuments(new Term("f", "who")); w.addDocument(doc); // disk fills up! FailTwiceDuringMerge ftdm = new FailTwiceDuringMerge(); ftdm.setDoFail(); dir.failOn(ftdm); try { w.commit(); fail("fake disk full IOExceptions not hit"); } catch (IOException ioe) { // expected assertTrue(ftdm.didFail1 || ftdm.didFail2); } _TestUtil.checkIndex(dir); ftdm.clearDoFail(); w.addDocument(doc); w.close(); dir.close(); } // LUCENE-1130: make sure immeidate disk full on creating // an IndexWriter (hit during DW.ThreadState.init()) is // OK: public void testImmediateDiskFull() throws IOException { MockDirectoryWrapper dir = newMockDirectory(); IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())) .setMaxBufferedDocs(2).setMergeScheduler(new ConcurrentMergeScheduler())); dir.setMaxSizeInBytes(Math.max(1, dir.getRecomputedActualSizeInBytes())); final Document doc = new Document(); FieldType customType = new FieldType(TextField.TYPE_STORED); doc.add(newField("field", "aaa bbb ccc ddd eee fff ggg hhh iii jjj", customType)); try { writer.addDocument(doc); fail("did not hit disk full"); } catch (IOException ioe) { } // Without fix for LUCENE-1130: this call will hang: try { writer.addDocument(doc); fail("did not hit disk full"); } catch (IOException ioe) { } try { writer.close(false); fail("did not hit disk full"); } catch (IOException ioe) { } // Make sure once disk space is avail again, we can // cleanly close: dir.setMaxSizeInBytes(0); writer.close(false); dir.close(); } // TODO: these are also in TestIndexWriter... add a simple doc-writing method // like this to LuceneTestCase? private void addDoc(IndexWriter writer) throws IOException { Document doc = new Document(); doc.add(newTextField("content", "aaa", Field.Store.NO)); writer.addDocument(doc); } private void addDocWithIndex(IndexWriter writer, int index) throws IOException { Document doc = new Document(); doc.add(newTextField("content", "aaa " + index, Field.Store.NO)); doc.add(newTextField("id", "" + index, Field.Store.NO)); writer.addDocument(doc); } }
true
true
public void testAddIndexOnDiskFull() throws IOException { // MemoryCodec, since it uses FST, is not necessarily // "additive", ie if you add up N small FSTs, then merge // them, the merged result can easily be larger than the // sum because the merged FST may use array encoding for // some arcs (which uses more space): final String idFormat = _TestUtil.getPostingsFormat("id"); final String contentFormat = _TestUtil.getPostingsFormat("content"); assumeFalse("This test cannot run with Memory codec", idFormat.equals("Memory") || contentFormat.equals("Memory")); int START_COUNT = 57; int NUM_DIR = TEST_NIGHTLY ? 50 : 5; int END_COUNT = START_COUNT + NUM_DIR* (TEST_NIGHTLY ? 25 : 5); // Build up a bunch of dirs that have indexes which we // will then merge together by calling addIndexes(*): Directory[] dirs = new Directory[NUM_DIR]; long inputDiskUsage = 0; for(int i=0;i<NUM_DIR;i++) { dirs[i] = newDirectory(); IndexWriter writer = new IndexWriter(dirs[i], newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))); for(int j=0;j<25;j++) { addDocWithIndex(writer, 25*i+j); } writer.close(); String[] files = dirs[i].listAll(); for(int j=0;j<files.length;j++) { inputDiskUsage += dirs[i].fileLength(files[j]); } } // Now, build a starting index that has START_COUNT docs. We // will then try to addIndexes into a copy of this: MockDirectoryWrapper startDir = newMockDirectory(); IndexWriter writer = new IndexWriter(startDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))); for(int j=0;j<START_COUNT;j++) { addDocWithIndex(writer, j); } writer.close(); // Make sure starting index seems to be working properly: Term searchTerm = new Term("content", "aaa"); IndexReader reader = DirectoryReader.open(startDir); assertEquals("first docFreq", 57, reader.docFreq(searchTerm)); IndexSearcher searcher = newSearcher(reader); ScoreDoc[] hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs; assertEquals("first number of hits", 57, hits.length); reader.close(); // Iterate with larger and larger amounts of free // disk space. With little free disk space, // addIndexes will certainly run out of space & // fail. Verify that when this happens, index is // not corrupt and index in fact has added no // documents. Then, we increase disk space by 2000 // bytes each iteration. At some point there is // enough free disk space and addIndexes should // succeed and index should show all documents were // added. // String[] files = startDir.listAll(); long diskUsage = startDir.sizeInBytes(); long startDiskUsage = 0; String[] files = startDir.listAll(); for(int i=0;i<files.length;i++) { startDiskUsage += startDir.fileLength(files[i]); } for(int iter=0;iter<3;iter++) { if (VERBOSE) { System.out.println("TEST: iter=" + iter); } // Start with 100 bytes more than we are currently using: long diskFree = diskUsage+_TestUtil.nextInt(random(), 50, 200); int method = iter; boolean success = false; boolean done = false; String methodName; if (0 == method) { methodName = "addIndexes(Directory[]) + forceMerge(1)"; } else if (1 == method) { methodName = "addIndexes(IndexReader[])"; } else { methodName = "addIndexes(Directory[])"; } while(!done) { if (VERBOSE) { System.out.println("TEST: cycle..."); } // Make a new dir that will enforce disk usage: MockDirectoryWrapper dir = new MockDirectoryWrapper(random(), new RAMDirectory(startDir, newIOContext(random()))); writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND).setMergePolicy(newLogMergePolicy())); IOException err = null; MergeScheduler ms = writer.getConfig().getMergeScheduler(); for(int x=0;x<2;x++) { if (ms instanceof ConcurrentMergeScheduler) // This test intentionally produces exceptions // in the threads that CMS launches; we don't // want to pollute test output with these. if (0 == x) ((ConcurrentMergeScheduler) ms).setSuppressExceptions(); else ((ConcurrentMergeScheduler) ms).clearSuppressExceptions(); // Two loops: first time, limit disk space & // throw random IOExceptions; second time, no // disk space limit: double rate = 0.05; double diskRatio = ((double) diskFree)/diskUsage; long thisDiskFree; String testName = null; if (0 == x) { thisDiskFree = diskFree; if (diskRatio >= 2.0) { rate /= 2; } if (diskRatio >= 4.0) { rate /= 2; } if (diskRatio >= 6.0) { rate = 0.0; } if (VERBOSE) testName = "disk full test " + methodName + " with disk full at " + diskFree + " bytes"; } else { thisDiskFree = 0; rate = 0.0; if (VERBOSE) testName = "disk full test " + methodName + " with unlimited disk space"; } if (VERBOSE) System.out.println("\ncycle: " + testName); dir.setTrackDiskUsage(true); dir.setMaxSizeInBytes(thisDiskFree); dir.setRandomIOExceptionRate(rate); try { if (0 == method) { if (VERBOSE) { System.out.println("TEST: now addIndexes count=" + dirs.length); } writer.addIndexes(dirs); if (VERBOSE) { System.out.println("TEST: now forceMerge"); } writer.forceMerge(1); } else if (1 == method) { IndexReader readers[] = new IndexReader[dirs.length]; for(int i=0;i<dirs.length;i++) { readers[i] = DirectoryReader.open(dirs[i]); } try { writer.addIndexes(readers); } finally { for(int i=0;i<dirs.length;i++) { readers[i].close(); } } } else { writer.addIndexes(dirs); } success = true; if (VERBOSE) { System.out.println(" success!"); } if (0 == x) { done = true; } } catch (IOException e) { success = false; err = e; if (VERBOSE) { System.out.println(" hit IOException: " + e); e.printStackTrace(System.out); } if (1 == x) { e.printStackTrace(System.out); fail(methodName + " hit IOException after disk space was freed up"); } } // Make sure all threads from // ConcurrentMergeScheduler are done _TestUtil.syncConcurrentMerges(writer); if (VERBOSE) { System.out.println(" now test readers"); } // Finally, verify index is not corrupt, and, if // we succeeded, we see all docs added, and if we // failed, we see either all docs or no docs added // (transactional semantics): try { reader = DirectoryReader.open(dir); } catch (IOException e) { e.printStackTrace(System.out); fail(testName + ": exception when creating IndexReader: " + e); } int result = reader.docFreq(searchTerm); if (success) { if (result != START_COUNT) { fail(testName + ": method did not throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT); } } else { // On hitting exception we still may have added // all docs: if (result != START_COUNT && result != END_COUNT) { err.printStackTrace(System.out); fail(testName + ": method did throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT + " or " + END_COUNT); } } searcher = newSearcher(reader); try { hits = searcher.search(new TermQuery(searchTerm), null, END_COUNT).scoreDocs; } catch (IOException e) { e.printStackTrace(System.out); fail(testName + ": exception when searching: " + e); } int result2 = hits.length; if (success) { if (result2 != result) { fail(testName + ": method did not throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + result); } } else { // On hitting exception we still may have added // all docs: if (result2 != result) { err.printStackTrace(System.out); fail(testName + ": method did throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + result); } } reader.close(); if (VERBOSE) { System.out.println(" count is " + result); } if (done || result == END_COUNT) { break; } } if (VERBOSE) { System.out.println(" start disk = " + startDiskUsage + "; input disk = " + inputDiskUsage + "; max used = " + dir.getMaxUsedSizeInBytes()); } if (done) { // Javadocs state that temp free Directory space // required is at most 2X total input size of // indices so let's make sure: assertTrue("max free Directory space required exceeded 1X the total input index sizes during " + methodName + ": max temp usage = " + (dir.getMaxUsedSizeInBytes()-startDiskUsage) + " bytes vs limit=" + (2*(startDiskUsage + inputDiskUsage)) + "; starting disk usage = " + startDiskUsage + " bytes; " + "input index disk usage = " + inputDiskUsage + " bytes", (dir.getMaxUsedSizeInBytes()-startDiskUsage) < 2*(startDiskUsage + inputDiskUsage)); } // Make sure we don't hit disk full during close below: dir.setMaxSizeInBytes(0); dir.setRandomIOExceptionRate(0.0); writer.close(); // Wait for all BG threads to finish else // dir.close() will throw IOException because // there are still open files _TestUtil.syncConcurrentMerges(ms); dir.close(); // Try again with more free space: diskFree += TEST_NIGHTLY ? _TestUtil.nextInt(random(), 4000, 8000) : _TestUtil.nextInt(random(), 40000, 80000); } } startDir.close(); for (Directory dir : dirs) dir.close(); }
public void testAddIndexOnDiskFull() throws IOException { // MemoryCodec, since it uses FST, is not necessarily // "additive", ie if you add up N small FSTs, then merge // them, the merged result can easily be larger than the // sum because the merged FST may use array encoding for // some arcs (which uses more space): final String idFormat = _TestUtil.getPostingsFormat("id"); final String contentFormat = _TestUtil.getPostingsFormat("content"); assumeFalse("This test cannot run with Memory codec", idFormat.equals("Memory") || contentFormat.equals("Memory")); int START_COUNT = 57; int NUM_DIR = TEST_NIGHTLY ? 50 : 5; int END_COUNT = START_COUNT + NUM_DIR* (TEST_NIGHTLY ? 25 : 5); // Build up a bunch of dirs that have indexes which we // will then merge together by calling addIndexes(*): Directory[] dirs = new Directory[NUM_DIR]; long inputDiskUsage = 0; for(int i=0;i<NUM_DIR;i++) { dirs[i] = newDirectory(); IndexWriter writer = new IndexWriter(dirs[i], newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))); for(int j=0;j<25;j++) { addDocWithIndex(writer, 25*i+j); } writer.close(); String[] files = dirs[i].listAll(); for(int j=0;j<files.length;j++) { inputDiskUsage += dirs[i].fileLength(files[j]); } } // Now, build a starting index that has START_COUNT docs. We // will then try to addIndexes into a copy of this: MockDirectoryWrapper startDir = newMockDirectory(); IndexWriter writer = new IndexWriter(startDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))); for(int j=0;j<START_COUNT;j++) { addDocWithIndex(writer, j); } writer.close(); // Make sure starting index seems to be working properly: Term searchTerm = new Term("content", "aaa"); IndexReader reader = DirectoryReader.open(startDir); assertEquals("first docFreq", 57, reader.docFreq(searchTerm)); IndexSearcher searcher = newSearcher(reader); ScoreDoc[] hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs; assertEquals("first number of hits", 57, hits.length); reader.close(); // Iterate with larger and larger amounts of free // disk space. With little free disk space, // addIndexes will certainly run out of space & // fail. Verify that when this happens, index is // not corrupt and index in fact has added no // documents. Then, we increase disk space by 2000 // bytes each iteration. At some point there is // enough free disk space and addIndexes should // succeed and index should show all documents were // added. // String[] files = startDir.listAll(); long diskUsage = startDir.sizeInBytes(); long startDiskUsage = 0; String[] files = startDir.listAll(); for(int i=0;i<files.length;i++) { startDiskUsage += startDir.fileLength(files[i]); } for(int iter=0;iter<3;iter++) { if (VERBOSE) { System.out.println("TEST: iter=" + iter); } // Start with 100 bytes more than we are currently using: long diskFree = diskUsage+_TestUtil.nextInt(random(), 50, 200); int method = iter; boolean success = false; boolean done = false; String methodName; if (0 == method) { methodName = "addIndexes(Directory[]) + forceMerge(1)"; } else if (1 == method) { methodName = "addIndexes(IndexReader[])"; } else { methodName = "addIndexes(Directory[])"; } while(!done) { if (VERBOSE) { System.out.println("TEST: cycle..."); } // Make a new dir that will enforce disk usage: MockDirectoryWrapper dir = new MockDirectoryWrapper(random(), new RAMDirectory(startDir, newIOContext(random()))); writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setOpenMode(OpenMode.APPEND).setMergePolicy(newLogMergePolicy(false))); IOException err = null; MergeScheduler ms = writer.getConfig().getMergeScheduler(); for(int x=0;x<2;x++) { if (ms instanceof ConcurrentMergeScheduler) // This test intentionally produces exceptions // in the threads that CMS launches; we don't // want to pollute test output with these. if (0 == x) ((ConcurrentMergeScheduler) ms).setSuppressExceptions(); else ((ConcurrentMergeScheduler) ms).clearSuppressExceptions(); // Two loops: first time, limit disk space & // throw random IOExceptions; second time, no // disk space limit: double rate = 0.05; double diskRatio = ((double) diskFree)/diskUsage; long thisDiskFree; String testName = null; if (0 == x) { thisDiskFree = diskFree; if (diskRatio >= 2.0) { rate /= 2; } if (diskRatio >= 4.0) { rate /= 2; } if (diskRatio >= 6.0) { rate = 0.0; } if (VERBOSE) testName = "disk full test " + methodName + " with disk full at " + diskFree + " bytes"; } else { thisDiskFree = 0; rate = 0.0; if (VERBOSE) testName = "disk full test " + methodName + " with unlimited disk space"; } if (VERBOSE) System.out.println("\ncycle: " + testName); dir.setTrackDiskUsage(true); dir.setMaxSizeInBytes(thisDiskFree); dir.setRandomIOExceptionRate(rate); try { if (0 == method) { if (VERBOSE) { System.out.println("TEST: now addIndexes count=" + dirs.length); } writer.addIndexes(dirs); if (VERBOSE) { System.out.println("TEST: now forceMerge"); } writer.forceMerge(1); } else if (1 == method) { IndexReader readers[] = new IndexReader[dirs.length]; for(int i=0;i<dirs.length;i++) { readers[i] = DirectoryReader.open(dirs[i]); } try { writer.addIndexes(readers); } finally { for(int i=0;i<dirs.length;i++) { readers[i].close(); } } } else { writer.addIndexes(dirs); } success = true; if (VERBOSE) { System.out.println(" success!"); } if (0 == x) { done = true; } } catch (IOException e) { success = false; err = e; if (VERBOSE) { System.out.println(" hit IOException: " + e); e.printStackTrace(System.out); } if (1 == x) { e.printStackTrace(System.out); fail(methodName + " hit IOException after disk space was freed up"); } } // Make sure all threads from // ConcurrentMergeScheduler are done _TestUtil.syncConcurrentMerges(writer); if (VERBOSE) { System.out.println(" now test readers"); } // Finally, verify index is not corrupt, and, if // we succeeded, we see all docs added, and if we // failed, we see either all docs or no docs added // (transactional semantics): try { reader = DirectoryReader.open(dir); } catch (IOException e) { e.printStackTrace(System.out); fail(testName + ": exception when creating IndexReader: " + e); } int result = reader.docFreq(searchTerm); if (success) { if (result != START_COUNT) { fail(testName + ": method did not throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT); } } else { // On hitting exception we still may have added // all docs: if (result != START_COUNT && result != END_COUNT) { err.printStackTrace(System.out); fail(testName + ": method did throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT + " or " + END_COUNT); } } searcher = newSearcher(reader); try { hits = searcher.search(new TermQuery(searchTerm), null, END_COUNT).scoreDocs; } catch (IOException e) { e.printStackTrace(System.out); fail(testName + ": exception when searching: " + e); } int result2 = hits.length; if (success) { if (result2 != result) { fail(testName + ": method did not throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + result); } } else { // On hitting exception we still may have added // all docs: if (result2 != result) { err.printStackTrace(System.out); fail(testName + ": method did throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + result); } } reader.close(); if (VERBOSE) { System.out.println(" count is " + result); } if (done || result == END_COUNT) { break; } } if (VERBOSE) { System.out.println(" start disk = " + startDiskUsage + "; input disk = " + inputDiskUsage + "; max used = " + dir.getMaxUsedSizeInBytes()); } if (done) { // Javadocs state that temp free Directory space // required is at most 2X total input size of // indices so let's make sure: assertTrue("max free Directory space required exceeded 1X the total input index sizes during " + methodName + ": max temp usage = " + (dir.getMaxUsedSizeInBytes()-startDiskUsage) + " bytes vs limit=" + (2*(startDiskUsage + inputDiskUsage)) + "; starting disk usage = " + startDiskUsage + " bytes; " + "input index disk usage = " + inputDiskUsage + " bytes", (dir.getMaxUsedSizeInBytes()-startDiskUsage) < 2*(startDiskUsage + inputDiskUsage)); } // Make sure we don't hit disk full during close below: dir.setMaxSizeInBytes(0); dir.setRandomIOExceptionRate(0.0); writer.close(); // Wait for all BG threads to finish else // dir.close() will throw IOException because // there are still open files _TestUtil.syncConcurrentMerges(ms); dir.close(); // Try again with more free space: diskFree += TEST_NIGHTLY ? _TestUtil.nextInt(random(), 4000, 8000) : _TestUtil.nextInt(random(), 40000, 80000); } } startDir.close(); for (Directory dir : dirs) dir.close(); }
diff --git a/Common/si/meansoft/logisticraft/common/core/Crate.java b/Common/si/meansoft/logisticraft/common/core/Crate.java index 0e4a3b5..babe276 100644 --- a/Common/si/meansoft/logisticraft/common/core/Crate.java +++ b/Common/si/meansoft/logisticraft/common/core/Crate.java @@ -1,83 +1,82 @@ package si.meansoft.logisticraft.common.core; import si.meansoft.logisticraft.common.blocks.LCBlocks; import net.minecraft.src.Block; import net.minecraft.src.Material; import net.minecraft.src.World; public class Crate { /* True == OK, False == NOT OK */ public static boolean checkIce(World world, int x, int y, int z) { int size = 3; for (int var5 = x - size; var5 <= x + size; ++var5) { for (int var6 = y - size; var6 <= y + size; ++var6) { for (int var7 = z - size; var7 <= z + size; ++var7) { if (world.getBlockId(var5, var6, var7) == Block.ice.blockID || world.getBlockId(var5, var6, var7) == Block.blockSnow.blockID || world.getBlockId(var5, var6, var7) == Block.snow.blockID) { return true; } } } } return false; } public static boolean checkWater(World world, int x, int y, int z) { Material up = world.getBlockMaterial(x, y + 1, z); Material dn = world.getBlockMaterial(x, y - 1, z); Material so = world.getBlockMaterial(x - 1, y, z); Material no = world.getBlockMaterial(x + 1, y, z); Material ea = world.getBlockMaterial(x, y, z - 1); Material we = world.getBlockMaterial(x, y, z + 1); Material ma = Material.water; int md = world.getBlockMetadata(x, y, z); int bl = world.getBlockId(x, y, z); if((bl==LCBlocks.crate.blockID && md!=0) || (bl==LCBlocks.box.blockID && md!=14)) { if((up == ma) || (dn == ma) || (so == ma) || (no == ma) || (ea == ma) || (we == ma)){ return true; } else { return false; } } else { return false; } } public static boolean checkRain(World world, int x, int y, int z){ int bl = world.getBlockId(x, y, z); int md = world.getBlockMetadata(x, y, z); boolean blockAbove = false; y++; if(!world.isRemote && world.isRaining()) { - System.out.println("It is raining"); if((bl==LCBlocks.crate.blockID && (md!=0 || md!=14 || md!=7)) || (bl==LCBlocks.box.blockID && (md!=13 || md!=6 || md!=14))){ while (y<256) { if(world.getBlockId(x, y, z) != 0) { y++; blockAbove = true; break; } else { y++; } } return blockAbove; } else { return false; } } else { return false; } } }
true
true
public static boolean checkRain(World world, int x, int y, int z){ int bl = world.getBlockId(x, y, z); int md = world.getBlockMetadata(x, y, z); boolean blockAbove = false; y++; if(!world.isRemote && world.isRaining()) { System.out.println("It is raining"); if((bl==LCBlocks.crate.blockID && (md!=0 || md!=14 || md!=7)) || (bl==LCBlocks.box.blockID && (md!=13 || md!=6 || md!=14))){ while (y<256) { if(world.getBlockId(x, y, z) != 0) { y++; blockAbove = true; break; } else { y++; } } return blockAbove; } else { return false; } } else { return false; } }
public static boolean checkRain(World world, int x, int y, int z){ int bl = world.getBlockId(x, y, z); int md = world.getBlockMetadata(x, y, z); boolean blockAbove = false; y++; if(!world.isRemote && world.isRaining()) { if((bl==LCBlocks.crate.blockID && (md!=0 || md!=14 || md!=7)) || (bl==LCBlocks.box.blockID && (md!=13 || md!=6 || md!=14))){ while (y<256) { if(world.getBlockId(x, y, z) != 0) { y++; blockAbove = true; break; } else { y++; } } return blockAbove; } else { return false; } } else { return false; } }
diff --git a/web/src/main/java/ru/sgu/csit/inoc/deansoffice/webui/gxt/login/client/LoginDialog.java b/web/src/main/java/ru/sgu/csit/inoc/deansoffice/webui/gxt/login/client/LoginDialog.java index 6669291..702fae2 100644 --- a/web/src/main/java/ru/sgu/csit/inoc/deansoffice/webui/gxt/login/client/LoginDialog.java +++ b/web/src/main/java/ru/sgu/csit/inoc/deansoffice/webui/gxt/login/client/LoginDialog.java @@ -1,81 +1,81 @@ package ru.sgu.csit.inoc.deansoffice.webui.gxt.login.client; import com.extjs.gxt.ui.client.Style; import com.extjs.gxt.ui.client.event.*; import com.extjs.gxt.ui.client.util.KeyNav; import com.extjs.gxt.ui.client.widget.Window; import com.extjs.gxt.ui.client.widget.button.Button; import com.extjs.gxt.ui.client.widget.form.FormPanel; import com.extjs.gxt.ui.client.widget.form.TextField; import com.google.gwt.core.client.GWT; /** * User: hd ([email protected]) * Date: Nov 3, 2010 * Time: 6:58:58 AM */ public class LoginDialog extends Window { private TextField<String> userNameTextField = new TextField<String>(); private FormPanel formPanel = new FormPanel(); public LoginDialog() { setHeading("Вход в систему \"Деканат\""); setWidth(330); setModal(true); formPanel.setHeaderVisible(false); formPanel.setBorders(false); formPanel.setAutoWidth(true); formPanel.setAction(GWT.getHostPageBaseURL() + "j_spring_security_check"); formPanel.setMethod(FormPanel.Method.POST); formPanel.addListener(Events.Submit, new Listener<FormEvent>() { @Override public void handleEvent(FormEvent be) { - com.google.gwt.user.client.Window.open("/", "_self", ""); + com.google.gwt.user.client.Window.open(GWT.getHostPageBaseURL(), "_self", ""); } }); userNameTextField.setAutoWidth(true); userNameTextField.setName("j_username"); userNameTextField.setFieldLabel("Логин"); TextField<String> passwordTextField = new TextField<String>(); passwordTextField.setAutoWidth(true); passwordTextField.setPassword(true); passwordTextField.setName("j_password"); passwordTextField.setFieldLabel("Пароль"); formPanel.add(userNameTextField); formPanel.add(passwordTextField); setButtonAlign(Style.HorizontalAlignment.CENTER); addButton(new Button("Вход", new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { tryLogin(); } })); new KeyNav<ComponentEvent>(formPanel) { @Override public void onEnter(ComponentEvent ce) { tryLogin(); } }; add(formPanel); } private void tryLogin() { formPanel.submit(); } @Override public void show() { super.show(); userNameTextField.focus(); } }
true
true
public LoginDialog() { setHeading("Вход в систему \"Деканат\""); setWidth(330); setModal(true); formPanel.setHeaderVisible(false); formPanel.setBorders(false); formPanel.setAutoWidth(true); formPanel.setAction(GWT.getHostPageBaseURL() + "j_spring_security_check"); formPanel.setMethod(FormPanel.Method.POST); formPanel.addListener(Events.Submit, new Listener<FormEvent>() { @Override public void handleEvent(FormEvent be) { com.google.gwt.user.client.Window.open("/", "_self", ""); } }); userNameTextField.setAutoWidth(true); userNameTextField.setName("j_username"); userNameTextField.setFieldLabel("Логин"); TextField<String> passwordTextField = new TextField<String>(); passwordTextField.setAutoWidth(true); passwordTextField.setPassword(true); passwordTextField.setName("j_password"); passwordTextField.setFieldLabel("Пароль"); formPanel.add(userNameTextField); formPanel.add(passwordTextField); setButtonAlign(Style.HorizontalAlignment.CENTER); addButton(new Button("Вход", new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { tryLogin(); } })); new KeyNav<ComponentEvent>(formPanel) { @Override public void onEnter(ComponentEvent ce) { tryLogin(); } }; add(formPanel); }
public LoginDialog() { setHeading("Вход в систему \"Деканат\""); setWidth(330); setModal(true); formPanel.setHeaderVisible(false); formPanel.setBorders(false); formPanel.setAutoWidth(true); formPanel.setAction(GWT.getHostPageBaseURL() + "j_spring_security_check"); formPanel.setMethod(FormPanel.Method.POST); formPanel.addListener(Events.Submit, new Listener<FormEvent>() { @Override public void handleEvent(FormEvent be) { com.google.gwt.user.client.Window.open(GWT.getHostPageBaseURL(), "_self", ""); } }); userNameTextField.setAutoWidth(true); userNameTextField.setName("j_username"); userNameTextField.setFieldLabel("Логин"); TextField<String> passwordTextField = new TextField<String>(); passwordTextField.setAutoWidth(true); passwordTextField.setPassword(true); passwordTextField.setName("j_password"); passwordTextField.setFieldLabel("Пароль"); formPanel.add(userNameTextField); formPanel.add(passwordTextField); setButtonAlign(Style.HorizontalAlignment.CENTER); addButton(new Button("Вход", new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { tryLogin(); } })); new KeyNav<ComponentEvent>(formPanel) { @Override public void onEnter(ComponentEvent ce) { tryLogin(); } }; add(formPanel); }
diff --git a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Repo2Runnable.java b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Repo2Runnable.java index 83e2ad6a2..8fa4e0c43 100644 --- a/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Repo2Runnable.java +++ b/bundles/org.eclipse.equinox.p2.repository.tools/src/org/eclipse/equinox/p2/internal/repository/tools/Repo2Runnable.java @@ -1,277 +1,279 @@ /******************************************************************************* * Copyright (c) 2009 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.equinox.p2.internal.repository.tools; import java.net.URISyntaxException; import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper; import org.eclipse.equinox.internal.p2.engine.DownloadManager; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager; import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRequest; import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException; import org.eclipse.equinox.internal.provisional.p2.engine.*; import org.eclipse.equinox.internal.provisional.p2.engine.phases.Collect; import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey; import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit; import org.eclipse.equinox.internal.provisional.p2.metadata.query.Collector; import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery; import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepository; /** * The transformer takes an existing p2 repository (local or remote), iterates over * its list of IUs, and fetches all of the corresponding artifacts to a user-specified location. * Once fetched, the artifacts will be in "runnable" form... that is directory-based bundles will be * extracted into folders and packed JAR files will be un-packed. * * @since 1.0 */ public class Repo2Runnable extends AbstractApplication implements IApplication { private static final String NATIVE_ARTIFACTS = "nativeArtifacts"; //$NON-NLS-1$ private static final String NATIVE_TYPE = "org.eclipse.equinox.p2.native"; //$NON-NLS-1$ private static final String PARM_OPERAND = "operand"; //$NON-NLS-1$ protected class CollectNativesAction extends ProvisioningAction { public IStatus execute(Map parameters) { InstallableUnitOperand operand = (InstallableUnitOperand) parameters.get(PARM_OPERAND); IInstallableUnit installableUnit = operand.second(); IArtifactRepositoryManager manager = null; try { manager = Activator.getArtifactRepositoryManager(); } catch (ProvisionException e) { return e.getStatus(); } IArtifactKey[] toDownload = installableUnit.getArtifacts(); if (toDownload == null) return Status.OK_STATUS; List artifactRequests = (List) parameters.get(NATIVE_ARTIFACTS); for (int i = 0; i < toDownload.length; i++) { IArtifactRequest request = manager.createMirrorRequest(toDownload[i], destinationArtifactRepository, null, null); artifactRequests.add(request); } return Status.OK_STATUS; } public IStatus undo(Map parameters) { // nothing to do for now return Status.OK_STATUS; } } protected class CollectNativesPhase extends InstallableUnitPhase { public CollectNativesPhase(int weight) { super(NATIVE_ARTIFACTS, weight); } protected ProvisioningAction[] getActions(InstallableUnitOperand operand) { IInstallableUnit unit = operand.second(); if (unit.getTouchpointType().getId().equals(NATIVE_TYPE)) { return new ProvisioningAction[] {new CollectNativesAction()}; } return null; } protected IStatus initializePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { parameters.put(NATIVE_ARTIFACTS, new ArrayList()); return null; } protected IStatus completePhase(IProgressMonitor monitor, IProfile profile, Map parameters) { List artifactRequests = (List) parameters.get(NATIVE_ARTIFACTS); ProvisioningContext context = (ProvisioningContext) parameters.get(PARM_CONTEXT); DownloadManager dm = new DownloadManager(context); for (Iterator it = artifactRequests.iterator(); it.hasNext();) { dm.add((IArtifactRequest) it.next()); } return dm.start(monitor); } } // the list of IUs that we actually transformed... could have come from the repo // or have been user-specified. private Collection processedIUs = new ArrayList(); /* * Perform the transformation. */ public IStatus run(IProgressMonitor monitor) throws ProvisionException { SubMonitor progress = SubMonitor.convert(monitor, 5); initializeRepos(progress); // ensure all the right parameters are set validate(); // figure out which IUs we need to process collectIUs(progress.newChild(1)); // create the operands from the list of IUs InstallableUnitOperand[] operands = new InstallableUnitOperand[processedIUs.size()]; int i = 0; for (Iterator iter = processedIUs.iterator(); iter.hasNext();) operands[i++] = new InstallableUnitOperand(null, (IInstallableUnit) iter.next()); // call the engine with only the "collect" phase so all we do is download IProfile profile = createProfile(); try { ProvisioningContext context = new ProvisioningContext(); IEngine engine = (IEngine) ServiceHelper.getService(Activator.getBundleContext(), IEngine.SERVICE_NAME); if (engine == null) throw new ProvisionException(Messages.exception_noEngineService); IStatus result = engine.perform(profile, getPhaseSet(), operands, context, progress.newChild(1)); - engine.perform(profile, getNativePhase(), operands, context, progress.newChild(1)); + PhaseSet nativeSet = getNativePhase(); + if (nativeSet != null) + engine.perform(profile, getNativePhase(), operands, context, progress.newChild(1)); // publish the metadata to a destination - if requested publishMetadata(progress.newChild(1)); // return the resulting status return result; } finally { // cleanup by removing the temporary profile and unloading the repos which were new removeProfile(profile); finalizeRepositories(); } } protected PhaseSet getPhaseSet() { return new PhaseSet(new Phase[] {new Collect(100)}) { /* nothing to override */}; } protected PhaseSet getNativePhase() { return new PhaseSet(new Phase[] {new CollectNativesPhase(100)}) { /*nothing to override */}; } /* * Figure out exactly which IUs we have to process. */ private void collectIUs(IProgressMonitor monitor) throws ProvisionException { // if the user told us exactly which IUs to process, then just set it and return. if (sourceIUs != null && !sourceIUs.isEmpty()) { processedIUs = sourceIUs; return; } // get all IUs from the repos if (!hasMetadataSources()) throw new ProvisionException(Messages.exception_needIUsOrNonEmptyRepo); processedIUs.addAll(getAllIUs(getCompositeMetadataRepository(), monitor).toCollection()); if (processedIUs.isEmpty()) throw new ProvisionException(Messages.exception_needIUsOrNonEmptyRepo); } /* * If there is a destination metadata repository set, then add all our transformed * IUs to it. */ private void publishMetadata(IProgressMonitor monitor) { // publishing the metadata is optional if (destinationMetadataRepository == null) return; destinationMetadataRepository.addInstallableUnits((IInstallableUnit[]) processedIUs.toArray(new IInstallableUnit[processedIUs.size()])); } /* * Return a collector over all the IUs contained in the given repository. */ private Collector getAllIUs(IMetadataRepository repository, IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, 2); try { return repository.query(InstallableUnitQuery.ANY, new Collector(), progress.newChild(1)); } finally { progress.done(); } } /* * Remove the given profile from the profile registry. */ private void removeProfile(IProfile profile) throws ProvisionException { IProfileRegistry registry = Activator.getProfileRegistry(); registry.removeProfile(profile.getProfileId()); } /* * Create and return a new profile. */ private IProfile createProfile() throws ProvisionException { Map properties = new Properties(); properties.put(IProfile.PROP_CACHE, URIUtil.toFile(destinationArtifactRepository.getLocation()).getAbsolutePath()); properties.put(IProfile.PROP_INSTALL_FOLDER, URIUtil.toFile(destinationArtifactRepository.getLocation()).getAbsolutePath()); IProfileRegistry registry = Activator.getProfileRegistry(); return registry.addProfile(System.currentTimeMillis() + "-" + Math.random(), properties); //$NON-NLS-1$ } /* (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) */ public Object start(IApplicationContext context) throws Exception { String[] args = (String[]) context.getArguments().get(IApplicationContext.APPLICATION_ARGS); processCommandLineArgs(args); // perform the transformation run(null); return IApplication.EXIT_OK; } /* * Iterate over the command-line arguments and prepare the transformer for processing. */ private void processCommandLineArgs(String[] args) throws URISyntaxException { if (args == null) return; for (int i = 0; i < args.length; i++) { String option = args[i]; if (i == args.length - 1 || args[i + 1].startsWith("-")) //$NON-NLS-1$ continue; String arg = args[++i]; if (option.equalsIgnoreCase("-source")) { //$NON-NLS-1$ RepositoryDescriptor source = new RepositoryDescriptor(); source.setLocation(URIUtil.fromString(arg)); addSource(source); } if (option.equalsIgnoreCase("-destination")) { //$NON-NLS-1$ RepositoryDescriptor destination = new RepositoryDescriptor(); destination.setLocation(URIUtil.fromString(arg)); addDestination(destination); } } } /* * Ensure all mandatory parameters have been set. Throw an exception if there * are any missing. We don't require the user to specify the artifact repository here, * we will default to the ones already registered in the manager. (callers are free * to add more if they wish) */ private void validate() throws ProvisionException { if (!hasMetadataSources() && sourceIUs == null) throw new ProvisionException(Messages.exception_needIUsOrNonEmptyRepo); if (destinationArtifactRepository == null) throw new ProvisionException(Messages.exception_needDestinationRepo); } /* (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#stop() */ public void stop() { // nothing to do } }
true
true
public IStatus run(IProgressMonitor monitor) throws ProvisionException { SubMonitor progress = SubMonitor.convert(monitor, 5); initializeRepos(progress); // ensure all the right parameters are set validate(); // figure out which IUs we need to process collectIUs(progress.newChild(1)); // create the operands from the list of IUs InstallableUnitOperand[] operands = new InstallableUnitOperand[processedIUs.size()]; int i = 0; for (Iterator iter = processedIUs.iterator(); iter.hasNext();) operands[i++] = new InstallableUnitOperand(null, (IInstallableUnit) iter.next()); // call the engine with only the "collect" phase so all we do is download IProfile profile = createProfile(); try { ProvisioningContext context = new ProvisioningContext(); IEngine engine = (IEngine) ServiceHelper.getService(Activator.getBundleContext(), IEngine.SERVICE_NAME); if (engine == null) throw new ProvisionException(Messages.exception_noEngineService); IStatus result = engine.perform(profile, getPhaseSet(), operands, context, progress.newChild(1)); engine.perform(profile, getNativePhase(), operands, context, progress.newChild(1)); // publish the metadata to a destination - if requested publishMetadata(progress.newChild(1)); // return the resulting status return result; } finally { // cleanup by removing the temporary profile and unloading the repos which were new removeProfile(profile); finalizeRepositories(); } }
public IStatus run(IProgressMonitor monitor) throws ProvisionException { SubMonitor progress = SubMonitor.convert(monitor, 5); initializeRepos(progress); // ensure all the right parameters are set validate(); // figure out which IUs we need to process collectIUs(progress.newChild(1)); // create the operands from the list of IUs InstallableUnitOperand[] operands = new InstallableUnitOperand[processedIUs.size()]; int i = 0; for (Iterator iter = processedIUs.iterator(); iter.hasNext();) operands[i++] = new InstallableUnitOperand(null, (IInstallableUnit) iter.next()); // call the engine with only the "collect" phase so all we do is download IProfile profile = createProfile(); try { ProvisioningContext context = new ProvisioningContext(); IEngine engine = (IEngine) ServiceHelper.getService(Activator.getBundleContext(), IEngine.SERVICE_NAME); if (engine == null) throw new ProvisionException(Messages.exception_noEngineService); IStatus result = engine.perform(profile, getPhaseSet(), operands, context, progress.newChild(1)); PhaseSet nativeSet = getNativePhase(); if (nativeSet != null) engine.perform(profile, getNativePhase(), operands, context, progress.newChild(1)); // publish the metadata to a destination - if requested publishMetadata(progress.newChild(1)); // return the resulting status return result; } finally { // cleanup by removing the temporary profile and unloading the repos which were new removeProfile(profile); finalizeRepositories(); } }
diff --git a/test/unit/org/apache/cassandra/db/KeyCacheTest.java b/test/unit/org/apache/cassandra/db/KeyCacheTest.java index 739bac3fb..7d054e8cd 100644 --- a/test/unit/org/apache/cassandra/db/KeyCacheTest.java +++ b/test/unit/org/apache/cassandra/db/KeyCacheTest.java @@ -1,147 +1,147 @@ package org.apache.cassandra.db; /* * * 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.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import org.junit.Test; import org.apache.cassandra.CleanupHelper; import org.apache.cassandra.Util; import org.apache.cassandra.db.filter.QueryPath; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.io.sstable.Descriptor; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.Pair; import static junit.framework.Assert.assertEquals; public class KeyCacheTest extends CleanupHelper { private static final String TABLE1 = "KeyCacheSpace"; private static final String COLUMN_FAMILY1 = "Standard1"; private static final String COLUMN_FAMILY2 = "Standard2"; private static final String COLUMN_FAMILY3 = "Standard3"; @Test public void testKeyCache50() throws IOException, ExecutionException, InterruptedException { testKeyCache(COLUMN_FAMILY1, 64); } @Test public void testKeyCache100() throws IOException, ExecutionException, InterruptedException { testKeyCache(COLUMN_FAMILY2, 128); } @Test public void testKeyCacheLoad() throws Exception { CompactionManager.instance.disableAutoCompaction(); ColumnFamilyStore store = Table.open(TABLE1).getColumnFamilyStore(COLUMN_FAMILY3); // empty the cache store.invalidateKeyCache(); assert store.getKeyCacheSize() == 0; // insert data and force to disk insertData(TABLE1, COLUMN_FAMILY3, 0, 100); store.forceBlockingFlush(); // populate the cache readData(TABLE1, COLUMN_FAMILY3, 0, 100); assertEquals(100, store.getKeyCacheSize()); // really? our caches don't implement the map interface? (hence no .addAll) Map<Pair<Descriptor, DecoratedKey>, Long> savedMap = new HashMap<Pair<Descriptor, DecoratedKey>, Long>(); for (Pair<Descriptor, DecoratedKey> k : store.getKeyCache().getKeySet()) { savedMap.put(k, store.getKeyCache().get(k)); } // force the cache to disk store.keyCache.submitWrite(Integer.MAX_VALUE).get(); // empty the cache again to make sure values came from disk store.invalidateKeyCache(); assert store.getKeyCacheSize() == 0; // load the cache from disk. unregister the old mbean so we can recreate a new CFS object. // but don't invalidate() the old CFS, which would nuke the data we want to try to load - store.invalidate(); // unregistering old MBean to test how key cache will be loaded + store.unregisterMBean(); ColumnFamilyStore newStore = ColumnFamilyStore.createColumnFamilyStore(Table.open(TABLE1), COLUMN_FAMILY3); assertEquals(100, newStore.getKeyCacheSize()); assertEquals(100, savedMap.size()); for (Map.Entry<Pair<Descriptor, DecoratedKey>, Long> entry : savedMap.entrySet()) { assert newStore.getKeyCache().get(entry.getKey()).equals(entry.getValue()); } } public void testKeyCache(String cfName, int expectedCacheSize) throws IOException, ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Table table = Table.open(TABLE1); ColumnFamilyStore cfs = table.getColumnFamilyStore(cfName); // KeyCache should start at size 1 if we're caching X% of zero data. int keyCacheSize = cfs.getKeyCacheCapacity(); assert keyCacheSize == 1 : keyCacheSize; DecoratedKey key1 = Util.dk("key1"); DecoratedKey key2 = Util.dk("key2"); RowMutation rm; // inserts rm = new RowMutation(TABLE1, key1.key); rm.add(new QueryPath(cfName, null, ByteBufferUtil.bytes("1")), ByteBufferUtil.EMPTY_BYTE_BUFFER, 0); rm.apply(); rm = new RowMutation(TABLE1, key2.key); rm.add(new QueryPath(cfName, null, ByteBufferUtil.bytes("2")), ByteBufferUtil.EMPTY_BYTE_BUFFER, 0); rm.apply(); // deletes rm = new RowMutation(TABLE1, key1.key); rm.delete(new QueryPath(cfName, null, ByteBufferUtil.bytes("1")), 1); rm.apply(); rm = new RowMutation(TABLE1, key2.key); rm.delete(new QueryPath(cfName, null, ByteBufferUtil.bytes("2")), 1); rm.apply(); // After a flush, the cache should expand to be X% of indices * INDEX_INTERVAL. cfs.forceBlockingFlush(); keyCacheSize = cfs.getKeyCacheCapacity(); assert keyCacheSize == expectedCacheSize : keyCacheSize; // After a compaction, the cache should expand to be X% of zero data. Util.compactAll(cfs).get(); keyCacheSize = cfs.getKeyCacheCapacity(); assert keyCacheSize == 1 : keyCacheSize; } }
true
true
public void testKeyCacheLoad() throws Exception { CompactionManager.instance.disableAutoCompaction(); ColumnFamilyStore store = Table.open(TABLE1).getColumnFamilyStore(COLUMN_FAMILY3); // empty the cache store.invalidateKeyCache(); assert store.getKeyCacheSize() == 0; // insert data and force to disk insertData(TABLE1, COLUMN_FAMILY3, 0, 100); store.forceBlockingFlush(); // populate the cache readData(TABLE1, COLUMN_FAMILY3, 0, 100); assertEquals(100, store.getKeyCacheSize()); // really? our caches don't implement the map interface? (hence no .addAll) Map<Pair<Descriptor, DecoratedKey>, Long> savedMap = new HashMap<Pair<Descriptor, DecoratedKey>, Long>(); for (Pair<Descriptor, DecoratedKey> k : store.getKeyCache().getKeySet()) { savedMap.put(k, store.getKeyCache().get(k)); } // force the cache to disk store.keyCache.submitWrite(Integer.MAX_VALUE).get(); // empty the cache again to make sure values came from disk store.invalidateKeyCache(); assert store.getKeyCacheSize() == 0; // load the cache from disk. unregister the old mbean so we can recreate a new CFS object. // but don't invalidate() the old CFS, which would nuke the data we want to try to load store.invalidate(); // unregistering old MBean to test how key cache will be loaded ColumnFamilyStore newStore = ColumnFamilyStore.createColumnFamilyStore(Table.open(TABLE1), COLUMN_FAMILY3); assertEquals(100, newStore.getKeyCacheSize()); assertEquals(100, savedMap.size()); for (Map.Entry<Pair<Descriptor, DecoratedKey>, Long> entry : savedMap.entrySet()) { assert newStore.getKeyCache().get(entry.getKey()).equals(entry.getValue()); } }
public void testKeyCacheLoad() throws Exception { CompactionManager.instance.disableAutoCompaction(); ColumnFamilyStore store = Table.open(TABLE1).getColumnFamilyStore(COLUMN_FAMILY3); // empty the cache store.invalidateKeyCache(); assert store.getKeyCacheSize() == 0; // insert data and force to disk insertData(TABLE1, COLUMN_FAMILY3, 0, 100); store.forceBlockingFlush(); // populate the cache readData(TABLE1, COLUMN_FAMILY3, 0, 100); assertEquals(100, store.getKeyCacheSize()); // really? our caches don't implement the map interface? (hence no .addAll) Map<Pair<Descriptor, DecoratedKey>, Long> savedMap = new HashMap<Pair<Descriptor, DecoratedKey>, Long>(); for (Pair<Descriptor, DecoratedKey> k : store.getKeyCache().getKeySet()) { savedMap.put(k, store.getKeyCache().get(k)); } // force the cache to disk store.keyCache.submitWrite(Integer.MAX_VALUE).get(); // empty the cache again to make sure values came from disk store.invalidateKeyCache(); assert store.getKeyCacheSize() == 0; // load the cache from disk. unregister the old mbean so we can recreate a new CFS object. // but don't invalidate() the old CFS, which would nuke the data we want to try to load store.unregisterMBean(); ColumnFamilyStore newStore = ColumnFamilyStore.createColumnFamilyStore(Table.open(TABLE1), COLUMN_FAMILY3); assertEquals(100, newStore.getKeyCacheSize()); assertEquals(100, savedMap.size()); for (Map.Entry<Pair<Descriptor, DecoratedKey>, Long> entry : savedMap.entrySet()) { assert newStore.getKeyCache().get(entry.getKey()).equals(entry.getValue()); } }
diff --git a/src/UI/AddNewBookDialog.java b/src/UI/AddNewBookDialog.java index 133736c..1777158 100644 --- a/src/UI/AddNewBookDialog.java +++ b/src/UI/AddNewBookDialog.java @@ -1,264 +1,281 @@ package UI; import java.awt.Container; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import Transactions.Transactions; public class AddNewBookDialog extends JFrame implements ActionListener { JTextField callNumber = new JTextField(); JTextField isbn = new JTextField(); JTextField title = new JTextField(); JTextField mainAuthor = new JTextField(); JTextField publisher = new JTextField(); JTextField year = new JTextField(); JTextField otherAuthor = new JTextField(); JTextField subject = new JTextField(); DefaultListModel authorListModel = new DefaultListModel(); DefaultListModel subjectListModel = new DefaultListModel(); String addAuthor = "Add Author"; String addSubject = "Add Subject"; List<String> authors = new ArrayList<String>(); List<String> subjects = new ArrayList<String>(); static String returnToLibrarianDialogCommand = "Return to Librarian Dialog"; static String add = "Add"; private Transactions con; public static final int VALIDATIONERROR = 2; public AddNewBookDialog(String name) { super (name); } private void addComponentsToPane(final Container pane) { JPanel panel = new JPanel(); panel.setSize(new Dimension (100, 300)); panel.setLayout(new GridLayout(11, 3)); panel.add(new Label("Call Number")); panel.add(callNumber); panel.add(new Label("")); panel.add(new Label("ISBN")); panel.add(isbn); panel.add(new Label("")); panel.add(new Label("Title")); panel.add(title); panel.add(new Label("")); panel.add(new Label("Main Author")); panel.add(mainAuthor); panel.add(new Label("")); JButton addAuthorButton = new JButton(addAuthor); addAuthorButton.setActionCommand(addAuthor); addAuthorButton.addActionListener(this); panel.add(new Label("Other Authors")); panel.add(otherAuthor); panel.add(addAuthorButton); panel.add(new Label("")); JList authorList = new JList(authorListModel); panel.add(new JScrollPane(authorList)); panel.add(new Label("")); JButton addSubjectButton = new JButton(addSubject); addSubjectButton.setActionCommand(addSubject); addSubjectButton.addActionListener(this); panel.add(new Label("Subject")); panel.add(subject); panel.add(addSubjectButton); panel.add(new Label("")); JList subjectList = new JList(subjectListModel); panel.add(new JScrollPane(subjectList)); panel.add(new Label("")); panel.add(new Label("Publisher")); panel.add(publisher); panel.add(new Label("")); panel.add(new Label("Year")); panel.add(year); panel.add(new Label("")); JButton returnToUserDialog = new JButton(returnToLibrarianDialogCommand); returnToUserDialog.setActionCommand(returnToLibrarianDialogCommand); returnToUserDialog.addActionListener(this); JButton addButton = new JButton(add); addButton.setActionCommand(add); addButton.addActionListener(this); panel.add(new Label("")); panel.add(returnToUserDialog); panel.add(addButton); pane.add(panel); } public static void createAndShowGUI() { //Create and set up the window. AddNewBookDialog frame = new AddNewBookDialog("Add New Book Dialog"); frame.setSize(300, 800); // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane. frame.addComponentsToPane(frame.getContentPane()); //Display the window. frame.pack(); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent arg0) { if (returnToLibrarianDialogCommand.equals(arg0.getActionCommand())) { this.dispose(); }else if(arg0.getActionCommand().equals("Add")) { addBook(); }else if (this.addAuthor.equals(arg0.getActionCommand())) { authorListModel.addElement(otherAuthor.getText()); authors.add(otherAuthor.getText()); otherAuthor.setText(""); }else if (this.addSubject.equals(arg0.getActionCommand())) { subjectListModel.addElement(subject.getText()); subjects.add(subject.getText()); subject.setText(""); } } public int addBook() { int callNo; int iIsbn; String sTitle; String mAuthor; String sPublisher; int yr; if (callNumber.getText().trim().length() != 0) { - callNo = Integer.parseInt(callNumber.getText()); + try { + callNo = Integer.parseInt(callNumber.getText()); + }catch(Exception e){ + showErrorDialog(); + return 0; + } } else { showErrorDialog(); return VALIDATIONERROR; } if (isbn.getText().trim().length() != 0) { - iIsbn = Integer.parseInt(isbn.getText()); + try{ + iIsbn = Integer.parseInt(isbn.getText()); + }catch (Exception e) + { + showErrorDialog(); + return 0; + } } else { showErrorDialog(); return VALIDATIONERROR; } if (title.getText().trim().length() != 0) { sTitle = title.getText(); } else { showErrorDialog(); return VALIDATIONERROR; } if (mainAuthor.getText().trim().length() != 0) { mAuthor = mainAuthor.getText(); } else { showErrorDialog(); return VALIDATIONERROR; } if (publisher.getText().trim().length() != 0) { sPublisher = publisher.getText(); } else { showErrorDialog(); return VALIDATIONERROR; } if (year.getText().trim().length() != 0) { - yr = Integer.parseInt(year.getText()); + try{ + yr = Integer.parseInt(year.getText()); + }catch(Exception e) + { + showErrorDialog(); + return 0; + } } else { showErrorDialog(); return VALIDATIONERROR; } Transactions trans = new Transactions(); if (trans.insertBook(callNo, iIsbn, sTitle, mAuthor, sPublisher,yr)) { GiveMeTitleAndMessageDialog.createAndShowGUI(Constants.SUCCESS, "Book added successfully"); if (trans.insertBookCopy(callNo, 1, Constants.IN)) { GiveMeTitleAndMessageDialog.createAndShowGUI(Constants.SUCCESS, "Copy added successfully"); } clearTextFields(); }else { showErrorDialog(); } for (String s : this.subjects) { trans.insertHasSubject(callNo, s); } for (String s : this.authors) { trans.insertHasAuthor(callNo, s); } this.subjects.clear(); this.authors.clear(); return 0; } private void showErrorDialog() { GiveMeTitleAndMessageDialog.createAndShowGUI(Constants.ERROR, Constants.AN_ERROR_OCCURRED); } private void clearTextFields(){ callNumber.setText(""); isbn.setText(""); title.setText(""); mainAuthor.setText(""); publisher.setText(""); year.setText(""); authorListModel.clear(); subjectListModel.clear(); } }
false
true
public int addBook() { int callNo; int iIsbn; String sTitle; String mAuthor; String sPublisher; int yr; if (callNumber.getText().trim().length() != 0) { callNo = Integer.parseInt(callNumber.getText()); } else { showErrorDialog(); return VALIDATIONERROR; } if (isbn.getText().trim().length() != 0) { iIsbn = Integer.parseInt(isbn.getText()); } else { showErrorDialog(); return VALIDATIONERROR; } if (title.getText().trim().length() != 0) { sTitle = title.getText(); } else { showErrorDialog(); return VALIDATIONERROR; } if (mainAuthor.getText().trim().length() != 0) { mAuthor = mainAuthor.getText(); } else { showErrorDialog(); return VALIDATIONERROR; } if (publisher.getText().trim().length() != 0) { sPublisher = publisher.getText(); } else { showErrorDialog(); return VALIDATIONERROR; } if (year.getText().trim().length() != 0) { yr = Integer.parseInt(year.getText()); } else { showErrorDialog(); return VALIDATIONERROR; } Transactions trans = new Transactions(); if (trans.insertBook(callNo, iIsbn, sTitle, mAuthor, sPublisher,yr)) { GiveMeTitleAndMessageDialog.createAndShowGUI(Constants.SUCCESS, "Book added successfully"); if (trans.insertBookCopy(callNo, 1, Constants.IN)) { GiveMeTitleAndMessageDialog.createAndShowGUI(Constants.SUCCESS, "Copy added successfully"); } clearTextFields(); }else { showErrorDialog(); } for (String s : this.subjects) { trans.insertHasSubject(callNo, s); } for (String s : this.authors) { trans.insertHasAuthor(callNo, s); } this.subjects.clear(); this.authors.clear(); return 0; }
public int addBook() { int callNo; int iIsbn; String sTitle; String mAuthor; String sPublisher; int yr; if (callNumber.getText().trim().length() != 0) { try { callNo = Integer.parseInt(callNumber.getText()); }catch(Exception e){ showErrorDialog(); return 0; } } else { showErrorDialog(); return VALIDATIONERROR; } if (isbn.getText().trim().length() != 0) { try{ iIsbn = Integer.parseInt(isbn.getText()); }catch (Exception e) { showErrorDialog(); return 0; } } else { showErrorDialog(); return VALIDATIONERROR; } if (title.getText().trim().length() != 0) { sTitle = title.getText(); } else { showErrorDialog(); return VALIDATIONERROR; } if (mainAuthor.getText().trim().length() != 0) { mAuthor = mainAuthor.getText(); } else { showErrorDialog(); return VALIDATIONERROR; } if (publisher.getText().trim().length() != 0) { sPublisher = publisher.getText(); } else { showErrorDialog(); return VALIDATIONERROR; } if (year.getText().trim().length() != 0) { try{ yr = Integer.parseInt(year.getText()); }catch(Exception e) { showErrorDialog(); return 0; } } else { showErrorDialog(); return VALIDATIONERROR; } Transactions trans = new Transactions(); if (trans.insertBook(callNo, iIsbn, sTitle, mAuthor, sPublisher,yr)) { GiveMeTitleAndMessageDialog.createAndShowGUI(Constants.SUCCESS, "Book added successfully"); if (trans.insertBookCopy(callNo, 1, Constants.IN)) { GiveMeTitleAndMessageDialog.createAndShowGUI(Constants.SUCCESS, "Copy added successfully"); } clearTextFields(); }else { showErrorDialog(); } for (String s : this.subjects) { trans.insertHasSubject(callNo, s); } for (String s : this.authors) { trans.insertHasAuthor(callNo, s); } this.subjects.clear(); this.authors.clear(); return 0; }
diff --git a/pn-dispatcher/src/main/java/info/papyri/dispatch/XSLTService.java b/pn-dispatcher/src/main/java/info/papyri/dispatch/XSLTService.java index f61ad0d1..09e664a9 100644 --- a/pn-dispatcher/src/main/java/info/papyri/dispatch/XSLTService.java +++ b/pn-dispatcher/src/main/java/info/papyri/dispatch/XSLTService.java @@ -1,176 +1,178 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package info.papyri.dispatch; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.Charset; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import javax.xml.transform.stream.StreamSource; import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.QName; import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.Serializer; import net.sf.saxon.s9api.XdmAtomicValue; import net.sf.saxon.s9api.XsltCompiler; import net.sf.saxon.s9api.XsltExecutable; import net.sf.saxon.s9api.XsltTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author hcayless */ @WebServlet(name = "XSLTService", urlPatterns = {"/epidocinator"}) public class XSLTService extends HttpServlet { private HashMap<String, XsltExecutable> xslts; private HashMap<String, String> resultTypes; private FileUtils util; private Processor processor = new Processor(false); private Logger log; @Override public void init(ServletConfig config) { log = LoggerFactory.getLogger(this.getClass()); util = new FileUtils(config.getInitParameter("xmlPath")); Enumeration<String> names = config.getInitParameterNames(); xslts = new HashMap<String, XsltExecutable>(); resultTypes = new HashMap<String, String>(); while (names.hasMoreElements()) { String name = names.nextElement(); if (name.contains("Path")) continue; if (name.contains("-type")) { resultTypes.put(name, config.getInitParameter(name)); log.info("Adding " + name + ": " + config.getInitParameter(name)); } else { try { XsltCompiler compiler = processor.newXsltCompiler(); XsltExecutable xslt = compiler.compile(new StreamSource(new File(config.getInitParameter(name)))); xslts.put(name, xslt); } catch (SaxonApiException e) { log.error("Failed to compile "+name+".", e); } } } } /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - PrintWriter out = response.getWriter(); + PrintWriter out; if ("GET".equals(request.getMethod())) { if (request.getParameter("doc") != null) { + response.setContentType(resultTypes.get(request.getParameter("xsl") + "-type") + ";charset=UTF-8"); + out = response.getWriter(); try { - out = response.getWriter(); - response.setContentType(resultTypes.get(request.getParameter("xsl") + "-type") + ";charset=UTF-8"); XsltTransformer xslt = xslts.get(request.getParameter("xsl")).load(); if (request.getParameter("coll") != null) { xslt.setParameter(new QName("collection"), new XdmAtomicValue(request.getParameter("coll"))); } xslt.setSource(new StreamSource(util.getXmlFileFromId(request.getParameter("doc")))); xslt.setDestination(new Serializer(out)); xslt.transform(); } catch (Exception e) { log.error("Transformation "+request.getParameter("xsl")+" failed.", e); } finally { out.close(); } } else { response.setContentType("application/json"); + out = response.getWriter(); if(request.getParameter("jsonp") != null) { out.print(request.getParameter("jsonp")); out.print("("); } out.print("{\"xslts\":["); Iterator<String> itr = xslts.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); out.print("{\""+key+"\": \""+resultTypes.get(key+"-type")+"\"}"); if (itr.hasNext()) { out.print(","); } } out.print("]}"); if(request.getParameter("jsonp") != null) { out.print(")"); } out.close(); } } else { + response.setContentType(resultTypes.get(request.getParameter("xsl") + "-type") + ";charset=UTF-8"); + out = response.getWriter(); try { - response.setContentType("text/html;charset=UTF-8"); XsltTransformer xslt = xslts.get(request.getParameter("xsl")).load(); if (request.getParameter("coll") != null) { xslt.setParameter(new QName("collection"), new XdmAtomicValue(request.getParameter("coll"))); } xslt.setSource(new StreamSource(request.getReader())); xslt.setDestination(new Serializer(out)); xslt.transform(); } catch (Exception e) { log.error("Transformation "+request.getParameter("xsl")+" failed.", e); } finally { out.close(); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
false
true
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); if ("GET".equals(request.getMethod())) { if (request.getParameter("doc") != null) { try { out = response.getWriter(); response.setContentType(resultTypes.get(request.getParameter("xsl") + "-type") + ";charset=UTF-8"); XsltTransformer xslt = xslts.get(request.getParameter("xsl")).load(); if (request.getParameter("coll") != null) { xslt.setParameter(new QName("collection"), new XdmAtomicValue(request.getParameter("coll"))); } xslt.setSource(new StreamSource(util.getXmlFileFromId(request.getParameter("doc")))); xslt.setDestination(new Serializer(out)); xslt.transform(); } catch (Exception e) { log.error("Transformation "+request.getParameter("xsl")+" failed.", e); } finally { out.close(); } } else { response.setContentType("application/json"); if(request.getParameter("jsonp") != null) { out.print(request.getParameter("jsonp")); out.print("("); } out.print("{\"xslts\":["); Iterator<String> itr = xslts.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); out.print("{\""+key+"\": \""+resultTypes.get(key+"-type")+"\"}"); if (itr.hasNext()) { out.print(","); } } out.print("]}"); if(request.getParameter("jsonp") != null) { out.print(")"); } out.close(); } } else { try { response.setContentType("text/html;charset=UTF-8"); XsltTransformer xslt = xslts.get(request.getParameter("xsl")).load(); if (request.getParameter("coll") != null) { xslt.setParameter(new QName("collection"), new XdmAtomicValue(request.getParameter("coll"))); } xslt.setSource(new StreamSource(request.getReader())); xslt.setDestination(new Serializer(out)); xslt.transform(); } catch (Exception e) { log.error("Transformation "+request.getParameter("xsl")+" failed.", e); } finally { out.close(); } } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; if ("GET".equals(request.getMethod())) { if (request.getParameter("doc") != null) { response.setContentType(resultTypes.get(request.getParameter("xsl") + "-type") + ";charset=UTF-8"); out = response.getWriter(); try { XsltTransformer xslt = xslts.get(request.getParameter("xsl")).load(); if (request.getParameter("coll") != null) { xslt.setParameter(new QName("collection"), new XdmAtomicValue(request.getParameter("coll"))); } xslt.setSource(new StreamSource(util.getXmlFileFromId(request.getParameter("doc")))); xslt.setDestination(new Serializer(out)); xslt.transform(); } catch (Exception e) { log.error("Transformation "+request.getParameter("xsl")+" failed.", e); } finally { out.close(); } } else { response.setContentType("application/json"); out = response.getWriter(); if(request.getParameter("jsonp") != null) { out.print(request.getParameter("jsonp")); out.print("("); } out.print("{\"xslts\":["); Iterator<String> itr = xslts.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); out.print("{\""+key+"\": \""+resultTypes.get(key+"-type")+"\"}"); if (itr.hasNext()) { out.print(","); } } out.print("]}"); if(request.getParameter("jsonp") != null) { out.print(")"); } out.close(); } } else { response.setContentType(resultTypes.get(request.getParameter("xsl") + "-type") + ";charset=UTF-8"); out = response.getWriter(); try { XsltTransformer xslt = xslts.get(request.getParameter("xsl")).load(); if (request.getParameter("coll") != null) { xslt.setParameter(new QName("collection"), new XdmAtomicValue(request.getParameter("coll"))); } xslt.setSource(new StreamSource(request.getReader())); xslt.setDestination(new Serializer(out)); xslt.transform(); } catch (Exception e) { log.error("Transformation "+request.getParameter("xsl")+" failed.", e); } finally { out.close(); } } }
diff --git a/src/main/java/it/grid/storm/filesystem/util/PosixFSUtil.java b/src/main/java/it/grid/storm/filesystem/util/PosixFSUtil.java index 1ebcfb9..69932b0 100644 --- a/src/main/java/it/grid/storm/filesystem/util/PosixFSUtil.java +++ b/src/main/java/it/grid/storm/filesystem/util/PosixFSUtil.java @@ -1,42 +1,42 @@ package it.grid.storm.filesystem.util; import java.io.File; import it.grid.storm.filesystem.swig.posixfs; public class PosixFSUtil { String mountPoint; String file; posixfs fs; public PosixFSUtil(String[] args) { if (args.length != 2){ System.err.println("usage: PosixFSUtil fsMountPoint fileToCheck"); System.exit(1); } mountPoint = args[0]; file = args[1]; fs = new posixfs(mountPoint); long freeSpace = fs.get_free_space(); - System.out.format("Free space on FS mounted on %s in bytes: %d", mountPoint, freeSpace); + System.out.format("Free space on FS mounted on %s in bytes: %d\n", mountPoint, freeSpace); File f = new File(file); if (!f.exists()){ System.err.println("File not found: "+file); System.exit(1); } long fileSize = fs.get_size(file); System.out.println("File size: "+fileSize); } public static void main(String[] args) { new PosixFSUtil(args); } }
true
true
public PosixFSUtil(String[] args) { if (args.length != 2){ System.err.println("usage: PosixFSUtil fsMountPoint fileToCheck"); System.exit(1); } mountPoint = args[0]; file = args[1]; fs = new posixfs(mountPoint); long freeSpace = fs.get_free_space(); System.out.format("Free space on FS mounted on %s in bytes: %d", mountPoint, freeSpace); File f = new File(file); if (!f.exists()){ System.err.println("File not found: "+file); System.exit(1); } long fileSize = fs.get_size(file); System.out.println("File size: "+fileSize); }
public PosixFSUtil(String[] args) { if (args.length != 2){ System.err.println("usage: PosixFSUtil fsMountPoint fileToCheck"); System.exit(1); } mountPoint = args[0]; file = args[1]; fs = new posixfs(mountPoint); long freeSpace = fs.get_free_space(); System.out.format("Free space on FS mounted on %s in bytes: %d\n", mountPoint, freeSpace); File f = new File(file); if (!f.exists()){ System.err.println("File not found: "+file); System.exit(1); } long fileSize = fs.get_size(file); System.out.println("File size: "+fileSize); }
diff --git a/src/de/team55/mms/gui/mainscreen.java b/src/de/team55/mms/gui/mainscreen.java index 2a49220..a9fa760 100644 --- a/src/de/team55/mms/gui/mainscreen.java +++ b/src/de/team55/mms/gui/mainscreen.java @@ -1,2725 +1,2725 @@ package de.team55.mms.gui; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridLayout; import java.awt.ScrollPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.FileNotFoundException; import java.io.IOException; import java.security.AllPermission; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import javax.swing.TransferHandler; import javax.swing.border.LineBorder; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import com.lowagie.text.DocumentException; import com.toedter.calendar.JDateChooser; import de.team55.mms.data.Feld; import de.team55.mms.data.Modul; import de.team55.mms.data.Modulhandbuch; import de.team55.mms.data.Nachricht; import de.team55.mms.data.Studiengang; import de.team55.mms.data.User; //import de.team55.mms.data.Zuordnung; import de.team55.mms.function.SendMail; import de.team55.mms.function.ServerConnection; public class mainscreen { private static JFrame frame; private static final int SUCCES = 2; private final Dimension btnSz = new Dimension(140, 50); public ServerConnection serverConnection = new ServerConnection(); // Variablen private static User current = new User("gast", "gast", "", "[email protected]", "d4061b1486fe2da19dd578e8d970f7eb", false, false, false, false, false, true); // Gast String studtransferstring = ""; // uebergabe String fuer Tabellen - // studiengang String modbuchtransferstring = ""; // uebergabe String fuer Tabellen - // modulbuch String modtyptransferstring = ""; // uebergabe String fuer Tabellen - // modultyp String modulselectionstring = ""; // ubergabe String des ausgewaehlten // Moduls private boolean canReadMessages=false; // Listen private ArrayList<User> worklist = null; // Liste mit Usern private ArrayList<User> neueUser = new ArrayList<User>(); // Liste mit Usern private ArrayList<Studiengang> studienlist = null; // Liste mit // Studieng�ngen private ArrayList<Modul> selectedmodullist = null; // Liste der Module im // durchst�bern segment // Liste der Modulhandbuecher des ausgew�hlten Studiengangs private ArrayList<Modulhandbuch> modulhandlist = null; // private ArrayList<Zuordnung> typen = null; // Liste mit Zuordnungen // Map der Dynamischen Buttons private HashMap<JButton, Integer> buttonmap = new HashMap<JButton, Integer>(); private ArrayList<String> defaultlabels = new ArrayList<String>(); private ArrayList<Nachricht> nachrichten = new ArrayList<Nachricht>(); // Modelle private DefaultTableModel tmodel; private DefaultTableModel studmodel; private DefaultTableModel modbuchmodel; private DefaultTableModel modtypmodel; private DefaultTableModel modshowmodel; private DefaultTableModel messagemodel; private DefaultComboBoxModel<Studiengang> cbmodel = new DefaultComboBoxModel<Studiengang>(); // private DefaultComboBoxModel<Zuordnung> cbmodel_Z = new // DefaultComboBoxModel<Zuordnung>(); private DefaultListModel<Modul> lm = new DefaultListModel<Modul>(); private DefaultListModel<Modul> lm_ack = new DefaultListModel<Modul>(); private DefaultListModel<Studiengang> studimodel = new DefaultListModel<Studiengang>(); // private DefaultListModel<Zuordnung> typenmodel = new // DefaultListModel<Zuordnung>(); // Komponenten private static JPanel cards = new JPanel(); private static JPanel modul_panel = new JPanel(); private static JPanel modul_panel_edit = new JPanel(); private static JButton btnModulEinreichen = new JButton("Modul Einreichen"); private static JButton btnVerwaltung = new JButton("Verwaltung"); private static JButton btnModulBearbeiten = new JButton("Modul bearbeiten"); private static JButton btnModulArchiv = new JButton("<html>Module<br>Durchst\u00f6bern"); private static JButton btnUserVerwaltung = new JButton("User Verwaltung"); private static JButton btnLogin = new JButton("Einloggen"); private static JButton btnModulAkzeptieren = new JButton("Modul akzeptieren"); private static JPanel mod = new JPanel(); private JTable tblmessages; private static JPanel welcome = new JPanel(); private static JPanel pnl_content = new JPanel(); //zum testen von drag and drop und f�r die Verwaltung der Modulverantwortlichen DefaultTableModel userstuff = new DefaultTableModel(new Object[][] {}, new String[] { "User-Email", "Vorname", "Nachname" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class, String.class, String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { return false; } }; DefaultTableModel userstuff2 = new DefaultTableModel(new Object[][] {}, new String[] { "User-Email", "Vorname", "Nachname" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class, String.class, String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { return false; } }; DefaultTableModel modstuff = new DefaultTableModel(new Object[][] {}, new String[] { "Modulname" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { return false; } }; // main Frame public mainscreen() { frame = new JFrame(); frame.setBounds(100, 100, 800, 480); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Mitte erzeugen centerscr(); // Obere Leiste erzeugen topscr(); // Linke Seite erzeugen leftscr(); frame.setVisible(true); } /** * Erstellt den mittleren Teil der GUI * */ private void centerscr() { frame.getContentPane().add(cards, BorderLayout.CENTER); cards.setLayout(new CardLayout(0, 0)); // Standartfelder Hinzuf�gen defaultlabels.add("Zuordnung"); defaultlabels.add("K�rzel"); defaultlabels.add("Pr�fungsform"); defaultlabels.add("Jahrgang"); defaultlabels.add("Name"); defaultlabels.add("K\u00fcrzel"); defaultlabels.add("Titel"); defaultlabels.add("Leistungspunkte"); defaultlabels.add("Dauer"); defaultlabels.add("Turnus"); defaultlabels.add("Modulverantwortlicher"); defaultlabels.add("Dozenten"); defaultlabels.add("Inhalt"); defaultlabels.add("Lernziele"); defaultlabels.add("Literatur"); defaultlabels.add("Sprache"); defaultlabels.add("Pr\u00fcfungsform"); defaultlabels.add("Notenbildung"); mod.setLayout(new BorderLayout()); homecard(); usermgtcard(); newmodulecard(); modulbearbeitenCard(); studiengangCard(); manage(); cards.add(mod, "modBearbeiten"); } private void manage() { JPanel pnl_manage = new JPanel(); cards.add(pnl_manage, "manage"); pnl_manage.setLayout(new BoxLayout(pnl_manage, BoxLayout.Y_AXIS)); JPanel pnl_studiengang = new JPanel(); pnl_manage.add(pnl_studiengang); pnl_studiengang.setLayout(new BorderLayout(0, 0)); // Liste mit Studieng�ngen in ScrollPane JList<Studiengang> list = new JList<Studiengang>(studimodel); JScrollPane scrollPane = new JScrollPane(list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); pnl_studiengang.add(scrollPane, BorderLayout.CENTER); JPanel buttons = new JPanel(); pnl_studiengang.add(buttons, BorderLayout.SOUTH); // Anlegen eines neuen Studienganges JButton btnNeuerStudiengang = new JButton("Neuer Studiengang"); btnNeuerStudiengang.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { // Dialog anzeigen, in dem Daten eingetragen werden String name = JOptionPane.showInputDialog(frame, "Name des neuen Studiengangs:", "neuer Studiengang", JOptionPane.PLAIN_MESSAGE); while (name.isEmpty()) { name = JOptionPane.showInputDialog(frame, "Bitte g\u00fcltigen Namen des neuen Studiengangs eingeben:", "neuer Studiengang", JOptionPane.PLAIN_MESSAGE); } String abschluss = JOptionPane.showInputDialog(frame, "Abschluss des neuen Studiengangs:", "Abschluss", JOptionPane.PLAIN_MESSAGE); while (name.isEmpty()) { name = JOptionPane.showInputDialog(frame, "Bitte g\u00fcltigen Abschluss des neuen Studiengangs eingeben:", "Abschluss", JOptionPane.PLAIN_MESSAGE); } // Vorhanden Studieng�nge aus der Datenbank abfragen studienlist = serverConnection.getStudiengaenge(); // Pr�fe, ob schon ein Studiengang mit dem selben Namen // existiert boolean neu = true; for (int i = 0; i < studienlist.size(); i++) { if (studienlist.get(i).equals(name)) { neu = false; break; } } // Wenn keiner Vorhanden ist, anlegen und in Datenbank // eintragen // Anschlie�end Liste und Modelle aktualisieren if (neu) { serverConnection.setStudiengang(name,abschluss); studimodel.removeAllElements(); cbmodel.removeAllElements(); studienlist = serverConnection.getStudiengaenge(); for (int i = 0; i < studienlist.size(); i++) { studimodel.addElement(studienlist.get(i)); cbmodel.addElement(studienlist.get(i)); } // Ansonsten Fehler ausgeben } else { JOptionPane.showMessageDialog(frame, "Studiengang ist schon vorhanden", "Fehler", JOptionPane.ERROR_MESSAGE); } } catch (NullPointerException np) { // Bei abbruch nichts tuen } } }); buttons.add(btnNeuerStudiengang); JLabel lblStudiengnge = new JLabel("Studieng\u00E4nge"); pnl_studiengang.add(lblStudiengnge, BorderLayout.NORTH); JPanel pnl_zuordnungen = new JPanel(); pnl_manage.add(pnl_zuordnungen); pnl_zuordnungen.setLayout(new BorderLayout(0, 0)); // Liste mit Zuordnungen (Modultypen) // JList<Zuordnung> list1 = new JList<Zuordnung>(typenmodel); JPanel buttons1 = new JPanel(); pnl_zuordnungen.add(buttons1, BorderLayout.SOUTH); // Anlegen einer neuen Zuordnung JButton btnNeueZuordnung = new JButton("Modul Verwalter"); btnNeueZuordnung.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // try { modverwaltung(); showCard("modverwaltung"); // JTextField neu_Name = new JTextField(); // JTextField neu_Abschluss = new JTextField(); // JComboBox<Studiengang> neu_sgbox = new JComboBox<Studiengang>(cbmodel); // // Object[] message = { "Name des Types:", neu_Name, "Abschluss:", neu_Abschluss, "Studiengang:", neu_sgbox }; // // // Dialog anzeigen, in dem Daten eingetragen werden // int option = JOptionPane.showConfirmDialog(frame, message, "Neuen Typ anlegen", JOptionPane.OK_CANCEL_OPTION); // if (option == JOptionPane.OK_OPTION) { // // // Teste, ob alle Felder ausgef�llt werden // while ((neu_Name.getText().isEmpty() || (neu_sgbox.getSelectedItem() == null) || neu_Abschluss.getText().isEmpty()) // && (option == JOptionPane.OK_OPTION)) { // Object[] messageEmpty = { "Bitte alle Felder ausf\u00fcllen!", "Name des Types:", neu_Name, "Abschluss:", // neu_Abschluss, "Studiengang:", neu_sgbox }; // option = JOptionPane.showConfirmDialog(frame, messageEmpty, "Neuen Typ anlegen", JOptionPane.OK_CANCEL_OPTION); // } // // Wenn ok gedr�ckt wird // if (option == JOptionPane.OK_OPTION) { // Studiengang s = (Studiengang) neu_sgbox.getSelectedItem(); // // Zuordnung z = new Zuordnung(neu_Name.getText(), // // s.getName(), s.getId(), neu_Abschluss.getText()); // // // Teste, ob Zuordnung schon vorhanden // boolean neu = true; // // for (int i = 0; i < typen.size(); i++) { // // if (typen.get(i).equals(z)) { // // neu = false; // // break; // // } // // } // // // Falls neu, in Datenbank eintragen und Liste und // // Model aktualisieren // if (neu) { // // serverConnection.setZuordnung(z); // // typen = serverConnection.getZuordnungen(); // // typenmodel.removeAllElements(); // // for (int i = 0; i < typen.size(); i++) { // // typenmodel.addElement(typen.get(i)); // // } // } // // Ansonsten Fehler ausgeben // else { // JOptionPane.showMessageDialog(frame, "Zuordnung ist schon vorhanden", "Fehler", JOptionPane.ERROR_MESSAGE); // } // } // } // // } catch (NullPointerException np) { // // Bei abbruch nichts tuen // } } }); buttons1.add(btnNeueZuordnung); JButton btnZurck_1 = new JButton("Zur\u00FCck"); btnZurck_1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Zur�ck zur Start Card showCard("welcome page"); } }); buttons1.add(btnZurck_1); // worklist = serverConnection.userload(); JLabel lblZuordnungen = new JLabel("Deadline"); pnl_zuordnungen.add(lblZuordnungen, BorderLayout.NORTH); final JDateChooser calender = new JDateChooser(); pnl_zuordnungen.add(calender); JButton savedate = new JButton("Datum setzen"); buttons1.add(savedate); JButton test = new JButton("test"); buttons1.add(test); test.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub calender.setDate(serverConnection.getDate()); } }); savedate.addActionListener(new ActionListener() { String dateString; @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub try{ serverConnection.savedate(calender.getDate()); } catch(Exception ex){ JOptionPane.showMessageDialog(frame, "Bitte w�hlen Sie ein g�ltiges Datum aus!", "Datenfehler", JOptionPane.ERROR_MESSAGE); } } }); // JScrollPane scrollPane_1 = new JScrollPane(x, // ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, // ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); // pnl_zuordnungen.add(scrollPane_1, BorderLayout.CENTER); // // JScrollPane scrollPane_2 = new JScrollPane(y, // ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, // ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); // pnl_zuordnungen.add(scrollPane_2, BorderLayout.CENTER); // // JScrollPane scrollPane_3 = new JScrollPane(z, // ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, // ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); // pnl_zuordnungen.add(scrollPane_3, BorderLayout.CENTER); // } private void modverwaltung(){ JPanel mv = new JPanel(); cards.add(mv,"modverwaltung"); JTable mods = new JTable(); JTable aktverwalter = new JTable(); JTable user = new JTable(); mv.setLayout(new GridLayout(2, 1)); JPanel buttons = new JPanel(); JPanel tabellen = new JPanel(); tabellen.setLayout(new GridLayout(2,3,0,0)); JLabel modules = new JLabel("Module"); JLabel aktuelle = new JLabel("Aktuelle Verwalter"); JLabel rest = new JLabel("Userlist"); mv.setLayout(new GridLayout(2,1)); mv.add(tabellen); mv.add(buttons); ScrollPane scp_1 = new ScrollPane(); ScrollPane scp_2 = new ScrollPane(); ScrollPane scp_3 = new ScrollPane(); scp_1.add(mods); scp_2.add(aktverwalter); scp_3.add(user); tabellen.add(modules); tabellen.add(aktuelle); tabellen.add(rest); tabellen.add(scp_1); tabellen.add(scp_2); tabellen.add(scp_3); JButton back = new JButton("Zur\u00FCck"); JButton save = new JButton("Speichern"); buttons.add(back); buttons.add(save); aktverwalter.setDragEnabled(true); user.setDragEnabled(true); mods.setModel(modstuff); aktverwalter.setModel(userstuff); user.setModel(userstuff2); userstuff.setRowCount(0); userstuff2.setRowCount(0); modstuff.setRowCount(0); //on construction ArrayList<Modul> modstufflist = new ArrayList<Modul>(); ArrayList<User> alluser = new ArrayList<User>(); ArrayList<User> verwalter = new ArrayList<User>(); modstuff.addRow(new Object[] { "Modul1" }); userstuff.addRow(new Object[] { "","bla1-1","bla1-2" }); userstuff2.addRow(new Object[] { "BLA2","bla2-1","bla2-2" }); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub showCard("manage"); } }); } /** * Erstellt den oberen Teil der GUI */ private void topscr() { JPanel top = new JPanel(); FlowLayout flowLayout = (FlowLayout) top.getLayout(); flowLayout.setAlignment(FlowLayout.LEFT); frame.getContentPane().add(top, BorderLayout.NORTH); JLabel lblMMS = new JLabel("Modul Management System"); lblMMS.setFont(new Font("Tahoma", Font.BOLD, 16)); lblMMS.setHorizontalAlignment(SwingConstants.LEFT); lblMMS.setLabelFor(frame); top.add(lblMMS); } /** * Hinzuf�gen eines Users in die Usertabelle * * @param usr * Zu hinzuf�gender User */ private void addToTable(User usr) { tmodel.addRow(new Object[] { usr.getTitel(), usr.getVorname(), usr.getNachname(), usr.geteMail(), usr.getManageUsers(), usr.getCreateModule(), usr.getAcceptModule(), usr.getManageSystem() }); } /** * Hinzuf�gen eines Studienganges zur Studiengangtabelle * * @param stud * Zu hinzuf�gender Studiengang */ private void addToTable(Studiengang stud) { studmodel.addRow(new Object[] { stud.getName() }); } /** * Hinzuf�gen eines Modules zur Modultabelle * * @param mod * Zu hinzuf�gendes Modul */ private void addToTable(Modul mod) { modshowmodel.addRow(new Object[] { mod.getName() }); } /** * Hinzuf�gen eines Modulhandbuches zur Modulhandbuchtabelle * * @param modbuch * Zu hinzuf�gendes Modulhandbuch */ private void addToTable(Modulhandbuch modbuch) { modbuchmodel.addRow(new Object[] { modbuch.getJahrgang() }); } /** * Hinzuf�gen einer Zuordnung zur Zuordnungstabelle * * @param modtyp * Name der zu hinzuf�genden Zuordnung */ private void addToTable(String modtyp) { modtypmodel.addRow(new Object[] { modtyp }); } private void addToTable(String user, int i) { if(i == 1) userstuff.addRow(new Object[] { user }); if(i == 2) userstuff2.addRow(new Object[] { user }); } /** * Liefert ein Feld mit Label, TextArea und Checkbox * * @return JPanel ausgef�lltes Panel * @param name * Beschriftung des Labels * @param string * Inhalt der TextArea * @param b * Gibt an, ob die Checkbox ausgew�hlt ist */ private JPanel defaultmodulPanel(String name, String string, boolean b) { final Dimension preferredSize = new Dimension(120, 20); JPanel pnl = new JPanel(); pnl.setLayout(new BoxLayout(pnl, BoxLayout.X_AXIS)); JLabel label = new JLabel(name); label.setPreferredSize(preferredSize); pnl.add(label); JTextArea txt = new JTextArea(string); txt.setLineWrap(true); pnl.add(txt); if (!name.equals("Jahrgang")) { JCheckBox dez = new JCheckBox("Dezernat 2", b); pnl.add(dez); } return pnl; } /** * Liefert ein Feld mit Label und TextArea * * @return JPanel ausgef�lltes Panel * @param name * Beschriftung des Labels * @param string * Inhalt der TextArea */ private JPanel modulPanel(String name, String string) { final Dimension preferredSize = new Dimension(120, 20); JPanel pnl = new JPanel(); pnl.setLayout(new GridLayout(1, 2, 0, 0)); pnl.setBorder(BorderFactory.createLineBorder(Color.black)); JLabel label = new JLabel(name); label.setPreferredSize(preferredSize); pnl.add(label); JLabel txt = new JLabel(string); txt.setPreferredSize(preferredSize); pnl.add(txt); return pnl; } /** * Erstellt den Startbildschirm der GUI * */ private void homecard() { final ArrayList<String> dialogs = new ArrayList<String>(); cards.add(welcome, "welcome page"); welcome.setLayout(new BorderLayout(0, 0)); pnl_content.setLayout(new BoxLayout(pnl_content, BoxLayout.Y_AXIS)); JPanel pnl_day = new JPanel(); pnl_content.add(pnl_day); JLabel lblStichtag = new JLabel("Stichtag f\u00FCr das Einreichen von Modulen: 30.08.13"); pnl_day.add(lblStichtag); lblStichtag.setHorizontalAlignment(SwingConstants.CENTER); lblStichtag.setAlignmentY(0.0f); lblStichtag.setForeground(Color.RED); lblStichtag.setFont(new Font("Tahoma", Font.BOLD, 14)); JPanel pnl_messages = new JPanel(); pnl_content.add(pnl_messages); pnl_messages.setLayout(new BoxLayout(pnl_messages, BoxLayout.Y_AXIS)); JPanel pnl_mestop = new JPanel(); pnl_messages.add(pnl_mestop); pnl_mestop.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5)); JLabel lblNachrichten = new JLabel("Nachrichten:"); pnl_mestop.add(lblNachrichten); lblNachrichten.setVerticalAlignment(SwingConstants.BOTTOM); lblNachrichten.setHorizontalAlignment(SwingConstants.CENTER); JScrollPane scrollPane = new JScrollPane(); pnl_messages.add(scrollPane); messagemodel = new DefaultTableModel(new Object[][] { { Boolean.FALSE, "", null, null }, }, new String[] { "", "Von", "Betreff", "Datum" }) { Class[] columnTypes = new Class[] { Boolean.class, String.class, String.class, String.class }; public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } boolean[] columnEditables = new boolean[] { true, false, false, false }; public boolean isCellEditable(int row, int column) { return columnEditables[column]; } }; refreshMessageTable(); tblmessages = new JTable(messagemodel); scrollPane.setViewportView(tblmessages); tblmessages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tblmessages.setFillsViewportHeight(true); tblmessages.setShowVerticalLines(false); tblmessages.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int row = tblmessages.getSelectedRow(); Nachricht n = nachrichten.get(row); nachrichten.remove(row); n.setGelesen(true); if(!dialogs.contains(n.toString())){ dialogs.add(n.toString()); MessageDialog dialog = new MessageDialog(n); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } nachrichten.add(n); refreshMessageTable(); } } }); JPanel pnl_mesbot = new JPanel(); pnl_messages.add(pnl_mesbot); JButton btnNeu = new JButton("Neu"); btnNeu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int x = -1; int von = 1; int an = 2; String betreff = "Neuer Test"; Date datum = new Date(); boolean gelesen = false; String nachricht = "foooooooooooo blabulb fooooooooo"; Nachricht neu = new Nachricht(x, von, an, betreff, datum, gelesen, nachricht); //abge�ndert damit das prog wieder startet nachrichten.add(neu); refreshMessageTable(); } }); pnl_mesbot.add(btnNeu); JButton btnAlsGelesenMarkieren = new JButton("Als gelesen markieren"); btnAlsGelesenMarkieren.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { for (int i = 0; i < messagemodel.getRowCount(); i++) { if ((boolean) messagemodel.getValueAt(i, 0)) { nachrichten.get(i).setGelesen(true); } } refreshMessageTable(); } }); pnl_mesbot.add(btnAlsGelesenMarkieren); JButton btnAlsUngelesenMarkieren = new JButton("Als ungelesen markieren"); btnAlsUngelesenMarkieren.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (int i = 0; i < messagemodel.getRowCount(); i++) { if ((boolean) messagemodel.getValueAt(i, 0)) { nachrichten.get(i).setGelesen(false); } } refreshMessageTable(); } }); pnl_mesbot.add(btnAlsUngelesenMarkieren); JButton btnLschen = new JButton("L\u00F6schen"); btnLschen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ArrayList<Nachricht> tmp = new ArrayList<Nachricht>(); for (int i = 0; i < messagemodel.getRowCount(); i++) { if ((boolean) messagemodel.getValueAt(i, 0)) { tmp.add(nachrichten.get(i)); } } nachrichten.removeAll(tmp); refreshMessageTable(); } }); pnl_mesbot.add(btnLschen); JPanel pnl_welc = new JPanel(); welcome.add(pnl_welc, BorderLayout.NORTH); JLabel lblNewLabel = new JLabel("Willkommen beim Modul Management System"); pnl_welc.add(lblNewLabel); } private void refreshMessageTable() { Collections.sort(nachrichten, new Comparator<Nachricht>() { public int compare(Nachricht n1, Nachricht n2) { return n1.getDatum().compareTo(n2.getDatum()) * -1; } }); messagemodel.setRowCount(0); for (int i = 0; i < nachrichten.size(); i++) { addToTable(nachrichten.get(i)); } } protected void addToTable(Nachricht neu) { if(neu.isGelesen()){ messagemodel.addRow(new Object[] { false, neu.getAbsender(), neu.getBetreff(), neu.getDatumString() }); } else { messagemodel.addRow(new Object[] { false, "<html><b>" +neu.getAbsender()+ "</b></html>", "<html><b>" +neu.getBetreff()+ "</b></html>", "<html><b>" +neu.getDatumString()+ "</b></html>" }); } } /** * Erstellt den linke Teil der GUI * */ private void leftscr() { btnLogin.setToolTipText("Klicken Sie hier, um in das MMS einzuloggen."); btnModulAkzeptieren.setToolTipText("Klicken Sie hier, um das ausgew�hlte Modul zu akzeptieren. Damit wird es freigegeben und in der Liste der aktuellen Module angezeigt."); btnModulArchiv.setToolTipText("Klicken Sie hier, um das Archiv der aktuellen Module zu durchst�bern."); btnModulBearbeiten.setToolTipText("Klicken Sie hier, um bereits vorhandene Module zu bearbeiten."); btnModulEinreichen.setToolTipText("Klicken Sie hier, um das Modul einzureichen. Damit wird es der verantwortlichen Stelle vorgelegt. Das Modul wird erst nach der Best�tigung der verantwortlichen Stelle in der Liste der aktuellen Module angezeigt."); btnUserVerwaltung.setToolTipText("Klicken Sie hier, um die Benutzerverwaltung aufzurufen. Hier k�nnen Sie neue Benutzer anlegen, deren Daten �ndern und ihre Rechte im MMS festlegen."); btnVerwaltung.setToolTipText("Klicken Sie hier, um die Verwaltung zu �ffnen. Hier k�nnen Sie m�gliche Studieng�nge festlegen, f�r die es Modulhandb�cher geben kann, die Deadline f�r die Modulhandb�cher aktualisieren und Verwalter f�r bestimmte Module festlegen."); JPanel leftpan = new JPanel(); frame.getContentPane().add(leftpan, BorderLayout.WEST); JPanel left = new JPanel(); leftpan.add(left); left.setLayout(new GridLayout(0, 1, 5, 20)); // Button zum Einreichen eines Modules left.add(btnModulEinreichen); btnModulEinreichen.setEnabled(false); btnModulEinreichen.setPreferredSize(btnSz); btnModulEinreichen.setAlignmentX(Component.CENTER_ALIGNMENT); btnModulEinreichen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Abfrage aller Zuordnungen und Studieng�nge aus der Datenbank // Danach Modelle f�llen und zur Card wechseln // typen = serverConnection.getZuordnungen(); studienlist = serverConnection.getStudiengaenge(); cbmodel.removeAllElements(); for (int i = 0; i < studienlist.size(); i++) { cbmodel.addElement(studienlist.get(i)); } // cbmodel_Z.removeAllElements(); // for (int i = 0; i < typen.size(); i++) { // cbmodel_Z.addElement(typen.get(i)); // } showCard("newmodule"); } }); // Button zum Bearbeiten eines Modules left.add(btnModulBearbeiten); btnModulBearbeiten.setEnabled(false); btnModulBearbeiten.setPreferredSize(btnSz); btnModulBearbeiten.setAlignmentX(Component.CENTER_ALIGNMENT); btnModulBearbeiten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Abfrage alles nicht nicht akzeptierten Module // Danach Modell f�llen ArrayList<Modul> module = serverConnection.getModule(false); lm.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm.addElement(module.get(i)); } // Abfrage alles nicht akzeptierten Module // Danach Modell f�llen module = serverConnection.getModule(true); lm_ack.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm_ack.addElement(module.get(i)); } // Zur card mit �bersicht an Modulen wechseln showCard("modulbearbeiten"); } }); // Button zum Login left.add(btnLogin); btnLogin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Verbindung zum Server current = serverConnection.login(current.geteMail(), current.getPassword()); if (current != null) { // Wenn noch nicht eingeloggt, einloggen if (current.geteMail().equals("[email protected]")) { logindialog log = new logindialog(frame, "Login", serverConnection); int resp = log.showCustomDialog(); if (resp == 1) { // User �bernehmen current = log.getUser(); serverConnection = log.getServerConnection(); btnLogin.setText("Ausloggen"); // Auf Rechte pr�fen checkRights(); } } // Wenn bereits eingeloggt, ausloggen else { current = new User("gast", "gast", "", "[email protected]", "d4061b1486fe2da19dd578e8d970f7eb", false, false, false, false, false, true); if (serverConnection.isConnected() == SUCCES) { checkRights(); } btnLogin.setText("Einloggen"); btnUserVerwaltung.setText("User Verwaltung"); btnUserVerwaltung.setEnabled(false); showCard("welcome page"); } } else { // Wenn keine Verbindung besteht noConnection(); } } }); btnLogin.setPreferredSize(btnSz); btnLogin.setAlignmentX(Component.CENTER_ALIGNMENT); // Button zur Userverwaltung btnUserVerwaltung.setEnabled(false); left.add(btnUserVerwaltung); btnUserVerwaltung.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Wenn User das Recht hat, um Benutzer zu Verwalten, // dann Anzeige der Benutzerverwaltung if (current.getManageUsers()) { // Tabelle leeren tmodel.setRowCount(0); // Tabelle mit neuen daten f�llen worklist = serverConnection.userload("true"); for (int i = 0; i < worklist.size(); i++) { // Wenn der User noch nicht freigeschaltet wurde, // zur Liste mit neuen Benutzern hinzuf�gen if (worklist.get(i).isFreigeschaltet()) { addToTable(worklist.get(i)); } else { neueUser.add(worklist.get(i)); } } // Zur Userverwaltungs Card wechseln showCard("user managment"); // Einblendung aller neuen User for (int i = 0; i < neueUser.size(); i++) { userdialog dlg = new userdialog(frame, "User best�tigen", neueUser.get(i), true, serverConnection); int response = dlg.showCustomDialog(); // Bei Best�tigung, neuen User freischalten und e-Mail // senden User tmp = dlg.getUser(); if (response == 1) { tmp.setFreigeschaltet(true); if (SendMail.send(current.geteMail(), neueUser.get(i).geteMail(), "Sie wurden freigeschaltet!") == 1) { tmp.setFreigeschaltet(true); if (serverConnection.userupdate(tmp, tmp.geteMail()).getStatus() == 201) { addToTable(tmp); neueUser.remove(i); } } // Ansonsten m�glichkeit ihn wieder zu l�schen } else { int n = JOptionPane.showConfirmDialog(frame, "M�chten Sie diesen Benutzer l�schen", "Best�tigung", JOptionPane.YES_NO_OPTION); if (n == 0) { serverConnection.deluser(tmp.geteMail()); } } } } else { // Ansonsten Dialog �ffnen, // in dem die eigenen Daten ge�ndert werden k�nnen userdialog dlg = new userdialog(frame, "User bearbeiten", current, false, serverConnection); int response = dlg.showCustomDialog(); // Wenn ok gedr�ckt wird // neuen User abfragen if (response == 1) { User tmp = dlg.getUser(); if (serverConnection.userupdate(tmp, current.geteMail()).getStatus() == 201) { current = tmp; checkRights(); } else JOptionPane.showMessageDialog(frame, "Update Fehlgeschlagen!", "Update Error", JOptionPane.ERROR_MESSAGE); } } } }); btnUserVerwaltung.setPreferredSize(btnSz); btnUserVerwaltung.setAlignmentX(Component.CENTER_ALIGNMENT); // Button zur Verwaltung von Studieng�ngen und Zuordnungen btnVerwaltung.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Zuordnungen und Studieng�nge aus Datenbank abrufen // und Listen f�llen studienlist = serverConnection.getStudiengaenge(); studimodel.removeAllElements(); for (int i = 0; i < studienlist.size(); i++) { studimodel.addElement(studienlist.get(i)); } cbmodel.removeAllElements(); for (int i = 0; i < studienlist.size(); i++) { cbmodel.addElement(studienlist.get(i)); } // typen = serverConnection.getZuordnungen(); // for (int i = 0; i < typen.size(); i++) { // typenmodel.addElement(typen.get(i)); // } // Zur Card wechseln showCard("manage"); } }); left.add(btnVerwaltung); btnVerwaltung.setEnabled(false); btnVerwaltung.setPreferredSize(btnSz); btnVerwaltung.setAlignmentX(Component.CENTER_ALIGNMENT); left.add(btnModulArchiv); btnModulArchiv.setEnabled(true); btnModulArchiv.setPreferredSize(btnSz); btnModulArchiv.setAlignmentX(Component.CENTER_ALIGNMENT); // Button zum Durchst�bern von Modulen btnModulArchiv.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { current = serverConnection.login(current.geteMail(), current.getPassword()); if (current != null) { // Studieng�nge und Zuordnungen abrufen studmodel.setRowCount(0); studienlist = serverConnection.getStudiengaenge(); for (int i = 0; i < studienlist.size(); i++) { addToTable(studienlist.get(i)); } //TODO something // typen = serverConnection.getZuordnungen(); // Zur Card wechseln showCard("studiengang show"); } else { noConnection(); } } }); } /** * Erstellt eine Card, um ein neues Modul anzulegen * */ private void newmodulecard() { // Alle vorhandenen Felder entfernen modul_panel.removeAll(); final JPanel pnl_newmod = new JPanel(); // Liste dynamischer Buttons leeren if (!buttonmap.isEmpty()) { for (int i = 0; i < buttonmap.size(); i++) buttonmap.remove(i); } // Liste mit bereits vorhandenen Felder erstellen und mit den // Standartfeldern f�llen final ArrayList<String> labels = new ArrayList<String>(); labels.addAll(defaultlabels); final Dimension preferredSize = new Dimension(120, 20); pnl_newmod.setLayout(new BorderLayout(0, 0)); JPanel pnl_bottom = new JPanel(); pnl_newmod.add(pnl_bottom, BorderLayout.SOUTH); // Button zum erstellen eines neuen Feldes JButton btnNeuesFeld = new JButton("Neues Feld"); btnNeuesFeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String text = "Name des Feldes"; // Abfrage des Namen des Feldes String name = JOptionPane.showInputDialog(frame, text); try { // Pr�fe, ob Name leer oder schon vorhanden ist while (name.isEmpty() || labels.contains(name)) { Object[] params = { "Bitte geben Sie eine g�ltige Bezeichnung ein!", text }; name = JOptionPane.showInputDialog(frame, params); } labels.add(name); JPanel pnl_tmp = new JPanel(); modul_panel.add(pnl_tmp); // Platzhalter modul_panel.add(Box.createRigidArea(new Dimension(0, 5))); // Abfrage der Anzahl an Panels, die bereits vorhanden sind int numOfPanels = modul_panel.getComponentCount(); pnl_tmp.setLayout(new BoxLayout(pnl_tmp, BoxLayout.X_AXIS)); JLabel label_tmp = new JLabel(name); label_tmp.setPreferredSize(preferredSize); pnl_tmp.add(label_tmp); JTextArea txt_tmp = new JTextArea(); txt_tmp.setLineWrap(true); pnl_tmp.add(txt_tmp); JCheckBox dez = new JCheckBox("Dezernat 2", false); pnl_tmp.add(dez); // Button, um das Feld wieder zu entfernen JButton btn_tmp_entf = new JButton("Entfernen"); btn_tmp_entf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = buttonmap.get(e.getSource()); // Bezeichnung aus Liste entfernen String name = ((JLabel) ((JPanel) modul_panel.getComponent(id)).getComponent(0)).getText(); labels.remove(name); // Feld mit ID id von Panel entfernen modul_panel.remove(id); // Platzhalter entfernen modul_panel.remove(id - 1); // Aus ButtonMap entfernen buttonmap.remove(e.getSource()); // ids der Buttons �ndern, damit auch ein Feld aus // der Mitte gel�cht werden kann HashMap<JButton, Integer> tmpmap = new HashMap<JButton, Integer>(); Iterator<Entry<JButton, Integer>> entries = buttonmap.entrySet().iterator(); while (entries.hasNext()) { Entry<JButton, Integer> thisEntry = entries.next(); JButton key = thisEntry.getKey(); int value = thisEntry.getValue(); if (value > id) { value = value - 2; } tmpmap.put(key, value); } buttonmap = tmpmap; modul_panel.revalidate(); } }); // Button btn_tmp_entf mit ID (numOfPanels-2) zu ButtonMap // hinzuf�gen buttonmap.put(btn_tmp_entf, numOfPanels - 2); pnl_tmp.add(btn_tmp_entf); modul_panel.revalidate(); } catch (NullPointerException npe) { // nichts tuen bei Abbruch } } }); pnl_bottom.add(btnNeuesFeld); // Zur�ck zur Startseite JButton btnHome = new JButton("Zur\u00fcck"); btnHome.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Card wieder erneuern und zur Startseite wechseln newmodulecard(); modul_panel.revalidate(); showCard("welcome page"); } }); pnl_bottom.add(btnHome); JScrollPane scrollPane = new JScrollPane(modul_panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); modul_panel.setLayout(new BoxLayout(modul_panel, BoxLayout.Y_AXIS)); // Panel Zuordnung + Platzhalter JPanel pnl_Z = new JPanel(); pnl_Z.setLayout(new BoxLayout(pnl_Z, BoxLayout.X_AXIS)); JLabel label_MH = new JLabel("Zuordnung"); label_MH.setPreferredSize(preferredSize); pnl_Z.add(label_MH); // Liste mit ausgew�hlten Zuordnungen // final DefaultListModel<Zuordnung> lm = new // DefaultListModel<Zuordnung>(); // final JList<Zuordnung> zlist = new JList<Zuordnung>(lm); // zlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // // pnl_Z.add(zlist); // // // ComboBox mit Zuordnungen // final JComboBox<Zuordnung> cb_Z = new // JComboBox<Zuordnung>(cbmodel_Z); // cb_Z.setMaximumSize(new Dimension(400, 20)); // // pnl_Z.add(cb_Z); // // // Auswahl einer Zuordnung aus der ComboBox // JButton z_btn = new JButton("Zuordnung ausw\u00e4hlen"); // z_btn.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // if (!lm.contains(cb_Z.getSelectedItem())) // lm.addElement((Zuordnung) cb_Z.getSelectedItem()); // } // }); // pnl_Z.add(z_btn); // // // In der Liste ausgew�hlte Zuordnung wieder entfernen // JButton btnZuordnungEntfernen = new JButton("Zuordnung entfernen"); // btnZuordnungEntfernen.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // int i = zlist.getSelectedIndex(); // if (i > -1) { // lm.remove(i); // } // } // }); // pnl_Z.add(btnZuordnungEntfernen); // // modul_panel.add(pnl_Z); modul_panel.add(Box.createRigidArea(new Dimension(0, 5))); // Alle Standartfelder, au�er Zuordnung erzeugen for (int i = 3; i < defaultlabels.size(); i++) { modul_panel.add(defaultmodulPanel(defaultlabels.get(i), "", false)); modul_panel.add(Box.createRigidArea(new Dimension(0, 5))); } // Button zum Annehmen eines Modules JButton btnOk = new JButton("Annehmen"); btnOk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // ArrayList<Zuordnung> zlist = new ArrayList<Zuordnung>(); String jg = ((JTextArea) ((JPanel) modul_panel.getComponent(2)).getComponent(1)).getText(); int jahrgang; try { jahrgang = Integer.parseInt(jg); } catch (NumberFormatException nfe) { jahrgang = 0; } // for (int i = 0; i < lm.getSize(); i++) { // zlist.add(lm.getElementAt(i)); // } // Pr�fe, ob min. eine Zuordnung ausgew�hlt und ein g�ltiger // Jahrgang eingegeben wurde // if (!zlist.isEmpty()) { // if (jahrgang != 0) { // // String Name = ((JTextArea) ((JPanel) // modul_panel.getComponent(4)).getComponent(1)).getText(); // // if (Name.isEmpty()) { // JOptionPane.showMessageDialog(frame, // "Bitte geben Sie einen Namen ein!", "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } else { // // boolean filled = true; // ArrayList<Feld> felder = new ArrayList<Feld>(); // // Eintraege der Reihe nach auslesen // for (int i = 6; i < modul_panel.getComponentCount(); i = i + // 2) { // JPanel tmp = (JPanel) modul_panel.getComponent(i); // JLabel tmplbl = (JLabel) tmp.getComponent(0); // JTextArea tmptxt = (JTextArea) tmp.getComponent(1); // // boolean dezernat2 = ((JCheckBox) // tmp.getComponent(2)).isSelected(); // String value = tmptxt.getText(); // String label = tmplbl.getText(); // // Pr�fe, ob alle Felder ausgef�llt wurden // if (value.isEmpty()) { // filled = false; // break; // } // felder.add(new Feld(label, value, dezernat2)); // } // // Wenn alle aussgef�llt wurden, neues Modul // // erzeugen und bei Best�tigung einreichen // if (filled == true) { // int version = serverConnection.getModulVersion(Name) + 1; // // Date d = new Date(); // ArrayList<String> user = new ArrayList<String>(); // user.add(current.geteMail()); // Modul neu = new Modul(Name, felder, version, d, 0, false, // user, ""); // int n = JOptionPane.showConfirmDialog(frame, // "Sind Sie sicher, dass Sie dieses Modul einreichen wollen?", // "Best�tigung", JOptionPane.YES_NO_OPTION); // if (n == 0) { // serverConnection.setModul(neu); // labels.removeAll(labels); // modul_panel.removeAll(); // modul_panel.revalidate(); // newmodulecard(); // showCard("newmodule"); // } // } // Fehler, wenn nicht alle ausgef�llt wurden // else { // JOptionPane.showMessageDialog(frame, // "Bitte f�llen Sie alle Felder aus!", "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte geben Sie einen g�ltigen Wert f�r den Jahrgang ein!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte w�hlen Sie min. einen Zuordnung aus!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } } }); pnl_bottom.add(btnOk); pnl_newmod.add(scrollPane); cards.add(pnl_newmod, "newmodule"); } /** * Entfernt einen Eintrag aus der Usertabelle * * @param rowid * Der Index des zu enfernenden Eintrages */ private void removeFromTable(int rowid) { tmodel.removeRow(rowid); } /** * Wechselt zur angegeben Card * * @param card * Die Bezeichnung der Card, zu der gewechselt werden soll */ private static void showCard(String card) { ((CardLayout) cards.getLayout()).show(cards, card); } /** * Erstellt eine Card zur Verwaltung von Benutzern */ @SuppressWarnings("serial") private void usermgtcard() { JPanel usrmg = new JPanel(); cards.add(usrmg, "user managment"); usrmg.setLayout(new BorderLayout(0, 0)); JPanel usrpan = new JPanel(); FlowLayout fl_usrpan = (FlowLayout) usrpan.getLayout(); fl_usrpan.setAlignment(FlowLayout.RIGHT); usrmg.add(usrpan, BorderLayout.SOUTH); final JTable usrtbl = new JTable(); JScrollPane ussrscp = new JScrollPane(usrtbl); usrtbl.setBorder(new LineBorder(new Color(0, 0, 0))); usrtbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // // Inhalt der Tabelle // tmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Titel", "Vorname", "Nachname", "e-Mail", "Benutzer verwalten", "Module einreichen", "Module Annehmen", "Verwaltung" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class, String.class, String.class, String.class, boolean.class, boolean.class, boolean.class, boolean.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; usrtbl.setModel(tmodel); // Button zum hinzuf�gen eines Benutzers JButton btnUserAdd = new JButton("User hinzuf\u00fcgen"); btnUserAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { userdialog dlg = new userdialog(frame, "User hinzuf\u00fcgen", serverConnection); int response = dlg.showCustomDialog(); // Wenn ok gedr�ckt wird // neuen User hinzuf�gen if (response == 1) { User tmp = dlg.getUser(); tmp.setFreigeschaltet(true); // Wenn er erfolgreich in die DB eingetragen wurde,zur // Tabelle hinzuf�gen if (serverConnection.usersave(tmp).getStatus() == 201) { addToTable(tmp); } } } }); usrpan.add(btnUserAdd); // Button zum bearbeiten eines in der Tabelle ausgew�hlten Users JButton btnUserEdit = new JButton("User bearbeiten"); btnUserEdit.setToolTipText("Zum Bearbeiten Benutzer in der Tabelle markieren"); btnUserEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int row = usrtbl.getSelectedRow(); if (row != -1) { // Daten aus der Tabelle abrufen und User erzeugen String t = (String) usrtbl.getValueAt(row, 0); String vn = (String) usrtbl.getValueAt(row, 1); String nn = (String) usrtbl.getValueAt(row, 2); String em = (String) usrtbl.getValueAt(row, 3); boolean r1 = (boolean) usrtbl.getValueAt(row, 4); boolean r2 = (boolean) usrtbl.getValueAt(row, 5); boolean r3 = (boolean) usrtbl.getValueAt(row, 6); boolean r4 = (boolean) usrtbl.getValueAt(row, 7); boolean r5 = (boolean) usrtbl.getValueAt(row, 8); User alt = new User(vn, nn, t, em, null, r1, r2, r3, r4, r5, true); // User an Bearbeiten dialog �bergeben userdialog dlg = new userdialog(frame, "User bearbeiten", alt, true, serverConnection); int response = dlg.showCustomDialog(); // Wenn ok ged\u00fcckt wird // neuen User abfragen if (response == 1) { User tmp = dlg.getUser(); tmp.setFreigeschaltet(true); // Wenn update erfolgreich war, alten user abfragen und // neu hinzuf�gen if (serverConnection.userupdate(tmp, em).getStatus() == 201) { removeFromTable(row); addToTable(tmp); // Falls eigener Benutzer bearbeitet wurde, Rechte // erneut pr�fen if (em.equals(current.geteMail())) { current = tmp; checkRights(); } } else JOptionPane.showMessageDialog(frame, "Update Fehlgeschlagen", "Update Fehler", JOptionPane.ERROR_MESSAGE); } } } }); usrpan.add(btnUserEdit); // L�schen eines ausgew�hlten Benutzers JButton btnUserDel = new JButton("User l\u00f6schen"); btnUserDel.setToolTipText("Zum L\u00f6schen Benutzer in der Tabelle markieren"); btnUserDel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int row = usrtbl.getSelectedRow(); if (row != -1) { int n = JOptionPane.showConfirmDialog(frame, "Sind Sie sicher, dass Sie diesen Benutzer l\u00f6schen wollen?", "Best�tigung", JOptionPane.YES_NO_OPTION); if (n == 0) { // Wenn L�schen erfolgreich war, aus der Tabelle // entfernen if (serverConnection.deluser((String) usrtbl.getValueAt(row, 3)).getStatus() != 201) { removeFromTable(row); } else JOptionPane.showMessageDialog(frame, "L\u00f6schen Fehlgeschlagen", "Fehler beim L\u00f6schen", JOptionPane.ERROR_MESSAGE); } } } }); usrpan.add(btnUserDel); // Zur�ck zur Startseite JButton btnHome = new JButton("Zur\u00fcck"); btnHome.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); usrpan.add(btnHome); JPanel usrcenter = new JPanel(); usrmg.add(usrcenter, BorderLayout.CENTER); usrcenter.setLayout(new BorderLayout(5, 5)); usrcenter.add(ussrscp); JPanel leftpan = new JPanel(); frame.getContentPane().add(leftpan, BorderLayout.WEST); } /** * �berpr�ft die Rechte des aktuell eingeloggten Benutzers und aktiviert * Buttons, auf die er Zugriff hat und deaktiviert Bttons, auf die er keinen * Zugriff hat */ protected void checkRights() { btnModulEinreichen.setEnabled(false); btnModulBearbeiten.setEnabled(false); btnVerwaltung.setEnabled(false); btnModulBearbeiten.setEnabled(false); btnUserVerwaltung.setEnabled(false); btnModulAkzeptieren.setEnabled(false); canReadMessages=false; welcome.remove(pnl_content); welcome.repaint(); if (current.getCreateModule()) { btnModulEinreichen.setEnabled(true); btnModulBearbeiten.setEnabled(true); canReadMessages=true; } if (current.getAcceptModule()) { btnModulBearbeiten.setEnabled(true); btnModulAkzeptieren.setEnabled(true); canReadMessages=true; } if (current.getManageSystem()) { btnVerwaltung.setEnabled(true); canReadMessages=true; } if (current.getManageUsers()) { btnUserVerwaltung.setEnabled(true); btnUserVerwaltung.setText("User Verwaltung"); canReadMessages=true; } else { btnUserVerwaltung.setEnabled(true); btnUserVerwaltung.setText("Account bearbeiten"); } if(canReadMessages){ welcome.add(pnl_content, BorderLayout.CENTER); nachrichten = serverConnection.getNachrichten(current.geteMail()); refreshMessageTable(); } showCard("welcome page"); } /** * Erstellt eine Card zur Bearbeitung von Modulen */ public void modulbearbeitenCard() { JPanel pnl_modedit = new JPanel(); pnl_modedit.setLayout(new BorderLayout(0, 0)); // Tab f�r akzeptierte und f�r nicht akzeptierte Module erstellen JTabbedPane tabs = new JTabbedPane(SwingConstants.TOP); pnl_modedit.add(tabs); JPanel nichtakzeptiert = new JPanel(); tabs.addTab("Noch nicht akzeptierte Module", null, nichtakzeptiert, null); nichtakzeptiert.setLayout(new BorderLayout(0, 0)); final JList<Modul> list_notack = new JList<Modul>(lm); list_notack.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_notack.setLayoutOrientation(JList.VERTICAL_WRAP); nichtakzeptiert.add(list_notack); JPanel buttonpnl = new JPanel(); nichtakzeptiert.add(buttonpnl, BorderLayout.SOUTH); // Button zum bearbeiten eines nicht akzeptierten Modules JButton btnModulBearbeiten = new JButton("Modul bearbeiten"); btnModulBearbeiten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Modul m = list_notack.getSelectedValue(); if (m != null) { // Abfragen, ob Modul in Bearbeitung ist m.setInbearbeitung(serverConnection.getModulInEdit(m.getName())); if (!m.isInbearbeitung()) { // Pr�fe, ob Benutzer das Rech hat, das Modul zu // Bearbeiten // Wenn er das Modul selbst erstellt hat, darf er es // auch bearbeiten // Ansonsten Pr�fen, ob es von einem Stellvertreter oder // Vorgesetzetn von ihm erstellt wurde boolean rights = false; if (m.getUser().equals(current.geteMail())) { rights = true; } else { ArrayList<String> rel = serverConnection.getUserRelation(current.geteMail()); if (rel.contains(m.getUser())) { rights = true; } } // Wenn er die Rechte dazu hat, Modul als in Bearbeitung // markieren und zur Bearbeitung wechseln if (rights) { mod.removeAll(); mod.add(modeditCard(m), BorderLayout.CENTER); m.setInbearbeitung(true); serverConnection.setModulInEdit(m); showCard("modBearbeiten"); } else { JOptionPane.showMessageDialog(frame, "Sie besitzen nicht die n\u00f6tigen Rechte, um dieses Modul zu bearbeiten!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "Dieses Modul befindet sich gerade in bearbeitung!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } } }); buttonpnl.add(btnModulBearbeiten); // Button zum akzeptieren eines Modules btnModulAkzeptieren.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Modul m = list_notack.getSelectedValue(); if (m != null) { // Pr�fe, ob Modul in Bearbeitung ist m.setInbearbeitung(serverConnection.getModulInEdit(m.getName())); if (!m.isInbearbeitung()) { if (m.getName().isEmpty()) { JOptionPane.showMessageDialog(frame, "Bei diesem Modul sind nicht alle Felder ausgef�llt!", "Fehler im Modul", JOptionPane.ERROR_MESSAGE); } else { // Pr�fe, ob ein Feld f�r das Dezernat 2 markiert // wurde // und ob alle Felder ausgef�llt wurden boolean hasDezernat = false; boolean isCorrect = true; ArrayList<Feld> felder = m.getFelder(); for (int i = 0; i < felder.size(); i++) { if (felder.get(i).getValue().isEmpty()) { JOptionPane.showMessageDialog(frame, "Bei diesem Modul sind nicht alle Felder ausgef�llt!", "Fehler im Modul", JOptionPane.ERROR_MESSAGE); isCorrect = false; break; } if (felder.get(i).isDezernat()) { hasDezernat = true; } } if (isCorrect) { boolean checked = true; // Wenn Felder als Dezernat 2 markiert wurden, // nach Best�tigung fragen if (hasDezernat) { int n = JOptionPane.showConfirmDialog(frame, "Dieses Modul besitzt Felder, die vom Dezernat2 �berpr�ft werden m�ssen, wurde das getan?", "Best�tigung", JOptionPane.YES_NO_OPTION); if (n == 0) { checked = true; } else { checked = false; } } if (checked) { // Bei best�tigung Modul akzeptieren und // Listen neu abrufen // dann zur Bearbeiten �bersicht wechseln serverConnection.acceptModul(m); ArrayList<Modul> module = serverConnection.getModule(false); lm.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm.addElement(module.get(i)); } module = serverConnection.getModule(true); lm_ack.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm_ack.addElement(module.get(i)); } showCard("modulbearbeiten"); } } } } else { JOptionPane.showMessageDialog(frame, "Dieses Modul befindet sich gerade in bearbeitung!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } } }); buttonpnl.add(btnModulAkzeptieren); // Zur�ck zur Startseite JButton btnZurck = new JButton("Zur\u00FCck"); btnZurck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); buttonpnl.add(btnZurck); // akzeptierte Module JPanel akzeptiert = new JPanel(); tabs.addTab("akzeptierte Module", null, akzeptiert, null); tabs.setEnabledAt(1, true); akzeptiert.setLayout(new BorderLayout(0, 0)); final JList<Modul> list_ack = new JList<Modul>(lm_ack); list_ack.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_ack.setLayoutOrientation(JList.VERTICAL_WRAP); akzeptiert.add(list_ack); JPanel buttonpnl2 = new JPanel(); akzeptiert.add(buttonpnl2, BorderLayout.SOUTH); // akzeptierte Module bearbeiten JButton btnModulBearbeiten2 = new JButton("Modul bearbeiten"); btnModulBearbeiten2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Modul m = list_ack.getSelectedValue(); if (m != null) { // Pr�fe, ob Modul in Bearbeitung ist m.setInbearbeitung(serverConnection.getModulInEdit(m.getName())); if (!m.isInbearbeitung()) { // Pr�fe, ob User das Recht hat, dieses Modul zu // bearbeiten boolean rights = false; if (m.getUser().equals(current.geteMail())) { rights = true; } else { ArrayList<String> rel = serverConnection.getUserRelation(current.geteMail()); if (rel.contains(m.getUser())) { rights = true; } } if (rights) { // Zur Bearbeitung wechseln mod.removeAll(); mod.add(modeditCard(m), BorderLayout.CENTER); showCard("modBearbeiten"); } else { JOptionPane.showMessageDialog(frame, "Sie besitzen nicht die n\u00f6tigen Rechte, um dieses Modul zu bearbeiten!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "Dieses Modul befindet sich gerade in bearbeitung!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } } }); buttonpnl2.add(btnModulBearbeiten2); // Zur�ck zur Startseite JButton btnZurck2 = new JButton("Zur\u00FCck"); btnZurck2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); buttonpnl2.add(btnZurck2); cards.add(pnl_modedit, "modulbearbeiten"); } /** * Liefert ein Panel, dass mit den Daten von Modul m ausgef�llt ist Die * Felder sind dabei nicht mehr bearbeitbar * * @return JPanel mit Daten ausgef�lltes Panel * @param m * Zu bearbeitendes Modul */ private JPanel modeditCardPrev(Modul m) { final JPanel pnl_editmod = new JPanel(); final JPanel pnl_mod_prev = new JPanel(); // Felder vom Modul abfragen final ArrayList<Feld> felder = m.getFelder(); final ArrayList<String> labels = new ArrayList<String>(); for (int i = 0; i < felder.size(); i++) { labels.add(felder.get(i).getLabel()); } final Dimension preferredSize = new Dimension(120, 20); pnl_editmod.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(pnl_mod_prev, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); pnl_mod_prev.setLayout(new BoxLayout(pnl_mod_prev, BoxLayout.Y_AXIS)); // Panel Zuordnung + Platzhalter JPanel pnl_Z = new JPanel(); pnl_Z.setLayout(new BoxLayout(pnl_Z, BoxLayout.X_AXIS)); JLabel label_MH = new JLabel("Zuordnung"); label_MH.setPreferredSize(preferredSize); pnl_Z.add(label_MH); // Zuordnugen vom Modul abfragen // final DefaultListModel<Zuordnung> lm = new // DefaultListModel<Zuordnung>(); // typen = m.getZuordnungen(); // for (int i = 0; i < typen.size(); i++) { // lm.addElement(typen.get(i)); // } // JList<Zuordnung> zlist = new JList<Zuordnung>(lm); // pnl_Z.add(zlist); pnl_mod_prev.add(pnl_Z); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); // Restliche Felder erzeugen JPanel jg = new JPanel(); jg.setLayout(new BoxLayout(jg, BoxLayout.X_AXIS)); JLabel lbl_jg = new JLabel("Jahrgang"); lbl_jg.setPreferredSize(preferredSize); jg.add(lbl_jg); // JTextArea txt_jg = new JTextArea(m.getJahrgang() + ""); // txt_jg.setLineWrap(true); // txt_jg.setEditable(false); // jg.add(txt_jg); pnl_mod_prev.add(jg); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); JPanel name = new JPanel(); name.setLayout(new BoxLayout(name, BoxLayout.X_AXIS)); JLabel lbl_n = new JLabel("Name"); lbl_n.setPreferredSize(preferredSize); name.add(lbl_n); JTextArea txt_n = new JTextArea(m.getName()); txt_n.setLineWrap(true); txt_n.setEditable(false); name.add(txt_n); pnl_mod_prev.add(name); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); for (int i = 0; i < m.getFelder().size(); i++) { Feld f = m.getFelder().get(i); JPanel pnl = new JPanel(); pnl.setLayout(new BoxLayout(pnl, BoxLayout.X_AXIS)); JLabel label = new JLabel(f.getLabel()); label.setPreferredSize(preferredSize); pnl.add(label); // Felder sind hier nicht bearbeitbar JTextArea txt = new JTextArea(f.getValue()); txt.setLineWrap(true); txt.setEditable(false); pnl.add(txt); JCheckBox dez = new JCheckBox("Dezernat 2", f.isDezernat()); dez.setEnabled(false); pnl.add(dez); pnl_mod_prev.add(pnl); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); } pnl_editmod.add(scrollPane); return pnl_editmod; } /** * Liefert ein Panel, dass mit den Daten von Modul m ausgef�llt ist * * @return JPanel mit Daten ausgef�lltes Panel * @param m * Zu bearbeitendes Modul */ private JPanel modeditCard(final Modul m) { // Alle Felder entfernen // Buttonmap leeren final JPanel pnl_editmod = new JPanel(); modul_panel_edit.removeAll(); if (!buttonmap.isEmpty()) { for (int i = 0; i < buttonmap.size(); i++) buttonmap.remove(i); } // Felder vom Modul abfragen final ArrayList<Feld> felder = m.getFelder(); final ArrayList<String> labels = new ArrayList<String>(); for (int i = 0; i < felder.size(); i++) { labels.add(felder.get(i).getLabel()); } final Dimension preferredSize = new Dimension(120, 20); pnl_editmod.setLayout(new BorderLayout(0, 0)); JPanel pnl_bottom = new JPanel(); pnl_editmod.add(pnl_bottom, BorderLayout.SOUTH); // Button zur anzeige der vorherigen Version JButton alt = new JButton("Vorherige Version"); alt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { int v = m.getVersion() - 1; if (v > 0) { String name = m.getName(); Modul pre = serverConnection.getModul(name, v); if (pre != null) JOptionPane.showMessageDialog(frame, modeditCardPrev(pre), "Vorherige Version", 1); } else { JOptionPane.showMessageDialog(frame, "Keine Vorherige Version vorhanden!", "Fehler", JOptionPane.ERROR_MESSAGE); } } }); pnl_bottom.add(alt); // Button zum erzeugen eines neuen Feldes JButton btnNeuesFeld = new JButton("Neues Feld"); btnNeuesFeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String text = "Name des Feldes"; String name = JOptionPane.showInputDialog(frame, text); try { while (name.isEmpty() || labels.contains(name)) { Object[] params = { "Bitte geben Sie eine g�ltige Bezeichnung ein!", text }; name = JOptionPane.showInputDialog(frame, params); } labels.add(name); // Platzhalter JPanel pnl_tmp = new JPanel(); modul_panel_edit.add(pnl_tmp); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); // Abfrage der Anzahl an Feldern int numOfPanels = modul_panel_edit.getComponentCount(); pnl_tmp.setLayout(new BoxLayout(pnl_tmp, BoxLayout.X_AXIS)); JLabel label_tmp = new JLabel(name); label_tmp.setPreferredSize(preferredSize); pnl_tmp.add(label_tmp); JTextArea txt_tmp = new JTextArea(); txt_tmp.setLineWrap(true); pnl_tmp.add(txt_tmp); JCheckBox dez = new JCheckBox("Dezernat 2", false); pnl_tmp.add(dez); // Feld wieder entfernen JButton btn_tmp_entf = new JButton("Entfernen"); btn_tmp_entf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = buttonmap.get(e.getSource()); // Bezeichnung aus Liste entfernen String name = ((JLabel) ((JPanel) modul_panel_edit.getComponent(id)).getComponent(0)).getText(); labels.remove(name); // Feld mit ID id von Panel entfernen modul_panel_edit.remove(id); // Platzhalter entfernen modul_panel_edit.remove(id - 1); // Aus ButtonMap entfernen buttonmap.remove(e.getSource()); // ids der Buttons �ndern, damit auch ein Feld aus // der Mitte gel�scht werden kann HashMap<JButton, Integer> tmpmap = new HashMap<JButton, Integer>(); Iterator<Entry<JButton, Integer>> entries = buttonmap.entrySet().iterator(); while (entries.hasNext()) { Entry<JButton, Integer> thisEntry = entries.next(); JButton key = thisEntry.getKey(); int value = thisEntry.getValue(); if (value > id) { value = value - 2; } tmpmap.put(key, value); } buttonmap = tmpmap; modul_panel_edit.revalidate(); } }); // Button btn_tmp_entf mit ID (numOfPanels-2) zu ButtonMap buttonmap.put(btn_tmp_entf, numOfPanels - 2); pnl_tmp.add(btn_tmp_entf); modul_panel_edit.revalidate(); } catch (NullPointerException npe) { // nichts tuen bei Abbruch } } }); pnl_bottom.add(btnNeuesFeld); // Zur�ck zur Startseite JButton btnHome = new JButton("Zur\u00fcck"); btnHome.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Panel wider neu erzeugen, // Modul als nicht in Bearbeitung markieren modul_panel_edit.removeAll(); modul_panel_edit.revalidate(); m.setInbearbeitung(false); serverConnection.setModulInEdit(m); modulbearbeitenCard(); showCard("modulbearbeiten"); } }); pnl_bottom.add(btnHome); JScrollPane scrollPane = new JScrollPane(modul_panel_edit, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); modul_panel_edit.setLayout(new BoxLayout(modul_panel_edit, BoxLayout.Y_AXIS)); // Panel Zuordnung + Platzhalter JPanel pnl_Z = new JPanel(); pnl_Z.setLayout(new BoxLayout(pnl_Z, BoxLayout.X_AXIS)); JLabel label_MH = new JLabel("Zuordnung"); label_MH.setPreferredSize(preferredSize); pnl_Z.add(label_MH); // Liste ausgew�hlter Zuordnungen // final DefaultListModel<Zuordnung> lm_Z = new // DefaultListModel<Zuordnung>(); // typen = m.getZuordnungen(); // for (int i = 0; i < typen.size(); i++) { // lm_Z.addElement(typen.get(i)); // } // final JList<Zuordnung> zlist = new JList<Zuordnung>(lm_Z); // zlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // // pnl_Z.add(zlist); // typen = serverConnection.getZuordnungen(); // cbmodel_Z.removeAllElements(); // for (int i = 0; i < typen.size(); i++) { // cbmodel_Z.addElement(typen.get(i)); // } // // Zur auswahlstehende Zuordnungen // final JComboBox<Zuordnung> cb_Z = new // JComboBox<Zuordnung>(cbmodel_Z); // cb_Z.setMaximumSize(new Dimension(cb_Z.getMaximumSize().width, 20)); // // pnl_Z.add(cb_Z); // // // Zuordnung ausw�hlen // JButton z_btn = new JButton("Zuordnung ausw\u00e4hlen"); // z_btn.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // if (!lm_Z.contains(cb_Z.getSelectedItem())) // lm_Z.addElement((Zuordnung) cb_Z.getSelectedItem()); // } // }); // pnl_Z.add(z_btn); // // // Zuordnung wieder entfernen // JButton btnZuordnungEntfernen = new JButton("Zuordnung entfernen"); // btnZuordnungEntfernen.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // int i = zlist.getSelectedIndex(); // if (i > -1) { // lm_Z.remove(i); // } // } // }); // pnl_Z.add(btnZuordnungEntfernen); modul_panel_edit.add(pnl_Z); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); // modul_panel_edit.add(defaultmodulPanel("Jahrgang", m.getJahrgang() + // "", false)); // modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); JPanel pnl = new JPanel(); pnl.setLayout(new BoxLayout(pnl, BoxLayout.X_AXIS)); JLabel label = new JLabel("Name"); label.setPreferredSize(preferredSize); pnl.add(label); JTextArea txt = new JTextArea(m.getName()); txt.setLineWrap(true); pnl.add(txt); txt.setEditable(false); modul_panel_edit.add(pnl); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); // Felder erzeugen und f�llen for (int i = 0; i < m.getFelder().size(); i++) { Feld f = m.getFelder().get(i); JPanel feld = defaultmodulPanel(f.getLabel(), f.getValue(), f.isDezernat()); // Wenn es kein Standart Feld ist, einen entfernen Button hinzuf�gen if (!defaultlabels.contains(f.getLabel())) { int numOfPanels = modul_panel_edit.getComponentCount(); JButton btn_tmp_entf = new JButton("Entfernen"); btn_tmp_entf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = buttonmap.get(e.getSource()); // Bezeichnung aus Liste entfernen String name = ((JLabel) ((JPanel) modul_panel_edit.getComponent(id)).getComponent(0)).getText(); labels.remove(name); // Feld mit ID id von Panel entfernen modul_panel_edit.remove(id); // Platzhalter entfernen modul_panel_edit.remove(id - 1); // Aus ButtonMap entfernen buttonmap.remove(e.getSource()); // ids der Buttons �ndern, damit auch ein Feld aus // der Mitte gel�scht werden kann HashMap<JButton, Integer> tmpmap = new HashMap<JButton, Integer>(); Iterator<Entry<JButton, Integer>> entries = buttonmap.entrySet().iterator(); while (entries.hasNext()) { Entry<JButton, Integer> thisEntry = entries.next(); JButton key = thisEntry.getKey(); int value = thisEntry.getValue(); if (value > id) { value = value - 2; } tmpmap.put(key, value); } buttonmap = tmpmap; modul_panel_edit.revalidate(); modul_panel_edit.repaint(); } }); feld.add(btn_tmp_entf); // Button btn_tmp_entf mit ID (numOfPanels-2) zu ButtonMap buttonmap.put(btn_tmp_entf, numOfPanels); } modul_panel_edit.add(feld); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); } // Button zum annehmen eines Modules JButton btnOk = new JButton("Annehmen"); btnOk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // ArrayList<Zuordnung> zlist = new ArrayList<Zuordnung>(); String jg = ((JTextArea) ((JPanel) modul_panel_edit.getComponent(2)).getComponent(1)).getText(); int jahrgang; try { jahrgang = Integer.parseInt(jg); } catch (NumberFormatException nfe) { jahrgang = 0; } // for (int i = 0; i < lm_Z.getSize(); i++) { // zlist.add(lm_Z.getElementAt(i)); // } // Pr�fe ob min. eine Zuordnung ausgew�hlt ist und ein korrekter // Jahrgang ausgew�hlt wurde // if (!zlist.isEmpty()) { // // if (jahrgang != 0) { // // String Name = ((JTextArea) ((JPanel) // modul_panel_edit.getComponent(4)).getComponent(1)).getText(); // // if (Name.isEmpty()) { // JOptionPane.showMessageDialog(frame, // "Bitte f�llen Sie alle Felder aus!", "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } else { // // boolean filled = true; // ArrayList<Feld> felder = new ArrayList<Feld>(); // // Eintraege der Reihe nach auslesen // for (int i = 6; i < modul_panel_edit.getComponentCount(); i = // i + 2) { // JPanel tmp = (JPanel) modul_panel_edit.getComponent(i); // JLabel tmplbl = (JLabel) tmp.getComponent(0); // JTextArea tmptxt = (JTextArea) tmp.getComponent(1); // // boolean dezernat2 = ((JCheckBox) // tmp.getComponent(2)).isSelected(); // String value = tmptxt.getText(); // String label = tmplbl.getText(); // // Pr�fe, ob Feld ausgef�llt ist // if (value.isEmpty()) { // filled = false; // break; // } // felder.add(new Feld(label, value, dezernat2)); // } // if (filled == true) { // // Wenn alle ausgef�llt sind, Modul erzeugen und // // bei Best�tigung einreichen // int version = serverConnection.getModulVersion(Name) + 1; // // Date d = new Date(); // // Modul neu = new Modul(Name, zlist, jahrgang, felder, version, // d, false, false, current.geteMail()); // // int n = JOptionPane.showConfirmDialog(frame, // "Sind Sie sicher, dass Sie dieses Modul einreichen wollen?", // "Best�tigung", JOptionPane.YES_NO_OPTION); // if (n == 0) { // m.setInbearbeitung(false); // serverConnection.setModul(neu); // labels.removeAll(labels); // modul_panel_edit.removeAll(); // modul_panel_edit.revalidate(); // // // Listen neu einlesen // ArrayList<Modul> module = serverConnection.getModule(false); // lm.removeAllElements(); // for (int i = 0; i < module.size(); i++) { // lm.addElement(module.get(i)); // } // // module = serverConnection.getModule(true); // lm_ack.removeAllElements(); // for (int i = 0; i < module.size(); i++) { // lm_ack.addElement(module.get(i)); // } // showCard("modulbearbeiten"); // } // } else { // // } // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte geben Sie einen g�ltigen Wert f�r den Jahrgang ein!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte w�hlen Sie min. einen Zuordnung aus!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } } }); pnl_bottom.add(btnOk); pnl_editmod.add(scrollPane); return pnl_editmod; } /** * Erstellt eine Card zur Auswahl des Studienganges */ @SuppressWarnings("serial") private void studiengangCard() { JPanel studiengangshow = new JPanel(); cards.add(studiengangshow, "studiengang show"); studiengangshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable studtable = new JTable(); JScrollPane studscp = new JScrollPane(studtable); studtable.setBorder(new LineBorder(new Color(0, 0, 0))); studtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); studiengangshow.add(studscp); studiengangshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Studieng�ngen studmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Studiengang" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; studtable.setModel(studmodel); studtransferstring = ""; // Wechseln zur Jahrgangsauswahl, wenn ein Studiengang ausgew�hlt wurde goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (studtable.getSelectedRow() != -1) { int openrow = studtable.getSelectedRow(); studtransferstring = (String) studtable.getValueAt(openrow, 0); modhandshowCard(); showCard("modbuch show"); } } }); // Zur�ck zur Startseite back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); } /** * Erstellt eine Card zur Auswahl des Jahrgangs */ @SuppressWarnings("serial") private void modhandshowCard() { JPanel modbuchshow = new JPanel(); cards.add(modbuchshow, "modbuch show"); modbuchshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable modbuchtable = new JTable(); JScrollPane modtypscp = new JScrollPane(modbuchtable); modbuchtable.setBorder(new LineBorder(new Color(0, 0, 0))); modbuchtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); modbuchshow.add(modtypscp); modbuchshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Jahrg�ngen modbuchmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Modulhandbuch Jahrgang" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; int zws = 0; // Tabelle f�llen modbuchtable.setModel(modbuchmodel); modbuchmodel.setRowCount(0); System.out.println(studienlist.get(0).getName()); System.out.println(studtransferstring); - System.out.println(studienlist.get(0).getModbuch().get(0).getId()); + //System.out.println(studienlist.get(0).getModbuch().get(0).getId()); //modulhandlist = serverConnection.getModulhandbuch(studtransferstring); for(int i = 0; i < studienlist.size(); i++){ if(studienlist.get(i).getName().equalsIgnoreCase(studtransferstring)){ zws = i; break; } } for (int i = 0; i < studienlist.get(0).getModbuch().size(); i++) { addToTable(studienlist.get(0).getModbuch().get(i)); } modbuchtransferstring = ""; // Wechseln zur Auswahl von Zuordnungen goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (modbuchtable.getSelectedRow() != -1) { int openrow = modbuchtable.getSelectedRow(); modbuchtransferstring = (String) modbuchtable.getValueAt(openrow, 0); modtypshowCard(); showCard("modtyp show"); } } }); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("studiengang show"); } }); } /** * Erstellt eine Card zur Auswahl des Modultypes */ @SuppressWarnings("serial") private void modtypshowCard() { JPanel modtypshow = new JPanel(); cards.add(modtypshow, "modtyp show"); modtypshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable modtyptable = new JTable(); JScrollPane modtypscp = new JScrollPane(modtyptable); modtyptable.setBorder(new LineBorder(new Color(0, 0, 0))); modtyptable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); modtypshow.add(modtypscp); modtypshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Zuordnungen modtypmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Modul Typ" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; // Tabelle f�llen modtyptable.setModel(modtypmodel); modtypmodel.setRowCount(0); int test = 0; for (int i = 0; i < studienlist.size(); i++) { if (studienlist.get(i).getName().equalsIgnoreCase(studtransferstring)) { test = studienlist.get(i).getId(); break; } } // for (int i = 0; i < typen.size(); i++) { // if (test == (typen.get(i).getSid())) // addToTable(typen.get(i).getName()); // } modtyptransferstring = ""; // Wechseln zur Anzeige mit Modulen goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (modtyptable.getSelectedRow() != -1) { int openrow = modtyptable.getSelectedRow(); modtyptransferstring = (String) modtyptable.getValueAt(openrow, 0); modshowCard(); showCard("mod show"); } } }); // Zur�ck zur vorherigen Ansicht back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("modbuch show"); } }); } /** * Erstellt eine Card zur Auswahl eines Modules */ @SuppressWarnings("serial") private void modshowCard() { JPanel modshow = new JPanel(); cards.add(modshow, "mod show"); modshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable modshowtable = new JTable(); JScrollPane modtypscp = new JScrollPane(modshowtable); modshowtable.setBorder(new LineBorder(new Color(0, 0, 0))); modshowtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); modshow.add(modtypscp); modshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Modulen modshowmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Module" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { return false; } }; // Tabelle f�llen modshowtable.setModel(modshowmodel); modshowmodel.setRowCount(0); selectedmodullist = serverConnection.getselectedModul(studtransferstring, modtyptransferstring, modbuchtransferstring); for (int i = 0; i < selectedmodullist.size(); i++) { addToTable(selectedmodullist.get(i)); } modulselectionstring = ""; // Wechsel zur Anzeige des Modules goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (modshowtable.getSelectedRow() != -1) { int openrow = modshowtable.getSelectedRow(); modulselectionstring = (String) modshowtable.getValueAt(openrow, 0); modCard(); showCard("selmodshow"); } } }); // Zur�ck zur vorherigen Ansicht back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("modtyp show"); } }); } /** * Erstellt eine Card zur Anzeige eines Modules */ private void modCard() { JPanel modshow = new JPanel(); cards.add(modshow, "selmodshow"); modshow.setLayout(new BorderLayout(0, 0)); JPanel modpanel = new JPanel(); JButton pdfbtn = new JButton("Als PDF ausgeben"); JButton back = new JButton("Zur\u00FCck"); JPanel btnpan = new JPanel(); btnpan.add(back); btnpan.add(pdfbtn); modshow.add(btnpan, BorderLayout.SOUTH); JScrollPane modscp = new JScrollPane(modpanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); modshow.add(modscp, BorderLayout.CENTER); Modul zws = null; modpanel.setLayout(new BoxLayout(modpanel, BoxLayout.Y_AXIS)); for (int i = 0; i < selectedmodullist.size(); i++) { if (selectedmodullist.get(i).getName().equalsIgnoreCase(modulselectionstring)) { zws = selectedmodullist.get(i); } } // Felder erstellen modpanel.add(modulPanel("Name", zws.getName())); modpanel.add(modulPanel("Jahrgang", modbuchtransferstring)); // for (int i = 0; i < zws.getZuordnungen().size(); i++) { // modpanel.add(modulPanel("Zuordnung", // zws.getZuordnungen().get(i).toString())); // } for (int i = 0; i < zws.getFelder().size(); i++) { modpanel.add(modulPanel(zws.getFelder().get(i).getLabel(), zws.getFelder().get(i).getValue())); } // Pdf f�r das Modul erstellen pdfbtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub try { serverConnection.toPdf(modulselectionstring); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); // Zur�ck zur vorherigen Ansicht back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("mod show"); } }); } /** * Wird aufgerufen, wenn keine Verbindung zum Server besteht Dabei wird der * Benutzer auf den Standart User zur�ckgesetzt */ public static void noConnection() { JOptionPane.showMessageDialog(frame, "Keine Verbindung zum Server!", "Verbindungsfehler", JOptionPane.ERROR_MESSAGE); current = new User("gast", "gast", "", "[email protected]", "d4061b1486fe2da19dd578e8d970f7eb", false, false, false, false, false, true); btnModulEinreichen.setEnabled(false); btnVerwaltung.setEnabled(false); btnModulBearbeiten.setEnabled(false); btnModulArchiv.setEnabled(true); btnUserVerwaltung.setEnabled(false); btnLogin.setText("Einloggen"); showCard("welcome page"); } }
true
true
private void homecard() { final ArrayList<String> dialogs = new ArrayList<String>(); cards.add(welcome, "welcome page"); welcome.setLayout(new BorderLayout(0, 0)); pnl_content.setLayout(new BoxLayout(pnl_content, BoxLayout.Y_AXIS)); JPanel pnl_day = new JPanel(); pnl_content.add(pnl_day); JLabel lblStichtag = new JLabel("Stichtag f\u00FCr das Einreichen von Modulen: 30.08.13"); pnl_day.add(lblStichtag); lblStichtag.setHorizontalAlignment(SwingConstants.CENTER); lblStichtag.setAlignmentY(0.0f); lblStichtag.setForeground(Color.RED); lblStichtag.setFont(new Font("Tahoma", Font.BOLD, 14)); JPanel pnl_messages = new JPanel(); pnl_content.add(pnl_messages); pnl_messages.setLayout(new BoxLayout(pnl_messages, BoxLayout.Y_AXIS)); JPanel pnl_mestop = new JPanel(); pnl_messages.add(pnl_mestop); pnl_mestop.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5)); JLabel lblNachrichten = new JLabel("Nachrichten:"); pnl_mestop.add(lblNachrichten); lblNachrichten.setVerticalAlignment(SwingConstants.BOTTOM); lblNachrichten.setHorizontalAlignment(SwingConstants.CENTER); JScrollPane scrollPane = new JScrollPane(); pnl_messages.add(scrollPane); messagemodel = new DefaultTableModel(new Object[][] { { Boolean.FALSE, "", null, null }, }, new String[] { "", "Von", "Betreff", "Datum" }) { Class[] columnTypes = new Class[] { Boolean.class, String.class, String.class, String.class }; public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } boolean[] columnEditables = new boolean[] { true, false, false, false }; public boolean isCellEditable(int row, int column) { return columnEditables[column]; } }; refreshMessageTable(); tblmessages = new JTable(messagemodel); scrollPane.setViewportView(tblmessages); tblmessages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tblmessages.setFillsViewportHeight(true); tblmessages.setShowVerticalLines(false); tblmessages.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int row = tblmessages.getSelectedRow(); Nachricht n = nachrichten.get(row); nachrichten.remove(row); n.setGelesen(true); if(!dialogs.contains(n.toString())){ dialogs.add(n.toString()); MessageDialog dialog = new MessageDialog(n); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } nachrichten.add(n); refreshMessageTable(); } } }); JPanel pnl_mesbot = new JPanel(); pnl_messages.add(pnl_mesbot); JButton btnNeu = new JButton("Neu"); btnNeu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int x = -1; int von = 1; int an = 2; String betreff = "Neuer Test"; Date datum = new Date(); boolean gelesen = false; String nachricht = "foooooooooooo blabulb fooooooooo"; Nachricht neu = new Nachricht(x, von, an, betreff, datum, gelesen, nachricht); //abge�ndert damit das prog wieder startet nachrichten.add(neu); refreshMessageTable(); } }); pnl_mesbot.add(btnNeu); JButton btnAlsGelesenMarkieren = new JButton("Als gelesen markieren"); btnAlsGelesenMarkieren.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { for (int i = 0; i < messagemodel.getRowCount(); i++) { if ((boolean) messagemodel.getValueAt(i, 0)) { nachrichten.get(i).setGelesen(true); } } refreshMessageTable(); } }); pnl_mesbot.add(btnAlsGelesenMarkieren); JButton btnAlsUngelesenMarkieren = new JButton("Als ungelesen markieren"); btnAlsUngelesenMarkieren.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (int i = 0; i < messagemodel.getRowCount(); i++) { if ((boolean) messagemodel.getValueAt(i, 0)) { nachrichten.get(i).setGelesen(false); } } refreshMessageTable(); } }); pnl_mesbot.add(btnAlsUngelesenMarkieren); JButton btnLschen = new JButton("L\u00F6schen"); btnLschen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ArrayList<Nachricht> tmp = new ArrayList<Nachricht>(); for (int i = 0; i < messagemodel.getRowCount(); i++) { if ((boolean) messagemodel.getValueAt(i, 0)) { tmp.add(nachrichten.get(i)); } } nachrichten.removeAll(tmp); refreshMessageTable(); } }); pnl_mesbot.add(btnLschen); JPanel pnl_welc = new JPanel(); welcome.add(pnl_welc, BorderLayout.NORTH); JLabel lblNewLabel = new JLabel("Willkommen beim Modul Management System"); pnl_welc.add(lblNewLabel); } private void refreshMessageTable() { Collections.sort(nachrichten, new Comparator<Nachricht>() { public int compare(Nachricht n1, Nachricht n2) { return n1.getDatum().compareTo(n2.getDatum()) * -1; } }); messagemodel.setRowCount(0); for (int i = 0; i < nachrichten.size(); i++) { addToTable(nachrichten.get(i)); } } protected void addToTable(Nachricht neu) { if(neu.isGelesen()){ messagemodel.addRow(new Object[] { false, neu.getAbsender(), neu.getBetreff(), neu.getDatumString() }); } else { messagemodel.addRow(new Object[] { false, "<html><b>" +neu.getAbsender()+ "</b></html>", "<html><b>" +neu.getBetreff()+ "</b></html>", "<html><b>" +neu.getDatumString()+ "</b></html>" }); } } /** * Erstellt den linke Teil der GUI * */ private void leftscr() { btnLogin.setToolTipText("Klicken Sie hier, um in das MMS einzuloggen."); btnModulAkzeptieren.setToolTipText("Klicken Sie hier, um das ausgew�hlte Modul zu akzeptieren. Damit wird es freigegeben und in der Liste der aktuellen Module angezeigt."); btnModulArchiv.setToolTipText("Klicken Sie hier, um das Archiv der aktuellen Module zu durchst�bern."); btnModulBearbeiten.setToolTipText("Klicken Sie hier, um bereits vorhandene Module zu bearbeiten."); btnModulEinreichen.setToolTipText("Klicken Sie hier, um das Modul einzureichen. Damit wird es der verantwortlichen Stelle vorgelegt. Das Modul wird erst nach der Best�tigung der verantwortlichen Stelle in der Liste der aktuellen Module angezeigt."); btnUserVerwaltung.setToolTipText("Klicken Sie hier, um die Benutzerverwaltung aufzurufen. Hier k�nnen Sie neue Benutzer anlegen, deren Daten �ndern und ihre Rechte im MMS festlegen."); btnVerwaltung.setToolTipText("Klicken Sie hier, um die Verwaltung zu �ffnen. Hier k�nnen Sie m�gliche Studieng�nge festlegen, f�r die es Modulhandb�cher geben kann, die Deadline f�r die Modulhandb�cher aktualisieren und Verwalter f�r bestimmte Module festlegen."); JPanel leftpan = new JPanel(); frame.getContentPane().add(leftpan, BorderLayout.WEST); JPanel left = new JPanel(); leftpan.add(left); left.setLayout(new GridLayout(0, 1, 5, 20)); // Button zum Einreichen eines Modules left.add(btnModulEinreichen); btnModulEinreichen.setEnabled(false); btnModulEinreichen.setPreferredSize(btnSz); btnModulEinreichen.setAlignmentX(Component.CENTER_ALIGNMENT); btnModulEinreichen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Abfrage aller Zuordnungen und Studieng�nge aus der Datenbank // Danach Modelle f�llen und zur Card wechseln // typen = serverConnection.getZuordnungen(); studienlist = serverConnection.getStudiengaenge(); cbmodel.removeAllElements(); for (int i = 0; i < studienlist.size(); i++) { cbmodel.addElement(studienlist.get(i)); } // cbmodel_Z.removeAllElements(); // for (int i = 0; i < typen.size(); i++) { // cbmodel_Z.addElement(typen.get(i)); // } showCard("newmodule"); } }); // Button zum Bearbeiten eines Modules left.add(btnModulBearbeiten); btnModulBearbeiten.setEnabled(false); btnModulBearbeiten.setPreferredSize(btnSz); btnModulBearbeiten.setAlignmentX(Component.CENTER_ALIGNMENT); btnModulBearbeiten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Abfrage alles nicht nicht akzeptierten Module // Danach Modell f�llen ArrayList<Modul> module = serverConnection.getModule(false); lm.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm.addElement(module.get(i)); } // Abfrage alles nicht akzeptierten Module // Danach Modell f�llen module = serverConnection.getModule(true); lm_ack.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm_ack.addElement(module.get(i)); } // Zur card mit �bersicht an Modulen wechseln showCard("modulbearbeiten"); } }); // Button zum Login left.add(btnLogin); btnLogin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Verbindung zum Server current = serverConnection.login(current.geteMail(), current.getPassword()); if (current != null) { // Wenn noch nicht eingeloggt, einloggen if (current.geteMail().equals("[email protected]")) { logindialog log = new logindialog(frame, "Login", serverConnection); int resp = log.showCustomDialog(); if (resp == 1) { // User �bernehmen current = log.getUser(); serverConnection = log.getServerConnection(); btnLogin.setText("Ausloggen"); // Auf Rechte pr�fen checkRights(); } } // Wenn bereits eingeloggt, ausloggen else { current = new User("gast", "gast", "", "[email protected]", "d4061b1486fe2da19dd578e8d970f7eb", false, false, false, false, false, true); if (serverConnection.isConnected() == SUCCES) { checkRights(); } btnLogin.setText("Einloggen"); btnUserVerwaltung.setText("User Verwaltung"); btnUserVerwaltung.setEnabled(false); showCard("welcome page"); } } else { // Wenn keine Verbindung besteht noConnection(); } } }); btnLogin.setPreferredSize(btnSz); btnLogin.setAlignmentX(Component.CENTER_ALIGNMENT); // Button zur Userverwaltung btnUserVerwaltung.setEnabled(false); left.add(btnUserVerwaltung); btnUserVerwaltung.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Wenn User das Recht hat, um Benutzer zu Verwalten, // dann Anzeige der Benutzerverwaltung if (current.getManageUsers()) { // Tabelle leeren tmodel.setRowCount(0); // Tabelle mit neuen daten f�llen worklist = serverConnection.userload("true"); for (int i = 0; i < worklist.size(); i++) { // Wenn der User noch nicht freigeschaltet wurde, // zur Liste mit neuen Benutzern hinzuf�gen if (worklist.get(i).isFreigeschaltet()) { addToTable(worklist.get(i)); } else { neueUser.add(worklist.get(i)); } } // Zur Userverwaltungs Card wechseln showCard("user managment"); // Einblendung aller neuen User for (int i = 0; i < neueUser.size(); i++) { userdialog dlg = new userdialog(frame, "User best�tigen", neueUser.get(i), true, serverConnection); int response = dlg.showCustomDialog(); // Bei Best�tigung, neuen User freischalten und e-Mail // senden User tmp = dlg.getUser(); if (response == 1) { tmp.setFreigeschaltet(true); if (SendMail.send(current.geteMail(), neueUser.get(i).geteMail(), "Sie wurden freigeschaltet!") == 1) { tmp.setFreigeschaltet(true); if (serverConnection.userupdate(tmp, tmp.geteMail()).getStatus() == 201) { addToTable(tmp); neueUser.remove(i); } } // Ansonsten m�glichkeit ihn wieder zu l�schen } else { int n = JOptionPane.showConfirmDialog(frame, "M�chten Sie diesen Benutzer l�schen", "Best�tigung", JOptionPane.YES_NO_OPTION); if (n == 0) { serverConnection.deluser(tmp.geteMail()); } } } } else { // Ansonsten Dialog �ffnen, // in dem die eigenen Daten ge�ndert werden k�nnen userdialog dlg = new userdialog(frame, "User bearbeiten", current, false, serverConnection); int response = dlg.showCustomDialog(); // Wenn ok gedr�ckt wird // neuen User abfragen if (response == 1) { User tmp = dlg.getUser(); if (serverConnection.userupdate(tmp, current.geteMail()).getStatus() == 201) { current = tmp; checkRights(); } else JOptionPane.showMessageDialog(frame, "Update Fehlgeschlagen!", "Update Error", JOptionPane.ERROR_MESSAGE); } } } }); btnUserVerwaltung.setPreferredSize(btnSz); btnUserVerwaltung.setAlignmentX(Component.CENTER_ALIGNMENT); // Button zur Verwaltung von Studieng�ngen und Zuordnungen btnVerwaltung.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Zuordnungen und Studieng�nge aus Datenbank abrufen // und Listen f�llen studienlist = serverConnection.getStudiengaenge(); studimodel.removeAllElements(); for (int i = 0; i < studienlist.size(); i++) { studimodel.addElement(studienlist.get(i)); } cbmodel.removeAllElements(); for (int i = 0; i < studienlist.size(); i++) { cbmodel.addElement(studienlist.get(i)); } // typen = serverConnection.getZuordnungen(); // for (int i = 0; i < typen.size(); i++) { // typenmodel.addElement(typen.get(i)); // } // Zur Card wechseln showCard("manage"); } }); left.add(btnVerwaltung); btnVerwaltung.setEnabled(false); btnVerwaltung.setPreferredSize(btnSz); btnVerwaltung.setAlignmentX(Component.CENTER_ALIGNMENT); left.add(btnModulArchiv); btnModulArchiv.setEnabled(true); btnModulArchiv.setPreferredSize(btnSz); btnModulArchiv.setAlignmentX(Component.CENTER_ALIGNMENT); // Button zum Durchst�bern von Modulen btnModulArchiv.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { current = serverConnection.login(current.geteMail(), current.getPassword()); if (current != null) { // Studieng�nge und Zuordnungen abrufen studmodel.setRowCount(0); studienlist = serverConnection.getStudiengaenge(); for (int i = 0; i < studienlist.size(); i++) { addToTable(studienlist.get(i)); } //TODO something // typen = serverConnection.getZuordnungen(); // Zur Card wechseln showCard("studiengang show"); } else { noConnection(); } } }); } /** * Erstellt eine Card, um ein neues Modul anzulegen * */ private void newmodulecard() { // Alle vorhandenen Felder entfernen modul_panel.removeAll(); final JPanel pnl_newmod = new JPanel(); // Liste dynamischer Buttons leeren if (!buttonmap.isEmpty()) { for (int i = 0; i < buttonmap.size(); i++) buttonmap.remove(i); } // Liste mit bereits vorhandenen Felder erstellen und mit den // Standartfeldern f�llen final ArrayList<String> labels = new ArrayList<String>(); labels.addAll(defaultlabels); final Dimension preferredSize = new Dimension(120, 20); pnl_newmod.setLayout(new BorderLayout(0, 0)); JPanel pnl_bottom = new JPanel(); pnl_newmod.add(pnl_bottom, BorderLayout.SOUTH); // Button zum erstellen eines neuen Feldes JButton btnNeuesFeld = new JButton("Neues Feld"); btnNeuesFeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String text = "Name des Feldes"; // Abfrage des Namen des Feldes String name = JOptionPane.showInputDialog(frame, text); try { // Pr�fe, ob Name leer oder schon vorhanden ist while (name.isEmpty() || labels.contains(name)) { Object[] params = { "Bitte geben Sie eine g�ltige Bezeichnung ein!", text }; name = JOptionPane.showInputDialog(frame, params); } labels.add(name); JPanel pnl_tmp = new JPanel(); modul_panel.add(pnl_tmp); // Platzhalter modul_panel.add(Box.createRigidArea(new Dimension(0, 5))); // Abfrage der Anzahl an Panels, die bereits vorhanden sind int numOfPanels = modul_panel.getComponentCount(); pnl_tmp.setLayout(new BoxLayout(pnl_tmp, BoxLayout.X_AXIS)); JLabel label_tmp = new JLabel(name); label_tmp.setPreferredSize(preferredSize); pnl_tmp.add(label_tmp); JTextArea txt_tmp = new JTextArea(); txt_tmp.setLineWrap(true); pnl_tmp.add(txt_tmp); JCheckBox dez = new JCheckBox("Dezernat 2", false); pnl_tmp.add(dez); // Button, um das Feld wieder zu entfernen JButton btn_tmp_entf = new JButton("Entfernen"); btn_tmp_entf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = buttonmap.get(e.getSource()); // Bezeichnung aus Liste entfernen String name = ((JLabel) ((JPanel) modul_panel.getComponent(id)).getComponent(0)).getText(); labels.remove(name); // Feld mit ID id von Panel entfernen modul_panel.remove(id); // Platzhalter entfernen modul_panel.remove(id - 1); // Aus ButtonMap entfernen buttonmap.remove(e.getSource()); // ids der Buttons �ndern, damit auch ein Feld aus // der Mitte gel�cht werden kann HashMap<JButton, Integer> tmpmap = new HashMap<JButton, Integer>(); Iterator<Entry<JButton, Integer>> entries = buttonmap.entrySet().iterator(); while (entries.hasNext()) { Entry<JButton, Integer> thisEntry = entries.next(); JButton key = thisEntry.getKey(); int value = thisEntry.getValue(); if (value > id) { value = value - 2; } tmpmap.put(key, value); } buttonmap = tmpmap; modul_panel.revalidate(); } }); // Button btn_tmp_entf mit ID (numOfPanels-2) zu ButtonMap // hinzuf�gen buttonmap.put(btn_tmp_entf, numOfPanels - 2); pnl_tmp.add(btn_tmp_entf); modul_panel.revalidate(); } catch (NullPointerException npe) { // nichts tuen bei Abbruch } } }); pnl_bottom.add(btnNeuesFeld); // Zur�ck zur Startseite JButton btnHome = new JButton("Zur\u00fcck"); btnHome.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Card wieder erneuern und zur Startseite wechseln newmodulecard(); modul_panel.revalidate(); showCard("welcome page"); } }); pnl_bottom.add(btnHome); JScrollPane scrollPane = new JScrollPane(modul_panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); modul_panel.setLayout(new BoxLayout(modul_panel, BoxLayout.Y_AXIS)); // Panel Zuordnung + Platzhalter JPanel pnl_Z = new JPanel(); pnl_Z.setLayout(new BoxLayout(pnl_Z, BoxLayout.X_AXIS)); JLabel label_MH = new JLabel("Zuordnung"); label_MH.setPreferredSize(preferredSize); pnl_Z.add(label_MH); // Liste mit ausgew�hlten Zuordnungen // final DefaultListModel<Zuordnung> lm = new // DefaultListModel<Zuordnung>(); // final JList<Zuordnung> zlist = new JList<Zuordnung>(lm); // zlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // // pnl_Z.add(zlist); // // // ComboBox mit Zuordnungen // final JComboBox<Zuordnung> cb_Z = new // JComboBox<Zuordnung>(cbmodel_Z); // cb_Z.setMaximumSize(new Dimension(400, 20)); // // pnl_Z.add(cb_Z); // // // Auswahl einer Zuordnung aus der ComboBox // JButton z_btn = new JButton("Zuordnung ausw\u00e4hlen"); // z_btn.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // if (!lm.contains(cb_Z.getSelectedItem())) // lm.addElement((Zuordnung) cb_Z.getSelectedItem()); // } // }); // pnl_Z.add(z_btn); // // // In der Liste ausgew�hlte Zuordnung wieder entfernen // JButton btnZuordnungEntfernen = new JButton("Zuordnung entfernen"); // btnZuordnungEntfernen.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // int i = zlist.getSelectedIndex(); // if (i > -1) { // lm.remove(i); // } // } // }); // pnl_Z.add(btnZuordnungEntfernen); // // modul_panel.add(pnl_Z); modul_panel.add(Box.createRigidArea(new Dimension(0, 5))); // Alle Standartfelder, au�er Zuordnung erzeugen for (int i = 3; i < defaultlabels.size(); i++) { modul_panel.add(defaultmodulPanel(defaultlabels.get(i), "", false)); modul_panel.add(Box.createRigidArea(new Dimension(0, 5))); } // Button zum Annehmen eines Modules JButton btnOk = new JButton("Annehmen"); btnOk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // ArrayList<Zuordnung> zlist = new ArrayList<Zuordnung>(); String jg = ((JTextArea) ((JPanel) modul_panel.getComponent(2)).getComponent(1)).getText(); int jahrgang; try { jahrgang = Integer.parseInt(jg); } catch (NumberFormatException nfe) { jahrgang = 0; } // for (int i = 0; i < lm.getSize(); i++) { // zlist.add(lm.getElementAt(i)); // } // Pr�fe, ob min. eine Zuordnung ausgew�hlt und ein g�ltiger // Jahrgang eingegeben wurde // if (!zlist.isEmpty()) { // if (jahrgang != 0) { // // String Name = ((JTextArea) ((JPanel) // modul_panel.getComponent(4)).getComponent(1)).getText(); // // if (Name.isEmpty()) { // JOptionPane.showMessageDialog(frame, // "Bitte geben Sie einen Namen ein!", "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } else { // // boolean filled = true; // ArrayList<Feld> felder = new ArrayList<Feld>(); // // Eintraege der Reihe nach auslesen // for (int i = 6; i < modul_panel.getComponentCount(); i = i + // 2) { // JPanel tmp = (JPanel) modul_panel.getComponent(i); // JLabel tmplbl = (JLabel) tmp.getComponent(0); // JTextArea tmptxt = (JTextArea) tmp.getComponent(1); // // boolean dezernat2 = ((JCheckBox) // tmp.getComponent(2)).isSelected(); // String value = tmptxt.getText(); // String label = tmplbl.getText(); // // Pr�fe, ob alle Felder ausgef�llt wurden // if (value.isEmpty()) { // filled = false; // break; // } // felder.add(new Feld(label, value, dezernat2)); // } // // Wenn alle aussgef�llt wurden, neues Modul // // erzeugen und bei Best�tigung einreichen // if (filled == true) { // int version = serverConnection.getModulVersion(Name) + 1; // // Date d = new Date(); // ArrayList<String> user = new ArrayList<String>(); // user.add(current.geteMail()); // Modul neu = new Modul(Name, felder, version, d, 0, false, // user, ""); // int n = JOptionPane.showConfirmDialog(frame, // "Sind Sie sicher, dass Sie dieses Modul einreichen wollen?", // "Best�tigung", JOptionPane.YES_NO_OPTION); // if (n == 0) { // serverConnection.setModul(neu); // labels.removeAll(labels); // modul_panel.removeAll(); // modul_panel.revalidate(); // newmodulecard(); // showCard("newmodule"); // } // } // Fehler, wenn nicht alle ausgef�llt wurden // else { // JOptionPane.showMessageDialog(frame, // "Bitte f�llen Sie alle Felder aus!", "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte geben Sie einen g�ltigen Wert f�r den Jahrgang ein!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte w�hlen Sie min. einen Zuordnung aus!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } } }); pnl_bottom.add(btnOk); pnl_newmod.add(scrollPane); cards.add(pnl_newmod, "newmodule"); } /** * Entfernt einen Eintrag aus der Usertabelle * * @param rowid * Der Index des zu enfernenden Eintrages */ private void removeFromTable(int rowid) { tmodel.removeRow(rowid); } /** * Wechselt zur angegeben Card * * @param card * Die Bezeichnung der Card, zu der gewechselt werden soll */ private static void showCard(String card) { ((CardLayout) cards.getLayout()).show(cards, card); } /** * Erstellt eine Card zur Verwaltung von Benutzern */ @SuppressWarnings("serial") private void usermgtcard() { JPanel usrmg = new JPanel(); cards.add(usrmg, "user managment"); usrmg.setLayout(new BorderLayout(0, 0)); JPanel usrpan = new JPanel(); FlowLayout fl_usrpan = (FlowLayout) usrpan.getLayout(); fl_usrpan.setAlignment(FlowLayout.RIGHT); usrmg.add(usrpan, BorderLayout.SOUTH); final JTable usrtbl = new JTable(); JScrollPane ussrscp = new JScrollPane(usrtbl); usrtbl.setBorder(new LineBorder(new Color(0, 0, 0))); usrtbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // // Inhalt der Tabelle // tmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Titel", "Vorname", "Nachname", "e-Mail", "Benutzer verwalten", "Module einreichen", "Module Annehmen", "Verwaltung" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class, String.class, String.class, String.class, boolean.class, boolean.class, boolean.class, boolean.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; usrtbl.setModel(tmodel); // Button zum hinzuf�gen eines Benutzers JButton btnUserAdd = new JButton("User hinzuf\u00fcgen"); btnUserAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { userdialog dlg = new userdialog(frame, "User hinzuf\u00fcgen", serverConnection); int response = dlg.showCustomDialog(); // Wenn ok gedr�ckt wird // neuen User hinzuf�gen if (response == 1) { User tmp = dlg.getUser(); tmp.setFreigeschaltet(true); // Wenn er erfolgreich in die DB eingetragen wurde,zur // Tabelle hinzuf�gen if (serverConnection.usersave(tmp).getStatus() == 201) { addToTable(tmp); } } } }); usrpan.add(btnUserAdd); // Button zum bearbeiten eines in der Tabelle ausgew�hlten Users JButton btnUserEdit = new JButton("User bearbeiten"); btnUserEdit.setToolTipText("Zum Bearbeiten Benutzer in der Tabelle markieren"); btnUserEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int row = usrtbl.getSelectedRow(); if (row != -1) { // Daten aus der Tabelle abrufen und User erzeugen String t = (String) usrtbl.getValueAt(row, 0); String vn = (String) usrtbl.getValueAt(row, 1); String nn = (String) usrtbl.getValueAt(row, 2); String em = (String) usrtbl.getValueAt(row, 3); boolean r1 = (boolean) usrtbl.getValueAt(row, 4); boolean r2 = (boolean) usrtbl.getValueAt(row, 5); boolean r3 = (boolean) usrtbl.getValueAt(row, 6); boolean r4 = (boolean) usrtbl.getValueAt(row, 7); boolean r5 = (boolean) usrtbl.getValueAt(row, 8); User alt = new User(vn, nn, t, em, null, r1, r2, r3, r4, r5, true); // User an Bearbeiten dialog �bergeben userdialog dlg = new userdialog(frame, "User bearbeiten", alt, true, serverConnection); int response = dlg.showCustomDialog(); // Wenn ok ged\u00fcckt wird // neuen User abfragen if (response == 1) { User tmp = dlg.getUser(); tmp.setFreigeschaltet(true); // Wenn update erfolgreich war, alten user abfragen und // neu hinzuf�gen if (serverConnection.userupdate(tmp, em).getStatus() == 201) { removeFromTable(row); addToTable(tmp); // Falls eigener Benutzer bearbeitet wurde, Rechte // erneut pr�fen if (em.equals(current.geteMail())) { current = tmp; checkRights(); } } else JOptionPane.showMessageDialog(frame, "Update Fehlgeschlagen", "Update Fehler", JOptionPane.ERROR_MESSAGE); } } } }); usrpan.add(btnUserEdit); // L�schen eines ausgew�hlten Benutzers JButton btnUserDel = new JButton("User l\u00f6schen"); btnUserDel.setToolTipText("Zum L\u00f6schen Benutzer in der Tabelle markieren"); btnUserDel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int row = usrtbl.getSelectedRow(); if (row != -1) { int n = JOptionPane.showConfirmDialog(frame, "Sind Sie sicher, dass Sie diesen Benutzer l\u00f6schen wollen?", "Best�tigung", JOptionPane.YES_NO_OPTION); if (n == 0) { // Wenn L�schen erfolgreich war, aus der Tabelle // entfernen if (serverConnection.deluser((String) usrtbl.getValueAt(row, 3)).getStatus() != 201) { removeFromTable(row); } else JOptionPane.showMessageDialog(frame, "L\u00f6schen Fehlgeschlagen", "Fehler beim L\u00f6schen", JOptionPane.ERROR_MESSAGE); } } } }); usrpan.add(btnUserDel); // Zur�ck zur Startseite JButton btnHome = new JButton("Zur\u00fcck"); btnHome.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); usrpan.add(btnHome); JPanel usrcenter = new JPanel(); usrmg.add(usrcenter, BorderLayout.CENTER); usrcenter.setLayout(new BorderLayout(5, 5)); usrcenter.add(ussrscp); JPanel leftpan = new JPanel(); frame.getContentPane().add(leftpan, BorderLayout.WEST); } /** * �berpr�ft die Rechte des aktuell eingeloggten Benutzers und aktiviert * Buttons, auf die er Zugriff hat und deaktiviert Bttons, auf die er keinen * Zugriff hat */ protected void checkRights() { btnModulEinreichen.setEnabled(false); btnModulBearbeiten.setEnabled(false); btnVerwaltung.setEnabled(false); btnModulBearbeiten.setEnabled(false); btnUserVerwaltung.setEnabled(false); btnModulAkzeptieren.setEnabled(false); canReadMessages=false; welcome.remove(pnl_content); welcome.repaint(); if (current.getCreateModule()) { btnModulEinreichen.setEnabled(true); btnModulBearbeiten.setEnabled(true); canReadMessages=true; } if (current.getAcceptModule()) { btnModulBearbeiten.setEnabled(true); btnModulAkzeptieren.setEnabled(true); canReadMessages=true; } if (current.getManageSystem()) { btnVerwaltung.setEnabled(true); canReadMessages=true; } if (current.getManageUsers()) { btnUserVerwaltung.setEnabled(true); btnUserVerwaltung.setText("User Verwaltung"); canReadMessages=true; } else { btnUserVerwaltung.setEnabled(true); btnUserVerwaltung.setText("Account bearbeiten"); } if(canReadMessages){ welcome.add(pnl_content, BorderLayout.CENTER); nachrichten = serverConnection.getNachrichten(current.geteMail()); refreshMessageTable(); } showCard("welcome page"); } /** * Erstellt eine Card zur Bearbeitung von Modulen */ public void modulbearbeitenCard() { JPanel pnl_modedit = new JPanel(); pnl_modedit.setLayout(new BorderLayout(0, 0)); // Tab f�r akzeptierte und f�r nicht akzeptierte Module erstellen JTabbedPane tabs = new JTabbedPane(SwingConstants.TOP); pnl_modedit.add(tabs); JPanel nichtakzeptiert = new JPanel(); tabs.addTab("Noch nicht akzeptierte Module", null, nichtakzeptiert, null); nichtakzeptiert.setLayout(new BorderLayout(0, 0)); final JList<Modul> list_notack = new JList<Modul>(lm); list_notack.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_notack.setLayoutOrientation(JList.VERTICAL_WRAP); nichtakzeptiert.add(list_notack); JPanel buttonpnl = new JPanel(); nichtakzeptiert.add(buttonpnl, BorderLayout.SOUTH); // Button zum bearbeiten eines nicht akzeptierten Modules JButton btnModulBearbeiten = new JButton("Modul bearbeiten"); btnModulBearbeiten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Modul m = list_notack.getSelectedValue(); if (m != null) { // Abfragen, ob Modul in Bearbeitung ist m.setInbearbeitung(serverConnection.getModulInEdit(m.getName())); if (!m.isInbearbeitung()) { // Pr�fe, ob Benutzer das Rech hat, das Modul zu // Bearbeiten // Wenn er das Modul selbst erstellt hat, darf er es // auch bearbeiten // Ansonsten Pr�fen, ob es von einem Stellvertreter oder // Vorgesetzetn von ihm erstellt wurde boolean rights = false; if (m.getUser().equals(current.geteMail())) { rights = true; } else { ArrayList<String> rel = serverConnection.getUserRelation(current.geteMail()); if (rel.contains(m.getUser())) { rights = true; } } // Wenn er die Rechte dazu hat, Modul als in Bearbeitung // markieren und zur Bearbeitung wechseln if (rights) { mod.removeAll(); mod.add(modeditCard(m), BorderLayout.CENTER); m.setInbearbeitung(true); serverConnection.setModulInEdit(m); showCard("modBearbeiten"); } else { JOptionPane.showMessageDialog(frame, "Sie besitzen nicht die n\u00f6tigen Rechte, um dieses Modul zu bearbeiten!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "Dieses Modul befindet sich gerade in bearbeitung!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } } }); buttonpnl.add(btnModulBearbeiten); // Button zum akzeptieren eines Modules btnModulAkzeptieren.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Modul m = list_notack.getSelectedValue(); if (m != null) { // Pr�fe, ob Modul in Bearbeitung ist m.setInbearbeitung(serverConnection.getModulInEdit(m.getName())); if (!m.isInbearbeitung()) { if (m.getName().isEmpty()) { JOptionPane.showMessageDialog(frame, "Bei diesem Modul sind nicht alle Felder ausgef�llt!", "Fehler im Modul", JOptionPane.ERROR_MESSAGE); } else { // Pr�fe, ob ein Feld f�r das Dezernat 2 markiert // wurde // und ob alle Felder ausgef�llt wurden boolean hasDezernat = false; boolean isCorrect = true; ArrayList<Feld> felder = m.getFelder(); for (int i = 0; i < felder.size(); i++) { if (felder.get(i).getValue().isEmpty()) { JOptionPane.showMessageDialog(frame, "Bei diesem Modul sind nicht alle Felder ausgef�llt!", "Fehler im Modul", JOptionPane.ERROR_MESSAGE); isCorrect = false; break; } if (felder.get(i).isDezernat()) { hasDezernat = true; } } if (isCorrect) { boolean checked = true; // Wenn Felder als Dezernat 2 markiert wurden, // nach Best�tigung fragen if (hasDezernat) { int n = JOptionPane.showConfirmDialog(frame, "Dieses Modul besitzt Felder, die vom Dezernat2 �berpr�ft werden m�ssen, wurde das getan?", "Best�tigung", JOptionPane.YES_NO_OPTION); if (n == 0) { checked = true; } else { checked = false; } } if (checked) { // Bei best�tigung Modul akzeptieren und // Listen neu abrufen // dann zur Bearbeiten �bersicht wechseln serverConnection.acceptModul(m); ArrayList<Modul> module = serverConnection.getModule(false); lm.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm.addElement(module.get(i)); } module = serverConnection.getModule(true); lm_ack.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm_ack.addElement(module.get(i)); } showCard("modulbearbeiten"); } } } } else { JOptionPane.showMessageDialog(frame, "Dieses Modul befindet sich gerade in bearbeitung!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } } }); buttonpnl.add(btnModulAkzeptieren); // Zur�ck zur Startseite JButton btnZurck = new JButton("Zur\u00FCck"); btnZurck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); buttonpnl.add(btnZurck); // akzeptierte Module JPanel akzeptiert = new JPanel(); tabs.addTab("akzeptierte Module", null, akzeptiert, null); tabs.setEnabledAt(1, true); akzeptiert.setLayout(new BorderLayout(0, 0)); final JList<Modul> list_ack = new JList<Modul>(lm_ack); list_ack.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_ack.setLayoutOrientation(JList.VERTICAL_WRAP); akzeptiert.add(list_ack); JPanel buttonpnl2 = new JPanel(); akzeptiert.add(buttonpnl2, BorderLayout.SOUTH); // akzeptierte Module bearbeiten JButton btnModulBearbeiten2 = new JButton("Modul bearbeiten"); btnModulBearbeiten2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Modul m = list_ack.getSelectedValue(); if (m != null) { // Pr�fe, ob Modul in Bearbeitung ist m.setInbearbeitung(serverConnection.getModulInEdit(m.getName())); if (!m.isInbearbeitung()) { // Pr�fe, ob User das Recht hat, dieses Modul zu // bearbeiten boolean rights = false; if (m.getUser().equals(current.geteMail())) { rights = true; } else { ArrayList<String> rel = serverConnection.getUserRelation(current.geteMail()); if (rel.contains(m.getUser())) { rights = true; } } if (rights) { // Zur Bearbeitung wechseln mod.removeAll(); mod.add(modeditCard(m), BorderLayout.CENTER); showCard("modBearbeiten"); } else { JOptionPane.showMessageDialog(frame, "Sie besitzen nicht die n\u00f6tigen Rechte, um dieses Modul zu bearbeiten!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "Dieses Modul befindet sich gerade in bearbeitung!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } } }); buttonpnl2.add(btnModulBearbeiten2); // Zur�ck zur Startseite JButton btnZurck2 = new JButton("Zur\u00FCck"); btnZurck2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); buttonpnl2.add(btnZurck2); cards.add(pnl_modedit, "modulbearbeiten"); } /** * Liefert ein Panel, dass mit den Daten von Modul m ausgef�llt ist Die * Felder sind dabei nicht mehr bearbeitbar * * @return JPanel mit Daten ausgef�lltes Panel * @param m * Zu bearbeitendes Modul */ private JPanel modeditCardPrev(Modul m) { final JPanel pnl_editmod = new JPanel(); final JPanel pnl_mod_prev = new JPanel(); // Felder vom Modul abfragen final ArrayList<Feld> felder = m.getFelder(); final ArrayList<String> labels = new ArrayList<String>(); for (int i = 0; i < felder.size(); i++) { labels.add(felder.get(i).getLabel()); } final Dimension preferredSize = new Dimension(120, 20); pnl_editmod.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(pnl_mod_prev, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); pnl_mod_prev.setLayout(new BoxLayout(pnl_mod_prev, BoxLayout.Y_AXIS)); // Panel Zuordnung + Platzhalter JPanel pnl_Z = new JPanel(); pnl_Z.setLayout(new BoxLayout(pnl_Z, BoxLayout.X_AXIS)); JLabel label_MH = new JLabel("Zuordnung"); label_MH.setPreferredSize(preferredSize); pnl_Z.add(label_MH); // Zuordnugen vom Modul abfragen // final DefaultListModel<Zuordnung> lm = new // DefaultListModel<Zuordnung>(); // typen = m.getZuordnungen(); // for (int i = 0; i < typen.size(); i++) { // lm.addElement(typen.get(i)); // } // JList<Zuordnung> zlist = new JList<Zuordnung>(lm); // pnl_Z.add(zlist); pnl_mod_prev.add(pnl_Z); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); // Restliche Felder erzeugen JPanel jg = new JPanel(); jg.setLayout(new BoxLayout(jg, BoxLayout.X_AXIS)); JLabel lbl_jg = new JLabel("Jahrgang"); lbl_jg.setPreferredSize(preferredSize); jg.add(lbl_jg); // JTextArea txt_jg = new JTextArea(m.getJahrgang() + ""); // txt_jg.setLineWrap(true); // txt_jg.setEditable(false); // jg.add(txt_jg); pnl_mod_prev.add(jg); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); JPanel name = new JPanel(); name.setLayout(new BoxLayout(name, BoxLayout.X_AXIS)); JLabel lbl_n = new JLabel("Name"); lbl_n.setPreferredSize(preferredSize); name.add(lbl_n); JTextArea txt_n = new JTextArea(m.getName()); txt_n.setLineWrap(true); txt_n.setEditable(false); name.add(txt_n); pnl_mod_prev.add(name); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); for (int i = 0; i < m.getFelder().size(); i++) { Feld f = m.getFelder().get(i); JPanel pnl = new JPanel(); pnl.setLayout(new BoxLayout(pnl, BoxLayout.X_AXIS)); JLabel label = new JLabel(f.getLabel()); label.setPreferredSize(preferredSize); pnl.add(label); // Felder sind hier nicht bearbeitbar JTextArea txt = new JTextArea(f.getValue()); txt.setLineWrap(true); txt.setEditable(false); pnl.add(txt); JCheckBox dez = new JCheckBox("Dezernat 2", f.isDezernat()); dez.setEnabled(false); pnl.add(dez); pnl_mod_prev.add(pnl); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); } pnl_editmod.add(scrollPane); return pnl_editmod; } /** * Liefert ein Panel, dass mit den Daten von Modul m ausgef�llt ist * * @return JPanel mit Daten ausgef�lltes Panel * @param m * Zu bearbeitendes Modul */ private JPanel modeditCard(final Modul m) { // Alle Felder entfernen // Buttonmap leeren final JPanel pnl_editmod = new JPanel(); modul_panel_edit.removeAll(); if (!buttonmap.isEmpty()) { for (int i = 0; i < buttonmap.size(); i++) buttonmap.remove(i); } // Felder vom Modul abfragen final ArrayList<Feld> felder = m.getFelder(); final ArrayList<String> labels = new ArrayList<String>(); for (int i = 0; i < felder.size(); i++) { labels.add(felder.get(i).getLabel()); } final Dimension preferredSize = new Dimension(120, 20); pnl_editmod.setLayout(new BorderLayout(0, 0)); JPanel pnl_bottom = new JPanel(); pnl_editmod.add(pnl_bottom, BorderLayout.SOUTH); // Button zur anzeige der vorherigen Version JButton alt = new JButton("Vorherige Version"); alt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { int v = m.getVersion() - 1; if (v > 0) { String name = m.getName(); Modul pre = serverConnection.getModul(name, v); if (pre != null) JOptionPane.showMessageDialog(frame, modeditCardPrev(pre), "Vorherige Version", 1); } else { JOptionPane.showMessageDialog(frame, "Keine Vorherige Version vorhanden!", "Fehler", JOptionPane.ERROR_MESSAGE); } } }); pnl_bottom.add(alt); // Button zum erzeugen eines neuen Feldes JButton btnNeuesFeld = new JButton("Neues Feld"); btnNeuesFeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String text = "Name des Feldes"; String name = JOptionPane.showInputDialog(frame, text); try { while (name.isEmpty() || labels.contains(name)) { Object[] params = { "Bitte geben Sie eine g�ltige Bezeichnung ein!", text }; name = JOptionPane.showInputDialog(frame, params); } labels.add(name); // Platzhalter JPanel pnl_tmp = new JPanel(); modul_panel_edit.add(pnl_tmp); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); // Abfrage der Anzahl an Feldern int numOfPanels = modul_panel_edit.getComponentCount(); pnl_tmp.setLayout(new BoxLayout(pnl_tmp, BoxLayout.X_AXIS)); JLabel label_tmp = new JLabel(name); label_tmp.setPreferredSize(preferredSize); pnl_tmp.add(label_tmp); JTextArea txt_tmp = new JTextArea(); txt_tmp.setLineWrap(true); pnl_tmp.add(txt_tmp); JCheckBox dez = new JCheckBox("Dezernat 2", false); pnl_tmp.add(dez); // Feld wieder entfernen JButton btn_tmp_entf = new JButton("Entfernen"); btn_tmp_entf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = buttonmap.get(e.getSource()); // Bezeichnung aus Liste entfernen String name = ((JLabel) ((JPanel) modul_panel_edit.getComponent(id)).getComponent(0)).getText(); labels.remove(name); // Feld mit ID id von Panel entfernen modul_panel_edit.remove(id); // Platzhalter entfernen modul_panel_edit.remove(id - 1); // Aus ButtonMap entfernen buttonmap.remove(e.getSource()); // ids der Buttons �ndern, damit auch ein Feld aus // der Mitte gel�scht werden kann HashMap<JButton, Integer> tmpmap = new HashMap<JButton, Integer>(); Iterator<Entry<JButton, Integer>> entries = buttonmap.entrySet().iterator(); while (entries.hasNext()) { Entry<JButton, Integer> thisEntry = entries.next(); JButton key = thisEntry.getKey(); int value = thisEntry.getValue(); if (value > id) { value = value - 2; } tmpmap.put(key, value); } buttonmap = tmpmap; modul_panel_edit.revalidate(); } }); // Button btn_tmp_entf mit ID (numOfPanels-2) zu ButtonMap buttonmap.put(btn_tmp_entf, numOfPanels - 2); pnl_tmp.add(btn_tmp_entf); modul_panel_edit.revalidate(); } catch (NullPointerException npe) { // nichts tuen bei Abbruch } } }); pnl_bottom.add(btnNeuesFeld); // Zur�ck zur Startseite JButton btnHome = new JButton("Zur\u00fcck"); btnHome.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Panel wider neu erzeugen, // Modul als nicht in Bearbeitung markieren modul_panel_edit.removeAll(); modul_panel_edit.revalidate(); m.setInbearbeitung(false); serverConnection.setModulInEdit(m); modulbearbeitenCard(); showCard("modulbearbeiten"); } }); pnl_bottom.add(btnHome); JScrollPane scrollPane = new JScrollPane(modul_panel_edit, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); modul_panel_edit.setLayout(new BoxLayout(modul_panel_edit, BoxLayout.Y_AXIS)); // Panel Zuordnung + Platzhalter JPanel pnl_Z = new JPanel(); pnl_Z.setLayout(new BoxLayout(pnl_Z, BoxLayout.X_AXIS)); JLabel label_MH = new JLabel("Zuordnung"); label_MH.setPreferredSize(preferredSize); pnl_Z.add(label_MH); // Liste ausgew�hlter Zuordnungen // final DefaultListModel<Zuordnung> lm_Z = new // DefaultListModel<Zuordnung>(); // typen = m.getZuordnungen(); // for (int i = 0; i < typen.size(); i++) { // lm_Z.addElement(typen.get(i)); // } // final JList<Zuordnung> zlist = new JList<Zuordnung>(lm_Z); // zlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // // pnl_Z.add(zlist); // typen = serverConnection.getZuordnungen(); // cbmodel_Z.removeAllElements(); // for (int i = 0; i < typen.size(); i++) { // cbmodel_Z.addElement(typen.get(i)); // } // // Zur auswahlstehende Zuordnungen // final JComboBox<Zuordnung> cb_Z = new // JComboBox<Zuordnung>(cbmodel_Z); // cb_Z.setMaximumSize(new Dimension(cb_Z.getMaximumSize().width, 20)); // // pnl_Z.add(cb_Z); // // // Zuordnung ausw�hlen // JButton z_btn = new JButton("Zuordnung ausw\u00e4hlen"); // z_btn.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // if (!lm_Z.contains(cb_Z.getSelectedItem())) // lm_Z.addElement((Zuordnung) cb_Z.getSelectedItem()); // } // }); // pnl_Z.add(z_btn); // // // Zuordnung wieder entfernen // JButton btnZuordnungEntfernen = new JButton("Zuordnung entfernen"); // btnZuordnungEntfernen.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // int i = zlist.getSelectedIndex(); // if (i > -1) { // lm_Z.remove(i); // } // } // }); // pnl_Z.add(btnZuordnungEntfernen); modul_panel_edit.add(pnl_Z); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); // modul_panel_edit.add(defaultmodulPanel("Jahrgang", m.getJahrgang() + // "", false)); // modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); JPanel pnl = new JPanel(); pnl.setLayout(new BoxLayout(pnl, BoxLayout.X_AXIS)); JLabel label = new JLabel("Name"); label.setPreferredSize(preferredSize); pnl.add(label); JTextArea txt = new JTextArea(m.getName()); txt.setLineWrap(true); pnl.add(txt); txt.setEditable(false); modul_panel_edit.add(pnl); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); // Felder erzeugen und f�llen for (int i = 0; i < m.getFelder().size(); i++) { Feld f = m.getFelder().get(i); JPanel feld = defaultmodulPanel(f.getLabel(), f.getValue(), f.isDezernat()); // Wenn es kein Standart Feld ist, einen entfernen Button hinzuf�gen if (!defaultlabels.contains(f.getLabel())) { int numOfPanels = modul_panel_edit.getComponentCount(); JButton btn_tmp_entf = new JButton("Entfernen"); btn_tmp_entf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = buttonmap.get(e.getSource()); // Bezeichnung aus Liste entfernen String name = ((JLabel) ((JPanel) modul_panel_edit.getComponent(id)).getComponent(0)).getText(); labels.remove(name); // Feld mit ID id von Panel entfernen modul_panel_edit.remove(id); // Platzhalter entfernen modul_panel_edit.remove(id - 1); // Aus ButtonMap entfernen buttonmap.remove(e.getSource()); // ids der Buttons �ndern, damit auch ein Feld aus // der Mitte gel�scht werden kann HashMap<JButton, Integer> tmpmap = new HashMap<JButton, Integer>(); Iterator<Entry<JButton, Integer>> entries = buttonmap.entrySet().iterator(); while (entries.hasNext()) { Entry<JButton, Integer> thisEntry = entries.next(); JButton key = thisEntry.getKey(); int value = thisEntry.getValue(); if (value > id) { value = value - 2; } tmpmap.put(key, value); } buttonmap = tmpmap; modul_panel_edit.revalidate(); modul_panel_edit.repaint(); } }); feld.add(btn_tmp_entf); // Button btn_tmp_entf mit ID (numOfPanels-2) zu ButtonMap buttonmap.put(btn_tmp_entf, numOfPanels); } modul_panel_edit.add(feld); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); } // Button zum annehmen eines Modules JButton btnOk = new JButton("Annehmen"); btnOk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // ArrayList<Zuordnung> zlist = new ArrayList<Zuordnung>(); String jg = ((JTextArea) ((JPanel) modul_panel_edit.getComponent(2)).getComponent(1)).getText(); int jahrgang; try { jahrgang = Integer.parseInt(jg); } catch (NumberFormatException nfe) { jahrgang = 0; } // for (int i = 0; i < lm_Z.getSize(); i++) { // zlist.add(lm_Z.getElementAt(i)); // } // Pr�fe ob min. eine Zuordnung ausgew�hlt ist und ein korrekter // Jahrgang ausgew�hlt wurde // if (!zlist.isEmpty()) { // // if (jahrgang != 0) { // // String Name = ((JTextArea) ((JPanel) // modul_panel_edit.getComponent(4)).getComponent(1)).getText(); // // if (Name.isEmpty()) { // JOptionPane.showMessageDialog(frame, // "Bitte f�llen Sie alle Felder aus!", "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } else { // // boolean filled = true; // ArrayList<Feld> felder = new ArrayList<Feld>(); // // Eintraege der Reihe nach auslesen // for (int i = 6; i < modul_panel_edit.getComponentCount(); i = // i + 2) { // JPanel tmp = (JPanel) modul_panel_edit.getComponent(i); // JLabel tmplbl = (JLabel) tmp.getComponent(0); // JTextArea tmptxt = (JTextArea) tmp.getComponent(1); // // boolean dezernat2 = ((JCheckBox) // tmp.getComponent(2)).isSelected(); // String value = tmptxt.getText(); // String label = tmplbl.getText(); // // Pr�fe, ob Feld ausgef�llt ist // if (value.isEmpty()) { // filled = false; // break; // } // felder.add(new Feld(label, value, dezernat2)); // } // if (filled == true) { // // Wenn alle ausgef�llt sind, Modul erzeugen und // // bei Best�tigung einreichen // int version = serverConnection.getModulVersion(Name) + 1; // // Date d = new Date(); // // Modul neu = new Modul(Name, zlist, jahrgang, felder, version, // d, false, false, current.geteMail()); // // int n = JOptionPane.showConfirmDialog(frame, // "Sind Sie sicher, dass Sie dieses Modul einreichen wollen?", // "Best�tigung", JOptionPane.YES_NO_OPTION); // if (n == 0) { // m.setInbearbeitung(false); // serverConnection.setModul(neu); // labels.removeAll(labels); // modul_panel_edit.removeAll(); // modul_panel_edit.revalidate(); // // // Listen neu einlesen // ArrayList<Modul> module = serverConnection.getModule(false); // lm.removeAllElements(); // for (int i = 0; i < module.size(); i++) { // lm.addElement(module.get(i)); // } // // module = serverConnection.getModule(true); // lm_ack.removeAllElements(); // for (int i = 0; i < module.size(); i++) { // lm_ack.addElement(module.get(i)); // } // showCard("modulbearbeiten"); // } // } else { // // } // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte geben Sie einen g�ltigen Wert f�r den Jahrgang ein!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte w�hlen Sie min. einen Zuordnung aus!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } } }); pnl_bottom.add(btnOk); pnl_editmod.add(scrollPane); return pnl_editmod; } /** * Erstellt eine Card zur Auswahl des Studienganges */ @SuppressWarnings("serial") private void studiengangCard() { JPanel studiengangshow = new JPanel(); cards.add(studiengangshow, "studiengang show"); studiengangshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable studtable = new JTable(); JScrollPane studscp = new JScrollPane(studtable); studtable.setBorder(new LineBorder(new Color(0, 0, 0))); studtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); studiengangshow.add(studscp); studiengangshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Studieng�ngen studmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Studiengang" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; studtable.setModel(studmodel); studtransferstring = ""; // Wechseln zur Jahrgangsauswahl, wenn ein Studiengang ausgew�hlt wurde goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (studtable.getSelectedRow() != -1) { int openrow = studtable.getSelectedRow(); studtransferstring = (String) studtable.getValueAt(openrow, 0); modhandshowCard(); showCard("modbuch show"); } } }); // Zur�ck zur Startseite back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); } /** * Erstellt eine Card zur Auswahl des Jahrgangs */ @SuppressWarnings("serial") private void modhandshowCard() { JPanel modbuchshow = new JPanel(); cards.add(modbuchshow, "modbuch show"); modbuchshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable modbuchtable = new JTable(); JScrollPane modtypscp = new JScrollPane(modbuchtable); modbuchtable.setBorder(new LineBorder(new Color(0, 0, 0))); modbuchtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); modbuchshow.add(modtypscp); modbuchshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Jahrg�ngen modbuchmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Modulhandbuch Jahrgang" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; int zws = 0; // Tabelle f�llen modbuchtable.setModel(modbuchmodel); modbuchmodel.setRowCount(0); System.out.println(studienlist.get(0).getName()); System.out.println(studtransferstring); System.out.println(studienlist.get(0).getModbuch().get(0).getId()); //modulhandlist = serverConnection.getModulhandbuch(studtransferstring); for(int i = 0; i < studienlist.size(); i++){ if(studienlist.get(i).getName().equalsIgnoreCase(studtransferstring)){ zws = i; break; } } for (int i = 0; i < studienlist.get(0).getModbuch().size(); i++) { addToTable(studienlist.get(0).getModbuch().get(i)); } modbuchtransferstring = ""; // Wechseln zur Auswahl von Zuordnungen goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (modbuchtable.getSelectedRow() != -1) { int openrow = modbuchtable.getSelectedRow(); modbuchtransferstring = (String) modbuchtable.getValueAt(openrow, 0); modtypshowCard(); showCard("modtyp show"); } } }); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("studiengang show"); } }); } /** * Erstellt eine Card zur Auswahl des Modultypes */ @SuppressWarnings("serial") private void modtypshowCard() { JPanel modtypshow = new JPanel(); cards.add(modtypshow, "modtyp show"); modtypshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable modtyptable = new JTable(); JScrollPane modtypscp = new JScrollPane(modtyptable); modtyptable.setBorder(new LineBorder(new Color(0, 0, 0))); modtyptable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); modtypshow.add(modtypscp); modtypshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Zuordnungen modtypmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Modul Typ" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; // Tabelle f�llen modtyptable.setModel(modtypmodel); modtypmodel.setRowCount(0); int test = 0; for (int i = 0; i < studienlist.size(); i++) { if (studienlist.get(i).getName().equalsIgnoreCase(studtransferstring)) { test = studienlist.get(i).getId(); break; } } // for (int i = 0; i < typen.size(); i++) { // if (test == (typen.get(i).getSid())) // addToTable(typen.get(i).getName()); // } modtyptransferstring = ""; // Wechseln zur Anzeige mit Modulen goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (modtyptable.getSelectedRow() != -1) { int openrow = modtyptable.getSelectedRow(); modtyptransferstring = (String) modtyptable.getValueAt(openrow, 0); modshowCard(); showCard("mod show"); } } }); // Zur�ck zur vorherigen Ansicht back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("modbuch show"); } }); } /** * Erstellt eine Card zur Auswahl eines Modules */ @SuppressWarnings("serial") private void modshowCard() { JPanel modshow = new JPanel(); cards.add(modshow, "mod show"); modshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable modshowtable = new JTable(); JScrollPane modtypscp = new JScrollPane(modshowtable); modshowtable.setBorder(new LineBorder(new Color(0, 0, 0))); modshowtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); modshow.add(modtypscp); modshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Modulen modshowmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Module" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { return false; } }; // Tabelle f�llen modshowtable.setModel(modshowmodel); modshowmodel.setRowCount(0); selectedmodullist = serverConnection.getselectedModul(studtransferstring, modtyptransferstring, modbuchtransferstring); for (int i = 0; i < selectedmodullist.size(); i++) { addToTable(selectedmodullist.get(i)); } modulselectionstring = ""; // Wechsel zur Anzeige des Modules goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (modshowtable.getSelectedRow() != -1) { int openrow = modshowtable.getSelectedRow(); modulselectionstring = (String) modshowtable.getValueAt(openrow, 0); modCard(); showCard("selmodshow"); } } }); // Zur�ck zur vorherigen Ansicht back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("modtyp show"); } }); } /** * Erstellt eine Card zur Anzeige eines Modules */ private void modCard() { JPanel modshow = new JPanel(); cards.add(modshow, "selmodshow"); modshow.setLayout(new BorderLayout(0, 0)); JPanel modpanel = new JPanel(); JButton pdfbtn = new JButton("Als PDF ausgeben"); JButton back = new JButton("Zur\u00FCck"); JPanel btnpan = new JPanel(); btnpan.add(back); btnpan.add(pdfbtn); modshow.add(btnpan, BorderLayout.SOUTH); JScrollPane modscp = new JScrollPane(modpanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); modshow.add(modscp, BorderLayout.CENTER); Modul zws = null; modpanel.setLayout(new BoxLayout(modpanel, BoxLayout.Y_AXIS)); for (int i = 0; i < selectedmodullist.size(); i++) { if (selectedmodullist.get(i).getName().equalsIgnoreCase(modulselectionstring)) { zws = selectedmodullist.get(i); } } // Felder erstellen modpanel.add(modulPanel("Name", zws.getName())); modpanel.add(modulPanel("Jahrgang", modbuchtransferstring)); // for (int i = 0; i < zws.getZuordnungen().size(); i++) { // modpanel.add(modulPanel("Zuordnung", // zws.getZuordnungen().get(i).toString())); // } for (int i = 0; i < zws.getFelder().size(); i++) { modpanel.add(modulPanel(zws.getFelder().get(i).getLabel(), zws.getFelder().get(i).getValue())); } // Pdf f�r das Modul erstellen pdfbtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub try { serverConnection.toPdf(modulselectionstring); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); // Zur�ck zur vorherigen Ansicht back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("mod show"); } }); } /** * Wird aufgerufen, wenn keine Verbindung zum Server besteht Dabei wird der * Benutzer auf den Standart User zur�ckgesetzt */ public static void noConnection() { JOptionPane.showMessageDialog(frame, "Keine Verbindung zum Server!", "Verbindungsfehler", JOptionPane.ERROR_MESSAGE); current = new User("gast", "gast", "", "[email protected]", "d4061b1486fe2da19dd578e8d970f7eb", false, false, false, false, false, true); btnModulEinreichen.setEnabled(false); btnVerwaltung.setEnabled(false); btnModulBearbeiten.setEnabled(false); btnModulArchiv.setEnabled(true); btnUserVerwaltung.setEnabled(false); btnLogin.setText("Einloggen"); showCard("welcome page"); } }
private void homecard() { final ArrayList<String> dialogs = new ArrayList<String>(); cards.add(welcome, "welcome page"); welcome.setLayout(new BorderLayout(0, 0)); pnl_content.setLayout(new BoxLayout(pnl_content, BoxLayout.Y_AXIS)); JPanel pnl_day = new JPanel(); pnl_content.add(pnl_day); JLabel lblStichtag = new JLabel("Stichtag f\u00FCr das Einreichen von Modulen: 30.08.13"); pnl_day.add(lblStichtag); lblStichtag.setHorizontalAlignment(SwingConstants.CENTER); lblStichtag.setAlignmentY(0.0f); lblStichtag.setForeground(Color.RED); lblStichtag.setFont(new Font("Tahoma", Font.BOLD, 14)); JPanel pnl_messages = new JPanel(); pnl_content.add(pnl_messages); pnl_messages.setLayout(new BoxLayout(pnl_messages, BoxLayout.Y_AXIS)); JPanel pnl_mestop = new JPanel(); pnl_messages.add(pnl_mestop); pnl_mestop.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5)); JLabel lblNachrichten = new JLabel("Nachrichten:"); pnl_mestop.add(lblNachrichten); lblNachrichten.setVerticalAlignment(SwingConstants.BOTTOM); lblNachrichten.setHorizontalAlignment(SwingConstants.CENTER); JScrollPane scrollPane = new JScrollPane(); pnl_messages.add(scrollPane); messagemodel = new DefaultTableModel(new Object[][] { { Boolean.FALSE, "", null, null }, }, new String[] { "", "Von", "Betreff", "Datum" }) { Class[] columnTypes = new Class[] { Boolean.class, String.class, String.class, String.class }; public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } boolean[] columnEditables = new boolean[] { true, false, false, false }; public boolean isCellEditable(int row, int column) { return columnEditables[column]; } }; refreshMessageTable(); tblmessages = new JTable(messagemodel); scrollPane.setViewportView(tblmessages); tblmessages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); tblmessages.setFillsViewportHeight(true); tblmessages.setShowVerticalLines(false); tblmessages.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int row = tblmessages.getSelectedRow(); Nachricht n = nachrichten.get(row); nachrichten.remove(row); n.setGelesen(true); if(!dialogs.contains(n.toString())){ dialogs.add(n.toString()); MessageDialog dialog = new MessageDialog(n); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } nachrichten.add(n); refreshMessageTable(); } } }); JPanel pnl_mesbot = new JPanel(); pnl_messages.add(pnl_mesbot); JButton btnNeu = new JButton("Neu"); btnNeu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { int x = -1; int von = 1; int an = 2; String betreff = "Neuer Test"; Date datum = new Date(); boolean gelesen = false; String nachricht = "foooooooooooo blabulb fooooooooo"; Nachricht neu = new Nachricht(x, von, an, betreff, datum, gelesen, nachricht); //abge�ndert damit das prog wieder startet nachrichten.add(neu); refreshMessageTable(); } }); pnl_mesbot.add(btnNeu); JButton btnAlsGelesenMarkieren = new JButton("Als gelesen markieren"); btnAlsGelesenMarkieren.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { for (int i = 0; i < messagemodel.getRowCount(); i++) { if ((boolean) messagemodel.getValueAt(i, 0)) { nachrichten.get(i).setGelesen(true); } } refreshMessageTable(); } }); pnl_mesbot.add(btnAlsGelesenMarkieren); JButton btnAlsUngelesenMarkieren = new JButton("Als ungelesen markieren"); btnAlsUngelesenMarkieren.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (int i = 0; i < messagemodel.getRowCount(); i++) { if ((boolean) messagemodel.getValueAt(i, 0)) { nachrichten.get(i).setGelesen(false); } } refreshMessageTable(); } }); pnl_mesbot.add(btnAlsUngelesenMarkieren); JButton btnLschen = new JButton("L\u00F6schen"); btnLschen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ArrayList<Nachricht> tmp = new ArrayList<Nachricht>(); for (int i = 0; i < messagemodel.getRowCount(); i++) { if ((boolean) messagemodel.getValueAt(i, 0)) { tmp.add(nachrichten.get(i)); } } nachrichten.removeAll(tmp); refreshMessageTable(); } }); pnl_mesbot.add(btnLschen); JPanel pnl_welc = new JPanel(); welcome.add(pnl_welc, BorderLayout.NORTH); JLabel lblNewLabel = new JLabel("Willkommen beim Modul Management System"); pnl_welc.add(lblNewLabel); } private void refreshMessageTable() { Collections.sort(nachrichten, new Comparator<Nachricht>() { public int compare(Nachricht n1, Nachricht n2) { return n1.getDatum().compareTo(n2.getDatum()) * -1; } }); messagemodel.setRowCount(0); for (int i = 0; i < nachrichten.size(); i++) { addToTable(nachrichten.get(i)); } } protected void addToTable(Nachricht neu) { if(neu.isGelesen()){ messagemodel.addRow(new Object[] { false, neu.getAbsender(), neu.getBetreff(), neu.getDatumString() }); } else { messagemodel.addRow(new Object[] { false, "<html><b>" +neu.getAbsender()+ "</b></html>", "<html><b>" +neu.getBetreff()+ "</b></html>", "<html><b>" +neu.getDatumString()+ "</b></html>" }); } } /** * Erstellt den linke Teil der GUI * */ private void leftscr() { btnLogin.setToolTipText("Klicken Sie hier, um in das MMS einzuloggen."); btnModulAkzeptieren.setToolTipText("Klicken Sie hier, um das ausgew�hlte Modul zu akzeptieren. Damit wird es freigegeben und in der Liste der aktuellen Module angezeigt."); btnModulArchiv.setToolTipText("Klicken Sie hier, um das Archiv der aktuellen Module zu durchst�bern."); btnModulBearbeiten.setToolTipText("Klicken Sie hier, um bereits vorhandene Module zu bearbeiten."); btnModulEinreichen.setToolTipText("Klicken Sie hier, um das Modul einzureichen. Damit wird es der verantwortlichen Stelle vorgelegt. Das Modul wird erst nach der Best�tigung der verantwortlichen Stelle in der Liste der aktuellen Module angezeigt."); btnUserVerwaltung.setToolTipText("Klicken Sie hier, um die Benutzerverwaltung aufzurufen. Hier k�nnen Sie neue Benutzer anlegen, deren Daten �ndern und ihre Rechte im MMS festlegen."); btnVerwaltung.setToolTipText("Klicken Sie hier, um die Verwaltung zu �ffnen. Hier k�nnen Sie m�gliche Studieng�nge festlegen, f�r die es Modulhandb�cher geben kann, die Deadline f�r die Modulhandb�cher aktualisieren und Verwalter f�r bestimmte Module festlegen."); JPanel leftpan = new JPanel(); frame.getContentPane().add(leftpan, BorderLayout.WEST); JPanel left = new JPanel(); leftpan.add(left); left.setLayout(new GridLayout(0, 1, 5, 20)); // Button zum Einreichen eines Modules left.add(btnModulEinreichen); btnModulEinreichen.setEnabled(false); btnModulEinreichen.setPreferredSize(btnSz); btnModulEinreichen.setAlignmentX(Component.CENTER_ALIGNMENT); btnModulEinreichen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Abfrage aller Zuordnungen und Studieng�nge aus der Datenbank // Danach Modelle f�llen und zur Card wechseln // typen = serverConnection.getZuordnungen(); studienlist = serverConnection.getStudiengaenge(); cbmodel.removeAllElements(); for (int i = 0; i < studienlist.size(); i++) { cbmodel.addElement(studienlist.get(i)); } // cbmodel_Z.removeAllElements(); // for (int i = 0; i < typen.size(); i++) { // cbmodel_Z.addElement(typen.get(i)); // } showCard("newmodule"); } }); // Button zum Bearbeiten eines Modules left.add(btnModulBearbeiten); btnModulBearbeiten.setEnabled(false); btnModulBearbeiten.setPreferredSize(btnSz); btnModulBearbeiten.setAlignmentX(Component.CENTER_ALIGNMENT); btnModulBearbeiten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Abfrage alles nicht nicht akzeptierten Module // Danach Modell f�llen ArrayList<Modul> module = serverConnection.getModule(false); lm.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm.addElement(module.get(i)); } // Abfrage alles nicht akzeptierten Module // Danach Modell f�llen module = serverConnection.getModule(true); lm_ack.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm_ack.addElement(module.get(i)); } // Zur card mit �bersicht an Modulen wechseln showCard("modulbearbeiten"); } }); // Button zum Login left.add(btnLogin); btnLogin.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Verbindung zum Server current = serverConnection.login(current.geteMail(), current.getPassword()); if (current != null) { // Wenn noch nicht eingeloggt, einloggen if (current.geteMail().equals("[email protected]")) { logindialog log = new logindialog(frame, "Login", serverConnection); int resp = log.showCustomDialog(); if (resp == 1) { // User �bernehmen current = log.getUser(); serverConnection = log.getServerConnection(); btnLogin.setText("Ausloggen"); // Auf Rechte pr�fen checkRights(); } } // Wenn bereits eingeloggt, ausloggen else { current = new User("gast", "gast", "", "[email protected]", "d4061b1486fe2da19dd578e8d970f7eb", false, false, false, false, false, true); if (serverConnection.isConnected() == SUCCES) { checkRights(); } btnLogin.setText("Einloggen"); btnUserVerwaltung.setText("User Verwaltung"); btnUserVerwaltung.setEnabled(false); showCard("welcome page"); } } else { // Wenn keine Verbindung besteht noConnection(); } } }); btnLogin.setPreferredSize(btnSz); btnLogin.setAlignmentX(Component.CENTER_ALIGNMENT); // Button zur Userverwaltung btnUserVerwaltung.setEnabled(false); left.add(btnUserVerwaltung); btnUserVerwaltung.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Wenn User das Recht hat, um Benutzer zu Verwalten, // dann Anzeige der Benutzerverwaltung if (current.getManageUsers()) { // Tabelle leeren tmodel.setRowCount(0); // Tabelle mit neuen daten f�llen worklist = serverConnection.userload("true"); for (int i = 0; i < worklist.size(); i++) { // Wenn der User noch nicht freigeschaltet wurde, // zur Liste mit neuen Benutzern hinzuf�gen if (worklist.get(i).isFreigeschaltet()) { addToTable(worklist.get(i)); } else { neueUser.add(worklist.get(i)); } } // Zur Userverwaltungs Card wechseln showCard("user managment"); // Einblendung aller neuen User for (int i = 0; i < neueUser.size(); i++) { userdialog dlg = new userdialog(frame, "User best�tigen", neueUser.get(i), true, serverConnection); int response = dlg.showCustomDialog(); // Bei Best�tigung, neuen User freischalten und e-Mail // senden User tmp = dlg.getUser(); if (response == 1) { tmp.setFreigeschaltet(true); if (SendMail.send(current.geteMail(), neueUser.get(i).geteMail(), "Sie wurden freigeschaltet!") == 1) { tmp.setFreigeschaltet(true); if (serverConnection.userupdate(tmp, tmp.geteMail()).getStatus() == 201) { addToTable(tmp); neueUser.remove(i); } } // Ansonsten m�glichkeit ihn wieder zu l�schen } else { int n = JOptionPane.showConfirmDialog(frame, "M�chten Sie diesen Benutzer l�schen", "Best�tigung", JOptionPane.YES_NO_OPTION); if (n == 0) { serverConnection.deluser(tmp.geteMail()); } } } } else { // Ansonsten Dialog �ffnen, // in dem die eigenen Daten ge�ndert werden k�nnen userdialog dlg = new userdialog(frame, "User bearbeiten", current, false, serverConnection); int response = dlg.showCustomDialog(); // Wenn ok gedr�ckt wird // neuen User abfragen if (response == 1) { User tmp = dlg.getUser(); if (serverConnection.userupdate(tmp, current.geteMail()).getStatus() == 201) { current = tmp; checkRights(); } else JOptionPane.showMessageDialog(frame, "Update Fehlgeschlagen!", "Update Error", JOptionPane.ERROR_MESSAGE); } } } }); btnUserVerwaltung.setPreferredSize(btnSz); btnUserVerwaltung.setAlignmentX(Component.CENTER_ALIGNMENT); // Button zur Verwaltung von Studieng�ngen und Zuordnungen btnVerwaltung.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // Zuordnungen und Studieng�nge aus Datenbank abrufen // und Listen f�llen studienlist = serverConnection.getStudiengaenge(); studimodel.removeAllElements(); for (int i = 0; i < studienlist.size(); i++) { studimodel.addElement(studienlist.get(i)); } cbmodel.removeAllElements(); for (int i = 0; i < studienlist.size(); i++) { cbmodel.addElement(studienlist.get(i)); } // typen = serverConnection.getZuordnungen(); // for (int i = 0; i < typen.size(); i++) { // typenmodel.addElement(typen.get(i)); // } // Zur Card wechseln showCard("manage"); } }); left.add(btnVerwaltung); btnVerwaltung.setEnabled(false); btnVerwaltung.setPreferredSize(btnSz); btnVerwaltung.setAlignmentX(Component.CENTER_ALIGNMENT); left.add(btnModulArchiv); btnModulArchiv.setEnabled(true); btnModulArchiv.setPreferredSize(btnSz); btnModulArchiv.setAlignmentX(Component.CENTER_ALIGNMENT); // Button zum Durchst�bern von Modulen btnModulArchiv.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { current = serverConnection.login(current.geteMail(), current.getPassword()); if (current != null) { // Studieng�nge und Zuordnungen abrufen studmodel.setRowCount(0); studienlist = serverConnection.getStudiengaenge(); for (int i = 0; i < studienlist.size(); i++) { addToTable(studienlist.get(i)); } //TODO something // typen = serverConnection.getZuordnungen(); // Zur Card wechseln showCard("studiengang show"); } else { noConnection(); } } }); } /** * Erstellt eine Card, um ein neues Modul anzulegen * */ private void newmodulecard() { // Alle vorhandenen Felder entfernen modul_panel.removeAll(); final JPanel pnl_newmod = new JPanel(); // Liste dynamischer Buttons leeren if (!buttonmap.isEmpty()) { for (int i = 0; i < buttonmap.size(); i++) buttonmap.remove(i); } // Liste mit bereits vorhandenen Felder erstellen und mit den // Standartfeldern f�llen final ArrayList<String> labels = new ArrayList<String>(); labels.addAll(defaultlabels); final Dimension preferredSize = new Dimension(120, 20); pnl_newmod.setLayout(new BorderLayout(0, 0)); JPanel pnl_bottom = new JPanel(); pnl_newmod.add(pnl_bottom, BorderLayout.SOUTH); // Button zum erstellen eines neuen Feldes JButton btnNeuesFeld = new JButton("Neues Feld"); btnNeuesFeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String text = "Name des Feldes"; // Abfrage des Namen des Feldes String name = JOptionPane.showInputDialog(frame, text); try { // Pr�fe, ob Name leer oder schon vorhanden ist while (name.isEmpty() || labels.contains(name)) { Object[] params = { "Bitte geben Sie eine g�ltige Bezeichnung ein!", text }; name = JOptionPane.showInputDialog(frame, params); } labels.add(name); JPanel pnl_tmp = new JPanel(); modul_panel.add(pnl_tmp); // Platzhalter modul_panel.add(Box.createRigidArea(new Dimension(0, 5))); // Abfrage der Anzahl an Panels, die bereits vorhanden sind int numOfPanels = modul_panel.getComponentCount(); pnl_tmp.setLayout(new BoxLayout(pnl_tmp, BoxLayout.X_AXIS)); JLabel label_tmp = new JLabel(name); label_tmp.setPreferredSize(preferredSize); pnl_tmp.add(label_tmp); JTextArea txt_tmp = new JTextArea(); txt_tmp.setLineWrap(true); pnl_tmp.add(txt_tmp); JCheckBox dez = new JCheckBox("Dezernat 2", false); pnl_tmp.add(dez); // Button, um das Feld wieder zu entfernen JButton btn_tmp_entf = new JButton("Entfernen"); btn_tmp_entf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = buttonmap.get(e.getSource()); // Bezeichnung aus Liste entfernen String name = ((JLabel) ((JPanel) modul_panel.getComponent(id)).getComponent(0)).getText(); labels.remove(name); // Feld mit ID id von Panel entfernen modul_panel.remove(id); // Platzhalter entfernen modul_panel.remove(id - 1); // Aus ButtonMap entfernen buttonmap.remove(e.getSource()); // ids der Buttons �ndern, damit auch ein Feld aus // der Mitte gel�cht werden kann HashMap<JButton, Integer> tmpmap = new HashMap<JButton, Integer>(); Iterator<Entry<JButton, Integer>> entries = buttonmap.entrySet().iterator(); while (entries.hasNext()) { Entry<JButton, Integer> thisEntry = entries.next(); JButton key = thisEntry.getKey(); int value = thisEntry.getValue(); if (value > id) { value = value - 2; } tmpmap.put(key, value); } buttonmap = tmpmap; modul_panel.revalidate(); } }); // Button btn_tmp_entf mit ID (numOfPanels-2) zu ButtonMap // hinzuf�gen buttonmap.put(btn_tmp_entf, numOfPanels - 2); pnl_tmp.add(btn_tmp_entf); modul_panel.revalidate(); } catch (NullPointerException npe) { // nichts tuen bei Abbruch } } }); pnl_bottom.add(btnNeuesFeld); // Zur�ck zur Startseite JButton btnHome = new JButton("Zur\u00fcck"); btnHome.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Card wieder erneuern und zur Startseite wechseln newmodulecard(); modul_panel.revalidate(); showCard("welcome page"); } }); pnl_bottom.add(btnHome); JScrollPane scrollPane = new JScrollPane(modul_panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); modul_panel.setLayout(new BoxLayout(modul_panel, BoxLayout.Y_AXIS)); // Panel Zuordnung + Platzhalter JPanel pnl_Z = new JPanel(); pnl_Z.setLayout(new BoxLayout(pnl_Z, BoxLayout.X_AXIS)); JLabel label_MH = new JLabel("Zuordnung"); label_MH.setPreferredSize(preferredSize); pnl_Z.add(label_MH); // Liste mit ausgew�hlten Zuordnungen // final DefaultListModel<Zuordnung> lm = new // DefaultListModel<Zuordnung>(); // final JList<Zuordnung> zlist = new JList<Zuordnung>(lm); // zlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // // pnl_Z.add(zlist); // // // ComboBox mit Zuordnungen // final JComboBox<Zuordnung> cb_Z = new // JComboBox<Zuordnung>(cbmodel_Z); // cb_Z.setMaximumSize(new Dimension(400, 20)); // // pnl_Z.add(cb_Z); // // // Auswahl einer Zuordnung aus der ComboBox // JButton z_btn = new JButton("Zuordnung ausw\u00e4hlen"); // z_btn.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // if (!lm.contains(cb_Z.getSelectedItem())) // lm.addElement((Zuordnung) cb_Z.getSelectedItem()); // } // }); // pnl_Z.add(z_btn); // // // In der Liste ausgew�hlte Zuordnung wieder entfernen // JButton btnZuordnungEntfernen = new JButton("Zuordnung entfernen"); // btnZuordnungEntfernen.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // int i = zlist.getSelectedIndex(); // if (i > -1) { // lm.remove(i); // } // } // }); // pnl_Z.add(btnZuordnungEntfernen); // // modul_panel.add(pnl_Z); modul_panel.add(Box.createRigidArea(new Dimension(0, 5))); // Alle Standartfelder, au�er Zuordnung erzeugen for (int i = 3; i < defaultlabels.size(); i++) { modul_panel.add(defaultmodulPanel(defaultlabels.get(i), "", false)); modul_panel.add(Box.createRigidArea(new Dimension(0, 5))); } // Button zum Annehmen eines Modules JButton btnOk = new JButton("Annehmen"); btnOk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // ArrayList<Zuordnung> zlist = new ArrayList<Zuordnung>(); String jg = ((JTextArea) ((JPanel) modul_panel.getComponent(2)).getComponent(1)).getText(); int jahrgang; try { jahrgang = Integer.parseInt(jg); } catch (NumberFormatException nfe) { jahrgang = 0; } // for (int i = 0; i < lm.getSize(); i++) { // zlist.add(lm.getElementAt(i)); // } // Pr�fe, ob min. eine Zuordnung ausgew�hlt und ein g�ltiger // Jahrgang eingegeben wurde // if (!zlist.isEmpty()) { // if (jahrgang != 0) { // // String Name = ((JTextArea) ((JPanel) // modul_panel.getComponent(4)).getComponent(1)).getText(); // // if (Name.isEmpty()) { // JOptionPane.showMessageDialog(frame, // "Bitte geben Sie einen Namen ein!", "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } else { // // boolean filled = true; // ArrayList<Feld> felder = new ArrayList<Feld>(); // // Eintraege der Reihe nach auslesen // for (int i = 6; i < modul_panel.getComponentCount(); i = i + // 2) { // JPanel tmp = (JPanel) modul_panel.getComponent(i); // JLabel tmplbl = (JLabel) tmp.getComponent(0); // JTextArea tmptxt = (JTextArea) tmp.getComponent(1); // // boolean dezernat2 = ((JCheckBox) // tmp.getComponent(2)).isSelected(); // String value = tmptxt.getText(); // String label = tmplbl.getText(); // // Pr�fe, ob alle Felder ausgef�llt wurden // if (value.isEmpty()) { // filled = false; // break; // } // felder.add(new Feld(label, value, dezernat2)); // } // // Wenn alle aussgef�llt wurden, neues Modul // // erzeugen und bei Best�tigung einreichen // if (filled == true) { // int version = serverConnection.getModulVersion(Name) + 1; // // Date d = new Date(); // ArrayList<String> user = new ArrayList<String>(); // user.add(current.geteMail()); // Modul neu = new Modul(Name, felder, version, d, 0, false, // user, ""); // int n = JOptionPane.showConfirmDialog(frame, // "Sind Sie sicher, dass Sie dieses Modul einreichen wollen?", // "Best�tigung", JOptionPane.YES_NO_OPTION); // if (n == 0) { // serverConnection.setModul(neu); // labels.removeAll(labels); // modul_panel.removeAll(); // modul_panel.revalidate(); // newmodulecard(); // showCard("newmodule"); // } // } // Fehler, wenn nicht alle ausgef�llt wurden // else { // JOptionPane.showMessageDialog(frame, // "Bitte f�llen Sie alle Felder aus!", "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte geben Sie einen g�ltigen Wert f�r den Jahrgang ein!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte w�hlen Sie min. einen Zuordnung aus!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } } }); pnl_bottom.add(btnOk); pnl_newmod.add(scrollPane); cards.add(pnl_newmod, "newmodule"); } /** * Entfernt einen Eintrag aus der Usertabelle * * @param rowid * Der Index des zu enfernenden Eintrages */ private void removeFromTable(int rowid) { tmodel.removeRow(rowid); } /** * Wechselt zur angegeben Card * * @param card * Die Bezeichnung der Card, zu der gewechselt werden soll */ private static void showCard(String card) { ((CardLayout) cards.getLayout()).show(cards, card); } /** * Erstellt eine Card zur Verwaltung von Benutzern */ @SuppressWarnings("serial") private void usermgtcard() { JPanel usrmg = new JPanel(); cards.add(usrmg, "user managment"); usrmg.setLayout(new BorderLayout(0, 0)); JPanel usrpan = new JPanel(); FlowLayout fl_usrpan = (FlowLayout) usrpan.getLayout(); fl_usrpan.setAlignment(FlowLayout.RIGHT); usrmg.add(usrpan, BorderLayout.SOUTH); final JTable usrtbl = new JTable(); JScrollPane ussrscp = new JScrollPane(usrtbl); usrtbl.setBorder(new LineBorder(new Color(0, 0, 0))); usrtbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // // Inhalt der Tabelle // tmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Titel", "Vorname", "Nachname", "e-Mail", "Benutzer verwalten", "Module einreichen", "Module Annehmen", "Verwaltung" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class, String.class, String.class, String.class, boolean.class, boolean.class, boolean.class, boolean.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; usrtbl.setModel(tmodel); // Button zum hinzuf�gen eines Benutzers JButton btnUserAdd = new JButton("User hinzuf\u00fcgen"); btnUserAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { userdialog dlg = new userdialog(frame, "User hinzuf\u00fcgen", serverConnection); int response = dlg.showCustomDialog(); // Wenn ok gedr�ckt wird // neuen User hinzuf�gen if (response == 1) { User tmp = dlg.getUser(); tmp.setFreigeschaltet(true); // Wenn er erfolgreich in die DB eingetragen wurde,zur // Tabelle hinzuf�gen if (serverConnection.usersave(tmp).getStatus() == 201) { addToTable(tmp); } } } }); usrpan.add(btnUserAdd); // Button zum bearbeiten eines in der Tabelle ausgew�hlten Users JButton btnUserEdit = new JButton("User bearbeiten"); btnUserEdit.setToolTipText("Zum Bearbeiten Benutzer in der Tabelle markieren"); btnUserEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int row = usrtbl.getSelectedRow(); if (row != -1) { // Daten aus der Tabelle abrufen und User erzeugen String t = (String) usrtbl.getValueAt(row, 0); String vn = (String) usrtbl.getValueAt(row, 1); String nn = (String) usrtbl.getValueAt(row, 2); String em = (String) usrtbl.getValueAt(row, 3); boolean r1 = (boolean) usrtbl.getValueAt(row, 4); boolean r2 = (boolean) usrtbl.getValueAt(row, 5); boolean r3 = (boolean) usrtbl.getValueAt(row, 6); boolean r4 = (boolean) usrtbl.getValueAt(row, 7); boolean r5 = (boolean) usrtbl.getValueAt(row, 8); User alt = new User(vn, nn, t, em, null, r1, r2, r3, r4, r5, true); // User an Bearbeiten dialog �bergeben userdialog dlg = new userdialog(frame, "User bearbeiten", alt, true, serverConnection); int response = dlg.showCustomDialog(); // Wenn ok ged\u00fcckt wird // neuen User abfragen if (response == 1) { User tmp = dlg.getUser(); tmp.setFreigeschaltet(true); // Wenn update erfolgreich war, alten user abfragen und // neu hinzuf�gen if (serverConnection.userupdate(tmp, em).getStatus() == 201) { removeFromTable(row); addToTable(tmp); // Falls eigener Benutzer bearbeitet wurde, Rechte // erneut pr�fen if (em.equals(current.geteMail())) { current = tmp; checkRights(); } } else JOptionPane.showMessageDialog(frame, "Update Fehlgeschlagen", "Update Fehler", JOptionPane.ERROR_MESSAGE); } } } }); usrpan.add(btnUserEdit); // L�schen eines ausgew�hlten Benutzers JButton btnUserDel = new JButton("User l\u00f6schen"); btnUserDel.setToolTipText("Zum L\u00f6schen Benutzer in der Tabelle markieren"); btnUserDel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int row = usrtbl.getSelectedRow(); if (row != -1) { int n = JOptionPane.showConfirmDialog(frame, "Sind Sie sicher, dass Sie diesen Benutzer l\u00f6schen wollen?", "Best�tigung", JOptionPane.YES_NO_OPTION); if (n == 0) { // Wenn L�schen erfolgreich war, aus der Tabelle // entfernen if (serverConnection.deluser((String) usrtbl.getValueAt(row, 3)).getStatus() != 201) { removeFromTable(row); } else JOptionPane.showMessageDialog(frame, "L\u00f6schen Fehlgeschlagen", "Fehler beim L\u00f6schen", JOptionPane.ERROR_MESSAGE); } } } }); usrpan.add(btnUserDel); // Zur�ck zur Startseite JButton btnHome = new JButton("Zur\u00fcck"); btnHome.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); usrpan.add(btnHome); JPanel usrcenter = new JPanel(); usrmg.add(usrcenter, BorderLayout.CENTER); usrcenter.setLayout(new BorderLayout(5, 5)); usrcenter.add(ussrscp); JPanel leftpan = new JPanel(); frame.getContentPane().add(leftpan, BorderLayout.WEST); } /** * �berpr�ft die Rechte des aktuell eingeloggten Benutzers und aktiviert * Buttons, auf die er Zugriff hat und deaktiviert Bttons, auf die er keinen * Zugriff hat */ protected void checkRights() { btnModulEinreichen.setEnabled(false); btnModulBearbeiten.setEnabled(false); btnVerwaltung.setEnabled(false); btnModulBearbeiten.setEnabled(false); btnUserVerwaltung.setEnabled(false); btnModulAkzeptieren.setEnabled(false); canReadMessages=false; welcome.remove(pnl_content); welcome.repaint(); if (current.getCreateModule()) { btnModulEinreichen.setEnabled(true); btnModulBearbeiten.setEnabled(true); canReadMessages=true; } if (current.getAcceptModule()) { btnModulBearbeiten.setEnabled(true); btnModulAkzeptieren.setEnabled(true); canReadMessages=true; } if (current.getManageSystem()) { btnVerwaltung.setEnabled(true); canReadMessages=true; } if (current.getManageUsers()) { btnUserVerwaltung.setEnabled(true); btnUserVerwaltung.setText("User Verwaltung"); canReadMessages=true; } else { btnUserVerwaltung.setEnabled(true); btnUserVerwaltung.setText("Account bearbeiten"); } if(canReadMessages){ welcome.add(pnl_content, BorderLayout.CENTER); nachrichten = serverConnection.getNachrichten(current.geteMail()); refreshMessageTable(); } showCard("welcome page"); } /** * Erstellt eine Card zur Bearbeitung von Modulen */ public void modulbearbeitenCard() { JPanel pnl_modedit = new JPanel(); pnl_modedit.setLayout(new BorderLayout(0, 0)); // Tab f�r akzeptierte und f�r nicht akzeptierte Module erstellen JTabbedPane tabs = new JTabbedPane(SwingConstants.TOP); pnl_modedit.add(tabs); JPanel nichtakzeptiert = new JPanel(); tabs.addTab("Noch nicht akzeptierte Module", null, nichtakzeptiert, null); nichtakzeptiert.setLayout(new BorderLayout(0, 0)); final JList<Modul> list_notack = new JList<Modul>(lm); list_notack.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_notack.setLayoutOrientation(JList.VERTICAL_WRAP); nichtakzeptiert.add(list_notack); JPanel buttonpnl = new JPanel(); nichtakzeptiert.add(buttonpnl, BorderLayout.SOUTH); // Button zum bearbeiten eines nicht akzeptierten Modules JButton btnModulBearbeiten = new JButton("Modul bearbeiten"); btnModulBearbeiten.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Modul m = list_notack.getSelectedValue(); if (m != null) { // Abfragen, ob Modul in Bearbeitung ist m.setInbearbeitung(serverConnection.getModulInEdit(m.getName())); if (!m.isInbearbeitung()) { // Pr�fe, ob Benutzer das Rech hat, das Modul zu // Bearbeiten // Wenn er das Modul selbst erstellt hat, darf er es // auch bearbeiten // Ansonsten Pr�fen, ob es von einem Stellvertreter oder // Vorgesetzetn von ihm erstellt wurde boolean rights = false; if (m.getUser().equals(current.geteMail())) { rights = true; } else { ArrayList<String> rel = serverConnection.getUserRelation(current.geteMail()); if (rel.contains(m.getUser())) { rights = true; } } // Wenn er die Rechte dazu hat, Modul als in Bearbeitung // markieren und zur Bearbeitung wechseln if (rights) { mod.removeAll(); mod.add(modeditCard(m), BorderLayout.CENTER); m.setInbearbeitung(true); serverConnection.setModulInEdit(m); showCard("modBearbeiten"); } else { JOptionPane.showMessageDialog(frame, "Sie besitzen nicht die n\u00f6tigen Rechte, um dieses Modul zu bearbeiten!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "Dieses Modul befindet sich gerade in bearbeitung!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } } }); buttonpnl.add(btnModulBearbeiten); // Button zum akzeptieren eines Modules btnModulAkzeptieren.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Modul m = list_notack.getSelectedValue(); if (m != null) { // Pr�fe, ob Modul in Bearbeitung ist m.setInbearbeitung(serverConnection.getModulInEdit(m.getName())); if (!m.isInbearbeitung()) { if (m.getName().isEmpty()) { JOptionPane.showMessageDialog(frame, "Bei diesem Modul sind nicht alle Felder ausgef�llt!", "Fehler im Modul", JOptionPane.ERROR_MESSAGE); } else { // Pr�fe, ob ein Feld f�r das Dezernat 2 markiert // wurde // und ob alle Felder ausgef�llt wurden boolean hasDezernat = false; boolean isCorrect = true; ArrayList<Feld> felder = m.getFelder(); for (int i = 0; i < felder.size(); i++) { if (felder.get(i).getValue().isEmpty()) { JOptionPane.showMessageDialog(frame, "Bei diesem Modul sind nicht alle Felder ausgef�llt!", "Fehler im Modul", JOptionPane.ERROR_MESSAGE); isCorrect = false; break; } if (felder.get(i).isDezernat()) { hasDezernat = true; } } if (isCorrect) { boolean checked = true; // Wenn Felder als Dezernat 2 markiert wurden, // nach Best�tigung fragen if (hasDezernat) { int n = JOptionPane.showConfirmDialog(frame, "Dieses Modul besitzt Felder, die vom Dezernat2 �berpr�ft werden m�ssen, wurde das getan?", "Best�tigung", JOptionPane.YES_NO_OPTION); if (n == 0) { checked = true; } else { checked = false; } } if (checked) { // Bei best�tigung Modul akzeptieren und // Listen neu abrufen // dann zur Bearbeiten �bersicht wechseln serverConnection.acceptModul(m); ArrayList<Modul> module = serverConnection.getModule(false); lm.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm.addElement(module.get(i)); } module = serverConnection.getModule(true); lm_ack.removeAllElements(); for (int i = 0; i < module.size(); i++) { lm_ack.addElement(module.get(i)); } showCard("modulbearbeiten"); } } } } else { JOptionPane.showMessageDialog(frame, "Dieses Modul befindet sich gerade in bearbeitung!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } } }); buttonpnl.add(btnModulAkzeptieren); // Zur�ck zur Startseite JButton btnZurck = new JButton("Zur\u00FCck"); btnZurck.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); buttonpnl.add(btnZurck); // akzeptierte Module JPanel akzeptiert = new JPanel(); tabs.addTab("akzeptierte Module", null, akzeptiert, null); tabs.setEnabledAt(1, true); akzeptiert.setLayout(new BorderLayout(0, 0)); final JList<Modul> list_ack = new JList<Modul>(lm_ack); list_ack.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_ack.setLayoutOrientation(JList.VERTICAL_WRAP); akzeptiert.add(list_ack); JPanel buttonpnl2 = new JPanel(); akzeptiert.add(buttonpnl2, BorderLayout.SOUTH); // akzeptierte Module bearbeiten JButton btnModulBearbeiten2 = new JButton("Modul bearbeiten"); btnModulBearbeiten2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { Modul m = list_ack.getSelectedValue(); if (m != null) { // Pr�fe, ob Modul in Bearbeitung ist m.setInbearbeitung(serverConnection.getModulInEdit(m.getName())); if (!m.isInbearbeitung()) { // Pr�fe, ob User das Recht hat, dieses Modul zu // bearbeiten boolean rights = false; if (m.getUser().equals(current.geteMail())) { rights = true; } else { ArrayList<String> rel = serverConnection.getUserRelation(current.geteMail()); if (rel.contains(m.getUser())) { rights = true; } } if (rights) { // Zur Bearbeitung wechseln mod.removeAll(); mod.add(modeditCard(m), BorderLayout.CENTER); showCard("modBearbeiten"); } else { JOptionPane.showMessageDialog(frame, "Sie besitzen nicht die n\u00f6tigen Rechte, um dieses Modul zu bearbeiten!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(frame, "Dieses Modul befindet sich gerade in bearbeitung!", "Zugriff verweigert", JOptionPane.ERROR_MESSAGE); } } } }); buttonpnl2.add(btnModulBearbeiten2); // Zur�ck zur Startseite JButton btnZurck2 = new JButton("Zur\u00FCck"); btnZurck2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); buttonpnl2.add(btnZurck2); cards.add(pnl_modedit, "modulbearbeiten"); } /** * Liefert ein Panel, dass mit den Daten von Modul m ausgef�llt ist Die * Felder sind dabei nicht mehr bearbeitbar * * @return JPanel mit Daten ausgef�lltes Panel * @param m * Zu bearbeitendes Modul */ private JPanel modeditCardPrev(Modul m) { final JPanel pnl_editmod = new JPanel(); final JPanel pnl_mod_prev = new JPanel(); // Felder vom Modul abfragen final ArrayList<Feld> felder = m.getFelder(); final ArrayList<String> labels = new ArrayList<String>(); for (int i = 0; i < felder.size(); i++) { labels.add(felder.get(i).getLabel()); } final Dimension preferredSize = new Dimension(120, 20); pnl_editmod.setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(pnl_mod_prev, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); pnl_mod_prev.setLayout(new BoxLayout(pnl_mod_prev, BoxLayout.Y_AXIS)); // Panel Zuordnung + Platzhalter JPanel pnl_Z = new JPanel(); pnl_Z.setLayout(new BoxLayout(pnl_Z, BoxLayout.X_AXIS)); JLabel label_MH = new JLabel("Zuordnung"); label_MH.setPreferredSize(preferredSize); pnl_Z.add(label_MH); // Zuordnugen vom Modul abfragen // final DefaultListModel<Zuordnung> lm = new // DefaultListModel<Zuordnung>(); // typen = m.getZuordnungen(); // for (int i = 0; i < typen.size(); i++) { // lm.addElement(typen.get(i)); // } // JList<Zuordnung> zlist = new JList<Zuordnung>(lm); // pnl_Z.add(zlist); pnl_mod_prev.add(pnl_Z); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); // Restliche Felder erzeugen JPanel jg = new JPanel(); jg.setLayout(new BoxLayout(jg, BoxLayout.X_AXIS)); JLabel lbl_jg = new JLabel("Jahrgang"); lbl_jg.setPreferredSize(preferredSize); jg.add(lbl_jg); // JTextArea txt_jg = new JTextArea(m.getJahrgang() + ""); // txt_jg.setLineWrap(true); // txt_jg.setEditable(false); // jg.add(txt_jg); pnl_mod_prev.add(jg); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); JPanel name = new JPanel(); name.setLayout(new BoxLayout(name, BoxLayout.X_AXIS)); JLabel lbl_n = new JLabel("Name"); lbl_n.setPreferredSize(preferredSize); name.add(lbl_n); JTextArea txt_n = new JTextArea(m.getName()); txt_n.setLineWrap(true); txt_n.setEditable(false); name.add(txt_n); pnl_mod_prev.add(name); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); for (int i = 0; i < m.getFelder().size(); i++) { Feld f = m.getFelder().get(i); JPanel pnl = new JPanel(); pnl.setLayout(new BoxLayout(pnl, BoxLayout.X_AXIS)); JLabel label = new JLabel(f.getLabel()); label.setPreferredSize(preferredSize); pnl.add(label); // Felder sind hier nicht bearbeitbar JTextArea txt = new JTextArea(f.getValue()); txt.setLineWrap(true); txt.setEditable(false); pnl.add(txt); JCheckBox dez = new JCheckBox("Dezernat 2", f.isDezernat()); dez.setEnabled(false); pnl.add(dez); pnl_mod_prev.add(pnl); pnl_mod_prev.add(Box.createRigidArea(new Dimension(0, 5))); } pnl_editmod.add(scrollPane); return pnl_editmod; } /** * Liefert ein Panel, dass mit den Daten von Modul m ausgef�llt ist * * @return JPanel mit Daten ausgef�lltes Panel * @param m * Zu bearbeitendes Modul */ private JPanel modeditCard(final Modul m) { // Alle Felder entfernen // Buttonmap leeren final JPanel pnl_editmod = new JPanel(); modul_panel_edit.removeAll(); if (!buttonmap.isEmpty()) { for (int i = 0; i < buttonmap.size(); i++) buttonmap.remove(i); } // Felder vom Modul abfragen final ArrayList<Feld> felder = m.getFelder(); final ArrayList<String> labels = new ArrayList<String>(); for (int i = 0; i < felder.size(); i++) { labels.add(felder.get(i).getLabel()); } final Dimension preferredSize = new Dimension(120, 20); pnl_editmod.setLayout(new BorderLayout(0, 0)); JPanel pnl_bottom = new JPanel(); pnl_editmod.add(pnl_bottom, BorderLayout.SOUTH); // Button zur anzeige der vorherigen Version JButton alt = new JButton("Vorherige Version"); alt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { int v = m.getVersion() - 1; if (v > 0) { String name = m.getName(); Modul pre = serverConnection.getModul(name, v); if (pre != null) JOptionPane.showMessageDialog(frame, modeditCardPrev(pre), "Vorherige Version", 1); } else { JOptionPane.showMessageDialog(frame, "Keine Vorherige Version vorhanden!", "Fehler", JOptionPane.ERROR_MESSAGE); } } }); pnl_bottom.add(alt); // Button zum erzeugen eines neuen Feldes JButton btnNeuesFeld = new JButton("Neues Feld"); btnNeuesFeld.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { String text = "Name des Feldes"; String name = JOptionPane.showInputDialog(frame, text); try { while (name.isEmpty() || labels.contains(name)) { Object[] params = { "Bitte geben Sie eine g�ltige Bezeichnung ein!", text }; name = JOptionPane.showInputDialog(frame, params); } labels.add(name); // Platzhalter JPanel pnl_tmp = new JPanel(); modul_panel_edit.add(pnl_tmp); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); // Abfrage der Anzahl an Feldern int numOfPanels = modul_panel_edit.getComponentCount(); pnl_tmp.setLayout(new BoxLayout(pnl_tmp, BoxLayout.X_AXIS)); JLabel label_tmp = new JLabel(name); label_tmp.setPreferredSize(preferredSize); pnl_tmp.add(label_tmp); JTextArea txt_tmp = new JTextArea(); txt_tmp.setLineWrap(true); pnl_tmp.add(txt_tmp); JCheckBox dez = new JCheckBox("Dezernat 2", false); pnl_tmp.add(dez); // Feld wieder entfernen JButton btn_tmp_entf = new JButton("Entfernen"); btn_tmp_entf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = buttonmap.get(e.getSource()); // Bezeichnung aus Liste entfernen String name = ((JLabel) ((JPanel) modul_panel_edit.getComponent(id)).getComponent(0)).getText(); labels.remove(name); // Feld mit ID id von Panel entfernen modul_panel_edit.remove(id); // Platzhalter entfernen modul_panel_edit.remove(id - 1); // Aus ButtonMap entfernen buttonmap.remove(e.getSource()); // ids der Buttons �ndern, damit auch ein Feld aus // der Mitte gel�scht werden kann HashMap<JButton, Integer> tmpmap = new HashMap<JButton, Integer>(); Iterator<Entry<JButton, Integer>> entries = buttonmap.entrySet().iterator(); while (entries.hasNext()) { Entry<JButton, Integer> thisEntry = entries.next(); JButton key = thisEntry.getKey(); int value = thisEntry.getValue(); if (value > id) { value = value - 2; } tmpmap.put(key, value); } buttonmap = tmpmap; modul_panel_edit.revalidate(); } }); // Button btn_tmp_entf mit ID (numOfPanels-2) zu ButtonMap buttonmap.put(btn_tmp_entf, numOfPanels - 2); pnl_tmp.add(btn_tmp_entf); modul_panel_edit.revalidate(); } catch (NullPointerException npe) { // nichts tuen bei Abbruch } } }); pnl_bottom.add(btnNeuesFeld); // Zur�ck zur Startseite JButton btnHome = new JButton("Zur\u00fcck"); btnHome.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Panel wider neu erzeugen, // Modul als nicht in Bearbeitung markieren modul_panel_edit.removeAll(); modul_panel_edit.revalidate(); m.setInbearbeitung(false); serverConnection.setModulInEdit(m); modulbearbeitenCard(); showCard("modulbearbeiten"); } }); pnl_bottom.add(btnHome); JScrollPane scrollPane = new JScrollPane(modul_panel_edit, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); modul_panel_edit.setLayout(new BoxLayout(modul_panel_edit, BoxLayout.Y_AXIS)); // Panel Zuordnung + Platzhalter JPanel pnl_Z = new JPanel(); pnl_Z.setLayout(new BoxLayout(pnl_Z, BoxLayout.X_AXIS)); JLabel label_MH = new JLabel("Zuordnung"); label_MH.setPreferredSize(preferredSize); pnl_Z.add(label_MH); // Liste ausgew�hlter Zuordnungen // final DefaultListModel<Zuordnung> lm_Z = new // DefaultListModel<Zuordnung>(); // typen = m.getZuordnungen(); // for (int i = 0; i < typen.size(); i++) { // lm_Z.addElement(typen.get(i)); // } // final JList<Zuordnung> zlist = new JList<Zuordnung>(lm_Z); // zlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // // pnl_Z.add(zlist); // typen = serverConnection.getZuordnungen(); // cbmodel_Z.removeAllElements(); // for (int i = 0; i < typen.size(); i++) { // cbmodel_Z.addElement(typen.get(i)); // } // // Zur auswahlstehende Zuordnungen // final JComboBox<Zuordnung> cb_Z = new // JComboBox<Zuordnung>(cbmodel_Z); // cb_Z.setMaximumSize(new Dimension(cb_Z.getMaximumSize().width, 20)); // // pnl_Z.add(cb_Z); // // // Zuordnung ausw�hlen // JButton z_btn = new JButton("Zuordnung ausw\u00e4hlen"); // z_btn.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // if (!lm_Z.contains(cb_Z.getSelectedItem())) // lm_Z.addElement((Zuordnung) cb_Z.getSelectedItem()); // } // }); // pnl_Z.add(z_btn); // // // Zuordnung wieder entfernen // JButton btnZuordnungEntfernen = new JButton("Zuordnung entfernen"); // btnZuordnungEntfernen.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // int i = zlist.getSelectedIndex(); // if (i > -1) { // lm_Z.remove(i); // } // } // }); // pnl_Z.add(btnZuordnungEntfernen); modul_panel_edit.add(pnl_Z); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); // modul_panel_edit.add(defaultmodulPanel("Jahrgang", m.getJahrgang() + // "", false)); // modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); JPanel pnl = new JPanel(); pnl.setLayout(new BoxLayout(pnl, BoxLayout.X_AXIS)); JLabel label = new JLabel("Name"); label.setPreferredSize(preferredSize); pnl.add(label); JTextArea txt = new JTextArea(m.getName()); txt.setLineWrap(true); pnl.add(txt); txt.setEditable(false); modul_panel_edit.add(pnl); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); // Felder erzeugen und f�llen for (int i = 0; i < m.getFelder().size(); i++) { Feld f = m.getFelder().get(i); JPanel feld = defaultmodulPanel(f.getLabel(), f.getValue(), f.isDezernat()); // Wenn es kein Standart Feld ist, einen entfernen Button hinzuf�gen if (!defaultlabels.contains(f.getLabel())) { int numOfPanels = modul_panel_edit.getComponentCount(); JButton btn_tmp_entf = new JButton("Entfernen"); btn_tmp_entf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int id = buttonmap.get(e.getSource()); // Bezeichnung aus Liste entfernen String name = ((JLabel) ((JPanel) modul_panel_edit.getComponent(id)).getComponent(0)).getText(); labels.remove(name); // Feld mit ID id von Panel entfernen modul_panel_edit.remove(id); // Platzhalter entfernen modul_panel_edit.remove(id - 1); // Aus ButtonMap entfernen buttonmap.remove(e.getSource()); // ids der Buttons �ndern, damit auch ein Feld aus // der Mitte gel�scht werden kann HashMap<JButton, Integer> tmpmap = new HashMap<JButton, Integer>(); Iterator<Entry<JButton, Integer>> entries = buttonmap.entrySet().iterator(); while (entries.hasNext()) { Entry<JButton, Integer> thisEntry = entries.next(); JButton key = thisEntry.getKey(); int value = thisEntry.getValue(); if (value > id) { value = value - 2; } tmpmap.put(key, value); } buttonmap = tmpmap; modul_panel_edit.revalidate(); modul_panel_edit.repaint(); } }); feld.add(btn_tmp_entf); // Button btn_tmp_entf mit ID (numOfPanels-2) zu ButtonMap buttonmap.put(btn_tmp_entf, numOfPanels); } modul_panel_edit.add(feld); modul_panel_edit.add(Box.createRigidArea(new Dimension(0, 5))); } // Button zum annehmen eines Modules JButton btnOk = new JButton("Annehmen"); btnOk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // ArrayList<Zuordnung> zlist = new ArrayList<Zuordnung>(); String jg = ((JTextArea) ((JPanel) modul_panel_edit.getComponent(2)).getComponent(1)).getText(); int jahrgang; try { jahrgang = Integer.parseInt(jg); } catch (NumberFormatException nfe) { jahrgang = 0; } // for (int i = 0; i < lm_Z.getSize(); i++) { // zlist.add(lm_Z.getElementAt(i)); // } // Pr�fe ob min. eine Zuordnung ausgew�hlt ist und ein korrekter // Jahrgang ausgew�hlt wurde // if (!zlist.isEmpty()) { // // if (jahrgang != 0) { // // String Name = ((JTextArea) ((JPanel) // modul_panel_edit.getComponent(4)).getComponent(1)).getText(); // // if (Name.isEmpty()) { // JOptionPane.showMessageDialog(frame, // "Bitte f�llen Sie alle Felder aus!", "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } else { // // boolean filled = true; // ArrayList<Feld> felder = new ArrayList<Feld>(); // // Eintraege der Reihe nach auslesen // for (int i = 6; i < modul_panel_edit.getComponentCount(); i = // i + 2) { // JPanel tmp = (JPanel) modul_panel_edit.getComponent(i); // JLabel tmplbl = (JLabel) tmp.getComponent(0); // JTextArea tmptxt = (JTextArea) tmp.getComponent(1); // // boolean dezernat2 = ((JCheckBox) // tmp.getComponent(2)).isSelected(); // String value = tmptxt.getText(); // String label = tmplbl.getText(); // // Pr�fe, ob Feld ausgef�llt ist // if (value.isEmpty()) { // filled = false; // break; // } // felder.add(new Feld(label, value, dezernat2)); // } // if (filled == true) { // // Wenn alle ausgef�llt sind, Modul erzeugen und // // bei Best�tigung einreichen // int version = serverConnection.getModulVersion(Name) + 1; // // Date d = new Date(); // // Modul neu = new Modul(Name, zlist, jahrgang, felder, version, // d, false, false, current.geteMail()); // // int n = JOptionPane.showConfirmDialog(frame, // "Sind Sie sicher, dass Sie dieses Modul einreichen wollen?", // "Best�tigung", JOptionPane.YES_NO_OPTION); // if (n == 0) { // m.setInbearbeitung(false); // serverConnection.setModul(neu); // labels.removeAll(labels); // modul_panel_edit.removeAll(); // modul_panel_edit.revalidate(); // // // Listen neu einlesen // ArrayList<Modul> module = serverConnection.getModule(false); // lm.removeAllElements(); // for (int i = 0; i < module.size(); i++) { // lm.addElement(module.get(i)); // } // // module = serverConnection.getModule(true); // lm_ack.removeAllElements(); // for (int i = 0; i < module.size(); i++) { // lm_ack.addElement(module.get(i)); // } // showCard("modulbearbeiten"); // } // } else { // // } // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte geben Sie einen g�ltigen Wert f�r den Jahrgang ein!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } // } else { // JOptionPane.showMessageDialog(frame, // "Bitte w�hlen Sie min. einen Zuordnung aus!", // "Eingabe Fehler", // JOptionPane.ERROR_MESSAGE); // } } }); pnl_bottom.add(btnOk); pnl_editmod.add(scrollPane); return pnl_editmod; } /** * Erstellt eine Card zur Auswahl des Studienganges */ @SuppressWarnings("serial") private void studiengangCard() { JPanel studiengangshow = new JPanel(); cards.add(studiengangshow, "studiengang show"); studiengangshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable studtable = new JTable(); JScrollPane studscp = new JScrollPane(studtable); studtable.setBorder(new LineBorder(new Color(0, 0, 0))); studtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); studiengangshow.add(studscp); studiengangshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Studieng�ngen studmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Studiengang" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; studtable.setModel(studmodel); studtransferstring = ""; // Wechseln zur Jahrgangsauswahl, wenn ein Studiengang ausgew�hlt wurde goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (studtable.getSelectedRow() != -1) { int openrow = studtable.getSelectedRow(); studtransferstring = (String) studtable.getValueAt(openrow, 0); modhandshowCard(); showCard("modbuch show"); } } }); // Zur�ck zur Startseite back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("welcome page"); } }); } /** * Erstellt eine Card zur Auswahl des Jahrgangs */ @SuppressWarnings("serial") private void modhandshowCard() { JPanel modbuchshow = new JPanel(); cards.add(modbuchshow, "modbuch show"); modbuchshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable modbuchtable = new JTable(); JScrollPane modtypscp = new JScrollPane(modbuchtable); modbuchtable.setBorder(new LineBorder(new Color(0, 0, 0))); modbuchtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); modbuchshow.add(modtypscp); modbuchshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Jahrg�ngen modbuchmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Modulhandbuch Jahrgang" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; int zws = 0; // Tabelle f�llen modbuchtable.setModel(modbuchmodel); modbuchmodel.setRowCount(0); System.out.println(studienlist.get(0).getName()); System.out.println(studtransferstring); //System.out.println(studienlist.get(0).getModbuch().get(0).getId()); //modulhandlist = serverConnection.getModulhandbuch(studtransferstring); for(int i = 0; i < studienlist.size(); i++){ if(studienlist.get(i).getName().equalsIgnoreCase(studtransferstring)){ zws = i; break; } } for (int i = 0; i < studienlist.get(0).getModbuch().size(); i++) { addToTable(studienlist.get(0).getModbuch().get(i)); } modbuchtransferstring = ""; // Wechseln zur Auswahl von Zuordnungen goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (modbuchtable.getSelectedRow() != -1) { int openrow = modbuchtable.getSelectedRow(); modbuchtransferstring = (String) modbuchtable.getValueAt(openrow, 0); modtypshowCard(); showCard("modtyp show"); } } }); back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("studiengang show"); } }); } /** * Erstellt eine Card zur Auswahl des Modultypes */ @SuppressWarnings("serial") private void modtypshowCard() { JPanel modtypshow = new JPanel(); cards.add(modtypshow, "modtyp show"); modtypshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable modtyptable = new JTable(); JScrollPane modtypscp = new JScrollPane(modtyptable); modtyptable.setBorder(new LineBorder(new Color(0, 0, 0))); modtyptable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); modtypshow.add(modtypscp); modtypshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Zuordnungen modtypmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Modul Typ" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // all cells false return false; } }; // Tabelle f�llen modtyptable.setModel(modtypmodel); modtypmodel.setRowCount(0); int test = 0; for (int i = 0; i < studienlist.size(); i++) { if (studienlist.get(i).getName().equalsIgnoreCase(studtransferstring)) { test = studienlist.get(i).getId(); break; } } // for (int i = 0; i < typen.size(); i++) { // if (test == (typen.get(i).getSid())) // addToTable(typen.get(i).getName()); // } modtyptransferstring = ""; // Wechseln zur Anzeige mit Modulen goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (modtyptable.getSelectedRow() != -1) { int openrow = modtyptable.getSelectedRow(); modtyptransferstring = (String) modtyptable.getValueAt(openrow, 0); modshowCard(); showCard("mod show"); } } }); // Zur�ck zur vorherigen Ansicht back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("modbuch show"); } }); } /** * Erstellt eine Card zur Auswahl eines Modules */ @SuppressWarnings("serial") private void modshowCard() { JPanel modshow = new JPanel(); cards.add(modshow, "mod show"); modshow.setLayout(new BorderLayout(0, 0)); JPanel btnpan = new JPanel(); JButton goforit = new JButton("\u00d6ffnen"); JButton back = new JButton("Zur\u00FCck"); btnpan.add(back); btnpan.add(goforit); final JTable modshowtable = new JTable(); JScrollPane modtypscp = new JScrollPane(modshowtable); modshowtable.setBorder(new LineBorder(new Color(0, 0, 0))); modshowtable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); modshow.add(modtypscp); modshow.add(btnpan, BorderLayout.SOUTH); // Tabelle mit Modulen modshowmodel = new DefaultTableModel(new Object[][] {}, new String[] { "Module" }) { @SuppressWarnings("rawtypes") Class[] columnTypes = new Class[] { String.class }; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Class getColumnClass(int columnIndex) { return columnTypes[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { return false; } }; // Tabelle f�llen modshowtable.setModel(modshowmodel); modshowmodel.setRowCount(0); selectedmodullist = serverConnection.getselectedModul(studtransferstring, modtyptransferstring, modbuchtransferstring); for (int i = 0; i < selectedmodullist.size(); i++) { addToTable(selectedmodullist.get(i)); } modulselectionstring = ""; // Wechsel zur Anzeige des Modules goforit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (modshowtable.getSelectedRow() != -1) { int openrow = modshowtable.getSelectedRow(); modulselectionstring = (String) modshowtable.getValueAt(openrow, 0); modCard(); showCard("selmodshow"); } } }); // Zur�ck zur vorherigen Ansicht back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("modtyp show"); } }); } /** * Erstellt eine Card zur Anzeige eines Modules */ private void modCard() { JPanel modshow = new JPanel(); cards.add(modshow, "selmodshow"); modshow.setLayout(new BorderLayout(0, 0)); JPanel modpanel = new JPanel(); JButton pdfbtn = new JButton("Als PDF ausgeben"); JButton back = new JButton("Zur\u00FCck"); JPanel btnpan = new JPanel(); btnpan.add(back); btnpan.add(pdfbtn); modshow.add(btnpan, BorderLayout.SOUTH); JScrollPane modscp = new JScrollPane(modpanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); modshow.add(modscp, BorderLayout.CENTER); Modul zws = null; modpanel.setLayout(new BoxLayout(modpanel, BoxLayout.Y_AXIS)); for (int i = 0; i < selectedmodullist.size(); i++) { if (selectedmodullist.get(i).getName().equalsIgnoreCase(modulselectionstring)) { zws = selectedmodullist.get(i); } } // Felder erstellen modpanel.add(modulPanel("Name", zws.getName())); modpanel.add(modulPanel("Jahrgang", modbuchtransferstring)); // for (int i = 0; i < zws.getZuordnungen().size(); i++) { // modpanel.add(modulPanel("Zuordnung", // zws.getZuordnungen().get(i).toString())); // } for (int i = 0; i < zws.getFelder().size(); i++) { modpanel.add(modulPanel(zws.getFelder().get(i).getLabel(), zws.getFelder().get(i).getValue())); } // Pdf f�r das Modul erstellen pdfbtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub try { serverConnection.toPdf(modulselectionstring); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); // Zur�ck zur vorherigen Ansicht back.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showCard("mod show"); } }); } /** * Wird aufgerufen, wenn keine Verbindung zum Server besteht Dabei wird der * Benutzer auf den Standart User zur�ckgesetzt */ public static void noConnection() { JOptionPane.showMessageDialog(frame, "Keine Verbindung zum Server!", "Verbindungsfehler", JOptionPane.ERROR_MESSAGE); current = new User("gast", "gast", "", "[email protected]", "d4061b1486fe2da19dd578e8d970f7eb", false, false, false, false, false, true); btnModulEinreichen.setEnabled(false); btnVerwaltung.setEnabled(false); btnModulBearbeiten.setEnabled(false); btnModulArchiv.setEnabled(true); btnUserVerwaltung.setEnabled(false); btnLogin.setText("Einloggen"); showCard("welcome page"); } }
diff --git a/core/src/main/java/org/apache/abdera/util/AbstractParser.java b/core/src/main/java/org/apache/abdera/util/AbstractParser.java index 8aa01bfd..7d04b5aa 100644 --- a/core/src/main/java/org/apache/abdera/util/AbstractParser.java +++ b/core/src/main/java/org/apache/abdera/util/AbstractParser.java @@ -1,96 +1,96 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.util; import java.io.InputStream; import java.io.Reader; import java.net.URI; import java.net.URISyntaxException; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.parser.ParseException; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.ParserOptions; public abstract class AbstractParser implements Parser { public <T extends Element>Document<T> parse( InputStream in) throws ParseException { return parse(in, (URI)null, getDefaultParserOptions()); } public <T extends Element>Document<T> parse( InputStream in, URI base) throws ParseException { return parse(in, base, getDefaultParserOptions()); } public <T extends Element>Document<T> parse( InputStream in, String base) throws ParseException, URISyntaxException { return parse(in, new URI(base), getDefaultParserOptions()); } public <T extends Element>Document<T> parse( InputStream in, String base, ParserOptions options) throws ParseException, URISyntaxException { - return parse(in, new URI(base), options); + return parse(in, (base != null) ? new URI(base) : null, options); } public <T extends Element>Document<T> parse( Reader in) throws ParseException { return parse(in, (URI)null, getDefaultParserOptions()); } public <T extends Element>Document<T> parse( Reader in, URI base) throws ParseException { return parse(in, base, getDefaultParserOptions()); } public <T extends Element>Document<T> parse( Reader in, String base) throws ParseException, URISyntaxException { return parse(in, new URI(base), getDefaultParserOptions()); } public <T extends Element>Document<T> parse( Reader in, String base, ParserOptions options) throws ParseException, URISyntaxException { return parse(in, new URI(base), options); } public abstract ParserOptions getDefaultParserOptions(); }
true
true
public <T extends Element>Document<T> parse( InputStream in, String base, ParserOptions options) throws ParseException, URISyntaxException { return parse(in, new URI(base), options); }
public <T extends Element>Document<T> parse( InputStream in, String base, ParserOptions options) throws ParseException, URISyntaxException { return parse(in, (base != null) ? new URI(base) : null, options); }
diff --git a/src/classviewer/changes/DescChange.java b/src/classviewer/changes/DescChange.java index a37bd52..3a60c28 100644 --- a/src/classviewer/changes/DescChange.java +++ b/src/classviewer/changes/DescChange.java @@ -1,120 +1,121 @@ package classviewer.changes; import java.util.HashMap; import classviewer.model.CourseModel; import classviewer.model.DescRec; /** * Add/delete/modify university or category. * * @author TK */ public class DescChange extends Change { public static final int UNIVERSITY = 1; public static final int CATEGORY = 2; /** * Is this University or Category? Don't want to subclass for just 2 options */ private int what; /** Field that changed, NULL of ADD/DELETE */ private String field = null; /** Affected description, if exists */ private DescRec desc = null; /** Affecting chunk of JSON, unless DELETE */ private HashMap<String, Object> json = null; public DescChange(int what, String type, String field, DescRec desc, HashMap<String, Object> json) { super(type); this.what = what; this.field = field; this.desc = desc; this.json = json; if (type == ADD) order = 1; else if (type == DELETE) order = 7; else order = 4; } public String getDescription() { return field; } public Object getTarget() { if (desc != null) return desc.getId(); return json.get("short_name"); } public Object getNewValue() { if (type == ADD) return json.get("name"); if (type == DELETE) return desc.getName(); if ("Name".equals(field)) return json.get("name"); return json.get("description"); } public Object getOldValue() { if (type == ADD || type == DELETE) return null; if ("Name".equals(field)) return desc.getName(); return desc.getDescription(); } @Override public void apply(CourseModel model) { if (type == ADD) { DescRec dr = makeDesc(); switch (what) { case UNIVERSITY: model.addUniversity(dr); return; case CATEGORY: model.addCategory(dr); return; default: throw new UnsupportedOperationException("Unknown object type " + what); } } else if (type == DELETE) { - String id = (String) json.get("short_name"); + // This is deletion, so we have a record but no JSON + String id = desc.getId(); switch (what) { case UNIVERSITY: model.removeUniversity(id); return; case CATEGORY: model.removeCategory(id); return; default: throw new UnsupportedOperationException("Unknown object type " + what); } } else { // Assume we have a pointer to the record we can change in place. // Assume short-name is the same, since it acts as an id. assert (json != null); assert (desc != null); if ("Name".equals(field)) { desc.setName((String) json.get("name")); } else if ("Description".equals(field)) { desc.setDescription((String) json.get("description")); } else { throw new UnsupportedOperationException("Unknown field " + field); } } } private DescRec makeDesc() { String id = (String) json.get("short_name"); String name = (String) json.get("name"); String dsc = (String) json.get("description"); return new DescRec(id, name, dsc); } }
true
true
public void apply(CourseModel model) { if (type == ADD) { DescRec dr = makeDesc(); switch (what) { case UNIVERSITY: model.addUniversity(dr); return; case CATEGORY: model.addCategory(dr); return; default: throw new UnsupportedOperationException("Unknown object type " + what); } } else if (type == DELETE) { String id = (String) json.get("short_name"); switch (what) { case UNIVERSITY: model.removeUniversity(id); return; case CATEGORY: model.removeCategory(id); return; default: throw new UnsupportedOperationException("Unknown object type " + what); } } else { // Assume we have a pointer to the record we can change in place. // Assume short-name is the same, since it acts as an id. assert (json != null); assert (desc != null); if ("Name".equals(field)) { desc.setName((String) json.get("name")); } else if ("Description".equals(field)) { desc.setDescription((String) json.get("description")); } else { throw new UnsupportedOperationException("Unknown field " + field); } } }
public void apply(CourseModel model) { if (type == ADD) { DescRec dr = makeDesc(); switch (what) { case UNIVERSITY: model.addUniversity(dr); return; case CATEGORY: model.addCategory(dr); return; default: throw new UnsupportedOperationException("Unknown object type " + what); } } else if (type == DELETE) { // This is deletion, so we have a record but no JSON String id = desc.getId(); switch (what) { case UNIVERSITY: model.removeUniversity(id); return; case CATEGORY: model.removeCategory(id); return; default: throw new UnsupportedOperationException("Unknown object type " + what); } } else { // Assume we have a pointer to the record we can change in place. // Assume short-name is the same, since it acts as an id. assert (json != null); assert (desc != null); if ("Name".equals(field)) { desc.setName((String) json.get("name")); } else if ("Description".equals(field)) { desc.setDescription((String) json.get("description")); } else { throw new UnsupportedOperationException("Unknown field " + field); } } }
diff --git a/src/main/java/net/md_5/specialsource/URLClassLoaderInheritanceProvider.java b/src/main/java/net/md_5/specialsource/URLClassLoaderInheritanceProvider.java index c404647..933b487 100644 --- a/src/main/java/net/md_5/specialsource/URLClassLoaderInheritanceProvider.java +++ b/src/main/java/net/md_5/specialsource/URLClassLoaderInheritanceProvider.java @@ -1,56 +1,56 @@ package net.md_5.specialsource; import org.objectweb.asm.ClassReader; import org.objectweb.asm.tree.ClassNode; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.List; /** * Lookup inheritance from a class in a given URLClassLoader. */ public class URLClassLoaderInheritanceProvider implements IInheritanceProvider { private final URLClassLoader classLoader; public URLClassLoaderInheritanceProvider(URLClassLoader classLoader) { this.classLoader = classLoader; } @Override @SuppressWarnings("unchecked") public List<String> getParents(String owner) { try { - String ownerInternalName = owner.replace('.', '/'); // TODO: abstract out + String ownerInternalName = owner.replace('.', '/').concat(".class"); URL url = classLoader.findResource(ownerInternalName); if (url == null) { return null; } InputStream inputStream = url.openStream(); if (inputStream == null) { return null; } // TODO: refactor ClassReader cr = new ClassReader(inputStream); ClassNode node = new ClassNode(); cr.accept(node, 0); List<String> parents = new ArrayList<String>(); for (String iface : (List<String>) node.interfaces) { parents.add(iface); } parents.add(node.superName); return parents; } catch (IOException ex) { return null; } } }
true
true
public List<String> getParents(String owner) { try { String ownerInternalName = owner.replace('.', '/'); // TODO: abstract out URL url = classLoader.findResource(ownerInternalName); if (url == null) { return null; } InputStream inputStream = url.openStream(); if (inputStream == null) { return null; } // TODO: refactor ClassReader cr = new ClassReader(inputStream); ClassNode node = new ClassNode(); cr.accept(node, 0); List<String> parents = new ArrayList<String>(); for (String iface : (List<String>) node.interfaces) { parents.add(iface); } parents.add(node.superName); return parents; } catch (IOException ex) { return null; } }
public List<String> getParents(String owner) { try { String ownerInternalName = owner.replace('.', '/').concat(".class"); URL url = classLoader.findResource(ownerInternalName); if (url == null) { return null; } InputStream inputStream = url.openStream(); if (inputStream == null) { return null; } // TODO: refactor ClassReader cr = new ClassReader(inputStream); ClassNode node = new ClassNode(); cr.accept(node, 0); List<String> parents = new ArrayList<String>(); for (String iface : (List<String>) node.interfaces) { parents.add(iface); } parents.add(node.superName); return parents; } catch (IOException ex) { return null; } }
diff --git a/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/ui/EditorConfigurationGenerator.java b/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/ui/EditorConfigurationGenerator.java index 148f8ae40..cc37e326c 100644 --- a/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/ui/EditorConfigurationGenerator.java +++ b/org.emftext.sdk.codegen/src/org/emftext/sdk/codegen/generators/ui/EditorConfigurationGenerator.java @@ -1,164 +1,164 @@ package org.emftext.sdk.codegen.generators.ui; import static org.emftext.sdk.codegen.generators.IClassNameConstants.*; import org.emftext.sdk.codegen.generators.BaseGenerator; import org.emftext.sdk.codegen.GenerationContext; import org.emftext.sdk.codegen.IGenerator; import java.io.PrintWriter; import org.emftext.sdk.codegen.EArtifact; public class EditorConfigurationGenerator extends BaseGenerator { private String editorClassName; private String colorManagerClassName; private String completionProcessorClassName; private String textTokenScannerClassName; private String textHoverClassName; private String hyperlinkDetectorClassName; public EditorConfigurationGenerator() { super(); } private EditorConfigurationGenerator(GenerationContext context) { super(context, EArtifact.EDITOR_CONFIGURATION); editorClassName = getContext().getQualifiedClassName(EArtifact.EDITOR); colorManagerClassName = getContext().getQualifiedClassName(EArtifact.COLOR_MANAGER); completionProcessorClassName = getContext().getQualifiedClassName(EArtifact.COMPLETION_PROCESSOR); textTokenScannerClassName = getContext().getQualifiedClassName(EArtifact.TOKEN_SCANNER); textHoverClassName = getContext().getQualifiedClassName(EArtifact.TEXT_HOVER); hyperlinkDetectorClassName = getContext().getQualifiedClassName(EArtifact.HYPERLINK_DETECTOR); } public boolean generate(PrintWriter out) { org.emftext.sdk.codegen.composites.StringComposite sc = new org.emftext.sdk.codegen.composites.JavaComposite(); sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); - sc.add("// This class provides the configuration for all EMFText editors. It registers"); + sc.add("// This class provides the configuration for the generated editor. It registers"); sc.add("// content assistance and syntax highlighting."); sc.add("public class " + getResourceClassName() + " extends " + SOURCE_VIEWER_CONFIGURATION + " {"); sc.addLineBreak(); addFields(sc); addConstructor(sc); addMethods(sc); sc.add("}"); out.print(sc.toString()); return true; } private void addMethods( org.emftext.sdk.codegen.composites.StringComposite sc) { addGetContentAssistantMethod(sc); addGetConfiguredContentTypesMethod(sc); addGetScannerMethod(sc); addGetPresentationReconcilerMethod(sc); addGetAnnotationHoverMethod(sc); addGetTextHoverMethod(sc); addGetHyperlinkDetectorsMethod(sc); } private void addGetHyperlinkDetectorsMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("public " + I_HYPERLINK_DETECTOR + "[] getHyperlinkDetectors(" + I_SOURCE_VIEWER + " sourceViewer) {"); sc.add("if (sourceViewer == null) {"); sc.add("return null;"); sc.add("}"); sc.add("return new " + I_HYPERLINK_DETECTOR + "[] { new " + hyperlinkDetectorClassName + "(theEditor.getResource()) };"); sc.add("}"); sc.addLineBreak(); } private void addGetTextHoverMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("public " + I_TEXT_HOVER + " getTextHover(" + I_SOURCE_VIEWER + " sourceViewer, String contentType) {"); sc.add("return new " + textHoverClassName + "(theEditor);"); sc.add("}"); sc.addLineBreak(); } private void addGetAnnotationHoverMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("public " + I_ANNOTATION_HOVER + " getAnnotationHover(" + I_SOURCE_VIEWER + " sourceViewer) {"); sc.add("return new " + DEFAULT_ANNOTATION_HOVER + "();"); sc.add("}"); sc.addLineBreak(); } private void addGetPresentationReconcilerMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("public " + I_PRESENTATION_RECONCILER + " getPresentationReconciler(" + I_SOURCE_VIEWER + " sourceViewer) {"); sc.addLineBreak(); sc.add(PRESENTATION_RECONCILER + " reconciler = new " + PRESENTATION_RECONCILER + "();"); sc.add("String fileName = theEditor.getEditorInput().getName();"); sc.addLineBreak(); sc.add(DEFAULT_DAMAGER_REPAIRER + " repairer = new " + DEFAULT_DAMAGER_REPAIRER + "(getScanner(fileName));"); sc.add("reconciler.setDamager(repairer, " + I_DOCUMENT + ".DEFAULT_CONTENT_TYPE);"); sc.add("reconciler.setRepairer(repairer, " + I_DOCUMENT + ".DEFAULT_CONTENT_TYPE);"); sc.addLineBreak(); sc.add("return reconciler;"); sc.add("}"); sc.addLineBreak(); } private void addGetScannerMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("// @param fileExtension"); sc.add("// @return"); sc.add("protected " + I_TOKEN_SCANNER + " getScanner(String fileName) {"); sc.add("return new " + textTokenScannerClassName + "(colorManager);"); sc.add("}"); sc.addLineBreak(); } private void addGetConfiguredContentTypesMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("public String[] getConfiguredContentTypes(" + I_SOURCE_VIEWER + " sourceViewer) {"); sc.add("return new String[] {"); sc.add(I_DOCUMENT + ".DEFAULT_CONTENT_TYPE,"); sc.add("};"); sc.add("}"); sc.addLineBreak(); } private void addGetContentAssistantMethod( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("public " + I_CONTENT_ASSISTANT + " getContentAssistant(" + I_SOURCE_VIEWER + " sourceViewer) {"); sc.addLineBreak(); sc.add(CONTENT_ASSISTANT + " assistant = new " + CONTENT_ASSISTANT + "();"); sc.add("assistant.setContentAssistProcessor(new " + completionProcessorClassName + "(theEditor), " + I_DOCUMENT + ".DEFAULT_CONTENT_TYPE);"); sc.add("assistant.enableAutoActivation(true);"); sc.add("assistant.setAutoActivationDelay(500);"); sc.add("assistant.setProposalPopupOrientation(" + I_CONTENT_ASSISTANT + ".PROPOSAL_OVERLAY);"); sc.add("assistant.setContextInformationPopupOrientation(" + I_CONTENT_ASSISTANT + ".CONTEXT_INFO_ABOVE);"); sc.addLineBreak(); sc.add("return assistant;"); sc.add("}"); sc.addLineBreak(); } private void addConstructor( org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("// Create a new editor configuration."); sc.add("//"); sc.add("// @param editor"); sc.add("// @param colorManager"); sc.add("///"); sc.add("public " + getResourceClassName() + "(" + editorClassName + " editor, " + colorManagerClassName + " colorManager) {"); sc.add("this.theEditor = editor;"); sc.add("this.colorManager = colorManager;"); sc.add("}"); sc.addLineBreak(); } private void addFields(org.emftext.sdk.codegen.composites.StringComposite sc) { sc.add("private " + colorManagerClassName + " colorManager;"); sc.add("private " + editorClassName + " theEditor;"); sc.addLineBreak(); } public IGenerator newInstance(GenerationContext context) { return new EditorConfigurationGenerator(context); } }
true
true
public boolean generate(PrintWriter out) { org.emftext.sdk.codegen.composites.StringComposite sc = new org.emftext.sdk.codegen.composites.JavaComposite(); sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); sc.add("// This class provides the configuration for all EMFText editors. It registers"); sc.add("// content assistance and syntax highlighting."); sc.add("public class " + getResourceClassName() + " extends " + SOURCE_VIEWER_CONFIGURATION + " {"); sc.addLineBreak(); addFields(sc); addConstructor(sc); addMethods(sc); sc.add("}"); out.print(sc.toString()); return true; }
public boolean generate(PrintWriter out) { org.emftext.sdk.codegen.composites.StringComposite sc = new org.emftext.sdk.codegen.composites.JavaComposite(); sc.add("package " + getResourcePackageName() + ";"); sc.addLineBreak(); sc.add("// This class provides the configuration for the generated editor. It registers"); sc.add("// content assistance and syntax highlighting."); sc.add("public class " + getResourceClassName() + " extends " + SOURCE_VIEWER_CONFIGURATION + " {"); sc.addLineBreak(); addFields(sc); addConstructor(sc); addMethods(sc); sc.add("}"); out.print(sc.toString()); return true; }
diff --git a/core/src/main/java/org/ow2/chameleon/rose/util/RoseTools.java b/core/src/main/java/org/ow2/chameleon/rose/util/RoseTools.java index 374fa30..bbdd2bf 100644 --- a/core/src/main/java/org/ow2/chameleon/rose/util/RoseTools.java +++ b/core/src/main/java/org/ow2/chameleon/rose/util/RoseTools.java @@ -1,317 +1,315 @@ package org.ow2.chameleon.rose.util; import static java.util.Collections.emptyList; import static org.osgi.framework.Constants.SERVICE_ID; import static org.osgi.framework.Constants.SERVICE_PID; import static org.osgi.service.remoteserviceadmin.RemoteConstants.ENDPOINT_ID; import static org.osgi.service.remoteserviceadmin.RemoteConstants.SERVICE_IMPORTED_CONFIGS; import static org.ow2.chameleon.rose.ExporterService.ENDPOINT_CONFIG_PREFIX; import static org.ow2.chameleon.rose.RoseMachine.ENDPOINT_LISTENER_INTEREST; import static org.ow2.chameleon.rose.RoseMachine.EndpointListerInterrest.ALL; import java.util.ArrayList; import java.util.Dictionary; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.packageadmin.ExportedPackage; import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.remoteserviceadmin.EndpointDescription; import org.osgi.service.remoteserviceadmin.EndpointListener; import org.osgi.service.remoteserviceadmin.RemoteConstants; import org.ow2.chameleon.rose.ExporterService; import org.ow2.chameleon.rose.ImporterService; import org.ow2.chameleon.rose.RoseMachine; import org.ow2.chameleon.rose.RoseMachine.EndpointListerInterrest; /** * This class contains some useful static methods. * * @author barjo */ public final class RoseTools { /** * Get the endpoint id from the {@link ServiceReference}. If the name * property if not set, use the {@link RemoteConstants#ENDPOINT_ID} property * or the {@link Constants#SERVICE_PID} or the {@link Constants#SERVICE_ID} * + <code>service</code> as a prefix. * * @param sref * @param configs * @return {@link String} the endpoint id. */ public static String computeEndpointId(final ServiceReference sref, final List<String> configs) { Object name = sref.getProperty(ENDPOINT_ID); // get the endpoint name from the given name properties int i = 0; while (name == null & configs != null && i < configs.size()) { name = sref.getProperty(configs.get(i++) + ENDPOINT_ID); } // try with instance.name if (name == null) { name = sref.getProperty("instance.name"); } // try with service.pid if (name == null) { name = sref.getProperty(SERVICE_PID); } // try with service.id if (name == null) { name = "service" + String.valueOf(sref.getProperty(SERVICE_ID)); } return String.valueOf(name); } /** * Compute some {@link EndpointDescription} extra properties from * <code>sref</code>, <code>extraProps</code> and <code>configPrefix</code>. * * @param sref * @param extraProps * @param configPrefix * Configuration prefix (e.g. <code>jsonrpc,org.jabsorb</code> * @return {@link Map} containing the extra properties. */ public static Map<String, Object> computeEndpointExtraProperties( ServiceReference sref, Map<String, Object> extraProps, List<String> configPrefix) { Map<String, Object> properties = new HashMap<String, Object>(); if (extraProps != null) { // Add given properties properties.putAll(extraProps); } // Set the SERVICE_IMPORTED_CONFIGS property properties.put(SERVICE_IMPORTED_CONFIGS, configPrefix); // Set the ENDPOINT_ID property properties.put(ENDPOINT_ID, computeEndpointId(sref, configPrefix)); return properties; } /** * Return a {@link Dictionary} representation of the * {@link EndpointDescription}. * * @param enddesc * @return a {@link Dictionary} representation of the * {@link EndpointDescription}. */ public static Dictionary<String, Object> endDescToDico( EndpointDescription enddesc) { return new Hashtable<String, Object>(enddesc.getProperties()); } /** * @param reference * The {@link ServiceReference} of an {@link EndpointListener}. * @return {@link EndpointListerInterrest} of the given * {@link ServiceReference} or <code>ALL</code> if it has not been * set. * @throws IllegalArgumentException * if the property * {@link RoseMachine#ENDPOINT_LISTENER_INTEREST} is not a valid * String or and {@link EndpointListerInterrest}. */ public static EndpointListerInterrest getEndpointListenerInterrest( ServiceReference reference) { Object ointerrest = reference.getProperty(ENDPOINT_LISTENER_INTEREST); EndpointListerInterrest interrest = null; // Parse the ENDPOINT_LISTENER_INTERRET property if (ointerrest instanceof EndpointListerInterrest) { interrest = (EndpointListerInterrest) ointerrest; } else if (ointerrest instanceof String) { interrest = EndpointListerInterrest.valueOf((String) ointerrest); } else if (ointerrest == null) { interrest = ALL; } else { throw new IllegalArgumentException( "The ENDPOINT_LISTENER_INTEREST property is neither an EndpointListerInterrest or a String object."); } return interrest; } /** * @param context * {@link BundleContext} * @return A Snapshot of All {@link ExporterService} available within this * Machine. */ public static List<ExporterService> getAllExporter(BundleContext context) { try { return getAllExporter(context, "(" + ENDPOINT_CONFIG_PREFIX + "=*)"); } catch (InvalidSyntaxException e) { assert false; // What would Dr. Gordon Freeman do ? } return emptyList(); } /** * @param context * {@link BundleContext} * @param filter * @return A Snapshot of All {@link ExporterService} available within this * Machine which match <code>filter</code>. * @throws InvalidSyntaxException * if <code>filter</code> is not valid. */ public static List<ExporterService> getAllExporter(BundleContext context, String filter) throws InvalidSyntaxException { List<ExporterService> exporters = new ArrayList<ExporterService>(); ServiceReference[] srefs = context.getAllServiceReferences( ExporterService.class.getName(), filter); for (ServiceReference sref : srefs) { exporters.add((ExporterService) context.getService(sref)); context.ungetService(sref); } return exporters; } /** * @param context * {@link BundleContext} * @return A Snapshot of All {@link ImporterService} available within this * Machine. */ public static List<ImporterService> getAllImporter(BundleContext context) { try { return getAllImporter(context, "(" + ImporterService.ENDPOINT_CONFIG_PREFIX + "=*)"); } catch (InvalidSyntaxException e) { assert false; // What would Dr. Gordon Freeman do ? } return emptyList(); } /** * @param context * {@link BundleContext} * @param filter * @return A Snapshot of All {@link ImporterService} available within this * Machine which match <code>filter</code>. * @throws InvalidSyntaxException * if <code>filter</code> is not valid. */ public static List<ImporterService> getAllImporter(BundleContext context, String filter) throws InvalidSyntaxException { List<ImporterService> importers = new ArrayList<ImporterService>(); ServiceReference[] srefs = context.getAllServiceReferences( ImporterService.class.getName(), filter); for (ServiceReference sref : srefs) { importers.add((ImporterService) context.getService(sref)); context.ungetService(sref); } return importers; } /** * Register <code>proxy</code> as a service providing the interface * specified within the <code>description</code> thanks to * <code>context</code>. All properties of <code>description</code> and * <code>properties</code> are provided as the service properties. * Properties within <code>description</code> override the one given by the * <code>properties</code> parameter. * * @throws IllegalArgumentException if there is any pb during the registration. * @param context {@link BundleContext} * @param proxy service instance. * @param description {@link EndpointDescription} of which <code>proxy</code> is a client. * @param properties optional properties, <code>null</code> is valid. * @return {@link ServiceRegistration} of <code>proxy</code> if success */ public static ServiceRegistration registerProxy(BundleContext context, Object proxy, EndpointDescription description, Map<String, Object> properties) { Hashtable<String, Object> props = new Hashtable<String, Object>(); if (properties != null){ props.putAll(properties); } props.putAll(description.getProperties()); return context.registerService((String[]) description.getInterfaces() .toArray(), proxy, props); } /** * Try to load the {@link EndpointDescription} interfaces from the * {@link PackageAdmin} of the gateway. * * FIXME throw exception rather than returning null * * @param context * The {@link BundleContext} from which we get the * {@link PackageAdmin} * @param description * The {@link EndpointDescription} * @return null if all specified interfaces cannot be load or the interface * {@link List}. */ public static List<Class<?>> loadClass(BundleContext context, EndpointDescription description) { ServiceReference sref = context.getServiceReference(PackageAdmin.class .getName()); List<String> interfaces = description.getInterfaces(); List<Class<?>> klass = new ArrayList<Class<?>>(interfaces.size()); if (sref == null) { // no package admin ! return null; } PackageAdmin padmin = (PackageAdmin) context.getService(sref); context.ungetService(sref); for (int i = 0; i < interfaces.size(); i++) { String itf = interfaces.get(i); - String pname = itf.substring(0, itf.lastIndexOf(".") - 1); // extract - // package - // name + String pname = itf.substring(0, itf.lastIndexOf(".")); // extract package name ExportedPackage pkg = padmin.getExportedPackage(pname); try { if (pkg.getVersion().compareTo( description.getPackageVersion(pname)) >= 0) { klass.add(pkg.getExportingBundle().loadClass(itf)); } } catch (ClassNotFoundException e) { continue;// XXX return null or continue } } if (klass.isEmpty() || klass.size() < interfaces.size()) { return null; } return klass; } }
true
true
public static List<Class<?>> loadClass(BundleContext context, EndpointDescription description) { ServiceReference sref = context.getServiceReference(PackageAdmin.class .getName()); List<String> interfaces = description.getInterfaces(); List<Class<?>> klass = new ArrayList<Class<?>>(interfaces.size()); if (sref == null) { // no package admin ! return null; } PackageAdmin padmin = (PackageAdmin) context.getService(sref); context.ungetService(sref); for (int i = 0; i < interfaces.size(); i++) { String itf = interfaces.get(i); String pname = itf.substring(0, itf.lastIndexOf(".") - 1); // extract // package // name ExportedPackage pkg = padmin.getExportedPackage(pname); try { if (pkg.getVersion().compareTo( description.getPackageVersion(pname)) >= 0) { klass.add(pkg.getExportingBundle().loadClass(itf)); } } catch (ClassNotFoundException e) { continue;// XXX return null or continue } } if (klass.isEmpty() || klass.size() < interfaces.size()) { return null; } return klass; }
public static List<Class<?>> loadClass(BundleContext context, EndpointDescription description) { ServiceReference sref = context.getServiceReference(PackageAdmin.class .getName()); List<String> interfaces = description.getInterfaces(); List<Class<?>> klass = new ArrayList<Class<?>>(interfaces.size()); if (sref == null) { // no package admin ! return null; } PackageAdmin padmin = (PackageAdmin) context.getService(sref); context.ungetService(sref); for (int i = 0; i < interfaces.size(); i++) { String itf = interfaces.get(i); String pname = itf.substring(0, itf.lastIndexOf(".")); // extract package name ExportedPackage pkg = padmin.getExportedPackage(pname); try { if (pkg.getVersion().compareTo( description.getPackageVersion(pname)) >= 0) { klass.add(pkg.getExportingBundle().loadClass(itf)); } } catch (ClassNotFoundException e) { continue;// XXX return null or continue } } if (klass.isEmpty() || klass.size() < interfaces.size()) { return null; } return klass; }
diff --git a/ant/org.eclipse.ant.core/src/org/eclipse/ant/core/Property.java b/ant/org.eclipse.ant.core/src/org/eclipse/ant/core/Property.java index d1378def5..702072cff 100644 --- a/ant/org.eclipse.ant.core/src/org/eclipse/ant/core/Property.java +++ b/ant/org.eclipse.ant.core/src/org/eclipse/ant/core/Property.java @@ -1,208 +1,207 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.ant.core; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.variables.VariablesPlugin; /** * Represents a Ant property. * @since 2.1 */ public class Property { private String name; private String value; private String className; private IAntPropertyValueProvider valueProvider; private String pluginLabel; private ClassLoader loader; private boolean eclipseRuntime= true; public Property(String name, String value) { this.name= name; this.value= value; } public Property() { } /** * Gets the name * @return Returns a String */ public String getName() { return name; } /** * Sets the name * @param name The name to set */ public void setName(String name) { this.name= name; } /* * @see Object#equals() */ public boolean equals(Object other) { if (other.getClass().equals(getClass())) { Property elem= (Property)other; return name.equals(elem.getName()); } return false; } /* * @see Object#hashCode() */ public int hashCode() { return name.hashCode(); } /** * Returns the value. * Equivalent to calling #getValue(true); * @return String */ public String getValue() { return getValue(true); } /** * Returns the value. * * @param substituteVariables whether the value has any variables resolved. * @return String * @since 3.0 */ public String getValue(boolean substituteVariables) { if (className != null) { Class cls = null; try { cls = loader.loadClass(className); } catch (ClassNotFoundException e) { AntCorePlugin.log(e); return null; } try { valueProvider = (IAntPropertyValueProvider)cls.newInstance(); } catch (InstantiationException e) { AntCorePlugin.log(e); return null; } catch (IllegalAccessException ex) { AntCorePlugin.log(ex); return null; } loader= null; className= null; } if (valueProvider != null) { return valueProvider.getAntPropertyValue(name); } if (substituteVariables) { try { String expanded = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(value); return expanded; } catch (CoreException e) { - AntCorePlugin.log(e); } } else { return value; } - return null; + return value; } /** * Sets the value. * @param value The value to set */ public void setValue(String value) { this.value = value; } /** * Returns whether this Ant property has been created because of an extension * point definition. * * @return boolean * @since 3.0 */ public boolean isDefault() { return pluginLabel != null; } /** * Sets the label of the plugin that contributed this Ant property via an extension * point. * * @param pluginLabel The label of the plugin * @since 3.0 */ public void setPluginLabel(String pluginLabel) { this.pluginLabel = pluginLabel; } /** * Returns the label of the plugin that contributed this Ant property via an extension * point. * * @return pluginLabel The label of the plugin * @since 3.0 */ public String getPluginLabel() { return this.pluginLabel; } /** * Sets the name of the class that is an <code>IAntPropertyValueProvider</code> to be used to dynamically provide a * value for this property. * Sets the class loader to load the <code>IAntPropertyValueProvider</code> to be used to dynamically provide a * value for this property. * * @param className The name of the value provider class to use to resolve the value of this property * @param loader The class loader to use to load the value provider class to use to resolve the value of this property * @since 3.0 */ public void setValueProvider(String className, ClassLoader loader) { this.className= className; this.loader= loader; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { StringBuffer buff= new StringBuffer("\""); //$NON-NLS-1$ buff.append(getName()); buff.append("\"= \""); //$NON-NLS-1$ buff.append(getValue(false)); buff.append("\""); //$NON-NLS-1$ return buff.toString(); } /** * Returns whether this property requires the Eclipse runtime to be * relevant. Defaults value is <code>true</code> * * @return whether this property requires the Eclipse runtime * @since 3.0 */ public boolean isEclipseRuntimeRequired() { return eclipseRuntime; } public void setEclipseRuntimeRequired(boolean eclipseRuntime) { this.eclipseRuntime= eclipseRuntime; } }
false
true
public String getValue(boolean substituteVariables) { if (className != null) { Class cls = null; try { cls = loader.loadClass(className); } catch (ClassNotFoundException e) { AntCorePlugin.log(e); return null; } try { valueProvider = (IAntPropertyValueProvider)cls.newInstance(); } catch (InstantiationException e) { AntCorePlugin.log(e); return null; } catch (IllegalAccessException ex) { AntCorePlugin.log(ex); return null; } loader= null; className= null; } if (valueProvider != null) { return valueProvider.getAntPropertyValue(name); } if (substituteVariables) { try { String expanded = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(value); return expanded; } catch (CoreException e) { AntCorePlugin.log(e); } } else { return value; } return null; }
public String getValue(boolean substituteVariables) { if (className != null) { Class cls = null; try { cls = loader.loadClass(className); } catch (ClassNotFoundException e) { AntCorePlugin.log(e); return null; } try { valueProvider = (IAntPropertyValueProvider)cls.newInstance(); } catch (InstantiationException e) { AntCorePlugin.log(e); return null; } catch (IllegalAccessException ex) { AntCorePlugin.log(ex); return null; } loader= null; className= null; } if (valueProvider != null) { return valueProvider.getAntPropertyValue(name); } if (substituteVariables) { try { String expanded = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(value); return expanded; } catch (CoreException e) { } } else { return value; } return value; }
diff --git a/src/java/org/xhtmlrenderer/pdf/ITextReplacedElementFactory.java b/src/java/org/xhtmlrenderer/pdf/ITextReplacedElementFactory.java index 6a01e947..4d2957f7 100644 --- a/src/java/org/xhtmlrenderer/pdf/ITextReplacedElementFactory.java +++ b/src/java/org/xhtmlrenderer/pdf/ITextReplacedElementFactory.java @@ -1,136 +1,135 @@ /* * {{{ header & license * Copyright (c) 2006 Wisconsin Court System * * This program 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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 org.xhtmlrenderer.pdf; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.w3c.dom.Element; import org.xhtmlrenderer.extend.FSImage; import org.xhtmlrenderer.extend.ReplacedElement; import org.xhtmlrenderer.extend.ReplacedElementFactory; import org.xhtmlrenderer.extend.UserAgentCallback; import org.xhtmlrenderer.layout.LayoutContext; import org.xhtmlrenderer.render.BlockBox; public class ITextReplacedElementFactory implements ReplacedElementFactory { private ITextOutputDevice _outputDevice; private Map _radioButtonsByElem = new HashMap(); private Map _radioButtonsByName = new HashMap(); public ITextReplacedElementFactory(ITextOutputDevice outputDevice) { _outputDevice = outputDevice; } public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) { Element e = box.getElement(); if (e == null) { return null; } String nodeName = e.getNodeName(); if (nodeName.equals("img")) { - FSImage fsImage = uac.getImageResource(e.getAttribute("src")) - .getImage(); + FSImage fsImage = uac.getImageResource(e.getAttribute("src")).getImage(); if (fsImage != null) { if (cssWidth != -1 || cssHeight != -1) { fsImage.scale(cssWidth, cssHeight); } return new ITextImageElement(fsImage); } } else if (nodeName.equals("input")) { String type = e.getAttribute("type"); if (type.equals("checkbox")) { return new CheckboxFormField(c, box, cssWidth, cssHeight); } else if (type.equals("radio")) { RadioButtonFormField result = new RadioButtonFormField( this, c, box, cssWidth, cssHeight); saveResult(e, result); return result; } else { return new TextFormField(c, box, cssWidth, cssHeight); } } else if (nodeName.equals("bookmark")) { // HACK Add box as named anchor and return placeholder BookmarkElement result = new BookmarkElement(); if (e.hasAttribute("name")) { String name = e.getAttribute("name"); c.addBoxId(name, box); result.setAnchorName(name); } return result; } return null; } private void saveResult(Element e, RadioButtonFormField result) { _radioButtonsByElem.put(e, result); String fieldName = result.getFieldName(_outputDevice, e); List fields = (List)_radioButtonsByName.get(fieldName); if (fields == null) { fields = new ArrayList(); _radioButtonsByName.put(fieldName, fields); } fields.add(result); } public void reset() { _radioButtonsByElem = new HashMap(); _radioButtonsByName = new HashMap(); } public void remove(Element e) { RadioButtonFormField field = (RadioButtonFormField)_radioButtonsByElem .remove(e); if (field != null) { String fieldName = field.getFieldName(_outputDevice, e); List values = (List)_radioButtonsByName.get(fieldName); if (values != null) { values.remove(field); if (values.size() == 0) { _radioButtonsByName.remove(fieldName); } } } } public void remove(String fieldName) { List values = (List)_radioButtonsByName.get(fieldName); if (values != null) { for (Iterator i = values.iterator(); i.hasNext();) { RadioButtonFormField field = (RadioButtonFormField)i.next(); _radioButtonsByElem.remove(field.getBox().getElement()); } } _radioButtonsByName.remove(fieldName); } public List getRadioButtons(String name) { return (List)_radioButtonsByName.get(name); } }
true
true
public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) { Element e = box.getElement(); if (e == null) { return null; } String nodeName = e.getNodeName(); if (nodeName.equals("img")) { FSImage fsImage = uac.getImageResource(e.getAttribute("src")) .getImage(); if (fsImage != null) { if (cssWidth != -1 || cssHeight != -1) { fsImage.scale(cssWidth, cssHeight); } return new ITextImageElement(fsImage); } } else if (nodeName.equals("input")) { String type = e.getAttribute("type"); if (type.equals("checkbox")) { return new CheckboxFormField(c, box, cssWidth, cssHeight); } else if (type.equals("radio")) { RadioButtonFormField result = new RadioButtonFormField( this, c, box, cssWidth, cssHeight); saveResult(e, result); return result; } else { return new TextFormField(c, box, cssWidth, cssHeight); } } else if (nodeName.equals("bookmark")) { // HACK Add box as named anchor and return placeholder BookmarkElement result = new BookmarkElement(); if (e.hasAttribute("name")) { String name = e.getAttribute("name"); c.addBoxId(name, box); result.setAnchorName(name); } return result; } return null; }
public ReplacedElement createReplacedElement(LayoutContext c, BlockBox box, UserAgentCallback uac, int cssWidth, int cssHeight) { Element e = box.getElement(); if (e == null) { return null; } String nodeName = e.getNodeName(); if (nodeName.equals("img")) { FSImage fsImage = uac.getImageResource(e.getAttribute("src")).getImage(); if (fsImage != null) { if (cssWidth != -1 || cssHeight != -1) { fsImage.scale(cssWidth, cssHeight); } return new ITextImageElement(fsImage); } } else if (nodeName.equals("input")) { String type = e.getAttribute("type"); if (type.equals("checkbox")) { return new CheckboxFormField(c, box, cssWidth, cssHeight); } else if (type.equals("radio")) { RadioButtonFormField result = new RadioButtonFormField( this, c, box, cssWidth, cssHeight); saveResult(e, result); return result; } else { return new TextFormField(c, box, cssWidth, cssHeight); } } else if (nodeName.equals("bookmark")) { // HACK Add box as named anchor and return placeholder BookmarkElement result = new BookmarkElement(); if (e.hasAttribute("name")) { String name = e.getAttribute("name"); c.addBoxId(name, box); result.setAnchorName(name); } return result; } return null; }
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/details/ProductDetailsPane.java b/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/details/ProductDetailsPane.java index 7f9a9add..750ed5e3 100644 --- a/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/details/ProductDetailsPane.java +++ b/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/details/ProductDetailsPane.java @@ -1,114 +1,115 @@ package devopsdistilled.operp.client.items.panes.details; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.inject.Inject; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JTextField; import net.miginfocom.swing.MigLayout; import devopsdistilled.operp.client.abstracts.AbstractEntityDetailsPane; import devopsdistilled.operp.client.items.controllers.ProductController; import devopsdistilled.operp.server.data.entity.items.Category; import devopsdistilled.operp.server.data.entity.items.Product; public class ProductDetailsPane extends AbstractEntityDetailsPane<Product> { @Inject private ProductController productController; private Product product; private final JPanel pane; private final JTextField productIdField; private final JTextField productNameField; private final JList<Category> productCategoryList; public ProductDetailsPane() { pane = new JPanel(); + getDialog().getContentPane().add(getPane()); pane.setLayout(new MigLayout("", "[][grow]", "[][][grow][]")); JLabel lblProductId = new JLabel("Product ID"); pane.add(lblProductId, "cell 0 0,alignx trailing"); productIdField = new JTextField(); productIdField.setEditable(false); pane.add(productIdField, "cell 1 0,growx"); productIdField.setColumns(10); JLabel lblProductName = new JLabel("Product Name"); pane.add(lblProductName, "cell 0 1,alignx trailing"); productNameField = new JTextField(); productNameField.setEditable(false); pane.add(productNameField, "cell 1 1,growx"); productNameField.setColumns(10); JLabel lblProductCategory = new JLabel("Product Category"); pane.add(lblProductCategory, "cell 0 2"); productCategoryList = new JList<>(); pane.add(productCategoryList, "cell 1 2,grow"); JButton btnDelete = new JButton("Delete"); btnDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); productController.delete(product); } }); pane.add(btnDelete, "flowx,cell 1 3"); JButton btnEdit = new JButton("Edit"); btnEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); productController.edit(product); } }); pane.add(btnEdit, "cell 1 3"); JButton btnOk = new JButton("OK"); btnOk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); } }); btnOk.setSelected(true); pane.add(btnOk, "cell 1 3"); } @Override public JComponent getPane() { return pane; } @Override public void show(Product product) { this.product = product; if (product != null) { productIdField.setText(product.getProductId().toString()); productNameField.setText(product.getProductName()); productCategoryList.setListData(new Vector<Category>(product .getCategories())); getDialog().setVisible(true); } } @Override public String getTitle() { return "Product Details"; } }
true
true
public ProductDetailsPane() { pane = new JPanel(); pane.setLayout(new MigLayout("", "[][grow]", "[][][grow][]")); JLabel lblProductId = new JLabel("Product ID"); pane.add(lblProductId, "cell 0 0,alignx trailing"); productIdField = new JTextField(); productIdField.setEditable(false); pane.add(productIdField, "cell 1 0,growx"); productIdField.setColumns(10); JLabel lblProductName = new JLabel("Product Name"); pane.add(lblProductName, "cell 0 1,alignx trailing"); productNameField = new JTextField(); productNameField.setEditable(false); pane.add(productNameField, "cell 1 1,growx"); productNameField.setColumns(10); JLabel lblProductCategory = new JLabel("Product Category"); pane.add(lblProductCategory, "cell 0 2"); productCategoryList = new JList<>(); pane.add(productCategoryList, "cell 1 2,grow"); JButton btnDelete = new JButton("Delete"); btnDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); productController.delete(product); } }); pane.add(btnDelete, "flowx,cell 1 3"); JButton btnEdit = new JButton("Edit"); btnEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); productController.edit(product); } }); pane.add(btnEdit, "cell 1 3"); JButton btnOk = new JButton("OK"); btnOk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); } }); btnOk.setSelected(true); pane.add(btnOk, "cell 1 3"); }
public ProductDetailsPane() { pane = new JPanel(); getDialog().getContentPane().add(getPane()); pane.setLayout(new MigLayout("", "[][grow]", "[][][grow][]")); JLabel lblProductId = new JLabel("Product ID"); pane.add(lblProductId, "cell 0 0,alignx trailing"); productIdField = new JTextField(); productIdField.setEditable(false); pane.add(productIdField, "cell 1 0,growx"); productIdField.setColumns(10); JLabel lblProductName = new JLabel("Product Name"); pane.add(lblProductName, "cell 0 1,alignx trailing"); productNameField = new JTextField(); productNameField.setEditable(false); pane.add(productNameField, "cell 1 1,growx"); productNameField.setColumns(10); JLabel lblProductCategory = new JLabel("Product Category"); pane.add(lblProductCategory, "cell 0 2"); productCategoryList = new JList<>(); pane.add(productCategoryList, "cell 1 2,grow"); JButton btnDelete = new JButton("Delete"); btnDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); productController.delete(product); } }); pane.add(btnDelete, "flowx,cell 1 3"); JButton btnEdit = new JButton("Edit"); btnEdit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); productController.edit(product); } }); pane.add(btnEdit, "cell 1 3"); JButton btnOk = new JButton("OK"); btnOk.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getDialog().dispose(); } }); btnOk.setSelected(true); pane.add(btnOk, "cell 1 3"); }
diff --git a/src/test/java/net/karneim/pojobuilder/AnnotationProcessorTest.java b/src/test/java/net/karneim/pojobuilder/AnnotationProcessorTest.java index 64fd782..69c75f2 100644 --- a/src/test/java/net/karneim/pojobuilder/AnnotationProcessorTest.java +++ b/src/test/java/net/karneim/pojobuilder/AnnotationProcessorTest.java @@ -1,110 +1,110 @@ package net.karneim.pojobuilder; import java.lang.reflect.Modifier; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import testenv.JavaProject; import testenv.Util; /** * The {@link AnnotationProcessorTest} is a simple acceptance test for running * the {@link AnnotationProcessor} on pojos. * */ public class AnnotationProcessorTest { JavaProject prj = new JavaProject(Util.createTempDir()); @Before public void setupJavaProject() { // Enable the AnnotationProcessor prj.getProcessorClasses().add(AnnotationProcessor.class); // Enable Logging AnnotationProcessor.enableLogging(); } @After public void tearDownJavaProject() { prj.delete(); } @Test public void testCompileShouldCompileEmptyPojo() throws Exception { // Given: there is a pojo source file prj.addSourceFile("src/test/data/testdata/EmptyPojo.java"); // When: the compilation is invoked boolean success = prj.compile(); // Then: the class file is generated Assert.assertEquals("success", true, success); Class<?> pojoClass = prj.findClass("testdata.EmptyPojo"); Assert.assertNotNull("pojoClass", pojoClass); } @Test public void testCompileShouldGeneratePojoBuilder1() throws Exception { // Given: there is an annotated pojo source file prj.addSourceFile("src/test/data/testdata/SimpleAnnotatedPojo.java"); // When: the compilation is invoked boolean success = prj.compile(); // Then: a new builder class is generated with a matching name Assert.assertEquals("success", true, success); Class<?> newClass = prj.findClass("testdata.SimpleAnnotatedPojoBuilder"); Assert.assertNotNull("newClass", newClass); } @Test public void testCompileShouldGeneratePojoBuilder2() throws Exception { // Given: there is an annotated pojo source file prj.addSourceFile("src/test/data/testdata/Contact.java"); // When: the compilation is invoked boolean success = prj.compile(); // Then: a new builder class is generated with a matching name Assert.assertEquals("success", true, success); Class<?> newClass = prj.findClass("testdata.ContactBuilder"); Assert.assertNotNull("newClass", newClass); } @Test public void testCompileShouldGeneratePojoBuilderIntoTargetPackage() throws Exception { // Given: there is an annotated pojo source file with "intoPackage" directive prj.addSourceFile("src/test/data/testdata/intoPackage/Contact.java"); // When: the compilation is invoked boolean success = prj.compile(); // Then: a new builder class is generated into target directory Assert.assertEquals("success", true, success); Class<?> newClass = prj.findClass("testdata.intoPackage.target.ContactBuilder"); Assert.assertNotNull("newClass", newClass); } @Test public void testCompileShouldGeneratePojoBuilderWithGenerationGap() throws Exception { // Given: there is an annotated pojo source file with "useGenerationGap" directive prj.addSourceFile("src/test/data/testdata/generationgap/Contact.java"); // When: the compilation is invoked boolean success = prj.compile(); // Then: two new classes are generated, one abstract and the other concrete Assert.assertEquals("success", true, success); Class<?> newClass = prj.findClass("testdata.generationgap.ContactBuilder"); Assert.assertNotNull("newClass", newClass); Class<?> newAbstractClass = prj.findClass("testdata.generationgap.AbstractContactBuilder"); Assert.assertNotNull("newAbstractClass", newAbstractClass); Assert.assertEquals( "abstract", true, Modifier.isAbstract(newAbstractClass.getModifiers())); Assert.assertEquals( "abstract", false, Modifier.isAbstract(newClass.getModifiers())); - Assert.assertEquals( "superclass", newAbstractClass, newClass.getSuperclass()); + Assert.assertEquals( "superclass", newAbstractClass.getCanonicalName(), newClass.getSuperclass().getCanonicalName()); } }
true
true
public void testCompileShouldGeneratePojoBuilderWithGenerationGap() throws Exception { // Given: there is an annotated pojo source file with "useGenerationGap" directive prj.addSourceFile("src/test/data/testdata/generationgap/Contact.java"); // When: the compilation is invoked boolean success = prj.compile(); // Then: two new classes are generated, one abstract and the other concrete Assert.assertEquals("success", true, success); Class<?> newClass = prj.findClass("testdata.generationgap.ContactBuilder"); Assert.assertNotNull("newClass", newClass); Class<?> newAbstractClass = prj.findClass("testdata.generationgap.AbstractContactBuilder"); Assert.assertNotNull("newAbstractClass", newAbstractClass); Assert.assertEquals( "abstract", true, Modifier.isAbstract(newAbstractClass.getModifiers())); Assert.assertEquals( "abstract", false, Modifier.isAbstract(newClass.getModifiers())); Assert.assertEquals( "superclass", newAbstractClass, newClass.getSuperclass()); }
public void testCompileShouldGeneratePojoBuilderWithGenerationGap() throws Exception { // Given: there is an annotated pojo source file with "useGenerationGap" directive prj.addSourceFile("src/test/data/testdata/generationgap/Contact.java"); // When: the compilation is invoked boolean success = prj.compile(); // Then: two new classes are generated, one abstract and the other concrete Assert.assertEquals("success", true, success); Class<?> newClass = prj.findClass("testdata.generationgap.ContactBuilder"); Assert.assertNotNull("newClass", newClass); Class<?> newAbstractClass = prj.findClass("testdata.generationgap.AbstractContactBuilder"); Assert.assertNotNull("newAbstractClass", newAbstractClass); Assert.assertEquals( "abstract", true, Modifier.isAbstract(newAbstractClass.getModifiers())); Assert.assertEquals( "abstract", false, Modifier.isAbstract(newClass.getModifiers())); Assert.assertEquals( "superclass", newAbstractClass.getCanonicalName(), newClass.getSuperclass().getCanonicalName()); }
diff --git a/src/plugins/WebOfTrust/util/RandomName.java b/src/plugins/WebOfTrust/util/RandomName.java index 96a677b8..a7eeb3cd 100644 --- a/src/plugins/WebOfTrust/util/RandomName.java +++ b/src/plugins/WebOfTrust/util/RandomName.java @@ -1,1141 +1,1141 @@ /* This code is part of WoT, a plugin for Freenet. It is distributed * under the GNU General Public License, version 2 (or at your option * any later version). See http://www.gnu.org/ for details of the GPL. * * The nameparts are compiled from names of (often long) deceased * scientists found in Wikipedia. Names themselves can not be * copyrighted and since the Wikipedia is based in the USA where no * copyright on uncreative databases exists(1), the list of names can be * used freely. Thus we have the right to use it under GPL (though this * does not protect the selection of names). * * (1) http://en.wikipedia.org/wiki/Database_copyright#United_States */ /** Create a random name from a list of names of scientists. **/ package plugins.WebOfTrust.util; import java.util.Random; import java.util.Set; import java.lang.StringBuffer; public class RandomName { /* Just allocate the String in one step. A better way would be to * read it from a static file, but I don’t know how to do that * reliably, so that has to wait. Indentation removed for the * construction, because it increases the filesize by 50%. */ final static String[] firstnames = { "Aatsista", "Abbas", "Abbott", "Abd", "’Abd", "Abdel", "Abdol", "Abdul", "AbdulrahmanAbhari", "Abdus", "Abel", "Abolfadl", "Abraham", "Abu", "Abū", "Abul", "Abu’l", "Abulcasis", "Achim", "Ada", "Adalbert", "Adam", "Addison", "Adele", "Adilson", "Adnan", "Adolf", "Adolfo", "Adolph", "Adolphe", "Adrian", "Adrien", "Agostino", "Ahearn", "Ahmad", "Ahmed", "Aimé", "Air", "Akhtar", "Al", "Ala’eddinAlavi", "Alain", "Alan", "Albert", "Alberte", "Alberto", "Albrecht", "Aldo", "Alec", "Alejandro", "Alexander", "Alexandre", "Alexei", "Alexis", "Alexius", "Alfred", "Alhazen", "AlhazenAmuli", "Ali", "Alicia", "Alistair", "Allan", "Allen", "Allenna", "Allvar", "Alois", "Alonzo", "Alphonse", "Alsayed", "Altman", "Alvar", "Alvin", "Alwin", "Amasa", "Ambrose", "Ambrozic", "Amin", "Amir", "Anatol", "Anders", "André", "Andreas", "Andrei", "Andrew", "Andy", "Angélique", "Anil", "Animesh", "Anita", "Ann", "Anna", "Anousheh", "AnsariAn", "Anselm", "Anthony", "Antoine", "Anton", "Antonella", "Antonio", "Antonius", "AnvariMo’ayyeduddin", "Ányos", "APJ", "Aqa", "Aqsara’iArzani", "Arbour", "Arden", "Armand", "Armin", "Armstrong", "Arnaldo", "Arndt", "Arne", "Arnold", "Arnoult", "Arthur", "Arun", "Arvid", "AryabhataBaudhayana", "Asad", "Asaph", "Aseem", "Ashok", "Ashoke", "Asper", "AstarabadiAufi", "Astronomers", "Athanase", "Athanasius", "Atul", "Auer", "August", "Auguste", "Augustin", "Augusto", "Augustus", "Aurel", "AverroesAl", "AverroesAvicenna", "AverroesIbn", "AverroesIbn", "AverroesIbn", "Avi", "AvicennaAbd", "AvicennaAbū", "AvicennaAl", "AvicennaAzophi", "AvicennaHakim", "AvicennaIbn", "Axel", "Axworthy", "Aziga", "Aziz", "Azizul", "Azod", "Ba", "Bacharuddin", "BaghawiBahai", "Bagshaw", "Bain", "BaladhuriBal’ami", "Baldwin", "Balfour", "BalkhiBalkhi", "BalkhiBanū", "Baltovich", "Baltzar", "Bandura", "Bangxing", "Banū", "Barbara", "Barlaam", "Barlow", "BarmakBayhaqi", "Barrie", "Barringer", "Barry", "Bartholomew", "Bartolomeo", "Baruj", "Bascom", "Beatrice", "Beatty", "Becky", "Bee", "Bégin", "BehbahaniIbn", "Beker", "Béla", "Belaney", "Bell", "Belsazar", "Ben", "Benedict", "Bengt", "Benjamin", "Benoît", "Berend", "Berger", "Bernard", "Bernardo", "Bernd", "Bernhard", "Bernt", "Berta", "Berthold", "Besette", "Beth", "Bethune", "Bhāskara", "Biéler", "Big", "Bigelow", "Bill", "Billy", "bin", "Bindy", "Bing", "Birbal", "Birjandi", "BiruniBukhari", "Bishop", "Bjarni", "Björn", "Black", "Blass", "Blaylock", "Blondin", "Blusson", "Bob", "Bombardier", "Bonnie", "Boris", "Bourassa", "Bourgault", "Boyd", "Boyle", "Braden", "Bradley", "BrahmadevaBrahmagupta", "Brant", "Brendan", "Brethren", "Brian", "Bridget", "Brigadier", "Broadbent", "Brockhouse", "Bronfman", "Brook", "Brossard", "Brother", "Brown", "Bruce", "Bruno", "Brunt", "Bryan", "Buck", "Bucke", "Bùi", "Bukhtishu", "BukhtishuBukhtishu,", "Bull", "Burzoe", "Bửu", "Cai", "Caleb", "Callaghan", "Callinicus", "Calvert", "Calvin", "Camille", "Campbell", "Campeau", "Captain", "Carbonneau", "Cardinal", "Carey", "Carl", "Carlo", "Carlos", "Carol", "Carolus", "Carroll", "Caryl", "Caspar", "Cassius", "Caten", "Cato", "Cecil", "Celeste", "Cerny", "César", "Cesare", "Chambers", "ChanakyaCharaka", "Chang", "Chante", "Chao", "Charles", "Charlotte", "Chauncey", "Chemistry", "Chen", "Chester", "Chiara", "Chief", "Chien", "Childs", "Chris", "Chrisholm", "Christian", "Christiane", "Christof", "Christoph", "Christophe", "Christopher", "Chu", "Clague", "Claire", "Clarence", "Clark", "Claude", "Claudia", "Claus", "Clifford", "CNR", "Coching", "Cohen", "Cojocaru", "Colin", "Colonel", "Conrad", "Constantine", "Constantinos", "Cooke", "Copps", "Corentin", "Corrado", "Cossette", "Craig", "Cummings", "Cumrun", "Cumshewa", "Cunning", "Currie", "CV", "Cynthia", "D", "Damian", "Dan", "Daniel", "Dankmar", "Danny", "D’Artosis", "Dave", "David", "Davidson", "Dean", "Death", "Debora", "Deborah", "Deepak", "DeGroote", "Delfino", "Demetrius", "Dennis", "Derek", "Derry", "Desmarais", "Detlev", "DeWitt", "Diamond", "Dian", "Dick", "Didymos", "Diederich", "Diederik", "Diedrich", "Dieter", "Dinawaree", "DīnawarīDinawaree", "Ding", "Dionysios", "Dionysius", "Dmitri", "Dmytruk", "Dobbin", "Don", "Donald", "Donaldson", "Doris", "Doug", "Dougal", "Douglas", "Dow", "Dr", "Dragoljub", "Dreimanis", "Dries", "Dwight", "E", "Eastman", "Eaton", "Ebbers", "Ebenezer", "Eberhard", "Ed", "Edgar", "Edmond", "Edmund", "Edouard", "Édouard", "Edsger", "Eduard", "Edward", "Edwin", "Efstratios", "Eilhard", "Eleftherios", "Eleuthère", "Eli", "Eliakim", "Elias", "Élie", "Elijah", "Elisabeth", "Elizabeth", "Ellen", "Elliot", "Elmer", "Eloise", "Elsa", "Elsayed", "Elsie", "Elwin", "Eman", "Emanuel", "Emil", "Emile", "Émile", "Émilie", "Emily", "Engelbert", "Enne", "Enrico", "Enzo", "Ephraim", "Eric", "Erich", "Erik", "Erna", "Ernest", "Ernesto", "Ernst", "ErnstViktor", "Erwin", "Esfarayeni", "Essam", "Etienne", "Étienne", "Eugen", "Eugene", "Eugène", "Eugenio", "Eustachio", "Eustathius", "EutociusChronas", "Eva", "Evangelista", "Evans", "Évariste", "Evliya", "Fabian", "Fabrice", "Faheem", "Fairclough", "Farabi", "Farghani", "Fariborz", "Farid", "Farkas", "Farouk", "Farsi", "Faten", "Fausto", "Fawzia", "Fazari", "Fazle", "Fazlur", "Federico", "Felice", "Felix", "Félix", "Fenerty", "Ferdinand", "Ferdinando", "Ferdowsi", "Ferid", "Fernando", "Fessenden", "Feyz", "Fields", "Filippo", "Fisher", "Florian", "Flossie", "Fonyo", "Fooke", "Foote", "Forrest", "Fortunio", "Fox", "Frances", "Francesco", "Francis", "Franciscus", "François", "Françoise", "Frank", "Franklin", "Franks", "Frans", "Franz", "Fraser", "Fred", "Frédéric", "Frederick", "Frieder", "Friederich", "Friedrich", "Fritjof", "Fritz", "Frum", "Frye", "Fuller", "Fullerian", "Gabriel", "Gabrielse", "Gabrio", "Gaetano", "Gajendra", "Galbraith", "Galileo", "Gamal", "Ganapathi", "Gao", "Gardezi", "Gaspard", "Gaspare", "Gaston", "Geber", "Gene", "General", "Georg", "George", "Georges", "Georgi", "Georgios", "Gerald", "Gerard", "Gerd", "Gerhard", "Gerhart", "Germinal", "Gernot", "Gerry", "Gertrud", "Gesner", "GhazaliGilani,", "Ghiyāth", "Giacinto", "Giacopo", "Giambattista", "Gian", "Gianni", "Gianpiero", "Giauque", "Gilbert", "Gill", "Gilles", "Giorgio", "Giovanni", "Giuliano", "Giulio", "Giuseppe", "Gopalasamudram", "Gordon", "Goresky", "Gorgani", "Gosling", "Gösta", "Gottfried", "Gotthilf", "Gotthold", "Gottlob", "Grace", "Grady", "Graeme", "Granholm", "Grant", "Greg", "Gregor", "Gregorio", "Gregory", "Grete", "Grigori", "Grote", "Groulx", "Guenter", "Guglielmo", "Guido", "Guité", "Günter", "Günther", "Guo", "Guoray", "Gustaf", "Gustav", "Gustavus", "Guujaaw", "Guy", "Gyula", "Håkan", "Hakim", "Hal", "HalayudhaJayadeva", "Hall", "Hallaj", "Haly", "Hamadani", "Hamed", "Hammad", "HanbalHarawi,", "Haney", "Hannes", "Hanns", "Hans", "Hansen", "Har", "Harald", "Harawi", "Harish", "Harley", "Harlow", "Harold", "Haroon", "Haroutioun", "Harren", "Harriet", "Harriette", "Harrison", "Harry", "Hartmut", "Harvey", "Hasan", "Hasani", "Haskell", "Hassan", "Hawley", "Hawthorne", "He", "Heber", "Hechtman", "Hector", "Hedy", "Heide", "Heike", "Heiko", "Heinrich", "Heinz", "Helen", "Helga", "Helge", "Helmut", "Helmuth", "Hendrik", "Henning", "Henri", "Henriette", "Henry", "Herbert", "Herman", "Hermann", "Herrick", "Hervé", "Herzberg", "Hessaby", "Hezarfen", "Hibat", "Hierocles", "Hieronymus", "Hillier", "Hippolyte", "Hiram", "hitects", "Hjalmar", "Ho", "Homayoun", "Homi", "Homolka", "Hongjia", "Hoodless", "Horace", "Horst", "Hotz", "Howard", "Howe", "Hsien", "Hubel", "Hubert", "Hugh", "Hugo", "Hulusi", "Humphrey", "Humphry", "Hunayn", "Ian", "Ibn", "Ibrahim", "Ignacio", "Ignatieff", "Ignaz", "Igo", "Ikhwan", "IlaqiIlyas,", "Ingo", "Innis", "Ioannes", "Ion", "Ioulianos", "Ira", "Irene", "Irène", "Irit", "Irvine", "Irving", "Isaac", "Isfahani", "Ishaq", "Ishfaq", "Ishrat", "Isidore", "IstakhriIranshahri", "Ivan", "Jabbo", "Jābir", "Jack", "Jacks", "Jacob", "Jacques", "Ja’far", "Jafar", "Jagadish", "Jagdish", "JaghminiJaldaki", "Jagmohan", "Jakob", "James", "Jamshīd", "Jan", "Jane", "Janet", "Janice", "Janne", "János", "Janus", "Jarrah", "Jay", "Jean", "Jeffrey", "Jegor", "Jennifer", "Jennings", "Jens", "Jeremy", "Jerome", "Jerry", "Jewgraf", "Jia", "Jiamo", "Jiang", "Jim", "Joan", "Joannes", "Joaquin", "Jochen", "Joe", "Joël", "Johan", "Johann", "Johannes", "Johanson", "John", "Johns", "Johnson", "Jon", "Jonas", "Jonathan", "Jones", "Jöns", "Jørgen", "José", "Josef", "Joseph", "Joshua", "Josiah", "Joyce", "József", "Jules", "Julia", "Julie", "Julien", "Julius", "June", "Jürgen", "Justin", "Justus", "JuvayniJuwayni", "JuzjaniJamasb", "Kailas", "Kajetan", "Kalidas", "Kamal", "Kamāl", "KarajiKashani", "Karel", "Karin", "Karl", "Karol", "KashfiKazerouni", "Kate", "Katharina", "Katherine", "Kathy", "Kazem", "Keen", "Kelvin", "Kenneth", "Kent", "Kerim", "KermaniKermani", "Kesterton", "Kevin", "Keyes", "KhademhosseiniKhazeni", "Khalid", "Khalil", "KhazeniKhayyám", "KhorasaniKhujandi", "KiamehrKhwarizmi", "Kieran", "Killam", "Kim", "Kimura", "Kirstin", "Klattasine", "Klaus", "Klein", "Knut", "Kometas", "Konrad", "Kotcherlakota", "Koyah", "Kristian", "Kristin", "Krogh", "KuhiKubra", "Kurd", "Kurt", "Kushyar", "Kyle", "L", "Labib", "Labīd", "Lacombe", "Lagari", "Laliberté", "Lalji", "Lambton", "Lance", "Lanctôt", "Landon", "Landrum", "Langlois", "Laramie", "Larry", "Lars", "László", "Latimer", "Lauren", "Lawrence", "Layton", "Lazareanu", "Lazarus", "Lazzaro", "Le", "Lebrecht", "Lee", "Legere", "Leigh", "Leland", "Len", "Lennart", "Lenore", "Leo", "Leon", "Leonard", "Leonardo", "Leonhard", "Leonid", "Leontios", "Leopold", "Leopoldo", "Lépine", "Leslie", "Lester", "Lewis", "Li", "Lieselott", "Lieutenant", "Lillian", "Lisa", "Lise", "Liselotte", "Liu", "Loránd", "Lorenz", "Lorenzo", "Lorraine", "Lortie", "Lotfi", "Lothar", "Louis", "Lucien", "Lucius", "Luckett", "Ludolph", "Ludovic", "Ludvig", "Ludwig", "Luigi", "Luisa", "Luko", "Lutz", "Lybbert", "Lyman", "Lynn", "Ma", "Macalister", "Macdonald", "Macedonio", "Mackay", "Macoun", "Macphail", "MacPherson", "Mae", "Maged", "Magnus", "MahaniMohammad", "Mahbub", "Mahmoud", "Main", "Mainse", "Major", "MajusiMarvazi", "Malcolm", "Mance", "Mandrake", "Manfred", "Manindra", "Manne", "Mansbridge", "MansooriMuhammad", "Mansukh", "Mansur", "Manuel", "Maquinna", "Marc", "Marcel", "Marcela", "Marcellin", "Marcia", "Marcin", "Marco", "Marcus", "Marek", "Margaret", "Marguerite", "Marian", "Mariano", "Marie", "Marigny", "Marjorie", "Mark", "Markle", "Marks", "Marshall", "Marta", "Martin", "Martinus", "MarvaziMasawaiyh", "Mary", "Maryam", "MashallahMasihi", "Mathias", "Matt", "Matthew", "Matthias", "Matyáš", "Maurice", "Max", "Maxime", "Maximilian", "Maximus", "Mayer", "McCain", "McCoy", "McCulloch", "McGee", "McLachlin", "McLeod", "McLuhan", "McMillan", "McNeil", "McPherson", "McTavish", "Mead", "Meghnad", "Mehdi", "Mehmet", "Mehran", "Meinolf", "Melanie", "Melchisédech", "Menten", "Menyhért", "Merle", "Merrill", "Michael", "Michail", "Michel", "Michelangelo", "Middleton", "Mihajlo", "Mike", "Milgaard", "Mills", "Mir", "Mirko", "Mirza", "MiskawayhMostowfi", "ML", "Mo", "Mo’ayyeduddin", "Mohamed", "Mohammad", "Molson", "Monica", "Monika", "Monte", "Monty", "Morgan", "Morgentaler", "Morin", "Moritz", "Morrow", "Moshe", "Mostafa", "Mountjoy", "Moustafa", "Moustapha", "Mozaffar", "Muhammad", "Muhammed", "Muḥyi", "Muise", "MullasadraMuqaffa", "Munir", "Munk", "Munro", "Murder", "Murray", "Mustafa", "MuwaffaqMuhammad", "Nachman", "Nader", "NagarjunaPingala", "NagawriNahavandi", "NahavandiNakhshabi", "Naismith", "Najab", "Naldrett", "Napoleone", "Narendra", "NasaviNatili", "Nasir", "Nasīr", "Nat", "Nathan", "Nathanael", "Nathaniel", "NaubakhtAl", "NaubakhtNaubakht", "NawbakhtyNawbakhti", "NayriziNaqshband", "Nazir", "Neil", "NeishaburiNeishaburi", "Nelson", "Neophytos", "Newman", "Nezami", "Nguyet", "Nicephorus", "Nicholas", "Nicola", "Nicolas", "Nicolaus", "Nicole", "Nicolò", "Niels", "Nikephoros", "Niketas", "Niklas", "Nikola", "Nikolai", "Nikolaos", "Nikolaus", "Nils", "Nima", "Nitya", "Niyaz", "Noam", "Noella", "Noga", "Norbert", "Noreen", "Norman", "Norwest", "Nur", "Nurbakhshi", "Ogden", "Olaus", "Olav", "Ole", "Olga", "Olinde", "Oliver", "Olson", "Omar", "Orest", "Ormsby", "Osborne", "Oscar", "Oskar", "Osler", "Othenio", "Othmar", "Ottaviano", "Otto", "Ottomar", "Ouyang", "Owen", "Padmanabhan", "Pafnuti", "Paikin", "Palmer", "Pan", "Pandurang", "Paolo", "Papineau", "ParacelsusClemens", "Parker", "Pasquale", "Patcha", "Patriarch", "Patrick", "Pattison", "Paul", "Pedro", "Pegahmagabow", "Pehr", "Pei", "Peltier", "Penfield", "Per", "Percy", "Perri", "Pervez", "Pete", "Peter", "Philip", "Philipp", "Philippe", "PiapotTecumseh", "Pickersgill", "Pickton", "Pierre", "Pieter", "Pietro", "Pinker", "Piri", "Pjotr", "Placidus", "Platon", "Polanyi", "Porritt", "Pouliot", "Prasanta", "Price", "Prince", "Prodromos", "Prof", "Prosper", "Qāḍī", "Qazi", "QazwiniQumi", "QumriQushayri", "Qutb", "Rachid", "Rafi", "Raghunath", "Raimondo", "Rainer", "Rajeev", "Rakesh", "Ralf", "Ralph", "Ralston", "Ram", "Ramesh", "Ranajit", "Randi", "Randy", "Ranj", "Raoul", "Ray", "Raymond", "RaziRazi", "Raziuddin", "Rear", "Rebecca", "Redpath", "Reeves", "Reichmann", "Reinhard", "Reinhold", "Rémy", "Ren", "Rene", "René", "Reyat", "Rhetorios", "Riaz", "RiazuddinAbdul", "Richard", "Rick", "Ricketts", "Riel", "Rivard", "Robert", "Roberta", "Roberto", "Roberts", "Robertson", "Rocha", "Roddam", "Rodney", "Roger", "Rogers", "Roland", "Rolf", "Rollo", "Ron", "Ronald", "Rosalind", "Rosalinde", "Rose", "Ross", "Roth", "Rousseau", "Roy", "Royal", "Rüdiger", "Rudolf", "Rudolph", "RumiRashid", "Rune", "Rupert", "Ruth", "Ruttan", "Ryan", "Ryerson", "Sabine", "Sabourin", "SabzevariSepahsalar", "Sackett", "Safer", "Saghani", "Saghir", "SahlSahl", "Saint", "Sake", "Salim", "Salimuzzaman", "Salman", "Salomon", "Salvatore", "Sam", "SamarqandiSamarqandi", "Sameera", "Samir", "Samuel", "Sandra", "Sandy", "Sanford", "Sangster", "Sanjeev", "Saputo", "SarakhsiSarakhsi", "SarakhsiSeifzadeh", "Saul", "Saunders", "Schawlow", "Schindler", "Schlumberger", "Schnarre", "Scholes", "Scipione", "Scott", "Sean", "Sebastian", "See", "Selim", "Selye", "Sergei", "Sergey", "Serhij", "Sethus", "Seymour", "Shahid", "Shahrastani", "ShahrazuriShahrazuri", "Shams", "Shanti", "Shao", "Shapur", "Sharaf", "Sharp", "Shawn", "Shaykh", "Sheikh", "Sheila", "Shen", "Shi", "Shinya", "ShiraziShirazi", "ShiraziSijzi", "Shoukai", "Shreeram", "Sicard", "Sidney", "Siegfried", "Siegmund", "Sigmund", "SijziSoleiman", "Silvanus", "Simard", "Siméon", "Simon", "Simpson", "Sir", "Siva", "SlumachSmith,", "Smith", "SN", "Sofia", "Sofja", "Sol", "Song", "Sophie", "Sophus", "Sotirichos", "Srinivasa", "St.", "Stacy", "Stairs", "Stam", "Stanley", "Stanton", "Starkman", "Steele", "Stefan", "Stefano", "Stefanos", "Stelck", "Stephanie", "Stephanos", "Stephen", "Stephenson", "Steve", "Steven", "Stewart", "Strangway", "Stronach", "Stuart", "Studholme", "Su", "Subramanyan", "Suhrawardi", "Sujoy", "Sultan", "Sultana", "Sun", "Sunatori", "Sundback", "Sunder", "Sunil", "Susanne", "SushrutaVyasa", "Suzuki", "Svante", "Sven", "Sydney", "Syed", "Sylvestre", "Symeon", "Symons", "Sztybel", "TabaraniTabari", "TabariTabari", "TabriziTaftazani", "Taché", "Taha", "TahirTayfur", "Talgat", "Tamsin", "Tan", "Tanner", "Taqi", "TāriqTirmidhi", "Taryn", "Taube", "Taylor", "Tej", "Tekakwitha", "Terry", "Thatcher", "The", "Theo", "Theodigios", "Theodoghius", "Theodor", "Theodore", "Théodore", "Theodoros", "Theofilos", "Thériault", "This", "Thomas", "Thomson", "Thorvald", "Tiberius", "Till", "Tilley", "Tim", "Timotheos", "Timothy", "Tipu", "Tobias", "Todd", "Toffy", "Tom", "Tommaso", "Tong", "Tony", "Torsten", "Traugott", "Trinh", "Trueman", "Truscott", "Tuan", "TunakabuniTughra’i", "TusiTusi", "Tyrrell", "Uchida", "Ugo", "Ulisse", "Ulrich", "Ulugh", "Urbain", "Uriel", "Urry", "Usamah", "Utpal", "Uwe", "Václav", "Vainu", "Valentin", "Vanier", "Vannoccio", "Vaughan", "Venkatraman", "Vernon", "Vickrey", "Vicky", "Victor", "Vidus", "Vijay", "Vikram", "Viktor", "Vilhelm", "Vincent", "Vincenzo", "VincenzoFederico", "Vinod", "Vinton", "Vito", "Vittorio", "Vladimir", "Volker", "Waddah", "Walker", "Wallace", "Waloddi", "Walter", "Walther", "Wang", "Waqidi", "Ward", "Warder", "Warner", "Warren", "Wasylyk", "Watson", "Wei", "Wendell", "Weng", "Weniamin", "Werbowy", "Werner", "Wernher", "Weston", "Wickanninish", "Wiktor", "Wilbur", "Wilfried", "Wilhelm", "Willem", "William", "Williams", "Willson", "Willy", "Wilma", "Wilson", "Win", "Winegard", "Wladimir", "Władysław", "Wo", "Woldemar", "Wolfgang", "Wolfram", "Woodbine", "Woodrow", "Woodward", "Wu", "Xavier", "Xiangzhong", "Xiaobo", "Xie", "Xuong", "Yang", "Yao", "Yaqūb", "YazdadYaqūb", "Ye", "Yehia", "Yehuda", "Yellapragada", "Yingjie", "York", "Yoshihiro", "Young", "Yu", "Yuanzhang", "Yumn", "Yusuf", "Zacharias", "Zachary", "Zaghloul", "zahid", "ZaiyatZamakhshari", "Zarrin", "Zayn", "Zhang", "Zhao", "Zheng", "Zhou", "Zhu", "Zhuang", "Zimmer", "Zygmunt"}; final static String[] lastnames = { ".", "&", "—", "1.", "3.", "a", "A.", "Abarth", "Abbas", "Abbās", "Abbe", "Abdollah", "Abdul", "Abdulaziz", "Abel", "Abenragel", "Abhay", "Abhyankar", "abi", "Abi", "Abidi", "Abolfadl", "Abol-fath", "Abol-hasan", "Abouleish", "Abraham", "Abu", "Abu’l-Barakat", "Achache", "Achard", "Acropolites", "activists", "actors", "Adam", "Adams", "Adelaide", "Adelson-Welski", "Adhémar", "Adler", "Admiral", "Adolf", "Adolph", "Aepinus", "Aeronautical", "Afek", "Afzal", "Agnes", "Agnethler", "Agrawal", "Agre", "Ahad", "Ahmad", "Ahmed", "Ahmet", "Aho", "Ahuja", "AIA", "AIBC", "Aimee", "Airy", "Aitken", "a.k.a.", "Akhtar", "al", "Ala", "Alabbas", "Alan", "Alana", "Baghdaadi", "Baghdadi", "Baitar", "Balkhi", "Banna", "Banna’", "Battānī", "Albers", "Albert", "Bīrūnī", "Alboacen", "Būzjānī", "Alcock", "Darir", "Alderson", "Din", "Dīn", "Aldini", "Dowleh", "Aleksis", "Alexander", "Alexandre", "Alexandrinos", "Alexandrowitsch", "Alexejewitsch", "Fārisī", "Fazari", "Alfred", "Alfvén", "Gazzar", "Habib", "Hamīd", "Harrānī", "Hasan", "Haytham", "Ali", "Alī", "Idrisi", "Istikmal", "Alivisatos", "Jawharī", "Jazzar", "Jurajani", "Kāshī", "Khatib", "Khāzin", "Khujandi", "Khwārizmī", "Allah", "Allan", "Latif", "Allee", "Allègre", "Allen", "Allenby", "Allman", "Maghribī", "Majusi", "Mo’ali", "Muqaddasi", "Mutaminwas", "Muwaffak", "Nafis", "Alon", "Alonzo", "Aloysius", "Alpert", "Alphonse", "Qalasādī", "Qalqashandi", "Qasim", "Quff", "Qūhī", "Rahman", "Rahman", "Rahwi", "Alroy", "Rūmī", "Sadiq", "Safa", "Samarqandī", "Shatir", "Alshaykh", "Shirazi", "also:", "Sufi:", "Alt", "Tabari", "Alter", "Thahabi", "Althaus", "Altmeyer", "Turabi", "Tusi", "Tūsī", "Uqlidisi", "Wafā’", "Alwall", "Yaman", "Zahrawi", "Zarqālī", "Alzinger", "Amaldi", "Amandus", "Amara", "Ambroise", "Ambronn", "Ambrose", "Ambrosius", "Amdahl", "Amed", "Amedeo", "Amici", "Amin", "Amoretti", "Ampère", "Amsler-Laffon", "an", "Anand", "Anant", "and", "Anderson", "Andræ", "André", "Andreae", "Andreas", "Andreessen", "Andrejewitsch", "Andrew", "Andrews", "Angas", "Ange", "Angelini", "Ångström", "Anh", "Annie", "an-Nu‘man", "Ansari", "Anschütz-Kaempfe", "Anthemius", "Anthony", "Antinori", "antiosteoporosis", "Antoine", "Anton", "Antonelli", "Antoni", "Antonio", "Antonucci", "Antoon", "Anwar", "AOE", "Appelbaum", "Appell", "Appelrath", "Apple", "application", "Apt", "Arago", "Arbib", "Archeologist", "Archer", "Archibald", "Archie", "’Arcy", "Ardré", "Arfwedson", "Argand", "Argyros", "Arkani-Hamed", "Armstrong", "Arndt", "Arnett", "Arnold", "Aronhold", "Arora", "Arrhenius", "Arrighetti", "Arseneau", "Arsenjew", "Artemjew", "Arthur", "article:", "articles:", "Artin", "artists", "Arturo", "Arzelà", "as", "Aschoff", "Ascoli", "Ashtekar", "Asker", "Aslam", "Aslihan", "Asma’i", "Asperger", "Asplund", "astronomers", "Astrophysicist", "astrophysicists", "Atala", "Athanase", "Atiya", "Atkinson", "Atleo", "Attaliates", "Atwater", "Auenbrugger", "Auer", "Auerbach", "August", "Auguste", "Augustin", "Augustine", "Augustus", "Avery", "Avogadro", "Avolio", "Avram", "Axon", "Ayako", "Ayrton", "Azophi", "B.", "Baader", "Babai", "Babbage", "Babinet", "Bach", "Bache", "Bächler", "Bachman", "Bachmann", "Backlund", "Bäcklund", "Backus", "Badawi", "Baerwald", "Baghdadi", "Bailey", "Bain", "Bajjah", "Baker", "Balaram", "Baldwin", "Ball", "Balmer", "Baltzer", "Balzani", "Balzert", "Banda", "bands", "Banerjee", "Banting", "Bappu", "Baptiste", "Baptiste", "Baptiste-Charles-Joseph", "Baqillani", "Baqir", "Bar", "Baran", "Bárány", "Barbara", "Barclay", "Baril", "Barker", "Barlow", "Baron", "Barratt-Boyes", "Barrett", "Bartels", "Bartholomäus", "Bartoli", "Basse", "Battista", "Battuta", "Bauer", "Baumann", "Baumgartner", "Bavink", "Bayer", "Bazaine", "Bear", "Bearpark", "Beaton", "Beauclair", "Beaverbrook", "Bechtolsheim", "Beck", "Becker", "Becquerel", "Beddington", "Beecher", "Beeck", "Beer", "Beetz", "Beg", "Behçet", "Behlendorf", "Bélanger", "Belgrado", "Bell", "Bellard", "Belli", "Bellocchi", "Beltrami", "Bement", "Bemer", "Ben", "Ben-Abraham", "Benacerraf", "Benedict", "Beneke", "Benischke", "Benjamin", "Benjamin", "Bennett", "Benz", "Bergen", "Bergter", "Berkeley", "Berliner", "Berman", "Bernard", "Berners-Lee", "Bernhard", "Bernie", "Bernstein", "Berthelot", "Bertin", "Bertini", "Bertram", "Bertrand", "Berzelius", "Besha", "Bessel", "Bessières", "Bestelmeyer", "Beth", "Betrugi", "Bettelheim", "Betti", "Beurle", "Beurling", "Beutler", "Beverly", "Beyer", "Beynon", "Beyrich", "Bezold", "Bhabha", "Bhaktivedanta", "Bhatkar", "Bhatnagar", "Bialy", "Bianchi", "Bibi", "Biddell", "Bidwell", "Bieling", "Bienvenu", "Biere", "Bierens", "Bierstedt", "Bijl", "Bilal", "Billet", "Bimber", "bin", "Binet", "Biologist", "Biot", "Birchall", "Biringuccio", "Birkeland", "Birnbaum", "Bischofberger", "Bishop", "Bishop.", "Bittner", "Bjerhammar", "Bjerknes", "Black", "Blake", "Blakesley", "Blanc", "Blanchard", "Blandowski", "Blaschke", "Blaserna", "Blasius", "Blauert", "Bleher", "Blemmydes", "Bloch", "Bloede", "Blömer", "Blondel", "Blondlot", "Bloodworth", "Blow", "Blum", "Bob", "Bôcher", "Bode", "Bodenstein", "Boehm", "Boehmer", "Bogdandy", "Böhler", "Bohlin", "Bohlmann", "Böhm-Bawerk", "Bohn", "Bohnenberger", "Boie", "Bois-Reymond", "Bokhari", "Boll-Dornberger", "Bolter", "Boltzmann", "Bolyai", "Bolzano", "Bond", "Bondar", "Bondar.", "Bonnet", "Booch", "Book", "Boole", "Bopp", "Borchardt", "Borchert", "Borg", "Boris", "Borissowitsch", "Born", "Born-", "Börnstein", "Borzouyeh-i", "Bosak", "Bosch", "Bose", "Boslough", "Bossart", "Böszörményi", "Botto", "Bottomley", "Boulos", "Bouquet", "Bourgelat", "Bourgeois", "Bourgeoys", "Bourne", "Boussinesq", "Boussingault", "Bowditch", "Bowen", "Bowman", "Boyce", "Boyd", "Boyer", "Boyle", "Boys", "Brace", "Brachet", "Bradley", "Brandan", "Brandes", "Brandt", "Branislav", "Branly", "Brant", "Brashear", "Brassard", "Bratt", "Brauer", "Braun", "Bravais", "Bray", "Brébeuf", "Breguet", "Breislak", "Brenner", "Brent", "Brentano", "Bresenham", "Bretschneider", "Breuer", "Brewer", "Brewster", "Brian", "Brianchon", "Bricklin", "Briefs", "Brienza", "Briggs", "Brill", "Brillouin", "Brin", "Brioschi", "Briot", "Bristol", "Britz", "Broca", "Brocchi", "Brock", "Broder", "Brodhun", "Brooks", "brothers", "Brothers", "Brown", "Brownlee", "Broy", "Brubaker", "Bruce", "Brücke", "Bruckmann", "Brügge", "Brunel", "Brunhes", "Brunner-von", "Brunnstein", "Bruno", "Bruns", "Bry", "Bryant", "Bt", "Bubb", "Buber", "Bucherer", "Buchholz", "Büchi", "Buchmann", "Buckingham", "Budach", "Budiansky", "Buff", "Bunjakowski", "Bunker", "Buquoy", "Burali-Forti", "Burch", "Burdon-Sanderson", "Burg", "Burgard", "Burgay", "Burgdorfer", "Bürger", "Burja", "Burkewood", "Burkhardt", "Burmeister", "Burr", "Buschke", "Bussard", "Butement", "Butterworth", "Büttner-Janz", "Buys-Ballot", "Buytaert", "Buzjani", "by", "Byrne", "c.", "C.", "Cabane", "Cabanis", "Cade", "Cahn", "Cai", "Cailletet", "Cailliau", "Caine", "Cairncross", "Cajori", "Calder", "Calhoun", "Callaway", "Callister", "Calmette", "Calvisius", "Camaterus", "Cameron", "Camille", "Campbell", "Campbell-Howe", "can", "Canada", "Canadian", "Cancrin", "candidate", "Canettieri", "Canguilhem", "Cant", "Cantor", "Capilano", "Capra", "Caracristi", "Card", "Cardinal", "Carey", "Carini", "Carl", "Carlebach", "Carleson", "Carleton", "Carlo", "Carlson", "Carlsson", "Carmack", "Carnot", "Carpenter", "Carrick", "Carroll", "Carruthers", "Cartan", "Cartier", "Carucci", "Cäsar", "Caselli", "Casey", "Casorati", "Cassian", "Castellani", "Castillo-Chavez", "Catalan", "Cathy", "Catlin", "Catmull", "Caton", "Cauchy", "Cavallo", "Cayley", "CB", "CBE", "CC", "CD", "Cecil", "Celebi", "Çelebi", "Célestin", "Celko", "Celsius", "century", "Century", "Cerami", "Cerf", "César", "Cesàro", "Cesi", "CH", "Chabanel", "Chain", "Chakmakjian", "Chakraborty", "Chakravorty", "Chalfie", "Chalmers", "Champneys", "Chand", "Chandra", "Chandrasekhar", "Chang", "Chapman", "Chappuis", "Charles", "Charpy", "Chasles", "Chastelain", "Châtelet", "Chattar", "Chaudhry", "Chauvenet", "Chazelles", "Che", "Chemist", "Chemist/Drug", "Chemistry", "Chen", "Cherry", "Chick", "chief", "Chilton", "Chin", "Ching-wu", "Chi-yun", "Chladni", "Chomsky", "Choniades", "Choniates", "Chortasmenos", "Choumnos", "Chrétien.", "Chris", "Christ", "Christian", "Christiansen", "Christie", "Christoffel", "Christoffer", "Christoph", "Christophe", "Christopher", "Chrobak", "Chroust", "Chrysokkokes", "Chrysoloras", "Chu", "Chua", "Church", "Chwolson", "Clah", "Clapeyron", "Clarence", "Claret", "Clark", "Clarke", "Claude", "Clausius", "Clebsch", "Clement", "Clément", "Clément-Désormes", "Clements", "Clerk", "Clifford", "Clifton", "Cluny", "Clyde", "Clynes", "CM", "CMG", "CMM", "Cockayne", "Cockburn", "Cocke", "Coco", "Codazzi", "Codd", "Cohen", "Cohn", "Colding", "Cole", "Coles", "Colin", "Colladon", "Colmerauer", "Colonel", "Commodore", "Comnena", "Computer", "Comrie", "Conant", "Conrad", "Constant", "Constantine-Cyril", "Constantinople", "content.", "Contreras", "Converse", "Conway", "Cook", "Coons", "Cooper", "Copley", "Corbató", "Corell", "Cori", "Coriolis", "Cormier", "Cornelius", "Cornu", "Corwin", "Cosgrave", "Costaz", "Couch", "Coudres", "Couette", "Couffignal", "Cournot", "Courtial", "Courtillot", "Cousin", "Cousteau", "Coutelle", "Covert", "Cox", "Coy", "Coyne", "CQ", "Craig", "Cramér", "Crandall", "Crandell", "Crane", "Cray", "Crear", "Creighton", "Crelle", "Cremona", "Creutzfeldt", "Crick", "Criegee", "Crivelli", "Crocco", "Croft", "Crofton", "Crookes", "Crosse", "Crossharbour", "Cruveilhier", "CSC/ASC", "Culliney", "Cumenge", "Cummins", "Cunard", "Cunningham", "Curie", "Curiel", "Currie", "Curry", "Curt", "Curtis", "Curtius", "Cushman", "Cutler", "Cuvier", "Cyprios", "Czapski", "Czuber", "d.", "D.", ".D.", "Dahl", "Dahm", "Dai", "Dalén", "Dalibard", "dalla", "Dallaire", "Dallas", "Dally", "Dalton", "Damietta", "Dan", "Dandelin", "Dandy", "Dani", "Daniel", "Danilowitsch", "Darboux", "DArch", "Darcy", "D’Arcy", "d’Ardena", "Daria", "Darley", "Darwin", "Dase", "dast", "Dathe", "Daudel", "Dausset", "Davenport", "David", "Davidoff", "Davidson", "Davies", "Davy", "Dawood", "Dawson", "DCL", "DComm", "de", "De", "Dean", "Debevec", "Dedekind", "Deese", "del", "Delabarre", "Delamétherie", "Delbrück", "della", "Delpino", "DeMarco", "Deming", "Demonferrand", "Demopoulos", "Denenberg", "Denian", "Denis", "Denneau", "Denso", "DePauli-Schimanovich", "der", "des", "Desaguliers", "Descartes", "design.He", "Desjarlais", "Desmond", "Despretz", "Desvalls", "Detlef", "Detlev", "Deutsch", "Deville", "Dewdney", "Dewey", "DFC", "Dhaliwal", "Dhaliwal.", "Dham", "di", "Diamond", "Dickstein", "Diderik", "Didymus", "Died", "Diels", "Dienger", "Diesterweg", "Dieterici", "Dijkstra", "Dilger", "Dillon", "Dingley", "Dini", "Dinur", "Dirac", "Dirichlet", "Dirksen", "Dirr", "Dittrich", "Divini", "Dizhou", "DLitt", "DMSc", "Dobler", "doctors", "Doernberg", "Dolderer", "Domagk", "Domenico", "Dominique", "Donald", "Donato", "Dongier", "Doniach", "Dopatka", "Doppler", "Doreen", "Dorigo", "Dorn", "d’Ortous", "Doty", "Dotzauer", "Doug", "Dove", "Draper", "Dresler", "Dressel", "Drobisch", "Droop", "Droysen", "Drude", "drug", "Druschel", "Dryander", "Dryden", "DSc", "DSC", "DSC*", "DSO", "DSO*", "du", "Du", "Dudeney", "Dudoward", "Duesberg", "Duff", "Duhamel", "Duhem", "Dulong", "Dumas", "Duncan", "Dunn", "Duong", "Dupin", "Dupré", "Dupuis", "Duraid", "Durham", "Durrance", "Durrant", "Dury", "Duzheng", "Dvorak", "Dyck", "Dye", "d’Youville", "e", "E.", "Earl", "early", "Earnshaw", "East", "Easton", "Eaton.", "Attar", "Eberhard", "Eberhardt", "Ebert", "Eckel", "Eckert", "Eckmiller", "Ed", "ED", "E.D.", "Ed-Din", "Edessinos", "Edgar", "Edison", "Edlén", "Edlund", "Edmond", "Edmund", "Édouard", "Eduard", "Edvard", "Edward", "Edwin", "Efesios", "Egertron", "Eglash", "Egyed", "Egypt.", "Egyptian", "Ehrenberg", "Ehrenfels", "Ehrenfest", "Ehrinn", "Ehrlich", "Eich", "Eichhorn", "Eichhorst", "Eigen", "Einstein", "Eisenlohr", "Eisenstein", "Eitel", "Ekeblad", "Ekman", "El", "el-Akkad", "el-Baghdadi", "El-Baz", "Eldon", "Electrical", "Elijah", "Elizabeth", "el-Latif", "Ellegård", "Ellen", "Ellis", "Ellison", "el-Mallakh", "El-Mashad", "Elmessiri", "Elmqvist", "El-Naggar", "Elsayed", "El-Sayed", "Elster", "Emanuel", "Emerson", "Emil", "Émile", "Emmett", "Emmons", "Encarnação", "Enders", "Enflo", "Engel", "Engelbart", "Engineer", "Engquist", "Ennemond", "Enneper", "Eötvös", "Eric", "Erickson", "Ericsson", "Erik", "Erman", "Ernest", "Ernst", "Ernster", "Erwin", "Erxleben", "Esaias", "Eschenmayer", "Escherich", "Eschwege", "Esmonde", "Essl", "Esson", "Eston", "et", "Ethel", "Etrich", "Ettingshausen", "Ettrich", "Eugen", "Eugène", "Eustachi", "Evelyn", "Everest", "Ewerbeck", "Ewing", "Exner", "experienced", "Eyck", "F.", "Faà", "Fabbroni", "Fabrizio", "Fabry", "Fadell", "Fadlan", "Fahim", "Fahlman", "Fakhri", "Falciani", "Falck", "Falk", "Famous", "Fanning", "Fano", "Farabi", "Faraday", "faraz", "Farber", "Fardella", "Farghani", "Faris", "Farkas", "Farrel", "Farrokh", "Fauque", "Féaux", "Fechner", "Feddersen", "Fehr", "Feige", "Feigenbaum", "Feigl", "Feilitzsch", "Feistel", "Feldman", "Felix", "Fellinger", "Felten", "Fensel", "Feodosjewitsch", "Ferchault", "Ferdinand", "Ferrara", "Ferrari", "Ferraris", "Ferrie", "Feuerbach", "Feuerlein", "Feuillée", "Feyerabend", "Ficinus", "Field", "Finch", "Finger", "Finke", "Finsterwalder", "Firmin", "Firnas", "Firsoff", "Fischer", "Fishman", "FitzGerald", "Five", "Fizeau", "Fjodorow", "Fjodorowitsch", "Flaherty", "Fleet", "Fleischl-Marxow", "Fleming", "Fletcher", "Fleurieu", "Floquet", "Florens", "Flory", "Flower", "Floyd", "FMC", "focus", "Foerster", "Fogg", "Foing", "Foley", "Fontaine", "Forbes", "Forgy", "Forrester", "Förstemann", "Forsyth", "Forthomme", "Fortnow", "Fossel", "Fossey", "Foster", "Foucault", "Fourier", "Fowler", "Fox", "FRAIC", "Frances", "Francesco", "Francis", "Franck", "Francoeur", "François", "François", "Frank", "Franke", "Frankel", "Frankenheim", "Frankl", "Franklin", "Frankston", "Franz", "Frattini", "Fraunhofer", "Frazer", "Frédéric", "Frederick", "Frederik", "Fredholm", "Freeden", "Freeman", "Frege", "Freiherr", "Frenet", "Fresneau", "Fresnel", "Freud", "FRIBA", "Frick", "Fricke", "Fridolin", "Friedlaender", "Friedman", "Friedrich", "Fries", "Friesenhausen", "Friis", "Frisch", "Frischauf", "Frobenius", "from", "Fronius", "Frosch", "Froude", "FRS", "FRSC", "Frullani", "Fu", "Fuchs", "Furbach", "Furrer", "Fuster", "Fuyu", "G", "G.", "Gaafar", "Gabler", "Gaboury", "Gabriel", "Gächter", "Gadbled", "Gadefelt", "Gaden", "Gadgil", "Gaffer", "Gajdusek", "Galen", "Galiani", "Galilei", "Gallagher", "Gallant", "Gallese", "Galois", "Gambacorti-Passerini", "Gamma", "Gan", "Ganjavi", "Ganot", "Ganzhorn", "Ganzinger", "Gaolian", "Garbiński", "Garneau", "Garnett", "Garnier", "Gaspard", "Gaston", "Gates", "Gauss", "Gauß", "Gavreau", "Gay-Lussac", "Gaza", "GBE", "GCB", "GCMG", "Gebelli", "Gegenbauer", "Gehrke", "Gehry", "Geinitz", "Geiser", "Geißler", "Geitel", "Gemelli", "General", "geographer", "Geographical", "Geometres", "geomorphologist", "Georg", "George", "George-Étienne", "Georges", "Gerald", "Gerard", "Gerber", "Gergonne", "Gerhard", "Gerling", "Germain", "Gernez", "Gerono", "Gerry", "Gersten", "Gerstner", "Gervais", "Gerzon", "Gesner", "Gettys", "Ghaboos", "Ghazali", "Ghica", "Ghiorso", "Ghoneim", "Ghulam", "Gibbs", "Gideon", "Gieseke", "Gifford", "Gilbert", "Gilbreth", "Gilman", "Giloi", "Gintl", "Girouard", "Gitt", "Giudice", "Givens", "Glaisher", "Glan", "Glantz", "Glaser", "Gleick", "Gleixner", "Glock", "Gluschkow", "Glykas", "GM", "Gmachl", "Gobind", "Goble", "Goddard", "Gödel", "Gohar", "Goher", "Göhner", "Golay", "Gold", "Goldberg", "Goldstein", "Golizyn", "Golz", "Gompertz", "Gomperz", "Goodenough", "Goodfield", "Goodman", "Goodwin", "Göpel", "GOQ", "Gordan", "Gordon", "Gorgani", "Gorini", "Gorrie", "Gosling", "Gosnell", "Gösta", "Gottfried", "Gottlieb", "Gould", "Goupil", "Goursat", "Gouy", "Grace", "Grady", "Graefe", "Graetz", "Gräffe", "Graffi", "Graham", "Gram", "Graßmann", "Graves", "Grawe", "Grayson", "Graziano", "Green", "Greenaugh", "Greenberg", "Greene", "Greenhill", "Gregoras", "Gretschel", "Griesbach", "Griess", "Grigorjewitsch", "Grilleau", "Grmek", "Gröbner", "Grodzinsky", "Gross", "Grossberg", "Grosseteste", "Grotthuß", "Grunert", "Grünwald", "Gruson", "Gudermann", "Guérin", "Gugler", "Guha", "Guillaume", "Guillemin", "Guinier", "Guldberg", "Gullstrand", "Gumlich", "Gunanoot", "Günther", "Guo", "Guozhi", "Gustaf", "Gustaf", "Gustafson", "Gustav", "Gustave", "Guthrie", "Guy", "Guye", "Gwynne-Vaughan", "H", "H.", "Haan", "Haas", "Haast", "Habachi", "Haber", "Habert", "Habibie", "Hachette", "Hacquet", "Hadamard", "Hadermur", "Hadfield", "Hagenbach-Bischoff", "Hahn", "Hairston", "Hajjāj", "Hakim", "Hales", "Halid", "Hall", "Hallaschka", "Hallowes", "Hallwachs", "Halphen", "Halsted", "Ham", "Hamadani", "Hamaker", "Hamdani", "Hameed", "Hamel", "Hamid", "Hamilton", "Hammer-Purgstall", "Hammond", "Hanafi", "Hang", "Hanganu", "Hanifa", "Ḥanīfa", "Hankel", "Hann", "Hannibal", "Hans", "Hansen", "Haq", "Haque", "Harawi", "Harcourt", "Harding", "Harkness", "Harnack", "Harold", "Harper", "Harris", "Harrison", "Harry", "Hart", "Hartland", "Hartmann", "Hartner", "Hartwell", "Harvey", "has", "Hasan", "Hasenöhrl", "Haskins", "Hass", "Hassan", "Hassanein", "Hasselmo", "Hassenfratz", "Håstad", "Hastings", "Hauber", "Hauck", "Hayan", "Hayek", "Hayes", "Haytham", "Hayyān", "He", "Heather", "Heaviside", "Heawood", "Hector", "Heeren", "Heffter", "Hegazi", "Heiberg", "Heider", "Heikal", "Heine", "Heinrich", "Heintz", "Heis", "Heisenberg", "Heliopolis", "Hell", "Heller", "Hellmann", "Hellwig", "Helm", "Helmert", "help", "Hemdan", "Heng", "Henize", "Henle", "Henneberg", "Hennert", "Henri", "Henrici", "Henrik", "Henry", "Hensel", "Hensley", "Herapath", "Herat", "Herbert", "Herbst", "Herforth", "Herglotz", "Hermann", "Hermes", "Hermite", "Herrmann", "Hershey", "Hertz", "Hess", "Hessaby", "Hesse", "Hessel", "Hessenberg", "Hettner", "Heun", "Heuser", "Heywood", "Hierholzer", "Higgins", "Hilbert", "Hilferding", "Hill", "Hillaire", "Hillenkamp", "Hillman", "Himstedt", "Hinrichs", "Hinrichsen", "Hinton", "Hippocrates", "Hirn", "Hirsch", "Hirst", "his", "historian", "historians", "Historiography", "Hittorf", "Hjelmslev", "Hobson", "Hockham", "Hoeflin", "Hoffmann", "Hofmann", "Hofmeister", "Hoge", "Hội", "Hoissen", "Holborn", "Hölder", "Holland", "Hollander", "Hollywood", "Holm", "Holmboe", "Holmes", "Holtz", "Homer", "Hoodbhoy", "Hoover", "Hopkins", "Hopkinson", "Hopper", "Hora", "Hörmander", "Hornaday", "Horne", "Horner", "Horsley", "Hörz", "Hosler", "Hough", "Hovanes", "Howard", "Hsu", "Hu", "Huang", "Hubal", "Hubert", "Hübner", "Hud", "Hudak", "Huggins", "Hugh", "Hugoniot", "Hull", "Hülße", "Hultz", "Humbert", "Humboldt", "Hunter", "Hurley", "Hurrelmann", "Hurst", "Hurwitz", "Husayn", "Husband", "Hussain", "Hussein", "Husserl", "Huth", "Hyde", "Hyrtl", "i", "I", "ibn", "Ibn", "Ibrahim", "Ibrāhīm", "Idrisi", "Ignatz", "III", "Iles", "Ilyas", "Imad", "Imam", "Imhof", "Immanuel", "in", "In", "Inderjit", "information", "Information", "Inoué", "Interio", "introducing", "invented", "Iqbal", "Irene", "Irina", "Irwin", "Isa", "Isaac", "Isaacs", "Isadore", "Isenkrahe", "Ishaq", "Ishāq", "islam", "Islam", "Islamic", "Isma‘il", "Ismail", "it.", "Ivanovitch", "Ivar", "Ivory", "Iwanowitsch", "Iyer", "Izaak", "Izzy", "J.", ".J.", "Jaber", "Jābir", "Jack", "Jacob", "Jacobi", "Jacobs", "Jacobson", "Jacques", "Jacquin", "Ja’far", "Jäger", "Jahiz", "Jain", "Jakob", "Jakosky", "Jakowlewitsch", "Jalaleddin", "James", "Jamin", "Jamshīd", "Jandera", "Janet", "Jason", "Jaumann", "Javan", "Jawhari", "Jay", "Jayant", "Jayyani", "Jazari", "Jazla", "Jean", "Jeanne", "Jedlik", "Jeffrey", "Jeffreys", "Jegorowitsch", "Jemison", "Jenkins", "Jenness", "Jennifer", "Jensen", "Jerrard", "Jessica", "Jhoti", "Ji", "Jiadong", "Jiazhen", "Jiazheng", "Jim", "Jinliang", "Jiuzhang", "Joel", "Jogues", "Johal", "Johan", "Johann", "Johannes", "Johansson", "John", "Johnson", "Johnston", "Johnstone", "Joliot-Curie", "Jolly", "Jonas", "Jones", "Jonquières", "Jordan", "Jöreskog", "José", "Josef", "Joseph", "Joseph-Armand", "Joule", "Jouzel", "Jr.", "Jubb", "Julianus", "Julien", "Julius", "July", "Jun", "Jung", "Jürgen", "Jusuf", "K", "K.", "Kadich", "Kaempfer", "Kagan", "Kakodkar", "Kalam", "Kalko", "Kallenberg", "Kallmann", "Kalm", "Kamal", "Kamel", "Kamerlingh", "Kāmil", "Kämtz", "Kane", "Kanfer", "Kanner", "Kantakouzenos", "Kao", "Kaplan", "Kaprekar", "Karaji", "karak", "Karas", "Kardar", "Karl", "Karla", "Karmarkar", "Károly", "Karoui", "Karsten", "Kashani", "Kasner", "Kaspar", "Kassem", "Kastner", "Kateri", "Kaufmann", "Kaul", "Kavka", "Kawaoka", "Kayser", "KB", "KBE", "KCB", "KCMG", "KCSG", "Kearton", "Keck", "Keeler", "Keeling", "Keil", "Keith", "Kekulé", "Kellner", "Kelly", "Kelsen", "Kelvin", "Kempe", "Kempelen", "Ken", "Kenneth", "Kenny", "Kent", "Kerékjártó", "Kerimov", "Kermani", "Kerr", "Kervran", "Keshia", "Kessler", "Keyser", "Khaldun", "Khalil", "Khalili", "Khan", "Khankhoje", "Khan-Mayberry", "Khaseb", "Khatima", "Khatsahlano", "Khayyám", "Khazini", "Khorana", "Khorasan", "Khordadbeh", "Khwarizmi", "Khwārizmī", "Kidson", "Kiepert", "Kilbourne", "Killian", "Killing", "Kils", "Kim", "Kincaid", "Kindi", "King", "Kingdon", "Kinkelin", "Kinnamos", "Kinnersley", "Kircher", "Kirchhoff", "Kirkman", "Kirschstein", "Kitab", "Klawdijewitsch", "Klebs", "Klein", "Klemenčič", "Kloor", "Klump", "Kneser", "Knoblauch", "Knoch", "Known", "Knudsen", "Köberle", "Kobilka", "Koch", "Koenig", "Koenigsberger", "Koepsel", "Köhler", "Kohlrausch", "Kohn", "Kohnen", "Kolberg", "Kölreuter", "Kompfner", "König", "Kopans", "Köppen", "Korbuly", "Korkin", "Körner", "Korselt", "Korteweg", "Köstlin", "Kovalevskaya", "Kowalewskaja", "Kraft", "Kramer", "Krauss", "Krauß", "Krauter", "Krazer", "Krebs", "Kress", "Kricfalusi", "Kristelli", "Krochmal", "Kronecker", "Kronke", "Krylow", "KSMG", "Kubach", "Küch", "Kuczynski", "Kugler", "Kuhl", "Kuhn", "Külp", "Kumar", "Kummer", "Kundt", "Kuo", "Kurlbaum", "Kussmaul", "Kuwabara", "Kwang", "Kwolek", "Kyan", "L.", "la", "Labban", "Lacroix", "Lacy", "Ladislav", "Ladwig", "Lafontaine", "Lafresnaye", "Laguerre", "Laidlaw", "Laisant", "Laitman", "Laiyan", "Lal", "Lalande", "Lallemand", "Lallemant", "Lamarck", "Lamarr", "Lamb", "Lamé", "Lamm", "Lamont", "Lampe", "Lamy", "Land", "Landauer", "Landell", "Landgraf", "Landsberg", "Landsteiner", "Lane", "Lang", "Langbein", "Lange", "Langenmantel", "Langguth", "Langley", "Langmuir", "Langsdorf", "Langsdorff", "Lanpo", "Lans", "Lanzavecchia", "Laplace", "Lardner", "Larmor", "Larry", "Lassell", "Laßwitz", "Latimer", "Latin", "Laubier", "Launhardt", "Laurent", "Lautmann", "Laval", "Lawrence", "Lazarsfeld", "Le", "leader", "Leamington", "Lebanon", "Lebedew", "Lebesgue", "Lecher", "Ledley", "Lee", "Lefroy", "Legendre", "Leger", "Léger", "Lehmann", "Lehmus", "Leibniz", "Leiste", "Lejeune", "Lemnios", "Lemoine", "Lenard", "Lennard-Jones", "Lennox", "Lenoir", "Lenormand", "Lenz", "Leon", "Léon", "Leonard", "Léonard", "Lerch", "Leroux", "Lersch", "Leslie", "Lévy", "Lewis", "Lhuilier", "Li", "Liao", "Libri", "Liceti", "Lichtenberg", "Lie", "Liebenthal", "Liebig", "Liebson", "Liedtke", "Liénard", "Lightfoot", "Lilienthal", "Lilly", "Linda", "Lindelöf", "Lindemann", "Lindo", "Lindqvist", "Lindsay", "Linnaeus", "Lino", "Lionel", "Liouville", "Lioy", "Lippmann", "Lipschitz", "Lis", "Lisiecki", "Lisker", "Lisle", "Lissajous", "List", "Lista", "Listing", "Liu", "Ljapunow", "LLD", "Lloyd", "Lo", "Lobatschewski", "Locard", "Lochs", "Lodge", "Loewenherz", "Loewi", "Loewy", "Löffelholz", "Logan", "Lohman", "Lommel", "Loomis", "Lord", "Lorentz", "Lorenz", "Loschmidt", "Louie", "Louis", "Louise", "Louis-Hippolyte", "Louis-Joseph", "Love", "Lovelace", "Lovering", "Löwdin", "Löwenstern-Kunckel", "Lübsen", "Lucas", "Lucien", "Ludvig", "Ludwig", "Luebbers", "Luhmann", "Luís", "Lumer", "Lummer", "Lundmark", "Lüroth", "Lux", "Lwowitsch", "Lykites", "Lykken", "Lyle", "Lymburner", "Lyon", "M.", "MacCullagh", "MacDiarmid", "Macdonald", "Macfarlane", "Mach", "Machura", "Mack", "MacKay", "Mackenzie", "Maclaurin", "MacLean", "MacMahon", "Macquorn", "MacWhinney", "Madan", "Madic", "Madison", "Maestlin", "Magister", "Magnus", "Mahalanobis", "Mahani", "Mahkan", "Mahmoud", "Mahmud", "Mahomet", "Mainardi", "Mairan", "Majid", "Major", "Majriti", "Malaise", "Malherbe", "Mallard", "Malmstén", "Malus", "Mangoldt", "Mansuète", "Mansur", "Manuel", "Mao", "Maqrizi", "Marburger", "Marc", "Marcellino", "March", "Marcus", "Margaret", "Marguerite", "Margulis", "Maria", "Marie", "Markow", "Marmur", "Marrakushi", "Marsh", "Marshall", "Marth", "Martin", "Martin-Löf", "Ma’ruf", "Marum", "Marwazi", "Marx", "Mary", "Maryanoff", "Mascart", "Maschke", "Mash", "Ma’shar", "Mashelkar", "Masihi", "Masquelier", "Masʾūd", "Masudi", "Masuya", "Matar", "Mataré", "Mathematical", "Mathematician", "Mathew", "Mathias", "Mathieu", "Mathur", "Matteucci", "Matthaeus", "Matthew", "Matthews", "Matthiessen", "Maud", "Maude", "Mauderli", "Maududi", "Maupertuis", "Maurice", "Maury", "Mawardi", "Max", "Maximilian", "Maximowitsch", "Maxwell", "Mayer", "Mayr", "MBE", "MC", "MC*", "McCafferty", "McCarthy", "McCarty", "McClintock", "McCollough", "McCormick", "McCrae", "McCrae.", "McFarlane", "McGaugh", "McIndoe", "McKubre", "McLaughlin", "McLean", "McNab", "McNaughton", "Mebel", "Medicinal", "Mehdi", "Mehler", "Mehmke", "Meidinger", "Mei’e", "Meier", "Meighen", "Meinong", "Meissel", "Meitner", "Mejdell", "Melde", "Melitene", "Mellin", "Melloni", "Melveger", "Mendelssohn", "Mendenhall", "Mengchao", "Menger", "Ménière", "Merck", "Merkel", "Merlin", "Merritt", "Mertens", "Mervyn", "Meslin", "Mesmer", "Messerschmidt", "Metallurgical", "Metochites", "Metzner", "Meucci", "Mewburn", "Meyer", "Michael", "Michailowitsch", "Michel", "Michelson", "Micura", "Mikros", "Miletus", "Millard", "Miller", "Milne-Edwards", "Milner", "Minding", "Mindlin", "Minkowski", "Mir", "Mirzakhani", "Mises", "Miskawayh", "Mitchel", "Mitchell", "Mitja", "Mittag-Leffler", "Mitterhofer", "MM", "MM**", "Möbius", "Mohammad", "Mohammed", "Mohmand", "Mohsen", "Moira", "Molecular", "Molien", "Moll", "Moller", "Mollet", "Mollier", "Mollweide", "Monachos", "Monaco", "monarchs", "Monge", "Monika", "Monique", "Monod", "Montgomery", "Montmor", "Moore", "Moosbrugger", "Morera", "Morgagni", "Morgan", "Morgenstern", "Moriarty", "Morin", "Moritz", "Morley", "Moro", "Morrison", "Mortimer", "Moscati", "Moschopulus", "Moser", "Mosharafa", "Mosher", "Mossotti", "most", "Motter", "Motwani", "Moura", "Mousharafa", "Moussa", "Moustafa", "Mouton", "Mozer", "MSC", "MSM", "Muhammad", "Muir", "Müller", "Mullins", "Munke", "Munqidh", "Munro", "Murad", "Murphy", "Murray", "Musa", "Mūsā", "Musabayev", "Musgrave", "Musharafa", "musicians", "Musivand", "Muslim", "Muszaphar", "Mu’taman", "Muwaffak:", "MVO", "Myron", "Mystic-philosopher", "N.", "Nabatiye", "Nagel", "Nahanee", "Nahar", "Nahavandi", "Nahum", "Nappi", "Naqi", "Naqvi", "Narasimha", "Narayana", "Nardelli", "Narlikar", "Nasawi", "Nason", "Nasr", "Nasser", "Nat", "Nath", "Nathan", "Nathusius", "Natterer", "Nau", "Naumann", "Navier", "Nayfeh", "Nayrizi", "nd", "Near", "Nebel", "Negrelli", "Neil", "Nell", "Nelson", "Neophytos", "Netravali", "Netting", "Netto", "Neugebauer", "Neuman", "Neumann", "Neumayer", "Neuner", "Neurath", "new", "Newcomb", "Newhook", "Newton", "Nguyen-Huu", "Nichola", "Nicholas", "Nichols", "Nicol", "Nicolai", "Nicolas", "Nicollet", "Niger", "Nikolajewitsch", "Nishaburi", "no", "Noack", "Noailles", "Nobel", "Nobili", "Noël", "Noether", "Nolfi", "Noll", "Nordenskiöld", "Nordmark", "Norman", "Nörrenberg", "Norris", "North", "Northrop", "North-West", "Norton", "Noulet", "Nowak", "Nuclear", "Nurun", "Nuu-chah-nulth", "Nyberg", "Nye", "O.", "OAA", "OBC", "OBE", "Obermaier", "OC", "OD", "Odlanicki", "Oettingen", "Oettinger", "of", "Ogilvie", "Ohm", "O’Keefe", "O’Leary", "Oliver", "Olivi", "Olov", "Olovolos", "Olshansky", "Olszewski", "Oltmanns", "OM", "OMM", "on", "ONB", "one", "Onnes", "OOnt", "Oppitz", "OQ", "or", "Orchard", "Oriental", "Orshansky", "Ørsted", "Ortmann", "Osann", "Osgood", "Ossian", "Ostell", "Osterloh", "Ostorlabi", "Ostrach", "Ostrogradski", "Ostry", "Otte", "Otto", "Ottokar", "Ottolini", "Öz", "P", "P.", "Paalzow", "Pachymeres", "Packard", "Padé", "Page", "Painlevé", "painters", "pakistan", "Pal", "Palágyi", "Palay", "Palermo", "Palestinian-American", "Palmgren", "Palmieri", "Pandey", "Panitz", "Pantone", "Paoletti", "Papperitz", "Parascandola", "Pariser", "Parish", "Parke", "Parker", "Parrot", "Parseval", "particle", "Particle", "Pascal", "Pasch", "Pasteur", "Patricius", "Patrikios", "Pätsch", "Patterson", "Paul", "Paul-Émile", "Pauli", "Paull", "Pausch", "Payette", "PC", "Peacock", "Peakall", "Peano", "Pearkes", "Pearson", "Peckolt", "Péclet", "Pedersen", "Pediasimos", "Peijian", "Peirce", "Peltier", "Penninger", "Pentland", "Penyngton", "Pepagomenos", "Perkins", "Perlis", "Perlovsky", "Pérot", "Perrin", "Persian", "personalities", "Perutz", "Pete", "Peter", "Peters", "Petersen", "Petit", "Petr", "Petrina", "Petrini", "Petter", "Pettit", "Petzval", "Peyton", "Pezzo", "Pfaff", "Pfaundler", "Pfefferle", "Pfeiffer", "Pferd", "PhD", "Philip", "Philipp", "Philippe", "Phillip", "Phillips", "Philoponus", "Philosopher", "Phong", "Photius", "Phragmén", "physician", "physicist", "Physicist", "Picard", "Pichon", "Pichot", "Pickel", "Pickering", "Pictet", "Piddington", "Pierce", "Pierpont", "Pierre", "Pierre", "Piers", "Pike", "Pinart", "Pincherle", "Pineo", "Piola", "pioneers", "Pirquet", "Pisa", "Pisani", "Pisidis", "Pispers", /* Yes, this is an easter egg. About one in 6 Million names * will be Volker Pispers :) */ "Pitman", "Pixii", "Plana", "Planck", "Planté", "Planudes", "Plateau", "Platen", "Playfair", "Pleijel", "Plendl", "Plötner", "Plücker", "Pochhammer", "Pockels", "Poczobutt", "Podolynskyj", "Poduska", "Poggendorff", "Pohl", "Poincaré", "Poinsot", "Point", "Poiseuille", "Poisson", "Poivre", "Pokrajac", "Pol", "Polhem", "Poli", "Polyakov", "Polycarp", "Pona", "Poncelet", "Pope", "Popow", "Poppe", "Popper", "Porezki", "Porges", "Porsche", "Porta", "Pösch", "Poste", "Postel", "Potrykus", "Potts", "Pouillet", "Pourmand", "Power", "Powers", "Poynting", "Prabhupada", "Prasse", "Pratt", "Pregl", "Prem", "Prescott", "Preston", "Prévost", "Pribram", "Price", "Priestley", "primary", "Pringsheim", "Prinz", "Priscu", "Probstein", "Prodi", "Prodromos", "Professor", "Proteus", "Prout", "Prym", "Psellus", "Pu", "Puch", "Puiseux", "Pullman", "Puluj", "Pupin", "Purity", "Qadeer", "Qavameddin", "Qazvini", "QC", "Quélet", "Quevedo", "Quincke", "Qutb", "R.", "Raabe", "Rabban", "Rabdas", "rabi’a", "Rabl", "Radandt", "radio", "Radon", "Raghava", "Rahman", "RAIC", "Ralston", "Ramachandra", "Ramachandran", "Ramakrishnan", "Raman", "Ramanujan", "Rampone", "Ramsayer", "Ramsey", "Ramsoomair", "Randall", "Randles", "Randolph", "Rangadhama", "Rank", "Rankine", "Ranvier", "Rao", "Raoult", "Raper", "Rapley", "Rapoport", "Raps", "Rashid", "Raskin", "Rattenbury", "Rayhān", "Rayleigh", "Raymond", "Razdan", "Réaumur", "Rebellion", "Rebellion.", "Reber", "Rechtschaffen", "Recknagel", "Red", "Reda", "Reddy", "Reece", "Rees", "Reginald", "Regnault", "Reich", "Reick", "Reiff", "Reinhold", "Reis", "Reiss", "Reitlinger", "religions", "Remez", "Ren", "René", "Rescinded", "Reski", "Resnick", "Ressel", "Reuss", "Reye", "Reynolds", "Rhodes", "Rhyne", "RIBA", "Ribbentrop", "Ricci-Curbastro", "Richard", "Richelot", "Richmond", "Richter", "Richthofen", "Rick", "Rickard", "Riddell", "Ridker", "Ridwan", "Riecke", "Riedl", "Riefler", "Riel.", "Riemann", "Rieß", "Rife", "Righi", "rights", "Ringel", "Rinner", "Rittenhouse", "Ritter", "Ritz", "Riva-Rocci", "Rive", "River", "RNAS", "Robb", "Robbins", "Robert", "Roberts", "Robinet", "Robinson", "Rocco", "Roch", "Rock", "Roden", "Rodrigues", "Rodriguez-Iturbe", "Rodwell", "Roger", "Rogers", "Rogowski", "Rohn", "Rohr", "Romagnosi", "Romano", "Roméo", "Ron", "Röntgen", "Rood", "Rosa", "Rosanes", "Rösch", "Rosemary", "Rosen", "Rosenhain", "Rosin", "Rosnay", "Ross", "Rossby", "Rostam", "Roth", "Rouché", "Rous", "Rouse", "Routh", "Roux", "Rowan", "Rowland", "Roy", "Royal", "Rubens", "Rudbeckius", "Rudio", "Rudolf", "Rudolph", "Ruffin", "Ruffini", "Rugg", "Ruggiero", "Rumpler", "Runge", "Ruoff", "Rusk", "Russell", "Rustah", "Rutherford", "Ruzicka", "Rydberg", "s", "S.", "Saalschütz", "Sabieh", "Sabine", "Sachs", "Sachsen-Weimar-Eisenach", "Sadashiv", "Sadegh-Zadeh", "Sadi", "Sadiq", "Saduq", "Saeed", "Safdie", "Saghani", "Saha", "Sahba", "Sahl", "Sahni", "Sa’id", "Said", "Saint-Venant", "Sajad", "Salam", "Salcher", "Salinger", "Salisbury", "Salman", "Salmon", "Salomo", "Salomon", "Saltzman", "Salviati", "Sam", "Samantha", "Samawal", "Samudrala", "Samuel", "Samuelian", "Sandberger", "Sanders", "Sandford", "Sangro", "Sanli", "Sarabhai", "Sarasin", "Sarrabat", "Sarrus", "Saud", "Savart", "Saverio", "Saxton", "Sayyid", "S.B.", "ScD", "ScDMil", "Schaeffer", "Schäfer-Korting", "Schafhäutl", "Scharrer", "Scheel", "Scheele", "Scheffers", "Scheffler", "Scheidel", "Schering", "Scherk", "Schilling", "Schläfli", "Schlegel", "Schlesinger", "Schlick", "Schlögl", "Schlömilch", "Schmidt", "Schmitt", "Schneider", "scholar", "Scholar", "Schönflies", "Schore", "Schott", "Schottky", "Schoute", "Schrader", "Schröder", "Schrödinger", "Schröter", "Schrötter", "Schubert", "Schukowski", "Schultz-Hencke", "Schumow", "Schumpeter", "Schur", "Schuster", "Schwabe", "Schwartz", "Schwarz", "Schwarzkopf", "Schwarzschild", "Schwehm", "Schweigger", "Schweikart", "Schwerd", "Scott", "Sealy", "Seaney", "Searle", "Sebastian", "Sébastien", "Second", "Secretary", "section", "see", "See", "Seebeck", "Seelman", "Seelmann-Eggebert", "Seely", "Sefström", "Segner", "Segre", "Seidel", "Seinfeld", "Seliwanow", "Sellmann", "Sellow", "Selwyn", "Selye", "Seminara", "Semmelweis", "Semple", "Sen", "Senefelder", "senior", "Serafin", "Seraji", "Sergejewitsch", "Serret", "Servais", "Seth", "Sewid", "Seykota", "S-H", "Shākir", "Shalom", "Shankar", "Shanks", "Shanlan", "Sharif", "Sheila", "Shermer", "Shettles", "Shetty", "Shihkao", "Shirazi", "Shonglin", "Short", "Shu-hua", "Shujā", "Shukla", "Shukor", "Shull", "Shuster", "Siacci", "Sibener", "Siddiqui", "Sidney", "Siegbahn", "Sigismund", "Sigmund", "Sijzi", "Sikelos", "Silberschlag", "Siliciano", "Sim", "Šimerka", "Simon", "Simon", "Simonds", "Simpson", "Sina", "Singer", "Singh", "Sinsteden", "Sir", "Sirin", "Sixun", "Slobodkin", "Small", "Smith", "Smoluchowski", "Snell", "Śniadecki", "Sohncke", "Sokal", "Solander", "Soldner", "Solotarjow", "SOM", "Somerville", "Sommaja", "Sommer", "Sömmerring", "Song", "Sorby", "Soret", "Spallanzani", "Spangler", "Spann", "Sparks", "Spaun", "Spertzel", "Spiegelman", "Spottiswoode", "Sprengel", "Sr.", "St.", "Stäckel", "Stahl", "Stampfer", "Stan", "Stanfield", "Stanhope", "Stanley", "Stanton", "Starkey", "Starzl", "States", "Staude", "Staudt", "Stawell", "Stebbins", "Steere", "Stefan", "Steglich", "Steiner", "Steinheil", "Steinitz", "Steinmetz", "Stepanowitsch", "Stephan", "Stephen", "Stern", "Sternberg", "Stetter", "Steve", "Steven", "Stevens", "Stewart", "Stickelberger", "Stieltjes", "Stirling", "Stoecker", "Stokes", "Stoletow", "Stolz", "Stone", "Stoney", "Størmer", "Stott", "Stowell", "Stradonitz", "Streintz", "Stresemann", "Strouhal", "Strutt", "Stuart", "Study", "Stulić", "Sturgeon", "Sturm", "Styles", "Subbarao", "Subra", "Succow", "Sue", "Sufi", "Suleyman", "Sultan", "Summers", "Sung-Hou", "Superti-Furga", "Süring", "Suryal", "Svedberg", "Swami", "Swan", "Swarup", "Sweeney", "Swetnam", "Sydney", "Syed", "Sykes", "Sylow", "Sylvester", "Systems", "Szarvassi", "Szep", "T.", "Tabari", "Tabib", "Tabrizi", "Tahir", "Tait", "taken", "Tamimi", "Tammann", "Tank", "Tannery", "Tardieu", "Tāriq", "Taurinus", "Tawfik", "Taylor", "Taymiyyah", "Teixeira", "television", "Temple", "Templeton", "Ten", "Tenchini", "Tengmalm", "Terry", "Tesla", "Tessmann", "Tetrode", "th", "Thaer", "Thalén", "Thanikaimoni", "the", "The", "Theimer", "Theodor", "Theodore", "Theophilus", "Theorell", "Theoretical", "Thérèse", "Thessalonica", "Thévenot", "Thibaut", "Thiele", "Thiéry", "Thilorier", "Thirsk", "Thom", "Thomae", "Thomas", "Thompson", "Thomson", "Thon", "Thorp", "Thuan", "Thue", "Thuma", "Tiedjens", "Tietze", "Tillberg", "Tim", "Timberell", "time.", "Timothy", "Tinsley", "Tisserand", "to", "Tobias", "Todhunter", "Toepler", "Tolba", "Tolver", "Tommy", "Tordoff", "Torres", "Torricelli", "Tosti", "Townsend", "Tralles", "traveler", "Treadwell", "Trebizond", "Trentel", "Trésaguet", "Treviranus", "Triclinius", "Trist", "Trouton", "Trudel", "Truetttley", "Tryggvason", "Tschebyschow", "Tseng", "Tsien", "Tsou", "Tufail", "Tường", "Turk", "Turner", "Turowicz", "Turton", "Tusi", "Tuve", "Tuzo", "Tyndall", "ud-Din", "Ude", "ul", "Ulbricht", "ul-din", "Ulrich", "Umpfenbach", "Umpleby", "Underwood", "Unger", "United", "Upton", "Uqlidisi", "Urdi", "Usmani", "Uvarov", "uz-Zaman", "V.", "Vafa", "Vahlen", "Val", "Valier", "Vallisneri", "Valsamon", "van", "Van", "Varshney", "Vaschy", "Vatvat", "VC", "Veillon", "Veranzio", "Verdet", "Verhulst", "Vernon", "Veronese", "Verrier", "Verschaffelt", "Vessiot", "VI", "Victor", "Vidius", "Vieillot", "Vietoris", "VII", "Villard", "Violle", "Virchow", "Viskanta", "Visvesvaraya", "Vitullo", "vizier", "Vo-Dinh", "Voelkner", "Vogel", "Voigt", "Vokes", "Volkman", "Volkmer", "Vollmer", "Volterra", "voluminous", "vom", "von", "Vonderlinn", "Voss", "Vries", "Vryennios", "Vyzantinos", "Vyzantios", "W.", "Waals", "Wachter", "Wade", "Waetzmann", "Wafa", "Wagih", "Wagman", "Wagner", "Wagner-Jauregg", "Wahab", "Wai-Ling", "Waismann", "Walckenaer", "Wald", "Walenta", "Walfrid", "Walker", "Wallace", "Wallenberg", "Waltenhofen", "Walter", "Walton", "Waly", "Wang", "Wangerin", "Wani", "Wansink", "Wantzel", "Warburg", "Ward", "Warner", "Warwick", "Wassiljewna", "Waterston", "Watson", "Watt", "Wattenberg", "Wattenwyl", "Watzlawick", "Weber", "Webster", "Wegener", "Wehnelt", "Weibull", "Weierstraß", "Weihan", "Weingarten", "Weinhold", "Weininger", "Weir", "Weisbach", "Weiss", "Weisskopf", "Weiszmann", "Wei-zang", "Welbourn", "Welker", "Wellington", "Wells", "Welsbach", "Welskopf-Henrich", "Wen", "Wendell", "Wendt", "Wenhao", "Wenström", "Wentworth", "Wentzel", "Wenzhong", "Werbos", "West", "Westbrook", "Westphal", "Weyer", "Weyr", "Whalen", "Wheatstone", "Wheeler", "Whitbread", "White", "Whitlow", "Whitney", "Wickner", "Wicks", "Widdowson", "Widnall", "Wiedemann", "Wiegand", "Wieghardt", "Wien", "Wiener", "Wiese", "Wieser", "Wijthoff", "Wikipedia", "Wilbanks", "Wilbur", "Wild", "Wilder", "Wiley", "Wilfred", "Wilhelm", "Wilkins", "Wilkinson", "Willard", "William", "Willis", "Williston", "Willman", "Willson", "Wilson", "Wiltheiss", "Wilton", "Wiman", "Wingquist", "Winkelmann", "Winkelstein", "Winkler", "Winslow", "Winter", "Wise", "with", "Withers", "Wittgenstein", "Witting", "Wlassak", "Woese", "Wold", "Wolf", "Wolff", "Wolffgramm", "Wolfgang", "Wolfrum", "Wolfskehl", "Wollaston", "Wolstenholme", "women’s", "Wong-Staal", "Wood", "Woodhouse", "Woodruff", "Woods", "Woodward", "Woolsey", "Wöpcke", "Woronoi", "Worpitzky", "Wratt", "Wright", "writers", "Wrobel", "Wróblewski", "Wronski", "wrote", "Wu", "Wüllner", "Wurman", "Würschmitt", "Wushmgir", "Wybe", "X.", "Xaver", "Xianghua", "Xiantu", "Xiaogang", "XII", "Xijin", "Ximing", "Xing", "Xitao", "Xuan", "Xuejing", "Y.", "Yafeng", "Yang", "Yaruss", "Yazami", "Yazdi", "Yazid", "Yeates", "Yener", "Yeo", "Yingxing", "Yize", "Yockey", "Yogore", "Yongzhi", "You", "Young", "Yousaf", "Yu", "Yuen", "Yuhanna", "Yunus", "Yusef", "Yusuf", "Yūsuf", "Yves", "Z.", "Zacharias", "Zāda", "Zadeh", "Zahn", "Zahran", "Zahrawi", "Zakerian", "Zamboni", "Zamecnik", "Zantedeschi", "Zayn", "Zehnder", "Zeilinger", "Zeller", "Zeuthen", "Zevelinos", "Zewail", "Zhan", "Zhen", "Zhengtang", "Zhongcheng", "Zhongjian", "Zhongli", "Zhou", "Ziaur", "Zijerdi", "Zillmer", "Zillur", "Zindel", "Zindler", "Zippe", "Ziyuan", "Zoch", "Zöllner", "Zonaras", "zoologist", "Zöppritz", "Zoretti", "Zsigmondy", "Zuberbier", "Zuckermandel", "Zuhr", "Zülicke", "Zwicker", "اخوان", "الصفا", "الوفا", "وخلان"}; /** Generate a Name. */ static public String newNameBase(String seperator){ StringBuffer name = new StringBuffer(); Random rand = new Random(); String nextpart = new String(firstnames[rand.nextInt(firstnames.length)]); name.append(nextpart); name.append(seperator); nextpart = lastnames[rand.nextInt(lastnames.length)]; name.append(nextpart); /* Append nameparts as long as the last part is either not * sensible (ends with . [middle name] or is ibn ["son of"] or * is just 1 letter) or you roll 1 on a die :) */ - while (nextpart.endsWith(".") || nextpart == "ibn" || nextpart == seperator || nextpart == "al" || rand.nextInt(6) == 1){ + while (nextpart.endsWith(".") || "ibn".equals(nextpart) || seperator.equals(nextpart) || "al".equals(nextpart) || rand.nextInt(6) == 1){ name.append(seperator); nextpart = lastnames[rand.nextInt(lastnames.length)]; name.append(nextpart); } return name.toString(); }; /** Generate a Name. */ static public String newName(){ return newNameBase(" "); }; /** Generate a Nickname: No spaces. */ static public String newNickname(){ return newNameBase("_"); }; /** Generate a new name without protected spaces. */ static public String newUnprotectedName(){ return newNameBase(" "); }; }
true
true
static public String newNameBase(String seperator){ StringBuffer name = new StringBuffer(); Random rand = new Random(); String nextpart = new String(firstnames[rand.nextInt(firstnames.length)]); name.append(nextpart); name.append(seperator); nextpart = lastnames[rand.nextInt(lastnames.length)]; name.append(nextpart); /* Append nameparts as long as the last part is either not * sensible (ends with . [middle name] or is ibn ["son of"] or * is just 1 letter) or you roll 1 on a die :) */ while (nextpart.endsWith(".") || nextpart == "ibn" || nextpart == seperator || nextpart == "al" || rand.nextInt(6) == 1){ name.append(seperator); nextpart = lastnames[rand.nextInt(lastnames.length)]; name.append(nextpart); } return name.toString(); };
static public String newNameBase(String seperator){ StringBuffer name = new StringBuffer(); Random rand = new Random(); String nextpart = new String(firstnames[rand.nextInt(firstnames.length)]); name.append(nextpart); name.append(seperator); nextpart = lastnames[rand.nextInt(lastnames.length)]; name.append(nextpart); /* Append nameparts as long as the last part is either not * sensible (ends with . [middle name] or is ibn ["son of"] or * is just 1 letter) or you roll 1 on a die :) */ while (nextpart.endsWith(".") || "ibn".equals(nextpart) || seperator.equals(nextpart) || "al".equals(nextpart) || rand.nextInt(6) == 1){ name.append(seperator); nextpart = lastnames[rand.nextInt(lastnames.length)]; name.append(nextpart); } return name.toString(); };
diff --git a/src/com/bzapps/personalProBeta/PersonalProBeta.java b/src/com/bzapps/personalProBeta/PersonalProBeta.java index 2af2829..a597e7c 100644 --- a/src/com/bzapps/personalProBeta/PersonalProBeta.java +++ b/src/com/bzapps/personalProBeta/PersonalProBeta.java @@ -1,36 +1,34 @@ /* 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 com.bzapps.personalProBeta; import android.os.Bundle; import org.apache.cordova.*; public class PersonalProBeta extends DroidGap { @Override public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - // Set by <content src="index.html" /> in config.xml - super.loadUrl(Config.getStartUrl()); - //super.loadUrl("file:///android_asset/www/index.html") + super.onCreate(savedInstanceState); + super.loadUrl("file:///android_asset/www/index.html"); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set by <content src="index.html" /> in config.xml super.loadUrl(Config.getStartUrl()); //super.loadUrl("file:///android_asset/www/index.html") }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.loadUrl("file:///android_asset/www/index.html"); }
diff --git a/src/main/java/nl/lolmen/sortal/SPlayerListener.java b/src/main/java/nl/lolmen/sortal/SPlayerListener.java index fc0e435..86f02fb 100644 --- a/src/main/java/nl/lolmen/sortal/SPlayerListener.java +++ b/src/main/java/nl/lolmen/sortal/SPlayerListener.java @@ -1,316 +1,319 @@ package nl.lolmen.sortal; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import net.milkbowl.vault.economy.Economy; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.plugin.RegisteredServiceProvider; public class SPlayerListener implements Listener{ public Main plugin; public SPlayerListener(Main main){ plugin = main; } @EventHandler(priority = EventPriority.NORMAL) public void onPlayerInteract(PlayerInteractEvent event){ Player p = event.getPlayer(); Action a = event.getAction(); if(a.equals(Action.LEFT_CLICK_BLOCK)){ if(leftClick(p, event.getClickedBlock())){ event.setCancelled(true); } return; } if(!a.equals(Action.RIGHT_CLICK_BLOCK)){ return; } Block b = event.getClickedBlock(); if(b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN){ Sign s = (Sign)b.getState(); String[] lines = s.getLines(); if(lines[0].equalsIgnoreCase(plugin.signContains) || lines[0].equalsIgnoreCase("[Sortal]")){ if(event.getPlayer().hasPermission("sortal.warp")){ String line2 = lines[1]; if(line2.startsWith("w:")){ String[] split = line2.split(":"); String warp = split[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This warp does not exist!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p, d)){ return; } d.getWorld().getChunkAt((int)d.getX(), (int)d.getZ()).load(); if(d.getWorld().equals(p.getLocation().getWorld())){ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); }else{ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getX())); //teleport to that world --\/ Teleport to exact location p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); } p.sendMessage("You teleported to " + ChatColor.RED + d.warp() +"!"); }else{ if(line2.contains(",")){ Warp d = new Warp(plugin); if(!pay(p,d)){ return; } String[] split = line2.split(","); if(split.length == 3){ //No world specified, using Players World if(isInt(split[0]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); Location loc = new Location(p.getWorld(), x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } if(split.length == 4){ //World specified. Probally. if(isInt(split[3]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); World world = plugin.getServer().getWorld(split[0]); Location loc = new Location(world, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } }else{ //Has [Sortal], but not w: or a , in secondline. p.sendMessage("[Sortal] There's something wrong with this sign.."); } } }else{ p.sendMessage(plugin.noPerm); } }else if(lines[1].equalsIgnoreCase(plugin.signContains) || lines[1].equalsIgnoreCase("[sortal]")){ if(event.getPlayer().hasPermission("sortal.warp")){ String line2 = lines[2]; if(line2.startsWith("w:")){ String[] split = line2.split(":"); String warp = split[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This warp does not exist!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p,d)){ return; } d.getWorld().getChunkAt((int)d.getX(), (int)d.getZ()).load(); if(d.getWorld().equals(p.getLocation().getWorld())){ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); }else{ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ())); p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); } p.sendMessage("You teleported to " + ChatColor.RED + d.warp()); }else{ if(line2.contains(",")){ String[] split = line2.split(","); if(split.length == 3){ //No world specified, using Players World if(isInt(split[0]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); Location loc = new Location(p.getWorld(), x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } if(split.length == 4){ //World specified. Probally. if(isInt(split[3]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); World world = plugin.getServer().getWorld(split[0]); Location loc = new Location(world, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } } } } }else{ if(event.getPlayer().hasPermission("sortal.warp")){ Location c = new Location(b.getWorld(), b.getX(), b.getY(), b.getZ()); if(plugin.loc.containsKey(c)){ String warp = plugin.loc.get(c); if(!plugin.warp.containsKey(warp)){ p.sendMessage("[Sortal] This sign pointer is broken! Ask an Admin to fix it!"); return; } Warp d = plugin.warp.get(warp); + if(!pay(p,d)){ + return; + } Location goo = new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch()); goo.getChunk().load(); if(d.getWorld().equals(p.getWorld())){ p.teleport(goo); }else{ p.teleport(goo); p.teleport(goo); } p.sendMessage("You teleported to " + ChatColor.RED + warp + "!"); } } } } } public boolean isInt(String i){ try{ Integer.parseInt(i); return true; }catch(NumberFormatException e){ return false; } } private boolean leftClick(Player p, Block b) { if(plugin.register.containsKey(p)){ String warp = plugin.register.get(p); try{ Properties prop = new Properties(); FileInputStream in = new FileInputStream(plugin.locs); prop.load(in); prop.setProperty(b.getWorld().getName() +"," + Integer.toString(b.getX()) +"," + Integer.toString(b.getY()) + "," + Integer.toString(b.getZ()), warp); FileOutputStream out = new FileOutputStream(plugin.locs); prop.store(out, "[World],[X],[Y],[Z]=[Warpname]"); out.flush(); out.close(); in.close(); plugin.loc.put(b.getLocation(), warp); }catch(IOException e){ e.printStackTrace(); } plugin.register.remove(p); p.sendMessage("Registered!"); return true; } if(plugin.cost.containsKey(p)){ int cost = plugin.cost.get(p); if(b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN){ Sign s = (Sign)b.getState(); Location loc = b.getLocation(); if(plugin.loc.containsKey(loc)){ //Sign is a registered one. String warp = plugin.loc.get(loc); if(plugin.warp.containsKey(warp)){ Warp d = plugin.warp.get(warp); d.setCost(cost); p.sendMessage("Cost set to " + ChatColor.RED + Integer.toString(cost) + "!"); plugin.cost.remove(p); }else{ p.sendMessage("This sign has been registered, but it's pointing to a non-existing warp!"); } }else{ String[] lines = s.getLines(); if(lines[0].equalsIgnoreCase(plugin.signContains) || lines[0].equalsIgnoreCase("[Sortal]")){ String line2 = lines[1]; if(line2.contains("w:")){ String[] splot = line2.split(":"); String warp = splot[1]; Warp d = plugin.warp.get(warp); d.setCost(cost); p.sendMessage("Cost set to " + ChatColor.RED + Integer.toString(cost) + "!"); plugin.cost.remove(p); } }else if(lines[1].equalsIgnoreCase(plugin.signContains) || lines[1].equalsIgnoreCase("[Sortal]")){ String line2 = lines[2]; if(line2.contains("w:")){ String[] splot = line2.split(":"); String warp = splot[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This sign is pointing to " +ChatColor.RED + warp +ChatColor.WHITE + ", a non-existant warp!"); } Warp d = plugin.warp.get(warp); d.setCost(cost); p.sendMessage("Cost set to " + ChatColor.RED + Integer.toString(cost) + "!"); plugin.cost.remove(p); } }else{ p.sendMessage("This sign is not usable for setting a price!"); } } }else{ p.sendMessage("[Sortal] This is not a sign, cannot set cost!"); } return true; } if(plugin.unreg.contains(p)){ if(plugin.loc.containsKey(b.getLocation())){ try { Properties prop = new Properties(); prop.load(new FileInputStream(plugin.locs)); prop.remove(b.getLocation()); prop.store(new FileOutputStream(plugin.locs), "[Location] = [Name]"); p.sendMessage("Deletion completed!"); plugin.unreg.remove(p); plugin.loc.remove(b.getLocation()); } catch (Exception e) { e.printStackTrace(); p.sendMessage("Something went wrong while deleting the warp. :O"); } }else{ p.sendMessage("This sign is not registered!"); } return true; } return false; } public boolean pay(Player p, Warp d) { if(!plugin.useVault){ return true; } Economy econ; RegisteredServiceProvider<Economy> rsp = plugin.getServer().getServicesManager().getRegistration(Economy.class); if(rsp == null){ return true; //No Vault found } econ = rsp.getProvider(); if(econ == null){ return true; //No Vault found } int money = d.getCost(); if(money == 0){ return true; } if(!econ.has(p.getName(), money)){ return false; } econ.withdrawPlayer(p.getName(), money); p.sendMessage("Withdrawing " + econ.format(money) + " from your account!"); return true; } }
true
true
public void onPlayerInteract(PlayerInteractEvent event){ Player p = event.getPlayer(); Action a = event.getAction(); if(a.equals(Action.LEFT_CLICK_BLOCK)){ if(leftClick(p, event.getClickedBlock())){ event.setCancelled(true); } return; } if(!a.equals(Action.RIGHT_CLICK_BLOCK)){ return; } Block b = event.getClickedBlock(); if(b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN){ Sign s = (Sign)b.getState(); String[] lines = s.getLines(); if(lines[0].equalsIgnoreCase(plugin.signContains) || lines[0].equalsIgnoreCase("[Sortal]")){ if(event.getPlayer().hasPermission("sortal.warp")){ String line2 = lines[1]; if(line2.startsWith("w:")){ String[] split = line2.split(":"); String warp = split[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This warp does not exist!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p, d)){ return; } d.getWorld().getChunkAt((int)d.getX(), (int)d.getZ()).load(); if(d.getWorld().equals(p.getLocation().getWorld())){ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); }else{ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getX())); //teleport to that world --\/ Teleport to exact location p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); } p.sendMessage("You teleported to " + ChatColor.RED + d.warp() +"!"); }else{ if(line2.contains(",")){ Warp d = new Warp(plugin); if(!pay(p,d)){ return; } String[] split = line2.split(","); if(split.length == 3){ //No world specified, using Players World if(isInt(split[0]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); Location loc = new Location(p.getWorld(), x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } if(split.length == 4){ //World specified. Probally. if(isInt(split[3]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); World world = plugin.getServer().getWorld(split[0]); Location loc = new Location(world, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } }else{ //Has [Sortal], but not w: or a , in secondline. p.sendMessage("[Sortal] There's something wrong with this sign.."); } } }else{ p.sendMessage(plugin.noPerm); } }else if(lines[1].equalsIgnoreCase(plugin.signContains) || lines[1].equalsIgnoreCase("[sortal]")){ if(event.getPlayer().hasPermission("sortal.warp")){ String line2 = lines[2]; if(line2.startsWith("w:")){ String[] split = line2.split(":"); String warp = split[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This warp does not exist!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p,d)){ return; } d.getWorld().getChunkAt((int)d.getX(), (int)d.getZ()).load(); if(d.getWorld().equals(p.getLocation().getWorld())){ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); }else{ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ())); p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); } p.sendMessage("You teleported to " + ChatColor.RED + d.warp()); }else{ if(line2.contains(",")){ String[] split = line2.split(","); if(split.length == 3){ //No world specified, using Players World if(isInt(split[0]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); Location loc = new Location(p.getWorld(), x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } if(split.length == 4){ //World specified. Probally. if(isInt(split[3]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); World world = plugin.getServer().getWorld(split[0]); Location loc = new Location(world, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } } } } }else{ if(event.getPlayer().hasPermission("sortal.warp")){ Location c = new Location(b.getWorld(), b.getX(), b.getY(), b.getZ()); if(plugin.loc.containsKey(c)){ String warp = plugin.loc.get(c); if(!plugin.warp.containsKey(warp)){ p.sendMessage("[Sortal] This sign pointer is broken! Ask an Admin to fix it!"); return; } Warp d = plugin.warp.get(warp); Location goo = new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch()); goo.getChunk().load(); if(d.getWorld().equals(p.getWorld())){ p.teleport(goo); }else{ p.teleport(goo); p.teleport(goo); } p.sendMessage("You teleported to " + ChatColor.RED + warp + "!"); } } } } }
public void onPlayerInteract(PlayerInteractEvent event){ Player p = event.getPlayer(); Action a = event.getAction(); if(a.equals(Action.LEFT_CLICK_BLOCK)){ if(leftClick(p, event.getClickedBlock())){ event.setCancelled(true); } return; } if(!a.equals(Action.RIGHT_CLICK_BLOCK)){ return; } Block b = event.getClickedBlock(); if(b.getType() == Material.SIGN_POST || b.getType() == Material.WALL_SIGN || b.getType() == Material.SIGN){ Sign s = (Sign)b.getState(); String[] lines = s.getLines(); if(lines[0].equalsIgnoreCase(plugin.signContains) || lines[0].equalsIgnoreCase("[Sortal]")){ if(event.getPlayer().hasPermission("sortal.warp")){ String line2 = lines[1]; if(line2.startsWith("w:")){ String[] split = line2.split(":"); String warp = split[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This warp does not exist!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p, d)){ return; } d.getWorld().getChunkAt((int)d.getX(), (int)d.getZ()).load(); if(d.getWorld().equals(p.getLocation().getWorld())){ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); }else{ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getX())); //teleport to that world --\/ Teleport to exact location p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); } p.sendMessage("You teleported to " + ChatColor.RED + d.warp() +"!"); }else{ if(line2.contains(",")){ Warp d = new Warp(plugin); if(!pay(p,d)){ return; } String[] split = line2.split(","); if(split.length == 3){ //No world specified, using Players World if(isInt(split[0]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); Location loc = new Location(p.getWorld(), x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } if(split.length == 4){ //World specified. Probally. if(isInt(split[3]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); World world = plugin.getServer().getWorld(split[0]); Location loc = new Location(world, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } }else{ //Has [Sortal], but not w: or a , in secondline. p.sendMessage("[Sortal] There's something wrong with this sign.."); } } }else{ p.sendMessage(plugin.noPerm); } }else if(lines[1].equalsIgnoreCase(plugin.signContains) || lines[1].equalsIgnoreCase("[sortal]")){ if(event.getPlayer().hasPermission("sortal.warp")){ String line2 = lines[2]; if(line2.startsWith("w:")){ String[] split = line2.split(":"); String warp = split[1]; if(!plugin.warp.containsKey(warp)){ p.sendMessage("This warp does not exist!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p,d)){ return; } d.getWorld().getChunkAt((int)d.getX(), (int)d.getZ()).load(); if(d.getWorld().equals(p.getLocation().getWorld())){ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); }else{ p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ())); p.teleport(new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch())); } p.sendMessage("You teleported to " + ChatColor.RED + d.warp()); }else{ if(line2.contains(",")){ String[] split = line2.split(","); if(split.length == 3){ //No world specified, using Players World if(isInt(split[0]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[0]); int y = Integer.parseInt(split[1]); int z = Integer.parseInt(split[2]); Location loc = new Location(p.getWorld(), x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } if(split.length == 4){ //World specified. Probally. if(isInt(split[3]) && isInt(split[1]) && isInt(split[2])){ int x = Integer.parseInt(split[1]); int y = Integer.parseInt(split[2]); int z = Integer.parseInt(split[3]); World world = plugin.getServer().getWorld(split[0]); Location loc = new Location(world, x, y, z, p.getLocation().getYaw(), p.getLocation().getPitch()); loc.getChunk().load(); p.teleport(loc); p.sendMessage("You teleported to " + ChatColor.RED + line2 + "!"); } } } } } }else{ if(event.getPlayer().hasPermission("sortal.warp")){ Location c = new Location(b.getWorld(), b.getX(), b.getY(), b.getZ()); if(plugin.loc.containsKey(c)){ String warp = plugin.loc.get(c); if(!plugin.warp.containsKey(warp)){ p.sendMessage("[Sortal] This sign pointer is broken! Ask an Admin to fix it!"); return; } Warp d = plugin.warp.get(warp); if(!pay(p,d)){ return; } Location goo = new Location(d.getWorld(), d.getX(), d.getY(), d.getZ(), p.getLocation().getYaw(), p.getLocation().getPitch()); goo.getChunk().load(); if(d.getWorld().equals(p.getWorld())){ p.teleport(goo); }else{ p.teleport(goo); p.teleport(goo); } p.sendMessage("You teleported to " + ChatColor.RED + warp + "!"); } } } } }
diff --git a/src/visualizer/LoadProcessing.java b/src/visualizer/LoadProcessing.java index 2b17d12..67db31a 100644 --- a/src/visualizer/LoadProcessing.java +++ b/src/visualizer/LoadProcessing.java @@ -1,168 +1,168 @@ package visualizer; import java.awt.AWTException; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.WindowConstants; import net.coobird.thumbnailator.Thumbnails; @SuppressWarnings("unused") public class LoadProcessing { JFrame welcomeFrame; JButton nextButton; int diffW, diffH, newDiffW, newDiffH; boolean adjustX = false; float ratio; public static int[] getPixelRGB(int pixel) { int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = (pixel) & 0xff; return new int[] {red, green, blue}; } public static int getPixelSum(int pixel){ int[] pixArray = getPixelRGB(pixel); return pixArray[0] + pixArray[1] + pixArray[2]; } public void getEdges(String filename, String nameExt, int index, File[] files, float lowThres, float highThres) throws IOException { // Get size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Get the image BufferedImage image = ImageIO.read( new File( filename ) ); // EDGE DETECTION visualizer.CannyEdgeDetector detector = new visualizer.CannyEdgeDetector(); detector.setLowThreshold(lowThres); detector.setHighThreshold(highThres); detector.setSourceImage(image); detector.process(); BufferedImage edges = detector.getEdgesImage(); File outputfile = new File("image" + nameExt + ".jpg"); ImageIO.write(edges, "jpg", outputfile); } public void loadProcessing(String filename, String nameExt, int index, File[] files, float lowThres, float highThres) throws IOException { - // Get size of the screen - Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); + // Get size of the screen + Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Get the image BufferedImage image = ImageIO.read( new File( filename ) ); // EDGE DETECTION visualizer.CannyEdgeDetector detector = new visualizer.CannyEdgeDetector(); detector.setLowThreshold(lowThres); detector.setHighThreshold(highThres); detector.setSourceImage(image); detector.process(); BufferedImage edges = detector.getEdgesImage(); // print the dimensions of the photo int startW = edges.getWidth(); int startH = edges.getHeight(); System.out.println(startW); System.out.println(startH); float ratio = 1; // Difference in image vs screen size diffW = dim.width - startW; - diffH = dim.height - startH; + diffH = dim.height - startH; - // Creates ratio to scale the image up or down - if (diffW < diffH) { - ratio = dim.width/startW; - } - else { - ratio = dim.height/startH; - } + // Creates ratio to scale the image up or down + if (diffW < diffH) { + ratio = dim.width/ (float) startW; + } + else { + ratio = dim.height/ (float) startH; + } System.out.println(ratio); int newW = Math.round(startW * ratio); int newH = Math.round(startH * ratio); System.out.println(newW); System.out.println(newH); newDiffW = dim.width - newW; newDiffH = dim.height - newH; if (newDiffW > newDiffH) { adjustX = true; newDiffW /= 2; } else { newDiffH /= 2; } // attempted cropping that's currently not doing anything // TODO set up cropping/resizing BufferedImage thumb = Thumbnails.of(edges).size(newW, newH).asBufferedImage(); BufferedImage orig = Thumbnails.of(image).size(newW, newH).asBufferedImage(); File outputfile = new File("image" + nameExt + ".jpg"); ImageIO.write(edges, "jpg", outputfile); PrintStream out = new PrintStream(new FileOutputStream("particles" + nameExt + ".txt")); System.setOut(out); out.println(newW + " " + newH); // get the colors for each coordinate in the file for( int i = 0; i < thumb.getWidth(); i++ ) for( int j = 0; j < thumb.getHeight(); j++ ){ int pix = thumb.getRGB( i, j ); int colorPix = orig.getRGB( i, j ); if (getPixelSum(pix) > 25){ int[] pixArray = getPixelRGB(colorPix); String tup = "(" + pixArray[0] + ", " + pixArray[1] + ", " + pixArray[2] + ")"; String coord = ""; // Move image horizontally to the center if (adjustX) { coord = (i + newDiffW) + " " + j + " " + tup; } // Move image vertically to the center else { coord = i + " " + (j + newDiffH) + " " + tup; } out.println(coord); } } out.close(); if (index < (files.length - 1)) { EdgeDetectFlow walkthrough = new EdgeDetectFlow(files[index + 1].getAbsolutePath(), Integer.toString(index + 1), index + 1, files); walkthrough.determineEdgeDetect(Integer.toString(index + 1)); } else { // MAYBE THE SOLUTION processing.core.PApplet sketch = new Sketch(); processing.core.PApplet.main(new String[] {"--present", "visualizer.Sketch"}); } } public void useDefaultImages() { processing.core.PApplet sketch = new Sketch(); processing.core.PApplet.main(new String[] {"--present", "visualizer.Sketch"}); } }
false
true
public void loadProcessing(String filename, String nameExt, int index, File[] files, float lowThres, float highThres) throws IOException { // Get size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Get the image BufferedImage image = ImageIO.read( new File( filename ) ); // EDGE DETECTION visualizer.CannyEdgeDetector detector = new visualizer.CannyEdgeDetector(); detector.setLowThreshold(lowThres); detector.setHighThreshold(highThres); detector.setSourceImage(image); detector.process(); BufferedImage edges = detector.getEdgesImage(); // print the dimensions of the photo int startW = edges.getWidth(); int startH = edges.getHeight(); System.out.println(startW); System.out.println(startH); float ratio = 1; // Difference in image vs screen size diffW = dim.width - startW; diffH = dim.height - startH; // Creates ratio to scale the image up or down if (diffW < diffH) { ratio = dim.width/startW; } else { ratio = dim.height/startH; } System.out.println(ratio); int newW = Math.round(startW * ratio); int newH = Math.round(startH * ratio); System.out.println(newW); System.out.println(newH); newDiffW = dim.width - newW; newDiffH = dim.height - newH; if (newDiffW > newDiffH) { adjustX = true; newDiffW /= 2; } else { newDiffH /= 2; } // attempted cropping that's currently not doing anything // TODO set up cropping/resizing BufferedImage thumb = Thumbnails.of(edges).size(newW, newH).asBufferedImage(); BufferedImage orig = Thumbnails.of(image).size(newW, newH).asBufferedImage(); File outputfile = new File("image" + nameExt + ".jpg"); ImageIO.write(edges, "jpg", outputfile); PrintStream out = new PrintStream(new FileOutputStream("particles" + nameExt + ".txt")); System.setOut(out); out.println(newW + " " + newH); // get the colors for each coordinate in the file for( int i = 0; i < thumb.getWidth(); i++ ) for( int j = 0; j < thumb.getHeight(); j++ ){ int pix = thumb.getRGB( i, j ); int colorPix = orig.getRGB( i, j ); if (getPixelSum(pix) > 25){ int[] pixArray = getPixelRGB(colorPix); String tup = "(" + pixArray[0] + ", " + pixArray[1] + ", " + pixArray[2] + ")"; String coord = ""; // Move image horizontally to the center if (adjustX) { coord = (i + newDiffW) + " " + j + " " + tup; } // Move image vertically to the center else { coord = i + " " + (j + newDiffH) + " " + tup; } out.println(coord); } } out.close(); if (index < (files.length - 1)) { EdgeDetectFlow walkthrough = new EdgeDetectFlow(files[index + 1].getAbsolutePath(), Integer.toString(index + 1), index + 1, files); walkthrough.determineEdgeDetect(Integer.toString(index + 1)); } else { // MAYBE THE SOLUTION processing.core.PApplet sketch = new Sketch(); processing.core.PApplet.main(new String[] {"--present", "visualizer.Sketch"}); } }
public void loadProcessing(String filename, String nameExt, int index, File[] files, float lowThres, float highThres) throws IOException { // Get size of the screen Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Get the image BufferedImage image = ImageIO.read( new File( filename ) ); // EDGE DETECTION visualizer.CannyEdgeDetector detector = new visualizer.CannyEdgeDetector(); detector.setLowThreshold(lowThres); detector.setHighThreshold(highThres); detector.setSourceImage(image); detector.process(); BufferedImage edges = detector.getEdgesImage(); // print the dimensions of the photo int startW = edges.getWidth(); int startH = edges.getHeight(); System.out.println(startW); System.out.println(startH); float ratio = 1; // Difference in image vs screen size diffW = dim.width - startW; diffH = dim.height - startH; // Creates ratio to scale the image up or down if (diffW < diffH) { ratio = dim.width/ (float) startW; } else { ratio = dim.height/ (float) startH; } System.out.println(ratio); int newW = Math.round(startW * ratio); int newH = Math.round(startH * ratio); System.out.println(newW); System.out.println(newH); newDiffW = dim.width - newW; newDiffH = dim.height - newH; if (newDiffW > newDiffH) { adjustX = true; newDiffW /= 2; } else { newDiffH /= 2; } // attempted cropping that's currently not doing anything // TODO set up cropping/resizing BufferedImage thumb = Thumbnails.of(edges).size(newW, newH).asBufferedImage(); BufferedImage orig = Thumbnails.of(image).size(newW, newH).asBufferedImage(); File outputfile = new File("image" + nameExt + ".jpg"); ImageIO.write(edges, "jpg", outputfile); PrintStream out = new PrintStream(new FileOutputStream("particles" + nameExt + ".txt")); System.setOut(out); out.println(newW + " " + newH); // get the colors for each coordinate in the file for( int i = 0; i < thumb.getWidth(); i++ ) for( int j = 0; j < thumb.getHeight(); j++ ){ int pix = thumb.getRGB( i, j ); int colorPix = orig.getRGB( i, j ); if (getPixelSum(pix) > 25){ int[] pixArray = getPixelRGB(colorPix); String tup = "(" + pixArray[0] + ", " + pixArray[1] + ", " + pixArray[2] + ")"; String coord = ""; // Move image horizontally to the center if (adjustX) { coord = (i + newDiffW) + " " + j + " " + tup; } // Move image vertically to the center else { coord = i + " " + (j + newDiffH) + " " + tup; } out.println(coord); } } out.close(); if (index < (files.length - 1)) { EdgeDetectFlow walkthrough = new EdgeDetectFlow(files[index + 1].getAbsolutePath(), Integer.toString(index + 1), index + 1, files); walkthrough.determineEdgeDetect(Integer.toString(index + 1)); } else { // MAYBE THE SOLUTION processing.core.PApplet sketch = new Sketch(); processing.core.PApplet.main(new String[] {"--present", "visualizer.Sketch"}); } }
diff --git a/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java b/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java index 506e250..0ac0877 100644 --- a/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java +++ b/onebusaway-nyc-webapp/src/main/java/org/onebusaway/nyc/webapp/actions/GaAction.java @@ -1,270 +1,270 @@ /** * Copyright (c) 2011 Metropolitan Transportation Authority * * 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.onebusaway.nyc.webapp.actions; import java.io.InputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import org.onebusaway.nyc.webapp.actions.OneBusAwayNYCActionSupport; /** * Adapted from Google Analytics' ga.jsp code, which was: Copyright 2009 Google Inc. All Rights Reserved. **/ @Results( {@Result(type = "stream", name = "pixel", params = {"contentType", "image/gif"})} ) public class GaAction extends OneBusAwayNYCActionSupport { private static final long serialVersionUID = 1L; // Download stream to write 1x1 px. GIF back to user. private InputStream inputStream; // Tracker version. private static final String version = "4.4sj"; private static final String COOKIE_NAME = "__utmmobile"; // The path the cookie will be available to, edit this to use a different // cookie path. private static final String COOKIE_PATH = "/"; // Two years in seconds. private static final int COOKIE_USER_PERSISTENCE = 63072000; // 1x1 transparent GIF private static final byte[] GIF_DATA = new byte[] { (byte)0x47, (byte)0x49, (byte)0x46, (byte)0x38, (byte)0x39, (byte)0x61, (byte)0x01, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x80, (byte)0xff, (byte)0x00, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x2c, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x00, (byte)0x02, (byte)0x02, (byte)0x44, (byte)0x01, (byte)0x00, (byte)0x3b }; // this is the download streamed to the user public InputStream getInputStream() { return inputStream; } // A string is empty in our terms, if it is null, empty or a dash. private static boolean isEmpty(String in) { return in == null || "-".equals(in) || "".equals(in); } // The last octect of the IP address is removed to anonymize the user. private static String getIP(String remoteAddress) { if (isEmpty(remoteAddress)) { return ""; } // Capture the first three octects of the IP address and replace the forth // with 0, e.g. 124.455.3.123 becomes 124.455.3.0 String regex = "^([^.]+\\.[^.]+\\.[^.]+\\.).*"; Pattern getFirstBitOfIPAddress = Pattern.compile(regex); Matcher m = getFirstBitOfIPAddress.matcher(remoteAddress); if (m.matches()) { return m.group(1) + "0"; } else { return ""; } } // Generate a visitor id for this hit. // If there is a visitor id in the cookie, use that, otherwise // use the guid if we have one, otherwise use a random number. private static String getVisitorId( String guid, String account, String userAgent, Cookie cookie) throws NoSuchAlgorithmException, UnsupportedEncodingException { // If there is a value in the cookie, don't change it. if (cookie != null && cookie.getValue() != null) { return cookie.getValue(); } String message; if (!isEmpty(guid)) { // Create the visitor id using the guid. message = guid + account; } else { // otherwise this is a new user, create a new random id. message = userAgent + getRandomNumber() + UUID.randomUUID().toString(); } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(message.getBytes("UTF-8"), 0, message.length()); byte[] sum = m.digest(); BigInteger messageAsNumber = new BigInteger(1, sum); String md5String = messageAsNumber.toString(16); // Pad to make sure id is 32 characters long. while (md5String.length() < 32) { md5String = "0" + md5String; } return "0x" + md5String.substring(0, 16); } // Get a random number string. private static String getRandomNumber() { return Integer.toString((int) (Math.random() * 0x7fffffff)); } // Make a tracking request to Google Analytics from this server. // Copies the headers from the original request to the new one. // If request containg utmdebug parameter, exceptions encountered // communicating with Google Analytics are thown. private void sendRequestToGoogleAnalytics( String utmUrl, HttpServletRequest request) throws Exception { try { URL url = new URL(utmUrl); URLConnection connection = url.openConnection(); connection.setUseCaches(false); connection.addRequestProperty("User-Agent", request.getHeader("User-Agent")); connection.addRequestProperty("Accepts-Language", request.getHeader("Accepts-Language")); connection.getContent(); } catch (Exception e) { if (request.getParameter("utmdebug") != null) { throw new Exception(e); } } } // Track a page view, updates all the cookies and campaign tracker, // makes a server side request to Google Analytics and writes the transparent // gif byte data to the response. @Override public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String domainName = request.getServerName(); if (isEmpty(domainName)) { domainName = ""; } // Get the referrer from the utmr parameter, this is the referrer to the // page that contains the tracking pixel, not the referrer for tracking // pixel. String documentReferer = request.getParameter("utmr"); if (isEmpty(documentReferer)) { documentReferer = "-"; } else { documentReferer = URLDecoder.decode(documentReferer, "UTF-8"); } String documentPath = request.getParameter("utmp"); if (isEmpty(documentPath)) { documentPath = ""; } else { documentPath = URLDecoder.decode(documentPath, "UTF-8"); } String account = request.getParameter("utmac"); String userAgent = request.getHeader("User-Agent"); if (isEmpty(userAgent)) { userAgent = ""; } // Try and get visitor cookie from the request. Cookie[] cookies = request.getCookies(); Cookie cookie = null; if (cookies != null) { for(int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(COOKIE_NAME)) { cookie = cookies[i]; } } } String visitorId = getVisitorId( request.getHeader("X-DCMGUID"), account, userAgent, cookie); // Always try and add the cookie to the response. Cookie newCookie = new Cookie(COOKIE_NAME, visitorId); newCookie.setMaxAge(COOKIE_USER_PERSISTENCE); newCookie.setPath(COOKIE_PATH); response.addCookie(newCookie); // Construct the gif hit url. String utmUrl = "utmwv=" + version + "&utmn=" + getRandomNumber() + "&utmhn=" + domainName + "&utmr=" + documentReferer + "&utmp=" + documentPath + "&utmac=" + account + "&utmcc=__utma%3D999.999.999.999.999.1%3B" + "&utmvid=" + visitorId + "&utmip=" + getIP(request.getRemoteAddr()); // event tracking String type = request.getParameter("utmt"); String event = request.getParameter("utme"); if (!isEmpty(type) && !isEmpty(event)) { utmUrl += "&utmt=" + URLDecoder.decode(type, "UTF-8"); utmUrl += "&utme=" + URLDecoder.decode(event, "UTF-8"); } URI utfGifLocationUri = new URI("http", null, "www.google-analytics.com", 80, "/__utm.gif", utmUrl, null); sendRequestToGoogleAnalytics(utfGifLocationUri.toASCIIString(), request); // If the debug parameter is on, add a header to the response that contains // the url that was used to contact Google Analytics. if (request.getParameter("utmdebug") != null) { - response.setHeader("X-GA-MOBILE-URL", utmUrl); + response.setHeader("X-GA-MOBILE-URL", utfGifLocationUri.toASCIIString()); } // write 1x1 pixel tracking gif to output stream final PipedInputStream pipedInputStream = new PipedInputStream(); final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); response.addHeader( "Cache-Control", "private, no-cache, no-cache=Set-Cookie, proxy-revalidate"); response.addHeader("Pragma", "no-cache"); response.addHeader("Expires", "Wed, 17 Sep 1975 21:32:10 GMT"); pipedOutputStream.write(GIF_DATA); pipedOutputStream.flush(); pipedOutputStream.close(); // the input stream will get populated by the piped output stream inputStream = pipedInputStream; return "pixel"; } }
true
true
public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String domainName = request.getServerName(); if (isEmpty(domainName)) { domainName = ""; } // Get the referrer from the utmr parameter, this is the referrer to the // page that contains the tracking pixel, not the referrer for tracking // pixel. String documentReferer = request.getParameter("utmr"); if (isEmpty(documentReferer)) { documentReferer = "-"; } else { documentReferer = URLDecoder.decode(documentReferer, "UTF-8"); } String documentPath = request.getParameter("utmp"); if (isEmpty(documentPath)) { documentPath = ""; } else { documentPath = URLDecoder.decode(documentPath, "UTF-8"); } String account = request.getParameter("utmac"); String userAgent = request.getHeader("User-Agent"); if (isEmpty(userAgent)) { userAgent = ""; } // Try and get visitor cookie from the request. Cookie[] cookies = request.getCookies(); Cookie cookie = null; if (cookies != null) { for(int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(COOKIE_NAME)) { cookie = cookies[i]; } } } String visitorId = getVisitorId( request.getHeader("X-DCMGUID"), account, userAgent, cookie); // Always try and add the cookie to the response. Cookie newCookie = new Cookie(COOKIE_NAME, visitorId); newCookie.setMaxAge(COOKIE_USER_PERSISTENCE); newCookie.setPath(COOKIE_PATH); response.addCookie(newCookie); // Construct the gif hit url. String utmUrl = "utmwv=" + version + "&utmn=" + getRandomNumber() + "&utmhn=" + domainName + "&utmr=" + documentReferer + "&utmp=" + documentPath + "&utmac=" + account + "&utmcc=__utma%3D999.999.999.999.999.1%3B" + "&utmvid=" + visitorId + "&utmip=" + getIP(request.getRemoteAddr()); // event tracking String type = request.getParameter("utmt"); String event = request.getParameter("utme"); if (!isEmpty(type) && !isEmpty(event)) { utmUrl += "&utmt=" + URLDecoder.decode(type, "UTF-8"); utmUrl += "&utme=" + URLDecoder.decode(event, "UTF-8"); } URI utfGifLocationUri = new URI("http", null, "www.google-analytics.com", 80, "/__utm.gif", utmUrl, null); sendRequestToGoogleAnalytics(utfGifLocationUri.toASCIIString(), request); // If the debug parameter is on, add a header to the response that contains // the url that was used to contact Google Analytics. if (request.getParameter("utmdebug") != null) { response.setHeader("X-GA-MOBILE-URL", utmUrl); } // write 1x1 pixel tracking gif to output stream final PipedInputStream pipedInputStream = new PipedInputStream(); final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); response.addHeader( "Cache-Control", "private, no-cache, no-cache=Set-Cookie, proxy-revalidate"); response.addHeader("Pragma", "no-cache"); response.addHeader("Expires", "Wed, 17 Sep 1975 21:32:10 GMT"); pipedOutputStream.write(GIF_DATA); pipedOutputStream.flush(); pipedOutputStream.close(); // the input stream will get populated by the piped output stream inputStream = pipedInputStream; return "pixel"; }
public String execute() throws Exception { HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); String domainName = request.getServerName(); if (isEmpty(domainName)) { domainName = ""; } // Get the referrer from the utmr parameter, this is the referrer to the // page that contains the tracking pixel, not the referrer for tracking // pixel. String documentReferer = request.getParameter("utmr"); if (isEmpty(documentReferer)) { documentReferer = "-"; } else { documentReferer = URLDecoder.decode(documentReferer, "UTF-8"); } String documentPath = request.getParameter("utmp"); if (isEmpty(documentPath)) { documentPath = ""; } else { documentPath = URLDecoder.decode(documentPath, "UTF-8"); } String account = request.getParameter("utmac"); String userAgent = request.getHeader("User-Agent"); if (isEmpty(userAgent)) { userAgent = ""; } // Try and get visitor cookie from the request. Cookie[] cookies = request.getCookies(); Cookie cookie = null; if (cookies != null) { for(int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(COOKIE_NAME)) { cookie = cookies[i]; } } } String visitorId = getVisitorId( request.getHeader("X-DCMGUID"), account, userAgent, cookie); // Always try and add the cookie to the response. Cookie newCookie = new Cookie(COOKIE_NAME, visitorId); newCookie.setMaxAge(COOKIE_USER_PERSISTENCE); newCookie.setPath(COOKIE_PATH); response.addCookie(newCookie); // Construct the gif hit url. String utmUrl = "utmwv=" + version + "&utmn=" + getRandomNumber() + "&utmhn=" + domainName + "&utmr=" + documentReferer + "&utmp=" + documentPath + "&utmac=" + account + "&utmcc=__utma%3D999.999.999.999.999.1%3B" + "&utmvid=" + visitorId + "&utmip=" + getIP(request.getRemoteAddr()); // event tracking String type = request.getParameter("utmt"); String event = request.getParameter("utme"); if (!isEmpty(type) && !isEmpty(event)) { utmUrl += "&utmt=" + URLDecoder.decode(type, "UTF-8"); utmUrl += "&utme=" + URLDecoder.decode(event, "UTF-8"); } URI utfGifLocationUri = new URI("http", null, "www.google-analytics.com", 80, "/__utm.gif", utmUrl, null); sendRequestToGoogleAnalytics(utfGifLocationUri.toASCIIString(), request); // If the debug parameter is on, add a header to the response that contains // the url that was used to contact Google Analytics. if (request.getParameter("utmdebug") != null) { response.setHeader("X-GA-MOBILE-URL", utfGifLocationUri.toASCIIString()); } // write 1x1 pixel tracking gif to output stream final PipedInputStream pipedInputStream = new PipedInputStream(); final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); response.addHeader( "Cache-Control", "private, no-cache, no-cache=Set-Cookie, proxy-revalidate"); response.addHeader("Pragma", "no-cache"); response.addHeader("Expires", "Wed, 17 Sep 1975 21:32:10 GMT"); pipedOutputStream.write(GIF_DATA); pipedOutputStream.flush(); pipedOutputStream.close(); // the input stream will get populated by the piped output stream inputStream = pipedInputStream; return "pixel"; }
diff --git a/mpi/src/ke/go/moh/oec/mpi/list/PersonIdentifierList.java b/mpi/src/ke/go/moh/oec/mpi/list/PersonIdentifierList.java index 2cc6643..f888d5e 100644 --- a/mpi/src/ke/go/moh/oec/mpi/list/PersonIdentifierList.java +++ b/mpi/src/ke/go/moh/oec/mpi/list/PersonIdentifierList.java @@ -1,118 +1,120 @@ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * 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 OpenEMRConnect. * * The Initial Developer of the Original Code is International Training & * Education Center for Health (I-TECH) <http://www.go2itech.org/> * * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ package ke.go.moh.oec.mpi.list; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import ke.go.moh.oec.PersonIdentifier; import ke.go.moh.oec.mpi.Mpi; import ke.go.moh.oec.mpi.Sql; import ke.go.moh.oec.mpi.ValueMap; /** * MPI Methods to operate on a list of person identifiers. * * @author Jim Grace */ public class PersonIdentifierList { /** * Loads into memory the person identifiers for a given person. * * @param conn Connection on which to do the query. * @param dbPersonId Internal database ID for the person associated with these identifiers. * @return The list of person identifiers. */ public static List<PersonIdentifier> load(Connection conn, int dbPersonId) { List<PersonIdentifier> personIdentifierList = null; String sql = "SELECT pi.identifier, pi.identifier_type_id\n" + "FROM person_identifier pi\n" + "WHERE pi.person_id = " + dbPersonId; ResultSet rs = Sql.query(conn, sql, Level.FINEST); try { while (rs.next()) { if (personIdentifierList == null) { personIdentifierList = new ArrayList<PersonIdentifier>(); } String idType = Integer.toString(rs.getInt("identifier_type_id")); PersonIdentifier.Type pit = (PersonIdentifier.Type) ValueMap.PERSON_IDENTIFIER_TYPE.getVal().get(idType); PersonIdentifier pi = new PersonIdentifier(); pi.setIdentifier(rs.getString("identifier")); pi.setIdentifierType(pit); personIdentifierList.add(pi); } rs.close(); } catch (SQLException ex) { Logger.getLogger(Mpi.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } return personIdentifierList; } public static List<PersonIdentifier> update(Connection conn, int personId, List<PersonIdentifier> newList, List<PersonIdentifier> oldList) { boolean newEntries = (newList != null && newList.size() > 0); boolean oldEntries = (oldList != null && oldList.size() > 0); if (newEntries) { String sql; List<PersonIdentifier> deleteList = new ArrayList<PersonIdentifier>(); for (PersonIdentifier newP : newList) { PersonIdentifier.Type piType = newP.getIdentifierType(); String id = newP.getIdentifier(); String dbType = ValueMap.PERSON_IDENTIFIER_TYPE.getDb().get(piType); if (oldList != null) { for (PersonIdentifier oldP : oldList) { if (oldP.getIdentifierType() == piType) { String oldId = oldP.getIdentifier(); if ((piType != PersonIdentifier.Type.cccLocalId && piType != PersonIdentifier.Type.cccLocalId) || (id.substring(0, 4).equals(oldId.substring(0, 4)))) { deleteList.add(oldP); sql = "DELETE FROM person_identifier " + " WHERE person_id = " + personId + " AND identifier_type_id = " + dbType + " AND identifier = " + Sql.quote(oldId); Sql.execute(conn, sql); } } } } sql = "INSERT INTO person_identifier (person_id, identifier_type_id, identifier) values (" + personId + ", " + dbType + ", " + Sql.quote(id) + ")"; Sql.execute(conn, sql); } - oldList.removeAll(deleteList); + if (oldList != null) { + oldList.removeAll(deleteList); + } } else { newList = new ArrayList<PersonIdentifier>(); } if (oldEntries) { newList.addAll(oldList); } return newList; } }
true
true
public static List<PersonIdentifier> update(Connection conn, int personId, List<PersonIdentifier> newList, List<PersonIdentifier> oldList) { boolean newEntries = (newList != null && newList.size() > 0); boolean oldEntries = (oldList != null && oldList.size() > 0); if (newEntries) { String sql; List<PersonIdentifier> deleteList = new ArrayList<PersonIdentifier>(); for (PersonIdentifier newP : newList) { PersonIdentifier.Type piType = newP.getIdentifierType(); String id = newP.getIdentifier(); String dbType = ValueMap.PERSON_IDENTIFIER_TYPE.getDb().get(piType); if (oldList != null) { for (PersonIdentifier oldP : oldList) { if (oldP.getIdentifierType() == piType) { String oldId = oldP.getIdentifier(); if ((piType != PersonIdentifier.Type.cccLocalId && piType != PersonIdentifier.Type.cccLocalId) || (id.substring(0, 4).equals(oldId.substring(0, 4)))) { deleteList.add(oldP); sql = "DELETE FROM person_identifier " + " WHERE person_id = " + personId + " AND identifier_type_id = " + dbType + " AND identifier = " + Sql.quote(oldId); Sql.execute(conn, sql); } } } } sql = "INSERT INTO person_identifier (person_id, identifier_type_id, identifier) values (" + personId + ", " + dbType + ", " + Sql.quote(id) + ")"; Sql.execute(conn, sql); } oldList.removeAll(deleteList); } else { newList = new ArrayList<PersonIdentifier>(); } if (oldEntries) { newList.addAll(oldList); } return newList; }
public static List<PersonIdentifier> update(Connection conn, int personId, List<PersonIdentifier> newList, List<PersonIdentifier> oldList) { boolean newEntries = (newList != null && newList.size() > 0); boolean oldEntries = (oldList != null && oldList.size() > 0); if (newEntries) { String sql; List<PersonIdentifier> deleteList = new ArrayList<PersonIdentifier>(); for (PersonIdentifier newP : newList) { PersonIdentifier.Type piType = newP.getIdentifierType(); String id = newP.getIdentifier(); String dbType = ValueMap.PERSON_IDENTIFIER_TYPE.getDb().get(piType); if (oldList != null) { for (PersonIdentifier oldP : oldList) { if (oldP.getIdentifierType() == piType) { String oldId = oldP.getIdentifier(); if ((piType != PersonIdentifier.Type.cccLocalId && piType != PersonIdentifier.Type.cccLocalId) || (id.substring(0, 4).equals(oldId.substring(0, 4)))) { deleteList.add(oldP); sql = "DELETE FROM person_identifier " + " WHERE person_id = " + personId + " AND identifier_type_id = " + dbType + " AND identifier = " + Sql.quote(oldId); Sql.execute(conn, sql); } } } } sql = "INSERT INTO person_identifier (person_id, identifier_type_id, identifier) values (" + personId + ", " + dbType + ", " + Sql.quote(id) + ")"; Sql.execute(conn, sql); } if (oldList != null) { oldList.removeAll(deleteList); } } else { newList = new ArrayList<PersonIdentifier>(); } if (oldEntries) { newList.addAll(oldList); } return newList; }
diff --git a/orbisgis-view/src/main/java/org/orbisgis/view/sqlconsole/ui/FunctionListRenderer.java b/orbisgis-view/src/main/java/org/orbisgis/view/sqlconsole/ui/FunctionListRenderer.java index 6e4418c25..a14381a94 100644 --- a/orbisgis-view/src/main/java/org/orbisgis/view/sqlconsole/ui/FunctionListRenderer.java +++ b/orbisgis-view/src/main/java/org/orbisgis/view/sqlconsole/ui/FunctionListRenderer.java @@ -1,74 +1,75 @@ /** * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able to * manipulate and create vector and raster spatial information. * * OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG" * team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488. * * Copyright (C) 2007-2012 IRSTV (FR CNRS 2488) * * This file is part of OrbisGIS. * * OrbisGIS 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. * * OrbisGIS 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 * OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: <http://www.orbisgis.org/> * or contact directly: * info_at_ orbisgis.org */ package org.orbisgis.view.sqlconsole.ui; import java.awt.Component; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JList; import org.orbisgis.view.components.renderers.ListLaFRenderer; import org.orbisgis.view.icons.OrbisGISIcon; /** * Class to improve the function list rendering. Add icons corresponding to * FunctionElement type. * * @author Erwan Bocher */ public class FunctionListRenderer extends ListLaFRenderer { private static final long serialVersionUID = 1L; public FunctionListRenderer(JList list) { super(list); } private static Icon getFunctionIcon(FunctionElement value) { int type = value.getFunctionType(); if (type == FunctionElement.BASIC_FUNCTION) { return OrbisGISIcon.getIcon("builtinfunctionmap"); } else if (type == FunctionElement.CUSTOM_FUNCTION) { return OrbisGISIcon.getIcon("builtincustomquerymap"); } else { return OrbisGISIcon.getIcon("builtincustomquerymaperror"); } } @Override public Component getListCellRendererComponent(JList jlist, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component nativeCell = lookAndFeelRenderer.getListCellRendererComponent(jlist, value, index, isSelected, cellHasFocus); if(nativeCell instanceof JLabel) { JLabel renderingComp = (JLabel) nativeCell; FunctionElement sqlFunction = (FunctionElement)value; renderingComp.setIcon(getFunctionIcon(sqlFunction)); renderingComp.setText(sqlFunction.getFunctionName()); - renderingComp.setToolTipText(sqlFunction.getToolTip()); + renderingComp.setToolTipText("<html><body><p style='width: 300px;'>" + + sqlFunction.getToolTip() + "</p></body></html>"); } return nativeCell; } }
true
true
public Component getListCellRendererComponent(JList jlist, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component nativeCell = lookAndFeelRenderer.getListCellRendererComponent(jlist, value, index, isSelected, cellHasFocus); if(nativeCell instanceof JLabel) { JLabel renderingComp = (JLabel) nativeCell; FunctionElement sqlFunction = (FunctionElement)value; renderingComp.setIcon(getFunctionIcon(sqlFunction)); renderingComp.setText(sqlFunction.getFunctionName()); renderingComp.setToolTipText(sqlFunction.getToolTip()); } return nativeCell; }
public Component getListCellRendererComponent(JList jlist, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component nativeCell = lookAndFeelRenderer.getListCellRendererComponent(jlist, value, index, isSelected, cellHasFocus); if(nativeCell instanceof JLabel) { JLabel renderingComp = (JLabel) nativeCell; FunctionElement sqlFunction = (FunctionElement)value; renderingComp.setIcon(getFunctionIcon(sqlFunction)); renderingComp.setText(sqlFunction.getFunctionName()); renderingComp.setToolTipText("<html><body><p style='width: 300px;'>" + sqlFunction.getToolTip() + "</p></body></html>"); } return nativeCell; }
diff --git a/src/com/vartala/soulofw0lf/rpgapi/loaders/DiseaseLoader.java b/src/com/vartala/soulofw0lf/rpgapi/loaders/DiseaseLoader.java index 84abb05..9b028a9 100644 --- a/src/com/vartala/soulofw0lf/rpgapi/loaders/DiseaseLoader.java +++ b/src/com/vartala/soulofw0lf/rpgapi/loaders/DiseaseLoader.java @@ -1,130 +1,130 @@ package com.vartala.soulofw0lf.rpgapi.loaders; import com.vartala.soulofw0lf.rpgapi.RpgAPI; import com.vartala.soulofw0lf.rpgapi.diseaseapi.Disease; import com.vartala.soulofw0lf.rpgapi.diseaseapi.DiseaseListeners; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by: soulofw0lf * Date: 7/29/13 * Time: 11:49 PM * <p/> * This file is part of the Rpg Suite Created by Soulofw0lf and Linksy. * <p/> * The Rpg Suite 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. * <p/> * The Rpg Suite 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. * <p/> * You should have received a copy of the GNU General Public License * along with The Rpg Suite Plugin you have downloaded. If not, see <http://www.gnu.org/licenses/>. */ public class DiseaseLoader { RpgAPI rpg; public DiseaseLoader(RpgAPI Rpg){ this.rpg = Rpg; this.rpg.diseaseListener = new DiseaseListeners(this.rpg); YamlConfiguration diseaseConfig = YamlConfiguration.loadConfiguration(new File("plugins/RpgDiseases/RpgDisease.yml")); YamlConfiguration diseaseLocale = YamlConfiguration.loadConfiguration(new File("plugins/RpgDiseases/Locale/DiseaseLocale.yml")); if (diseaseLocale.get("Disease Commands") == null){ diseaseLocale.set("Disease Commands.Add Disease", "disadd"); } try { diseaseLocale.save(new File("plugins/RpgDiseases/Locale/DiseaseLocale.yml")); } catch (IOException e){ e.printStackTrace(); } RpgAPI.commandSettings.put("Add Disease", diseaseLocale.getString("Disease Commands.Add Disease")); RpgAPI.commands.add(diseaseLocale.getString("Disease Commands.Add Disease")); if (diseaseConfig.get("Diseases") == null){ diseaseConfig.set("Diseases.Withering Death.Severity Level", 5); diseaseConfig.set("Diseases.Withering Death.Spreadable", true); diseaseConfig.set("Diseases.Withering Death.Use Air Spread", true); diseaseConfig.set("Diseases.Withering Death.Air Spread Chance", 12.5); diseaseConfig.set("Diseases.Withering Death.Air Spread Distance", 15); diseaseConfig.set("Diseases.Withering Death.Use Hit Spread", true); diseaseConfig.set("Diseases.Withering Death.Hit Spread Chance", 12.5); diseaseConfig.set("Diseases.Withering Death.Stackable", true); diseaseConfig.set("Diseases.Withering Death.Fatal", true); diseaseConfig.set("Diseases.Withering Death.Ticks Before Death", 20); diseaseConfig.set("Diseases.Withering Death.Gets Worse", false); diseaseConfig.set("Diseases.Withering Death.Morphs Into", ""); diseaseConfig.set("Diseases.Withering Death.Regresses To", ""); diseaseConfig.set("Diseases.Withering Death.Morph Progression Timer", 0); diseaseConfig.set("Diseases.Withering Death.Effect Damage Dealt", true); diseaseConfig.set("Diseases.Withering Death.Adjust Damage Dealt By", -1.5); diseaseConfig.set("Diseases.Withering Death.Miss Chance", true); diseaseConfig.set("Diseases.Withering Death.Miss Percentage", 5.5); diseaseConfig.set("Diseases.Withering Death.Effect Damage Taken", true); diseaseConfig.set("Diseases.Withering Death.Adjust Damage Taken By", 3.5); diseaseConfig.set("Diseases.Withering Death.Effects.SLOW.Duration", 120); diseaseConfig.set("Diseases.Withering Death.Effects.SLOW.Amplifier", 1); diseaseConfig.set("Diseases.Withering Death.Behavior Timer", 0); diseaseConfig.set("Diseases.Withering Death.Use Damage Over Time", true); diseaseConfig.set("Diseases.Withering Death.Damage Per DOT Tick", 2.5); diseaseConfig.set("Diseases.Withering Death.Dot Tick Time", 6); diseaseConfig.set("Diseases.Withering Death.Adjust Health", false); diseaseConfig.set("Diseases.Withering Death.Adjust Health Amount", 0); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 1st Behavior true or false once behaviors are added", false); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 2nd Behavior true or false once behaviors are added", false); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 3rd Behavior true or false once behaviors are added", false); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 4th Behavior true or false once behaviors are added", false); try { diseaseConfig.save(new File("plugins/RpgDiseases/RpgDisease.yml")); } catch (IOException e){ e.printStackTrace(); } for (String key : diseaseConfig.getConfigurationSection("Diseases").getKeys(false)){ Disease dis = new Disease(); dis.setSeverity(diseaseConfig.getInt("Diseases." + key + ".Severity Level")); dis.setSpreadable(diseaseConfig.getBoolean("Diseases." + key + ".Spreadable")); dis.setAirSpread(diseaseConfig.getBoolean("Diseases." + key + ".Use Air Spread")); dis.setAirSpreadChance(diseaseConfig.getDouble("Diseases." + key + ".Air Spread Chance")); dis.setSpreadDistance(diseaseConfig.getDouble("Diseases." + key + ".Air Spread Distance")); dis.setHitSpread(diseaseConfig.getBoolean("Diseases." + key + ".Use Hit Spread")); dis.setHitSpreadChance(diseaseConfig.getDouble("Diseases." + key + ".Hit Spread Chance")); dis.setStackable(diseaseConfig.getBoolean("Diseases." + key + ".Stackable")); dis.setFatal(diseaseConfig.getBoolean("Diseases." + key + ".Fatal")); dis.setTicksBeforeDeath(diseaseConfig.getInt("Diseases." + key + ".Ticks Before Death")); dis.setGetsWorse(diseaseConfig.getBoolean("Diseases." + key + ".Gets Worse")); dis.setProgressiveDisease(diseaseConfig.getString("Diseases." + key + ".Morphs Into")); dis.setRegressiveDisease(diseaseConfig.getString("Diseases." + key + ".Regresses To")); dis.setProgressionTime(diseaseConfig.getInt("Diseases." + key + ".Morph Progression Timer")); dis.setEffectDamage(diseaseConfig.getBoolean("Diseases." + key + ".Effect Damage Dealt")); dis.setAdjustDamage(diseaseConfig.getDouble("Diseases." + key + ".Adjust Damage Dealt By")); dis.setMiss(diseaseConfig.getBoolean("Diseases." + key + ".Miss Chance")); dis.setMissChance(diseaseConfig.getDouble("Diseases." + key + ".Miss Percentage")); dis.setEffectDamageTaken(diseaseConfig.getBoolean("Diseases." + key + ".Effect Damage Taken")); dis.setAdjustDamageTaken(diseaseConfig.getDouble("Diseases." + key + ".Adjust Damage Taken By")); List<PotionEffect> pots = new ArrayList<>(); - for (String type : diseaseConfig.getConfigurationSection("Diseases." + key + ".effects").getKeys(false)){ + for (String type : diseaseConfig.getConfigurationSection("Diseases." + key + ".Effects").getKeys(false)){ PotionEffect pE = new PotionEffect(PotionEffectType.getByName(type.toUpperCase()), diseaseConfig.getInt("Diseases." + key + ".Effects." + type + ".Duration"), diseaseConfig.getInt("Diseases." + key + ".Effects." + type + ".Amplifier")); pots.add(pE); } dis.setDiseasePots(pots); dis.setDiseaseTime(diseaseConfig.getInt("Diseases." + key + ".Behavior Timer")); dis.setDot(diseaseConfig.getBoolean("Diseases." + key + ".Use Damage Over Time")); dis.setDotDamage(diseaseConfig.getDouble("Diseases." + key + ".Damage Per DOT Tick")); dis.setDotTimer(diseaseConfig.getInt("Diseases." + key + ".Dot Tick Time")); dis.setHealthEffect(diseaseConfig.getBoolean("Diseases." + key + ".Adjust Health")); dis.setHealthChange(diseaseConfig.getDouble("Diseases." + key + ".Adjust Health Amount")); RpgAPI.diseases.add(dis); System.out.print(dis.getDiseaseName()); } } } }
true
true
public DiseaseLoader(RpgAPI Rpg){ this.rpg = Rpg; this.rpg.diseaseListener = new DiseaseListeners(this.rpg); YamlConfiguration diseaseConfig = YamlConfiguration.loadConfiguration(new File("plugins/RpgDiseases/RpgDisease.yml")); YamlConfiguration diseaseLocale = YamlConfiguration.loadConfiguration(new File("plugins/RpgDiseases/Locale/DiseaseLocale.yml")); if (diseaseLocale.get("Disease Commands") == null){ diseaseLocale.set("Disease Commands.Add Disease", "disadd"); } try { diseaseLocale.save(new File("plugins/RpgDiseases/Locale/DiseaseLocale.yml")); } catch (IOException e){ e.printStackTrace(); } RpgAPI.commandSettings.put("Add Disease", diseaseLocale.getString("Disease Commands.Add Disease")); RpgAPI.commands.add(diseaseLocale.getString("Disease Commands.Add Disease")); if (diseaseConfig.get("Diseases") == null){ diseaseConfig.set("Diseases.Withering Death.Severity Level", 5); diseaseConfig.set("Diseases.Withering Death.Spreadable", true); diseaseConfig.set("Diseases.Withering Death.Use Air Spread", true); diseaseConfig.set("Diseases.Withering Death.Air Spread Chance", 12.5); diseaseConfig.set("Diseases.Withering Death.Air Spread Distance", 15); diseaseConfig.set("Diseases.Withering Death.Use Hit Spread", true); diseaseConfig.set("Diseases.Withering Death.Hit Spread Chance", 12.5); diseaseConfig.set("Diseases.Withering Death.Stackable", true); diseaseConfig.set("Diseases.Withering Death.Fatal", true); diseaseConfig.set("Diseases.Withering Death.Ticks Before Death", 20); diseaseConfig.set("Diseases.Withering Death.Gets Worse", false); diseaseConfig.set("Diseases.Withering Death.Morphs Into", ""); diseaseConfig.set("Diseases.Withering Death.Regresses To", ""); diseaseConfig.set("Diseases.Withering Death.Morph Progression Timer", 0); diseaseConfig.set("Diseases.Withering Death.Effect Damage Dealt", true); diseaseConfig.set("Diseases.Withering Death.Adjust Damage Dealt By", -1.5); diseaseConfig.set("Diseases.Withering Death.Miss Chance", true); diseaseConfig.set("Diseases.Withering Death.Miss Percentage", 5.5); diseaseConfig.set("Diseases.Withering Death.Effect Damage Taken", true); diseaseConfig.set("Diseases.Withering Death.Adjust Damage Taken By", 3.5); diseaseConfig.set("Diseases.Withering Death.Effects.SLOW.Duration", 120); diseaseConfig.set("Diseases.Withering Death.Effects.SLOW.Amplifier", 1); diseaseConfig.set("Diseases.Withering Death.Behavior Timer", 0); diseaseConfig.set("Diseases.Withering Death.Use Damage Over Time", true); diseaseConfig.set("Diseases.Withering Death.Damage Per DOT Tick", 2.5); diseaseConfig.set("Diseases.Withering Death.Dot Tick Time", 6); diseaseConfig.set("Diseases.Withering Death.Adjust Health", false); diseaseConfig.set("Diseases.Withering Death.Adjust Health Amount", 0); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 1st Behavior true or false once behaviors are added", false); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 2nd Behavior true or false once behaviors are added", false); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 3rd Behavior true or false once behaviors are added", false); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 4th Behavior true or false once behaviors are added", false); try { diseaseConfig.save(new File("plugins/RpgDiseases/RpgDisease.yml")); } catch (IOException e){ e.printStackTrace(); } for (String key : diseaseConfig.getConfigurationSection("Diseases").getKeys(false)){ Disease dis = new Disease(); dis.setSeverity(diseaseConfig.getInt("Diseases." + key + ".Severity Level")); dis.setSpreadable(diseaseConfig.getBoolean("Diseases." + key + ".Spreadable")); dis.setAirSpread(diseaseConfig.getBoolean("Diseases." + key + ".Use Air Spread")); dis.setAirSpreadChance(diseaseConfig.getDouble("Diseases." + key + ".Air Spread Chance")); dis.setSpreadDistance(diseaseConfig.getDouble("Diseases." + key + ".Air Spread Distance")); dis.setHitSpread(diseaseConfig.getBoolean("Diseases." + key + ".Use Hit Spread")); dis.setHitSpreadChance(diseaseConfig.getDouble("Diseases." + key + ".Hit Spread Chance")); dis.setStackable(diseaseConfig.getBoolean("Diseases." + key + ".Stackable")); dis.setFatal(diseaseConfig.getBoolean("Diseases." + key + ".Fatal")); dis.setTicksBeforeDeath(diseaseConfig.getInt("Diseases." + key + ".Ticks Before Death")); dis.setGetsWorse(diseaseConfig.getBoolean("Diseases." + key + ".Gets Worse")); dis.setProgressiveDisease(diseaseConfig.getString("Diseases." + key + ".Morphs Into")); dis.setRegressiveDisease(diseaseConfig.getString("Diseases." + key + ".Regresses To")); dis.setProgressionTime(diseaseConfig.getInt("Diseases." + key + ".Morph Progression Timer")); dis.setEffectDamage(diseaseConfig.getBoolean("Diseases." + key + ".Effect Damage Dealt")); dis.setAdjustDamage(diseaseConfig.getDouble("Diseases." + key + ".Adjust Damage Dealt By")); dis.setMiss(diseaseConfig.getBoolean("Diseases." + key + ".Miss Chance")); dis.setMissChance(diseaseConfig.getDouble("Diseases." + key + ".Miss Percentage")); dis.setEffectDamageTaken(diseaseConfig.getBoolean("Diseases." + key + ".Effect Damage Taken")); dis.setAdjustDamageTaken(diseaseConfig.getDouble("Diseases." + key + ".Adjust Damage Taken By")); List<PotionEffect> pots = new ArrayList<>(); for (String type : diseaseConfig.getConfigurationSection("Diseases." + key + ".effects").getKeys(false)){ PotionEffect pE = new PotionEffect(PotionEffectType.getByName(type.toUpperCase()), diseaseConfig.getInt("Diseases." + key + ".Effects." + type + ".Duration"), diseaseConfig.getInt("Diseases." + key + ".Effects." + type + ".Amplifier")); pots.add(pE); } dis.setDiseasePots(pots); dis.setDiseaseTime(diseaseConfig.getInt("Diseases." + key + ".Behavior Timer")); dis.setDot(diseaseConfig.getBoolean("Diseases." + key + ".Use Damage Over Time")); dis.setDotDamage(diseaseConfig.getDouble("Diseases." + key + ".Damage Per DOT Tick")); dis.setDotTimer(diseaseConfig.getInt("Diseases." + key + ".Dot Tick Time")); dis.setHealthEffect(diseaseConfig.getBoolean("Diseases." + key + ".Adjust Health")); dis.setHealthChange(diseaseConfig.getDouble("Diseases." + key + ".Adjust Health Amount")); RpgAPI.diseases.add(dis); System.out.print(dis.getDiseaseName()); } } }
public DiseaseLoader(RpgAPI Rpg){ this.rpg = Rpg; this.rpg.diseaseListener = new DiseaseListeners(this.rpg); YamlConfiguration diseaseConfig = YamlConfiguration.loadConfiguration(new File("plugins/RpgDiseases/RpgDisease.yml")); YamlConfiguration diseaseLocale = YamlConfiguration.loadConfiguration(new File("plugins/RpgDiseases/Locale/DiseaseLocale.yml")); if (diseaseLocale.get("Disease Commands") == null){ diseaseLocale.set("Disease Commands.Add Disease", "disadd"); } try { diseaseLocale.save(new File("plugins/RpgDiseases/Locale/DiseaseLocale.yml")); } catch (IOException e){ e.printStackTrace(); } RpgAPI.commandSettings.put("Add Disease", diseaseLocale.getString("Disease Commands.Add Disease")); RpgAPI.commands.add(diseaseLocale.getString("Disease Commands.Add Disease")); if (diseaseConfig.get("Diseases") == null){ diseaseConfig.set("Diseases.Withering Death.Severity Level", 5); diseaseConfig.set("Diseases.Withering Death.Spreadable", true); diseaseConfig.set("Diseases.Withering Death.Use Air Spread", true); diseaseConfig.set("Diseases.Withering Death.Air Spread Chance", 12.5); diseaseConfig.set("Diseases.Withering Death.Air Spread Distance", 15); diseaseConfig.set("Diseases.Withering Death.Use Hit Spread", true); diseaseConfig.set("Diseases.Withering Death.Hit Spread Chance", 12.5); diseaseConfig.set("Diseases.Withering Death.Stackable", true); diseaseConfig.set("Diseases.Withering Death.Fatal", true); diseaseConfig.set("Diseases.Withering Death.Ticks Before Death", 20); diseaseConfig.set("Diseases.Withering Death.Gets Worse", false); diseaseConfig.set("Diseases.Withering Death.Morphs Into", ""); diseaseConfig.set("Diseases.Withering Death.Regresses To", ""); diseaseConfig.set("Diseases.Withering Death.Morph Progression Timer", 0); diseaseConfig.set("Diseases.Withering Death.Effect Damage Dealt", true); diseaseConfig.set("Diseases.Withering Death.Adjust Damage Dealt By", -1.5); diseaseConfig.set("Diseases.Withering Death.Miss Chance", true); diseaseConfig.set("Diseases.Withering Death.Miss Percentage", 5.5); diseaseConfig.set("Diseases.Withering Death.Effect Damage Taken", true); diseaseConfig.set("Diseases.Withering Death.Adjust Damage Taken By", 3.5); diseaseConfig.set("Diseases.Withering Death.Effects.SLOW.Duration", 120); diseaseConfig.set("Diseases.Withering Death.Effects.SLOW.Amplifier", 1); diseaseConfig.set("Diseases.Withering Death.Behavior Timer", 0); diseaseConfig.set("Diseases.Withering Death.Use Damage Over Time", true); diseaseConfig.set("Diseases.Withering Death.Damage Per DOT Tick", 2.5); diseaseConfig.set("Diseases.Withering Death.Dot Tick Time", 6); diseaseConfig.set("Diseases.Withering Death.Adjust Health", false); diseaseConfig.set("Diseases.Withering Death.Adjust Health Amount", 0); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 1st Behavior true or false once behaviors are added", false); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 2nd Behavior true or false once behaviors are added", false); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 3rd Behavior true or false once behaviors are added", false); diseaseConfig.set("Diseases.Withering Death.Behaviors.Use 4th Behavior true or false once behaviors are added", false); try { diseaseConfig.save(new File("plugins/RpgDiseases/RpgDisease.yml")); } catch (IOException e){ e.printStackTrace(); } for (String key : diseaseConfig.getConfigurationSection("Diseases").getKeys(false)){ Disease dis = new Disease(); dis.setSeverity(diseaseConfig.getInt("Diseases." + key + ".Severity Level")); dis.setSpreadable(diseaseConfig.getBoolean("Diseases." + key + ".Spreadable")); dis.setAirSpread(diseaseConfig.getBoolean("Diseases." + key + ".Use Air Spread")); dis.setAirSpreadChance(diseaseConfig.getDouble("Diseases." + key + ".Air Spread Chance")); dis.setSpreadDistance(diseaseConfig.getDouble("Diseases." + key + ".Air Spread Distance")); dis.setHitSpread(diseaseConfig.getBoolean("Diseases." + key + ".Use Hit Spread")); dis.setHitSpreadChance(diseaseConfig.getDouble("Diseases." + key + ".Hit Spread Chance")); dis.setStackable(diseaseConfig.getBoolean("Diseases." + key + ".Stackable")); dis.setFatal(diseaseConfig.getBoolean("Diseases." + key + ".Fatal")); dis.setTicksBeforeDeath(diseaseConfig.getInt("Diseases." + key + ".Ticks Before Death")); dis.setGetsWorse(diseaseConfig.getBoolean("Diseases." + key + ".Gets Worse")); dis.setProgressiveDisease(diseaseConfig.getString("Diseases." + key + ".Morphs Into")); dis.setRegressiveDisease(diseaseConfig.getString("Diseases." + key + ".Regresses To")); dis.setProgressionTime(diseaseConfig.getInt("Diseases." + key + ".Morph Progression Timer")); dis.setEffectDamage(diseaseConfig.getBoolean("Diseases." + key + ".Effect Damage Dealt")); dis.setAdjustDamage(diseaseConfig.getDouble("Diseases." + key + ".Adjust Damage Dealt By")); dis.setMiss(diseaseConfig.getBoolean("Diseases." + key + ".Miss Chance")); dis.setMissChance(diseaseConfig.getDouble("Diseases." + key + ".Miss Percentage")); dis.setEffectDamageTaken(diseaseConfig.getBoolean("Diseases." + key + ".Effect Damage Taken")); dis.setAdjustDamageTaken(diseaseConfig.getDouble("Diseases." + key + ".Adjust Damage Taken By")); List<PotionEffect> pots = new ArrayList<>(); for (String type : diseaseConfig.getConfigurationSection("Diseases." + key + ".Effects").getKeys(false)){ PotionEffect pE = new PotionEffect(PotionEffectType.getByName(type.toUpperCase()), diseaseConfig.getInt("Diseases." + key + ".Effects." + type + ".Duration"), diseaseConfig.getInt("Diseases." + key + ".Effects." + type + ".Amplifier")); pots.add(pE); } dis.setDiseasePots(pots); dis.setDiseaseTime(diseaseConfig.getInt("Diseases." + key + ".Behavior Timer")); dis.setDot(diseaseConfig.getBoolean("Diseases." + key + ".Use Damage Over Time")); dis.setDotDamage(diseaseConfig.getDouble("Diseases." + key + ".Damage Per DOT Tick")); dis.setDotTimer(diseaseConfig.getInt("Diseases." + key + ".Dot Tick Time")); dis.setHealthEffect(diseaseConfig.getBoolean("Diseases." + key + ".Adjust Health")); dis.setHealthChange(diseaseConfig.getDouble("Diseases." + key + ".Adjust Health Amount")); RpgAPI.diseases.add(dis); System.out.print(dis.getDiseaseName()); } } }
diff --git a/langtools/src/share/classes/com/sun/tools/javac/main/RecognizedOptions.java b/langtools/src/share/classes/com/sun/tools/javac/main/RecognizedOptions.java index 4d8894eb7..d01452a9f 100644 --- a/langtools/src/share/classes/com/sun/tools/javac/main/RecognizedOptions.java +++ b/langtools/src/share/classes/com/sun/tools/javac/main/RecognizedOptions.java @@ -1,750 +1,749 @@ /* * Copyright (c) 2006, 2011, Oracle and/or its affiliates. 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.javac.main; import com.sun.tools.javac.code.Lint; import com.sun.tools.javac.code.Source; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.jvm.Target; import com.sun.tools.javac.main.JavacOption.HiddenOption; import com.sun.tools.javac.main.JavacOption.Option; import com.sun.tools.javac.main.JavacOption.COption; import com.sun.tools.javac.main.JavacOption.XOption; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Options; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; import java.util.EnumSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.lang.model.SourceVersion; import static com.sun.tools.javac.main.OptionName.*; /** * TODO: describe com.sun.tools.javac.main.RecognizedOptions * * <p><b>This is NOT part of any supported API. * If you write code that depends on this, you do so at your own * risk. This code and its internal interfaces are subject to change * or deletion without notice.</b></p> */ public class RecognizedOptions { private RecognizedOptions() {} public interface OptionHelper { void setOut(PrintWriter out); void error(String key, Object... args); void printVersion(); void printFullVersion(); void printHelp(); void printJhelp(); void printXhelp(); void addFile(File f); void addClassName(String s); } public static class GrumpyHelper implements OptionHelper { public void setOut(PrintWriter out) { throw new IllegalArgumentException(); } public void error(String key, Object... args) { throw new IllegalArgumentException(Main.getLocalizedString(key, args)); } public void printVersion() { throw new IllegalArgumentException(); } public void printFullVersion() { throw new IllegalArgumentException(); } public void printHelp() { throw new IllegalArgumentException(); } public void printJhelp() { throw new IllegalArgumentException(); } public void printXhelp() { throw new IllegalArgumentException(); } public void addFile(File f) { throw new IllegalArgumentException(f.getPath()); } public void addClassName(String s) { throw new IllegalArgumentException(s); } } static Set<OptionName> javacOptions = EnumSet.of( G, G_NONE, G_CUSTOM, XLINT, XLINT_CUSTOM, NOWARN, VERBOSE, VERBOSE_CUSTOM, DEPRECATION, CLASSPATH, CP, CEYLONREPO, CEYLONUSER, CEYLONPASS, SOURCEPATH, CEYLONSOURCEPATH, BOOTCLASSPATH, XBOOTCLASSPATH_PREPEND, XBOOTCLASSPATH_APPEND, XBOOTCLASSPATH, EXTDIRS, DJAVA_EXT_DIRS, ENDORSEDDIRS, DJAVA_ENDORSED_DIRS, PROC, PROCESSOR, PROCESSORPATH, D, CEYLONOUT, S, IMPLICIT, ENCODING, SOURCE, TARGET, VERSION, FULLVERSION, DIAGS, HELP, JHELP, A, X, J, MOREINFO, WERROR, // COMPLEXINFERENCE, PROMPT, DOE, PRINTSOURCE, WARNUNCHECKED, XMAXERRS, XMAXWARNS, XSTDOUT, XPKGINFO, XPRINT, XPRINTROUNDS, XPRINTPROCESSORINFO, XPREFER, O, XJCOV, XD, AT, SOURCEFILE, SRC, BOOTSTRAPCEYLON, CEYLONALLOWWARNINGS); static Set<OptionName> javacFileManagerOptions = EnumSet.of( CLASSPATH, CP, CEYLONREPO, CEYLONUSER, CEYLONPASS, SOURCEPATH, CEYLONSOURCEPATH, BOOTCLASSPATH, XBOOTCLASSPATH_PREPEND, XBOOTCLASSPATH_APPEND, XBOOTCLASSPATH, EXTDIRS, DJAVA_EXT_DIRS, ENDORSEDDIRS, DJAVA_ENDORSED_DIRS, PROCESSORPATH, D, CEYLONOUT, S, ENCODING, SOURCE, SRC); static Set<OptionName> javacToolOptions = EnumSet.of( G, G_NONE, G_CUSTOM, XLINT, XLINT_CUSTOM, NOWARN, VERBOSE, VERBOSE_CUSTOM, DEPRECATION, PROC, PROCESSOR, IMPLICIT, SOURCE, TARGET, // VERSION, // FULLVERSION, // HELP, A, // X, // J, MOREINFO, WERROR, // COMPLEXINFERENCE, PROMPT, DOE, PRINTSOURCE, WARNUNCHECKED, XMAXERRS, XMAXWARNS, // XSTDOUT, XPKGINFO, XPRINT, XPRINTROUNDS, XPRINTPROCESSORINFO, XPREFER, O, XJCOV, XD, BOOTSTRAPCEYLON, CEYLONALLOWWARNINGS); public static Option[] getJavaCompilerOptions(OptionHelper helper) { return getOptions(helper, javacOptions); } public static Option[] getJavacFileManagerOptions(OptionHelper helper) { return getOptions(helper, javacFileManagerOptions); } public static Option[] getJavacToolOptions(OptionHelper helper) { return getOptions(helper, javacToolOptions); } static Option[] getOptions(OptionHelper helper, Set<OptionName> desired) { ListBuffer<Option> options = new ListBuffer<Option>(); for (Option option : getAll(helper)) if (desired.contains(option.getName())) options.append(option); return options.toArray(new Option[options.length()]); } /** * Get all the recognized options. * @param helper an {@code OptionHelper} to help when processing options * @return an array of options */ public static Option[] getAll(final OptionHelper helper) { return new Option[] { new Option(G, "opt.g"), new Option(G_NONE, "opt.g.none") { @Override public boolean process(Options options, String option) { options.put("-g:", "none"); return false; } }, new Option(G_CUSTOM, "opt.g.lines.vars.source", Option.ChoiceKind.ANYOF, "lines", "vars", "source"), new XOption(XLINT, "opt.Xlint"), new XOption(XLINT_CUSTOM, "opt.Xlint.suboptlist", Option.ChoiceKind.ANYOF, getXLintChoices()), // -nowarn is retained for command-line backward compatibility new Option(NOWARN, "opt.nowarn") { @Override public boolean process(Options options, String option) { options.put("-Xlint:none", option); return false; } }, new Option(VERBOSE, "opt.verbose"), new Option(VERBOSE_CUSTOM, "opt.verbose.suboptlist") { public boolean matches(String s) { return s.startsWith("-verbose:"); } public boolean process(Options options, String option) { String suboptions = option.substring(9); options.put("-verbose:", suboptions); // enter all the -verbose suboptions as "-verbose:suboption" for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) { String tok = t.nextToken(); String opt = "-verbose:" + tok; options.put(opt, opt); } return false; } }, // -deprecation is retained for command-line backward compatibility new Option(DEPRECATION, "opt.deprecation") { @Override public boolean process(Options options, String option) { options.put("-Xlint:deprecation", option); return false; } }, new Option(CLASSPATH, "opt.arg.path", "opt.classpath"), new Option(CP, "opt.arg.path", "opt.classpath") { @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-classpath", arg); } }, new COption(CEYLONREPO, "opt.arg.url", "opt.ceylonrepo"){ @Override public boolean process(Options options, String option, String arg) { if(options != null) options.addMulti(CEYLONREPO, arg); return false; } }, new COption(CEYLONUSER, "opt.arg.value", "opt.ceylonuser"), new COption(CEYLONPASS, "opt.arg.value", "opt.ceylonpass"), new Option(SOURCEPATH, "opt.arg.path", "opt.sourcepath"), new COption(CEYLONSOURCEPATH, "opt.arg.directory", "opt.ceylonsourcepath"){ @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-sourcepath", arg); } }, new Option(BOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") { @Override public boolean process(Options options, String option, String arg) { options.remove("-Xbootclasspath/p:"); options.remove("-Xbootclasspath/a:"); return super.process(options, option, arg); } }, new XOption(XBOOTCLASSPATH_PREPEND,"opt.arg.path", "opt.Xbootclasspath.p"), new XOption(XBOOTCLASSPATH_APPEND, "opt.arg.path", "opt.Xbootclasspath.a"), new XOption(XBOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") { @Override public boolean process(Options options, String option, String arg) { options.remove("-Xbootclasspath/p:"); options.remove("-Xbootclasspath/a:"); return super.process(options, "-bootclasspath", arg); } }, new Option(EXTDIRS, "opt.arg.dirs", "opt.extdirs"), new XOption(DJAVA_EXT_DIRS, "opt.arg.dirs", "opt.extdirs") { @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-extdirs", arg); } }, new Option(ENDORSEDDIRS, "opt.arg.dirs", "opt.endorseddirs"), new XOption(DJAVA_ENDORSED_DIRS, "opt.arg.dirs", "opt.endorseddirs") { @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-endorseddirs", arg); } }, new Option(PROC, "opt.proc.none.only", Option.ChoiceKind.ONEOF, "none", "only"), new Option(PROCESSOR, "opt.arg.class.list", "opt.processor"), new Option(PROCESSORPATH, "opt.arg.path", "opt.processorpath"), new Option(D, "opt.arg.directory", "opt.d"), new COption(CEYLONOUT, "opt.arg.url", "opt.ceylonout"){ @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-d", arg); } }, new Option(S, "opt.arg.directory", "opt.sourceDest"), new Option(IMPLICIT, "opt.implicit", Option.ChoiceKind.ONEOF, "none", "class"), new Option(ENCODING, "opt.arg.encoding", "opt.encoding"), new Option(SOURCE, "opt.arg.release", "opt.source") { @Override public boolean process(Options options, String option, String operand) { Source source = Source.lookup(operand); if (source == null) { helper.error("err.invalid.source", operand); return true; } return super.process(options, option, operand); } }, new Option(TARGET, "opt.arg.release", "opt.target") { @Override public boolean process(Options options, String option, String operand) { Target target = Target.lookup(operand); if (target == null) { helper.error("err.invalid.target", operand); return true; } return super.process(options, option, operand); } }, new COption(VERSION, "opt.version") { @Override public boolean process(Options options, String option) { helper.printVersion(); return super.process(options, option); } }, new HiddenOption(FULLVERSION) { @Override public boolean process(Options options, String option) { helper.printFullVersion(); return super.process(options, option); } }, new HiddenOption(DIAGS) { @Override public boolean process(Options options, String option) { Option xd = getOptions(helper, EnumSet.of(XD))[0]; option = option.substring(option.indexOf('=') + 1); String diagsOption = option.contains("%") ? "-XDdiagsFormat=" : "-XDdiags="; diagsOption += option; if (xd.matches(diagsOption)) return xd.process(options, diagsOption); else return false; } }, new COption(HELP, "opt.help") { @Override public boolean process(Options options, String option) { helper.printHelp(); return super.process(options, option); } }, new COption(JHELP, "opt.jhelp") { @Override public boolean process(Options options, String option) { helper.printJhelp(); return super.process(options, option); } }, new Option(A, "opt.arg.key.equals.value","opt.A") { @Override String helpSynopsis() { hasSuffix = true; return super.helpSynopsis(); } @Override public boolean matches(String arg) { return arg.startsWith("-A"); } @Override public boolean hasArg() { return false; } // Mapping for processor options created in // JavacProcessingEnvironment @Override public boolean process(Options options, String option) { int argLength = option.length(); if (argLength == 2) { helper.error("err.empty.A.argument"); return true; } int sepIndex = option.indexOf('='); String key = option.substring(2, (sepIndex != -1 ? sepIndex : argLength) ); if (!JavacProcessingEnvironment.isValidOptionName(key)) { helper.error("err.invalid.A.key", option); return true; } return process(options, option, option); } }, new Option(X, "opt.X") { @Override public boolean process(Options options, String option) { helper.printXhelp(); return super.process(options, option); } }, // This option exists only for the purpose of documenting itself. // It's actually implemented by the launcher. new Option(J, "opt.arg.flag", "opt.J") { @Override String helpSynopsis() { hasSuffix = true; return super.helpSynopsis(); } @Override public boolean process(Options options, String option) { throw new AssertionError ("the -J flag should be caught by the launcher."); } }, // stop after parsing and attributing. // new HiddenOption("-attrparseonly"), // new Option("-moreinfo", "opt.moreinfo") { new HiddenOption(MOREINFO) { @Override public boolean process(Options options, String option) { Type.moreInfo = true; return super.process(options, option); } }, // treat warnings as errors new Option(WERROR, "opt.Werror"), new Option(SRC, "opt.arg.src", "opt.src") { public boolean process(Options options, String option, String arg) { return super.process(options, "-src", arg); } }, // use complex inference from context in the position of a method call argument new HiddenOption(COMPLEXINFERENCE), // generare source stubs // new HiddenOption("-stubs"), // relax some constraints to allow compiling from stubs // new HiddenOption("-relax"), // output source after translating away inner classes // new Option("-printflat", "opt.printflat"), // new HiddenOption("-printflat"), // display scope search details // new Option("-printsearch", "opt.printsearch"), // new HiddenOption("-printsearch"), // prompt after each error // new Option("-prompt", "opt.prompt"), new HiddenOption(PROMPT), // dump stack on error new HiddenOption(DOE), // output source after type erasure // new Option("-s", "opt.s"), new HiddenOption(PRINTSOURCE), // allow us to compile ceylon.language new HiddenOption(BOOTSTRAPCEYLON), // do not halt on typechecker warnings new HiddenOption(CEYLONALLOWWARNINGS), // output shrouded class files // new Option("-scramble", "opt.scramble"), // new Option("-scrambleall", "opt.scrambleall"), // display warnings for generic unchecked operations new HiddenOption(WARNUNCHECKED) { @Override public boolean process(Options options, String option) { options.put("-Xlint:unchecked", option); return false; } }, new XOption(XMAXERRS, "opt.arg.number", "opt.maxerrs"), new XOption(XMAXWARNS, "opt.arg.number", "opt.maxwarns"), new XOption(XSTDOUT, "opt.arg.file", "opt.Xstdout") { @Override public boolean process(Options options, String option, String arg) { try { helper.setOut(new PrintWriter(new FileWriter(arg), true)); } catch (java.io.IOException e) { helper.error("err.error.writing.file", arg, e); return true; } return super.process(options, option, arg); } }, new XOption(XPRINT, "opt.print"), new XOption(XPRINTROUNDS, "opt.printRounds"), new XOption(XPRINTPROCESSORINFO, "opt.printProcessorInfo"), new XOption(XPREFER, "opt.prefer", Option.ChoiceKind.ONEOF, "source", "newer"), new XOption(XPKGINFO, "opt.pkginfo", Option.ChoiceKind.ONEOF, "always", "legacy", "nonempty"), /* -O is a no-op, accepted for backward compatibility. */ new HiddenOption(O), /* -Xjcov produces tables to support the code coverage tool jcov. */ new HiddenOption(XJCOV), /* This is a back door to the compiler's option table. * -XDx=y sets the option x to the value y. * -XDx sets the option x to the value x. */ new HiddenOption(XD) { String s; @Override public boolean matches(String s) { this.s = s; return s.startsWith(name.optionName); } @Override public boolean process(Options options, String option) { s = s.substring(name.optionName.length()); int eq = s.indexOf('='); String key = (eq < 0) ? s : s.substring(0, eq); String value = (eq < 0) ? s : s.substring(eq+1); options.put(key, value); return false; } }, // This option exists only for the purpose of documenting itself. // It's actually implemented by the CommandLine class. new Option(AT, "opt.arg.file", "opt.AT") { @Override String helpSynopsis() { hasSuffix = true; return super.helpSynopsis(); } @Override public boolean process(Options options, String option) { throw new AssertionError ("the @ flag should be caught by CommandLine."); } }, /* * TODO: With apt, the matches method accepts anything if * -XclassAsDecls is used; code elsewhere does the lookup to * see if the class name is both legal and found. * * In apt, the process method adds the candidate class file * name to a separate list. */ new HiddenOption(SOURCEFILE) { String s; @Override public boolean matches(String s) { this.s = s; return s.endsWith(".java") // Java source file || s.endsWith(".ceylon") // FIXME: Should be a FileManager query || "default".equals(s) // FIX for ceylon because default is not a valid name for Java || SourceVersion.isName(s); // Legal type name } @Override public boolean process(Options options, String option) { if (s.endsWith(".java") || s.endsWith(".ceylon") // FIXME: Should be a FileManager query ) { File f = new File(s); if (!f.exists()) { - if (s.endsWith(".ceylon")) { - // -sourcepath not -src because the COption for - // CEYLONSOURCEPATH puts it in the options map as -sourcepath - String path = options.get("-sourcepath"); - if (path != null) { - File ff = new File(path + File.separator + s); - if (ff.isFile()) { - helper.addFile(ff); - return false; - } else if (new File(path + File.separator + s.replace(".", "/")).isDirectory()) { - // A Ceylon module name that ends with .ceylon - helper.addClassName(s); - return false; - } + // -sourcepath not -src because the COption for + // CEYLONSOURCEPATH puts it in the options map as -sourcepath + String path = options.get("-sourcepath"); + if(path == null) + path = "source";// default value + // split the path + for(String part : path.split("\\"+File.pathSeparator)){ + // try to see if it's a module folder + File moduleFolder = new File(part, s.replace(".", File.separator)); + if (moduleFolder.isDirectory()) { + // A Ceylon module name that ends with .ceylon or .java + helper.addClassName(s); + return false; } } helper.error("err.file.not.found", f); return true; } if (!f.isFile()) { helper.error("err.file.not.file", f); return true; } helper.addFile(f); } else helper.addClassName(s); return false; } }, }; } public enum PkgInfo { ALWAYS, LEGACY, NONEMPTY; public static PkgInfo get(Options options) { String v = options.get(XPKGINFO); return (v == null ? PkgInfo.LEGACY : PkgInfo.valueOf(v.toUpperCase())); } } private static Map<String,Boolean> getXLintChoices() { Map<String,Boolean> choices = new LinkedHashMap<String,Boolean>(); choices.put("all", false); for (Lint.LintCategory c : Lint.LintCategory.values()) choices.put(c.option, c.hidden); for (Lint.LintCategory c : Lint.LintCategory.values()) choices.put("-" + c.option, c.hidden); choices.put("none", false); return choices; } }
true
true
public static Option[] getAll(final OptionHelper helper) { return new Option[] { new Option(G, "opt.g"), new Option(G_NONE, "opt.g.none") { @Override public boolean process(Options options, String option) { options.put("-g:", "none"); return false; } }, new Option(G_CUSTOM, "opt.g.lines.vars.source", Option.ChoiceKind.ANYOF, "lines", "vars", "source"), new XOption(XLINT, "opt.Xlint"), new XOption(XLINT_CUSTOM, "opt.Xlint.suboptlist", Option.ChoiceKind.ANYOF, getXLintChoices()), // -nowarn is retained for command-line backward compatibility new Option(NOWARN, "opt.nowarn") { @Override public boolean process(Options options, String option) { options.put("-Xlint:none", option); return false; } }, new Option(VERBOSE, "opt.verbose"), new Option(VERBOSE_CUSTOM, "opt.verbose.suboptlist") { public boolean matches(String s) { return s.startsWith("-verbose:"); } public boolean process(Options options, String option) { String suboptions = option.substring(9); options.put("-verbose:", suboptions); // enter all the -verbose suboptions as "-verbose:suboption" for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) { String tok = t.nextToken(); String opt = "-verbose:" + tok; options.put(opt, opt); } return false; } }, // -deprecation is retained for command-line backward compatibility new Option(DEPRECATION, "opt.deprecation") { @Override public boolean process(Options options, String option) { options.put("-Xlint:deprecation", option); return false; } }, new Option(CLASSPATH, "opt.arg.path", "opt.classpath"), new Option(CP, "opt.arg.path", "opt.classpath") { @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-classpath", arg); } }, new COption(CEYLONREPO, "opt.arg.url", "opt.ceylonrepo"){ @Override public boolean process(Options options, String option, String arg) { if(options != null) options.addMulti(CEYLONREPO, arg); return false; } }, new COption(CEYLONUSER, "opt.arg.value", "opt.ceylonuser"), new COption(CEYLONPASS, "opt.arg.value", "opt.ceylonpass"), new Option(SOURCEPATH, "opt.arg.path", "opt.sourcepath"), new COption(CEYLONSOURCEPATH, "opt.arg.directory", "opt.ceylonsourcepath"){ @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-sourcepath", arg); } }, new Option(BOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") { @Override public boolean process(Options options, String option, String arg) { options.remove("-Xbootclasspath/p:"); options.remove("-Xbootclasspath/a:"); return super.process(options, option, arg); } }, new XOption(XBOOTCLASSPATH_PREPEND,"opt.arg.path", "opt.Xbootclasspath.p"), new XOption(XBOOTCLASSPATH_APPEND, "opt.arg.path", "opt.Xbootclasspath.a"), new XOption(XBOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") { @Override public boolean process(Options options, String option, String arg) { options.remove("-Xbootclasspath/p:"); options.remove("-Xbootclasspath/a:"); return super.process(options, "-bootclasspath", arg); } }, new Option(EXTDIRS, "opt.arg.dirs", "opt.extdirs"), new XOption(DJAVA_EXT_DIRS, "opt.arg.dirs", "opt.extdirs") { @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-extdirs", arg); } }, new Option(ENDORSEDDIRS, "opt.arg.dirs", "opt.endorseddirs"), new XOption(DJAVA_ENDORSED_DIRS, "opt.arg.dirs", "opt.endorseddirs") { @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-endorseddirs", arg); } }, new Option(PROC, "opt.proc.none.only", Option.ChoiceKind.ONEOF, "none", "only"), new Option(PROCESSOR, "opt.arg.class.list", "opt.processor"), new Option(PROCESSORPATH, "opt.arg.path", "opt.processorpath"), new Option(D, "opt.arg.directory", "opt.d"), new COption(CEYLONOUT, "opt.arg.url", "opt.ceylonout"){ @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-d", arg); } }, new Option(S, "opt.arg.directory", "opt.sourceDest"), new Option(IMPLICIT, "opt.implicit", Option.ChoiceKind.ONEOF, "none", "class"), new Option(ENCODING, "opt.arg.encoding", "opt.encoding"), new Option(SOURCE, "opt.arg.release", "opt.source") { @Override public boolean process(Options options, String option, String operand) { Source source = Source.lookup(operand); if (source == null) { helper.error("err.invalid.source", operand); return true; } return super.process(options, option, operand); } }, new Option(TARGET, "opt.arg.release", "opt.target") { @Override public boolean process(Options options, String option, String operand) { Target target = Target.lookup(operand); if (target == null) { helper.error("err.invalid.target", operand); return true; } return super.process(options, option, operand); } }, new COption(VERSION, "opt.version") { @Override public boolean process(Options options, String option) { helper.printVersion(); return super.process(options, option); } }, new HiddenOption(FULLVERSION) { @Override public boolean process(Options options, String option) { helper.printFullVersion(); return super.process(options, option); } }, new HiddenOption(DIAGS) { @Override public boolean process(Options options, String option) { Option xd = getOptions(helper, EnumSet.of(XD))[0]; option = option.substring(option.indexOf('=') + 1); String diagsOption = option.contains("%") ? "-XDdiagsFormat=" : "-XDdiags="; diagsOption += option; if (xd.matches(diagsOption)) return xd.process(options, diagsOption); else return false; } }, new COption(HELP, "opt.help") { @Override public boolean process(Options options, String option) { helper.printHelp(); return super.process(options, option); } }, new COption(JHELP, "opt.jhelp") { @Override public boolean process(Options options, String option) { helper.printJhelp(); return super.process(options, option); } }, new Option(A, "opt.arg.key.equals.value","opt.A") { @Override String helpSynopsis() { hasSuffix = true; return super.helpSynopsis(); } @Override public boolean matches(String arg) { return arg.startsWith("-A"); } @Override public boolean hasArg() { return false; } // Mapping for processor options created in // JavacProcessingEnvironment @Override public boolean process(Options options, String option) { int argLength = option.length(); if (argLength == 2) { helper.error("err.empty.A.argument"); return true; } int sepIndex = option.indexOf('='); String key = option.substring(2, (sepIndex != -1 ? sepIndex : argLength) ); if (!JavacProcessingEnvironment.isValidOptionName(key)) { helper.error("err.invalid.A.key", option); return true; } return process(options, option, option); } }, new Option(X, "opt.X") { @Override public boolean process(Options options, String option) { helper.printXhelp(); return super.process(options, option); } }, // This option exists only for the purpose of documenting itself. // It's actually implemented by the launcher. new Option(J, "opt.arg.flag", "opt.J") { @Override String helpSynopsis() { hasSuffix = true; return super.helpSynopsis(); } @Override public boolean process(Options options, String option) { throw new AssertionError ("the -J flag should be caught by the launcher."); } }, // stop after parsing and attributing. // new HiddenOption("-attrparseonly"), // new Option("-moreinfo", "opt.moreinfo") { new HiddenOption(MOREINFO) { @Override public boolean process(Options options, String option) { Type.moreInfo = true; return super.process(options, option); } }, // treat warnings as errors new Option(WERROR, "opt.Werror"), new Option(SRC, "opt.arg.src", "opt.src") { public boolean process(Options options, String option, String arg) { return super.process(options, "-src", arg); } }, // use complex inference from context in the position of a method call argument new HiddenOption(COMPLEXINFERENCE), // generare source stubs // new HiddenOption("-stubs"), // relax some constraints to allow compiling from stubs // new HiddenOption("-relax"), // output source after translating away inner classes // new Option("-printflat", "opt.printflat"), // new HiddenOption("-printflat"), // display scope search details // new Option("-printsearch", "opt.printsearch"), // new HiddenOption("-printsearch"), // prompt after each error // new Option("-prompt", "opt.prompt"), new HiddenOption(PROMPT), // dump stack on error new HiddenOption(DOE), // output source after type erasure // new Option("-s", "opt.s"), new HiddenOption(PRINTSOURCE), // allow us to compile ceylon.language new HiddenOption(BOOTSTRAPCEYLON), // do not halt on typechecker warnings new HiddenOption(CEYLONALLOWWARNINGS), // output shrouded class files // new Option("-scramble", "opt.scramble"), // new Option("-scrambleall", "opt.scrambleall"), // display warnings for generic unchecked operations new HiddenOption(WARNUNCHECKED) { @Override public boolean process(Options options, String option) { options.put("-Xlint:unchecked", option); return false; } }, new XOption(XMAXERRS, "opt.arg.number", "opt.maxerrs"), new XOption(XMAXWARNS, "opt.arg.number", "opt.maxwarns"), new XOption(XSTDOUT, "opt.arg.file", "opt.Xstdout") { @Override public boolean process(Options options, String option, String arg) { try { helper.setOut(new PrintWriter(new FileWriter(arg), true)); } catch (java.io.IOException e) { helper.error("err.error.writing.file", arg, e); return true; } return super.process(options, option, arg); } }, new XOption(XPRINT, "opt.print"), new XOption(XPRINTROUNDS, "opt.printRounds"), new XOption(XPRINTPROCESSORINFO, "opt.printProcessorInfo"), new XOption(XPREFER, "opt.prefer", Option.ChoiceKind.ONEOF, "source", "newer"), new XOption(XPKGINFO, "opt.pkginfo", Option.ChoiceKind.ONEOF, "always", "legacy", "nonempty"), /* -O is a no-op, accepted for backward compatibility. */ new HiddenOption(O), /* -Xjcov produces tables to support the code coverage tool jcov. */ new HiddenOption(XJCOV), /* This is a back door to the compiler's option table. * -XDx=y sets the option x to the value y. * -XDx sets the option x to the value x. */ new HiddenOption(XD) { String s; @Override public boolean matches(String s) { this.s = s; return s.startsWith(name.optionName); } @Override public boolean process(Options options, String option) { s = s.substring(name.optionName.length()); int eq = s.indexOf('='); String key = (eq < 0) ? s : s.substring(0, eq); String value = (eq < 0) ? s : s.substring(eq+1); options.put(key, value); return false; } }, // This option exists only for the purpose of documenting itself. // It's actually implemented by the CommandLine class. new Option(AT, "opt.arg.file", "opt.AT") { @Override String helpSynopsis() { hasSuffix = true; return super.helpSynopsis(); } @Override public boolean process(Options options, String option) { throw new AssertionError ("the @ flag should be caught by CommandLine."); } }, /* * TODO: With apt, the matches method accepts anything if * -XclassAsDecls is used; code elsewhere does the lookup to * see if the class name is both legal and found. * * In apt, the process method adds the candidate class file * name to a separate list. */ new HiddenOption(SOURCEFILE) { String s; @Override public boolean matches(String s) { this.s = s; return s.endsWith(".java") // Java source file || s.endsWith(".ceylon") // FIXME: Should be a FileManager query || "default".equals(s) // FIX for ceylon because default is not a valid name for Java || SourceVersion.isName(s); // Legal type name } @Override public boolean process(Options options, String option) { if (s.endsWith(".java") || s.endsWith(".ceylon") // FIXME: Should be a FileManager query ) { File f = new File(s); if (!f.exists()) { if (s.endsWith(".ceylon")) { // -sourcepath not -src because the COption for // CEYLONSOURCEPATH puts it in the options map as -sourcepath String path = options.get("-sourcepath"); if (path != null) { File ff = new File(path + File.separator + s); if (ff.isFile()) { helper.addFile(ff); return false; } else if (new File(path + File.separator + s.replace(".", "/")).isDirectory()) { // A Ceylon module name that ends with .ceylon helper.addClassName(s); return false; } } } helper.error("err.file.not.found", f); return true; } if (!f.isFile()) { helper.error("err.file.not.file", f); return true; } helper.addFile(f); } else helper.addClassName(s); return false; } }, }; }
public static Option[] getAll(final OptionHelper helper) { return new Option[] { new Option(G, "opt.g"), new Option(G_NONE, "opt.g.none") { @Override public boolean process(Options options, String option) { options.put("-g:", "none"); return false; } }, new Option(G_CUSTOM, "opt.g.lines.vars.source", Option.ChoiceKind.ANYOF, "lines", "vars", "source"), new XOption(XLINT, "opt.Xlint"), new XOption(XLINT_CUSTOM, "opt.Xlint.suboptlist", Option.ChoiceKind.ANYOF, getXLintChoices()), // -nowarn is retained for command-line backward compatibility new Option(NOWARN, "opt.nowarn") { @Override public boolean process(Options options, String option) { options.put("-Xlint:none", option); return false; } }, new Option(VERBOSE, "opt.verbose"), new Option(VERBOSE_CUSTOM, "opt.verbose.suboptlist") { public boolean matches(String s) { return s.startsWith("-verbose:"); } public boolean process(Options options, String option) { String suboptions = option.substring(9); options.put("-verbose:", suboptions); // enter all the -verbose suboptions as "-verbose:suboption" for (StringTokenizer t = new StringTokenizer(suboptions, ","); t.hasMoreTokens(); ) { String tok = t.nextToken(); String opt = "-verbose:" + tok; options.put(opt, opt); } return false; } }, // -deprecation is retained for command-line backward compatibility new Option(DEPRECATION, "opt.deprecation") { @Override public boolean process(Options options, String option) { options.put("-Xlint:deprecation", option); return false; } }, new Option(CLASSPATH, "opt.arg.path", "opt.classpath"), new Option(CP, "opt.arg.path", "opt.classpath") { @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-classpath", arg); } }, new COption(CEYLONREPO, "opt.arg.url", "opt.ceylonrepo"){ @Override public boolean process(Options options, String option, String arg) { if(options != null) options.addMulti(CEYLONREPO, arg); return false; } }, new COption(CEYLONUSER, "opt.arg.value", "opt.ceylonuser"), new COption(CEYLONPASS, "opt.arg.value", "opt.ceylonpass"), new Option(SOURCEPATH, "opt.arg.path", "opt.sourcepath"), new COption(CEYLONSOURCEPATH, "opt.arg.directory", "opt.ceylonsourcepath"){ @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-sourcepath", arg); } }, new Option(BOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") { @Override public boolean process(Options options, String option, String arg) { options.remove("-Xbootclasspath/p:"); options.remove("-Xbootclasspath/a:"); return super.process(options, option, arg); } }, new XOption(XBOOTCLASSPATH_PREPEND,"opt.arg.path", "opt.Xbootclasspath.p"), new XOption(XBOOTCLASSPATH_APPEND, "opt.arg.path", "opt.Xbootclasspath.a"), new XOption(XBOOTCLASSPATH, "opt.arg.path", "opt.bootclasspath") { @Override public boolean process(Options options, String option, String arg) { options.remove("-Xbootclasspath/p:"); options.remove("-Xbootclasspath/a:"); return super.process(options, "-bootclasspath", arg); } }, new Option(EXTDIRS, "opt.arg.dirs", "opt.extdirs"), new XOption(DJAVA_EXT_DIRS, "opt.arg.dirs", "opt.extdirs") { @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-extdirs", arg); } }, new Option(ENDORSEDDIRS, "opt.arg.dirs", "opt.endorseddirs"), new XOption(DJAVA_ENDORSED_DIRS, "opt.arg.dirs", "opt.endorseddirs") { @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-endorseddirs", arg); } }, new Option(PROC, "opt.proc.none.only", Option.ChoiceKind.ONEOF, "none", "only"), new Option(PROCESSOR, "opt.arg.class.list", "opt.processor"), new Option(PROCESSORPATH, "opt.arg.path", "opt.processorpath"), new Option(D, "opt.arg.directory", "opt.d"), new COption(CEYLONOUT, "opt.arg.url", "opt.ceylonout"){ @Override public boolean process(Options options, String option, String arg) { return super.process(options, "-d", arg); } }, new Option(S, "opt.arg.directory", "opt.sourceDest"), new Option(IMPLICIT, "opt.implicit", Option.ChoiceKind.ONEOF, "none", "class"), new Option(ENCODING, "opt.arg.encoding", "opt.encoding"), new Option(SOURCE, "opt.arg.release", "opt.source") { @Override public boolean process(Options options, String option, String operand) { Source source = Source.lookup(operand); if (source == null) { helper.error("err.invalid.source", operand); return true; } return super.process(options, option, operand); } }, new Option(TARGET, "opt.arg.release", "opt.target") { @Override public boolean process(Options options, String option, String operand) { Target target = Target.lookup(operand); if (target == null) { helper.error("err.invalid.target", operand); return true; } return super.process(options, option, operand); } }, new COption(VERSION, "opt.version") { @Override public boolean process(Options options, String option) { helper.printVersion(); return super.process(options, option); } }, new HiddenOption(FULLVERSION) { @Override public boolean process(Options options, String option) { helper.printFullVersion(); return super.process(options, option); } }, new HiddenOption(DIAGS) { @Override public boolean process(Options options, String option) { Option xd = getOptions(helper, EnumSet.of(XD))[0]; option = option.substring(option.indexOf('=') + 1); String diagsOption = option.contains("%") ? "-XDdiagsFormat=" : "-XDdiags="; diagsOption += option; if (xd.matches(diagsOption)) return xd.process(options, diagsOption); else return false; } }, new COption(HELP, "opt.help") { @Override public boolean process(Options options, String option) { helper.printHelp(); return super.process(options, option); } }, new COption(JHELP, "opt.jhelp") { @Override public boolean process(Options options, String option) { helper.printJhelp(); return super.process(options, option); } }, new Option(A, "opt.arg.key.equals.value","opt.A") { @Override String helpSynopsis() { hasSuffix = true; return super.helpSynopsis(); } @Override public boolean matches(String arg) { return arg.startsWith("-A"); } @Override public boolean hasArg() { return false; } // Mapping for processor options created in // JavacProcessingEnvironment @Override public boolean process(Options options, String option) { int argLength = option.length(); if (argLength == 2) { helper.error("err.empty.A.argument"); return true; } int sepIndex = option.indexOf('='); String key = option.substring(2, (sepIndex != -1 ? sepIndex : argLength) ); if (!JavacProcessingEnvironment.isValidOptionName(key)) { helper.error("err.invalid.A.key", option); return true; } return process(options, option, option); } }, new Option(X, "opt.X") { @Override public boolean process(Options options, String option) { helper.printXhelp(); return super.process(options, option); } }, // This option exists only for the purpose of documenting itself. // It's actually implemented by the launcher. new Option(J, "opt.arg.flag", "opt.J") { @Override String helpSynopsis() { hasSuffix = true; return super.helpSynopsis(); } @Override public boolean process(Options options, String option) { throw new AssertionError ("the -J flag should be caught by the launcher."); } }, // stop after parsing and attributing. // new HiddenOption("-attrparseonly"), // new Option("-moreinfo", "opt.moreinfo") { new HiddenOption(MOREINFO) { @Override public boolean process(Options options, String option) { Type.moreInfo = true; return super.process(options, option); } }, // treat warnings as errors new Option(WERROR, "opt.Werror"), new Option(SRC, "opt.arg.src", "opt.src") { public boolean process(Options options, String option, String arg) { return super.process(options, "-src", arg); } }, // use complex inference from context in the position of a method call argument new HiddenOption(COMPLEXINFERENCE), // generare source stubs // new HiddenOption("-stubs"), // relax some constraints to allow compiling from stubs // new HiddenOption("-relax"), // output source after translating away inner classes // new Option("-printflat", "opt.printflat"), // new HiddenOption("-printflat"), // display scope search details // new Option("-printsearch", "opt.printsearch"), // new HiddenOption("-printsearch"), // prompt after each error // new Option("-prompt", "opt.prompt"), new HiddenOption(PROMPT), // dump stack on error new HiddenOption(DOE), // output source after type erasure // new Option("-s", "opt.s"), new HiddenOption(PRINTSOURCE), // allow us to compile ceylon.language new HiddenOption(BOOTSTRAPCEYLON), // do not halt on typechecker warnings new HiddenOption(CEYLONALLOWWARNINGS), // output shrouded class files // new Option("-scramble", "opt.scramble"), // new Option("-scrambleall", "opt.scrambleall"), // display warnings for generic unchecked operations new HiddenOption(WARNUNCHECKED) { @Override public boolean process(Options options, String option) { options.put("-Xlint:unchecked", option); return false; } }, new XOption(XMAXERRS, "opt.arg.number", "opt.maxerrs"), new XOption(XMAXWARNS, "opt.arg.number", "opt.maxwarns"), new XOption(XSTDOUT, "opt.arg.file", "opt.Xstdout") { @Override public boolean process(Options options, String option, String arg) { try { helper.setOut(new PrintWriter(new FileWriter(arg), true)); } catch (java.io.IOException e) { helper.error("err.error.writing.file", arg, e); return true; } return super.process(options, option, arg); } }, new XOption(XPRINT, "opt.print"), new XOption(XPRINTROUNDS, "opt.printRounds"), new XOption(XPRINTPROCESSORINFO, "opt.printProcessorInfo"), new XOption(XPREFER, "opt.prefer", Option.ChoiceKind.ONEOF, "source", "newer"), new XOption(XPKGINFO, "opt.pkginfo", Option.ChoiceKind.ONEOF, "always", "legacy", "nonempty"), /* -O is a no-op, accepted for backward compatibility. */ new HiddenOption(O), /* -Xjcov produces tables to support the code coverage tool jcov. */ new HiddenOption(XJCOV), /* This is a back door to the compiler's option table. * -XDx=y sets the option x to the value y. * -XDx sets the option x to the value x. */ new HiddenOption(XD) { String s; @Override public boolean matches(String s) { this.s = s; return s.startsWith(name.optionName); } @Override public boolean process(Options options, String option) { s = s.substring(name.optionName.length()); int eq = s.indexOf('='); String key = (eq < 0) ? s : s.substring(0, eq); String value = (eq < 0) ? s : s.substring(eq+1); options.put(key, value); return false; } }, // This option exists only for the purpose of documenting itself. // It's actually implemented by the CommandLine class. new Option(AT, "opt.arg.file", "opt.AT") { @Override String helpSynopsis() { hasSuffix = true; return super.helpSynopsis(); } @Override public boolean process(Options options, String option) { throw new AssertionError ("the @ flag should be caught by CommandLine."); } }, /* * TODO: With apt, the matches method accepts anything if * -XclassAsDecls is used; code elsewhere does the lookup to * see if the class name is both legal and found. * * In apt, the process method adds the candidate class file * name to a separate list. */ new HiddenOption(SOURCEFILE) { String s; @Override public boolean matches(String s) { this.s = s; return s.endsWith(".java") // Java source file || s.endsWith(".ceylon") // FIXME: Should be a FileManager query || "default".equals(s) // FIX for ceylon because default is not a valid name for Java || SourceVersion.isName(s); // Legal type name } @Override public boolean process(Options options, String option) { if (s.endsWith(".java") || s.endsWith(".ceylon") // FIXME: Should be a FileManager query ) { File f = new File(s); if (!f.exists()) { // -sourcepath not -src because the COption for // CEYLONSOURCEPATH puts it in the options map as -sourcepath String path = options.get("-sourcepath"); if(path == null) path = "source";// default value // split the path for(String part : path.split("\\"+File.pathSeparator)){ // try to see if it's a module folder File moduleFolder = new File(part, s.replace(".", File.separator)); if (moduleFolder.isDirectory()) { // A Ceylon module name that ends with .ceylon or .java helper.addClassName(s); return false; } } helper.error("err.file.not.found", f); return true; } if (!f.isFile()) { helper.error("err.file.not.file", f); return true; } helper.addFile(f); } else helper.addClassName(s); return false; } }, }; }
diff --git a/cobertura/src/net/sourceforge/cobertura/util/FileLocker.java b/cobertura/src/net/sourceforge/cobertura/util/FileLocker.java index 803794c..b415593 100644 --- a/cobertura/src/net/sourceforge/cobertura/util/FileLocker.java +++ b/cobertura/src/net/sourceforge/cobertura/util/FileLocker.java @@ -1,192 +1,200 @@ /* Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2006 John Lewis * Copyright (C) 2006 Mark Doliner * * Note: This file is dual licensed under the GPL and the Apache * Source License 1.1 (so that it can be used from both the main * Cobertura classes and the ant tasks). * * Cobertura 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. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.util; import java.io.File; import java.io.FileNotFoundException; import java.io.RandomAccessFile; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * This class controls access to any file so that multiple JVMs will * not be able to write to the file at the same time. * * A file called "filename.lock" is created and Java's FileLock class * is used to lock the file. * * The java.nio classes were introduced in Java 1.4, so this class * does a no-op when used with Java 1.3. The class maintains * compatability with Java 1.3 by accessing the java.nio classes * using reflection. * * @author John Lewis * @author Mark Doliner */ public class FileLocker { /** * An object of type FileLock, created using reflection. */ private Object lock = null; /** * An object of type FileChannel, created using reflection. */ private Object lockChannel = null; /** * A file called "filename.lock" that resides in the same directory * as "filename" */ private File lockFile; public FileLocker(File file) { String lockFileName = file.getName() + ".lock"; File parent = file.getParentFile(); if (parent == null) { lockFile = new File(lockFileName); } else { lockFile = new File(parent, lockFileName); } lockFile.deleteOnExit(); } /** * Obtains a lock on the file. This blocks until the lock is obtained. */ public boolean lock() { if (System.getProperty("java.version").startsWith("1.3")) { return true; } try { Class aClass = Class.forName("java.io.RandomAccessFile"); Method method = aClass.getDeclaredMethod("getChannel", (Class[])null); lockChannel = method.invoke(new RandomAccessFile(lockFile, "rw"), (Object[])null); } catch (FileNotFoundException e) { System.err.println("Unable to get lock channel for " + lockFile.getAbsolutePath() + ": " + e.getLocalizedMessage()); return false; } catch (InvocationTargetException e) { System.err.println("Unable to get lock channel for " + lockFile.getAbsolutePath() + ": " + e.getLocalizedMessage()); return false; } catch (Throwable t) { System.err.println("Unable to execute RandomAccessFile.getChannel() using reflection: " + t.getLocalizedMessage()); t.printStackTrace(); } try { Class aClass = Class.forName("java.nio.channels.FileChannel"); Method method = aClass.getDeclaredMethod("lock", (Class[])null); lock = method.invoke(lockChannel, (Object[])null); } catch (InvocationTargetException e) { + System.err.println("---------------------------------------"); + e.printStackTrace(System.err); + System.err.println("---------------------------------------"); System.err.println("Unable to get lock on " + lockFile.getAbsolutePath() + ": " + e.getLocalizedMessage()); + System.err.println("This is known to happen on Linux kernel 2.6.20."); + System.err.println("Make sure cobertura.jar is in your server's base classpath."); + System.err.println("Don't put multiple copies of cobertura.jar in different WEB-INF/lib directories."); + System.err.println("It is important that cobertura be loaded by the parent classloader."); + System.err.println("---------------------------------------"); return false; } catch (Throwable t) { System.err.println("Unable to execute FileChannel.lock() using reflection: " + t.getLocalizedMessage()); t.printStackTrace(); } return true; } /** * Releases the lock on the file. */ public void release() { if (lock != null) lock = releaseFileLock(lock); if (lockChannel != null) lockChannel = closeChannel(lockChannel); lockFile.delete(); } private static Object releaseFileLock(Object lock) { try { Class aClass = Class.forName("java.nio.channels.FileLock"); Method method = aClass.getDeclaredMethod("isValid", (Class[])null); if (((Boolean)method.invoke(lock, (Object[])null)).booleanValue()) { method = aClass.getDeclaredMethod("release", (Class[])null); method.invoke(lock, (Object[])null); lock = null; } } catch (Throwable t) { System.err.println("Unable to release locked file: " + t.getLocalizedMessage()); } return lock; } private static Object closeChannel(Object channel) { try { Class aClass = Class.forName("java.nio.channels.spi.AbstractInterruptibleChannel"); Method method = aClass.getDeclaredMethod("isOpen", (Class[])null); if (((Boolean)method.invoke(channel, (Object[])null)).booleanValue()) { method = aClass.getDeclaredMethod("close", (Class[])null); method.invoke(channel, (Object[])null); channel = null; } } catch (Throwable t) { System.err.println("Unable to close file channel: " + t.getLocalizedMessage()); } return channel; } }
false
true
public boolean lock() { if (System.getProperty("java.version").startsWith("1.3")) { return true; } try { Class aClass = Class.forName("java.io.RandomAccessFile"); Method method = aClass.getDeclaredMethod("getChannel", (Class[])null); lockChannel = method.invoke(new RandomAccessFile(lockFile, "rw"), (Object[])null); } catch (FileNotFoundException e) { System.err.println("Unable to get lock channel for " + lockFile.getAbsolutePath() + ": " + e.getLocalizedMessage()); return false; } catch (InvocationTargetException e) { System.err.println("Unable to get lock channel for " + lockFile.getAbsolutePath() + ": " + e.getLocalizedMessage()); return false; } catch (Throwable t) { System.err.println("Unable to execute RandomAccessFile.getChannel() using reflection: " + t.getLocalizedMessage()); t.printStackTrace(); } try { Class aClass = Class.forName("java.nio.channels.FileChannel"); Method method = aClass.getDeclaredMethod("lock", (Class[])null); lock = method.invoke(lockChannel, (Object[])null); } catch (InvocationTargetException e) { System.err.println("Unable to get lock on " + lockFile.getAbsolutePath() + ": " + e.getLocalizedMessage()); return false; } catch (Throwable t) { System.err.println("Unable to execute FileChannel.lock() using reflection: " + t.getLocalizedMessage()); t.printStackTrace(); } return true; }
public boolean lock() { if (System.getProperty("java.version").startsWith("1.3")) { return true; } try { Class aClass = Class.forName("java.io.RandomAccessFile"); Method method = aClass.getDeclaredMethod("getChannel", (Class[])null); lockChannel = method.invoke(new RandomAccessFile(lockFile, "rw"), (Object[])null); } catch (FileNotFoundException e) { System.err.println("Unable to get lock channel for " + lockFile.getAbsolutePath() + ": " + e.getLocalizedMessage()); return false; } catch (InvocationTargetException e) { System.err.println("Unable to get lock channel for " + lockFile.getAbsolutePath() + ": " + e.getLocalizedMessage()); return false; } catch (Throwable t) { System.err.println("Unable to execute RandomAccessFile.getChannel() using reflection: " + t.getLocalizedMessage()); t.printStackTrace(); } try { Class aClass = Class.forName("java.nio.channels.FileChannel"); Method method = aClass.getDeclaredMethod("lock", (Class[])null); lock = method.invoke(lockChannel, (Object[])null); } catch (InvocationTargetException e) { System.err.println("---------------------------------------"); e.printStackTrace(System.err); System.err.println("---------------------------------------"); System.err.println("Unable to get lock on " + lockFile.getAbsolutePath() + ": " + e.getLocalizedMessage()); System.err.println("This is known to happen on Linux kernel 2.6.20."); System.err.println("Make sure cobertura.jar is in your server's base classpath."); System.err.println("Don't put multiple copies of cobertura.jar in different WEB-INF/lib directories."); System.err.println("It is important that cobertura be loaded by the parent classloader."); System.err.println("---------------------------------------"); return false; } catch (Throwable t) { System.err.println("Unable to execute FileChannel.lock() using reflection: " + t.getLocalizedMessage()); t.printStackTrace(); } return true; }
diff --git a/src/main/wikiduper/analysis/HistogramClusters.java b/src/main/wikiduper/analysis/HistogramClusters.java index 5aa4942..7d15b54 100644 --- a/src/main/wikiduper/analysis/HistogramClusters.java +++ b/src/main/wikiduper/analysis/HistogramClusters.java @@ -1,435 +1,435 @@ package wikiduper.analysis; import java.io.EOFException; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.TreeMap; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.apache.log4j.Logger; import edu.umd.cloud9.io.pair.PairOfStrings; import wikiduper.utils.MergeClusters; public class HistogramClusters extends Configured implements Tool { private static final Logger LOG = Logger.getLogger(MergeClusters.class); private static final String INPUT = "input"; private static final String THRESH = "large_cluster_threshold"; private static final String BINSIZE = "bin_size"; private static final String MAX = "max_bin"; @SuppressWarnings("static-access") @Override public int run(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path") .hasArg().withDescription("minhash pipeline output").create(INPUT)); options.addOption(OptionBuilder.withArgName("num") .hasArg().withDescription("large cluster threshold").create(THRESH)); options.addOption(OptionBuilder.withArgName("num") .hasArg().withDescription("size of histogram bins").create(BINSIZE)); options.addOption(OptionBuilder.withArgName("num") .hasArg().withDescription("max bin to display in graph").create(MAX)); CommandLine cmdline; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); return -1; } if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(THRESH) || !cmdline.hasOption(BINSIZE) || !cmdline.hasOption(MAX)){ HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); formatter.printHelp(this.getClass().getName(), options); ToolRunner.printGenericCommandUsage(System.out); return -1; } String inputPath = cmdline.getOptionValue(INPUT); int thresh = Integer.parseInt(cmdline.getOptionValue(THRESH)); //30; int binsize = Integer.parseInt(cmdline.getOptionValue(BINSIZE));//30; int max = Integer.parseInt(cmdline.getOptionValue(MAX)); //30; 1501; LOG.info("Tool name: " + this.getClass().getName()); JobConf conf = new JobConf(getConf(), MergeClusters.class); conf.set(INPUT, inputPath); conf.setInt(THRESH, thresh); conf.setInt(BINSIZE, binsize); conf.setInt(MAX, max); getHistogram(conf);//inputPath,conf); return 0; } public void getHistogram(JobConf conf){ String filein = conf.get(INPUT); int max = conf.getInt(MAX, 30); int thresh = conf.getInt(THRESH, 30); int binsize = conf.getInt(BINSIZE, 10); //IntWritable, Text // Overall histogram: cluster sizes -> cluster cts TreeMap<Integer,Integer> histogram = new TreeMap<Integer,Integer>(); // Unique title histogram: # unique titles in cluster -> cluster cts TreeMap<Integer,Integer> titlehistogram = new TreeMap<Integer,Integer>(); // Unique sentence histogra: # unique sentences in cluster -> cluster cts TreeMap<Integer,Integer> sentencehistogram = new TreeMap<Integer,Integer>(); // Sets to keep track of overall unique title and sentences //HashSet<String> titleset = new HashSet<String>(); HashSet<String> sentenceset = new HashSet<String>(); // Per cluster data structures ArrayList<String> cluster = new ArrayList<String>(); HashSet<String> clustertitles = new HashSet<String>(); HashSet<String> clustersentences = new HashSet<String>(); int bigclusterlinect = 0; int smallclusterlinect = 0; int clusterct = 0; int linect = 0; long clustcurr = -1; int maxclustersize = 0; //Pattern linepat = Pattern.compile("^([^\t]+)\t(.*)$"); //Pattern linepat = Pattern.compile("^([^\t]+)\t((?>\\P{M}\\p{M}*)+)$"); try { FileSystem fs = FileSystem.get(conf); System.out.println("filein = " + filein); FileStatus[] infiles = fs.globStatus(new Path(filein + "/part-*")); for(FileStatus filestatus : infiles){ System.out.println(filestatus.getPath().toString()); try{ FSDataInputStream in = fs.open(filestatus.getPath()); SequenceFile.Reader reader; reader = new SequenceFile.Reader(conf, SequenceFile.Reader.stream(in)); LongWritable clusterid = new LongWritable(); PairOfStrings articlesentence = new PairOfStrings(); while(reader.next(clusterid, articlesentence)){ String linetext = articlesentence.toString().replace("\n", " "); //Matcher m = linepat.matcher(linetext); String title = ""; String sentence = ""; title = articlesentence.getLeftElement(); sentence = articlesentence.getRightElement(); if(clustcurr == -1){ clustcurr = clusterid.get(); } if(!(clustcurr == clusterid.get())){ if(clusterct % 10000 == 0) System.err.println("clusterct = " + clusterct); // Once we've found a new cluster Update each histogram int size = cluster.size(); if(size > maxclustersize){ maxclustersize = size; } if(size > thresh){ bigclusterlinect+=size; }else{ smallclusterlinect+=size; } if(!histogram.containsKey(size)){ histogram.put(size, 0); } histogram.put(size, histogram.get(size) + 1); size = clustertitles.size(); if(!titlehistogram.containsKey(size)){ titlehistogram.put(size, 0); } titlehistogram.put(size, titlehistogram.get(size) + 1); size = clustersentences.size(); if(!sentencehistogram.containsKey(size)){ sentencehistogram.put(size, 0); } sentencehistogram.put(size, sentencehistogram.get(size) + 1); /* // Code for examining cluster contents if(cluster.size() > 10000){ int ct = 0; System.out.println("Cluster size: " + cluster.size()); System.out.println("N unique sentences " + clustersentences.size()); System.out.println("N unique titles " + clustertitles.size()); for(String l : cluster){ if(ct > 10) break; System.out.println(l); ct++; } System.out.println(); } */ // Clear per cluster data structures cluster.clear(); clustersentences.clear(); clustertitles.clear(); clusterct++; } clustcurr = clusterid.get(); cluster.add(articlesentence.toString()); clustersentences.add(sentence); clustertitles.add(title); //titleset.add(title); sentenceset.add(sentence); linect++; clusterid = new LongWritable(); articlesentence = new PairOfStrings(); } reader.close(); }catch (EOFException e) { // For some reason it doesn't know when the input stream is done?? } // Update one time at the end of each file input loop to add remaining cluster int size = cluster.size(); if(size > thresh){ bigclusterlinect+=size; }else{ smallclusterlinect+=size; } if(!histogram.containsKey(size)){ histogram.put(size, 0); } histogram.put(size, histogram.get(size) + 1); size = clustertitles.size(); if(!titlehistogram.containsKey(size)){ titlehistogram.put(size, 0); } titlehistogram.put(size, titlehistogram.get(size) + 1); size = clustersentences.size(); if(!sentencehistogram.containsKey(size)){ sentencehistogram.put(size, 0); } sentencehistogram.put(size, sentencehistogram.get(size) + 1); // Clear per cluster data structures cluster.clear(); clustersentences.clear(); clustertitles.clear(); clusterct++; clusterct++; } System.out.println("N lines: " + linect); System.out.println("N clusters: " + clusterct); //System.out.println("N unique titles: " + titleset.size()); System.out.println("N unique sentences: " + sentenceset.size()); StringBuffer histvals = new StringBuffer(); StringBuffer histkeys = new StringBuffer(); System.out.println("Cluster histogram"); int sum = 0; int sumsentence = 0; int sumtitle = 0; int gtx = 0; int ltex = 0; for(int b : histogram.keySet()){ //System.out.println(b + "\t" + histogram.get(b)); if(b <= thresh){ ltex += histogram.get(b); }else{ gtx += histogram.get(b); } } System.out.println("Cluster threshold: " + thresh); System.out.println("N Lte " + thresh + ": " + ltex + " " + (1.0*ltex/clusterct)); System.out.println("N gt " + thresh + ": " + gtx + " " + (1.0*gtx/clusterct)); System.out.println("Number of lines in big clusters = " + bigclusterlinect + " " + (1.0*bigclusterlinect/linect)); System.out.println("Number of lines in small clusters = " + smallclusterlinect + " " + (1.0*smallclusterlinect/linect)); System.out.println("Size of largest cluster: " + maxclustersize); int binmax = max>0?max:histogram.lastKey(); for(int i=1;i<=binmax;i++){ int b = histogram.containsKey(i) ? histogram.get(i) : 0; sum+=b; b = sentencehistogram.containsKey(i) ? sentencehistogram.get(i) : 0; sumsentence+=b; b = titlehistogram.containsKey(i) ? titlehistogram.get(i) : 0; sumtitle+=b; if((i+1)%binsize == 0){ int rangel = i-binsize; int rangeh = i-1; histkeys.append(","); histkeys.append("\""); - if((i-binsize)%1000 == 0){ + if((i-binsize)%100 == 0){ histkeys.append(rangel); //histkeys.append("-"); //histkeys.append(rangeh); } histkeys.append("\""); histvals.append(","); // histvals.append("{"); histvals.append(sum); // histvals.append(","); // histvals.append(sumsentence); // histvals.append(","); // histvals.append(sumtitle); // histvals.append("}"); sum = 0; sumsentence = 0; sumtitle = 0; } } // Calculate rest of distribution weight sum = 0; sumsentence = 0; sumtitle = 0; for(int i=binmax;i<=histogram.lastKey();i++){ int b = histogram.containsKey(i) ? histogram.get(i) : 0; sum+=b; b = sentencehistogram.containsKey(i) ? sentencehistogram.get(i) : 0; sumsentence+=b; b = titlehistogram.containsKey(i) ? titlehistogram.get(i) : 0; sumtitle+=b; } int rangel = binmax; int rangeh = histogram.lastKey(); histkeys.append(","); histkeys.append("\""); histkeys.append(rangel); histkeys.append("+"); // histkeys.append("-"); // histkeys.append(rangeh); histkeys.append("\""); histvals.append(","); histvals.append(sum); //Mathematic output: System.out.println("BarChart[{"+histvals.substring(1)+"}, " +"ChartLabels ->Placed[{(Rotate[#, Pi/4] & /@{"+histkeys.substring(1)+"}), " +"{" + histvals.substring(1) + "}},{Axis,Above}], " +"ScalingFunctions -> \"Log\", BaseStyle -> {FontSize -> 18},ImageSize->Scaled[.6]]"); histkeys.setLength(0); histvals.setLength(0); /* System.out.println("Unique Title histogram"); sum = 0; for(int i=titlehistogram.firstKey();i<500;i++){ int b = titlehistogram.containsKey(i) ? titlehistogram.get(i) : 0; sum+=b; if(i%binsize == 0){ int rangel = i-binsize; int rangeh = i-1; histkeys.append(","); histkeys.append("\""); histkeys.append(rangel); histkeys.append("-"); histkeys.append(rangeh); histkeys.append("\""); histvals.append(","); histvals.append(sum); // System.out.println(sum + "\t" + sum); sum = 0; } } //Mathematica output System.out.println("BarChart[{"+histvals.substring(1)+"}, ChartLabels ->Placed[{"+histkeys.substring(1)+"},Below],ScalingFunctions -> \"Log\", ImageSize -> Full]"); histkeys.setLength(0); histvals.setLength(0); System.out.println("Uniqe Sentence histogram"); for(int i=sentencehistogram.firstKey();i<500;i++){ int b = sentencehistogram.containsKey(i) ? sentencehistogram.get(i) : 0; sum+=b; if(i%binsize == 0){ int rangel = i-binsize; int rangeh = i-1; histkeys.append(","); histkeys.append("\""); histkeys.append(rangel); histkeys.append("-"); histkeys.append(rangeh); histkeys.append("\""); histvals.append(","); histvals.append(sum); //System.out.println(sum + "\t" + sum); sum = 0; } } //Mathematica output System.out.println("BarChart[{"+histvals.substring(1)+"}, ChartLabels ->Placed[{"+histkeys.substring(1)+"},Below],ScalingFunctions -> \"Log\", ImageSize -> Full]"); histkeys.setLength(0); histvals.setLength(0); */ }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public HistogramClusters() {} public static void main(String[] args) throws Exception { ToolRunner.run(new HistogramClusters(), args); } }
true
true
public void getHistogram(JobConf conf){ String filein = conf.get(INPUT); int max = conf.getInt(MAX, 30); int thresh = conf.getInt(THRESH, 30); int binsize = conf.getInt(BINSIZE, 10); //IntWritable, Text // Overall histogram: cluster sizes -> cluster cts TreeMap<Integer,Integer> histogram = new TreeMap<Integer,Integer>(); // Unique title histogram: # unique titles in cluster -> cluster cts TreeMap<Integer,Integer> titlehistogram = new TreeMap<Integer,Integer>(); // Unique sentence histogra: # unique sentences in cluster -> cluster cts TreeMap<Integer,Integer> sentencehistogram = new TreeMap<Integer,Integer>(); // Sets to keep track of overall unique title and sentences //HashSet<String> titleset = new HashSet<String>(); HashSet<String> sentenceset = new HashSet<String>(); // Per cluster data structures ArrayList<String> cluster = new ArrayList<String>(); HashSet<String> clustertitles = new HashSet<String>(); HashSet<String> clustersentences = new HashSet<String>(); int bigclusterlinect = 0; int smallclusterlinect = 0; int clusterct = 0; int linect = 0; long clustcurr = -1; int maxclustersize = 0; //Pattern linepat = Pattern.compile("^([^\t]+)\t(.*)$"); //Pattern linepat = Pattern.compile("^([^\t]+)\t((?>\\P{M}\\p{M}*)+)$"); try { FileSystem fs = FileSystem.get(conf); System.out.println("filein = " + filein); FileStatus[] infiles = fs.globStatus(new Path(filein + "/part-*")); for(FileStatus filestatus : infiles){ System.out.println(filestatus.getPath().toString()); try{ FSDataInputStream in = fs.open(filestatus.getPath()); SequenceFile.Reader reader; reader = new SequenceFile.Reader(conf, SequenceFile.Reader.stream(in)); LongWritable clusterid = new LongWritable(); PairOfStrings articlesentence = new PairOfStrings(); while(reader.next(clusterid, articlesentence)){ String linetext = articlesentence.toString().replace("\n", " "); //Matcher m = linepat.matcher(linetext); String title = ""; String sentence = ""; title = articlesentence.getLeftElement(); sentence = articlesentence.getRightElement(); if(clustcurr == -1){ clustcurr = clusterid.get(); } if(!(clustcurr == clusterid.get())){ if(clusterct % 10000 == 0) System.err.println("clusterct = " + clusterct); // Once we've found a new cluster Update each histogram int size = cluster.size(); if(size > maxclustersize){ maxclustersize = size; } if(size > thresh){ bigclusterlinect+=size; }else{ smallclusterlinect+=size; } if(!histogram.containsKey(size)){ histogram.put(size, 0); } histogram.put(size, histogram.get(size) + 1); size = clustertitles.size(); if(!titlehistogram.containsKey(size)){ titlehistogram.put(size, 0); } titlehistogram.put(size, titlehistogram.get(size) + 1); size = clustersentences.size(); if(!sentencehistogram.containsKey(size)){ sentencehistogram.put(size, 0); } sentencehistogram.put(size, sentencehistogram.get(size) + 1); /* // Code for examining cluster contents if(cluster.size() > 10000){ int ct = 0; System.out.println("Cluster size: " + cluster.size()); System.out.println("N unique sentences " + clustersentences.size()); System.out.println("N unique titles " + clustertitles.size()); for(String l : cluster){ if(ct > 10) break; System.out.println(l); ct++; } System.out.println(); } */ // Clear per cluster data structures cluster.clear(); clustersentences.clear(); clustertitles.clear(); clusterct++; } clustcurr = clusterid.get(); cluster.add(articlesentence.toString()); clustersentences.add(sentence); clustertitles.add(title); //titleset.add(title); sentenceset.add(sentence); linect++; clusterid = new LongWritable(); articlesentence = new PairOfStrings(); } reader.close(); }catch (EOFException e) { // For some reason it doesn't know when the input stream is done?? } // Update one time at the end of each file input loop to add remaining cluster int size = cluster.size(); if(size > thresh){ bigclusterlinect+=size; }else{ smallclusterlinect+=size; } if(!histogram.containsKey(size)){ histogram.put(size, 0); } histogram.put(size, histogram.get(size) + 1); size = clustertitles.size(); if(!titlehistogram.containsKey(size)){ titlehistogram.put(size, 0); } titlehistogram.put(size, titlehistogram.get(size) + 1); size = clustersentences.size(); if(!sentencehistogram.containsKey(size)){ sentencehistogram.put(size, 0); } sentencehistogram.put(size, sentencehistogram.get(size) + 1); // Clear per cluster data structures cluster.clear(); clustersentences.clear(); clustertitles.clear(); clusterct++; clusterct++; } System.out.println("N lines: " + linect); System.out.println("N clusters: " + clusterct); //System.out.println("N unique titles: " + titleset.size()); System.out.println("N unique sentences: " + sentenceset.size()); StringBuffer histvals = new StringBuffer(); StringBuffer histkeys = new StringBuffer(); System.out.println("Cluster histogram"); int sum = 0; int sumsentence = 0; int sumtitle = 0; int gtx = 0; int ltex = 0; for(int b : histogram.keySet()){ //System.out.println(b + "\t" + histogram.get(b)); if(b <= thresh){ ltex += histogram.get(b); }else{ gtx += histogram.get(b); } } System.out.println("Cluster threshold: " + thresh); System.out.println("N Lte " + thresh + ": " + ltex + " " + (1.0*ltex/clusterct)); System.out.println("N gt " + thresh + ": " + gtx + " " + (1.0*gtx/clusterct)); System.out.println("Number of lines in big clusters = " + bigclusterlinect + " " + (1.0*bigclusterlinect/linect)); System.out.println("Number of lines in small clusters = " + smallclusterlinect + " " + (1.0*smallclusterlinect/linect)); System.out.println("Size of largest cluster: " + maxclustersize); int binmax = max>0?max:histogram.lastKey(); for(int i=1;i<=binmax;i++){ int b = histogram.containsKey(i) ? histogram.get(i) : 0; sum+=b; b = sentencehistogram.containsKey(i) ? sentencehistogram.get(i) : 0; sumsentence+=b; b = titlehistogram.containsKey(i) ? titlehistogram.get(i) : 0; sumtitle+=b; if((i+1)%binsize == 0){ int rangel = i-binsize; int rangeh = i-1; histkeys.append(","); histkeys.append("\""); if((i-binsize)%1000 == 0){ histkeys.append(rangel); //histkeys.append("-"); //histkeys.append(rangeh); } histkeys.append("\""); histvals.append(","); // histvals.append("{"); histvals.append(sum); // histvals.append(","); // histvals.append(sumsentence); // histvals.append(","); // histvals.append(sumtitle); // histvals.append("}"); sum = 0; sumsentence = 0; sumtitle = 0; } } // Calculate rest of distribution weight sum = 0; sumsentence = 0; sumtitle = 0; for(int i=binmax;i<=histogram.lastKey();i++){ int b = histogram.containsKey(i) ? histogram.get(i) : 0; sum+=b; b = sentencehistogram.containsKey(i) ? sentencehistogram.get(i) : 0; sumsentence+=b; b = titlehistogram.containsKey(i) ? titlehistogram.get(i) : 0; sumtitle+=b; } int rangel = binmax; int rangeh = histogram.lastKey(); histkeys.append(","); histkeys.append("\""); histkeys.append(rangel); histkeys.append("+"); // histkeys.append("-"); // histkeys.append(rangeh); histkeys.append("\""); histvals.append(","); histvals.append(sum); //Mathematic output: System.out.println("BarChart[{"+histvals.substring(1)+"}, " +"ChartLabels ->Placed[{(Rotate[#, Pi/4] & /@{"+histkeys.substring(1)+"}), " +"{" + histvals.substring(1) + "}},{Axis,Above}], " +"ScalingFunctions -> \"Log\", BaseStyle -> {FontSize -> 18},ImageSize->Scaled[.6]]"); histkeys.setLength(0); histvals.setLength(0); /* System.out.println("Unique Title histogram"); sum = 0; for(int i=titlehistogram.firstKey();i<500;i++){ int b = titlehistogram.containsKey(i) ? titlehistogram.get(i) : 0; sum+=b; if(i%binsize == 0){ int rangel = i-binsize; int rangeh = i-1; histkeys.append(","); histkeys.append("\""); histkeys.append(rangel); histkeys.append("-"); histkeys.append(rangeh); histkeys.append("\""); histvals.append(","); histvals.append(sum); // System.out.println(sum + "\t" + sum); sum = 0; } } //Mathematica output System.out.println("BarChart[{"+histvals.substring(1)+"}, ChartLabels ->Placed[{"+histkeys.substring(1)+"},Below],ScalingFunctions -> \"Log\", ImageSize -> Full]"); histkeys.setLength(0); histvals.setLength(0); System.out.println("Uniqe Sentence histogram"); for(int i=sentencehistogram.firstKey();i<500;i++){ int b = sentencehistogram.containsKey(i) ? sentencehistogram.get(i) : 0; sum+=b; if(i%binsize == 0){ int rangel = i-binsize; int rangeh = i-1; histkeys.append(","); histkeys.append("\""); histkeys.append(rangel); histkeys.append("-"); histkeys.append(rangeh); histkeys.append("\""); histvals.append(","); histvals.append(sum); //System.out.println(sum + "\t" + sum); sum = 0; } } //Mathematica output System.out.println("BarChart[{"+histvals.substring(1)+"}, ChartLabels ->Placed[{"+histkeys.substring(1)+"},Below],ScalingFunctions -> \"Log\", ImageSize -> Full]"); histkeys.setLength(0); histvals.setLength(0); */ }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void getHistogram(JobConf conf){ String filein = conf.get(INPUT); int max = conf.getInt(MAX, 30); int thresh = conf.getInt(THRESH, 30); int binsize = conf.getInt(BINSIZE, 10); //IntWritable, Text // Overall histogram: cluster sizes -> cluster cts TreeMap<Integer,Integer> histogram = new TreeMap<Integer,Integer>(); // Unique title histogram: # unique titles in cluster -> cluster cts TreeMap<Integer,Integer> titlehistogram = new TreeMap<Integer,Integer>(); // Unique sentence histogra: # unique sentences in cluster -> cluster cts TreeMap<Integer,Integer> sentencehistogram = new TreeMap<Integer,Integer>(); // Sets to keep track of overall unique title and sentences //HashSet<String> titleset = new HashSet<String>(); HashSet<String> sentenceset = new HashSet<String>(); // Per cluster data structures ArrayList<String> cluster = new ArrayList<String>(); HashSet<String> clustertitles = new HashSet<String>(); HashSet<String> clustersentences = new HashSet<String>(); int bigclusterlinect = 0; int smallclusterlinect = 0; int clusterct = 0; int linect = 0; long clustcurr = -1; int maxclustersize = 0; //Pattern linepat = Pattern.compile("^([^\t]+)\t(.*)$"); //Pattern linepat = Pattern.compile("^([^\t]+)\t((?>\\P{M}\\p{M}*)+)$"); try { FileSystem fs = FileSystem.get(conf); System.out.println("filein = " + filein); FileStatus[] infiles = fs.globStatus(new Path(filein + "/part-*")); for(FileStatus filestatus : infiles){ System.out.println(filestatus.getPath().toString()); try{ FSDataInputStream in = fs.open(filestatus.getPath()); SequenceFile.Reader reader; reader = new SequenceFile.Reader(conf, SequenceFile.Reader.stream(in)); LongWritable clusterid = new LongWritable(); PairOfStrings articlesentence = new PairOfStrings(); while(reader.next(clusterid, articlesentence)){ String linetext = articlesentence.toString().replace("\n", " "); //Matcher m = linepat.matcher(linetext); String title = ""; String sentence = ""; title = articlesentence.getLeftElement(); sentence = articlesentence.getRightElement(); if(clustcurr == -1){ clustcurr = clusterid.get(); } if(!(clustcurr == clusterid.get())){ if(clusterct % 10000 == 0) System.err.println("clusterct = " + clusterct); // Once we've found a new cluster Update each histogram int size = cluster.size(); if(size > maxclustersize){ maxclustersize = size; } if(size > thresh){ bigclusterlinect+=size; }else{ smallclusterlinect+=size; } if(!histogram.containsKey(size)){ histogram.put(size, 0); } histogram.put(size, histogram.get(size) + 1); size = clustertitles.size(); if(!titlehistogram.containsKey(size)){ titlehistogram.put(size, 0); } titlehistogram.put(size, titlehistogram.get(size) + 1); size = clustersentences.size(); if(!sentencehistogram.containsKey(size)){ sentencehistogram.put(size, 0); } sentencehistogram.put(size, sentencehistogram.get(size) + 1); /* // Code for examining cluster contents if(cluster.size() > 10000){ int ct = 0; System.out.println("Cluster size: " + cluster.size()); System.out.println("N unique sentences " + clustersentences.size()); System.out.println("N unique titles " + clustertitles.size()); for(String l : cluster){ if(ct > 10) break; System.out.println(l); ct++; } System.out.println(); } */ // Clear per cluster data structures cluster.clear(); clustersentences.clear(); clustertitles.clear(); clusterct++; } clustcurr = clusterid.get(); cluster.add(articlesentence.toString()); clustersentences.add(sentence); clustertitles.add(title); //titleset.add(title); sentenceset.add(sentence); linect++; clusterid = new LongWritable(); articlesentence = new PairOfStrings(); } reader.close(); }catch (EOFException e) { // For some reason it doesn't know when the input stream is done?? } // Update one time at the end of each file input loop to add remaining cluster int size = cluster.size(); if(size > thresh){ bigclusterlinect+=size; }else{ smallclusterlinect+=size; } if(!histogram.containsKey(size)){ histogram.put(size, 0); } histogram.put(size, histogram.get(size) + 1); size = clustertitles.size(); if(!titlehistogram.containsKey(size)){ titlehistogram.put(size, 0); } titlehistogram.put(size, titlehistogram.get(size) + 1); size = clustersentences.size(); if(!sentencehistogram.containsKey(size)){ sentencehistogram.put(size, 0); } sentencehistogram.put(size, sentencehistogram.get(size) + 1); // Clear per cluster data structures cluster.clear(); clustersentences.clear(); clustertitles.clear(); clusterct++; clusterct++; } System.out.println("N lines: " + linect); System.out.println("N clusters: " + clusterct); //System.out.println("N unique titles: " + titleset.size()); System.out.println("N unique sentences: " + sentenceset.size()); StringBuffer histvals = new StringBuffer(); StringBuffer histkeys = new StringBuffer(); System.out.println("Cluster histogram"); int sum = 0; int sumsentence = 0; int sumtitle = 0; int gtx = 0; int ltex = 0; for(int b : histogram.keySet()){ //System.out.println(b + "\t" + histogram.get(b)); if(b <= thresh){ ltex += histogram.get(b); }else{ gtx += histogram.get(b); } } System.out.println("Cluster threshold: " + thresh); System.out.println("N Lte " + thresh + ": " + ltex + " " + (1.0*ltex/clusterct)); System.out.println("N gt " + thresh + ": " + gtx + " " + (1.0*gtx/clusterct)); System.out.println("Number of lines in big clusters = " + bigclusterlinect + " " + (1.0*bigclusterlinect/linect)); System.out.println("Number of lines in small clusters = " + smallclusterlinect + " " + (1.0*smallclusterlinect/linect)); System.out.println("Size of largest cluster: " + maxclustersize); int binmax = max>0?max:histogram.lastKey(); for(int i=1;i<=binmax;i++){ int b = histogram.containsKey(i) ? histogram.get(i) : 0; sum+=b; b = sentencehistogram.containsKey(i) ? sentencehistogram.get(i) : 0; sumsentence+=b; b = titlehistogram.containsKey(i) ? titlehistogram.get(i) : 0; sumtitle+=b; if((i+1)%binsize == 0){ int rangel = i-binsize; int rangeh = i-1; histkeys.append(","); histkeys.append("\""); if((i-binsize)%100 == 0){ histkeys.append(rangel); //histkeys.append("-"); //histkeys.append(rangeh); } histkeys.append("\""); histvals.append(","); // histvals.append("{"); histvals.append(sum); // histvals.append(","); // histvals.append(sumsentence); // histvals.append(","); // histvals.append(sumtitle); // histvals.append("}"); sum = 0; sumsentence = 0; sumtitle = 0; } } // Calculate rest of distribution weight sum = 0; sumsentence = 0; sumtitle = 0; for(int i=binmax;i<=histogram.lastKey();i++){ int b = histogram.containsKey(i) ? histogram.get(i) : 0; sum+=b; b = sentencehistogram.containsKey(i) ? sentencehistogram.get(i) : 0; sumsentence+=b; b = titlehistogram.containsKey(i) ? titlehistogram.get(i) : 0; sumtitle+=b; } int rangel = binmax; int rangeh = histogram.lastKey(); histkeys.append(","); histkeys.append("\""); histkeys.append(rangel); histkeys.append("+"); // histkeys.append("-"); // histkeys.append(rangeh); histkeys.append("\""); histvals.append(","); histvals.append(sum); //Mathematic output: System.out.println("BarChart[{"+histvals.substring(1)+"}, " +"ChartLabels ->Placed[{(Rotate[#, Pi/4] & /@{"+histkeys.substring(1)+"}), " +"{" + histvals.substring(1) + "}},{Axis,Above}], " +"ScalingFunctions -> \"Log\", BaseStyle -> {FontSize -> 18},ImageSize->Scaled[.6]]"); histkeys.setLength(0); histvals.setLength(0); /* System.out.println("Unique Title histogram"); sum = 0; for(int i=titlehistogram.firstKey();i<500;i++){ int b = titlehistogram.containsKey(i) ? titlehistogram.get(i) : 0; sum+=b; if(i%binsize == 0){ int rangel = i-binsize; int rangeh = i-1; histkeys.append(","); histkeys.append("\""); histkeys.append(rangel); histkeys.append("-"); histkeys.append(rangeh); histkeys.append("\""); histvals.append(","); histvals.append(sum); // System.out.println(sum + "\t" + sum); sum = 0; } } //Mathematica output System.out.println("BarChart[{"+histvals.substring(1)+"}, ChartLabels ->Placed[{"+histkeys.substring(1)+"},Below],ScalingFunctions -> \"Log\", ImageSize -> Full]"); histkeys.setLength(0); histvals.setLength(0); System.out.println("Uniqe Sentence histogram"); for(int i=sentencehistogram.firstKey();i<500;i++){ int b = sentencehistogram.containsKey(i) ? sentencehistogram.get(i) : 0; sum+=b; if(i%binsize == 0){ int rangel = i-binsize; int rangeh = i-1; histkeys.append(","); histkeys.append("\""); histkeys.append(rangel); histkeys.append("-"); histkeys.append(rangeh); histkeys.append("\""); histvals.append(","); histvals.append(sum); //System.out.println(sum + "\t" + sum); sum = 0; } } //Mathematica output System.out.println("BarChart[{"+histvals.substring(1)+"}, ChartLabels ->Placed[{"+histkeys.substring(1)+"},Below],ScalingFunctions -> \"Log\", ImageSize -> Full]"); histkeys.setLength(0); histvals.setLength(0); */ }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/distro/jbossas71/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/service/MscManagedProcessEngineController.java b/distro/jbossas71/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/service/MscManagedProcessEngineController.java index 3c29dd286..9a2a6b745 100644 --- a/distro/jbossas71/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/service/MscManagedProcessEngineController.java +++ b/distro/jbossas71/subsystem/src/main/java/org/camunda/bpm/container/impl/jboss/service/MscManagedProcessEngineController.java @@ -1,229 +1,231 @@ /** * Copyright (C) 2011, 2012 camunda services GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.container.impl.jboss.service; import java.util.concurrent.ExecutorService; import java.util.logging.Level; import java.util.logging.Logger; import javax.sql.DataSource; import javax.transaction.TransactionManager; import org.camunda.bpm.container.impl.jboss.config.ManagedJtaProcessEngineConfiguration; import org.camunda.bpm.container.impl.jboss.config.ManagedProcessEngineMetadata; import org.camunda.bpm.container.impl.jboss.util.Tccl; import org.camunda.bpm.container.impl.jboss.util.Tccl.Operation; import org.camunda.bpm.container.impl.jmx.services.JmxManagedProcessEngineController; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.ProcessEngineConfiguration; import org.camunda.bpm.engine.ProcessEngineException; import org.camunda.bpm.engine.impl.cfg.JtaProcessEngineConfiguration; import org.jboss.as.connector.subsystems.datasources.DataSourceReferenceFactoryService; import org.jboss.as.naming.deployment.ContextNames; import org.jboss.as.server.Services; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; /** * <p>Service responsible for starting / stopping a managed process engine inside the Msc</p> * * <p>This service is used for managing process engines that are started / stopped * through the application server management infrastructure.</p> * * <p>This is the Msc counterpart of the {@link JmxManagedProcessEngineController}</p> * * @author Daniel Meyer */ public class MscManagedProcessEngineController extends MscManagedProcessEngine { private final static Logger LOGGER = Logger.getLogger(MscManagedProcessEngineController.class.getName()); protected InjectedValue<ExecutorService> executorInjector = new InjectedValue<ExecutorService>(); // Injecting these values makes the MSC aware of our dependencies on these resources. // This ensures that they are available when this service is started protected final InjectedValue<TransactionManager> transactionManagerInjector = new InjectedValue<TransactionManager>(); protected final InjectedValue<DataSourceReferenceFactoryService> datasourceBinderServiceInjector = new InjectedValue<DataSourceReferenceFactoryService>(); protected final InjectedValue<MscRuntimeContainerDelegate> containerPlatformServiceInjector = new InjectedValue<MscRuntimeContainerDelegate>(); protected final InjectedValue<MscRuntimeContainerJobExecutor> mscRuntimeContainerJobExecutorInjector = new InjectedValue<MscRuntimeContainerJobExecutor>(); protected ManagedProcessEngineMetadata processEngineMetadata; protected JtaProcessEngineConfiguration processEngineConfiguration; /** * Instantiate the process engine controller for a process engine configuration. * */ public MscManagedProcessEngineController(ManagedProcessEngineMetadata processEngineConfiguration) { this.processEngineMetadata = processEngineConfiguration; } public void start(final StartContext context) throws StartException { context.asynchronous(); executorInjector.getValue().submit(new Runnable() { public void run() { try { start(); context.complete(); } catch (Throwable e) { context.failed(new StartException(e)); } } }); } public void stop(final StopContext context) { context.asynchronous(); executorInjector.getValue().submit(new Runnable() { public void run() { try { try { processEngine.close(); } catch(Exception e) { LOGGER.log(Level.SEVERE, "exception while closing process engine", e); } } finally { context.complete(); } } }); } public void start() { // setting the TCCL to the Classloader of this module. // this exploits a hack in MyBatis allowing it to use the TCCL to load the // mapping files from the process engine module Tccl.runUnderClassloader(new Operation<Void>() { public Void run() { startProcessEngine(); return null; } }, ProcessEngine.class.getClassLoader()); } protected void startProcessEngine() { processEngineConfiguration = createProcessEngineConfiguration(); // set the name for the process engine processEngineConfiguration.setProcessEngineName(processEngineMetadata.getEngineName()); // set the value for the history processEngineConfiguration.setHistory(processEngineMetadata.getHistoryLevel()); // use the injected datasource processEngineConfiguration.setDataSource((DataSource) datasourceBinderServiceInjector.getValue().getReference().getInstance()); // use the injected transaction manager processEngineConfiguration.setTransactionManager(transactionManagerInjector.getValue()); // set auto schema update if(processEngineMetadata.isAutoSchemaUpdate()) { processEngineConfiguration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE); + } else { + processEngineConfiguration.setDatabaseSchemaUpdate("off"); } // set db table prefix if( processEngineMetadata.getDbTablePrefix() != null ) { processEngineConfiguration.setDatabaseTablePrefix(processEngineMetadata.getDbTablePrefix()); } // set job executor on process engine. MscRuntimeContainerJobExecutor mscRuntimeContainerJobExecutor = mscRuntimeContainerJobExecutorInjector.getValue(); processEngineConfiguration.setJobExecutor(mscRuntimeContainerJobExecutor); processEngine = processEngineConfiguration.buildProcessEngine(); } protected JtaProcessEngineConfiguration createProcessEngineConfiguration() { String configurationClassName = ManagedJtaProcessEngineConfiguration.class.getName(); if(processEngineMetadata.getConfiguration() != null && !processEngineMetadata.getConfiguration().isEmpty()) { configurationClassName = processEngineMetadata.getConfiguration(); } Object configurationObject = null; try { Class<?> configurationClass = getClass().getClassLoader().loadClass(configurationClassName); configurationObject = configurationClass.newInstance(); } catch (Exception e) { throw new ProcessEngineException("Could not load '"+configurationClassName+"': the class must be visible from the camunda-jboss-subsystem module."); } if (configurationObject instanceof JtaProcessEngineConfiguration) { return (JtaProcessEngineConfiguration) configurationObject; } else { throw new ProcessEngineException("Configuration class '"+configurationClassName+"' " + "is not a subclass of " + JtaProcessEngineConfiguration.class.getName()); } } public Injector<TransactionManager> getTransactionManagerInjector() { return transactionManagerInjector; } public Injector<DataSourceReferenceFactoryService> getDatasourceBinderServiceInjector() { return datasourceBinderServiceInjector; } public InjectedValue<MscRuntimeContainerDelegate> getContainerPlatformServiceInjector() { return containerPlatformServiceInjector; } public InjectedValue<MscRuntimeContainerJobExecutor> getMscRuntimeContainerJobExecutorInjector() { return mscRuntimeContainerJobExecutorInjector; } public static void initializeServiceBuilder(ManagedProcessEngineMetadata processEngineConfiguration, MscManagedProcessEngineController service, ServiceBuilder<ProcessEngine> serviceBuilder, String jobExecutorName) { ContextNames.BindInfo datasourceBindInfo = ContextNames.bindInfoFor(processEngineConfiguration.getDatasourceJndiName()); serviceBuilder.addDependency(ServiceName.JBOSS.append("txn").append("TransactionManager"), TransactionManager.class, service.getTransactionManagerInjector()) .addDependency(datasourceBindInfo.getBinderServiceName(), DataSourceReferenceFactoryService.class, service.getDatasourceBinderServiceInjector()) .addDependency(ServiceNames.forMscRuntimeContainerDelegate(), MscRuntimeContainerDelegate.class, service.getContainerPlatformServiceInjector()) .addDependency(ServiceNames.forMscRuntimeContainerJobExecutorService(jobExecutorName), MscRuntimeContainerJobExecutor.class, service.getMscRuntimeContainerJobExecutorInjector()) .addDependency(ServiceNames.forMscExecutorService()) .setInitialMode(Mode.ACTIVE); Services.addServerExecutorDependency(serviceBuilder, service.getExecutorInjector(), false); } public ProcessEngine getProcessEngine() { return processEngine; } public InjectedValue<ExecutorService> getExecutorInjector() { return executorInjector; } }
true
true
protected void startProcessEngine() { processEngineConfiguration = createProcessEngineConfiguration(); // set the name for the process engine processEngineConfiguration.setProcessEngineName(processEngineMetadata.getEngineName()); // set the value for the history processEngineConfiguration.setHistory(processEngineMetadata.getHistoryLevel()); // use the injected datasource processEngineConfiguration.setDataSource((DataSource) datasourceBinderServiceInjector.getValue().getReference().getInstance()); // use the injected transaction manager processEngineConfiguration.setTransactionManager(transactionManagerInjector.getValue()); // set auto schema update if(processEngineMetadata.isAutoSchemaUpdate()) { processEngineConfiguration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE); } // set db table prefix if( processEngineMetadata.getDbTablePrefix() != null ) { processEngineConfiguration.setDatabaseTablePrefix(processEngineMetadata.getDbTablePrefix()); } // set job executor on process engine. MscRuntimeContainerJobExecutor mscRuntimeContainerJobExecutor = mscRuntimeContainerJobExecutorInjector.getValue(); processEngineConfiguration.setJobExecutor(mscRuntimeContainerJobExecutor); processEngine = processEngineConfiguration.buildProcessEngine(); }
protected void startProcessEngine() { processEngineConfiguration = createProcessEngineConfiguration(); // set the name for the process engine processEngineConfiguration.setProcessEngineName(processEngineMetadata.getEngineName()); // set the value for the history processEngineConfiguration.setHistory(processEngineMetadata.getHistoryLevel()); // use the injected datasource processEngineConfiguration.setDataSource((DataSource) datasourceBinderServiceInjector.getValue().getReference().getInstance()); // use the injected transaction manager processEngineConfiguration.setTransactionManager(transactionManagerInjector.getValue()); // set auto schema update if(processEngineMetadata.isAutoSchemaUpdate()) { processEngineConfiguration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE); } else { processEngineConfiguration.setDatabaseSchemaUpdate("off"); } // set db table prefix if( processEngineMetadata.getDbTablePrefix() != null ) { processEngineConfiguration.setDatabaseTablePrefix(processEngineMetadata.getDbTablePrefix()); } // set job executor on process engine. MscRuntimeContainerJobExecutor mscRuntimeContainerJobExecutor = mscRuntimeContainerJobExecutorInjector.getValue(); processEngineConfiguration.setJobExecutor(mscRuntimeContainerJobExecutor); processEngine = processEngineConfiguration.buildProcessEngine(); }
diff --git a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/util/EMV2Util.java b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/util/EMV2Util.java index 7ae23922..63337a83 100644 --- a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/util/EMV2Util.java +++ b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/util/EMV2Util.java @@ -1,2203 +1,2203 @@ package org.osate.xtext.aadl2.errormodel.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Stack; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.osate.aadl2.Aadl2Package; import org.osate.aadl2.AnnexSubclause; import org.osate.aadl2.BasicPropertyAssociation; import org.osate.aadl2.Classifier; import org.osate.aadl2.ComponentCategory; import org.osate.aadl2.ComponentClassifier; import org.osate.aadl2.ComponentImplementation; import org.osate.aadl2.ContainedNamedElement; import org.osate.aadl2.ContainmentPathElement; import org.osate.aadl2.DirectionType; import org.osate.aadl2.Element; import org.osate.aadl2.EnumerationLiteral; import org.osate.aadl2.Feature; import org.osate.aadl2.ModalPropertyValue; import org.osate.aadl2.NamedElement; import org.osate.aadl2.NamedValue; import org.osate.aadl2.Property; import org.osate.aadl2.PropertyAssociation; import org.osate.aadl2.PropertyExpression; import org.osate.aadl2.RealLiteral; import org.osate.aadl2.RecordValue; import org.osate.aadl2.Subcomponent; import org.osate.aadl2.instance.ComponentInstance; import org.osate.aadl2.instance.ConnectionInstanceEnd; import org.osate.aadl2.instance.FeatureInstance; import org.osate.aadl2.instance.InstanceObject; import org.osate.aadl2.modelsupport.modeltraversal.ForAllElement; import org.osate.aadl2.modelsupport.util.AadlUtil; import org.osate.aadl2.util.Aadl2Util; import org.osate.xtext.aadl2.errormodel.errorModel.ComponentErrorBehavior; import org.osate.xtext.aadl2.errormodel.errorModel.ConditionElement; import org.osate.xtext.aadl2.errormodel.errorModel.ConditionExpression; import org.osate.xtext.aadl2.errormodel.errorModel.EBSMUseContext; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorEvent; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorState; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorStateMachine; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorTransition; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorDetection; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorFlow; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelLibrary; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelSubclause; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPath; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPropagation; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPropagations; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorSink; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorSource; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorType; import org.osate.xtext.aadl2.errormodel.errorModel.ErrorTypes; import org.osate.xtext.aadl2.errormodel.errorModel.FeatureReference; import org.osate.xtext.aadl2.errormodel.errorModel.OutgoingPropagationCondition; import org.osate.xtext.aadl2.errormodel.errorModel.PropagationPaths; import org.osate.xtext.aadl2.errormodel.errorModel.PropagationPoint; import org.osate.xtext.aadl2.errormodel.errorModel.PropagationPointConnection; import org.osate.xtext.aadl2.errormodel.errorModel.QualifiedPropagationPoint; import org.osate.xtext.aadl2.errormodel.errorModel.SubcomponentElement; import org.osate.xtext.aadl2.errormodel.errorModel.TypeMappingSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeToken; import org.osate.xtext.aadl2.errormodel.errorModel.TypeTransformationSet; import org.osate.xtext.aadl2.errormodel.errorModel.TypeUseContext; public class EMV2Util { public final static String ErrorModelAnnexName = "EMV2"; private static EClass EMV2subclauseEClass = Aadl2Package.eINSTANCE.getAnnexSubclause(); /** * Get the error-annex subclause for a given Component Instance * @param ci The component instance that contains the error model subclause * @return EList<AnnexSubclause> list of ErrorModelSubclause objects */ public static EList<AnnexSubclause> getErrorAnnexSubclauses (ComponentInstance ci) { return ci.getComponentClassifier().getAllAnnexSubclauses(EMV2subclauseEClass); } public static ContainedNamedElement getHazardProperty(ComponentInstance ci, Element localContext,Element target, TypeSet ts){ ContainedNamedElement result = EMV2Util.getProperty("EMV2::hazard",ci,localContext,target,ts); return result; } /** * Retrieve the value of the OccurenceDistribution property of the * EMV2 property. You can use it like this: * ContainedNamedElement PA = EM2Util.getOccurenceDistributionProperty(instance,null,ee,null); * res = EM2Util.getOccurenceValue (PA); * * @see Util * @param ci ComponentInstance object that contains the property * @param localContext the context or null * @param target the property * @param ts corresponding typeset or null * @return */ public static ContainedNamedElement getOccurenceDistributionProperty(ComponentInstance ci, NamedElement localContext,NamedElement target, TypeSet ts){ ContainedNamedElement result = EMV2Util.getProperty("EMV2::OccurrenceDistribution",ci,localContext,target,ts); return result; } /** * Retrieve the value associated with a containment path * See RDB action to see how it is used. * * @param PAContainmentPath value get from getOccurenceDistributionProperty */ public static double getOccurenceValue (final ContainedNamedElement PAContainmentPath) { double result; result = 0; if (PAContainmentPath == null) { return 0; } for (ModalPropertyValue modalPropertyValue : AadlUtil.getContainingPropertyAssociation(PAContainmentPath).getOwnedValues()) { PropertyExpression val = modalPropertyValue.getOwnedValue(); if (val instanceof RecordValue){ RecordValue rv = (RecordValue)val; EList<BasicPropertyAssociation> fields = rv.getOwnedFieldValues(); // for all error types/aliases in type set or the element identified in the containment clause for (BasicPropertyAssociation bpa : fields) { if (bpa.getProperty().getName().equalsIgnoreCase("probabilityvalue")) { if (bpa.getValue() instanceof RealLiteral) { RealLiteral rl = (RealLiteral)bpa.getValue(); result = rl.getScaledValue(); } } } } } return result; } /** * Retrieve the type/kind of distribution associated * with the Occurrence property * See PRISM converter to see how it is used. * * @param PAContainmentPath string value describing the distribution get from getOccurenceDistributionProperty */ public static String getOccurenceType (final ContainedNamedElement PAContainmentPath) { if (PAContainmentPath == null) { return "unknown_distribution"; } for (ModalPropertyValue modalPropertyValue : AadlUtil.getContainingPropertyAssociation(PAContainmentPath).getOwnedValues()) { PropertyExpression val = modalPropertyValue.getOwnedValue(); if (val instanceof RecordValue){ RecordValue rv = (RecordValue)val; EList<BasicPropertyAssociation> fields = rv.getOwnedFieldValues(); // for all error types/aliases in type set or the element identified in the containment clause for (BasicPropertyAssociation bpa : fields) { if (bpa.getProperty().getName().equalsIgnoreCase("distribution")) { if (bpa.getValue() instanceof NamedValue) { EnumerationLiteral el = (EnumerationLiteral)((NamedValue)bpa.getValue()).getNamedValue(); return (el.getName().toLowerCase()); //RealLiteral rl = (NamedValue)bpa.getValue(); //result = rl.getScaledValue(); } } } } } return "unknown_distribution"; } /** * get ErrorModelSubclause object that contains the element object. * @param element error annex element * @return ErrorModelSubclause */ public static ErrorModelSubclause getContainingErrorModelSubclause(Element element) { EObject container = element; while (container != null && !(container instanceof ErrorModelSubclause)) container = container.eContainer(); return (ErrorModelSubclause) container; } /** * get error propagations object that contains the element object. * @param element error annex element * @return ErrorPropagations */ public static ErrorPropagations getContainingErrorPropagations(Element element) { EObject container = element; while (container != null && !(container instanceof ErrorPropagations)) container = container.eContainer(); return (ErrorPropagations) container; } /** * get enclosing object within the error annex that has a properties section.. * ErrorModelLibrary, ErrorBehaviorStateMachine, and ErrorModelSubclause have properties sections * @param element declarative model element or error annex element * @return ErrorModelLibrary, ErrorBehaviorStateMachine, ErrorModelSubclause */ public static EList<PropertyAssociation> getContainingPropertiesHolder(Element element) { EObject container = element; while (container != null ){ if (container instanceof ErrorModelSubclause ){ return ((ErrorModelSubclause)container).getProperties(); } if (container instanceof ErrorModelLibrary ){ return ((ErrorModelLibrary)container).getProperties(); } if (container instanceof ErrorBehaviorStateMachine ){ return ((ErrorBehaviorStateMachine)container).getProperties(); } container = container.eContainer(); } return null; } /** * get ErrorModelSubclause object in the classifier * @param cl classifier * @return ErrorModelSubclause */ private static void getClassifierEMV2Subclause(Classifier cl,EList<ErrorModelSubclause> result) { ErrorModelSubclause ems = getOwnEMV2Subclause(cl); if (ems != null) result.add(ems); } /** * recursively add all EMV2 subclauses of classifier and its extends ancestors * in case of implementations do not follow to the type * cl can be null or an unresolved proxy. * if cl has a subclause its subclause is added before following the extends hierarhy * @param cl Component Implementation * @param result list of EMV2 subclauses */ private static void getAllClassifierEMV2Subclause(Classifier cl,EList<ErrorModelSubclause> result) { if (!Aadl2Util.isNull(cl)){ getClassifierEMV2Subclause(cl, result); getAllClassifierEMV2Subclause(cl.getExtended(),result); } } /** * return the list of EMV2 subclauses of the classifier and * The extends hierarchy and the type in the case of an implementation are searched for the ErrorModelSubcany of its extends ancestors * @param element declarative model element or error annex element * @return ErrorModelSubclause */ public static EList<ErrorModelSubclause> getAllContainingClassifierEMV2Subclauses(Element element) { EList<ErrorModelSubclause> result = new BasicEList<ErrorModelSubclause>(); Classifier cl = element.getContainingClassifier(); if (cl instanceof ComponentImplementation){ getAllClassifierEMV2Subclause(cl, result); getAllClassifierEMV2Subclause(((ComponentImplementation)cl).getType(),result); } else { getAllClassifierEMV2Subclause(cl, result); } return result; } /** * get the error model subclause for the specified classifier. * Does not look in the extends hierarchy * @param cl CLassifier * @return */ public static ErrorModelSubclause getOwnEMV2Subclause(Classifier cl){ if (cl == null) return null; EList<AnnexSubclause> asl = cl.getOwnedAnnexSubclauses(); for (AnnexSubclause al : asl){ if (al instanceof ErrorModelSubclause){ return ((ErrorModelSubclause)al); } } return null; } /** * get the error model subclause for the specified classifier. * It effectively returns the first subclause that applies to the classifier. * This is the subclause that determines the EBSM to be used (specified in use behavior). * The mthods goes up the extends hierarchy, and in the case of an implementation * tries its type and the type's hierarchy. * * @param cl Classifier * @return */ public static ErrorModelSubclause getClassifierEMV2Subclause(Classifier cl){ if (cl == null) return null; ErrorModelSubclause ems = getOwnEMV2Subclause(cl); if (ems != null) return ems; if (cl instanceof ComponentImplementation){ ems = getExtendsEMV2Subclause((ComponentImplementation)cl); if (ems != null) return ems; ems = getExtendsEMV2Subclause(((ComponentImplementation)cl).getType()); if (ems != null) return ems; } else { ems = getExtendsEMV2Subclause(cl); if (ems != null) return ems; } return null; } /** * find the first subclause on the classifier or its extends hierachy. * When used on a component implementation this method does not go from an implemetnation to a type. * * @param cl * @return */ public static ErrorModelSubclause getExtendsEMV2Subclause(Classifier cl){ if (cl == null) return null; ErrorModelSubclause ems = getOwnEMV2Subclause(cl); if (ems != null) return ems; if (!Aadl2Util.isNull(cl.getExtended())){ ems= getExtendsEMV2Subclause(cl.getExtended()); if (ems != null) return ems; } return null; } /** * find propagation point including those inherited from classifiers being extended * @param element context * @param name String * @return PropagationPoint propagation point */ public static PropagationPoint findPropagationPoint(Element element, String name){ EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(element); for (ErrorModelSubclause errorModelSubclause : emslist) { PropagationPaths eps = errorModelSubclause.getPropagationPaths(); if (eps!= null){ EList<PropagationPoint> eflist = eps.getPoints(); for (PropagationPoint propPoint : eflist) { if ( name.equalsIgnoreCase(propPoint.getName())){ return propPoint; } } } } return null; } /** * Find error propagation point in the extends hierarchy of the containing component of context * @param context * @param name * @param dir * @param isNot * @return */ public static ErrorPropagation findErrorPropagationPoint(Element context, String name, DirectionType dir, boolean isNot){ EList<ErrorModelSubclause> emslist =null; if (context instanceof QualifiedPropagationPoint){ Subcomponent sub = ((QualifiedPropagationPoint)context).getSubcomponent(); emslist = getAllContainingClassifierEMV2Subclauses(sub.getAllClassifier()); } else { emslist = getAllContainingClassifierEMV2Subclauses(context); } for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagation res = findErrorPropagation(errorModelSubclause, name, dir, isNot); if (res != null) return res; } return null; } /** * Find error propagation point in the EMV2 subclause only * @param ems * @param name * @param dir * @param isNot * @return */ public static ErrorPropagation findErrorPropagation(ErrorModelSubclause ems, String name, DirectionType dir, boolean isNot){ ErrorPropagations eps = ems.getErrorPropagations(); if (eps != null){ for (ErrorPropagation ep : eps.getPropagations()){ if (ep.isNot() == isNot&& (dir == null ||ep.getDirection()== dir)){ // do we need to check (context instanceof QualifiedObservableErrorPropagationPoint) EList<FeatureReference> refs = ep.getFeaturerefs(); if (!refs.isEmpty()){ String refname = ""; for (FeatureReference featureReference : refs) { if (Aadl2Util.isNull(featureReference.getFeature())) return null; refname = refname + (refname.isEmpty()?"":".")+featureReference.getFeature().getName(); } if (refname.equalsIgnoreCase(name)) return ep; } String kind = ep.getKind(); if (kind != null && kind.equalsIgnoreCase(name)&& (dir == null||dir.equals(ep.getDirection()))) return ep; } } } return null; } /** * find the incoming error propagation point of the specified name * @param element the model element in the context of which we find the error propagation * @param eppName Name of error propagation point we are looking for * @return ErrorPropagation */ public static ErrorPropagation findIncomingErrorPropagation(Element element, String eppName){ EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(element); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagation res = findErrorPropagation(errorModelSubclause, eppName, DirectionType.IN,false); if (res != null) return res; } return null; } public static ErrorPropagation findIncomingErrorPropagation(EList<ErrorModelSubclause> emslist, String eppName){ for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagation res = findErrorPropagation(errorModelSubclause, eppName, DirectionType.IN,false); if (res != null) return res; } return null; } /** * find the outgoing error propagation point of the specified name * @param element the model element in the context of which we find the error propagation * @param eppName Name of error propagation point we are looking for * @return ErrorPropagation */ public static ErrorPropagation findOutgoingErrorPropagation(Element element, String eppName){ EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(element); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagation res = findErrorPropagation(errorModelSubclause, eppName, DirectionType.OUT,false); if (res != null) return res; } return null; } public static ErrorPropagation findOutgoingErrorPropagation(EList<ErrorModelSubclause> emslist, String eppName){ for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagation res = findErrorPropagation(errorModelSubclause, eppName, DirectionType.OUT,false); if (res != null) return res; } return null; } /** * find the outgoing error containment point of the specified name * @param element the model element in the context of which we find the error propagation * @param eppName Name of error propagation point we are looking for * @return ErrorPropagation */ public static ErrorPropagation findOutgoingErrorContainment(Element element, String eppName){ EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(element); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagation res = findErrorPropagation(errorModelSubclause, eppName, DirectionType.OUT,true); if (res != null) return res; } return null; } public static ErrorPropagation findOutgoingErrorContainment(EList<ErrorModelSubclause> emslist, String eppName){ for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagation res = findErrorPropagation(errorModelSubclause, eppName, DirectionType.OUT,true); if (res != null) return res; } return null; } /** * find the incoming error propagation point of the specified name * @param element the model element in the context of which we find the error propagation * @param eppName Name of error propagation point we are looking for * @return ErrorPropagation */ public static ErrorPropagation findIncomingErrorContainment(Element element, String eppName){ EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(element); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagation res = findErrorPropagation(errorModelSubclause, eppName, DirectionType.IN,true); if (res != null) return res; } return null; } public static ErrorPropagation findIncomingErrorContainment(EList<ErrorModelSubclause> emslist, String eppName){ for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagation res = findErrorPropagation(errorModelSubclause, eppName, DirectionType.IN,true); if (res != null) return res; } return null; } /** * Get outgoing error propagation associated with feature instance * @param fi feature instance * @return error propagation */ public static ErrorPropagation getOutgoingErrorPropagation(FeatureInstance fi){ ComponentInstance ci = fi.getContainingComponentInstance(); return EMV2Util.findOutgoingErrorPropagation(ci.getComponentClassifier(), fi.getName()); } /** * Get incoming error propagation associated with feature instance * @param fi feature instance * @return error propagation */ public static ErrorPropagation getIncomingErrorPropagation(FeatureInstance fi){ ComponentInstance ci = fi.getContainingComponentInstance(); return EMV2Util.findIncomingErrorPropagation(ci.getComponentClassifier(), fi.getName()); } /** * Get outgoing error propagation associated with feature instance * @param fi feature instance * @return error propagation */ public static ErrorPropagation getOutgoingErrorContainment(FeatureInstance fi){ ComponentInstance ci = fi.getContainingComponentInstance(); return EMV2Util.findOutgoingErrorContainment(ci.getComponentClassifier(), fi.getName()); } /** * Get incoming error propagation associated with feature instance * @param fi feature instance * @return error propagation */ public static ErrorPropagation getIncomingErrorContainment(FeatureInstance fi){ ComponentInstance ci = fi.getContainingComponentInstance(); return EMV2Util.findIncomingErrorContainment(ci.getComponentClassifier(), fi.getName()); } /** * Get incoming error propagation associated with component instance access * @param ci component instance * @return error propagation */ public static ErrorPropagation getIncomingAccessErrorPropagation(ComponentInstance ci){ return EMV2Util.findIncomingErrorPropagation(ci.getComponentClassifier(), "access"); } /** * Get outgoing error propagation associated with component instance access * @param ci component instance * @return error propagation */ public static ErrorPropagation getOutgoingAccessErrorPropagation(ComponentInstance ci){ return EMV2Util.findOutgoingErrorPropagation(ci.getComponentClassifier(), "access"); } /** * find error flow starting with given classifier by looking through all error flows * @param cl * @param name * @return ErrorFlow */ public static ErrorFlow findErrorFlow(Element el, String name){ Classifier cl= el.getContainingClassifier(); if (cl != null){ HashMap<String, ErrorFlow> efhashtab = getAllErrorFlows(cl,null); return efhashtab.get(name); } return null; } /** * find the error flow whose incoming error propagation point is incie * @param eps List of error propagations * @param incie connection instance end, which can be a component instance or feature instance * @return ErrorFlow */ public static ErrorFlow findErrorFlowFrom(Collection<ErrorFlow> efs, ConnectionInstanceEnd incie){ if (!(incie instanceof FeatureInstance)) return null; FeatureInstance fi = (FeatureInstance)incie; for (ErrorFlow ef : efs) { ErrorPropagation eprop = null; if (ef instanceof ErrorPath){ ErrorPath ep = (ErrorPath)ef; eprop = ep.getIncoming(); } else if (ef instanceof ErrorSink){ ErrorSink es = (ErrorSink)ef; eprop =es.getIncoming(); } if (isErrorPropagationOf(eprop, fi)){ return ef; } } return null; } /** * find the error flow whose outgoing error propagation point is incie * @param eps List of error propagations * @param incie connection instance end, which can be a component instance or feature instance * @return ErrorFlow */ public static ErrorFlow findReverseErrorFlowFrom(Collection<ErrorFlow> efs, ConnectionInstanceEnd incie){ if (!(incie instanceof FeatureInstance)) return null; FeatureInstance fi = (FeatureInstance)incie; for (ErrorFlow ef : efs) { ErrorPropagation eprop = null; if (ef instanceof ErrorPath){ ErrorPath ep = (ErrorPath)ef; eprop=ep.getOutgoing(); } else if (ef instanceof ErrorSource){ ErrorSource es = (ErrorSource)ef; eprop=es.getOutgoing(); } if (isErrorPropagationOf(eprop, fi)){ return ef; } } return null; } public static ErrorBehaviorState findErrorBehaviorState(Element context, String name){ ErrorBehaviorStateMachine ebsm; if (context instanceof ConditionElement && !((ConditionElement)context).getSubcomponents().isEmpty()){ // look up state in state machine of subcomponent ConditionElement tcs = (ConditionElement)context; EList<SubcomponentElement> sublist = tcs.getSubcomponents(); Subcomponent sub = sublist.get(sublist.size()-1).getSubcomponent(); ComponentClassifier sc = sub.getAllClassifier(); if (sc == null) return null; return findErrorBehaviorStateinUseBehavior( sc,name); } else { // resolve in local context, which is assumed to be an EBSM ebsm = EMV2Util.getContainingErrorBehaviorStateMachine(context); if (ebsm == null) ebsm = EMV2Util.getUsedErrorBehaviorStateMachine(context); return findErrorBehaviorStateInEBSM(ebsm, name); } } /** * find the first subclause and look for this Use Behavior. * Since Use behavior is optional it might not find any * It will not assume that Use Behavior is inherited * @param cl * @param name * @return */ public static ErrorBehaviorState findErrorBehaviorStateinUseBehavior(Classifier cl, String name){ if (cl == null) return null; // XXX if we want to support inherit of Use Behavior we call getClassifierUseBehavior to get the EBSM // and then do a find on it. ErrorModelSubclause ems = getClassifierEMV2Subclause(cl); ErrorBehaviorStateMachine ebsm = ems.getUseBehavior(); if (ebsm != null){ return findErrorBehaviorStateInEBSM(ebsm, name); } return null; } /** * find error behavior state in state machine * @param ebsm * @param name * @return */ public static ErrorBehaviorState findErrorBehaviorStateInEBSM(ErrorBehaviorStateMachine ebsm, String name){ if (ebsm != null){ EList<ErrorBehaviorState> ebsl= ebsm.getStates(); for (ErrorBehaviorState ebs : ebsl){ if (EMV2Util.getItemName(name).equalsIgnoreCase(ebs.getName())) return ebs; } // enable if we support extends on EBSM // if (ebsm.getExtends() != null){ // return findErrorBehaviorStateInEBSM(ebsm.getExtends(), name); // } } return null; } /** * get the subclause use behavior (EBSM) for the specified classifier. * Does not look in the extends hierarchy * @param cl CLassifier * @return ErrorBehaviorStateMachine */ public static ErrorBehaviorStateMachine getOwnUseBehavior(Classifier cl){ if (cl == null) return null; EList<AnnexSubclause> asl = cl.getOwnedAnnexSubclauses(); for (AnnexSubclause al : asl){ if (al instanceof ErrorModelSubclause){ return ((ErrorModelSubclause)al).getUseBehavior(); } } return null; } /** * get the subclause use behavior (EBSM) for the specified classifier. * It effectively returns the first EBSM that applies to the classifier. * The method goes up the extends hierarchy, and in the case of an implementation * tries its type and the type's hierarchy. * * @param cl Classifier * @return */ public static ErrorBehaviorStateMachine getClassifierUseBehavior(Classifier cl){ if (cl == null) return null; ErrorModelSubclause ems = getOwnEMV2Subclause(cl); if (ems != null) { ErrorBehaviorStateMachine ebsm = ems.getUseBehavior(); if (ebsm != null) return ebsm; } if (cl instanceof ComponentImplementation){ ems = getExtendsEMV2Subclause((ComponentImplementation)cl); if (ems != null) { ErrorBehaviorStateMachine ebsm = ems.getUseBehavior(); if (ebsm != null) return ebsm; } ems = getExtendsEMV2Subclause(((ComponentImplementation)cl).getType()); if (ems != null) { ErrorBehaviorStateMachine ebsm = ems.getUseBehavior(); if (ebsm != null) return ebsm; } } else { ems = getExtendsEMV2Subclause(cl); if (ems != null) { ErrorBehaviorStateMachine ebsm = ems.getUseBehavior(); if (ebsm != null) return ebsm; } } return null; } /** * find the first subclause Use Behavior on the classifier or its extends hierachy. * When used on a component implementation this method does not go from an implemetnation to a type. * * @param cl * @return */ public static ErrorBehaviorStateMachine getExtendsUseBehavior(Classifier cl){ if (cl == null) return null; ErrorModelSubclause ems = getOwnEMV2Subclause(cl); if (ems != null) { ErrorBehaviorStateMachine ebsm = ems.getUseBehavior(); if (ebsm != null) return ebsm; } if (!Aadl2Util.isNull(cl.getExtended())){ ems= getExtendsEMV2Subclause(cl.getExtended()); if (ems != null) { ErrorBehaviorStateMachine ebsm = ems.getUseBehavior(); if (ebsm != null) return ebsm; } } return null; } /** * find error behavior transition in the specified context, i.e., its enclosing classifier subclause or inherited subclauses * we look in the component error behavior sections first, and then in the EBSM of the use behavior. * @param context * @param name * @return */ public static ErrorBehaviorTransition findErrorBehaviorTransition(Element context, String name){ Classifier cl = context.getContainingClassifier(); if (cl != null){ // we are not in an error library ErrorBehaviorTransition ebt = findErrorBehaviorTransitioninCEB(cl, name); if (ebt != null) return ebt; // find it in the EBSM from the use behavior return findErrorBehaviorTransitioninUseBehavior(cl, name); } else { // we are inside an error library resolving transition references ErrorBehaviorStateMachine ebsm = EMV2Util.getContainingErrorBehaviorStateMachine(context); if (ebsm == null) ebsm = EMV2Util.getUsedErrorBehaviorStateMachine(context); return findErrorBehaviorTransitionInEBSM(ebsm, name); } } /** * find the first subclause and look for this Use Behavior. * Since Use behavior is optional it might not find any * It will not assume that Use Behavior is inherited * @param cl * @param name * @return */ public static ErrorBehaviorTransition findErrorBehaviorTransitioninUseBehavior(Classifier cl, String name){ if (cl == null) return null; // XXX if we want to support inherit of Use Behavior we call getClassifierUseBehavior to get the EBSM // and then do a find on it. ErrorModelSubclause ems = getClassifierEMV2Subclause(cl); ErrorBehaviorStateMachine ebsm = ems.getUseBehavior(); if (ebsm != null){ return findErrorBehaviorTransitionInEBSM(ebsm, name); } return null; } /** * find transition in EBSM * @param ebsm * @param name * @return */ public static ErrorBehaviorTransition findErrorBehaviorTransitionInEBSM(ErrorBehaviorStateMachine ebsm, String name){ if (ebsm != null){ EList<ErrorBehaviorTransition> ebsl= ebsm.getTransitions(); for (ErrorBehaviorTransition ebs : ebsl){ if (EMV2Util.getItemName(name).equalsIgnoreCase(ebs.getName())) return ebs; } // enable if we introduce extends of EBSM // if (ebsm.getExtends() != null){ // return findErrorBehaviorTransitionInEBSM(ebsm.getExtends(), name); // } } return null; } /** * find the error behavior transition in the component error behavior looking in all inherited subclauses according to extends and type of implementation * @param cl * @param name * @return */ public static ErrorBehaviorTransition findErrorBehaviorTransitioninCEB(Classifier cl, String name){ if (cl == null) return null; EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorBehaviorTransition res = findOwnErrorBehaviorTransition(errorModelSubclause, name); if (res != null) return res; } return null; } /** * find transition in given subclause component error behavior * @param ems * @param name * @return */ public static ErrorBehaviorTransition findOwnErrorBehaviorTransition(ErrorModelSubclause ems, String name){ if (ems == null) return null; ComponentErrorBehavior ceb = ems.getComponentBehavior(); if (ceb != null){ EList<ErrorBehaviorTransition> transitions = ceb.getTransitions(); for (ErrorBehaviorTransition errorBehaviorTransition : transitions) { if (name.equalsIgnoreCase(errorBehaviorTransition.getName())) return errorBehaviorTransition; } } return null; } public static ErrorBehaviorEvent findOwnErrorBehaviorEvent(ErrorModelSubclause ems, String name){ if (ems == null) return null; ComponentErrorBehavior ceb = ems.getComponentBehavior(); if (ceb != null){ EList<ErrorBehaviorEvent> events = ceb.getEvents(); for (ErrorBehaviorEvent errorBehaviorEvent : events) { if (name.equalsIgnoreCase(errorBehaviorEvent.getName())) return errorBehaviorEvent; } } return null; } /** * find the error behavior event in the component error behavior looking in all inherited subclauses according to extends and type of implementation * @param cl * @param name * @return */ public static ErrorBehaviorEvent findErrorBehaviorEventinCEB(Classifier cl, String name){ if (cl == null) return null; EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorBehaviorEvent res = findOwnErrorBehaviorEvent(errorModelSubclause, name); if (res != null) return res; } return null; } /** * find error behavior event in the specified context, i.e., its enclosing classifier subclause or inherited subclauses * we look in the component error behavior sections first, and then in the EBSM of the use behavior. * @param context * @param name * @return */ public static ErrorBehaviorEvent findErrorBehaviorEvent(Element context, String name){ Classifier cl = context.getContainingClassifier(); if (cl != null){ // we are not in an error library ErrorBehaviorEvent ebt = findErrorBehaviorEventinCEB(cl, name); if (ebt != null) return ebt; // find it in the EBSM from the use behavior return findErrorBehaviorEventinUseBehavior(cl, name); } else { // we are inside an error library resolving transition references ErrorBehaviorStateMachine ebsm = EMV2Util.getContainingErrorBehaviorStateMachine(context); if (ebsm == null) ebsm = EMV2Util.getUsedErrorBehaviorStateMachine(context); return findErrorBehaviorEventInEBSM(ebsm, name); } } /** * find the first subclause and look for this Use Behavior. * Since Use behavior is optional it might not find any * It will not assume that Use Behavior is inherited * @param cl * @param name * @return */ public static ErrorBehaviorEvent findErrorBehaviorEventinUseBehavior(Classifier cl, String name){ if (cl == null) return null; // XXX if we want to support inherit of Use Behavior we call getClassifierUseBehavior to get the EBSM // and then do a find on it. ErrorModelSubclause ems = getClassifierEMV2Subclause(cl); ErrorBehaviorStateMachine ebsm = ems.getUseBehavior(); if (ebsm != null){ return findErrorBehaviorEventInEBSM(ebsm, name); } return null; } public static ErrorBehaviorEvent findErrorBehaviorEventInEBSM(ErrorBehaviorStateMachine ebsm, String name){ if (ebsm != null){ EList<ErrorBehaviorEvent> ebsl= ebsm.getEvents(); for (ErrorBehaviorEvent ebs : ebsl){ if (EMV2Util.getItemName(name).equalsIgnoreCase(ebs.getName())) return ebs; } // enable if we support extends of EBSM // if (ebsm.getExtends() != null){ // return findErrorBehaviorEventInEBSM(ebsm.getExtends(), name); // } } return null; } /** * find Error Detection in own subclause component error behavior * @param ems * @param name * @return */ public static ErrorDetection findOwnErrorDetection(ErrorModelSubclause ems, String name){ if (ems == null) return null; ComponentErrorBehavior ceb = ems.getComponentBehavior(); if (ceb != null){ EList<ErrorDetection> detections = ceb.getErrorDetections(); for (ErrorDetection errorDetection : detections) { if (name.equalsIgnoreCase(errorDetection.getName())) return errorDetection; } } return null; } /** * find the error detection in the component error behavior looking in all inherited subclauses according to extends and type of implementation * @param cl * @param name * @return */ public static ErrorDetection findErrorDetectioninCEB(Classifier cl, String name){ if (cl == null) return null; EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorDetection res = findOwnErrorDetection(errorModelSubclause, name); if (res != null) return res; } return null; } /** * find error detection in the specified context, i.e., its enclosing classifier subclause or inherited subclauses * we look in the component error behavior sections . * @param context * @param name * @return */ public static ErrorDetection findErrorDetection(Element context, String name){ Classifier cl = context.getContainingClassifier(); if (cl != null){ // we are not in an error library ErrorDetection ebt = findErrorDetectioninCEB(cl, name); return ebt; } return null; } /** * find Error Detection in own subclause component error behavior * @param ems * @param name * @return */ public static OutgoingPropagationCondition findOwnOutgoingPropagationCondition(ErrorModelSubclause ems, String name){ if (ems == null) return null; ComponentErrorBehavior ceb = ems.getComponentBehavior(); if (ceb != null){ EList<OutgoingPropagationCondition> outgoingPs = ceb.getOutgoingPropagationConditions(); for (OutgoingPropagationCondition outgoingPropagationCondition : outgoingPs) { if (name.equalsIgnoreCase(outgoingPropagationCondition.getName())) return outgoingPropagationCondition; } } return null; } /** * find the error detection in the component error behavior looking in all inherited subclauses according to extends and type of implementation * @param cl * @param name * @return */ public static OutgoingPropagationCondition findOutgoingPropagationConditioninCEB(Classifier cl, String name){ if (cl == null) return null; EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { OutgoingPropagationCondition res = findOwnOutgoingPropagationCondition(errorModelSubclause, name); if (res != null) return res; } return null; } /** * find error detection in the specified context, i.e., its enclosing classifier subclause or inherited subclauses * we look in the component error behavior sections . * @param context * @param name * @return */ public static OutgoingPropagationCondition findOutgoingPropagationCondition(Element context, String name){ Classifier cl = context.getContainingClassifier(); if (cl != null){ // we are not in an error library return findOutgoingPropagationConditioninCEB(cl, name); } return null; } /** * return list of error propagations including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorPropagation> list of ErrorPropagations excluding duplicates */ public static Collection<ErrorPropagation> getAllErrorPropagations(Classifier cl){ return getAllErrorPropagations(cl, null).values(); } /** * return list of outgoing error propagations including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorPropagation> list of ErrorPropagations excluding duplicates */ public static Collection<ErrorPropagation> getAllOutgoingErrorPropagations(Classifier cl){ Collection<ErrorPropagation> props = getAllErrorPropagations(cl, null).values(); BasicEList<ErrorPropagation> result = new BasicEList<ErrorPropagation>(); for (ErrorPropagation errorPropagation : props) { if (errorPropagation.getDirection().equals(DirectionType.OUT)){ result.add(errorPropagation); } } return result; } /** * return list of error propagations including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorPropagation> list of ErrorPropagations excluding duplicates */ public static Collection<ErrorPropagation> getAllIncomingErrorPropagations(Classifier cl){ Collection<ErrorPropagation> props = getAllErrorPropagations(cl, null).values(); BasicEList<ErrorPropagation> result = new BasicEList<ErrorPropagation>(); for (ErrorPropagation errorPropagation : props) { if (errorPropagation.getDirection().equals(DirectionType.IN)){ result.add(errorPropagation); } } return result; } /** * return list of error propagations including those inherited from classifiers being extended * @param cl Classifier * @param dup Collection (ArrayList) <ErrorPropagation> will contain found duplicates * @return HashMap<String,ErrorPropagation> list of ErrorPropagation excluding duplicates */ public static HashMap<String,ErrorPropagation> getAllErrorPropagations(Classifier cl, Collection<ErrorPropagation> dup){ HashMap<String,ErrorPropagation> result = new HashMap<String,ErrorPropagation>(); EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagations eps = errorModelSubclause.getErrorPropagations(); if (eps!= null){ EList<ErrorPropagation> eflist = eps.getPropagations(); for (ErrorPropagation errorProp : eflist) { if (!errorProp.isNot()){ String epname = EMV2Util.getPrintName(errorProp); if (!result.containsKey(epname)){ result.put(epname,errorProp); } else { if (dup != null) dup.add(errorProp); } } } } } return result; } /** * return list of error containments including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorPropagation> list of ErrorPropagations excluding duplicates */ public static Collection<ErrorPropagation> getAllErrorContainments(Classifier cl){ return getAllErrorPropagations(cl, null).values(); } /** * return list of error containments including those inherited from classifiers being extended * @param cl Classifier * @param dup Collection (ArrayList) <ErrorPropagation> will contain found duplicates * @return HashMap<String,ErrorPropagation> list of ErrorPropagation containments excluding duplicates */ public static HashMap<String,ErrorPropagation> getAllErrorContainments(Classifier cl, Collection<ErrorPropagation> dup){ HashMap<String,ErrorPropagation> result = new HashMap<String,ErrorPropagation>(); EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagations eps = errorModelSubclause.getErrorPropagations(); if (eps!= null){ EList<ErrorPropagation> eflist = eps.getPropagations(); for (ErrorPropagation errorProp : eflist) { if (!errorProp.isNot()){ String epname = EMV2Util.getPrintName(errorProp); if (!result.containsKey(epname)){ result.put(epname,errorProp); } else { if (dup != null) dup.add(errorProp); } } } } } return result; } /** * return list of error flow including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorFlow> list of error flow */ public static Collection<ErrorFlow> getAllErrorFlows(Classifier cl){ return getAllErrorFlows(cl, null).values(); } /** * return list of error flow including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorFlow> list of error flow */ public static Collection<ErrorFlow> getDuplicateErrorFlows(Classifier cl){ Collection<ErrorFlow> dup = new ArrayList<ErrorFlow>(); getAllErrorFlows(cl, dup); return dup; } /** * return list of error flows including those inherited from classifiers being extended * @param cl Classifier * @param dup Collection (ArrayList) <ErrorFlow> will contain found duplicates * @return Collection<ErrorFlow> list of error flows excluding duplicates */ public static HashMap<String,ErrorFlow> getAllErrorFlows(Classifier cl, Collection<ErrorFlow> dup){ HashMap<String,ErrorFlow> result = new HashMap<String,ErrorFlow>(); EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagations eps = errorModelSubclause.getErrorPropagations(); if (eps!= null){ EList<ErrorFlow> eflist = eps.getFlows(); for (ErrorFlow errorFlow : eflist) { if (!result.containsKey(errorFlow.getName())){ result.put(errorFlow.getName(),errorFlow); } else { if (dup != null) dup.add(errorFlow); } } } } return result; } /** * return list of error sources including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorSource> list of error flow */ public static Collection<ErrorSource> getAllErrorSources(Classifier cl){ return getAllErrorSources(cl, null); } /** * return list of error sources including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorSource> list of error sources */ public static Collection<ErrorSource> getDuplicateErrorSources(Classifier cl){ Collection<ErrorSource> dup = new ArrayList<ErrorSource>(); getAllErrorSources(cl, dup); return dup; } /** * return list of error sources including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorFlow> list of error flow as HashMap for quick lookup of names */ public static Collection<ErrorSource> getAllErrorSources(Classifier cl, Collection<ErrorSource> dup){ HashMap<String,ErrorSource> result = new HashMap<String,ErrorSource>(); EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorPropagations eps = errorModelSubclause.getErrorPropagations(); if (eps!= null){ EList<ErrorFlow> eflist = eps.getFlows(); for (ErrorFlow errorFlow : eflist) { if (errorFlow instanceof ErrorSource){ if( !result.containsKey(errorFlow.getName())){ result.put(errorFlow.getName(),(ErrorSource)errorFlow); } else { if (dup != null) dup.add((ErrorSource)errorFlow); } } } } } return result.values(); } /** * return list of propagation points including those inherited from classifiers being extended * @param cl Classifier * @return Collection<PropagationPoint> list of propagation points as HashMap for quick lookup of names */ public static Collection<PropagationPoint> getAllPropagationPoints(Classifier cl){ return getAllPropagationPoints(cl, null).values(); } /** * return list of propagation points including those inherited from classifiers being extended * @param cl Classifier * @return HashMap<String,PropagationPoint> list of propagation points as HashMap for quick lookup of names */ public static HashMap<String,PropagationPoint> getAllPropagationPoints(Classifier cl, Collection<PropagationPoint> dup){ HashMap<String,PropagationPoint> result = new HashMap<String,PropagationPoint>(); EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { PropagationPaths eps = errorModelSubclause.getPropagationPaths(); if (eps!= null){ EList<PropagationPoint> eflist = eps.getPoints(); for (PropagationPoint propPoint : eflist) { if ( !result.containsKey(propPoint.getName())){ result.put(propPoint.getName(),propPoint); } else { if (dup != null) dup.add(propPoint); } } } } return result; } /** * return list of PropagationPointConnections including those inherited from classifiers being extended * @param cl Classifier * @return HashMap<String,PropagationPointConnection> list of PropagationPointConnections as HashMap for quick lookup of names */ public static HashMap<String,PropagationPointConnection> getAllPropagationPointConnections(Classifier cl,Collection<PropagationPointConnection> dup){ HashMap<String,PropagationPointConnection> result = new HashMap<String,PropagationPointConnection>(); EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { PropagationPaths eps = errorModelSubclause.getPropagationPaths(); if (eps!= null){ EList<PropagationPointConnection> eflist = eps.getConnections(); for (PropagationPointConnection propPointConn : eflist) { if ( !result.containsKey(propPointConn.getName())){ result.put(propPointConn.getName(),propPointConn); } else { if (dup != null) dup.add(propPointConn); } } } } return result; } /** * return list of PropagationPointConnections including those inherited from classifiers being extended * @param cl Classifier * @return Collection<PropagationPointConnection> list of PropagationPointConnections as HashMap for quick lookup of names */ public static Collection<PropagationPointConnection> getAllPropagationPointConnections(Classifier cl){ return getAllPropagationPointConnections(cl, null).values(); } /** * return list of ErrorBehaviorEvents including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorBehaviorEvent> list of ErrorBehaviorEvents as HashMap for quick lookup of names */ public static Collection<ErrorBehaviorEvent> getAllErrorBehaviorEvents(Classifier cl){ return getAllErrorBehaviorEvents(cl, null).values(); } /** * return list of ErrorBehaviorEvents including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorBehaviorEvent> list of ErrorBehaviorEvents as HashMap for quick lookup of names */ public static HashMap<String,ErrorBehaviorEvent> getAllErrorBehaviorEvents(Classifier cl,Collection<ErrorBehaviorEvent> dup){ HashMap<String,ErrorBehaviorEvent> result = new HashMap<String,ErrorBehaviorEvent>(); EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); boolean foundEBSM = false; for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorBehaviorStateMachine ebsm = errorModelSubclause.getUseBehavior(); ComponentErrorBehavior ceb = errorModelSubclause.getComponentBehavior(); if (ceb!= null){ EList<ErrorBehaviorEvent> eflist = ceb.getEvents(); for (ErrorBehaviorEvent ebe : eflist) { if ( !result.containsKey(ebe.getName())){ result.put(ebe.getName(),ebe); } else { if (dup != null) dup.add(ebe); } } } if (!foundEBSM && ebsm!= null){ foundEBSM = true; EList<ErrorBehaviorEvent> eflist = ebsm.getEvents(); for (ErrorBehaviorEvent ebe : eflist) { if ( !result.containsKey(ebe.getName())){ result.put(ebe.getName(),ebe); } else { if (dup != null) dup.add(ebe); } } } } return result; } /** * return list of ErrorBehaviorStates including those inherited from classifiers being extended * @param cl Classifier * @return Collection<ErrorBehaviorState> list of ErrorBehaviorStates as HashMap for quick lookup of names */ public static Collection<ErrorBehaviorState> getAllErrorBehaviorStates(Classifier cl){ HashMap<String,ErrorBehaviorState> result = new HashMap<String,ErrorBehaviorState>(); EList<ErrorModelSubclause> emslist = getAllContainingClassifierEMV2Subclauses(cl); for (ErrorModelSubclause errorModelSubclause : emslist) { ErrorBehaviorStateMachine ebsm = errorModelSubclause.getUseBehavior(); if ( ebsm!= null){ EList<ErrorBehaviorState> eflist = ebsm.getStates(); for (ErrorBehaviorState ebs : eflist) { if ( !result.containsKey(ebs.getName())){ result.put(ebs.getName(),ebs); } } return result.values(); } } return Collections.EMPTY_LIST; } /** * get the EM object that contains the condition expression. * Traverses up the expression tree to the enclosing EM object * @param element * @return Error Model object that contains the expression */ public static EObject getConditionOwner(Element element) { EObject container = element; while (container != null && (container instanceof ConditionExpression)) container = container.eContainer(); return container ; } /** * get the state machine that contains the EM element * @param element * @return ErrorBehaviorStateMachine object or null if element is not inside an EBSM */ public static ErrorBehaviorStateMachine getContainingErrorBehaviorStateMachine(Element element) { EObject container = element; while (container != null && !(container instanceof ErrorBehaviorStateMachine)) container = container.eContainer(); return (ErrorBehaviorStateMachine) container; } /** * get the enclosing error model library. * Returns null if the element is not in a error model library * @param element * @return ErrorModelLibrary or null */ public static ErrorModelLibrary getContainingErrorModelLibrary(Element element) { EObject container = element; while (container != null && !(container instanceof ErrorModelLibrary)) container = container.eContainer(); return (ErrorModelLibrary) container; } /** * get the enclosing type use context * A type use context is is the object that contains use references to error model/type libraries * @param element * @return Type transformation set, type mapping set, error propagations object, EBSM, * component error behavior, composite error behavior * or null if not in any */ public static TypeUseContext getContainingTypeUseContext(Element element) { EObject container = element; while (container != null && !(container instanceof TypeUseContext)) container = container.eContainer(); return (TypeUseContext) container; } /** * extract the item name from a qualified name, the identifier after the last :: * @param qualname String Qualified name * @return String item name */ public static String getItemName(String qualname){ final int idx = qualname.lastIndexOf("::"); if (idx != -1) { return qualname.substring(idx + 2); } return qualname; } /** * extract the package name of a qualified name, everything up to the last :: or null * @param qualname * @return String */ public static String getPackageName(String qualname){ final int idx = qualname.lastIndexOf("::"); if (idx != -1) { return qualname.substring(0, idx); } return null; } public static String getPrintName(Element el){ if (el instanceof NamedElement){ NamedElement ne = (NamedElement)el; if(ne.getName() != null) return ne.getName(); } if (el instanceof ErrorPropagation){ ErrorPropagation ep = (ErrorPropagation)el; String res = getPrintName(ep); if (!res.isEmpty()) return res; if (ep.getKind() != null) return ep.getKind(); } return ""; } /** * get printName of Error Propagation * @param ep * @return */ public static String getPrintName(ErrorPropagation ep){ EList<FeatureReference> refs = ep.getFeaturerefs(); String refname = ""; for (FeatureReference featureReference : refs) { if (Aadl2Util.isNull(featureReference.getFeature())) return null; refname = refname + (refname.isEmpty()?"":".")+featureReference.getFeature().getName(); } return refname; } public static String getPrintName(TypeSet ts){ return getPrintableName(ts, ", "); } public static String getPrintName(ErrorModelLibrary eml){ return AadlUtil.getContainingPackage(eml).getName(); } public static String getTableName(TypeSet ts){ return getPrintableName(ts, "/"); } public static String getPrintableName(TypeSet ts,String separator){ if (ts == null) return ""; String res ="{"; EList<TypeToken> te = ts.getElementType(); boolean docomma = false; for (TypeToken typeSetElement : te) { EList<ErrorType> et = typeSetElement.getType(); if (docomma) res = res+separator; else docomma = true; if (et != null&& !et.isEmpty()){ boolean doproduct = false; for (ErrorType errorType : et) { if (doproduct) res = res+"+"; else doproduct = true; res = res + errorType.getName(); } } } return res+"}"; } public static String getPrintName(TypeToken tu){ return "{"+getName(tu)+"}"; } public static String getName(TypeToken tu){ if (tu == null) return ""; String res =""; EList<ErrorType> te = tu.getType(); boolean docomma = false; for (ErrorType et : te) { if (docomma) res = res+"+"; else docomma = true; res = res + et.getName(); } return res; } public static String getPrintName(EList<TypeToken> tul){ String res ="("; for (TypeToken tu : tul) { res = res + "\n "+getPrintName(tu); } return res+"\n)"; } /** * get the EBSM referenced in the enclosing context, i.e., by the * component error behavior or composite error behavior declaration * or contained in the element if it is a classifier. * @param element model object contained in a component or composite error behavior declaration * @return ErrorBehaviorStateMachine or null */ public static ErrorBehaviorStateMachine getUsedErrorBehaviorStateMachine(EObject element) { if (element instanceof Classifier){ Classifier cl = (Classifier)element; return EMV2Util.getClassifierUseBehavior(cl); } EObject container = element; while (container != null && !(container instanceof EBSMUseContext)) container = container.eContainer(); if (container == null) return null; return getUseBehavior((EBSMUseContext) container); } /** * resolve the errortype if it is an alias, otherwise return the error type * @param et ErrorType that may be an alias * @return ErrorType without alias */ public static ErrorType resolveAlias(ErrorType et){ if (Aadl2Util.isNull(et)) return null; while (!Aadl2Util.isNull(et.getAliasedType())){ et = et.getAliasedType(); } return et; } /** * resolve the typeset if it is an alias, otherwise return the typeset * @param typeset TypeSet * @return TypeSet resolved TypeSet */ public static TypeSet resolveAlias(TypeSet typeset){ if (Aadl2Util.isNull(typeset)) return null; if (!Aadl2Util.isNull(typeset.getReference())){ typeset = typeset.getReference(); } while (!Aadl2Util.isNull(typeset.getAliasedType())){ typeset = typeset.getAliasedType(); } return typeset; } /** * find the actual ErrorTypes following the alias link * @param et * @return */ public static ErrorTypes resolveAlias(ErrorTypes et){ if (Aadl2Util.isNull(et)) return null; return (et instanceof ErrorType)?EMV2Util.resolveAlias((ErrorType)et):EMV2Util.resolveAlias((TypeSet)et); } /** * get UseBehavior, i.e., the referenced error behavior state machine * @param context * @return ErrorBehaviorStateMachine */ public static ErrorBehaviorStateMachine getUseBehavior(EBSMUseContext context){ if (context instanceof ErrorModelSubclause) return ((ErrorModelSubclause)context).getUseBehavior(); return null; } /** * get list of ErrorModelLibraries listed in UseTypes * @param context Type use context * @return EList<ErrorModelLibrary> */ public static EList<ErrorModelLibrary> getUseTypes(TypeUseContext context){ if (context instanceof ErrorModelSubclause) return ((ErrorModelSubclause)context).getUseTypes(); if (context instanceof TypeTransformationSet) return ((TypeTransformationSet)context).getUseTypes(); if (context instanceof TypeMappingSet) return ((TypeMappingSet)context).getUseTypes(); if (context instanceof ErrorBehaviorStateMachine) return ((ErrorBehaviorStateMachine)context).getUseTypes(); return null; } /** * find the model object that contains the condition expression * @param ce Condition Expression * @return EObject */ public static EObject getConditionExpressionContext(ConditionExpression ce){ EObject res = ce; while (res instanceof ConditionExpression){ res = res.eContainer(); } return res; } /** return list of property associations that meet the property name * * @param props property association list from the properties section * @param propertyName name of property * @return EList<PropertyAssociation> */ public static List<PropertyAssociation> getProperty(EList<PropertyAssociation> props,String propertyName){ List<PropertyAssociation> result = new BasicEList<PropertyAssociation>(); for (PropertyAssociation propertyAssociation : props) { Property prop = propertyAssociation.getProperty(); String name = prop.getQualifiedName(); if (propertyName.equalsIgnoreCase(name)){ result.add(propertyAssociation); } } return result; } /** * find property by first looking for it down the component instance hierarchy to ci * Then try to find it in the local context if not null. The context is the context object of the referenced target. * For example: the transition for a state reference. * Finally, we look for the property at the definition site of the referenced object. * NOTE: the target element may actually be contained in a different context from the context in which we are interested in its property. * For example, we are interested in the occurrence distribution for an error state. It actually is contained in an error behavior state machine. * We are interested in its property value in the context of of the reference to the state, e.g., an error source. * In some cases we are interested in the state as it is associated with the component via the use behavior clause. * In that case there is no local context for the state reference. * @param propertyName String * @param ci ComponentInstance the component with the error model element, whose property we are retrieving * @param localContext Element the object that contains the reference to a target object, or null. * @param target Element the target object in the error model whose property we retrieve * @return */ public static ContainedNamedElement getProperty(String propertyName, ComponentInstance ci,Element localContext,Element target, TypeSet ts){ ContainedNamedElement result = getPropertyInInstanceHierarchy(propertyName,ci,target,localContext, ts); if (result==null&& localContext != null){ // look up in local context of target reference // for example: the flow source in error propagations or transition in component error behavior for a state reference EList<PropertyAssociation> props = EMV2Util.getContainingPropertiesHolder(localContext); if (props != null) { result = getProperty(props, propertyName, target,localContext,ts); } } if (result==null){ // look up in context of target definition // for example: for a state reference the properties section of the EBSM that defines the state EList<PropertyAssociation> props = EMV2Util.getContainingPropertiesHolder(target); if (props != null) { result = getProperty(props, propertyName, target,localContext,ts); } } return result; } /** * retrieve an error model property (such as Hazard) attached to an error model element based on contained property associations * in the annex subclause properties section. * Here we come down the component instance hierarchy to find the outmost property association * in the properties section of the annex subclauses. Those are the ones that can override down the component hierarchy. * @param props list of property associations from the properties section in the error model * @param propertyName name of property we are looking for * @param target the error model element (first item in the containment path) * @return property association */ public static ContainedNamedElement getPropertyInInstanceHierarchy(String propertyName, ComponentInstance ci,Element target, Element localContext, TypeSet ts){ Stack<ComponentInstance> ciStack = new Stack<ComponentInstance>(); return getPropertyInInstanceHierarchy(propertyName,ci,target,localContext,ciStack, ts); } private static ContainedNamedElement getPropertyInInstanceHierarchy(String propertyName, ComponentInstance ci,Element target, Element localContext,Stack<ComponentInstance> ciStack, TypeSet ts){ ContainedNamedElement result = null; if (ci.getContainingComponentInstance() != null) { ciStack.push(ci); result = getPropertyInInstanceHierarchy(propertyName, ci.getContainingComponentInstance(), target,localContext,ciStack,ts); ciStack.pop(); } if (result==null){ ErrorModelSubclause ems = EMV2Util.getClassifierEMV2Subclause(ci.getComponentClassifier()); if (ems != null) { EList<PropertyAssociation> props = ems.getProperties(); result = getProperty(props, propertyName, target, localContext,ciStack,ts); } } return result; } /** * retrieve an error model property (such as Hazard) attached to an error model element. * @param props list of property associations from the properties section in the error model * @param propertyName name of property we are looking for * @param target the error model element * @param ciStack stack of nested CI * @return property association */ public static ContainedNamedElement getProperty(EList<PropertyAssociation> props,String propertyName, Element target, Element localContext, Stack<ComponentInstance> ciStack, TypeSet ts){ if (props == null) return null; ContainedNamedElement result = null; for (PropertyAssociation propertyAssociation : props) { Property prop = propertyAssociation.getProperty(); String name = prop.getQualifiedName(); if (propertyName.equalsIgnoreCase(name)){ result = EMV2Util.isErrorModelElementProperty(propertyAssociation, target,localContext,ciStack,ts); if (result!=null) return result; } } return result; } /** * retrieve an error model property (such as Hazard) attached to an error model element. * @param props list of property associations from the properties section in the error model * @param propertyName name of property we are looking for * @param target the error model element * @param ciStack stack of nested CI * @return property association */ public static ContainedNamedElement getProperty(EList<PropertyAssociation> props,String propertyName, Element target, Element localContext, TypeSet ts){ if (props == null) return null; ContainedNamedElement result = null; for (PropertyAssociation propertyAssociation : props) { Property prop = propertyAssociation.getProperty(); String name = prop.getQualifiedName(); if (propertyName.equalsIgnoreCase(name)){ result = EMV2Util.isErrorModelElementProperty(propertyAssociation, target,localContext,null,ts); if (result!=null) return result; } } return result; } /** * determine whether the property applies to specified error model element or elements contained in it * (typically error types inside an error model element) * ciStack represents the path from the context of the PA to the component instance whose property we want to retrieve * In other words target must be the last or second to last element in a path. * @param propertyAssociation PropertyAssociation that is the candidate * @param ciStack ComponentInstance in instance model hierarchy with the error model element, whose property we are retrieving * @param localContext Element the object that contains the reference to a target object, or null. * @param target Element the target object in the error model whose property we retrieve * @return ContainedNamedElement the containment path that matches */ public static ContainedNamedElement isErrorModelElementProperty(PropertyAssociation propertyAssociation, Element target, Element localContext,Stack<ComponentInstance> ciStack, TypeSet ts ){ if (ciStack == null) { return null; } EList<ContainedNamedElement> applies = propertyAssociation.getAppliesTos(); for (ContainedNamedElement containedNamedElement : applies) { EList<ContainmentPathElement> cpes = containedNamedElement.getContainmentPathElements(); int targetsize = (ciStack.size()+1+(localContext==null?0:1)); - boolean nomatch = false; + boolean match = true; if (cpes.size() == targetsize || cpes.size()== targetsize+1){ for (int i = 0; i< ciStack.size(); i++){ if (ciStack.get(i).getSubcomponent() != cpes.get(i).getNamedElement()){ - nomatch = true; + match = false; break; } } - if (nomatch) break; + if (match) { // we are past the component portion of the path NamedElement targetel = cpes.get(cpes.size()-1).getNamedElement(); // check on the last element + boolean typematch = true; if (targetel instanceof ErrorTypes){ // it points to an error type or type set if (ts !=null){ if (targetel instanceof ErrorType){ // we refer to a type if (!EM2TypeSetUtil.contains(ts, (ErrorType)targetel)){ - break; + typematch = false; } } else if (targetel instanceof TypeSet){ // we refer to a type if (!EM2TypeSetUtil.contains(ts, (TypeSet)targetel)){ - break; + typematch = false; } } } - targetel = cpes.get(cpes.size()-2).getNamedElement(); - if (targetel == target) - return containedNamedElement; + if (typematch){ + targetel = cpes.get(cpes.size()-2).getNamedElement(); + if (targetel == target) + return containedNamedElement; + } } else { // last element should be target element if ( target == targetel){ if (localContext != null){ // make sure the local context matches the previous element in the path NamedElement localContextme = cpes.get(cpes.size()-2).getNamedElement(); - if ( localContext != localContextme){ - break; - } else { + if ( localContext == localContextme){ return containedNamedElement; } } else { return containedNamedElement; } - } else { - break; } } + } } } return null; } /** * get list of error types, one for each containment path * We assume that each path is of length one * @param containedNamedElement Containment path * @return EList<ErrorType> */ public static ErrorType getContainmentErrorType(ContainedNamedElement containedNamedElement){ EList<ContainmentPathElement> cpes = containedNamedElement.getContainmentPathElements(); if (cpes.size()==1){ ContainmentPathElement cpe = cpes.get(0); NamedElement appliestome = cpe.getNamedElement(); if (appliestome instanceof ErrorType) return((ErrorType)appliestome); } return null; } /** * test only current classifier, not inherited * @param ci * @return */ public static boolean hasErrorPropagations(ComponentInstance ci){ return hasErrorPropagations(ci.getComponentClassifier()); } public static boolean hasErrorPropagations(ComponentClassifier cl){ ErrorModelSubclause ems = getClassifierEMV2Subclause(cl); return ems != null && ems.getErrorPropagations() != null; } public static boolean hasComponentErrorBehavior(ComponentInstance ci){ return hasComponentErrorBehavior(ci.getComponentClassifier()); } /** * * @param cl The component classifier that is under test to have * an error-annex subclause. * @return True is the component classifier has an error annex * subclause. False otherwise. */ public static boolean hasComponentErrorBehavior(ComponentClassifier cl){ ErrorModelSubclause emsc = getClassifierEMV2Subclause(cl); return (emsc != null&& emsc.getComponentBehavior() != null); } public static boolean hasCompositeErrorBehavior(ComponentInstance ci){ return hasCompositeErrorBehavior(ci.getComponentClassifier()); } public static boolean hasCompositeErrorBehavior(ComponentClassifier cl){ ErrorModelSubclause emsc = getClassifierEMV2Subclause(cl); return emsc != null&&emsc.getCompositeBehavior() != null; } /** * retrieve list of component instances that have error propagations specified * For process component instances do not recurse below and include the component instance * even if no error propagation is attached. * For other component instances include the component instance if it does not have children even if it does not include * error propagations * @param ci ComponentInstance * @return EList of leaf component instances */ public static EList<ComponentInstance> getComponentInstancesWithErrorPropagations(ComponentInstance ci){ EList result = new ForAllElement(){ @Override protected boolean suchThat(Element obj) { return (obj instanceof ComponentInstance&& (EMV2Util.hasErrorPropagations((ComponentInstance)obj) || ((ComponentInstance)obj).getComponentInstances().isEmpty() || ((ComponentInstance)obj).getCategory() == ComponentCategory.PROCESS )); } }.processPreOrderComponentInstanceStop(ci); return result ; } /** * retrieve list of component instances that have error propagations specified * For process component instances or component instance without children, do not recurse below and do not include the component instance * @param ci ComponentInstance * @return EList of leaf component instances */ public static EList<ComponentInstance> getComponentInstancesWithErrorPropagationsOnly(ComponentInstance ci){ EList result = new ForAllElement(){ @Override protected boolean suchThat(Element obj) { return (obj instanceof ComponentInstance&& (EMV2Util.hasErrorPropagations((ComponentInstance)obj) )); } @Override protected boolean processStop (Element theElement) { if (suchThat((Element) theElement)) { if (theElement instanceof NamedElement){ //{ System.out.println(((NamedElement) theElement).getName());} action((Element) theElement); return true; } } if (((ComponentInstance)theElement).getCategory() == ComponentCategory.PROCESS) { return true; } else { return false; } } }.processPreOrderComponentInstanceStop(ci); return result ; } /** * retrieve list of component instances that have component error behavior specified * For process component instances do not recurse below and include the component instance * even if no error propagation is attached. * Foe other component instances include the component instance if it does not have children even if it does not include * error propagations * @param ci ComponentInstance * @return EList of leaf component instances */ public static EList<ComponentInstance> getComponentInstancesWithComponentErrorBehavior(ComponentInstance ci){ EList result = new ForAllElement(){ @Override protected boolean suchThat(Element obj) { return (obj instanceof ComponentInstance&& (EMV2Util.hasComponentErrorBehavior((ComponentInstance)obj) || ((ComponentInstance)obj).getComponentInstances().isEmpty() || ((ComponentInstance)obj).getCategory() == ComponentCategory.PROCESS )); } }.processPreOrderComponentInstanceStop(ci); return result ; } /** * retrieve list of component instances that have component error behavior specified * For process component instances or component instance without children, do not recurse below and do not include the component instance * @param ci ComponentInstance * @return EList of leaf component instances */ public static EList<ComponentInstance> getComponentInstancesWithComponentErrorBehaviorOnly(ComponentInstance ci){ EList result = new ForAllElement(){ @Override protected boolean suchThat(Element obj) { return (obj instanceof ComponentInstance&& (EMV2Util.hasComponentErrorBehavior((ComponentInstance)obj) )); } @Override protected boolean processStop (Element theElement) { if (suchThat((Element) theElement)) { if (theElement instanceof NamedElement){ //{ System.out.println(((NamedElement) theElement).getName());} action((Element) theElement); return true; } } if (((ComponentInstance)theElement).getCategory() == ComponentCategory.PROCESS) { return true; } else { return false; } } }.processPreOrderComponentInstanceStop(ci); return result ; } /** * retrieve list of component instances that have composite error behavior specified * For process component instances do not recurse below and include the component instance * even if no error propagation is attached. * Foe other component instances include the component instance if it does not have children even if it does not include * error propagations * @param ci ComponentInstance * @return EList of leaf component instances */ public static EList<ComponentInstance> getCompositeInstancesWithComponentErrorBehavior(ComponentInstance ci){ EList result = new ForAllElement(){ @Override protected boolean suchThat(Element obj) { return (obj instanceof ComponentInstance&& (EMV2Util.hasCompositeErrorBehavior((ComponentInstance)obj) || ((ComponentInstance)obj).getComponentInstances().isEmpty() || ((ComponentInstance)obj).getCategory() == ComponentCategory.PROCESS )); } }.processPreOrderComponentInstanceStop(ci); return result ; } /** * retrieve list of component instances that have composite error behavior specified * For process component instances or component instance without children, do not recurse below and do not include the component instance * @param ci ComponentInstance * @return EList of leaf component instances */ public static EList<ComponentInstance> getComponentInstancesWithhasCompositeErrorBehaviorOnly(ComponentInstance ci){ EList result = new ForAllElement(){ @Override protected boolean suchThat(Element obj) { return (obj instanceof ComponentInstance&& (EMV2Util.hasCompositeErrorBehavior((ComponentInstance)obj) )); } @Override protected boolean processStop (Element theElement) { if (suchThat((Element) theElement)) { if (theElement instanceof NamedElement){ //{ System.out.println(((NamedElement) theElement).getName());} action((Element) theElement); return true; } } if (((ComponentInstance)theElement).getCategory() == ComponentCategory.PROCESS) { return true; } else { return false; } } }.processPreOrderComponentInstanceStop(ci); return result ; } /** * returns the feature instance in the component instance that is referenced by the Error Propagation (or Containment) * @param ep * @param ci * @return */ public static FeatureInstance findFeatureInstance(ErrorPropagation ep, ComponentInstance ci){ EList<FeatureReference> frefs = ep.getFeaturerefs(); if (frefs.isEmpty()) return null; InstanceObject container = ci; for (FeatureReference featureReference : frefs) { NamedElement ne = featureReference.getFeature(); if (ne instanceof Feature){ Feature fe = (Feature)ne; FeatureInstance fi = (container instanceof ComponentInstance? ((ComponentInstance)container).findFeatureInstance(fe): ((FeatureInstance)container).findFeatureInstance(fe)); if (fi != null){ container = fi; } else { return null; } } else { return null; } } return (FeatureInstance)container; } /** * return true if error propagation points to feature instance * @param ep Error Propagation (or Containment) * @param fi Feature Instance * @return Boolean */ public static boolean isErrorPropagationOf(ErrorPropagation ep, FeatureInstance fi){ Feature fif = fi.getFeature(); if (Aadl2Util.isNull(fif)) return false; EList<FeatureReference> frefs = ep.getFeaturerefs(); if (frefs.isEmpty()) return false; for (int i = frefs.size()-1; i >0; i--) { FeatureReference fref = frefs.get(i); if (Aadl2Util.isNull(fref.getFeature())||fref.getFeature() != fi.getFeature()){ return false; } } return true; } /** * returns the last feature in the error propagation feature reference. * @param ep * @return feature */ public static Feature getFeature(ErrorPropagation ep){ EList<FeatureReference> frefs = ep.getFeaturerefs(); if (frefs.isEmpty()) return null; NamedElement res = frefs.get(frefs.size()-1).getFeature(); if (res instanceof Feature) return (Feature)res; return null; } }
false
true
public static ContainedNamedElement isErrorModelElementProperty(PropertyAssociation propertyAssociation, Element target, Element localContext,Stack<ComponentInstance> ciStack, TypeSet ts ){ if (ciStack == null) { return null; } EList<ContainedNamedElement> applies = propertyAssociation.getAppliesTos(); for (ContainedNamedElement containedNamedElement : applies) { EList<ContainmentPathElement> cpes = containedNamedElement.getContainmentPathElements(); int targetsize = (ciStack.size()+1+(localContext==null?0:1)); boolean nomatch = false; if (cpes.size() == targetsize || cpes.size()== targetsize+1){ for (int i = 0; i< ciStack.size(); i++){ if (ciStack.get(i).getSubcomponent() != cpes.get(i).getNamedElement()){ nomatch = true; break; } } if (nomatch) break; // we are past the component portion of the path NamedElement targetel = cpes.get(cpes.size()-1).getNamedElement(); // check on the last element if (targetel instanceof ErrorTypes){ // it points to an error type or type set if (ts !=null){ if (targetel instanceof ErrorType){ // we refer to a type if (!EM2TypeSetUtil.contains(ts, (ErrorType)targetel)){ break; } } else if (targetel instanceof TypeSet){ // we refer to a type if (!EM2TypeSetUtil.contains(ts, (TypeSet)targetel)){ break; } } } targetel = cpes.get(cpes.size()-2).getNamedElement(); if (targetel == target) return containedNamedElement; } else { // last element should be target element if ( target == targetel){ if (localContext != null){ // make sure the local context matches the previous element in the path NamedElement localContextme = cpes.get(cpes.size()-2).getNamedElement(); if ( localContext != localContextme){ break; } else { return containedNamedElement; } } else { return containedNamedElement; } } else { break; } } } } return null; }
public static ContainedNamedElement isErrorModelElementProperty(PropertyAssociation propertyAssociation, Element target, Element localContext,Stack<ComponentInstance> ciStack, TypeSet ts ){ if (ciStack == null) { return null; } EList<ContainedNamedElement> applies = propertyAssociation.getAppliesTos(); for (ContainedNamedElement containedNamedElement : applies) { EList<ContainmentPathElement> cpes = containedNamedElement.getContainmentPathElements(); int targetsize = (ciStack.size()+1+(localContext==null?0:1)); boolean match = true; if (cpes.size() == targetsize || cpes.size()== targetsize+1){ for (int i = 0; i< ciStack.size(); i++){ if (ciStack.get(i).getSubcomponent() != cpes.get(i).getNamedElement()){ match = false; break; } } if (match) { // we are past the component portion of the path NamedElement targetel = cpes.get(cpes.size()-1).getNamedElement(); // check on the last element boolean typematch = true; if (targetel instanceof ErrorTypes){ // it points to an error type or type set if (ts !=null){ if (targetel instanceof ErrorType){ // we refer to a type if (!EM2TypeSetUtil.contains(ts, (ErrorType)targetel)){ typematch = false; } } else if (targetel instanceof TypeSet){ // we refer to a type if (!EM2TypeSetUtil.contains(ts, (TypeSet)targetel)){ typematch = false; } } } if (typematch){ targetel = cpes.get(cpes.size()-2).getNamedElement(); if (targetel == target) return containedNamedElement; } } else { // last element should be target element if ( target == targetel){ if (localContext != null){ // make sure the local context matches the previous element in the path NamedElement localContextme = cpes.get(cpes.size()-2).getNamedElement(); if ( localContext == localContextme){ return containedNamedElement; } } else { return containedNamedElement; } } } } } } return null; }
diff --git a/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/PerChannelBookieClient.java b/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/PerChannelBookieClient.java index 05f31d72..d3fbdc67 100644 --- a/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/PerChannelBookieClient.java +++ b/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/PerChannelBookieClient.java @@ -1,932 +1,932 @@ /** * 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.bookkeeper.proto; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayDeque; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadEntryCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback; import org.apache.bookkeeper.proto.BookkeeperProtocol.AddRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.AddResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.BKPacketHeader; import org.apache.bookkeeper.proto.BookkeeperProtocol.OperationType; import org.apache.bookkeeper.proto.BookkeeperProtocol.ProtocolVersion; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.stats.ClientStatsProvider; import org.apache.bookkeeper.stats.PCBookieClientStatsLogger; import org.apache.bookkeeper.stats.PCBookieClientStatsLogger.PCBookieClientOp; import org.apache.bookkeeper.util.MathUtils; import org.apache.bookkeeper.util.OrderedSafeExecutor; import org.apache.bookkeeper.util.SafeRunnable; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.handler.codec.frame.CorruptedFrameException; import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.LengthFieldPrepender; import org.jboss.netty.handler.codec.frame.TooLongFrameException; import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder; import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder; import org.jboss.netty.handler.timeout.ReadTimeoutException; import org.jboss.netty.handler.timeout.ReadTimeoutHandler; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timer; import java.nio.channels.ClosedChannelException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.ByteString; /** * This class manages all details of connection to a particular bookie. It also * has reconnect logic if a connection to a bookie fails. * */ @ChannelPipelineCoverage("one") public class PerChannelBookieClient extends SimpleChannelHandler implements ChannelPipelineFactory { private final static Logger LOG = LoggerFactory.getLogger(PerChannelBookieClient.class); public static final int MAX_FRAME_LENGTH = 2 * 1024 * 1024; // 2M // TODO: txnId generator per bookie? public static final AtomicLong txnIdGenerator = new AtomicLong(0); private final PCBookieClientStatsLogger statsLogger; /** * Maps a completion key to a completion object that is of the respective completion type. */ private final ConcurrentMap<CompletionKey, CompletionValue> completionObjects = new ConcurrentHashMap<CompletionKey, CompletionValue>(); InetSocketAddress addr; AtomicLong totalBytesOutstanding; ClientSocketChannelFactory channelFactory; OrderedSafeExecutor executor; ScheduledExecutorService timeoutExecutor; // TODO(Aniruddha): Remove this completely or should we have a lower read timeout and a somewhat higher timeout task interval private Timer readTimeoutTimer; private volatile Queue<GenericCallback<Void>> pendingOps = new ArrayDeque<GenericCallback<Void>>(); volatile Channel channel = null; /** * This task is submitted to the scheduled executor service thread. It periodically wakes up * and errors out entries that have timed out. */ private class TimeoutTask implements Runnable { @Override public void run() { errorOutTimedOutEntries(false); } } public enum ConnectionState { DISCONNECTED, CONNECTING, CONNECTED, CLOSED }; volatile ConnectionState state; private final ClientConfiguration conf; /** * Error out any entries that have timed out. */ private void errorOutTimedOutEntries(boolean isNettyTimeout) { int numAdd = 0, numRead = 0; int total = 0; for (CompletionKey key : PerChannelBookieClient.this.completionObjects.keySet()) { total++; long elapsedTime = key.elapsedTime(); try { switch (key.operationType) { case ADD_ENTRY: if (elapsedTime < conf.getAddEntryTimeout() * 1000) { continue; } errorOutAddKey(key); numAdd++; if (isNettyTimeout) { statsLogger.getOpStatsLogger(PCBookieClientOp.NETTY_TIMEOUT_ADD_ENTRY) .registerSuccessfulEvent(elapsedTime); } else { statsLogger.getOpStatsLogger(PCBookieClientOp.TIMEOUT_ADD_ENTRY) .registerSuccessfulEvent(elapsedTime); } break; case READ_ENTRY: if (elapsedTime < conf.getReadEntryTimeout() * 1000) { continue; } errorOutReadKey(key); numRead++; if (isNettyTimeout) { statsLogger.getOpStatsLogger(PCBookieClientOp.NETTY_TIMEOUT_READ_ENTRY) .registerSuccessfulEvent(elapsedTime); } else { statsLogger.getOpStatsLogger(PCBookieClientOp.TIMEOUT_READ_ENTRY) .registerSuccessfulEvent(elapsedTime); } break; } } catch (RuntimeException e) { LOG.error("Caught RuntimeException while erroring out key " + key + " : ", e); } } if (numAdd + numRead > 0) { LOG.warn("Timeout task iterated through a total of {} keys.", total); LOG.warn("Timeout Task errored out {} add entry requests.", numAdd); LOG.warn("Timeout Task errored out {} read entry requests.", numRead); } } public PerChannelBookieClient(OrderedSafeExecutor executor, ClientSocketChannelFactory channelFactory, InetSocketAddress addr, AtomicLong totalBytesOutstanding, ScheduledExecutorService timeoutExecutor) { this(new ClientConfiguration(), executor, channelFactory, addr, totalBytesOutstanding, timeoutExecutor); } public PerChannelBookieClient(OrderedSafeExecutor executor, ClientSocketChannelFactory channelFactory, InetSocketAddress addr, AtomicLong totalBytesOutstanding) { this(new ClientConfiguration(), executor, channelFactory, addr, totalBytesOutstanding, null); } public PerChannelBookieClient(ClientConfiguration conf, OrderedSafeExecutor executor, ClientSocketChannelFactory channelFactory, InetSocketAddress addr, AtomicLong totalBytesOutstanding, ScheduledExecutorService timeoutExecutor) { this.conf = conf; this.addr = addr; this.executor = executor; this.totalBytesOutstanding = totalBytesOutstanding; this.channelFactory = channelFactory; this.state = ConnectionState.DISCONNECTED; this.readTimeoutTimer = null; this.statsLogger = ClientStatsProvider.getPCBookieStatsLoggerInstance(addr); this.timeoutExecutor = timeoutExecutor; // Schedule the timeout task if (null != this.timeoutExecutor) { this.timeoutExecutor.scheduleWithFixedDelay(new TimeoutTask(), conf.getTimeoutTaskIntervalMillis(), conf.getTimeoutTaskIntervalMillis(), TimeUnit.MILLISECONDS); } } private void connect() { LOG.debug("Connecting to bookie: {}", addr); // Set up the ClientBootStrap so we can create a new Channel connection // to the bookie. ClientBootstrap bootstrap = new ClientBootstrap(channelFactory); bootstrap.setPipelineFactory(this); bootstrap.setOption("tcpNoDelay", conf.getClientTcpNoDelay()); bootstrap.setOption("keepAlive", true); ChannelFuture future = bootstrap.connect(addr); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { int rc; Queue<GenericCallback<Void>> oldPendingOps; synchronized (PerChannelBookieClient.this) { if (future.isSuccess() && state == ConnectionState.CONNECTING) { - LOG.info("Successfully connected to bookie: {} with channel {}", addr, channel); rc = BKException.Code.OK; channel = future.getChannel(); state = ConnectionState.CONNECTED; + LOG.info("Successfully connected to bookie: {} with channel {}", addr, channel); } else if (future.isSuccess() && state == ConnectionState.CONNECTED) { LOG.info("Already connected with another channel {}, so close the new channel {}", channel, future.getChannel()); rc = BKException.Code.OK; future.getChannel().close(); assert (state == ConnectionState.CONNECTED); } else if (future.isSuccess() && (state == ConnectionState.CLOSED || state == ConnectionState.DISCONNECTED)) { LOG.error("Closed before connection completed state {}, clean up: {}", state, future.getChannel()); future.getChannel().close(); rc = BKException.Code.BookieHandleNotAvailableException; channel = null; } else { LOG.error("Could not connect to bookie: " + addr); rc = BKException.Code.BookieHandleNotAvailableException; channel = null; if (state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; } } // trick to not do operations under the lock, take the list // of pending ops and assign it to a new variable, while // emptying the pending ops by just assigning it to a new // list oldPendingOps = pendingOps; pendingOps = new ArrayDeque<GenericCallback<Void>>(); } for (GenericCallback<Void> pendingOp : oldPendingOps) { pendingOp.operationComplete(rc, null); } } }); } void connectIfNeededAndDoOp(GenericCallback<Void> op) { boolean completeOpNow = false; int opRc = BKException.Code.OK; // common case without lock first if (state == ConnectionState.CONNECTED && channel != null && channel.isConnected()) { completeOpNow = true; } else { synchronized (this) { // check the channel status again under lock if (channel != null && channel.isConnected() && state == ConnectionState.CONNECTED) { completeOpNow = true; opRc = BKException.Code.OK; } else if (state == ConnectionState.CLOSED) { completeOpNow = true; opRc = BKException.Code.BookieHandleNotAvailableException; } else { // channel is either null (first connection attempt), or the // channel is disconnected. Connection attempt is still in // progress, queue up this op. Op will be executed when // connection attempt either fails or succeeds pendingOps.add(op); if (state == ConnectionState.CONNECTING) { // just return as connection request has already send // and waiting for the response. return; } // switch state to connecting and do connection attempt state = ConnectionState.CONNECTING; } } if (!completeOpNow) { // Start connection attempt to the input server host. connect(); } } if (completeOpNow) { op.operationComplete(opRc, null); } } // In case of tear down several exceptions maybe expected and as such should not pollute the log with // warning messages. Each such explicitly white-listed exceptions would have their own return code and // can be handled without generating any noise in the log // private interface ChannelRequestCompletionCode { int OK = 0; int ChannelClosedException = -1; int UnknownError = -2; } /** * @param channel * @param request * @param cb */ private void writeRequestToChannel(final Channel channel, final Request request, final GenericCallback<Void> cb) { try { channel.write(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { if (!channelFuture.isSuccess()) { if (channelFuture.getCause() instanceof ClosedChannelException) { cb.operationComplete(ChannelRequestCompletionCode.ChannelClosedException, null); } else { LOG.warn("Writing a request:" + request + " to channel:" + channel + " failed", channelFuture.getCause()); cb.operationComplete(ChannelRequestCompletionCode.UnknownError, null); } } else { cb.operationComplete(ChannelRequestCompletionCode.OK, null); } } }); } catch (Throwable t) { LOG.warn("Writing a request:" + request + " to channel:" + channel + " failed.", t); cb.operationComplete(-1, null); } } public void addEntry(final long ledgerId, byte[] masterKey, final long entryId, ChannelBuffer toSend, WriteCallback cb, Object ctx, final int options) { final long txnId = getTxnId(); final int entrySize = toSend.readableBytes(); final CompletionKey completionKey = new CompletionKey(txnId, OperationType.ADD_ENTRY); completionObjects.put(completionKey, new AddCompletion(statsLogger, cb, ctx, ledgerId, entryId)); // Build the request and calculate the total size to be included in the packet. BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder() .setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.ADD_ENTRY) .setTxnId(txnId); AddRequest.Builder addBuilder = AddRequest.newBuilder() .setLedgerId(ledgerId) .setEntryId(entryId) .setMasterKey(ByteString.copyFrom(masterKey)) .setBody(ByteString.copyFrom(toSend.toByteBuffer())); if (((short)options & BookieProtocol.FLAG_RECOVERY_ADD) == BookieProtocol.FLAG_RECOVERY_ADD) { addBuilder.setFlag(AddRequest.Flag.RECOVERY_ADD); } final Request addRequest = Request.newBuilder() .setHeader(headerBuilder) .setAddRequest(addBuilder) .build(); writeRequestToChannel(channel, addRequest, new GenericCallback<Void>() { @Override public void operationComplete(int rc, Void result) { if (rc != 0) { if (rc == ChannelRequestCompletionCode.UnknownError) { LOG.warn("Add entry operation for ledger:" + ledgerId + " and entry:" + entryId + " failed."); } errorOutAddKey(completionKey); } else { // Success if (LOG.isDebugEnabled()) { LOG.debug("Successfully wrote request for adding entry: " + entryId + " ledger-id: " + ledgerId + " bookie: " + channel.getRemoteAddress() + " entry length: " + entrySize); } } } }); } public void readEntry(final long ledgerId, final long entryId, ReadEntryCallback cb, Object ctx) { final long txnId = getTxnId(); final CompletionKey completionKey = new CompletionKey(txnId, OperationType.READ_ENTRY); completionObjects.put(completionKey, new ReadCompletion(statsLogger, cb, ctx, ledgerId, entryId)); // Build the request and calculate the total size to be included in the packet. BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder() .setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.READ_ENTRY) .setTxnId(txnId); ReadRequest.Builder readBuilder = ReadRequest.newBuilder() .setLedgerId(ledgerId) .setEntryId(entryId); final Request readRequest = Request.newBuilder() .setHeader(headerBuilder) .setReadRequest(readBuilder) .build(); writeRequestToChannel(channel, readRequest, new GenericCallback<Void>() { @Override public void operationComplete(int rc, Void result) { if (rc != 0) { if (rc == ChannelRequestCompletionCode.UnknownError) { LOG.warn("Read entry operation for ledger:" + ledgerId + " and entry:" + entryId + " failed."); } errorOutReadKey(completionKey); } else { // Success if (LOG.isDebugEnabled()) { LOG.debug("Successfully wrote request for reading entry: " + entryId + " ledger-id: " + ledgerId + " bookie: " + channel.getRemoteAddress()); } } } }); } public void readEntryAndFenceLedger(final long ledgerId, byte[] masterKey, final long entryId, ReadEntryCallback cb, Object ctx) { final long txnId = getTxnId(); final CompletionKey completionKey = new CompletionKey(txnId, OperationType.READ_ENTRY); completionObjects.put(completionKey, new ReadCompletion(statsLogger, cb, ctx, ledgerId, entryId)); BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder() .setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.READ_ENTRY) .setTxnId(txnId); ReadRequest.Builder readBuilder = ReadRequest.newBuilder() .setLedgerId(ledgerId) .setEntryId(entryId) .setMasterKey(ByteString.copyFrom(masterKey)) .setFlag(ReadRequest.Flag.FENCE_LEDGER); final Request readRequest = Request.newBuilder() .setHeader(headerBuilder) .setReadRequest(readBuilder) .build(); writeRequestToChannel(channel, readRequest, new GenericCallback<Void>() { @Override public void operationComplete(int rc, Void result) { if (rc != 0) { if (rc == ChannelRequestCompletionCode.UnknownError) { LOG.warn("Read entry and fence operation for ledger:" + ledgerId + " and entry:" + entryId + " failed."); } errorOutReadKey(completionKey); } else { // Success if (LOG.isDebugEnabled()) { LOG.debug("Successfully wrote request to fence ledger and read entry: " + entryId + " ledger-id: " + ledgerId + " bookie: " + channel.getRemoteAddress()); } } } }); } /** * Disconnects the bookie client. It can be reused. */ public void disconnect() { LOG.info("Disconnecting the per channel bookie client for {}", addr); closeInternal(false); } /** * Closes the bookie client permanently. It cannot be reused. */ public void close() { LOG.info("Closing the per channel bookie client for {}", addr); closeInternal(true); } private void closeInternal(boolean permanent) { Channel channelToClose = null; Timer timerToStop = null; synchronized (this) { if (permanent) { state = ConnectionState.CLOSED; } else if (state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; } if (null != channel) { channelToClose = channel; timerToStop = readTimeoutTimer; readTimeoutTimer = null; } } if (null != channelToClose) { channelToClose.close().awaitUninterruptibly(); } if (null != timerToStop) { timerToStop.stop(); } } void errorOutReadKey(final CompletionKey key) { final ReadCompletion rc = (ReadCompletion)completionObjects.remove(key); if (null == rc) { return; } executor.submitOrdered(rc.ledgerId, new SafeRunnable() { @Override public void safeRun() { String bAddress = "null"; if (null != channel) { bAddress = channel.getRemoteAddress().toString(); } if (LOG.isDebugEnabled()) { LOG.debug("Could not write request for reading entry: " + rc.entryId + " ledger-id: " + rc.ledgerId + " bookie: " + bAddress); } rc.cb.readEntryComplete(BKException.Code.BookieHandleNotAvailableException, rc.ledgerId, rc.entryId, null, rc.ctx); } }); } void errorOutAddKey(final CompletionKey key) { final AddCompletion ac = (AddCompletion)completionObjects.remove(key); if (null == ac) { return; } executor.submitOrdered(ac.ledgerId, new SafeRunnable() { @Override public void safeRun() { String bAddress = "null"; if(channel != null) bAddress = channel.getRemoteAddress().toString(); if (LOG.isDebugEnabled()) { LOG.debug("Could not write request for adding entry: " + ac.entryId + " ledger-id: " + ac.ledgerId + " bookie: " + bAddress); LOG.debug("Invoked callback method: " + ac.entryId); } ac.cb.writeComplete(BKException.Code.BookieHandleNotAvailableException, ac.ledgerId, ac.entryId, addr, ac.ctx); } }); } /** * Errors out pending entries. We call this method from one thread to avoid * concurrent executions to QuorumOpMonitor (implements callbacks). It seems * simpler to call it from BookieHandle instead of calling directly from * here. */ void errorOutOutstandingEntries() { // DO NOT rewrite these using Map.Entry iterations. We want to iterate // on keys and see if we are successfully able to remove the key from // the map. Because the add and the read methods also do the same thing // in case they get a write failure on the socket. Make sure that the // callback is invoked in the thread responsible for the ledger. for (CompletionKey key : completionObjects.keySet()) { switch (key.operationType) { case ADD_ENTRY: errorOutAddKey(key); break; case READ_ENTRY: errorOutReadKey(key); break; } } } /** * In the netty pipeline, we need to split packets based on length, so we * use the {@link LengthFieldBasedFrameDecoder}. Other than that all actions * are carried out in this class, e.g., making sense of received messages, * prepending the length to outgoing packets etc. */ @Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); if (readTimeoutTimer == null) { readTimeoutTimer = new HashedWheelTimer(); } pipeline.addLast("readTimeout", new ReadTimeoutHandler(readTimeoutTimer, conf.getReadTimeout())); pipeline.addLast("lengthbasedframedecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, 0, 4, 0, 4)); pipeline.addLast("lengthprepender", new LengthFieldPrepender(4)); pipeline.addLast("protobufdecoder", new ProtobufDecoder(Response.getDefaultInstance())); pipeline.addLast("protobufencoder", new ProtobufEncoder()); pipeline.addLast("mainhandler", this); return pipeline; } /** * If our channel has disconnected, we just error out the pending entries */ @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { errorOutOutstandingEntries(); reactToDisconnectedChannel(e); // we don't want to reconnect right away. If someone sends a request to // this address, we will reconnect. } private void reactToDisconnectedChannel(ChannelStateEvent disconnectedChannelEvent) { if (null == disconnectedChannelEvent.getChannel()) { return; } LOG.info("Disconnecting channel {}", disconnectedChannelEvent.getChannel()); disconnectedChannelEvent.getChannel().close(); // If the channel being closed is the same as the current channel then mark the state as // disconnected forcing the next request to connect synchronized (this) { if (disconnectedChannelEvent.getChannel().equals(channel)) { if (state != ConnectionState.CLOSED) { LOG.info("Disconnected from bookie: {} Event {}", addr, disconnectedChannelEvent); state = ConnectionState.DISCONNECTED; } } } } /** * Called by netty when an exception happens in one of the netty threads * (mostly due to what we do in the netty threads) */ @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Throwable t = e.getCause(); if (t instanceof CorruptedFrameException || t instanceof TooLongFrameException) { LOG.error("Corrupted fram received from bookie: " + e.getChannel().getRemoteAddress()); return; } if (t instanceof ReadTimeoutException) { errorOutTimedOutEntries(true); return; } if (t instanceof IOException) { // these are thrown when a bookie fails, logging them just pollutes // the logs (the failure is logged from the listeners on the write // operation), so I'll just ignore it here. return; } LOG.error("Unexpected exception caught by bookie client channel handler", t); // Since we are a library, cant terminate App here, can we? } /** * Called by netty when a message is received on a channel */ @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (!(e.getMessage() instanceof Response)) { ctx.sendUpstream(e); return; } final Response response = (Response) e.getMessage(); final BKPacketHeader header = response.getHeader(); final CompletionValue completionValue = completionObjects.remove(newCompletionKey(header.getTxnId(), header.getOperation())); if (null == completionValue) { // Unexpected response, so log it. The txnId should have been present. if (LOG.isDebugEnabled()) { LOG.debug("Unexpected response received from bookie : " + addr + " for type : " + header.getOperation() + " and txnId : " + header.getTxnId()); } } else { long orderingKey = completionValue.ledgerId; executor.submitOrdered(orderingKey, new SafeRunnable() { @Override public void safeRun() { OperationType type = header.getOperation(); switch (type) { case ADD_ENTRY: handleAddResponse(response.getAddResponse(), completionValue); break; case READ_ENTRY: handleReadResponse(response.getReadResponse(), completionValue); break; default: LOG.error("Unexpected response, type:" + type + " received from bookie:" + addr + ", ignoring"); break; } } }); } } /** * Note : Response handler functions for different types of responses follow. One function for each type of response. */ void handleAddResponse(AddResponse response, CompletionValue completionValue) { // The completion value should always be an instance of an AddCompletion object when we reach here. AddCompletion ac = (AddCompletion)completionValue; long ledgerId = response.getLedgerId(); long entryId = response.getEntryId(); StatusCode status = response.getStatus(); if (LOG.isDebugEnabled()) { LOG.debug("Got response for add request from bookie: " + addr + " for ledger: " + ledgerId + " entry: " + entryId + " rc: " + status); } // convert to BKException code because thats what the uppper // layers expect. This is UGLY, there should just be one set of // error codes. Integer rcToRet = statusCodeToExceptionCode(status); if (null == rcToRet) { if (LOG.isDebugEnabled()) { LOG.debug("Add for ledger: " + ledgerId + ", entry: " + entryId + " failed on bookie: " + addr + " with code:" + status); } rcToRet = BKException.Code.WriteException; } ac.cb.writeComplete(rcToRet, ledgerId, entryId, addr, ac.ctx); } void handleReadResponse(ReadResponse response, CompletionValue completionValue) { // The completion value should always be an instance of a ReadCompletion object when we reach here. ReadCompletion rc = (ReadCompletion)completionValue; long ledgerId = response.getLedgerId(); long entryId = response.getEntryId(); StatusCode status = response.getStatus(); ChannelBuffer buffer = ChannelBuffers.buffer(0); if (response.hasBody()) { buffer = ChannelBuffers.copiedBuffer(response.getBody().asReadOnlyByteBuffer()); } if (LOG.isDebugEnabled()) { LOG.debug("Got response for read request from bookie: " + addr + " for ledger: " + ledgerId + " entry: " + entryId + " rc: " + rc + " entry length: " + buffer.readableBytes()); } // convert to BKException code because thats what the uppper // layers expect. This is UGLY, there should just be one set of // error codes. Integer rcToRet = statusCodeToExceptionCode(status); if (null == rcToRet) { LOG.error("Read entry for ledger:" + ledgerId + ", entry:" + entryId + " failed on bookie:" + addr + " with code:" + status); rcToRet = BKException.Code.ReadException; } rc.cb.readEntryComplete(rcToRet, ledgerId, entryId, buffer.slice(), rc.ctx); } /** * Note : All completion objects follow. There should be a completion object for each different request type. */ static abstract class CompletionValue { public final Object ctx; // The ledgerId and entryId values are passed to the callbacks in case of a timeout. // TODO: change the callback signatures to remove these. protected final long ledgerId; protected final long entryId; public CompletionValue(Object ctx, long ledgerId, long entryId) { this.ctx = ctx; this.ledgerId = ledgerId; this.entryId = entryId; } } static class ReadCompletion extends CompletionValue { final ReadEntryCallback cb; public ReadCompletion(final PCBookieClientStatsLogger statsLogger, final ReadEntryCallback originalCallback, final Object originalCtx, final long ledgerId, final long entryId) { super(originalCtx, ledgerId, entryId); final long requestTimeMillis = MathUtils.now(); this.cb = new ReadEntryCallback() { @Override public void readEntryComplete(int rc, long ledgerId, long entryId, ChannelBuffer buffer, Object ctx) { long latencyMillis = MathUtils.now() - requestTimeMillis; if (rc != BKException.Code.OK) { statsLogger.getOpStatsLogger(PCBookieClientOp.READ_ENTRY).registerFailedEvent(latencyMillis); } else { statsLogger.getOpStatsLogger(PCBookieClientOp.READ_ENTRY).registerSuccessfulEvent(latencyMillis); } originalCallback.readEntryComplete(rc, ledgerId, entryId, buffer, originalCtx); } }; } } static class AddCompletion extends CompletionValue { final WriteCallback cb; public AddCompletion(final PCBookieClientStatsLogger statsLogger, final WriteCallback originalCallback, final Object originalCtx, final long ledgerId, final long entryId) { super(originalCtx, ledgerId, entryId); final long requestTimeMillis = MathUtils.now(); this.cb = new WriteCallback() { @Override public void writeComplete(int rc, long ledgerId, long entryId, InetSocketAddress addr, Object ctx) { long latencyMillis = MathUtils.now() - requestTimeMillis; if (rc != BKException.Code.OK) { statsLogger.getOpStatsLogger(PCBookieClientOp.ADD_ENTRY).registerFailedEvent(latencyMillis); } else { statsLogger.getOpStatsLogger(PCBookieClientOp.ADD_ENTRY).registerSuccessfulEvent(latencyMillis); } originalCallback.writeComplete(rc, ledgerId, entryId, addr, originalCtx); } }; } } /** * Note : Code related to completion keys follows. */ CompletionKey newCompletionKey(long txnId, OperationType operationType) { return new CompletionKey(txnId, operationType); } class CompletionKey { public final long txnId; public final OperationType operationType; public final long requestAt; CompletionKey(long txnId, OperationType operationType) { this.txnId = txnId; this.operationType = operationType; this.requestAt = MathUtils.nowInNano(); } @Override public boolean equals(Object obj) { if (!(obj instanceof CompletionKey)) { return false; } CompletionKey that = (CompletionKey) obj; return this.txnId == that.txnId && this.operationType == that.operationType; } @Override public int hashCode() { return ((int) txnId); } @Override public String toString() { return String.format("TxnId(%d), OperationType(%s)", txnId, operationType); } public boolean shouldTimeout() { return elapsedTime() >= conf.getReadTimeout() * 1000; } public long elapsedTime() { return MathUtils.elapsedMSec(requestAt); } } /** * Note : Helper functions follow */ /** * @param status * @return null if the statuscode is unknown. */ private Integer statusCodeToExceptionCode(StatusCode status) { Integer rcToRet = null; switch (status) { case EOK: rcToRet = BKException.Code.OK; break; case ENOENTRY: case ENOLEDGER: rcToRet = BKException.Code.NoSuchEntryException; break; case EBADVERSION: rcToRet = BKException.Code.ProtocolVersionException; break; case EUA: rcToRet = BKException.Code.UnauthorizedAccessException; break; case EFENCED: rcToRet = BKException.Code.LedgerFencedException; break; } return rcToRet; } private long getTxnId() { return txnIdGenerator.incrementAndGet(); } }
false
true
private void connect() { LOG.debug("Connecting to bookie: {}", addr); // Set up the ClientBootStrap so we can create a new Channel connection // to the bookie. ClientBootstrap bootstrap = new ClientBootstrap(channelFactory); bootstrap.setPipelineFactory(this); bootstrap.setOption("tcpNoDelay", conf.getClientTcpNoDelay()); bootstrap.setOption("keepAlive", true); ChannelFuture future = bootstrap.connect(addr); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { int rc; Queue<GenericCallback<Void>> oldPendingOps; synchronized (PerChannelBookieClient.this) { if (future.isSuccess() && state == ConnectionState.CONNECTING) { LOG.info("Successfully connected to bookie: {} with channel {}", addr, channel); rc = BKException.Code.OK; channel = future.getChannel(); state = ConnectionState.CONNECTED; } else if (future.isSuccess() && state == ConnectionState.CONNECTED) { LOG.info("Already connected with another channel {}, so close the new channel {}", channel, future.getChannel()); rc = BKException.Code.OK; future.getChannel().close(); assert (state == ConnectionState.CONNECTED); } else if (future.isSuccess() && (state == ConnectionState.CLOSED || state == ConnectionState.DISCONNECTED)) { LOG.error("Closed before connection completed state {}, clean up: {}", state, future.getChannel()); future.getChannel().close(); rc = BKException.Code.BookieHandleNotAvailableException; channel = null; } else { LOG.error("Could not connect to bookie: " + addr); rc = BKException.Code.BookieHandleNotAvailableException; channel = null; if (state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; } } // trick to not do operations under the lock, take the list // of pending ops and assign it to a new variable, while // emptying the pending ops by just assigning it to a new // list oldPendingOps = pendingOps; pendingOps = new ArrayDeque<GenericCallback<Void>>(); } for (GenericCallback<Void> pendingOp : oldPendingOps) { pendingOp.operationComplete(rc, null); } } }); }
private void connect() { LOG.debug("Connecting to bookie: {}", addr); // Set up the ClientBootStrap so we can create a new Channel connection // to the bookie. ClientBootstrap bootstrap = new ClientBootstrap(channelFactory); bootstrap.setPipelineFactory(this); bootstrap.setOption("tcpNoDelay", conf.getClientTcpNoDelay()); bootstrap.setOption("keepAlive", true); ChannelFuture future = bootstrap.connect(addr); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { int rc; Queue<GenericCallback<Void>> oldPendingOps; synchronized (PerChannelBookieClient.this) { if (future.isSuccess() && state == ConnectionState.CONNECTING) { rc = BKException.Code.OK; channel = future.getChannel(); state = ConnectionState.CONNECTED; LOG.info("Successfully connected to bookie: {} with channel {}", addr, channel); } else if (future.isSuccess() && state == ConnectionState.CONNECTED) { LOG.info("Already connected with another channel {}, so close the new channel {}", channel, future.getChannel()); rc = BKException.Code.OK; future.getChannel().close(); assert (state == ConnectionState.CONNECTED); } else if (future.isSuccess() && (state == ConnectionState.CLOSED || state == ConnectionState.DISCONNECTED)) { LOG.error("Closed before connection completed state {}, clean up: {}", state, future.getChannel()); future.getChannel().close(); rc = BKException.Code.BookieHandleNotAvailableException; channel = null; } else { LOG.error("Could not connect to bookie: " + addr); rc = BKException.Code.BookieHandleNotAvailableException; channel = null; if (state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; } } // trick to not do operations under the lock, take the list // of pending ops and assign it to a new variable, while // emptying the pending ops by just assigning it to a new // list oldPendingOps = pendingOps; pendingOps = new ArrayDeque<GenericCallback<Void>>(); } for (GenericCallback<Void> pendingOp : oldPendingOps) { pendingOp.operationComplete(rc, null); } } }); }
diff --git a/src/com/android/providers/contacts/ContactAggregator.java b/src/com/android/providers/contacts/ContactAggregator.java index 88270c1..de55f93 100644 --- a/src/com/android/providers/contacts/ContactAggregator.java +++ b/src/com/android/providers/contacts/ContactAggregator.java @@ -1,1665 +1,1665 @@ /* * Copyright (C) 2009 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.providers.contacts; import com.android.providers.contacts.ContactMatcher.MatchScore; import com.android.providers.contacts.ContactsDatabaseHelper.AggregatedPresenceColumns; import com.android.providers.contacts.ContactsDatabaseHelper.ContactsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.DataColumns; import com.android.providers.contacts.ContactsDatabaseHelper.NameLookupColumns; import com.android.providers.contacts.ContactsDatabaseHelper.NameLookupType; import com.android.providers.contacts.ContactsDatabaseHelper.PhoneLookupColumns; import com.android.providers.contacts.ContactsDatabaseHelper.PresenceColumns; import com.android.providers.contacts.ContactsDatabaseHelper.RawContactsColumns; import com.android.providers.contacts.ContactsDatabaseHelper.Tables; import android.content.ContentValues; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteStatement; import android.net.Uri; import android.provider.ContactsContract.AggregationExceptions; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.DisplayNameSources; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.StatusUpdates; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Photo; import android.text.TextUtils; import android.util.EventLog; import android.util.Log; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; /** * ContactAggregator deals with aggregating contact information coming from different sources. * Two John Doe contacts from two disjoint sources are presumed to be the same * person unless the user declares otherwise. */ public class ContactAggregator { private static final String TAG = "ContactAggregator"; private static final boolean VERBOSE_LOGGING = Log.isLoggable(TAG, Log.VERBOSE); private static final String STRUCTURED_NAME_BASED_LOOKUP_SQL = NameLookupColumns.NAME_TYPE + " IN (" + NameLookupType.NAME_EXACT + "," + NameLookupType.NAME_VARIANT + "," + NameLookupType.NAME_COLLATION_KEY + ")"; // From system/core/logcat/event-log-tags // aggregator [time, count] will be logged for each aggregator cycle. // For the query (as opposed to the merge), count will be negative public static final int LOG_SYNC_CONTACTS_AGGREGATION = 2747; // If we encounter more than this many contacts with matching names, aggregate only this many private static final int PRIMARY_HIT_LIMIT = 15; private static final String PRIMARY_HIT_LIMIT_STRING = String.valueOf(PRIMARY_HIT_LIMIT); // If we encounter more than this many contacts with matching phone number or email, // don't attempt to aggregate - this is likely an error or a shared corporate data element. private static final int SECONDARY_HIT_LIMIT = 20; private static final String SECONDARY_HIT_LIMIT_STRING = String.valueOf(SECONDARY_HIT_LIMIT); // If we encounter more than this many contacts with matching name during aggregation // suggestion lookup, ignore the remaining results. private static final int FIRST_LETTER_SUGGESTION_HIT_LIMIT = 100; private final ContactsProvider2 mContactsProvider; private final ContactsDatabaseHelper mDbHelper; private boolean mEnabled = true; /** Precompiled sql statement for setting an aggregated presence */ private SQLiteStatement mAggregatedPresenceReplace; private SQLiteStatement mPresenceContactIdUpdate; private SQLiteStatement mRawContactCountQuery; private SQLiteStatement mContactDelete; private SQLiteStatement mAggregatedPresenceDelete; private SQLiteStatement mMarkForAggregation; private SQLiteStatement mPhotoIdUpdate; private SQLiteStatement mDisplayNameUpdate; private SQLiteStatement mHasPhoneNumberUpdate; private SQLiteStatement mLookupKeyUpdate; private SQLiteStatement mStarredUpdate; private SQLiteStatement mContactIdAndMarkAggregatedUpdate; private SQLiteStatement mContactIdUpdate; private SQLiteStatement mMarkAggregatedUpdate; private SQLiteStatement mContactUpdate; private SQLiteStatement mContactInsert; private HashMap<Long, Integer> mRawContactsMarkedForAggregation = new HashMap<Long, Integer>(); private String[] mSelectionArgs1 = new String[1]; private String[] mSelectionArgs2 = new String[2]; private String[] mSelectionArgs3 = new String[3]; private long mMimeTypeIdEmail; private long mMimeTypeIdPhoto; private long mMimeTypeIdPhone; private String mRawContactsQueryByRawContactId; private String mRawContactsQueryByContactId; private StringBuilder mSb = new StringBuilder(); private MatchCandidateList mCandidates = new MatchCandidateList(); private ContactMatcher mMatcher = new ContactMatcher(); private ContentValues mValues = new ContentValues(); private DisplayNameCandidate mDisplayNameCandidate = new DisplayNameCandidate(); /** * Captures a potential match for a given name. The matching algorithm * constructs a bunch of NameMatchCandidate objects for various potential matches * and then executes the search in bulk. */ private static class NameMatchCandidate { String mName; int mLookupType; public NameMatchCandidate(String name, int nameLookupType) { mName = name; mLookupType = nameLookupType; } } /** * A list of {@link NameMatchCandidate} that keeps its elements even when the list is * truncated. This is done for optimization purposes to avoid excessive object allocation. */ private static class MatchCandidateList { private final ArrayList<NameMatchCandidate> mList = new ArrayList<NameMatchCandidate>(); private int mCount; /** * Adds a {@link NameMatchCandidate} element or updates the next one if it already exists. */ public void add(String name, int nameLookupType) { if (mCount >= mList.size()) { mList.add(new NameMatchCandidate(name, nameLookupType)); } else { NameMatchCandidate candidate = mList.get(mCount); candidate.mName = name; candidate.mLookupType = nameLookupType; } mCount++; } public void clear() { mCount = 0; } } /** * A convenience class used in the algorithm that figures out which of available * display names to use for an aggregate contact. */ private static class DisplayNameCandidate { long rawContactId; String displayName; int displayNameSource; boolean verified; boolean writableAccount; public DisplayNameCandidate() { clear(); } public void clear() { rawContactId = -1; displayName = null; displayNameSource = DisplayNameSources.UNDEFINED; verified = false; writableAccount = false; } } /** * Constructor. */ public ContactAggregator(ContactsProvider2 contactsProvider, ContactsDatabaseHelper contactsDatabaseHelper) { mContactsProvider = contactsProvider; mDbHelper = contactsDatabaseHelper; SQLiteDatabase db = mDbHelper.getReadableDatabase(); // Since we have no way of determining which custom status was set last, // we'll just pick one randomly. We are using MAX as an approximation of randomness mAggregatedPresenceReplace = db.compileStatement( "INSERT OR REPLACE INTO " + Tables.AGGREGATED_PRESENCE + "(" + AggregatedPresenceColumns.CONTACT_ID + ", " + StatusUpdates.PRESENCE_STATUS + ") SELECT ?, MAX(" + StatusUpdates.PRESENCE_STATUS + ") " + " FROM " + Tables.PRESENCE + " WHERE " + PresenceColumns.CONTACT_ID + "=?"); mRawContactCountQuery = db.compileStatement( "SELECT COUNT(" + RawContacts._ID + ")" + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts.CONTACT_ID + "=?" + " AND " + RawContacts._ID + "<>?"); mContactDelete = db.compileStatement( "DELETE FROM " + Tables.CONTACTS + " WHERE " + Contacts._ID + "=?"); mAggregatedPresenceDelete = db.compileStatement( "DELETE FROM " + Tables.AGGREGATED_PRESENCE + " WHERE " + AggregatedPresenceColumns.CONTACT_ID + "=?"); mMarkForAggregation = db.compileStatement( "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContactsColumns.AGGREGATION_NEEDED + "=1" + " WHERE " + RawContacts._ID + "=?" + " AND " + RawContactsColumns.AGGREGATION_NEEDED + "=0"); mPhotoIdUpdate = db.compileStatement( "UPDATE " + Tables.CONTACTS + " SET " + Contacts.PHOTO_ID + "=? " + " WHERE " + Contacts._ID + "=?"); mDisplayNameUpdate = db.compileStatement( "UPDATE " + Tables.CONTACTS + " SET " + Contacts.NAME_RAW_CONTACT_ID + "=? " + " WHERE " + Contacts._ID + "=?"); mLookupKeyUpdate = db.compileStatement( "UPDATE " + Tables.CONTACTS + " SET " + Contacts.LOOKUP_KEY + "=? " + " WHERE " + Contacts._ID + "=?"); mHasPhoneNumberUpdate = db.compileStatement( "UPDATE " + Tables.CONTACTS + " SET " + Contacts.HAS_PHONE_NUMBER + "=" + "(SELECT (CASE WHEN COUNT(*)=0 THEN 0 ELSE 1 END)" + " FROM " + Tables.DATA_JOIN_RAW_CONTACTS + " WHERE " + DataColumns.MIMETYPE_ID + "=?" + " AND " + Phone.NUMBER + " NOT NULL" + " AND " + RawContacts.CONTACT_ID + "=?)" + " WHERE " + Contacts._ID + "=?"); mStarredUpdate = db.compileStatement("UPDATE " + Tables.CONTACTS + " SET " + Contacts.STARRED + "=(SELECT (CASE WHEN COUNT(" + RawContacts.STARRED + ")=0 THEN 0 ELSE 1 END) FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts.CONTACT_ID + "=" + ContactsColumns.CONCRETE_ID + " AND " + RawContacts.STARRED + "=1)" + " WHERE " + Contacts._ID + "=?"); mContactIdAndMarkAggregatedUpdate = db.compileStatement( "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContacts.CONTACT_ID + "=?, " + RawContactsColumns.AGGREGATION_NEEDED + "=0" + " WHERE " + RawContacts._ID + "=?"); mContactIdUpdate = db.compileStatement( "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContacts.CONTACT_ID + "=?" + " WHERE " + RawContacts._ID + "=?"); mMarkAggregatedUpdate = db.compileStatement( "UPDATE " + Tables.RAW_CONTACTS + " SET " + RawContactsColumns.AGGREGATION_NEEDED + "=0" + " WHERE " + RawContacts._ID + "=?"); mPresenceContactIdUpdate = db.compileStatement( "UPDATE " + Tables.PRESENCE + " SET " + PresenceColumns.CONTACT_ID + "=?" + " WHERE " + PresenceColumns.RAW_CONTACT_ID + "=?"); mContactUpdate = db.compileStatement(ContactReplaceSqlStatement.UPDATE_SQL); mContactInsert = db.compileStatement(ContactReplaceSqlStatement.INSERT_SQL); mMimeTypeIdEmail = mDbHelper.getMimeTypeId(Email.CONTENT_ITEM_TYPE); mMimeTypeIdPhoto = mDbHelper.getMimeTypeId(Photo.CONTENT_ITEM_TYPE); mMimeTypeIdPhone = mDbHelper.getMimeTypeId(Phone.CONTENT_ITEM_TYPE); // Query used to retrieve data from raw contacts to populate the corresponding aggregate mRawContactsQueryByRawContactId = String.format( RawContactsQuery.SQL_FORMAT_BY_RAW_CONTACT_ID, mMimeTypeIdPhoto, mMimeTypeIdPhone); mRawContactsQueryByContactId = String.format( RawContactsQuery.SQL_FORMAT_BY_CONTACT_ID, mMimeTypeIdPhoto, mMimeTypeIdPhone); } public void setEnabled(boolean enabled) { mEnabled = enabled; } public boolean isEnabled() { return mEnabled; } private interface AggregationQuery { String SQL = "SELECT " + RawContacts._ID + "," + RawContacts.CONTACT_ID + " FROM " + Tables.RAW_CONTACTS + " WHERE " + RawContacts._ID + " IN("; int _ID = 0; int CONTACT_ID = 1; } /** * Aggregate all raw contacts that were marked for aggregation in the current transaction. * Call just before committing the transaction. */ public void aggregateInTransaction(SQLiteDatabase db) { int count = mRawContactsMarkedForAggregation.size(); if (count == 0) { return; } long start = System.currentTimeMillis(); if (VERBOSE_LOGGING) { Log.v(TAG, "Contact aggregation: " + count); } EventLog.writeEvent(LOG_SYNC_CONTACTS_AGGREGATION, start, -count); String selectionArgs[] = new String[count]; int index = 0; mSb.setLength(0); mSb.append(AggregationQuery.SQL); for (long rawContactId : mRawContactsMarkedForAggregation.keySet()) { if (index > 0) { mSb.append(','); } mSb.append('?'); selectionArgs[index++] = String.valueOf(rawContactId); } mSb.append(')'); long rawContactIds[] = new long[count]; long contactIds[] = new long[count]; Cursor c = db.rawQuery(mSb.toString(), selectionArgs); try { count = c.getCount(); index = 0; while (c.moveToNext()) { rawContactIds[index] = c.getLong(AggregationQuery._ID); contactIds[index] = c.getLong(AggregationQuery.CONTACT_ID); index++; } } finally { c.close(); } for (int i = 0; i < count; i++) { aggregateContact(db, rawContactIds[i], contactIds[i], mCandidates, mMatcher, mValues); } long elapsedTime = System.currentTimeMillis() - start; EventLog.writeEvent(LOG_SYNC_CONTACTS_AGGREGATION, elapsedTime, count); if (VERBOSE_LOGGING) { String performance = count == 0 ? "" : ", " + (elapsedTime / count) + " ms per contact"; Log.i(TAG, "Contact aggregation complete: " + count + performance); } } public void clearPendingAggregations() { mRawContactsMarkedForAggregation.clear(); } public void markNewForAggregation(long rawContactId, int aggregationMode) { mRawContactsMarkedForAggregation.put(rawContactId, aggregationMode); } public void markForAggregation(long rawContactId, int aggregationMode) { if (mRawContactsMarkedForAggregation.containsKey(rawContactId)) { // As per ContactsContract documentation, default aggregation mode // does not override a previously set mode if (aggregationMode == RawContacts.AGGREGATION_MODE_DEFAULT) { aggregationMode = mRawContactsMarkedForAggregation.get(rawContactId); } } else { mMarkForAggregation.bindLong(1, rawContactId); mMarkForAggregation.execute(); } mRawContactsMarkedForAggregation.put(rawContactId, aggregationMode); } /** * Creates a new contact based on the given raw contact. Does not perform aggregation. */ public void onRawContactInsert(SQLiteDatabase db, long rawContactId) { mSelectionArgs1[0] = String.valueOf(rawContactId); computeAggregateData(db, mRawContactsQueryByRawContactId, mSelectionArgs1, mContactInsert); long contactId = mContactInsert.executeInsert(); setContactId(rawContactId, contactId); mDbHelper.updateContactVisible(contactId); } /** * Synchronously aggregate the specified contact assuming an open transaction. */ public void aggregateContact(SQLiteDatabase db, long rawContactId, long currentContactId) { if (!mEnabled) { return; } MatchCandidateList candidates = new MatchCandidateList(); ContactMatcher matcher = new ContactMatcher(); ContentValues values = new ContentValues(); aggregateContact(db, rawContactId, currentContactId, candidates, matcher, values); } public void updateAggregateData(long contactId) { if (!mEnabled) { return; } final SQLiteDatabase db = mDbHelper.getWritableDatabase(); computeAggregateData(db, contactId, mContactUpdate); mContactUpdate.bindLong(ContactReplaceSqlStatement.CONTACT_ID, contactId); mContactUpdate.execute(); mDbHelper.updateContactVisible(contactId); updateAggregatedPresence(contactId); } private void updateAggregatedPresence(long contactId) { mAggregatedPresenceReplace.bindLong(1, contactId); mAggregatedPresenceReplace.bindLong(2, contactId); mAggregatedPresenceReplace.execute(); } /** * Given a specific raw contact, finds all matching aggregate contacts and chooses the one * with the highest match score. If no such contact is found, creates a new contact. */ private synchronized void aggregateContact(SQLiteDatabase db, long rawContactId, long currentContactId, MatchCandidateList candidates, ContactMatcher matcher, ContentValues values) { int aggregationMode = RawContacts.AGGREGATION_MODE_DEFAULT; Integer aggModeObject = mRawContactsMarkedForAggregation.remove(rawContactId); if (aggModeObject != null) { aggregationMode = aggModeObject; } long contactId = -1; if (aggregationMode == RawContacts.AGGREGATION_MODE_DEFAULT) { candidates.clear(); matcher.clear(); contactId = pickBestMatchBasedOnExceptions(db, rawContactId, matcher); if (contactId == -1) { contactId = pickBestMatchBasedOnData(db, rawContactId, candidates, matcher); } } else if (aggregationMode == RawContacts.AGGREGATION_MODE_DISABLED) { return; } long currentContactContentsCount = 0; if (currentContactId != 0) { mRawContactCountQuery.bindLong(1, currentContactId); mRawContactCountQuery.bindLong(2, rawContactId); currentContactContentsCount = mRawContactCountQuery.simpleQueryForLong(); } // If there are no other raw contacts in the current aggregate, we might as well reuse it. // Also, if the aggregation mode is SUSPENDED, we must reuse the same aggregate. if (contactId == -1 && currentContactId != 0 && (currentContactContentsCount == 0 || aggregationMode == RawContacts.AGGREGATION_MODE_SUSPENDED)) { contactId = currentContactId; } if (contactId == currentContactId) { // Aggregation unchanged markAggregated(rawContactId); } else if (contactId == -1) { // Splitting an aggregate mSelectionArgs1[0] = String.valueOf(rawContactId); computeAggregateData(db, mRawContactsQueryByRawContactId, mSelectionArgs1, mContactInsert); contactId = mContactInsert.executeInsert(); setContactIdAndMarkAggregated(rawContactId, contactId); mDbHelper.updateContactVisible(contactId); setPresenceContactId(rawContactId, contactId); updateAggregatedPresence(contactId); if (currentContactContentsCount > 0) { updateAggregateData(currentContactId); } } else { // Joining with an existing aggregate if (currentContactContentsCount == 0) { // Delete a previous aggregate if it only contained this raw contact mContactDelete.bindLong(1, currentContactId); mContactDelete.execute(); mAggregatedPresenceDelete.bindLong(1, currentContactId); mAggregatedPresenceDelete.execute(); } setContactIdAndMarkAggregated(rawContactId, contactId); computeAggregateData(db, contactId, mContactUpdate); mContactUpdate.bindLong(ContactReplaceSqlStatement.CONTACT_ID, contactId); mContactUpdate.execute(); mDbHelper.updateContactVisible(contactId); updateAggregatedPresence(contactId); } } /** * Updates the contact ID for the specified contact. */ private void setContactId(long rawContactId, long contactId) { mContactIdUpdate.bindLong(1, contactId); mContactIdUpdate.bindLong(2, rawContactId); mContactIdUpdate.execute(); } /** * Marks the specified raw contact ID as aggregated */ private void markAggregated(long rawContactId) { mMarkAggregatedUpdate.bindLong(1, rawContactId); mMarkAggregatedUpdate.execute(); } /** * Updates the contact ID for the specified contact and marks the raw contact as aggregated. */ private void setContactIdAndMarkAggregated(long rawContactId, long contactId) { mContactIdAndMarkAggregatedUpdate.bindLong(1, contactId); mContactIdAndMarkAggregatedUpdate.bindLong(2, rawContactId); mContactIdAndMarkAggregatedUpdate.execute(); } private void setPresenceContactId(long rawContactId, long contactId) { mPresenceContactIdUpdate.bindLong(1, contactId); mPresenceContactIdUpdate.bindLong(2, rawContactId); mPresenceContactIdUpdate.execute(); } interface AggregateExceptionPrefetchQuery { String TABLE = Tables.AGGREGATION_EXCEPTIONS; String[] COLUMNS = { AggregationExceptions.RAW_CONTACT_ID1, AggregationExceptions.RAW_CONTACT_ID2, }; int RAW_CONTACT_ID1 = 0; int RAW_CONTACT_ID2 = 1; } // A set of raw contact IDs for which there are aggregation exceptions private final HashSet<Long> mAggregationExceptionIds = new HashSet<Long>(); private boolean mAggregationExceptionIdsValid; public void invalidateAggregationExceptionCache() { mAggregationExceptionIdsValid = false; } /** * Finds all raw contact IDs for which there are aggregation exceptions. The list of * ids is used as an optimization in aggregation: there is no point to run a query against * the agg_exceptions table if it is known that there are no records there for a given * raw contact ID. */ private void prefetchAggregationExceptionIds(SQLiteDatabase db) { mAggregationExceptionIds.clear(); final Cursor c = db.query(AggregateExceptionPrefetchQuery.TABLE, AggregateExceptionPrefetchQuery.COLUMNS, null, null, null, null, null); try { while (c.moveToNext()) { long rawContactId1 = c.getLong(AggregateExceptionPrefetchQuery.RAW_CONTACT_ID1); long rawContactId2 = c.getLong(AggregateExceptionPrefetchQuery.RAW_CONTACT_ID2); mAggregationExceptionIds.add(rawContactId1); mAggregationExceptionIds.add(rawContactId2); } } finally { c.close(); } mAggregationExceptionIdsValid = true; } interface AggregateExceptionQuery { String TABLE = Tables.AGGREGATION_EXCEPTIONS + " JOIN raw_contacts raw_contacts1 " + " ON (agg_exceptions.raw_contact_id1 = raw_contacts1._id) " + " JOIN raw_contacts raw_contacts2 " + " ON (agg_exceptions.raw_contact_id2 = raw_contacts2._id) "; String[] COLUMNS = { AggregationExceptions.TYPE, AggregationExceptions.RAW_CONTACT_ID1, "raw_contacts1." + RawContacts.CONTACT_ID, "raw_contacts1." + RawContactsColumns.AGGREGATION_NEEDED, "raw_contacts2." + RawContacts.CONTACT_ID, "raw_contacts2." + RawContactsColumns.AGGREGATION_NEEDED, }; int TYPE = 0; int RAW_CONTACT_ID1 = 1; int CONTACT_ID1 = 2; int AGGREGATION_NEEDED_1 = 3; int CONTACT_ID2 = 4; int AGGREGATION_NEEDED_2 = 5; } /** * Computes match scores based on exceptions entered by the user: always match and never match. * Returns the aggregate contact with the always match exception if any. */ private long pickBestMatchBasedOnExceptions(SQLiteDatabase db, long rawContactId, ContactMatcher matcher) { if (!mAggregationExceptionIdsValid) { prefetchAggregationExceptionIds(db); } // If there are no aggregation exceptions involving this raw contact, there is no need to // run a query and we can just return -1, which stands for "nothing found" if (!mAggregationExceptionIds.contains(rawContactId)) { return -1; } final Cursor c = db.query(AggregateExceptionQuery.TABLE, AggregateExceptionQuery.COLUMNS, AggregationExceptions.RAW_CONTACT_ID1 + "=" + rawContactId + " OR " + AggregationExceptions.RAW_CONTACT_ID2 + "=" + rawContactId, null, null, null, null); try { while (c.moveToNext()) { int type = c.getInt(AggregateExceptionQuery.TYPE); long rawContactId1 = c.getLong(AggregateExceptionQuery.RAW_CONTACT_ID1); long contactId = -1; if (rawContactId == rawContactId1) { if (c.getInt(AggregateExceptionQuery.AGGREGATION_NEEDED_2) == 0 && !c.isNull(AggregateExceptionQuery.CONTACT_ID2)) { contactId = c.getLong(AggregateExceptionQuery.CONTACT_ID2); } } else { if (c.getInt(AggregateExceptionQuery.AGGREGATION_NEEDED_1) == 0 && !c.isNull(AggregateExceptionQuery.CONTACT_ID1)) { contactId = c.getLong(AggregateExceptionQuery.CONTACT_ID1); } } if (contactId != -1) { if (type == AggregationExceptions.TYPE_KEEP_TOGETHER) { matcher.keepIn(contactId); } else { matcher.keepOut(contactId); } } } } finally { c.close(); } return matcher.pickBestMatch(ContactMatcher.MAX_SCORE); } /** * Picks the best matching contact based on matches between data elements. It considers * name match to be primary and phone, email etc matches to be secondary. A good primary * match triggers aggregation, while a good secondary match only triggers aggregation in * the absence of a strong primary mismatch. * <p> * Consider these examples: * <p> * John Doe with phone number 111-111-1111 and Jon Doe with phone number 111-111-1111 should * be aggregated (same number, similar names). * <p> * John Doe with phone number 111-111-1111 and Deborah Doe with phone number 111-111-1111 should * not be aggregated (same number, different names). */ private long pickBestMatchBasedOnData(SQLiteDatabase db, long rawContactId, MatchCandidateList candidates, ContactMatcher matcher) { // Find good matches based on name alone long bestMatch = updateMatchScoresBasedOnDataMatches(db, rawContactId, candidates, matcher); if (bestMatch == -1) { // We haven't found a good match on name, see if we have any matches on phone, email etc bestMatch = pickBestMatchBasedOnSecondaryData(db, rawContactId, candidates, matcher); } return bestMatch; } /** * Picks the best matching contact based on secondary data matches. The method loads * structured names for all candidate contacts and recomputes match scores using approximate * matching. */ private long pickBestMatchBasedOnSecondaryData(SQLiteDatabase db, long rawContactId, MatchCandidateList candidates, ContactMatcher matcher) { List<Long> secondaryContactIds = matcher.prepareSecondaryMatchCandidates( ContactMatcher.SCORE_THRESHOLD_PRIMARY); if (secondaryContactIds == null || secondaryContactIds.size() > SECONDARY_HIT_LIMIT) { return -1; } loadNameMatchCandidates(db, rawContactId, candidates, true); mSb.setLength(0); mSb.append(RawContacts.CONTACT_ID).append(" IN ("); for (int i = 0; i < secondaryContactIds.size(); i++) { if (i != 0) { mSb.append(','); } mSb.append(secondaryContactIds.get(i)); } // We only want to compare structured names to structured names // at this stage, we need to ignore all other sources of name lookup data. mSb.append(") AND " + STRUCTURED_NAME_BASED_LOOKUP_SQL); matchAllCandidates(db, mSb.toString(), candidates, matcher, ContactMatcher.MATCHING_ALGORITHM_CONSERVATIVE, null); return matcher.pickBestMatch(ContactMatcher.SCORE_THRESHOLD_SECONDARY); } private interface NameLookupQuery { String TABLE = Tables.NAME_LOOKUP; String SELECTION = NameLookupColumns.RAW_CONTACT_ID + "=?"; String SELECTION_STRUCTURED_NAME_BASED = SELECTION + " AND " + STRUCTURED_NAME_BASED_LOOKUP_SQL; String[] COLUMNS = new String[] { NameLookupColumns.NORMALIZED_NAME, NameLookupColumns.NAME_TYPE }; int NORMALIZED_NAME = 0; int NAME_TYPE = 1; } private void loadNameMatchCandidates(SQLiteDatabase db, long rawContactId, MatchCandidateList candidates, boolean structuredNameBased) { candidates.clear(); mSelectionArgs1[0] = String.valueOf(rawContactId); Cursor c = db.query(NameLookupQuery.TABLE, NameLookupQuery.COLUMNS, structuredNameBased ? NameLookupQuery.SELECTION_STRUCTURED_NAME_BASED : NameLookupQuery.SELECTION, mSelectionArgs1, null, null, null); try { while (c.moveToNext()) { String normalizedName = c.getString(NameLookupQuery.NORMALIZED_NAME); int type = c.getInt(NameLookupQuery.NAME_TYPE); candidates.add(normalizedName, type); } } finally { c.close(); } } /** * Computes scores for contacts that have matching data rows. */ private long updateMatchScoresBasedOnDataMatches(SQLiteDatabase db, long rawContactId, MatchCandidateList candidates, ContactMatcher matcher) { updateMatchScoresBasedOnNameMatches(db, rawContactId, matcher); long bestMatch = matcher.pickBestMatch(ContactMatcher.SCORE_THRESHOLD_PRIMARY); if (bestMatch != -1) { return bestMatch; } updateMatchScoresBasedOnEmailMatches(db, rawContactId, matcher); updateMatchScoresBasedOnPhoneMatches(db, rawContactId, matcher); return -1; } private interface NameLookupMatchQuery { String TABLE = Tables.NAME_LOOKUP + " nameA" + " JOIN " + Tables.NAME_LOOKUP + " nameB" + " ON (" + "nameA." + NameLookupColumns.NORMALIZED_NAME + "=" + "nameB." + NameLookupColumns.NORMALIZED_NAME + ")" + " JOIN " + Tables.RAW_CONTACTS + " ON (nameB." + NameLookupColumns.RAW_CONTACT_ID + " = " + Tables.RAW_CONTACTS + "." + RawContacts._ID + ")"; String SELECTION = "nameA." + NameLookupColumns.RAW_CONTACT_ID + "=?" + " AND " + RawContactsColumns.AGGREGATION_NEEDED + "=0"; String[] COLUMNS = new String[] { RawContacts.CONTACT_ID, "nameA." + NameLookupColumns.NORMALIZED_NAME, "nameA." + NameLookupColumns.NAME_TYPE, "nameB." + NameLookupColumns.NAME_TYPE, }; int CONTACT_ID = 0; int NAME = 1; int NAME_TYPE_A = 2; int NAME_TYPE_B = 3; } private void updateMatchScoresBasedOnNameMatches(SQLiteDatabase db, long rawContactId, ContactMatcher matcher) { mSelectionArgs1[0] = String.valueOf(rawContactId); Cursor c = db.query(NameLookupMatchQuery.TABLE, NameLookupMatchQuery.COLUMNS, NameLookupMatchQuery.SELECTION, mSelectionArgs1, null, null, null, PRIMARY_HIT_LIMIT_STRING); try { while (c.moveToNext()) { long contactId = c.getLong(NameLookupMatchQuery.CONTACT_ID); String name = c.getString(NameLookupMatchQuery.NAME); int nameTypeA = c.getInt(NameLookupMatchQuery.NAME_TYPE_A); int nameTypeB = c.getInt(NameLookupMatchQuery.NAME_TYPE_B); matcher.matchName(contactId, nameTypeA, name, nameTypeB, name, ContactMatcher.MATCHING_ALGORITHM_EXACT); if (nameTypeA == NameLookupType.NICKNAME && nameTypeB == NameLookupType.NICKNAME) { matcher.updateScoreWithNicknameMatch(contactId); } } } finally { c.close(); } } private interface EmailLookupQuery { String TABLE = Tables.DATA + " dataA" + " JOIN " + Tables.DATA + " dataB" + " ON (" + "dataA." + Email.DATA + "=dataB." + Email.DATA + ")" + " JOIN " + Tables.RAW_CONTACTS + " ON (dataB." + Data.RAW_CONTACT_ID + " = " + Tables.RAW_CONTACTS + "." + RawContacts._ID + ")"; String SELECTION = "dataA." + Data.RAW_CONTACT_ID + "=?" + " AND dataA." + DataColumns.MIMETYPE_ID + "=?" + " AND dataA." + Email.DATA + " NOT NULL" + " AND dataB." + DataColumns.MIMETYPE_ID + "=?" + " AND " + RawContactsColumns.AGGREGATION_NEEDED + "=0"; String[] COLUMNS = new String[] { RawContacts.CONTACT_ID }; int CONTACT_ID = 0; } private void updateMatchScoresBasedOnEmailMatches(SQLiteDatabase db, long rawContactId, ContactMatcher matcher) { mSelectionArgs3[0] = String.valueOf(rawContactId); mSelectionArgs3[1] = mSelectionArgs3[2] = String.valueOf(mMimeTypeIdEmail); Cursor c = db.query(EmailLookupQuery.TABLE, EmailLookupQuery.COLUMNS, EmailLookupQuery.SELECTION, mSelectionArgs3, null, null, null, SECONDARY_HIT_LIMIT_STRING); try { while (c.moveToNext()) { long contactId = c.getLong(EmailLookupQuery.CONTACT_ID); matcher.updateScoreWithEmailMatch(contactId); } } finally { c.close(); } } private interface PhoneLookupQuery { String TABLE = Tables.PHONE_LOOKUP + " phoneA" + " JOIN " + Tables.DATA + " dataA" + " ON (dataA." + Data._ID + "=phoneA." + PhoneLookupColumns.DATA_ID + ")" + " JOIN " + Tables.PHONE_LOOKUP + " phoneB" + " ON (phoneA." + PhoneLookupColumns.MIN_MATCH + "=" + "phoneB." + PhoneLookupColumns.MIN_MATCH + ")" + " JOIN " + Tables.DATA + " dataB" + " ON (dataB." + Data._ID + "=phoneB." + PhoneLookupColumns.DATA_ID + ")" + " JOIN " + Tables.RAW_CONTACTS + " ON (dataB." + Data.RAW_CONTACT_ID + " = " + Tables.RAW_CONTACTS + "." + RawContacts._ID + ")"; String SELECTION = "dataA." + Data.RAW_CONTACT_ID + "=?" + " AND PHONE_NUMBERS_EQUAL(dataA." + Phone.NUMBER + ", " + "dataB." + Phone.NUMBER + ",?)" + " AND " + RawContactsColumns.AGGREGATION_NEEDED + "=0"; String[] COLUMNS = new String[] { RawContacts.CONTACT_ID }; int CONTACT_ID = 0; } private void updateMatchScoresBasedOnPhoneMatches(SQLiteDatabase db, long rawContactId, ContactMatcher matcher) { mSelectionArgs2[0] = String.valueOf(rawContactId); mSelectionArgs2[1] = mDbHelper.getUseStrictPhoneNumberComparisonParameter(); Cursor c = db.query(PhoneLookupQuery.TABLE, PhoneLookupQuery.COLUMNS, PhoneLookupQuery.SELECTION, mSelectionArgs2, null, null, null, SECONDARY_HIT_LIMIT_STRING); try { while (c.moveToNext()) { long contactId = c.getLong(PhoneLookupQuery.CONTACT_ID); matcher.updateScoreWithPhoneNumberMatch(contactId); } } finally { c.close(); } } /** * Loads name lookup rows for approximate name matching and updates match scores based on that * data. */ private void lookupApproximateNameMatches(SQLiteDatabase db, MatchCandidateList candidates, ContactMatcher matcher) { HashSet<String> firstLetters = new HashSet<String>(); for (int i = 0; i < candidates.mCount; i++) { final NameMatchCandidate candidate = candidates.mList.get(i); if (candidate.mName.length() >= 2) { String firstLetter = candidate.mName.substring(0, 2); if (!firstLetters.contains(firstLetter)) { firstLetters.add(firstLetter); final String selection = "(" + NameLookupColumns.NORMALIZED_NAME + " GLOB '" + firstLetter + "*') AND " + NameLookupColumns.NAME_TYPE + " IN(" + NameLookupType.NAME_COLLATION_KEY + "," + NameLookupType.EMAIL_BASED_NICKNAME + "," + NameLookupType.NICKNAME + ")"; matchAllCandidates(db, selection, candidates, matcher, ContactMatcher.MATCHING_ALGORITHM_APPROXIMATE, String.valueOf(FIRST_LETTER_SUGGESTION_HIT_LIMIT)); } } } } private interface ContactNameLookupQuery { String TABLE = Tables.NAME_LOOKUP_JOIN_RAW_CONTACTS; String[] COLUMNS = new String[] { RawContacts.CONTACT_ID, NameLookupColumns.NORMALIZED_NAME, NameLookupColumns.NAME_TYPE }; int CONTACT_ID = 0; int NORMALIZED_NAME = 1; int NAME_TYPE = 2; } /** * Loads all candidate rows from the name lookup table and updates match scores based * on that data. */ private void matchAllCandidates(SQLiteDatabase db, String selection, MatchCandidateList candidates, ContactMatcher matcher, int algorithm, String limit) { final Cursor c = db.query(ContactNameLookupQuery.TABLE, ContactNameLookupQuery.COLUMNS, selection, null, null, null, null, limit); try { while (c.moveToNext()) { Long contactId = c.getLong(ContactNameLookupQuery.CONTACT_ID); String name = c.getString(ContactNameLookupQuery.NORMALIZED_NAME); int nameType = c.getInt(ContactNameLookupQuery.NAME_TYPE); // Note the N^2 complexity of the following fragment. This is not a huge concern // since the number of candidates is very small and in general secondary hits // in the absence of primary hits are rare. for (int i = 0; i < candidates.mCount; i++) { NameMatchCandidate candidate = candidates.mList.get(i); matcher.matchName(contactId, candidate.mLookupType, candidate.mName, nameType, name, algorithm); } } } finally { c.close(); } } private interface RawContactsQuery { String SQL_FORMAT = "SELECT " + RawContactsColumns.CONCRETE_ID + "," + RawContactsColumns.DISPLAY_NAME + "," + RawContactsColumns.DISPLAY_NAME_SOURCE + "," + RawContacts.ACCOUNT_TYPE + "," + RawContacts.ACCOUNT_NAME + "," + RawContacts.SOURCE_ID + "," + RawContacts.CUSTOM_RINGTONE + "," + RawContacts.SEND_TO_VOICEMAIL + "," + RawContacts.LAST_TIME_CONTACTED + "," + RawContacts.TIMES_CONTACTED + "," + RawContacts.STARRED + "," + RawContacts.IS_RESTRICTED + "," + RawContacts.NAME_VERIFIED + "," + DataColumns.CONCRETE_ID + "," + DataColumns.CONCRETE_MIMETYPE_ID + "," + Data.IS_SUPER_PRIMARY + " FROM " + Tables.RAW_CONTACTS + " LEFT OUTER JOIN " + Tables.DATA + " ON (" + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + " AND ((" + DataColumns.MIMETYPE_ID + "=%d" + " AND " + Photo.PHOTO + " NOT NULL)" + " OR (" + DataColumns.MIMETYPE_ID + "=%d" + " AND " + Phone.NUMBER + " NOT NULL)))"; String SQL_FORMAT_BY_RAW_CONTACT_ID = SQL_FORMAT + " WHERE " + RawContactsColumns.CONCRETE_ID + "=?"; String SQL_FORMAT_BY_CONTACT_ID = SQL_FORMAT + " WHERE " + RawContacts.CONTACT_ID + "=?" + " AND " + RawContacts.DELETED + "=0"; int RAW_CONTACT_ID = 0; int DISPLAY_NAME = 1; int DISPLAY_NAME_SOURCE = 2; int ACCOUNT_TYPE = 3; int ACCOUNT_NAME = 4; int SOURCE_ID = 5; int CUSTOM_RINGTONE = 6; int SEND_TO_VOICEMAIL = 7; int LAST_TIME_CONTACTED = 8; int TIMES_CONTACTED = 9; int STARRED = 10; int IS_RESTRICTED = 11; int NAME_VERIFIED = 12; int DATA_ID = 13; int MIMETYPE_ID = 14; int IS_SUPER_PRIMARY = 15; } private interface ContactReplaceSqlStatement { String UPDATE_SQL = "UPDATE " + Tables.CONTACTS + " SET " + Contacts.NAME_RAW_CONTACT_ID + "=?, " + Contacts.PHOTO_ID + "=?, " + Contacts.SEND_TO_VOICEMAIL + "=?, " + Contacts.CUSTOM_RINGTONE + "=?, " + Contacts.LAST_TIME_CONTACTED + "=?, " + Contacts.TIMES_CONTACTED + "=?, " + Contacts.STARRED + "=?, " + Contacts.HAS_PHONE_NUMBER + "=?, " + ContactsColumns.SINGLE_IS_RESTRICTED + "=?, " + Contacts.LOOKUP_KEY + "=? " + " WHERE " + Contacts._ID + "=?"; String INSERT_SQL = "INSERT INTO " + Tables.CONTACTS + " (" + Contacts.NAME_RAW_CONTACT_ID + ", " + Contacts.PHOTO_ID + ", " + Contacts.SEND_TO_VOICEMAIL + ", " + Contacts.CUSTOM_RINGTONE + ", " + Contacts.LAST_TIME_CONTACTED + ", " + Contacts.TIMES_CONTACTED + ", " + Contacts.STARRED + ", " + Contacts.HAS_PHONE_NUMBER + ", " + ContactsColumns.SINGLE_IS_RESTRICTED + ", " + Contacts.LOOKUP_KEY + ", " + Contacts.IN_VISIBLE_GROUP + ") " + " VALUES (?,?,?,?,?,?,?,?,?,?,0)"; int NAME_RAW_CONTACT_ID = 1; int PHOTO_ID = 2; int SEND_TO_VOICEMAIL = 3; int CUSTOM_RINGTONE = 4; int LAST_TIME_CONTACTED = 5; int TIMES_CONTACTED = 6; int STARRED = 7; int HAS_PHONE_NUMBER = 8; int SINGLE_IS_RESTRICTED = 9; int LOOKUP_KEY = 10; int CONTACT_ID = 11; } /** * Computes aggregate-level data for the specified aggregate contact ID. */ private void computeAggregateData(SQLiteDatabase db, long contactId, SQLiteStatement statement) { mSelectionArgs1[0] = String.valueOf(contactId); computeAggregateData(db, mRawContactsQueryByContactId, mSelectionArgs1, statement); } /** * Computes aggregate-level data from constituent raw contacts. */ private void computeAggregateData(final SQLiteDatabase db, String sql, String[] sqlArgs, SQLiteStatement statement) { long currentRawContactId = -1; long bestPhotoId = -1; boolean foundSuperPrimaryPhoto = false; String photoAccount = null; int totalRowCount = 0; int contactSendToVoicemail = 0; String contactCustomRingtone = null; long contactLastTimeContacted = 0; int contactTimesContacted = 0; int contactStarred = 0; int singleIsRestricted = 1; int hasPhoneNumber = 0; mDisplayNameCandidate.clear(); mSb.setLength(0); // Lookup key Cursor c = db.rawQuery(sql, sqlArgs); try { while (c.moveToNext()) { long rawContactId = c.getLong(RawContactsQuery.RAW_CONTACT_ID); if (rawContactId != currentRawContactId) { currentRawContactId = rawContactId; totalRowCount++; // Display name String displayName = c.getString(RawContactsQuery.DISPLAY_NAME); int displayNameSource = c.getInt(RawContactsQuery.DISPLAY_NAME_SOURCE); int nameVerified = c.getInt(RawContactsQuery.NAME_VERIFIED); String accountType = c.getString(RawContactsQuery.ACCOUNT_TYPE); processDisplayNameCanditate(rawContactId, displayName, displayNameSource, mContactsProvider.isWritableAccount(accountType), nameVerified != 0); // Contact options if (!c.isNull(RawContactsQuery.SEND_TO_VOICEMAIL)) { boolean sendToVoicemail = (c.getInt(RawContactsQuery.SEND_TO_VOICEMAIL) != 0); if (sendToVoicemail) { contactSendToVoicemail++; } } if (contactCustomRingtone == null && !c.isNull(RawContactsQuery.CUSTOM_RINGTONE)) { contactCustomRingtone = c.getString(RawContactsQuery.CUSTOM_RINGTONE); } long lastTimeContacted = c.getLong(RawContactsQuery.LAST_TIME_CONTACTED); if (lastTimeContacted > contactLastTimeContacted) { contactLastTimeContacted = lastTimeContacted; } int timesContacted = c.getInt(RawContactsQuery.TIMES_CONTACTED); if (timesContacted > contactTimesContacted) { contactTimesContacted = timesContacted; } if (c.getInt(RawContactsQuery.STARRED) != 0) { contactStarred = 1; } // Single restricted if (totalRowCount > 1) { // Not single singleIsRestricted = 0; } else { int isRestricted = c.getInt(RawContactsQuery.IS_RESTRICTED); if (isRestricted == 0) { // Not restricted singleIsRestricted = 0; } } ContactLookupKey.appendToLookupKey(mSb, c.getString(RawContactsQuery.ACCOUNT_TYPE), c.getString(RawContactsQuery.ACCOUNT_NAME), rawContactId, c.getString(RawContactsQuery.SOURCE_ID), displayName); } if (!c.isNull(RawContactsQuery.DATA_ID)) { long dataId = c.getLong(RawContactsQuery.DATA_ID); int mimetypeId = c.getInt(RawContactsQuery.MIMETYPE_ID); boolean superprimary = c.getInt(RawContactsQuery.IS_SUPER_PRIMARY) != 0; if (mimetypeId == mMimeTypeIdPhoto) { // For now, just choose the first photo in a list sorted by account name. String account = c.getString(RawContactsQuery.ACCOUNT_NAME); - if (!foundSuperPrimaryPhoto - && (superprimary - || photoAccount == null - || photoAccount.compareToIgnoreCase(account) >= 0)) { + if (!foundSuperPrimaryPhoto && ( + superprimary || photoAccount == null || + (account != null && + photoAccount.compareToIgnoreCase(account) >= 0))) { photoAccount = account; bestPhotoId = dataId; foundSuperPrimaryPhoto |= superprimary; } } else if (mimetypeId == mMimeTypeIdPhone) { hasPhoneNumber = 1; } } } } finally { c.close(); } statement.bindLong(ContactReplaceSqlStatement.NAME_RAW_CONTACT_ID, mDisplayNameCandidate.rawContactId); if (bestPhotoId != -1) { statement.bindLong(ContactReplaceSqlStatement.PHOTO_ID, bestPhotoId); } else { statement.bindNull(ContactReplaceSqlStatement.PHOTO_ID); } statement.bindLong(ContactReplaceSqlStatement.SEND_TO_VOICEMAIL, totalRowCount == contactSendToVoicemail ? 1 : 0); DatabaseUtils.bindObjectToProgram(statement, ContactReplaceSqlStatement.CUSTOM_RINGTONE, contactCustomRingtone); statement.bindLong(ContactReplaceSqlStatement.LAST_TIME_CONTACTED, contactLastTimeContacted); statement.bindLong(ContactReplaceSqlStatement.TIMES_CONTACTED, contactTimesContacted); statement.bindLong(ContactReplaceSqlStatement.STARRED, contactStarred); statement.bindLong(ContactReplaceSqlStatement.HAS_PHONE_NUMBER, hasPhoneNumber); statement.bindLong(ContactReplaceSqlStatement.SINGLE_IS_RESTRICTED, singleIsRestricted); statement.bindString(ContactReplaceSqlStatement.LOOKUP_KEY, Uri.encode(mSb.toString())); } /** * Uses the supplied values to determine if they represent a "better" display name * for the aggregate contact currently evaluated. If so, it updates * {@link #mDisplayNameCandidate} with the new values. */ private void processDisplayNameCanditate(long rawContactId, String displayName, int displayNameSource, boolean writableAccount, boolean verified) { boolean replace = false; if (mDisplayNameCandidate.rawContactId == -1) { // No previous values available replace = true; } else if (!TextUtils.isEmpty(displayName)) { if (!mDisplayNameCandidate.verified && verified) { // A verified name is better than any other name replace = true; } else if (mDisplayNameCandidate.verified == verified) { if (mDisplayNameCandidate.displayNameSource < displayNameSource) { // New values come from an superior source, e.g. structured name vs phone number replace = true; } else if (mDisplayNameCandidate.displayNameSource == displayNameSource) { if (!mDisplayNameCandidate.writableAccount && writableAccount) { replace = true; } else if (mDisplayNameCandidate.writableAccount == writableAccount) { if (NameNormalizer.compareComplexity(displayName, mDisplayNameCandidate.displayName) > 0) { // New name is more complex than the previously found one replace = true; } } } } } if (replace) { mDisplayNameCandidate.rawContactId = rawContactId; mDisplayNameCandidate.displayName = displayName; mDisplayNameCandidate.displayNameSource = displayNameSource; mDisplayNameCandidate.verified = verified; mDisplayNameCandidate.writableAccount = writableAccount; } } private interface PhotoIdQuery { String[] COLUMNS = new String[] { RawContacts.ACCOUNT_NAME, DataColumns.CONCRETE_ID, Data.IS_SUPER_PRIMARY, }; int ACCOUNT_NAME = 0; int DATA_ID = 1; int IS_SUPER_PRIMARY = 2; } public void updatePhotoId(SQLiteDatabase db, long rawContactId) { long contactId = mDbHelper.getContactId(rawContactId); if (contactId == 0) { return; } long bestPhotoId = -1; String photoAccount = null; long photoMimeType = mDbHelper.getMimeTypeId(Photo.CONTENT_ITEM_TYPE); String tables = Tables.RAW_CONTACTS + " JOIN " + Tables.DATA + " ON(" + DataColumns.CONCRETE_RAW_CONTACT_ID + "=" + RawContactsColumns.CONCRETE_ID + " AND (" + DataColumns.MIMETYPE_ID + "=" + photoMimeType + " AND " + Photo.PHOTO + " NOT NULL))"; mSelectionArgs1[0] = String.valueOf(contactId); final Cursor c = db.query(tables, PhotoIdQuery.COLUMNS, RawContacts.CONTACT_ID + "=?", mSelectionArgs1, null, null, null); try { while (c.moveToNext()) { long dataId = c.getLong(PhotoIdQuery.DATA_ID); boolean superprimary = c.getInt(PhotoIdQuery.IS_SUPER_PRIMARY) != 0; if (superprimary) { bestPhotoId = dataId; break; } // For now, just choose the first photo in a list sorted by account name. String account = c.getString(PhotoIdQuery.ACCOUNT_NAME); if (photoAccount == null) { photoAccount = account; bestPhotoId = dataId; } else { if (account.compareToIgnoreCase(photoAccount) < 0) { photoAccount = account; bestPhotoId = dataId; } } } } finally { c.close(); } if (bestPhotoId == -1) { mPhotoIdUpdate.bindNull(1); } else { mPhotoIdUpdate.bindLong(1, bestPhotoId); } mPhotoIdUpdate.bindLong(2, contactId); mPhotoIdUpdate.execute(); } private interface DisplayNameQuery { String[] COLUMNS = new String[] { RawContacts._ID, RawContactsColumns.DISPLAY_NAME, RawContactsColumns.DISPLAY_NAME_SOURCE, RawContacts.NAME_VERIFIED, RawContacts.SOURCE_ID, RawContacts.ACCOUNT_TYPE, }; int _ID = 0; int DISPLAY_NAME = 1; int DISPLAY_NAME_SOURCE = 2; int NAME_VERIFIED = 3; int SOURCE_ID = 4; int ACCOUNT_TYPE = 5; } public void updateDisplayNameForRawContact(SQLiteDatabase db, long rawContactId) { long contactId = mDbHelper.getContactId(rawContactId); if (contactId == 0) { return; } updateDisplayNameForContact(db, contactId); } public void updateDisplayNameForContact(SQLiteDatabase db, long contactId) { boolean lookupKeyUpdateNeeded = false; mDisplayNameCandidate.clear(); mSelectionArgs1[0] = String.valueOf(contactId); final Cursor c = db.query(Tables.RAW_CONTACTS, DisplayNameQuery.COLUMNS, RawContacts.CONTACT_ID + "=?", mSelectionArgs1, null, null, null); try { while (c.moveToNext()) { long rawContactId = c.getLong(DisplayNameQuery._ID); String displayName = c.getString(DisplayNameQuery.DISPLAY_NAME); int displayNameSource = c.getInt(DisplayNameQuery.DISPLAY_NAME_SOURCE); int nameVerified = c.getInt(DisplayNameQuery.NAME_VERIFIED); String accountType = c.getString(DisplayNameQuery.ACCOUNT_TYPE); processDisplayNameCanditate(rawContactId, displayName, displayNameSource, mContactsProvider.isWritableAccount(accountType), nameVerified != 0); // If the raw contact has no source id, the lookup key is based on the display // name, so the lookup key needs to be updated. lookupKeyUpdateNeeded |= c.isNull(DisplayNameQuery.SOURCE_ID); } } finally { c.close(); } if (mDisplayNameCandidate.rawContactId != -1) { mDisplayNameUpdate.bindLong(1, mDisplayNameCandidate.rawContactId); mDisplayNameUpdate.bindLong(2, contactId); mDisplayNameUpdate.execute(); } if (lookupKeyUpdateNeeded) { updateLookupKeyForContact(db, contactId); } } /** * Updates the {@link Contacts#HAS_PHONE_NUMBER} flag for the aggregate contact containing the * specified raw contact. */ public void updateHasPhoneNumber(SQLiteDatabase db, long rawContactId) { long contactId = mDbHelper.getContactId(rawContactId); if (contactId == 0) { return; } mHasPhoneNumberUpdate.bindLong(1, mDbHelper.getMimeTypeId(Phone.CONTENT_ITEM_TYPE)); mHasPhoneNumberUpdate.bindLong(2, contactId); mHasPhoneNumberUpdate.bindLong(3, contactId); mHasPhoneNumberUpdate.execute(); } private interface LookupKeyQuery { String[] COLUMNS = new String[] { RawContacts._ID, RawContactsColumns.DISPLAY_NAME, RawContacts.ACCOUNT_TYPE, RawContacts.ACCOUNT_NAME, RawContacts.SOURCE_ID, }; int ID = 0; int DISPLAY_NAME = 1; int ACCOUNT_TYPE = 2; int ACCOUNT_NAME = 3; int SOURCE_ID = 4; } public void updateLookupKeyForRawContact(SQLiteDatabase db, long rawContactId) { long contactId = mDbHelper.getContactId(rawContactId); if (contactId == 0) { return; } updateLookupKeyForContact(db, contactId); } public void updateLookupKeyForContact(SQLiteDatabase db, long contactId) { mSb.setLength(0); mSelectionArgs1[0] = String.valueOf(contactId); final Cursor c = db.query(Tables.RAW_CONTACTS, LookupKeyQuery.COLUMNS, RawContacts.CONTACT_ID + "=?", mSelectionArgs1, null, null, RawContacts._ID); try { while (c.moveToNext()) { ContactLookupKey.appendToLookupKey(mSb, c.getString(LookupKeyQuery.ACCOUNT_TYPE), c.getString(LookupKeyQuery.ACCOUNT_NAME), c.getLong(LookupKeyQuery.ID), c.getString(LookupKeyQuery.SOURCE_ID), c.getString(LookupKeyQuery.DISPLAY_NAME)); } } finally { c.close(); } if (mSb.length() == 0) { mLookupKeyUpdate.bindNull(1); } else { mLookupKeyUpdate.bindString(1, Uri.encode(mSb.toString())); } mLookupKeyUpdate.bindLong(2, contactId); mLookupKeyUpdate.execute(); } /** * Execute {@link SQLiteStatement} that will update the * {@link Contacts#STARRED} flag for the given {@link RawContacts#_ID}. */ protected void updateStarred(long rawContactId) { long contactId = mDbHelper.getContactId(rawContactId); if (contactId == 0) { return; } mStarredUpdate.bindLong(1, contactId); mStarredUpdate.execute(); } /** * Finds matching contacts and returns a cursor on those. */ public Cursor queryAggregationSuggestions(SQLiteQueryBuilder qb, String[] projection, long contactId, int maxSuggestions, String filter) { final SQLiteDatabase db = mDbHelper.getReadableDatabase(); List<MatchScore> bestMatches = findMatchingContacts(db, contactId); return queryMatchingContacts(qb, db, contactId, projection, bestMatches, maxSuggestions, filter); } private interface ContactIdQuery { String[] COLUMNS = new String[] { Contacts._ID }; int _ID = 0; } /** * Loads contacts with specified IDs and returns them in the order of IDs in the * supplied list. */ private Cursor queryMatchingContacts(SQLiteQueryBuilder qb, SQLiteDatabase db, long contactId, String[] projection, List<MatchScore> bestMatches, int maxSuggestions, String filter) { StringBuilder sb = new StringBuilder(); sb.append(Contacts._ID); sb.append(" IN ("); for (int i = 0; i < bestMatches.size(); i++) { MatchScore matchScore = bestMatches.get(i); if (i != 0) { sb.append(","); } sb.append(matchScore.getContactId()); } sb.append(")"); if (!TextUtils.isEmpty(filter)) { sb.append(" AND " + Contacts._ID + " IN "); mContactsProvider.appendContactFilterAsNestedQuery(sb, filter); } // Run a query and find ids of best matching contacts satisfying the filter (if any) HashSet<Long> foundIds = new HashSet<Long>(); Cursor cursor = db.query(qb.getTables(), ContactIdQuery.COLUMNS, sb.toString(), null, null, null, null); try { while(cursor.moveToNext()) { foundIds.add(cursor.getLong(ContactIdQuery._ID)); } } finally { cursor.close(); } // Exclude all contacts that did not match the filter Iterator<MatchScore> iter = bestMatches.iterator(); while (iter.hasNext()) { long id = iter.next().getContactId(); if (!foundIds.contains(id)) { iter.remove(); } } // Limit the number of returned suggestions if (bestMatches.size() > maxSuggestions) { bestMatches = bestMatches.subList(0, maxSuggestions); } // Build an in-clause with the remaining contact IDs sb.setLength(0); sb.append(Contacts._ID); sb.append(" IN ("); for (int i = 0; i < bestMatches.size(); i++) { MatchScore matchScore = bestMatches.get(i); if (i != 0) { sb.append(","); } sb.append(matchScore.getContactId()); } sb.append(")"); // Run the final query with the required projection and contact IDs found by the first query cursor = qb.query(db, projection, sb.toString(), null, null, null, Contacts._ID); // Build a sorted list of discovered IDs ArrayList<Long> sortedContactIds = new ArrayList<Long>(bestMatches.size()); for (MatchScore matchScore : bestMatches) { sortedContactIds.add(matchScore.getContactId()); } Collections.sort(sortedContactIds); // Map cursor indexes according to the descending order of match scores int[] positionMap = new int[bestMatches.size()]; for (int i = 0; i < positionMap.length; i++) { long id = bestMatches.get(i).getContactId(); positionMap[i] = sortedContactIds.indexOf(id); } return new ReorderingCursorWrapper(cursor, positionMap); } private interface RawContactIdQuery { String TABLE = Tables.RAW_CONTACTS; String[] COLUMNS = new String[] { RawContacts._ID }; int _ID = 0; } /** * Finds contacts with data matches and returns a list of {@link MatchScore}'s in the * descending order of match score. */ private List<MatchScore> findMatchingContacts(final SQLiteDatabase db, long contactId) { MatchCandidateList candidates = new MatchCandidateList(); ContactMatcher matcher = new ContactMatcher(); // Don't aggregate a contact with itself matcher.keepOut(contactId); final Cursor c = db.query(RawContactIdQuery.TABLE, RawContactIdQuery.COLUMNS, RawContacts.CONTACT_ID + "=" + contactId, null, null, null, null); try { while (c.moveToNext()) { long rawContactId = c.getLong(RawContactIdQuery._ID); updateMatchScoresForSuggestionsBasedOnDataMatches(db, rawContactId, candidates, matcher); } } finally { c.close(); } return matcher.pickBestMatches(ContactMatcher.SCORE_THRESHOLD_SUGGEST); } /** * Computes scores for contacts that have matching data rows. */ private void updateMatchScoresForSuggestionsBasedOnDataMatches(SQLiteDatabase db, long rawContactId, MatchCandidateList candidates, ContactMatcher matcher) { updateMatchScoresBasedOnNameMatches(db, rawContactId, matcher); updateMatchScoresBasedOnEmailMatches(db, rawContactId, matcher); updateMatchScoresBasedOnPhoneMatches(db, rawContactId, matcher); loadNameMatchCandidates(db, rawContactId, candidates, false); lookupApproximateNameMatches(db, candidates, matcher); } }
true
true
private void computeAggregateData(final SQLiteDatabase db, String sql, String[] sqlArgs, SQLiteStatement statement) { long currentRawContactId = -1; long bestPhotoId = -1; boolean foundSuperPrimaryPhoto = false; String photoAccount = null; int totalRowCount = 0; int contactSendToVoicemail = 0; String contactCustomRingtone = null; long contactLastTimeContacted = 0; int contactTimesContacted = 0; int contactStarred = 0; int singleIsRestricted = 1; int hasPhoneNumber = 0; mDisplayNameCandidate.clear(); mSb.setLength(0); // Lookup key Cursor c = db.rawQuery(sql, sqlArgs); try { while (c.moveToNext()) { long rawContactId = c.getLong(RawContactsQuery.RAW_CONTACT_ID); if (rawContactId != currentRawContactId) { currentRawContactId = rawContactId; totalRowCount++; // Display name String displayName = c.getString(RawContactsQuery.DISPLAY_NAME); int displayNameSource = c.getInt(RawContactsQuery.DISPLAY_NAME_SOURCE); int nameVerified = c.getInt(RawContactsQuery.NAME_VERIFIED); String accountType = c.getString(RawContactsQuery.ACCOUNT_TYPE); processDisplayNameCanditate(rawContactId, displayName, displayNameSource, mContactsProvider.isWritableAccount(accountType), nameVerified != 0); // Contact options if (!c.isNull(RawContactsQuery.SEND_TO_VOICEMAIL)) { boolean sendToVoicemail = (c.getInt(RawContactsQuery.SEND_TO_VOICEMAIL) != 0); if (sendToVoicemail) { contactSendToVoicemail++; } } if (contactCustomRingtone == null && !c.isNull(RawContactsQuery.CUSTOM_RINGTONE)) { contactCustomRingtone = c.getString(RawContactsQuery.CUSTOM_RINGTONE); } long lastTimeContacted = c.getLong(RawContactsQuery.LAST_TIME_CONTACTED); if (lastTimeContacted > contactLastTimeContacted) { contactLastTimeContacted = lastTimeContacted; } int timesContacted = c.getInt(RawContactsQuery.TIMES_CONTACTED); if (timesContacted > contactTimesContacted) { contactTimesContacted = timesContacted; } if (c.getInt(RawContactsQuery.STARRED) != 0) { contactStarred = 1; } // Single restricted if (totalRowCount > 1) { // Not single singleIsRestricted = 0; } else { int isRestricted = c.getInt(RawContactsQuery.IS_RESTRICTED); if (isRestricted == 0) { // Not restricted singleIsRestricted = 0; } } ContactLookupKey.appendToLookupKey(mSb, c.getString(RawContactsQuery.ACCOUNT_TYPE), c.getString(RawContactsQuery.ACCOUNT_NAME), rawContactId, c.getString(RawContactsQuery.SOURCE_ID), displayName); } if (!c.isNull(RawContactsQuery.DATA_ID)) { long dataId = c.getLong(RawContactsQuery.DATA_ID); int mimetypeId = c.getInt(RawContactsQuery.MIMETYPE_ID); boolean superprimary = c.getInt(RawContactsQuery.IS_SUPER_PRIMARY) != 0; if (mimetypeId == mMimeTypeIdPhoto) { // For now, just choose the first photo in a list sorted by account name. String account = c.getString(RawContactsQuery.ACCOUNT_NAME); if (!foundSuperPrimaryPhoto && (superprimary || photoAccount == null || photoAccount.compareToIgnoreCase(account) >= 0)) { photoAccount = account; bestPhotoId = dataId; foundSuperPrimaryPhoto |= superprimary; } } else if (mimetypeId == mMimeTypeIdPhone) { hasPhoneNumber = 1; } } } } finally { c.close(); } statement.bindLong(ContactReplaceSqlStatement.NAME_RAW_CONTACT_ID, mDisplayNameCandidate.rawContactId); if (bestPhotoId != -1) { statement.bindLong(ContactReplaceSqlStatement.PHOTO_ID, bestPhotoId); } else { statement.bindNull(ContactReplaceSqlStatement.PHOTO_ID); } statement.bindLong(ContactReplaceSqlStatement.SEND_TO_VOICEMAIL, totalRowCount == contactSendToVoicemail ? 1 : 0); DatabaseUtils.bindObjectToProgram(statement, ContactReplaceSqlStatement.CUSTOM_RINGTONE, contactCustomRingtone); statement.bindLong(ContactReplaceSqlStatement.LAST_TIME_CONTACTED, contactLastTimeContacted); statement.bindLong(ContactReplaceSqlStatement.TIMES_CONTACTED, contactTimesContacted); statement.bindLong(ContactReplaceSqlStatement.STARRED, contactStarred); statement.bindLong(ContactReplaceSqlStatement.HAS_PHONE_NUMBER, hasPhoneNumber); statement.bindLong(ContactReplaceSqlStatement.SINGLE_IS_RESTRICTED, singleIsRestricted); statement.bindString(ContactReplaceSqlStatement.LOOKUP_KEY, Uri.encode(mSb.toString())); }
private void computeAggregateData(final SQLiteDatabase db, String sql, String[] sqlArgs, SQLiteStatement statement) { long currentRawContactId = -1; long bestPhotoId = -1; boolean foundSuperPrimaryPhoto = false; String photoAccount = null; int totalRowCount = 0; int contactSendToVoicemail = 0; String contactCustomRingtone = null; long contactLastTimeContacted = 0; int contactTimesContacted = 0; int contactStarred = 0; int singleIsRestricted = 1; int hasPhoneNumber = 0; mDisplayNameCandidate.clear(); mSb.setLength(0); // Lookup key Cursor c = db.rawQuery(sql, sqlArgs); try { while (c.moveToNext()) { long rawContactId = c.getLong(RawContactsQuery.RAW_CONTACT_ID); if (rawContactId != currentRawContactId) { currentRawContactId = rawContactId; totalRowCount++; // Display name String displayName = c.getString(RawContactsQuery.DISPLAY_NAME); int displayNameSource = c.getInt(RawContactsQuery.DISPLAY_NAME_SOURCE); int nameVerified = c.getInt(RawContactsQuery.NAME_VERIFIED); String accountType = c.getString(RawContactsQuery.ACCOUNT_TYPE); processDisplayNameCanditate(rawContactId, displayName, displayNameSource, mContactsProvider.isWritableAccount(accountType), nameVerified != 0); // Contact options if (!c.isNull(RawContactsQuery.SEND_TO_VOICEMAIL)) { boolean sendToVoicemail = (c.getInt(RawContactsQuery.SEND_TO_VOICEMAIL) != 0); if (sendToVoicemail) { contactSendToVoicemail++; } } if (contactCustomRingtone == null && !c.isNull(RawContactsQuery.CUSTOM_RINGTONE)) { contactCustomRingtone = c.getString(RawContactsQuery.CUSTOM_RINGTONE); } long lastTimeContacted = c.getLong(RawContactsQuery.LAST_TIME_CONTACTED); if (lastTimeContacted > contactLastTimeContacted) { contactLastTimeContacted = lastTimeContacted; } int timesContacted = c.getInt(RawContactsQuery.TIMES_CONTACTED); if (timesContacted > contactTimesContacted) { contactTimesContacted = timesContacted; } if (c.getInt(RawContactsQuery.STARRED) != 0) { contactStarred = 1; } // Single restricted if (totalRowCount > 1) { // Not single singleIsRestricted = 0; } else { int isRestricted = c.getInt(RawContactsQuery.IS_RESTRICTED); if (isRestricted == 0) { // Not restricted singleIsRestricted = 0; } } ContactLookupKey.appendToLookupKey(mSb, c.getString(RawContactsQuery.ACCOUNT_TYPE), c.getString(RawContactsQuery.ACCOUNT_NAME), rawContactId, c.getString(RawContactsQuery.SOURCE_ID), displayName); } if (!c.isNull(RawContactsQuery.DATA_ID)) { long dataId = c.getLong(RawContactsQuery.DATA_ID); int mimetypeId = c.getInt(RawContactsQuery.MIMETYPE_ID); boolean superprimary = c.getInt(RawContactsQuery.IS_SUPER_PRIMARY) != 0; if (mimetypeId == mMimeTypeIdPhoto) { // For now, just choose the first photo in a list sorted by account name. String account = c.getString(RawContactsQuery.ACCOUNT_NAME); if (!foundSuperPrimaryPhoto && ( superprimary || photoAccount == null || (account != null && photoAccount.compareToIgnoreCase(account) >= 0))) { photoAccount = account; bestPhotoId = dataId; foundSuperPrimaryPhoto |= superprimary; } } else if (mimetypeId == mMimeTypeIdPhone) { hasPhoneNumber = 1; } } } } finally { c.close(); } statement.bindLong(ContactReplaceSqlStatement.NAME_RAW_CONTACT_ID, mDisplayNameCandidate.rawContactId); if (bestPhotoId != -1) { statement.bindLong(ContactReplaceSqlStatement.PHOTO_ID, bestPhotoId); } else { statement.bindNull(ContactReplaceSqlStatement.PHOTO_ID); } statement.bindLong(ContactReplaceSqlStatement.SEND_TO_VOICEMAIL, totalRowCount == contactSendToVoicemail ? 1 : 0); DatabaseUtils.bindObjectToProgram(statement, ContactReplaceSqlStatement.CUSTOM_RINGTONE, contactCustomRingtone); statement.bindLong(ContactReplaceSqlStatement.LAST_TIME_CONTACTED, contactLastTimeContacted); statement.bindLong(ContactReplaceSqlStatement.TIMES_CONTACTED, contactTimesContacted); statement.bindLong(ContactReplaceSqlStatement.STARRED, contactStarred); statement.bindLong(ContactReplaceSqlStatement.HAS_PHONE_NUMBER, hasPhoneNumber); statement.bindLong(ContactReplaceSqlStatement.SINGLE_IS_RESTRICTED, singleIsRestricted); statement.bindString(ContactReplaceSqlStatement.LOOKUP_KEY, Uri.encode(mSb.toString())); }
diff --git a/src/com/dmdirc/plugins/LegacyServiceLocator.java b/src/com/dmdirc/plugins/LegacyServiceLocator.java index 180e9320a..c836ef87a 100644 --- a/src/com/dmdirc/plugins/LegacyServiceLocator.java +++ b/src/com/dmdirc/plugins/LegacyServiceLocator.java @@ -1,97 +1,96 @@ /* * Copyright (c) 2006-2014 DMDirc Developers * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.plugins; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashSet; import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; import static com.google.common.base.Preconditions.checkNotNull; /** * A service locator backed by a {@link PluginManager} and exported methods. */ @Singleton public class LegacyServiceLocator implements ServiceLocator { /** The plugin manager to use to find services. */ private final PluginManager pluginManager; @Inject public LegacyServiceLocator(final PluginManager pluginManager) { this.pluginManager = checkNotNull(pluginManager); } @Override public <T> Collection<T> getAllServices(final Class<T> serviceType) { return getServices(serviceType, null); } @Override public <T> T getService(final Class<T> serviceType, final String implementation) { final Collection<T> services = getServices(serviceType, implementation); return services.isEmpty() ? null : services.iterator().next(); } @SuppressWarnings("unchecked") private <T> Collection<T> getServices( final Class<T> serviceType, @Nullable final String implementation) { checkNotNull(serviceType); final Collection<T> services = new HashSet<>(); for (PluginInfo pluginInfo : pluginManager.getPluginInfos()) { if (pluginInfo.isLoaded()) { final Plugin plugin = pluginInfo.getPlugin(); - if (implementation == null || implementation.equals(plugin.getClass().getName())) { - for (Method method : plugin.getClass().getMethods()) { - if (method.isAnnotationPresent(Exported.class) - && method.getParameterTypes().length == 0 - && serviceType.isAssignableFrom(method.getReturnType())) { - try { - method.setAccessible(true); - final Object object = method.invoke(plugin); - if (object != null) { - services.add((T) object); - } - } catch (ReflectiveOperationException ex) { - Logger.appError(ErrorLevel.LOW, - "Unable to execute exported method " + method.getName() - + " in plugin " + pluginInfo.getMetaData().getName(), ex); + for (Method method : plugin.getClass().getMethods()) { + if (method.isAnnotationPresent(Exported.class) + && method.getParameterTypes().length == 0 + && serviceType.isAssignableFrom(method.getReturnType())) { + try { + method.setAccessible(true); + final Object object = method.invoke(plugin); + if (object != null && (implementation == null + || implementation.equals(object.getClass().getName()))) { + services.add((T) object); } + } catch (ReflectiveOperationException ex) { + Logger.appError(ErrorLevel.LOW, + "Unable to execute exported method " + method.getName() + + " in plugin " + pluginInfo.getMetaData().getName(), ex); } } } } } return services; } }
false
true
private <T> Collection<T> getServices( final Class<T> serviceType, @Nullable final String implementation) { checkNotNull(serviceType); final Collection<T> services = new HashSet<>(); for (PluginInfo pluginInfo : pluginManager.getPluginInfos()) { if (pluginInfo.isLoaded()) { final Plugin plugin = pluginInfo.getPlugin(); if (implementation == null || implementation.equals(plugin.getClass().getName())) { for (Method method : plugin.getClass().getMethods()) { if (method.isAnnotationPresent(Exported.class) && method.getParameterTypes().length == 0 && serviceType.isAssignableFrom(method.getReturnType())) { try { method.setAccessible(true); final Object object = method.invoke(plugin); if (object != null) { services.add((T) object); } } catch (ReflectiveOperationException ex) { Logger.appError(ErrorLevel.LOW, "Unable to execute exported method " + method.getName() + " in plugin " + pluginInfo.getMetaData().getName(), ex); } } } } } } return services; }
private <T> Collection<T> getServices( final Class<T> serviceType, @Nullable final String implementation) { checkNotNull(serviceType); final Collection<T> services = new HashSet<>(); for (PluginInfo pluginInfo : pluginManager.getPluginInfos()) { if (pluginInfo.isLoaded()) { final Plugin plugin = pluginInfo.getPlugin(); for (Method method : plugin.getClass().getMethods()) { if (method.isAnnotationPresent(Exported.class) && method.getParameterTypes().length == 0 && serviceType.isAssignableFrom(method.getReturnType())) { try { method.setAccessible(true); final Object object = method.invoke(plugin); if (object != null && (implementation == null || implementation.equals(object.getClass().getName()))) { services.add((T) object); } } catch (ReflectiveOperationException ex) { Logger.appError(ErrorLevel.LOW, "Unable to execute exported method " + method.getName() + " in plugin " + pluginInfo.getMetaData().getName(), ex); } } } } } return services; }
diff --git a/AlloyCompiler.java b/AlloyCompiler.java index 371d061..d4d94c1 100644 --- a/AlloyCompiler.java +++ b/AlloyCompiler.java @@ -1,30 +1,30 @@ /** Running the Alloy Compiller. By Gail Terman */ import edu.mit.csail.sdg.alloy4.Err; import edu.mit.csail.sdg.alloy4compiler.parser.CompUtil; import edu.mit.csail.sdg.alloy4compiler.ast.Module; import edu.mit.csail.sdg.alloy4compiler.ast.Command; import edu.mit.csail.sdg.alloy4compiler.translator.A4Solution; import edu.mit.csail.sdg.alloy4compiler.translator.A4Options; import edu.mit.csail.sdg.alloy4compiler.translator.TranslateAlloyToKodkod; public class AlloyCompiler { public static void main (String[] args) throws Err{ String filename = args[0]; Module mod = CompUtil.parseEverything_fromFile(null, null, filename); A4Options opts = new A4Options(); opts.solver = A4Options.SatSolver.SAT4J; String cwd = System.getProperty("user.dir"); for (Command command: mod.getAllCommands()) { A4Solution ans = TranslateAlloyToKodkod.execute_command(null, mod.getAllReachableSigs(), command, opts); if (ans.satisfiable()) { - ans.writeXML(cwd+"\\out.xml"); + ans.writeXML(cwd+"/out.xml"); }else System.out.println("Not satisfiable."); } } }
true
true
public static void main (String[] args) throws Err{ String filename = args[0]; Module mod = CompUtil.parseEverything_fromFile(null, null, filename); A4Options opts = new A4Options(); opts.solver = A4Options.SatSolver.SAT4J; String cwd = System.getProperty("user.dir"); for (Command command: mod.getAllCommands()) { A4Solution ans = TranslateAlloyToKodkod.execute_command(null, mod.getAllReachableSigs(), command, opts); if (ans.satisfiable()) { ans.writeXML(cwd+"\\out.xml"); }else System.out.println("Not satisfiable."); } }
public static void main (String[] args) throws Err{ String filename = args[0]; Module mod = CompUtil.parseEverything_fromFile(null, null, filename); A4Options opts = new A4Options(); opts.solver = A4Options.SatSolver.SAT4J; String cwd = System.getProperty("user.dir"); for (Command command: mod.getAllCommands()) { A4Solution ans = TranslateAlloyToKodkod.execute_command(null, mod.getAllReachableSigs(), command, opts); if (ans.satisfiable()) { ans.writeXML(cwd+"/out.xml"); }else System.out.println("Not satisfiable."); } }
diff --git a/cometd-javascript/jquery/src/test/java/org/cometd/javascript/jquery/AbstractCometdJQueryTest.java b/cometd-javascript/jquery/src/test/java/org/cometd/javascript/jquery/AbstractCometdJQueryTest.java index ef82d84fe..4a2c20f3a 100644 --- a/cometd-javascript/jquery/src/test/java/org/cometd/javascript/jquery/AbstractCometdJQueryTest.java +++ b/cometd-javascript/jquery/src/test/java/org/cometd/javascript/jquery/AbstractCometdJQueryTest.java @@ -1,65 +1,65 @@ package org.cometd.javascript.jquery; import java.io.File; import java.net.URL; import org.cometd.AbstractCometdTest; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.util.resource.ResourceCollection; /** * @version $Revision$ $Date$ */ public abstract class AbstractCometdJQueryTest extends AbstractCometdTest { protected void customizeContext(ServletContextHandler context) throws Exception { File baseDirectory = new File(System.getProperty("basedir", ".")); File webappDirectory = new File(baseDirectory, "src/main/webapp"); File overlaidScriptDirectory = new File(baseDirectory, "target/scripts"); File testResourcesDirectory = new File(baseDirectory, "src/test/resources"); context.setBaseResource(new ResourceCollection(new String[] { webappDirectory.getCanonicalPath(), overlaidScriptDirectory.getCanonicalPath(), testResourcesDirectory.getCanonicalPath() })); } @Override protected void setUp() throws Exception { super.setUp(); initPage(); } public void initPage() throws Exception { initJavaScript(); // Order of the script evaluation is important, as they depend one from the other URL envURL = new URL(contextURL + "/env.js"); evaluateURL(envURL); evaluateScript("window.location = '" + contextURL + "'"); URL cometdURL = new URL(contextURL + "/org/cometd.js"); evaluateURL(cometdURL); - URL jqueryURL = new URL(contextURL + "/jquery/jquery-1.3.2.js"); + URL jqueryURL = new URL(contextURL + "/jquery/jquery-1.4.2.js"); evaluateURL(jqueryURL); URL jqueryJSONURL = new URL(contextURL + "/jquery/jquery.json-2.2.js"); evaluateURL(jqueryJSONURL); URL jqueryCometdURL = new URL(contextURL + "/jquery/jquery.cometd.js"); evaluateURL(jqueryCometdURL); } @Override protected void tearDown() throws Exception { super.tearDown(); destroyPage(); } public void destroyPage() throws Exception { destroyJavaScript(); } }
true
true
public void initPage() throws Exception { initJavaScript(); // Order of the script evaluation is important, as they depend one from the other URL envURL = new URL(contextURL + "/env.js"); evaluateURL(envURL); evaluateScript("window.location = '" + contextURL + "'"); URL cometdURL = new URL(contextURL + "/org/cometd.js"); evaluateURL(cometdURL); URL jqueryURL = new URL(contextURL + "/jquery/jquery-1.3.2.js"); evaluateURL(jqueryURL); URL jqueryJSONURL = new URL(contextURL + "/jquery/jquery.json-2.2.js"); evaluateURL(jqueryJSONURL); URL jqueryCometdURL = new URL(contextURL + "/jquery/jquery.cometd.js"); evaluateURL(jqueryCometdURL); }
public void initPage() throws Exception { initJavaScript(); // Order of the script evaluation is important, as they depend one from the other URL envURL = new URL(contextURL + "/env.js"); evaluateURL(envURL); evaluateScript("window.location = '" + contextURL + "'"); URL cometdURL = new URL(contextURL + "/org/cometd.js"); evaluateURL(cometdURL); URL jqueryURL = new URL(contextURL + "/jquery/jquery-1.4.2.js"); evaluateURL(jqueryURL); URL jqueryJSONURL = new URL(contextURL + "/jquery/jquery.json-2.2.js"); evaluateURL(jqueryJSONURL); URL jqueryCometdURL = new URL(contextURL + "/jquery/jquery.cometd.js"); evaluateURL(jqueryCometdURL); }
diff --git a/sahi/src/com/redhat/qe/jon/sahi/tasks/Navigator.java b/sahi/src/com/redhat/qe/jon/sahi/tasks/Navigator.java index 716699b2..2ed72468 100644 --- a/sahi/src/com/redhat/qe/jon/sahi/tasks/Navigator.java +++ b/sahi/src/com/redhat/qe/jon/sahi/tasks/Navigator.java @@ -1,78 +1,78 @@ package com.redhat.qe.jon.sahi.tasks; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; /** * This class should abstract navigation on RHQ in general * @author lzoubek * @since 25.Nov 2011 * */ public class Navigator { private static Logger log = Logger.getLogger(Navigator.class.getName()); private final SahiTasks tasks; private final Map<String,String> itNav; public Navigator(SahiTasks tasks) { this.tasks = tasks; // initialize navigation mappings itNav = new HashMap<String, String>(); itNav.put("Summary", "Service_up_16.png"); itNav.put("Inventory", "Inventory_grey_16.png"); itNav.put("Alerts", "Alerts_16.png"); itNav.put("Operations", "Operation_grey_16.png"); } /** * selects given inventory tab * you have to be in Inventory to use this method * @param it inventory Tab name * @param subTab sub tab to jump in within inventory tab */ public void inventorySelectTab(String it, String subTab) { if (itNav.containsKey(it)) { log.fine("select resourceTab "+it.toString()); if ("Summary".equals(it)) { tasks.image(itNav.get(it)).near(tasks.cell(it)).click(); } else { - tasks.image(itNav.get(it)).click(); + tasks.xy(tasks.image(itNav.get(it)),3,3).click(); } if (subTab!=null) { tasks.xy(tasks.cell(subTab), 3, 3).click(); } } else { throw new RuntimeException("Selecting tab of type "+it.toString()+" is not implemented"); } } /** * selects given inventory tab * you HAVE to be on Inventory page when using this method * @param it Inventory Tab name */ public void inventorySelectTab(String it) { inventorySelectTab(it, null); } /** * navigates to resource in inventory defined by its path * @param agent = platform containing desired resource * @param it = inventory tab you want to jump in (Operations/Drifts/...) * @param resourcePath for example 'Eap server-one','datasources','java:jboss/datasources/ExampleDS' * would navigate to example datasource on EAP server-one resource */ public void inventoryGoToResource(String agent, String it, String... resourcePath) { tasks.link("Inventory").click(); tasks.cell("Platforms").click(); log.fine("select agent "+agent); tasks.link(agent).click(); for (String element : resourcePath) { log.fine("select resource : "+element); inventorySelectTab("Inventory","Child Resources"); tasks.link(element).click(); } inventorySelectTab(it); } }
true
true
public void inventorySelectTab(String it, String subTab) { if (itNav.containsKey(it)) { log.fine("select resourceTab "+it.toString()); if ("Summary".equals(it)) { tasks.image(itNav.get(it)).near(tasks.cell(it)).click(); } else { tasks.image(itNav.get(it)).click(); } if (subTab!=null) { tasks.xy(tasks.cell(subTab), 3, 3).click(); } } else { throw new RuntimeException("Selecting tab of type "+it.toString()+" is not implemented"); } }
public void inventorySelectTab(String it, String subTab) { if (itNav.containsKey(it)) { log.fine("select resourceTab "+it.toString()); if ("Summary".equals(it)) { tasks.image(itNav.get(it)).near(tasks.cell(it)).click(); } else { tasks.xy(tasks.image(itNav.get(it)),3,3).click(); } if (subTab!=null) { tasks.xy(tasks.cell(subTab), 3, 3).click(); } } else { throw new RuntimeException("Selecting tab of type "+it.toString()+" is not implemented"); } }
diff --git a/src/task2/graphviz/Main.java b/src/task2/graphviz/Main.java index 5490e11..76f8e44 100644 --- a/src/task2/graphviz/Main.java +++ b/src/task2/graphviz/Main.java @@ -1,38 +1,39 @@ package task2.graphviz; import java.io.FileWriter; import java.io.Writer; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import task1.FSM; public class Main { public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: input-prolog-filename output-filename"); System.exit(0); } try { Velocity.init(); VelocityContext context = new VelocityContext(); FSM fsm = new FSM(args[0]); context.put("nodes", fsm.nodes); context.put("edges", fsm.edges); Template template = null; template = Velocity.getTemplate("task2-fsm.vm"); - Writer writer = new FileWriter(args[1]); + Writer writer = new FileWriter(args[1]+".dot"); + context.put("filename", args[1]); template.merge(context, writer); writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
true
true
public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: input-prolog-filename output-filename"); System.exit(0); } try { Velocity.init(); VelocityContext context = new VelocityContext(); FSM fsm = new FSM(args[0]); context.put("nodes", fsm.nodes); context.put("edges", fsm.edges); Template template = null; template = Velocity.getTemplate("task2-fsm.vm"); Writer writer = new FileWriter(args[1]); template.merge(context, writer); writer.close(); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { if (args.length != 2) { System.out.println("Usage: input-prolog-filename output-filename"); System.exit(0); } try { Velocity.init(); VelocityContext context = new VelocityContext(); FSM fsm = new FSM(args[0]); context.put("nodes", fsm.nodes); context.put("edges", fsm.edges); Template template = null; template = Velocity.getTemplate("task2-fsm.vm"); Writer writer = new FileWriter(args[1]+".dot"); context.put("filename", args[1]); template.merge(context, writer); writer.close(); } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandSmite.java b/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandSmite.java index f6609e35e..21f5e6c73 100644 --- a/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandSmite.java +++ b/src/FE_SRC_COMMON/com/ForgeEssentials/commands/CommandSmite.java @@ -1,99 +1,99 @@ package com.ForgeEssentials.commands; import java.util.List; import net.minecraft.command.ICommandSender; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MovingObjectPosition; import com.ForgeEssentials.core.commands.ForgeEssentialsCommandBase; import com.ForgeEssentials.util.FunctionHelper; import com.ForgeEssentials.util.Localization; import com.ForgeEssentials.util.OutputHandler; import cpw.mods.fml.common.FMLCommonHandler; public class CommandSmite extends ForgeEssentialsCommandBase { @Override public String getCommandName() { return "smite"; } @Override public void processCommandPlayer(EntityPlayer sender, String[] args) { if (args.length >= 1) { if (args[0].toLowerCase().equals("me")) { sender.worldObj.addWeatherEffect(new EntityLightningBolt(sender.worldObj, sender.posX, sender.posY, sender.posZ)); sender.sendChatToPlayer(Localization.get(Localization.SMITE_SELF)); } else { - EntityPlayer victim = FMLCommonHandler.instance().getSidedDelegate().getServer().getConfigurationManager().getPlayerForUsername(args[0]); + EntityPlayer victim = FunctionHelper.getPlayerFromUsername(args[0]); if (victim != null) { - victim.worldObj.addWeatherEffect(new EntityLightningBolt(sender.worldObj, sender.posX, sender.posY, sender.posZ)); + victim.worldObj.addWeatherEffect(new EntityLightningBolt(victim.worldObj, victim.posX, victim.posY, victim.posZ)); sender.sendChatToPlayer(Localization.get(Localization.SMITE_PLAYER)); } else OutputHandler.chatError(sender, Localization.format(Localization.ERROR_NOPLAYER, args[0])); } } else { MovingObjectPosition mop = FunctionHelper.getPlayerLookingSpot(sender, false); if (mop == null) OutputHandler.chatError(sender, Localization.get(Localization.ERROR_TARGET)); else { sender.worldObj.addWeatherEffect(new EntityLightningBolt(sender.worldObj, mop.blockX, mop.blockY, mop.blockZ)); sender.sendChatToPlayer(Localization.get(Localization.SMITE_GROUND)); } } } @Override public void processCommandConsole(ICommandSender sender, String[] args) { if (args.length >= 1) { EntityPlayer victim = FMLCommonHandler.instance().getSidedDelegate().getServer().getConfigurationManager().getPlayerForUsername(args[0]); if (victim != null) { victim.worldObj.addWeatherEffect(new EntityLightningBolt(victim.worldObj, victim.posX, victim.posY, victim.posZ)); sender.sendChatToPlayer(Localization.get(Localization.SMITE_PLAYER)); } else sender.sendChatToPlayer(Localization.format(Localization.ERROR_NOPLAYER, args[0])); } else sender.sendChatToPlayer(Localization.get(Localization.ERROR_BADSYNTAX) + getSyntaxConsole()); } @Override public boolean canConsoleUseCommand() { return true; } @Override public String getCommandPerm() { return "ForgeEssentials.BasicCommands." + getCommandName(); } @Override public List addTabCompletionOptions(ICommandSender sender, String[] args) { if(args.length == 1) { return getListOfStringsMatchingLastWord(args, FMLCommonHandler.instance().getMinecraftServerInstance().getAllUsernames()); } else { return null; } } }
false
true
public void processCommandPlayer(EntityPlayer sender, String[] args) { if (args.length >= 1) { if (args[0].toLowerCase().equals("me")) { sender.worldObj.addWeatherEffect(new EntityLightningBolt(sender.worldObj, sender.posX, sender.posY, sender.posZ)); sender.sendChatToPlayer(Localization.get(Localization.SMITE_SELF)); } else { EntityPlayer victim = FMLCommonHandler.instance().getSidedDelegate().getServer().getConfigurationManager().getPlayerForUsername(args[0]); if (victim != null) { victim.worldObj.addWeatherEffect(new EntityLightningBolt(sender.worldObj, sender.posX, sender.posY, sender.posZ)); sender.sendChatToPlayer(Localization.get(Localization.SMITE_PLAYER)); } else OutputHandler.chatError(sender, Localization.format(Localization.ERROR_NOPLAYER, args[0])); } } else { MovingObjectPosition mop = FunctionHelper.getPlayerLookingSpot(sender, false); if (mop == null) OutputHandler.chatError(sender, Localization.get(Localization.ERROR_TARGET)); else { sender.worldObj.addWeatherEffect(new EntityLightningBolt(sender.worldObj, mop.blockX, mop.blockY, mop.blockZ)); sender.sendChatToPlayer(Localization.get(Localization.SMITE_GROUND)); } } }
public void processCommandPlayer(EntityPlayer sender, String[] args) { if (args.length >= 1) { if (args[0].toLowerCase().equals("me")) { sender.worldObj.addWeatherEffect(new EntityLightningBolt(sender.worldObj, sender.posX, sender.posY, sender.posZ)); sender.sendChatToPlayer(Localization.get(Localization.SMITE_SELF)); } else { EntityPlayer victim = FunctionHelper.getPlayerFromUsername(args[0]); if (victim != null) { victim.worldObj.addWeatherEffect(new EntityLightningBolt(victim.worldObj, victim.posX, victim.posY, victim.posZ)); sender.sendChatToPlayer(Localization.get(Localization.SMITE_PLAYER)); } else OutputHandler.chatError(sender, Localization.format(Localization.ERROR_NOPLAYER, args[0])); } } else { MovingObjectPosition mop = FunctionHelper.getPlayerLookingSpot(sender, false); if (mop == null) OutputHandler.chatError(sender, Localization.get(Localization.ERROR_TARGET)); else { sender.worldObj.addWeatherEffect(new EntityLightningBolt(sender.worldObj, mop.blockX, mop.blockY, mop.blockZ)); sender.sendChatToPlayer(Localization.get(Localization.SMITE_GROUND)); } } }
diff --git a/src/com/cyanogenmod/trebuchet/preference/DoubleNumberPickerPreference.java b/src/com/cyanogenmod/trebuchet/preference/DoubleNumberPickerPreference.java index 81b766a4..eacc9278 100644 --- a/src/com/cyanogenmod/trebuchet/preference/DoubleNumberPickerPreference.java +++ b/src/com/cyanogenmod/trebuchet/preference/DoubleNumberPickerPreference.java @@ -1,186 +1,186 @@ /* * Copyright (C) 2011 The CyanogenMod 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.cyanogenmod.trebuchet.preference; import android.content.Context; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.preference.Preference; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import android.widget.EditText; import android.widget.NumberPicker; import com.cyanogenmod.trebuchet.R; /* * @author Danesh * @author nebkat */ public class DoubleNumberPickerPreference extends DialogPreference { private int mMin1, mMax1, mDefault1; private int mMin2, mMax2, mDefault2; private String mMaxExternalKey1, mMinExternalKey1; private String mMaxExternalKey2, mMinExternalKey2; private String mPickerTitle1; private String mPickerTitle2; private NumberPicker mNumberPicker1; private NumberPicker mNumberPicker2; public DoubleNumberPickerPreference(Context context, AttributeSet attrs) { super(context, attrs); TypedArray dialogType = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.DialogPreference, 0, 0); TypedArray doubleNumberPickerType = context.obtainStyledAttributes(attrs, R.styleable.DoubleNumberPickerPreference, 0, 0); mMaxExternalKey1 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_maxExternal1); mMinExternalKey1 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_minExternal1); mMaxExternalKey2 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_maxExternal2); mMinExternalKey2 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_minExternal2); mPickerTitle1 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_pickerTitle1); mPickerTitle2 = doubleNumberPickerType.getString(R.styleable.DoubleNumberPickerPreference_pickerTitle2); mMax1 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_max1, 5); mMin1 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_min1, 0); mMax2 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_max2, 5); mMin2 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_min2, 0); mDefault1 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_defaultValue1, mMin1); mDefault2 = doubleNumberPickerType.getInt(R.styleable.DoubleNumberPickerPreference_defaultValue2, mMin2); dialogType.recycle(); doubleNumberPickerType.recycle(); } @Override protected View onCreateDialogView() { int max1 = mMax1; int min1 = mMin1; int max2 = mMax2; int min2 = mMin2; // External values if (mMaxExternalKey1 != null) { max1 = getSharedPreferences().getInt(mMaxExternalKey1, mMax1); } if (mMinExternalKey1 != null) { min1 = getSharedPreferences().getInt(mMinExternalKey1, mMin1); } if (mMaxExternalKey2 != null) { max2 = getSharedPreferences().getInt(mMaxExternalKey2, mMax2); } if (mMinExternalKey2 != null) { min2 = getSharedPreferences().getInt(mMinExternalKey2, mMin2); } LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.double_number_picker_dialog, null); mNumberPicker1 = (NumberPicker) view.findViewById(R.id.number_picker_1); mNumberPicker2 = (NumberPicker) view.findViewById(R.id.number_picker_2); if (mNumberPicker1 == null || mNumberPicker2 == null) { throw new RuntimeException("mNumberPicker1 or mNumberPicker2 is null!"); } // Initialize state - mNumberPicker1.setWrapSelectorWheel(false); mNumberPicker1.setMaxValue(max1); mNumberPicker1.setMinValue(min1); mNumberPicker1.setValue(getPersistedValue(1)); - mNumberPicker2.setWrapSelectorWheel(false); + mNumberPicker1.setWrapSelectorWheel(false); mNumberPicker2.setMaxValue(max2); mNumberPicker2.setMinValue(min2); mNumberPicker2.setValue(getPersistedValue(2)); + mNumberPicker2.setWrapSelectorWheel(false); // Titles TextView pickerTitle1 = (TextView) view.findViewById(R.id.picker_title_1); TextView pickerTitle2 = (TextView) view.findViewById(R.id.picker_title_2); if (pickerTitle1 != null && pickerTitle2 != null) { pickerTitle1.setText(mPickerTitle1); pickerTitle2.setText(mPickerTitle2); } // No keyboard popup EditText textInput1 = (EditText) mNumberPicker1.findViewById(com.android.internal.R.id.numberpicker_input); EditText textInput2 = (EditText) mNumberPicker2.findViewById(com.android.internal.R.id.numberpicker_input); if (textInput1 != null && textInput2 != null) { textInput1.setCursorVisible(false); textInput1.setFocusable(false); textInput1.setFocusableInTouchMode(false); textInput2.setCursorVisible(false); textInput2.setFocusable(false); textInput2.setFocusableInTouchMode(false); } return view; } private int getPersistedValue(int value) { String[] values = getPersistedString(mDefault1 + "|" + mDefault2).split("\\|"); if (value == 1) { try { return Integer.parseInt(values[0]); } catch (NumberFormatException e) { return mDefault1; } } else { try { return Integer.parseInt(values[1]); } catch (NumberFormatException e) { return mDefault2; } } } @Override protected void onDialogClosed(boolean positiveResult) { if (positiveResult) { persistString(mNumberPicker1.getValue() + "|" + mNumberPicker2.getValue()); } } public void setMin1(int min) { mMin1 = min; } public void setMax1(int max) { mMax1 = max; } public void setMin2(int min) { mMin2 = min; } public void setMax2(int max) { mMax2 = max; } public void setDefault1(int def) { mDefault1 = def; } public void setDefault2(int def) { mDefault2 = def; } }
false
true
protected View onCreateDialogView() { int max1 = mMax1; int min1 = mMin1; int max2 = mMax2; int min2 = mMin2; // External values if (mMaxExternalKey1 != null) { max1 = getSharedPreferences().getInt(mMaxExternalKey1, mMax1); } if (mMinExternalKey1 != null) { min1 = getSharedPreferences().getInt(mMinExternalKey1, mMin1); } if (mMaxExternalKey2 != null) { max2 = getSharedPreferences().getInt(mMaxExternalKey2, mMax2); } if (mMinExternalKey2 != null) { min2 = getSharedPreferences().getInt(mMinExternalKey2, mMin2); } LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.double_number_picker_dialog, null); mNumberPicker1 = (NumberPicker) view.findViewById(R.id.number_picker_1); mNumberPicker2 = (NumberPicker) view.findViewById(R.id.number_picker_2); if (mNumberPicker1 == null || mNumberPicker2 == null) { throw new RuntimeException("mNumberPicker1 or mNumberPicker2 is null!"); } // Initialize state mNumberPicker1.setWrapSelectorWheel(false); mNumberPicker1.setMaxValue(max1); mNumberPicker1.setMinValue(min1); mNumberPicker1.setValue(getPersistedValue(1)); mNumberPicker2.setWrapSelectorWheel(false); mNumberPicker2.setMaxValue(max2); mNumberPicker2.setMinValue(min2); mNumberPicker2.setValue(getPersistedValue(2)); // Titles TextView pickerTitle1 = (TextView) view.findViewById(R.id.picker_title_1); TextView pickerTitle2 = (TextView) view.findViewById(R.id.picker_title_2); if (pickerTitle1 != null && pickerTitle2 != null) { pickerTitle1.setText(mPickerTitle1); pickerTitle2.setText(mPickerTitle2); } // No keyboard popup EditText textInput1 = (EditText) mNumberPicker1.findViewById(com.android.internal.R.id.numberpicker_input); EditText textInput2 = (EditText) mNumberPicker2.findViewById(com.android.internal.R.id.numberpicker_input); if (textInput1 != null && textInput2 != null) { textInput1.setCursorVisible(false); textInput1.setFocusable(false); textInput1.setFocusableInTouchMode(false); textInput2.setCursorVisible(false); textInput2.setFocusable(false); textInput2.setFocusableInTouchMode(false); } return view; }
protected View onCreateDialogView() { int max1 = mMax1; int min1 = mMin1; int max2 = mMax2; int min2 = mMin2; // External values if (mMaxExternalKey1 != null) { max1 = getSharedPreferences().getInt(mMaxExternalKey1, mMax1); } if (mMinExternalKey1 != null) { min1 = getSharedPreferences().getInt(mMinExternalKey1, mMin1); } if (mMaxExternalKey2 != null) { max2 = getSharedPreferences().getInt(mMaxExternalKey2, mMax2); } if (mMinExternalKey2 != null) { min2 = getSharedPreferences().getInt(mMinExternalKey2, mMin2); } LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.double_number_picker_dialog, null); mNumberPicker1 = (NumberPicker) view.findViewById(R.id.number_picker_1); mNumberPicker2 = (NumberPicker) view.findViewById(R.id.number_picker_2); if (mNumberPicker1 == null || mNumberPicker2 == null) { throw new RuntimeException("mNumberPicker1 or mNumberPicker2 is null!"); } // Initialize state mNumberPicker1.setMaxValue(max1); mNumberPicker1.setMinValue(min1); mNumberPicker1.setValue(getPersistedValue(1)); mNumberPicker1.setWrapSelectorWheel(false); mNumberPicker2.setMaxValue(max2); mNumberPicker2.setMinValue(min2); mNumberPicker2.setValue(getPersistedValue(2)); mNumberPicker2.setWrapSelectorWheel(false); // Titles TextView pickerTitle1 = (TextView) view.findViewById(R.id.picker_title_1); TextView pickerTitle2 = (TextView) view.findViewById(R.id.picker_title_2); if (pickerTitle1 != null && pickerTitle2 != null) { pickerTitle1.setText(mPickerTitle1); pickerTitle2.setText(mPickerTitle2); } // No keyboard popup EditText textInput1 = (EditText) mNumberPicker1.findViewById(com.android.internal.R.id.numberpicker_input); EditText textInput2 = (EditText) mNumberPicker2.findViewById(com.android.internal.R.id.numberpicker_input); if (textInput1 != null && textInput2 != null) { textInput1.setCursorVisible(false); textInput1.setFocusable(false); textInput1.setFocusableInTouchMode(false); textInput2.setCursorVisible(false); textInput2.setFocusable(false); textInput2.setFocusableInTouchMode(false); } return view; }
diff --git a/src/assemblernator/Instruction.java b/src/assemblernator/Instruction.java index d424c57..360d7d1 100644 --- a/src/assemblernator/Instruction.java +++ b/src/assemblernator/Instruction.java @@ -1,860 +1,860 @@ package assemblernator; import static assemblernator.ErrorReporting.makeError; import instructions.Comment; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import assemblernator.ErrorReporting.ErrorHandler; import assemblernator.ErrorReporting.URBANSyntaxException; /** * The Instruction class is the do-all, see-all, have-all class for instruction * use and representation. * * This class is both a descriptor class and a storage class. It represents the * main mechanisms for tokenizing, lexing, and assembling URBAN code. * * The Instruction class is designed such that every module of the * Assemblernator can utilize it in some form or another. * * These modules can interact with it in two ways, depending on what is * available: * * First, they can interface with it using a static (or singleton) instance * obtained via getInstance(). These singleton instances have no context in a * particular piece of code; they are used for methods that would otherwise be * static if we could look up static instances. It is from these instances of * Instruction that methods such as getNewInstance() and execute() are most * likely to be called (though they are still valid for other instances, it is * the static instance which will be most handy). * * Second, modules can interface with Instructions that were pulled from code. * These instances of Instruction are obtained using the static method * Instruction.parse(). It is for these instances of Instruction that the * check() and assemble() methods are valid. * * @author Josh Ventura * @date Apr 4, 2012 1:39:03 AM */ public abstract class Instruction { /** * @author Josh Ventura * @date Apr 8, 2012; 1:51:01 AM * @modified Apr 17, 2012; 6:43:11 PM: added value field and toString() function. - Noah */ public static class Operand { /** The operand keyword */ public String operand; /** The expression given to the operand */ public String expression; /** The value of the operand. */ public int value; /** * The position in the line at which the keyword for this operand * started */ public int keywordStartPosition; /** * The position in the line at which the value for this operand * started */ public int valueStartPosition; /** * @param op * The operand keyword. * @param exp * The expression. * @param key_sp * The index of the first character of this keyword's name in * the line from which it was parsed. * @param val_sp * The index of the first character of this keyword's value * in the line from which it was parsed. */ public Operand(String op, String exp, int key_sp, int val_sp) { operand = op; expression = exp; keywordStartPosition = key_sp; valueStartPosition = val_sp; } /** * @author Noah * @date Apr 17, 2012; 5:52:59 PM * @return The bit string of the value of this operand. * @specRef N/A */ @Override public String toString() { return Integer.toBinaryString(value); } } /** * @author Josh Ventura * @date Apr 5, 2012; 10:40:23 PM * @modified UNMODIFIED * @tested UNTESTED * @errors NO ERRORS REPORTED * @codingStandards Awaiting signature * @testingStandards Awaiting signature * @return A newly allocated instance of a particular child instruction. * @specRef N/A */ public abstract Instruction getNewInstance(); /** * An enumeration of constants that can be used as our usage kind. * * @author Josh Ventura */ public enum Usage { /** This item should not appear in the symbol table */ NONE, /** Reference to external label */ EXTERNAL, /** Preprocessor value */ EQUATE, /** Entry point */ ENTRY, /** A local label of some instruction */ LABEL, /** The name of this module */ PROGNAME } /** * An enumeration of ranges for operand values of type FC. * @author Noah * @date Apr 17, 2012; 10:20:27 PM */ public enum ConstantRange { /** DMP constant range.*/ RANGE_DMP(1,3), //[1,3] /** SHIFT constant range.*/ RANGE_SHIFT(0, 31), //[0, 31] /** 13 bit 2's complement range.*/ RANGE_13_TC(-4095, 4095), //[-2^12, (2^12) - 1] /** 16 bit 2's complement range.*/ RANGE_16_TC(-32768, 32767), //[-2^15, (2^15) - 1] /** 12 bit address range.*/ RANGE_ADDR(0, 4095); //[0, 4095] /** max value of constant. */ public int max; /** minimum value of constant. */ public int min; /** * constructs ConstantRange with a minimum value and maximum value. * @param min minimum value of constant operand. * @param max maximum value of constant operand. */ ConstantRange(int min, int max) { this.min = min; this.max = max; } } // ===================================================================== // == Members valid in the global instance, obtained with getInstance() // ===================================================================== /** * Get the operation identifier used to refer to this instruction, such as * "MOVD", "IADD", or "NUM". Literally, get the name of this instruction. * * @author Josh Ventura * @date Apr 5, 2012; 6:52:21 PM * @modified UNMODIFIED * @tested UNTESTED * @errors NO ERRORS REPORTED * @codingStandards Awaiting signature * @testingStandards Awaiting signature * @return The name of this instruction. * @specRef N/A */ abstract public String getOpId(); /** * The byte code that identifies this instruction to the machine. It should * be possible to compare against this instruction by ANDing the complete * instruction by this opcode, and then comparing the result to this opcode. * * This is NOT a complete instruction opcode, just the segment that * identifies WHICH instruction is affiliated. To get the complete * instruction's opcode, use assemble(). * * @author Josh Ventura * @date Apr 5, 2012; 6:53:30 PM * @modified UNMODIFIED * @tested UNTESTED * @errors NO ERRORS REPORTED * @codingStandards Awaiting signature * @testingStandards Awaiting signature * @return The byte code identifying this instruction. * @specRef N/A */ abstract public int getOpcode(); /** * Get the location counter of the instruction following this instruction, * where the location counter at this instruction is provided as an * argument. * * @author Josh Ventura * @date Apr 5, 2012; 11:36:32 PM * @modified Apr 8, 2012; 1:43:59 PM: Renamed method and * @tested UNTESTED * @errors NO ERRORS REPORTED * @codingStandards Awaiting signature * @testingStandards Awaiting signature * @param lc * The original value of the location counter. * @param mod * The Module which can be used to look up symbols if needed. * @return The value of the location counter for the next instruction. * @specRef N/A: See specification reference for individual Instance * subclasses. */ abstract public int getNewLC(int lc, Module mod); // ===================================================================== // == Members valid with new instances ================================= // ===================================================================== /** Any label that was given before this instruction. */ public String label; /** The line counter index at which this instruction was read. */ public int lc; /** A hash map of any instructions encountered. */ public ArrayList<Operand> operands = new ArrayList<Operand>(); /** The type of this instruction as one of the {@link Usage} constants. */ public Usage usage = Usage.NONE; /** line number in source file. */ public int lineNum; /** original source line. */ public String origSrcLine; /** * Trivial utility method to check if an operand is used in this particular * instruction. * * @author Josh Ventura * @param op * The operand to check for. * @return True if this Instruction contains at least one instance of the * given operand, false otherwise. * @date Apr 8, 2012; 1:35:52 AM */ public boolean hasOperand(String op) { for (int i = 0; i < operands.size(); i++) if (operands.get(i).operand.equals(op)) return true; return false; } /** * Trivial utility method to get the number of times an operand is used * in this particular instruction. * * @author Josh Ventura * @param op * The operand to check for. * @return The number of times the given operand is given for this * Instruction. * @date Apr 8, 2012; 1:35:52 AM */ public int countOperand(String op) { int count = 0; for (int i = 0; i < operands.size(); i++) if (operands.get(i).operand.equals(op)) ++count; return count; } /** * Trivial utility method to get the expression of a given operand. * * @author Josh Ventura * @param op * The operand to check for. * @return The expression given to the operand. * @date Apr 8, 2012; 1:35:52 AM */ public String getOperand(String op) { for (int i = 0; i < operands.size(); i++) if (operands.get(i).operand.equals(op)) return operands.get(i).expression; return null; } /** * Trivial utility method to get an Operand by its name. * * @author Josh Ventura * @param op * The operand to check for. * @return The complete operand. * @date Apr 15, 2012; 11:59:07 AM */ public Operand getOperandData(String op) { for (int i = 0; i < operands.size(); i++) if (operands.get(i).operand.equals(op)) return operands.get(i); return null; } /** * Trivial utility method to get the expression of the Nth occurrence a * given operand. * * @author Josh Ventura * @param op * The operand to check for. * @param indx * The number of matching operands to skip. * @return The expression given to the operand. * @date Apr 8, 2012; 1:35:52 AM */ public String getOperand(String op, int indx) { for (int i = 0; i < operands.size(); i++) if (operands.get(i).operand.equals(op)) if (--indx <= 0) return operands.get(i).expression; return null; } /** * Trivial utility method to get the Nth occurrence an Operand with a * given name. * * @author Josh Ventura * @param op * The operand to check for. * @param indx * The number of matching operands to skip. * @return The complete Operand. * @date Apr 8, 2012; 1:35:52 AM */ public Operand getOperandData(String op, int indx) { for (int i = 0; i < operands.size(); i++) if (operands.get(i).operand.equals(op)) if (--indx <= 0) return operands.get(i); return null; } /** * @author Josh Ventura * @date Apr 13, 2012; 8:20:18 PM * @modified UNMODIFIED * @tested UNTESTED * @errors NO ERRORS REPORTED * @codingStandards Awaiting signature * @testingStandards Awaiting signature * @param expectedOperands * All expected operands. * @return True if our operands match the expected operands precisely * (except for order), false otherwise. */ boolean matchOperands(String... expectedOperands) { HashMap<String, Integer> expOps = new HashMap<String, Integer>(); // Populate our hash map with all expected operands, by the number // of operands we expect to see. for (String opr : expectedOperands) { Integer ov = expOps.put(opr, new Integer(1)); if (ov != null) expOps.put(opr, ov + 1); } // Remove operands from that map as they are matched in this. for (int i = 0; i < operands.size(); i++) { Integer remaining = expOps.get(operands.get(i).operand); // If this operand was not in our map, we don't have a match. if (remaining == null) return false; // Otherwise, remove it (or one of it). if (remaining == 1) expOps.remove(operands.get(i)); else expOps.put(operands.get(i).operand, remaining - 1); } // If there is anything left in expOps, we have missing operands. if (expOps.size() > 0) return false; // Seems we have a match. return true; } /** * Parse a string containing the operands of an instruction, storing the * operands locally. * * If the given code does not contain an instruction, null is returned. * * If the instruction is not concluded on the given line, this method will * throw an IOException with the message "RAL". "RAL" is short for "Request * Another Line"; the caller should read an additional line from the input, * append it to the string that was passed to the instance of this method * that generated the "RAL" exception, and then pass the concatenated string * back to this method to obtain the complete Instruction. This can happen * any number of times in sequence. * * @author Josh Ventura * @date Apr 4, 2012; 1:40:21 AM * @modified Apr 5, 2012: 10:02:26 PM: Wrote body. * * Apr 6, 2012; 11:04:12 AM: Modified behavior for incomplete * lines to more gracefully account for non-operational lines. * * Apr 7, 2012; 12:32:17 AM: Completed first working draft; more * instruction classes required to test properly. * * Apr 8, 2012; 12:11:32 AM: Added usage information to output * Instructions. * * Apr 15, 2012; 10:29:03 AM: Changed to allow spaces before * colons as well as after them. Fixes bug in which quotes in * labels are parsed as strings when in operand values. * * Apr 15, 2012; 12:14:28 PM: Added tracking of operand locations * relative to the line on which they are used. Refactored operand * loop. * @tested Apr 7, 2012; 12:52:43 AM: Tested with basic MOVD codes, given * various kinds of expressions. While more instructions are * necessary to get a full idea of whether or not this code is * working, for the time being, it seems to function as required. * @errors NO ERRORS REPORTED * @codingStandards Awaiting signature * @testingStandards Awaiting signature * @param line * A String containing the line of code to be parsed for an * Instruction. * @return A new Instruction as defined in the given line of URBAN-ASM code, * or null if the line was syntactically correct but did not contain * an instruction. * @throws IOException * Throws an IOException with the message "RAL" when the * instruction is not concluded in the given string. The caller * should re-invoke this method with the original parameter * suffixed with the next line in the file. * @throws URBANSyntaxException * Thrown when a syntax error occurs. * @specRef S2.1 * @specRef S4.1 */ public static final Instruction parse(String line) throws IOException, URBANSyntaxException { int i = 0; // Skip leading whitespace and check boundaries. if (i >= line.length()) // If the line is empty, return null; // Then there's no point asking for another. while (Character.isWhitespace(line.charAt(i))) if (++i >= line.length()) // If the line is empty except whitespace, return null; // Then there's no point asking for another. // Exit if comment line. if (line.charAt(i) == ';') // If the line is just a comment, return new Comment(line.substring(++i)); // From here on out, we assume there is a valid instruction on this line // which may or may not expand to other lines. // Read in label and instruction data. String label = IOFormat.readLabel(line, i); // Read in a label String instruction; // Check if we are at an instruction or a label if (Assembler.instructions.containsKey(label.toUpperCase())) { i += label.length(); // Skip the label instruction = label; label = null; } else { if (i != 0) throw new URBANSyntaxException(makeError("labelNotCol0", label, (IOFormat.isAlpha(label) ? "known" : "valid")), i); // Skip the label we read earlier i += label.length(); if (i >= line.length()) throw new IOException("RAL"); if (!Character.isWhitespace(line.charAt(i))) - throw new URBANSyntaxException(makeError("unexSymFollow", "" + throw new URBANSyntaxException(makeError("unexpSymFollow", "" + line.charAt(i), "label"), i); while (++i < line.length() && Character.isWhitespace(line.charAt(i))); if (i >= line.length()) throw new IOException("RAL"); instruction = IOFormat.readLabel(line, i); // Read instruction now if (!Assembler.instructions.containsKey(instruction.toUpperCase())) { if (IOFormat.isAlpha(instruction)) throw new URBANSyntaxException(makeError("instrUnknown", instruction), i); throw new URBANSyntaxException(makeError("instrInvalid", instruction), i); } i += instruction.length(); } if (i >= line.length()) throw new IOException("RAL2"); // Request another line // So, now we know a bit about our instruction. Instruction res, resp; resp = Assembler.instructions.get(instruction.toUpperCase()); res = resp.getNewInstance(); res.label = label; // Skip whitespace between instruction and operands. while (Character.isWhitespace(line.charAt(i))) { if (++i >= line.length()) // If we overrun this line looking, throw new IOException("RAL3"); // Request another line. } // Our method can now handle a number of operand instructions. while (line.charAt(i) != ';') { // All operand keywords contain only letters. if (!Character.isLetter(line.charAt(i))) throw new URBANSyntaxException(makeError("expectOpBefore", "" + line.charAt(i)), i); // Isolate the keyword final int key_sp = i; while (Character.isLetter(line.charAt(++i))); String operand = line.substring(key_sp, i); if (!Assembler.keyWords.contains(operand.toUpperCase())) throw new URBANSyntaxException( makeError("notOperand", operand), i); if (Character.isWhitespace(line.charAt(i))) do if (++i >= line.length()) throw new IOException("RAL4"); while (Character.isWhitespace(line.charAt(i))); if (line.charAt(i) != ':') throw new URBANSyntaxException(makeError("expectOpColon", operand), i); if (++i >= line.length()) throw new IOException("RAL5"); while (Character.isWhitespace(line.charAt(i))) if (++i >= line.length()) throw new IOException("RAL6"); final int val_sp = i; while (line.charAt(i) != ';' && line.charAt(i) != ',') // Search. { // Don't get bitten by oddly formatted labels. if (Character.isLetter(line.charAt(i))) { i += IOFormat.readLabel(line, i).length(); continue; } /* Don't get tripped up by string literals. * Specification says that the single quote is the delimiter. * This loop searches for a matching quote, while observing * escape sequences. When a backslash is encountered, the * character proceeding it is skipped. We can prove the validity * of this design by examining its three basic cases: * * If the escape sequence is \', the quote is skipped, and the * behavior is correct. * * If the escape sequence is \\, the second slash is skipped, * and cannot accidentally escape another character, so '\\' is * correct. * * In any other case, \r \n \xFF \100, the proceeding character * is immaterial, and can safely be skipped. */ if (line.charAt(i) == '\'') { while (++i < line.length() && line.charAt(i) != '\'') if (line.charAt(i) == '\\') ++i; // Make sure we didn't just run out of line if (++i >= line.length()) throw new IOException("RAL8"); continue; } if (!Character.isWhitespace(line.charAt(i)) && !Character.isDigit(line.charAt(i))) switch (line.charAt(i)) // Figure out what we have { case '+': case '-': case '*': case '/': break; default: throw new URBANSyntaxException(makeError("unexpSymOp", "" + line.charAt(i), operand), i); } // Whatever we're at isn't our problem. if (++i >= line.length()) // If we overrun this line looking, throw new IOException("RAL7"); // Request another line. } String exp = line.substring(val_sp, i); res.operands.add(new Operand(operand.toUpperCase(), exp, key_sp, val_sp)); // Check if we have more work to do. if (line.charAt(i) == ',') do if (++i >= line.length()) throw new IOException("RAL9"); while (Character.isWhitespace(line.charAt(i))); } res.usage = resp.usage; if (res.usage == Usage.NONE && res.label != null) res.usage = Usage.LABEL; return res; } /** * Check if the token is semantically correct. This means that it has the * correct number of operands and the correct kinds of operands. * Also, checks whether operand values are within range. * * @author Josh Ventura * @modified Apr 14, 2012; 12:00 PM: Added error handler to parameters. * @errors NO ERRORS REPORTED * @codingStandards This method is abstract. * @testingStandards This method is abstract. * @param hErr * An error handler which will receive any error or warning * messages. * @param module TODO * @return Returns whether the instruction is semantically correct. * @date Apr 4, 2012; 01:40:29AM */ public abstract boolean check(ErrorHandler hErr, Module module); /** * Checks for lexical correctness; called immediately after construction. * * @author Josh Ventura * @modified Apr 14, 2012; 12:00 PM: Added error handler to parameters. * @errors NO ERRORS REPORTED * @codingStandards This method is abstract. * @testingStandards This method is abstract. * @param hErr * An error handler which will receive any error or warning * messages. * @param module TODO * @return Returns whether the instruction is semantically correct. * @date Apr 4, 2012; 01:40:29AM */ public abstract boolean immediateCheck(ErrorHandler hErr, Module module); /** * Used to check if this Instruction is actually a directive. * @author Josh Ventura * @date Apr 16, 2012; 8:24:58 PM * @modified UNMODIFIED * @tested UNTESTED * @errors NO ERRORS REPORTED * @codingStandards Awaiting signature * @testingStandards Awaiting signature * @return Returns whether this Instruction is actually a directive * @specRef N/A */ public abstract boolean isDirective(); /** * Assemble this instruction to byte code after it has been checked. * * @author Josh Ventura * @date Apr 4, 2012; 1:40:52 AM * @modified UNMODIFIED * @tested This method is abstract. * @errors NO ERRORS REPORTED * @codingStandards This method is abstract. * @testingStandards This method is abstract. * @return Returns an array of getWordCount() integers representing this * instruction's byte code. */ public abstract int[] assemble(); /** * @author Josh Ventura * @date Apr 4, 2012; 9:11:51 AM * @modified UNMODIFIED * @tested This method is abstract. * @errors NO ERRORS REPORTED * @codingStandards This method is abstract. * @testingStandards This method is abstract. * @param instruction * The byte code of the instruction to be executed. */ public abstract void execute(int instruction); /** * Returns a string representation of Instruction: * origSourceLine + "Line number: " + instr.LineNum + " " + LC: " + lc + " " + "Label: " + label + ",\n" * + "instruction/Directive: " + instr.getOpID() + " " + Binary Equivalent: " + binEquiv + "\n" * + "operand " + i + operandKeyWord + ":" + operandValue + "Binary Equivalent: " + operBinEquiv; * where if instr does not have a label, then label = "", * else label = instr.label, and * if instr is a directive and thus has no opcode, then binEquiv = "------", * else binEquiv = instr.opcode in binary format, and * i represents the ith operand of instr, and * operandKeyword = the key word for the ith operand; * operandValue = the value associated w the operand with operandKeyword keyword for the ith operand, and * origSourceLine = instr.origSrcLine, * operBinEquiv = string representation of Operand. * and lc = instr.lc displayed in hexadecimal w/ 4 bits. * @author Josh Ventura * @date Apr 5, 2012; 9:37:34 PM * @modified Apr 7 2012; 12:39:44 AM: Corrected formatting for printing * multiple operands (added a comma between them). -Josh * Apr 17, 2012; 6:39:41 PM: changed definition of toString to breakdown of Instruction. -Noah. * @tested Apr 7 2012; 12:38:06 AM: Tested with basic MOVD instructions. * @errors NO ERRORS REPORTED * @codingStandards Awaiting signature * @testingStandards Awaiting signature * @return Returns a string representation of Instruction. * @specRef N/A */ @Override public String toString() { String rep = ""; rep = rep + "original source line: " + this.origSrcLine + "\n"; // opcode. String binEquiv = IOFormat.formatBinInteger(this.getOpcode(), 6); String lc = IOFormat.formatHexInteger(this.lc, 4); String label = this.label; // instr is a directive and thus has no opcode. if (this.getOpcode() == 0xFFFFFFFF) { binEquiv = "------"; // so binary equivalent is non-existant. } // if the instruction has no label if (this.label == null) { label = ""; // no label to print. // also, can't print "------" b/c label may be "------". } String instrBreak = "Line number: " + this.lineNum + " " + "LC: " + lc + " " + "Label: " + label + ",\n" + "instruction/Directive: " + this.getOpId() + " " + "Binary Equivalent: " + binEquiv + "\n"; Iterator<Operand> operandIt = operands.iterator(); int i = 1; while (operandIt.hasNext()) { Operand oprnd = operandIt.next(); instrBreak = instrBreak + "Operand " + i + ": " + oprnd.operand + ":" + oprnd.expression + "\tBinary Equivalent: " + oprnd.toString() + "\n"; for(String error : errors) { instrBreak = instrBreak + error + "\n"; } i++; } instrBreak = instrBreak + "\n"; rep = rep + instrBreak; return rep; } /** * Default constructor. The constructor is protected so that the parse() * method must be used externally to obtain an Instruction. */ protected Instruction() {} /** * Default constructor. The constructor is protected so that the parse() * method must be used externally to obtain an Instruction. * * @param iname * The name of this instruction as returned by getOpId(). * @param opcode * The byte code for this instruction as returned by getOpCode(). */ protected Instruction(String iname, int opcode) { Assembler.instructions.put(iname, this); Assembler.byteCodes.put(opcode, this); } // ------------------------------------------------------------------ // --- Error Handling ----------------------------------------------- // ------------------------------------------------------------------ /** Any errors reported through our handler */ ArrayList<String> errors = new ArrayList<String>(); /** * @author Josh Ventura * @date Apr 18, 2012; 3:13:22 AM * @param hErr The error handler which will be invoked in chain. * @return A wrapper to the error handler which also logs errors to this. */ public final ErrorHandler getHErr(ErrorHandler hErr) { return new WrapHErr(hErr); } /** * Wrapper class to an error handler that copies errors into this. * @author Josh Ventura * @date Apr 18, 2012; 3:10:59 AM */ class WrapHErr implements ErrorHandler { /** The error handler we are intercepting messages to. */ private final ErrorHandler wrapped; /** * Adds error to our list and calls wrapped instance. * * @see assemblernator.ErrorReporting.ErrorHandler#reportError(java.lang.String, int, int) */ @Override public void reportError(String err, int line, int pos) { errors.add("ERROR: " + err); wrapped.reportError(err, line, pos); } /** * Adds warning to our list and calls wrapped instance. * * @see assemblernator.ErrorReporting.ErrorHandler#reportWarning(java.lang.String, int, int) */ @Override public void reportWarning(String warn, int line, int pos) { errors.add("Warning: " + warn); wrapped.reportWarning(warn, line, pos); } /** * @param hErr The error handler to wrap reports to. */ WrapHErr(ErrorHandler hErr) { wrapped = hErr; } } }
true
true
public static final Instruction parse(String line) throws IOException, URBANSyntaxException { int i = 0; // Skip leading whitespace and check boundaries. if (i >= line.length()) // If the line is empty, return null; // Then there's no point asking for another. while (Character.isWhitespace(line.charAt(i))) if (++i >= line.length()) // If the line is empty except whitespace, return null; // Then there's no point asking for another. // Exit if comment line. if (line.charAt(i) == ';') // If the line is just a comment, return new Comment(line.substring(++i)); // From here on out, we assume there is a valid instruction on this line // which may or may not expand to other lines. // Read in label and instruction data. String label = IOFormat.readLabel(line, i); // Read in a label String instruction; // Check if we are at an instruction or a label if (Assembler.instructions.containsKey(label.toUpperCase())) { i += label.length(); // Skip the label instruction = label; label = null; } else { if (i != 0) throw new URBANSyntaxException(makeError("labelNotCol0", label, (IOFormat.isAlpha(label) ? "known" : "valid")), i); // Skip the label we read earlier i += label.length(); if (i >= line.length()) throw new IOException("RAL"); if (!Character.isWhitespace(line.charAt(i))) throw new URBANSyntaxException(makeError("unexSymFollow", "" + line.charAt(i), "label"), i); while (++i < line.length() && Character.isWhitespace(line.charAt(i))); if (i >= line.length()) throw new IOException("RAL"); instruction = IOFormat.readLabel(line, i); // Read instruction now if (!Assembler.instructions.containsKey(instruction.toUpperCase())) { if (IOFormat.isAlpha(instruction)) throw new URBANSyntaxException(makeError("instrUnknown", instruction), i); throw new URBANSyntaxException(makeError("instrInvalid", instruction), i); } i += instruction.length(); } if (i >= line.length()) throw new IOException("RAL2"); // Request another line // So, now we know a bit about our instruction. Instruction res, resp; resp = Assembler.instructions.get(instruction.toUpperCase()); res = resp.getNewInstance(); res.label = label; // Skip whitespace between instruction and operands. while (Character.isWhitespace(line.charAt(i))) { if (++i >= line.length()) // If we overrun this line looking, throw new IOException("RAL3"); // Request another line. } // Our method can now handle a number of operand instructions. while (line.charAt(i) != ';') { // All operand keywords contain only letters. if (!Character.isLetter(line.charAt(i))) throw new URBANSyntaxException(makeError("expectOpBefore", "" + line.charAt(i)), i); // Isolate the keyword final int key_sp = i; while (Character.isLetter(line.charAt(++i))); String operand = line.substring(key_sp, i); if (!Assembler.keyWords.contains(operand.toUpperCase())) throw new URBANSyntaxException( makeError("notOperand", operand), i); if (Character.isWhitespace(line.charAt(i))) do if (++i >= line.length()) throw new IOException("RAL4"); while (Character.isWhitespace(line.charAt(i))); if (line.charAt(i) != ':') throw new URBANSyntaxException(makeError("expectOpColon", operand), i); if (++i >= line.length()) throw new IOException("RAL5"); while (Character.isWhitespace(line.charAt(i))) if (++i >= line.length()) throw new IOException("RAL6"); final int val_sp = i; while (line.charAt(i) != ';' && line.charAt(i) != ',') // Search. { // Don't get bitten by oddly formatted labels. if (Character.isLetter(line.charAt(i))) { i += IOFormat.readLabel(line, i).length(); continue; } /* Don't get tripped up by string literals. * Specification says that the single quote is the delimiter. * This loop searches for a matching quote, while observing * escape sequences. When a backslash is encountered, the * character proceeding it is skipped. We can prove the validity * of this design by examining its three basic cases: * * If the escape sequence is \', the quote is skipped, and the * behavior is correct. * * If the escape sequence is \\, the second slash is skipped, * and cannot accidentally escape another character, so '\\' is * correct. * * In any other case, \r \n \xFF \100, the proceeding character * is immaterial, and can safely be skipped. */ if (line.charAt(i) == '\'') { while (++i < line.length() && line.charAt(i) != '\'') if (line.charAt(i) == '\\') ++i; // Make sure we didn't just run out of line if (++i >= line.length()) throw new IOException("RAL8"); continue; } if (!Character.isWhitespace(line.charAt(i)) && !Character.isDigit(line.charAt(i))) switch (line.charAt(i)) // Figure out what we have { case '+': case '-': case '*': case '/': break; default: throw new URBANSyntaxException(makeError("unexpSymOp", "" + line.charAt(i), operand), i); } // Whatever we're at isn't our problem. if (++i >= line.length()) // If we overrun this line looking, throw new IOException("RAL7"); // Request another line. } String exp = line.substring(val_sp, i); res.operands.add(new Operand(operand.toUpperCase(), exp, key_sp, val_sp)); // Check if we have more work to do. if (line.charAt(i) == ',') do if (++i >= line.length()) throw new IOException("RAL9"); while (Character.isWhitespace(line.charAt(i))); } res.usage = resp.usage; if (res.usage == Usage.NONE && res.label != null) res.usage = Usage.LABEL; return res; }
public static final Instruction parse(String line) throws IOException, URBANSyntaxException { int i = 0; // Skip leading whitespace and check boundaries. if (i >= line.length()) // If the line is empty, return null; // Then there's no point asking for another. while (Character.isWhitespace(line.charAt(i))) if (++i >= line.length()) // If the line is empty except whitespace, return null; // Then there's no point asking for another. // Exit if comment line. if (line.charAt(i) == ';') // If the line is just a comment, return new Comment(line.substring(++i)); // From here on out, we assume there is a valid instruction on this line // which may or may not expand to other lines. // Read in label and instruction data. String label = IOFormat.readLabel(line, i); // Read in a label String instruction; // Check if we are at an instruction or a label if (Assembler.instructions.containsKey(label.toUpperCase())) { i += label.length(); // Skip the label instruction = label; label = null; } else { if (i != 0) throw new URBANSyntaxException(makeError("labelNotCol0", label, (IOFormat.isAlpha(label) ? "known" : "valid")), i); // Skip the label we read earlier i += label.length(); if (i >= line.length()) throw new IOException("RAL"); if (!Character.isWhitespace(line.charAt(i))) throw new URBANSyntaxException(makeError("unexpSymFollow", "" + line.charAt(i), "label"), i); while (++i < line.length() && Character.isWhitespace(line.charAt(i))); if (i >= line.length()) throw new IOException("RAL"); instruction = IOFormat.readLabel(line, i); // Read instruction now if (!Assembler.instructions.containsKey(instruction.toUpperCase())) { if (IOFormat.isAlpha(instruction)) throw new URBANSyntaxException(makeError("instrUnknown", instruction), i); throw new URBANSyntaxException(makeError("instrInvalid", instruction), i); } i += instruction.length(); } if (i >= line.length()) throw new IOException("RAL2"); // Request another line // So, now we know a bit about our instruction. Instruction res, resp; resp = Assembler.instructions.get(instruction.toUpperCase()); res = resp.getNewInstance(); res.label = label; // Skip whitespace between instruction and operands. while (Character.isWhitespace(line.charAt(i))) { if (++i >= line.length()) // If we overrun this line looking, throw new IOException("RAL3"); // Request another line. } // Our method can now handle a number of operand instructions. while (line.charAt(i) != ';') { // All operand keywords contain only letters. if (!Character.isLetter(line.charAt(i))) throw new URBANSyntaxException(makeError("expectOpBefore", "" + line.charAt(i)), i); // Isolate the keyword final int key_sp = i; while (Character.isLetter(line.charAt(++i))); String operand = line.substring(key_sp, i); if (!Assembler.keyWords.contains(operand.toUpperCase())) throw new URBANSyntaxException( makeError("notOperand", operand), i); if (Character.isWhitespace(line.charAt(i))) do if (++i >= line.length()) throw new IOException("RAL4"); while (Character.isWhitespace(line.charAt(i))); if (line.charAt(i) != ':') throw new URBANSyntaxException(makeError("expectOpColon", operand), i); if (++i >= line.length()) throw new IOException("RAL5"); while (Character.isWhitespace(line.charAt(i))) if (++i >= line.length()) throw new IOException("RAL6"); final int val_sp = i; while (line.charAt(i) != ';' && line.charAt(i) != ',') // Search. { // Don't get bitten by oddly formatted labels. if (Character.isLetter(line.charAt(i))) { i += IOFormat.readLabel(line, i).length(); continue; } /* Don't get tripped up by string literals. * Specification says that the single quote is the delimiter. * This loop searches for a matching quote, while observing * escape sequences. When a backslash is encountered, the * character proceeding it is skipped. We can prove the validity * of this design by examining its three basic cases: * * If the escape sequence is \', the quote is skipped, and the * behavior is correct. * * If the escape sequence is \\, the second slash is skipped, * and cannot accidentally escape another character, so '\\' is * correct. * * In any other case, \r \n \xFF \100, the proceeding character * is immaterial, and can safely be skipped. */ if (line.charAt(i) == '\'') { while (++i < line.length() && line.charAt(i) != '\'') if (line.charAt(i) == '\\') ++i; // Make sure we didn't just run out of line if (++i >= line.length()) throw new IOException("RAL8"); continue; } if (!Character.isWhitespace(line.charAt(i)) && !Character.isDigit(line.charAt(i))) switch (line.charAt(i)) // Figure out what we have { case '+': case '-': case '*': case '/': break; default: throw new URBANSyntaxException(makeError("unexpSymOp", "" + line.charAt(i), operand), i); } // Whatever we're at isn't our problem. if (++i >= line.length()) // If we overrun this line looking, throw new IOException("RAL7"); // Request another line. } String exp = line.substring(val_sp, i); res.operands.add(new Operand(operand.toUpperCase(), exp, key_sp, val_sp)); // Check if we have more work to do. if (line.charAt(i) == ',') do if (++i >= line.length()) throw new IOException("RAL9"); while (Character.isWhitespace(line.charAt(i))); } res.usage = resp.usage; if (res.usage == Usage.NONE && res.label != null) res.usage = Usage.LABEL; return res; }
diff --git a/src/main/java/syam/likes/listener/BlockListener.java b/src/main/java/syam/likes/listener/BlockListener.java index 5dd5f7f..9bc0e38 100644 --- a/src/main/java/syam/likes/listener/BlockListener.java +++ b/src/main/java/syam/likes/listener/BlockListener.java @@ -1,76 +1,76 @@ /** * Likes - Package: syam.likes.listener * Created: 2012/10/01 6:23:26 */ package syam.likes.listener; import java.util.logging.Logger; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.SignChangeEvent; import syam.likes.LikesPlugin; import syam.likes.permission.Perms; import syam.likes.util.Actions; /** * BlockListener (BlockListener.java) * @author syam(syamn) */ public class BlockListener implements Listener { public final static Logger log = LikesPlugin.log; private static final String logPrefix = LikesPlugin.logPrefix; private static final String msgPrefix = LikesPlugin.msgPrefix; private final LikesPlugin plugin; public BlockListener(final LikesPlugin plugin){ this.plugin = plugin; } // 看板を設置した @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onSignChange(final SignChangeEvent event){ Player player = event.getPlayer(); Block block = event.getBlock(); BlockState state = event.getBlock().getState(); if (state instanceof Sign){ Sign sign = (Sign)state; /* [Likes] 特殊看板 */ if (event.getLine(0).toLowerCase().indexOf("[likes]") != -1 || event.getLine(0).toLowerCase().indexOf("[like]") != -1){ // 権限チェック if (!Perms.PLACESIGN.has(player)){ event.setLine(0, "§c[Likes]"); event.setLine(1, "Perm Denied :("); Actions.message(player, "&cYou don't have permission to use this!"); return; } // 内容チェック boolean err = false; // エラーフラグ // 1行目の文字色 if (err){ event.setLine(0, "§c[Likes]"); }else{ event.setLine(0, "§a[Likes]"); - event.setLine(2, "§e== READY =="); - event.setLine(3, "§7Placed by"); - if (player.getName().length() > 15) { event.setLine(4, player.getName().substring(0, 13) + ".."); } - else { event.setLine(4, player.getName()); } + event.setLine(1, "§e== READY =="); + event.setLine(2, "§7Placed by"); + if (player.getName().length() > 15) { event.setLine(3, player.getName().substring(0, 13) + ".."); } + else { event.setLine(3, player.getName()); } Actions.message(player, "&aLikes看板を設置しました!"); } } } } }
true
true
public void onSignChange(final SignChangeEvent event){ Player player = event.getPlayer(); Block block = event.getBlock(); BlockState state = event.getBlock().getState(); if (state instanceof Sign){ Sign sign = (Sign)state; /* [Likes] 特殊看板 */ if (event.getLine(0).toLowerCase().indexOf("[likes]") != -1 || event.getLine(0).toLowerCase().indexOf("[like]") != -1){ // 権限チェック if (!Perms.PLACESIGN.has(player)){ event.setLine(0, "§c[Likes]"); event.setLine(1, "Perm Denied :("); Actions.message(player, "&cYou don't have permission to use this!"); return; } // 内容チェック boolean err = false; // エラーフラグ // 1行目の文字色 if (err){ event.setLine(0, "§c[Likes]"); }else{ event.setLine(0, "§a[Likes]"); event.setLine(2, "§e== READY =="); event.setLine(3, "§7Placed by"); if (player.getName().length() > 15) { event.setLine(4, player.getName().substring(0, 13) + ".."); } else { event.setLine(4, player.getName()); } Actions.message(player, "&aLikes看板を設置しました!"); } } } }
public void onSignChange(final SignChangeEvent event){ Player player = event.getPlayer(); Block block = event.getBlock(); BlockState state = event.getBlock().getState(); if (state instanceof Sign){ Sign sign = (Sign)state; /* [Likes] 特殊看板 */ if (event.getLine(0).toLowerCase().indexOf("[likes]") != -1 || event.getLine(0).toLowerCase().indexOf("[like]") != -1){ // 権限チェック if (!Perms.PLACESIGN.has(player)){ event.setLine(0, "§c[Likes]"); event.setLine(1, "Perm Denied :("); Actions.message(player, "&cYou don't have permission to use this!"); return; } // 内容チェック boolean err = false; // エラーフラグ // 1行目の文字色 if (err){ event.setLine(0, "§c[Likes]"); }else{ event.setLine(0, "§a[Likes]"); event.setLine(1, "§e== READY =="); event.setLine(2, "§7Placed by"); if (player.getName().length() > 15) { event.setLine(3, player.getName().substring(0, 13) + ".."); } else { event.setLine(3, player.getName()); } Actions.message(player, "&aLikes看板を設置しました!"); } } } }
diff --git a/src/java/uk/tripbrush/service/PDFService.java b/src/java/uk/tripbrush/service/PDFService.java index 3165cc7..8cf143e 100644 --- a/src/java/uk/tripbrush/service/PDFService.java +++ b/src/java/uk/tripbrush/service/PDFService.java @@ -1,781 +1,781 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package uk.tripbrush.service; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfImportedPage; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.ArrayList; import java.util.Calendar; import java.util.Iterator; import java.util.List; import uk.tripbrush.model.core.Plan; import uk.tripbrush.model.pdf.Header; import uk.tripbrush.model.travel.Attraction; import uk.tripbrush.model.travel.Event; import uk.tripbrush.util.DateUtil; import uk.tripbrush.util.StringUtil; import uk.tripbrush.view.AttractionOpenView; import uk.tripbrush.view.MResult; /** * * @author Samir */ public class PDFService { public static String createPlan(Plan plan) throws Exception { createTitlePage(plan); createCalendar(plan); for (int datecounter = 0; datecounter < plan.getLength(); datecounter++) { createSubTitlePage(plan,datecounter); createEvents(plan,datecounter); } createLastPage(plan); return merge(plan); } public static void createTitlePage(Plan plan) throws Exception { FileOutputStream fos = new FileOutputStream(new File(ConfigService.getRoot() + "title" + plan.getId() + ".pdf")); Document document = new Document(PageSize.A4, 50, 50, 50, 50); document.open(); Rectangle area = new Rectangle(36, 24, 559, 802); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.setBoxSize("art", area); //writer.setPDFXConformance(PdfWriter.PDFX1A2001); Header event = new Header(plan.getTitle(),true); writer.setPageEvent(event); document.open(); int tableheight = 740; int tablewidth = 500; //create first page PdfPTable table = new PdfPTable(1); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.setTotalWidth(tablewidth); table.setLockedWidth(true); int[] widths = {1}; table.setWidths(widths); Paragraph destination = new Paragraph("Trip to " + plan.getLocation().getName()); destination.setAlignment(Element.ALIGN_CENTER); destination.getFont().setFamily("Arial"); destination.getFont().setSize(20); Paragraph date = new Paragraph("\n\n" + DateUtil.getFullDay(plan.getStartdate()) + "\n\nto\n\n" + DateUtil.getFullDay(plan.getEnddate())); date.getFont().setFamily("Arial"); date.setAlignment(Element.ALIGN_CENTER); date.getFont().setSize(16); PdfPCell titlecell = new PdfPCell(); titlecell.setBorder(Rectangle.BOX); titlecell.setHorizontalAlignment(Element.ALIGN_CENTER); titlecell.setVerticalAlignment(Element.ALIGN_MIDDLE); titlecell.setFixedHeight(tableheight); titlecell.addElement(destination); titlecell.addElement(date); table.addCell(titlecell); document.add(table); document.close(); } public static void createLastPage(Plan plan) throws Exception { FileOutputStream fos = new FileOutputStream(new File(ConfigService.getRoot() + "last" + plan.getId() + ".pdf")); Document document = new Document(PageSize.A4, 50, 50, 50, 50); document.open(); Rectangle area = new Rectangle(36, 24, 559, 802); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.setBoxSize("art", area); //writer.setPDFXConformance(PdfWriter.PDFX1A2001); Header event = new Header(plan.getTitle(),true); writer.setPageEvent(event); document.open(); int tableheight = 740; int tablewidth = 500; //create first page PdfPTable table = new PdfPTable(1); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.setTotalWidth(tablewidth); table.setLockedWidth(true); int[] widths = {1}; table.setWidths(widths); Paragraph destination = new Paragraph("TripBrush. Let's Paint!"); destination.setAlignment(Element.ALIGN_CENTER); destination.getFont().setFamily("Arial"); destination.getFont().setSize(20); PdfPCell titlecell = new PdfPCell(); titlecell.setBorder(Rectangle.BOX); titlecell.setHorizontalAlignment(Element.ALIGN_CENTER); titlecell.setVerticalAlignment(Element.ALIGN_MIDDLE); titlecell.setFixedHeight(tableheight); titlecell.addElement(destination); table.addCell(titlecell); document.add(table); document.close(); } public static void createSubTitlePage(Plan plan,int datecounter) throws Exception { FileOutputStream fos = new FileOutputStream(new File(ConfigService.getRoot() + "stitle" + plan.getId() + datecounter + ".pdf")); Document document = new Document(PageSize.A4, 50, 50, 50, 50); document.open(); Rectangle area = new Rectangle(36, 24, 559, 802); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.setBoxSize("art", area); //writer.setPDFXConformance(PdfWriter.PDFX1A2001); Header event = new Header(plan.getTitle()); writer.setPageEvent(event); document.open(); int tableheight = 740; int tablewidth = 500; //create first page PdfPTable table = new PdfPTable(1); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.setTotalWidth(tablewidth); table.setLockedWidth(true); int[] widths = {1}; table.setWidths(widths); Paragraph destination = new Paragraph("Trip to " + plan.getLocation().getName()); destination.setAlignment(Element.ALIGN_CENTER); destination.getFont().setFamily("Arial"); destination.getFont().setSize(20); Calendar cal = Calendar.getInstance(); cal.setTime(plan.getStartdate().getTime()); cal.add(Calendar.DAY_OF_MONTH, datecounter); Paragraph date = new Paragraph("\n\nDay" + (datecounter+1) + "\n\n" + DateUtil.getFullDay(cal)); date.getFont().setFamily("Arial"); date.setAlignment(Element.ALIGN_CENTER); date.getFont().setSize(16); PdfPCell titlecell = new PdfPCell(); titlecell.setBorder(Rectangle.BOX); titlecell.setHorizontalAlignment(Element.ALIGN_CENTER); titlecell.setVerticalAlignment(Element.ALIGN_MIDDLE); titlecell.setFixedHeight(tableheight); titlecell.addElement(destination); titlecell.addElement(date); table.addCell(titlecell); document.add(table); document.close(); } public static void createEvents(Plan plan,int datecounter) throws Exception { FileOutputStream fos = new FileOutputStream(new File(ConfigService.getRoot() + "events" + plan.getId() + datecounter + ".pdf")); Document document = new Document(PageSize.A4, 50, 50, 50, 50); document.open(); Rectangle area = new Rectangle(36, 24, 559, 802); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.setBoxSize("art", area); //writer.setPDFXConformance(PdfWriter.PDFX1A2001); Header event = new Header(plan.getTitle()); writer.setPageEvent(event); document.open(); int tableheight = 740; int tablewidth = 500; //create first page Calendar cal = Calendar.getInstance(); cal.setTime(plan.getStartdate().getTime()); cal.add(Calendar.DAY_OF_MONTH, datecounter); String date = DateUtil.getFullDay(cal); List<Event> todaysevents = plan.getEvents(cal); PdfPTable table = null; if (!todaysevents.isEmpty()) { int counter = 0; for (Event sevent: todaysevents) { table = new PdfPTable(2); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.setTotalWidth(tablewidth); table.setLockedWidth(true); int[] widths = {280,220}; table.setWidths(widths); Chunk datetitle = new Chunk(DateUtil.getFullDay(cal)); datetitle.setUnderline(0.1f,-2f); datetitle.getFont().setFamily("Arial"); datetitle.getFont().setSize(16); datetitle.getFont().setColor(51,102,00); PdfPCell datecell = new PdfPCell(); datecell.setBorder(Rectangle.NO_BORDER); datecell.addElement(datetitle); datecell.setColspan(2); Paragraph time = new Paragraph(sevent.getDuration()); time.getFont().setFamily("Arial"); time.getFont().setSize(14); PdfPCell timecell = new PdfPCell(time); timecell.setBorder(Rectangle.NO_BORDER); timecell.setColspan(2); Attraction attraction = sevent.getAttraction(); Paragraph eventname = new Paragraph(attraction.getName()); eventname.getFont().setFamily("Arial"); eventname.getFont().setSize(14); Paragraph eventdesc = new Paragraph(attraction.getDescription()); eventdesc.getFont().setFamily("Arial"); eventdesc.getFont().setSize(12); PdfPCell eventcell = new PdfPCell(); eventcell.addElement(eventname); eventcell.addElement(eventdesc); eventcell.setBorder(Rectangle.NO_BORDER); eventcell.setColspan(1); URL url = new URL(ConfigService.getUrl()+ "/includes/images/data/"+attraction.getImageFileName()); Image image = Image.getInstance(url); PdfPCell piccell = new PdfPCell(image); piccell.setBorder(Rectangle.NO_BORDER); piccell.setColspan(1); Paragraph eventhours = new Paragraph("Opening Hours"); eventhours.getFont().setFamily("Arial"); eventhours.getFont().setSize(14); CalendarService.loadAttractionTimes(plan, attraction); PdfPCell description = new PdfPCell(); description.addElement(eventhours); description.setBorder(Rectangle.NO_BORDER); description.setColspan(2); for (AttractionOpenView view: attraction.getOpeningTimes()) { Paragraph eventtimes = new Paragraph(DateUtil.getDay(view.getFrom())+" " + DateUtil.getTime(view.getFrom()) + "-"+ DateUtil.getTime(view.getTo())); eventtimes.getFont().setFamily("Arial"); eventtimes.getFont().setSize(12); description.addElement(eventtimes); } if (!StringUtil.isEmpty(sevent.getAttraction().getPhone())) { Paragraph eventphone = new Paragraph("Telephone: " + attraction.getPhone()); eventphone.getFont().setFamily("Arial"); eventphone.getFont().setSize(14); description.addElement(eventphone); } if (!StringUtil.isEmpty(sevent.getAttraction().getAddress())) { Paragraph eventaddress = new Paragraph("Address: " + attraction.getAddress()); eventaddress.getFont().setFamily("Arial"); eventaddress.getFont().setSize(14); description.addElement(eventaddress); } table.addCell(datecell); table.addCell(timecell); table.addCell(eventcell); table.addCell(piccell); table.addCell(description); document.add(table); document.newPage(); if (counter!=todaysevents.size()-1) { Event nextevent = todaysevents.get(counter+1); Attraction nextatt = nextevent.getAttraction(); //add directions page PdfPTable table1 = new PdfPTable(1); table1.getDefaultCell().setBorder(Rectangle.NO_BORDER); table1.setTotalWidth(tablewidth); table1.setLockedWidth(true); int[] widths3 = {1}; table1.setWidths(widths3); table1.addCell(datecell); Paragraph directions = new Paragraph("Directions from A. " + attraction.getName() + " to B. " + nextatt.getName()); directions.getFont().setFamily("Arial"); directions.getFont().setSize(14); PdfPCell dcell = new PdfPCell(directions); dcell.setBorder(Rectangle.NO_BORDER); dcell.setColspan(1); table1.addCell(dcell); String fpostcode = attraction.getPostcode().replaceAll(" ","")+",UK"; String tpostcode = nextatt.getPostcode().replaceAll(" ","")+",UK"; String wsearchUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + fpostcode + "&destination=" + tpostcode + "&sensor=false&mode=walking"; String response = Browser.getPage(wsearchUrl).toString(); int duration = Integer.parseInt(getLastData(response, "<duration>", "<value>", "</value>")); String durationt = "Walking Time: " + getLastData(response, "<duration>", "<text>", "</text>"); if (duration>60*(ConfigService.getMaxWalking())) { - String dsearchUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + fpostcode + "&destination=" + tpostcode + "&sensor=false"; + String dsearchUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + fpostcode + "&destination=" + tpostcode + "&sensor=false&mode=transit"; response = Browser.getPage(dsearchUrl).toString(); durationt = "Driving Time: " + getLastData(response, "<duration>", "<text>", "</text>"); } double latfrom = Double.parseDouble(getData(response,"<start_location>","<lat>","</lat>")); double lngfrom = Double.parseDouble(getData(response,"<start_location>","<lng>","</lng>")); double latto= Double.parseDouble(getLastData(response,"<end_location>","<lat>","</lat>")); double lngto = Double.parseDouble(getLastData(response,"<end_location>","<lng>","</lng>")); String polyline = getData(response,"<overview_polyline>","<points>","</points>"); PdfPCell instructions = new PdfPCell(); instructions.setBorder(Rectangle.NO_BORDER); - Paragraph p = new Paragraph("Written Directions (" + durationt + ")");; + Paragraph p = new Paragraph("Written Directions (" + durationt + ")"); instructions.addElement(p); String header = "<html_instructions>"; String headere = "</html_instructions>"; int index = 0; while (true) { int indexp = response.indexOf(header,index); int indexpe = response.indexOf(headere,indexp); if (indexp<index) break; String line = clean(response.substring(indexp+header.length(),indexpe)); p = new Paragraph(line); instructions.addElement(p); index = indexpe+1; } URL google = new URL("http://maps.googleapis.com/maps/api/staticmap?sensor=false&size=500x250&path=weight:3|color:red|enc:" + polyline + "&markers=label:A|" + latfrom + "," + lngfrom + "&markers=label:B|" + latto + "," + lngto); Image image1 = Image.getInstance(google); PdfPCell smap = new PdfPCell(image1); smap.setBorder(Rectangle.NO_BORDER); smap.setColspan(1); table1.addCell(smap); table1.addCell(instructions); document.add(table1); document.newPage(); } counter++; } } else { table = new PdfPTable(1); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.setTotalWidth(tablewidth); table.setLockedWidth(true); int[] widths2 = {1}; table.setWidths(widths2); Paragraph noact = new Paragraph("No Activities Planned"); noact.getFont().setFamily("Arial"); noact.setAlignment(Element.ALIGN_CENTER); noact.getFont().setSize(16); PdfPCell titlecell = new PdfPCell(); titlecell.setBorder(Rectangle.BOX); titlecell.setHorizontalAlignment(Element.ALIGN_CENTER); titlecell.setVerticalAlignment(Element.ALIGN_MIDDLE); titlecell.setFixedHeight(tableheight); titlecell.addElement(noact); table.addCell(titlecell); document.add(table); } document.close(); } public static void createCalendar(Plan plan) throws Exception { FileOutputStream fos = new FileOutputStream(new File(ConfigService.getRoot() + "calendar" + plan.getId() + ".pdf")); Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50); document.open(); Rectangle area = new Rectangle(36, 24, 559, 802); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.setBoxSize("art", area); //writer.setPDFXConformance(PdfWriter.PDFX1A2001); Header header = new Header(plan.getTitle()); writer.setPageEvent(header); document.open(); int tableheight = 490; int tablewidth = 740; //create first page PdfPTable table = new PdfPTable(plan.getLength() + 1); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.setTotalWidth(tablewidth); table.setLockedWidth(true); int[] widths = new int[table.getNumberOfColumns()]; widths[0] = 10; for (int counter = 1; counter < widths.length; counter++) { widths[counter] = (100 - 10) / plan.getLength(); } table.setWidths(widths); Paragraph destination = new Paragraph("Trip to " + plan.getLocation().getName()); destination.setAlignment(Element.ALIGN_CENTER); destination.getFont().setFamily("Arial"); destination.getFont().setSize(20); Paragraph date = new Paragraph("\n\n" + DateUtil.getFullDay(plan.getStartdate()) + "\n\nto\n\n" + DateUtil.getFullDay(plan.getEnddate())); date.getFont().setFamily("Arial"); date.setAlignment(Element.ALIGN_CENTER); date.getFont().setSize(16); table.addCell(getCaldendarAllCell("")); Calendar today = Calendar.getInstance(); today.setTime(plan.getStartdate().getTime()); while (true) { today.add(Calendar.DAY_OF_MONTH, 1); if (today.after(plan.getEnddate())) { break; } table.addCell(getDateCell(today)); } today.setTime(plan.getStartdate().getTime()); int minhour = 9; int maxhour = 17; for (Event event : plan.getEvents()) { int s = event.getStartdate().get(Calendar.HOUR_OF_DAY); int e = event.getEnddate().get(Calendar.HOUR_OF_DAY); if (s < minhour) { minhour = s; } if (e > maxhour) { maxhour = e; } } int eachheight = 464 / (maxhour - minhour); for (int counter = minhour; counter < maxhour; counter++) { table.addCell(getTimeCell(counter + ":00", eachheight, counter == maxhour - 1)); for (int datecounter = 0; datecounter < plan.getLength(); datecounter++) { PdfPCell cell = getEvent(plan,datecounter, counter, 0,eachheight/4); if (cell!=null) { table.addCell(cell); } } for (int datecounter = 0; datecounter < plan.getLength(); datecounter++) { PdfPCell cell = getEvent(plan,datecounter, counter, 1,eachheight/4); if (cell!=null) { table.addCell(cell); } } for (int datecounter = 0; datecounter < plan.getLength(); datecounter++) { PdfPCell cell = getEvent(plan,datecounter, counter, 2,eachheight/4); if (cell!=null) { table.addCell(cell); } } for (int datecounter = 0; datecounter < plan.getLength(); datecounter++) { PdfPCell cell = getEvent(plan,datecounter, counter, 3,eachheight/4); if (cell!=null) { table.addCell(cell); } } } document.add(table); document.close(); } public static PdfPCell getDateCell(Calendar date) { PdfPCell datecell = getCaldendarAllCell(DateUtil.getFullDay(date)); datecell.setFixedHeight(20); return datecell; } public static PdfPCell getTimeCell(String input, int height, boolean lastone) { PdfPCell time = getCaldendarTopCell(input); if (lastone) { time.setBorder(Rectangle.BOX); } time.setRowspan(4); time.setFixedHeight(height); return time; } public static PdfPCell getCaldendarAllCell(String text) { PdfPCell titlecell = new PdfPCell(new Paragraph(text)); titlecell.setBorder(Rectangle.BOX); titlecell.setHorizontalAlignment(Element.ALIGN_CENTER); titlecell.setVerticalAlignment(Element.ALIGN_MIDDLE); return titlecell; } public static PdfPCell getCaldendarTopCell(String text) { PdfPCell titlecell = new PdfPCell(new Paragraph(text)); titlecell.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.TOP); titlecell.setHorizontalAlignment(Element.ALIGN_CENTER); titlecell.setVerticalAlignment(Element.ALIGN_MIDDLE); return titlecell; } public static PdfPCell getCaldendarBottomCell(String text) { PdfPCell titlecell = new PdfPCell(new Paragraph(text)); titlecell.setBorder(Rectangle.LEFT | Rectangle.RIGHT | Rectangle.BOTTOM); titlecell.setHorizontalAlignment(Element.ALIGN_CENTER); titlecell.setVerticalAlignment(Element.ALIGN_MIDDLE); return titlecell; } public static PdfPCell getCaldendarCell(String text) { PdfPCell titlecell = new PdfPCell(new Paragraph(text)); titlecell.setBorder(Rectangle.LEFT | Rectangle.RIGHT); titlecell.setHorizontalAlignment(Element.ALIGN_CENTER); titlecell.setVerticalAlignment(Element.ALIGN_MIDDLE); return titlecell; } public static String merge(Plan plan) { try { List<InputStream> pdfs = new ArrayList<InputStream>(); pdfs.add(new FileInputStream(ConfigService.getRoot() + "title" + plan.getId() + ".pdf")); pdfs.add(new FileInputStream(ConfigService.getRoot() + "calendar" + plan.getId() + ".pdf")); for (int datecounter = 0; datecounter < plan.getLength(); datecounter++) { pdfs.add(new FileInputStream(ConfigService.getRoot() + "stitle" + plan.getId() + datecounter+ ".pdf")); pdfs.add(new FileInputStream(ConfigService.getRoot() + "events" + plan.getId() + datecounter+".pdf")); } pdfs.add(new FileInputStream(ConfigService.getRoot() + "last" + plan.getId() + ".pdf")); OutputStream output = new FileOutputStream(ConfigService.getRoot() + "plan" + plan.getId() + ".pdf"); concatPDFs(pdfs, output, true); return ConfigService.getRoot() + "plan" + plan.getId() + ".pdf"; } catch (Exception e) { e.printStackTrace(); } return ""; } public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) { Document document = new Document(); try { List<InputStream> pdfs = streamOfPDFFiles; List<PdfReader> readers = new ArrayList<PdfReader>(); int totalPages = 0; Iterator<InputStream> iteratorPDFs = pdfs.iterator(); // Create Readers for the pdfs. while (iteratorPDFs.hasNext()) { InputStream pdf = iteratorPDFs.next(); PdfReader pdfReader = new PdfReader(pdf); readers.add(pdfReader); totalPages += pdfReader.getNumberOfPages(); } // Create a writer for the outputstream PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); PdfContentByte cb = writer.getDirectContent(); // Holds the PDF // data PdfImportedPage page; int currentPageNumber = 0; int pageOfCurrentReaderPDF = 0; Iterator<PdfReader> iteratorPDFReader = readers.iterator(); // Loop through the PDF files and add to the output. while (iteratorPDFReader.hasNext()) { PdfReader pdfReader = iteratorPDFReader.next(); // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; currentPageNumber++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); cb.addTemplate(page, 0, 0); // Code for pagination. if (paginate) { cb.beginText(); cb.setFontAndSize(bf, 9); cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "" + currentPageNumber, 300, 20, 0); cb.endText(); } } pageOfCurrentReaderPDF = 0; } outputStream.flush(); document.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (document.isOpen()) { document.close(); } try { if (outputStream != null) { outputStream.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } } } public static PdfPCell getEvent(Plan plan,int datecounter, int hour, int slot,int eachheight) { Calendar cal = Calendar.getInstance(); cal.setTime(plan.getStartdate().getTime()); cal.add(Calendar.DAY_OF_MONTH, datecounter); PdfPCell pcell = null; int numslot = 1; for (Event event: plan.getEvents()) { if (startSlot(event.getStartdate(),cal,hour,slot)) { numslot = event.getNumberSlots(); if (numslot>1) { pcell = new PdfPCell(getEventParagraph(event.getAttraction().getName()+"\n"+DateUtil.getTime(event.getStartdate())+"-"+DateUtil.getTime(event.getEnddate()))); } else { pcell = new PdfPCell(getEventParagraph(event.getAttraction().getName())); } pcell.setBackgroundColor(BaseColor.LIGHT_GRAY); pcell.setRowspan(numslot); } else if (inSlot(event,cal,hour,slot)) { return null; } } if (pcell==null) { switch (slot) { case 0: pcell = getCaldendarTopCell(""); break; case 3: pcell = getCaldendarBottomCell(""); break; default:pcell = getCaldendarCell(""); } } pcell.setHorizontalAlignment(Element.ALIGN_CENTER); pcell.setVerticalAlignment(Element.ALIGN_MIDDLE); pcell.setFixedHeight(eachheight*numslot); return pcell; } public static Paragraph getEventParagraph(String text) { Paragraph result = new Paragraph(text); result.getFont().setFamily("Arial"); result.getFont().setSize(12); result.setAlignment(Element.ALIGN_CENTER); return result; } public static boolean startSlot(Calendar start,Calendar today,int hour,int slot) { return (start.get(Calendar.YEAR)==today.get(Calendar.YEAR) && start.get(Calendar.MONTH)==today.get(Calendar.MONTH) && start.get(Calendar.DAY_OF_MONTH)==today.get(Calendar.DAY_OF_MONTH) && start.get(Calendar.HOUR_OF_DAY)==hour && start.get(Calendar.MINUTE)==(15*slot)); } public static boolean inSlot(Event event,Calendar today,int hour,int slot) { if (event.getStartdate().get(Calendar.YEAR)==today.get(Calendar.YEAR) && event.getStartdate().get(Calendar.MONTH)==today.get(Calendar.MONTH) && event.getStartdate().get(Calendar.DAY_OF_MONTH)==today.get(Calendar.DAY_OF_MONTH)) { int bhour = event.getStartdate().get(Calendar.HOUR_OF_DAY)*60+event.getStartdate().get(Calendar.MINUTE); int ehour = event.getEnddate().get(Calendar.HOUR_OF_DAY)*60+event.getEnddate().get(Calendar.MINUTE); int current = hour*60+(slot*15) ; return (bhour<=current && current<ehour); } return false; } public static String getData(String response,String prefix,String from,String to) { int index = response.indexOf(prefix); int findex = response.indexOf(from,index); int findexe = response.indexOf(to,findex); return response.substring(findex+from.length(),findexe); } public static String getLastData(String response,String prefix,String from,String to) { int index = response.lastIndexOf(prefix); int findex = response.indexOf(from,index); int findexe = response.indexOf(to,findex); return response.substring(findex+from.length(),findexe); } public static String clean(String line) { line = line.replaceAll("&lt;b&gt;","").replaceAll("&lt;/b&gt;","").replaceAll("&lt;i&gt;","").replaceAll("&lt;/i&gt;",""); while (true) { int index = line.indexOf("&lt;div"); if (index!=-1) { int indexa = line.indexOf("&gt;",index); int indexe = line.indexOf("&lt;/div&gt;",indexa); line = line.substring(0,index)+" " + line.substring(indexa+4,indexe) + " " + line.substring(indexe+12); } else { break; } } return line; } public static void main(String[] args) throws Exception { Database.beginTransaction(); MResult plan = PlanService.getPlan("BMJMJCZQB"); createPlan((Plan) plan.getObject()); Database.commitTransaction(); } }
false
true
public static void createEvents(Plan plan,int datecounter) throws Exception { FileOutputStream fos = new FileOutputStream(new File(ConfigService.getRoot() + "events" + plan.getId() + datecounter + ".pdf")); Document document = new Document(PageSize.A4, 50, 50, 50, 50); document.open(); Rectangle area = new Rectangle(36, 24, 559, 802); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.setBoxSize("art", area); //writer.setPDFXConformance(PdfWriter.PDFX1A2001); Header event = new Header(plan.getTitle()); writer.setPageEvent(event); document.open(); int tableheight = 740; int tablewidth = 500; //create first page Calendar cal = Calendar.getInstance(); cal.setTime(plan.getStartdate().getTime()); cal.add(Calendar.DAY_OF_MONTH, datecounter); String date = DateUtil.getFullDay(cal); List<Event> todaysevents = plan.getEvents(cal); PdfPTable table = null; if (!todaysevents.isEmpty()) { int counter = 0; for (Event sevent: todaysevents) { table = new PdfPTable(2); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.setTotalWidth(tablewidth); table.setLockedWidth(true); int[] widths = {280,220}; table.setWidths(widths); Chunk datetitle = new Chunk(DateUtil.getFullDay(cal)); datetitle.setUnderline(0.1f,-2f); datetitle.getFont().setFamily("Arial"); datetitle.getFont().setSize(16); datetitle.getFont().setColor(51,102,00); PdfPCell datecell = new PdfPCell(); datecell.setBorder(Rectangle.NO_BORDER); datecell.addElement(datetitle); datecell.setColspan(2); Paragraph time = new Paragraph(sevent.getDuration()); time.getFont().setFamily("Arial"); time.getFont().setSize(14); PdfPCell timecell = new PdfPCell(time); timecell.setBorder(Rectangle.NO_BORDER); timecell.setColspan(2); Attraction attraction = sevent.getAttraction(); Paragraph eventname = new Paragraph(attraction.getName()); eventname.getFont().setFamily("Arial"); eventname.getFont().setSize(14); Paragraph eventdesc = new Paragraph(attraction.getDescription()); eventdesc.getFont().setFamily("Arial"); eventdesc.getFont().setSize(12); PdfPCell eventcell = new PdfPCell(); eventcell.addElement(eventname); eventcell.addElement(eventdesc); eventcell.setBorder(Rectangle.NO_BORDER); eventcell.setColspan(1); URL url = new URL(ConfigService.getUrl()+ "/includes/images/data/"+attraction.getImageFileName()); Image image = Image.getInstance(url); PdfPCell piccell = new PdfPCell(image); piccell.setBorder(Rectangle.NO_BORDER); piccell.setColspan(1); Paragraph eventhours = new Paragraph("Opening Hours"); eventhours.getFont().setFamily("Arial"); eventhours.getFont().setSize(14); CalendarService.loadAttractionTimes(plan, attraction); PdfPCell description = new PdfPCell(); description.addElement(eventhours); description.setBorder(Rectangle.NO_BORDER); description.setColspan(2); for (AttractionOpenView view: attraction.getOpeningTimes()) { Paragraph eventtimes = new Paragraph(DateUtil.getDay(view.getFrom())+" " + DateUtil.getTime(view.getFrom()) + "-"+ DateUtil.getTime(view.getTo())); eventtimes.getFont().setFamily("Arial"); eventtimes.getFont().setSize(12); description.addElement(eventtimes); } if (!StringUtil.isEmpty(sevent.getAttraction().getPhone())) { Paragraph eventphone = new Paragraph("Telephone: " + attraction.getPhone()); eventphone.getFont().setFamily("Arial"); eventphone.getFont().setSize(14); description.addElement(eventphone); } if (!StringUtil.isEmpty(sevent.getAttraction().getAddress())) { Paragraph eventaddress = new Paragraph("Address: " + attraction.getAddress()); eventaddress.getFont().setFamily("Arial"); eventaddress.getFont().setSize(14); description.addElement(eventaddress); } table.addCell(datecell); table.addCell(timecell); table.addCell(eventcell); table.addCell(piccell); table.addCell(description); document.add(table); document.newPage(); if (counter!=todaysevents.size()-1) { Event nextevent = todaysevents.get(counter+1); Attraction nextatt = nextevent.getAttraction(); //add directions page PdfPTable table1 = new PdfPTable(1); table1.getDefaultCell().setBorder(Rectangle.NO_BORDER); table1.setTotalWidth(tablewidth); table1.setLockedWidth(true); int[] widths3 = {1}; table1.setWidths(widths3); table1.addCell(datecell); Paragraph directions = new Paragraph("Directions from A. " + attraction.getName() + " to B. " + nextatt.getName()); directions.getFont().setFamily("Arial"); directions.getFont().setSize(14); PdfPCell dcell = new PdfPCell(directions); dcell.setBorder(Rectangle.NO_BORDER); dcell.setColspan(1); table1.addCell(dcell); String fpostcode = attraction.getPostcode().replaceAll(" ","")+",UK"; String tpostcode = nextatt.getPostcode().replaceAll(" ","")+",UK"; String wsearchUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + fpostcode + "&destination=" + tpostcode + "&sensor=false&mode=walking"; String response = Browser.getPage(wsearchUrl).toString(); int duration = Integer.parseInt(getLastData(response, "<duration>", "<value>", "</value>")); String durationt = "Walking Time: " + getLastData(response, "<duration>", "<text>", "</text>"); if (duration>60*(ConfigService.getMaxWalking())) { String dsearchUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + fpostcode + "&destination=" + tpostcode + "&sensor=false"; response = Browser.getPage(dsearchUrl).toString(); durationt = "Driving Time: " + getLastData(response, "<duration>", "<text>", "</text>"); } double latfrom = Double.parseDouble(getData(response,"<start_location>","<lat>","</lat>")); double lngfrom = Double.parseDouble(getData(response,"<start_location>","<lng>","</lng>")); double latto= Double.parseDouble(getLastData(response,"<end_location>","<lat>","</lat>")); double lngto = Double.parseDouble(getLastData(response,"<end_location>","<lng>","</lng>")); String polyline = getData(response,"<overview_polyline>","<points>","</points>"); PdfPCell instructions = new PdfPCell(); instructions.setBorder(Rectangle.NO_BORDER); Paragraph p = new Paragraph("Written Directions (" + durationt + ")");; instructions.addElement(p); String header = "<html_instructions>"; String headere = "</html_instructions>"; int index = 0; while (true) { int indexp = response.indexOf(header,index); int indexpe = response.indexOf(headere,indexp); if (indexp<index) break; String line = clean(response.substring(indexp+header.length(),indexpe)); p = new Paragraph(line); instructions.addElement(p); index = indexpe+1; } URL google = new URL("http://maps.googleapis.com/maps/api/staticmap?sensor=false&size=500x250&path=weight:3|color:red|enc:" + polyline + "&markers=label:A|" + latfrom + "," + lngfrom + "&markers=label:B|" + latto + "," + lngto); Image image1 = Image.getInstance(google); PdfPCell smap = new PdfPCell(image1); smap.setBorder(Rectangle.NO_BORDER); smap.setColspan(1); table1.addCell(smap); table1.addCell(instructions); document.add(table1); document.newPage(); } counter++; } } else { table = new PdfPTable(1); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.setTotalWidth(tablewidth); table.setLockedWidth(true); int[] widths2 = {1}; table.setWidths(widths2); Paragraph noact = new Paragraph("No Activities Planned"); noact.getFont().setFamily("Arial"); noact.setAlignment(Element.ALIGN_CENTER); noact.getFont().setSize(16); PdfPCell titlecell = new PdfPCell(); titlecell.setBorder(Rectangle.BOX); titlecell.setHorizontalAlignment(Element.ALIGN_CENTER); titlecell.setVerticalAlignment(Element.ALIGN_MIDDLE); titlecell.setFixedHeight(tableheight); titlecell.addElement(noact); table.addCell(titlecell); document.add(table); } document.close(); }
public static void createEvents(Plan plan,int datecounter) throws Exception { FileOutputStream fos = new FileOutputStream(new File(ConfigService.getRoot() + "events" + plan.getId() + datecounter + ".pdf")); Document document = new Document(PageSize.A4, 50, 50, 50, 50); document.open(); Rectangle area = new Rectangle(36, 24, 559, 802); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.setBoxSize("art", area); //writer.setPDFXConformance(PdfWriter.PDFX1A2001); Header event = new Header(plan.getTitle()); writer.setPageEvent(event); document.open(); int tableheight = 740; int tablewidth = 500; //create first page Calendar cal = Calendar.getInstance(); cal.setTime(plan.getStartdate().getTime()); cal.add(Calendar.DAY_OF_MONTH, datecounter); String date = DateUtil.getFullDay(cal); List<Event> todaysevents = plan.getEvents(cal); PdfPTable table = null; if (!todaysevents.isEmpty()) { int counter = 0; for (Event sevent: todaysevents) { table = new PdfPTable(2); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.setTotalWidth(tablewidth); table.setLockedWidth(true); int[] widths = {280,220}; table.setWidths(widths); Chunk datetitle = new Chunk(DateUtil.getFullDay(cal)); datetitle.setUnderline(0.1f,-2f); datetitle.getFont().setFamily("Arial"); datetitle.getFont().setSize(16); datetitle.getFont().setColor(51,102,00); PdfPCell datecell = new PdfPCell(); datecell.setBorder(Rectangle.NO_BORDER); datecell.addElement(datetitle); datecell.setColspan(2); Paragraph time = new Paragraph(sevent.getDuration()); time.getFont().setFamily("Arial"); time.getFont().setSize(14); PdfPCell timecell = new PdfPCell(time); timecell.setBorder(Rectangle.NO_BORDER); timecell.setColspan(2); Attraction attraction = sevent.getAttraction(); Paragraph eventname = new Paragraph(attraction.getName()); eventname.getFont().setFamily("Arial"); eventname.getFont().setSize(14); Paragraph eventdesc = new Paragraph(attraction.getDescription()); eventdesc.getFont().setFamily("Arial"); eventdesc.getFont().setSize(12); PdfPCell eventcell = new PdfPCell(); eventcell.addElement(eventname); eventcell.addElement(eventdesc); eventcell.setBorder(Rectangle.NO_BORDER); eventcell.setColspan(1); URL url = new URL(ConfigService.getUrl()+ "/includes/images/data/"+attraction.getImageFileName()); Image image = Image.getInstance(url); PdfPCell piccell = new PdfPCell(image); piccell.setBorder(Rectangle.NO_BORDER); piccell.setColspan(1); Paragraph eventhours = new Paragraph("Opening Hours"); eventhours.getFont().setFamily("Arial"); eventhours.getFont().setSize(14); CalendarService.loadAttractionTimes(plan, attraction); PdfPCell description = new PdfPCell(); description.addElement(eventhours); description.setBorder(Rectangle.NO_BORDER); description.setColspan(2); for (AttractionOpenView view: attraction.getOpeningTimes()) { Paragraph eventtimes = new Paragraph(DateUtil.getDay(view.getFrom())+" " + DateUtil.getTime(view.getFrom()) + "-"+ DateUtil.getTime(view.getTo())); eventtimes.getFont().setFamily("Arial"); eventtimes.getFont().setSize(12); description.addElement(eventtimes); } if (!StringUtil.isEmpty(sevent.getAttraction().getPhone())) { Paragraph eventphone = new Paragraph("Telephone: " + attraction.getPhone()); eventphone.getFont().setFamily("Arial"); eventphone.getFont().setSize(14); description.addElement(eventphone); } if (!StringUtil.isEmpty(sevent.getAttraction().getAddress())) { Paragraph eventaddress = new Paragraph("Address: " + attraction.getAddress()); eventaddress.getFont().setFamily("Arial"); eventaddress.getFont().setSize(14); description.addElement(eventaddress); } table.addCell(datecell); table.addCell(timecell); table.addCell(eventcell); table.addCell(piccell); table.addCell(description); document.add(table); document.newPage(); if (counter!=todaysevents.size()-1) { Event nextevent = todaysevents.get(counter+1); Attraction nextatt = nextevent.getAttraction(); //add directions page PdfPTable table1 = new PdfPTable(1); table1.getDefaultCell().setBorder(Rectangle.NO_BORDER); table1.setTotalWidth(tablewidth); table1.setLockedWidth(true); int[] widths3 = {1}; table1.setWidths(widths3); table1.addCell(datecell); Paragraph directions = new Paragraph("Directions from A. " + attraction.getName() + " to B. " + nextatt.getName()); directions.getFont().setFamily("Arial"); directions.getFont().setSize(14); PdfPCell dcell = new PdfPCell(directions); dcell.setBorder(Rectangle.NO_BORDER); dcell.setColspan(1); table1.addCell(dcell); String fpostcode = attraction.getPostcode().replaceAll(" ","")+",UK"; String tpostcode = nextatt.getPostcode().replaceAll(" ","")+",UK"; String wsearchUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + fpostcode + "&destination=" + tpostcode + "&sensor=false&mode=walking"; String response = Browser.getPage(wsearchUrl).toString(); int duration = Integer.parseInt(getLastData(response, "<duration>", "<value>", "</value>")); String durationt = "Walking Time: " + getLastData(response, "<duration>", "<text>", "</text>"); if (duration>60*(ConfigService.getMaxWalking())) { String dsearchUrl = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + fpostcode + "&destination=" + tpostcode + "&sensor=false&mode=transit"; response = Browser.getPage(dsearchUrl).toString(); durationt = "Driving Time: " + getLastData(response, "<duration>", "<text>", "</text>"); } double latfrom = Double.parseDouble(getData(response,"<start_location>","<lat>","</lat>")); double lngfrom = Double.parseDouble(getData(response,"<start_location>","<lng>","</lng>")); double latto= Double.parseDouble(getLastData(response,"<end_location>","<lat>","</lat>")); double lngto = Double.parseDouble(getLastData(response,"<end_location>","<lng>","</lng>")); String polyline = getData(response,"<overview_polyline>","<points>","</points>"); PdfPCell instructions = new PdfPCell(); instructions.setBorder(Rectangle.NO_BORDER); Paragraph p = new Paragraph("Written Directions (" + durationt + ")"); instructions.addElement(p); String header = "<html_instructions>"; String headere = "</html_instructions>"; int index = 0; while (true) { int indexp = response.indexOf(header,index); int indexpe = response.indexOf(headere,indexp); if (indexp<index) break; String line = clean(response.substring(indexp+header.length(),indexpe)); p = new Paragraph(line); instructions.addElement(p); index = indexpe+1; } URL google = new URL("http://maps.googleapis.com/maps/api/staticmap?sensor=false&size=500x250&path=weight:3|color:red|enc:" + polyline + "&markers=label:A|" + latfrom + "," + lngfrom + "&markers=label:B|" + latto + "," + lngto); Image image1 = Image.getInstance(google); PdfPCell smap = new PdfPCell(image1); smap.setBorder(Rectangle.NO_BORDER); smap.setColspan(1); table1.addCell(smap); table1.addCell(instructions); document.add(table1); document.newPage(); } counter++; } } else { table = new PdfPTable(1); table.getDefaultCell().setBorder(Rectangle.NO_BORDER); table.setTotalWidth(tablewidth); table.setLockedWidth(true); int[] widths2 = {1}; table.setWidths(widths2); Paragraph noact = new Paragraph("No Activities Planned"); noact.getFont().setFamily("Arial"); noact.setAlignment(Element.ALIGN_CENTER); noact.getFont().setSize(16); PdfPCell titlecell = new PdfPCell(); titlecell.setBorder(Rectangle.BOX); titlecell.setHorizontalAlignment(Element.ALIGN_CENTER); titlecell.setVerticalAlignment(Element.ALIGN_MIDDLE); titlecell.setFixedHeight(tableheight); titlecell.addElement(noact); table.addCell(titlecell); document.add(table); } document.close(); }