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/basex-core/src/main/java/org/basex/gui/text/TextPanel.java b/basex-core/src/main/java/org/basex/gui/text/TextPanel.java
index 6927baa19..c109bac2a 100644
--- a/basex-core/src/main/java/org/basex/gui/text/TextPanel.java
+++ b/basex-core/src/main/java/org/basex/gui/text/TextPanel.java
@@ -1,1012 +1,1012 @@
package org.basex.gui.text;
import static org.basex.gui.layout.BaseXKeys.*;
import static org.basex.util.Token.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.*;
import org.basex.core.*;
import org.basex.gui.*;
import org.basex.gui.GUIConstants.Fill;
import org.basex.gui.dialog.*;
import org.basex.gui.layout.*;
import org.basex.io.*;
import org.basex.util.*;
/**
* Renders and provides edit capabilities for text.
*
* @author BaseX Team 2005-13, BSD License
* @author Christian Gruen
*/
public class TextPanel extends BaseXPanel {
/** Delay for highlighting an error. */
private static final int ERROR_DELAY = 500;
/** Search direction. */
public enum SearchDir {
/** Current hit. */
CURRENT,
/** Next hit. */
FORWARD,
/** Previous hit. */
BACKWARD,
}
/** Editor action. */
public enum Action {
/** Check for changes; do nothing if input has not changed. */
CHECK,
/** Enforce parsing of input. */
PARSE,
/** Enforce execution of input. */
EXECUTE
}
/** Text editor. */
protected final TextEditor editor = new TextEditor(EMPTY);
/** Undo history. */
public final History hist;
/** Search bar. */
public SearchBar search;
/** Renderer reference. */
private final TextRenderer rend;
/** Scrollbar reference. */
private final BaseXScrollBar scroll;
/** Editable flag. */
private final boolean editable;
/** Link listener. */
private LinkListener linkListener;
/**
* Default constructor.
* @param edit editable flag
* @param win parent window
*/
public TextPanel(final boolean edit, final Window win) {
this(edit, win, EMPTY);
}
/**
* Default constructor.
* @param edit editable flag
* @param win parent window
* @param txt initial text
*/
public TextPanel(final boolean edit, final Window win, final byte[] txt) {
super(win);
setFocusable(true);
setFocusTraversalKeysEnabled(!edit);
editable = edit;
addMouseMotionListener(this);
addMouseWheelListener(this);
addComponentListener(this);
addMouseListener(this);
addKeyListener(this);
addFocusListener(new FocusAdapter() {
@Override
public void focusGained(final FocusEvent e) {
if(isEnabled()) caret(true);
}
@Override
public void focusLost(final FocusEvent e) {
caret(false);
rend.caret(false);
}
});
setFont(GUIConstants.dmfont);
layout(new BorderLayout());
scroll = new BaseXScrollBar(this);
rend = new TextRenderer(editor, scroll, editable);
add(rend, BorderLayout.CENTER);
add(scroll, BorderLayout.EAST);
setText(txt);
hist = new History(edit ? editor.text() : null);
if(edit) {
setBackground(Color.white);
setBorder(new MatteBorder(1, 1, 0, 0, GUIConstants.color(6)));
} else {
mode(Fill.NONE);
}
new BaseXPopup(this, edit ?
new GUICommand[] {
new FindCmd(), new FindNextCmd(), new FindPrevCmd(), null, new GotoCmd(), null,
new UndoCmd(), new RedoCmd(), null,
new AllCmd(), new CutCmd(), new CopyCmd(), new PasteCmd(), new DelCmd() } :
new GUICommand[] {
new FindCmd(), new FindNextCmd(), new FindPrevCmd(), null, new GotoCmd(), null,
new AllCmd(), new CopyCmd() }
);
}
/**
* Sets the output text.
* @param t output text
*/
public void setText(final String t) {
setText(token(t));
}
/**
* Sets the output text.
* @param t output text
*/
public void setText(final byte[] t) {
setText(t, t.length);
resetError();
}
/**
* Returns the line and column of the current caret position.
* @return line/column
*/
public final int[] pos() {
return rend.pos();
}
/**
* Sets the output text.
* @param t output text
* @param s text size
*/
public final void setText(final byte[] t, final int s) {
byte[] txt = t;
if(Token.contains(t, '\r')) {
// remove carriage returns
int ns = 0;
for(int r = 0; r < s; ++r) {
final byte b = t[r];
if(b != '\r') t[ns++] = b;
}
// new text is different...
txt = Arrays.copyOf(t, ns);
}
if(editor.text(txt)) {
if(hist != null) hist.store(txt, editor.caret(), 0);
}
componentResized(null);
}
/**
* Sets a syntax highlighter, based on the file format.
* @param file file reference
* @param opened indicates if file was opened from disk
*/
protected final void setSyntax(final IO file, final boolean opened) {
setSyntax(!opened || file.hasSuffix(IO.XQSUFFIXES) ? new SyntaxXQuery() :
file.hasSuffix(IO.JSONSUFFIX) ? new SyntaxJSON() :
file.hasSuffix(IO.XMLSUFFIXES) || file.hasSuffix(IO.HTMLSUFFIXES) ||
file.hasSuffix(IO.XSLSUFFIXES) || file.hasSuffix(IO.BXSSUFFIX) ?
new SyntaxXML() : Syntax.SIMPLE);
}
/**
* Returns the editable flag.
* @return boolean result
*/
public final boolean isEditable() {
return editable;
}
/**
* Sets a syntax highlighter.
* @param syntax syntax reference
*/
public final void setSyntax(final Syntax syntax) {
rend.setSyntax(syntax);
}
/**
* Sets the caret to the specified position. A text selection will be removed.
* @param pos caret position
*/
public final void setCaret(final int pos) {
editor.setCaret(pos);
editor.noSelect();
cursorCode.invokeLater(1);
caret(true);
}
/**
* Returns the current text cursor.
* @return cursor position
*/
public final int getCaret() {
return editor.caret();
}
/**
* Jumps to the end of the text.
*/
public final void scrollToEnd() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
editor.setCaret(editor.size());
cursorCode.execute(2);
}
});
}
/**
* Returns the output text.
* @return output text
*/
public final byte[] getText() {
return editor.text();
}
/**
* Tests if text has been selected.
* @return result of check
*/
public final boolean selected() {
return editor.selected();
}
@Override
public final void setFont(final Font f) {
super.setFont(f);
if(rend != null) {
rend.setFont(f);
scrollCode.invokeLater(true);
}
}
/** Thread counter. */
private int errorID;
/**
* Removes the error marker.
*/
public final void resetError() {
++errorID;
editor.error(-1);
rend.repaint();
}
/**
* Sets the error marker.
* @param pos start of optional error mark
*/
public final void error(final int pos) {
final int eid = ++errorID;
editor.error(pos);
new Thread() {
@Override
public void run() {
Performance.sleep(ERROR_DELAY);
if(eid == errorID) rend.repaint();
}
}.start();
}
/**
* Adds or removes a comment.
*/
public void comment() {
final int caret = editor.caret();
if(editor.comment(rend.getSyntax())) hist.store(editor.text(), caret, editor.caret());
scrollCode.invokeLater(true);
}
/**
* Formats the selected text.
*/
public void format() {
final int caret = editor.caret();
if(editor.format(rend.getSyntax())) hist.store(editor.text(), caret, editor.caret());
scrollCode.invokeLater(true);
}
@Override
public final void setEnabled(final boolean enabled) {
super.setEnabled(enabled);
rend.setEnabled(enabled);
scroll.setEnabled(enabled);
caret(enabled);
}
/**
* Selects the whole text.
*/
final void selectAll() {
final int s = editor.size();
editor.select(0, s);
editor.setCaret(s);
rend.repaint();
}
// SEARCH OPERATIONS ==================================================================
/**
* Installs a link listener.
* @param ll link listener
*/
public final void setLinkListener(final LinkListener ll) {
linkListener = ll;
}
/**
* Installs a search bar.
* @param s search bar
*/
final void setSearch(final SearchBar s) {
search = s;
}
/**
* Returns the search bar.
* @return search bar
*/
public final SearchBar getSearch() {
return search;
}
/**
* Performs a search.
* @param sc search context
* @param jump jump to next hit
*/
final void search(final SearchContext sc, final boolean jump) {
try {
rend.search(sc);
gui.status.setText(sc.search.isEmpty() ? Text.OK : Util.info(Text.STRINGS_FOUND_X, sc.nr()));
if(jump) jump(SearchDir.CURRENT, false);
} catch(final Exception ex) {
final String msg = Util.message(ex).replaceAll(Prop.NL + ".*", "");
gui.status.setError(Text.REGULAR_EXPR + Text.COLS + msg);
}
}
/**
* Replaces the text.
* @param rc replace context
*/
final void replace(final ReplaceContext rc) {
try {
final int[] select = rend.replace(rc);
if(rc.text != null) {
final boolean sel = editor.selected();
setText(rc.text);
if(sel) editor.select(select[0], select[1]);
editor.setCaret(select[0]);
release(Action.CHECK);
}
gui.status.setText(Util.info(Text.STRINGS_REPLACED));
} catch(final Exception ex) {
final String msg = Util.message(ex).replaceAll(Prop.NL + ".*", "");
gui.status.setError(Text.REGULAR_EXPR + Text.COLS + msg);
}
}
/**
* Jumps to the current, next or previous search string.
* @param dir search direction
* @param select select hit
*/
protected final void jump(final SearchDir dir, final boolean select) {
// updates the visible area
final int y = rend.jump(dir, select);
final int h = getHeight();
final int p = scroll.pos();
final int m = y + rend.fontHeight() * 3 - h;
if(y != -1 && (p < m || p > y)) scroll.pos(y - h / 2);
rend.repaint();
}
// MOUSE INTERACTIONS =================================================================
@Override
public final void mouseEntered(final MouseEvent e) {
gui.cursor(GUIConstants.CURSORTEXT);
}
@Override
public final void mouseExited(final MouseEvent e) {
gui.cursor(GUIConstants.CURSORARROW);
}
@Override
public final void mouseMoved(final MouseEvent e) {
if(linkListener == null) return;
final TextIterator iter = rend.jump(e.getPoint());
gui.cursor(iter.link() != null ? GUIConstants.CURSORHAND : GUIConstants.CURSORARROW);
}
@Override
public void mouseReleased(final MouseEvent e) {
if(linkListener == null) return;
if(SwingUtilities.isLeftMouseButton(e)) {
editor.checkSelect();
// evaluate link
if(!editor.selected()) {
final TextIterator iter = rend.jump(e.getPoint());
final String link = iter.link();
if(link != null) linkListener.linkClicked(link);
}
}
}
@Override
public void mouseClicked(final MouseEvent e) {
if(!SwingUtilities.isMiddleMouseButton(e)) return;
new PasteCmd().execute(gui);
}
@Override
public final void mouseDragged(final MouseEvent e) {
if(!SwingUtilities.isLeftMouseButton(e)) return;
// selection mode
rend.select(e.getPoint(), false);
final int y = Math.max(20, Math.min(e.getY(), getHeight() - 20));
if(y != e.getY()) scroll.pos(scroll.pos() + e.getY() - y);
}
@Override
public final void mousePressed(final MouseEvent e) {
if(!isEnabled() || !isFocusable()) return;
requestFocusInWindow();
caret(true);
if(SwingUtilities.isMiddleMouseButton(e)) copy();
final boolean selecting = e.isShiftDown();
final boolean selected = editor.selected();
if(SwingUtilities.isLeftMouseButton(e)) {
final int c = e.getClickCount();
if(c == 1) {
// selection mode
if(selecting && !selected) editor.startSelect();
rend.select(e.getPoint(), !selecting);
} else if(c == 2) {
editor.selectWord();
} else {
editor.selectLine();
}
} else if(!selected) {
rend.select(e.getPoint(), true);
}
}
// KEY INTERACTIONS =======================================================
/**
* Invokes special keys.
* @param e key event
* @return {@code true} if special key was processed
*/
private boolean specialKey(final KeyEvent e) {
if(PREVTAB.is(e)) {
gui.editor.tab(false);
} else if(NEXTTAB.is(e)) {
gui.editor.tab(true);
} else if(CLOSETAB.is(e)) {
gui.editor.close(null);
} else if(search != null && ESCAPE.is(e)) {
search.deactivate(true);
} else {
return false;
}
e.consume();
return true;
}
@Override
public void keyPressed(final KeyEvent e) {
// ignore modifier keys
if(specialKey(e) || modifier(e)) return;
// re-animate cursor
caret(true);
// operations without cursor movement...
final int fh = rend.fontHeight();
if(SCROLLDOWN.is(e)) {
scroll.pos(scroll.pos() + fh);
return;
}
if(SCROLLUP.is(e)) {
scroll.pos(scroll.pos() - fh);
return;
}
// set cursor position and reset last column
final int caret = editor.caret();
editor.pos(caret);
if(!PREVLINE.is(e) && !NEXTLINE.is(e)) lastCol = -1;
final boolean selecting = e.isShiftDown() && !BACKSPACE.is(e) && !PASTE2.is(e) &&
- !DELLINE.is(e) && !PREVPAGE_RO.is(e);
+ !DELLINE.is(e) && !PREVPAGE_RO.is(e) && !DELETE.is(e);
final boolean selected = editor.selected();
if(selecting && !selected) editor.startSelect();
boolean down = true, consumed = true;
// operations that consider the last text mark..
final byte[] txt = editor.text();
if(MOVEDOWN.is(e)) {
editor.move(true);
} else if(MOVEUP.is(e)) {
editor.move(false);
} else if(NEXTWORD.is(e)) {
editor.nextToken(selecting);
} else if(PREVWORD.is(e)) {
editor.prevToken(selecting);
down = false;
} else if(TEXTSTART.is(e)) {
if(!selecting) editor.noSelect();
editor.pos(0);
down = false;
} else if(TEXTEND.is(e)) {
if(!selecting) editor.noSelect();
editor.pos(editor.size());
} else if(LINESTART.is(e)) {
editor.home(selecting);
down = false;
} else if(LINEEND.is(e)) {
editor.eol(selecting);
} else if(PREVPAGE.is(e) || !hist.active() && PREVPAGE_RO.is(e)) {
up(getHeight() / fh, selecting);
down = false;
} else if(NEXTPAGE.is(e) || !hist.active() && NEXTPAGE_RO.is(e)) {
down(getHeight() / fh, selecting);
} else if(NEXT.is(e)) {
editor.next(selecting);
} else if(PREV.is(e)) {
editor.prev(selecting);
down = false;
} else if(PREVLINE.is(e)) {
up(1, selecting);
down = false;
} else if(NEXTLINE.is(e)) {
down(1, selecting);
} else {
consumed = false;
}
if(selecting) {
// refresh scroll position
editor.finishSelect();
} else if(hist.active()) {
// edit operations...
if(COMPLETE.is(e)) {
editor.complete();
} else if(DELLINE.is(e)) {
editor.deleteLine();
} else if(DELLINEEND.is(e) || DELNEXTWORD.is(e) || DELETE.is(e)) {
if(!selected) {
if(editor.pos() == editor.size()) return;
editor.startSelect();
if(DELNEXTWORD.is(e)) {
editor.nextToken(true);
} else if(DELLINEEND.is(e)) {
editor.eol(true);
} else {
editor.next(true);
}
editor.finishSelect();
}
editor.delete();
} else if(DELLINESTART.is(e) || DELPREVWORD.is(e) || BACKSPACE.is(e)) {
if(!selected) {
if(editor.pos() == 0) return;
if(DELPREVWORD.is(e)) {
editor.startSelect();
editor.prevToken(true);
editor.finishSelect();
} else if(DELLINESTART.is(e)) {
editor.startSelect();
editor.bol(true);
editor.finishSelect();
} else {
editor.backspace();
}
}
editor.delete();
down = false;
} else {
consumed = false;
}
}
if(consumed) e.consume();
editor.setCaret();
final byte[] tmp = editor.text();
if(txt != tmp) {
// text has changed: add old text to history
hist.store(tmp, caret, editor.caret());
scrollCode.invokeLater(down);
} else if(caret != editor.caret()) {
// cursor position has changed
cursorCode.invokeLater(down ? 2 : 0);
}
}
/** Updates the scroll bar. */
public final GUICode scrollCode = new GUICode() {
@Override
public void execute(final Object down) {
rend.updateScrollbar();
cursorCode.execute((Boolean) down ? 2 : 0);
}
};
/** Updates the cursor position. */
private final GUICode cursorCode = new GUICode() {
@Override
public void execute(final Object algn) {
// updates the visible area
final int p = scroll.pos();
final int y = rend.cursorY();
final int m = y + rend.fontHeight() * 3 - getHeight();
if(p < m || p > y) {
final int align = (Integer) algn;
scroll.pos(align == 0 ? y : align == 1 ? y - getHeight() / 2 : m);
rend.repaint();
}
}
};
/**
* Moves the cursor down. The current column position is remembered in
* {@link #lastCol} and, if possible, restored.
* @param l number of lines to move cursor
* @param mark mark flag
*/
private void down(final int l, final boolean mark) {
if(!mark) editor.noSelect();
final int x = editor.bol(mark);
if(lastCol == -1) lastCol = x;
for(int i = 0; i < l; ++i) {
editor.eol(mark);
editor.next(mark);
}
editor.forward(lastCol, mark);
if(editor.pos() == editor.size()) lastCol = -1;
}
/**
* Moves the cursor up.
* @param l number of lines to move cursor
* @param mark mark flag
*/
private void up(final int l, final boolean mark) {
if(!mark) editor.noSelect();
final int x = editor.bol(mark);
if(lastCol == -1) lastCol = x;
if(editor.pos() == 0) {
lastCol = -1;
return;
}
for(int i = 0; i < l; ++i) {
editor.prev(mark);
editor.bol(mark);
}
editor.forward(lastCol, mark);
}
/** Last horizontal position. */
private int lastCol = -1;
@Override
public void keyTyped(final KeyEvent e) {
if(!hist.active() || control(e) || DELETE.is(e) || BACKSPACE.is(e) || ESCAPE.is(e)) return;
final int caret = editor.caret();
editor.pos(caret);
// remember if marked text is to be deleted
final StringBuilder sb = new StringBuilder(1).append(e.getKeyChar());
final boolean indent = TAB.is(e) && editor.indent(sb, e.isShiftDown());
// delete marked text
final boolean selected = editor.selected() && !indent;
if(selected) editor.delete();
final int ps = editor.pos();
final int move = ENTER.is(e) ? editor.enter(sb) : editor.add(sb, selected);
// refresh history and adjust cursor position
hist.store(editor.text(), caret, editor.caret());
if(move != 0) editor.setCaret(Math.min(editor.size(), ps + move));
// adjust text height
scrollCode.invokeLater(true);
e.consume();
}
/**
* Releases a key or mouse. Can be overwritten to react on events.
* @param action action
*/
@SuppressWarnings("unused")
protected void release(final Action action) { }
// EDITOR COMMANDS ==========================================================
/**
* Copies the selected text to the clipboard.
* @return true if text was copied
*/
final boolean copy() {
final String txt = editor.copy();
if(txt.isEmpty()) {
editor.noSelect();
return false;
}
// copy selection to clipboard
BaseXLayout.copy(txt);
return true;
}
/**
* Returns the clipboard text.
* @return text
*/
private static String clip() {
// copy selection to clipboard
final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
final Transferable tr = clip.getContents(null);
if(tr != null) for(final Object o : BaseXLayout.contents(tr)) return o.toString();
return null;
}
/**
* Finishes a command.
* @param old old cursor position; store entry to history if position != -1
*/
void finish(final int old) {
editor.setCaret();
if(old != -1) hist.store(editor.text(), old, editor.caret());
scrollCode.invokeLater(true);
release(Action.CHECK);
}
/** Text caret. */
private final Timer caretTimer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
rend.caret(!rend.caret());
}
});
/**
* Stops an old text cursor thread and, if requested, starts a new one.
* @param start start/stop flag
*/
final void caret(final boolean start) {
caretTimer.stop();
if(start) caretTimer.start();
rend.caret(start);
}
@Override
public final void mouseWheelMoved(final MouseWheelEvent e) {
scroll.pos(scroll.pos() + e.getUnitsToScroll() * 20);
rend.repaint();
}
/** Calculation counter. */
private final GUICode resizeCode = new GUICode() {
@Override
public void execute(final Object arg) {
rend.updateScrollbar();
// update scrollbar to display value within valid range
scroll.pos(scroll.pos());
rend.repaint();
}
};
@Override
public final void componentResized(final ComponentEvent e) {
resizeCode.invokeLater();
}
/** Undo command. */
class UndoCmd extends GUIPopupCmd {
/** Constructor. */
UndoCmd() { super(Text.UNDO, UNDOSTEP); }
@Override
public void execute() {
if(!hist.active()) return;
final byte[] t = hist.prev();
if(t == null) return;
editor.text(t);
editor.pos(hist.caret());
finish(-1);
}
@Override
public boolean enabled(final GUI main) { return !hist.first(); }
}
/** Redo command. */
class RedoCmd extends GUIPopupCmd {
/** Constructor. */
RedoCmd() { super(Text.REDO, REDOSTEP); }
@Override
public void execute() {
if(!hist.active()) return;
final byte[] t = hist.next();
if(t == null) return;
editor.text(t);
editor.pos(hist.caret());
finish(-1);
}
@Override
public boolean enabled(final GUI main) { return !hist.last(); }
}
/** Cut command. */
class CutCmd extends GUIPopupCmd {
/** Constructor. */
CutCmd() { super(Text.CUT, CUT1, CUT2); }
@Override
public void execute() {
final int tc = editor.caret();
editor.pos(tc);
if(!copy()) return;
editor.delete();
editor.setCaret();
finish(tc);
}
@Override
public boolean enabled(final GUI main) { return hist.active() && editor.selected(); }
}
/** Copy command. */
class CopyCmd extends GUIPopupCmd {
/** Constructor. */
CopyCmd() { super(Text.COPY, COPY1, COPY2); }
@Override
public void execute() { copy(); }
@Override
public boolean enabled(final GUI main) { return editor.selected(); }
}
/** Paste command. */
class PasteCmd extends GUIPopupCmd {
/** Constructor. */
PasteCmd() { super(Text.PASTE, PASTE1, PASTE2); }
@Override
public void execute() {
final int tc = editor.caret();
editor.pos(tc);
final String clip = clip();
if(clip == null) return;
if(editor.selected()) editor.delete();
editor.add(clip);
finish(tc);
}
@Override
public boolean enabled(final GUI main) { return hist.active() && clip() != null; }
}
/** Delete command. */
class DelCmd extends GUIPopupCmd {
/** Constructor. */
DelCmd() { super(Text.DELETE, DELETE); }
@Override
public void execute() {
final int tc = editor.caret();
editor.pos(tc);
editor.delete();
finish(tc);
}
@Override
public boolean enabled(final GUI main) { return hist.active() && editor.selected(); }
}
/** Select all command. */
class AllCmd extends GUIPopupCmd {
/** Constructor. */
AllCmd() { super(Text.SELECT_ALL, SELECTALL); }
@Override
public void execute() { selectAll(); }
}
/** Find next hit. */
class FindCmd extends GUIPopupCmd {
/** Constructor. */
FindCmd() { super(Text.FIND + Text.DOTS, FIND); }
@Override
public void execute() { search.activate(editor.copy(), true); }
@Override
public boolean enabled(final GUI main) { return search != null; }
}
/** Find next hit. */
class FindNextCmd extends GUIPopupCmd {
/** Constructor. */
FindNextCmd() { super(Text.FIND_NEXT, FINDNEXT1, FINDNEXT2); }
@Override
public void execute() { find(true); }
@Override
public boolean enabled(final GUI main) { return search != null; }
}
/** Find previous hit. */
class FindPrevCmd extends GUIPopupCmd {
/** Constructor. */
FindPrevCmd() { super(Text.FIND_PREVIOUS, FINDPREV1, FINDPREV2); }
@Override
public void execute() { find(false); }
@Override
public boolean enabled(final GUI main) { return search != null; }
}
/**
* Highlights the next/previous hit.
* @param next next/previous hit
*/
private void find(final boolean next) {
final boolean vis = search.isVisible();
search.activate(editor.copy(), false);
jump(vis ? next ? SearchDir.FORWARD : SearchDir.BACKWARD : SearchDir.CURRENT, true);
}
/** Go to line. */
class GotoCmd extends GUIPopupCmd {
/** Constructor. */
GotoCmd() { super(Text.GO_TO_LINE + Text.DOTS, GOTOLINE); }
@Override
public void execute() { gotoLine(); }
@Override
public boolean enabled(final GUI main) { return search != null; }
}
/**
* Jumps to a specific line.
*/
private void gotoLine() {
final byte[] last = editor.text();
final int ll = last.length;
final int cr = getCaret();
int l = 1;
for(int e = 0; e < ll && e < cr; e += cl(last, e)) {
if(last[e] == '\n') ++l;
}
final DialogLine dl = new DialogLine(gui, l);
if(!dl.ok()) return;
final int el = dl.line();
l = 1;
int p = 0;
for(int e = 0; e < ll && l < el; e += cl(last, e)) {
if(last[e] != '\n') continue;
p = e + 1;
++l;
}
setCaret(p);
gui.editor.posCode.invokeLater();
}
}
| true | true | public void keyPressed(final KeyEvent e) {
// ignore modifier keys
if(specialKey(e) || modifier(e)) return;
// re-animate cursor
caret(true);
// operations without cursor movement...
final int fh = rend.fontHeight();
if(SCROLLDOWN.is(e)) {
scroll.pos(scroll.pos() + fh);
return;
}
if(SCROLLUP.is(e)) {
scroll.pos(scroll.pos() - fh);
return;
}
// set cursor position and reset last column
final int caret = editor.caret();
editor.pos(caret);
if(!PREVLINE.is(e) && !NEXTLINE.is(e)) lastCol = -1;
final boolean selecting = e.isShiftDown() && !BACKSPACE.is(e) && !PASTE2.is(e) &&
!DELLINE.is(e) && !PREVPAGE_RO.is(e);
final boolean selected = editor.selected();
if(selecting && !selected) editor.startSelect();
boolean down = true, consumed = true;
// operations that consider the last text mark..
final byte[] txt = editor.text();
if(MOVEDOWN.is(e)) {
editor.move(true);
} else if(MOVEUP.is(e)) {
editor.move(false);
} else if(NEXTWORD.is(e)) {
editor.nextToken(selecting);
} else if(PREVWORD.is(e)) {
editor.prevToken(selecting);
down = false;
} else if(TEXTSTART.is(e)) {
if(!selecting) editor.noSelect();
editor.pos(0);
down = false;
} else if(TEXTEND.is(e)) {
if(!selecting) editor.noSelect();
editor.pos(editor.size());
} else if(LINESTART.is(e)) {
editor.home(selecting);
down = false;
} else if(LINEEND.is(e)) {
editor.eol(selecting);
} else if(PREVPAGE.is(e) || !hist.active() && PREVPAGE_RO.is(e)) {
up(getHeight() / fh, selecting);
down = false;
} else if(NEXTPAGE.is(e) || !hist.active() && NEXTPAGE_RO.is(e)) {
down(getHeight() / fh, selecting);
} else if(NEXT.is(e)) {
editor.next(selecting);
} else if(PREV.is(e)) {
editor.prev(selecting);
down = false;
} else if(PREVLINE.is(e)) {
up(1, selecting);
down = false;
} else if(NEXTLINE.is(e)) {
down(1, selecting);
} else {
consumed = false;
}
if(selecting) {
// refresh scroll position
editor.finishSelect();
} else if(hist.active()) {
// edit operations...
if(COMPLETE.is(e)) {
editor.complete();
} else if(DELLINE.is(e)) {
editor.deleteLine();
} else if(DELLINEEND.is(e) || DELNEXTWORD.is(e) || DELETE.is(e)) {
if(!selected) {
if(editor.pos() == editor.size()) return;
editor.startSelect();
if(DELNEXTWORD.is(e)) {
editor.nextToken(true);
} else if(DELLINEEND.is(e)) {
editor.eol(true);
} else {
editor.next(true);
}
editor.finishSelect();
}
editor.delete();
} else if(DELLINESTART.is(e) || DELPREVWORD.is(e) || BACKSPACE.is(e)) {
if(!selected) {
if(editor.pos() == 0) return;
if(DELPREVWORD.is(e)) {
editor.startSelect();
editor.prevToken(true);
editor.finishSelect();
} else if(DELLINESTART.is(e)) {
editor.startSelect();
editor.bol(true);
editor.finishSelect();
} else {
editor.backspace();
}
}
editor.delete();
down = false;
} else {
consumed = false;
}
}
if(consumed) e.consume();
editor.setCaret();
final byte[] tmp = editor.text();
if(txt != tmp) {
// text has changed: add old text to history
hist.store(tmp, caret, editor.caret());
scrollCode.invokeLater(down);
} else if(caret != editor.caret()) {
// cursor position has changed
cursorCode.invokeLater(down ? 2 : 0);
}
}
| public void keyPressed(final KeyEvent e) {
// ignore modifier keys
if(specialKey(e) || modifier(e)) return;
// re-animate cursor
caret(true);
// operations without cursor movement...
final int fh = rend.fontHeight();
if(SCROLLDOWN.is(e)) {
scroll.pos(scroll.pos() + fh);
return;
}
if(SCROLLUP.is(e)) {
scroll.pos(scroll.pos() - fh);
return;
}
// set cursor position and reset last column
final int caret = editor.caret();
editor.pos(caret);
if(!PREVLINE.is(e) && !NEXTLINE.is(e)) lastCol = -1;
final boolean selecting = e.isShiftDown() && !BACKSPACE.is(e) && !PASTE2.is(e) &&
!DELLINE.is(e) && !PREVPAGE_RO.is(e) && !DELETE.is(e);
final boolean selected = editor.selected();
if(selecting && !selected) editor.startSelect();
boolean down = true, consumed = true;
// operations that consider the last text mark..
final byte[] txt = editor.text();
if(MOVEDOWN.is(e)) {
editor.move(true);
} else if(MOVEUP.is(e)) {
editor.move(false);
} else if(NEXTWORD.is(e)) {
editor.nextToken(selecting);
} else if(PREVWORD.is(e)) {
editor.prevToken(selecting);
down = false;
} else if(TEXTSTART.is(e)) {
if(!selecting) editor.noSelect();
editor.pos(0);
down = false;
} else if(TEXTEND.is(e)) {
if(!selecting) editor.noSelect();
editor.pos(editor.size());
} else if(LINESTART.is(e)) {
editor.home(selecting);
down = false;
} else if(LINEEND.is(e)) {
editor.eol(selecting);
} else if(PREVPAGE.is(e) || !hist.active() && PREVPAGE_RO.is(e)) {
up(getHeight() / fh, selecting);
down = false;
} else if(NEXTPAGE.is(e) || !hist.active() && NEXTPAGE_RO.is(e)) {
down(getHeight() / fh, selecting);
} else if(NEXT.is(e)) {
editor.next(selecting);
} else if(PREV.is(e)) {
editor.prev(selecting);
down = false;
} else if(PREVLINE.is(e)) {
up(1, selecting);
down = false;
} else if(NEXTLINE.is(e)) {
down(1, selecting);
} else {
consumed = false;
}
if(selecting) {
// refresh scroll position
editor.finishSelect();
} else if(hist.active()) {
// edit operations...
if(COMPLETE.is(e)) {
editor.complete();
} else if(DELLINE.is(e)) {
editor.deleteLine();
} else if(DELLINEEND.is(e) || DELNEXTWORD.is(e) || DELETE.is(e)) {
if(!selected) {
if(editor.pos() == editor.size()) return;
editor.startSelect();
if(DELNEXTWORD.is(e)) {
editor.nextToken(true);
} else if(DELLINEEND.is(e)) {
editor.eol(true);
} else {
editor.next(true);
}
editor.finishSelect();
}
editor.delete();
} else if(DELLINESTART.is(e) || DELPREVWORD.is(e) || BACKSPACE.is(e)) {
if(!selected) {
if(editor.pos() == 0) return;
if(DELPREVWORD.is(e)) {
editor.startSelect();
editor.prevToken(true);
editor.finishSelect();
} else if(DELLINESTART.is(e)) {
editor.startSelect();
editor.bol(true);
editor.finishSelect();
} else {
editor.backspace();
}
}
editor.delete();
down = false;
} else {
consumed = false;
}
}
if(consumed) e.consume();
editor.setCaret();
final byte[] tmp = editor.text();
if(txt != tmp) {
// text has changed: add old text to history
hist.store(tmp, caret, editor.caret());
scrollCode.invokeLater(down);
} else if(caret != editor.caret()) {
// cursor position has changed
cursorCode.invokeLater(down ? 2 : 0);
}
}
|
diff --git a/src/main/java/com/jadventure/game/classes/Recruit.java b/src/main/java/com/jadventure/game/classes/Recruit.java
index 6ddcd24..4a8f0e8 100644
--- a/src/main/java/com/jadventure/game/classes/Recruit.java
+++ b/src/main/java/com/jadventure/game/classes/Recruit.java
@@ -1,17 +1,17 @@
package com.jadventure.game.classes;
import com.jadventure.game.entities.Player;
public class Recruit extends Player {
public Recruit() {
this.setClassName("Recruit");
this.setHealth(100);
this.setHealthMax(100);
this.setDamage(50);
this.setArmour(1);
this.setLevel(1);
- this.setIntro("Hey... you alive?\n*You let out a groan...*\nHey mate, you need to wake up. The guards will be cominga round soon and they put a spear through the last guy they found still asleep.\n*Slowly you sit up.*\nThat's the way! I'm going to head back up. Follow me as soon as you can.\nBy the way, I'm Thorall, what's your name?");
+ this.setIntro("Hey... you alive?\n*You let out a groan...*\nHey mate, you need to wake up. The guards will be coming round soon and they put a spear through the last guy they found still asleep.\n*Slowly you sit up.*\nThat's the way! I'm going to head back up. Follow me as soon as you can.\nBy the way, I'm Thorall, what's your name?");
}
}
| true | true | public Recruit() {
this.setClassName("Recruit");
this.setHealth(100);
this.setHealthMax(100);
this.setDamage(50);
this.setArmour(1);
this.setLevel(1);
this.setIntro("Hey... you alive?\n*You let out a groan...*\nHey mate, you need to wake up. The guards will be cominga round soon and they put a spear through the last guy they found still asleep.\n*Slowly you sit up.*\nThat's the way! I'm going to head back up. Follow me as soon as you can.\nBy the way, I'm Thorall, what's your name?");
}
| public Recruit() {
this.setClassName("Recruit");
this.setHealth(100);
this.setHealthMax(100);
this.setDamage(50);
this.setArmour(1);
this.setLevel(1);
this.setIntro("Hey... you alive?\n*You let out a groan...*\nHey mate, you need to wake up. The guards will be coming round soon and they put a spear through the last guy they found still asleep.\n*Slowly you sit up.*\nThat's the way! I'm going to head back up. Follow me as soon as you can.\nBy the way, I'm Thorall, what's your name?");
}
|
diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java
index 9b68c5c13..4b355f7c9 100644
--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java
+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/zookeeper/RecoverableZooKeeper.java
@@ -1,598 +1,598 @@
/**
*
* 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.hbase.zookeeper;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.RetryCounter;
import org.apache.hadoop.hbase.util.RetryCounterFactory;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
/**
* A zookeeper that can handle 'recoverable' errors.
* To handle recoverable errors, developers need to realize that there are two
* classes of requests: idempotent and non-idempotent requests. Read requests
* and unconditional sets and deletes are examples of idempotent requests, they
* can be reissued with the same results.
* (Although, the delete may throw a NoNodeException on reissue its effect on
* the ZooKeeper state is the same.) Non-idempotent requests need special
* handling, application and library writers need to keep in mind that they may
* need to encode information in the data or name of znodes to detect
* retries. A simple example is a create that uses a sequence flag.
* If a process issues a create("/x-", ..., SEQUENCE) and gets a connection
* loss exception, that process will reissue another
* create("/x-", ..., SEQUENCE) and get back x-111. When the process does a
* getChildren("/"), it sees x-1,x-30,x-109,x-110,x-111, now it could be
* that x-109 was the result of the previous create, so the process actually
* owns both x-109 and x-111. An easy way around this is to use "x-process id-"
* when doing the create. If the process is using an id of 352, before reissuing
* the create it will do a getChildren("/") and see "x-222-1", "x-542-30",
* "x-352-109", x-333-110". The process will know that the original create
* succeeded an the znode it created is "x-352-109".
* @see "http://wiki.apache.org/hadoop/ZooKeeper/ErrorHandling"
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class RecoverableZooKeeper {
private static final Log LOG = LogFactory.getLog(RecoverableZooKeeper.class);
// the actual ZooKeeper client instance
private ZooKeeper zk;
private final RetryCounterFactory retryCounterFactory;
// An identifier of this process in the cluster
private final String identifier;
private final byte[] id;
private Watcher watcher;
private int sessionTimeout;
private String quorumServers;
private final Random salter;
// The metadata attached to each piece of data has the
// format:
// <magic> 1-byte constant
// <id length> 4-byte big-endian integer (length of next field)
// <id> identifier corresponding uniquely to this process
// It is prepended to the data supplied by the user.
// the magic number is to be backward compatible
private static final byte MAGIC =(byte) 0XFF;
private static final int MAGIC_SIZE = Bytes.SIZEOF_BYTE;
private static final int ID_LENGTH_OFFSET = MAGIC_SIZE;
private static final int ID_LENGTH_SIZE = Bytes.SIZEOF_INT;
public RecoverableZooKeeper(String quorumServers, int sessionTimeout,
Watcher watcher, int maxRetries, int retryIntervalMillis)
throws IOException {
this.zk = new ZooKeeper(quorumServers, sessionTimeout, watcher);
this.retryCounterFactory =
new RetryCounterFactory(maxRetries, retryIntervalMillis);
// the identifier = processID@hostName
this.identifier = ManagementFactory.getRuntimeMXBean().getName();
LOG.info("The identifier of this process is " + identifier);
this.id = Bytes.toBytes(identifier);
this.watcher = watcher;
this.sessionTimeout = sessionTimeout;
this.quorumServers = quorumServers;
salter = new SecureRandom();
}
public void reconnectAfterExpiration()
throws IOException, InterruptedException {
LOG.info("Closing dead ZooKeeper connection, session" +
" was: 0x"+Long.toHexString(zk.getSessionId()));
zk.close();
this.zk = new ZooKeeper(this.quorumServers,
this.sessionTimeout, this.watcher);
LOG.info("Recreated a ZooKeeper, session" +
" is: 0x"+Long.toHexString(zk.getSessionId()));
}
/**
* delete is an idempotent operation. Retry before throwing exception.
* This function will not throw NoNodeException if the path does not
* exist.
*/
public void delete(String path, int version)
throws InterruptedException, KeeperException {
RetryCounter retryCounter = retryCounterFactory.create();
boolean isRetry = false; // False for first attempt, true for all retries.
while (true) {
try {
zk.delete(path, version);
return;
} catch (KeeperException e) {
switch (e.code()) {
case NONODE:
if (isRetry) {
LOG.info("Node " + path + " already deleted. Assuming a " +
"previous attempt succeeded.");
return;
}
LOG.warn("Node " + path + " already deleted, retry=" + isRetry);
throw e;
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "delete");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
isRetry = true;
}
}
/**
* exists is an idempotent operation. Retry before throwing exception
* @return A Stat instance
*/
public Stat exists(String path, Watcher watcher)
throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
while (true) {
try {
return zk.exists(path, watcher);
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "exists");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
}
}
/**
* exists is an idempotent operation. Retry before throwing exception
* @return A Stat instance
*/
public Stat exists(String path, boolean watch)
throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
while (true) {
try {
return zk.exists(path, watch);
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "exists");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
}
}
private void retryOrThrow(RetryCounter retryCounter, KeeperException e,
String opName) throws KeeperException {
LOG.warn("Possibly transient ZooKeeper exception: " + e);
if (!retryCounter.shouldRetry()) {
LOG.error("ZooKeeper " + opName + " failed after "
+ retryCounter.getMaxRetries() + " retries");
throw e;
}
}
/**
* getChildren is an idempotent operation. Retry before throwing exception
* @return List of children znodes
*/
public List<String> getChildren(String path, Watcher watcher)
throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
while (true) {
try {
return zk.getChildren(path, watcher);
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "getChildren");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
}
}
/**
* getChildren is an idempotent operation. Retry before throwing exception
* @return List of children znodes
*/
public List<String> getChildren(String path, boolean watch)
throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
while (true) {
try {
return zk.getChildren(path, watch);
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "getChildren");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
}
}
/**
* getData is an idempotent operation. Retry before throwing exception
* @return Data
*/
public byte[] getData(String path, Watcher watcher, Stat stat)
throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
while (true) {
try {
byte[] revData = zk.getData(path, watcher, stat);
return this.removeMetaData(revData);
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "getData");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
}
}
/**
* getData is an idemnpotent operation. Retry before throwing exception
* @return Data
*/
public byte[] getData(String path, boolean watch, Stat stat)
throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
while (true) {
try {
byte[] revData = zk.getData(path, watch, stat);
return this.removeMetaData(revData);
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "getData");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
}
}
/**
* setData is NOT an idempotent operation. Retry may cause BadVersion Exception
* Adding an identifier field into the data to check whether
* badversion is caused by the result of previous correctly setData
* @return Stat instance
*/
public Stat setData(String path, byte[] data, int version)
throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
byte[] newData = appendMetaData(data);
boolean isRetry = false;
while (true) {
try {
return zk.setData(path, newData, version);
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "setData");
break;
case BADVERSION:
if (isRetry) {
// try to verify whether the previous setData success or not
try{
Stat stat = new Stat();
byte[] revData = zk.getData(path, false, stat);
if(Bytes.compareTo(revData, newData) == 0) {
// the bad version is caused by previous successful setData
return stat;
}
} catch(KeeperException keeperException){
// the ZK is not reliable at this moment. just throwing exception
throw keeperException;
}
}
// throw other exceptions and verified bad version exceptions
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
isRetry = true;
}
}
/**
* <p>
* NONSEQUENTIAL create is idempotent operation.
* Retry before throwing exceptions.
* But this function will not throw the NodeExist exception back to the
* application.
* </p>
* <p>
* But SEQUENTIAL is NOT idempotent operation. It is necessary to add
* identifier to the path to verify, whether the previous one is successful
* or not.
* </p>
*
* @return Path
*/
public String create(String path, byte[] data, List<ACL> acl,
CreateMode createMode)
throws KeeperException, InterruptedException {
byte[] newData = appendMetaData(data);
switch (createMode) {
case EPHEMERAL:
case PERSISTENT:
return createNonSequential(path, newData, acl, createMode);
case EPHEMERAL_SEQUENTIAL:
case PERSISTENT_SEQUENTIAL:
return createSequential(path, newData, acl, createMode);
default:
throw new IllegalArgumentException("Unrecognized CreateMode: " +
createMode);
}
}
private String createNonSequential(String path, byte[] data, List<ACL> acl,
CreateMode createMode) throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
boolean isRetry = false; // False for first attempt, true for all retries.
while (true) {
try {
return zk.create(path, data, acl, createMode);
} catch (KeeperException e) {
switch (e.code()) {
case NODEEXISTS:
if (isRetry) {
// If the connection was lost, there is still a possibility that
// we have successfully created the node at our previous attempt,
// so we read the node and compare.
byte[] currentData = zk.getData(path, false, null);
if (currentData != null &&
Bytes.compareTo(currentData, data) == 0) {
// We successfully created a non-sequential node
return path;
}
LOG.error("Node " + path + " already exists with " +
Bytes.toStringBinary(currentData) + ", could not write " +
Bytes.toStringBinary(data));
throw e;
}
- LOG.error("Node " + path + " already exists and this is not a " +
+ LOG.info("Node " + path + " already exists and this is not a " +
"retry");
throw e;
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "create");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
isRetry = true;
}
}
private String createSequential(String path, byte[] data,
List<ACL> acl, CreateMode createMode)
throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
boolean first = true;
String newPath = path+this.identifier;
while (true) {
try {
if (!first) {
// Check if we succeeded on a previous attempt
String previousResult = findPreviousSequentialNode(newPath);
if (previousResult != null) {
return previousResult;
}
}
first = false;
return zk.create(newPath, data, acl, createMode);
} catch (KeeperException e) {
switch (e.code()) {
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "create");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
}
}
private String findPreviousSequentialNode(String path)
throws KeeperException, InterruptedException {
int lastSlashIdx = path.lastIndexOf('/');
assert(lastSlashIdx != -1);
String parent = path.substring(0, lastSlashIdx);
String nodePrefix = path.substring(lastSlashIdx+1);
List<String> nodes = zk.getChildren(parent, false);
List<String> matching = filterByPrefix(nodes, nodePrefix);
for (String node : matching) {
String nodePath = parent + "/" + node;
Stat stat = zk.exists(nodePath, false);
if (stat != null) {
return nodePath;
}
}
return null;
}
public byte[] removeMetaData(byte[] data) {
if(data == null || data.length == 0) {
return data;
}
// check the magic data; to be backward compatible
byte magic = data[0];
if(magic != MAGIC) {
return data;
}
int idLength = Bytes.toInt(data, ID_LENGTH_OFFSET);
int dataLength = data.length-MAGIC_SIZE-ID_LENGTH_SIZE-idLength;
int dataOffset = MAGIC_SIZE+ID_LENGTH_SIZE+idLength;
byte[] newData = new byte[dataLength];
System.arraycopy(data, dataOffset, newData, 0, dataLength);
return newData;
}
private byte[] appendMetaData(byte[] data) {
if(data == null || data.length == 0){
return data;
}
byte[] salt = Bytes.toBytes(salter.nextLong());
int idLength = id.length + salt.length;
byte[] newData = new byte[MAGIC_SIZE+ID_LENGTH_SIZE+idLength+data.length];
int pos = 0;
pos = Bytes.putByte(newData, pos, MAGIC);
pos = Bytes.putInt(newData, pos, idLength);
pos = Bytes.putBytes(newData, pos, id, 0, id.length);
pos = Bytes.putBytes(newData, pos, salt, 0, salt.length);
pos = Bytes.putBytes(newData, pos, data, 0, data.length);
return newData;
}
public long getSessionId() {
return zk.getSessionId();
}
public void close() throws InterruptedException {
zk.close();
}
public States getState() {
return zk.getState();
}
public ZooKeeper getZooKeeper() {
return zk;
}
public byte[] getSessionPasswd() {
return zk.getSessionPasswd();
}
public void sync(String path, AsyncCallback.VoidCallback cb, Object ctx) {
this.zk.sync(path, null, null);
}
/**
* Filters the given node list by the given prefixes.
* This method is all-inclusive--if any element in the node list starts
* with any of the given prefixes, then it is included in the result.
*
* @param nodes the nodes to filter
* @param prefixes the prefixes to include in the result
* @return list of every element that starts with one of the prefixes
*/
private static List<String> filterByPrefix(List<String> nodes,
String... prefixes) {
List<String> lockChildren = new ArrayList<String>();
for (String child : nodes){
for (String prefix : prefixes){
if (child.startsWith(prefix)){
lockChildren.add(child);
break;
}
}
}
return lockChildren;
}
}
| true | true | private String createNonSequential(String path, byte[] data, List<ACL> acl,
CreateMode createMode) throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
boolean isRetry = false; // False for first attempt, true for all retries.
while (true) {
try {
return zk.create(path, data, acl, createMode);
} catch (KeeperException e) {
switch (e.code()) {
case NODEEXISTS:
if (isRetry) {
// If the connection was lost, there is still a possibility that
// we have successfully created the node at our previous attempt,
// so we read the node and compare.
byte[] currentData = zk.getData(path, false, null);
if (currentData != null &&
Bytes.compareTo(currentData, data) == 0) {
// We successfully created a non-sequential node
return path;
}
LOG.error("Node " + path + " already exists with " +
Bytes.toStringBinary(currentData) + ", could not write " +
Bytes.toStringBinary(data));
throw e;
}
LOG.error("Node " + path + " already exists and this is not a " +
"retry");
throw e;
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "create");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
isRetry = true;
}
}
| private String createNonSequential(String path, byte[] data, List<ACL> acl,
CreateMode createMode) throws KeeperException, InterruptedException {
RetryCounter retryCounter = retryCounterFactory.create();
boolean isRetry = false; // False for first attempt, true for all retries.
while (true) {
try {
return zk.create(path, data, acl, createMode);
} catch (KeeperException e) {
switch (e.code()) {
case NODEEXISTS:
if (isRetry) {
// If the connection was lost, there is still a possibility that
// we have successfully created the node at our previous attempt,
// so we read the node and compare.
byte[] currentData = zk.getData(path, false, null);
if (currentData != null &&
Bytes.compareTo(currentData, data) == 0) {
// We successfully created a non-sequential node
return path;
}
LOG.error("Node " + path + " already exists with " +
Bytes.toStringBinary(currentData) + ", could not write " +
Bytes.toStringBinary(data));
throw e;
}
LOG.info("Node " + path + " already exists and this is not a " +
"retry");
throw e;
case CONNECTIONLOSS:
case SESSIONEXPIRED:
case OPERATIONTIMEOUT:
retryOrThrow(retryCounter, e, "create");
break;
default:
throw e;
}
}
retryCounter.sleepUntilNextRetry();
retryCounter.useRetry();
isRetry = true;
}
}
|
diff --git a/web-selenium/src/main/java/org/jbehave/web/selenium/RemoteWebDriverProvider.java b/web-selenium/src/main/java/org/jbehave/web/selenium/RemoteWebDriverProvider.java
index e26d901..7eaa65c 100644
--- a/web-selenium/src/main/java/org/jbehave/web/selenium/RemoteWebDriverProvider.java
+++ b/web-selenium/src/main/java/org/jbehave/web/selenium/RemoteWebDriverProvider.java
@@ -1,79 +1,86 @@
package org.jbehave.web.selenium;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.DriverCommand;
import org.openqa.selenium.remote.RemoteWebDriver;
/**
* <p>Provides a {@link RemoteWebDriver} that connects to a URL specified by system property "REMOTE_WEBDRIVER_URL"
* and allows to take screenshots.</p>
* <p>The default {@link DesiredCapabilities}, specified by {@link #defaultDesiredCapabilities()}, are for
* Windows Firefox 3.6 allowing screenshots.</p>
*/
public class RemoteWebDriverProvider extends DelegatingWebDriverProvider {
protected DesiredCapabilities desiredCapabilities;
public RemoteWebDriverProvider() {
this(defaultDesiredCapabilities());
}
public static DesiredCapabilities defaultDesiredCapabilities() {
DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
desiredCapabilities.setVersion("3.6.");
desiredCapabilities.setPlatform(Platform.WINDOWS);
desiredCapabilities.setCapability(CapabilityType.TAKES_SCREENSHOT, true);
return desiredCapabilities;
}
public RemoteWebDriverProvider(DesiredCapabilities desiredCapabilities) {
this.desiredCapabilities = desiredCapabilities;
}
public void initialize() {
URL url = null;
+ WebDriver remoteWebDriver;
try {
url = createRemoteURL();
- } catch (MalformedURLException e) {
- throw new UnsupportedOperationException("Invalid URL " + url + ": " + e.getMessage(), e);
+ remoteWebDriver = new ScreenshootingRemoteWebDriver(url, desiredCapabilities);
+ } catch (Throwable e) {
+ System.err.println("*******************");
+ System.err.println("***** FAILED ******");
+ System.err.println("*******************");
+ System.err.print(e.getMessage());
+ e.printStackTrace();
+ System.err.println("*******************");
+ throw new UnsupportedOperationException("Connecting to remote URL '" + url + "' failed: " + e.getMessage(), e);
}
- WebDriver remoteWebDriver = new ScreenshootingRemoteWebDriver(url, desiredCapabilities);
// Augmenter does not work. Resulting WebDriver is good for exclusive
// screenshooting, but not normal operation as 'session is null'
// remoteWebDriver = new Augmenter().augment(remoteWebDriver);
// should allow instanceof TakesScreenshot
delegate.set(remoteWebDriver);
}
public URL createRemoteURL() throws MalformedURLException {
String url = System.getProperty("REMOTE_WEBDRIVER_URL");
if (url == null) {
throw new UnsupportedOperationException("REMOTE_WEBDRIVER_URL property not specified");
}
return new URL(url);
}
static class ScreenshootingRemoteWebDriver extends RemoteWebDriver implements TakesScreenshot {
public ScreenshootingRemoteWebDriver(URL remoteURL, DesiredCapabilities desiredCapabilities) {
super(remoteURL, desiredCapabilities);
}
public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
// Paul: Copied from FirefoxDriver.......
// Get the screenshot as base64.
String base64 = execute(DriverCommand.SCREENSHOT).getValue().toString();
// ... and convert it.
return target.convertFromBase64Png(base64);
}
}
}
| false | true | public void initialize() {
URL url = null;
try {
url = createRemoteURL();
} catch (MalformedURLException e) {
throw new UnsupportedOperationException("Invalid URL " + url + ": " + e.getMessage(), e);
}
WebDriver remoteWebDriver = new ScreenshootingRemoteWebDriver(url, desiredCapabilities);
// Augmenter does not work. Resulting WebDriver is good for exclusive
// screenshooting, but not normal operation as 'session is null'
// remoteWebDriver = new Augmenter().augment(remoteWebDriver);
// should allow instanceof TakesScreenshot
delegate.set(remoteWebDriver);
}
| public void initialize() {
URL url = null;
WebDriver remoteWebDriver;
try {
url = createRemoteURL();
remoteWebDriver = new ScreenshootingRemoteWebDriver(url, desiredCapabilities);
} catch (Throwable e) {
System.err.println("*******************");
System.err.println("***** FAILED ******");
System.err.println("*******************");
System.err.print(e.getMessage());
e.printStackTrace();
System.err.println("*******************");
throw new UnsupportedOperationException("Connecting to remote URL '" + url + "' failed: " + e.getMessage(), e);
}
// Augmenter does not work. Resulting WebDriver is good for exclusive
// screenshooting, but not normal operation as 'session is null'
// remoteWebDriver = new Augmenter().augment(remoteWebDriver);
// should allow instanceof TakesScreenshot
delegate.set(remoteWebDriver);
}
|
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index ec8fd96a..f17f0e45 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -1,8687 +1,8689 @@
/*
* 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 android.view;
import com.android.internal.R;
import com.android.internal.view.menu.MenuBuilder;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.Shader;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.util.AttributeSet;
import android.util.Config;
import android.util.EventLog;
import android.util.Log;
import android.util.Pool;
import android.util.Poolable;
import android.util.PoolableManager;
import android.util.Pools;
import android.util.SparseArray;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityEventSource;
import android.view.accessibility.AccessibilityManager;
import android.view.animation.Animation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.ScrollBarDrawable;
import java.lang.ref.SoftReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.WeakHashMap;
/**
* <p>
* This class represents the basic building block for user interface components. A View
* occupies a rectangular area on the screen and is responsible for drawing and
* event handling. View is the base class for <em>widgets</em>, which are
* used to create interactive UI components (buttons, text fields, etc.). The
* {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which
* are invisible containers that hold other Views (or other ViewGroups) and define
* their layout properties.
* </p>
*
* <div class="special">
* <p>For an introduction to using this class to develop your
* application's user interface, read the Developer Guide documentation on
* <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics
* include:
* <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>
* <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a>
* <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a>
* <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a>
* <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a>
* <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>
* <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>
* <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>.
* </p>
* </div>
*
* <a name="Using"></a>
* <h3>Using Views</h3>
* <p>
* All of the views in a window are arranged in a single tree. You can add views
* either from code or by specifying a tree of views in one or more XML layout
* files. There are many specialized subclasses of views that act as controls or
* are capable of displaying text, images, or other content.
* </p>
* <p>
* Once you have created a tree of views, there are typically a few types of
* common operations you may wish to perform:
* <ul>
* <li><strong>Set properties:</strong> for example setting the text of a
* {@link android.widget.TextView}. The available properties and the methods
* that set them will vary among the different subclasses of views. Note that
* properties that are known at build time can be set in the XML layout
* files.</li>
* <li><strong>Set focus:</strong> The framework will handled moving focus in
* response to user input. To force focus to a specific view, call
* {@link #requestFocus}.</li>
* <li><strong>Set up listeners:</strong> Views allow clients to set listeners
* that will be notified when something interesting happens to the view. For
* example, all views will let you set a listener to be notified when the view
* gains or loses focus. You can register such a listener using
* {@link #setOnFocusChangeListener}. Other view subclasses offer more
* specialized listeners. For example, a Button exposes a listener to notify
* clients when the button is clicked.</li>
* <li><strong>Set visibility:</strong> You can hide or show views using
* {@link #setVisibility}.</li>
* </ul>
* </p>
* <p><em>
* Note: The Android framework is responsible for measuring, laying out and
* drawing views. You should not call methods that perform these actions on
* views yourself unless you are actually implementing a
* {@link android.view.ViewGroup}.
* </em></p>
*
* <a name="Lifecycle"></a>
* <h3>Implementing a Custom View</h3>
*
* <p>
* To implement a custom view, you will usually begin by providing overrides for
* some of the standard methods that the framework calls on all views. You do
* not need to override all of these methods. In fact, you can start by just
* overriding {@link #onDraw(android.graphics.Canvas)}.
* <table border="2" width="85%" align="center" cellpadding="5">
* <thead>
* <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr>
* </thead>
*
* <tbody>
* <tr>
* <td rowspan="2">Creation</td>
* <td>Constructors</td>
* <td>There is a form of the constructor that are called when the view
* is created from code and a form that is called when the view is
* inflated from a layout file. The second form should parse and apply
* any attributes defined in the layout file.
* </td>
* </tr>
* <tr>
* <td><code>{@link #onFinishInflate()}</code></td>
* <td>Called after a view and all of its children has been inflated
* from XML.</td>
* </tr>
*
* <tr>
* <td rowspan="3">Layout</td>
* <td><code>{@link #onMeasure}</code></td>
* <td>Called to determine the size requirements for this view and all
* of its children.
* </td>
* </tr>
* <tr>
* <td><code>{@link #onLayout}</code></td>
* <td>Called when this view should assign a size and position to all
* of its children.
* </td>
* </tr>
* <tr>
* <td><code>{@link #onSizeChanged}</code></td>
* <td>Called when the size of this view has changed.
* </td>
* </tr>
*
* <tr>
* <td>Drawing</td>
* <td><code>{@link #onDraw}</code></td>
* <td>Called when the view should render its content.
* </td>
* </tr>
*
* <tr>
* <td rowspan="4">Event processing</td>
* <td><code>{@link #onKeyDown}</code></td>
* <td>Called when a new key event occurs.
* </td>
* </tr>
* <tr>
* <td><code>{@link #onKeyUp}</code></td>
* <td>Called when a key up event occurs.
* </td>
* </tr>
* <tr>
* <td><code>{@link #onTrackballEvent}</code></td>
* <td>Called when a trackball motion event occurs.
* </td>
* </tr>
* <tr>
* <td><code>{@link #onTouchEvent}</code></td>
* <td>Called when a touch screen motion event occurs.
* </td>
* </tr>
*
* <tr>
* <td rowspan="2">Focus</td>
* <td><code>{@link #onFocusChanged}</code></td>
* <td>Called when the view gains or loses focus.
* </td>
* </tr>
*
* <tr>
* <td><code>{@link #onWindowFocusChanged}</code></td>
* <td>Called when the window containing the view gains or loses focus.
* </td>
* </tr>
*
* <tr>
* <td rowspan="3">Attaching</td>
* <td><code>{@link #onAttachedToWindow()}</code></td>
* <td>Called when the view is attached to a window.
* </td>
* </tr>
*
* <tr>
* <td><code>{@link #onDetachedFromWindow}</code></td>
* <td>Called when the view is detached from its window.
* </td>
* </tr>
*
* <tr>
* <td><code>{@link #onWindowVisibilityChanged}</code></td>
* <td>Called when the visibility of the window containing the view
* has changed.
* </td>
* </tr>
* </tbody>
*
* </table>
* </p>
*
* <a name="IDs"></a>
* <h3>IDs</h3>
* Views may have an integer id associated with them. These ids are typically
* assigned in the layout XML files, and are used to find specific views within
* the view tree. A common pattern is to:
* <ul>
* <li>Define a Button in the layout file and assign it a unique ID.
* <pre>
* <Button id="@+id/my_button"
* android:layout_width="wrap_content"
* android:layout_height="wrap_content"
* android:text="@string/my_button_text"/>
* </pre></li>
* <li>From the onCreate method of an Activity, find the Button
* <pre class="prettyprint">
* Button myButton = (Button) findViewById(R.id.my_button);
* </pre></li>
* </ul>
* <p>
* View IDs need not be unique throughout the tree, but it is good practice to
* ensure that they are at least unique within the part of the tree you are
* searching.
* </p>
*
* <a name="Position"></a>
* <h3>Position</h3>
* <p>
* The geometry of a view is that of a rectangle. A view has a location,
* expressed as a pair of <em>left</em> and <em>top</em> coordinates, and
* two dimensions, expressed as a width and a height. The unit for location
* and dimensions is the pixel.
* </p>
*
* <p>
* It is possible to retrieve the location of a view by invoking the methods
* {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X,
* coordinate of the rectangle representing the view. The latter returns the
* top, or Y, coordinate of the rectangle representing the view. These methods
* both return the location of the view relative to its parent. For instance,
* when getLeft() returns 20, that means the view is located 20 pixels to the
* right of the left edge of its direct parent.
* </p>
*
* <p>
* In addition, several convenience methods are offered to avoid unnecessary
* computations, namely {@link #getRight()} and {@link #getBottom()}.
* These methods return the coordinates of the right and bottom edges of the
* rectangle representing the view. For instance, calling {@link #getRight()}
* is similar to the following computation: <code>getLeft() + getWidth()</code>
* (see <a href="#SizePaddingMargins">Size</a> for more information about the width.)
* </p>
*
* <a name="SizePaddingMargins"></a>
* <h3>Size, padding and margins</h3>
* <p>
* The size of a view is expressed with a width and a height. A view actually
* possess two pairs of width and height values.
* </p>
*
* <p>
* The first pair is known as <em>measured width</em> and
* <em>measured height</em>. These dimensions define how big a view wants to be
* within its parent (see <a href="#Layout">Layout</a> for more details.) The
* measured dimensions can be obtained by calling {@link #getMeasuredWidth()}
* and {@link #getMeasuredHeight()}.
* </p>
*
* <p>
* The second pair is simply known as <em>width</em> and <em>height</em>, or
* sometimes <em>drawing width</em> and <em>drawing height</em>. These
* dimensions define the actual size of the view on screen, at drawing time and
* after layout. These values may, but do not have to, be different from the
* measured width and height. The width and height can be obtained by calling
* {@link #getWidth()} and {@link #getHeight()}.
* </p>
*
* <p>
* To measure its dimensions, a view takes into account its padding. The padding
* is expressed in pixels for the left, top, right and bottom parts of the view.
* Padding can be used to offset the content of the view by a specific amount of
* pixels. For instance, a left padding of 2 will push the view's content by
* 2 pixels to the right of the left edge. Padding can be set using the
* {@link #setPadding(int, int, int, int)} method and queried by calling
* {@link #getPaddingLeft()}, {@link #getPaddingTop()},
* {@link #getPaddingRight()} and {@link #getPaddingBottom()}.
* </p>
*
* <p>
* Even though a view can define a padding, it does not provide any support for
* margins. However, view groups provide such a support. Refer to
* {@link android.view.ViewGroup} and
* {@link android.view.ViewGroup.MarginLayoutParams} for further information.
* </p>
*
* <a name="Layout"></a>
* <h3>Layout</h3>
* <p>
* Layout is a two pass process: a measure pass and a layout pass. The measuring
* pass is implemented in {@link #measure(int, int)} and is a top-down traversal
* of the view tree. Each view pushes dimension specifications down the tree
* during the recursion. At the end of the measure pass, every view has stored
* its measurements. The second pass happens in
* {@link #layout(int,int,int,int)} and is also top-down. During
* this pass each parent is responsible for positioning all of its children
* using the sizes computed in the measure pass.
* </p>
*
* <p>
* When a view's measure() method returns, its {@link #getMeasuredWidth()} and
* {@link #getMeasuredHeight()} values must be set, along with those for all of
* that view's descendants. A view's measured width and measured height values
* must respect the constraints imposed by the view's parents. This guarantees
* that at the end of the measure pass, all parents accept all of their
* children's measurements. A parent view may call measure() more than once on
* its children. For example, the parent may measure each child once with
* unspecified dimensions to find out how big they want to be, then call
* measure() on them again with actual numbers if the sum of all the children's
* unconstrained sizes is too big or too small.
* </p>
*
* <p>
* The measure pass uses two classes to communicate dimensions. The
* {@link MeasureSpec} class is used by views to tell their parents how they
* want to be measured and positioned. The base LayoutParams class just
* describes how big the view wants to be for both width and height. For each
* dimension, it can specify one of:
* <ul>
* <li> an exact number
* <li>FILL_PARENT, which means the view wants to be as big as its parent
* (minus padding)
* <li> WRAP_CONTENT, which means that the view wants to be just big enough to
* enclose its content (plus padding).
* </ul>
* There are subclasses of LayoutParams for different subclasses of ViewGroup.
* For example, AbsoluteLayout has its own subclass of LayoutParams which adds
* an X and Y value.
* </p>
*
* <p>
* MeasureSpecs are used to push requirements down the tree from parent to
* child. A MeasureSpec can be in one of three modes:
* <ul>
* <li>UNSPECIFIED: This is used by a parent to determine the desired dimension
* of a child view. For example, a LinearLayout may call measure() on its child
* with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how
* tall the child view wants to be given a width of 240 pixels.
* <li>EXACTLY: This is used by the parent to impose an exact size on the
* child. The child must use this size, and guarantee that all of its
* descendants will fit within this size.
* <li>AT_MOST: This is used by the parent to impose a maximum size on the
* child. The child must gurantee that it and all of its descendants will fit
* within this size.
* </ul>
* </p>
*
* <p>
* To intiate a layout, call {@link #requestLayout}. This method is typically
* called by a view on itself when it believes that is can no longer fit within
* its current bounds.
* </p>
*
* <a name="Drawing"></a>
* <h3>Drawing</h3>
* <p>
* Drawing is handled by walking the tree and rendering each view that
* intersects the the invalid region. Because the tree is traversed in-order,
* this means that parents will draw before (i.e., behind) their children, with
* siblings drawn in the order they appear in the tree.
* If you set a background drawable for a View, then the View will draw it for you
* before calling back to its <code>onDraw()</code> method.
* </p>
*
* <p>
* Note that the framework will not draw views that are not in the invalid region.
* </p>
*
* <p>
* To force a view to draw, call {@link #invalidate()}.
* </p>
*
* <a name="EventHandlingThreading"></a>
* <h3>Event Handling and Threading</h3>
* <p>
* The basic cycle of a view is as follows:
* <ol>
* <li>An event comes in and is dispatched to the appropriate view. The view
* handles the event and notifies any listeners.</li>
* <li>If in the course of processing the event, the view's bounds may need
* to be changed, the view will call {@link #requestLayout()}.</li>
* <li>Similarly, if in the course of processing the event the view's appearance
* may need to be changed, the view will call {@link #invalidate()}.</li>
* <li>If either {@link #requestLayout()} or {@link #invalidate()} were called,
* the framework will take care of measuring, laying out, and drawing the tree
* as appropriate.</li>
* </ol>
* </p>
*
* <p><em>Note: The entire view tree is single threaded. You must always be on
* the UI thread when calling any method on any view.</em>
* If you are doing work on other threads and want to update the state of a view
* from that thread, you should use a {@link Handler}.
* </p>
*
* <a name="FocusHandling"></a>
* <h3>Focus Handling</h3>
* <p>
* The framework will handle routine focus movement in response to user input.
* This includes changing the focus as views are removed or hidden, or as new
* views become available. Views indicate their willingness to take focus
* through the {@link #isFocusable} method. To change whether a view can take
* focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below)
* views indicate whether they still would like focus via {@link #isFocusableInTouchMode}
* and can change this via {@link #setFocusableInTouchMode(boolean)}.
* </p>
* <p>
* Focus movement is based on an algorithm which finds the nearest neighbor in a
* given direction. In rare cases, the default algorithm may not match the
* intended behavior of the developer. In these situations, you can provide
* explicit overrides by using these XML attributes in the layout file:
* <pre>
* nextFocusDown
* nextFocusLeft
* nextFocusRight
* nextFocusUp
* </pre>
* </p>
*
*
* <p>
* To get a particular view to take focus, call {@link #requestFocus()}.
* </p>
*
* <a name="TouchMode"></a>
* <h3>Touch Mode</h3>
* <p>
* When a user is navigating a user interface via directional keys such as a D-pad, it is
* necessary to give focus to actionable items such as buttons so the user can see
* what will take input. If the device has touch capabilities, however, and the user
* begins interacting with the interface by touching it, it is no longer necessary to
* always highlight, or give focus to, a particular view. This motivates a mode
* for interaction named 'touch mode'.
* </p>
* <p>
* For a touch capable device, once the user touches the screen, the device
* will enter touch mode. From this point onward, only views for which
* {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets.
* Other views that are touchable, like buttons, will not take focus when touched; they will
* only fire the on click listeners.
* </p>
* <p>
* Any time a user hits a directional key, such as a D-pad direction, the view device will
* exit touch mode, and find a view to take focus, so that the user may resume interacting
* with the user interface without touching the screen again.
* </p>
* <p>
* The touch mode state is maintained across {@link android.app.Activity}s. Call
* {@link #isInTouchMode} to see whether the device is currently in touch mode.
* </p>
*
* <a name="Scrolling"></a>
* <h3>Scrolling</h3>
* <p>
* The framework provides basic support for views that wish to internally
* scroll their content. This includes keeping track of the X and Y scroll
* offset as well as mechanisms for drawing scrollbars. See
* {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)} for more details.
* </p>
*
* <a name="Tags"></a>
* <h3>Tags</h3>
* <p>
* Unlike IDs, tags are not used to identify views. Tags are essentially an
* extra piece of information that can be associated with a view. They are most
* often used as a convenience to store data related to views in the views
* themselves rather than by putting them in a separate structure.
* </p>
*
* <a name="Animation"></a>
* <h3>Animation</h3>
* <p>
* You can attach an {@link Animation} object to a view using
* {@link #setAnimation(Animation)} or
* {@link #startAnimation(Animation)}. The animation can alter the scale,
* rotation, translation and alpha of a view over time. If the animation is
* attached to a view that has children, the animation will affect the entire
* subtree rooted by that node. When an animation is started, the framework will
* take care of redrawing the appropriate views until the animation completes.
* </p>
*
* @attr ref android.R.styleable#View_background
* @attr ref android.R.styleable#View_clickable
* @attr ref android.R.styleable#View_contentDescription
* @attr ref android.R.styleable#View_drawingCacheQuality
* @attr ref android.R.styleable#View_duplicateParentState
* @attr ref android.R.styleable#View_id
* @attr ref android.R.styleable#View_fadingEdge
* @attr ref android.R.styleable#View_fadingEdgeLength
* @attr ref android.R.styleable#View_fitsSystemWindows
* @attr ref android.R.styleable#View_isScrollContainer
* @attr ref android.R.styleable#View_focusable
* @attr ref android.R.styleable#View_focusableInTouchMode
* @attr ref android.R.styleable#View_hapticFeedbackEnabled
* @attr ref android.R.styleable#View_keepScreenOn
* @attr ref android.R.styleable#View_longClickable
* @attr ref android.R.styleable#View_minHeight
* @attr ref android.R.styleable#View_minWidth
* @attr ref android.R.styleable#View_nextFocusDown
* @attr ref android.R.styleable#View_nextFocusLeft
* @attr ref android.R.styleable#View_nextFocusRight
* @attr ref android.R.styleable#View_nextFocusUp
* @attr ref android.R.styleable#View_onClick
* @attr ref android.R.styleable#View_padding
* @attr ref android.R.styleable#View_paddingBottom
* @attr ref android.R.styleable#View_paddingLeft
* @attr ref android.R.styleable#View_paddingRight
* @attr ref android.R.styleable#View_paddingTop
* @attr ref android.R.styleable#View_saveEnabled
* @attr ref android.R.styleable#View_scrollX
* @attr ref android.R.styleable#View_scrollY
* @attr ref android.R.styleable#View_scrollbarSize
* @attr ref android.R.styleable#View_scrollbarStyle
* @attr ref android.R.styleable#View_scrollbars
* @attr ref android.R.styleable#View_scrollbarTrackHorizontal
* @attr ref android.R.styleable#View_scrollbarThumbHorizontal
* @attr ref android.R.styleable#View_scrollbarThumbVertical
* @attr ref android.R.styleable#View_scrollbarTrackVertical
* @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack
* @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack
* @attr ref android.R.styleable#View_soundEffectsEnabled
* @attr ref android.R.styleable#View_tag
* @attr ref android.R.styleable#View_visibility
*
* @see android.view.ViewGroup
*/
public class View implements Drawable.Callback, KeyEvent.Callback, AccessibilityEventSource {
private static final boolean DBG = false;
/**
* The logging tag used by this class with android.util.Log.
*/
protected static final String VIEW_LOG_TAG = "View";
/**
* Used to mark a View that has no ID.
*/
public static final int NO_ID = -1;
/**
* This view does not want keystrokes. Use with TAKES_FOCUS_MASK when
* calling setFlags.
*/
private static final int NOT_FOCUSABLE = 0x00000000;
/**
* This view wants keystrokes. Use with TAKES_FOCUS_MASK when calling
* setFlags.
*/
private static final int FOCUSABLE = 0x00000001;
/**
* Mask for use with setFlags indicating bits used for focus.
*/
private static final int FOCUSABLE_MASK = 0x00000001;
/**
* This view will adjust its padding to fit sytem windows (e.g. status bar)
*/
private static final int FITS_SYSTEM_WINDOWS = 0x00000002;
/**
* This view is visible. Use with {@link #setVisibility}.
*/
public static final int VISIBLE = 0x00000000;
/**
* This view is invisible, but it still takes up space for layout purposes.
* Use with {@link #setVisibility}.
*/
public static final int INVISIBLE = 0x00000004;
/**
* This view is invisible, and it doesn't take any space for layout
* purposes. Use with {@link #setVisibility}.
*/
public static final int GONE = 0x00000008;
/**
* Mask for use with setFlags indicating bits used for visibility.
* {@hide}
*/
static final int VISIBILITY_MASK = 0x0000000C;
private static final int[] VISIBILITY_FLAGS = {VISIBLE, INVISIBLE, GONE};
/**
* This view is enabled. Intrepretation varies by subclass.
* Use with ENABLED_MASK when calling setFlags.
* {@hide}
*/
static final int ENABLED = 0x00000000;
/**
* This view is disabled. Intrepretation varies by subclass.
* Use with ENABLED_MASK when calling setFlags.
* {@hide}
*/
static final int DISABLED = 0x00000020;
/**
* Mask for use with setFlags indicating bits used for indicating whether
* this view is enabled
* {@hide}
*/
static final int ENABLED_MASK = 0x00000020;
/**
* This view won't draw. {@link #onDraw} won't be called and further
* optimizations
* will be performed. It is okay to have this flag set and a background.
* Use with DRAW_MASK when calling setFlags.
* {@hide}
*/
static final int WILL_NOT_DRAW = 0x00000080;
/**
* Mask for use with setFlags indicating bits used for indicating whether
* this view is will draw
* {@hide}
*/
static final int DRAW_MASK = 0x00000080;
/**
* <p>This view doesn't show scrollbars.</p>
* {@hide}
*/
static final int SCROLLBARS_NONE = 0x00000000;
/**
* <p>This view shows horizontal scrollbars.</p>
* {@hide}
*/
static final int SCROLLBARS_HORIZONTAL = 0x00000100;
/**
* <p>This view shows vertical scrollbars.</p>
* {@hide}
*/
static final int SCROLLBARS_VERTICAL = 0x00000200;
/**
* <p>Mask for use with setFlags indicating bits used for indicating which
* scrollbars are enabled.</p>
* {@hide}
*/
static final int SCROLLBARS_MASK = 0x00000300;
// note 0x00000400 and 0x00000800 are now available for next flags...
/**
* <p>This view doesn't show fading edges.</p>
* {@hide}
*/
static final int FADING_EDGE_NONE = 0x00000000;
/**
* <p>This view shows horizontal fading edges.</p>
* {@hide}
*/
static final int FADING_EDGE_HORIZONTAL = 0x00001000;
/**
* <p>This view shows vertical fading edges.</p>
* {@hide}
*/
static final int FADING_EDGE_VERTICAL = 0x00002000;
/**
* <p>Mask for use with setFlags indicating bits used for indicating which
* fading edges are enabled.</p>
* {@hide}
*/
static final int FADING_EDGE_MASK = 0x00003000;
/**
* <p>Indicates this view can be clicked. When clickable, a View reacts
* to clicks by notifying the OnClickListener.<p>
* {@hide}
*/
static final int CLICKABLE = 0x00004000;
/**
* <p>Indicates this view is caching its drawing into a bitmap.</p>
* {@hide}
*/
static final int DRAWING_CACHE_ENABLED = 0x00008000;
/**
* <p>Indicates that no icicle should be saved for this view.<p>
* {@hide}
*/
static final int SAVE_DISABLED = 0x000010000;
/**
* <p>Mask for use with setFlags indicating bits used for the saveEnabled
* property.</p>
* {@hide}
*/
static final int SAVE_DISABLED_MASK = 0x000010000;
/**
* <p>Indicates that no drawing cache should ever be created for this view.<p>
* {@hide}
*/
static final int WILL_NOT_CACHE_DRAWING = 0x000020000;
/**
* <p>Indicates this view can take / keep focus when int touch mode.</p>
* {@hide}
*/
static final int FOCUSABLE_IN_TOUCH_MODE = 0x00040000;
/**
* <p>Enables low quality mode for the drawing cache.</p>
*/
public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000;
/**
* <p>Enables high quality mode for the drawing cache.</p>
*/
public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000;
/**
* <p>Enables automatic quality mode for the drawing cache.</p>
*/
public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000;
private static final int[] DRAWING_CACHE_QUALITY_FLAGS = {
DRAWING_CACHE_QUALITY_AUTO, DRAWING_CACHE_QUALITY_LOW, DRAWING_CACHE_QUALITY_HIGH
};
/**
* <p>Mask for use with setFlags indicating bits used for the cache
* quality property.</p>
* {@hide}
*/
static final int DRAWING_CACHE_QUALITY_MASK = 0x00180000;
/**
* <p>
* Indicates this view can be long clicked. When long clickable, a View
* reacts to long clicks by notifying the OnLongClickListener or showing a
* context menu.
* </p>
* {@hide}
*/
static final int LONG_CLICKABLE = 0x00200000;
/**
* <p>Indicates that this view gets its drawable states from its direct parent
* and ignores its original internal states.</p>
*
* @hide
*/
static final int DUPLICATE_PARENT_STATE = 0x00400000;
/**
* The scrollbar style to display the scrollbars inside the content area,
* without increasing the padding. The scrollbars will be overlaid with
* translucency on the view's content.
*/
public static final int SCROLLBARS_INSIDE_OVERLAY = 0;
/**
* The scrollbar style to display the scrollbars inside the padded area,
* increasing the padding of the view. The scrollbars will not overlap the
* content area of the view.
*/
public static final int SCROLLBARS_INSIDE_INSET = 0x01000000;
/**
* The scrollbar style to display the scrollbars at the edge of the view,
* without increasing the padding. The scrollbars will be overlaid with
* translucency.
*/
public static final int SCROLLBARS_OUTSIDE_OVERLAY = 0x02000000;
/**
* The scrollbar style to display the scrollbars at the edge of the view,
* increasing the padding of the view. The scrollbars will only overlap the
* background, if any.
*/
public static final int SCROLLBARS_OUTSIDE_INSET = 0x03000000;
/**
* Mask to check if the scrollbar style is overlay or inset.
* {@hide}
*/
static final int SCROLLBARS_INSET_MASK = 0x01000000;
/**
* Mask to check if the scrollbar style is inside or outside.
* {@hide}
*/
static final int SCROLLBARS_OUTSIDE_MASK = 0x02000000;
/**
* Mask for scrollbar style.
* {@hide}
*/
static final int SCROLLBARS_STYLE_MASK = 0x03000000;
/**
* View flag indicating that the screen should remain on while the
* window containing this view is visible to the user. This effectively
* takes care of automatically setting the WindowManager's
* {@link WindowManager.LayoutParams#FLAG_KEEP_SCREEN_ON}.
*/
public static final int KEEP_SCREEN_ON = 0x04000000;
/**
* View flag indicating whether this view should have sound effects enabled
* for events such as clicking and touching.
*/
public static final int SOUND_EFFECTS_ENABLED = 0x08000000;
/**
* View flag indicating whether this view should have haptic feedback
* enabled for events such as long presses.
*/
public static final int HAPTIC_FEEDBACK_ENABLED = 0x10000000;
/**
* View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
* should add all focusable Views regardless if they are focusable in touch mode.
*/
public static final int FOCUSABLES_ALL = 0x00000000;
/**
* View flag indicating whether {@link #addFocusables(ArrayList, int, int)}
* should add only Views focusable in touch mode.
*/
public static final int FOCUSABLES_TOUCH_MODE = 0x00000001;
/**
* Use with {@link #focusSearch}. Move focus to the previous selectable
* item.
*/
public static final int FOCUS_BACKWARD = 0x00000001;
/**
* Use with {@link #focusSearch}. Move focus to the next selectable
* item.
*/
public static final int FOCUS_FORWARD = 0x00000002;
/**
* Use with {@link #focusSearch}. Move focus to the left.
*/
public static final int FOCUS_LEFT = 0x00000011;
/**
* Use with {@link #focusSearch}. Move focus up.
*/
public static final int FOCUS_UP = 0x00000021;
/**
* Use with {@link #focusSearch}. Move focus to the right.
*/
public static final int FOCUS_RIGHT = 0x00000042;
/**
* Use with {@link #focusSearch}. Move focus down.
*/
public static final int FOCUS_DOWN = 0x00000082;
/**
* Base View state sets
*/
// Singles
/**
* Indicates the view has no states set. States are used with
* {@link android.graphics.drawable.Drawable} to change the drawing of the
* view depending on its state.
*
* @see android.graphics.drawable.Drawable
* @see #getDrawableState()
*/
protected static final int[] EMPTY_STATE_SET = {};
/**
* Indicates the view is enabled. States are used with
* {@link android.graphics.drawable.Drawable} to change the drawing of the
* view depending on its state.
*
* @see android.graphics.drawable.Drawable
* @see #getDrawableState()
*/
protected static final int[] ENABLED_STATE_SET = {R.attr.state_enabled};
/**
* Indicates the view is focused. States are used with
* {@link android.graphics.drawable.Drawable} to change the drawing of the
* view depending on its state.
*
* @see android.graphics.drawable.Drawable
* @see #getDrawableState()
*/
protected static final int[] FOCUSED_STATE_SET = {R.attr.state_focused};
/**
* Indicates the view is selected. States are used with
* {@link android.graphics.drawable.Drawable} to change the drawing of the
* view depending on its state.
*
* @see android.graphics.drawable.Drawable
* @see #getDrawableState()
*/
protected static final int[] SELECTED_STATE_SET = {R.attr.state_selected};
/**
* Indicates the view is pressed. States are used with
* {@link android.graphics.drawable.Drawable} to change the drawing of the
* view depending on its state.
*
* @see android.graphics.drawable.Drawable
* @see #getDrawableState()
* @hide
*/
protected static final int[] PRESSED_STATE_SET = {R.attr.state_pressed};
/**
* Indicates the view's window has focus. States are used with
* {@link android.graphics.drawable.Drawable} to change the drawing of the
* view depending on its state.
*
* @see android.graphics.drawable.Drawable
* @see #getDrawableState()
*/
protected static final int[] WINDOW_FOCUSED_STATE_SET =
{R.attr.state_window_focused};
// Doubles
/**
* Indicates the view is enabled and has the focus.
*
* @see #ENABLED_STATE_SET
* @see #FOCUSED_STATE_SET
*/
protected static final int[] ENABLED_FOCUSED_STATE_SET =
stateSetUnion(ENABLED_STATE_SET, FOCUSED_STATE_SET);
/**
* Indicates the view is enabled and selected.
*
* @see #ENABLED_STATE_SET
* @see #SELECTED_STATE_SET
*/
protected static final int[] ENABLED_SELECTED_STATE_SET =
stateSetUnion(ENABLED_STATE_SET, SELECTED_STATE_SET);
/**
* Indicates the view is enabled and that its window has focus.
*
* @see #ENABLED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] ENABLED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is focused and selected.
*
* @see #FOCUSED_STATE_SET
* @see #SELECTED_STATE_SET
*/
protected static final int[] FOCUSED_SELECTED_STATE_SET =
stateSetUnion(FOCUSED_STATE_SET, SELECTED_STATE_SET);
/**
* Indicates the view has the focus and that its window has the focus.
*
* @see #FOCUSED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] FOCUSED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is selected and that its window has the focus.
*
* @see #SELECTED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] SELECTED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
// Triples
/**
* Indicates the view is enabled, focused and selected.
*
* @see #ENABLED_STATE_SET
* @see #FOCUSED_STATE_SET
* @see #SELECTED_STATE_SET
*/
protected static final int[] ENABLED_FOCUSED_SELECTED_STATE_SET =
stateSetUnion(ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
/**
* Indicates the view is enabled, focused and its window has the focus.
*
* @see #ENABLED_STATE_SET
* @see #FOCUSED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is enabled, selected and its window has the focus.
*
* @see #ENABLED_STATE_SET
* @see #SELECTED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is focused, selected and its window has the focus.
*
* @see #FOCUSED_STATE_SET
* @see #SELECTED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is enabled, focused, selected and its window
* has the focus.
*
* @see #ENABLED_STATE_SET
* @see #FOCUSED_STATE_SET
* @see #SELECTED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(ENABLED_FOCUSED_SELECTED_STATE_SET,
WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is pressed and its window has the focus.
*
* @see #PRESSED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(PRESSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is pressed and selected.
*
* @see #PRESSED_STATE_SET
* @see #SELECTED_STATE_SET
*/
protected static final int[] PRESSED_SELECTED_STATE_SET =
stateSetUnion(PRESSED_STATE_SET, SELECTED_STATE_SET);
/**
* Indicates the view is pressed, selected and its window has the focus.
*
* @see #PRESSED_STATE_SET
* @see #SELECTED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(PRESSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is pressed and focused.
*
* @see #PRESSED_STATE_SET
* @see #FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_FOCUSED_STATE_SET =
stateSetUnion(PRESSED_STATE_SET, FOCUSED_STATE_SET);
/**
* Indicates the view is pressed, focused and its window has the focus.
*
* @see #PRESSED_STATE_SET
* @see #FOCUSED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(PRESSED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is pressed, focused and selected.
*
* @see #PRESSED_STATE_SET
* @see #SELECTED_STATE_SET
* @see #FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_FOCUSED_SELECTED_STATE_SET =
stateSetUnion(PRESSED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
/**
* Indicates the view is pressed, focused, selected and its window has the focus.
*
* @see #PRESSED_STATE_SET
* @see #FOCUSED_STATE_SET
* @see #SELECTED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(PRESSED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is pressed and enabled.
*
* @see #PRESSED_STATE_SET
* @see #ENABLED_STATE_SET
*/
protected static final int[] PRESSED_ENABLED_STATE_SET =
stateSetUnion(PRESSED_STATE_SET, ENABLED_STATE_SET);
/**
* Indicates the view is pressed, enabled and its window has the focus.
*
* @see #PRESSED_STATE_SET
* @see #ENABLED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(PRESSED_ENABLED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is pressed, enabled and selected.
*
* @see #PRESSED_STATE_SET
* @see #ENABLED_STATE_SET
* @see #SELECTED_STATE_SET
*/
protected static final int[] PRESSED_ENABLED_SELECTED_STATE_SET =
stateSetUnion(PRESSED_ENABLED_STATE_SET, SELECTED_STATE_SET);
/**
* Indicates the view is pressed, enabled, selected and its window has the
* focus.
*
* @see #PRESSED_STATE_SET
* @see #ENABLED_STATE_SET
* @see #SELECTED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(PRESSED_ENABLED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is pressed, enabled and focused.
*
* @see #PRESSED_STATE_SET
* @see #ENABLED_STATE_SET
* @see #FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_ENABLED_FOCUSED_STATE_SET =
stateSetUnion(PRESSED_ENABLED_STATE_SET, FOCUSED_STATE_SET);
/**
* Indicates the view is pressed, enabled, focused and its window has the
* focus.
*
* @see #PRESSED_STATE_SET
* @see #ENABLED_STATE_SET
* @see #FOCUSED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* Indicates the view is pressed, enabled, focused and selected.
*
* @see #PRESSED_STATE_SET
* @see #ENABLED_STATE_SET
* @see #SELECTED_STATE_SET
* @see #FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET =
stateSetUnion(PRESSED_ENABLED_FOCUSED_STATE_SET, SELECTED_STATE_SET);
/**
* Indicates the view is pressed, enabled, focused, selected and its window
* has the focus.
*
* @see #PRESSED_STATE_SET
* @see #ENABLED_STATE_SET
* @see #SELECTED_STATE_SET
* @see #FOCUSED_STATE_SET
* @see #WINDOW_FOCUSED_STATE_SET
*/
protected static final int[] PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET =
stateSetUnion(PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, WINDOW_FOCUSED_STATE_SET);
/**
* The order here is very important to {@link #getDrawableState()}
*/
private static final int[][] VIEW_STATE_SETS = {
EMPTY_STATE_SET, // 0 0 0 0 0
WINDOW_FOCUSED_STATE_SET, // 0 0 0 0 1
SELECTED_STATE_SET, // 0 0 0 1 0
SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 0 1 1
FOCUSED_STATE_SET, // 0 0 1 0 0
FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 0 1
FOCUSED_SELECTED_STATE_SET, // 0 0 1 1 0
FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 0 1 1 1
ENABLED_STATE_SET, // 0 1 0 0 0
ENABLED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 0 1
ENABLED_SELECTED_STATE_SET, // 0 1 0 1 0
ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 0 1 1
ENABLED_FOCUSED_STATE_SET, // 0 1 1 0 0
ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 0 1
ENABLED_FOCUSED_SELECTED_STATE_SET, // 0 1 1 1 0
ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 0 1 1 1 1
PRESSED_STATE_SET, // 1 0 0 0 0
PRESSED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 0 1
PRESSED_SELECTED_STATE_SET, // 1 0 0 1 0
PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 0 1 1
PRESSED_FOCUSED_STATE_SET, // 1 0 1 0 0
PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 0 1
PRESSED_FOCUSED_SELECTED_STATE_SET, // 1 0 1 1 0
PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 0 1 1 1
PRESSED_ENABLED_STATE_SET, // 1 1 0 0 0
PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 0 1
PRESSED_ENABLED_SELECTED_STATE_SET, // 1 1 0 1 0
PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 0 1 1
PRESSED_ENABLED_FOCUSED_STATE_SET, // 1 1 1 0 0
PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 0 1
PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET, // 1 1 1 1 0
PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET, // 1 1 1 1 1
};
/**
* Used by views that contain lists of items. This state indicates that
* the view is showing the last item.
* @hide
*/
protected static final int[] LAST_STATE_SET = {R.attr.state_last};
/**
* Used by views that contain lists of items. This state indicates that
* the view is showing the first item.
* @hide
*/
protected static final int[] FIRST_STATE_SET = {R.attr.state_first};
/**
* Used by views that contain lists of items. This state indicates that
* the view is showing the middle item.
* @hide
*/
protected static final int[] MIDDLE_STATE_SET = {R.attr.state_middle};
/**
* Used by views that contain lists of items. This state indicates that
* the view is showing only one item.
* @hide
*/
protected static final int[] SINGLE_STATE_SET = {R.attr.state_single};
/**
* Used by views that contain lists of items. This state indicates that
* the view is pressed and showing the last item.
* @hide
*/
protected static final int[] PRESSED_LAST_STATE_SET = {R.attr.state_last, R.attr.state_pressed};
/**
* Used by views that contain lists of items. This state indicates that
* the view is pressed and showing the first item.
* @hide
*/
protected static final int[] PRESSED_FIRST_STATE_SET = {R.attr.state_first, R.attr.state_pressed};
/**
* Used by views that contain lists of items. This state indicates that
* the view is pressed and showing the middle item.
* @hide
*/
protected static final int[] PRESSED_MIDDLE_STATE_SET = {R.attr.state_middle, R.attr.state_pressed};
/**
* Used by views that contain lists of items. This state indicates that
* the view is pressed and showing only one item.
* @hide
*/
protected static final int[] PRESSED_SINGLE_STATE_SET = {R.attr.state_single, R.attr.state_pressed};
/**
* Temporary Rect currently for use in setBackground(). This will probably
* be extended in the future to hold our own class with more than just
* a Rect. :)
*/
static final ThreadLocal<Rect> sThreadLocal = new ThreadLocal<Rect>();
/**
* Map used to store views' tags.
*/
private static WeakHashMap<View, SparseArray<Object>> sTags;
/**
* Lock used to access sTags.
*/
private static final Object sTagsLock = new Object();
/**
* The animation currently associated with this view.
* @hide
*/
protected Animation mCurrentAnimation = null;
/**
* Width as measured during measure pass.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mMeasuredWidth;
/**
* Height as measured during measure pass.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mMeasuredHeight;
/**
* The view's identifier.
* {@hide}
*
* @see #setId(int)
* @see #getId()
*/
@ViewDebug.ExportedProperty(resolveId = true)
int mID = NO_ID;
/**
* The view's tag.
* {@hide}
*
* @see #setTag(Object)
* @see #getTag()
*/
protected Object mTag;
// for mPrivateFlags:
/** {@hide} */
static final int WANTS_FOCUS = 0x00000001;
/** {@hide} */
static final int FOCUSED = 0x00000002;
/** {@hide} */
static final int SELECTED = 0x00000004;
/** {@hide} */
static final int IS_ROOT_NAMESPACE = 0x00000008;
/** {@hide} */
static final int HAS_BOUNDS = 0x00000010;
/** {@hide} */
static final int DRAWN = 0x00000020;
/**
* When this flag is set, this view is running an animation on behalf of its
* children and should therefore not cancel invalidate requests, even if they
* lie outside of this view's bounds.
*
* {@hide}
*/
static final int DRAW_ANIMATION = 0x00000040;
/** {@hide} */
static final int SKIP_DRAW = 0x00000080;
/** {@hide} */
static final int ONLY_DRAWS_BACKGROUND = 0x00000100;
/** {@hide} */
static final int REQUEST_TRANSPARENT_REGIONS = 0x00000200;
/** {@hide} */
static final int DRAWABLE_STATE_DIRTY = 0x00000400;
/** {@hide} */
static final int MEASURED_DIMENSION_SET = 0x00000800;
/** {@hide} */
static final int FORCE_LAYOUT = 0x00001000;
private static final int LAYOUT_REQUIRED = 0x00002000;
private static final int PRESSED = 0x00004000;
/** {@hide} */
static final int DRAWING_CACHE_VALID = 0x00008000;
/**
* Flag used to indicate that this view should be drawn once more (and only once
* more) after its animation has completed.
* {@hide}
*/
static final int ANIMATION_STARTED = 0x00010000;
private static final int SAVE_STATE_CALLED = 0x00020000;
/**
* Indicates that the View returned true when onSetAlpha() was called and that
* the alpha must be restored.
* {@hide}
*/
static final int ALPHA_SET = 0x00040000;
/**
* Set by {@link #setScrollContainer(boolean)}.
*/
static final int SCROLL_CONTAINER = 0x00080000;
/**
* Set by {@link #setScrollContainer(boolean)}.
*/
static final int SCROLL_CONTAINER_ADDED = 0x00100000;
/**
* View flag indicating whether this view was invalidated (fully or partially.)
*
* @hide
*/
static final int DIRTY = 0x00200000;
/**
* View flag indicating whether this view was invalidated by an opaque
* invalidate request.
*
* @hide
*/
static final int DIRTY_OPAQUE = 0x00400000;
/**
* Mask for {@link #DIRTY} and {@link #DIRTY_OPAQUE}.
*
* @hide
*/
static final int DIRTY_MASK = 0x00600000;
/**
* Indicates whether the background is opaque.
*
* @hide
*/
static final int OPAQUE_BACKGROUND = 0x00800000;
/**
* Indicates whether the scrollbars are opaque.
*
* @hide
*/
static final int OPAQUE_SCROLLBARS = 0x01000000;
/**
* Indicates whether the view is opaque.
*
* @hide
*/
static final int OPAQUE_MASK = 0x01800000;
/**
* The parent this view is attached to.
* {@hide}
*
* @see #getParent()
*/
protected ViewParent mParent;
/**
* {@hide}
*/
AttachInfo mAttachInfo;
/**
* {@hide}
*/
@ViewDebug.ExportedProperty(flagMapping = {
@ViewDebug.FlagToString(mask = FORCE_LAYOUT, equals = FORCE_LAYOUT,
name = "FORCE_LAYOUT"),
@ViewDebug.FlagToString(mask = LAYOUT_REQUIRED, equals = LAYOUT_REQUIRED,
name = "LAYOUT_REQUIRED"),
@ViewDebug.FlagToString(mask = DRAWING_CACHE_VALID, equals = DRAWING_CACHE_VALID,
name = "DRAWING_CACHE_INVALID", outputIf = false),
@ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "DRAWN", outputIf = true),
@ViewDebug.FlagToString(mask = DRAWN, equals = DRAWN, name = "NOT_DRAWN", outputIf = false),
@ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY_OPAQUE, name = "DIRTY_OPAQUE"),
@ViewDebug.FlagToString(mask = DIRTY_MASK, equals = DIRTY, name = "DIRTY")
})
int mPrivateFlags;
/**
* Count of how many windows this view has been attached to.
*/
int mWindowAttachCount;
/**
* The layout parameters associated with this view and used by the parent
* {@link android.view.ViewGroup} to determine how this view should be
* laid out.
* {@hide}
*/
protected ViewGroup.LayoutParams mLayoutParams;
/**
* The view flags hold various views states.
* {@hide}
*/
@ViewDebug.ExportedProperty
int mViewFlags;
/**
* The distance in pixels from the left edge of this view's parent
* to the left edge of this view.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mLeft;
/**
* The distance in pixels from the left edge of this view's parent
* to the right edge of this view.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mRight;
/**
* The distance in pixels from the top edge of this view's parent
* to the top edge of this view.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mTop;
/**
* The distance in pixels from the top edge of this view's parent
* to the bottom edge of this view.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mBottom;
/**
* The offset, in pixels, by which the content of this view is scrolled
* horizontally.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mScrollX;
/**
* The offset, in pixels, by which the content of this view is scrolled
* vertically.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mScrollY;
/**
* The left padding in pixels, that is the distance in pixels between the
* left edge of this view and the left edge of its content.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mPaddingLeft;
/**
* The right padding in pixels, that is the distance in pixels between the
* right edge of this view and the right edge of its content.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mPaddingRight;
/**
* The top padding in pixels, that is the distance in pixels between the
* top edge of this view and the top edge of its content.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mPaddingTop;
/**
* The bottom padding in pixels, that is the distance in pixels between the
* bottom edge of this view and the bottom edge of its content.
* {@hide}
*/
@ViewDebug.ExportedProperty
protected int mPaddingBottom;
/**
* Briefly describes the view and is primarily used for accessibility support.
*/
private CharSequence mContentDescription;
/**
* Cache the paddingRight set by the user to append to the scrollbar's size.
*/
@ViewDebug.ExportedProperty
int mUserPaddingRight;
/**
* Cache the paddingBottom set by the user to append to the scrollbar's size.
*/
@ViewDebug.ExportedProperty
int mUserPaddingBottom;
/**
* @hide
*/
int mOldWidthMeasureSpec = Integer.MIN_VALUE;
/**
* @hide
*/
int mOldHeightMeasureSpec = Integer.MIN_VALUE;
private Resources mResources = null;
private Drawable mBGDrawable;
private int mBackgroundResource;
private boolean mBackgroundSizeChanged;
/**
* Listener used to dispatch focus change events.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
protected OnFocusChangeListener mOnFocusChangeListener;
/**
* Listener used to dispatch click events.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
protected OnClickListener mOnClickListener;
/**
* Listener used to dispatch long click events.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
protected OnLongClickListener mOnLongClickListener;
/**
* Listener used to build the context menu.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
protected OnCreateContextMenuListener mOnCreateContextMenuListener;
private OnKeyListener mOnKeyListener;
private OnTouchListener mOnTouchListener;
/**
* The application environment this view lives in.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
*/
protected Context mContext;
private ScrollabilityCache mScrollCache;
private int[] mDrawableState = null;
private SoftReference<Bitmap> mDrawingCache;
/**
* When this view has focus and the next focus is {@link #FOCUS_LEFT},
* the user may specify which view to go to next.
*/
private int mNextFocusLeftId = View.NO_ID;
/**
* When this view has focus and the next focus is {@link #FOCUS_RIGHT},
* the user may specify which view to go to next.
*/
private int mNextFocusRightId = View.NO_ID;
/**
* When this view has focus and the next focus is {@link #FOCUS_UP},
* the user may specify which view to go to next.
*/
private int mNextFocusUpId = View.NO_ID;
/**
* When this view has focus and the next focus is {@link #FOCUS_DOWN},
* the user may specify which view to go to next.
*/
private int mNextFocusDownId = View.NO_ID;
private CheckForLongPress mPendingCheckForLongPress;
private UnsetPressedState mUnsetPressedState;
/**
* Whether the long press's action has been invoked. The tap's action is invoked on the
* up event while a long press is invoked as soon as the long press duration is reached, so
* a long press could be performed before the tap is checked, in which case the tap's action
* should not be invoked.
*/
private boolean mHasPerformedLongPress;
/**
* The minimum height of the view. We'll try our best to have the height
* of this view to at least this amount.
*/
@ViewDebug.ExportedProperty
private int mMinHeight;
/**
* The minimum width of the view. We'll try our best to have the width
* of this view to at least this amount.
*/
@ViewDebug.ExportedProperty
private int mMinWidth;
/**
* The delegate to handle touch events that are physically in this view
* but should be handled by another view.
*/
private TouchDelegate mTouchDelegate = null;
/**
* Solid color to use as a background when creating the drawing cache. Enables
* the cache to use 16 bit bitmaps instead of 32 bit.
*/
private int mDrawingCacheBackgroundColor = 0;
/**
* Special tree observer used when mAttachInfo is null.
*/
private ViewTreeObserver mFloatingTreeObserver;
// Used for debug only
static long sInstanceCount = 0;
/**
* Simple constructor to use when creating a view from code.
*
* @param context The Context the view is running in, through which it can
* access the current theme, resources, etc.
*/
public View(Context context) {
mContext = context;
mResources = context != null ? context.getResources() : null;
mViewFlags = SOUND_EFFECTS_ENABLED | HAPTIC_FEEDBACK_ENABLED;
++sInstanceCount;
}
/**
* Constructor that is called when inflating a view from XML. This is called
* when a view is being constructed from an XML file, supplying attributes
* that were specified in the XML file. This version uses a default style of
* 0, so the only attribute values applied are those in the Context's Theme
* and the given AttributeSet.
*
* <p>
* The method onFinishInflate() will be called after all children have been
* added.
*
* @param context The Context the view is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the view.
* @see #View(Context, AttributeSet, int)
*/
public View(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Perform inflation from XML and apply a class-specific base style. This
* constructor of View allows subclasses to use their own base style when
* they are inflating. For example, a Button class's constructor would call
* this version of the super class constructor and supply
* <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
* the theme's button style to modify all of the base view attributes (in
* particular its background) as well as the Button class's attributes.
*
* @param context The Context the view is running in, through which it can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the view.
* @param defStyle The default style to apply to this view. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
* @see #View(Context, AttributeSet)
*/
public View(Context context, AttributeSet attrs, int defStyle) {
this(context);
TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
defStyle, 0);
Drawable background = null;
int leftPadding = -1;
int topPadding = -1;
int rightPadding = -1;
int bottomPadding = -1;
int padding = -1;
int viewFlagValues = 0;
int viewFlagMasks = 0;
boolean setScrollContainer = false;
int x = 0;
int y = 0;
int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
switch (attr) {
case com.android.internal.R.styleable.View_background:
background = a.getDrawable(attr);
break;
case com.android.internal.R.styleable.View_padding:
padding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingLeft:
leftPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingTop:
topPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingRight:
rightPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingBottom:
bottomPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_scrollX:
x = a.getDimensionPixelOffset(attr, 0);
break;
case com.android.internal.R.styleable.View_scrollY:
y = a.getDimensionPixelOffset(attr, 0);
break;
case com.android.internal.R.styleable.View_id:
mID = a.getResourceId(attr, NO_ID);
break;
case com.android.internal.R.styleable.View_tag:
mTag = a.getText(attr);
break;
case com.android.internal.R.styleable.View_fitsSystemWindows:
if (a.getBoolean(attr, false)) {
viewFlagValues |= FITS_SYSTEM_WINDOWS;
viewFlagMasks |= FITS_SYSTEM_WINDOWS;
}
break;
case com.android.internal.R.styleable.View_focusable:
if (a.getBoolean(attr, false)) {
viewFlagValues |= FOCUSABLE;
viewFlagMasks |= FOCUSABLE_MASK;
}
break;
case com.android.internal.R.styleable.View_focusableInTouchMode:
if (a.getBoolean(attr, false)) {
viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
}
break;
case com.android.internal.R.styleable.View_clickable:
if (a.getBoolean(attr, false)) {
viewFlagValues |= CLICKABLE;
viewFlagMasks |= CLICKABLE;
}
break;
case com.android.internal.R.styleable.View_longClickable:
if (a.getBoolean(attr, false)) {
viewFlagValues |= LONG_CLICKABLE;
viewFlagMasks |= LONG_CLICKABLE;
}
break;
case com.android.internal.R.styleable.View_saveEnabled:
if (!a.getBoolean(attr, true)) {
viewFlagValues |= SAVE_DISABLED;
viewFlagMasks |= SAVE_DISABLED_MASK;
}
break;
case com.android.internal.R.styleable.View_duplicateParentState:
if (a.getBoolean(attr, false)) {
viewFlagValues |= DUPLICATE_PARENT_STATE;
viewFlagMasks |= DUPLICATE_PARENT_STATE;
}
break;
case com.android.internal.R.styleable.View_visibility:
final int visibility = a.getInt(attr, 0);
if (visibility != 0) {
viewFlagValues |= VISIBILITY_FLAGS[visibility];
viewFlagMasks |= VISIBILITY_MASK;
}
break;
case com.android.internal.R.styleable.View_drawingCacheQuality:
final int cacheQuality = a.getInt(attr, 0);
if (cacheQuality != 0) {
viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
}
break;
case com.android.internal.R.styleable.View_contentDescription:
mContentDescription = a.getString(attr);
break;
case com.android.internal.R.styleable.View_soundEffectsEnabled:
if (!a.getBoolean(attr, true)) {
viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
viewFlagMasks |= SOUND_EFFECTS_ENABLED;
}
+ break;
case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
if (!a.getBoolean(attr, true)) {
viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
}
+ break;
case R.styleable.View_scrollbars:
final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
if (scrollbars != SCROLLBARS_NONE) {
viewFlagValues |= scrollbars;
viewFlagMasks |= SCROLLBARS_MASK;
initializeScrollbars(a);
}
break;
case R.styleable.View_fadingEdge:
final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
if (fadingEdge != FADING_EDGE_NONE) {
viewFlagValues |= fadingEdge;
viewFlagMasks |= FADING_EDGE_MASK;
initializeFadingEdge(a);
}
break;
case R.styleable.View_scrollbarStyle:
scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
viewFlagMasks |= SCROLLBARS_STYLE_MASK;
}
break;
case R.styleable.View_isScrollContainer:
setScrollContainer = true;
if (a.getBoolean(attr, false)) {
setScrollContainer(true);
}
break;
case com.android.internal.R.styleable.View_keepScreenOn:
if (a.getBoolean(attr, false)) {
viewFlagValues |= KEEP_SCREEN_ON;
viewFlagMasks |= KEEP_SCREEN_ON;
}
break;
case R.styleable.View_nextFocusLeft:
mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_nextFocusRight:
mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_nextFocusUp:
mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_nextFocusDown:
mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_minWidth:
mMinWidth = a.getDimensionPixelSize(attr, 0);
break;
case R.styleable.View_minHeight:
mMinHeight = a.getDimensionPixelSize(attr, 0);
break;
case R.styleable.View_onClick:
final String handlerName = a.getString(attr);
if (handlerName != null) {
setOnClickListener(new OnClickListener() {
private Method mHandler;
public void onClick(View v) {
if (mHandler == null) {
try {
mHandler = getContext().getClass().getMethod(handlerName,
View.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity", e);
}
}
try {
mHandler.invoke(getContext(), View.this);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not execute non "
+ "public method of the activity", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not execute "
+ "method of the activity", e);
}
}
});
}
break;
}
}
if (background != null) {
setBackgroundDrawable(background);
}
if (padding >= 0) {
leftPadding = padding;
topPadding = padding;
rightPadding = padding;
bottomPadding = padding;
}
// If the user specified the padding (either with android:padding or
// android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
// use the default padding or the padding from the background drawable
// (stored at this point in mPadding*)
setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
topPadding >= 0 ? topPadding : mPaddingTop,
rightPadding >= 0 ? rightPadding : mPaddingRight,
bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
if (viewFlagMasks != 0) {
setFlags(viewFlagValues, viewFlagMasks);
}
// Needs to be called after mViewFlags is set
if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
recomputePadding();
}
if (x != 0 || y != 0) {
scrollTo(x, y);
}
if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
setScrollContainer(true);
}
computeOpaqueFlags();
a.recycle();
}
/**
* Non-public constructor for use in testing
*/
View() {
}
@Override
protected void finalize() throws Throwable {
super.finalize();
--sInstanceCount;
}
/**
* <p>
* Initializes the fading edges from a given set of styled attributes. This
* method should be called by subclasses that need fading edges and when an
* instance of these subclasses is created programmatically rather than
* being inflated from XML. This method is automatically called when the XML
* is inflated.
* </p>
*
* @param a the styled attributes set to initialize the fading edges from
*/
protected void initializeFadingEdge(TypedArray a) {
initScrollCache();
mScrollCache.fadingEdgeLength = a.getDimensionPixelSize(
R.styleable.View_fadingEdgeLength,
ViewConfiguration.get(mContext).getScaledFadingEdgeLength());
}
/**
* Returns the size of the vertical faded edges used to indicate that more
* content in this view is visible.
*
* @return The size in pixels of the vertical faded edge or 0 if vertical
* faded edges are not enabled for this view.
* @attr ref android.R.styleable#View_fadingEdgeLength
*/
public int getVerticalFadingEdgeLength() {
if (isVerticalFadingEdgeEnabled()) {
ScrollabilityCache cache = mScrollCache;
if (cache != null) {
return cache.fadingEdgeLength;
}
}
return 0;
}
/**
* Set the size of the faded edge used to indicate that more content in this
* view is available. Will not change whether the fading edge is enabled; use
* {@link #setVerticalFadingEdgeEnabled} or {@link #setHorizontalFadingEdgeEnabled}
* to enable the fading edge for the vertical or horizontal fading edges.
*
* @param length The size in pixels of the faded edge used to indicate that more
* content in this view is visible.
*/
public void setFadingEdgeLength(int length) {
initScrollCache();
mScrollCache.fadingEdgeLength = length;
}
/**
* Returns the size of the horizontal faded edges used to indicate that more
* content in this view is visible.
*
* @return The size in pixels of the horizontal faded edge or 0 if horizontal
* faded edges are not enabled for this view.
* @attr ref android.R.styleable#View_fadingEdgeLength
*/
public int getHorizontalFadingEdgeLength() {
if (isHorizontalFadingEdgeEnabled()) {
ScrollabilityCache cache = mScrollCache;
if (cache != null) {
return cache.fadingEdgeLength;
}
}
return 0;
}
/**
* Returns the width of the vertical scrollbar.
*
* @return The width in pixels of the vertical scrollbar or 0 if there
* is no vertical scrollbar.
*/
public int getVerticalScrollbarWidth() {
ScrollabilityCache cache = mScrollCache;
if (cache != null) {
ScrollBarDrawable scrollBar = cache.scrollBar;
if (scrollBar != null) {
int size = scrollBar.getSize(true);
if (size <= 0) {
size = cache.scrollBarSize;
}
return size;
}
return 0;
}
return 0;
}
/**
* Returns the height of the horizontal scrollbar.
*
* @return The height in pixels of the horizontal scrollbar or 0 if
* there is no horizontal scrollbar.
*/
protected int getHorizontalScrollbarHeight() {
ScrollabilityCache cache = mScrollCache;
if (cache != null) {
ScrollBarDrawable scrollBar = cache.scrollBar;
if (scrollBar != null) {
int size = scrollBar.getSize(false);
if (size <= 0) {
size = cache.scrollBarSize;
}
return size;
}
return 0;
}
return 0;
}
/**
* <p>
* Initializes the scrollbars from a given set of styled attributes. This
* method should be called by subclasses that need scrollbars and when an
* instance of these subclasses is created programmatically rather than
* being inflated from XML. This method is automatically called when the XML
* is inflated.
* </p>
*
* @param a the styled attributes set to initialize the scrollbars from
*/
protected void initializeScrollbars(TypedArray a) {
initScrollCache();
if (mScrollCache.scrollBar == null) {
mScrollCache.scrollBar = new ScrollBarDrawable();
}
final ScrollabilityCache scrollabilityCache = mScrollCache;
scrollabilityCache.scrollBarSize = a.getDimensionPixelSize(
com.android.internal.R.styleable.View_scrollbarSize,
ViewConfiguration.get(mContext).getScaledScrollBarSize());
Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal);
scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track);
Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal);
if (thumb != null) {
scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb);
}
boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack,
false);
if (alwaysDraw) {
scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true);
}
track = a.getDrawable(R.styleable.View_scrollbarTrackVertical);
scrollabilityCache.scrollBar.setVerticalTrackDrawable(track);
thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical);
if (thumb != null) {
scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb);
}
alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack,
false);
if (alwaysDraw) {
scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true);
}
// Re-apply user/background padding so that scrollbar(s) get added
recomputePadding();
}
/**
* <p>
* Initalizes the scrollability cache if necessary.
* </p>
*/
private void initScrollCache() {
if (mScrollCache == null) {
mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext));
}
}
/**
* Register a callback to be invoked when focus of this view changed.
*
* @param l The callback that will run.
*/
public void setOnFocusChangeListener(OnFocusChangeListener l) {
mOnFocusChangeListener = l;
}
/**
* Returns the focus-change callback registered for this view.
*
* @return The callback, or null if one is not registered.
*/
public OnFocusChangeListener getOnFocusChangeListener() {
return mOnFocusChangeListener;
}
/**
* Register a callback to be invoked when this view is clicked. If this view is not
* clickable, it becomes clickable.
*
* @param l The callback that will run
*
* @see #setClickable(boolean)
*/
public void setOnClickListener(OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
mOnClickListener = l;
}
/**
* Register a callback to be invoked when this view is clicked and held. If this view is not
* long clickable, it becomes long clickable.
*
* @param l The callback that will run
*
* @see #setLongClickable(boolean)
*/
public void setOnLongClickListener(OnLongClickListener l) {
if (!isLongClickable()) {
setLongClickable(true);
}
mOnLongClickListener = l;
}
/**
* Register a callback to be invoked when the context menu for this view is
* being built. If this view is not long clickable, it becomes long clickable.
*
* @param l The callback that will run
*
*/
public void setOnCreateContextMenuListener(OnCreateContextMenuListener l) {
if (!isLongClickable()) {
setLongClickable(true);
}
mOnCreateContextMenuListener = l;
}
/**
* Call this view's OnClickListener, if it is defined.
*
* @return True there was an assigned OnClickListener that was called, false
* otherwise is returned.
*/
public boolean performClick() {
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
if (mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mOnClickListener.onClick(this);
return true;
}
return false;
}
/**
* Call this view's OnLongClickListener, if it is defined. Invokes the context menu
* if the OnLongClickListener did not consume the event.
*
* @return True there was an assigned OnLongClickListener that was called, false
* otherwise is returned.
*/
public boolean performLongClick() {
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_LONG_CLICKED);
boolean handled = false;
if (mOnLongClickListener != null) {
handled = mOnLongClickListener.onLongClick(View.this);
}
if (!handled) {
handled = showContextMenu();
}
if (handled) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
}
return handled;
}
/**
* Bring up the context menu for this view.
*
* @return Whether a context menu was displayed.
*/
public boolean showContextMenu() {
return getParent().showContextMenuForChild(this);
}
/**
* Register a callback to be invoked when a key is pressed in this view.
* @param l the key listener to attach to this view
*/
public void setOnKeyListener(OnKeyListener l) {
mOnKeyListener = l;
}
/**
* Register a callback to be invoked when a touch event is sent to this view.
* @param l the touch listener to attach to this view
*/
public void setOnTouchListener(OnTouchListener l) {
mOnTouchListener = l;
}
/**
* Give this view focus. This will cause {@link #onFocusChanged} to be called.
*
* Note: this does not check whether this {@link View} should get focus, it just
* gives it focus no matter what. It should only be called internally by framework
* code that knows what it is doing, namely {@link #requestFocus(int, Rect)}.
*
* @param direction values are View.FOCUS_UP, View.FOCUS_DOWN,
* View.FOCUS_LEFT or View.FOCUS_RIGHT. This is the direction which
* focus moved when requestFocus() is called. It may not always
* apply, in which case use the default View.FOCUS_DOWN.
* @param previouslyFocusedRect The rectangle of the view that had focus
* prior in this View's coordinate system.
*/
void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
if (DBG) {
System.out.println(this + " requestFocus()");
}
if ((mPrivateFlags & FOCUSED) == 0) {
mPrivateFlags |= FOCUSED;
if (mParent != null) {
mParent.requestChildFocus(this, this);
}
onFocusChanged(true, direction, previouslyFocusedRect);
refreshDrawableState();
}
}
/**
* Request that a rectangle of this view be visible on the screen,
* scrolling if necessary just enough.
*
* <p>A View should call this if it maintains some notion of which part
* of its content is interesting. For example, a text editing view
* should call this when its cursor moves.
*
* @param rectangle The rectangle.
* @return Whether any parent scrolled.
*/
public boolean requestRectangleOnScreen(Rect rectangle) {
return requestRectangleOnScreen(rectangle, false);
}
/**
* Request that a rectangle of this view be visible on the screen,
* scrolling if necessary just enough.
*
* <p>A View should call this if it maintains some notion of which part
* of its content is interesting. For example, a text editing view
* should call this when its cursor moves.
*
* <p>When <code>immediate</code> is set to true, scrolling will not be
* animated.
*
* @param rectangle The rectangle.
* @param immediate True to forbid animated scrolling, false otherwise
* @return Whether any parent scrolled.
*/
public boolean requestRectangleOnScreen(Rect rectangle, boolean immediate) {
View child = this;
ViewParent parent = mParent;
boolean scrolled = false;
while (parent != null) {
scrolled |= parent.requestChildRectangleOnScreen(child,
rectangle, immediate);
// offset rect so next call has the rectangle in the
// coordinate system of its direct child.
rectangle.offset(child.getLeft(), child.getTop());
rectangle.offset(-child.getScrollX(), -child.getScrollY());
if (!(parent instanceof View)) {
break;
}
child = (View) parent;
parent = child.getParent();
}
return scrolled;
}
/**
* Called when this view wants to give up focus. This will cause
* {@link #onFocusChanged} to be called.
*/
public void clearFocus() {
if (DBG) {
System.out.println(this + " clearFocus()");
}
if ((mPrivateFlags & FOCUSED) != 0) {
mPrivateFlags &= ~FOCUSED;
if (mParent != null) {
mParent.clearChildFocus(this);
}
onFocusChanged(false, 0, null);
refreshDrawableState();
}
}
/**
* Called to clear the focus of a view that is about to be removed.
* Doesn't call clearChildFocus, which prevents this view from taking
* focus again before it has been removed from the parent
*/
void clearFocusForRemoval() {
if ((mPrivateFlags & FOCUSED) != 0) {
mPrivateFlags &= ~FOCUSED;
onFocusChanged(false, 0, null);
refreshDrawableState();
}
}
/**
* Called internally by the view system when a new view is getting focus.
* This is what clears the old focus.
*/
void unFocus() {
if (DBG) {
System.out.println(this + " unFocus()");
}
if ((mPrivateFlags & FOCUSED) != 0) {
mPrivateFlags &= ~FOCUSED;
onFocusChanged(false, 0, null);
refreshDrawableState();
}
}
/**
* Returns true if this view has focus iteself, or is the ancestor of the
* view that has focus.
*
* @return True if this view has or contains focus, false otherwise.
*/
@ViewDebug.ExportedProperty
public boolean hasFocus() {
return (mPrivateFlags & FOCUSED) != 0;
}
/**
* Returns true if this view is focusable or if it contains a reachable View
* for which {@link #hasFocusable()} returns true. A "reachable hasFocusable()"
* is a View whose parents do not block descendants focus.
*
* Only {@link #VISIBLE} views are considered focusable.
*
* @return True if the view is focusable or if the view contains a focusable
* View, false otherwise.
*
* @see ViewGroup#FOCUS_BLOCK_DESCENDANTS
*/
public boolean hasFocusable() {
return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
}
/**
* Called by the view system when the focus state of this view changes.
* When the focus change event is caused by directional navigation, direction
* and previouslyFocusedRect provide insight into where the focus is coming from.
* When overriding, be sure to call up through to the super class so that
* the standard focus handling will occur.
*
* @param gainFocus True if the View has focus; false otherwise.
* @param direction The direction focus has moved when requestFocus()
* is called to give this view focus. Values are
* View.FOCUS_UP, View.FOCUS_DOWN, View.FOCUS_LEFT or
* View.FOCUS_RIGHT. It may not always apply, in which
* case use the default.
* @param previouslyFocusedRect The rectangle, in this view's coordinate
* system, of the previously focused view. If applicable, this will be
* passed in as finer grained information about where the focus is coming
* from (in addition to direction). Will be <code>null</code> otherwise.
*/
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
if (gainFocus) {
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);
}
InputMethodManager imm = InputMethodManager.peekInstance();
if (!gainFocus) {
if (isPressed()) {
setPressed(false);
}
if (imm != null && mAttachInfo != null
&& mAttachInfo.mHasWindowFocus) {
imm.focusOut(this);
}
onFocusLost();
} else if (imm != null && mAttachInfo != null
&& mAttachInfo.mHasWindowFocus) {
imm.focusIn(this);
}
invalidate();
if (mOnFocusChangeListener != null) {
mOnFocusChangeListener.onFocusChange(this, gainFocus);
}
}
/**
* {@inheritDoc}
*/
public void sendAccessibilityEvent(int eventType) {
if (AccessibilityManager.getInstance(mContext).isEnabled()) {
sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType));
}
}
/**
* {@inheritDoc}
*/
public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
event.setClassName(getClass().getName());
event.setPackageName(getContext().getPackageName());
event.setEnabled(isEnabled());
event.setContentDescription(mContentDescription);
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED && mAttachInfo != null) {
ArrayList<View> focusablesTempList = mAttachInfo.mFocusablesTempList;
getRootView().addFocusables(focusablesTempList, View.FOCUS_FORWARD, FOCUSABLES_ALL);
event.setItemCount(focusablesTempList.size());
event.setCurrentItemIndex(focusablesTempList.indexOf(this));
focusablesTempList.clear();
}
dispatchPopulateAccessibilityEvent(event);
AccessibilityManager.getInstance(mContext).sendAccessibilityEvent(event);
}
/**
* Dispatches an {@link AccessibilityEvent} to the {@link View} children
* to be populated.
*
* @param event The event.
*
* @return True if the event population was completed.
*/
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
return false;
}
/**
* Gets the {@link View} description. It briefly describes the view and is
* primarily used for accessibility support. Set this property to enable
* better accessibility support for your application. This is especially
* true for views that do not have textual representation (For example,
* ImageButton).
*
* @return The content descriptiopn.
*
* @attr ref android.R.styleable#View_contentDescription
*/
public CharSequence getContentDescription() {
return mContentDescription;
}
/**
* Sets the {@link View} description. It briefly describes the view and is
* primarily used for accessibility support. Set this property to enable
* better accessibility support for your application. This is especially
* true for views that do not have textual representation (For example,
* ImageButton).
*
* @param contentDescription The content description.
*
* @attr ref android.R.styleable#View_contentDescription
*/
public void setContentDescription(CharSequence contentDescription) {
mContentDescription = contentDescription;
}
/**
* Invoked whenever this view loses focus, either by losing window focus or by losing
* focus within its window. This method can be used to clear any state tied to the
* focus. For instance, if a button is held pressed with the trackball and the window
* loses focus, this method can be used to cancel the press.
*
* Subclasses of View overriding this method should always call super.onFocusLost().
*
* @see #onFocusChanged(boolean, int, android.graphics.Rect)
* @see #onWindowFocusChanged(boolean)
*
* @hide pending API council approval
*/
protected void onFocusLost() {
resetPressedState();
}
private void resetPressedState() {
if ((mViewFlags & ENABLED_MASK) == DISABLED) {
return;
}
if (isPressed()) {
setPressed(false);
if (!mHasPerformedLongPress) {
if (mPendingCheckForLongPress != null) {
removeCallbacks(mPendingCheckForLongPress);
}
}
}
}
/**
* Returns true if this view has focus
*
* @return True if this view has focus, false otherwise.
*/
@ViewDebug.ExportedProperty
public boolean isFocused() {
return (mPrivateFlags & FOCUSED) != 0;
}
/**
* Find the view in the hierarchy rooted at this view that currently has
* focus.
*
* @return The view that currently has focus, or null if no focused view can
* be found.
*/
public View findFocus() {
return (mPrivateFlags & FOCUSED) != 0 ? this : null;
}
/**
* Change whether this view is one of the set of scrollable containers in
* its window. This will be used to determine whether the window can
* resize or must pan when a soft input area is open -- scrollable
* containers allow the window to use resize mode since the container
* will appropriately shrink.
*/
public void setScrollContainer(boolean isScrollContainer) {
if (isScrollContainer) {
if (mAttachInfo != null && (mPrivateFlags&SCROLL_CONTAINER_ADDED) == 0) {
mAttachInfo.mScrollContainers.add(this);
mPrivateFlags |= SCROLL_CONTAINER_ADDED;
}
mPrivateFlags |= SCROLL_CONTAINER;
} else {
if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
mAttachInfo.mScrollContainers.remove(this);
}
mPrivateFlags &= ~(SCROLL_CONTAINER|SCROLL_CONTAINER_ADDED);
}
}
/**
* Returns the quality of the drawing cache.
*
* @return One of {@link #DRAWING_CACHE_QUALITY_AUTO},
* {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
*
* @see #setDrawingCacheQuality(int)
* @see #setDrawingCacheEnabled(boolean)
* @see #isDrawingCacheEnabled()
*
* @attr ref android.R.styleable#View_drawingCacheQuality
*/
public int getDrawingCacheQuality() {
return mViewFlags & DRAWING_CACHE_QUALITY_MASK;
}
/**
* Set the drawing cache quality of this view. This value is used only when the
* drawing cache is enabled
*
* @param quality One of {@link #DRAWING_CACHE_QUALITY_AUTO},
* {@link #DRAWING_CACHE_QUALITY_LOW}, or {@link #DRAWING_CACHE_QUALITY_HIGH}
*
* @see #getDrawingCacheQuality()
* @see #setDrawingCacheEnabled(boolean)
* @see #isDrawingCacheEnabled()
*
* @attr ref android.R.styleable#View_drawingCacheQuality
*/
public void setDrawingCacheQuality(int quality) {
setFlags(quality, DRAWING_CACHE_QUALITY_MASK);
}
/**
* Returns whether the screen should remain on, corresponding to the current
* value of {@link #KEEP_SCREEN_ON}.
*
* @return Returns true if {@link #KEEP_SCREEN_ON} is set.
*
* @see #setKeepScreenOn(boolean)
*
* @attr ref android.R.styleable#View_keepScreenOn
*/
public boolean getKeepScreenOn() {
return (mViewFlags & KEEP_SCREEN_ON) != 0;
}
/**
* Controls whether the screen should remain on, modifying the
* value of {@link #KEEP_SCREEN_ON}.
*
* @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
*
* @see #getKeepScreenOn()
*
* @attr ref android.R.styleable#View_keepScreenOn
*/
public void setKeepScreenOn(boolean keepScreenOn) {
setFlags(keepScreenOn ? KEEP_SCREEN_ON : 0, KEEP_SCREEN_ON);
}
/**
* @return The user specified next focus ID.
*
* @attr ref android.R.styleable#View_nextFocusLeft
*/
public int getNextFocusLeftId() {
return mNextFocusLeftId;
}
/**
* Set the id of the view to use for the next focus
*
* @param nextFocusLeftId
*
* @attr ref android.R.styleable#View_nextFocusLeft
*/
public void setNextFocusLeftId(int nextFocusLeftId) {
mNextFocusLeftId = nextFocusLeftId;
}
/**
* @return The user specified next focus ID.
*
* @attr ref android.R.styleable#View_nextFocusRight
*/
public int getNextFocusRightId() {
return mNextFocusRightId;
}
/**
* Set the id of the view to use for the next focus
*
* @param nextFocusRightId
*
* @attr ref android.R.styleable#View_nextFocusRight
*/
public void setNextFocusRightId(int nextFocusRightId) {
mNextFocusRightId = nextFocusRightId;
}
/**
* @return The user specified next focus ID.
*
* @attr ref android.R.styleable#View_nextFocusUp
*/
public int getNextFocusUpId() {
return mNextFocusUpId;
}
/**
* Set the id of the view to use for the next focus
*
* @param nextFocusUpId
*
* @attr ref android.R.styleable#View_nextFocusUp
*/
public void setNextFocusUpId(int nextFocusUpId) {
mNextFocusUpId = nextFocusUpId;
}
/**
* @return The user specified next focus ID.
*
* @attr ref android.R.styleable#View_nextFocusDown
*/
public int getNextFocusDownId() {
return mNextFocusDownId;
}
/**
* Set the id of the view to use for the next focus
*
* @param nextFocusDownId
*
* @attr ref android.R.styleable#View_nextFocusDown
*/
public void setNextFocusDownId(int nextFocusDownId) {
mNextFocusDownId = nextFocusDownId;
}
/**
* Returns the visibility of this view and all of its ancestors
*
* @return True if this view and all of its ancestors are {@link #VISIBLE}
*/
public boolean isShown() {
View current = this;
//noinspection ConstantConditions
do {
if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
return false;
}
ViewParent parent = current.mParent;
if (parent == null) {
return false; // We are not attached to the view root
}
if (!(parent instanceof View)) {
return true;
}
current = (View) parent;
} while (current != null);
return false;
}
/**
* Apply the insets for system windows to this view, if the FITS_SYSTEM_WINDOWS flag
* is set
*
* @param insets Insets for system windows
*
* @return True if this view applied the insets, false otherwise
*/
protected boolean fitSystemWindows(Rect insets) {
if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {
mPaddingLeft = insets.left;
mPaddingTop = insets.top;
mPaddingRight = insets.right;
mPaddingBottom = insets.bottom;
requestLayout();
return true;
}
return false;
}
/**
* Returns the visibility status for this view.
*
* @return One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
* @attr ref android.R.styleable#View_visibility
*/
@ViewDebug.ExportedProperty(mapping = {
@ViewDebug.IntToString(from = VISIBLE, to = "VISIBLE"),
@ViewDebug.IntToString(from = INVISIBLE, to = "INVISIBLE"),
@ViewDebug.IntToString(from = GONE, to = "GONE")
})
public int getVisibility() {
return mViewFlags & VISIBILITY_MASK;
}
/**
* Set the enabled state of this view.
*
* @param visibility One of {@link #VISIBLE}, {@link #INVISIBLE}, or {@link #GONE}.
* @attr ref android.R.styleable#View_visibility
*/
@RemotableViewMethod
public void setVisibility(int visibility) {
setFlags(visibility, VISIBILITY_MASK);
if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false);
}
/**
* Returns the enabled status for this view. The interpretation of the
* enabled state varies by subclass.
*
* @return True if this view is enabled, false otherwise.
*/
@ViewDebug.ExportedProperty
public boolean isEnabled() {
return (mViewFlags & ENABLED_MASK) == ENABLED;
}
/**
* Set the enabled state of this view. The interpretation of the enabled
* state varies by subclass.
*
* @param enabled True if this view is enabled, false otherwise.
*/
public void setEnabled(boolean enabled) {
setFlags(enabled ? ENABLED : DISABLED, ENABLED_MASK);
/*
* The View most likely has to change its appearance, so refresh
* the drawable state.
*/
refreshDrawableState();
// Invalidate too, since the default behavior for views is to be
// be drawn at 50% alpha rather than to change the drawable.
invalidate();
}
/**
* Set whether this view can receive the focus.
*
* Setting this to false will also ensure that this view is not focusable
* in touch mode.
*
* @param focusable If true, this view can receive the focus.
*
* @see #setFocusableInTouchMode(boolean)
* @attr ref android.R.styleable#View_focusable
*/
public void setFocusable(boolean focusable) {
if (!focusable) {
setFlags(0, FOCUSABLE_IN_TOUCH_MODE);
}
setFlags(focusable ? FOCUSABLE : NOT_FOCUSABLE, FOCUSABLE_MASK);
}
/**
* Set whether this view can receive focus while in touch mode.
*
* Setting this to true will also ensure that this view is focusable.
*
* @param focusableInTouchMode If true, this view can receive the focus while
* in touch mode.
*
* @see #setFocusable(boolean)
* @attr ref android.R.styleable#View_focusableInTouchMode
*/
public void setFocusableInTouchMode(boolean focusableInTouchMode) {
// Focusable in touch mode should always be set before the focusable flag
// otherwise, setting the focusable flag will trigger a focusableViewAvailable()
// which, in touch mode, will not successfully request focus on this view
// because the focusable in touch mode flag is not set
setFlags(focusableInTouchMode ? FOCUSABLE_IN_TOUCH_MODE : 0, FOCUSABLE_IN_TOUCH_MODE);
if (focusableInTouchMode) {
setFlags(FOCUSABLE, FOCUSABLE_MASK);
}
}
/**
* Set whether this view should have sound effects enabled for events such as
* clicking and touching.
*
* <p>You may wish to disable sound effects for a view if you already play sounds,
* for instance, a dial key that plays dtmf tones.
*
* @param soundEffectsEnabled whether sound effects are enabled for this view.
* @see #isSoundEffectsEnabled()
* @see #playSoundEffect(int)
* @attr ref android.R.styleable#View_soundEffectsEnabled
*/
public void setSoundEffectsEnabled(boolean soundEffectsEnabled) {
setFlags(soundEffectsEnabled ? SOUND_EFFECTS_ENABLED: 0, SOUND_EFFECTS_ENABLED);
}
/**
* @return whether this view should have sound effects enabled for events such as
* clicking and touching.
*
* @see #setSoundEffectsEnabled(boolean)
* @see #playSoundEffect(int)
* @attr ref android.R.styleable#View_soundEffectsEnabled
*/
@ViewDebug.ExportedProperty
public boolean isSoundEffectsEnabled() {
return SOUND_EFFECTS_ENABLED == (mViewFlags & SOUND_EFFECTS_ENABLED);
}
/**
* Set whether this view should have haptic feedback for events such as
* long presses.
*
* <p>You may wish to disable haptic feedback if your view already controls
* its own haptic feedback.
*
* @param hapticFeedbackEnabled whether haptic feedback enabled for this view.
* @see #isHapticFeedbackEnabled()
* @see #performHapticFeedback(int)
* @attr ref android.R.styleable#View_hapticFeedbackEnabled
*/
public void setHapticFeedbackEnabled(boolean hapticFeedbackEnabled) {
setFlags(hapticFeedbackEnabled ? HAPTIC_FEEDBACK_ENABLED: 0, HAPTIC_FEEDBACK_ENABLED);
}
/**
* @return whether this view should have haptic feedback enabled for events
* long presses.
*
* @see #setHapticFeedbackEnabled(boolean)
* @see #performHapticFeedback(int)
* @attr ref android.R.styleable#View_hapticFeedbackEnabled
*/
@ViewDebug.ExportedProperty
public boolean isHapticFeedbackEnabled() {
return HAPTIC_FEEDBACK_ENABLED == (mViewFlags & HAPTIC_FEEDBACK_ENABLED);
}
/**
* If this view doesn't do any drawing on its own, set this flag to
* allow further optimizations. By default, this flag is not set on
* View, but could be set on some View subclasses such as ViewGroup.
*
* Typically, if you override {@link #onDraw} you should clear this flag.
*
* @param willNotDraw whether or not this View draw on its own
*/
public void setWillNotDraw(boolean willNotDraw) {
setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
}
/**
* Returns whether or not this View draws on its own.
*
* @return true if this view has nothing to draw, false otherwise
*/
@ViewDebug.ExportedProperty
public boolean willNotDraw() {
return (mViewFlags & DRAW_MASK) == WILL_NOT_DRAW;
}
/**
* When a View's drawing cache is enabled, drawing is redirected to an
* offscreen bitmap. Some views, like an ImageView, must be able to
* bypass this mechanism if they already draw a single bitmap, to avoid
* unnecessary usage of the memory.
*
* @param willNotCacheDrawing true if this view does not cache its
* drawing, false otherwise
*/
public void setWillNotCacheDrawing(boolean willNotCacheDrawing) {
setFlags(willNotCacheDrawing ? WILL_NOT_CACHE_DRAWING : 0, WILL_NOT_CACHE_DRAWING);
}
/**
* Returns whether or not this View can cache its drawing or not.
*
* @return true if this view does not cache its drawing, false otherwise
*/
@ViewDebug.ExportedProperty
public boolean willNotCacheDrawing() {
return (mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING;
}
/**
* Indicates whether this view reacts to click events or not.
*
* @return true if the view is clickable, false otherwise
*
* @see #setClickable(boolean)
* @attr ref android.R.styleable#View_clickable
*/
@ViewDebug.ExportedProperty
public boolean isClickable() {
return (mViewFlags & CLICKABLE) == CLICKABLE;
}
/**
* Enables or disables click events for this view. When a view
* is clickable it will change its state to "pressed" on every click.
* Subclasses should set the view clickable to visually react to
* user's clicks.
*
* @param clickable true to make the view clickable, false otherwise
*
* @see #isClickable()
* @attr ref android.R.styleable#View_clickable
*/
public void setClickable(boolean clickable) {
setFlags(clickable ? CLICKABLE : 0, CLICKABLE);
}
/**
* Indicates whether this view reacts to long click events or not.
*
* @return true if the view is long clickable, false otherwise
*
* @see #setLongClickable(boolean)
* @attr ref android.R.styleable#View_longClickable
*/
public boolean isLongClickable() {
return (mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
}
/**
* Enables or disables long click events for this view. When a view is long
* clickable it reacts to the user holding down the button for a longer
* duration than a tap. This event can either launch the listener or a
* context menu.
*
* @param longClickable true to make the view long clickable, false otherwise
* @see #isLongClickable()
* @attr ref android.R.styleable#View_longClickable
*/
public void setLongClickable(boolean longClickable) {
setFlags(longClickable ? LONG_CLICKABLE : 0, LONG_CLICKABLE);
}
/**
* Sets the pressed that for this view.
*
* @see #isClickable()
* @see #setClickable(boolean)
*
* @param pressed Pass true to set the View's internal state to "pressed", or false to reverts
* the View's internal state from a previously set "pressed" state.
*/
public void setPressed(boolean pressed) {
if (pressed) {
mPrivateFlags |= PRESSED;
} else {
mPrivateFlags &= ~PRESSED;
}
refreshDrawableState();
dispatchSetPressed(pressed);
}
/**
* Dispatch setPressed to all of this View's children.
*
* @see #setPressed(boolean)
*
* @param pressed The new pressed state
*/
protected void dispatchSetPressed(boolean pressed) {
}
/**
* Indicates whether the view is currently in pressed state. Unless
* {@link #setPressed(boolean)} is explicitly called, only clickable views can enter
* the pressed state.
*
* @see #setPressed
* @see #isClickable()
* @see #setClickable(boolean)
*
* @return true if the view is currently pressed, false otherwise
*/
public boolean isPressed() {
return (mPrivateFlags & PRESSED) == PRESSED;
}
/**
* Indicates whether this view will save its state (that is,
* whether its {@link #onSaveInstanceState} method will be called).
*
* @return Returns true if the view state saving is enabled, else false.
*
* @see #setSaveEnabled(boolean)
* @attr ref android.R.styleable#View_saveEnabled
*/
public boolean isSaveEnabled() {
return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
}
/**
* Controls whether the saving of this view's state is
* enabled (that is, whether its {@link #onSaveInstanceState} method
* will be called). Note that even if freezing is enabled, the
* view still must have an id assigned to it (via {@link #setId setId()})
* for its state to be saved. This flag can only disable the
* saving of this view; any child views may still have their state saved.
*
* @param enabled Set to false to <em>disable</em> state saving, or true
* (the default) to allow it.
*
* @see #isSaveEnabled()
* @see #setId(int)
* @see #onSaveInstanceState()
* @attr ref android.R.styleable#View_saveEnabled
*/
public void setSaveEnabled(boolean enabled) {
setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
}
/**
* Returns whether this View is able to take focus.
*
* @return True if this view can take focus, or false otherwise.
* @attr ref android.R.styleable#View_focusable
*/
@ViewDebug.ExportedProperty
public final boolean isFocusable() {
return FOCUSABLE == (mViewFlags & FOCUSABLE_MASK);
}
/**
* When a view is focusable, it may not want to take focus when in touch mode.
* For example, a button would like focus when the user is navigating via a D-pad
* so that the user can click on it, but once the user starts touching the screen,
* the button shouldn't take focus
* @return Whether the view is focusable in touch mode.
* @attr ref android.R.styleable#View_focusableInTouchMode
*/
@ViewDebug.ExportedProperty
public final boolean isFocusableInTouchMode() {
return FOCUSABLE_IN_TOUCH_MODE == (mViewFlags & FOCUSABLE_IN_TOUCH_MODE);
}
/**
* Find the nearest view in the specified direction that can take focus.
* This does not actually give focus to that view.
*
* @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
*
* @return The nearest focusable in the specified direction, or null if none
* can be found.
*/
public View focusSearch(int direction) {
if (mParent != null) {
return mParent.focusSearch(this, direction);
} else {
return null;
}
}
/**
* This method is the last chance for the focused view and its ancestors to
* respond to an arrow key. This is called when the focused view did not
* consume the key internally, nor could the view system find a new view in
* the requested direction to give focus to.
*
* @param focused The currently focused view.
* @param direction The direction focus wants to move. One of FOCUS_UP,
* FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
* @return True if the this view consumed this unhandled move.
*/
public boolean dispatchUnhandledMove(View focused, int direction) {
return false;
}
/**
* If a user manually specified the next view id for a particular direction,
* use the root to look up the view. Once a view is found, it is cached
* for future lookups.
* @param root The root view of the hierarchy containing this view.
* @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
* @return The user specified next view, or null if there is none.
*/
View findUserSetNextFocus(View root, int direction) {
switch (direction) {
case FOCUS_LEFT:
if (mNextFocusLeftId == View.NO_ID) return null;
return findViewShouldExist(root, mNextFocusLeftId);
case FOCUS_RIGHT:
if (mNextFocusRightId == View.NO_ID) return null;
return findViewShouldExist(root, mNextFocusRightId);
case FOCUS_UP:
if (mNextFocusUpId == View.NO_ID) return null;
return findViewShouldExist(root, mNextFocusUpId);
case FOCUS_DOWN:
if (mNextFocusDownId == View.NO_ID) return null;
return findViewShouldExist(root, mNextFocusDownId);
}
return null;
}
private static View findViewShouldExist(View root, int childViewId) {
View result = root.findViewById(childViewId);
if (result == null) {
Log.w(VIEW_LOG_TAG, "couldn't find next focus view specified "
+ "by user for id " + childViewId);
}
return result;
}
/**
* Find and return all focusable views that are descendants of this view,
* possibly including this view if it is focusable itself.
*
* @param direction The direction of the focus
* @return A list of focusable views
*/
public ArrayList<View> getFocusables(int direction) {
ArrayList<View> result = new ArrayList<View>(24);
addFocusables(result, direction);
return result;
}
/**
* Add any focusable views that are descendants of this view (possibly
* including this view if it is focusable itself) to views. If we are in touch mode,
* only add views that are also focusable in touch mode.
*
* @param views Focusable views found so far
* @param direction The direction of the focus
*/
public void addFocusables(ArrayList<View> views, int direction) {
addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
}
/**
* Adds any focusable views that are descendants of this view (possibly
* including this view if it is focusable itself) to views. This method
* adds all focusable views regardless if we are in touch mode or
* only views focusable in touch mode if we are in touch mode depending on
* the focusable mode paramater.
*
* @param views Focusable views found so far or null if all we are interested is
* the number of focusables.
* @param direction The direction of the focus.
* @param focusableMode The type of focusables to be added.
*
* @see #FOCUSABLES_ALL
* @see #FOCUSABLES_TOUCH_MODE
*/
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
if (!isFocusable()) {
return;
}
if ((focusableMode & FOCUSABLES_TOUCH_MODE) == FOCUSABLES_TOUCH_MODE &&
isInTouchMode() && !isFocusableInTouchMode()) {
return;
}
if (views != null) {
views.add(this);
}
}
/**
* Find and return all touchable views that are descendants of this view,
* possibly including this view if it is touchable itself.
*
* @return A list of touchable views
*/
public ArrayList<View> getTouchables() {
ArrayList<View> result = new ArrayList<View>();
addTouchables(result);
return result;
}
/**
* Add any touchable views that are descendants of this view (possibly
* including this view if it is touchable itself) to views.
*
* @param views Touchable views found so far
*/
public void addTouchables(ArrayList<View> views) {
final int viewFlags = mViewFlags;
if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
&& (viewFlags & ENABLED_MASK) == ENABLED) {
views.add(this);
}
}
/**
* Call this to try to give focus to a specific view or to one of its
* descendants.
*
* A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
* or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
* while the device is in touch mode.
*
* See also {@link #focusSearch}, which is what you call to say that you
* have focus, and you want your parent to look for the next one.
*
* This is equivalent to calling {@link #requestFocus(int, Rect)} with arguments
* {@link #FOCUS_DOWN} and <code>null</code>.
*
* @return Whether this view or one of its descendants actually took focus.
*/
public final boolean requestFocus() {
return requestFocus(View.FOCUS_DOWN);
}
/**
* Call this to try to give focus to a specific view or to one of its
* descendants and give it a hint about what direction focus is heading.
*
* A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
* or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
* while the device is in touch mode.
*
* See also {@link #focusSearch}, which is what you call to say that you
* have focus, and you want your parent to look for the next one.
*
* This is equivalent to calling {@link #requestFocus(int, Rect)} with
* <code>null</code> set for the previously focused rectangle.
*
* @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
* @return Whether this view or one of its descendants actually took focus.
*/
public final boolean requestFocus(int direction) {
return requestFocus(direction, null);
}
/**
* Call this to try to give focus to a specific view or to one of its descendants
* and give it hints about the direction and a specific rectangle that the focus
* is coming from. The rectangle can help give larger views a finer grained hint
* about where focus is coming from, and therefore, where to show selection, or
* forward focus change internally.
*
* A view will not actually take focus if it is not focusable ({@link #isFocusable} returns false),
* or if it is focusable and it is not focusable in touch mode ({@link #isFocusableInTouchMode})
* while the device is in touch mode.
*
* A View will not take focus if it is not visible.
*
* A View will not take focus if one of its parents has {@link android.view.ViewGroup#getDescendantFocusability()}
* equal to {@link ViewGroup#FOCUS_BLOCK_DESCENDANTS}.
*
* See also {@link #focusSearch}, which is what you call to say that you
* have focus, and you want your parent to look for the next one.
*
* You may wish to override this method if your custom {@link View} has an internal
* {@link View} that it wishes to forward the request to.
*
* @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
* @param previouslyFocusedRect The rectangle (in this View's coordinate system)
* to give a finer grained hint about where focus is coming from. May be null
* if there is no hint.
* @return Whether this view or one of its descendants actually took focus.
*/
public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
// need to be focusable
if ((mViewFlags & FOCUSABLE_MASK) != FOCUSABLE ||
(mViewFlags & VISIBILITY_MASK) != VISIBLE) {
return false;
}
// need to be focusable in touch mode if in touch mode
if (isInTouchMode() &&
(FOCUSABLE_IN_TOUCH_MODE != (mViewFlags & FOCUSABLE_IN_TOUCH_MODE))) {
return false;
}
// need to not have any parents blocking us
if (hasAncestorThatBlocksDescendantFocus()) {
return false;
}
handleFocusGainInternal(direction, previouslyFocusedRect);
return true;
}
/**
* Call this to try to give focus to a specific view or to one of its descendants. This is a
* special variant of {@link #requestFocus() } that will allow views that are not focuable in
* touch mode to request focus when they are touched.
*
* @return Whether this view or one of its descendants actually took focus.
*
* @see #isInTouchMode()
*
*/
public final boolean requestFocusFromTouch() {
// Leave touch mode if we need to
if (isInTouchMode()) {
View root = getRootView();
if (root != null) {
ViewRoot viewRoot = (ViewRoot)root.getParent();
if (viewRoot != null) {
viewRoot.ensureTouchMode(false);
}
}
}
return requestFocus(View.FOCUS_DOWN);
}
/**
* @return Whether any ancestor of this view blocks descendant focus.
*/
private boolean hasAncestorThatBlocksDescendantFocus() {
ViewParent ancestor = mParent;
while (ancestor instanceof ViewGroup) {
final ViewGroup vgAncestor = (ViewGroup) ancestor;
if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) {
return true;
} else {
ancestor = vgAncestor.getParent();
}
}
return false;
}
/**
* This is called when a container is going to temporarily detach a child
* that currently has focus, with
* {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}.
* It will either be followed by {@link #onFinishTemporaryDetach()} or
* {@link #onDetachedFromWindow()} when the container is done. Generally
* this is currently only done ListView for a view with focus.
*/
public void onStartTemporaryDetach() {
}
/**
* Called after {@link #onStartTemporaryDetach} when the container is done
* changing the view.
*/
public void onFinishTemporaryDetach() {
}
/**
* capture information of this view for later analysis: developement only
* check dynamic switch to make sure we only dump view
* when ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW) is set
*/
private static void captureViewInfo(String subTag, View v) {
if (v == null || SystemProperties.getInt(ViewDebug.SYSTEM_PROPERTY_CAPTURE_VIEW, 0) == 0) {
return;
}
ViewDebug.dumpCapturedView(subTag, v);
}
/**
* Dispatch a key event before it is processed by any input method
* associated with the view hierarchy. This can be used to intercept
* key events in special situations before the IME consumes them; a
* typical example would be handling the BACK key to update the application's
* UI instead of allowing the IME to see it and close itself.
*
* @param event The key event to be dispatched.
* @return True if the event was handled, false otherwise.
*/
public boolean dispatchKeyEventPreIme(KeyEvent event) {
return onKeyPreIme(event.getKeyCode(), event);
}
/**
* Dispatch a key event to the next view on the focus path. This path runs
* from the top of the view tree down to the currently focused view. If this
* view has focus, it will dispatch to itself. Otherwise it will dispatch
* the next node down the focus path. This method also fires any key
* listeners.
*
* @param event The key event to be dispatched.
* @return True if the event was handled, false otherwise.
*/
public boolean dispatchKeyEvent(KeyEvent event) {
// If any attached key listener a first crack at the event.
//noinspection SimplifiableIfStatement
if (android.util.Config.LOGV) {
captureViewInfo("captureViewKeyEvent", this);
}
if (mOnKeyListener != null && (mViewFlags & ENABLED_MASK) == ENABLED
&& mOnKeyListener.onKey(this, event.getKeyCode(), event)) {
return true;
}
return event.dispatch(this);
}
/**
* Dispatches a key shortcut event.
*
* @param event The key event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchKeyShortcutEvent(KeyEvent event) {
return onKeyShortcut(event.getKeyCode(), event);
}
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent event) {
if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
mOnTouchListener.onTouch(this, event)) {
return true;
}
return onTouchEvent(event);
}
/**
* Pass a trackball motion event down to the focused view.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTrackballEvent(MotionEvent event) {
//Log.i("view", "view=" + this + ", " + event.toString());
return onTrackballEvent(event);
}
/**
* Called when the window containing this view gains or loses window focus.
* ViewGroups should override to route to their children.
*
* @param hasFocus True if the window containing this view now has focus,
* false otherwise.
*/
public void dispatchWindowFocusChanged(boolean hasFocus) {
onWindowFocusChanged(hasFocus);
}
/**
* Called when the window containing this view gains or loses focus. Note
* that this is separate from view focus: to receive key events, both
* your view and its window must have focus. If a window is displayed
* on top of yours that takes input focus, then your own window will lose
* focus but the view focus will remain unchanged.
*
* @param hasWindowFocus True if the window containing this view now has
* focus, false otherwise.
*/
public void onWindowFocusChanged(boolean hasWindowFocus) {
InputMethodManager imm = InputMethodManager.peekInstance();
if (!hasWindowFocus) {
if (isPressed()) {
setPressed(false);
}
if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
imm.focusOut(this);
}
if (mPendingCheckForLongPress != null) {
removeCallbacks(mPendingCheckForLongPress);
}
onFocusLost();
} else if (imm != null && (mPrivateFlags & FOCUSED) != 0) {
imm.focusIn(this);
}
refreshDrawableState();
}
/**
* Returns true if this view is in a window that currently has window focus.
* Note that this is not the same as the view itself having focus.
*
* @return True if this view is in a window that currently has window focus.
*/
public boolean hasWindowFocus() {
return mAttachInfo != null && mAttachInfo.mHasWindowFocus;
}
/**
* Dispatch a window visibility change down the view hierarchy.
* ViewGroups should override to route to their children.
*
* @param visibility The new visibility of the window.
*
* @see #onWindowVisibilityChanged
*/
public void dispatchWindowVisibilityChanged(int visibility) {
onWindowVisibilityChanged(visibility);
}
/**
* Called when the window containing has change its visibility
* (between {@link #GONE}, {@link #INVISIBLE}, and {@link #VISIBLE}). Note
* that this tells you whether or not your window is being made visible
* to the window manager; this does <em>not</em> tell you whether or not
* your window is obscured by other windows on the screen, even if it
* is itself visible.
*
* @param visibility The new visibility of the window.
*/
protected void onWindowVisibilityChanged(int visibility) {
}
/**
* Returns the current visibility of the window this view is attached to
* (either {@link #GONE}, {@link #INVISIBLE}, or {@link #VISIBLE}).
*
* @return Returns the current visibility of the view's window.
*/
public int getWindowVisibility() {
return mAttachInfo != null ? mAttachInfo.mWindowVisibility : GONE;
}
/**
* Retrieve the overall visible display size in which the window this view is
* attached to has been positioned in. This takes into account screen
* decorations above the window, for both cases where the window itself
* is being position inside of them or the window is being placed under
* then and covered insets are used for the window to position its content
* inside. In effect, this tells you the available area where content can
* be placed and remain visible to users.
*
* <p>This function requires an IPC back to the window manager to retrieve
* the requested information, so should not be used in performance critical
* code like drawing.
*
* @param outRect Filled in with the visible display frame. If the view
* is not attached to a window, this is simply the raw display size.
*/
public void getWindowVisibleDisplayFrame(Rect outRect) {
if (mAttachInfo != null) {
try {
mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);
} catch (RemoteException e) {
return;
}
// XXX This is really broken, and probably all needs to be done
// in the window manager, and we need to know more about whether
// we want the area behind or in front of the IME.
final Rect insets = mAttachInfo.mVisibleInsets;
outRect.left += insets.left;
outRect.top += insets.top;
outRect.right -= insets.right;
outRect.bottom -= insets.bottom;
return;
}
Display d = WindowManagerImpl.getDefault().getDefaultDisplay();
outRect.set(0, 0, d.getWidth(), d.getHeight());
}
/**
* Private function to aggregate all per-view attributes in to the view
* root.
*/
void dispatchCollectViewAttributes(int visibility) {
performCollectViewAttributes(visibility);
}
void performCollectViewAttributes(int visibility) {
//noinspection PointlessBitwiseExpression
if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON))
== (VISIBLE | KEEP_SCREEN_ON)) {
mAttachInfo.mKeepScreenOn = true;
}
}
void needGlobalAttributesUpdate(boolean force) {
AttachInfo ai = mAttachInfo;
if (ai != null) {
if (ai.mKeepScreenOn || force) {
ai.mRecomputeGlobalAttributes = true;
}
}
}
/**
* Returns whether the device is currently in touch mode. Touch mode is entered
* once the user begins interacting with the device by touch, and affects various
* things like whether focus is always visible to the user.
*
* @return Whether the device is in touch mode.
*/
@ViewDebug.ExportedProperty
public boolean isInTouchMode() {
if (mAttachInfo != null) {
return mAttachInfo.mInTouchMode;
} else {
return ViewRoot.isInTouchMode();
}
}
/**
* Returns the context the view is running in, through which it can
* access the current theme, resources, etc.
*
* @return The view's Context.
*/
@ViewDebug.CapturedViewProperty
public final Context getContext() {
return mContext;
}
/**
* Handle a key event before it is processed by any input method
* associated with the view hierarchy. This can be used to intercept
* key events in special situations before the IME consumes them; a
* typical example would be handling the BACK key to update the application's
* UI instead of allowing the IME to see it and close itself.
*
* @param keyCode The value in event.getKeyCode().
* @param event Description of the key event.
* @return If you handled the event, return true. If you want to allow the
* event to be handled by the next receiver, return false.
*/
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
return false;
}
/**
* Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
* KeyEvent.Callback.onKeyMultiple()}: perform press of the view
* when {@link KeyEvent#KEYCODE_DPAD_CENTER} or {@link KeyEvent#KEYCODE_ENTER}
* is released, if the view is enabled and clickable.
*
* @param keyCode A key code that represents the button pressed, from
* {@link android.view.KeyEvent}.
* @param event The KeyEvent object that defines the button action.
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean result = false;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER: {
if ((mViewFlags & ENABLED_MASK) == DISABLED) {
return true;
}
// Long clickable items don't necessarily have to be clickable
if (((mViewFlags & CLICKABLE) == CLICKABLE ||
(mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) &&
(event.getRepeatCount() == 0)) {
setPressed(true);
if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
postCheckForLongClick();
}
return true;
}
break;
}
}
return result;
}
/**
* Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
* KeyEvent.Callback.onKeyMultiple()}: perform clicking of the view
* when {@link KeyEvent#KEYCODE_DPAD_CENTER} or
* {@link KeyEvent#KEYCODE_ENTER} is released.
*
* @param keyCode A key code that represents the button pressed, from
* {@link android.view.KeyEvent}.
* @param event The KeyEvent object that defines the button action.
*/
public boolean onKeyUp(int keyCode, KeyEvent event) {
boolean result = false;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER: {
if ((mViewFlags & ENABLED_MASK) == DISABLED) {
return true;
}
if ((mViewFlags & CLICKABLE) == CLICKABLE && isPressed()) {
setPressed(false);
if (!mHasPerformedLongPress) {
// This is a tap, so remove the longpress check
if (mPendingCheckForLongPress != null) {
removeCallbacks(mPendingCheckForLongPress);
}
result = performClick();
}
}
break;
}
}
return result;
}
/**
* Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
* KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
* the event).
*
* @param keyCode A key code that represents the button pressed, from
* {@link android.view.KeyEvent}.
* @param repeatCount The number of times the action was made.
* @param event The KeyEvent object that defines the button action.
*/
public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
return false;
}
/**
* Called when an unhandled key shortcut event occurs.
*
* @param keyCode The value in event.getKeyCode().
* @param event Description of the key event.
* @return If you handled the event, return true. If you want to allow the
* event to be handled by the next receiver, return false.
*/
public boolean onKeyShortcut(int keyCode, KeyEvent event) {
return false;
}
/**
* Check whether the called view is a text editor, in which case it
* would make sense to automatically display a soft input window for
* it. Subclasses should override this if they implement
* {@link #onCreateInputConnection(EditorInfo)} to return true if
* a call on that method would return a non-null InputConnection, and
* they are really a first-class editor that the user would normally
* start typing on when the go into a window containing your view.
*
* <p>The default implementation always returns false. This does
* <em>not</em> mean that its {@link #onCreateInputConnection(EditorInfo)}
* will not be called or the user can not otherwise perform edits on your
* view; it is just a hint to the system that this is not the primary
* purpose of this view.
*
* @return Returns true if this view is a text editor, else false.
*/
public boolean onCheckIsTextEditor() {
return false;
}
/**
* Create a new InputConnection for an InputMethod to interact
* with the view. The default implementation returns null, since it doesn't
* support input methods. You can override this to implement such support.
* This is only needed for views that take focus and text input.
*
* <p>When implementing this, you probably also want to implement
* {@link #onCheckIsTextEditor()} to indicate you will return a
* non-null InputConnection.
*
* @param outAttrs Fill in with attribute information about the connection.
*/
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return null;
}
/**
* Called by the {@link android.view.inputmethod.InputMethodManager}
* when a view who is not the current
* input connection target is trying to make a call on the manager. The
* default implementation returns false; you can override this to return
* true for certain views if you are performing InputConnection proxying
* to them.
* @param view The View that is making the InputMethodManager call.
* @return Return true to allow the call, false to reject.
*/
public boolean checkInputConnectionProxy(View view) {
return false;
}
/**
* Show the context menu for this view. It is not safe to hold on to the
* menu after returning from this method.
*
* @param menu The context menu to populate
*/
public void createContextMenu(ContextMenu menu) {
ContextMenuInfo menuInfo = getContextMenuInfo();
// Sets the current menu info so all items added to menu will have
// my extra info set.
((MenuBuilder)menu).setCurrentMenuInfo(menuInfo);
onCreateContextMenu(menu);
if (mOnCreateContextMenuListener != null) {
mOnCreateContextMenuListener.onCreateContextMenu(menu, this, menuInfo);
}
// Clear the extra information so subsequent items that aren't mine don't
// have my extra info.
((MenuBuilder)menu).setCurrentMenuInfo(null);
if (mParent != null) {
mParent.createContextMenu(menu);
}
}
/**
* Views should implement this if they have extra information to associate
* with the context menu. The return result is supplied as a parameter to
* the {@link OnCreateContextMenuListener#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)}
* callback.
*
* @return Extra information about the item for which the context menu
* should be shown. This information will vary across different
* subclasses of View.
*/
protected ContextMenuInfo getContextMenuInfo() {
return null;
}
/**
* Views should implement this if the view itself is going to add items to
* the context menu.
*
* @param menu the context menu to populate
*/
protected void onCreateContextMenu(ContextMenu menu) {
}
/**
* Implement this method to handle trackball motion events. The
* <em>relative</em> movement of the trackball since the last event
* can be retrieve with {@link MotionEvent#getX MotionEvent.getX()} and
* {@link MotionEvent#getY MotionEvent.getY()}. These are normalized so
* that a movement of 1 corresponds to the user pressing one DPAD key (so
* they will often be fractional values, representing the more fine-grained
* movement information available from a trackball).
*
* @param event The motion event.
* @return True if the event was handled, false otherwise.
*/
public boolean onTrackballEvent(MotionEvent event) {
return false;
}
/**
* Implement this method to handle touch screen motion events.
*
* @param event The motion event.
* @return True if the event was handled, false otherwise.
*/
public boolean onTouchEvent(MotionEvent event) {
final int viewFlags = mViewFlags;
if ((viewFlags & ENABLED_MASK) == DISABLED) {
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if ((mPrivateFlags & PRESSED) != 0) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (!mHasPerformedLongPress) {
// This is a tap, so remove the longpress check
if (mPendingCheckForLongPress != null) {
removeCallbacks(mPendingCheckForLongPress);
}
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
performClick();
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
}
break;
case MotionEvent.ACTION_DOWN:
mPrivateFlags |= PRESSED;
refreshDrawableState();
if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {
postCheckForLongClick();
}
break;
case MotionEvent.ACTION_CANCEL:
mPrivateFlags &= ~PRESSED;
refreshDrawableState();
break;
case MotionEvent.ACTION_MOVE:
final int x = (int) event.getX();
final int y = (int) event.getY();
// Be lenient about moving outside of buttons
int slop = ViewConfiguration.get(mContext).getScaledTouchSlop();
if ((x < 0 - slop) || (x >= getWidth() + slop) ||
(y < 0 - slop) || (y >= getHeight() + slop)) {
// Outside button
if ((mPrivateFlags & PRESSED) != 0) {
// Remove any future long press checks
if (mPendingCheckForLongPress != null) {
removeCallbacks(mPendingCheckForLongPress);
}
// Need to switch from pressed to not pressed
mPrivateFlags &= ~PRESSED;
refreshDrawableState();
}
} else {
// Inside button
if ((mPrivateFlags & PRESSED) == 0) {
// Need to switch from not pressed to pressed
mPrivateFlags |= PRESSED;
refreshDrawableState();
}
}
break;
}
return true;
}
return false;
}
/**
* Cancels a pending long press. Your subclass can use this if you
* want the context menu to come up if the user presses and holds
* at the same place, but you don't want it to come up if they press
* and then move around enough to cause scrolling.
*/
public void cancelLongPress() {
if (mPendingCheckForLongPress != null) {
removeCallbacks(mPendingCheckForLongPress);
}
}
/**
* Sets the TouchDelegate for this View.
*/
public void setTouchDelegate(TouchDelegate delegate) {
mTouchDelegate = delegate;
}
/**
* Gets the TouchDelegate for this View.
*/
public TouchDelegate getTouchDelegate() {
return mTouchDelegate;
}
/**
* Set flags controlling behavior of this view.
*
* @param flags Constant indicating the value which should be set
* @param mask Constant indicating the bit range that should be changed
*/
void setFlags(int flags, int mask) {
int old = mViewFlags;
mViewFlags = (mViewFlags & ~mask) | (flags & mask);
int changed = mViewFlags ^ old;
if (changed == 0) {
return;
}
int privateFlags = mPrivateFlags;
/* Check if the FOCUSABLE bit has changed */
if (((changed & FOCUSABLE_MASK) != 0) &&
((privateFlags & HAS_BOUNDS) !=0)) {
if (((old & FOCUSABLE_MASK) == FOCUSABLE)
&& ((privateFlags & FOCUSED) != 0)) {
/* Give up focus if we are no longer focusable */
clearFocus();
} else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
&& ((privateFlags & FOCUSED) == 0)) {
/*
* Tell the view system that we are now available to take focus
* if no one else already has it.
*/
if (mParent != null) mParent.focusableViewAvailable(this);
}
}
if ((flags & VISIBILITY_MASK) == VISIBLE) {
if ((changed & VISIBILITY_MASK) != 0) {
/*
* If this view is becoming visible, set the DRAWN flag so that
* the next invalidate() will not be skipped.
*/
mPrivateFlags |= DRAWN;
needGlobalAttributesUpdate(true);
// a view becoming visible is worth notifying the parent
// about in case nothing has focus. even if this specific view
// isn't focusable, it may contain something that is, so let
// the root view try to give this focus if nothing else does.
if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
mParent.focusableViewAvailable(this);
}
}
}
/* Check if the GONE bit has changed */
if ((changed & GONE) != 0) {
needGlobalAttributesUpdate(false);
requestLayout();
invalidate();
if (((mViewFlags & VISIBILITY_MASK) == GONE) && hasFocus()) {
clearFocus();
}
if (mAttachInfo != null) {
mAttachInfo.mViewVisibilityChanged = true;
}
}
/* Check if the VISIBLE bit has changed */
if ((changed & INVISIBLE) != 0) {
needGlobalAttributesUpdate(false);
invalidate();
if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE) && hasFocus()) {
// root view becoming invisible shouldn't clear focus
if (getRootView() != this) {
clearFocus();
}
}
if (mAttachInfo != null) {
mAttachInfo.mViewVisibilityChanged = true;
}
}
if ((changed & WILL_NOT_CACHE_DRAWING) != 0) {
destroyDrawingCache();
}
if ((changed & DRAWING_CACHE_ENABLED) != 0) {
destroyDrawingCache();
mPrivateFlags &= ~DRAWING_CACHE_VALID;
}
if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) {
destroyDrawingCache();
mPrivateFlags &= ~DRAWING_CACHE_VALID;
}
if ((changed & DRAW_MASK) != 0) {
if ((mViewFlags & WILL_NOT_DRAW) != 0) {
if (mBGDrawable != null) {
mPrivateFlags &= ~SKIP_DRAW;
mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
} else {
mPrivateFlags |= SKIP_DRAW;
}
} else {
mPrivateFlags &= ~SKIP_DRAW;
}
requestLayout();
invalidate();
}
if ((changed & KEEP_SCREEN_ON) != 0) {
if (mParent != null) {
mParent.recomputeViewAttributes(this);
}
}
}
/**
* Change the view's z order in the tree, so it's on top of other sibling
* views
*/
public void bringToFront() {
if (mParent != null) {
mParent.bringChildToFront(this);
}
}
/**
* This is called in response to an internal scroll in this view (i.e., the
* view scrolled its own contents). This is typically as a result of
* {@link #scrollBy(int, int)} or {@link #scrollTo(int, int)} having been
* called.
*
* @param l Current horizontal scroll origin.
* @param t Current vertical scroll origin.
* @param oldl Previous horizontal scroll origin.
* @param oldt Previous vertical scroll origin.
*/
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
mBackgroundSizeChanged = true;
final AttachInfo ai = mAttachInfo;
if (ai != null) {
ai.mViewScrollChanged = true;
}
}
/**
* This is called during layout when the size of this view has changed. If
* you were just added to the view hierarchy, you're called with the old
* values of 0.
*
* @param w Current width of this view.
* @param h Current height of this view.
* @param oldw Old width of this view.
* @param oldh Old height of this view.
*/
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
}
/**
* Called by draw to draw the child views. This may be overridden
* by derived classes to gain control just before its children are drawn
* (but after its own view has been drawn).
* @param canvas the canvas on which to draw the view
*/
protected void dispatchDraw(Canvas canvas) {
}
/**
* Gets the parent of this view. Note that the parent is a
* ViewParent and not necessarily a View.
*
* @return Parent of this view.
*/
public final ViewParent getParent() {
return mParent;
}
/**
* Return the scrolled left position of this view. This is the left edge of
* the displayed part of your view. You do not need to draw any pixels
* farther left, since those are outside of the frame of your view on
* screen.
*
* @return The left edge of the displayed part of your view, in pixels.
*/
public final int getScrollX() {
return mScrollX;
}
/**
* Return the scrolled top position of this view. This is the top edge of
* the displayed part of your view. You do not need to draw any pixels above
* it, since those are outside of the frame of your view on screen.
*
* @return The top edge of the displayed part of your view, in pixels.
*/
public final int getScrollY() {
return mScrollY;
}
/**
* Return the width of the your view.
*
* @return The width of your view, in pixels.
*/
@ViewDebug.ExportedProperty
public final int getWidth() {
return mRight - mLeft;
}
/**
* Return the height of your view.
*
* @return The height of your view, in pixels.
*/
@ViewDebug.ExportedProperty
public final int getHeight() {
return mBottom - mTop;
}
/**
* Return the visible drawing bounds of your view. Fills in the output
* rectangle with the values from getScrollX(), getScrollY(),
* getWidth(), and getHeight().
*
* @param outRect The (scrolled) drawing bounds of the view.
*/
public void getDrawingRect(Rect outRect) {
outRect.left = mScrollX;
outRect.top = mScrollY;
outRect.right = mScrollX + (mRight - mLeft);
outRect.bottom = mScrollY + (mBottom - mTop);
}
/**
* The width of this view as measured in the most recent call to measure().
* This should be used during measurement and layout calculations only. Use
* {@link #getWidth()} to see how wide a view is after layout.
*
* @return The measured width of this view.
*/
public final int getMeasuredWidth() {
return mMeasuredWidth;
}
/**
* The height of this view as measured in the most recent call to measure().
* This should be used during measurement and layout calculations only. Use
* {@link #getHeight()} to see how tall a view is after layout.
*
* @return The measured height of this view.
*/
public final int getMeasuredHeight() {
return mMeasuredHeight;
}
/**
* Top position of this view relative to its parent.
*
* @return The top of this view, in pixels.
*/
@ViewDebug.CapturedViewProperty
public final int getTop() {
return mTop;
}
/**
* Bottom position of this view relative to its parent.
*
* @return The bottom of this view, in pixels.
*/
@ViewDebug.CapturedViewProperty
public final int getBottom() {
return mBottom;
}
/**
* Left position of this view relative to its parent.
*
* @return The left edge of this view, in pixels.
*/
@ViewDebug.CapturedViewProperty
public final int getLeft() {
return mLeft;
}
/**
* Right position of this view relative to its parent.
*
* @return The right edge of this view, in pixels.
*/
@ViewDebug.CapturedViewProperty
public final int getRight() {
return mRight;
}
/**
* Hit rectangle in parent's coordinates
*
* @param outRect The hit rectangle of the view.
*/
public void getHitRect(Rect outRect) {
outRect.set(mLeft, mTop, mRight, mBottom);
}
/**
* When a view has focus and the user navigates away from it, the next view is searched for
* starting from the rectangle filled in by this method.
*
* By default, the rectange is the {@link #getDrawingRect})of the view. However, if your
* view maintains some idea of internal selection, such as a cursor, or a selected row
* or column, you should override this method and fill in a more specific rectangle.
*
* @param r The rectangle to fill in, in this view's coordinates.
*/
public void getFocusedRect(Rect r) {
getDrawingRect(r);
}
/**
* If some part of this view is not clipped by any of its parents, then
* return that area in r in global (root) coordinates. To convert r to local
* coordinates, offset it by -globalOffset (e.g. r.offset(-globalOffset.x,
* -globalOffset.y)) If the view is completely clipped or translated out,
* return false.
*
* @param r If true is returned, r holds the global coordinates of the
* visible portion of this view.
* @param globalOffset If true is returned, globalOffset holds the dx,dy
* between this view and its root. globalOffet may be null.
* @return true if r is non-empty (i.e. part of the view is visible at the
* root level.
*/
public boolean getGlobalVisibleRect(Rect r, Point globalOffset) {
int width = mRight - mLeft;
int height = mBottom - mTop;
if (width > 0 && height > 0) {
r.set(0, 0, width, height);
if (globalOffset != null) {
globalOffset.set(-mScrollX, -mScrollY);
}
return mParent == null || mParent.getChildVisibleRect(this, r, globalOffset);
}
return false;
}
public final boolean getGlobalVisibleRect(Rect r) {
return getGlobalVisibleRect(r, null);
}
public final boolean getLocalVisibleRect(Rect r) {
Point offset = new Point();
if (getGlobalVisibleRect(r, offset)) {
r.offset(-offset.x, -offset.y); // make r local
return true;
}
return false;
}
/**
* Offset this view's vertical location by the specified number of pixels.
*
* @param offset the number of pixels to offset the view by
*/
public void offsetTopAndBottom(int offset) {
mTop += offset;
mBottom += offset;
}
/**
* Offset this view's horizontal location by the specified amount of pixels.
*
* @param offset the numer of pixels to offset the view by
*/
public void offsetLeftAndRight(int offset) {
mLeft += offset;
mRight += offset;
}
/**
* Get the LayoutParams associated with this view. All views should have
* layout parameters. These supply parameters to the <i>parent</i> of this
* view specifying how it should be arranged. There are many subclasses of
* ViewGroup.LayoutParams, and these correspond to the different subclasses
* of ViewGroup that are responsible for arranging their children.
* @return The LayoutParams associated with this view
*/
@ViewDebug.ExportedProperty(deepExport = true, prefix = "layout_")
public ViewGroup.LayoutParams getLayoutParams() {
return mLayoutParams;
}
/**
* Set the layout parameters associated with this view. These supply
* parameters to the <i>parent</i> of this view specifying how it should be
* arranged. There are many subclasses of ViewGroup.LayoutParams, and these
* correspond to the different subclasses of ViewGroup that are responsible
* for arranging their children.
*
* @param params the layout parameters for this view
*/
public void setLayoutParams(ViewGroup.LayoutParams params) {
if (params == null) {
throw new NullPointerException("params == null");
}
mLayoutParams = params;
requestLayout();
}
/**
* Set the scrolled position of your view. This will cause a call to
* {@link #onScrollChanged(int, int, int, int)} and the view will be
* invalidated.
* @param x the x position to scroll to
* @param y the y position to scroll to
*/
public void scrollTo(int x, int y) {
if (mScrollX != x || mScrollY != y) {
int oldX = mScrollX;
int oldY = mScrollY;
mScrollX = x;
mScrollY = y;
onScrollChanged(mScrollX, mScrollY, oldX, oldY);
invalidate();
}
}
/**
* Move the scrolled position of your view. This will cause a call to
* {@link #onScrollChanged(int, int, int, int)} and the view will be
* invalidated.
* @param x the amount of pixels to scroll by horizontally
* @param y the amount of pixels to scroll by vertically
*/
public void scrollBy(int x, int y) {
scrollTo(mScrollX + x, mScrollY + y);
}
/**
* Mark the the area defined by dirty as needing to be drawn. If the view is
* visible, {@link #onDraw} will be called at some point in the future.
* This must be called from a UI thread. To call from a non-UI thread, call
* {@link #postInvalidate()}.
*
* WARNING: This method is destructive to dirty.
* @param dirty the rectangle representing the bounds of the dirty region
*/
public void invalidate(Rect dirty) {
if (ViewDebug.TRACE_HIERARCHY) {
ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
}
if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
mPrivateFlags &= ~DRAWING_CACHE_VALID;
final ViewParent p = mParent;
final AttachInfo ai = mAttachInfo;
if (p != null && ai != null) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
final Rect r = ai.mTmpInvalRect;
r.set(dirty.left - scrollX, dirty.top - scrollY,
dirty.right - scrollX, dirty.bottom - scrollY);
mParent.invalidateChild(this, r);
}
}
}
/**
* Mark the the area defined by the rect (l,t,r,b) as needing to be drawn.
* The coordinates of the dirty rect are relative to the view.
* If the view is visible, {@link #onDraw} will be called at some point
* in the future. This must be called from a UI thread. To call
* from a non-UI thread, call {@link #postInvalidate()}.
* @param l the left position of the dirty region
* @param t the top position of the dirty region
* @param r the right position of the dirty region
* @param b the bottom position of the dirty region
*/
public void invalidate(int l, int t, int r, int b) {
if (ViewDebug.TRACE_HIERARCHY) {
ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
}
if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
mPrivateFlags &= ~DRAWING_CACHE_VALID;
final ViewParent p = mParent;
final AttachInfo ai = mAttachInfo;
if (p != null && ai != null && l < r && t < b) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
final Rect tmpr = ai.mTmpInvalRect;
tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY);
p.invalidateChild(this, tmpr);
}
}
}
/**
* Invalidate the whole view. If the view is visible, {@link #onDraw} will
* be called at some point in the future. This must be called from a
* UI thread. To call from a non-UI thread, call {@link #postInvalidate()}.
*/
public void invalidate() {
if (ViewDebug.TRACE_HIERARCHY) {
ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE);
}
if ((mPrivateFlags & (DRAWN | HAS_BOUNDS)) == (DRAWN | HAS_BOUNDS)) {
mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
final ViewParent p = mParent;
final AttachInfo ai = mAttachInfo;
if (p != null && ai != null) {
final Rect r = ai.mTmpInvalRect;
r.set(0, 0, mRight - mLeft, mBottom - mTop);
// Don't call invalidate -- we don't want to internally scroll
// our own bounds
p.invalidateChild(this, r);
}
}
}
/**
* Indicates whether this View is opaque. An opaque View guarantees that it will
* draw all the pixels overlapping its bounds using a fully opaque color.
*
* Subclasses of View should override this method whenever possible to indicate
* whether an instance is opaque. Opaque Views are treated in a special way by
* the View hierarchy, possibly allowing it to perform optimizations during
* invalidate/draw passes.
*
* @return True if this View is guaranteed to be fully opaque, false otherwise.
*
* @hide Pending API council approval
*/
@ViewDebug.ExportedProperty
public boolean isOpaque() {
return (mPrivateFlags & OPAQUE_MASK) == OPAQUE_MASK;
}
private void computeOpaqueFlags() {
// Opaque if:
// - Has a background
// - Background is opaque
// - Doesn't have scrollbars or scrollbars are inside overlay
if (mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE) {
mPrivateFlags |= OPAQUE_BACKGROUND;
} else {
mPrivateFlags &= ~OPAQUE_BACKGROUND;
}
final int flags = mViewFlags;
if (((flags & SCROLLBARS_VERTICAL) == 0 && (flags & SCROLLBARS_HORIZONTAL) == 0) ||
(flags & SCROLLBARS_STYLE_MASK) == SCROLLBARS_INSIDE_OVERLAY) {
mPrivateFlags |= OPAQUE_SCROLLBARS;
} else {
mPrivateFlags &= ~OPAQUE_SCROLLBARS;
}
}
/**
* @hide
*/
protected boolean hasOpaqueScrollbars() {
return (mPrivateFlags & OPAQUE_SCROLLBARS) == OPAQUE_SCROLLBARS;
}
/**
* @return A handler associated with the thread running the View. This
* handler can be used to pump events in the UI events queue.
*/
public Handler getHandler() {
if (mAttachInfo != null) {
return mAttachInfo.mHandler;
}
return null;
}
/**
* Causes the Runnable to be added to the message queue.
* The runnable will be run on the user interface thread.
*
* @param action The Runnable that will be executed.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*/
public boolean post(Runnable action) {
Handler handler;
if (mAttachInfo != null) {
handler = mAttachInfo.mHandler;
} else {
// Assume that post will succeed later
ViewRoot.getRunQueue().post(action);
return true;
}
return handler.post(action);
}
/**
* Causes the Runnable to be added to the message queue, to be run
* after the specified amount of time elapses.
* The runnable will be run on the user interface thread.
*
* @param action The Runnable that will be executed.
* @param delayMillis The delay (in milliseconds) until the Runnable
* will be executed.
*
* @return true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting. Note that a
* result of true does not mean the Runnable will be processed --
* if the looper is quit before the delivery time of the message
* occurs then the message will be dropped.
*/
public boolean postDelayed(Runnable action, long delayMillis) {
Handler handler;
if (mAttachInfo != null) {
handler = mAttachInfo.mHandler;
} else {
// Assume that post will succeed later
ViewRoot.getRunQueue().postDelayed(action, delayMillis);
return true;
}
return handler.postDelayed(action, delayMillis);
}
/**
* Removes the specified Runnable from the message queue.
*
* @param action The Runnable to remove from the message handling queue
*
* @return true if this view could ask the Handler to remove the Runnable,
* false otherwise. When the returned value is true, the Runnable
* may or may not have been actually removed from the message queue
* (for instance, if the Runnable was not in the queue already.)
*/
public boolean removeCallbacks(Runnable action) {
Handler handler;
if (mAttachInfo != null) {
handler = mAttachInfo.mHandler;
} else {
// Assume that post will succeed later
ViewRoot.getRunQueue().removeCallbacks(action);
return true;
}
handler.removeCallbacks(action);
return true;
}
/**
* Cause an invalidate to happen on a subsequent cycle through the event loop.
* Use this to invalidate the View from a non-UI thread.
*
* @see #invalidate()
*/
public void postInvalidate() {
postInvalidateDelayed(0);
}
/**
* Cause an invalidate of the specified area to happen on a subsequent cycle
* through the event loop. Use this to invalidate the View from a non-UI thread.
*
* @param left The left coordinate of the rectangle to invalidate.
* @param top The top coordinate of the rectangle to invalidate.
* @param right The right coordinate of the rectangle to invalidate.
* @param bottom The bottom coordinate of the rectangle to invalidate.
*
* @see #invalidate(int, int, int, int)
* @see #invalidate(Rect)
*/
public void postInvalidate(int left, int top, int right, int bottom) {
postInvalidateDelayed(0, left, top, right, bottom);
}
/**
* Cause an invalidate to happen on a subsequent cycle through the event
* loop. Waits for the specified amount of time.
*
* @param delayMilliseconds the duration in milliseconds to delay the
* invalidation by
*/
public void postInvalidateDelayed(long delayMilliseconds) {
// We try only with the AttachInfo because there's no point in invalidating
// if we are not attached to our window
if (mAttachInfo != null) {
Message msg = Message.obtain();
msg.what = AttachInfo.INVALIDATE_MSG;
msg.obj = this;
mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
}
}
/**
* Cause an invalidate of the specified area to happen on a subsequent cycle
* through the event loop. Waits for the specified amount of time.
*
* @param delayMilliseconds the duration in milliseconds to delay the
* invalidation by
* @param left The left coordinate of the rectangle to invalidate.
* @param top The top coordinate of the rectangle to invalidate.
* @param right The right coordinate of the rectangle to invalidate.
* @param bottom The bottom coordinate of the rectangle to invalidate.
*/
public void postInvalidateDelayed(long delayMilliseconds, int left, int top,
int right, int bottom) {
// We try only with the AttachInfo because there's no point in invalidating
// if we are not attached to our window
if (mAttachInfo != null) {
final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire();
info.target = this;
info.left = left;
info.top = top;
info.right = right;
info.bottom = bottom;
final Message msg = Message.obtain();
msg.what = AttachInfo.INVALIDATE_RECT_MSG;
msg.obj = info;
mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds);
}
}
/**
* Called by a parent to request that a child update its values for mScrollX
* and mScrollY if necessary. This will typically be done if the child is
* animating a scroll using a {@link android.widget.Scroller Scroller}
* object.
*/
public void computeScroll() {
}
/**
* <p>Indicate whether the horizontal edges are faded when the view is
* scrolled horizontally.</p>
*
* @return true if the horizontal edges should are faded on scroll, false
* otherwise
*
* @see #setHorizontalFadingEdgeEnabled(boolean)
* @attr ref android.R.styleable#View_fadingEdge
*/
public boolean isHorizontalFadingEdgeEnabled() {
return (mViewFlags & FADING_EDGE_HORIZONTAL) == FADING_EDGE_HORIZONTAL;
}
/**
* <p>Define whether the horizontal edges should be faded when this view
* is scrolled horizontally.</p>
*
* @param horizontalFadingEdgeEnabled true if the horizontal edges should
* be faded when the view is scrolled
* horizontally
*
* @see #isHorizontalFadingEdgeEnabled()
* @attr ref android.R.styleable#View_fadingEdge
*/
public void setHorizontalFadingEdgeEnabled(boolean horizontalFadingEdgeEnabled) {
if (isHorizontalFadingEdgeEnabled() != horizontalFadingEdgeEnabled) {
if (horizontalFadingEdgeEnabled) {
initScrollCache();
}
mViewFlags ^= FADING_EDGE_HORIZONTAL;
}
}
/**
* <p>Indicate whether the vertical edges are faded when the view is
* scrolled horizontally.</p>
*
* @return true if the vertical edges should are faded on scroll, false
* otherwise
*
* @see #setVerticalFadingEdgeEnabled(boolean)
* @attr ref android.R.styleable#View_fadingEdge
*/
public boolean isVerticalFadingEdgeEnabled() {
return (mViewFlags & FADING_EDGE_VERTICAL) == FADING_EDGE_VERTICAL;
}
/**
* <p>Define whether the vertical edges should be faded when this view
* is scrolled vertically.</p>
*
* @param verticalFadingEdgeEnabled true if the vertical edges should
* be faded when the view is scrolled
* vertically
*
* @see #isVerticalFadingEdgeEnabled()
* @attr ref android.R.styleable#View_fadingEdge
*/
public void setVerticalFadingEdgeEnabled(boolean verticalFadingEdgeEnabled) {
if (isVerticalFadingEdgeEnabled() != verticalFadingEdgeEnabled) {
if (verticalFadingEdgeEnabled) {
initScrollCache();
}
mViewFlags ^= FADING_EDGE_VERTICAL;
}
}
/**
* Returns the strength, or intensity, of the top faded edge. The strength is
* a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
* returns 0.0 or 1.0 but no value in between.
*
* Subclasses should override this method to provide a smoother fade transition
* when scrolling occurs.
*
* @return the intensity of the top fade as a float between 0.0f and 1.0f
*/
protected float getTopFadingEdgeStrength() {
return computeVerticalScrollOffset() > 0 ? 1.0f : 0.0f;
}
/**
* Returns the strength, or intensity, of the bottom faded edge. The strength is
* a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
* returns 0.0 or 1.0 but no value in between.
*
* Subclasses should override this method to provide a smoother fade transition
* when scrolling occurs.
*
* @return the intensity of the bottom fade as a float between 0.0f and 1.0f
*/
protected float getBottomFadingEdgeStrength() {
return computeVerticalScrollOffset() + computeVerticalScrollExtent() <
computeVerticalScrollRange() ? 1.0f : 0.0f;
}
/**
* Returns the strength, or intensity, of the left faded edge. The strength is
* a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
* returns 0.0 or 1.0 but no value in between.
*
* Subclasses should override this method to provide a smoother fade transition
* when scrolling occurs.
*
* @return the intensity of the left fade as a float between 0.0f and 1.0f
*/
protected float getLeftFadingEdgeStrength() {
return computeHorizontalScrollOffset() > 0 ? 1.0f : 0.0f;
}
/**
* Returns the strength, or intensity, of the right faded edge. The strength is
* a value between 0.0 (no fade) and 1.0 (full fade). The default implementation
* returns 0.0 or 1.0 but no value in between.
*
* Subclasses should override this method to provide a smoother fade transition
* when scrolling occurs.
*
* @return the intensity of the right fade as a float between 0.0f and 1.0f
*/
protected float getRightFadingEdgeStrength() {
return computeHorizontalScrollOffset() + computeHorizontalScrollExtent() <
computeHorizontalScrollRange() ? 1.0f : 0.0f;
}
/**
* <p>Indicate whether the horizontal scrollbar should be drawn or not. The
* scrollbar is not drawn by default.</p>
*
* @return true if the horizontal scrollbar should be painted, false
* otherwise
*
* @see #setHorizontalScrollBarEnabled(boolean)
*/
public boolean isHorizontalScrollBarEnabled() {
return (mViewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
}
/**
* <p>Define whether the horizontal scrollbar should be drawn or not. The
* scrollbar is not drawn by default.</p>
*
* @param horizontalScrollBarEnabled true if the horizontal scrollbar should
* be painted
*
* @see #isHorizontalScrollBarEnabled()
*/
public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
if (isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) {
mViewFlags ^= SCROLLBARS_HORIZONTAL;
computeOpaqueFlags();
recomputePadding();
}
}
/**
* <p>Indicate whether the vertical scrollbar should be drawn or not. The
* scrollbar is not drawn by default.</p>
*
* @return true if the vertical scrollbar should be painted, false
* otherwise
*
* @see #setVerticalScrollBarEnabled(boolean)
*/
public boolean isVerticalScrollBarEnabled() {
return (mViewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL;
}
/**
* <p>Define whether the vertical scrollbar should be drawn or not. The
* scrollbar is not drawn by default.</p>
*
* @param verticalScrollBarEnabled true if the vertical scrollbar should
* be painted
*
* @see #isVerticalScrollBarEnabled()
*/
public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
if (isVerticalScrollBarEnabled() != verticalScrollBarEnabled) {
mViewFlags ^= SCROLLBARS_VERTICAL;
computeOpaqueFlags();
recomputePadding();
}
}
private void recomputePadding() {
setPadding(mPaddingLeft, mPaddingTop, mUserPaddingRight, mUserPaddingBottom);
}
/**
* <p>Specify the style of the scrollbars. The scrollbars can be overlaid or
* inset. When inset, they add to the padding of the view. And the scrollbars
* can be drawn inside the padding area or on the edge of the view. For example,
* if a view has a background drawable and you want to draw the scrollbars
* inside the padding specified by the drawable, you can use
* SCROLLBARS_INSIDE_OVERLAY or SCROLLBARS_INSIDE_INSET. If you want them to
* appear at the edge of the view, ignoring the padding, then you can use
* SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.</p>
* @param style the style of the scrollbars. Should be one of
* SCROLLBARS_INSIDE_OVERLAY, SCROLLBARS_INSIDE_INSET,
* SCROLLBARS_OUTSIDE_OVERLAY or SCROLLBARS_OUTSIDE_INSET.
* @see #SCROLLBARS_INSIDE_OVERLAY
* @see #SCROLLBARS_INSIDE_INSET
* @see #SCROLLBARS_OUTSIDE_OVERLAY
* @see #SCROLLBARS_OUTSIDE_INSET
*/
public void setScrollBarStyle(int style) {
if (style != (mViewFlags & SCROLLBARS_STYLE_MASK)) {
mViewFlags = (mViewFlags & ~SCROLLBARS_STYLE_MASK) | (style & SCROLLBARS_STYLE_MASK);
computeOpaqueFlags();
recomputePadding();
}
}
/**
* <p>Returns the current scrollbar style.</p>
* @return the current scrollbar style
* @see #SCROLLBARS_INSIDE_OVERLAY
* @see #SCROLLBARS_INSIDE_INSET
* @see #SCROLLBARS_OUTSIDE_OVERLAY
* @see #SCROLLBARS_OUTSIDE_INSET
*/
public int getScrollBarStyle() {
return mViewFlags & SCROLLBARS_STYLE_MASK;
}
/**
* <p>Compute the horizontal range that the horizontal scrollbar
* represents.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the
* units used by {@link #computeHorizontalScrollExtent()} and
* {@link #computeHorizontalScrollOffset()}.</p>
*
* <p>The default range is the drawing width of this view.</p>
*
* @return the total horizontal range represented by the horizontal
* scrollbar
*
* @see #computeHorizontalScrollExtent()
* @see #computeHorizontalScrollOffset()
* @see android.widget.ScrollBarDrawable
*/
protected int computeHorizontalScrollRange() {
return getWidth();
}
/**
* <p>Compute the horizontal offset of the horizontal scrollbar's thumb
* within the horizontal range. This value is used to compute the position
* of the thumb within the scrollbar's track.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the
* units used by {@link #computeHorizontalScrollRange()} and
* {@link #computeHorizontalScrollExtent()}.</p>
*
* <p>The default offset is the scroll offset of this view.</p>
*
* @return the horizontal offset of the scrollbar's thumb
*
* @see #computeHorizontalScrollRange()
* @see #computeHorizontalScrollExtent()
* @see android.widget.ScrollBarDrawable
*/
protected int computeHorizontalScrollOffset() {
return mScrollX;
}
/**
* <p>Compute the horizontal extent of the horizontal scrollbar's thumb
* within the horizontal range. This value is used to compute the length
* of the thumb within the scrollbar's track.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the
* units used by {@link #computeHorizontalScrollRange()} and
* {@link #computeHorizontalScrollOffset()}.</p>
*
* <p>The default extent is the drawing width of this view.</p>
*
* @return the horizontal extent of the scrollbar's thumb
*
* @see #computeHorizontalScrollRange()
* @see #computeHorizontalScrollOffset()
* @see android.widget.ScrollBarDrawable
*/
protected int computeHorizontalScrollExtent() {
return getWidth();
}
/**
* <p>Compute the vertical range that the vertical scrollbar represents.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the
* units used by {@link #computeVerticalScrollExtent()} and
* {@link #computeVerticalScrollOffset()}.</p>
*
* @return the total vertical range represented by the vertical scrollbar
*
* <p>The default range is the drawing height of this view.</p>
*
* @see #computeVerticalScrollExtent()
* @see #computeVerticalScrollOffset()
* @see android.widget.ScrollBarDrawable
*/
protected int computeVerticalScrollRange() {
return getHeight();
}
/**
* <p>Compute the vertical offset of the vertical scrollbar's thumb
* within the horizontal range. This value is used to compute the position
* of the thumb within the scrollbar's track.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the
* units used by {@link #computeVerticalScrollRange()} and
* {@link #computeVerticalScrollExtent()}.</p>
*
* <p>The default offset is the scroll offset of this view.</p>
*
* @return the vertical offset of the scrollbar's thumb
*
* @see #computeVerticalScrollRange()
* @see #computeVerticalScrollExtent()
* @see android.widget.ScrollBarDrawable
*/
protected int computeVerticalScrollOffset() {
return mScrollY;
}
/**
* <p>Compute the vertical extent of the horizontal scrollbar's thumb
* within the vertical range. This value is used to compute the length
* of the thumb within the scrollbar's track.</p>
*
* <p>The range is expressed in arbitrary units that must be the same as the
* units used by {@link #computeHorizontalScrollRange()} and
* {@link #computeVerticalScrollOffset()}.</p>
*
* <p>The default extent is the drawing height of this view.</p>
*
* @return the vertical extent of the scrollbar's thumb
*
* @see #computeVerticalScrollRange()
* @see #computeVerticalScrollOffset()
* @see android.widget.ScrollBarDrawable
*/
protected int computeVerticalScrollExtent() {
return getHeight();
}
/**
* <p>Request the drawing of the horizontal and the vertical scrollbar. The
* scrollbars are painted only if they have been awakened first.</p>
*
* @param canvas the canvas on which to draw the scrollbars
*/
private void onDrawScrollBars(Canvas canvas) {
// scrollbars are drawn only when the animation is running
final ScrollabilityCache cache = mScrollCache;
if (cache != null) {
final int viewFlags = mViewFlags;
final boolean drawHorizontalScrollBar =
(viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL;
final boolean drawVerticalScrollBar =
(viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL
&& !isVerticalScrollBarHidden();
if (drawVerticalScrollBar || drawHorizontalScrollBar) {
final int width = mRight - mLeft;
final int height = mBottom - mTop;
final ScrollBarDrawable scrollBar = cache.scrollBar;
int size = scrollBar.getSize(false);
if (size <= 0) {
size = cache.scrollBarSize;
}
if (drawHorizontalScrollBar) {
onDrawHorizontalScrollBar(canvas, scrollBar, width, height, size);
}
if (drawVerticalScrollBar) {
onDrawVerticalScrollBar(canvas, scrollBar, width, height, size);
}
}
}
}
/**
* Override this if the vertical scrollbar needs to be hidden in a subclass, like when
* FastScroller is visible.
* @return whether to temporarily hide the vertical scrollbar
* @hide
*/
protected boolean isVerticalScrollBarHidden() {
return false;
}
/**
* <p>Draw the horizontal scrollbar if
* {@link #isHorizontalScrollBarEnabled()} returns true.</p>
*
* <p>The length of the scrollbar and its thumb is computed according to the
* values returned by {@link #computeHorizontalScrollRange()},
* {@link #computeHorizontalScrollExtent()} and
* {@link #computeHorizontalScrollOffset()}. Refer to
* {@link android.widget.ScrollBarDrawable} for more information about how
* these values relate to each other.</p>
*
* @param canvas the canvas on which to draw the scrollbar
* @param scrollBar the scrollbar's drawable
* @param width the width of the drawing surface
* @param height the height of the drawing surface
* @param size the size of the scrollbar
*
* @see #isHorizontalScrollBarEnabled()
* @see #computeHorizontalScrollRange()
* @see #computeHorizontalScrollExtent()
* @see #computeHorizontalScrollOffset()
* @see android.widget.ScrollBarDrawable
*/
private void onDrawHorizontalScrollBar(Canvas canvas, ScrollBarDrawable scrollBar, int width,
int height, int size) {
final int viewFlags = mViewFlags;
final int scrollX = mScrollX;
final int scrollY = mScrollY;
final int inside = (viewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
final int top = scrollY + height - size - (mUserPaddingBottom & inside);
final int verticalScrollBarGap =
(viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL ?
getVerticalScrollbarWidth() : 0;
scrollBar.setBounds(scrollX + (mPaddingLeft & inside), top,
scrollX + width - (mUserPaddingRight & inside) - verticalScrollBarGap, top + size);
scrollBar.setParameters(
computeHorizontalScrollRange(),
computeHorizontalScrollOffset(),
computeHorizontalScrollExtent(), false);
scrollBar.draw(canvas);
}
/**
* <p>Draw the vertical scrollbar if {@link #isVerticalScrollBarEnabled()}
* returns true.</p>
*
* <p>The length of the scrollbar and its thumb is computed according to the
* values returned by {@link #computeVerticalScrollRange()},
* {@link #computeVerticalScrollExtent()} and
* {@link #computeVerticalScrollOffset()}. Refer to
* {@link android.widget.ScrollBarDrawable} for more information about how
* these values relate to each other.</p>
*
* @param canvas the canvas on which to draw the scrollbar
* @param scrollBar the scrollbar's drawable
* @param width the width of the drawing surface
* @param height the height of the drawing surface
* @param size the size of the scrollbar
*
* @see #isVerticalScrollBarEnabled()
* @see #computeVerticalScrollRange()
* @see #computeVerticalScrollExtent()
* @see #computeVerticalScrollOffset()
* @see android.widget.ScrollBarDrawable
*/
private void onDrawVerticalScrollBar(Canvas canvas, ScrollBarDrawable scrollBar, int width,
int height, int size) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
final int inside = (mViewFlags & SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0;
// TODO: Deal with RTL languages to position scrollbar on left
final int left = scrollX + width - size - (mUserPaddingRight & inside);
scrollBar.setBounds(left, scrollY + (mPaddingTop & inside),
left + size, scrollY + height - (mUserPaddingBottom & inside));
scrollBar.setParameters(
computeVerticalScrollRange(),
computeVerticalScrollOffset(),
computeVerticalScrollExtent(), true);
scrollBar.draw(canvas);
}
/**
* Implement this to do your drawing.
*
* @param canvas the canvas on which the background will be drawn
*/
protected void onDraw(Canvas canvas) {
}
/*
* Caller is responsible for calling requestLayout if necessary.
* (This allows addViewInLayout to not request a new layout.)
*/
void assignParent(ViewParent parent) {
if (mParent == null) {
mParent = parent;
} else if (parent == null) {
mParent = null;
} else {
throw new RuntimeException("view " + this + " being added, but"
+ " it already has a parent");
}
}
/**
* This is called when the view is attached to a window. At this point it
* has a Surface and will start drawing. Note that this function is
* guaranteed to be called before {@link #onDraw}, however it may be called
* any time before the first onDraw -- including before or after
* {@link #onMeasure}.
*
* @see #onDetachedFromWindow()
*/
protected void onAttachedToWindow() {
if ((mPrivateFlags & REQUEST_TRANSPARENT_REGIONS) != 0) {
mParent.requestTransparentRegion(this);
}
}
/**
* This is called when the view is detached from a window. At this point it
* no longer has a surface for drawing.
*
* @see #onAttachedToWindow()
*/
protected void onDetachedFromWindow() {
if (mPendingCheckForLongPress != null) {
removeCallbacks(mPendingCheckForLongPress);
}
destroyDrawingCache();
}
/**
* @return The number of times this view has been attached to a window
*/
protected int getWindowAttachCount() {
return mWindowAttachCount;
}
/**
* Retrieve a unique token identifying the window this view is attached to.
* @return Return the window's token for use in
* {@link WindowManager.LayoutParams#token WindowManager.LayoutParams.token}.
*/
public IBinder getWindowToken() {
return mAttachInfo != null ? mAttachInfo.mWindowToken : null;
}
/**
* Retrieve a unique token identifying the top-level "real" window of
* the window that this view is attached to. That is, this is like
* {@link #getWindowToken}, except if the window this view in is a panel
* window (attached to another containing window), then the token of
* the containing window is returned instead.
*
* @return Returns the associated window token, either
* {@link #getWindowToken()} or the containing window's token.
*/
public IBinder getApplicationWindowToken() {
AttachInfo ai = mAttachInfo;
if (ai != null) {
IBinder appWindowToken = ai.mPanelParentWindowToken;
if (appWindowToken == null) {
appWindowToken = ai.mWindowToken;
}
return appWindowToken;
}
return null;
}
/**
* Retrieve private session object this view hierarchy is using to
* communicate with the window manager.
* @return the session object to communicate with the window manager
*/
/*package*/ IWindowSession getWindowSession() {
return mAttachInfo != null ? mAttachInfo.mSession : null;
}
/**
* @param info the {@link android.view.View.AttachInfo} to associated with
* this view
*/
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
//System.out.println("Attached! " + this);
mAttachInfo = info;
mWindowAttachCount++;
if (mFloatingTreeObserver != null) {
info.mTreeObserver.merge(mFloatingTreeObserver);
mFloatingTreeObserver = null;
}
if ((mPrivateFlags&SCROLL_CONTAINER) != 0) {
mAttachInfo.mScrollContainers.add(this);
mPrivateFlags |= SCROLL_CONTAINER_ADDED;
}
performCollectViewAttributes(visibility);
onAttachedToWindow();
int vis = info.mWindowVisibility;
if (vis != GONE) {
onWindowVisibilityChanged(vis);
}
}
void dispatchDetachedFromWindow() {
//System.out.println("Detached! " + this);
AttachInfo info = mAttachInfo;
if (info != null) {
int vis = info.mWindowVisibility;
if (vis != GONE) {
onWindowVisibilityChanged(GONE);
}
}
onDetachedFromWindow();
if ((mPrivateFlags&SCROLL_CONTAINER_ADDED) != 0) {
mAttachInfo.mScrollContainers.remove(this);
mPrivateFlags &= ~SCROLL_CONTAINER_ADDED;
}
mAttachInfo = null;
}
/**
* Store this view hierarchy's frozen state into the given container.
*
* @param container The SparseArray in which to save the view's state.
*
* @see #restoreHierarchyState
* @see #dispatchSaveInstanceState
* @see #onSaveInstanceState
*/
public void saveHierarchyState(SparseArray<Parcelable> container) {
dispatchSaveInstanceState(container);
}
/**
* Called by {@link #saveHierarchyState} to store the state for this view and its children.
* May be overridden to modify how freezing happens to a view's children; for example, some
* views may want to not store state for their children.
*
* @param container The SparseArray in which to save the view's state.
*
* @see #dispatchRestoreInstanceState
* @see #saveHierarchyState
* @see #onSaveInstanceState
*/
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
mPrivateFlags &= ~SAVE_STATE_CALLED;
Parcelable state = onSaveInstanceState();
if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
throw new IllegalStateException(
"Derived class did not call super.onSaveInstanceState()");
}
if (state != null) {
// Log.i("View", "Freezing #" + Integer.toHexString(mID)
// + ": " + state);
container.put(mID, state);
}
}
}
/**
* Hook allowing a view to generate a representation of its internal state
* that can later be used to create a new instance with that same state.
* This state should only contain information that is not persistent or can
* not be reconstructed later. For example, you will never store your
* current position on screen because that will be computed again when a
* new instance of the view is placed in its view hierarchy.
* <p>
* Some examples of things you may store here: the current cursor position
* in a text view (but usually not the text itself since that is stored in a
* content provider or other persistent storage), the currently selected
* item in a list view.
*
* @return Returns a Parcelable object containing the view's current dynamic
* state, or null if there is nothing interesting to save. The
* default implementation returns null.
* @see #onRestoreInstanceState
* @see #saveHierarchyState
* @see #dispatchSaveInstanceState
* @see #setSaveEnabled(boolean)
*/
protected Parcelable onSaveInstanceState() {
mPrivateFlags |= SAVE_STATE_CALLED;
return BaseSavedState.EMPTY_STATE;
}
/**
* Restore this view hierarchy's frozen state from the given container.
*
* @param container The SparseArray which holds previously frozen states.
*
* @see #saveHierarchyState
* @see #dispatchRestoreInstanceState
* @see #onRestoreInstanceState
*/
public void restoreHierarchyState(SparseArray<Parcelable> container) {
dispatchRestoreInstanceState(container);
}
/**
* Called by {@link #restoreHierarchyState} to retrieve the state for this view and its
* children. May be overridden to modify how restoreing happens to a view's children; for
* example, some views may want to not store state for their children.
*
* @param container The SparseArray which holds previously saved state.
*
* @see #dispatchSaveInstanceState
* @see #restoreHierarchyState
* @see #onRestoreInstanceState
*/
protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
if (mID != NO_ID) {
Parcelable state = container.get(mID);
if (state != null) {
// Log.i("View", "Restoreing #" + Integer.toHexString(mID)
// + ": " + state);
mPrivateFlags &= ~SAVE_STATE_CALLED;
onRestoreInstanceState(state);
if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) {
throw new IllegalStateException(
"Derived class did not call super.onRestoreInstanceState()");
}
}
}
}
/**
* Hook allowing a view to re-apply a representation of its internal state that had previously
* been generated by {@link #onSaveInstanceState}. This function will never be called with a
* null state.
*
* @param state The frozen state that had previously been returned by
* {@link #onSaveInstanceState}.
*
* @see #onSaveInstanceState
* @see #restoreHierarchyState
* @see #dispatchRestoreInstanceState
*/
protected void onRestoreInstanceState(Parcelable state) {
mPrivateFlags |= SAVE_STATE_CALLED;
if (state != BaseSavedState.EMPTY_STATE && state != null) {
throw new IllegalArgumentException("Wrong state class -- expecting View State");
}
}
/**
* <p>Return the time at which the drawing of the view hierarchy started.</p>
*
* @return the drawing start time in milliseconds
*/
public long getDrawingTime() {
return mAttachInfo != null ? mAttachInfo.mDrawingTime : 0;
}
/**
* <p>Enables or disables the duplication of the parent's state into this view. When
* duplication is enabled, this view gets its drawable state from its parent rather
* than from its own internal properties.</p>
*
* <p>Note: in the current implementation, setting this property to true after the
* view was added to a ViewGroup might have no effect at all. This property should
* always be used from XML or set to true before adding this view to a ViewGroup.</p>
*
* <p>Note: if this view's parent addStateFromChildren property is enabled and this
* property is enabled, an exception will be thrown.</p>
*
* @param enabled True to enable duplication of the parent's drawable state, false
* to disable it.
*
* @see #getDrawableState()
* @see #isDuplicateParentStateEnabled()
*/
public void setDuplicateParentStateEnabled(boolean enabled) {
setFlags(enabled ? DUPLICATE_PARENT_STATE : 0, DUPLICATE_PARENT_STATE);
}
/**
* <p>Indicates whether this duplicates its drawable state from its parent.</p>
*
* @return True if this view's drawable state is duplicated from the parent,
* false otherwise
*
* @see #getDrawableState()
* @see #setDuplicateParentStateEnabled(boolean)
*/
public boolean isDuplicateParentStateEnabled() {
return (mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE;
}
/**
* <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
* to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
* bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
* the cache is enabled. To benefit from the cache, you must request the drawing cache by
* calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
* null.</p>
*
* @param enabled true to enable the drawing cache, false otherwise
*
* @see #isDrawingCacheEnabled()
* @see #getDrawingCache()
* @see #buildDrawingCache()
*/
public void setDrawingCacheEnabled(boolean enabled) {
setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
}
/**
* <p>Indicates whether the drawing cache is enabled for this view.</p>
*
* @return true if the drawing cache is enabled
*
* @see #setDrawingCacheEnabled(boolean)
* @see #getDrawingCache()
*/
@ViewDebug.ExportedProperty
public boolean isDrawingCacheEnabled() {
return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED;
}
/**
* <p>Returns the bitmap in which this view drawing is cached. The returned bitmap
* is null when caching is disabled. If caching is enabled and the cache is not ready,
* this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not
* draw from the cache when the cache is enabled. To benefit from the cache, you must
* request the drawing cache by calling this method and draw it on screen if the
* returned bitmap is not null.</p>
*
* @return a bitmap representing this view or null if cache is disabled
*
* @see #setDrawingCacheEnabled(boolean)
* @see #isDrawingCacheEnabled()
* @see #buildDrawingCache()
* @see #destroyDrawingCache()
*/
public Bitmap getDrawingCache() {
if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) {
return null;
}
if ((mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED) {
buildDrawingCache();
}
return mDrawingCache == null ? null : mDrawingCache.get();
}
/**
* <p>Frees the resources used by the drawing cache. If you call
* {@link #buildDrawingCache()} manually without calling
* {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
* should cleanup the cache with this method afterwards.</p>
*
* @see #setDrawingCacheEnabled(boolean)
* @see #buildDrawingCache()
* @see #getDrawingCache()
*/
public void destroyDrawingCache() {
if (mDrawingCache != null) {
final Bitmap bitmap = mDrawingCache.get();
if (bitmap != null) bitmap.recycle();
mDrawingCache = null;
}
}
/**
* Setting a solid background color for the drawing cache's bitmaps will improve
* perfromance and memory usage. Note, though that this should only be used if this
* view will always be drawn on top of a solid color.
*
* @param color The background color to use for the drawing cache's bitmap
*
* @see #setDrawingCacheEnabled(boolean)
* @see #buildDrawingCache()
* @see #getDrawingCache()
*/
public void setDrawingCacheBackgroundColor(int color) {
mDrawingCacheBackgroundColor = color;
}
/**
* @see #setDrawingCacheBackgroundColor(int)
*
* @return The background color to used for the drawing cache's bitmap
*/
public int getDrawingCacheBackgroundColor() {
return mDrawingCacheBackgroundColor;
}
/**
* <p>Forces the drawing cache to be built if the drawing cache is invalid.</p>
*
* <p>If you call {@link #buildDrawingCache()} manually without calling
* {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you
* should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p>
*
* @see #getDrawingCache()
* @see #destroyDrawingCache()
*/
public void buildDrawingCache() {
if ((mPrivateFlags & DRAWING_CACHE_VALID) == 0 || mDrawingCache == null ||
mDrawingCache.get() == null) {
if (ViewDebug.TRACE_HIERARCHY) {
ViewDebug.trace(this, ViewDebug.HierarchyTraceType.BUILD_CACHE);
}
if (Config.DEBUG && ViewDebug.profileDrawing) {
EventLog.writeEvent(60002, hashCode());
}
int width = mRight - mLeft;
int height = mBottom - mTop;
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
final boolean scalingRequired = attachInfo.mScalingRequired;
if (scalingRequired) {
width = (int) ((width * attachInfo.mApplicationScale) + 0.5f);
height = (int) ((height * attachInfo.mApplicationScale) + 0.5f);
}
}
final int drawingCacheBackgroundColor = mDrawingCacheBackgroundColor;
final boolean opaque = drawingCacheBackgroundColor != 0 ||
(mBGDrawable != null && mBGDrawable.getOpacity() == PixelFormat.OPAQUE);
if (width <= 0 || height <= 0 ||
(width * height * (opaque ? 2 : 4) > // Projected bitmap size in bytes
ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) {
destroyDrawingCache();
return;
}
boolean clear = true;
Bitmap bitmap = mDrawingCache == null ? null : mDrawingCache.get();
if (bitmap == null || bitmap.getWidth() != width || bitmap.getHeight() != height) {
Bitmap.Config quality;
if (!opaque) {
switch (mViewFlags & DRAWING_CACHE_QUALITY_MASK) {
case DRAWING_CACHE_QUALITY_AUTO:
quality = Bitmap.Config.ARGB_8888;
break;
case DRAWING_CACHE_QUALITY_LOW:
quality = Bitmap.Config.ARGB_4444;
break;
case DRAWING_CACHE_QUALITY_HIGH:
quality = Bitmap.Config.ARGB_8888;
break;
default:
quality = Bitmap.Config.ARGB_8888;
break;
}
} else {
quality = Bitmap.Config.RGB_565;
}
// Try to cleanup memory
if (bitmap != null) bitmap.recycle();
try {
bitmap = Bitmap.createBitmap(width, height, quality);
mDrawingCache = new SoftReference<Bitmap>(bitmap);
} catch (OutOfMemoryError e) {
// If there is not enough memory to create the bitmap cache, just
// ignore the issue as bitmap caches are not required to draw the
// view hierarchy
mDrawingCache = null;
return;
}
clear = drawingCacheBackgroundColor != 0;
}
Canvas canvas;
if (attachInfo != null) {
canvas = attachInfo.mCanvas;
if (canvas == null) {
canvas = new Canvas();
// NOTE: This should have to happen only once since compatibility
// mode should not change at runtime
if (attachInfo.mScalingRequired) {
final float scale = attachInfo.mApplicationScale;
canvas.scale(scale, scale);
}
}
canvas.setBitmap(bitmap);
// Temporarily clobber the cached Canvas in case one of our children
// is also using a drawing cache. Without this, the children would
// steal the canvas by attaching their own bitmap to it and bad, bad
// thing would happen (invisible views, corrupted drawings, etc.)
attachInfo.mCanvas = null;
} else {
// This case should hopefully never or seldom happen
canvas = new Canvas(bitmap);
}
if (clear) {
bitmap.eraseColor(drawingCacheBackgroundColor);
}
computeScroll();
final int restoreCount = canvas.save();
canvas.translate(-mScrollX, -mScrollY);
mPrivateFlags |= DRAWN;
// Fast path for layouts with no backgrounds
if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
if (ViewDebug.TRACE_HIERARCHY) {
ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
}
mPrivateFlags &= ~DIRTY_MASK;
dispatchDraw(canvas);
} else {
draw(canvas);
}
canvas.restoreToCount(restoreCount);
if (attachInfo != null) {
// Restore the cached Canvas for our siblings
attachInfo.mCanvas = canvas;
}
mPrivateFlags |= DRAWING_CACHE_VALID;
}
}
/**
* Create a snapshot of the view into a bitmap. We should probably make
* some form of this public, but should think about the API.
*/
Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor) {
final int width = mRight - mLeft;
final int height = mBottom - mTop;
Bitmap bitmap = Bitmap.createBitmap(width, height, quality);
if (bitmap == null) {
throw new OutOfMemoryError();
}
Canvas canvas;
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
canvas = attachInfo.mCanvas;
if (canvas == null) {
canvas = new Canvas();
}
canvas.setBitmap(bitmap);
// Temporarily clobber the cached Canvas in case one of our children
// is also using a drawing cache. Without this, the children would
// steal the canvas by attaching their own bitmap to it and bad, bad
// things would happen (invisible views, corrupted drawings, etc.)
attachInfo.mCanvas = null;
} else {
// This case should hopefully never or seldom happen
canvas = new Canvas(bitmap);
}
if ((backgroundColor & 0xff000000) != 0) {
bitmap.eraseColor(backgroundColor);
}
computeScroll();
final int restoreCount = canvas.save();
canvas.translate(-mScrollX, -mScrollY);
// Temporarily remove the dirty mask
int flags = mPrivateFlags;
mPrivateFlags &= ~DIRTY_MASK;
// Fast path for layouts with no backgrounds
if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
dispatchDraw(canvas);
} else {
draw(canvas);
}
mPrivateFlags = flags;
canvas.restoreToCount(restoreCount);
if (attachInfo != null) {
// Restore the cached Canvas for our siblings
attachInfo.mCanvas = canvas;
}
return bitmap;
}
/**
* Indicates whether this View is currently in edit mode. A View is usually
* in edit mode when displayed within a developer tool. For instance, if
* this View is being drawn by a visual user interface builder, this method
* should return true.
*
* Subclasses should check the return value of this method to provide
* different behaviors if their normal behavior might interfere with the
* host environment. For instance: the class spawns a thread in its
* constructor, the drawing code relies on device-specific features, etc.
*
* This method is usually checked in the drawing code of custom widgets.
*
* @return True if this View is in edit mode, false otherwise.
*/
public boolean isInEditMode() {
return false;
}
/**
* If the View draws content inside its padding and enables fading edges,
* it needs to support padding offsets. Padding offsets are added to the
* fading edges to extend the length of the fade so that it covers pixels
* drawn inside the padding.
*
* Subclasses of this class should override this method if they need
* to draw content inside the padding.
*
* @return True if padding offset must be applied, false otherwise.
*
* @see #getLeftPaddingOffset()
* @see #getRightPaddingOffset()
* @see #getTopPaddingOffset()
* @see #getBottomPaddingOffset()
*
* @since CURRENT
*/
protected boolean isPaddingOffsetRequired() {
return false;
}
/**
* Amount by which to extend the left fading region. Called only when
* {@link #isPaddingOffsetRequired()} returns true.
*
* @return The left padding offset in pixels.
*
* @see #isPaddingOffsetRequired()
*
* @since CURRENT
*/
protected int getLeftPaddingOffset() {
return 0;
}
/**
* Amount by which to extend the right fading region. Called only when
* {@link #isPaddingOffsetRequired()} returns true.
*
* @return The right padding offset in pixels.
*
* @see #isPaddingOffsetRequired()
*
* @since CURRENT
*/
protected int getRightPaddingOffset() {
return 0;
}
/**
* Amount by which to extend the top fading region. Called only when
* {@link #isPaddingOffsetRequired()} returns true.
*
* @return The top padding offset in pixels.
*
* @see #isPaddingOffsetRequired()
*
* @since CURRENT
*/
protected int getTopPaddingOffset() {
return 0;
}
/**
* Amount by which to extend the bottom fading region. Called only when
* {@link #isPaddingOffsetRequired()} returns true.
*
* @return The bottom padding offset in pixels.
*
* @see #isPaddingOffsetRequired()
*
* @since CURRENT
*/
protected int getBottomPaddingOffset() {
return 0;
}
/**
* Manually render this view (and all of its children) to the given Canvas.
* The view must have already done a full layout before this function is
* called. When implementing a view, do not override this method; instead,
* you should implement {@link #onDraw}.
*
* @param canvas The Canvas to which the View is rendered.
*/
public void draw(Canvas canvas) {
if (ViewDebug.TRACE_HIERARCHY) {
ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
}
final int privateFlags = mPrivateFlags;
final boolean dirtyOpaque = (privateFlags & DIRTY_MASK) == DIRTY_OPAQUE &&
(mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
mPrivateFlags = (privateFlags & ~DIRTY_MASK) | DRAWN;
/*
* Draw traversal performs several drawing steps which must be executed
* in the appropriate order:
*
* 1. Draw the background
* 2. If necessary, save the canvas' layers to prepare for fading
* 3. Draw view's content
* 4. Draw children
* 5. If necessary, draw the fading edges and restore layers
* 6. Draw decorations (scrollbars for instance)
*/
// Step 1, draw the background, if needed
int saveCount;
if (!dirtyOpaque) {
final Drawable background = mBGDrawable;
if (background != null) {
final int scrollX = mScrollX;
final int scrollY = mScrollY;
if (mBackgroundSizeChanged) {
background.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
mBackgroundSizeChanged = false;
}
if ((scrollX | scrollY) == 0) {
background.draw(canvas);
} else {
canvas.translate(scrollX, scrollY);
background.draw(canvas);
canvas.translate(-scrollX, -scrollY);
}
}
}
// skip step 2 & 5 if possible (common case)
final int viewFlags = mViewFlags;
boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
if (!verticalEdges && !horizontalEdges) {
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Step 6, draw decorations (scrollbars)
onDrawScrollBars(canvas);
// we're done...
return;
}
/*
* Here we do the full fledged routine...
* (this is an uncommon case where speed matters less,
* this is why we repeat some of the tests that have been
* done above)
*/
boolean drawTop = false;
boolean drawBottom = false;
boolean drawLeft = false;
boolean drawRight = false;
float topFadeStrength = 0.0f;
float bottomFadeStrength = 0.0f;
float leftFadeStrength = 0.0f;
float rightFadeStrength = 0.0f;
// Step 2, save the canvas' layers
int paddingLeft = mPaddingLeft;
int paddingTop = mPaddingTop;
final boolean offsetRequired = isPaddingOffsetRequired();
if (offsetRequired) {
paddingLeft += getLeftPaddingOffset();
paddingTop += getTopPaddingOffset();
}
int left = mScrollX + paddingLeft;
int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
int top = mScrollY + paddingTop;
int bottom = top + mBottom - mTop - mPaddingBottom - paddingTop;
if (offsetRequired) {
right += getRightPaddingOffset();
bottom += getBottomPaddingOffset();
}
final ScrollabilityCache scrollabilityCache = mScrollCache;
int length = scrollabilityCache.fadingEdgeLength;
// clip the fade length if top and bottom fades overlap
// overlapping fades produce odd-looking artifacts
if (verticalEdges && (top + length > bottom - length)) {
length = (bottom - top) / 2;
}
// also clip horizontal fades if necessary
if (horizontalEdges && (left + length > right - length)) {
length = (right - left) / 2;
}
if (verticalEdges) {
topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
drawTop = topFadeStrength >= 0.0f;
bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
drawBottom = bottomFadeStrength >= 0.0f;
}
if (horizontalEdges) {
leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
drawLeft = leftFadeStrength >= 0.0f;
rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
drawRight = rightFadeStrength >= 0.0f;
}
saveCount = canvas.getSaveCount();
int solidColor = getSolidColor();
if (solidColor == 0) {
final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
if (drawTop) {
canvas.saveLayer(left, top, right, top + length, null, flags);
}
if (drawBottom) {
canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
}
if (drawLeft) {
canvas.saveLayer(left, top, left + length, bottom, null, flags);
}
if (drawRight) {
canvas.saveLayer(right - length, top, right, bottom, null, flags);
}
} else {
scrollabilityCache.setFadeColor(solidColor);
}
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Step 5, draw the fade effect and restore layers
final Paint p = scrollabilityCache.paint;
final Matrix matrix = scrollabilityCache.matrix;
final Shader fade = scrollabilityCache.shader;
final float fadeHeight = scrollabilityCache.fadingEdgeLength;
if (drawTop) {
matrix.setScale(1, fadeHeight * topFadeStrength);
matrix.postTranslate(left, top);
fade.setLocalMatrix(matrix);
canvas.drawRect(left, top, right, top + length, p);
}
if (drawBottom) {
matrix.setScale(1, fadeHeight * bottomFadeStrength);
matrix.postRotate(180);
matrix.postTranslate(left, bottom);
fade.setLocalMatrix(matrix);
canvas.drawRect(left, bottom - length, right, bottom, p);
}
if (drawLeft) {
matrix.setScale(1, fadeHeight * leftFadeStrength);
matrix.postRotate(-90);
matrix.postTranslate(left, top);
fade.setLocalMatrix(matrix);
canvas.drawRect(left, top, left + length, bottom, p);
}
if (drawRight) {
matrix.setScale(1, fadeHeight * rightFadeStrength);
matrix.postRotate(90);
matrix.postTranslate(right, top);
fade.setLocalMatrix(matrix);
canvas.drawRect(right - length, top, right, bottom, p);
}
canvas.restoreToCount(saveCount);
// Step 6, draw decorations (scrollbars)
onDrawScrollBars(canvas);
}
/**
* Override this if your view is known to always be drawn on top of a solid color background,
* and needs to draw fading edges. Returning a non-zero color enables the view system to
* optimize the drawing of the fading edges. If you do return a non-zero color, the alpha
* should be set to 0xFF.
*
* @see #setVerticalFadingEdgeEnabled
* @see #setHorizontalFadingEdgeEnabled
*
* @return The known solid color background for this view, or 0 if the color may vary
*/
public int getSolidColor() {
return 0;
}
/**
* Build a human readable string representation of the specified view flags.
*
* @param flags the view flags to convert to a string
* @return a String representing the supplied flags
*/
private static String printFlags(int flags) {
String output = "";
int numFlags = 0;
if ((flags & FOCUSABLE_MASK) == FOCUSABLE) {
output += "TAKES_FOCUS";
numFlags++;
}
switch (flags & VISIBILITY_MASK) {
case INVISIBLE:
if (numFlags > 0) {
output += " ";
}
output += "INVISIBLE";
// USELESS HERE numFlags++;
break;
case GONE:
if (numFlags > 0) {
output += " ";
}
output += "GONE";
// USELESS HERE numFlags++;
break;
default:
break;
}
return output;
}
/**
* Build a human readable string representation of the specified private
* view flags.
*
* @param privateFlags the private view flags to convert to a string
* @return a String representing the supplied flags
*/
private static String printPrivateFlags(int privateFlags) {
String output = "";
int numFlags = 0;
if ((privateFlags & WANTS_FOCUS) == WANTS_FOCUS) {
output += "WANTS_FOCUS";
numFlags++;
}
if ((privateFlags & FOCUSED) == FOCUSED) {
if (numFlags > 0) {
output += " ";
}
output += "FOCUSED";
numFlags++;
}
if ((privateFlags & SELECTED) == SELECTED) {
if (numFlags > 0) {
output += " ";
}
output += "SELECTED";
numFlags++;
}
if ((privateFlags & IS_ROOT_NAMESPACE) == IS_ROOT_NAMESPACE) {
if (numFlags > 0) {
output += " ";
}
output += "IS_ROOT_NAMESPACE";
numFlags++;
}
if ((privateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
if (numFlags > 0) {
output += " ";
}
output += "HAS_BOUNDS";
numFlags++;
}
if ((privateFlags & DRAWN) == DRAWN) {
if (numFlags > 0) {
output += " ";
}
output += "DRAWN";
// USELESS HERE numFlags++;
}
return output;
}
/**
* <p>Indicates whether or not this view's layout will be requested during
* the next hierarchy layout pass.</p>
*
* @return true if the layout will be forced during next layout pass
*/
public boolean isLayoutRequested() {
return (mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT;
}
/**
* Assign a size and position to a view and all of its
* descendants
*
* <p>This is the second phase of the layout mechanism.
* (The first is measuring). In this phase, each parent calls
* layout on all of its children to position them.
* This is typically done using the child measurements
* that were stored in the measure pass().
*
* Derived classes with children should override
* onLayout. In that method, they should
* call layout on each of their their children.
*
* @param l Left position, relative to parent
* @param t Top position, relative to parent
* @param r Right position, relative to parent
* @param b Bottom position, relative to parent
*/
public final void layout(int l, int t, int r, int b) {
boolean changed = setFrame(l, t, r, b);
if (changed || (mPrivateFlags & LAYOUT_REQUIRED) == LAYOUT_REQUIRED) {
if (ViewDebug.TRACE_HIERARCHY) {
ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_LAYOUT);
}
onLayout(changed, l, t, r, b);
mPrivateFlags &= ~LAYOUT_REQUIRED;
}
mPrivateFlags &= ~FORCE_LAYOUT;
}
/**
* Called from layout when this view should
* assign a size and position to each of its children.
*
* Derived classes with children should override
* this method and call layout on each of
* their their children.
* @param changed This is a new size or position for this view
* @param left Left position, relative to parent
* @param top Top position, relative to parent
* @param right Right position, relative to parent
* @param bottom Bottom position, relative to parent
*/
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
/**
* Assign a size and position to this view.
*
* This is called from layout.
*
* @param left Left position, relative to parent
* @param top Top position, relative to parent
* @param right Right position, relative to parent
* @param bottom Bottom position, relative to parent
* @return true if the new size and position are different than the
* previous ones
* {@hide}
*/
protected boolean setFrame(int left, int top, int right, int bottom) {
boolean changed = false;
if (DBG) {
System.out.println(this + " View.setFrame(" + left + "," + top + ","
+ right + "," + bottom + ")");
}
if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
changed = true;
// Remember our drawn bit
int drawn = mPrivateFlags & DRAWN;
// Invalidate our old position
invalidate();
int oldWidth = mRight - mLeft;
int oldHeight = mBottom - mTop;
mLeft = left;
mTop = top;
mRight = right;
mBottom = bottom;
mPrivateFlags |= HAS_BOUNDS;
int newWidth = right - left;
int newHeight = bottom - top;
if (newWidth != oldWidth || newHeight != oldHeight) {
onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);
}
if ((mViewFlags & VISIBILITY_MASK) == VISIBLE) {
// If we are visible, force the DRAWN bit to on so that
// this invalidate will go through (at least to our parent).
// This is because someone may have invalidated this view
// before this call to setFrame came in, therby clearing
// the DRAWN bit.
mPrivateFlags |= DRAWN;
invalidate();
}
// Reset drawn bit to original value (invalidate turns it off)
mPrivateFlags |= drawn;
mBackgroundSizeChanged = true;
}
return changed;
}
/**
* Finalize inflating a view from XML. This is called as the last phase
* of inflation, after all child views have been added.
*
* <p>Even if the subclass overrides onFinishInflate, they should always be
* sure to call the super method, so that we get called.
*/
protected void onFinishInflate() {
}
/**
* Returns the resources associated with this view.
*
* @return Resources object.
*/
public Resources getResources() {
return mResources;
}
/**
* Invalidates the specified Drawable.
*
* @param drawable the drawable to invalidate
*/
public void invalidateDrawable(Drawable drawable) {
if (verifyDrawable(drawable)) {
final Rect dirty = drawable.getBounds();
final int scrollX = mScrollX;
final int scrollY = mScrollY;
invalidate(dirty.left + scrollX, dirty.top + scrollY,
dirty.right + scrollX, dirty.bottom + scrollY);
}
}
/**
* Schedules an action on a drawable to occur at a specified time.
*
* @param who the recipient of the action
* @param what the action to run on the drawable
* @param when the time at which the action must occur. Uses the
* {@link SystemClock#uptimeMillis} timebase.
*/
public void scheduleDrawable(Drawable who, Runnable what, long when) {
if (verifyDrawable(who) && what != null && mAttachInfo != null) {
mAttachInfo.mHandler.postAtTime(what, who, when);
}
}
/**
* Cancels a scheduled action on a drawable.
*
* @param who the recipient of the action
* @param what the action to cancel
*/
public void unscheduleDrawable(Drawable who, Runnable what) {
if (verifyDrawable(who) && what != null && mAttachInfo != null) {
mAttachInfo.mHandler.removeCallbacks(what, who);
}
}
/**
* Unschedule any events associated with the given Drawable. This can be
* used when selecting a new Drawable into a view, so that the previous
* one is completely unscheduled.
*
* @param who The Drawable to unschedule.
*
* @see #drawableStateChanged
*/
public void unscheduleDrawable(Drawable who) {
if (mAttachInfo != null) {
mAttachInfo.mHandler.removeCallbacksAndMessages(who);
}
}
/**
* If your view subclass is displaying its own Drawable objects, it should
* override this function and return true for any Drawable it is
* displaying. This allows animations for those drawables to be
* scheduled.
*
* <p>Be sure to call through to the super class when overriding this
* function.
*
* @param who The Drawable to verify. Return true if it is one you are
* displaying, else return the result of calling through to the
* super class.
*
* @return boolean If true than the Drawable is being displayed in the
* view; else false and it is not allowed to animate.
*
* @see #unscheduleDrawable
* @see #drawableStateChanged
*/
protected boolean verifyDrawable(Drawable who) {
return who == mBGDrawable;
}
/**
* This function is called whenever the state of the view changes in such
* a way that it impacts the state of drawables being shown.
*
* <p>Be sure to call through to the superclass when overriding this
* function.
*
* @see Drawable#setState
*/
protected void drawableStateChanged() {
Drawable d = mBGDrawable;
if (d != null && d.isStateful()) {
d.setState(getDrawableState());
}
}
/**
* Call this to force a view to update its drawable state. This will cause
* drawableStateChanged to be called on this view. Views that are interested
* in the new state should call getDrawableState.
*
* @see #drawableStateChanged
* @see #getDrawableState
*/
public void refreshDrawableState() {
mPrivateFlags |= DRAWABLE_STATE_DIRTY;
drawableStateChanged();
ViewParent parent = mParent;
if (parent != null) {
parent.childDrawableStateChanged(this);
}
}
/**
* Return an array of resource IDs of the drawable states representing the
* current state of the view.
*
* @return The current drawable state
*
* @see Drawable#setState
* @see #drawableStateChanged
* @see #onCreateDrawableState
*/
public final int[] getDrawableState() {
if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {
return mDrawableState;
} else {
mDrawableState = onCreateDrawableState(0);
mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;
return mDrawableState;
}
}
/**
* Generate the new {@link android.graphics.drawable.Drawable} state for
* this view. This is called by the view
* system when the cached Drawable state is determined to be invalid. To
* retrieve the current state, you should use {@link #getDrawableState}.
*
* @param extraSpace if non-zero, this is the number of extra entries you
* would like in the returned array in which you can place your own
* states.
*
* @return Returns an array holding the current {@link Drawable} state of
* the view.
*
* @see #mergeDrawableStates
*/
protected int[] onCreateDrawableState(int extraSpace) {
if ((mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE &&
mParent instanceof View) {
return ((View) mParent).onCreateDrawableState(extraSpace);
}
int[] drawableState;
int privateFlags = mPrivateFlags;
int viewStateIndex = (((privateFlags & PRESSED) != 0) ? 1 : 0);
viewStateIndex = (viewStateIndex << 1)
+ (((mViewFlags & ENABLED_MASK) == ENABLED) ? 1 : 0);
viewStateIndex = (viewStateIndex << 1) + (isFocused() ? 1 : 0);
viewStateIndex = (viewStateIndex << 1)
+ (((privateFlags & SELECTED) != 0) ? 1 : 0);
final boolean hasWindowFocus = hasWindowFocus();
viewStateIndex = (viewStateIndex << 1) + (hasWindowFocus ? 1 : 0);
drawableState = VIEW_STATE_SETS[viewStateIndex];
//noinspection ConstantIfStatement
if (false) {
Log.i("View", "drawableStateIndex=" + viewStateIndex);
Log.i("View", toString()
+ " pressed=" + ((privateFlags & PRESSED) != 0)
+ " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED)
+ " fo=" + hasFocus()
+ " sl=" + ((privateFlags & SELECTED) != 0)
+ " wf=" + hasWindowFocus
+ ": " + Arrays.toString(drawableState));
}
if (extraSpace == 0) {
return drawableState;
}
final int[] fullState;
if (drawableState != null) {
fullState = new int[drawableState.length + extraSpace];
System.arraycopy(drawableState, 0, fullState, 0, drawableState.length);
} else {
fullState = new int[extraSpace];
}
return fullState;
}
/**
* Merge your own state values in <var>additionalState</var> into the base
* state values <var>baseState</var> that were returned by
* {@link #onCreateDrawableState}.
*
* @param baseState The base state values returned by
* {@link #onCreateDrawableState}, which will be modified to also hold your
* own additional state values.
*
* @param additionalState The additional state values you would like
* added to <var>baseState</var>; this array is not modified.
*
* @return As a convenience, the <var>baseState</var> array you originally
* passed into the function is returned.
*
* @see #onCreateDrawableState
*/
protected static int[] mergeDrawableStates(int[] baseState, int[] additionalState) {
final int N = baseState.length;
int i = N - 1;
while (i >= 0 && baseState[i] == 0) {
i--;
}
System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length);
return baseState;
}
/**
* Sets the background color for this view.
* @param color the color of the background
*/
public void setBackgroundColor(int color) {
setBackgroundDrawable(new ColorDrawable(color));
}
/**
* Set the background to a given resource. The resource should refer to
* a Drawable object.
* @param resid The identifier of the resource.
* @attr ref android.R.styleable#View_background
*/
public void setBackgroundResource(int resid) {
if (resid != 0 && resid == mBackgroundResource) {
return;
}
Drawable d= null;
if (resid != 0) {
d = mResources.getDrawable(resid);
}
setBackgroundDrawable(d);
mBackgroundResource = resid;
}
/**
* Set the background to a given Drawable, or remove the background. If the
* background has padding, this View's padding is set to the background's
* padding. However, when a background is removed, this View's padding isn't
* touched. If setting the padding is desired, please use
* {@link #setPadding(int, int, int, int)}.
*
* @param d The Drawable to use as the background, or null to remove the
* background
*/
public void setBackgroundDrawable(Drawable d) {
boolean requestLayout = false;
mBackgroundResource = 0;
/*
* Regardless of whether we're setting a new background or not, we want
* to clear the previous drawable.
*/
if (mBGDrawable != null) {
mBGDrawable.setCallback(null);
unscheduleDrawable(mBGDrawable);
}
if (d != null) {
Rect padding = sThreadLocal.get();
if (padding == null) {
padding = new Rect();
sThreadLocal.set(padding);
}
if (d.getPadding(padding)) {
setPadding(padding.left, padding.top, padding.right, padding.bottom);
}
// Compare the minimum sizes of the old Drawable and the new. If there isn't an old or
// if it has a different minimum size, we should layout again
if (mBGDrawable == null || mBGDrawable.getMinimumHeight() != d.getMinimumHeight() ||
mBGDrawable.getMinimumWidth() != d.getMinimumWidth()) {
requestLayout = true;
}
d.setCallback(this);
if (d.isStateful()) {
d.setState(getDrawableState());
}
d.setVisible(getVisibility() == VISIBLE, false);
mBGDrawable = d;
if ((mPrivateFlags & SKIP_DRAW) != 0) {
mPrivateFlags &= ~SKIP_DRAW;
mPrivateFlags |= ONLY_DRAWS_BACKGROUND;
requestLayout = true;
}
} else {
/* Remove the background */
mBGDrawable = null;
if ((mPrivateFlags & ONLY_DRAWS_BACKGROUND) != 0) {
/*
* This view ONLY drew the background before and we're removing
* the background, so now it won't draw anything
* (hence we SKIP_DRAW)
*/
mPrivateFlags &= ~ONLY_DRAWS_BACKGROUND;
mPrivateFlags |= SKIP_DRAW;
}
/*
* When the background is set, we try to apply its padding to this
* View. When the background is removed, we don't touch this View's
* padding. This is noted in the Javadocs. Hence, we don't need to
* requestLayout(), the invalidate() below is sufficient.
*/
// The old background's minimum size could have affected this
// View's layout, so let's requestLayout
requestLayout = true;
}
computeOpaqueFlags();
if (requestLayout) {
requestLayout();
}
mBackgroundSizeChanged = true;
invalidate();
}
/**
* Gets the background drawable
* @return The drawable used as the background for this view, if any.
*/
public Drawable getBackground() {
return mBGDrawable;
}
/**
* Sets the padding. The view may add on the space required to display
* the scrollbars, depending on the style and visibility of the scrollbars.
* So the values returned from {@link #getPaddingLeft}, {@link #getPaddingTop},
* {@link #getPaddingRight} and {@link #getPaddingBottom} may be different
* from the values set in this call.
*
* @attr ref android.R.styleable#View_padding
* @attr ref android.R.styleable#View_paddingBottom
* @attr ref android.R.styleable#View_paddingLeft
* @attr ref android.R.styleable#View_paddingRight
* @attr ref android.R.styleable#View_paddingTop
* @param left the left padding in pixels
* @param top the top padding in pixels
* @param right the right padding in pixels
* @param bottom the bottom padding in pixels
*/
public void setPadding(int left, int top, int right, int bottom) {
boolean changed = false;
mUserPaddingRight = right;
mUserPaddingBottom = bottom;
final int viewFlags = mViewFlags;
// Common case is there are no scroll bars.
if ((viewFlags & (SCROLLBARS_VERTICAL|SCROLLBARS_HORIZONTAL)) != 0) {
// TODO: Deal with RTL languages to adjust left padding instead of right.
if ((viewFlags & SCROLLBARS_VERTICAL) != 0) {
right += (viewFlags & SCROLLBARS_INSET_MASK) == 0
? 0 : getVerticalScrollbarWidth();
}
if ((viewFlags & SCROLLBARS_HORIZONTAL) == 0) {
bottom += (viewFlags & SCROLLBARS_INSET_MASK) == 0
? 0 : getHorizontalScrollbarHeight();
}
}
if (mPaddingLeft != left) {
changed = true;
mPaddingLeft = left;
}
if (mPaddingTop != top) {
changed = true;
mPaddingTop = top;
}
if (mPaddingRight != right) {
changed = true;
mPaddingRight = right;
}
if (mPaddingBottom != bottom) {
changed = true;
mPaddingBottom = bottom;
}
if (changed) {
requestLayout();
}
}
/**
* Returns the top padding of this view.
*
* @return the top padding in pixels
*/
public int getPaddingTop() {
return mPaddingTop;
}
/**
* Returns the bottom padding of this view. If there are inset and enabled
* scrollbars, this value may include the space required to display the
* scrollbars as well.
*
* @return the bottom padding in pixels
*/
public int getPaddingBottom() {
return mPaddingBottom;
}
/**
* Returns the left padding of this view. If there are inset and enabled
* scrollbars, this value may include the space required to display the
* scrollbars as well.
*
* @return the left padding in pixels
*/
public int getPaddingLeft() {
return mPaddingLeft;
}
/**
* Returns the right padding of this view. If there are inset and enabled
* scrollbars, this value may include the space required to display the
* scrollbars as well.
*
* @return the right padding in pixels
*/
public int getPaddingRight() {
return mPaddingRight;
}
/**
* Changes the selection state of this view. A view can be selected or not.
* Note that selection is not the same as focus. Views are typically
* selected in the context of an AdapterView like ListView or GridView;
* the selected view is the view that is highlighted.
*
* @param selected true if the view must be selected, false otherwise
*/
public void setSelected(boolean selected) {
if (((mPrivateFlags & SELECTED) != 0) != selected) {
mPrivateFlags = (mPrivateFlags & ~SELECTED) | (selected ? SELECTED : 0);
if (!selected) resetPressedState();
invalidate();
refreshDrawableState();
dispatchSetSelected(selected);
}
}
/**
* Dispatch setSelected to all of this View's children.
*
* @see #setSelected(boolean)
*
* @param selected The new selected state
*/
protected void dispatchSetSelected(boolean selected) {
}
/**
* Indicates the selection state of this view.
*
* @return true if the view is selected, false otherwise
*/
@ViewDebug.ExportedProperty
public boolean isSelected() {
return (mPrivateFlags & SELECTED) != 0;
}
/**
* Returns the ViewTreeObserver for this view's hierarchy. The view tree
* observer can be used to get notifications when global events, like
* layout, happen.
*
* The returned ViewTreeObserver observer is not guaranteed to remain
* valid for the lifetime of this View. If the caller of this method keeps
* a long-lived reference to ViewTreeObserver, it should always check for
* the return value of {@link ViewTreeObserver#isAlive()}.
*
* @return The ViewTreeObserver for this view's hierarchy.
*/
public ViewTreeObserver getViewTreeObserver() {
if (mAttachInfo != null) {
return mAttachInfo.mTreeObserver;
}
if (mFloatingTreeObserver == null) {
mFloatingTreeObserver = new ViewTreeObserver();
}
return mFloatingTreeObserver;
}
/**
* <p>Finds the topmost view in the current view hierarchy.</p>
*
* @return the topmost view containing this view
*/
public View getRootView() {
if (mAttachInfo != null) {
final View v = mAttachInfo.mRootView;
if (v != null) {
return v;
}
}
View parent = this;
while (parent.mParent != null && parent.mParent instanceof View) {
parent = (View) parent.mParent;
}
return parent;
}
/**
* <p>Computes the coordinates of this view on the screen. The argument
* must be an array of two integers. After the method returns, the array
* contains the x and y location in that order.</p>
*
* @param location an array of two integers in which to hold the coordinates
*/
public void getLocationOnScreen(int[] location) {
getLocationInWindow(location);
final AttachInfo info = mAttachInfo;
if (info != null) {
location[0] += info.mWindowLeft;
location[1] += info.mWindowTop;
}
}
/**
* <p>Computes the coordinates of this view in its window. The argument
* must be an array of two integers. After the method returns, the array
* contains the x and y location in that order.</p>
*
* @param location an array of two integers in which to hold the coordinates
*/
public void getLocationInWindow(int[] location) {
if (location == null || location.length < 2) {
throw new IllegalArgumentException("location must be an array of "
+ "two integers");
}
location[0] = mLeft;
location[1] = mTop;
ViewParent viewParent = mParent;
while (viewParent instanceof View) {
final View view = (View)viewParent;
location[0] += view.mLeft - view.mScrollX;
location[1] += view.mTop - view.mScrollY;
viewParent = view.mParent;
}
if (viewParent instanceof ViewRoot) {
// *cough*
final ViewRoot vr = (ViewRoot)viewParent;
location[1] -= vr.mCurScrollY;
}
}
/**
* {@hide}
* @param id the id of the view to be found
* @return the view of the specified id, null if cannot be found
*/
protected View findViewTraversal(int id) {
if (id == mID) {
return this;
}
return null;
}
/**
* {@hide}
* @param tag the tag of the view to be found
* @return the view of specified tag, null if cannot be found
*/
protected View findViewWithTagTraversal(Object tag) {
if (tag != null && tag.equals(mTag)) {
return this;
}
return null;
}
/**
* Look for a child view with the given id. If this view has the given
* id, return this view.
*
* @param id The id to search for.
* @return The view that has the given id in the hierarchy or null
*/
public final View findViewById(int id) {
if (id < 0) {
return null;
}
return findViewTraversal(id);
}
/**
* Look for a child view with the given tag. If this view has the given
* tag, return this view.
*
* @param tag The tag to search for, using "tag.equals(getTag())".
* @return The View that has the given tag in the hierarchy or null
*/
public final View findViewWithTag(Object tag) {
if (tag == null) {
return null;
}
return findViewWithTagTraversal(tag);
}
/**
* Sets the identifier for this view. The identifier does not have to be
* unique in this view's hierarchy. The identifier should be a positive
* number.
*
* @see #NO_ID
* @see #getId
* @see #findViewById
*
* @param id a number used to identify the view
*
* @attr ref android.R.styleable#View_id
*/
public void setId(int id) {
mID = id;
}
/**
* {@hide}
*
* @param isRoot true if the view belongs to the root namespace, false
* otherwise
*/
public void setIsRootNamespace(boolean isRoot) {
if (isRoot) {
mPrivateFlags |= IS_ROOT_NAMESPACE;
} else {
mPrivateFlags &= ~IS_ROOT_NAMESPACE;
}
}
/**
* {@hide}
*
* @return true if the view belongs to the root namespace, false otherwise
*/
public boolean isRootNamespace() {
return (mPrivateFlags&IS_ROOT_NAMESPACE) != 0;
}
/**
* Returns this view's identifier.
*
* @return a positive integer used to identify the view or {@link #NO_ID}
* if the view has no ID
*
* @see #setId
* @see #findViewById
* @attr ref android.R.styleable#View_id
*/
@ViewDebug.CapturedViewProperty
public int getId() {
return mID;
}
/**
* Returns this view's tag.
*
* @return the Object stored in this view as a tag
*
* @see #setTag(Object)
* @see #getTag(int)
*/
@ViewDebug.ExportedProperty
public Object getTag() {
return mTag;
}
/**
* Sets the tag associated with this view. A tag can be used to mark
* a view in its hierarchy and does not have to be unique within the
* hierarchy. Tags can also be used to store data within a view without
* resorting to another data structure.
*
* @param tag an Object to tag the view with
*
* @see #getTag()
* @see #setTag(int, Object)
*/
public void setTag(final Object tag) {
mTag = tag;
}
/**
* Returns the tag associated with this view and the specified key.
*
* @param key The key identifying the tag
*
* @return the Object stored in this view as a tag
*
* @see #setTag(int, Object)
* @see #getTag()
*/
public Object getTag(int key) {
SparseArray<Object> tags = null;
synchronized (sTagsLock) {
if (sTags != null) {
tags = sTags.get(this);
}
}
if (tags != null) return tags.get(key);
return null;
}
/**
* Sets a tag associated with this view and a key. A tag can be used
* to mark a view in its hierarchy and does not have to be unique within
* the hierarchy. Tags can also be used to store data within a view
* without resorting to another data structure.
*
* The specified key should be an id declared in the resources of the
* application to ensure it is unique. Keys identified as belonging to
* the Android framework or not associated with any package will cause
* an {@link IllegalArgumentException} to be thrown.
*
* @param key The key identifying the tag
* @param tag An Object to tag the view with
*
* @throws IllegalArgumentException If they specified key is not valid
*
* @see #setTag(Object)
* @see #getTag(int)
*/
public void setTag(int key, final Object tag) {
// If the package id is 0x00 or 0x01, it's either an undefined package
// or a framework id
if ((key >>> 24) < 2) {
throw new IllegalArgumentException("The key must be an application-specific "
+ "resource id.");
}
setTagInternal(this, key, tag);
}
/**
* Variation of {@link #setTag(int, Object)} that enforces the key to be a
* framework id.
*
* @hide
*/
public void setTagInternal(int key, Object tag) {
if ((key >>> 24) != 0x1) {
throw new IllegalArgumentException("The key must be a framework-specific "
+ "resource id.");
}
setTagInternal(this, key, tag);
}
private static void setTagInternal(View view, int key, Object tag) {
SparseArray<Object> tags = null;
synchronized (sTagsLock) {
if (sTags == null) {
sTags = new WeakHashMap<View, SparseArray<Object>>();
} else {
tags = sTags.get(view);
}
}
if (tags == null) {
tags = new SparseArray<Object>(2);
synchronized (sTagsLock) {
sTags.put(view, tags);
}
}
tags.put(key, tag);
}
/**
* @param consistency The type of consistency. See ViewDebug for more information.
*
* @hide
*/
protected boolean dispatchConsistencyCheck(int consistency) {
return onConsistencyCheck(consistency);
}
/**
* Method that subclasses should implement to check their consistency. The type of
* consistency check is indicated by the bit field passed as a parameter.
*
* @param consistency The type of consistency. See ViewDebug for more information.
*
* @throws IllegalStateException if the view is in an inconsistent state.
*
* @hide
*/
protected boolean onConsistencyCheck(int consistency) {
boolean result = true;
final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
if (checkLayout) {
if (getParent() == null) {
result = false;
android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
"View " + this + " does not have a parent.");
}
if (mAttachInfo == null) {
result = false;
android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
"View " + this + " is not attached to a window.");
}
}
if (checkDrawing) {
// Do not check the DIRTY/DRAWN flags because views can call invalidate()
// from their draw() method
if ((mPrivateFlags & DRAWN) != DRAWN &&
(mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
result = false;
android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
"View " + this + " was invalidated but its drawing cache is valid.");
}
}
return result;
}
/**
* Prints information about this view in the log output, with the tag
* {@link #VIEW_LOG_TAG}.
*
* @hide
*/
public void debug() {
debug(0);
}
/**
* Prints information about this view in the log output, with the tag
* {@link #VIEW_LOG_TAG}. Each line in the output is preceded with an
* indentation defined by the <code>depth</code>.
*
* @param depth the indentation level
*
* @hide
*/
protected void debug(int depth) {
String output = debugIndent(depth - 1);
output += "+ " + this;
int id = getId();
if (id != -1) {
output += " (id=" + id + ")";
}
Object tag = getTag();
if (tag != null) {
output += " (tag=" + tag + ")";
}
Log.d(VIEW_LOG_TAG, output);
if ((mPrivateFlags & FOCUSED) != 0) {
output = debugIndent(depth) + " FOCUSED";
Log.d(VIEW_LOG_TAG, output);
}
output = debugIndent(depth);
output += "frame={" + mLeft + ", " + mTop + ", " + mRight
+ ", " + mBottom + "} scroll={" + mScrollX + ", " + mScrollY
+ "} ";
Log.d(VIEW_LOG_TAG, output);
if (mPaddingLeft != 0 || mPaddingTop != 0 || mPaddingRight != 0
|| mPaddingBottom != 0) {
output = debugIndent(depth);
output += "padding={" + mPaddingLeft + ", " + mPaddingTop
+ ", " + mPaddingRight + ", " + mPaddingBottom + "}";
Log.d(VIEW_LOG_TAG, output);
}
output = debugIndent(depth);
output += "mMeasureWidth=" + mMeasuredWidth +
" mMeasureHeight=" + mMeasuredHeight;
Log.d(VIEW_LOG_TAG, output);
output = debugIndent(depth);
if (mLayoutParams == null) {
output += "BAD! no layout params";
} else {
output = mLayoutParams.debug(output);
}
Log.d(VIEW_LOG_TAG, output);
output = debugIndent(depth);
output += "flags={";
output += View.printFlags(mViewFlags);
output += "}";
Log.d(VIEW_LOG_TAG, output);
output = debugIndent(depth);
output += "privateFlags={";
output += View.printPrivateFlags(mPrivateFlags);
output += "}";
Log.d(VIEW_LOG_TAG, output);
}
/**
* Creates an string of whitespaces used for indentation.
*
* @param depth the indentation level
* @return a String containing (depth * 2 + 3) * 2 white spaces
*
* @hide
*/
protected static String debugIndent(int depth) {
StringBuilder spaces = new StringBuilder((depth * 2 + 3) * 2);
for (int i = 0; i < (depth * 2) + 3; i++) {
spaces.append(' ').append(' ');
}
return spaces.toString();
}
/**
* <p>Return the offset of the widget's text baseline from the widget's top
* boundary. If this widget does not support baseline alignment, this
* method returns -1. </p>
*
* @return the offset of the baseline within the widget's bounds or -1
* if baseline alignment is not supported
*/
@ViewDebug.ExportedProperty
public int getBaseline() {
return -1;
}
/**
* Call this when something has changed which has invalidated the
* layout of this view. This will schedule a layout pass of the view
* tree.
*/
public void requestLayout() {
if (ViewDebug.TRACE_HIERARCHY) {
ViewDebug.trace(this, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);
}
mPrivateFlags |= FORCE_LAYOUT;
if (mParent != null && !mParent.isLayoutRequested()) {
mParent.requestLayout();
}
}
/**
* Forces this view to be laid out during the next layout pass.
* This method does not call requestLayout() or forceLayout()
* on the parent.
*/
public void forceLayout() {
mPrivateFlags |= FORCE_LAYOUT;
}
/**
* <p>
* This is called to find out how big a view should be. The parent
* supplies constraint information in the width and height parameters.
* </p>
*
* <p>
* The actual mesurement work of a view is performed in
* {@link #onMeasure(int, int)}, called by this method. Therefore, only
* {@link #onMeasure(int, int)} can and must be overriden by subclasses.
* </p>
*
*
* @param widthMeasureSpec Horizontal space requirements as imposed by the
* parent
* @param heightMeasureSpec Vertical space requirements as imposed by the
* parent
*
* @see #onMeasure(int, int)
*/
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT ||
widthMeasureSpec != mOldWidthMeasureSpec ||
heightMeasureSpec != mOldHeightMeasureSpec) {
// first clears the measured dimension flag
mPrivateFlags &= ~MEASURED_DIMENSION_SET;
if (ViewDebug.TRACE_HIERARCHY) {
ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE);
}
// measure ourselves, this should set the measured dimension flag back
onMeasure(widthMeasureSpec, heightMeasureSpec);
// flag not set, setMeasuredDimension() was not invoked, we raise
// an exception to warn the developer
if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) {
throw new IllegalStateException("onMeasure() did not set the"
+ " measured dimension by calling"
+ " setMeasuredDimension()");
}
mPrivateFlags |= LAYOUT_REQUIRED;
}
mOldWidthMeasureSpec = widthMeasureSpec;
mOldHeightMeasureSpec = heightMeasureSpec;
}
/**
* <p>
* Measure the view and its content to determine the measured width and the
* measured height. This method is invoked by {@link #measure(int, int)} and
* should be overriden by subclasses to provide accurate and efficient
* measurement of their contents.
* </p>
*
* <p>
* <strong>CONTRACT:</strong> When overriding this method, you
* <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
* measured width and height of this view. Failure to do so will trigger an
* <code>IllegalStateException</code>, thrown by
* {@link #measure(int, int)}. Calling the superclass'
* {@link #onMeasure(int, int)} is a valid use.
* </p>
*
* <p>
* The base class implementation of measure defaults to the background size,
* unless a larger size is allowed by the MeasureSpec. Subclasses should
* override {@link #onMeasure(int, int)} to provide better measurements of
* their content.
* </p>
*
* <p>
* If this method is overridden, it is the subclass's responsibility to make
* sure the measured height and width are at least the view's minimum height
* and width ({@link #getSuggestedMinimumHeight()} and
* {@link #getSuggestedMinimumWidth()}).
* </p>
*
* @param widthMeasureSpec horizontal space requirements as imposed by the parent.
* The requirements are encoded with
* {@link android.view.View.MeasureSpec}.
* @param heightMeasureSpec vertical space requirements as imposed by the parent.
* The requirements are encoded with
* {@link android.view.View.MeasureSpec}.
*
* @see #getMeasuredWidth()
* @see #getMeasuredHeight()
* @see #setMeasuredDimension(int, int)
* @see #getSuggestedMinimumHeight()
* @see #getSuggestedMinimumWidth()
* @see android.view.View.MeasureSpec#getMode(int)
* @see android.view.View.MeasureSpec#getSize(int)
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
/**
* <p>This mehod must be called by {@link #onMeasure(int, int)} to store the
* measured width and measured height. Failing to do so will trigger an
* exception at measurement time.</p>
*
* @param measuredWidth the measured width of this view
* @param measuredHeight the measured height of this view
*/
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
mPrivateFlags |= MEASURED_DIMENSION_SET;
}
/**
* Utility to reconcile a desired size with constraints imposed by a MeasureSpec.
* Will take the desired size, unless a different size is imposed by the constraints.
*
* @param size How big the view wants to be
* @param measureSpec Constraints imposed by the parent
* @return The size this view should be.
*/
public static int resolveSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
result = Math.min(size, specSize);
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
/**
* Utility to return a default size. Uses the supplied size if the
* MeasureSpec imposed no contraints. Will get larger if allowed
* by the MeasureSpec.
*
* @param size Default size for this view
* @param measureSpec Constraints imposed by the parent
* @return The size this view should be.
*/
public static int getDefaultSize(int size, int measureSpec) {
int result = size;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch (specMode) {
case MeasureSpec.UNSPECIFIED:
result = size;
break;
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
/**
* Returns the suggested minimum height that the view should use. This
* returns the maximum of the view's minimum height
* and the background's minimum height
* ({@link android.graphics.drawable.Drawable#getMinimumHeight()}).
* <p>
* When being used in {@link #onMeasure(int, int)}, the caller should still
* ensure the returned height is within the requirements of the parent.
*
* @return The suggested minimum height of the view.
*/
protected int getSuggestedMinimumHeight() {
int suggestedMinHeight = mMinHeight;
if (mBGDrawable != null) {
final int bgMinHeight = mBGDrawable.getMinimumHeight();
if (suggestedMinHeight < bgMinHeight) {
suggestedMinHeight = bgMinHeight;
}
}
return suggestedMinHeight;
}
/**
* Returns the suggested minimum width that the view should use. This
* returns the maximum of the view's minimum width)
* and the background's minimum width
* ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
* <p>
* When being used in {@link #onMeasure(int, int)}, the caller should still
* ensure the returned width is within the requirements of the parent.
*
* @return The suggested minimum width of the view.
*/
protected int getSuggestedMinimumWidth() {
int suggestedMinWidth = mMinWidth;
if (mBGDrawable != null) {
final int bgMinWidth = mBGDrawable.getMinimumWidth();
if (suggestedMinWidth < bgMinWidth) {
suggestedMinWidth = bgMinWidth;
}
}
return suggestedMinWidth;
}
/**
* Sets the minimum height of the view. It is not guaranteed the view will
* be able to achieve this minimum height (for example, if its parent layout
* constrains it with less available height).
*
* @param minHeight The minimum height the view will try to be.
*/
public void setMinimumHeight(int minHeight) {
mMinHeight = minHeight;
}
/**
* Sets the minimum width of the view. It is not guaranteed the view will
* be able to achieve this minimum width (for example, if its parent layout
* constrains it with less available width).
*
* @param minWidth The minimum width the view will try to be.
*/
public void setMinimumWidth(int minWidth) {
mMinWidth = minWidth;
}
/**
* Get the animation currently associated with this view.
*
* @return The animation that is currently playing or
* scheduled to play for this view.
*/
public Animation getAnimation() {
return mCurrentAnimation;
}
/**
* Start the specified animation now.
*
* @param animation the animation to start now
*/
public void startAnimation(Animation animation) {
animation.setStartTime(Animation.START_ON_FIRST_FRAME);
setAnimation(animation);
invalidate();
}
/**
* Cancels any animations for this view.
*/
public void clearAnimation() {
mCurrentAnimation = null;
}
/**
* Sets the next animation to play for this view.
* If you want the animation to play immediately, use
* startAnimation. This method provides allows fine-grained
* control over the start time and invalidation, but you
* must make sure that 1) the animation has a start time set, and
* 2) the view will be invalidated when the animation is supposed to
* start.
*
* @param animation The next animation, or null.
*/
public void setAnimation(Animation animation) {
mCurrentAnimation = animation;
if (animation != null) {
animation.reset();
}
}
/**
* Invoked by a parent ViewGroup to notify the start of the animation
* currently associated with this view. If you override this method,
* always call super.onAnimationStart();
*
* @see #setAnimation(android.view.animation.Animation)
* @see #getAnimation()
*/
protected void onAnimationStart() {
mPrivateFlags |= ANIMATION_STARTED;
}
/**
* Invoked by a parent ViewGroup to notify the end of the animation
* currently associated with this view. If you override this method,
* always call super.onAnimationEnd();
*
* @see #setAnimation(android.view.animation.Animation)
* @see #getAnimation()
*/
protected void onAnimationEnd() {
mPrivateFlags &= ~ANIMATION_STARTED;
}
/**
* Invoked if there is a Transform that involves alpha. Subclass that can
* draw themselves with the specified alpha should return true, and then
* respect that alpha when their onDraw() is called. If this returns false
* then the view may be redirected to draw into an offscreen buffer to
* fulfill the request, which will look fine, but may be slower than if the
* subclass handles it internally. The default implementation returns false.
*
* @param alpha The alpha (0..255) to apply to the view's drawing
* @return true if the view can draw with the specified alpha.
*/
protected boolean onSetAlpha(int alpha) {
return false;
}
/**
* This is used by the RootView to perform an optimization when
* the view hierarchy contains one or several SurfaceView.
* SurfaceView is always considered transparent, but its children are not,
* therefore all View objects remove themselves from the global transparent
* region (passed as a parameter to this function).
*
* @param region The transparent region for this ViewRoot (window).
*
* @return Returns true if the effective visibility of the view at this
* point is opaque, regardless of the transparent region; returns false
* if it is possible for underlying windows to be seen behind the view.
*
* {@hide}
*/
public boolean gatherTransparentRegion(Region region) {
final AttachInfo attachInfo = mAttachInfo;
if (region != null && attachInfo != null) {
final int pflags = mPrivateFlags;
if ((pflags & SKIP_DRAW) == 0) {
// The SKIP_DRAW flag IS NOT set, so this view draws. We need to
// remove it from the transparent region.
final int[] location = attachInfo.mTransparentLocation;
getLocationInWindow(location);
region.op(location[0], location[1], location[0] + mRight - mLeft,
location[1] + mBottom - mTop, Region.Op.DIFFERENCE);
} else if ((pflags & ONLY_DRAWS_BACKGROUND) != 0 && mBGDrawable != null) {
// The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable
// exists, so we remove the background drawable's non-transparent
// parts from this transparent region.
applyDrawableToTransparentRegion(mBGDrawable, region);
}
}
return true;
}
/**
* Play a sound effect for this view.
*
* <p>The framework will play sound effects for some built in actions, such as
* clicking, but you may wish to play these effects in your widget,
* for instance, for internal navigation.
*
* <p>The sound effect will only be played if sound effects are enabled by the user, and
* {@link #isSoundEffectsEnabled()} is true.
*
* @param soundConstant One of the constants defined in {@link SoundEffectConstants}
*/
public void playSoundEffect(int soundConstant) {
if (mAttachInfo == null || mAttachInfo.mRootCallbacks == null || !isSoundEffectsEnabled()) {
return;
}
mAttachInfo.mRootCallbacks.playSoundEffect(soundConstant);
}
/**
* BZZZTT!!1!
*
* <p>Provide haptic feedback to the user for this view.
*
* <p>The framework will provide haptic feedback for some built in actions,
* such as long presses, but you may wish to provide feedback for your
* own widget.
*
* <p>The feedback will only be performed if
* {@link #isHapticFeedbackEnabled()} is true.
*
* @param feedbackConstant One of the constants defined in
* {@link HapticFeedbackConstants}
*/
public boolean performHapticFeedback(int feedbackConstant) {
return performHapticFeedback(feedbackConstant, 0);
}
/**
* BZZZTT!!1!
*
* <p>Like {@link #performHapticFeedback(int)}, with additional options.
*
* @param feedbackConstant One of the constants defined in
* {@link HapticFeedbackConstants}
* @param flags Additional flags as per {@link HapticFeedbackConstants}.
*/
public boolean performHapticFeedback(int feedbackConstant, int flags) {
if (mAttachInfo == null) {
return false;
}
if ((flags&HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING) == 0
&& !isHapticFeedbackEnabled()) {
return false;
}
return mAttachInfo.mRootCallbacks.performHapticFeedback(
feedbackConstant,
(flags&HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING) != 0);
}
/**
* Given a Drawable whose bounds have been set to draw into this view,
* update a Region being computed for {@link #gatherTransparentRegion} so
* that any non-transparent parts of the Drawable are removed from the
* given transparent region.
*
* @param dr The Drawable whose transparency is to be applied to the region.
* @param region A Region holding the current transparency information,
* where any parts of the region that are set are considered to be
* transparent. On return, this region will be modified to have the
* transparency information reduced by the corresponding parts of the
* Drawable that are not transparent.
* {@hide}
*/
public void applyDrawableToTransparentRegion(Drawable dr, Region region) {
if (DBG) {
Log.i("View", "Getting transparent region for: " + this);
}
final Region r = dr.getTransparentRegion();
final Rect db = dr.getBounds();
final AttachInfo attachInfo = mAttachInfo;
if (r != null && attachInfo != null) {
final int w = getRight()-getLeft();
final int h = getBottom()-getTop();
if (db.left > 0) {
//Log.i("VIEW", "Drawable left " + db.left + " > view 0");
r.op(0, 0, db.left, h, Region.Op.UNION);
}
if (db.right < w) {
//Log.i("VIEW", "Drawable right " + db.right + " < view " + w);
r.op(db.right, 0, w, h, Region.Op.UNION);
}
if (db.top > 0) {
//Log.i("VIEW", "Drawable top " + db.top + " > view 0");
r.op(0, 0, w, db.top, Region.Op.UNION);
}
if (db.bottom < h) {
//Log.i("VIEW", "Drawable bottom " + db.bottom + " < view " + h);
r.op(0, db.bottom, w, h, Region.Op.UNION);
}
final int[] location = attachInfo.mTransparentLocation;
getLocationInWindow(location);
r.translate(location[0], location[1]);
region.op(r, Region.Op.INTERSECT);
} else {
region.op(db, Region.Op.DIFFERENCE);
}
}
private void postCheckForLongClick() {
mHasPerformedLongPress = false;
if (mPendingCheckForLongPress == null) {
mPendingCheckForLongPress = new CheckForLongPress();
}
mPendingCheckForLongPress.rememberWindowAttachCount();
postDelayed(mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout());
}
private static int[] stateSetUnion(final int[] stateSet1,
final int[] stateSet2) {
final int stateSet1Length = stateSet1.length;
final int stateSet2Length = stateSet2.length;
final int[] newSet = new int[stateSet1Length + stateSet2Length];
int k = 0;
int i = 0;
int j = 0;
// This is a merge of the two input state sets and assumes that the
// input sets are sorted by the order imposed by ViewDrawableStates.
for (int viewState : R.styleable.ViewDrawableStates) {
if (i < stateSet1Length && stateSet1[i] == viewState) {
newSet[k++] = viewState;
i++;
} else if (j < stateSet2Length && stateSet2[j] == viewState) {
newSet[k++] = viewState;
j++;
}
if (k > 1) {
assert(newSet[k - 1] > newSet[k - 2]);
}
}
return newSet;
}
/**
* Inflate a view from an XML resource. This convenience method wraps the {@link
* LayoutInflater} class, which provides a full range of options for view inflation.
*
* @param context The Context object for your activity or application.
* @param resource The resource ID to inflate
* @param root A view group that will be the parent. Used to properly inflate the
* layout_* parameters.
* @see LayoutInflater
*/
public static View inflate(Context context, int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}
/**
* A MeasureSpec encapsulates the layout requirements passed from parent to child.
* Each MeasureSpec represents a requirement for either the width or the height.
* A MeasureSpec is comprised of a size and a mode. There are three possible
* modes:
* <dl>
* <dt>UNSPECIFIED</dt>
* <dd>
* The parent has not imposed any constraint on the child. It can be whatever size
* it wants.
* </dd>
*
* <dt>EXACTLY</dt>
* <dd>
* The parent has determined an exact size for the child. The child is going to be
* given those bounds regardless of how big it wants to be.
* </dd>
*
* <dt>AT_MOST</dt>
* <dd>
* The child can be as large as it wants up to the specified size.
* </dd>
* </dl>
*
* MeasureSpecs are implemented as ints to reduce object allocation. This class
* is provided to pack and unpack the <size, mode> tuple into the int.
*/
public static class MeasureSpec {
private static final int MODE_SHIFT = 30;
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
/**
* Measure specification mode: The parent has not imposed any constraint
* on the child. It can be whatever size it wants.
*/
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
/**
* Measure specification mode: The parent has determined an exact size
* for the child. The child is going to be given those bounds regardless
* of how big it wants to be.
*/
public static final int EXACTLY = 1 << MODE_SHIFT;
/**
* Measure specification mode: The child can be as large as it wants up
* to the specified size.
*/
public static final int AT_MOST = 2 << MODE_SHIFT;
/**
* Creates a measure specification based on the supplied size and mode.
*
* The mode must always be one of the following:
* <ul>
* <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
* <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
* <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
* </ul>
*
* @param size the size of the measure specification
* @param mode the mode of the measure specification
* @return the measure specification based on size and mode
*/
public static int makeMeasureSpec(int size, int mode) {
return size + mode;
}
/**
* Extracts the mode from the supplied measure specification.
*
* @param measureSpec the measure specification to extract the mode from
* @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
* {@link android.view.View.MeasureSpec#AT_MOST} or
* {@link android.view.View.MeasureSpec#EXACTLY}
*/
public static int getMode(int measureSpec) {
return (measureSpec & MODE_MASK);
}
/**
* Extracts the size from the supplied measure specification.
*
* @param measureSpec the measure specification to extract the size from
* @return the size in pixels defined in the supplied measure specification
*/
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
/**
* Returns a String representation of the specified measure
* specification.
*
* @param measureSpec the measure specification to convert to a String
* @return a String with the following format: "MeasureSpec: MODE SIZE"
*/
public static String toString(int measureSpec) {
int mode = getMode(measureSpec);
int size = getSize(measureSpec);
StringBuilder sb = new StringBuilder("MeasureSpec: ");
if (mode == UNSPECIFIED)
sb.append("UNSPECIFIED ");
else if (mode == EXACTLY)
sb.append("EXACTLY ");
else if (mode == AT_MOST)
sb.append("AT_MOST ");
else
sb.append(mode).append(" ");
sb.append(size);
return sb.toString();
}
}
class CheckForLongPress implements Runnable {
private int mOriginalWindowAttachCount;
public void run() {
if (isPressed() && (mParent != null)
&& mOriginalWindowAttachCount == mWindowAttachCount) {
if (performLongClick()) {
mHasPerformedLongPress = true;
}
}
}
public void rememberWindowAttachCount() {
mOriginalWindowAttachCount = mWindowAttachCount;
}
}
/**
* Interface definition for a callback to be invoked when a key event is
* dispatched to this view. The callback will be invoked before the key
* event is given to the view.
*/
public interface OnKeyListener {
/**
* Called when a key is dispatched to a view. This allows listeners to
* get a chance to respond before the target view.
*
* @param v The view the key has been dispatched to.
* @param keyCode The code for the physical key that was pressed
* @param event The KeyEvent object containing full information about
* the event.
* @return True if the listener has consumed the event, false otherwise.
*/
boolean onKey(View v, int keyCode, KeyEvent event);
}
/**
* Interface definition for a callback to be invoked when a touch event is
* dispatched to this view. The callback will be invoked before the touch
* event is given to the view.
*/
public interface OnTouchListener {
/**
* Called when a touch event is dispatched to a view. This allows listeners to
* get a chance to respond before the target view.
*
* @param v The view the touch event has been dispatched to.
* @param event The MotionEvent object containing full information about
* the event.
* @return True if the listener has consumed the event, false otherwise.
*/
boolean onTouch(View v, MotionEvent event);
}
/**
* Interface definition for a callback to be invoked when a view has been clicked and held.
*/
public interface OnLongClickListener {
/**
* Called when a view has been clicked and held.
*
* @param v The view that was clicked and held.
*
* return True if the callback consumed the long click, false otherwise
*/
boolean onLongClick(View v);
}
/**
* Interface definition for a callback to be invoked when the focus state of
* a view changed.
*/
public interface OnFocusChangeListener {
/**
* Called when the focus state of a view has changed.
*
* @param v The view whose state has changed.
* @param hasFocus The new focus state of v.
*/
void onFocusChange(View v, boolean hasFocus);
}
/**
* Interface definition for a callback to be invoked when a view is clicked.
*/
public interface OnClickListener {
/**
* Called when a view has been clicked.
*
* @param v The view that was clicked.
*/
void onClick(View v);
}
/**
* Interface definition for a callback to be invoked when the context menu
* for this view is being built.
*/
public interface OnCreateContextMenuListener {
/**
* Called when the context menu for this view is being built. It is not
* safe to hold onto the menu after this method returns.
*
* @param menu The context menu that is being built
* @param v The view for which the context menu is being built
* @param menuInfo Extra information about the item for which the
* context menu should be shown. This information will vary
* depending on the class of v.
*/
void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo);
}
private final class UnsetPressedState implements Runnable {
public void run() {
setPressed(false);
}
}
/**
* Base class for derived classes that want to save and restore their own
* state in {@link android.view.View#onSaveInstanceState()}.
*/
public static class BaseSavedState extends AbsSavedState {
/**
* Constructor used when reading from a parcel. Reads the state of the superclass.
*
* @param source
*/
public BaseSavedState(Parcel source) {
super(source);
}
/**
* Constructor called by derived classes when creating their SavedState objects
*
* @param superState The state of the superclass of this view
*/
public BaseSavedState(Parcelable superState) {
super(superState);
}
public static final Parcelable.Creator<BaseSavedState> CREATOR =
new Parcelable.Creator<BaseSavedState>() {
public BaseSavedState createFromParcel(Parcel in) {
return new BaseSavedState(in);
}
public BaseSavedState[] newArray(int size) {
return new BaseSavedState[size];
}
};
}
/**
* A set of information given to a view when it is attached to its parent
* window.
*/
static class AttachInfo {
interface Callbacks {
void playSoundEffect(int effectId);
boolean performHapticFeedback(int effectId, boolean always);
}
/**
* InvalidateInfo is used to post invalidate(int, int, int, int) messages
* to a Handler. This class contains the target (View) to invalidate and
* the coordinates of the dirty rectangle.
*
* For performance purposes, this class also implements a pool of up to
* POOL_LIMIT objects that get reused. This reduces memory allocations
* whenever possible.
*/
static class InvalidateInfo implements Poolable<InvalidateInfo> {
private static final int POOL_LIMIT = 10;
private static final Pool<InvalidateInfo> sPool = Pools.synchronizedPool(
Pools.finitePool(new PoolableManager<InvalidateInfo>() {
public InvalidateInfo newInstance() {
return new InvalidateInfo();
}
public void onAcquired(InvalidateInfo element) {
}
public void onReleased(InvalidateInfo element) {
}
}, POOL_LIMIT)
);
private InvalidateInfo mNext;
View target;
int left;
int top;
int right;
int bottom;
public void setNextPoolable(InvalidateInfo element) {
mNext = element;
}
public InvalidateInfo getNextPoolable() {
return mNext;
}
static InvalidateInfo acquire() {
return sPool.acquire();
}
void release() {
sPool.release(this);
}
}
final IWindowSession mSession;
final IWindow mWindow;
final IBinder mWindowToken;
final Callbacks mRootCallbacks;
/**
* The top view of the hierarchy.
*/
View mRootView;
IBinder mPanelParentWindowToken;
Surface mSurface;
/**
* Scale factor used by the compatibility mode
*/
float mApplicationScale;
/**
* Indicates whether the application is in compatibility mode
*/
boolean mScalingRequired;
/**
* Left position of this view's window
*/
int mWindowLeft;
/**
* Top position of this view's window
*/
int mWindowTop;
/**
* For windows that are full-screen but using insets to layout inside
* of the screen decorations, these are the current insets for the
* content of the window.
*/
final Rect mContentInsets = new Rect();
/**
* For windows that are full-screen but using insets to layout inside
* of the screen decorations, these are the current insets for the
* actual visible parts of the window.
*/
final Rect mVisibleInsets = new Rect();
/**
* The internal insets given by this window. This value is
* supplied by the client (through
* {@link ViewTreeObserver.OnComputeInternalInsetsListener}) and will
* be given to the window manager when changed to be used in laying
* out windows behind it.
*/
final ViewTreeObserver.InternalInsetsInfo mGivenInternalInsets
= new ViewTreeObserver.InternalInsetsInfo();
/**
* All views in the window's hierarchy that serve as scroll containers,
* used to determine if the window can be resized or must be panned
* to adjust for a soft input area.
*/
final ArrayList<View> mScrollContainers = new ArrayList<View>();
/**
* Indicates whether the view's window currently has the focus.
*/
boolean mHasWindowFocus;
/**
* The current visibility of the window.
*/
int mWindowVisibility;
/**
* Indicates the time at which drawing started to occur.
*/
long mDrawingTime;
/**
* Indicates whether or not ignoring the DIRTY_MASK flags.
*/
boolean mIgnoreDirtyState;
/**
* Indicates whether the view's window is currently in touch mode.
*/
boolean mInTouchMode;
/**
* Indicates that ViewRoot should trigger a global layout change
* the next time it performs a traversal
*/
boolean mRecomputeGlobalAttributes;
/**
* Set to true when attributes (like mKeepScreenOn) need to be
* recomputed.
*/
boolean mAttributesChanged;
/**
* Set during a traveral if any views want to keep the screen on.
*/
boolean mKeepScreenOn;
/**
* Set if the visibility of any views has changed.
*/
boolean mViewVisibilityChanged;
/**
* Set to true if a view has been scrolled.
*/
boolean mViewScrollChanged;
/**
* Global to the view hierarchy used as a temporary for dealing with
* x/y points in the transparent region computations.
*/
final int[] mTransparentLocation = new int[2];
/**
* Global to the view hierarchy used as a temporary for dealing with
* x/y points in the ViewGroup.invalidateChild implementation.
*/
final int[] mInvalidateChildLocation = new int[2];
/**
* The view tree observer used to dispatch global events like
* layout, pre-draw, touch mode change, etc.
*/
final ViewTreeObserver mTreeObserver = new ViewTreeObserver();
/**
* A Canvas used by the view hierarchy to perform bitmap caching.
*/
Canvas mCanvas;
/**
* A Handler supplied by a view's {@link android.view.ViewRoot}. This
* handler can be used to pump events in the UI events queue.
*/
final Handler mHandler;
/**
* Identifier for messages requesting the view to be invalidated.
* Such messages should be sent to {@link #mHandler}.
*/
static final int INVALIDATE_MSG = 0x1;
/**
* Identifier for messages requesting the view to invalidate a region.
* Such messages should be sent to {@link #mHandler}.
*/
static final int INVALIDATE_RECT_MSG = 0x2;
/**
* Temporary for use in computing invalidate rectangles while
* calling up the hierarchy.
*/
final Rect mTmpInvalRect = new Rect();
/**
* Temporary list for use in collecting focusable descendents of a view.
*/
final ArrayList<View> mFocusablesTempList = new ArrayList<View>(24);
/**
* Creates a new set of attachment information with the specified
* events handler and thread.
*
* @param handler the events handler the view must use
*/
AttachInfo(IWindowSession session, IWindow window,
Handler handler, Callbacks effectPlayer) {
mSession = session;
mWindow = window;
mWindowToken = window.asBinder();
mHandler = handler;
mRootCallbacks = effectPlayer;
}
}
/**
* <p>ScrollabilityCache holds various fields used by a View when scrolling
* is supported. This avoids keeping too many unused fields in most
* instances of View.</p>
*/
private static class ScrollabilityCache {
public int fadingEdgeLength;
public int scrollBarSize;
public ScrollBarDrawable scrollBar;
public final Paint paint;
public final Matrix matrix;
public Shader shader;
private int mLastColor;
public ScrollabilityCache(ViewConfiguration configuration) {
fadingEdgeLength = configuration.getScaledFadingEdgeLength();
scrollBarSize = configuration.getScaledScrollBarSize();
paint = new Paint();
matrix = new Matrix();
// use use a height of 1, and then wack the matrix each time we
// actually use it.
shader = new LinearGradient(0, 0, 0, 1, 0xFF000000, 0, Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
}
public void setFadeColor(int color) {
if (color != 0 && color != mLastColor) {
mLastColor = color;
color |= 0xFF000000;
shader = new LinearGradient(0, 0, 0, 1, color, 0, Shader.TileMode.CLAMP);
paint.setShader(shader);
// Restore the default transfer mode (src_over)
paint.setXfermode(null);
}
}
}
}
| false | true | public View(Context context, AttributeSet attrs, int defStyle) {
this(context);
TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
defStyle, 0);
Drawable background = null;
int leftPadding = -1;
int topPadding = -1;
int rightPadding = -1;
int bottomPadding = -1;
int padding = -1;
int viewFlagValues = 0;
int viewFlagMasks = 0;
boolean setScrollContainer = false;
int x = 0;
int y = 0;
int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
switch (attr) {
case com.android.internal.R.styleable.View_background:
background = a.getDrawable(attr);
break;
case com.android.internal.R.styleable.View_padding:
padding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingLeft:
leftPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingTop:
topPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingRight:
rightPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingBottom:
bottomPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_scrollX:
x = a.getDimensionPixelOffset(attr, 0);
break;
case com.android.internal.R.styleable.View_scrollY:
y = a.getDimensionPixelOffset(attr, 0);
break;
case com.android.internal.R.styleable.View_id:
mID = a.getResourceId(attr, NO_ID);
break;
case com.android.internal.R.styleable.View_tag:
mTag = a.getText(attr);
break;
case com.android.internal.R.styleable.View_fitsSystemWindows:
if (a.getBoolean(attr, false)) {
viewFlagValues |= FITS_SYSTEM_WINDOWS;
viewFlagMasks |= FITS_SYSTEM_WINDOWS;
}
break;
case com.android.internal.R.styleable.View_focusable:
if (a.getBoolean(attr, false)) {
viewFlagValues |= FOCUSABLE;
viewFlagMasks |= FOCUSABLE_MASK;
}
break;
case com.android.internal.R.styleable.View_focusableInTouchMode:
if (a.getBoolean(attr, false)) {
viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
}
break;
case com.android.internal.R.styleable.View_clickable:
if (a.getBoolean(attr, false)) {
viewFlagValues |= CLICKABLE;
viewFlagMasks |= CLICKABLE;
}
break;
case com.android.internal.R.styleable.View_longClickable:
if (a.getBoolean(attr, false)) {
viewFlagValues |= LONG_CLICKABLE;
viewFlagMasks |= LONG_CLICKABLE;
}
break;
case com.android.internal.R.styleable.View_saveEnabled:
if (!a.getBoolean(attr, true)) {
viewFlagValues |= SAVE_DISABLED;
viewFlagMasks |= SAVE_DISABLED_MASK;
}
break;
case com.android.internal.R.styleable.View_duplicateParentState:
if (a.getBoolean(attr, false)) {
viewFlagValues |= DUPLICATE_PARENT_STATE;
viewFlagMasks |= DUPLICATE_PARENT_STATE;
}
break;
case com.android.internal.R.styleable.View_visibility:
final int visibility = a.getInt(attr, 0);
if (visibility != 0) {
viewFlagValues |= VISIBILITY_FLAGS[visibility];
viewFlagMasks |= VISIBILITY_MASK;
}
break;
case com.android.internal.R.styleable.View_drawingCacheQuality:
final int cacheQuality = a.getInt(attr, 0);
if (cacheQuality != 0) {
viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
}
break;
case com.android.internal.R.styleable.View_contentDescription:
mContentDescription = a.getString(attr);
break;
case com.android.internal.R.styleable.View_soundEffectsEnabled:
if (!a.getBoolean(attr, true)) {
viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
viewFlagMasks |= SOUND_EFFECTS_ENABLED;
}
case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
if (!a.getBoolean(attr, true)) {
viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
}
case R.styleable.View_scrollbars:
final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
if (scrollbars != SCROLLBARS_NONE) {
viewFlagValues |= scrollbars;
viewFlagMasks |= SCROLLBARS_MASK;
initializeScrollbars(a);
}
break;
case R.styleable.View_fadingEdge:
final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
if (fadingEdge != FADING_EDGE_NONE) {
viewFlagValues |= fadingEdge;
viewFlagMasks |= FADING_EDGE_MASK;
initializeFadingEdge(a);
}
break;
case R.styleable.View_scrollbarStyle:
scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
viewFlagMasks |= SCROLLBARS_STYLE_MASK;
}
break;
case R.styleable.View_isScrollContainer:
setScrollContainer = true;
if (a.getBoolean(attr, false)) {
setScrollContainer(true);
}
break;
case com.android.internal.R.styleable.View_keepScreenOn:
if (a.getBoolean(attr, false)) {
viewFlagValues |= KEEP_SCREEN_ON;
viewFlagMasks |= KEEP_SCREEN_ON;
}
break;
case R.styleable.View_nextFocusLeft:
mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_nextFocusRight:
mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_nextFocusUp:
mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_nextFocusDown:
mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_minWidth:
mMinWidth = a.getDimensionPixelSize(attr, 0);
break;
case R.styleable.View_minHeight:
mMinHeight = a.getDimensionPixelSize(attr, 0);
break;
case R.styleable.View_onClick:
final String handlerName = a.getString(attr);
if (handlerName != null) {
setOnClickListener(new OnClickListener() {
private Method mHandler;
public void onClick(View v) {
if (mHandler == null) {
try {
mHandler = getContext().getClass().getMethod(handlerName,
View.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity", e);
}
}
try {
mHandler.invoke(getContext(), View.this);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not execute non "
+ "public method of the activity", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not execute "
+ "method of the activity", e);
}
}
});
}
break;
}
}
if (background != null) {
setBackgroundDrawable(background);
}
if (padding >= 0) {
leftPadding = padding;
topPadding = padding;
rightPadding = padding;
bottomPadding = padding;
}
// If the user specified the padding (either with android:padding or
// android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
// use the default padding or the padding from the background drawable
// (stored at this point in mPadding*)
setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
topPadding >= 0 ? topPadding : mPaddingTop,
rightPadding >= 0 ? rightPadding : mPaddingRight,
bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
if (viewFlagMasks != 0) {
setFlags(viewFlagValues, viewFlagMasks);
}
// Needs to be called after mViewFlags is set
if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
recomputePadding();
}
if (x != 0 || y != 0) {
scrollTo(x, y);
}
if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
setScrollContainer(true);
}
computeOpaqueFlags();
a.recycle();
}
| public View(Context context, AttributeSet attrs, int defStyle) {
this(context);
TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
defStyle, 0);
Drawable background = null;
int leftPadding = -1;
int topPadding = -1;
int rightPadding = -1;
int bottomPadding = -1;
int padding = -1;
int viewFlagValues = 0;
int viewFlagMasks = 0;
boolean setScrollContainer = false;
int x = 0;
int y = 0;
int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
final int N = a.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = a.getIndex(i);
switch (attr) {
case com.android.internal.R.styleable.View_background:
background = a.getDrawable(attr);
break;
case com.android.internal.R.styleable.View_padding:
padding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingLeft:
leftPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingTop:
topPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingRight:
rightPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_paddingBottom:
bottomPadding = a.getDimensionPixelSize(attr, -1);
break;
case com.android.internal.R.styleable.View_scrollX:
x = a.getDimensionPixelOffset(attr, 0);
break;
case com.android.internal.R.styleable.View_scrollY:
y = a.getDimensionPixelOffset(attr, 0);
break;
case com.android.internal.R.styleable.View_id:
mID = a.getResourceId(attr, NO_ID);
break;
case com.android.internal.R.styleable.View_tag:
mTag = a.getText(attr);
break;
case com.android.internal.R.styleable.View_fitsSystemWindows:
if (a.getBoolean(attr, false)) {
viewFlagValues |= FITS_SYSTEM_WINDOWS;
viewFlagMasks |= FITS_SYSTEM_WINDOWS;
}
break;
case com.android.internal.R.styleable.View_focusable:
if (a.getBoolean(attr, false)) {
viewFlagValues |= FOCUSABLE;
viewFlagMasks |= FOCUSABLE_MASK;
}
break;
case com.android.internal.R.styleable.View_focusableInTouchMode:
if (a.getBoolean(attr, false)) {
viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
}
break;
case com.android.internal.R.styleable.View_clickable:
if (a.getBoolean(attr, false)) {
viewFlagValues |= CLICKABLE;
viewFlagMasks |= CLICKABLE;
}
break;
case com.android.internal.R.styleable.View_longClickable:
if (a.getBoolean(attr, false)) {
viewFlagValues |= LONG_CLICKABLE;
viewFlagMasks |= LONG_CLICKABLE;
}
break;
case com.android.internal.R.styleable.View_saveEnabled:
if (!a.getBoolean(attr, true)) {
viewFlagValues |= SAVE_DISABLED;
viewFlagMasks |= SAVE_DISABLED_MASK;
}
break;
case com.android.internal.R.styleable.View_duplicateParentState:
if (a.getBoolean(attr, false)) {
viewFlagValues |= DUPLICATE_PARENT_STATE;
viewFlagMasks |= DUPLICATE_PARENT_STATE;
}
break;
case com.android.internal.R.styleable.View_visibility:
final int visibility = a.getInt(attr, 0);
if (visibility != 0) {
viewFlagValues |= VISIBILITY_FLAGS[visibility];
viewFlagMasks |= VISIBILITY_MASK;
}
break;
case com.android.internal.R.styleable.View_drawingCacheQuality:
final int cacheQuality = a.getInt(attr, 0);
if (cacheQuality != 0) {
viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
}
break;
case com.android.internal.R.styleable.View_contentDescription:
mContentDescription = a.getString(attr);
break;
case com.android.internal.R.styleable.View_soundEffectsEnabled:
if (!a.getBoolean(attr, true)) {
viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
viewFlagMasks |= SOUND_EFFECTS_ENABLED;
}
break;
case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
if (!a.getBoolean(attr, true)) {
viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
}
break;
case R.styleable.View_scrollbars:
final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
if (scrollbars != SCROLLBARS_NONE) {
viewFlagValues |= scrollbars;
viewFlagMasks |= SCROLLBARS_MASK;
initializeScrollbars(a);
}
break;
case R.styleable.View_fadingEdge:
final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
if (fadingEdge != FADING_EDGE_NONE) {
viewFlagValues |= fadingEdge;
viewFlagMasks |= FADING_EDGE_MASK;
initializeFadingEdge(a);
}
break;
case R.styleable.View_scrollbarStyle:
scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
viewFlagMasks |= SCROLLBARS_STYLE_MASK;
}
break;
case R.styleable.View_isScrollContainer:
setScrollContainer = true;
if (a.getBoolean(attr, false)) {
setScrollContainer(true);
}
break;
case com.android.internal.R.styleable.View_keepScreenOn:
if (a.getBoolean(attr, false)) {
viewFlagValues |= KEEP_SCREEN_ON;
viewFlagMasks |= KEEP_SCREEN_ON;
}
break;
case R.styleable.View_nextFocusLeft:
mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_nextFocusRight:
mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_nextFocusUp:
mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_nextFocusDown:
mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
break;
case R.styleable.View_minWidth:
mMinWidth = a.getDimensionPixelSize(attr, 0);
break;
case R.styleable.View_minHeight:
mMinHeight = a.getDimensionPixelSize(attr, 0);
break;
case R.styleable.View_onClick:
final String handlerName = a.getString(attr);
if (handlerName != null) {
setOnClickListener(new OnClickListener() {
private Method mHandler;
public void onClick(View v) {
if (mHandler == null) {
try {
mHandler = getContext().getClass().getMethod(handlerName,
View.class);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity", e);
}
}
try {
mHandler.invoke(getContext(), View.this);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not execute non "
+ "public method of the activity", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not execute "
+ "method of the activity", e);
}
}
});
}
break;
}
}
if (background != null) {
setBackgroundDrawable(background);
}
if (padding >= 0) {
leftPadding = padding;
topPadding = padding;
rightPadding = padding;
bottomPadding = padding;
}
// If the user specified the padding (either with android:padding or
// android:paddingLeft/Top/Right/Bottom), use this padding, otherwise
// use the default padding or the padding from the background drawable
// (stored at this point in mPadding*)
setPadding(leftPadding >= 0 ? leftPadding : mPaddingLeft,
topPadding >= 0 ? topPadding : mPaddingTop,
rightPadding >= 0 ? rightPadding : mPaddingRight,
bottomPadding >= 0 ? bottomPadding : mPaddingBottom);
if (viewFlagMasks != 0) {
setFlags(viewFlagValues, viewFlagMasks);
}
// Needs to be called after mViewFlags is set
if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
recomputePadding();
}
if (x != 0 || y != 0) {
scrollTo(x, y);
}
if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
setScrollContainer(true);
}
computeOpaqueFlags();
a.recycle();
}
|
diff --git a/src/diaketas/UI/UI.java b/src/diaketas/UI/UI.java
index 6eb016b..fc1783d 100644
--- a/src/diaketas/UI/UI.java
+++ b/src/diaketas/UI/UI.java
@@ -1,222 +1,222 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package diaketas.UI;
import diaketas.UI.Beneficiarios.jBeneficiario;
import diaketas.UI.Voluntarios.jVoluntarios;
import diaketas.UI.Donaciones.jDonaciones;
import diaketas.UI.Donantes.jDonantes;
import diaketas.UI.Empleo.jEmpleo;
import diaketas.UI.HistorialesyAcciones.jHistorialyAcciones;
import java.awt.CardLayout;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
/**
*
* @author kesada
*/
public class UI extends javax.swing.JFrame {
public static CardLayout cl;
/**
* Creates new form Main
*/
public UI() {
initComponents();
jPrincipalScroll.getViewport().setView(jPrincipal);
cl = (CardLayout)(jPrincipal.getLayout());
/*Paneles acciones */
/*Categorias principales jPrincipal*/
JPanel beneficiarios = new jBeneficiario();
JPanel diaketas = new jVoluntarios();
JPanel donaciones = new jDonaciones();
JPanel empleo = new jEmpleo();
JPanel donantes = new jDonantes();
JPanel historialyacciones = new jHistorialyAcciones();
/*JPrincipal*/
jPrincipal.add("Donantes", donantes);
jPrincipal.add("Empleo", empleo);
jPrincipal.add("Donaciones", donaciones);
jPrincipal.add("Diaketas", diaketas);
jPrincipal.add("Beneficiarios", beneficiarios);
jPrincipal.add("HistorialyAcciones", historialyacciones);
/*Mostramos Diaketas*/
cl.show(jPrincipal, "Diaketas");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jMenuBotones = new javax.swing.JPanel();
botonDiaketas = new javax.swing.JButton();
botonDonantes = new javax.swing.JButton();
botonBeneficiarios = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
botonDonaciones = new javax.swing.JButton();
botonEmpleo = new javax.swing.JButton();
jPrincipal = new javax.swing.JPanel();
jPrincipalScroll = new javax.swing.JScrollPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Diaketas");
setIconImage(getIconImage());
setMinimumSize(new java.awt.Dimension(1262, 628));
setName("Principal");
setPreferredSize(new java.awt.Dimension(1262, 109));
jMenuBotones.setLayout(new java.awt.GridLayout(1, 0));
- botonDiaketas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/Home.png"))); // NOI18N
+ botonDiaketas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/Voluntario.png"))); // NOI18N
botonDiaketas.setText("Voluntarios");
botonDiaketas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonDiaketasActionPerformed(evt);
}
});
jMenuBotones.add(botonDiaketas);
botonDonantes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/Socios.gif"))); // NOI18N
botonDonantes.setText("Donantes");
botonDonantes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonDonantesActionPerformed(evt);
}
});
jMenuBotones.add(botonDonantes);
botonBeneficiarios.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/beneficiarios.png"))); // NOI18N
botonBeneficiarios.setText("Beneficiarios");
botonBeneficiarios.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonBeneficiariosActionPerformed(evt);
}
});
jMenuBotones.add(botonBeneficiarios);
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/historiales.png"))); // NOI18N
jButton1.setText("Historiales");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jMenuBotones.add(jButton1);
botonDonaciones.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/Donaciones.png"))); // NOI18N
botonDonaciones.setText("Donaciones");
botonDonaciones.setEnabled(false);
botonDonaciones.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonDonacionesActionPerformed(evt);
}
});
jMenuBotones.add(botonDonaciones);
botonEmpleo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/empleo.png"))); // NOI18N
botonEmpleo.setText("Empleo");
botonEmpleo.setEnabled(false);
botonEmpleo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonEmpleoActionPerformed(evt);
}
});
jMenuBotones.add(botonEmpleo);
getContentPane().add(jMenuBotones, java.awt.BorderLayout.NORTH);
jPrincipal.setLayout(new java.awt.CardLayout());
getContentPane().add(jPrincipal, java.awt.BorderLayout.CENTER);
getContentPane().add(jPrincipalScroll, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void botonBeneficiariosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonBeneficiariosActionPerformed
/*Modificamos zona principal*/
cl.show(jPrincipal, "Beneficiarios");
}//GEN-LAST:event_botonBeneficiariosActionPerformed
private void botonDiaketasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonDiaketasActionPerformed
/*Modificamos zona principal*/
cl.show(jPrincipal, "Diaketas");
}//GEN-LAST:event_botonDiaketasActionPerformed
private void botonDonacionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonDonacionesActionPerformed
/*Modificamos zona principal*/
cl.show(jPrincipal, "Donaciones");
}//GEN-LAST:event_botonDonacionesActionPerformed
private void botonEmpleoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonEmpleoActionPerformed
/*Modificamos zona principal*/
cl.show(jPrincipal, "Empleo");
}//GEN-LAST:event_botonEmpleoActionPerformed
private void botonDonantesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonDonantesActionPerformed
/*Modificamos zona principal*/
cl.show(jPrincipal, "Donantes");
}//GEN-LAST:event_botonDonantesActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
cl.show(jPrincipal, "HistorialyAcciones");
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
/* try{
UIManager.setLookAndFeel(new SyntheticaBlueMoonLookAndFeel());
} catch (Exception e) {
}
*
/*
* Create and display the form
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new UI().setVisible(true);
}
});
}*/
@Override
public Image getIconImage() {
Image retValue = Toolkit.getDefaultToolkit().
getImage(ClassLoader.getSystemResource("diaketas/Iconos/diaketas.png"));
return retValue;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton botonBeneficiarios;
private javax.swing.JButton botonDiaketas;
private javax.swing.JButton botonDonaciones;
private javax.swing.JButton botonDonantes;
private javax.swing.JButton botonEmpleo;
private javax.swing.JButton jButton1;
private javax.swing.JPanel jMenuBotones;
public static javax.swing.JPanel jPrincipal;
private javax.swing.JScrollPane jPrincipalScroll;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
jMenuBotones = new javax.swing.JPanel();
botonDiaketas = new javax.swing.JButton();
botonDonantes = new javax.swing.JButton();
botonBeneficiarios = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
botonDonaciones = new javax.swing.JButton();
botonEmpleo = new javax.swing.JButton();
jPrincipal = new javax.swing.JPanel();
jPrincipalScroll = new javax.swing.JScrollPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Diaketas");
setIconImage(getIconImage());
setMinimumSize(new java.awt.Dimension(1262, 628));
setName("Principal");
setPreferredSize(new java.awt.Dimension(1262, 109));
jMenuBotones.setLayout(new java.awt.GridLayout(1, 0));
botonDiaketas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/Home.png"))); // NOI18N
botonDiaketas.setText("Voluntarios");
botonDiaketas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonDiaketasActionPerformed(evt);
}
});
jMenuBotones.add(botonDiaketas);
botonDonantes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/Socios.gif"))); // NOI18N
botonDonantes.setText("Donantes");
botonDonantes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonDonantesActionPerformed(evt);
}
});
jMenuBotones.add(botonDonantes);
botonBeneficiarios.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/beneficiarios.png"))); // NOI18N
botonBeneficiarios.setText("Beneficiarios");
botonBeneficiarios.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonBeneficiariosActionPerformed(evt);
}
});
jMenuBotones.add(botonBeneficiarios);
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/historiales.png"))); // NOI18N
jButton1.setText("Historiales");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jMenuBotones.add(jButton1);
botonDonaciones.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/Donaciones.png"))); // NOI18N
botonDonaciones.setText("Donaciones");
botonDonaciones.setEnabled(false);
botonDonaciones.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonDonacionesActionPerformed(evt);
}
});
jMenuBotones.add(botonDonaciones);
botonEmpleo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/empleo.png"))); // NOI18N
botonEmpleo.setText("Empleo");
botonEmpleo.setEnabled(false);
botonEmpleo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonEmpleoActionPerformed(evt);
}
});
jMenuBotones.add(botonEmpleo);
getContentPane().add(jMenuBotones, java.awt.BorderLayout.NORTH);
jPrincipal.setLayout(new java.awt.CardLayout());
getContentPane().add(jPrincipal, java.awt.BorderLayout.CENTER);
getContentPane().add(jPrincipalScroll, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jMenuBotones = new javax.swing.JPanel();
botonDiaketas = new javax.swing.JButton();
botonDonantes = new javax.swing.JButton();
botonBeneficiarios = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
botonDonaciones = new javax.swing.JButton();
botonEmpleo = new javax.swing.JButton();
jPrincipal = new javax.swing.JPanel();
jPrincipalScroll = new javax.swing.JScrollPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Diaketas");
setIconImage(getIconImage());
setMinimumSize(new java.awt.Dimension(1262, 628));
setName("Principal");
setPreferredSize(new java.awt.Dimension(1262, 109));
jMenuBotones.setLayout(new java.awt.GridLayout(1, 0));
botonDiaketas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/Voluntario.png"))); // NOI18N
botonDiaketas.setText("Voluntarios");
botonDiaketas.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonDiaketasActionPerformed(evt);
}
});
jMenuBotones.add(botonDiaketas);
botonDonantes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/Socios.gif"))); // NOI18N
botonDonantes.setText("Donantes");
botonDonantes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonDonantesActionPerformed(evt);
}
});
jMenuBotones.add(botonDonantes);
botonBeneficiarios.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/beneficiarios.png"))); // NOI18N
botonBeneficiarios.setText("Beneficiarios");
botonBeneficiarios.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonBeneficiariosActionPerformed(evt);
}
});
jMenuBotones.add(botonBeneficiarios);
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/historiales.png"))); // NOI18N
jButton1.setText("Historiales");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jMenuBotones.add(jButton1);
botonDonaciones.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/Donaciones.png"))); // NOI18N
botonDonaciones.setText("Donaciones");
botonDonaciones.setEnabled(false);
botonDonaciones.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonDonacionesActionPerformed(evt);
}
});
jMenuBotones.add(botonDonaciones);
botonEmpleo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/diaketas/Iconos/empleo.png"))); // NOI18N
botonEmpleo.setText("Empleo");
botonEmpleo.setEnabled(false);
botonEmpleo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonEmpleoActionPerformed(evt);
}
});
jMenuBotones.add(botonEmpleo);
getContentPane().add(jMenuBotones, java.awt.BorderLayout.NORTH);
jPrincipal.setLayout(new java.awt.CardLayout());
getContentPane().add(jPrincipal, java.awt.BorderLayout.CENTER);
getContentPane().add(jPrincipalScroll, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/platform/com.subgraph.vega.http.proxy/src/com/subgraph/vega/internal/http/proxy/ProxyRequestHandler.java b/platform/com.subgraph.vega.http.proxy/src/com/subgraph/vega/internal/http/proxy/ProxyRequestHandler.java
index 1ea5c283..1b0e1bf3 100644
--- a/platform/com.subgraph.vega.http.proxy/src/com/subgraph/vega/internal/http/proxy/ProxyRequestHandler.java
+++ b/platform/com.subgraph.vega.http.proxy/src/com/subgraph/vega/internal/http/proxy/ProxyRequestHandler.java
@@ -1,165 +1,167 @@
package com.subgraph.vega.internal.http.proxy;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpMessage;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.ProtocolException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
import com.subgraph.vega.api.http.requests.IHttpRequestEngine;
import com.subgraph.vega.api.http.requests.IHttpResponse;
import com.subgraph.vega.http.requests.custom.HttpEntityEnclosingRawRequest;
import com.subgraph.vega.http.requests.custom.HttpRawRequest;
public class ProxyRequestHandler implements HttpRequestHandler {
/**
* Hop-by-hop headers to be removed by this proxy.
*/
private final static String[] HOP_BY_HOP_HEADERS = {
// Hop-by-hop headers specified in RFC2616 section 13.5.1.
HTTP.CONN_DIRECTIVE, // "Connection"
HTTP.CONN_KEEP_ALIVE, // "Keep-Alive"
"Proxy-Authenticate",
"Proxy-Authorization",
"TE",
"Trailers",
HTTP.TRANSFER_ENCODING, // "Transfer-Encoding"
"Upgrade",
// Not part of the RFC but should not be forwarded; see http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/web-proxy-connection-header.html
"Proxy-Connection",
};
private final HttpProxy httpProxy;
private final IHttpRequestEngine requestEngine;
ProxyRequestHandler(HttpProxy httpProxy, IHttpRequestEngine requestEngine) {
this.httpProxy = httpProxy;
this.requestEngine = requestEngine;
}
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
final ProxyTransaction transaction = new ProxyTransaction(requestEngine, context);
context.setAttribute(HttpProxy.PROXY_HTTP_TRANSACTION, transaction);
try {
if (handleRequest(transaction, request) == false) {
response.setStatusCode(503);
transaction.signalComplete(false);
return;
}
HttpUriRequest uriRequest = transaction.getRequest();
BasicHttpContext ctx = new BasicHttpContext();
transaction.signalForward();
IHttpResponse r = requestEngine.sendRequest(uriRequest, ctx);
if(r == null) {
response.setStatusCode(503);
transaction.signalComplete(false);
return;
}
if (handleResponse(transaction, r) == false) {
response.setStatusCode(503);
transaction.signalComplete(true);
return;
}
HttpResponse httpResponse = copyResponse(r.getRawResponse());
removeHeaders(httpResponse);
response.setStatusLine(httpResponse.getStatusLine());
response.setHeaders(httpResponse.getAllHeaders());
response.setEntity(httpResponse.getEntity());
transaction.signalForward();
} catch (InterruptedException e) {
response.setStatusCode(503);
+ } catch (IOException e) {
+ response.setStatusCode(502);
} catch (ProtocolException e) {
response.setStatusCode(400);
} finally {
transaction.signalComplete(false);
}
}
private HttpEntity copyEntity(HttpEntity entity) {
try {
if(entity == null) {
return null;
}
final ByteArrayEntity newEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity));
newEntity.setContentEncoding(entity.getContentEncoding());
newEntity.setContentType(entity.getContentType());
return newEntity;
} catch (IOException e) {
return null;
}
}
private HttpUriRequest copyToUriRequest(HttpRequest request) throws ProtocolException {
URI uri;
try {
uri = new URI(request.getRequestLine().getUri());
} catch (URISyntaxException e) {
throw new ProtocolException("Invalid URI: " + request.getRequestLine().getUri(), e);
}
// REVISIT: verify uri contains scheme, host part
final HttpUriRequest uriRequest;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRawRequest tmp = new HttpEntityEnclosingRawRequest(null, request.getRequestLine().getMethod(), uri);
tmp.setEntity(copyEntity(((HttpEntityEnclosingRequest) request).getEntity()));
uriRequest = tmp;
} else {
uriRequest = new HttpRawRequest(null, request.getRequestLine().getMethod(), uri);
}
uriRequest.setParams(request.getParams());
uriRequest.setHeaders(request.getAllHeaders());
return uriRequest;
}
private HttpResponse copyResponse(HttpResponse originalResponse) {
HttpResponse r = new BasicHttpResponse(originalResponse.getStatusLine());
r.setHeaders(originalResponse.getAllHeaders());
r.setEntity(originalResponse.getEntity());
return r;
}
private void removeHeaders(HttpMessage message) {
for(String hdr: HOP_BY_HOP_HEADERS) {
message.removeHeaders(hdr);
}
}
private boolean handleRequest(ProxyTransaction transaction, HttpRequest request) throws InterruptedException, ProtocolException {
removeHeaders(request);
transaction.setRequest(copyToUriRequest(request));
if (httpProxy.handleTransaction(transaction) == true) {
return transaction.getForward();
} else {
return true;
}
}
private boolean handleResponse(ProxyTransaction transaction, IHttpResponse response) throws InterruptedException {
transaction.setResponse(response);
if (httpProxy.handleTransaction(transaction) == true) {
return transaction.getForward();
} else {
return true;
}
}
}
| true | true | public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
final ProxyTransaction transaction = new ProxyTransaction(requestEngine, context);
context.setAttribute(HttpProxy.PROXY_HTTP_TRANSACTION, transaction);
try {
if (handleRequest(transaction, request) == false) {
response.setStatusCode(503);
transaction.signalComplete(false);
return;
}
HttpUriRequest uriRequest = transaction.getRequest();
BasicHttpContext ctx = new BasicHttpContext();
transaction.signalForward();
IHttpResponse r = requestEngine.sendRequest(uriRequest, ctx);
if(r == null) {
response.setStatusCode(503);
transaction.signalComplete(false);
return;
}
if (handleResponse(transaction, r) == false) {
response.setStatusCode(503);
transaction.signalComplete(true);
return;
}
HttpResponse httpResponse = copyResponse(r.getRawResponse());
removeHeaders(httpResponse);
response.setStatusLine(httpResponse.getStatusLine());
response.setHeaders(httpResponse.getAllHeaders());
response.setEntity(httpResponse.getEntity());
transaction.signalForward();
} catch (InterruptedException e) {
response.setStatusCode(503);
} catch (ProtocolException e) {
response.setStatusCode(400);
} finally {
transaction.signalComplete(false);
}
}
| public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
final ProxyTransaction transaction = new ProxyTransaction(requestEngine, context);
context.setAttribute(HttpProxy.PROXY_HTTP_TRANSACTION, transaction);
try {
if (handleRequest(transaction, request) == false) {
response.setStatusCode(503);
transaction.signalComplete(false);
return;
}
HttpUriRequest uriRequest = transaction.getRequest();
BasicHttpContext ctx = new BasicHttpContext();
transaction.signalForward();
IHttpResponse r = requestEngine.sendRequest(uriRequest, ctx);
if(r == null) {
response.setStatusCode(503);
transaction.signalComplete(false);
return;
}
if (handleResponse(transaction, r) == false) {
response.setStatusCode(503);
transaction.signalComplete(true);
return;
}
HttpResponse httpResponse = copyResponse(r.getRawResponse());
removeHeaders(httpResponse);
response.setStatusLine(httpResponse.getStatusLine());
response.setHeaders(httpResponse.getAllHeaders());
response.setEntity(httpResponse.getEntity());
transaction.signalForward();
} catch (InterruptedException e) {
response.setStatusCode(503);
} catch (IOException e) {
response.setStatusCode(502);
} catch (ProtocolException e) {
response.setStatusCode(400);
} finally {
transaction.signalComplete(false);
}
}
|
diff --git a/src/com/cafeform/esxi/esximonitor/OperationButtonPanel.java b/src/com/cafeform/esxi/esximonitor/OperationButtonPanel.java
index a84eeb8..fa6e317 100644
--- a/src/com/cafeform/esxi/esximonitor/OperationButtonPanel.java
+++ b/src/com/cafeform/esxi/esximonitor/OperationButtonPanel.java
@@ -1,208 +1,209 @@
package com.cafeform.esxi.esximonitor;
import com.cafeform.esxi.ESXiConnection;
import com.cafeform.esxi.VM;
import com.cafeform.esxi.Vmsvc;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.Task;
import com.vmware.vim25.mo.VirtualMachine;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
/**
* Panel for buttons for virtial macnine operations
*
*/
public class OperationButtonPanel extends JPanel implements ActionListener {
public static final Logger logger = Logger.getLogger(OperationButtonPanel.class.getName());
private Main esximon;
private OperationButtonPanel() {
}
private VirtualMachine vm;
static Icon control_stop_blue = null;
static Icon control_play_blue = null;
static Icon control_pause_blue = null;
static Icon exclamation = null;
private Server server;
/* Load Icons */
static {
try {
control_stop_blue = Main.getScaledImageIcon("com/cafeform/esxi/esximonitor/control_stop_blue.png");
control_play_blue = Main.getScaledImageIcon("com/cafeform/esxi/esximonitor/control_play_blue.png");
control_pause_blue = Main.getScaledImageIcon("com/cafeform/esxi/esximonitor/control_pause_blue.png");
exclamation = Main.getScaledImageIcon("com/cafeform/esxi/esximonitor/exclamation.png");
} catch (IOException ex) {
logger.severe("Cannot load icon image");
}
}
public OperationButtonPanel(Main esximon, VirtualMachine vm, Server server) {
this.vm = vm;
this.esximon = esximon;
boolean poweredOn = vm.getSummary().getRuntime().getPowerState().equals(VirtualMachinePowerState.poweredOn);
this.setLayout(new GridLayout(1, 4));
this.setBackground(Color.white);
/* Power off */
JButton powerOffButton = new JButton(control_stop_blue);
powerOffButton.setBackground(Color.white);
powerOffButton.setToolTipText("Power OFF");
powerOffButton.setActionCommand("poweroff");
powerOffButton.addActionListener(this);
powerOffButton.setPreferredSize(new Dimension(Main.iconSize, Main.iconSize));
powerOffButton.setMaximumSize(new Dimension(Main.iconSize, Main.iconSize));
if (poweredOn == false) {
powerOffButton.setEnabled(false);
}
/* Power On */
JButton powerOnButton = new JButton(control_play_blue);
powerOnButton.setBackground(Color.white);
powerOnButton.setToolTipText("Power ON");
powerOnButton.setActionCommand("poweron");
powerOnButton.addActionListener(this);
powerOnButton.setPreferredSize(new Dimension(Main.iconSize, Main.iconSize));
if (poweredOn) {
powerOnButton.setEnabled(false);
}
/* Power reset */
JButton resetButton = new JButton(control_pause_blue);
resetButton.setBackground(Color.white);
resetButton.setToolTipText("Reset");
resetButton.setActionCommand("reset");
resetButton.addActionListener(this);
resetButton.setPreferredSize(new Dimension(Main.iconSize, Main.iconSize));
if (poweredOn == false) {
resetButton.setEnabled(false);
}
/* Shutdown Guest OS */
JButton shutdownButton = new JButton(exclamation);
shutdownButton.setBackground(Color.white);
shutdownButton.setToolTipText("Shutdown Guest OS");
shutdownButton.setActionCommand("shutdown");
shutdownButton.addActionListener(this);
shutdownButton.setPreferredSize(new Dimension(Main.iconSize, Main.iconSize));
if (poweredOn == false) {
shutdownButton.setEnabled(false);
}
this.add(powerOnButton);
this.add(powerOffButton);
this.add(resetButton);
this.add(shutdownButton);
setMaximumSize(getSize());
}
@Override
public void actionPerformed(ActionEvent ae) {
final String actionCommand = ae.getActionCommand();
logger.finer(ae.getActionCommand() + " event for " + vm.getName() + " recieved.");
ExecutorService executor = Executors.newSingleThreadScheduledExecutor();
/* try to execute command in backgroup */
executor.submit(new Runnable() {
@Override
public void run() {
doCommand(actionCommand);
}
});
}
private void doCommand(String command) throws HeadlessException {
esximon.getProgressBar().setIndeterminate(true);
esximon.getStatusLabel().setText("Running " + command + " on " + vm.getName());
try {
Task task = null;
if ("poweroff".equals(command)) {
int response = JOptionPane.showConfirmDialog(esximon,
"Are you sure want to power down \"" + vm.getName() + "\" ?",
"Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
return;
} else {
task = vm.powerOffVM_Task();
}
} else if ("poweron".equals(command)) {
task = vm.powerOnVM_Task(null);
} else if ("reset".equals(command)) {
int response = JOptionPane.showConfirmDialog(esximon,
"Are you sure want to reset \"" + vm.getName() + "\" ?",
"Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
return;
} else {
task = vm.resetVM_Task();
}
} else if ("shutdown".equals(command)) {
int response = JOptionPane.showConfirmDialog(esximon,
"Are you sure want to shutdown \"" + vm.getName() + "\" ?",
"Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
return;
} else {
vm.shutdownGuest();
}
}
if (task != null) {
task.waitForTask();
}
} catch (InterruptedException ex) {
// interrupted
} catch (InvalidState ex) {
JOptionPane.showMessageDialog(esximon, "Invalid State\n", "Error", JOptionPane.WARNING_MESSAGE);
} catch (TaskInProgress ex) {
JOptionPane.showMessageDialog(esximon, "Task Inprogress\n"
+ ex.getMessage() + "\n" + ex.getTask().getVal()
+ "\n" + ex.getTask().getType(), "Error", JOptionPane.WARNING_MESSAGE);
} catch (ToolsUnavailable ex) {
JOptionPane.showMessageDialog(esximon, "Cannot complete operation "
+ "because VMware\n Tools is not running in this virtual machine.", "Error", JOptionPane.WARNING_MESSAGE);
} catch (RestrictedVersion ex) {
try {
/* Seems remote ESXi server doesn't accept command via VI API
* try to run command via SSH
*/
+ logger.finer("Get RestrictedVersion from ESXi. Try command via SSH.");
server.runCommandViaSsh(command, vm);
} catch (Exception ex2) {
/* Fummm, command faild via SSH too... Report the result to user. */
- logger.severe("runCommandViaSSH recieved IOException");
- ex.printStackTrace();
- JOptionPane.showMessageDialog(esximon, "RestrictedVersion\n", "Error", JOptionPane.WARNING_MESSAGE);
+ logger.severe("runCommandViaSSH recieved " + ex2.toString());
+ ex2.printStackTrace();
+ JOptionPane.showMessageDialog(esximon, ex2.toString(), "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (RuntimeFault ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(esximon, "RuntimeFault\n", "Error", JOptionPane.WARNING_MESSAGE);
} catch (RemoteException ex) {
JOptionPane.showMessageDialog(esximon, "RemoteFault\n", "Error", JOptionPane.WARNING_MESSAGE);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
esximon.getProgressBar().setIndeterminate(false);
}
esximon.updateVMLIstPanel();
logger.finer("panel update request posted");
}
}
| false | true | private void doCommand(String command) throws HeadlessException {
esximon.getProgressBar().setIndeterminate(true);
esximon.getStatusLabel().setText("Running " + command + " on " + vm.getName());
try {
Task task = null;
if ("poweroff".equals(command)) {
int response = JOptionPane.showConfirmDialog(esximon,
"Are you sure want to power down \"" + vm.getName() + "\" ?",
"Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
return;
} else {
task = vm.powerOffVM_Task();
}
} else if ("poweron".equals(command)) {
task = vm.powerOnVM_Task(null);
} else if ("reset".equals(command)) {
int response = JOptionPane.showConfirmDialog(esximon,
"Are you sure want to reset \"" + vm.getName() + "\" ?",
"Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
return;
} else {
task = vm.resetVM_Task();
}
} else if ("shutdown".equals(command)) {
int response = JOptionPane.showConfirmDialog(esximon,
"Are you sure want to shutdown \"" + vm.getName() + "\" ?",
"Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
return;
} else {
vm.shutdownGuest();
}
}
if (task != null) {
task.waitForTask();
}
} catch (InterruptedException ex) {
// interrupted
} catch (InvalidState ex) {
JOptionPane.showMessageDialog(esximon, "Invalid State\n", "Error", JOptionPane.WARNING_MESSAGE);
} catch (TaskInProgress ex) {
JOptionPane.showMessageDialog(esximon, "Task Inprogress\n"
+ ex.getMessage() + "\n" + ex.getTask().getVal()
+ "\n" + ex.getTask().getType(), "Error", JOptionPane.WARNING_MESSAGE);
} catch (ToolsUnavailable ex) {
JOptionPane.showMessageDialog(esximon, "Cannot complete operation "
+ "because VMware\n Tools is not running in this virtual machine.", "Error", JOptionPane.WARNING_MESSAGE);
} catch (RestrictedVersion ex) {
try {
/* Seems remote ESXi server doesn't accept command via VI API
* try to run command via SSH
*/
server.runCommandViaSsh(command, vm);
} catch (Exception ex2) {
/* Fummm, command faild via SSH too... Report the result to user. */
logger.severe("runCommandViaSSH recieved IOException");
ex.printStackTrace();
JOptionPane.showMessageDialog(esximon, "RestrictedVersion\n", "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (RuntimeFault ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(esximon, "RuntimeFault\n", "Error", JOptionPane.WARNING_MESSAGE);
} catch (RemoteException ex) {
JOptionPane.showMessageDialog(esximon, "RemoteFault\n", "Error", JOptionPane.WARNING_MESSAGE);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
esximon.getProgressBar().setIndeterminate(false);
}
esximon.updateVMLIstPanel();
logger.finer("panel update request posted");
}
| private void doCommand(String command) throws HeadlessException {
esximon.getProgressBar().setIndeterminate(true);
esximon.getStatusLabel().setText("Running " + command + " on " + vm.getName());
try {
Task task = null;
if ("poweroff".equals(command)) {
int response = JOptionPane.showConfirmDialog(esximon,
"Are you sure want to power down \"" + vm.getName() + "\" ?",
"Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
return;
} else {
task = vm.powerOffVM_Task();
}
} else if ("poweron".equals(command)) {
task = vm.powerOnVM_Task(null);
} else if ("reset".equals(command)) {
int response = JOptionPane.showConfirmDialog(esximon,
"Are you sure want to reset \"" + vm.getName() + "\" ?",
"Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
return;
} else {
task = vm.resetVM_Task();
}
} else if ("shutdown".equals(command)) {
int response = JOptionPane.showConfirmDialog(esximon,
"Are you sure want to shutdown \"" + vm.getName() + "\" ?",
"Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
return;
} else {
vm.shutdownGuest();
}
}
if (task != null) {
task.waitForTask();
}
} catch (InterruptedException ex) {
// interrupted
} catch (InvalidState ex) {
JOptionPane.showMessageDialog(esximon, "Invalid State\n", "Error", JOptionPane.WARNING_MESSAGE);
} catch (TaskInProgress ex) {
JOptionPane.showMessageDialog(esximon, "Task Inprogress\n"
+ ex.getMessage() + "\n" + ex.getTask().getVal()
+ "\n" + ex.getTask().getType(), "Error", JOptionPane.WARNING_MESSAGE);
} catch (ToolsUnavailable ex) {
JOptionPane.showMessageDialog(esximon, "Cannot complete operation "
+ "because VMware\n Tools is not running in this virtual machine.", "Error", JOptionPane.WARNING_MESSAGE);
} catch (RestrictedVersion ex) {
try {
/* Seems remote ESXi server doesn't accept command via VI API
* try to run command via SSH
*/
logger.finer("Get RestrictedVersion from ESXi. Try command via SSH.");
server.runCommandViaSsh(command, vm);
} catch (Exception ex2) {
/* Fummm, command faild via SSH too... Report the result to user. */
logger.severe("runCommandViaSSH recieved " + ex2.toString());
ex2.printStackTrace();
JOptionPane.showMessageDialog(esximon, ex2.toString(), "Error", JOptionPane.WARNING_MESSAGE);
}
} catch (RuntimeFault ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(esximon, "RuntimeFault\n", "Error", JOptionPane.WARNING_MESSAGE);
} catch (RemoteException ex) {
JOptionPane.showMessageDialog(esximon, "RemoteFault\n", "Error", JOptionPane.WARNING_MESSAGE);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
esximon.getProgressBar().setIndeterminate(false);
}
esximon.updateVMLIstPanel();
logger.finer("panel update request posted");
}
|
diff --git a/CodenameG/src/edu/chl/codenameg/model/entity/MovingBlock.java b/CodenameG/src/edu/chl/codenameg/model/entity/MovingBlock.java
index 4e8788e..7356114 100644
--- a/CodenameG/src/edu/chl/codenameg/model/entity/MovingBlock.java
+++ b/CodenameG/src/edu/chl/codenameg/model/entity/MovingBlock.java
@@ -1,48 +1,50 @@
package edu.chl.codenameg.model.entity;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenManager;
import edu.chl.codenameg.model.EntityTweenAccessor;
import edu.chl.codenameg.model.Entity;
import edu.chl.codenameg.model.Hitbox;
import edu.chl.codenameg.model.Position;
public class MovingBlock extends Block {
boolean moving = false;
private int travelTime;
private Position endPos;
private Position startPos;
private TweenManager manager = new TweenManager();
@Override
public void collide(Entity e) {
super.collide(e);
if (e instanceof PlayerCharacter) {
PlayerCharacter landedPlayer = (PlayerCharacter) e;
landedPlayer.getVector2D().add(this.getVector2D());
}
}
public MovingBlock(Hitbox hb, Position ps, Position endPos, int travelTime) {
super(hb, ps);
this.startPos=ps;
this.endPos = endPos;
this.travelTime = travelTime;
Tween.registerAccessor(MovingBlock.class, new EntityTweenAccessor());
Tween.to(this, EntityTweenAccessor.POSITION_XY, this.travelTime)
- .target(endPos.getX(), endPos.getY()).start(manager).repeatYoyo(2, 500);
+ .target(endPos.getX(), endPos.getY()).repeat(-1, this.travelTime).start(manager);
+ Tween.to(this, EntityTweenAccessor.POSITION_XY, this.travelTime)
+ .target(ps.getX(), ps.getY()).repeat(-1, this.travelTime).delay(this.travelTime).start(manager);
}
public MovingBlock() {
this(new Hitbox(20, 10), new Position(2.5f, 2.5f), new Position(7.5f,
7.5f), 100);
}
public void update(int elapsedTime) {
manager.update(elapsedTime);
}
// We can now create as many interpolations as we need !
}
| true | true | public MovingBlock(Hitbox hb, Position ps, Position endPos, int travelTime) {
super(hb, ps);
this.startPos=ps;
this.endPos = endPos;
this.travelTime = travelTime;
Tween.registerAccessor(MovingBlock.class, new EntityTweenAccessor());
Tween.to(this, EntityTweenAccessor.POSITION_XY, this.travelTime)
.target(endPos.getX(), endPos.getY()).start(manager).repeatYoyo(2, 500);
}
| public MovingBlock(Hitbox hb, Position ps, Position endPos, int travelTime) {
super(hb, ps);
this.startPos=ps;
this.endPos = endPos;
this.travelTime = travelTime;
Tween.registerAccessor(MovingBlock.class, new EntityTweenAccessor());
Tween.to(this, EntityTweenAccessor.POSITION_XY, this.travelTime)
.target(endPos.getX(), endPos.getY()).repeat(-1, this.travelTime).start(manager);
Tween.to(this, EntityTweenAccessor.POSITION_XY, this.travelTime)
.target(ps.getX(), ps.getY()).repeat(-1, this.travelTime).delay(this.travelTime).start(manager);
}
|
diff --git a/src/graph/Graph.java b/src/graph/Graph.java
index 6fc3363..9762e8c 100644
--- a/src/graph/Graph.java
+++ b/src/graph/Graph.java
@@ -1,128 +1,130 @@
package graph;
import java.util.Iterator;
import controller.Controller;
import dataStructure.Connection;
import dataStructure.DynArray;
import dataStructure.Point;
/**Graph handler class for points.
* This works on a graph.
* This is used for finding shortest path between points in map.
*
* @author Claus L. Henriksen - [email protected]
* @see EdgeWeightedDigraph
* @see DirectedEdge
*/
public class Graph {
private EdgeWeightedDigraph g;
private Connection[] connections;
private double xMin = 70000, xMax = 0, yMin = 70000, yMax = 0;
public Graph(){
//Get points
Point[] points = Controller.getInstance().getPoints();
//Get roads
connections = Controller.getInstance().getConnections();
//Create graph
g = new EdgeWeightedDigraph(points.length+1); //vertices
//add edges
for(Connection c : connections){
if(c != null){
//from, to, connection ID, weight
g.addEdge(new DirectedEdge(c.getLeft().getID(), c.getRight().getID(), c.getID(), c.getWeight()));
g.addEdge(new DirectedEdge(c.getRight().getID(), c.getLeft().getID(), c.getID(), c.getWeight()));
}
}
}
/**
* Find shortest path between two points.
* @param from
* @param to
* @return Path as array of connections
* @throws RuntimeException if there is no path between points
* @see Connection
* @see DijkstraSP
*/
public Connection[] shortestPath(Point from, Point to) throws RuntimeException{
+ //Reset values
+ xMin = 70000; xMax = 0; yMin = 70000; yMax = 0;
//Create Dijkstra
DijkstraSP dijk = new DijkstraSP(g, from.getID());
//If there is no path between points
if(!dijk.hasPathTo(to.getID())) throw new RuntimeException("No path");
//Iterate points on path and get Connection IDs
DynArray<Integer> cs = new DynArray<Integer>(Integer[].class);
Iterator<DirectedEdge> it = dijk.pathTo(to.getID()).iterator();
while(it.hasNext()){
DirectedEdge edge = it.next();
cs.add(edge.id());
}
//Convert IDs to actual connections and return them
Connection[] path = new Connection[cs.size()];
int index = 0;
for(Integer i : cs){
Connection con = connections[i];
path[index++] = con;
//Set xMin, xMax, yMin, yMax. These are used for zooming in on route
double xLow = con.getLeft().getX();
double xHigh = con.getRight().getX();
double yLow, yHigh;
if(con.getY1() < con.getY2()){
yLow = con.getY1();
yHigh = con.getY2();
}else{
yLow = con.getY2();
yHigh = con.getY1();
}
if(xLow < xMin) xMin = xLow;
if(yLow < yMin) yMin = yLow;
if(xHigh > xMax) xMax = xHigh;
if(yHigh > yMax) yMax = yHigh;
}
return path;
}
/**
* Getter for path boundary limit value.
* Used by MapComponent to zoom in on route.
* @return Smallest x-value on route
*/
public double getXmin(){
return xMin;
}
/**
* Getter for path boundary limit value.
* Used by MapComponent to zoom in on route.
* @return Biggest x-value on route
*/
public double getXmax(){
return xMax;
}
/**
* Getter for path boundary limit value.
* Used by MapComponent to zoom in on route.
* @return Smallest y-value on route
*/
public double getYmin(){
return yMin;
}
/**
* Getter for path boundary limit value.
* Used by MapComponent to zoom in on route.
* @return Biggest y-value on route
*/
public double getYmax(){
return yMax;
}
}
| true | true | public Connection[] shortestPath(Point from, Point to) throws RuntimeException{
//Create Dijkstra
DijkstraSP dijk = new DijkstraSP(g, from.getID());
//If there is no path between points
if(!dijk.hasPathTo(to.getID())) throw new RuntimeException("No path");
//Iterate points on path and get Connection IDs
DynArray<Integer> cs = new DynArray<Integer>(Integer[].class);
Iterator<DirectedEdge> it = dijk.pathTo(to.getID()).iterator();
while(it.hasNext()){
DirectedEdge edge = it.next();
cs.add(edge.id());
}
//Convert IDs to actual connections and return them
Connection[] path = new Connection[cs.size()];
int index = 0;
for(Integer i : cs){
Connection con = connections[i];
path[index++] = con;
//Set xMin, xMax, yMin, yMax. These are used for zooming in on route
double xLow = con.getLeft().getX();
double xHigh = con.getRight().getX();
double yLow, yHigh;
if(con.getY1() < con.getY2()){
yLow = con.getY1();
yHigh = con.getY2();
}else{
yLow = con.getY2();
yHigh = con.getY1();
}
if(xLow < xMin) xMin = xLow;
if(yLow < yMin) yMin = yLow;
if(xHigh > xMax) xMax = xHigh;
if(yHigh > yMax) yMax = yHigh;
}
return path;
}
| public Connection[] shortestPath(Point from, Point to) throws RuntimeException{
//Reset values
xMin = 70000; xMax = 0; yMin = 70000; yMax = 0;
//Create Dijkstra
DijkstraSP dijk = new DijkstraSP(g, from.getID());
//If there is no path between points
if(!dijk.hasPathTo(to.getID())) throw new RuntimeException("No path");
//Iterate points on path and get Connection IDs
DynArray<Integer> cs = new DynArray<Integer>(Integer[].class);
Iterator<DirectedEdge> it = dijk.pathTo(to.getID()).iterator();
while(it.hasNext()){
DirectedEdge edge = it.next();
cs.add(edge.id());
}
//Convert IDs to actual connections and return them
Connection[] path = new Connection[cs.size()];
int index = 0;
for(Integer i : cs){
Connection con = connections[i];
path[index++] = con;
//Set xMin, xMax, yMin, yMax. These are used for zooming in on route
double xLow = con.getLeft().getX();
double xHigh = con.getRight().getX();
double yLow, yHigh;
if(con.getY1() < con.getY2()){
yLow = con.getY1();
yHigh = con.getY2();
}else{
yLow = con.getY2();
yHigh = con.getY1();
}
if(xLow < xMin) xMin = xLow;
if(yLow < yMin) yMin = yLow;
if(xHigh > xMax) xMax = xHigh;
if(yHigh > yMax) yMax = yHigh;
}
return path;
}
|
diff --git a/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/Battleship.java b/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/Battleship.java
index aef2ead..fb25b7a 100644
--- a/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/Battleship.java
+++ b/Battleship/src/main/java/ch/bfh/bti7301/w2013/battleship/Battleship.java
@@ -1,255 +1,254 @@
/**
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or distribute
* this software, either in source code form or as a compiled binary, for any
* purpose, commercial or non-commercial, and by any means.
*
* In jurisdictions that recognize copyright laws, the author or authors of this
* software dedicate any and all copyright interest in the software to the
* public domain. We make this dedication for the benefit of the public at large
* and to the detriment of our heirs and successors. We intend this dedication
* to be an overt act of relinquishment in perpetuity of all present and future
* rights to this software under copyright law.
*
* 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 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.
*
* For more information, please refer to [http://unlicense.org]
*/
package ch.bfh.bti7301.w2013.battleship;
import static ch.bfh.bti7301.w2013.battleship.gui.BoardView.SIZE;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import javafx.animation.ParallelTransitionBuilder;
import javafx.animation.ScaleTransitionBuilder;
import javafx.animation.TranslateTransitionBuilder;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Point2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
import javafx.util.Duration;
import ch.bfh.bti7301.w2013.battleship.game.Board;
import ch.bfh.bti7301.w2013.battleship.game.Board.Coordinates;
import ch.bfh.bti7301.w2013.battleship.game.Board.Direction;
import ch.bfh.bti7301.w2013.battleship.game.Game;
import ch.bfh.bti7301.w2013.battleship.game.GameRule;
import ch.bfh.bti7301.w2013.battleship.game.Missile;
import ch.bfh.bti7301.w2013.battleship.game.Ship;
import ch.bfh.bti7301.w2013.battleship.gui.BoardView;
import ch.bfh.bti7301.w2013.battleship.gui.ShipView;
import ch.bfh.bti7301.w2013.battleship.network.ConnectionState;
import ch.bfh.bti7301.w2013.battleship.network.ConnectionStateListener;
import ch.bfh.bti7301.w2013.battleship.network.NetworkInformation;
/**
* @author Christian Meyer <[email protected]>
*
*/
public class Battleship extends Application {
private ResourceBundle labels;
private Game game;
private GameRule rule;
public Battleship() {
labels = ResourceBundle.getBundle("translations");
game = Game.getInstance();
rule = new GameRule();
game.getOpponent().getBoard()
.placeMissile(new Missile(new Coordinates(1, 1)));
game.getOpponent().getBoard()
.placeMissile(new Missile(new Coordinates(3, 4)));
}
/**
* @param args
*/
public static void main(String[] args) {
// Output this for debugging and testing
System.out.println(NetworkInformation.getIntAddresses());
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle(labels.getString("title"));
final Group root = new Group();
final Scene scene = new Scene(root, 800, 600, Color.WHITE);
primaryStage.setScene(scene);
final Board playerBoard = game.getLocalPlayer().getBoard();
final BoardView pbv = new BoardView(playerBoard);
pbv.relocate(10, 10);
root.getChildren().add(pbv);
Board opponentBoard = game.getOpponent().getBoard();
final BoardView obv = new BoardView(opponentBoard);
obv.getTransforms().add(new Scale(0.5, 0.5, 0, 0));
obv.relocate(pbv.getBoundsInParent().getMaxX() + 20, 10);
root.getChildren().add(obv);
final HBox shipStack = new HBox(-16);
// FIXME: this is just for layout debugging
shipStack.setStyle("-fx-background-color: #ffc;");
shipStack.setMaxHeight(SIZE);
for (Ship s : getAvailableShips()) {
final ShipView sv = new ShipView(s);
shipStack.getChildren().add(sv);
sv.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
initX = sv.getTranslateX();
initY = sv.getTranslateY();
dragAnchor = new Point2D(me.getSceneX(), me.getSceneY());
}
});
sv.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double dragX = me.getSceneX() - dragAnchor.getX();
double dragY = me.getSceneY() - dragAnchor.getY();
// calculate new position of the circle
double newXPosition = initX + dragX;
double newYPosition = initY + dragY;
sv.setTranslateX(newXPosition);
sv.setTranslateY(newYPosition);
}
});
sv.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double shipStartX = me.getSceneX() - me.getX()
- pbv.getLayoutX();
double shipStartY = me.getSceneY() - me.getY()
- pbv.getLayoutY();
if (pbv.contains(shipStartX, shipStartY)) {
// if on board, snap & add to it
Coordinates c = pbv.getCoordinates(shipStartX,
shipStartY);
Ship ship = buildShip(sv.getShipType(), c,
Direction.SOUTH);
playerBoard.placeShip(ship);
// TODO: handle illegal ship placement
shipStack.getChildren().remove(sv);
pbv.addShip(ship);
} else {
// snap back
sv.setTranslateX(initX);
sv.setTranslateY(initY);
}
}
});
}
shipStack.relocate(obv.getBoundsInParent().getMinX(), obv
.getBoundsInParent().getMaxY() + 8);
root.getChildren().add(shipStack);
// Temporary input field to enter the opponent's
final HBox ipBox = new HBox();
final TextField ipAddress = new TextField();
ipBox.getChildren().add(ipAddress);
final Button connect = new Button("Connect");
// TODO: add listener to Connection
new ConnectionStateListener() {
@Override
public void stateChanged(ConnectionState newState) {
switch (newState) {
case CLOSED:
case LISTENING:
ipBox.setVisible(true);
break;
case CONNECTED:
- case CONNECTING:
ipBox.setVisible(false);
break;
}
}
};
connect.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
ParallelTransitionBuilder
.create()
.children(
ScaleTransitionBuilder.create().node(pbv)
.duration(Duration.seconds(1)).toX(0.5)
.toY(0.5).build(),
TranslateTransitionBuilder.create().node(pbv)
.duration(Duration.seconds(1))
.toX(-100).toY(-100).build(),
ScaleTransitionBuilder.create().node(obv)
.duration(Duration.seconds(1)).toX(2)
.toY(2).build(),
TranslateTransitionBuilder.create().node(obv)
.duration(Duration.seconds(1)).toY(200)
.build()//
).build().play();
// TODO
// Connection.getInstance().connectOpponent()
System.out.println(ipAddress.getText());
}
});
ipBox.getChildren().add(connect);
ipBox.relocate(pbv.getBoundsInParent().getMinX(), pbv
.getBoundsInParent().getMaxY() + 20);
ipBox.getChildren().add(
new Label(NetworkInformation.getIntAddresses().toString()));
root.getChildren().add(ipBox);
primaryStage.show();
}
private List<Ship> getAvailableShips() {
List<Ship> availableShips = new LinkedList<>();
Coordinates dc = new Coordinates(0, 0);
Direction dd = Direction.SOUTH;
for (Entry<Class<? extends Ship>, Integer> e : rule.getShipList()
.entrySet()) {
Ship ship = buildShip(e.getKey(), dc, dd);
for (int i = 0; i < e.getValue(); i++)
availableShips.add(ship);
}
return availableShips;
}
private Ship buildShip(Class<? extends Ship> type, Coordinates c,
Direction d) {
try {
return type.getConstructor(Coordinates.class, Direction.class)
.newInstance(c, d);
} catch (Exception e) {
throw new RuntimeException(
"Error while creating ships through reflection", e);
}
}
private double initX;
private double initY;
private Point2D dragAnchor;
}
| true | true | public void start(Stage primaryStage) {
primaryStage.setTitle(labels.getString("title"));
final Group root = new Group();
final Scene scene = new Scene(root, 800, 600, Color.WHITE);
primaryStage.setScene(scene);
final Board playerBoard = game.getLocalPlayer().getBoard();
final BoardView pbv = new BoardView(playerBoard);
pbv.relocate(10, 10);
root.getChildren().add(pbv);
Board opponentBoard = game.getOpponent().getBoard();
final BoardView obv = new BoardView(opponentBoard);
obv.getTransforms().add(new Scale(0.5, 0.5, 0, 0));
obv.relocate(pbv.getBoundsInParent().getMaxX() + 20, 10);
root.getChildren().add(obv);
final HBox shipStack = new HBox(-16);
// FIXME: this is just for layout debugging
shipStack.setStyle("-fx-background-color: #ffc;");
shipStack.setMaxHeight(SIZE);
for (Ship s : getAvailableShips()) {
final ShipView sv = new ShipView(s);
shipStack.getChildren().add(sv);
sv.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
initX = sv.getTranslateX();
initY = sv.getTranslateY();
dragAnchor = new Point2D(me.getSceneX(), me.getSceneY());
}
});
sv.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double dragX = me.getSceneX() - dragAnchor.getX();
double dragY = me.getSceneY() - dragAnchor.getY();
// calculate new position of the circle
double newXPosition = initX + dragX;
double newYPosition = initY + dragY;
sv.setTranslateX(newXPosition);
sv.setTranslateY(newYPosition);
}
});
sv.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double shipStartX = me.getSceneX() - me.getX()
- pbv.getLayoutX();
double shipStartY = me.getSceneY() - me.getY()
- pbv.getLayoutY();
if (pbv.contains(shipStartX, shipStartY)) {
// if on board, snap & add to it
Coordinates c = pbv.getCoordinates(shipStartX,
shipStartY);
Ship ship = buildShip(sv.getShipType(), c,
Direction.SOUTH);
playerBoard.placeShip(ship);
// TODO: handle illegal ship placement
shipStack.getChildren().remove(sv);
pbv.addShip(ship);
} else {
// snap back
sv.setTranslateX(initX);
sv.setTranslateY(initY);
}
}
});
}
shipStack.relocate(obv.getBoundsInParent().getMinX(), obv
.getBoundsInParent().getMaxY() + 8);
root.getChildren().add(shipStack);
// Temporary input field to enter the opponent's
final HBox ipBox = new HBox();
final TextField ipAddress = new TextField();
ipBox.getChildren().add(ipAddress);
final Button connect = new Button("Connect");
// TODO: add listener to Connection
new ConnectionStateListener() {
@Override
public void stateChanged(ConnectionState newState) {
switch (newState) {
case CLOSED:
case LISTENING:
ipBox.setVisible(true);
break;
case CONNECTED:
case CONNECTING:
ipBox.setVisible(false);
break;
}
}
};
connect.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
ParallelTransitionBuilder
.create()
.children(
ScaleTransitionBuilder.create().node(pbv)
.duration(Duration.seconds(1)).toX(0.5)
.toY(0.5).build(),
TranslateTransitionBuilder.create().node(pbv)
.duration(Duration.seconds(1))
.toX(-100).toY(-100).build(),
ScaleTransitionBuilder.create().node(obv)
.duration(Duration.seconds(1)).toX(2)
.toY(2).build(),
TranslateTransitionBuilder.create().node(obv)
.duration(Duration.seconds(1)).toY(200)
.build()//
).build().play();
// TODO
// Connection.getInstance().connectOpponent()
System.out.println(ipAddress.getText());
}
});
ipBox.getChildren().add(connect);
ipBox.relocate(pbv.getBoundsInParent().getMinX(), pbv
.getBoundsInParent().getMaxY() + 20);
ipBox.getChildren().add(
new Label(NetworkInformation.getIntAddresses().toString()));
root.getChildren().add(ipBox);
primaryStage.show();
}
| public void start(Stage primaryStage) {
primaryStage.setTitle(labels.getString("title"));
final Group root = new Group();
final Scene scene = new Scene(root, 800, 600, Color.WHITE);
primaryStage.setScene(scene);
final Board playerBoard = game.getLocalPlayer().getBoard();
final BoardView pbv = new BoardView(playerBoard);
pbv.relocate(10, 10);
root.getChildren().add(pbv);
Board opponentBoard = game.getOpponent().getBoard();
final BoardView obv = new BoardView(opponentBoard);
obv.getTransforms().add(new Scale(0.5, 0.5, 0, 0));
obv.relocate(pbv.getBoundsInParent().getMaxX() + 20, 10);
root.getChildren().add(obv);
final HBox shipStack = new HBox(-16);
// FIXME: this is just for layout debugging
shipStack.setStyle("-fx-background-color: #ffc;");
shipStack.setMaxHeight(SIZE);
for (Ship s : getAvailableShips()) {
final ShipView sv = new ShipView(s);
shipStack.getChildren().add(sv);
sv.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
initX = sv.getTranslateX();
initY = sv.getTranslateY();
dragAnchor = new Point2D(me.getSceneX(), me.getSceneY());
}
});
sv.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double dragX = me.getSceneX() - dragAnchor.getX();
double dragY = me.getSceneY() - dragAnchor.getY();
// calculate new position of the circle
double newXPosition = initX + dragX;
double newYPosition = initY + dragY;
sv.setTranslateX(newXPosition);
sv.setTranslateY(newYPosition);
}
});
sv.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent me) {
double shipStartX = me.getSceneX() - me.getX()
- pbv.getLayoutX();
double shipStartY = me.getSceneY() - me.getY()
- pbv.getLayoutY();
if (pbv.contains(shipStartX, shipStartY)) {
// if on board, snap & add to it
Coordinates c = pbv.getCoordinates(shipStartX,
shipStartY);
Ship ship = buildShip(sv.getShipType(), c,
Direction.SOUTH);
playerBoard.placeShip(ship);
// TODO: handle illegal ship placement
shipStack.getChildren().remove(sv);
pbv.addShip(ship);
} else {
// snap back
sv.setTranslateX(initX);
sv.setTranslateY(initY);
}
}
});
}
shipStack.relocate(obv.getBoundsInParent().getMinX(), obv
.getBoundsInParent().getMaxY() + 8);
root.getChildren().add(shipStack);
// Temporary input field to enter the opponent's
final HBox ipBox = new HBox();
final TextField ipAddress = new TextField();
ipBox.getChildren().add(ipAddress);
final Button connect = new Button("Connect");
// TODO: add listener to Connection
new ConnectionStateListener() {
@Override
public void stateChanged(ConnectionState newState) {
switch (newState) {
case CLOSED:
case LISTENING:
ipBox.setVisible(true);
break;
case CONNECTED:
ipBox.setVisible(false);
break;
}
}
};
connect.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
ParallelTransitionBuilder
.create()
.children(
ScaleTransitionBuilder.create().node(pbv)
.duration(Duration.seconds(1)).toX(0.5)
.toY(0.5).build(),
TranslateTransitionBuilder.create().node(pbv)
.duration(Duration.seconds(1))
.toX(-100).toY(-100).build(),
ScaleTransitionBuilder.create().node(obv)
.duration(Duration.seconds(1)).toX(2)
.toY(2).build(),
TranslateTransitionBuilder.create().node(obv)
.duration(Duration.seconds(1)).toY(200)
.build()//
).build().play();
// TODO
// Connection.getInstance().connectOpponent()
System.out.println(ipAddress.getText());
}
});
ipBox.getChildren().add(connect);
ipBox.relocate(pbv.getBoundsInParent().getMinX(), pbv
.getBoundsInParent().getMaxY() + 20);
ipBox.getChildren().add(
new Label(NetworkInformation.getIntAddresses().toString()));
root.getChildren().add(ipBox);
primaryStage.show();
}
|
diff --git a/overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/JdkHttpConnector.java b/overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/JdkHttpConnector.java
index dd32b25..2f9d56e 100644
--- a/overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/JdkHttpConnector.java
+++ b/overthere/src/main/java/com/xebialabs/overthere/cifs/winrm/connector/JdkHttpConnector.java
@@ -1,136 +1,136 @@
/*
* This file is part of WinRM.
*
* WinRM 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.
*
* WinRM 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 WinRM. If not, see <http://www.gnu.org/licenses/>.
*/
package com.xebialabs.overthere.cifs.winrm.connector;
import com.google.common.io.Closeables;
import com.xebialabs.overthere.cifs.winrm.HttpConnector;
import com.xebialabs.overthere.cifs.winrm.SoapAction;
import com.xebialabs.overthere.cifs.winrm.TokenGenerator;
import com.xebialabs.overthere.cifs.winrm.exception.BlankValueRuntimeException;
import com.xebialabs.overthere.cifs.winrm.exception.InvalidFilePathRuntimeException;
import com.xebialabs.overthere.cifs.winrm.exception.WinRMRuntimeIOException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
*/
public class JdkHttpConnector implements HttpConnector {
private final URL targetURL;
private final TokenGenerator tokenGenerator;
public JdkHttpConnector(URL targetURL, TokenGenerator tokenGenerator) {
this.targetURL = targetURL;
this.tokenGenerator = tokenGenerator;
}
@Override
public Document sendMessage(Document requestDocument, SoapAction soapAction) {
try {
final URLConnection urlConnection = targetURL.openConnection();
HttpURLConnection con = (HttpURLConnection) urlConnection;
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8");
final String authToken = tokenGenerator.generateToken();
if (authToken != null)
con.addRequestProperty("Authorization", authToken);
if (soapAction != null) {
con.setRequestProperty("SOAPAction", soapAction.getValue());
}
final String requestDocAsString = toString(requestDocument);
logger.trace("Sending request to {}", targetURL);
- logger.trace("Request body: {}", targetURL, requestDocAsString);
+ logger.trace("Request body: {} {}", targetURL, requestDocAsString);
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(
con.getOutputStream()));
try {
bw.write(requestDocAsString, 0, requestDocAsString.length());
} finally {
Closeables.closeQuietly(bw);
}
InputStream is = null;
if (con.getResponseCode() >= 400) {
is = con.getErrorStream();
}
if(is == null) {
is = con.getInputStream();
}
Writer writer = new StringWriter();
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
try {
int n;
char[] buffer = new char[1024];
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
Closeables.closeQuietly(reader);
Closeables.closeQuietly(is);
}
if (logger.isDebugEnabled()) {
for (int i = 0; i < con.getHeaderFields().size(); i++) {
logger.trace("Header {}: {}", con.getHeaderFieldKey(i), con.getHeaderField(i));
}
}
final String text = writer.toString();
logger.trace("Response body: {}", text);
return DocumentHelper.parseText(text);
} catch (BlankValueRuntimeException bvrte) {
throw bvrte;
} catch (InvalidFilePathRuntimeException ifprte) {
throw ifprte;
} catch (Exception e) {
throw new WinRMRuntimeIOException("Send message on " + targetURL + " error ", requestDocument, null, e);
}
}
private String toString(Document doc) {
StringWriter stringWriter = new StringWriter();
XMLWriter xmlWriter = new XMLWriter(stringWriter, OutputFormat.createPrettyPrint());
try {
xmlWriter.write(doc);
xmlWriter.close();
} catch (IOException e) {
throw new WinRMRuntimeIOException("Cannnot convert XML to String ", e);
}
return stringWriter.toString();
}
private static Logger logger = LoggerFactory.getLogger(JdkHttpConnector.class);
}
| true | true | public Document sendMessage(Document requestDocument, SoapAction soapAction) {
try {
final URLConnection urlConnection = targetURL.openConnection();
HttpURLConnection con = (HttpURLConnection) urlConnection;
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8");
final String authToken = tokenGenerator.generateToken();
if (authToken != null)
con.addRequestProperty("Authorization", authToken);
if (soapAction != null) {
con.setRequestProperty("SOAPAction", soapAction.getValue());
}
final String requestDocAsString = toString(requestDocument);
logger.trace("Sending request to {}", targetURL);
logger.trace("Request body: {}", targetURL, requestDocAsString);
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(
con.getOutputStream()));
try {
bw.write(requestDocAsString, 0, requestDocAsString.length());
} finally {
Closeables.closeQuietly(bw);
}
InputStream is = null;
if (con.getResponseCode() >= 400) {
is = con.getErrorStream();
}
if(is == null) {
is = con.getInputStream();
}
Writer writer = new StringWriter();
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
try {
int n;
char[] buffer = new char[1024];
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
Closeables.closeQuietly(reader);
Closeables.closeQuietly(is);
}
if (logger.isDebugEnabled()) {
for (int i = 0; i < con.getHeaderFields().size(); i++) {
logger.trace("Header {}: {}", con.getHeaderFieldKey(i), con.getHeaderField(i));
}
}
final String text = writer.toString();
logger.trace("Response body: {}", text);
return DocumentHelper.parseText(text);
} catch (BlankValueRuntimeException bvrte) {
throw bvrte;
} catch (InvalidFilePathRuntimeException ifprte) {
throw ifprte;
} catch (Exception e) {
throw new WinRMRuntimeIOException("Send message on " + targetURL + " error ", requestDocument, null, e);
}
}
| public Document sendMessage(Document requestDocument, SoapAction soapAction) {
try {
final URLConnection urlConnection = targetURL.openConnection();
HttpURLConnection con = (HttpURLConnection) urlConnection;
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/soap+xml; charset=UTF-8");
final String authToken = tokenGenerator.generateToken();
if (authToken != null)
con.addRequestProperty("Authorization", authToken);
if (soapAction != null) {
con.setRequestProperty("SOAPAction", soapAction.getValue());
}
final String requestDocAsString = toString(requestDocument);
logger.trace("Sending request to {}", targetURL);
logger.trace("Request body: {} {}", targetURL, requestDocAsString);
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(
con.getOutputStream()));
try {
bw.write(requestDocAsString, 0, requestDocAsString.length());
} finally {
Closeables.closeQuietly(bw);
}
InputStream is = null;
if (con.getResponseCode() >= 400) {
is = con.getErrorStream();
}
if(is == null) {
is = con.getInputStream();
}
Writer writer = new StringWriter();
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
try {
int n;
char[] buffer = new char[1024];
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
Closeables.closeQuietly(reader);
Closeables.closeQuietly(is);
}
if (logger.isDebugEnabled()) {
for (int i = 0; i < con.getHeaderFields().size(); i++) {
logger.trace("Header {}: {}", con.getHeaderFieldKey(i), con.getHeaderField(i));
}
}
final String text = writer.toString();
logger.trace("Response body: {}", text);
return DocumentHelper.parseText(text);
} catch (BlankValueRuntimeException bvrte) {
throw bvrte;
} catch (InvalidFilePathRuntimeException ifprte) {
throw ifprte;
} catch (Exception e) {
throw new WinRMRuntimeIOException("Send message on " + targetURL + " error ", requestDocument, null, e);
}
}
|
diff --git a/src/main/java/edu/umd/cs/linqs/vision/ImagePatchUtils.java b/src/main/java/edu/umd/cs/linqs/vision/ImagePatchUtils.java
index 75d8430..e2d4bca 100644
--- a/src/main/java/edu/umd/cs/linqs/vision/ImagePatchUtils.java
+++ b/src/main/java/edu/umd/cs/linqs/vision/ImagePatchUtils.java
@@ -1,422 +1,422 @@
package edu.umd.cs.linqs.vision;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.linqs.vision.PatchStructure.Patch;
import edu.umd.cs.psl.database.Database;
import edu.umd.cs.psl.database.DatabaseQuery;
import edu.umd.cs.psl.database.ResultList;
import edu.umd.cs.psl.model.argument.GroundTerm;
import edu.umd.cs.psl.model.argument.UniqueID;
import edu.umd.cs.psl.model.argument.Variable;
import edu.umd.cs.psl.model.atom.Atom;
import edu.umd.cs.psl.model.atom.GroundAtom;
import edu.umd.cs.psl.model.atom.QueryAtom;
import edu.umd.cs.psl.model.atom.RandomVariableAtom;
import edu.umd.cs.psl.model.predicate.Predicate;
import edu.umd.cs.psl.util.database.Queries;
public class ImagePatchUtils {
static Logger log = LoggerFactory.getLogger(ImagePatchUtils.class);
public static void insertFromPatchMap(Predicate relation, Database data, Map<Patch, Patch> map) {
for (Map.Entry<Patch, Patch> e : map.entrySet()) {
UniqueID A = data.getUniqueID(e.getKey().uniqueID());
UniqueID B = data.getUniqueID(e.getValue().uniqueID());
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(relation, A, B);
atom.setValue(1.0);
data.commit(atom);
}
}
/** do not use **/
public static void insertChildren(Predicate relation, Database data, PatchStructure h) {
// for (Map.Entry<Patch, Patch> e : h.getParent().entrySet()) {
// UniqueID B = data.getUniqueID(e.getKey().uniqueID());
// UniqueID A = data.getUniqueID(e.getValue().uniqueID());
// RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(relation, A, B);
// atom.setValue(1.0);
// data.commit(atom);
// }
}
public static void insertPixelPatchChildren(Predicate children, Database data, PatchStructure h) {
for (Patch p : h.getPatches().values()) {
UniqueID patch = data.getUniqueID(p.uniqueID());
for (int i : p.pixelList()) {
UniqueID pixel = data.getUniqueID(i);
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(children, patch, pixel);
atom.setValue(1.0);
data.commit(atom);
}
}
}
public static void insertNeighbors(Predicate neighbor, Database data, PatchStructure ps) {
RandomVariableAtom atom;
for (Map.Entry<Patch, Patch> e : ps.getNorth().entrySet()) {
UniqueID A = data.getUniqueID(e.getKey().uniqueID());
UniqueID B = data.getUniqueID(e.getKey().uniqueID());
atom = (RandomVariableAtom) data.getAtom(neighbor, A, B);
atom.setValue(1.0);
data.commit(atom);
atom = (RandomVariableAtom) data.getAtom(neighbor, B, A);
atom.setValue(1.0);
data.commit(atom);
}
for (Map.Entry<Patch, Patch> e : ps.getEast().entrySet()) {
UniqueID A = data.getUniqueID(e.getKey().uniqueID());
UniqueID B = data.getUniqueID(e.getKey().uniqueID());
atom = (RandomVariableAtom) data.getAtom(neighbor, A, B);
atom.setValue(1.0);
data.commit(atom);
atom = (RandomVariableAtom) data.getAtom(neighbor, B, A);
atom.setValue(1.0);
data.commit(atom);
}
}
public static void insertPatchLevels(Database data, PatchStructure h, Predicate level) {
for (Patch p : h.getPatches().values()) {
UniqueID L = data.getUniqueID(p.getLevel());
UniqueID A = data.getUniqueID(p.uniqueID());
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(level, A, L);
atom.setValue(1.0);
data.commit(atom);
}
}
/**
* Assumes image is columnwise vectorized matrix of grayscale values in [0,1]
* @param brightness predicate of brightness
* @param imageID UniqueID of current image
* @param data database to insert pixel values
* @param hierarchy
* @param width width of image
* @param height height of image
* @param image vectorized image
* @param mask vectorized mask of which entries to set ground truth on. If null, all entries are entered
*/
public static void setPixels(Predicate brightness, UniqueID imageID, Database data, PatchStructure hierarchy, int width, int height, double [] image, boolean [] mask) {
int k = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (mask == null || mask[k]) {
UniqueID pixel = data.getUniqueID(k);
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(brightness, pixel, imageID);
atom.setValue(image[k]);
data.commit(atom);
}
k++;
}
}
}
/**
* Sets k-means representation of observed image.
*
* Assumes image is columnwise vectorized matrix of grayscale values in [0,1].
*
* @param hasMean predicate of k-means representation
* @param mean predicate used to store means for image
* @param imageID UniqueID of current image
* @param data database to insert pixel values
* @param hierarchy
* @param width width of image
* @param height height of image
* @param image vectorized image
* @param mask vectorized mask of which entries to set ground truth on. If null, all entries are entered
*/
public static void setObservedHasMean(Predicate hasMean, Predicate mean, UniqueID imageID, Database data, int width, int height, int numMeans, double variance, double [] image, boolean [] mask) {
/* Counts the number of observed pixels in the image */
int numObservedPixels = 0;
for (boolean masked : mask)
if (masked)
numObservedPixels++;
/* Puts the observed pixels into their own array */
double[] observedImage = new double[numObservedPixels];
int j = 0;
for (int i = 0; i < image.length; i++)
if (mask[i])
observedImage[j++] = image[i];
/* Sorts the pixel intensities */
Arrays.sort(observedImage);
/* For each mean, identifies the quantiles, then computes the quantile's mean */
double [] means = new double[numMeans];
int currentIndex = 0;
int numPerQuantile = numObservedPixels / numMeans;
int numWithPlusOne = numObservedPixels % numMeans;
for (int m = 0; m < numMeans; m++) {
int numInThisQuantile = (m < numWithPlusOne) ? numPerQuantile + 1 : numPerQuantile;
int numProcessed = 0;
double total = 0.0;
while (numProcessed < numInThisQuantile && currentIndex < numObservedPixels) {
total += observedImage[currentIndex++];
numProcessed++;
}
means[m] = total / numInThisQuantile;
}
/* Computes value of hasMean(imageID, pixel, mean) for each pixel and mean */
int k = 0;
for (int i = 0; i < width; i++) {
for (j = 0; j < height; j++) {
if (mask == null || mask[k]) {
/* Populates HasMean with the k-means representation */
- UniqueID pixel = data.getUniqueID(k);
+ UniqueID pixelID = data.getUniqueID(k);
double[] hasMeanValues = computeHasMean(image[k], means, variance);
for (int m = 0; m < numMeans; m++) {
UniqueID meanID = data.getUniqueID(m);
- RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(mean, pixel, imageID, meanID);
+ RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(hasMean, imageID, pixelID, meanID);
atom.setValue(hasMeanValues[m]);
data.commit(atom);
}
}
k++;
}
}
/* Finally, stores the means */
for (int m = 0; m < numMeans; m++) {
UniqueID meanID = data.getUniqueID(m);
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(mean, imageID, meanID);
atom.setValue(means[m]);
data.commit(atom);
}
}
static double[] computeHasMean(double brightness, double[] means, double variance) {
double[] densities = new double[means.length];
for (int m = 0; m < means.length; m++) {
densities[m] = Math.exp(-1 * (brightness - means[m]) * (brightness - means[m]) / 2 / variance);
densities[m] /= Math.sqrt(2 * Math.PI * variance);
}
double total = 0.0;
for (double density : densities)
total += density;
for (int m = 0; m < means.length; m++)
densities[m] /= total;
return densities;
}
public static void populateHasMean(int width, int height, int numMeans, Predicate hasMean, Database data, UniqueID imageID) {
for (int m = 0; m < numMeans; m++) {
UniqueID meanID = data.getUniqueID(m);
int rvCount = 0;
int observedCount = 0;
int k = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < width; j++) {
UniqueID pixelID = data.getUniqueID(k);
GroundAtom atom = data.getAtom(hasMean, imageID, pixelID, meanID);
if (atom instanceof RandomVariableAtom) {
((RandomVariableAtom) atom).setValue(0.0);
data.commit((RandomVariableAtom) atom);
rvCount++;
}
else
observedCount++;
k++;
}
}
log.debug("Image " + imageID + ", {} observed hasMean atoms, {} random variable hasMean atoms", observedCount, rvCount);
}
}
/**
*
* @param hasMean
* @param mean
* @param brightness
* @param pic
* @param data
* @param width
* @param height
* @param numMeans
*/
public static void decodeBrightness(Predicate hasMean, Predicate mean, Predicate brightness, Predicate pic, Database data, int width, int height, int numMeans) {
Set<GroundAtom> picAtoms = Queries.getAllAtoms(data, pic);
ArrayList<GroundTerm> pics = new ArrayList<GroundTerm>();
for (GroundAtom atom : picAtoms)
pics.add(atom.getArguments()[0]);
for (GroundTerm imageID : pics) {
int k = 0;
double [] means = new double[numMeans];
for (int m = 0; m < numMeans; m++) {
UniqueID meanID = data.getUniqueID(m);
GroundAtom meanAtom = data.getAtom(mean, imageID, meanID);
means[m] = meanAtom.getValue();
}
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
UniqueID pixelID = data.getUniqueID(k);
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(brightness, pixelID, imageID);
double numer = 0;
double denom = 0;
for (int m = 0; m < numMeans; m++) {
UniqueID meanID = data.getUniqueID(m);
GroundAtom hasMeanAtom = data.getAtom(hasMean, imageID, pixelID, meanID);
numer += hasMeanAtom.getValue() * means[m];
denom += hasMeanAtom.getValue();
}
atom.setValue(numer / denom);
k++;
}
}
}
}
public static void populatePixels(int width, int height, Predicate pixelBrightness, Database data, UniqueID imageID) {
int rv = 0;
int ov = 0;
int k = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
UniqueID pixel = data.getUniqueID(k);
Atom atom = data.getAtom(pixelBrightness, pixel, imageID);
if (atom instanceof RandomVariableAtom) {
((RandomVariableAtom) atom).setValue(0.0);
data.commit((RandomVariableAtom) atom);
rv++;
} else
ov++;
k++;
}
}
log.debug("Saw {} random variables, {} observed variables", rv, ov);
}
/**
* Populate all patches in hierarchy for given image
* @param brightness
* @param imageID
* @param data
* @param hierarchy
*/
public static void populateAllPatches(Predicate brightness, UniqueID imageID, Database data, PatchStructure hierarchy) {
log.debug("Populating " + brightness + " on image " + imageID);
for (Patch p : hierarchy.getPatches().values()) {
UniqueID patch = data.getUniqueID(p.uniqueID());
Atom atom = data.getAtom(brightness, patch, imageID);
if (atom instanceof RandomVariableAtom) {
data.commit((RandomVariableAtom) atom);
}
}
}
// /**
// * Populate all patches in hierarchy for given image
// * @param brightness
// * @param imageID
// * @param data
// * @param hierarchy
// */
// public static void populateAllPatches(List<Predicate> brightnessList, UniqueID imageID, Database data, PatchStructure hierarchy) {
// for (Patch p : hierarchy.getPatches().values()) {
// int level = p.getLevel();
// UniqueID patch = data.getUniqueID(p.uniqueID());
// Atom atom = data.getAtom(brightnessList.get(level), patch, imageID);
// if (atom instanceof RandomVariableAtom) {
// data.commit((RandomVariableAtom) atom);
// }
// }
// }
/**
* Loads vectorized image file
* @param filename
* @param width
* @param height
* @return
*/
public static List<double []> loadImages(String filename, int width, int height) {
Scanner imageScanner;
List<double []> images = new ArrayList<double []>();
try {
imageScanner = new Scanner(new FileReader(filename));
while (imageScanner.hasNext() && images.size() < 9999) {
String line = imageScanner.nextLine();
String [] tokens = line.split("\t");
assert(tokens.length == width * height);
double [] image = new double[width * height];
for (int i = 0; i < tokens.length; i++) {
image[i] = Double.parseDouble(tokens[i]);
}
images.add(image);
}
imageScanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return images;
}
/**
* precomputes patch brightness from fully-observed database
*/
public static void computePatchBrightness(Predicate brightness, Predicate pixelBrightness, Database data, UniqueID imageID, PatchStructure ps, double [] image) {
log.debug("Computing patch brightness for image {}", imageID);
for (Patch p : ps.getPatches().values()) {
UniqueID patch = data.getUniqueID(p.uniqueID());
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(brightness, patch, imageID);
double sum = 0.0;
for (Integer pixel : p.pixelList()) {
sum += image[pixel];
}
atom.setValue(sum / p.pixelList().size());
}
}
/**
*
*/
public static void computeNeighborBrightness(Predicate neighborBrightness, Predicate brightness, Predicate neighbors, Database data, UniqueID imageID, PatchStructure ps) {
log.debug("Computing neighbor brightness for image {}", imageID);
for (Patch p : ps.getPatches().values()) {
UniqueID patch = data.getUniqueID(p.uniqueID());
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(neighborBrightness, patch, imageID);
double sum = 0.0;
Variable neigh = new Variable("neighbor");
QueryAtom q = new QueryAtom(neighbors, patch, neigh);
ResultList list = data.executeQuery(new DatabaseQuery(q));
if (list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
GroundAtom nb = data.getAtom(brightness, list.get(i)[0], imageID);
sum += nb.getValue();
}
atom.setValue(sum / list.size());
}
}
}
}
| false | true | public static void setObservedHasMean(Predicate hasMean, Predicate mean, UniqueID imageID, Database data, int width, int height, int numMeans, double variance, double [] image, boolean [] mask) {
/* Counts the number of observed pixels in the image */
int numObservedPixels = 0;
for (boolean masked : mask)
if (masked)
numObservedPixels++;
/* Puts the observed pixels into their own array */
double[] observedImage = new double[numObservedPixels];
int j = 0;
for (int i = 0; i < image.length; i++)
if (mask[i])
observedImage[j++] = image[i];
/* Sorts the pixel intensities */
Arrays.sort(observedImage);
/* For each mean, identifies the quantiles, then computes the quantile's mean */
double [] means = new double[numMeans];
int currentIndex = 0;
int numPerQuantile = numObservedPixels / numMeans;
int numWithPlusOne = numObservedPixels % numMeans;
for (int m = 0; m < numMeans; m++) {
int numInThisQuantile = (m < numWithPlusOne) ? numPerQuantile + 1 : numPerQuantile;
int numProcessed = 0;
double total = 0.0;
while (numProcessed < numInThisQuantile && currentIndex < numObservedPixels) {
total += observedImage[currentIndex++];
numProcessed++;
}
means[m] = total / numInThisQuantile;
}
/* Computes value of hasMean(imageID, pixel, mean) for each pixel and mean */
int k = 0;
for (int i = 0; i < width; i++) {
for (j = 0; j < height; j++) {
if (mask == null || mask[k]) {
/* Populates HasMean with the k-means representation */
UniqueID pixel = data.getUniqueID(k);
double[] hasMeanValues = computeHasMean(image[k], means, variance);
for (int m = 0; m < numMeans; m++) {
UniqueID meanID = data.getUniqueID(m);
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(mean, pixel, imageID, meanID);
atom.setValue(hasMeanValues[m]);
data.commit(atom);
}
}
k++;
}
}
/* Finally, stores the means */
for (int m = 0; m < numMeans; m++) {
UniqueID meanID = data.getUniqueID(m);
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(mean, imageID, meanID);
atom.setValue(means[m]);
data.commit(atom);
}
}
| public static void setObservedHasMean(Predicate hasMean, Predicate mean, UniqueID imageID, Database data, int width, int height, int numMeans, double variance, double [] image, boolean [] mask) {
/* Counts the number of observed pixels in the image */
int numObservedPixels = 0;
for (boolean masked : mask)
if (masked)
numObservedPixels++;
/* Puts the observed pixels into their own array */
double[] observedImage = new double[numObservedPixels];
int j = 0;
for (int i = 0; i < image.length; i++)
if (mask[i])
observedImage[j++] = image[i];
/* Sorts the pixel intensities */
Arrays.sort(observedImage);
/* For each mean, identifies the quantiles, then computes the quantile's mean */
double [] means = new double[numMeans];
int currentIndex = 0;
int numPerQuantile = numObservedPixels / numMeans;
int numWithPlusOne = numObservedPixels % numMeans;
for (int m = 0; m < numMeans; m++) {
int numInThisQuantile = (m < numWithPlusOne) ? numPerQuantile + 1 : numPerQuantile;
int numProcessed = 0;
double total = 0.0;
while (numProcessed < numInThisQuantile && currentIndex < numObservedPixels) {
total += observedImage[currentIndex++];
numProcessed++;
}
means[m] = total / numInThisQuantile;
}
/* Computes value of hasMean(imageID, pixel, mean) for each pixel and mean */
int k = 0;
for (int i = 0; i < width; i++) {
for (j = 0; j < height; j++) {
if (mask == null || mask[k]) {
/* Populates HasMean with the k-means representation */
UniqueID pixelID = data.getUniqueID(k);
double[] hasMeanValues = computeHasMean(image[k], means, variance);
for (int m = 0; m < numMeans; m++) {
UniqueID meanID = data.getUniqueID(m);
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(hasMean, imageID, pixelID, meanID);
atom.setValue(hasMeanValues[m]);
data.commit(atom);
}
}
k++;
}
}
/* Finally, stores the means */
for (int m = 0; m < numMeans; m++) {
UniqueID meanID = data.getUniqueID(m);
RandomVariableAtom atom = (RandomVariableAtom) data.getAtom(mean, imageID, meanID);
atom.setValue(means[m]);
data.commit(atom);
}
}
|
diff --git a/src/java/com/threerings/tudey/server/util/SceneTicker.java b/src/java/com/threerings/tudey/server/util/SceneTicker.java
index 801e9e99..369542db 100644
--- a/src/java/com/threerings/tudey/server/util/SceneTicker.java
+++ b/src/java/com/threerings/tudey/server/util/SceneTicker.java
@@ -1,266 +1,266 @@
//
// $Id$
//
// Clyde library - tools for developing networked games
// Copyright (C) 2005-2010 Three Rings Design, Inc.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package com.threerings.tudey.server.util;
import java.util.Arrays;
import java.util.List;
import com.google.common.collect.Lists;
import com.samskivert.util.Interval;
import com.samskivert.util.LoopingThread;
import com.samskivert.util.RunQueue;
import com.threerings.tudey.server.TudeySceneManager;
import com.threerings.tudey.util.TruncatedAverage;
import static com.threerings.tudey.Log.*;
/**
* Ticks some number of scene managers.
*/
public abstract class SceneTicker
{
/**
* Ticks the scenes on the event thread.
*/
public static class EventThread extends SceneTicker
{
/**
* Creates a new event thread ticker.
*/
public EventThread (RunQueue runQueue, int targetInterval)
{
super(runQueue, targetInterval);
}
@Override // documentation inherited
protected void start ()
{
(_interval = new Interval(_runQueue) {
@Override public void expired () {
long remaining = tick();
if (_interval != null) {
_interval.schedule(Math.max(remaining, 1L));
}
}
}).schedule(_targetInterval);
}
@Override // documentation inherited
protected void stop ()
{
if (_interval != null) {
_interval.cancel();
_interval = null;
}
}
/** The ticker interval. */
protected Interval _interval;
}
/**
* Ticks the scenes on a dedicated thread.
*/
public static class DedicatedThread extends SceneTicker
{
/**
* Creates a new dedicated thread ticker.
*/
public DedicatedThread (RunQueue runQueue, int targetInterval)
{
super(runQueue, targetInterval);
}
@Override // documentation inherited
protected void start ()
{
(_thread = new LoopingThread("sceneTicker") {
@Override protected void iterate () {
try {
Thread.sleep(_remaining);
} catch (InterruptedException e) {
return;
}
_remaining = tick();
}
@Override protected void kick () {
interrupt();
}
protected long _remaining = _targetInterval;
}).start();
}
@Override // documentation inherited
protected void stop ()
{
if (_thread != null) {
_thread.shutdown();
_thread = null;
}
}
/** The thread on which we run. */
protected LoopingThread _thread;
}
/**
* Creates a new scene ticker.
*/
public SceneTicker (RunQueue runQueue, int targetInterval)
{
_runQueue = runQueue;
_targetInterval = _actualInterval = targetInterval;
}
/**
* Sets the target interval.
*/
public void setTargetInterval (int interval)
{
_targetInterval = interval;
}
/**
* Returns the average actual interval.
*/
public int getActualInterval ()
{
return _actualInterval;
}
/**
* Adds a scene manager to be ticked.
*/
public void add (TudeySceneManager scenemgr)
{
synchronized (_scenemgrs) {
_scenemgrs.add(scenemgr);
if (_scenemgrs.size() == 1) {
_lastTick = System.currentTimeMillis();
start();
}
}
}
/**
* Removes a scene manager.
*/
public void remove (TudeySceneManager scenemgr)
{
synchronized (_scenemgrs) {
if (_scenemgrs.remove(scenemgr) && _scenemgrs.isEmpty()) {
stop();
}
}
}
/**
* Checks whether the specified scene manager is being ticked.
*/
public boolean contains (TudeySceneManager scenemgr)
{
synchronized (_scenemgrs) {
return _scenemgrs.contains(scenemgr);
}
}
/**
* Starts ticking.
*/
protected abstract void start ();
/**
* Stops ticking.
*/
protected abstract void stop ();
/**
* Ticks the scene managers.
*/
protected long tick ()
{
// compute the elapsed time since the last tick
long now = System.currentTimeMillis();
int elapsed = (int)(now - _lastTick);
// note when we enter or leave a period of overlong ticking
- if (elapsed >= _targetInterval*4 && !_lastLong) {
+ if (elapsed >= _targetInterval*5 && !_lastLong) {
log.info("Overlong ticking started.", "elapsed", elapsed, "target", _targetInterval);
_lastLong = true;
- } else if (elapsed <= _targetInterval*3 && _lastLong) {
+ } else if (elapsed <= _targetInterval*2 && _lastLong) {
log.info("Overlong ticking stopped.", "elapsed", elapsed, "target", _targetInterval);
_lastLong = false;
}
_lastTick = now;
_intervalAverage.record(elapsed);
_actualInterval = _intervalAverage.value();
// tick the scene managers
synchronized (_scenemgrs) {
_sarray = _scenemgrs.toArray(_sarray);
}
for (TudeySceneManager scenemgr : _sarray) {
if (scenemgr == null) {
break;
}
try {
scenemgr.tick();
} catch (Exception e) {
log.warning("Exception thrown in scene tick.", "where", scenemgr.where(), e);
}
}
Arrays.fill(_sarray, null);
// return the amount of time remaining until the next tick
return _targetInterval - (System.currentTimeMillis() - _lastTick);
}
/** The event thread run queue. */
protected RunQueue _runQueue;
/** The target interval. */
protected volatile int _targetInterval;
/** The average actual interval. */
protected volatile int _actualInterval;
/** The list of scene managers to tick. */
protected List<TudeySceneManager> _scenemgrs = Lists.newArrayList();
/** Holds the scene managers during processing. */
protected TudeySceneManager[] _sarray = new TudeySceneManager[0];
/** The time of the last tick. */
protected long _lastTick;
/** Whether the last tick was considered "long." */
protected boolean _lastLong;
/** The trailing average of the actual intervals. */
protected TruncatedAverage _intervalAverage = new TruncatedAverage();
}
| false | true | protected long tick ()
{
// compute the elapsed time since the last tick
long now = System.currentTimeMillis();
int elapsed = (int)(now - _lastTick);
// note when we enter or leave a period of overlong ticking
if (elapsed >= _targetInterval*4 && !_lastLong) {
log.info("Overlong ticking started.", "elapsed", elapsed, "target", _targetInterval);
_lastLong = true;
} else if (elapsed <= _targetInterval*3 && _lastLong) {
log.info("Overlong ticking stopped.", "elapsed", elapsed, "target", _targetInterval);
_lastLong = false;
}
_lastTick = now;
_intervalAverage.record(elapsed);
_actualInterval = _intervalAverage.value();
// tick the scene managers
synchronized (_scenemgrs) {
_sarray = _scenemgrs.toArray(_sarray);
}
for (TudeySceneManager scenemgr : _sarray) {
if (scenemgr == null) {
break;
}
try {
scenemgr.tick();
} catch (Exception e) {
log.warning("Exception thrown in scene tick.", "where", scenemgr.where(), e);
}
}
Arrays.fill(_sarray, null);
// return the amount of time remaining until the next tick
return _targetInterval - (System.currentTimeMillis() - _lastTick);
}
| protected long tick ()
{
// compute the elapsed time since the last tick
long now = System.currentTimeMillis();
int elapsed = (int)(now - _lastTick);
// note when we enter or leave a period of overlong ticking
if (elapsed >= _targetInterval*5 && !_lastLong) {
log.info("Overlong ticking started.", "elapsed", elapsed, "target", _targetInterval);
_lastLong = true;
} else if (elapsed <= _targetInterval*2 && _lastLong) {
log.info("Overlong ticking stopped.", "elapsed", elapsed, "target", _targetInterval);
_lastLong = false;
}
_lastTick = now;
_intervalAverage.record(elapsed);
_actualInterval = _intervalAverage.value();
// tick the scene managers
synchronized (_scenemgrs) {
_sarray = _scenemgrs.toArray(_sarray);
}
for (TudeySceneManager scenemgr : _sarray) {
if (scenemgr == null) {
break;
}
try {
scenemgr.tick();
} catch (Exception e) {
log.warning("Exception thrown in scene tick.", "where", scenemgr.where(), e);
}
}
Arrays.fill(_sarray, null);
// return the amount of time remaining until the next tick
return _targetInterval - (System.currentTimeMillis() - _lastTick);
}
|
diff --git a/activemq-core/src/main/java/org/apache/activemq/broker/region/PrefetchSubscription.java b/activemq-core/src/main/java/org/apache/activemq/broker/region/PrefetchSubscription.java
index 14385c31e..621c466b0 100755
--- a/activemq-core/src/main/java/org/apache/activemq/broker/region/PrefetchSubscription.java
+++ b/activemq-core/src/main/java/org/apache/activemq/broker/region/PrefetchSubscription.java
@@ -1,756 +1,756 @@
/**
* 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.activemq.broker.region;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.jms.InvalidSelectorException;
import javax.jms.JMSException;
import org.apache.activemq.ActiveMQMessageAudit;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.region.cursors.PendingMessageCursor;
import org.apache.activemq.broker.region.cursors.VMPendingMessageCursor;
import org.apache.activemq.command.ConsumerControl;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.MessageAck;
import org.apache.activemq.command.MessageDispatch;
import org.apache.activemq.command.MessageDispatchNotification;
import org.apache.activemq.command.MessageId;
import org.apache.activemq.command.MessagePull;
import org.apache.activemq.command.Response;
import org.apache.activemq.thread.Scheduler;
import org.apache.activemq.transaction.Synchronization;
import org.apache.activemq.usage.SystemUsage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* A subscription that honors the pre-fetch option of the ConsumerInfo.
*
* @version $Revision: 1.15 $
*/
public abstract class PrefetchSubscription extends AbstractSubscription {
private static final Log LOG = LogFactory.getLog(PrefetchSubscription.class);
protected final Scheduler scheduler;
protected PendingMessageCursor pending;
protected final List<MessageReference> dispatched = new CopyOnWriteArrayList<MessageReference>();
protected int prefetchExtension;
protected boolean usePrefetchExtension = true;
protected long enqueueCounter;
protected long dispatchCounter;
protected long dequeueCounter;
private int maxProducersToAudit=32;
private int maxAuditDepth=2048;
protected final SystemUsage usageManager;
private final Object pendingLock = new Object();
private final Object dispatchLock = new Object();
protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit();
private final CountDownLatch okForAckAsDispatchDone = new CountDownLatch(1);
public PrefetchSubscription(Broker broker, SystemUsage usageManager, ConnectionContext context, ConsumerInfo info, PendingMessageCursor cursor) throws InvalidSelectorException {
super(broker,context, info);
this.usageManager=usageManager;
pending = cursor;
this.scheduler = broker.getScheduler();
}
public PrefetchSubscription(Broker broker,SystemUsage usageManager, ConnectionContext context, ConsumerInfo info) throws InvalidSelectorException {
this(broker,usageManager,context, info, new VMPendingMessageCursor(false));
}
/**
* Allows a message to be pulled on demand by a client
*/
public Response pullMessage(ConnectionContext context, MessagePull pull) throws Exception {
// The slave should not deliver pull messages. TODO: when the slave
// becomes a master,
// He should send a NULL message to all the consumers to 'wake them up'
// in case
// they were waiting for a message.
if (getPrefetchSize() == 0 && !isSlave()) {
final long dispatchCounterBeforePull;
synchronized(this) {
prefetchExtension++;
dispatchCounterBeforePull = dispatchCounter;
}
// Have the destination push us some messages.
for (Destination dest : destinations) {
dest.iterate();
}
dispatchPending();
synchronized(this) {
// If there was nothing dispatched.. we may need to setup a timeout.
if (dispatchCounterBeforePull == dispatchCounter) {
// immediate timeout used by receiveNoWait()
if (pull.getTimeout() == -1) {
// Send a NULL message.
add(QueueMessageReference.NULL_MESSAGE);
dispatchPending();
}
if (pull.getTimeout() > 0) {
scheduler.executeAfterDelay(new Runnable() {
public void run() {
pullTimeout(dispatchCounterBeforePull);
}
}, pull.getTimeout());
}
}
}
}
return null;
}
/**
* Occurs when a pull times out. If nothing has been dispatched since the
* timeout was setup, then send the NULL message.
*/
final void pullTimeout(long dispatchCounterBeforePull) {
synchronized (pendingLock) {
if (dispatchCounterBeforePull == dispatchCounter) {
try {
add(QueueMessageReference.NULL_MESSAGE);
dispatchPending();
} catch (Exception e) {
context.getConnection().serviceException(e);
}
}
}
}
public void add(MessageReference node) throws Exception {
synchronized (pendingLock) {
// The destination may have just been removed...
if( !destinations.contains(node.getRegionDestination()) && node!=QueueMessageReference.NULL_MESSAGE) {
// perhaps we should inform the caller that we are no longer valid to dispatch to?
return;
}
enqueueCounter++;
pending.addMessageLast(node);
}
dispatchPending();
}
public void processMessageDispatchNotification(MessageDispatchNotification mdn) throws Exception {
synchronized(pendingLock) {
try {
pending.reset();
while (pending.hasNext()) {
MessageReference node = pending.next();
node.decrementReferenceCount();
if (node.getMessageId().equals(mdn.getMessageId())) {
// Synchronize between dispatched list and removal of messages from pending list
// related to remove subscription action
synchronized(dispatchLock) {
pending.remove();
createMessageDispatch(node, node.getMessage());
dispatched.add(node);
onDispatch(node, node.getMessage());
}
return;
}
}
} finally {
pending.release();
}
}
throw new JMSException(
"Slave broker out of sync with master: Dispatched message ("
+ mdn.getMessageId() + ") was not in the pending list for "
+ mdn.getConsumerId() + " on " + mdn.getDestination().getPhysicalName());
}
public final void acknowledge(final ConnectionContext context,final MessageAck ack) throws Exception {
// Handle the standard acknowledgment case.
boolean callDispatchMatched = false;
Destination destination = null;
if (!isSlave()) {
if (!okForAckAsDispatchDone.await(0l, TimeUnit.MILLISECONDS)) {
// suppress unexpected ack exception in this expected case
LOG.warn("Ignoring ack received before dispatch; result of failover with an outstanding ack. Acked messages will be replayed if present on this broker. Ignored ack: " + ack);
return;
}
}
if (LOG.isTraceEnabled()) {
LOG.trace("ack:" + ack);
}
synchronized(dispatchLock) {
if (ack.isStandardAck()) {
// First check if the ack matches the dispatched. When using failover this might
// not be the case. We don't ever want to ack the wrong messages.
assertAckMatchesDispatched(ack);
// Acknowledge all dispatched messages up till the message id of
// the acknowledgment.
int index = 0;
boolean inAckRange = false;
List<MessageReference> removeList = new ArrayList<MessageReference>();
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null
|| ack.getFirstMessageId().equals(messageId)) {
inAckRange = true;
}
if (inAckRange) {
// Don't remove the nodes until we are committed.
if (!context.isInTransaction()) {
dequeueCounter++;
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
removeList.add(node);
} else {
// setup a Synchronization to remove nodes from the
// dispatched list.
context.getTransaction().addSynchronization(
new Synchronization() {
@Override
public void afterCommit()
throws Exception {
synchronized(dispatchLock) {
dequeueCounter++;
dispatched.remove(node);
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
}
}
@Override
public void afterRollback() throws Exception {
synchronized(dispatchLock) {
if (isSlave()) {
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
} else {
// poisionAck will decrement - otherwise still inflight on client
}
}
}
});
}
index++;
acknowledge(context, ack, node);
if (ack.getLastMessageId().equals(messageId)) {
// contract prefetch if dispatch required a pull
if (getPrefetchSize() == 0) {
prefetchExtension = Math.max(0, prefetchExtension - index);
} else if (usePrefetchExtension && context.isInTransaction()) {
// extend prefetch window only if not a pulling consumer
prefetchExtension = Math.max(prefetchExtension, index);
}
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
}
for (final MessageReference node : removeList) {
dispatched.remove(node);
}
// this only happens after a reconnect - get an ack which is not
// valid
if (!callDispatchMatched) {
- LOG.error("Could not correlate acknowledgment with dispatched message: "
+ LOG.warn("Could not correlate acknowledgment with dispatched message: "
+ ack);
}
} else if (ack.isIndividualAck()) {
// Message was delivered and acknowledge - but only delete the
// individual message
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getLastMessageId().equals(messageId)) {
// this should never be within a transaction
dequeueCounter++;
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
destination = node.getRegionDestination();
acknowledge(context, ack, node);
dispatched.remove(node);
prefetchExtension = Math.max(0, prefetchExtension - 1);
callDispatchMatched = true;
break;
}
}
}else if (ack.isDeliveredAck()) {
// Message was delivered but not acknowledged: update pre-fetch
// counters.
int index = 0;
for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) {
final MessageReference node = iter.next();
if (node.isExpired()) {
if (broker.isExpired(node)) {
node.getRegionDestination().messageExpired(context, this, node);
}
dispatched.remove(node);
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
}
if (ack.getLastMessageId().equals(node.getMessageId())) {
if (usePrefetchExtension) {
prefetchExtension = Math.max(prefetchExtension, index + 1);
}
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
if (!callDispatchMatched) {
throw new JMSException(
"Could not correlate acknowledgment with dispatched message: "
+ ack);
}
} else if (ack.isRedeliveredAck()) {
// Message was re-delivered but it was not yet considered to be
// a DLQ message.
boolean inAckRange = false;
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null
|| ack.getFirstMessageId().equals(messageId)) {
inAckRange = true;
}
if (inAckRange) {
if (ack.getLastMessageId().equals(messageId)) {
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
}
if (!callDispatchMatched) {
throw new JMSException(
"Could not correlate acknowledgment with dispatched message: "
+ ack);
}
} else if (ack.isPoisonAck()) {
// TODO: what if the message is already in a DLQ???
// Handle the poison ACK case: we need to send the message to a
// DLQ
if (ack.isInTransaction()) {
throw new JMSException("Poison ack cannot be transacted: "
+ ack);
}
int index = 0;
boolean inAckRange = false;
List<MessageReference> removeList = new ArrayList<MessageReference>();
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null
|| ack.getFirstMessageId().equals(messageId)) {
inAckRange = true;
}
if (inAckRange) {
sendToDLQ(context, node);
node.getRegionDestination().getDestinationStatistics()
.getInflight().decrement();
removeList.add(node);
dequeueCounter++;
index++;
acknowledge(context, ack, node);
if (ack.getLastMessageId().equals(messageId)) {
prefetchExtension = Math.max(0, prefetchExtension
- (index + 1));
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
}
for (final MessageReference node : removeList) {
dispatched.remove(node);
}
if (!callDispatchMatched) {
throw new JMSException(
"Could not correlate acknowledgment with dispatched message: "
+ ack);
}
}
}
if (callDispatchMatched && destination != null) {
destination.wakeup();
dispatchPending();
} else {
if (isSlave()) {
throw new JMSException(
"Slave broker out of sync with master: Acknowledgment ("
+ ack + ") was not in the dispatch list: "
+ dispatched);
} else {
LOG.debug("Acknowledgment out of sync (Normally occurs when failover connection reconnects): "
+ ack);
}
}
}
/**
* Checks an ack versus the contents of the dispatched list.
*
* @param ack
* @throws JMSException if it does not match
*/
protected void assertAckMatchesDispatched(MessageAck ack) throws JMSException {
MessageId firstAckedMsg = ack.getFirstMessageId();
MessageId lastAckedMsg = ack.getLastMessageId();
int checkCount = 0;
boolean checkFoundStart = false;
boolean checkFoundEnd = false;
for (MessageReference node : dispatched) {
if (firstAckedMsg == null) {
checkFoundStart = true;
} else if (!checkFoundStart && firstAckedMsg.equals(node.getMessageId())) {
checkFoundStart = true;
}
if (checkFoundStart) {
checkCount++;
}
if (lastAckedMsg != null && lastAckedMsg.equals(node.getMessageId())) {
checkFoundEnd = true;
break;
}
}
if (!checkFoundStart && firstAckedMsg != null)
throw new JMSException("Unmatched acknowledge: " + ack
+ "; Could not find Message-ID " + firstAckedMsg
+ " in dispatched-list (start of ack)");
if (!checkFoundEnd && lastAckedMsg != null)
throw new JMSException("Unmatched acknowledge: " + ack
+ "; Could not find Message-ID " + lastAckedMsg
+ " in dispatched-list (end of ack)");
if (ack.getMessageCount() != checkCount && !ack.isInTransaction()) {
throw new JMSException("Unmatched acknowledge: " + ack
+ "; Expected message count (" + ack.getMessageCount()
+ ") differs from count in dispatched-list (" + checkCount
+ ")");
}
}
/**
* @param context
* @param node
* @throws IOException
* @throws Exception
*/
protected void sendToDLQ(final ConnectionContext context, final MessageReference node) throws IOException, Exception {
broker.getRoot().sendToDeadLetterQueue(context, node);
}
public int getInFlightSize() {
return dispatched.size();
}
/**
* Used to determine if the broker can dispatch to the consumer.
*
* @return
*/
public boolean isFull() {
return dispatched.size() - prefetchExtension >= info.getPrefetchSize();
}
/**
* @return true when 60% or more room is left for dispatching messages
*/
public boolean isLowWaterMark() {
return (dispatched.size() - prefetchExtension) <= (info.getPrefetchSize() * .4);
}
/**
* @return true when 10% or less room is left for dispatching messages
*/
public boolean isHighWaterMark() {
return (dispatched.size() - prefetchExtension) >= (info.getPrefetchSize() * .9);
}
@Override
public int countBeforeFull() {
return info.getPrefetchSize() + prefetchExtension - dispatched.size();
}
public int getPendingQueueSize() {
return pending.size();
}
public int getDispatchedQueueSize() {
return dispatched.size();
}
public long getDequeueCounter() {
return dequeueCounter;
}
public long getDispatchedCounter() {
return dispatchCounter;
}
public long getEnqueueCounter() {
return enqueueCounter;
}
@Override
public boolean isRecoveryRequired() {
return pending.isRecoveryRequired();
}
public PendingMessageCursor getPending() {
return this.pending;
}
public void setPending(PendingMessageCursor pending) {
this.pending = pending;
if (this.pending!=null) {
this.pending.setSystemUsage(usageManager);
this.pending.setMemoryUsageHighWaterMark(getCursorMemoryHighWaterMark());
}
}
@Override
public void add(ConnectionContext context, Destination destination) throws Exception {
synchronized(pendingLock) {
super.add(context, destination);
pending.add(context, destination);
}
}
@Override
public List<MessageReference> remove(ConnectionContext context, Destination destination) throws Exception {
List<MessageReference> rc = new ArrayList<MessageReference>();
synchronized(pendingLock) {
super.remove(context, destination);
// Here is a potential problem concerning Inflight stat:
// Messages not already committed or rolled back may not be removed from dispatched list at the moment
// Except if each commit or rollback callback action comes before remove of subscriber.
rc.addAll(pending.remove(context, destination));
// Synchronized to DispatchLock
synchronized(dispatchLock) {
for (MessageReference r : dispatched) {
if( r.getRegionDestination() == destination) {
rc.add(r);
}
}
destination.getDestinationStatistics().getDispatched().subtract(dispatched.size());
destination.getDestinationStatistics().getInflight().subtract(dispatched.size());
dispatched.clear();
}
}
return rc;
}
protected void dispatchPending() throws IOException {
if (!isSlave()) {
synchronized(pendingLock) {
try {
int numberToDispatch = countBeforeFull();
if (numberToDispatch > 0) {
setSlowConsumer(false);
pending.setMaxBatchSize(numberToDispatch);
int count = 0;
pending.reset();
while (pending.hasNext() && !isFull()
&& count < numberToDispatch) {
MessageReference node = pending.next();
if (node == null) {
break;
}
// Synchronize between dispatched list and remove of message from pending list
// related to remove subscription action
synchronized(dispatchLock) {
pending.remove();
node.decrementReferenceCount();
if( !isDropped(node) && canDispatch(node)) {
// Message may have been sitting in the pending
// list a while waiting for the consumer to ak the message.
if (node!=QueueMessageReference.NULL_MESSAGE && node.isExpired()) {
//increment number to dispatch
numberToDispatch++;
if (broker.isExpired(node)) {
node.getRegionDestination().messageExpired(context, this, node);
}
continue;
}
dispatch(node);
count++;
}
}
}
} else if (!isSlowConsumer()) {
setSlowConsumer(true);
for (Destination dest :destinations) {
dest.slowConsumer(context, this);
}
}
} finally {
pending.release();
}
}
}
}
protected boolean dispatch(final MessageReference node) throws IOException {
final Message message = node.getMessage();
if (message == null) {
return false;
}
okForAckAsDispatchDone.countDown();
// No reentrant lock - Patch needed to IndirectMessageReference on method lock
if (!isSlave()) {
MessageDispatch md = createMessageDispatch(node, message);
// NULL messages don't count... they don't get Acked.
if (node != QueueMessageReference.NULL_MESSAGE) {
dispatchCounter++;
dispatched.add(node);
} else {
prefetchExtension = Math.max(0, prefetchExtension - 1);
}
if (info.isDispatchAsync()) {
md.setTransmitCallback(new Runnable() {
public void run() {
// Since the message gets queued up in async dispatch,
// we don't want to
// decrease the reference count until it gets put on the
// wire.
onDispatch(node, message);
}
});
context.getConnection().dispatchAsync(md);
} else {
context.getConnection().dispatchSync(md);
onDispatch(node, message);
}
return true;
} else {
return false;
}
}
protected void onDispatch(final MessageReference node, final Message message) {
if (node.getRegionDestination() != null) {
if (node != QueueMessageReference.NULL_MESSAGE) {
node.getRegionDestination().getDestinationStatistics().getDispatched().increment();
node.getRegionDestination().getDestinationStatistics().getInflight().increment();
if (LOG.isTraceEnabled()) {
LOG.trace(info.getConsumerId() + " dispatched: " + message.getMessageId()
+ ", dispatched: " + dispatchCounter + ", inflight: " + dispatched.size());
}
}
}
if (info.isDispatchAsync()) {
try {
dispatchPending();
} catch (IOException e) {
context.getConnection().serviceExceptionAsync(e);
}
}
}
/**
* inform the MessageConsumer on the client to change it's prefetch
*
* @param newPrefetch
*/
public void updateConsumerPrefetch(int newPrefetch) {
if (context != null && context.getConnection() != null && context.getConnection().isManageable()) {
ConsumerControl cc = new ConsumerControl();
cc.setConsumerId(info.getConsumerId());
cc.setPrefetch(newPrefetch);
context.getConnection().dispatchAsync(cc);
}
}
/**
* @param node
* @param message
* @return MessageDispatch
*/
protected MessageDispatch createMessageDispatch(MessageReference node, Message message) {
if (node == QueueMessageReference.NULL_MESSAGE) {
MessageDispatch md = new MessageDispatch();
md.setMessage(null);
md.setConsumerId(info.getConsumerId());
md.setDestination(null);
return md;
} else {
MessageDispatch md = new MessageDispatch();
md.setConsumerId(info.getConsumerId());
md.setDestination(node.getRegionDestination().getActiveMQDestination());
md.setMessage(message);
md.setRedeliveryCounter(node.getRedeliveryCounter());
return md;
}
}
/**
* Use when a matched message is about to be dispatched to the client.
*
* @param node
* @return false if the message should not be dispatched to the client
* (another sub may have already dispatched it for example).
* @throws IOException
*/
protected abstract boolean canDispatch(MessageReference node) throws IOException;
protected abstract boolean isDropped(MessageReference node);
/**
* Used during acknowledgment to remove the message.
*
* @throws IOException
*/
protected abstract void acknowledge(ConnectionContext context, final MessageAck ack, final MessageReference node) throws IOException;
public int getMaxProducersToAudit() {
return maxProducersToAudit;
}
public void setMaxProducersToAudit(int maxProducersToAudit) {
this.maxProducersToAudit = maxProducersToAudit;
}
public int getMaxAuditDepth() {
return maxAuditDepth;
}
public void setMaxAuditDepth(int maxAuditDepth) {
this.maxAuditDepth = maxAuditDepth;
}
public boolean isUsePrefetchExtension() {
return usePrefetchExtension;
}
public void setUsePrefetchExtension(boolean usePrefetchExtension) {
this.usePrefetchExtension = usePrefetchExtension;
}
}
| true | true | public final void acknowledge(final ConnectionContext context,final MessageAck ack) throws Exception {
// Handle the standard acknowledgment case.
boolean callDispatchMatched = false;
Destination destination = null;
if (!isSlave()) {
if (!okForAckAsDispatchDone.await(0l, TimeUnit.MILLISECONDS)) {
// suppress unexpected ack exception in this expected case
LOG.warn("Ignoring ack received before dispatch; result of failover with an outstanding ack. Acked messages will be replayed if present on this broker. Ignored ack: " + ack);
return;
}
}
if (LOG.isTraceEnabled()) {
LOG.trace("ack:" + ack);
}
synchronized(dispatchLock) {
if (ack.isStandardAck()) {
// First check if the ack matches the dispatched. When using failover this might
// not be the case. We don't ever want to ack the wrong messages.
assertAckMatchesDispatched(ack);
// Acknowledge all dispatched messages up till the message id of
// the acknowledgment.
int index = 0;
boolean inAckRange = false;
List<MessageReference> removeList = new ArrayList<MessageReference>();
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null
|| ack.getFirstMessageId().equals(messageId)) {
inAckRange = true;
}
if (inAckRange) {
// Don't remove the nodes until we are committed.
if (!context.isInTransaction()) {
dequeueCounter++;
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
removeList.add(node);
} else {
// setup a Synchronization to remove nodes from the
// dispatched list.
context.getTransaction().addSynchronization(
new Synchronization() {
@Override
public void afterCommit()
throws Exception {
synchronized(dispatchLock) {
dequeueCounter++;
dispatched.remove(node);
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
}
}
@Override
public void afterRollback() throws Exception {
synchronized(dispatchLock) {
if (isSlave()) {
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
} else {
// poisionAck will decrement - otherwise still inflight on client
}
}
}
});
}
index++;
acknowledge(context, ack, node);
if (ack.getLastMessageId().equals(messageId)) {
// contract prefetch if dispatch required a pull
if (getPrefetchSize() == 0) {
prefetchExtension = Math.max(0, prefetchExtension - index);
} else if (usePrefetchExtension && context.isInTransaction()) {
// extend prefetch window only if not a pulling consumer
prefetchExtension = Math.max(prefetchExtension, index);
}
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
}
for (final MessageReference node : removeList) {
dispatched.remove(node);
}
// this only happens after a reconnect - get an ack which is not
// valid
if (!callDispatchMatched) {
LOG.error("Could not correlate acknowledgment with dispatched message: "
+ ack);
}
} else if (ack.isIndividualAck()) {
// Message was delivered and acknowledge - but only delete the
// individual message
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getLastMessageId().equals(messageId)) {
// this should never be within a transaction
dequeueCounter++;
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
destination = node.getRegionDestination();
acknowledge(context, ack, node);
dispatched.remove(node);
prefetchExtension = Math.max(0, prefetchExtension - 1);
callDispatchMatched = true;
break;
}
}
}else if (ack.isDeliveredAck()) {
// Message was delivered but not acknowledged: update pre-fetch
// counters.
int index = 0;
for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) {
final MessageReference node = iter.next();
if (node.isExpired()) {
if (broker.isExpired(node)) {
node.getRegionDestination().messageExpired(context, this, node);
}
dispatched.remove(node);
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
}
if (ack.getLastMessageId().equals(node.getMessageId())) {
if (usePrefetchExtension) {
prefetchExtension = Math.max(prefetchExtension, index + 1);
}
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
if (!callDispatchMatched) {
throw new JMSException(
"Could not correlate acknowledgment with dispatched message: "
+ ack);
}
} else if (ack.isRedeliveredAck()) {
// Message was re-delivered but it was not yet considered to be
// a DLQ message.
boolean inAckRange = false;
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null
|| ack.getFirstMessageId().equals(messageId)) {
inAckRange = true;
}
if (inAckRange) {
if (ack.getLastMessageId().equals(messageId)) {
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
}
if (!callDispatchMatched) {
throw new JMSException(
"Could not correlate acknowledgment with dispatched message: "
+ ack);
}
} else if (ack.isPoisonAck()) {
// TODO: what if the message is already in a DLQ???
// Handle the poison ACK case: we need to send the message to a
// DLQ
if (ack.isInTransaction()) {
throw new JMSException("Poison ack cannot be transacted: "
+ ack);
}
int index = 0;
boolean inAckRange = false;
List<MessageReference> removeList = new ArrayList<MessageReference>();
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null
|| ack.getFirstMessageId().equals(messageId)) {
inAckRange = true;
}
if (inAckRange) {
sendToDLQ(context, node);
node.getRegionDestination().getDestinationStatistics()
.getInflight().decrement();
removeList.add(node);
dequeueCounter++;
index++;
acknowledge(context, ack, node);
if (ack.getLastMessageId().equals(messageId)) {
prefetchExtension = Math.max(0, prefetchExtension
- (index + 1));
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
}
for (final MessageReference node : removeList) {
dispatched.remove(node);
}
if (!callDispatchMatched) {
throw new JMSException(
"Could not correlate acknowledgment with dispatched message: "
+ ack);
}
}
}
if (callDispatchMatched && destination != null) {
destination.wakeup();
dispatchPending();
} else {
if (isSlave()) {
throw new JMSException(
"Slave broker out of sync with master: Acknowledgment ("
+ ack + ") was not in the dispatch list: "
+ dispatched);
} else {
LOG.debug("Acknowledgment out of sync (Normally occurs when failover connection reconnects): "
+ ack);
}
}
}
| public final void acknowledge(final ConnectionContext context,final MessageAck ack) throws Exception {
// Handle the standard acknowledgment case.
boolean callDispatchMatched = false;
Destination destination = null;
if (!isSlave()) {
if (!okForAckAsDispatchDone.await(0l, TimeUnit.MILLISECONDS)) {
// suppress unexpected ack exception in this expected case
LOG.warn("Ignoring ack received before dispatch; result of failover with an outstanding ack. Acked messages will be replayed if present on this broker. Ignored ack: " + ack);
return;
}
}
if (LOG.isTraceEnabled()) {
LOG.trace("ack:" + ack);
}
synchronized(dispatchLock) {
if (ack.isStandardAck()) {
// First check if the ack matches the dispatched. When using failover this might
// not be the case. We don't ever want to ack the wrong messages.
assertAckMatchesDispatched(ack);
// Acknowledge all dispatched messages up till the message id of
// the acknowledgment.
int index = 0;
boolean inAckRange = false;
List<MessageReference> removeList = new ArrayList<MessageReference>();
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null
|| ack.getFirstMessageId().equals(messageId)) {
inAckRange = true;
}
if (inAckRange) {
// Don't remove the nodes until we are committed.
if (!context.isInTransaction()) {
dequeueCounter++;
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
removeList.add(node);
} else {
// setup a Synchronization to remove nodes from the
// dispatched list.
context.getTransaction().addSynchronization(
new Synchronization() {
@Override
public void afterCommit()
throws Exception {
synchronized(dispatchLock) {
dequeueCounter++;
dispatched.remove(node);
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
}
}
@Override
public void afterRollback() throws Exception {
synchronized(dispatchLock) {
if (isSlave()) {
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
} else {
// poisionAck will decrement - otherwise still inflight on client
}
}
}
});
}
index++;
acknowledge(context, ack, node);
if (ack.getLastMessageId().equals(messageId)) {
// contract prefetch if dispatch required a pull
if (getPrefetchSize() == 0) {
prefetchExtension = Math.max(0, prefetchExtension - index);
} else if (usePrefetchExtension && context.isInTransaction()) {
// extend prefetch window only if not a pulling consumer
prefetchExtension = Math.max(prefetchExtension, index);
}
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
}
for (final MessageReference node : removeList) {
dispatched.remove(node);
}
// this only happens after a reconnect - get an ack which is not
// valid
if (!callDispatchMatched) {
LOG.warn("Could not correlate acknowledgment with dispatched message: "
+ ack);
}
} else if (ack.isIndividualAck()) {
// Message was delivered and acknowledge - but only delete the
// individual message
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getLastMessageId().equals(messageId)) {
// this should never be within a transaction
dequeueCounter++;
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
destination = node.getRegionDestination();
acknowledge(context, ack, node);
dispatched.remove(node);
prefetchExtension = Math.max(0, prefetchExtension - 1);
callDispatchMatched = true;
break;
}
}
}else if (ack.isDeliveredAck()) {
// Message was delivered but not acknowledged: update pre-fetch
// counters.
int index = 0;
for (Iterator<MessageReference> iter = dispatched.iterator(); iter.hasNext(); index++) {
final MessageReference node = iter.next();
if (node.isExpired()) {
if (broker.isExpired(node)) {
node.getRegionDestination().messageExpired(context, this, node);
}
dispatched.remove(node);
node.getRegionDestination().getDestinationStatistics().getInflight().decrement();
}
if (ack.getLastMessageId().equals(node.getMessageId())) {
if (usePrefetchExtension) {
prefetchExtension = Math.max(prefetchExtension, index + 1);
}
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
if (!callDispatchMatched) {
throw new JMSException(
"Could not correlate acknowledgment with dispatched message: "
+ ack);
}
} else if (ack.isRedeliveredAck()) {
// Message was re-delivered but it was not yet considered to be
// a DLQ message.
boolean inAckRange = false;
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null
|| ack.getFirstMessageId().equals(messageId)) {
inAckRange = true;
}
if (inAckRange) {
if (ack.getLastMessageId().equals(messageId)) {
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
}
if (!callDispatchMatched) {
throw new JMSException(
"Could not correlate acknowledgment with dispatched message: "
+ ack);
}
} else if (ack.isPoisonAck()) {
// TODO: what if the message is already in a DLQ???
// Handle the poison ACK case: we need to send the message to a
// DLQ
if (ack.isInTransaction()) {
throw new JMSException("Poison ack cannot be transacted: "
+ ack);
}
int index = 0;
boolean inAckRange = false;
List<MessageReference> removeList = new ArrayList<MessageReference>();
for (final MessageReference node : dispatched) {
MessageId messageId = node.getMessageId();
if (ack.getFirstMessageId() == null
|| ack.getFirstMessageId().equals(messageId)) {
inAckRange = true;
}
if (inAckRange) {
sendToDLQ(context, node);
node.getRegionDestination().getDestinationStatistics()
.getInflight().decrement();
removeList.add(node);
dequeueCounter++;
index++;
acknowledge(context, ack, node);
if (ack.getLastMessageId().equals(messageId)) {
prefetchExtension = Math.max(0, prefetchExtension
- (index + 1));
destination = node.getRegionDestination();
callDispatchMatched = true;
break;
}
}
}
for (final MessageReference node : removeList) {
dispatched.remove(node);
}
if (!callDispatchMatched) {
throw new JMSException(
"Could not correlate acknowledgment with dispatched message: "
+ ack);
}
}
}
if (callDispatchMatched && destination != null) {
destination.wakeup();
dispatchPending();
} else {
if (isSlave()) {
throw new JMSException(
"Slave broker out of sync with master: Acknowledgment ("
+ ack + ") was not in the dispatch list: "
+ dispatched);
} else {
LOG.debug("Acknowledgment out of sync (Normally occurs when failover connection reconnects): "
+ ack);
}
}
}
|
diff --git a/wicket-contrib-dojo-examples/src/main/java/wicket/contrib/dojo/examples/SimpleAutoRefreshExample.java b/wicket-contrib-dojo-examples/src/main/java/wicket/contrib/dojo/examples/SimpleAutoRefreshExample.java
index c55d746a8..b95c93179 100644
--- a/wicket-contrib-dojo-examples/src/main/java/wicket/contrib/dojo/examples/SimpleAutoRefreshExample.java
+++ b/wicket-contrib-dojo-examples/src/main/java/wicket/contrib/dojo/examples/SimpleAutoRefreshExample.java
@@ -1,37 +1,38 @@
package wicket.contrib.dojo.examples;
import wicket.Component;
import wicket.contrib.dojo.autoupdate.DojoAutoUpdateHandler;
import wicket.markup.html.WebPage;
import wicket.markup.html.basic.Label;
import wicket.model.Model;
public class SimpleAutoRefreshExample extends WebPage {
Label label;
String display;
int timer;
public SimpleAutoRefreshExample() {
timer = 0;
updateTimer();
+ label = new Label(this, "label");
label.add(new DojoAutoUpdateHandler(1000){
@Override
protected void update(Component component) {
updateTimer();
component.setModel(new Model<String>(display));
}
});
}
public void updateTimer(){
display = "resfreshed " + timer + " time(s)";
timer++;
}
}
| true | true | public SimpleAutoRefreshExample() {
timer = 0;
updateTimer();
label.add(new DojoAutoUpdateHandler(1000){
@Override
protected void update(Component component) {
updateTimer();
component.setModel(new Model<String>(display));
}
});
}
| public SimpleAutoRefreshExample() {
timer = 0;
updateTimer();
label = new Label(this, "label");
label.add(new DojoAutoUpdateHandler(1000){
@Override
protected void update(Component component) {
updateTimer();
component.setModel(new Model<String>(display));
}
});
}
|
diff --git a/org.springframework.integration/src/main/java/org/springframework/integration/controlbus/ControlBus.java b/org.springframework.integration/src/main/java/org/springframework/integration/controlbus/ControlBus.java
index ce0e6cc382..a5da45deec 100644
--- a/org.springframework.integration/src/main/java/org/springframework/integration/controlbus/ControlBus.java
+++ b/org.springframework.integration/src/main/java/org/springframework/integration/controlbus/ControlBus.java
@@ -1,30 +1,30 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.controlbus;
import org.springframework.integration.channel.SubscribableChannel;
/**
* Defines base interface for implementation of the Control Bus EIP pattern ({@linkplain http://www.eaipatterns.com/ControlBus.html})
* Control Bus infrastructure is assembled with various components provided by the framework with the main entry point
* being {@link SubscribableChannel} making this interface more of a convenience wrapper over target {@link SubscribableChannel}
*
* @author Oleg Zhurakousky
* @since 2.0
*/
public interface ControlBus extends SubscribableChannel {
- public String getBusName();
+ public boolean isBusAvailable();
}
| true | true | public String getBusName();
| public boolean isBusAvailable();
|
diff --git a/src/com/modcrafting/diablodrops/commands/DiabloDropCommand.java b/src/com/modcrafting/diablodrops/commands/DiabloDropCommand.java
index 5997785..af22e43 100644
--- a/src/com/modcrafting/diablodrops/commands/DiabloDropCommand.java
+++ b/src/com/modcrafting/diablodrops/commands/DiabloDropCommand.java
@@ -1,406 +1,409 @@
package com.modcrafting.diablodrops.commands;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import com.modcrafting.diablodrops.DiabloDrops;
import com.modcrafting.diablodrops.items.IdentifyTome;
import com.modcrafting.diablodrops.items.Socket;
import com.modcrafting.diablodrops.sets.ArmorSet;
import com.modcrafting.diablodrops.tier.Tier;
public class DiabloDropCommand implements CommandExecutor
{
private final DiabloDrops plugin;
public DiabloDropCommand(final DiabloDrops plugin)
{
this.plugin = plugin;
}
public String combineSplit(final int startIndex, final String[] string,
final String seperator)
{
StringBuilder builder = new StringBuilder();
if (string.length >= 1)
{
for (int i = startIndex; i < string.length; i++)
{
builder.append(string[i]);
builder.append(seperator);
}
if (builder.length() > seperator.length())
{
builder.deleteCharAt(builder.length() - seperator.length()); // remove
return builder.toString();
}
}
return "";
}
@SuppressWarnings("deprecation")
@Override
public boolean onCommand(final CommandSender sender, final Command command,
final String commandLabel, final String[] args)
{
if (!(sender instanceof Player)
|| !sender.hasPermission(command.getPermission()))
{
sender.sendMessage(ChatColor.RED + "You cannot run this command.");
return true;
}
Player player = ((Player) sender);
PlayerInventory pi = player.getInventory();
switch (args.length)
{
case 0:
ItemStack ci = plugin.getDropAPI().getItem();
while (ci == null)
{
ci = plugin.getDropAPI().getItem();
}
pi.addItem(ci);
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
default:
if (args[0].equalsIgnoreCase("tome")
|| args[0].equalsIgnoreCase("book"))
{
pi.addItem(new IdentifyTome());
player.sendMessage(ChatColor.GREEN
+ "You have been given a tome.");
player.updateInventory();
return true;
}
if (args[0].equalsIgnoreCase("socket")
|| args[0].equalsIgnoreCase("socketitem"))
{
List<String> l = plugin.getConfig().getStringList(
"SocketItem.Items");
pi.addItem(new Socket(Material.valueOf(l.get(
plugin.getSingleRandom().nextInt(l.size()))
.toUpperCase())));
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a SocketItem.");
return true;
}
if (args[0].equalsIgnoreCase("custom"))
{
- pi.addItem(plugin.custom.get(plugin.getSingleRandom()
- .nextInt(plugin.custom.size())));
+ if (plugin.custom.size() > 0)
+ pi.addItem(plugin.custom.get(plugin.getSingleRandom()
+ .nextInt(plugin.custom.size())));
+ else
+ pi.addItem(plugin.getDropAPI().getItem());
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
if (args[0].equalsIgnoreCase("modify"))
{
if ((args.length < 2)
|| (player.getItemInHand() == null)
|| player.getItemInHand().getType()
.equals(Material.AIR))
return true;
ItemStack tool = player.getItemInHand();
ItemMeta meta = tool.getItemMeta();
if (args[1].equalsIgnoreCase("lore"))
{
if (args[2].equalsIgnoreCase("clear"))
{
meta.setLore(null);
tool.setItemMeta(meta);
player.sendMessage(ChatColor.GREEN
+ "Cleared the lore for the item!");
return true;
}
String lore = combineSplit(2, args, " ");
lore = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], lore);
meta.setLore(Arrays.asList(lore.split(",")));
tool.setItemMeta(meta);
player.sendMessage(ChatColor.GREEN
+ "Set the lore for the item!");
return true;
}
if (args[1].equalsIgnoreCase("name"))
{
if (args[2].equalsIgnoreCase("clear"))
{
tool.getItemMeta().setDisplayName(null);
player.sendMessage(ChatColor.GREEN
+ "Cleared the name for the item!");
return true;
}
String name = combineSplit(2, args, " ");
name = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], name);
meta.setDisplayName(name);
tool.setItemMeta(meta);
player.sendMessage(ChatColor.GREEN
+ "Set the name for the item!");
return true;
}
if (args[1].equalsIgnoreCase("enchant"))
{
if (args.length < 4)
{
if ((args.length == 3)
&& args[2].equalsIgnoreCase("clear"))
{
for (Enchantment e : Enchantment.values())
tool.getItemMeta().removeEnchant(e);
player.sendMessage(ChatColor.GREEN
+ "Cleared the enchantments for the item!");
return true;
}
player.sendMessage(ChatColor.RED
+ "Correct usage: /dd modify enchant"
+ " [enchantment name] [enchantment level]");
return true;
}
if (args[2].equalsIgnoreCase("add"))
{
if (args.length < 5)
return true;
int i = 1;
try
{
i = Integer.parseInt(args[4]);
}
catch (NumberFormatException nfe)
{
if (plugin.getDebug())
{
plugin.log.warning(nfe.getMessage());
}
}
Enchantment ech = Enchantment.getByName(args[3]
.toUpperCase());
if (ech != null)
{
player.getItemInHand().addUnsafeEnchantment(
ech, i);
player.sendMessage(ChatColor.GREEN
+ "Added enchantment.");
}
else
{
player.sendMessage(ChatColor.RED + args[3]
+ " :enchantment does not exist!");
}
return true;
}
if (args[2].equalsIgnoreCase("remove"))
{
ItemStack is = player.getItemInHand();
Map<Enchantment, Integer> hm = new HashMap<Enchantment, Integer>();
for (Enchantment e1 : is.getEnchantments().keySet())
{
if (!e1.getName().equalsIgnoreCase(args[3]))
{
hm.put(e1, is.getEnchantmentLevel(e1));
}
}
is.addUnsafeEnchantments(hm);
player.sendMessage(ChatColor.GREEN
+ "Removed enchantment.");
return true;
}
}
}
if (args[0].equalsIgnoreCase("reload")
&& sender.hasPermission("diablodrops.reload"))
{
plugin.getServer().getPluginManager().disablePlugin(plugin);
plugin.getServer().getPluginManager().enablePlugin(plugin);
plugin.reloadConfig();
plugin.getLogger().info("Reloaded");
sender.sendMessage(ChatColor.GREEN + "DiabloDrops Reloaded");
return true;
}
if (args[0].equalsIgnoreCase("repair"))
{
if (plugin.getDropAPI().canBeItem(
player.getItemInHand().getType()))
{
player.getItemInHand().setDurability((short) 0);
player.sendMessage(ChatColor.GREEN + "Item repaired.");
return true;
}
player.sendMessage("Unable to repair item.");
return true;
}
if (args[0].equalsIgnoreCase("debug"))
{
int customsize = plugin.custom.size();
plugin.getLogger().info(
customsize + "]: Custom Items Loaded.");
sender.sendMessage(customsize + "]: Custom Items Loaded.");
int armorsets = plugin.armorSets.size();
plugin.getLogger().info(armorsets + "]: ArmorSets Loaded.");
sender.sendMessage(armorsets + "]: ArmorSets Loaded.");
int tier = plugin.tiers.size();
plugin.getLogger().info(tier + "]: Tiers Loaded.");
sender.sendMessage(tier + "]: Tiers Loaded.");
int defaultP = plugin.prefix.size();
plugin.getLogger().info(
defaultP + "]: Default Prefixes Loaded.");
sender.sendMessage(defaultP + "]: Default Prefixes Loaded.");
int defaultS = plugin.suffix.size();
plugin.getLogger().info(
defaultS + "]: Default Suffixes Loaded.");
sender.sendMessage(defaultS + "]: Default Suffixes Loaded.");
int customP = plugin.hmprefix.size();
plugin.getLogger().info(
customP + "]: Custom Prefixes Loaded.");
sender.sendMessage(customP + "]: Custom Prefixes Loaded.");
int customS = plugin.hmsuffix.size();
plugin.getLogger().info(
customS + "]: Custom Suffixes Loaded.");
sender.sendMessage(customS + "]: Custom Suffixes Loaded.");
int dlore = plugin.defenselore.size();
plugin.getLogger().info(dlore + "]: Defense Lore Loaded.");
sender.sendMessage(dlore + "]: Defense Lore Loaded.");
int olore = plugin.offenselore.size();
plugin.getLogger().info(olore + "]: Offense Lore Loaded.");
sender.sendMessage(olore + "]: Offense Lore Loaded.");
int w = plugin.worlds.size();
plugin.getLogger().info(w + "]: Worlds allowing Loaded.");
sender.sendMessage(w + "]: Worlds allowing Loaded.");
if (args.length > 1)
{
if (args[1].equalsIgnoreCase("detailed"))
{
StringBuilder sb = new StringBuilder();
sb.append("\n");
sb.append("-----Custom-----");
sb.append("\n");
for (ItemStack tool : plugin.custom)
{
sb.append(tool.getItemMeta().getDisplayName()
+ " ");
}
sb.append("\n");
sb.append("-----ArmorSet-----");
sb.append("\n");
for (ArmorSet a : plugin.armorSets)
{
sb.append(a.getName() + " ");
}
sb.append("\n");
sb.append("-----Tiers-----");
sb.append("\n");
for (Tier a : plugin.tiers)
{
sb.append(a.getName() + " ");
}
sb.append("\n");
sb.append("-----DefaultPrefix-----");
sb.append("\n");
for (String s : plugin.prefix)
{
sb.append(s + " ");
}
sb.append("\n");
sb.append("-----DefaultSuffix-----");
sb.append("\n");
for (String s : plugin.suffix)
{
sb.append(s + " ");
}
sb.append("\n");
sb.append("-----CustomPrefix-----");
sb.append("\n");
for (Material m : plugin.hmprefix.keySet())
{
sb.append(m.toString() + "\n");
for (String p : plugin.hmprefix.get(m))
{
sb.append(p + " ");
}
}
sb.append("\n");
sb.append("-----CustomSuffix-----");
sb.append("\n");
for (Material m : plugin.hmsuffix.keySet())
{
sb.append(m.toString() + "\n");
for (String p : plugin.hmsuffix.get(m))
{
sb.append(p + " ");
}
}
sb.append("\n");
sb.append("-----Defense Lore-----");
sb.append("\n");
for (String s : plugin.defenselore)
{
sb.append(s + " ");
}
sb.append("\n");
sb.append("-----Offense Lore-----");
sb.append("\n");
for (String s : plugin.offenselore)
{
sb.append(s + " ");
}
plugin.getLogger().info(sb.toString());
}
}
return true;
}
if (args[0].equalsIgnoreCase("tier"))
{
Tier tier = plugin.getDropAPI().getTier(args[1]);
ItemStack ci2 = plugin.getDropAPI().getItem(tier);
while (ci2 == null)
{
ci2 = plugin.getDropAPI().getItem(tier);
}
pi.addItem(ci2);
player.updateInventory();
if (tier == null)
{
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
}
else
{
player.sendMessage(ChatColor.GREEN
+ "You have been given a " + tier.getColor()
+ tier.getName() + ChatColor.GREEN
+ " DiabloDrops item.");
}
return true;
}
ItemStack ci2 = plugin.getDropAPI().getItem();
while (ci2 == null)
{
ci2 = plugin.getDropAPI().getItem();
}
pi.addItem(ci2);
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
}
}
| true | true | public boolean onCommand(final CommandSender sender, final Command command,
final String commandLabel, final String[] args)
{
if (!(sender instanceof Player)
|| !sender.hasPermission(command.getPermission()))
{
sender.sendMessage(ChatColor.RED + "You cannot run this command.");
return true;
}
Player player = ((Player) sender);
PlayerInventory pi = player.getInventory();
switch (args.length)
{
case 0:
ItemStack ci = plugin.getDropAPI().getItem();
while (ci == null)
{
ci = plugin.getDropAPI().getItem();
}
pi.addItem(ci);
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
default:
if (args[0].equalsIgnoreCase("tome")
|| args[0].equalsIgnoreCase("book"))
{
pi.addItem(new IdentifyTome());
player.sendMessage(ChatColor.GREEN
+ "You have been given a tome.");
player.updateInventory();
return true;
}
if (args[0].equalsIgnoreCase("socket")
|| args[0].equalsIgnoreCase("socketitem"))
{
List<String> l = plugin.getConfig().getStringList(
"SocketItem.Items");
pi.addItem(new Socket(Material.valueOf(l.get(
plugin.getSingleRandom().nextInt(l.size()))
.toUpperCase())));
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a SocketItem.");
return true;
}
if (args[0].equalsIgnoreCase("custom"))
{
pi.addItem(plugin.custom.get(plugin.getSingleRandom()
.nextInt(plugin.custom.size())));
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
if (args[0].equalsIgnoreCase("modify"))
{
if ((args.length < 2)
|| (player.getItemInHand() == null)
|| player.getItemInHand().getType()
.equals(Material.AIR))
return true;
ItemStack tool = player.getItemInHand();
ItemMeta meta = tool.getItemMeta();
if (args[1].equalsIgnoreCase("lore"))
{
if (args[2].equalsIgnoreCase("clear"))
{
meta.setLore(null);
tool.setItemMeta(meta);
player.sendMessage(ChatColor.GREEN
+ "Cleared the lore for the item!");
return true;
}
String lore = combineSplit(2, args, " ");
lore = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], lore);
meta.setLore(Arrays.asList(lore.split(",")));
tool.setItemMeta(meta);
player.sendMessage(ChatColor.GREEN
+ "Set the lore for the item!");
return true;
}
if (args[1].equalsIgnoreCase("name"))
{
if (args[2].equalsIgnoreCase("clear"))
{
tool.getItemMeta().setDisplayName(null);
player.sendMessage(ChatColor.GREEN
+ "Cleared the name for the item!");
return true;
}
String name = combineSplit(2, args, " ");
name = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], name);
meta.setDisplayName(name);
tool.setItemMeta(meta);
player.sendMessage(ChatColor.GREEN
+ "Set the name for the item!");
return true;
}
if (args[1].equalsIgnoreCase("enchant"))
{
if (args.length < 4)
{
if ((args.length == 3)
&& args[2].equalsIgnoreCase("clear"))
{
for (Enchantment e : Enchantment.values())
tool.getItemMeta().removeEnchant(e);
player.sendMessage(ChatColor.GREEN
+ "Cleared the enchantments for the item!");
return true;
}
player.sendMessage(ChatColor.RED
+ "Correct usage: /dd modify enchant"
+ " [enchantment name] [enchantment level]");
return true;
}
if (args[2].equalsIgnoreCase("add"))
{
if (args.length < 5)
return true;
int i = 1;
try
{
i = Integer.parseInt(args[4]);
}
catch (NumberFormatException nfe)
{
if (plugin.getDebug())
{
plugin.log.warning(nfe.getMessage());
}
}
Enchantment ech = Enchantment.getByName(args[3]
.toUpperCase());
if (ech != null)
{
player.getItemInHand().addUnsafeEnchantment(
ech, i);
player.sendMessage(ChatColor.GREEN
+ "Added enchantment.");
}
else
{
player.sendMessage(ChatColor.RED + args[3]
+ " :enchantment does not exist!");
}
return true;
}
if (args[2].equalsIgnoreCase("remove"))
{
ItemStack is = player.getItemInHand();
Map<Enchantment, Integer> hm = new HashMap<Enchantment, Integer>();
for (Enchantment e1 : is.getEnchantments().keySet())
{
if (!e1.getName().equalsIgnoreCase(args[3]))
{
hm.put(e1, is.getEnchantmentLevel(e1));
}
}
is.addUnsafeEnchantments(hm);
player.sendMessage(ChatColor.GREEN
+ "Removed enchantment.");
return true;
}
}
}
if (args[0].equalsIgnoreCase("reload")
&& sender.hasPermission("diablodrops.reload"))
{
plugin.getServer().getPluginManager().disablePlugin(plugin);
plugin.getServer().getPluginManager().enablePlugin(plugin);
plugin.reloadConfig();
plugin.getLogger().info("Reloaded");
sender.sendMessage(ChatColor.GREEN + "DiabloDrops Reloaded");
return true;
}
if (args[0].equalsIgnoreCase("repair"))
{
if (plugin.getDropAPI().canBeItem(
player.getItemInHand().getType()))
{
player.getItemInHand().setDurability((short) 0);
player.sendMessage(ChatColor.GREEN + "Item repaired.");
return true;
}
player.sendMessage("Unable to repair item.");
return true;
}
if (args[0].equalsIgnoreCase("debug"))
{
int customsize = plugin.custom.size();
plugin.getLogger().info(
customsize + "]: Custom Items Loaded.");
sender.sendMessage(customsize + "]: Custom Items Loaded.");
int armorsets = plugin.armorSets.size();
plugin.getLogger().info(armorsets + "]: ArmorSets Loaded.");
sender.sendMessage(armorsets + "]: ArmorSets Loaded.");
int tier = plugin.tiers.size();
plugin.getLogger().info(tier + "]: Tiers Loaded.");
sender.sendMessage(tier + "]: Tiers Loaded.");
int defaultP = plugin.prefix.size();
plugin.getLogger().info(
defaultP + "]: Default Prefixes Loaded.");
sender.sendMessage(defaultP + "]: Default Prefixes Loaded.");
int defaultS = plugin.suffix.size();
plugin.getLogger().info(
defaultS + "]: Default Suffixes Loaded.");
sender.sendMessage(defaultS + "]: Default Suffixes Loaded.");
int customP = plugin.hmprefix.size();
plugin.getLogger().info(
customP + "]: Custom Prefixes Loaded.");
sender.sendMessage(customP + "]: Custom Prefixes Loaded.");
int customS = plugin.hmsuffix.size();
plugin.getLogger().info(
customS + "]: Custom Suffixes Loaded.");
sender.sendMessage(customS + "]: Custom Suffixes Loaded.");
int dlore = plugin.defenselore.size();
plugin.getLogger().info(dlore + "]: Defense Lore Loaded.");
sender.sendMessage(dlore + "]: Defense Lore Loaded.");
int olore = plugin.offenselore.size();
plugin.getLogger().info(olore + "]: Offense Lore Loaded.");
sender.sendMessage(olore + "]: Offense Lore Loaded.");
int w = plugin.worlds.size();
plugin.getLogger().info(w + "]: Worlds allowing Loaded.");
sender.sendMessage(w + "]: Worlds allowing Loaded.");
if (args.length > 1)
{
if (args[1].equalsIgnoreCase("detailed"))
{
StringBuilder sb = new StringBuilder();
sb.append("\n");
sb.append("-----Custom-----");
sb.append("\n");
for (ItemStack tool : plugin.custom)
{
sb.append(tool.getItemMeta().getDisplayName()
+ " ");
}
sb.append("\n");
sb.append("-----ArmorSet-----");
sb.append("\n");
for (ArmorSet a : plugin.armorSets)
{
sb.append(a.getName() + " ");
}
sb.append("\n");
sb.append("-----Tiers-----");
sb.append("\n");
for (Tier a : plugin.tiers)
{
sb.append(a.getName() + " ");
}
sb.append("\n");
sb.append("-----DefaultPrefix-----");
sb.append("\n");
for (String s : plugin.prefix)
{
sb.append(s + " ");
}
sb.append("\n");
sb.append("-----DefaultSuffix-----");
sb.append("\n");
for (String s : plugin.suffix)
{
sb.append(s + " ");
}
sb.append("\n");
sb.append("-----CustomPrefix-----");
sb.append("\n");
for (Material m : plugin.hmprefix.keySet())
{
sb.append(m.toString() + "\n");
for (String p : plugin.hmprefix.get(m))
{
sb.append(p + " ");
}
}
sb.append("\n");
sb.append("-----CustomSuffix-----");
sb.append("\n");
for (Material m : plugin.hmsuffix.keySet())
{
sb.append(m.toString() + "\n");
for (String p : plugin.hmsuffix.get(m))
{
sb.append(p + " ");
}
}
sb.append("\n");
sb.append("-----Defense Lore-----");
sb.append("\n");
for (String s : plugin.defenselore)
{
sb.append(s + " ");
}
sb.append("\n");
sb.append("-----Offense Lore-----");
sb.append("\n");
for (String s : plugin.offenselore)
{
sb.append(s + " ");
}
plugin.getLogger().info(sb.toString());
}
}
return true;
}
if (args[0].equalsIgnoreCase("tier"))
{
Tier tier = plugin.getDropAPI().getTier(args[1]);
ItemStack ci2 = plugin.getDropAPI().getItem(tier);
while (ci2 == null)
{
ci2 = plugin.getDropAPI().getItem(tier);
}
pi.addItem(ci2);
player.updateInventory();
if (tier == null)
{
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
}
else
{
player.sendMessage(ChatColor.GREEN
+ "You have been given a " + tier.getColor()
+ tier.getName() + ChatColor.GREEN
+ " DiabloDrops item.");
}
return true;
}
ItemStack ci2 = plugin.getDropAPI().getItem();
while (ci2 == null)
{
ci2 = plugin.getDropAPI().getItem();
}
pi.addItem(ci2);
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
}
| public boolean onCommand(final CommandSender sender, final Command command,
final String commandLabel, final String[] args)
{
if (!(sender instanceof Player)
|| !sender.hasPermission(command.getPermission()))
{
sender.sendMessage(ChatColor.RED + "You cannot run this command.");
return true;
}
Player player = ((Player) sender);
PlayerInventory pi = player.getInventory();
switch (args.length)
{
case 0:
ItemStack ci = plugin.getDropAPI().getItem();
while (ci == null)
{
ci = plugin.getDropAPI().getItem();
}
pi.addItem(ci);
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
default:
if (args[0].equalsIgnoreCase("tome")
|| args[0].equalsIgnoreCase("book"))
{
pi.addItem(new IdentifyTome());
player.sendMessage(ChatColor.GREEN
+ "You have been given a tome.");
player.updateInventory();
return true;
}
if (args[0].equalsIgnoreCase("socket")
|| args[0].equalsIgnoreCase("socketitem"))
{
List<String> l = plugin.getConfig().getStringList(
"SocketItem.Items");
pi.addItem(new Socket(Material.valueOf(l.get(
plugin.getSingleRandom().nextInt(l.size()))
.toUpperCase())));
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a SocketItem.");
return true;
}
if (args[0].equalsIgnoreCase("custom"))
{
if (plugin.custom.size() > 0)
pi.addItem(plugin.custom.get(plugin.getSingleRandom()
.nextInt(plugin.custom.size())));
else
pi.addItem(plugin.getDropAPI().getItem());
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
if (args[0].equalsIgnoreCase("modify"))
{
if ((args.length < 2)
|| (player.getItemInHand() == null)
|| player.getItemInHand().getType()
.equals(Material.AIR))
return true;
ItemStack tool = player.getItemInHand();
ItemMeta meta = tool.getItemMeta();
if (args[1].equalsIgnoreCase("lore"))
{
if (args[2].equalsIgnoreCase("clear"))
{
meta.setLore(null);
tool.setItemMeta(meta);
player.sendMessage(ChatColor.GREEN
+ "Cleared the lore for the item!");
return true;
}
String lore = combineSplit(2, args, " ");
lore = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], lore);
meta.setLore(Arrays.asList(lore.split(",")));
tool.setItemMeta(meta);
player.sendMessage(ChatColor.GREEN
+ "Set the lore for the item!");
return true;
}
if (args[1].equalsIgnoreCase("name"))
{
if (args[2].equalsIgnoreCase("clear"))
{
tool.getItemMeta().setDisplayName(null);
player.sendMessage(ChatColor.GREEN
+ "Cleared the name for the item!");
return true;
}
String name = combineSplit(2, args, " ");
name = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], name);
meta.setDisplayName(name);
tool.setItemMeta(meta);
player.sendMessage(ChatColor.GREEN
+ "Set the name for the item!");
return true;
}
if (args[1].equalsIgnoreCase("enchant"))
{
if (args.length < 4)
{
if ((args.length == 3)
&& args[2].equalsIgnoreCase("clear"))
{
for (Enchantment e : Enchantment.values())
tool.getItemMeta().removeEnchant(e);
player.sendMessage(ChatColor.GREEN
+ "Cleared the enchantments for the item!");
return true;
}
player.sendMessage(ChatColor.RED
+ "Correct usage: /dd modify enchant"
+ " [enchantment name] [enchantment level]");
return true;
}
if (args[2].equalsIgnoreCase("add"))
{
if (args.length < 5)
return true;
int i = 1;
try
{
i = Integer.parseInt(args[4]);
}
catch (NumberFormatException nfe)
{
if (plugin.getDebug())
{
plugin.log.warning(nfe.getMessage());
}
}
Enchantment ech = Enchantment.getByName(args[3]
.toUpperCase());
if (ech != null)
{
player.getItemInHand().addUnsafeEnchantment(
ech, i);
player.sendMessage(ChatColor.GREEN
+ "Added enchantment.");
}
else
{
player.sendMessage(ChatColor.RED + args[3]
+ " :enchantment does not exist!");
}
return true;
}
if (args[2].equalsIgnoreCase("remove"))
{
ItemStack is = player.getItemInHand();
Map<Enchantment, Integer> hm = new HashMap<Enchantment, Integer>();
for (Enchantment e1 : is.getEnchantments().keySet())
{
if (!e1.getName().equalsIgnoreCase(args[3]))
{
hm.put(e1, is.getEnchantmentLevel(e1));
}
}
is.addUnsafeEnchantments(hm);
player.sendMessage(ChatColor.GREEN
+ "Removed enchantment.");
return true;
}
}
}
if (args[0].equalsIgnoreCase("reload")
&& sender.hasPermission("diablodrops.reload"))
{
plugin.getServer().getPluginManager().disablePlugin(plugin);
plugin.getServer().getPluginManager().enablePlugin(plugin);
plugin.reloadConfig();
plugin.getLogger().info("Reloaded");
sender.sendMessage(ChatColor.GREEN + "DiabloDrops Reloaded");
return true;
}
if (args[0].equalsIgnoreCase("repair"))
{
if (plugin.getDropAPI().canBeItem(
player.getItemInHand().getType()))
{
player.getItemInHand().setDurability((short) 0);
player.sendMessage(ChatColor.GREEN + "Item repaired.");
return true;
}
player.sendMessage("Unable to repair item.");
return true;
}
if (args[0].equalsIgnoreCase("debug"))
{
int customsize = plugin.custom.size();
plugin.getLogger().info(
customsize + "]: Custom Items Loaded.");
sender.sendMessage(customsize + "]: Custom Items Loaded.");
int armorsets = plugin.armorSets.size();
plugin.getLogger().info(armorsets + "]: ArmorSets Loaded.");
sender.sendMessage(armorsets + "]: ArmorSets Loaded.");
int tier = plugin.tiers.size();
plugin.getLogger().info(tier + "]: Tiers Loaded.");
sender.sendMessage(tier + "]: Tiers Loaded.");
int defaultP = plugin.prefix.size();
plugin.getLogger().info(
defaultP + "]: Default Prefixes Loaded.");
sender.sendMessage(defaultP + "]: Default Prefixes Loaded.");
int defaultS = plugin.suffix.size();
plugin.getLogger().info(
defaultS + "]: Default Suffixes Loaded.");
sender.sendMessage(defaultS + "]: Default Suffixes Loaded.");
int customP = plugin.hmprefix.size();
plugin.getLogger().info(
customP + "]: Custom Prefixes Loaded.");
sender.sendMessage(customP + "]: Custom Prefixes Loaded.");
int customS = plugin.hmsuffix.size();
plugin.getLogger().info(
customS + "]: Custom Suffixes Loaded.");
sender.sendMessage(customS + "]: Custom Suffixes Loaded.");
int dlore = plugin.defenselore.size();
plugin.getLogger().info(dlore + "]: Defense Lore Loaded.");
sender.sendMessage(dlore + "]: Defense Lore Loaded.");
int olore = plugin.offenselore.size();
plugin.getLogger().info(olore + "]: Offense Lore Loaded.");
sender.sendMessage(olore + "]: Offense Lore Loaded.");
int w = plugin.worlds.size();
plugin.getLogger().info(w + "]: Worlds allowing Loaded.");
sender.sendMessage(w + "]: Worlds allowing Loaded.");
if (args.length > 1)
{
if (args[1].equalsIgnoreCase("detailed"))
{
StringBuilder sb = new StringBuilder();
sb.append("\n");
sb.append("-----Custom-----");
sb.append("\n");
for (ItemStack tool : plugin.custom)
{
sb.append(tool.getItemMeta().getDisplayName()
+ " ");
}
sb.append("\n");
sb.append("-----ArmorSet-----");
sb.append("\n");
for (ArmorSet a : plugin.armorSets)
{
sb.append(a.getName() + " ");
}
sb.append("\n");
sb.append("-----Tiers-----");
sb.append("\n");
for (Tier a : plugin.tiers)
{
sb.append(a.getName() + " ");
}
sb.append("\n");
sb.append("-----DefaultPrefix-----");
sb.append("\n");
for (String s : plugin.prefix)
{
sb.append(s + " ");
}
sb.append("\n");
sb.append("-----DefaultSuffix-----");
sb.append("\n");
for (String s : plugin.suffix)
{
sb.append(s + " ");
}
sb.append("\n");
sb.append("-----CustomPrefix-----");
sb.append("\n");
for (Material m : plugin.hmprefix.keySet())
{
sb.append(m.toString() + "\n");
for (String p : plugin.hmprefix.get(m))
{
sb.append(p + " ");
}
}
sb.append("\n");
sb.append("-----CustomSuffix-----");
sb.append("\n");
for (Material m : plugin.hmsuffix.keySet())
{
sb.append(m.toString() + "\n");
for (String p : plugin.hmsuffix.get(m))
{
sb.append(p + " ");
}
}
sb.append("\n");
sb.append("-----Defense Lore-----");
sb.append("\n");
for (String s : plugin.defenselore)
{
sb.append(s + " ");
}
sb.append("\n");
sb.append("-----Offense Lore-----");
sb.append("\n");
for (String s : plugin.offenselore)
{
sb.append(s + " ");
}
plugin.getLogger().info(sb.toString());
}
}
return true;
}
if (args[0].equalsIgnoreCase("tier"))
{
Tier tier = plugin.getDropAPI().getTier(args[1]);
ItemStack ci2 = plugin.getDropAPI().getItem(tier);
while (ci2 == null)
{
ci2 = plugin.getDropAPI().getItem(tier);
}
pi.addItem(ci2);
player.updateInventory();
if (tier == null)
{
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
}
else
{
player.sendMessage(ChatColor.GREEN
+ "You have been given a " + tier.getColor()
+ tier.getName() + ChatColor.GREEN
+ " DiabloDrops item.");
}
return true;
}
ItemStack ci2 = plugin.getDropAPI().getItem();
while (ci2 == null)
{
ci2 = plugin.getDropAPI().getItem();
}
pi.addItem(ci2);
player.updateInventory();
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
}
|
diff --git a/src/main/java/com/sobey/cmop/mvc/web/operate/OperateController.java b/src/main/java/com/sobey/cmop/mvc/web/operate/OperateController.java
index 214be3b..950ff9c 100644
--- a/src/main/java/com/sobey/cmop/mvc/web/operate/OperateController.java
+++ b/src/main/java/com/sobey/cmop/mvc/web/operate/OperateController.java
@@ -1,311 +1,309 @@
package com.sobey.cmop.mvc.web.operate;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.sobey.cmop.mvc.comm.BaseController;
import com.sobey.cmop.mvc.constant.RedmineConstant;
import com.sobey.cmop.mvc.entity.ComputeItem;
import com.sobey.cmop.mvc.entity.NetworkEipItem;
import com.sobey.cmop.mvc.entity.NetworkElbItem;
import com.sobey.cmop.mvc.entity.RedmineIssue;
import com.sobey.cmop.mvc.entity.StorageItem;
import com.sobey.cmop.mvc.service.redmine.RedmineService;
import com.sobey.framework.utils.Servlets;
import com.taskadapter.redmineapi.bean.Issue;
import com.taskadapter.redmineapi.bean.Project;
import com.taskadapter.redmineapi.bean.User;
/**
* OperateController负责工单的管理
*
* @author liukai
*
*/
@Controller
@RequestMapping(value = "/operate")
public class OperateController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(OperateController.class);
private static final String REDIRECT_SUCCESS_URL = "redirect:/operate/";
/**
* 显示指派给自己的工单operate list
*/
@RequestMapping(value = { "list", "" })
public String assigned(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize, Model model,
ServletRequest request) {
Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, REQUEST_PREFIX);
model.addAttribute("page", comm.operateService.getAssignedIssuePageable(searchParams, pageNumber, pageSize));
// 将搜索条件编码成字符串,分页的URL
model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, REQUEST_PREFIX));
// 跳转到reported
model.addAttribute("toReported", "toReported");
return "operate/operateList";
}
/**
* 显示所有的工单operate list
*/
@RequestMapping(value = "reported")
public String reported(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize, Model model,
ServletRequest request) {
Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, REQUEST_PREFIX);
model.addAttribute("page", comm.operateService.getReportedIssuePageable(searchParams, pageNumber, pageSize));
// 将搜索条件编码成字符串,分页的URL
model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, REQUEST_PREFIX));
return "operate/operateList";
}
/**
* 跳转到更新页面,并替换掉redmine文本中的ip.(100%流程后无法替换.)
*
* @param id
* @param model
* @param redirectAttributes
* @return
*/
@RequestMapping(value = "update/{id}")
public String update(@PathVariable("id") Integer id, Model model, RedirectAttributes redirectAttributes) {
logger.info("--->工单处理...issueId=" + id);
Issue issue = RedmineService.getIssue(id);
model.addAttribute("issue", issue);
model.addAttribute("user", comm.accountService.getCurrentUser());
RedmineIssue redmineIssue = comm.operateService.findByIssueId(id);
model.addAttribute("redmineIssue", redmineIssue);
if (issue != null) {
String desc = issue.getDescription();
desc = desc.replaceAll("\\*服务申请的详细信息\\*", "");
desc = desc.replaceAll("\\*服务变更的详细信息\\*", "");
- desc = desc.replaceAll("\\*", "");
- desc = desc.replaceAll("\\+", "");
if (desc.indexOf("# 基本信息") >= 0) {
desc = desc.replaceAll("# 基本信息", "<br># 基本信息");
} else {
desc = "<br>" + desc;
}
// 更新写入Redmine的IP
List list = comm.operateService.getComputeStorageElbEip(redmineIssue);
List<ComputeItem> computeList = (List) list.get(0);
List<StorageItem> storageList = (List) list.get(1);
List<NetworkElbItem> networkElbList = (List) list.get(2);
List<NetworkEipItem> networkEipList = (List) list.get(3);
// oldIP替换分配的IP.
logger.info("--->更新写入Redmine的IP(计算资源)..." + computeList.size());
desc = this.replaceComputeTextFromOldIpToInnerIp(desc, computeList);
logger.info("--->更新写入Redmine的IP(EIP)..." + networkEipList.size());
desc = this.replaceEIPTextFromOldIpToInnerIp(desc, networkEipList);
logger.info("--->更新写入Redmine的IP(ELB)..." + networkElbList.size());
desc = this.replaceELBTextFromOldIpToInnerIp(desc, networkElbList);
model.addAttribute("description", desc);
if (!computeList.isEmpty()) {
model.addAttribute("computeList", computeList);
int poolType = 0;
logger.info("--->has compute: " + computeList.size() + ",poolType=" + poolType);
model.addAttribute("server", comm.operateService.findHostMapByServerType(2)); // 物理机
model.addAttribute("hostServer", comm.operateService.findHostMapByServerType(1));
model.addAttribute("osStorage", comm.oneCmdbUtilService.getOsStorageFromOnecmdb());
}
if (!storageList.isEmpty()) {
model.addAttribute("storageList", storageList);
model.addAttribute("fimasController", comm.oneCmdbUtilService.getFimasHardWareFromOnecmdb());
model.addAttribute("netappController", comm.oneCmdbUtilService.getNfsHardWareFromOnecmdb());
}
if (!networkEipList.isEmpty()) {
model.addAttribute("eipList", networkEipList);
logger.info("--->has eip: " + networkEipList.size());
model.addAttribute("telecomIpPool", comm.operateService.getAllIpPoolByPoolType(3));
}
if (!networkElbList.isEmpty()) {
model.addAttribute("elbList", networkElbList);
// 暂不处理ELB的虚拟IP池
}
model.addAttribute("location", comm.operateService.getLocationFromOnecmdb());
model.addAttribute("vlan", comm.operateService.getVlanFromOnecmdb());
return "operate/operateForm";
} else {
// 查询Redmine中的Issue信息失败
redirectAttributes.addFlashAttribute("message", "查询工单信息失败,请稍后重试!");
return "redirect:/operate";
}
}
/**
* 将redmine文本中Compute的oldIP替换成已经分配的IP.
*
* @param desc
* @param computeList
* @return
*/
private String replaceComputeTextFromOldIpToInnerIp(String desc, List<ComputeItem> computeList) {
int size = computeList.size();
String[] searchList = new String[size];
String[] replacementList = new String[size];
for (int i = 0; i < computeList.size(); i++) {
searchList[i] = computeList.get(i).getIdentifier() + "(" + computeList.get(i).getRemark() + " - "
+ computeList.get(i).getOldIp() + ")";
replacementList[i] = computeList.get(i).getIdentifier() + "(" + computeList.get(i).getRemark() + " - "
+ computeList.get(i).getInnerIp() + ")";
}
return StringUtils.replaceEach(desc, searchList, replacementList);
}
/**
* 将redmine文本中EIP的oldIP替换成已经分配的IP.
*
* @param desc
* @param networkEipList
* @return
*/
private String replaceEIPTextFromOldIpToInnerIp(String desc, List<NetworkEipItem> networkEipList) {
int size = networkEipList.size();
String[] searchList = new String[size];
String[] replacementList = new String[size];
for (int i = 0; i < networkEipList.size(); i++) {
searchList[i] = networkEipList.get(i).getIdentifier() + "(" + networkEipList.get(i).getOldIp() + ")";
replacementList[i] = networkEipList.get(i).getIdentifier() + "(" + networkEipList.get(i).getIpAddress()
+ ")";
}
return StringUtils.replaceEach(desc, searchList, replacementList);
}
/**
* 将redmine文本中ELB的oldIP替换成已经分配的IP.
*
* @param desc
* @param networkElbList
* @return
*/
private String replaceELBTextFromOldIpToInnerIp(String desc, List<NetworkElbItem> networkElbList) {
int size = networkElbList.size();
String[] searchList = new String[size];
String[] replacementList = new String[size];
for (int i = 0; i < networkElbList.size(); i++) {
searchList[i] = networkElbList.get(i).getIdentifier() + "(" + networkElbList.get(i).getOldIp() + ")";
replacementList[i] = networkElbList.get(i).getIdentifier() + "(" + networkElbList.get(i).getVirtualIp()
+ ")";
}
return StringUtils.replaceEach(desc, searchList, replacementList);
}
/**
* 更新工单
*
* @param id
* @param authorId
* @param priority
* @param assignTo
* @param projectId
* @param doneRatio
* @param estimatedHours
* @param dueDate
* @param note
* @param redirectAttributes
* @return
*/
@RequestMapping(value = "update")
public String updateForm(@RequestParam(value = "issueId") int issueId, @RequestParam("projectId") int projectId,
@RequestParam("note") String note, @RequestParam("priority") int priority,
@RequestParam("authorId") int authorId, @RequestParam("assignTo") int assignTo,
@RequestParam("dueDate") String dueDate, @RequestParam("estimatedHours") float estimatedHours,
@RequestParam("doneRatio") int doneRatio, @RequestParam("computes") String computes,
@RequestParam("storages") String storages, @RequestParam("hostNames") String hostNames,
@RequestParam("serverAlias") String serverAlias, @RequestParam("osStorageAlias") String osStorageAlias,
@RequestParam("controllerAlias") String controllerAlias, @RequestParam("volumes") String volumes,
@RequestParam("innerIps") String innerIps, @RequestParam("eipIds") String eipIds,
@RequestParam("eipAddresss") String eipAddresss, @RequestParam("locationAlias") String locationAlias,
@RequestParam("elbIds") String elbIds, @RequestParam("virtualIps") String virtualIps,
RedirectAttributes redirectAttributes) {
logger.info("[issueId,projectId,priority,assignTo,dueDate,estimatedHours,doneRatio,note]:" + issueId + ","
+ projectId + "," + priority + "," + assignTo + "," + dueDate + "," + estimatedHours + "," + doneRatio
+ "," + note);
logger.info("[computes,storages,hostNames,serverAlias,osStorageAlias,controllerAlias, volumes]:" + computes
+ "|" + storages + "|" + hostNames + "|" + serverAlias + "|" + osStorageAlias + "|" + controllerAlias
+ "|" + volumes);
logger.info("[innerIps,eipIds,eipAddresss,locationAlias,elbIds,virtualIps]:" + innerIps + "|" + eipIds + "|"
+ eipAddresss + "|" + locationAlias + "|" + elbIds + "|" + virtualIps);
Issue issue = RedmineService.getIssue(issueId);
// 此处的User是redmine中的User对象.
User assignee = new User();
assignee.setId(assignTo);
User author = new User();
author.setId(authorId);
Project project = new Project();
project.setId(projectId);
// 当完成度为100时,设置状态 statusId 为 5.关闭; 其它完成度则为 2.处理中.
Integer statusId = RedmineConstant.MAX_DONERATIO.equals(doneRatio) ? RedmineConstant.Status.关闭.toInteger()
: RedmineConstant.Status.处理中.toInteger();
issue.setAssignee(assignee);// 指派给
issue.setDoneRatio(doneRatio);// 完成率
issue.setStatusId(statusId); // 设置状态
issue.setStatusName(RedmineConstant.Status.get(statusId)); // 设置状态名称
issue.setDueDate(new Date()); // 完成期限
issue.setEstimatedHours(new Float(estimatedHours)); // 耗费时间
issue.setNotes(note); // 描述
issue.setPriorityId(priority); // 优先级
issue.setProject(project); // 所属项目
issue.setAuthor(author); // issue作者
// TODO 还有IP分配等功能,待以后完成.
boolean result = comm.operateService.updateOperate(issue, computes, storages, hostNames, serverAlias,
osStorageAlias, controllerAlias, volumes, innerIps, eipIds, eipAddresss, locationAlias, elbIds,
virtualIps);
String message = result ? "工单更新成功!" : "工单更新失败,请稍后重试或联系管理员!";
redirectAttributes.addFlashAttribute("message", message);
return REDIRECT_SUCCESS_URL;
}
}
| true | true | public String update(@PathVariable("id") Integer id, Model model, RedirectAttributes redirectAttributes) {
logger.info("--->工单处理...issueId=" + id);
Issue issue = RedmineService.getIssue(id);
model.addAttribute("issue", issue);
model.addAttribute("user", comm.accountService.getCurrentUser());
RedmineIssue redmineIssue = comm.operateService.findByIssueId(id);
model.addAttribute("redmineIssue", redmineIssue);
if (issue != null) {
String desc = issue.getDescription();
desc = desc.replaceAll("\\*服务申请的详细信息\\*", "");
desc = desc.replaceAll("\\*服务变更的详细信息\\*", "");
desc = desc.replaceAll("\\*", "");
desc = desc.replaceAll("\\+", "");
if (desc.indexOf("# 基本信息") >= 0) {
desc = desc.replaceAll("# 基本信息", "<br># 基本信息");
} else {
desc = "<br>" + desc;
}
// 更新写入Redmine的IP
List list = comm.operateService.getComputeStorageElbEip(redmineIssue);
List<ComputeItem> computeList = (List) list.get(0);
List<StorageItem> storageList = (List) list.get(1);
List<NetworkElbItem> networkElbList = (List) list.get(2);
List<NetworkEipItem> networkEipList = (List) list.get(3);
// oldIP替换分配的IP.
logger.info("--->更新写入Redmine的IP(计算资源)..." + computeList.size());
desc = this.replaceComputeTextFromOldIpToInnerIp(desc, computeList);
logger.info("--->更新写入Redmine的IP(EIP)..." + networkEipList.size());
desc = this.replaceEIPTextFromOldIpToInnerIp(desc, networkEipList);
logger.info("--->更新写入Redmine的IP(ELB)..." + networkElbList.size());
desc = this.replaceELBTextFromOldIpToInnerIp(desc, networkElbList);
model.addAttribute("description", desc);
if (!computeList.isEmpty()) {
model.addAttribute("computeList", computeList);
int poolType = 0;
logger.info("--->has compute: " + computeList.size() + ",poolType=" + poolType);
model.addAttribute("server", comm.operateService.findHostMapByServerType(2)); // 物理机
model.addAttribute("hostServer", comm.operateService.findHostMapByServerType(1));
model.addAttribute("osStorage", comm.oneCmdbUtilService.getOsStorageFromOnecmdb());
}
if (!storageList.isEmpty()) {
model.addAttribute("storageList", storageList);
model.addAttribute("fimasController", comm.oneCmdbUtilService.getFimasHardWareFromOnecmdb());
model.addAttribute("netappController", comm.oneCmdbUtilService.getNfsHardWareFromOnecmdb());
}
if (!networkEipList.isEmpty()) {
model.addAttribute("eipList", networkEipList);
logger.info("--->has eip: " + networkEipList.size());
model.addAttribute("telecomIpPool", comm.operateService.getAllIpPoolByPoolType(3));
}
if (!networkElbList.isEmpty()) {
model.addAttribute("elbList", networkElbList);
// 暂不处理ELB的虚拟IP池
}
model.addAttribute("location", comm.operateService.getLocationFromOnecmdb());
model.addAttribute("vlan", comm.operateService.getVlanFromOnecmdb());
return "operate/operateForm";
} else {
// 查询Redmine中的Issue信息失败
redirectAttributes.addFlashAttribute("message", "查询工单信息失败,请稍后重试!");
return "redirect:/operate";
}
}
| public String update(@PathVariable("id") Integer id, Model model, RedirectAttributes redirectAttributes) {
logger.info("--->工单处理...issueId=" + id);
Issue issue = RedmineService.getIssue(id);
model.addAttribute("issue", issue);
model.addAttribute("user", comm.accountService.getCurrentUser());
RedmineIssue redmineIssue = comm.operateService.findByIssueId(id);
model.addAttribute("redmineIssue", redmineIssue);
if (issue != null) {
String desc = issue.getDescription();
desc = desc.replaceAll("\\*服务申请的详细信息\\*", "");
desc = desc.replaceAll("\\*服务变更的详细信息\\*", "");
if (desc.indexOf("# 基本信息") >= 0) {
desc = desc.replaceAll("# 基本信息", "<br># 基本信息");
} else {
desc = "<br>" + desc;
}
// 更新写入Redmine的IP
List list = comm.operateService.getComputeStorageElbEip(redmineIssue);
List<ComputeItem> computeList = (List) list.get(0);
List<StorageItem> storageList = (List) list.get(1);
List<NetworkElbItem> networkElbList = (List) list.get(2);
List<NetworkEipItem> networkEipList = (List) list.get(3);
// oldIP替换分配的IP.
logger.info("--->更新写入Redmine的IP(计算资源)..." + computeList.size());
desc = this.replaceComputeTextFromOldIpToInnerIp(desc, computeList);
logger.info("--->更新写入Redmine的IP(EIP)..." + networkEipList.size());
desc = this.replaceEIPTextFromOldIpToInnerIp(desc, networkEipList);
logger.info("--->更新写入Redmine的IP(ELB)..." + networkElbList.size());
desc = this.replaceELBTextFromOldIpToInnerIp(desc, networkElbList);
model.addAttribute("description", desc);
if (!computeList.isEmpty()) {
model.addAttribute("computeList", computeList);
int poolType = 0;
logger.info("--->has compute: " + computeList.size() + ",poolType=" + poolType);
model.addAttribute("server", comm.operateService.findHostMapByServerType(2)); // 物理机
model.addAttribute("hostServer", comm.operateService.findHostMapByServerType(1));
model.addAttribute("osStorage", comm.oneCmdbUtilService.getOsStorageFromOnecmdb());
}
if (!storageList.isEmpty()) {
model.addAttribute("storageList", storageList);
model.addAttribute("fimasController", comm.oneCmdbUtilService.getFimasHardWareFromOnecmdb());
model.addAttribute("netappController", comm.oneCmdbUtilService.getNfsHardWareFromOnecmdb());
}
if (!networkEipList.isEmpty()) {
model.addAttribute("eipList", networkEipList);
logger.info("--->has eip: " + networkEipList.size());
model.addAttribute("telecomIpPool", comm.operateService.getAllIpPoolByPoolType(3));
}
if (!networkElbList.isEmpty()) {
model.addAttribute("elbList", networkElbList);
// 暂不处理ELB的虚拟IP池
}
model.addAttribute("location", comm.operateService.getLocationFromOnecmdb());
model.addAttribute("vlan", comm.operateService.getVlanFromOnecmdb());
return "operate/operateForm";
} else {
// 查询Redmine中的Issue信息失败
redirectAttributes.addFlashAttribute("message", "查询工单信息失败,请稍后重试!");
return "redirect:/operate";
}
}
|
diff --git a/src/com/android/email/MessagingController.java b/src/com/android/email/MessagingController.java
index 02996f98..a706ab92 100644
--- a/src/com/android/email/MessagingController.java
+++ b/src/com/android/email/MessagingController.java
@@ -1,2107 +1,2112 @@
/*
* Copyright (C) 2008 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.email;
import com.android.email.mail.FetchProfile;
import com.android.email.mail.Flag;
import com.android.email.mail.Folder;
import com.android.email.mail.Message;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Part;
import com.android.email.mail.Sender;
import com.android.email.mail.Store;
import com.android.email.mail.StoreSynchronizer;
import com.android.email.mail.Folder.FolderType;
import com.android.email.mail.Folder.MessageRetrievalListener;
import com.android.email.mail.Folder.OpenMode;
import com.android.email.mail.internet.MimeBodyPart;
import com.android.email.mail.internet.MimeHeader;
import com.android.email.mail.internet.MimeMultipart;
import com.android.email.mail.internet.MimeUtility;
import com.android.email.provider.AttachmentProvider;
import com.android.email.provider.EmailContent;
import com.android.email.provider.EmailContent.Attachment;
import com.android.email.provider.EmailContent.AttachmentColumns;
import com.android.email.provider.EmailContent.Mailbox;
import com.android.email.provider.EmailContent.MailboxColumns;
import com.android.email.provider.EmailContent.MessageColumns;
import com.android.email.provider.EmailContent.SyncColumns;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Process;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Starts a long running (application) Thread that will run through commands
* that require remote mailbox access. This class is used to serialize and
* prioritize these commands. Each method that will submit a command requires a
* MessagingListener instance to be provided. It is expected that that listener
* has also been added as a registered listener using addListener(). When a
* command is to be executed, if the listener that was provided with the command
* is no longer registered the command is skipped. The design idea for the above
* is that when an Activity starts it registers as a listener. When it is paused
* it removes itself. Thus, any commands that that activity submitted are
* removed from the queue once the activity is no longer active.
*/
public class MessagingController implements Runnable {
/**
* The maximum message size that we'll consider to be "small". A small message is downloaded
* in full immediately instead of in pieces. Anything over this size will be downloaded in
* pieces with attachments being left off completely and downloaded on demand.
*
*
* 25k for a "small" message was picked by educated trial and error.
* http://answers.google.com/answers/threadview?id=312463 claims that the
* average size of an email is 59k, which I feel is too large for our
* blind download. The following tests were performed on a download of
* 25 random messages.
* <pre>
* 5k - 61 seconds,
* 25k - 51 seconds,
* 55k - 53 seconds,
* </pre>
* So 25k gives good performance and a reasonable data footprint. Sounds good to me.
*/
private static final int MAX_SMALL_MESSAGE_SIZE = (25 * 1024);
private static final Flag[] FLAG_LIST_SEEN = new Flag[] { Flag.SEEN };
private static final Flag[] FLAG_LIST_FLAGGED = new Flag[] { Flag.FLAGGED };
/**
* We write this into the serverId field of messages that will never be upsynced.
*/
private static final String LOCAL_SERVERID_PREFIX = "Local-";
/**
* Projections & CVs used by pruneCachedAttachments
*/
private static final String[] PRUNE_ATTACHMENT_PROJECTION = new String[] {
AttachmentColumns.LOCATION
};
private static final ContentValues PRUNE_ATTACHMENT_CV = new ContentValues();
static {
PRUNE_ATTACHMENT_CV.putNull(AttachmentColumns.CONTENT_URI);
}
private static MessagingController sInstance = null;
private final BlockingQueue<Command> mCommands = new LinkedBlockingQueue<Command>();
private final Thread mThread;
/**
* All access to mListeners *must* be synchronized
*/
private final GroupMessagingListener mListeners = new GroupMessagingListener();
private boolean mBusy;
private final Context mContext;
private final Controller mController;
protected MessagingController(Context _context, Controller _controller) {
mContext = _context.getApplicationContext();
mController = _controller;
mThread = new Thread(this);
mThread.start();
}
/**
* Gets or creates the singleton instance of MessagingController. Application is used to
* provide a Context to classes that need it.
*/
public synchronized static MessagingController getInstance(Context _context,
Controller _controller) {
if (sInstance == null) {
sInstance = new MessagingController(_context, _controller);
}
return sInstance;
}
/**
* Inject a mock controller. Used only for testing. Affects future calls to getInstance().
*/
public static void injectMockController(MessagingController mockController) {
sInstance = mockController;
}
// TODO: seems that this reading of mBusy isn't thread-safe
public boolean isBusy() {
return mBusy;
}
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
// TODO: add an end test to this infinite loop
while (true) {
Command command;
try {
command = mCommands.take();
} catch (InterruptedException e) {
continue; //re-test the condition on the eclosing while
}
if (command.listener == null || isActiveListener(command.listener)) {
mBusy = true;
command.runnable.run();
mListeners.controllerCommandCompleted(mCommands.size() > 0);
}
mBusy = false;
}
}
private void put(String description, MessagingListener listener, Runnable runnable) {
try {
Command command = new Command();
command.listener = listener;
command.runnable = runnable;
command.description = description;
mCommands.add(command);
}
catch (IllegalStateException ie) {
throw new Error(ie);
}
}
public void addListener(MessagingListener listener) {
mListeners.addListener(listener);
}
public void removeListener(MessagingListener listener) {
mListeners.removeListener(listener);
}
private boolean isActiveListener(MessagingListener listener) {
return mListeners.isActiveListener(listener);
}
/**
* Lightweight class for capturing local mailboxes in an account. Just the columns
* necessary for a sync.
*/
private static class LocalMailboxInfo {
private static final int COLUMN_ID = 0;
private static final int COLUMN_DISPLAY_NAME = 1;
private static final int COLUMN_ACCOUNT_KEY = 2;
private static final int COLUMN_TYPE = 3;
private static final String[] PROJECTION = new String[] {
EmailContent.RECORD_ID,
MailboxColumns.DISPLAY_NAME, MailboxColumns.ACCOUNT_KEY, MailboxColumns.TYPE,
};
final long mId;
final String mDisplayName;
final long mAccountKey;
final int mType;
public LocalMailboxInfo(Cursor c) {
mId = c.getLong(COLUMN_ID);
mDisplayName = c.getString(COLUMN_DISPLAY_NAME);
mAccountKey = c.getLong(COLUMN_ACCOUNT_KEY);
mType = c.getInt(COLUMN_TYPE);
}
}
/**
* Lists folders that are available locally and remotely. This method calls
* listFoldersCallback for local folders before it returns, and then for
* remote folders at some later point. If there are no local folders
* includeRemote is forced by this method. This method should be called from
* a Thread as it may take several seconds to list the local folders.
*
* TODO this needs to cache the remote folder list
* TODO break out an inner listFoldersSynchronized which could simplify checkMail
*
* @param account
* @param listener
* @throws MessagingException
*/
public void listFolders(final long accountId, MessagingListener listener) {
final EmailContent.Account account =
EmailContent.Account.restoreAccountWithId(mContext, accountId);
if (account == null) {
return;
}
mListeners.listFoldersStarted(accountId);
put("listFolders", listener, new Runnable() {
public void run() {
Cursor localFolderCursor = null;
try {
// Step 1: Get remote folders, make a list, and add any local folders
// that don't already exist.
Store store = Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder[] remoteFolders = store.getPersonalNamespaces();
HashSet<String> remoteFolderNames = new HashSet<String>();
for (int i = 0, count = remoteFolders.length; i < count; i++) {
remoteFolderNames.add(remoteFolders[i].getName());
}
HashMap<String, LocalMailboxInfo> localFolders =
new HashMap<String, LocalMailboxInfo>();
HashSet<String> localFolderNames = new HashSet<String>();
localFolderCursor = mContext.getContentResolver().query(
EmailContent.Mailbox.CONTENT_URI,
LocalMailboxInfo.PROJECTION,
EmailContent.MailboxColumns.ACCOUNT_KEY + "=?",
new String[] { String.valueOf(account.mId) },
null);
while (localFolderCursor.moveToNext()) {
LocalMailboxInfo info = new LocalMailboxInfo(localFolderCursor);
localFolders.put(info.mDisplayName, info);
localFolderNames.add(info.mDisplayName);
}
// Short circuit the rest if the sets are the same (the usual case)
if (!remoteFolderNames.equals(localFolderNames)) {
// They are different, so we have to do some adds and drops
// Drops first, to make things smaller rather than larger
HashSet<String> localsToDrop = new HashSet<String>(localFolderNames);
localsToDrop.removeAll(remoteFolderNames);
for (String localNameToDrop : localsToDrop) {
LocalMailboxInfo localInfo = localFolders.get(localNameToDrop);
// Exclusion list - never delete local special folders, irrespective
// of server-side existence.
switch (localInfo.mType) {
case Mailbox.TYPE_INBOX:
case Mailbox.TYPE_DRAFTS:
case Mailbox.TYPE_OUTBOX:
case Mailbox.TYPE_SENT:
case Mailbox.TYPE_TRASH:
break;
default:
// Drop all attachment files related to this mailbox
AttachmentProvider.deleteAllMailboxAttachmentFiles(
mContext, accountId, localInfo.mId);
// Delete the mailbox. Triggers will take care of
// related Message, Body and Attachment records.
Uri uri = ContentUris.withAppendedId(
EmailContent.Mailbox.CONTENT_URI, localInfo.mId);
mContext.getContentResolver().delete(uri, null, null);
break;
}
}
// Now do the adds
remoteFolderNames.removeAll(localFolderNames);
for (String remoteNameToAdd : remoteFolderNames) {
EmailContent.Mailbox box = new EmailContent.Mailbox();
box.mDisplayName = remoteNameToAdd;
// box.mServerId;
// box.mParentServerId;
box.mAccountKey = account.mId;
box.mType = LegacyConversions.inferMailboxTypeFromName(
mContext, remoteNameToAdd);
// box.mDelimiter;
// box.mSyncKey;
// box.mSyncLookback;
// box.mSyncFrequency;
// box.mSyncTime;
// box.mUnreadCount;
box.mFlagVisible = true;
// box.mFlags;
box.mVisibleLimit = Email.VISIBLE_LIMIT_DEFAULT;
box.save(mContext);
}
}
mListeners.listFoldersFinished(accountId);
} catch (Exception e) {
mListeners.listFoldersFailed(accountId, "");
} finally {
if (localFolderCursor != null) {
localFolderCursor.close();
}
}
}
});
}
/**
* Start background synchronization of the specified folder.
* @param account
* @param folder
* @param listener
*/
public void synchronizeMailbox(final EmailContent.Account account,
final EmailContent.Mailbox folder, MessagingListener listener) {
/*
* We don't ever sync the Outbox.
*/
if (folder.mType == EmailContent.Mailbox.TYPE_OUTBOX) {
return;
}
mListeners.synchronizeMailboxStarted(account.mId, folder.mId);
put("synchronizeMailbox", listener, new Runnable() {
public void run() {
synchronizeMailboxSynchronous(account, folder);
}
});
}
/**
* Start foreground synchronization of the specified folder. This is called by
* synchronizeMailbox or checkMail.
* TODO this should use ID's instead of fully-restored objects
* @param account
* @param folder
*/
private void synchronizeMailboxSynchronous(final EmailContent.Account account,
final EmailContent.Mailbox folder) {
mListeners.synchronizeMailboxStarted(account.mId, folder.mId);
try {
processPendingActionsSynchronous(account);
StoreSynchronizer.SyncResults results;
// Select generic sync or store-specific sync
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
StoreSynchronizer customSync = remoteStore.getMessageSynchronizer();
if (customSync == null) {
results = synchronizeMailboxGeneric(account, folder);
} else {
results = customSync.SynchronizeMessagesSynchronous(
account, folder, mListeners, mContext);
}
mListeners.synchronizeMailboxFinished(account.mId, folder.mId,
results.mTotalMessages,
results.mNewMessages);
} catch (MessagingException e) {
if (Email.LOGD) {
Log.v(Email.LOG_TAG, "synchronizeMailbox", e);
}
mListeners.synchronizeMailboxFailed(account.mId, folder.mId, e);
}
}
/**
* Lightweight record for the first pass of message sync, where I'm just seeing if
* the local message requires sync. Later (for messages that need syncing) we'll do a full
* readout from the DB.
*/
private static class LocalMessageInfo {
private static final int COLUMN_ID = 0;
private static final int COLUMN_FLAG_READ = 1;
private static final int COLUMN_FLAG_FAVORITE = 2;
private static final int COLUMN_FLAG_LOADED = 3;
private static final int COLUMN_SERVER_ID = 4;
private static final String[] PROJECTION = new String[] {
EmailContent.RECORD_ID,
MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_LOADED,
SyncColumns.SERVER_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY
};
final int mCursorIndex;
final long mId;
final boolean mFlagRead;
final boolean mFlagFavorite;
final int mFlagLoaded;
final String mServerId;
public LocalMessageInfo(Cursor c) {
mCursorIndex = c.getPosition();
mId = c.getLong(COLUMN_ID);
mFlagRead = c.getInt(COLUMN_FLAG_READ) != 0;
mFlagFavorite = c.getInt(COLUMN_FLAG_FAVORITE) != 0;
mFlagLoaded = c.getInt(COLUMN_FLAG_LOADED);
mServerId = c.getString(COLUMN_SERVER_ID);
// Note: mailbox key and account key not needed - they are projected for the SELECT
}
}
private void saveOrUpdate(EmailContent content, Context context) {
if (content.isSaved()) {
content.update(context, content.toContentValues());
} else {
content.save(context);
}
}
/**
* Generic synchronizer - used for POP3 and IMAP.
*
* TODO Break this method up into smaller chunks.
*
* @param account the account to sync
* @param folder the mailbox to sync
* @return results of the sync pass
* @throws MessagingException
*/
private StoreSynchronizer.SyncResults synchronizeMailboxGeneric(
final EmailContent.Account account, final EmailContent.Mailbox folder)
throws MessagingException {
Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***");
ContentResolver resolver = mContext.getContentResolver();
// 0. We do not ever sync DRAFTS or OUTBOX (down or up)
if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) {
int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null);
return new StoreSynchronizer.SyncResults(totalMessages, 0);
}
// 1. Get the message list from the local store and create an index of the uids
Cursor localUidCursor = null;
HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
try {
localUidCursor = resolver.query(
EmailContent.Message.CONTENT_URI,
LocalMessageInfo.PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
},
null);
while (localUidCursor.moveToNext()) {
LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
localMessageMap.put(info.mServerId, info);
}
} finally {
if (localUidCursor != null) {
localUidCursor.close();
}
}
// 1a. Count the unread messages before changing anything
int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?" +
" AND " + MessageColumns.FLAG_READ + "=0",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
});
// 2. Open the remote folder and create the remote folder if necessary
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
|| folder.mType == Mailbox.TYPE_DRAFTS) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return new StoreSynchronizer.SyncResults(0, 0);
}
}
}
// 3, Open the remote folder. This pre-loads certain metadata like message count.
remoteFolder.open(OpenMode.READ_WRITE, null);
// 4. Trash any remote messages that are marked as trashed locally.
// TODO - this comment was here, but no code was here.
// 5. Get the remote message count.
int remoteMessageCount = remoteFolder.getMessageCount();
// 6. Determine the limit # of messages to download
int visibleLimit = folder.mVisibleLimit;
if (visibleLimit <= 0) {
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
mContext);
visibleLimit = info.mVisibleLimitDefault;
}
// 7. Create a list of messages to download
Message[] remoteMessages = new Message[0];
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
int newMessageCount = 0;
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
* Note, we also skip syncing messages which are flagged as "deleted message" sentinels,
* because they are locally deleted and we don't need or want the old message from
* the server.
*/
for (Message message : remoteMessages) {
LocalMessageInfo localMessage = localMessageMap.get(message.getUid());
if (localMessage == null) {
newMessageCount++;
}
- if (localMessage == null
- || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)
- || (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_PARTIAL)) {
+ // localMessage == null -> message has never been created (not even headers)
+ // mFlagLoaded = UNLOADED -> message created, but none of body loaded
+ // mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded
+ // mFlagLoaded = COMPLETE -> message body has been completely loaded
+ // mFlagLoaded = DELETED -> message has been deleted
+ // Only the first two of these are "unsynced", so let's retrieve them
+ if (localMessage == null ||
+ (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) {
unsyncedMessages.add(message);
}
}
}
// 8. Download basic info about the new/unloaded messages (if any)
/*
* A list of messages that were downloaded and which did not have the Seen flag set.
* This will serve to indicate the true "new" message count that will be reported to
* the user via notification.
*/
final ArrayList<Message> newMessages = new ArrayList<Message>();
/*
* Fetch the flags and envelope only of the new messages. This is intended to get us
* critical data as fast as possible, and then we'll fill in the details.
*/
if (unsyncedMessages.size() > 0) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
fp.add(FetchProfile.Item.ENVELOPE);
final HashMap<String, LocalMessageInfo> localMapCopy =
new HashMap<String, LocalMessageInfo>(localMessageMap);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
try {
// Determine if the new message was already known (e.g. partial)
// And create or reload the full message info
LocalMessageInfo localMessageInfo =
localMapCopy.get(message.getUid());
EmailContent.Message localMessage = null;
if (localMessageInfo == null) {
localMessage = new EmailContent.Message();
} else {
localMessage = EmailContent.Message.restoreMessageWithId(
mContext, localMessageInfo.mId);
}
if (localMessage != null) {
try {
// Copy the fields that are available into the message
LegacyConversions.updateMessageFields(localMessage,
message, account.mId, folder.mId);
// Commit the message to the local store
saveOrUpdate(localMessage, mContext);
// Track the "new" ness of the downloaded message
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
} catch (MessagingException me) {
Log.e(Email.LOG_TAG,
"Error while copying downloaded message." + me);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message." + e.toString());
}
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
}
// 9. Refresh the flags for any messages in the local store that we didn't just download.
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages, fp, null);
boolean remoteSupportsSeen = false;
boolean remoteSupportsFlagged = false;
for (Flag flag : remoteFolder.getPermanentFlags()) {
if (flag == Flag.SEEN) {
remoteSupportsSeen = true;
}
if (flag == Flag.FLAGGED) {
remoteSupportsFlagged = true;
}
}
// Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3)
if (remoteSupportsSeen || remoteSupportsFlagged) {
for (Message remoteMessage : remoteMessages) {
LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid());
if (localMessageInfo == null) {
continue;
}
boolean localSeen = localMessageInfo.mFlagRead;
boolean remoteSeen = remoteMessage.isSet(Flag.SEEN);
boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen));
boolean localFlagged = localMessageInfo.mFlagFavorite;
boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED);
boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged));
if (newSeen || newFlagged) {
Uri uri = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, localMessageInfo.mId);
ContentValues updateValues = new ContentValues();
updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen);
updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged);
resolver.update(uri, updateValues, null, null);
}
}
}
// 10. Compute and store the unread message count.
// -- no longer necessary - Provider uses DB triggers to keep track
// int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
// if (remoteUnreadMessageCount == -1) {
// if (remoteSupportsSeenFlag) {
// /*
// * If remote folder doesn't supported unread message count but supports
// * seen flag, use local folder's unread message count and the size of
// * new messages. This mode is not used for POP3, or IMAP.
// */
//
// remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size();
// } else {
// /*
// * If remote folder doesn't supported unread message count and doesn't
// * support seen flag, use localUnreadCount and newMessageCount which
// * don't rely on remote SEEN flag. This mode is used by POP3.
// */
// remoteUnreadMessageCount = localUnreadCount + newMessageCount;
// }
// } else {
// /*
// * If remote folder supports unread message count, use remoteUnreadMessageCount.
// * This mode is used by IMAP.
// */
// }
// Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId);
// ContentValues updateValues = new ContentValues();
// updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount);
// resolver.update(uri, updateValues, null, null);
// 11. Remove any messages that are in the local store but no longer on the remote store.
HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet());
localUidsToDelete.removeAll(remoteUidMap.keySet());
for (String uidToDelete : localUidsToDelete) {
LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete);
// Delete associated data (attachment files)
// Attachment & Body records are auto-deleted when we delete the Message record
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId);
// Delete the message itself
Uri uriToDelete = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, infoToDelete.mId);
resolver.delete(uriToDelete, null, null);
// Delete extra rows (e.g. synced or deleted)
Uri syncRowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(syncRowToDelete, null, null);
Uri deletERowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(deletERowToDelete, null, null);
}
// 12. Divide the unsynced messages into small & large (by size)
// TODO doing this work here (synchronously) is problematic because it prevents the UI
// from affecting the order (e.g. download a message because the user requested it.) Much
// of this logic should move out to a different sync loop that attempts to update small
// groups of messages at a time, as a background task. However, we can't just return
// (yet) because POP messages don't have an envelope yet....
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
// 13. Download small messages
// TODO Problems with this implementation. 1. For IMAP, where we get a real envelope,
// this is going to be inefficient and duplicate work we've already done. 2. It's going
// back to the DB for a local message that we already had (and discarded).
// For small messages, we specify "body", which returns everything (incl. attachments)
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
// 14. Download large messages. We ask the server to give us the message structure,
// but not all of the attachments.
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
// POP doesn't support STRUCTURE mode, so we'll just do a partial download
// (hopefully enough to see some/all of the body) and mark the message for
// further download.
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
// TODO a good optimization here would be to make sure that all Stores set
// the proper size after this fetch and compare the before and after size. If
// they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the partially-loaded message and mark it partially loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_PARTIAL);
} else {
// We have a structure to deal with, from which
// we can pull down the parts we want to actually store.
// Build a list of parts we are interested in. Text parts will be downloaded
// right now, attachments will be left for later.
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
// Download the viewables immediately
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
}
// 15. Clean up and report results
remoteFolder.close(false);
// TODO - more
// Original sync code. Using for reference, will delete when done.
if (false) {
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
// localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
// localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// Update the listener with what we've found
// synchronized (mListeners) {
// for (MessagingListener l : mListeners) {
// l.synchronizeMailboxNewMessage(
// account,
// folder,
// localFolder.getMessage(message.getUid()));
// }
// }
}
/*
* Report successful sync
*/
StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults(
remoteFolder.getMessageCount(), newMessages.size());
remoteFolder.close(false);
// localFolder.close(false);
return results;
}
return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size());
}
/**
* Copy one downloaded message (which may have partially-loaded sections)
* into a newly created EmailProvider Message, given the account and mailbox
*
* @param message the remote message we've just downloaded
* @param account the account it will be stored into
* @param folder the mailbox it will be stored into
* @param loadStatus when complete, the message will be marked with this status (e.g.
* EmailContent.Message.LOADED)
*/
public void copyOneMessageToProvider(Message message, EmailContent.Account account,
EmailContent.Mailbox folder, int loadStatus) {
EmailContent.Message localMessage = null;
Cursor c = null;
try {
c = mContext.getContentResolver().query(
EmailContent.Message.CONTENT_URI,
EmailContent.Message.CONTENT_PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?" +
" AND " + SyncColumns.SERVER_ID + "=?",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId),
String.valueOf(message.getUid())
},
null);
if (c.moveToNext()) {
localMessage = EmailContent.getContent(c, EmailContent.Message.class);
localMessage.mMailboxKey = folder.mId;
localMessage.mAccountKey = account.mId;
copyOneMessageToProvider(message, localMessage, loadStatus, mContext);
}
} finally {
if (c != null) {
c.close();
}
}
}
/**
* Copy one downloaded message (which may have partially-loaded sections)
* into an already-created EmailProvider Message
*
* @param message the remote message we've just downloaded
* @param localMessage the EmailProvider Message, already created
* @param loadStatus when complete, the message will be marked with this status (e.g.
* EmailContent.Message.LOADED)
* @param context the context to be used for EmailProvider
*/
public void copyOneMessageToProvider(Message message, EmailContent.Message localMessage,
int loadStatus, Context context) {
try {
EmailContent.Body body = EmailContent.Body.restoreBodyWithMessageId(context,
localMessage.mId);
if (body == null) {
body = new EmailContent.Body();
}
try {
// Copy the fields that are available into the message object
LegacyConversions.updateMessageFields(localMessage, message,
localMessage.mAccountKey, localMessage.mMailboxKey);
// Now process body parts & attachments
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
LegacyConversions.updateBodyFields(body, localMessage, viewables);
// Commit the message & body to the local store immediately
saveOrUpdate(localMessage, context);
saveOrUpdate(body, context);
// process (and save) attachments
LegacyConversions.updateAttachments(context, localMessage,
attachments, false);
// One last update of message with two updated flags
localMessage.mFlagLoaded = loadStatus;
ContentValues cv = new ContentValues();
cv.put(EmailContent.MessageColumns.FLAG_ATTACHMENT, localMessage.mFlagAttachment);
cv.put(EmailContent.MessageColumns.FLAG_LOADED, localMessage.mFlagLoaded);
Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI,
localMessage.mId);
context.getContentResolver().update(uri, cv, null, null);
} catch (MessagingException me) {
Log.e(Email.LOG_TAG, "Error while copying downloaded message." + me);
}
} catch (RuntimeException rte) {
Log.e(Email.LOG_TAG, "Error while storing downloaded message." + rte.toString());
} catch (IOException ioe) {
Log.e(Email.LOG_TAG, "Error while storing attachment." + ioe.toString());
}
}
public void processPendingActions(final long accountId) {
put("processPendingActions", null, new Runnable() {
public void run() {
try {
EmailContent.Account account =
EmailContent.Account.restoreAccountWithId(mContext, accountId);
if (account == null) {
return;
}
processPendingActionsSynchronous(account);
}
catch (MessagingException me) {
if (Email.LOGD) {
Log.v(Email.LOG_TAG, "processPendingActions", me);
}
/*
* Ignore any exceptions from the commands. Commands will be processed
* on the next round.
*/
}
}
});
}
/**
* Find messages in the updated table that need to be written back to server.
*
* Handles:
* Read/Unread
* Flagged
* Append (upload)
* Move To Trash
* Empty trash
* TODO:
* Move
*
* @param account the account to scan for pending actions
* @throws MessagingException
*/
private void processPendingActionsSynchronous(EmailContent.Account account)
throws MessagingException {
ContentResolver resolver = mContext.getContentResolver();
String[] accountIdArgs = new String[] { Long.toString(account.mId) };
// Handle deletes first, it's always better to get rid of things first
processPendingDeletesSynchronous(account, resolver, accountIdArgs);
// Handle uploads (currently, only to sent messages)
processPendingUploadsSynchronous(account, resolver, accountIdArgs);
// Now handle updates / upsyncs
processPendingUpdatesSynchronous(account, resolver, accountIdArgs);
}
/**
* Scan for messages that are in the Message_Deletes table, look for differences that
* we can deal with, and do the work.
*
* @param account
* @param resolver
* @param accountIdArgs
*/
private void processPendingDeletesSynchronous(EmailContent.Account account,
ContentResolver resolver, String[] accountIdArgs) {
Cursor deletes = resolver.query(EmailContent.Message.DELETED_CONTENT_URI,
EmailContent.Message.CONTENT_PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?", accountIdArgs,
EmailContent.MessageColumns.MAILBOX_KEY);
long lastMessageId = -1;
try {
// Defer setting up the store until we know we need to access it
Store remoteStore = null;
// Demand load mailbox (note order-by to reduce thrashing here)
Mailbox mailbox = null;
// loop through messages marked as deleted
while (deletes.moveToNext()) {
boolean deleteFromTrash = false;
EmailContent.Message oldMessage =
EmailContent.getContent(deletes, EmailContent.Message.class);
if (oldMessage != null) {
lastMessageId = oldMessage.mId;
if (mailbox == null || mailbox.mId != oldMessage.mMailboxKey) {
mailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
if (mailbox == null) {
continue; // Mailbox removed. Move to the next message.
}
}
deleteFromTrash = mailbox.mType == Mailbox.TYPE_TRASH;
}
// Load the remote store if it will be needed
if (remoteStore == null && deleteFromTrash) {
remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
}
// Dispatch here for specific change types
if (deleteFromTrash) {
// Move message to trash
processPendingDeleteFromTrash(remoteStore, account, mailbox, oldMessage);
}
// Finally, delete the update
Uri uri = ContentUris.withAppendedId(EmailContent.Message.DELETED_CONTENT_URI,
oldMessage.mId);
resolver.delete(uri, null, null);
}
} catch (MessagingException me) {
// Presumably an error here is an account connection failure, so there is
// no point in continuing through the rest of the pending updates.
if (Email.DEBUG) {
Log.d(Email.LOG_TAG, "Unable to process pending delete for id="
+ lastMessageId + ": " + me);
}
} finally {
deletes.close();
}
}
/**
* Scan for messages that are in Sent, and are in need of upload,
* and send them to the server. "In need of upload" is defined as:
* serverId == null (no UID has been assigned)
* or
* message is in the updated list
*
* Note we also look for messages that are moving from drafts->outbox->sent. They never
* go through "drafts" or "outbox" on the server, so we hang onto these until they can be
* uploaded directly to the Sent folder.
*
* @param account
* @param resolver
* @param accountIdArgs
*/
private void processPendingUploadsSynchronous(EmailContent.Account account,
ContentResolver resolver, String[] accountIdArgs) throws MessagingException {
// Find the Sent folder (since that's all we're uploading for now
Cursor mailboxes = resolver.query(Mailbox.CONTENT_URI, Mailbox.ID_PROJECTION,
MailboxColumns.ACCOUNT_KEY + "=?"
+ " and " + MailboxColumns.TYPE + "=" + Mailbox.TYPE_SENT,
accountIdArgs, null);
long lastMessageId = -1;
try {
// Defer setting up the store until we know we need to access it
Store remoteStore = null;
while (mailboxes.moveToNext()) {
long mailboxId = mailboxes.getLong(Mailbox.ID_PROJECTION_COLUMN);
String[] mailboxKeyArgs = new String[] { Long.toString(mailboxId) };
// Demand load mailbox
Mailbox mailbox = null;
// First handle the "new" messages (serverId == null)
Cursor upsyncs1 = resolver.query(EmailContent.Message.CONTENT_URI,
EmailContent.Message.ID_PROJECTION,
EmailContent.Message.MAILBOX_KEY + "=?"
+ " and (" + EmailContent.Message.SERVER_ID + " is null"
+ " or " + EmailContent.Message.SERVER_ID + "=''" + ")",
mailboxKeyArgs,
null);
try {
while (upsyncs1.moveToNext()) {
// Load the remote store if it will be needed
if (remoteStore == null) {
remoteStore =
Store.getInstance(account.getStoreUri(mContext), mContext, null);
}
// Load the mailbox if it will be needed
if (mailbox == null) {
mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
if (mailbox == null) {
continue; // Mailbox removed. Move to the next message.
}
}
// upsync the message
long id = upsyncs1.getLong(EmailContent.Message.ID_PROJECTION_COLUMN);
lastMessageId = id;
processUploadMessage(resolver, remoteStore, account, mailbox, id);
}
} finally {
if (upsyncs1 != null) {
upsyncs1.close();
}
}
// Next, handle any updates (e.g. edited in place, although this shouldn't happen)
Cursor upsyncs2 = resolver.query(EmailContent.Message.UPDATED_CONTENT_URI,
EmailContent.Message.ID_PROJECTION,
EmailContent.MessageColumns.MAILBOX_KEY + "=?", mailboxKeyArgs,
null);
try {
while (upsyncs2.moveToNext()) {
// Load the remote store if it will be needed
if (remoteStore == null) {
remoteStore =
Store.getInstance(account.getStoreUri(mContext), mContext, null);
}
// Load the mailbox if it will be needed
if (mailbox == null) {
mailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId);
if (mailbox == null) {
continue; // Mailbox removed. Move to the next message.
}
}
// upsync the message
long id = upsyncs2.getLong(EmailContent.Message.ID_PROJECTION_COLUMN);
lastMessageId = id;
processUploadMessage(resolver, remoteStore, account, mailbox, id);
}
} finally {
if (upsyncs2 != null) {
upsyncs2.close();
}
}
}
} catch (MessagingException me) {
// Presumably an error here is an account connection failure, so there is
// no point in continuing through the rest of the pending updates.
if (Email.DEBUG) {
Log.d(Email.LOG_TAG, "Unable to process pending upsync for id="
+ lastMessageId + ": " + me);
}
} finally {
if (mailboxes != null) {
mailboxes.close();
}
}
}
/**
* Scan for messages that are in the Message_Updates table, look for differences that
* we can deal with, and do the work.
*
* @param account
* @param resolver
* @param accountIdArgs
*/
private void processPendingUpdatesSynchronous(EmailContent.Account account,
ContentResolver resolver, String[] accountIdArgs) {
Cursor updates = resolver.query(EmailContent.Message.UPDATED_CONTENT_URI,
EmailContent.Message.CONTENT_PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?", accountIdArgs,
EmailContent.MessageColumns.MAILBOX_KEY);
long lastMessageId = -1;
try {
// Defer setting up the store until we know we need to access it
Store remoteStore = null;
// Demand load mailbox (note order-by to reduce thrashing here)
Mailbox mailbox = null;
// loop through messages marked as needing updates
while (updates.moveToNext()) {
boolean changeMoveToTrash = false;
boolean changeRead = false;
boolean changeFlagged = false;
boolean changeMailbox = false;
EmailContent.Message oldMessage =
EmailContent.getContent(updates, EmailContent.Message.class);
lastMessageId = oldMessage.mId;
EmailContent.Message newMessage =
EmailContent.Message.restoreMessageWithId(mContext, oldMessage.mId);
if (newMessage != null) {
if (mailbox == null || mailbox.mId != newMessage.mMailboxKey) {
mailbox = Mailbox.restoreMailboxWithId(mContext, newMessage.mMailboxKey);
if (mailbox == null) {
continue; // Mailbox removed. Move to the next message.
}
}
if (oldMessage.mMailboxKey != newMessage.mMailboxKey) {
if (mailbox.mType == Mailbox.TYPE_TRASH) {
changeMoveToTrash = true;
} else {
changeMailbox = true;
}
}
changeRead = oldMessage.mFlagRead != newMessage.mFlagRead;
changeFlagged = oldMessage.mFlagFavorite != newMessage.mFlagFavorite;
}
// Load the remote store if it will be needed
if (remoteStore == null &&
(changeMoveToTrash || changeRead || changeFlagged || changeMailbox)) {
remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
}
// Dispatch here for specific change types
if (changeMoveToTrash) {
// Move message to trash
processPendingMoveToTrash(remoteStore, account, mailbox, oldMessage,
newMessage);
} else if (changeRead || changeFlagged || changeMailbox) {
processPendingDataChange(remoteStore, mailbox, changeRead, changeFlagged,
changeMailbox, oldMessage, newMessage);
}
// Finally, delete the update
Uri uri = ContentUris.withAppendedId(EmailContent.Message.UPDATED_CONTENT_URI,
oldMessage.mId);
resolver.delete(uri, null, null);
}
} catch (MessagingException me) {
// Presumably an error here is an account connection failure, so there is
// no point in continuing through the rest of the pending updates.
if (Email.DEBUG) {
Log.d(Email.LOG_TAG, "Unable to process pending update for id="
+ lastMessageId + ": " + me);
}
} finally {
updates.close();
}
}
/**
* Upsync an entire message. This must also unwind whatever triggered it (either by
* updating the serverId, or by deleting the update record, or it's going to keep happening
* over and over again.
*
* Note: If the message is being uploaded into an unexpected mailbox, we *do not* upload.
* This is to avoid unnecessary uploads into the trash. Although the caller attempts to select
* only the Drafts and Sent folders, this can happen when the update record and the current
* record mismatch. In this case, we let the update record remain, because the filters
* in processPendingUpdatesSynchronous() will pick it up as a move and handle it (or drop it)
* appropriately.
*
* @param resolver
* @param remoteStore
* @param account
* @param mailbox the actual mailbox
* @param messageId
*/
private void processUploadMessage(ContentResolver resolver, Store remoteStore,
EmailContent.Account account, Mailbox mailbox, long messageId)
throws MessagingException {
EmailContent.Message message =
EmailContent.Message.restoreMessageWithId(mContext, messageId);
boolean deleteUpdate = false;
if (message == null) {
deleteUpdate = true;
Log.d(Email.LOG_TAG, "Upsync failed for null message, id=" + messageId);
} else if (mailbox.mType == Mailbox.TYPE_DRAFTS) {
deleteUpdate = false;
Log.d(Email.LOG_TAG, "Upsync skipped for mailbox=drafts, id=" + messageId);
} else if (mailbox.mType == Mailbox.TYPE_OUTBOX) {
deleteUpdate = false;
Log.d(Email.LOG_TAG, "Upsync skipped for mailbox=outbox, id=" + messageId);
} else if (mailbox.mType == Mailbox.TYPE_TRASH) {
deleteUpdate = false;
Log.d(Email.LOG_TAG, "Upsync skipped for mailbox=trash, id=" + messageId);
} else {
Log.d(Email.LOG_TAG, "Upsyc triggered for message id=" + messageId);
deleteUpdate = processPendingAppend(remoteStore, account, mailbox, message);
}
if (deleteUpdate) {
// Finally, delete the update (if any)
Uri uri = ContentUris.withAppendedId(EmailContent.Message.UPDATED_CONTENT_URI, messageId);
resolver.delete(uri, null, null);
}
}
/**
* Upsync changes to read, flagged, or mailbox
*
* @param remoteStore the remote store for this mailbox
* @param mailbox the mailbox the message is stored in
* @param changeRead whether the message's read state has changed
* @param changeFlagged whether the message's flagged state has changed
* @param changeMailbox whether the message's mailbox has changed
* @param oldMessage the message in it's pre-change state
* @param newMessage the current version of the message
*/
private void processPendingDataChange(Store remoteStore, Mailbox mailbox, boolean changeRead,
boolean changeFlagged, boolean changeMailbox, EmailContent.Message oldMessage,
EmailContent.Message newMessage) throws MessagingException {
Mailbox newMailbox = null;;
// 0. No remote update if the message is local-only
if (newMessage.mServerId == null || newMessage.mServerId.equals("")
|| newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX) || (mailbox == null)) {
return;
}
// 0.5 If the mailbox has changed, use the original mailbox for operations
// After any flag changes (which we execute in the original mailbox), we then
// copy the message to the new mailbox
if (changeMailbox) {
newMailbox = mailbox;
mailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
}
// 1. No remote update for DRAFTS or OUTBOX
if (mailbox.mType == Mailbox.TYPE_DRAFTS || mailbox.mType == Mailbox.TYPE_OUTBOX) {
return;
}
// 2. Open the remote store & folder
Folder remoteFolder = remoteStore.getFolder(mailbox.mDisplayName);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(OpenMode.READ_WRITE, null);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
return;
}
// 3. Finally, apply the changes to the message
Message remoteMessage = remoteFolder.getMessage(newMessage.mServerId);
if (remoteMessage == null) {
return;
}
if (Email.DEBUG) {
Log.d(Email.LOG_TAG,
"Update for msg id=" + newMessage.mId
+ " read=" + newMessage.mFlagRead
+ " flagged=" + newMessage.mFlagFavorite
+ " new mailbox=" + newMessage.mMailboxKey);
}
Message[] messages = new Message[] { remoteMessage };
if (changeRead) {
remoteFolder.setFlags(messages, FLAG_LIST_SEEN, newMessage.mFlagRead);
}
if (changeFlagged) {
remoteFolder.setFlags(messages, FLAG_LIST_FLAGGED, newMessage.mFlagFavorite);
}
if (changeMailbox) {
Folder toFolder = remoteStore.getFolder(newMailbox.mDisplayName);
if (!remoteFolder.exists()) {
return;
}
// Copy the message to its new folder
remoteFolder.copyMessages(messages, toFolder, null);
// Delete the message from the remote source folder
remoteMessage.setFlag(Flag.DELETED, true);
remoteFolder.expunge();
// Set the serverId to 0, since we don't know what the new server id will be
ContentValues cv = new ContentValues();
cv.put(EmailContent.Message.SERVER_ID, "0");
mContext.getContentResolver().update(ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, newMessage.mId), cv, null, null);
}
remoteFolder.close(false);
}
/**
* Process a pending trash message command.
*
* @param remoteStore the remote store we're working in
* @param account The account in which we are working
* @param newMailbox The local trash mailbox
* @param oldMessage The message copy that was saved in the updates shadow table
* @param newMessage The message that was moved to the mailbox
*/
private void processPendingMoveToTrash(Store remoteStore,
EmailContent.Account account, Mailbox newMailbox, EmailContent.Message oldMessage,
final EmailContent.Message newMessage) throws MessagingException {
// 0. No remote move if the message is local-only
if (newMessage.mServerId == null || newMessage.mServerId.equals("")
|| newMessage.mServerId.startsWith(LOCAL_SERVERID_PREFIX)) {
return;
}
// 1. Escape early if we can't find the local mailbox
// TODO smaller projection here
Mailbox oldMailbox = Mailbox.restoreMailboxWithId(mContext, oldMessage.mMailboxKey);
if (oldMailbox == null) {
// can't find old mailbox, it may have been deleted. just return.
return;
}
// 2. We don't support delete-from-trash here
if (oldMailbox.mType == Mailbox.TYPE_TRASH) {
return;
}
// 3. If DELETE_POLICY_NEVER, simply write back the deleted sentinel and return
//
// This sentinel takes the place of the server-side message, and locally "deletes" it
// by inhibiting future sync or display of the message. It will eventually go out of
// scope when it becomes old, or is deleted on the server, and the regular sync code
// will clean it up for us.
if (account.getDeletePolicy() == Account.DELETE_POLICY_NEVER) {
EmailContent.Message sentinel = new EmailContent.Message();
sentinel.mAccountKey = oldMessage.mAccountKey;
sentinel.mMailboxKey = oldMessage.mMailboxKey;
sentinel.mFlagLoaded = EmailContent.Message.FLAG_LOADED_DELETED;
sentinel.mFlagRead = true;
sentinel.mServerId = oldMessage.mServerId;
sentinel.save(mContext);
return;
}
// The rest of this method handles server-side deletion
// 4. Find the remote mailbox (that we deleted from), and open it
Folder remoteFolder = remoteStore.getFolder(oldMailbox.mDisplayName);
if (!remoteFolder.exists()) {
return;
}
remoteFolder.open(OpenMode.READ_WRITE, null);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
remoteFolder.close(false);
return;
}
// 5. Find the remote original message
Message remoteMessage = remoteFolder.getMessage(oldMessage.mServerId);
if (remoteMessage == null) {
remoteFolder.close(false);
return;
}
// 6. Find the remote trash folder, and create it if not found
Folder remoteTrashFolder = remoteStore.getFolder(newMailbox.mDisplayName);
if (!remoteTrashFolder.exists()) {
/*
* If the remote trash folder doesn't exist we try to create it.
*/
remoteTrashFolder.create(FolderType.HOLDS_MESSAGES);
}
// 7. Try to copy the message into the remote trash folder
// Note, this entire section will be skipped for POP3 because there's no remote trash
if (remoteTrashFolder.exists()) {
/*
* Because remoteTrashFolder may be new, we need to explicitly open it
*/
remoteTrashFolder.open(OpenMode.READ_WRITE, null);
if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
remoteFolder.close(false);
remoteTrashFolder.close(false);
return;
}
remoteFolder.copyMessages(new Message[] { remoteMessage }, remoteTrashFolder,
new Folder.MessageUpdateCallbacks() {
public void onMessageUidChange(Message message, String newUid) {
// update the UID in the local trash folder, because some stores will
// have to change it when copying to remoteTrashFolder
ContentValues cv = new ContentValues();
cv.put(EmailContent.Message.SERVER_ID, newUid);
mContext.getContentResolver().update(newMessage.getUri(), cv, null, null);
}
/**
* This will be called if the deleted message doesn't exist and can't be
* deleted (e.g. it was already deleted from the server.) In this case,
* attempt to delete the local copy as well.
*/
public void onMessageNotFound(Message message) {
mContext.getContentResolver().delete(newMessage.getUri(), null, null);
}
});
remoteTrashFolder.close(false);
}
// 8. Delete the message from the remote source folder
remoteMessage.setFlag(Flag.DELETED, true);
remoteFolder.expunge();
remoteFolder.close(false);
}
/**
* Process a pending trash message command.
*
* @param remoteStore the remote store we're working in
* @param account The account in which we are working
* @param oldMailbox The local trash mailbox
* @param oldMessage The message that was deleted from the trash
*/
private void processPendingDeleteFromTrash(Store remoteStore,
EmailContent.Account account, Mailbox oldMailbox, EmailContent.Message oldMessage)
throws MessagingException {
// 1. We only support delete-from-trash here
if (oldMailbox.mType != Mailbox.TYPE_TRASH) {
return;
}
// 2. Find the remote trash folder (that we are deleting from), and open it
Folder remoteTrashFolder = remoteStore.getFolder(oldMailbox.mDisplayName);
if (!remoteTrashFolder.exists()) {
return;
}
remoteTrashFolder.open(OpenMode.READ_WRITE, null);
if (remoteTrashFolder.getMode() != OpenMode.READ_WRITE) {
remoteTrashFolder.close(false);
return;
}
// 3. Find the remote original message
Message remoteMessage = remoteTrashFolder.getMessage(oldMessage.mServerId);
if (remoteMessage == null) {
remoteTrashFolder.close(false);
return;
}
// 4. Delete the message from the remote trash folder
remoteMessage.setFlag(Flag.DELETED, true);
remoteTrashFolder.expunge();
remoteTrashFolder.close(false);
}
/**
* Process a pending append message command. This command uploads a local message to the
* server, first checking to be sure that the server message is not newer than
* the local message.
*
* @param remoteStore the remote store we're working in
* @param account The account in which we are working
* @param newMailbox The mailbox we're appending to
* @param message The message we're appending
* @return true if successfully uploaded
*/
private boolean processPendingAppend(Store remoteStore, EmailContent.Account account,
Mailbox newMailbox, EmailContent.Message message)
throws MessagingException {
boolean updateInternalDate = false;
boolean updateMessage = false;
boolean deleteMessage = false;
// 1. Find the remote folder that we're appending to and create and/or open it
Folder remoteFolder = remoteStore.getFolder(newMailbox.mDisplayName);
if (!remoteFolder.exists()) {
if (!remoteFolder.canCreate(FolderType.HOLDS_MESSAGES)) {
// This is POP3, we cannot actually upload. Instead, we'll update the message
// locally with a fake serverId (so we don't keep trying here) and return.
if (message.mServerId == null || message.mServerId.length() == 0) {
message.mServerId = LOCAL_SERVERID_PREFIX + message.mId;
Uri uri =
ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, message.mId);
ContentValues cv = new ContentValues();
cv.put(EmailContent.Message.SERVER_ID, message.mServerId);
mContext.getContentResolver().update(uri, cv, null, null);
}
return true;
}
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
// This is a (hopefully) transient error and we return false to try again later
return false;
}
}
remoteFolder.open(OpenMode.READ_WRITE, null);
if (remoteFolder.getMode() != OpenMode.READ_WRITE) {
return false;
}
// 2. If possible, load a remote message with the matching UID
Message remoteMessage = null;
if (message.mServerId != null && message.mServerId.length() > 0) {
remoteMessage = remoteFolder.getMessage(message.mServerId);
}
// 3. If a remote message could not be found, upload our local message
if (remoteMessage == null) {
// 3a. Create a legacy message to upload
Message localMessage = LegacyConversions.makeMessage(mContext, message);
// 3b. Upload it
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.appendMessages(new Message[] { localMessage });
// 3b. And record the UID from the server
message.mServerId = localMessage.getUid();
updateInternalDate = true;
updateMessage = true;
} else {
// 4. If the remote message exists we need to determine which copy to keep.
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
Date localDate = new Date(message.mServerTimeStamp);
Date remoteDate = remoteMessage.getInternalDate();
if (remoteDate != null && remoteDate.compareTo(localDate) > 0) {
// 4a. If the remote message is newer than ours we'll just
// delete ours and move on. A sync will get the server message
// if we need to be able to see it.
deleteMessage = true;
} else {
// 4b. Otherwise we'll upload our message and then delete the remote message.
// Create a legacy message to upload
Message localMessage = LegacyConversions.makeMessage(mContext, message);
// 4c. Upload it
fp.clear();
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.appendMessages(new Message[] { localMessage });
// 4d. Record the UID and new internalDate from the server
message.mServerId = localMessage.getUid();
updateInternalDate = true;
updateMessage = true;
// 4e. And delete the old copy of the message from the server
remoteMessage.setFlag(Flag.DELETED, true);
}
}
// 5. If requested, Best-effort to capture new "internaldate" from the server
if (updateInternalDate && message.mServerId != null) {
try {
Message remoteMessage2 = remoteFolder.getMessage(message.mServerId);
if (remoteMessage2 != null) {
FetchProfile fp2 = new FetchProfile();
fp2.add(FetchProfile.Item.ENVELOPE);
remoteFolder.fetch(new Message[] { remoteMessage2 }, fp2, null);
message.mServerTimeStamp = remoteMessage2.getInternalDate().getTime();
updateMessage = true;
}
} catch (MessagingException me) {
// skip it - we can live without this
}
}
// 6. Perform required edits to local copy of message
if (deleteMessage || updateMessage) {
Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, message.mId);
ContentResolver resolver = mContext.getContentResolver();
if (deleteMessage) {
resolver.delete(uri, null, null);
} else if (updateMessage) {
ContentValues cv = new ContentValues();
cv.put(EmailContent.Message.SERVER_ID, message.mServerId);
cv.put(EmailContent.Message.SERVER_TIMESTAMP, message.mServerTimeStamp);
resolver.update(uri, cv, null, null);
}
}
return true;
}
/**
* Finish loading a message that have been partially downloaded.
*
* @param messageId the message to load
* @param listener the callback by which results will be reported
*/
public void loadMessageForView(final long messageId, MessagingListener listener) {
mListeners.loadMessageForViewStarted(messageId);
put("loadMessageForViewRemote", listener, new Runnable() {
public void run() {
try {
// 1. Resample the message, in case it disappeared or synced while
// this command was in queue
EmailContent.Message message =
EmailContent.Message.restoreMessageWithId(mContext, messageId);
if (message == null) {
mListeners.loadMessageForViewFailed(messageId, "Unknown message");
return;
}
if (message.mFlagLoaded == EmailContent.Message.FLAG_LOADED_COMPLETE) {
mListeners.loadMessageForViewFinished(messageId);
return;
}
// 2. Open the remote folder.
// TODO all of these could be narrower projections
// TODO combine with common code in loadAttachment
EmailContent.Account account =
EmailContent.Account.restoreAccountWithId(mContext, message.mAccountKey);
EmailContent.Mailbox mailbox =
EmailContent.Mailbox.restoreMailboxWithId(mContext, message.mMailboxKey);
if (account == null || mailbox == null) {
mListeners.loadMessageForViewFailed(messageId, "null account or mailbox");
return;
}
Store remoteStore =
Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(mailbox.mDisplayName);
remoteFolder.open(OpenMode.READ_WRITE, null);
// 3. Not supported, because IMAP & POP don't use it: structure prefetch
// if (remoteStore.requireStructurePrefetch()) {
// // For remote stores that require it, prefetch the message structure.
// FetchProfile fp = new FetchProfile();
// fp.add(FetchProfile.Item.STRUCTURE);
// localFolder.fetch(new Message[] { message }, fp, null);
//
// ArrayList<Part> viewables = new ArrayList<Part>();
// ArrayList<Part> attachments = new ArrayList<Part>();
// MimeUtility.collectParts(message, viewables, attachments);
// fp.clear();
// for (Part part : viewables) {
// fp.add(part);
// }
//
// remoteFolder.fetch(new Message[] { message }, fp, null);
//
// // Store the updated message locally
// localFolder.updateMessage((LocalMessage)message);
// 4. Set up to download the entire message
Message remoteMessage = remoteFolder.getMessage(message.mServerId);
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(new Message[] { remoteMessage }, fp, null);
// 5. Write to provider
copyOneMessageToProvider(remoteMessage, account, mailbox,
EmailContent.Message.FLAG_LOADED_COMPLETE);
// 6. Notify UI
mListeners.loadMessageForViewFinished(messageId);
} catch (MessagingException me) {
if (Email.LOGD) Log.v(Email.LOG_TAG, "", me);
mListeners.loadMessageForViewFailed(messageId, me.getMessage());
} catch (RuntimeException rte) {
mListeners.loadMessageForViewFailed(messageId, rte.getMessage());
}
}
});
}
/**
* Attempts to load the attachment specified by id from the given account and message.
* @param account
* @param message
* @param part
* @param listener
*/
public void loadAttachment(final long accountId, final long messageId, final long mailboxId,
final long attachmentId, MessagingListener listener) {
mListeners.loadAttachmentStarted(accountId, messageId, attachmentId, true);
put("loadAttachment", listener, new Runnable() {
public void run() {
try {
//1. Check if the attachment is already here and return early in that case
Attachment attachment =
Attachment.restoreAttachmentWithId(mContext, attachmentId);
if (attachment == null) {
mListeners.loadAttachmentFailed(accountId, messageId, attachmentId,
new MessagingException("The attachment is null"));
return;
}
if (Utility.attachmentExists(mContext, attachment)) {
mListeners.loadAttachmentFinished(accountId, messageId, attachmentId);
return;
}
// 2. Open the remote folder.
// TODO all of these could be narrower projections
EmailContent.Account account =
EmailContent.Account.restoreAccountWithId(mContext, accountId);
EmailContent.Mailbox mailbox =
EmailContent.Mailbox.restoreMailboxWithId(mContext, mailboxId);
EmailContent.Message message =
EmailContent.Message.restoreMessageWithId(mContext, messageId);
if (account == null || mailbox == null || message == null) {
mListeners.loadAttachmentFailed(accountId, messageId, attachmentId,
new MessagingException(
"Account, mailbox, message or attachment are null"));
return;
}
Store remoteStore =
Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(mailbox.mDisplayName);
remoteFolder.open(OpenMode.READ_WRITE, null);
// 3. Generate a shell message in which to retrieve the attachment,
// and a shell BodyPart for the attachment. Then glue them together.
Message storeMessage = remoteFolder.createMessage(message.mServerId);
MimeBodyPart storePart = new MimeBodyPart();
storePart.setSize((int)attachment.mSize);
storePart.setHeader(MimeHeader.HEADER_ANDROID_ATTACHMENT_STORE_DATA,
attachment.mLocation);
storePart.setHeader(MimeHeader.HEADER_CONTENT_TYPE,
String.format("%s;\n name=\"%s\"",
attachment.mMimeType,
attachment.mFileName));
// TODO is this always true for attachments? I think we dropped the
// true encoding along the way
storePart.setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
MimeMultipart multipart = new MimeMultipart();
multipart.setSubType("mixed");
multipart.addBodyPart(storePart);
storeMessage.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "multipart/mixed");
storeMessage.setBody(multipart);
// 4. Now ask for the attachment to be fetched
FetchProfile fp = new FetchProfile();
fp.add(storePart);
remoteFolder.fetch(new Message[] { storeMessage }, fp,
mController.new LegacyListener(messageId, attachmentId));
// If we failed to load the attachment, throw an Exception here, so that
// AttachmentDownloadService knows that we failed
if (storePart.getBody() == null) {
throw new MessagingException("Attachment not loaded.");
}
// 5. Save the downloaded file and update the attachment as necessary
LegacyConversions.saveAttachmentBody(mContext, storePart, attachment,
accountId);
// 6. Report success
mListeners.loadAttachmentFinished(accountId, messageId, attachmentId);
}
catch (MessagingException me) {
if (Email.LOGD) Log.v(Email.LOG_TAG, "", me);
mListeners.loadAttachmentFailed(accountId, messageId, attachmentId, me);
} catch (IOException ioe) {
Log.e(Email.LOG_TAG, "Error while storing attachment." + ioe.toString());
}
}});
}
/**
* Attempt to send any messages that are sitting in the Outbox.
* @param account
* @param listener
*/
public void sendPendingMessages(final EmailContent.Account account, final long sentFolderId,
MessagingListener listener) {
put("sendPendingMessages", listener, new Runnable() {
public void run() {
sendPendingMessagesSynchronous(account, sentFolderId);
}
});
}
/**
* Attempt to send any messages that are sitting in the Outbox.
*
* @param account
* @param listener
*/
public void sendPendingMessagesSynchronous(final EmailContent.Account account,
long sentFolderId) {
// 1. Loop through all messages in the account's outbox
long outboxId = Mailbox.findMailboxOfType(mContext, account.mId, Mailbox.TYPE_OUTBOX);
if (outboxId == Mailbox.NO_MAILBOX) {
return;
}
ContentResolver resolver = mContext.getContentResolver();
Cursor c = resolver.query(EmailContent.Message.CONTENT_URI,
EmailContent.Message.ID_COLUMN_PROJECTION,
EmailContent.Message.MAILBOX_KEY + "=?", new String[] { Long.toString(outboxId) },
null);
try {
// 2. exit early
if (c.getCount() <= 0) {
return;
}
// 3. do one-time setup of the Sender & other stuff
mListeners.sendPendingMessagesStarted(account.mId, -1);
Sender sender = Sender.getInstance(mContext, account.getSenderUri(mContext));
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
boolean requireMoveMessageToSentFolder = remoteStore.requireCopyMessageToSentFolder();
ContentValues moveToSentValues = null;
if (requireMoveMessageToSentFolder) {
moveToSentValues = new ContentValues();
moveToSentValues.put(MessageColumns.MAILBOX_KEY, sentFolderId);
}
// 4. loop through the available messages and send them
while (c.moveToNext()) {
long messageId = -1;
try {
messageId = c.getLong(0);
mListeners.sendPendingMessagesStarted(account.mId, messageId);
// Don't send messages with unloaded attachments
if (Utility.hasUnloadedAttachments(mContext, messageId)) {
if (Email.DEBUG) {
Log.d(Email.LOG_TAG, "Can't send #" + messageId +
"; unloaded attachments");
}
continue;
}
sender.sendMessage(messageId);
} catch (MessagingException me) {
// report error for this message, but keep trying others
mListeners.sendPendingMessagesFailed(account.mId, messageId, me);
continue;
}
// 5. move to sent, or delete
Uri syncedUri =
ContentUris.withAppendedId(EmailContent.Message.SYNCED_CONTENT_URI, messageId);
if (requireMoveMessageToSentFolder) {
// If this is a forwarded message and it has attachments, delete them, as they
// duplicate information found elsewhere (on the server). This saves storage.
EmailContent.Message msg =
EmailContent.Message.restoreMessageWithId(mContext, messageId);
if (msg != null &&
((msg.mFlags & EmailContent.Message.FLAG_TYPE_FORWARD) != 0)) {
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId,
messageId);
}
resolver.update(syncedUri, moveToSentValues, null, null);
} else {
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, messageId);
Uri uri =
ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, messageId);
resolver.delete(uri, null, null);
resolver.delete(syncedUri, null, null);
}
}
// 6. report completion/success
mListeners.sendPendingMessagesCompleted(account.mId);
} catch (MessagingException me) {
mListeners.sendPendingMessagesFailed(account.mId, -1, me);
} finally {
c.close();
}
}
/**
* Checks mail for an account.
* This entry point is for use by the mail checking service only, because it
* gives slightly different callbacks (so the service doesn't get confused by callbacks
* triggered by/for the foreground UI.
*
* TODO clean up the execution model which is unnecessarily threaded due to legacy code
*
* @param accountId the account to check
* @param listener
*/
public void checkMail(final long accountId, final long tag, final MessagingListener listener) {
mListeners.checkMailStarted(mContext, accountId, tag);
// This puts the command on the queue (not synchronous)
listFolders(accountId, null);
// Put this on the queue as well so it follows listFolders
put("checkMail", listener, new Runnable() {
public void run() {
// send any pending outbound messages. note, there is a slight race condition
// here if we somehow don't have a sent folder, but this should never happen
// because the call to sendMessage() would have built one previously.
long inboxId = -1;
EmailContent.Account account =
EmailContent.Account.restoreAccountWithId(mContext, accountId);
if (account != null) {
long sentboxId = Mailbox.findMailboxOfType(mContext, accountId,
Mailbox.TYPE_SENT);
if (sentboxId != Mailbox.NO_MAILBOX) {
sendPendingMessagesSynchronous(account, sentboxId);
}
// find mailbox # for inbox and sync it.
// TODO we already know this in Controller, can we pass it in?
inboxId = Mailbox.findMailboxOfType(mContext, accountId, Mailbox.TYPE_INBOX);
if (inboxId != Mailbox.NO_MAILBOX) {
EmailContent.Mailbox mailbox =
EmailContent.Mailbox.restoreMailboxWithId(mContext, inboxId);
if (mailbox != null) {
synchronizeMailboxSynchronous(account, mailbox);
}
}
}
mListeners.checkMailFinished(mContext, accountId, inboxId, tag);
}
});
}
private static class Command {
public Runnable runnable;
public MessagingListener listener;
public String description;
@Override
public String toString() {
return description;
}
}
}
| true | true | private StoreSynchronizer.SyncResults synchronizeMailboxGeneric(
final EmailContent.Account account, final EmailContent.Mailbox folder)
throws MessagingException {
Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***");
ContentResolver resolver = mContext.getContentResolver();
// 0. We do not ever sync DRAFTS or OUTBOX (down or up)
if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) {
int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null);
return new StoreSynchronizer.SyncResults(totalMessages, 0);
}
// 1. Get the message list from the local store and create an index of the uids
Cursor localUidCursor = null;
HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
try {
localUidCursor = resolver.query(
EmailContent.Message.CONTENT_URI,
LocalMessageInfo.PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
},
null);
while (localUidCursor.moveToNext()) {
LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
localMessageMap.put(info.mServerId, info);
}
} finally {
if (localUidCursor != null) {
localUidCursor.close();
}
}
// 1a. Count the unread messages before changing anything
int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?" +
" AND " + MessageColumns.FLAG_READ + "=0",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
});
// 2. Open the remote folder and create the remote folder if necessary
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
|| folder.mType == Mailbox.TYPE_DRAFTS) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return new StoreSynchronizer.SyncResults(0, 0);
}
}
}
// 3, Open the remote folder. This pre-loads certain metadata like message count.
remoteFolder.open(OpenMode.READ_WRITE, null);
// 4. Trash any remote messages that are marked as trashed locally.
// TODO - this comment was here, but no code was here.
// 5. Get the remote message count.
int remoteMessageCount = remoteFolder.getMessageCount();
// 6. Determine the limit # of messages to download
int visibleLimit = folder.mVisibleLimit;
if (visibleLimit <= 0) {
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
mContext);
visibleLimit = info.mVisibleLimitDefault;
}
// 7. Create a list of messages to download
Message[] remoteMessages = new Message[0];
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
int newMessageCount = 0;
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
* Note, we also skip syncing messages which are flagged as "deleted message" sentinels,
* because they are locally deleted and we don't need or want the old message from
* the server.
*/
for (Message message : remoteMessages) {
LocalMessageInfo localMessage = localMessageMap.get(message.getUid());
if (localMessage == null) {
newMessageCount++;
}
if (localMessage == null
|| (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)
|| (localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_PARTIAL)) {
unsyncedMessages.add(message);
}
}
}
// 8. Download basic info about the new/unloaded messages (if any)
/*
* A list of messages that were downloaded and which did not have the Seen flag set.
* This will serve to indicate the true "new" message count that will be reported to
* the user via notification.
*/
final ArrayList<Message> newMessages = new ArrayList<Message>();
/*
* Fetch the flags and envelope only of the new messages. This is intended to get us
* critical data as fast as possible, and then we'll fill in the details.
*/
if (unsyncedMessages.size() > 0) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
fp.add(FetchProfile.Item.ENVELOPE);
final HashMap<String, LocalMessageInfo> localMapCopy =
new HashMap<String, LocalMessageInfo>(localMessageMap);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
try {
// Determine if the new message was already known (e.g. partial)
// And create or reload the full message info
LocalMessageInfo localMessageInfo =
localMapCopy.get(message.getUid());
EmailContent.Message localMessage = null;
if (localMessageInfo == null) {
localMessage = new EmailContent.Message();
} else {
localMessage = EmailContent.Message.restoreMessageWithId(
mContext, localMessageInfo.mId);
}
if (localMessage != null) {
try {
// Copy the fields that are available into the message
LegacyConversions.updateMessageFields(localMessage,
message, account.mId, folder.mId);
// Commit the message to the local store
saveOrUpdate(localMessage, mContext);
// Track the "new" ness of the downloaded message
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
} catch (MessagingException me) {
Log.e(Email.LOG_TAG,
"Error while copying downloaded message." + me);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message." + e.toString());
}
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
}
// 9. Refresh the flags for any messages in the local store that we didn't just download.
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages, fp, null);
boolean remoteSupportsSeen = false;
boolean remoteSupportsFlagged = false;
for (Flag flag : remoteFolder.getPermanentFlags()) {
if (flag == Flag.SEEN) {
remoteSupportsSeen = true;
}
if (flag == Flag.FLAGGED) {
remoteSupportsFlagged = true;
}
}
// Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3)
if (remoteSupportsSeen || remoteSupportsFlagged) {
for (Message remoteMessage : remoteMessages) {
LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid());
if (localMessageInfo == null) {
continue;
}
boolean localSeen = localMessageInfo.mFlagRead;
boolean remoteSeen = remoteMessage.isSet(Flag.SEEN);
boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen));
boolean localFlagged = localMessageInfo.mFlagFavorite;
boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED);
boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged));
if (newSeen || newFlagged) {
Uri uri = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, localMessageInfo.mId);
ContentValues updateValues = new ContentValues();
updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen);
updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged);
resolver.update(uri, updateValues, null, null);
}
}
}
// 10. Compute and store the unread message count.
// -- no longer necessary - Provider uses DB triggers to keep track
// int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
// if (remoteUnreadMessageCount == -1) {
// if (remoteSupportsSeenFlag) {
// /*
// * If remote folder doesn't supported unread message count but supports
// * seen flag, use local folder's unread message count and the size of
// * new messages. This mode is not used for POP3, or IMAP.
// */
//
// remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size();
// } else {
// /*
// * If remote folder doesn't supported unread message count and doesn't
// * support seen flag, use localUnreadCount and newMessageCount which
// * don't rely on remote SEEN flag. This mode is used by POP3.
// */
// remoteUnreadMessageCount = localUnreadCount + newMessageCount;
// }
// } else {
// /*
// * If remote folder supports unread message count, use remoteUnreadMessageCount.
// * This mode is used by IMAP.
// */
// }
// Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId);
// ContentValues updateValues = new ContentValues();
// updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount);
// resolver.update(uri, updateValues, null, null);
// 11. Remove any messages that are in the local store but no longer on the remote store.
HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet());
localUidsToDelete.removeAll(remoteUidMap.keySet());
for (String uidToDelete : localUidsToDelete) {
LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete);
// Delete associated data (attachment files)
// Attachment & Body records are auto-deleted when we delete the Message record
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId);
// Delete the message itself
Uri uriToDelete = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, infoToDelete.mId);
resolver.delete(uriToDelete, null, null);
// Delete extra rows (e.g. synced or deleted)
Uri syncRowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(syncRowToDelete, null, null);
Uri deletERowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(deletERowToDelete, null, null);
}
// 12. Divide the unsynced messages into small & large (by size)
// TODO doing this work here (synchronously) is problematic because it prevents the UI
// from affecting the order (e.g. download a message because the user requested it.) Much
// of this logic should move out to a different sync loop that attempts to update small
// groups of messages at a time, as a background task. However, we can't just return
// (yet) because POP messages don't have an envelope yet....
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
// 13. Download small messages
// TODO Problems with this implementation. 1. For IMAP, where we get a real envelope,
// this is going to be inefficient and duplicate work we've already done. 2. It's going
// back to the DB for a local message that we already had (and discarded).
// For small messages, we specify "body", which returns everything (incl. attachments)
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
// 14. Download large messages. We ask the server to give us the message structure,
// but not all of the attachments.
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
// POP doesn't support STRUCTURE mode, so we'll just do a partial download
// (hopefully enough to see some/all of the body) and mark the message for
// further download.
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
// TODO a good optimization here would be to make sure that all Stores set
// the proper size after this fetch and compare the before and after size. If
// they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the partially-loaded message and mark it partially loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_PARTIAL);
} else {
// We have a structure to deal with, from which
// we can pull down the parts we want to actually store.
// Build a list of parts we are interested in. Text parts will be downloaded
// right now, attachments will be left for later.
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
// Download the viewables immediately
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
}
// 15. Clean up and report results
remoteFolder.close(false);
// TODO - more
// Original sync code. Using for reference, will delete when done.
if (false) {
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
// localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
// localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// Update the listener with what we've found
// synchronized (mListeners) {
// for (MessagingListener l : mListeners) {
// l.synchronizeMailboxNewMessage(
// account,
// folder,
// localFolder.getMessage(message.getUid()));
// }
// }
}
/*
* Report successful sync
*/
StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults(
remoteFolder.getMessageCount(), newMessages.size());
remoteFolder.close(false);
// localFolder.close(false);
return results;
}
return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size());
}
| private StoreSynchronizer.SyncResults synchronizeMailboxGeneric(
final EmailContent.Account account, final EmailContent.Mailbox folder)
throws MessagingException {
Log.d(Email.LOG_TAG, "*** synchronizeMailboxGeneric ***");
ContentResolver resolver = mContext.getContentResolver();
// 0. We do not ever sync DRAFTS or OUTBOX (down or up)
if (folder.mType == Mailbox.TYPE_DRAFTS || folder.mType == Mailbox.TYPE_OUTBOX) {
int totalMessages = EmailContent.count(mContext, folder.getUri(), null, null);
return new StoreSynchronizer.SyncResults(totalMessages, 0);
}
// 1. Get the message list from the local store and create an index of the uids
Cursor localUidCursor = null;
HashMap<String, LocalMessageInfo> localMessageMap = new HashMap<String, LocalMessageInfo>();
try {
localUidCursor = resolver.query(
EmailContent.Message.CONTENT_URI,
LocalMessageInfo.PROJECTION,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
},
null);
while (localUidCursor.moveToNext()) {
LocalMessageInfo info = new LocalMessageInfo(localUidCursor);
localMessageMap.put(info.mServerId, info);
}
} finally {
if (localUidCursor != null) {
localUidCursor.close();
}
}
// 1a. Count the unread messages before changing anything
int localUnreadCount = EmailContent.count(mContext, EmailContent.Message.CONTENT_URI,
EmailContent.MessageColumns.ACCOUNT_KEY + "=?" +
" AND " + MessageColumns.MAILBOX_KEY + "=?" +
" AND " + MessageColumns.FLAG_READ + "=0",
new String[] {
String.valueOf(account.mId),
String.valueOf(folder.mId)
});
// 2. Open the remote folder and create the remote folder if necessary
Store remoteStore = Store.getInstance(account.getStoreUri(mContext), mContext, null);
Folder remoteFolder = remoteStore.getFolder(folder.mDisplayName);
/*
* If the folder is a "special" folder we need to see if it exists
* on the remote server. It if does not exist we'll try to create it. If we
* can't create we'll abort. This will happen on every single Pop3 folder as
* designed and on Imap folders during error conditions. This allows us
* to treat Pop3 and Imap the same in this code.
*/
if (folder.mType == Mailbox.TYPE_TRASH || folder.mType == Mailbox.TYPE_SENT
|| folder.mType == Mailbox.TYPE_DRAFTS) {
if (!remoteFolder.exists()) {
if (!remoteFolder.create(FolderType.HOLDS_MESSAGES)) {
return new StoreSynchronizer.SyncResults(0, 0);
}
}
}
// 3, Open the remote folder. This pre-loads certain metadata like message count.
remoteFolder.open(OpenMode.READ_WRITE, null);
// 4. Trash any remote messages that are marked as trashed locally.
// TODO - this comment was here, but no code was here.
// 5. Get the remote message count.
int remoteMessageCount = remoteFolder.getMessageCount();
// 6. Determine the limit # of messages to download
int visibleLimit = folder.mVisibleLimit;
if (visibleLimit <= 0) {
Store.StoreInfo info = Store.StoreInfo.getStoreInfo(account.getStoreUri(mContext),
mContext);
visibleLimit = info.mVisibleLimitDefault;
}
// 7. Create a list of messages to download
Message[] remoteMessages = new Message[0];
final ArrayList<Message> unsyncedMessages = new ArrayList<Message>();
HashMap<String, Message> remoteUidMap = new HashMap<String, Message>();
int newMessageCount = 0;
if (remoteMessageCount > 0) {
/*
* Message numbers start at 1.
*/
int remoteStart = Math.max(0, remoteMessageCount - visibleLimit) + 1;
int remoteEnd = remoteMessageCount;
remoteMessages = remoteFolder.getMessages(remoteStart, remoteEnd, null);
for (Message message : remoteMessages) {
remoteUidMap.put(message.getUid(), message);
}
/*
* Get a list of the messages that are in the remote list but not on the
* local store, or messages that are in the local store but failed to download
* on the last sync. These are the new messages that we will download.
* Note, we also skip syncing messages which are flagged as "deleted message" sentinels,
* because they are locally deleted and we don't need or want the old message from
* the server.
*/
for (Message message : remoteMessages) {
LocalMessageInfo localMessage = localMessageMap.get(message.getUid());
if (localMessage == null) {
newMessageCount++;
}
// localMessage == null -> message has never been created (not even headers)
// mFlagLoaded = UNLOADED -> message created, but none of body loaded
// mFlagLoaded = PARTIAL -> message created, a "sane" amt of body has been loaded
// mFlagLoaded = COMPLETE -> message body has been completely loaded
// mFlagLoaded = DELETED -> message has been deleted
// Only the first two of these are "unsynced", so let's retrieve them
if (localMessage == null ||
(localMessage.mFlagLoaded == EmailContent.Message.FLAG_LOADED_UNLOADED)) {
unsyncedMessages.add(message);
}
}
}
// 8. Download basic info about the new/unloaded messages (if any)
/*
* A list of messages that were downloaded and which did not have the Seen flag set.
* This will serve to indicate the true "new" message count that will be reported to
* the user via notification.
*/
final ArrayList<Message> newMessages = new ArrayList<Message>();
/*
* Fetch the flags and envelope only of the new messages. This is intended to get us
* critical data as fast as possible, and then we'll fill in the details.
*/
if (unsyncedMessages.size() > 0) {
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
fp.add(FetchProfile.Item.ENVELOPE);
final HashMap<String, LocalMessageInfo> localMapCopy =
new HashMap<String, LocalMessageInfo>(localMessageMap);
remoteFolder.fetch(unsyncedMessages.toArray(new Message[0]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
try {
// Determine if the new message was already known (e.g. partial)
// And create or reload the full message info
LocalMessageInfo localMessageInfo =
localMapCopy.get(message.getUid());
EmailContent.Message localMessage = null;
if (localMessageInfo == null) {
localMessage = new EmailContent.Message();
} else {
localMessage = EmailContent.Message.restoreMessageWithId(
mContext, localMessageInfo.mId);
}
if (localMessage != null) {
try {
// Copy the fields that are available into the message
LegacyConversions.updateMessageFields(localMessage,
message, account.mId, folder.mId);
// Commit the message to the local store
saveOrUpdate(localMessage, mContext);
// Track the "new" ness of the downloaded message
if (!message.isSet(Flag.SEEN)) {
newMessages.add(message);
}
} catch (MessagingException me) {
Log.e(Email.LOG_TAG,
"Error while copying downloaded message." + me);
}
}
}
catch (Exception e) {
Log.e(Email.LOG_TAG,
"Error while storing downloaded message." + e.toString());
}
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
}
// 9. Refresh the flags for any messages in the local store that we didn't just download.
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.FLAGS);
remoteFolder.fetch(remoteMessages, fp, null);
boolean remoteSupportsSeen = false;
boolean remoteSupportsFlagged = false;
for (Flag flag : remoteFolder.getPermanentFlags()) {
if (flag == Flag.SEEN) {
remoteSupportsSeen = true;
}
if (flag == Flag.FLAGGED) {
remoteSupportsFlagged = true;
}
}
// Update the SEEN & FLAGGED (star) flags (if supported remotely - e.g. not for POP3)
if (remoteSupportsSeen || remoteSupportsFlagged) {
for (Message remoteMessage : remoteMessages) {
LocalMessageInfo localMessageInfo = localMessageMap.get(remoteMessage.getUid());
if (localMessageInfo == null) {
continue;
}
boolean localSeen = localMessageInfo.mFlagRead;
boolean remoteSeen = remoteMessage.isSet(Flag.SEEN);
boolean newSeen = (remoteSupportsSeen && (remoteSeen != localSeen));
boolean localFlagged = localMessageInfo.mFlagFavorite;
boolean remoteFlagged = remoteMessage.isSet(Flag.FLAGGED);
boolean newFlagged = (remoteSupportsFlagged && (localFlagged != remoteFlagged));
if (newSeen || newFlagged) {
Uri uri = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, localMessageInfo.mId);
ContentValues updateValues = new ContentValues();
updateValues.put(EmailContent.Message.FLAG_READ, remoteSeen);
updateValues.put(EmailContent.Message.FLAG_FAVORITE, remoteFlagged);
resolver.update(uri, updateValues, null, null);
}
}
}
// 10. Compute and store the unread message count.
// -- no longer necessary - Provider uses DB triggers to keep track
// int remoteUnreadMessageCount = remoteFolder.getUnreadMessageCount();
// if (remoteUnreadMessageCount == -1) {
// if (remoteSupportsSeenFlag) {
// /*
// * If remote folder doesn't supported unread message count but supports
// * seen flag, use local folder's unread message count and the size of
// * new messages. This mode is not used for POP3, or IMAP.
// */
//
// remoteUnreadMessageCount = folder.mUnreadCount + newMessages.size();
// } else {
// /*
// * If remote folder doesn't supported unread message count and doesn't
// * support seen flag, use localUnreadCount and newMessageCount which
// * don't rely on remote SEEN flag. This mode is used by POP3.
// */
// remoteUnreadMessageCount = localUnreadCount + newMessageCount;
// }
// } else {
// /*
// * If remote folder supports unread message count, use remoteUnreadMessageCount.
// * This mode is used by IMAP.
// */
// }
// Uri uri = ContentUris.withAppendedId(EmailContent.Mailbox.CONTENT_URI, folder.mId);
// ContentValues updateValues = new ContentValues();
// updateValues.put(EmailContent.Mailbox.UNREAD_COUNT, remoteUnreadMessageCount);
// resolver.update(uri, updateValues, null, null);
// 11. Remove any messages that are in the local store but no longer on the remote store.
HashSet<String> localUidsToDelete = new HashSet<String>(localMessageMap.keySet());
localUidsToDelete.removeAll(remoteUidMap.keySet());
for (String uidToDelete : localUidsToDelete) {
LocalMessageInfo infoToDelete = localMessageMap.get(uidToDelete);
// Delete associated data (attachment files)
// Attachment & Body records are auto-deleted when we delete the Message record
AttachmentProvider.deleteAllAttachmentFiles(mContext, account.mId, infoToDelete.mId);
// Delete the message itself
Uri uriToDelete = ContentUris.withAppendedId(
EmailContent.Message.CONTENT_URI, infoToDelete.mId);
resolver.delete(uriToDelete, null, null);
// Delete extra rows (e.g. synced or deleted)
Uri syncRowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(syncRowToDelete, null, null);
Uri deletERowToDelete = ContentUris.withAppendedId(
EmailContent.Message.UPDATED_CONTENT_URI, infoToDelete.mId);
resolver.delete(deletERowToDelete, null, null);
}
// 12. Divide the unsynced messages into small & large (by size)
// TODO doing this work here (synchronously) is problematic because it prevents the UI
// from affecting the order (e.g. download a message because the user requested it.) Much
// of this logic should move out to a different sync loop that attempts to update small
// groups of messages at a time, as a background task. However, we can't just return
// (yet) because POP messages don't have an envelope yet....
ArrayList<Message> largeMessages = new ArrayList<Message>();
ArrayList<Message> smallMessages = new ArrayList<Message>();
for (Message message : unsyncedMessages) {
if (message.getSize() > (MAX_SMALL_MESSAGE_SIZE)) {
largeMessages.add(message);
} else {
smallMessages.add(message);
}
}
// 13. Download small messages
// TODO Problems with this implementation. 1. For IMAP, where we get a real envelope,
// this is going to be inefficient and duplicate work we've already done. 2. It's going
// back to the DB for a local message that we already had (and discarded).
// For small messages, we specify "body", which returns everything (incl. attachments)
fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
remoteFolder.fetch(smallMessages.toArray(new Message[smallMessages.size()]), fp,
new MessageRetrievalListener() {
public void messageRetrieved(Message message) {
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
@Override
public void loadAttachmentProgress(int progress) {
}
});
// 14. Download large messages. We ask the server to give us the message structure,
// but not all of the attachments.
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]), fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
// POP doesn't support STRUCTURE mode, so we'll just do a partial download
// (hopefully enough to see some/all of the body) and mark the message for
// further download.
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
// TODO a good optimization here would be to make sure that all Stores set
// the proper size after this fetch and compare the before and after size. If
// they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the partially-loaded message and mark it partially loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_PARTIAL);
} else {
// We have a structure to deal with, from which
// we can pull down the parts we want to actually store.
// Build a list of parts we are interested in. Text parts will be downloaded
// right now, attachments will be left for later.
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
// Download the viewables immediately
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally and mark it fully loaded
copyOneMessageToProvider(message, account, folder,
EmailContent.Message.FLAG_LOADED_COMPLETE);
}
}
// 15. Clean up and report results
remoteFolder.close(false);
// TODO - more
// Original sync code. Using for reference, will delete when done.
if (false) {
/*
* Now do the large messages that require more round trips.
*/
fp.clear();
fp.add(FetchProfile.Item.STRUCTURE);
remoteFolder.fetch(largeMessages.toArray(new Message[largeMessages.size()]),
fp, null);
for (Message message : largeMessages) {
if (message.getBody() == null) {
/*
* The provider was unable to get the structure of the message, so
* we'll download a reasonable portion of the messge and mark it as
* incomplete so the entire thing can be downloaded later if the user
* wishes to download it.
*/
fp.clear();
fp.add(FetchProfile.Item.BODY_SANE);
/*
* TODO a good optimization here would be to make sure that all Stores set
* the proper size after this fetch and compare the before and after size. If
* they equal we can mark this SYNCHRONIZED instead of PARTIALLY_SYNCHRONIZED
*/
remoteFolder.fetch(new Message[] { message }, fp, null);
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating that the message has been partially downloaded and
// is ready for view.
// localMessage.setFlag(Flag.X_DOWNLOADED_PARTIAL, true);
} else {
/*
* We have a structure to deal with, from which
* we can pull down the parts we want to actually store.
* Build a list of parts we are interested in. Text parts will be downloaded
* right now, attachments will be left for later.
*/
ArrayList<Part> viewables = new ArrayList<Part>();
ArrayList<Part> attachments = new ArrayList<Part>();
MimeUtility.collectParts(message, viewables, attachments);
/*
* Now download the parts we're interested in storing.
*/
for (Part part : viewables) {
fp.clear();
fp.add(part);
// TODO what happens if the network connection dies? We've got partial
// messages with incorrect status stored.
remoteFolder.fetch(new Message[] { message }, fp, null);
}
// Store the updated message locally
// localFolder.appendMessages(new Message[] {
// message
// });
// Message localMessage = localFolder.getMessage(message.getUid());
// Set a flag indicating this message has been fully downloaded and can be
// viewed.
// localMessage.setFlag(Flag.X_DOWNLOADED_FULL, true);
}
// Update the listener with what we've found
// synchronized (mListeners) {
// for (MessagingListener l : mListeners) {
// l.synchronizeMailboxNewMessage(
// account,
// folder,
// localFolder.getMessage(message.getUid()));
// }
// }
}
/*
* Report successful sync
*/
StoreSynchronizer.SyncResults results = new StoreSynchronizer.SyncResults(
remoteFolder.getMessageCount(), newMessages.size());
remoteFolder.close(false);
// localFolder.close(false);
return results;
}
return new StoreSynchronizer.SyncResults(remoteMessageCount, newMessages.size());
}
|
diff --git a/src/DVN-web/src/edu/harvard/hmdc/vdcnet/web/servlet/VDCAdminServlet.java b/src/DVN-web/src/edu/harvard/hmdc/vdcnet/web/servlet/VDCAdminServlet.java
index fab64d81d..e147cab31 100644
--- a/src/DVN-web/src/edu/harvard/hmdc/vdcnet/web/servlet/VDCAdminServlet.java
+++ b/src/DVN-web/src/edu/harvard/hmdc/vdcnet/web/servlet/VDCAdminServlet.java
@@ -1,216 +1,220 @@
/*
* Dataverse Network - A web application to distribute, share and analyze quantitative data.
* Copyright (C) 2007
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* VDCAdminServlet.java
*
* Created on August 30, 2007, 3:05 PM
*/
package edu.harvard.hmdc.vdcnet.web.servlet;
import edu.harvard.hmdc.vdcnet.admin.NetworkRoleServiceLocal;
import edu.harvard.hmdc.vdcnet.admin.PasswordEncryption;
import edu.harvard.hmdc.vdcnet.admin.UserServiceLocal;
import edu.harvard.hmdc.vdcnet.admin.VDCUser;
import edu.harvard.hmdc.vdcnet.study.StudyServiceLocal;
import java.io.*;
import java.net.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;
/**
*
* @author Gustavo
* @version
*/
public class VDCAdminServlet extends HttpServlet {
@Resource(name="jdbc/VDCNetDS") DataSource dvnDatasource;
@EJB StudyServiceLocal studyService;
@EJB UserServiceLocal userService;
private boolean isNetworkAdmin(HttpServletRequest req) {
VDCUser user = null;
if ( LoginFilter.getLoginBean(req) != null ) {
user= LoginFilter.getLoginBean(req).getUser();
if (user.getNetworkRole()!=null && user.getNetworkRole().getName().equals(NetworkRoleServiceLocal.ADMIN) ) {
return true;
}
}
return false;
}
/** Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
beginPage(out);
out.println("<h3>Admin</h3>");
out.println("<form method=POST>");
if (isNetworkAdmin(req)) {
out.println("To remove a study lock, input the study id and click on the button below.<br/>");
out.print("<input name=\"studyId\" size=8>");
out.print("<input name=removeLock value=\"Remove Lock\" type=submit />");
out.print("<hr>");
}
out.println("To encrypt all current passwords, click on the Encrypt Passwords button<br/>");
out.print("<input name=encryptPasswords value=\"Encrypt Passwords\" type=submit />");
out.print("<hr>");
out.print("<input name=exportStudies value=\"Export Studies\" type=submit />");
out.print("<hr>");
out.println("</form>");
endPage(out);
}
/** Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
if (isNetworkAdmin(req) || req.getParameter("encryptPasswords")!=null ) {
if ( req.getParameter("removeLock") != null) {
Long studyId = null;
try {
studyId = new Long( req.getParameter("studyId") );
studyService.removeStudyLock(studyId);
displayMessage (out,"Study lock removed.", "(for study id = " + studyId + ")");
} catch (NumberFormatException nfe) {
displayMessage (out, "Action failed.", "The study id must be of type Long.");
} catch (Exception e) {
e.printStackTrace();
displayMessage (out, "Action failed.", "An unknown error occurred trying to remove lock for study id = " + studyId);
}
} else if (req.getParameter("encryptPasswords") != null) {
try {
encryptPasswords();
displayMessage(out, "Passwords encrypted.");
} catch(SQLException e) {
e.printStackTrace();
if (e.getSQLState().equals("42703")) {
displayMessage(out, "Passwords already encrypted");
} else {
displayMessage (out, "SQLException updating passwords");
}
}
} else if (req.getParameter("exportStudies") != null) {
- studyService.exportUpdatedStudies();
- displayMessage(out, "Export completed.");
+ try {
+ studyService.exportUpdatedStudies();
+ displayMessage(out, "Export completed.");
+ } catch (Exception e) {
+ displayMessage(out, "Exception occurred while exporting studies. See export log for details.");
+ }
}else {
displayMessage (out, "You have selected an action that is not allowed.");
}
} else {
displayMessage(out, "You are not authorized for this action, please log in as a network administrator.");
}
}
private void beginPage(PrintWriter out) {
out.println("<html>");
out.println("<head>");
out.println("<title>Admin Servlet</title>");
out.println("</head>");
out.println("<body><center>");
}
private void endPage(PrintWriter out) {
out.println("</center></body>");
out.println("</html>");
out.close();
}
private void displayMessage(PrintWriter out, String title) {
displayMessage(out, title, null);
}
private void displayMessage(PrintWriter out, String title, String message) {
beginPage(out);
out.println("<h3>" + title + "</h3>");
if (message != null && !message.trim().equals("") ) {
out.println(message);
}
endPage(out);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "VDC Admin Servlet";
}
private void encryptPasswords() throws SQLException {
String selectString = "SELECT id, password from vdcuser";
String updateString = "update vdcUser set encryptedpassword = ? where id = ?";
Connection conn=null;
PreparedStatement sth = null;
PreparedStatement updateStatement=null;
conn = dvnDatasource.getConnection();
sth = conn.prepareStatement(selectString);
ResultSet rs = sth.executeQuery();
List<String> ids = new ArrayList<String>();
List<String> passwords = new ArrayList<String>();
while(rs.next()) {
ids.add(rs.getString(1));
passwords.add(rs.getString(2));
}
updateStatement = conn.prepareStatement(updateString);
for (int i=0;i<ids.size();i++) {
if (passwords.get(i)!=null && !passwords.get(i).trim().equals("")) {
updateStatement.setString(1, userService.encryptPassword(passwords.get(i)));
updateStatement.setString(2, ids.get(i));
updateStatement.executeUpdate();
}
}
updateStatement = conn.prepareStatement("alter table vdcuser drop column password");
updateStatement.executeUpdate();
}
// </editor-fold>
}
| true | true | protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
if (isNetworkAdmin(req) || req.getParameter("encryptPasswords")!=null ) {
if ( req.getParameter("removeLock") != null) {
Long studyId = null;
try {
studyId = new Long( req.getParameter("studyId") );
studyService.removeStudyLock(studyId);
displayMessage (out,"Study lock removed.", "(for study id = " + studyId + ")");
} catch (NumberFormatException nfe) {
displayMessage (out, "Action failed.", "The study id must be of type Long.");
} catch (Exception e) {
e.printStackTrace();
displayMessage (out, "Action failed.", "An unknown error occurred trying to remove lock for study id = " + studyId);
}
} else if (req.getParameter("encryptPasswords") != null) {
try {
encryptPasswords();
displayMessage(out, "Passwords encrypted.");
} catch(SQLException e) {
e.printStackTrace();
if (e.getSQLState().equals("42703")) {
displayMessage(out, "Passwords already encrypted");
} else {
displayMessage (out, "SQLException updating passwords");
}
}
} else if (req.getParameter("exportStudies") != null) {
studyService.exportUpdatedStudies();
displayMessage(out, "Export completed.");
}else {
displayMessage (out, "You have selected an action that is not allowed.");
}
} else {
displayMessage(out, "You are not authorized for this action, please log in as a network administrator.");
}
}
| protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
if (isNetworkAdmin(req) || req.getParameter("encryptPasswords")!=null ) {
if ( req.getParameter("removeLock") != null) {
Long studyId = null;
try {
studyId = new Long( req.getParameter("studyId") );
studyService.removeStudyLock(studyId);
displayMessage (out,"Study lock removed.", "(for study id = " + studyId + ")");
} catch (NumberFormatException nfe) {
displayMessage (out, "Action failed.", "The study id must be of type Long.");
} catch (Exception e) {
e.printStackTrace();
displayMessage (out, "Action failed.", "An unknown error occurred trying to remove lock for study id = " + studyId);
}
} else if (req.getParameter("encryptPasswords") != null) {
try {
encryptPasswords();
displayMessage(out, "Passwords encrypted.");
} catch(SQLException e) {
e.printStackTrace();
if (e.getSQLState().equals("42703")) {
displayMessage(out, "Passwords already encrypted");
} else {
displayMessage (out, "SQLException updating passwords");
}
}
} else if (req.getParameter("exportStudies") != null) {
try {
studyService.exportUpdatedStudies();
displayMessage(out, "Export completed.");
} catch (Exception e) {
displayMessage(out, "Exception occurred while exporting studies. See export log for details.");
}
}else {
displayMessage (out, "You have selected an action that is not allowed.");
}
} else {
displayMessage(out, "You are not authorized for this action, please log in as a network administrator.");
}
}
|
diff --git a/src/com/sis/util/StringHelper.java b/src/com/sis/util/StringHelper.java
index 32f369d..e837776 100644
--- a/src/com/sis/util/StringHelper.java
+++ b/src/com/sis/util/StringHelper.java
@@ -1,149 +1,149 @@
package com.sis.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import org.apache.commons.lang.StringEscapeUtils;
/**
* miscellaneous helper for String related tasks
*
* @author CR
*
*/
public class StringHelper {
// public static byte[] parse
private static final DateFormat databaseDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String databaseDate() {
return databaseDate(new Date());
}
public static String databaseDate(Date date) {
return databaseDateFormat.format(date);
}
public static Date createDateByDatabaseDate(String databaseDate) {
return createDateByDatabaseDate(databaseDate, new Date());
}
public static Date createDateByDatabaseDate(String databaseDate, Date defaultValue) {
try {
return databaseDateFormat.parse(databaseDate);
} catch (ParseException e) {
return defaultValue;
}
}
public static String calculateMD5(java.lang.String input) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
md5.reset();
md5.update(input.getBytes());
byte[] result = md5.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0; i<result.length; i++) {
- hexString.append(Integer.toHexString(0xFF & result[i]));
+ hexString.append(String.format("%02X", 0xFF & result[i]));
}
return hexString.toString();
}
public static String[] objectArrayToStringArray(Object [] objArray) {
String [] array = new String[objArray.length];
int i = 0;
for (Object obj : objArray) {
array[i++] = obj.toString();
}
return array;
}
/**
* @deprecated use {@link ArrayHelper#objectArrayToObjectArray(Object[])} instead
* @param objArray
* @return
*/
public static Object[] objectArrayToObjectArray(Object [] objArray) {
return ArrayHelper.objectArrayToObjectArray(objArray);
}
public static String coalesce(Object[] coll, Character seperator) {
StringBuilder sb = new StringBuilder();
for (Object object : coll) {
if (object == null) {
continue;
}
if (sb.length() > 0) {
sb.append(seperator);
}
sb.append(object.toString());
}
return sb.toString();
}
public static String coalesce(Collection<?> coll, Character seperator) {
StringBuilder sb = new StringBuilder();
for (Object object : coll) {
if (object == null) {
continue;
}
if (sb.length() > 0) {
sb.append(seperator);
}
sb.append(object.toString());
}
return sb.toString();
}
/**
* @deprecated use {@link ArrayHelper#inArrayList(ArrayList, Object)} instead
*/
public static boolean inArrayList(ArrayList<?> strings, String string) {
for (Object object : strings) {
if (object.toString().equals(string)) {
return true;
}
}
return false;
}
/**
* @deprecated use {@link ArrayHelper#inArray(Object[], Object)} instead
*/
public static boolean inArray(String[] strings, String string) {
for (Object object : strings) {
if (object.toString().equals(string)) {
return true;
}
}
return false;
}
public static String escapeHtml(String input) {
return StringEscapeUtils.escapeHtml(input);
}
}
| true | true | public static String calculateMD5(java.lang.String input) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
md5.reset();
md5.update(input.getBytes());
byte[] result = md5.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0; i<result.length; i++) {
hexString.append(Integer.toHexString(0xFF & result[i]));
}
return hexString.toString();
}
| public static String calculateMD5(java.lang.String input) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
md5.reset();
md5.update(input.getBytes());
byte[] result = md5.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0; i<result.length; i++) {
hexString.append(String.format("%02X", 0xFF & result[i]));
}
return hexString.toString();
}
|
diff --git a/src/main/java/net/pterodactylus/sone/web/CreateReplyPage.java b/src/main/java/net/pterodactylus/sone/web/CreateReplyPage.java
index 8fb44801..420fb86f 100644
--- a/src/main/java/net/pterodactylus/sone/web/CreateReplyPage.java
+++ b/src/main/java/net/pterodactylus/sone/web/CreateReplyPage.java
@@ -1,81 +1,84 @@
/*
* Sone - CreateReplyPage.java - Copyright © 2010 David Roden
*
* 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.pterodactylus.sone.web;
import net.pterodactylus.sone.data.Post;
import net.pterodactylus.sone.data.Sone;
import net.pterodactylus.sone.web.page.Page.Request.Method;
import net.pterodactylus.util.template.Template;
/**
* This page lets the user post a reply to a post.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public class CreateReplyPage extends SoneTemplatePage {
/**
* Creates a new “create reply” page.
*
* @param template
* The template to render
* @param webInterface
* The Sone web interface
*/
public CreateReplyPage(Template template, WebInterface webInterface) {
super("createReply.html", template, "Page.CreateReply.Title", webInterface);
}
//
// TEMPLATEPAGE METHODS
//
/**
* {@inheritDoc}
*/
@Override
protected void processTemplate(Request request, Template template) throws RedirectException {
super.processTemplate(request, template);
String postId = request.getHttpRequest().getPartAsStringFailsafe("post", 36);
String text = request.getHttpRequest().getPartAsStringFailsafe("text", 65536).trim();
+ String returnPage = request.getHttpRequest().getPartAsStringFailsafe("returnPage", 64);
+ System.out.println("postId: " + postId + ", text: " + text + ", returnPage: " + returnPage);
if (request.getMethod() == Method.POST) {
Post post = webInterface.core().getPost(postId);
if (text.length() > 0) {
Sone currentSone = getCurrentSone(request.getToadletContext());
webInterface.core().createReply(currentSone, post, text);
- throw new RedirectException("viewPost.html?post=" + post.getId());
+ throw new RedirectException(returnPage);
}
template.set("errorTextEmpty", true);
}
template.set("postId", postId);
template.set("text", text);
+ template.set("returnPage", returnPage);
}
//
// SONETEMPLATEPAGE METHODS
//
/**
* {@inheritDoc}
*/
@Override
protected boolean requiresLogin() {
return true;
}
}
| false | true | protected void processTemplate(Request request, Template template) throws RedirectException {
super.processTemplate(request, template);
String postId = request.getHttpRequest().getPartAsStringFailsafe("post", 36);
String text = request.getHttpRequest().getPartAsStringFailsafe("text", 65536).trim();
if (request.getMethod() == Method.POST) {
Post post = webInterface.core().getPost(postId);
if (text.length() > 0) {
Sone currentSone = getCurrentSone(request.getToadletContext());
webInterface.core().createReply(currentSone, post, text);
throw new RedirectException("viewPost.html?post=" + post.getId());
}
template.set("errorTextEmpty", true);
}
template.set("postId", postId);
template.set("text", text);
}
| protected void processTemplate(Request request, Template template) throws RedirectException {
super.processTemplate(request, template);
String postId = request.getHttpRequest().getPartAsStringFailsafe("post", 36);
String text = request.getHttpRequest().getPartAsStringFailsafe("text", 65536).trim();
String returnPage = request.getHttpRequest().getPartAsStringFailsafe("returnPage", 64);
System.out.println("postId: " + postId + ", text: " + text + ", returnPage: " + returnPage);
if (request.getMethod() == Method.POST) {
Post post = webInterface.core().getPost(postId);
if (text.length() > 0) {
Sone currentSone = getCurrentSone(request.getToadletContext());
webInterface.core().createReply(currentSone, post, text);
throw new RedirectException(returnPage);
}
template.set("errorTextEmpty", true);
}
template.set("postId", postId);
template.set("text", text);
template.set("returnPage", returnPage);
}
|
diff --git a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java
index e9ba4c22a..e342a7b3f 100644
--- a/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java
+++ b/tests/gdx-tests-lwjgl/src/com/badlogic/gdx/tests/lwjgl/LwjglDebugStarter.java
@@ -1,50 +1,49 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.tests.lwjgl;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.tests.AnimationTest;
import com.badlogic.gdx.tests.ETC1Test;
import com.badlogic.gdx.tests.FullscreenTest;
import com.badlogic.gdx.tests.InputTest;
import com.badlogic.gdx.tests.TideMapAssetManagerTest;
import com.badlogic.gdx.tests.TideMapDirectLoaderTest;
import com.badlogic.gdx.tests.TiledMapAssetManagerTest;
import com.badlogic.gdx.tests.TiledMapDirectLoaderTest;
import com.badlogic.gdx.tests.bench.TiledMapBench;
import com.badlogic.gdx.tests.superkoalio.SuperKoalio;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.utils.SharedLibraryLoader;
public class LwjglDebugStarter {
public static void main (String[] argv) {
// this is only here for me to debug native code faster
new SharedLibraryLoader("../../extensions/gdx-audio/libs/gdx-audio-natives.jar").load("gdx-audio");
new SharedLibraryLoader("../../extensions/gdx-image/libs/gdx-image-natives.jar").load("gdx-image");
new SharedLibraryLoader("../../extensions/gdx-freetype/libs/gdx-freetype-natives.jar").load("gdx-freetype");
new SharedLibraryLoader("../../extensions/gdx-controllers/gdx-controllers-desktop/libs/gdx-controllers-desktop-natives.jar").load("gdx-controllers-desktop");
new SharedLibraryLoader("../../gdx/libs/gdx-natives.jar").load("gdx");
- MathUtils.ceil(1);
GdxTest test = new AnimationTest();
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.useGL20 = test.needsGL20();
new LwjglApplication(test, config);
}
}
| true | true | public static void main (String[] argv) {
// this is only here for me to debug native code faster
new SharedLibraryLoader("../../extensions/gdx-audio/libs/gdx-audio-natives.jar").load("gdx-audio");
new SharedLibraryLoader("../../extensions/gdx-image/libs/gdx-image-natives.jar").load("gdx-image");
new SharedLibraryLoader("../../extensions/gdx-freetype/libs/gdx-freetype-natives.jar").load("gdx-freetype");
new SharedLibraryLoader("../../extensions/gdx-controllers/gdx-controllers-desktop/libs/gdx-controllers-desktop-natives.jar").load("gdx-controllers-desktop");
new SharedLibraryLoader("../../gdx/libs/gdx-natives.jar").load("gdx");
MathUtils.ceil(1);
GdxTest test = new AnimationTest();
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.useGL20 = test.needsGL20();
new LwjglApplication(test, config);
}
| public static void main (String[] argv) {
// this is only here for me to debug native code faster
new SharedLibraryLoader("../../extensions/gdx-audio/libs/gdx-audio-natives.jar").load("gdx-audio");
new SharedLibraryLoader("../../extensions/gdx-image/libs/gdx-image-natives.jar").load("gdx-image");
new SharedLibraryLoader("../../extensions/gdx-freetype/libs/gdx-freetype-natives.jar").load("gdx-freetype");
new SharedLibraryLoader("../../extensions/gdx-controllers/gdx-controllers-desktop/libs/gdx-controllers-desktop-natives.jar").load("gdx-controllers-desktop");
new SharedLibraryLoader("../../gdx/libs/gdx-natives.jar").load("gdx");
GdxTest test = new AnimationTest();
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.useGL20 = test.needsGL20();
new LwjglApplication(test, config);
}
|
diff --git a/vme-web/src/main/java/org/vme/service/search/vme/VmeSearchService.java b/vme-web/src/main/java/org/vme/service/search/vme/VmeSearchService.java
index f5cff487..d3416343 100644
--- a/vme-web/src/main/java/org/vme/service/search/vme/VmeSearchService.java
+++ b/vme-web/src/main/java/org/vme/service/search/vme/VmeSearchService.java
@@ -1,357 +1,357 @@
package org.vme.service.search.vme;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.apache.commons.lang.StringUtils;
import org.fao.fi.figis.dao.FigisDao;
import org.fao.fi.figis.domain.VmeObservation;
import org.fao.fi.vme.dao.config.VmeDB;
import org.fao.fi.vme.domain.GeneralMeasure;
import org.fao.fi.vme.domain.GeoRef;
import org.fao.fi.vme.domain.InformationSource;
import org.fao.fi.vme.domain.Profile;
import org.fao.fi.vme.domain.SpecificMeasure;
import org.fao.fi.vme.domain.ValidityPeriod;
import org.fao.fi.vme.domain.Vme;
import org.fao.fi.vme.domain.util.MultiLingualStringUtil;
import org.vme.service.dto.VmeGetRequestDto;
import org.vme.service.dto.VmeRequestDto;
import org.vme.service.dto.VmeSearchDto;
import org.vme.service.dto.VmeSearchRequestDto;
import org.vme.service.dto.VmeSearchResult;
import org.vme.service.reference.ReferenceServiceException;
import org.vme.service.reference.ReferenceServiceFactory;
import org.vme.service.reference.domain.Authority;
import org.vme.service.reference.domain.VmeCriteria;
import org.vme.service.reference.domain.VmeType;
public class VmeSearchService implements SearchService {
@Inject
@VmeDB
private EntityManager entityManager;
protected FigisDao dao;
private MultiLingualStringUtil u = new MultiLingualStringUtil();
public VmeSearchService() {
System.out.println("VME search engine 1.0");
}
@SuppressWarnings("unchecked")
public VmeSearchResult search(VmeSearchRequestDto request) throws Exception {
if (request.hasYear()){
} else {
request.setYear( Calendar.getInstance().get(Calendar.YEAR));
}
Query query = entityManager.createQuery(createHibernateSearchTextualQuery(request));
List<Vme> result = (List<Vme>)query.getResultList();
List<Vme> toRemove = postPurgeResult(request, result);
VmeSearchResult res = convertPersistenceResult(request, (List<Vme>) result, toRemove);
return res;
}
public VmeSearchResult get(VmeGetRequestDto request) {
if (request.hasYear()){
} else {
request.setYear( Calendar.getInstance().get(Calendar.YEAR));
}
String text_query;
if (request.getId()>0){
text_query = "from Vme vme where vme.id = " + request.getId();
} else if (request.hasInventoryIdentifier()) {
text_query = "from Vme vme where vme.inventoryIdentifier = '" + request.getInventoryIdentifier() + "'";
} else if (request.hasGeographicFeatureId()) {
text_query = "SELECT vme from Vme vme, GEO_REF gfl WHERE vme = gfl.vme and gfl IN (SELECT gfl from GEO_REF WHERE gfl.geographicFeatureID = '" + request.getGeographicFeatureId() + "')";
} else text_query = "";
Query query = entityManager.createQuery(text_query);
List<?> result = query.getResultList();
@SuppressWarnings("unchecked")
VmeSearchResult res = convertPersistenceResult(request, (List<Vme>) result, null);
return res;
}
private String createHibernateSearchTextualQuery(VmeSearchRequestDto request) throws Exception {
StringBuffer txtQuery = new StringBuffer(200);
String conjunction;
txtQuery.append("Select vme from Vme vme");
if (request.hasAtLeastOneParameterButText()){
txtQuery.append(" where");
conjunction = "";
} else {
return txtQuery.toString();
}
if (request.hasAuthority()){
Authority vmeAuthority = (Authority) ReferenceServiceFactory.getService().getReference(Authority.class, (long) request.getAuthority());
String authority = vmeAuthority.getAcronym();
txtQuery.append(conjunction);
txtQuery.append(" vme.rfmo.id = '");
txtQuery.append(authority);
txtQuery.append("'");
conjunction = " AND";
}
if (request.hasCriteria()){
VmeCriteria vmeCriteria = (VmeCriteria) ReferenceServiceFactory.getService().getReference(VmeCriteria.class, (long) request.getCriteria());
String criteria = vmeCriteria.getName();
txtQuery.append(conjunction);
txtQuery.append(" vme.criteria = '");
txtQuery.append(criteria);
txtQuery.append("'");
conjunction = " AND";
}
if (request.hasType()){
VmeType vmeType = (VmeType) ReferenceServiceFactory.getService().getReference(VmeType.class, (long) request.getType());
String areaType = vmeType.getName();
txtQuery.append(conjunction);
txtQuery.append(" vme.areaType = '");
txtQuery.append(areaType);
txtQuery.append("'");
conjunction = " AND";
}
txtQuery.append(" AND vme.validityPeriod.beginYear <= ");
txtQuery.append(request.getYear());
txtQuery.append(" AND vme.validityPeriod.endYear >= ");
txtQuery.append(request.getYear());
String res = txtQuery.toString();
System.out.println("FAB:" + res);
return res;
}
private List<Vme> postPurgeResult (VmeSearchRequestDto request, List<Vme> result){
int requested_year = request.getYear();
List<Vme> res = new LinkedList<Vme>();
// Patch placed to solve VME-10 JIRA issue.
for (Vme vme : result) {
if (vme.getRfmo().getId().trim().equals("SIODFA")){
res.add(vme);
}
}
if (requested_year>0) {
for (Vme vme : result) {
boolean is_good = false;
List<GeoRef> georef = vme.getGeoRefList();
for (GeoRef profile : georef) {
if (profile.getYear()==requested_year) {
is_good = true;
break;
}
}
if (!is_good){
ValidityPeriod validityPeriod = vme.getValidityPeriod();
if (validityPeriod.getBeginYear()<= requested_year && validityPeriod.getEndYear()>= requested_year){
is_good = true;
}
}
if (is_good && request.hasText()){
is_good = containRelevantText(vme, request.getText());
}
if (!is_good){
res.add(vme);
}
}
}
return res;
}
private boolean containRelevantText(Vme vme, String text) {
if (StringUtils.containsIgnoreCase(vme.getAreaType(), text)) return true;
if (StringUtils.containsIgnoreCase(vme.getCriteria(), text)) return true;
for (String element : vme.getGeoArea().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
if (StringUtils.containsIgnoreCase(vme.getGeoform(), text)) return true;
for (GeoRef geoRef : vme.getGeoRefList()) {
if (StringUtils.containsIgnoreCase(geoRef.getGeographicFeatureID(), text)) return true;
}
if (StringUtils.containsIgnoreCase(vme.getInventoryIdentifier(), text)) return true;
for (String element : vme.getName().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
for (Profile profile : vme.getProfileList()) {
for (String element : profile.getDescriptionBiological().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
for (String element : profile.getDescriptionImpact().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
for (String element : profile.getDescriptionPhisical().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
for (GeneralMeasure generalMeasure : vme.getRfmo().getGeneralMeasureList()) {
if (StringUtils.containsIgnoreCase(generalMeasure.getFishingAreas(), text)) return true;
if (generalMeasure.getExplorataryFishingProtocols()!=null){
for (String element : generalMeasure.getExplorataryFishingProtocols().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getVmeEncounterProtocols()!=null){
for (String element : generalMeasure.getVmeEncounterProtocols().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getVmeIndicatorSpecies()!=null){
for (String element : generalMeasure.getVmeIndicatorSpecies().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getVmeThreshold()!=null){
for (String element : generalMeasure.getVmeThreshold().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getInformationSourceList()!=null){
for (InformationSource informationSource : generalMeasure.getInformationSourceList()) {
if (informationSource.getCitation()!=null){
for (String element : informationSource.getCitation().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (informationSource.getCommittee()!=null){
for (String element : informationSource.getCommittee().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (informationSource.getReportSummary()!=null){
for (String element : informationSource.getReportSummary().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (StringUtils.containsIgnoreCase( Integer.toString(informationSource.getPublicationYear()), text)) return true;
if (StringUtils.containsIgnoreCase(informationSource.getUrl()!=null?informationSource.getUrl().toExternalForm():"", text)) return true;
}
}
}
for (SpecificMeasure specificMeasure : vme.getSpecificMeasureList()) {
if (specificMeasure.getVmeSpecificMeasure()!=null){
for (String element : specificMeasure.getVmeSpecificMeasure().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (specificMeasure.getInformationSource()!=null){
if(specificMeasure.getInformationSource().getCitation()!=null){
for (String element : specificMeasure.getInformationSource().getCitation().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (StringUtils.containsIgnoreCase( Integer.toString(specificMeasure.getInformationSource().getPublicationYear()), text)) return true;
if (StringUtils.containsIgnoreCase(specificMeasure.getInformationSource().getUrl()!=null?specificMeasure.getInformationSource().getUrl().toExternalForm():"", text)) return true;
}
- if (specificMeasure.getVmeSpecificMeasure()!=null && specificMeasure.getInformationSource().getCommittee()!=null){
+ if (specificMeasure.getInformationSource()!=null && specificMeasure.getInformationSource().getCommittee()!=null){
for (String element : specificMeasure.getInformationSource().getCommittee().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (specificMeasure.getInformationSource()!=null && specificMeasure.getInformationSource().getReportSummary()!=null){
for (String element : specificMeasure.getInformationSource().getReportSummary().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
}
return false;
}
private VmeSearchResult convertPersistenceResult(VmeRequestDto request, List<Vme> result, List<Vme> toRemove){
VmeSearchResult res = new VmeSearchResult(request);
for (Vme vme : result) {
if (toRemove==null || (toRemove!=null && !toRemove.contains(vme))){
res.addElement(getVmeSearchDto(vme,request.getYear()));
}
}
return res;
}
private VmeSearchDto getVmeSearchDto(Vme vme, int year) {
VmeSearchDto res = new VmeSearchDto();
res.setVmeId(vme.getId());
res.setInventoryIdentifier(vme.getInventoryIdentifier());
res.setLocalName(u.getEnglish(vme.getName()));
res.setEnvelope("");
String authority_acronym = vme.getRfmo().getId();
try {
Authority authority = (Authority)ReferenceServiceFactory.getService().getReferencebyAcronym(Authority.class, authority_acronym);
res.setOwner(authority.getName() + " (" + authority.getAcronym() + ")");
} catch (ReferenceServiceException e) {
res.setOwner(authority_acronym);
e.printStackTrace();
}
VmeObservation vo = dao.findFirstVmeObservation(vme.getId(), Integer.toString(year));
if (vo!=null){
res.setFactsheetUrl("fishery/vme/"+ vo.getId().getVmeId() + "/" + vo.getId().getObservationId() +"/en");
} else {
res.setFactsheetUrl("");
}
res.setGeoArea(u.getEnglish(vme.getGeoArea()));
res.setValidityPeriodFrom(vme.getValidityPeriod().getBeginYear());
res.setValidityPeriodTo(vme.getValidityPeriod().getEndYear());
res.setVmeType(vme.getAreaType());
res.setYear(year);
res.setGeographicFeatureId(vme.getGeoRefList().size()>0?vme.getGeoRefList().get(0).getGeographicFeatureID():"");
return res;
}
/**
* @param dao the dao to set
*/
@Inject
public void setDao(FigisDao dao) {
this.dao = dao;
}
}
| true | true | private boolean containRelevantText(Vme vme, String text) {
if (StringUtils.containsIgnoreCase(vme.getAreaType(), text)) return true;
if (StringUtils.containsIgnoreCase(vme.getCriteria(), text)) return true;
for (String element : vme.getGeoArea().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
if (StringUtils.containsIgnoreCase(vme.getGeoform(), text)) return true;
for (GeoRef geoRef : vme.getGeoRefList()) {
if (StringUtils.containsIgnoreCase(geoRef.getGeographicFeatureID(), text)) return true;
}
if (StringUtils.containsIgnoreCase(vme.getInventoryIdentifier(), text)) return true;
for (String element : vme.getName().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
for (Profile profile : vme.getProfileList()) {
for (String element : profile.getDescriptionBiological().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
for (String element : profile.getDescriptionImpact().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
for (String element : profile.getDescriptionPhisical().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
for (GeneralMeasure generalMeasure : vme.getRfmo().getGeneralMeasureList()) {
if (StringUtils.containsIgnoreCase(generalMeasure.getFishingAreas(), text)) return true;
if (generalMeasure.getExplorataryFishingProtocols()!=null){
for (String element : generalMeasure.getExplorataryFishingProtocols().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getVmeEncounterProtocols()!=null){
for (String element : generalMeasure.getVmeEncounterProtocols().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getVmeIndicatorSpecies()!=null){
for (String element : generalMeasure.getVmeIndicatorSpecies().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getVmeThreshold()!=null){
for (String element : generalMeasure.getVmeThreshold().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getInformationSourceList()!=null){
for (InformationSource informationSource : generalMeasure.getInformationSourceList()) {
if (informationSource.getCitation()!=null){
for (String element : informationSource.getCitation().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (informationSource.getCommittee()!=null){
for (String element : informationSource.getCommittee().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (informationSource.getReportSummary()!=null){
for (String element : informationSource.getReportSummary().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (StringUtils.containsIgnoreCase( Integer.toString(informationSource.getPublicationYear()), text)) return true;
if (StringUtils.containsIgnoreCase(informationSource.getUrl()!=null?informationSource.getUrl().toExternalForm():"", text)) return true;
}
}
}
for (SpecificMeasure specificMeasure : vme.getSpecificMeasureList()) {
if (specificMeasure.getVmeSpecificMeasure()!=null){
for (String element : specificMeasure.getVmeSpecificMeasure().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (specificMeasure.getInformationSource()!=null){
if(specificMeasure.getInformationSource().getCitation()!=null){
for (String element : specificMeasure.getInformationSource().getCitation().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (StringUtils.containsIgnoreCase( Integer.toString(specificMeasure.getInformationSource().getPublicationYear()), text)) return true;
if (StringUtils.containsIgnoreCase(specificMeasure.getInformationSource().getUrl()!=null?specificMeasure.getInformationSource().getUrl().toExternalForm():"", text)) return true;
}
if (specificMeasure.getVmeSpecificMeasure()!=null && specificMeasure.getInformationSource().getCommittee()!=null){
for (String element : specificMeasure.getInformationSource().getCommittee().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (specificMeasure.getInformationSource()!=null && specificMeasure.getInformationSource().getReportSummary()!=null){
for (String element : specificMeasure.getInformationSource().getReportSummary().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
}
return false;
}
| private boolean containRelevantText(Vme vme, String text) {
if (StringUtils.containsIgnoreCase(vme.getAreaType(), text)) return true;
if (StringUtils.containsIgnoreCase(vme.getCriteria(), text)) return true;
for (String element : vme.getGeoArea().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
if (StringUtils.containsIgnoreCase(vme.getGeoform(), text)) return true;
for (GeoRef geoRef : vme.getGeoRefList()) {
if (StringUtils.containsIgnoreCase(geoRef.getGeographicFeatureID(), text)) return true;
}
if (StringUtils.containsIgnoreCase(vme.getInventoryIdentifier(), text)) return true;
for (String element : vme.getName().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
for (Profile profile : vme.getProfileList()) {
for (String element : profile.getDescriptionBiological().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
for (String element : profile.getDescriptionImpact().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
for (String element : profile.getDescriptionPhisical().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
for (GeneralMeasure generalMeasure : vme.getRfmo().getGeneralMeasureList()) {
if (StringUtils.containsIgnoreCase(generalMeasure.getFishingAreas(), text)) return true;
if (generalMeasure.getExplorataryFishingProtocols()!=null){
for (String element : generalMeasure.getExplorataryFishingProtocols().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getVmeEncounterProtocols()!=null){
for (String element : generalMeasure.getVmeEncounterProtocols().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getVmeIndicatorSpecies()!=null){
for (String element : generalMeasure.getVmeIndicatorSpecies().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getVmeThreshold()!=null){
for (String element : generalMeasure.getVmeThreshold().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (generalMeasure.getInformationSourceList()!=null){
for (InformationSource informationSource : generalMeasure.getInformationSourceList()) {
if (informationSource.getCitation()!=null){
for (String element : informationSource.getCitation().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (informationSource.getCommittee()!=null){
for (String element : informationSource.getCommittee().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (informationSource.getReportSummary()!=null){
for (String element : informationSource.getReportSummary().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (StringUtils.containsIgnoreCase( Integer.toString(informationSource.getPublicationYear()), text)) return true;
if (StringUtils.containsIgnoreCase(informationSource.getUrl()!=null?informationSource.getUrl().toExternalForm():"", text)) return true;
}
}
}
for (SpecificMeasure specificMeasure : vme.getSpecificMeasureList()) {
if (specificMeasure.getVmeSpecificMeasure()!=null){
for (String element : specificMeasure.getVmeSpecificMeasure().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (specificMeasure.getInformationSource()!=null){
if(specificMeasure.getInformationSource().getCitation()!=null){
for (String element : specificMeasure.getInformationSource().getCitation().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (StringUtils.containsIgnoreCase( Integer.toString(specificMeasure.getInformationSource().getPublicationYear()), text)) return true;
if (StringUtils.containsIgnoreCase(specificMeasure.getInformationSource().getUrl()!=null?specificMeasure.getInformationSource().getUrl().toExternalForm():"", text)) return true;
}
if (specificMeasure.getInformationSource()!=null && specificMeasure.getInformationSource().getCommittee()!=null){
for (String element : specificMeasure.getInformationSource().getCommittee().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
if (specificMeasure.getInformationSource()!=null && specificMeasure.getInformationSource().getReportSummary()!=null){
for (String element : specificMeasure.getInformationSource().getReportSummary().getStringMap().values()) {
if (StringUtils.containsIgnoreCase(element, text)) return true;
}
}
}
return false;
}
|
diff --git a/bundles/net.i2cat.nexus.resources/src/main/java/net/i2cat/nexus/resources/shell/CreateResourceCommand.java b/bundles/net.i2cat.nexus.resources/src/main/java/net/i2cat/nexus/resources/shell/CreateResourceCommand.java
index cd4e52644..09de9e5dd 100644
--- a/bundles/net.i2cat.nexus.resources/src/main/java/net/i2cat/nexus/resources/shell/CreateResourceCommand.java
+++ b/bundles/net.i2cat.nexus.resources/src/main/java/net/i2cat/nexus/resources/shell/CreateResourceCommand.java
@@ -1,207 +1,214 @@
package net.i2cat.nexus.resources.shell;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import net.i2cat.nexus.resources.Activator;
import net.i2cat.nexus.resources.IResource;
import net.i2cat.nexus.resources.IResourceManager;
import net.i2cat.nexus.resources.IResourceRepository;
import net.i2cat.nexus.resources.ResourceException;
import net.i2cat.nexus.resources.ResourceManager;
import net.i2cat.nexus.resources.command.GenericKarafCommand;
import net.i2cat.nexus.resources.descriptor.ResourceDescriptor;
/**
* Create a new resource from the URL or file given on the karaf shell
*
* @author Scott Campbell (CRC)
*
*/
@Command(scope = "resource", name = "create", description = "Create one or more resources from a given descriptor")
public class CreateResourceCommand extends GenericKarafCommand {
@Argument(index = 0, name = "paths or urls", description = "A space delimited list of file paths or urls to resource descriptors ", required = true, multiValued = true)
private List<String> paths;
@Option(name = "--profile", aliases = { "-p" }, description = "Allows explicit declaration of profile to be used")
String profileName;
@Override
protected Object doExecute() throws Exception {
initcommand("create resource");
Boolean created = false;
IResourceManager manager = getResourceManager();
ResourceDescriptor descriptor = null;
// For each argument path or URL
for (String filename : paths) {
File file = new File(filename);
// check if the argument path is a directory
// if it is, load all the descriptor files of the directory
if (file.isDirectory()) {
for (File files : file.listFiles()) {
// only accept the files with '.descriptor' extension
if (files.getName().endsWith(".descriptor")) {
totalFiles++;
try {
descriptor = getResourceDescriptor(files.getPath());
try {
createResource(manager, descriptor);
} catch (NullPointerException f) {
printError("Error creating Resource.");
printError(f);
}
} catch (FileNotFoundException f) {
printError("File not found: " + files);
} catch (NullPointerException f) {
printError("Error parsing descriptor on " + files.getName());
} catch (JAXBException f) {
printError("Error parsing descriptor ");
printError(f);
} catch (ResourceException f) {
printError("In file: " + files.getName());
printError(f);
}
}
printSymbol(underLine);
}
} else {
+ // In windows, failing to specify double slash (\\) often result in random chars escaped to control chars.
+ if (filename.contains("\r")) {
+ printError("Malformed filename: " + filename + " ( ");
+ if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
+ printInfo("You seem to be in windows. Are you using proper double escaped slashes? C:\\\\dir\\\\\file instead of C:\\dir\\file.");
+ continue;
+ }
if (filename.endsWith(".descriptor")) {
totalFiles++;
try {
descriptor = getResourceDescriptor(filename);
try {
createResource(manager, descriptor);
} catch (NullPointerException f) {
printError("Error creating Resource. ");
printError(f);
}
} catch (JAXBException f) {
printError("Error parsing descriptor ");
printError(f);
} catch (FileNotFoundException f) {
printError("File not found: " + filename);
} catch (NullPointerException f) {
printError("The descriptor is not loaded " + filename);
} catch (ResourceException f) {
printError("File: " + filename);
printError(f);
}
} else {
printError("The file type is not a valid for " + filename);
}
printSymbol(underLine);
}
}
if (counter == 0) {
printInfo("No resource has been created.");
} else {
- printInfo("Created " + counter + " resource/s from " + totalFiles);
+ printInfo("Created " + counter + " resource/s from " + totalFiles + " descriptors.");
}
endcommand();
return null;
}
public int createResource(IResourceManager manager, ResourceDescriptor descriptor) {
// check if profile option is active
if (profileName != null && profileName != "") {
// Override profile in the descriptor
descriptor.setProfileId(profileName);
}
IResource resource = null;
try {
printInfo("Creating Resource ...... ");
resource = manager.createResource(descriptor);
} catch (ResourceException e) {
printError(e.getLocalizedMessage());
ResourceManager rm = (ResourceManager) manager;
Hashtable<String, IResourceRepository> rr = (Hashtable<String, IResourceRepository>) rm.getResourceRepositories();
if (rr.isEmpty()) {
printError("There aren't any Resource Repositories registered.");
return -1;
}
return -1;
} catch (NullPointerException e) {
printError(e);
return -1;
}
printInfo("Resource of type " + resource.getResourceDescriptor().getInformation().getType() + " created with name: "
+ resource.getResourceDescriptor().getInformation().getName());
counter++;
return 0;
}
public ResourceDescriptor getResourceDescriptor(String filename) throws JAXBException, IOException, ResourceException {
InputStream stream = null;
// First try a URL
try {
URL url = new URL(filename);
printInfo("URL: " + url);
stream = url.openStream();
} catch (MalformedURLException ignore) {
// Then try a file
printInfo("file: " + filename);
stream = new FileInputStream(filename);
}
ResourceDescriptor rd = getDescriptor(stream);
if (rd.getInformation().getType() == null || rd.getInformation().getType() == "") {
throw new ResourceException("ResourceDescriptor: Needed to indicate a resource type.");
}
if (rd.getInformation().getName().equals("") || rd.getInformation().getName() == null) {
throw new ResourceException("ResourceDescriptor: The resourceName field cannot be null.");
}
printInfo("Descriptor loaded for resource " + rd.getInformation().getName() + " with type: " + rd.getInformation()
.getType());
return rd;
}
private ResourceDescriptor getDescriptor(InputStream stream) throws JAXBException {
ResourceDescriptor descriptor = null;
try {
JAXBContext context = JAXBContext.newInstance(ResourceDescriptor.class);
descriptor = (ResourceDescriptor) context.createUnmarshaller().unmarshal(stream);
} finally {
try {
stream.close();
} catch (IOException e) {
// Ingore
}
}
return descriptor;
}
public IResourceManager getResourceManager() throws Exception {
IResourceManager resourceManager = Activator.getResourceManagerService();
return resourceManager;
}
}
| false | true | protected Object doExecute() throws Exception {
initcommand("create resource");
Boolean created = false;
IResourceManager manager = getResourceManager();
ResourceDescriptor descriptor = null;
// For each argument path or URL
for (String filename : paths) {
File file = new File(filename);
// check if the argument path is a directory
// if it is, load all the descriptor files of the directory
if (file.isDirectory()) {
for (File files : file.listFiles()) {
// only accept the files with '.descriptor' extension
if (files.getName().endsWith(".descriptor")) {
totalFiles++;
try {
descriptor = getResourceDescriptor(files.getPath());
try {
createResource(manager, descriptor);
} catch (NullPointerException f) {
printError("Error creating Resource.");
printError(f);
}
} catch (FileNotFoundException f) {
printError("File not found: " + files);
} catch (NullPointerException f) {
printError("Error parsing descriptor on " + files.getName());
} catch (JAXBException f) {
printError("Error parsing descriptor ");
printError(f);
} catch (ResourceException f) {
printError("In file: " + files.getName());
printError(f);
}
}
printSymbol(underLine);
}
} else {
if (filename.endsWith(".descriptor")) {
totalFiles++;
try {
descriptor = getResourceDescriptor(filename);
try {
createResource(manager, descriptor);
} catch (NullPointerException f) {
printError("Error creating Resource. ");
printError(f);
}
} catch (JAXBException f) {
printError("Error parsing descriptor ");
printError(f);
} catch (FileNotFoundException f) {
printError("File not found: " + filename);
} catch (NullPointerException f) {
printError("The descriptor is not loaded " + filename);
} catch (ResourceException f) {
printError("File: " + filename);
printError(f);
}
} else {
printError("The file type is not a valid for " + filename);
}
printSymbol(underLine);
}
}
if (counter == 0) {
printInfo("No resource has been created.");
} else {
printInfo("Created " + counter + " resource/s from " + totalFiles);
}
endcommand();
return null;
}
| protected Object doExecute() throws Exception {
initcommand("create resource");
Boolean created = false;
IResourceManager manager = getResourceManager();
ResourceDescriptor descriptor = null;
// For each argument path or URL
for (String filename : paths) {
File file = new File(filename);
// check if the argument path is a directory
// if it is, load all the descriptor files of the directory
if (file.isDirectory()) {
for (File files : file.listFiles()) {
// only accept the files with '.descriptor' extension
if (files.getName().endsWith(".descriptor")) {
totalFiles++;
try {
descriptor = getResourceDescriptor(files.getPath());
try {
createResource(manager, descriptor);
} catch (NullPointerException f) {
printError("Error creating Resource.");
printError(f);
}
} catch (FileNotFoundException f) {
printError("File not found: " + files);
} catch (NullPointerException f) {
printError("Error parsing descriptor on " + files.getName());
} catch (JAXBException f) {
printError("Error parsing descriptor ");
printError(f);
} catch (ResourceException f) {
printError("In file: " + files.getName());
printError(f);
}
}
printSymbol(underLine);
}
} else {
// In windows, failing to specify double slash (\\) often result in random chars escaped to control chars.
if (filename.contains("\r")) {
printError("Malformed filename: " + filename + " ( ");
if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
printInfo("You seem to be in windows. Are you using proper double escaped slashes? C:\\\\dir\\\\\file instead of C:\\dir\\file.");
continue;
}
if (filename.endsWith(".descriptor")) {
totalFiles++;
try {
descriptor = getResourceDescriptor(filename);
try {
createResource(manager, descriptor);
} catch (NullPointerException f) {
printError("Error creating Resource. ");
printError(f);
}
} catch (JAXBException f) {
printError("Error parsing descriptor ");
printError(f);
} catch (FileNotFoundException f) {
printError("File not found: " + filename);
} catch (NullPointerException f) {
printError("The descriptor is not loaded " + filename);
} catch (ResourceException f) {
printError("File: " + filename);
printError(f);
}
} else {
printError("The file type is not a valid for " + filename);
}
printSymbol(underLine);
}
}
if (counter == 0) {
printInfo("No resource has been created.");
} else {
printInfo("Created " + counter + " resource/s from " + totalFiles + " descriptors.");
}
endcommand();
return null;
}
|
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/api/CreateBranchCommand.java b/org.eclipse.jgit/src/org/eclipse/jgit/api/CreateBranchCommand.java
index 791145e8..beee9a4a 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/api/CreateBranchCommand.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/api/CreateBranchCommand.java
@@ -1,359 +1,361 @@
/*
* Copyright (C) 2010, Mathias Kinzler <[email protected]>
* Copyright (C) 2010, Chris Aniszczyk <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. 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 COPYRIGHT OWNER 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.eclipse.jgit.api;
import java.io.IOException;
import java.text.MessageFormat;
import org.eclipse.jgit.JGitText;
import org.eclipse.jgit.api.errors.InvalidRefNameException;
import org.eclipse.jgit.api.errors.JGitInternalException;
import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
import org.eclipse.jgit.api.errors.RefNotFoundException;
import org.eclipse.jgit.errors.AmbiguousObjectException;
import org.eclipse.jgit.lib.ConfigConstants;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.lib.RefUpdate.Result;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
/**
* Used to create a local branch.
*
* @see <a
* href="http://www.kernel.org/pub/software/scm/git/docs/git-branch.html"
* >Git documentation about Branch</a>
*/
public class CreateBranchCommand extends GitCommand<Ref> {
private String name;
private boolean force = false;
private SetupUpstreamMode upstreamMode;
private String startPoint = Constants.HEAD;
private RevCommit startCommit;
/**
* The modes available for setting up the upstream configuration
* (corresponding to the --set-upstream, --track, --no-track options
*
*/
public enum SetupUpstreamMode {
/**
* Corresponds to the --track option
*/
TRACK,
/**
* Corresponds to the --no-track option
*/
NOTRACK,
/**
* Corresponds to the --set-upstream option
*/
SET_UPSTREAM;
}
/**
* @param repo
*/
protected CreateBranchCommand(Repository repo) {
super(repo);
}
/**
* @throws RefAlreadyExistsException
* when trying to create (without force) a branch with a name
* that already exists
* @throws RefNotFoundException
* if the start point can not be found
* @throws InvalidRefNameException
* if the provided name is <code>null</code> or otherwise
* invalid
* @return the newly created branch
*/
public Ref call() throws JGitInternalException, RefAlreadyExistsException,
RefNotFoundException, InvalidRefNameException {
checkCallable();
processOptions();
try {
- boolean exists = repo.getRef(name) != null;
+ Ref refToCheck = repo.getRef(name);
+ boolean exists = refToCheck != null
+ && refToCheck.getName().startsWith(Constants.R_HEADS);
if (!force && exists)
throw new RefAlreadyExistsException(MessageFormat.format(
JGitText.get().refAlreadExists, name));
ObjectId startAt = getStartPoint();
String startPointFullName = null;
if (startPoint != null) {
Ref baseRef = repo.getRef(startPoint);
if (baseRef != null)
startPointFullName = baseRef.getName();
}
// determine whether we are based on a commit,
// a branch, or a tag and compose the reflog message
String refLogMessage;
String baseBranch = "";
if (startPointFullName == null) {
String baseCommit;
if (startCommit != null)
baseCommit = startCommit.getShortMessage();
else {
RevCommit commit = new RevWalk(repo).parseCommit(repo
.resolve(startPoint));
baseCommit = commit.getShortMessage();
}
if (exists)
refLogMessage = "branch: Reset start-point to commit "
+ baseCommit;
else
refLogMessage = "branch: Created from commit " + baseCommit;
} else if (startPointFullName.startsWith(Constants.R_HEADS)
|| startPointFullName.startsWith(Constants.R_REMOTES)) {
baseBranch = startPointFullName;
if (exists)
refLogMessage = "branch: Reset start-point to branch "
+ startPointFullName; // TODO
else
refLogMessage = "branch: Created from branch " + baseBranch;
} else {
if (exists)
refLogMessage = "branch: Reset start-point to tag "
+ startPointFullName;
else
refLogMessage = "branch: Created from tag "
+ startPointFullName;
}
RefUpdate updateRef = repo.updateRef(Constants.R_HEADS + name);
updateRef.setNewObjectId(startAt);
updateRef.setRefLogMessage(refLogMessage, false);
Result updateResult;
if (exists && force)
updateResult = updateRef.forceUpdate();
else
updateResult = updateRef.update();
setCallable(false);
boolean ok = false;
switch (updateResult) {
case NEW:
ok = !exists;
break;
case NO_CHANGE:
case FAST_FORWARD:
case FORCED:
ok = exists;
break;
default:
break;
}
if (!ok)
throw new JGitInternalException(MessageFormat.format(JGitText
.get().createBranchUnexpectedResult, updateResult
.name()));
Ref result = repo.getRef(name);
if (result == null)
throw new JGitInternalException(
JGitText.get().createBranchFailedUnknownReason);
if (baseBranch.length() == 0) {
return result;
}
// if we are based on another branch, see
// if we need to configure upstream configuration: first check
// whether the setting was done explicitly
boolean doConfigure;
if (upstreamMode == SetupUpstreamMode.SET_UPSTREAM
|| upstreamMode == SetupUpstreamMode.TRACK)
// explicitly set to configure
doConfigure = true;
else if (upstreamMode == SetupUpstreamMode.NOTRACK)
// explicitly set to not configure
doConfigure = false;
else {
// if there was no explicit setting, check the configuration
String autosetupflag = repo.getConfig().getString(
ConfigConstants.CONFIG_BRANCH_SECTION, null,
ConfigConstants.CONFIG_KEY_AUTOSETUPMERGE);
if ("false".equals(autosetupflag)) {
doConfigure = false;
} else if ("always".equals(autosetupflag)) {
doConfigure = true;
} else {
// in this case, the default is to configure
// only in case the base branch was a remote branch
doConfigure = baseBranch.startsWith(Constants.R_REMOTES);
}
}
if (doConfigure) {
StoredConfig config = repo.getConfig();
String[] tokens = baseBranch.split("/", 4);
boolean isRemote = tokens[1].equals("remotes");
if (isRemote) {
// refs/remotes/<remote name>/<branch>
String remoteName = tokens[2];
String branchName = tokens[3];
config
.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_REMOTE,
remoteName);
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_MERGE,
Constants.R_HEADS + branchName);
} else {
// set "." as remote
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_REMOTE, ".");
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_MERGE, baseBranch);
}
config.save();
}
return result;
} catch (IOException ioe) {
throw new JGitInternalException(ioe.getMessage(), ioe);
}
}
private ObjectId getStartPoint() throws AmbiguousObjectException,
RefNotFoundException, IOException {
if (startCommit != null)
return startCommit.getId();
ObjectId result = null;
try {
result = repo.resolve((startPoint == null) ? Constants.HEAD
: startPoint);
} catch (AmbiguousObjectException e) {
throw e;
}
if (result == null)
throw new RefNotFoundException(MessageFormat.format(
JGitText.get().refNotResolved,
startPoint != null ? startPoint : Constants.HEAD));
return result;
}
private void processOptions() throws InvalidRefNameException {
if (name == null
|| !Repository.isValidRefName(Constants.R_HEADS + name))
throw new InvalidRefNameException(MessageFormat.format(JGitText
.get().branchNameInvalid, name == null ? "<null>" : name));
}
/**
* @param name
* the name of the new branch
* @return this instance
*/
public CreateBranchCommand setName(String name) {
checkCallable();
this.name = name;
return this;
}
/**
* @param force
* if <code>true</code> and the branch with the given name
* already exists, the start-point of an existing branch will be
* set to a new start-point; if false, the existing branch will
* not be changed
* @return this instance
*/
public CreateBranchCommand setForce(boolean force) {
checkCallable();
this.force = force;
return this;
}
/**
* @param startPoint
* corresponds to the start-point option; if <code>null</code>,
* the current HEAD will be used
* @return this instance
*/
public CreateBranchCommand setStartPoint(String startPoint) {
checkCallable();
this.startPoint = startPoint;
this.startCommit = null;
return this;
}
/**
* @param startPoint
* corresponds to the start-point option; if <code>null</code>,
* the current HEAD will be used
* @return this instance
*/
public CreateBranchCommand setStartPoint(RevCommit startPoint) {
checkCallable();
this.startCommit = startPoint;
this.startPoint = null;
return this;
}
/**
* @param mode
* corresponds to the --track/--no-track/--set-upstream options;
* may be <code>null</code>
* @return this instance
*/
public CreateBranchCommand setUpstreamMode(SetupUpstreamMode mode) {
checkCallable();
this.upstreamMode = mode;
return this;
}
}
| true | true | public Ref call() throws JGitInternalException, RefAlreadyExistsException,
RefNotFoundException, InvalidRefNameException {
checkCallable();
processOptions();
try {
boolean exists = repo.getRef(name) != null;
if (!force && exists)
throw new RefAlreadyExistsException(MessageFormat.format(
JGitText.get().refAlreadExists, name));
ObjectId startAt = getStartPoint();
String startPointFullName = null;
if (startPoint != null) {
Ref baseRef = repo.getRef(startPoint);
if (baseRef != null)
startPointFullName = baseRef.getName();
}
// determine whether we are based on a commit,
// a branch, or a tag and compose the reflog message
String refLogMessage;
String baseBranch = "";
if (startPointFullName == null) {
String baseCommit;
if (startCommit != null)
baseCommit = startCommit.getShortMessage();
else {
RevCommit commit = new RevWalk(repo).parseCommit(repo
.resolve(startPoint));
baseCommit = commit.getShortMessage();
}
if (exists)
refLogMessage = "branch: Reset start-point to commit "
+ baseCommit;
else
refLogMessage = "branch: Created from commit " + baseCommit;
} else if (startPointFullName.startsWith(Constants.R_HEADS)
|| startPointFullName.startsWith(Constants.R_REMOTES)) {
baseBranch = startPointFullName;
if (exists)
refLogMessage = "branch: Reset start-point to branch "
+ startPointFullName; // TODO
else
refLogMessage = "branch: Created from branch " + baseBranch;
} else {
if (exists)
refLogMessage = "branch: Reset start-point to tag "
+ startPointFullName;
else
refLogMessage = "branch: Created from tag "
+ startPointFullName;
}
RefUpdate updateRef = repo.updateRef(Constants.R_HEADS + name);
updateRef.setNewObjectId(startAt);
updateRef.setRefLogMessage(refLogMessage, false);
Result updateResult;
if (exists && force)
updateResult = updateRef.forceUpdate();
else
updateResult = updateRef.update();
setCallable(false);
boolean ok = false;
switch (updateResult) {
case NEW:
ok = !exists;
break;
case NO_CHANGE:
case FAST_FORWARD:
case FORCED:
ok = exists;
break;
default:
break;
}
if (!ok)
throw new JGitInternalException(MessageFormat.format(JGitText
.get().createBranchUnexpectedResult, updateResult
.name()));
Ref result = repo.getRef(name);
if (result == null)
throw new JGitInternalException(
JGitText.get().createBranchFailedUnknownReason);
if (baseBranch.length() == 0) {
return result;
}
// if we are based on another branch, see
// if we need to configure upstream configuration: first check
// whether the setting was done explicitly
boolean doConfigure;
if (upstreamMode == SetupUpstreamMode.SET_UPSTREAM
|| upstreamMode == SetupUpstreamMode.TRACK)
// explicitly set to configure
doConfigure = true;
else if (upstreamMode == SetupUpstreamMode.NOTRACK)
// explicitly set to not configure
doConfigure = false;
else {
// if there was no explicit setting, check the configuration
String autosetupflag = repo.getConfig().getString(
ConfigConstants.CONFIG_BRANCH_SECTION, null,
ConfigConstants.CONFIG_KEY_AUTOSETUPMERGE);
if ("false".equals(autosetupflag)) {
doConfigure = false;
} else if ("always".equals(autosetupflag)) {
doConfigure = true;
} else {
// in this case, the default is to configure
// only in case the base branch was a remote branch
doConfigure = baseBranch.startsWith(Constants.R_REMOTES);
}
}
if (doConfigure) {
StoredConfig config = repo.getConfig();
String[] tokens = baseBranch.split("/", 4);
boolean isRemote = tokens[1].equals("remotes");
if (isRemote) {
// refs/remotes/<remote name>/<branch>
String remoteName = tokens[2];
String branchName = tokens[3];
config
.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_REMOTE,
remoteName);
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_MERGE,
Constants.R_HEADS + branchName);
} else {
// set "." as remote
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_REMOTE, ".");
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_MERGE, baseBranch);
}
config.save();
}
return result;
} catch (IOException ioe) {
throw new JGitInternalException(ioe.getMessage(), ioe);
}
}
| public Ref call() throws JGitInternalException, RefAlreadyExistsException,
RefNotFoundException, InvalidRefNameException {
checkCallable();
processOptions();
try {
Ref refToCheck = repo.getRef(name);
boolean exists = refToCheck != null
&& refToCheck.getName().startsWith(Constants.R_HEADS);
if (!force && exists)
throw new RefAlreadyExistsException(MessageFormat.format(
JGitText.get().refAlreadExists, name));
ObjectId startAt = getStartPoint();
String startPointFullName = null;
if (startPoint != null) {
Ref baseRef = repo.getRef(startPoint);
if (baseRef != null)
startPointFullName = baseRef.getName();
}
// determine whether we are based on a commit,
// a branch, or a tag and compose the reflog message
String refLogMessage;
String baseBranch = "";
if (startPointFullName == null) {
String baseCommit;
if (startCommit != null)
baseCommit = startCommit.getShortMessage();
else {
RevCommit commit = new RevWalk(repo).parseCommit(repo
.resolve(startPoint));
baseCommit = commit.getShortMessage();
}
if (exists)
refLogMessage = "branch: Reset start-point to commit "
+ baseCommit;
else
refLogMessage = "branch: Created from commit " + baseCommit;
} else if (startPointFullName.startsWith(Constants.R_HEADS)
|| startPointFullName.startsWith(Constants.R_REMOTES)) {
baseBranch = startPointFullName;
if (exists)
refLogMessage = "branch: Reset start-point to branch "
+ startPointFullName; // TODO
else
refLogMessage = "branch: Created from branch " + baseBranch;
} else {
if (exists)
refLogMessage = "branch: Reset start-point to tag "
+ startPointFullName;
else
refLogMessage = "branch: Created from tag "
+ startPointFullName;
}
RefUpdate updateRef = repo.updateRef(Constants.R_HEADS + name);
updateRef.setNewObjectId(startAt);
updateRef.setRefLogMessage(refLogMessage, false);
Result updateResult;
if (exists && force)
updateResult = updateRef.forceUpdate();
else
updateResult = updateRef.update();
setCallable(false);
boolean ok = false;
switch (updateResult) {
case NEW:
ok = !exists;
break;
case NO_CHANGE:
case FAST_FORWARD:
case FORCED:
ok = exists;
break;
default:
break;
}
if (!ok)
throw new JGitInternalException(MessageFormat.format(JGitText
.get().createBranchUnexpectedResult, updateResult
.name()));
Ref result = repo.getRef(name);
if (result == null)
throw new JGitInternalException(
JGitText.get().createBranchFailedUnknownReason);
if (baseBranch.length() == 0) {
return result;
}
// if we are based on another branch, see
// if we need to configure upstream configuration: first check
// whether the setting was done explicitly
boolean doConfigure;
if (upstreamMode == SetupUpstreamMode.SET_UPSTREAM
|| upstreamMode == SetupUpstreamMode.TRACK)
// explicitly set to configure
doConfigure = true;
else if (upstreamMode == SetupUpstreamMode.NOTRACK)
// explicitly set to not configure
doConfigure = false;
else {
// if there was no explicit setting, check the configuration
String autosetupflag = repo.getConfig().getString(
ConfigConstants.CONFIG_BRANCH_SECTION, null,
ConfigConstants.CONFIG_KEY_AUTOSETUPMERGE);
if ("false".equals(autosetupflag)) {
doConfigure = false;
} else if ("always".equals(autosetupflag)) {
doConfigure = true;
} else {
// in this case, the default is to configure
// only in case the base branch was a remote branch
doConfigure = baseBranch.startsWith(Constants.R_REMOTES);
}
}
if (doConfigure) {
StoredConfig config = repo.getConfig();
String[] tokens = baseBranch.split("/", 4);
boolean isRemote = tokens[1].equals("remotes");
if (isRemote) {
// refs/remotes/<remote name>/<branch>
String remoteName = tokens[2];
String branchName = tokens[3];
config
.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_REMOTE,
remoteName);
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_MERGE,
Constants.R_HEADS + branchName);
} else {
// set "." as remote
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_REMOTE, ".");
config.setString(ConfigConstants.CONFIG_BRANCH_SECTION,
name, ConfigConstants.CONFIG_KEY_MERGE, baseBranch);
}
config.save();
}
return result;
} catch (IOException ioe) {
throw new JGitInternalException(ioe.getMessage(), ioe);
}
}
|
diff --git a/android-project/src/org/libsdl/app/SDLActivity.java b/android-project/src/org/libsdl/app/SDLActivity.java
index 1c77e730..e0a850f4 100644
--- a/android-project/src/org/libsdl/app/SDLActivity.java
+++ b/android-project/src/org/libsdl/app/SDLActivity.java
@@ -1,745 +1,745 @@
package org.libsdl.app;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.egl.*;
import android.app.*;
import android.content.*;
import android.view.*;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsoluteLayout;
import android.os.*;
import android.util.Log;
import android.graphics.*;
import android.text.method.*;
import android.text.*;
import android.media.*;
import android.hardware.*;
import android.content.*;
import java.lang.*;
/**
SDL Activity
*/
public class SDLActivity extends Activity {
// Keep track of the paused state
public static boolean mIsPaused;
// Main components
private static SDLActivity mSingleton;
private static SDLSurface mSurface;
private static View mTextEdit;
private static ViewGroup mLayout;
// This is what SDL runs in. It invokes SDL_main(), eventually
private static Thread mSDLThread;
// Audio
private static Thread mAudioThread;
private static AudioTrack mAudioTrack;
// EGL private objects
private static EGLContext mEGLContext;
private static EGLSurface mEGLSurface;
private static EGLDisplay mEGLDisplay;
private static EGLConfig mEGLConfig;
private static int mGLMajor, mGLMinor;
// Load the .so
static {
System.loadLibrary("SDL2");
//System.loadLibrary("SDL2_image");
//System.loadLibrary("SDL2_mixer");
//System.loadLibrary("SDL2_ttf");
System.loadLibrary("main");
}
// Setup
protected void onCreate(Bundle savedInstanceState) {
//Log.v("SDL", "onCreate()");
super.onCreate(savedInstanceState);
// So we can call stuff from static callbacks
mSingleton = this;
// Keep track of the paused state
mIsPaused = false;
// Set up the surface
mSurface = new SDLSurface(getApplication());
mLayout = new AbsoluteLayout(this);
mLayout.addView(mSurface);
setContentView(mLayout);
SurfaceHolder holder = mSurface.getHolder();
}
// Events
/*protected void onPause() {
Log.v("SDL", "onPause()");
super.onPause();
// Don't call SDLActivity.nativePause(); here, it will be called by SDLSurface::surfaceDestroyed
}
protected void onResume() {
Log.v("SDL", "onResume()");
super.onResume();
// Don't call SDLActivity.nativeResume(); here, it will be called via SDLSurface::surfaceChanged->SDLActivity::startApp
}*/
protected void onDestroy() {
super.onDestroy();
Log.v("SDL", "onDestroy()");
// Send a quit message to the application
SDLActivity.nativeQuit();
// Now wait for the SDL thread to quit
if (mSDLThread != null) {
try {
mSDLThread.join();
} catch(Exception e) {
Log.v("SDL", "Problem stopping thread: " + e);
}
mSDLThread = null;
//Log.v("SDL", "Finished waiting for SDL thread");
}
}
// Messages from the SDLMain thread
static final int COMMAND_CHANGE_TITLE = 1;
static final int COMMAND_UNUSED = 2;
static final int COMMAND_TEXTEDIT_HIDE = 3;
// Handler for the messages
Handler commandHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.arg1) {
case COMMAND_CHANGE_TITLE:
setTitle((String)msg.obj);
break;
case COMMAND_TEXTEDIT_HIDE:
if (mTextEdit != null) {
mTextEdit.setVisibility(View.GONE);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTextEdit.getWindowToken(), 0);
}
break;
}
}
};
// Send a message from the SDLMain thread
void sendCommand(int command, Object data) {
Message msg = commandHandler.obtainMessage();
msg.arg1 = command;
msg.obj = data;
commandHandler.sendMessage(msg);
}
// C functions we call
public static native void nativeInit();
public static native void nativeQuit();
public static native void nativePause();
public static native void nativeResume();
public static native void onNativeResize(int x, int y, int format);
public static native void onNativeKeyDown(int keycode);
public static native void onNativeKeyUp(int keycode);
public static native void onNativeTouch(int touchDevId, int pointerFingerId,
int action, float x,
float y, float p);
public static native void onNativeAccel(float x, float y, float z);
public static native void nativeRunAudioThread();
// Java functions called from C
public static boolean createGLContext(int majorVersion, int minorVersion, int[] attribs) {
return initEGL(majorVersion, minorVersion, attribs);
}
public static void flipBuffers() {
flipEGL();
}
public static void setActivityTitle(String title) {
// Called from SDLMain() thread and can't directly affect the view
mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title);
}
public static void sendMessage(int command, int param) {
mSingleton.sendCommand(command, Integer.valueOf(param));
}
public static Context getContext() {
return mSingleton;
}
public static void startApp() {
// Start up the C app thread
if (mSDLThread == null) {
mSDLThread = new Thread(new SDLMain(), "SDLThread");
mSDLThread.start();
}
else {
/*
* Some Android variants may send multiple surfaceChanged events, so we don't need to resume every time
* every time we get one of those events, only if it comes after surfaceDestroyed
*/
if (mIsPaused) {
SDLActivity.nativeResume();
SDLActivity.mIsPaused = false;
}
}
}
static class ShowTextInputHandler implements Runnable {
/*
* This is used to regulate the pan&scan method to have some offset from
* the bottom edge of the input region and the top edge of an input
* method (soft keyboard)
*/
static final int HEIGHT_PADDING = 15;
public int x, y, w, h;
public ShowTextInputHandler(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
public void run() {
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(
w, h + HEIGHT_PADDING, x, y);
if (mTextEdit == null) {
mTextEdit = new DummyEdit(getContext());
mLayout.addView(mTextEdit, params);
} else {
mTextEdit.setLayoutParams(params);
}
mTextEdit.setVisibility(View.VISIBLE);
mTextEdit.requestFocus();
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mTextEdit, 0);
}
}
public static void showTextInput(int x, int y, int w, int h) {
// Transfer the task to the main thread as a Runnable
mSingleton.commandHandler.post(new ShowTextInputHandler(x, y, w, h));
}
// EGL functions
public static boolean initEGL(int majorVersion, int minorVersion, int[] attribs) {
try {
if (SDLActivity.mEGLDisplay == null) {
Log.v("SDL", "Starting up OpenGL ES " + majorVersion + "." + minorVersion);
EGL10 egl = (EGL10)EGLContext.getEGL();
EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(dpy, version);
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
if (!egl.eglChooseConfig(dpy, attribs, configs, 1, num_config) || num_config[0] == 0) {
Log.e("SDL", "No EGL config available");
return false;
}
EGLConfig config = configs[0];
SDLActivity.mEGLDisplay = dpy;
SDLActivity.mEGLConfig = config;
SDLActivity.mGLMajor = majorVersion;
SDLActivity.mGLMinor = minorVersion;
}
return SDLActivity.createEGLSurface();
} catch(Exception e) {
Log.v("SDL", e + "");
for (StackTraceElement s : e.getStackTrace()) {
Log.v("SDL", s.toString());
}
return false;
}
}
public static boolean createEGLContext() {
EGL10 egl = (EGL10)EGLContext.getEGL();
int EGL_CONTEXT_CLIENT_VERSION=0x3098;
int contextAttrs[] = new int[] { EGL_CONTEXT_CLIENT_VERSION, SDLActivity.mGLMajor, EGL10.EGL_NONE };
SDLActivity.mEGLContext = egl.eglCreateContext(SDLActivity.mEGLDisplay, SDLActivity.mEGLConfig, EGL10.EGL_NO_CONTEXT, contextAttrs);
if (SDLActivity.mEGLContext == EGL10.EGL_NO_CONTEXT) {
Log.e("SDL", "Couldn't create context");
return false;
}
return true;
}
public static boolean createEGLSurface() {
if (SDLActivity.mEGLDisplay != null && SDLActivity.mEGLConfig != null) {
EGL10 egl = (EGL10)EGLContext.getEGL();
if (SDLActivity.mEGLContext == null) createEGLContext();
Log.v("SDL", "Creating new EGL Surface");
EGLSurface surface = egl.eglCreateWindowSurface(SDLActivity.mEGLDisplay, SDLActivity.mEGLConfig, SDLActivity.mSurface, null);
if (surface == EGL10.EGL_NO_SURFACE) {
Log.e("SDL", "Couldn't create surface");
return false;
}
if (egl.eglGetCurrentContext() != SDLActivity.mEGLContext) {
if (!egl.eglMakeCurrent(SDLActivity.mEGLDisplay, surface, surface, SDLActivity.mEGLContext)) {
Log.e("SDL", "Old EGL Context doesnt work, trying with a new one");
// TODO: Notify the user via a message that the old context could not be restored, and that textures need to be manually restored.
createEGLContext();
if (!egl.eglMakeCurrent(SDLActivity.mEGLDisplay, surface, surface, SDLActivity.mEGLContext)) {
Log.e("SDL", "Failed making EGL Context current");
return false;
}
}
}
SDLActivity.mEGLSurface = surface;
return true;
} else {
Log.e("SDL", "Surface creation failed, display = " + SDLActivity.mEGLDisplay + ", config = " + SDLActivity.mEGLConfig);
return false;
}
}
// EGL buffer flip
public static void flipEGL() {
try {
EGL10 egl = (EGL10)EGLContext.getEGL();
egl.eglWaitNative(EGL10.EGL_CORE_NATIVE_ENGINE, null);
// drawing here
egl.eglWaitGL();
egl.eglSwapBuffers(SDLActivity.mEGLDisplay, SDLActivity.mEGLSurface);
} catch(Exception e) {
Log.v("SDL", "flipEGL(): " + e);
for (StackTraceElement s : e.getStackTrace()) {
Log.v("SDL", s.toString());
}
}
}
// Audio
public static void audioInit(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) {
int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT;
int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1);
Log.v("SDL", "SDL audio: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + ((float)sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer");
// Let the user pick a larger buffer if they really want -- but ye
// gods they probably shouldn't, the minimums are horrifyingly high
// latency already
desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
audioStartThread();
Log.v("SDL", "SDL audio: got " + ((mAudioTrack.getChannelCount() >= 2) ? "stereo" : "mono") + " " + ((mAudioTrack.getAudioFormat() == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit" : "8-bit") + " " + ((float)mAudioTrack.getSampleRate() / 1000f) + "kHz, " + desiredFrames + " frames buffer");
}
public static void audioStartThread() {
mAudioThread = new Thread(new Runnable() {
public void run() {
mAudioTrack.play();
nativeRunAudioThread();
}
});
// I'd take REALTIME if I could get it!
mAudioThread.setPriority(Thread.MAX_PRIORITY);
mAudioThread.start();
}
public static void audioWriteShortBuffer(short[] buffer) {
for (int i = 0; i < buffer.length; ) {
int result = mAudioTrack.write(buffer, i, buffer.length - i);
if (result > 0) {
i += result;
} else if (result == 0) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
// Nom nom
}
} else {
Log.w("SDL", "SDL audio: error return from write(short)");
return;
}
}
}
public static void audioWriteByteBuffer(byte[] buffer) {
for (int i = 0; i < buffer.length; ) {
int result = mAudioTrack.write(buffer, i, buffer.length - i);
if (result > 0) {
i += result;
} else if (result == 0) {
try {
Thread.sleep(1);
} catch(InterruptedException e) {
// Nom nom
}
} else {
Log.w("SDL", "SDL audio: error return from write(short)");
return;
}
}
}
public static void audioQuit() {
if (mAudioThread != null) {
try {
mAudioThread.join();
} catch(Exception e) {
Log.v("SDL", "Problem stopping audio thread: " + e);
}
mAudioThread = null;
//Log.v("SDL", "Finished waiting for audio thread");
}
if (mAudioTrack != null) {
mAudioTrack.stop();
mAudioTrack = null;
}
}
}
/**
Simple nativeInit() runnable
*/
class SDLMain implements Runnable {
public void run() {
// Runs SDL_main()
SDLActivity.nativeInit();
//Log.v("SDL", "SDL thread terminated");
}
}
/**
SDLSurface. This is what we draw on, so we need to know when it's created
in order to do anything useful.
Because of this, that's where we set up the SDL thread
*/
class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
View.OnKeyListener, View.OnTouchListener, SensorEventListener {
// Sensors
private static SensorManager mSensorManager;
// Keep track of the surface size to normalize touch events
private static float mWidth, mHeight;
// Startup
public SDLSurface(Context context) {
super(context);
getHolder().addCallback(this);
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
setOnKeyListener(this);
setOnTouchListener(this);
mSensorManager = (SensorManager)context.getSystemService("sensor");
// Some arbitrary defaults to avoid a potential division by zero
mWidth = 1.0f;
mHeight = 1.0f;
}
// Called when we have a valid drawing surface
public void surfaceCreated(SurfaceHolder holder) {
Log.v("SDL", "surfaceCreated()");
holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
enableSensor(Sensor.TYPE_ACCELEROMETER, true);
}
// Called when we lose the surface
public void surfaceDestroyed(SurfaceHolder holder) {
Log.v("SDL", "surfaceDestroyed()");
if (!SDLActivity.mIsPaused) {
SDLActivity.mIsPaused = true;
SDLActivity.nativePause();
}
enableSensor(Sensor.TYPE_ACCELEROMETER, false);
}
// Called when the surface is resized
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
Log.v("SDL", "surfaceChanged()");
- int sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 by default
+ int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default
switch (format) {
case PixelFormat.A_8:
Log.v("SDL", "pixel format A_8");
break;
case PixelFormat.LA_88:
Log.v("SDL", "pixel format LA_88");
break;
case PixelFormat.L_8:
Log.v("SDL", "pixel format L_8");
break;
case PixelFormat.RGBA_4444:
Log.v("SDL", "pixel format RGBA_4444");
- sdlFormat = 0x85421002; // SDL_PIXELFORMAT_RGBA4444
+ sdlFormat = 0x15421002; // SDL_PIXELFORMAT_RGBA4444
break;
case PixelFormat.RGBA_5551:
Log.v("SDL", "pixel format RGBA_5551");
- sdlFormat = 0x85441002; // SDL_PIXELFORMAT_RGBA5551
+ sdlFormat = 0x15441002; // SDL_PIXELFORMAT_RGBA5551
break;
case PixelFormat.RGBA_8888:
Log.v("SDL", "pixel format RGBA_8888");
- sdlFormat = 0x86462004; // SDL_PIXELFORMAT_RGBA8888
+ sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888
break;
case PixelFormat.RGBX_8888:
Log.v("SDL", "pixel format RGBX_8888");
- sdlFormat = 0x86262004; // SDL_PIXELFORMAT_RGBX8888
+ sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888
break;
case PixelFormat.RGB_332:
Log.v("SDL", "pixel format RGB_332");
- sdlFormat = 0x84110801; // SDL_PIXELFORMAT_RGB332
+ sdlFormat = 0x14110801; // SDL_PIXELFORMAT_RGB332
break;
case PixelFormat.RGB_565:
Log.v("SDL", "pixel format RGB_565");
- sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565
+ sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565
break;
case PixelFormat.RGB_888:
Log.v("SDL", "pixel format RGB_888");
// Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
- sdlFormat = 0x86161804; // SDL_PIXELFORMAT_RGB888
+ sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888
break;
default:
Log.v("SDL", "pixel format unknown " + format);
break;
}
mWidth = (float) width;
mHeight = (float) height;
SDLActivity.onNativeResize(width, height, sdlFormat);
Log.v("SDL", "Window size:" + width + "x"+height);
SDLActivity.startApp();
}
// unused
public void onDraw(Canvas canvas) {}
// Key events
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
//Log.v("SDL", "key down: " + keyCode);
SDLActivity.onNativeKeyDown(keyCode);
return true;
}
else if (event.getAction() == KeyEvent.ACTION_UP) {
//Log.v("SDL", "key up: " + keyCode);
SDLActivity.onNativeKeyUp(keyCode);
return true;
}
return false;
}
// Touch events
public boolean onTouch(View v, MotionEvent event) {
{
final int touchDevId = event.getDeviceId();
final int pointerCount = event.getPointerCount();
// touchId, pointerId, action, x, y, pressure
int actionPointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent. ACTION_POINTER_ID_SHIFT; /* API 8: event.getActionIndex(); */
int pointerFingerId = event.getPointerId(actionPointerIndex);
int action = (event.getAction() & MotionEvent.ACTION_MASK); /* API 8: event.getActionMasked(); */
float x = event.getX(actionPointerIndex) / mWidth;
float y = event.getY(actionPointerIndex) / mHeight;
float p = event.getPressure(actionPointerIndex);
if (action == MotionEvent.ACTION_MOVE && pointerCount > 1) {
// TODO send motion to every pointer if its position has
// changed since prev event.
for (int i = 0; i < pointerCount; i++) {
pointerFingerId = event.getPointerId(i);
x = event.getX(i) / mWidth;
y = event.getY(i) / mHeight;
p = event.getPressure(i);
SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
}
} else {
SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
}
}
return true;
}
// Sensor events
public void enableSensor(int sensortype, boolean enabled) {
// TODO: This uses getDefaultSensor - what if we have >1 accels?
if (enabled) {
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(sensortype),
SensorManager.SENSOR_DELAY_GAME, null);
} else {
mSensorManager.unregisterListener(this,
mSensorManager.getDefaultSensor(sensortype));
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
SDLActivity.onNativeAccel(event.values[0] / SensorManager.GRAVITY_EARTH,
event.values[1] / SensorManager.GRAVITY_EARTH,
event.values[2] / SensorManager.GRAVITY_EARTH);
}
}
}
/* This is a fake invisible editor view that receives the input and defines the
* pan&scan region
*/
class DummyEdit extends View implements View.OnKeyListener {
InputConnection ic;
public DummyEdit(Context context) {
super(context);
setFocusableInTouchMode(true);
setFocusable(true);
setOnKeyListener(this);
}
@Override
public boolean onCheckIsTextEditor() {
return true;
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
// This handles the hardware keyboard input
if (event.isPrintingKey()) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
ic.commitText(String.valueOf((char) event.getUnicodeChar()), 1);
}
return true;
}
if (event.getAction() == KeyEvent.ACTION_DOWN) {
SDLActivity.onNativeKeyDown(keyCode);
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
SDLActivity.onNativeKeyUp(keyCode);
return true;
}
return false;
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
ic = new SDLInputConnection(this, true);
outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
| 33554432 /* API 11: EditorInfo.IME_FLAG_NO_FULLSCREEN */;
return ic;
}
}
class SDLInputConnection extends BaseInputConnection {
public SDLInputConnection(View targetView, boolean fullEditor) {
super(targetView, fullEditor);
}
@Override
public boolean sendKeyEvent(KeyEvent event) {
/*
* This handles the keycodes from soft keyboard (and IME-translated
* input from hardkeyboard)
*/
int keyCode = event.getKeyCode();
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (event.isPrintingKey()) {
commitText(String.valueOf((char) event.getUnicodeChar()), 1);
}
SDLActivity.onNativeKeyDown(keyCode);
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
SDLActivity.onNativeKeyUp(keyCode);
return true;
}
return super.sendKeyEvent(event);
}
@Override
public boolean commitText(CharSequence text, int newCursorPosition) {
nativeCommitText(text.toString(), newCursorPosition);
return super.commitText(text, newCursorPosition);
}
@Override
public boolean setComposingText(CharSequence text, int newCursorPosition) {
nativeSetComposingText(text.toString(), newCursorPosition);
return super.setComposingText(text, newCursorPosition);
}
public native void nativeCommitText(String text, int newCursorPosition);
public native void nativeSetComposingText(String text, int newCursorPosition);
}
| false | true | public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
Log.v("SDL", "surfaceChanged()");
int sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 by default
switch (format) {
case PixelFormat.A_8:
Log.v("SDL", "pixel format A_8");
break;
case PixelFormat.LA_88:
Log.v("SDL", "pixel format LA_88");
break;
case PixelFormat.L_8:
Log.v("SDL", "pixel format L_8");
break;
case PixelFormat.RGBA_4444:
Log.v("SDL", "pixel format RGBA_4444");
sdlFormat = 0x85421002; // SDL_PIXELFORMAT_RGBA4444
break;
case PixelFormat.RGBA_5551:
Log.v("SDL", "pixel format RGBA_5551");
sdlFormat = 0x85441002; // SDL_PIXELFORMAT_RGBA5551
break;
case PixelFormat.RGBA_8888:
Log.v("SDL", "pixel format RGBA_8888");
sdlFormat = 0x86462004; // SDL_PIXELFORMAT_RGBA8888
break;
case PixelFormat.RGBX_8888:
Log.v("SDL", "pixel format RGBX_8888");
sdlFormat = 0x86262004; // SDL_PIXELFORMAT_RGBX8888
break;
case PixelFormat.RGB_332:
Log.v("SDL", "pixel format RGB_332");
sdlFormat = 0x84110801; // SDL_PIXELFORMAT_RGB332
break;
case PixelFormat.RGB_565:
Log.v("SDL", "pixel format RGB_565");
sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565
break;
case PixelFormat.RGB_888:
Log.v("SDL", "pixel format RGB_888");
// Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
sdlFormat = 0x86161804; // SDL_PIXELFORMAT_RGB888
break;
default:
Log.v("SDL", "pixel format unknown " + format);
break;
}
mWidth = (float) width;
mHeight = (float) height;
SDLActivity.onNativeResize(width, height, sdlFormat);
Log.v("SDL", "Window size:" + width + "x"+height);
SDLActivity.startApp();
}
| public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
Log.v("SDL", "surfaceChanged()");
int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default
switch (format) {
case PixelFormat.A_8:
Log.v("SDL", "pixel format A_8");
break;
case PixelFormat.LA_88:
Log.v("SDL", "pixel format LA_88");
break;
case PixelFormat.L_8:
Log.v("SDL", "pixel format L_8");
break;
case PixelFormat.RGBA_4444:
Log.v("SDL", "pixel format RGBA_4444");
sdlFormat = 0x15421002; // SDL_PIXELFORMAT_RGBA4444
break;
case PixelFormat.RGBA_5551:
Log.v("SDL", "pixel format RGBA_5551");
sdlFormat = 0x15441002; // SDL_PIXELFORMAT_RGBA5551
break;
case PixelFormat.RGBA_8888:
Log.v("SDL", "pixel format RGBA_8888");
sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888
break;
case PixelFormat.RGBX_8888:
Log.v("SDL", "pixel format RGBX_8888");
sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888
break;
case PixelFormat.RGB_332:
Log.v("SDL", "pixel format RGB_332");
sdlFormat = 0x14110801; // SDL_PIXELFORMAT_RGB332
break;
case PixelFormat.RGB_565:
Log.v("SDL", "pixel format RGB_565");
sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565
break;
case PixelFormat.RGB_888:
Log.v("SDL", "pixel format RGB_888");
// Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888
break;
default:
Log.v("SDL", "pixel format unknown " + format);
break;
}
mWidth = (float) width;
mHeight = (float) height;
SDLActivity.onNativeResize(width, height, sdlFormat);
Log.v("SDL", "Window size:" + width + "x"+height);
SDLActivity.startApp();
}
|
diff --git a/src/thesaurus/gui/window/PopupFactory.java b/src/thesaurus/gui/window/PopupFactory.java
index 6c4da33..8bee1a9 100644
--- a/src/thesaurus/gui/window/PopupFactory.java
+++ b/src/thesaurus/gui/window/PopupFactory.java
@@ -1,247 +1,247 @@
package thesaurus.gui.window;
import java.util.LinkedList;
import thesaurus.parser.Vertex;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Popup;
public class PopupFactory {
Popup currentPopup = null;
MainWindow referenceWindow;
public PopupFactory(String inputChoice, MainWindow inputWindow) {
referenceWindow = inputWindow;
if (inputChoice.equals("add")) {
currentPopup = new Popup();
currentPopup.getContent().add(makeCanvasAdd());
} else if (inputChoice.equals("edit")) {
currentPopup = new Popup();
currentPopup.getContent().add(makeCanvasEdit());
} else if (inputChoice.equals("remove")) {
currentPopup = new Popup();
currentPopup.getContent().add(makeCanvasRemove());
} else if (inputChoice.equals("fileError")) {
currentPopup = new Popup();
currentPopup.getContent().add(makeCanvasFileError());
} else if (inputChoice.equals("about")) {
currentPopup = new Popup();
currentPopup.getContent().add(makeAbout());
}
}
private Pane makeCanvasAdd() {
Pane canvas = getPane(220,230);
Text addWordLabel = getText(35,10,"Add Word",2);
Text promptWordLabel = getText(5,52,"Word: ",1);
final TextField addWordInput = getTextField(80, 50, 120);
Text promptSynLabel = getText(5,82,"Synonyms: ",1);
final TextField addSynInput = getTextField(80, 80, 120);
Text promptAntLabel = getText(5,112,"Antonyms: ",1);
final TextField addAntInput = getTextField(80, 110, 120);
Text promptCatLabel = getText(5,142,"Category: ",1);
final TextField addCatInput = getTextField(80, 140, 120);
Button confirmButton = new Button();
confirmButton.setText("Confirm");
confirmButton.relocate(25, 190);
confirmButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
referenceWindow.getVisualisationRoot().getCurrentParser().addVertex(addWordInput.getText(), addSynInput.getText(),addAntInput.getText(),addCatInput.getText());
System.out.printf("\n\n=========== %s ======== %s\n\n",addWordInput.getText(), addSynInput.getText());
currentPopup.hide();
currentPopup = null;
referenceWindow.getVisualisationRoot().doClickSearchGraph(addWordInput.getText());
referenceWindow.getVisualisationRoot().addCanvas();
referenceWindow.getVisualisationRoot().addTable();
}
});
Button cancelButton = new Button();
cancelButton.setText("Cancel");
cancelButton.relocate(105, 190);
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
currentPopup.hide();
currentPopup = null;
}
});
canvas.getChildren().addAll(addWordLabel, promptWordLabel,
addWordInput, promptSynLabel, addSynInput, promptAntLabel,
addAntInput, promptCatLabel, addCatInput, confirmButton, cancelButton);
canvas.setStyle(" -fx-background-color: #dfdfdf;"
+ "-fx-border-color: black;" + "-fx-border-width: 1px;" + "-fx-font-family: 'Arial';");
return canvas;
}
private Pane makeCanvasFileError() {
Pane canvas = getPane(150,80);
Text confirmLabel = getText(25,10,"File Does Not Exist",1);
Button confirmButton = new Button();
confirmButton.setText("Confirm");
confirmButton.relocate(40, 42);
confirmButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
currentPopup.hide();
currentPopup = null;
}
});
canvas.getChildren().addAll(confirmLabel, confirmButton);
canvas.setStyle(" -fx-background-color: #dfdfdf;"
+ "-fx-border-color: black;" + "-fx-border-width: 1px;" + "-fx-font-family: 'Arial';");
return canvas;
}
private Pane makeAbout() {
Pane canvas = getPane(150,80);
Text one_Label = getText(8,10,"Graphical Thesaurus",1);
Text two_Label = getText(35,26,"by Team O",1);
Button confirmButton = new Button();
confirmButton.setText("OK");
confirmButton.relocate(55, 45);
confirmButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
currentPopup.hide();
currentPopup = null;
}
});
canvas.getChildren().addAll(one_Label, two_Label, confirmButton);
canvas.setStyle(" -fx-background-color: #dfdfdf;"
+ "-fx-border-color: black;" + "-fx-border-width: 1px;" + "-fx-font-family: 'Arial';");
return canvas;
}
private Pane makeCanvasEdit() {
Pane canvas = getPane(220,230);
Text addWordLabel = getText(35,10,"Edit Word",2);
Text promptWordLabel = getText(5,52,"Word: ",1);
final TextField addWordInput = getTextField(80, 50, 120);
Text promptSynLabel = getText(5,82,"Synonyms: ",1);
final TextField addSynInput = getTextField(80, 80, 120);
Text promptAntLabel = getText(5,112,"Antonyms: ",1);
final TextField addAntInput = getTextField(80, 110, 120);
Text promptCatLabel = getText(5,142,"Category: ",1);
final TextField addCatInput = getTextField(80, 140, 120);
Button confirmButton = new Button();
confirmButton.setText("Confirm");
confirmButton.relocate(25, 190);
confirmButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
String newWord = addWordInput.getText();
String oldWord = referenceWindow.getVisualisationRoot().getCurrentVertex().getWord();
if(!oldWord.equalsIgnoreCase(newWord)) {
- referenceWindow.getVisualisationRoot().getCurrentParser().editVertex(oldWord, newWord);
+ //referenceWindow.getVisualisationRoot().getCurrentParser().editVertex(oldWord, newWord);
}
referenceWindow.getVisualisationRoot().getCurrentParser().addVertex(newWord, addSynInput.getText(), addAntInput.getText(),"");
currentPopup.hide();
currentPopup = null;
}
});
Button cancelButton = new Button();
cancelButton.setText("Cancel");
cancelButton.relocate(105, 190);
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
currentPopup.hide();
currentPopup = null;
}
});
canvas.getChildren().addAll(addWordLabel, promptWordLabel,
addWordInput, promptSynLabel, addSynInput, promptAntLabel,
addAntInput, promptCatLabel, addCatInput, confirmButton, cancelButton);
canvas.setStyle(" -fx-background-color: #dfdfdf;"
+ "-fx-border-color: black;" + "-fx-border-width: 1px;" + "-fx-font-family: 'Arial';");
addWordInput.setText(referenceWindow.getVisualisationRoot().getCurrentVertex().getWord());
addSynInput.setText(convertCsv(referenceWindow.getVisualisationRoot().getCurrentVertex().getSynomyns()));
addAntInput.setText(convertCsv(referenceWindow.getVisualisationRoot().getCurrentVertex().getAntonyms()));
addCatInput.setText(convertCsv(referenceWindow.getVisualisationRoot().getCurrentVertex().getGroupings()));
return canvas;
}
private Pane makeCanvasRemove() {
Pane canvas = getPane(200,200);
Text addWordLabel = getText(50,10,"Remove Word",2);
Text promptWordLabel = getText(10,52,"Word: ",1);
final TextField addWordInput = getTextField(70, 50, 120);
Button confirmButton = new Button();
confirmButton.setText("Confirm");
confirmButton.relocate(25, 160);
confirmButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
referenceWindow.getVisualisationRoot().getCurrentParser().removeVertex(addWordInput.getText());
currentPopup.hide();
currentPopup = null;
referenceWindow.getVisualisationRoot().initialSearch();
}
});
Button cancelButton = new Button();
cancelButton.setText("Cancel");
cancelButton.relocate(105, 160);
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
currentPopup.hide();
currentPopup = null;
}
});
canvas.getChildren().addAll(addWordLabel, promptWordLabel,addWordInput, confirmButton, cancelButton);
canvas.setStyle(" -fx-background-color: #dfdfdf;"+ "-fx-border-color: black;" + "-fx-border-width: 1px;" + "-fx-font-family: 'Arial';");
return canvas;
}
public Popup getPopup() {
return currentPopup;
}
private Pane getPane(int x, int y) {
Pane currentCanvas = new Pane();
currentCanvas.setPrefSize(x, y);
return currentCanvas;
}
private Text getText(int x, int y, String inputString, int scale) {
Text currentWordLabel = new Text();
currentWordLabel.relocate(x, y);
currentWordLabel.setText(inputString);
currentWordLabel.setScaleX(scale);
currentWordLabel.setScaleY(scale);
return currentWordLabel;
}
private TextField getTextField(int x, int y, int width) {
TextField currentWordInput = new TextField();
currentWordInput.setPrefWidth(width);
currentWordInput.relocate(x, y);
return currentWordInput;
}
private String convertCsv(LinkedList<Vertex> input){
String toreturn = "";
for(Vertex s:input){
if(!toreturn.equals("")){
System.out.println(s.getWord());
toreturn = toreturn + ", "+s.getWord();
}
else{
System.out.println(s.getWord());
toreturn = toreturn + s.getWord();
}
}
return toreturn;
}
}
| true | true | private Pane makeCanvasEdit() {
Pane canvas = getPane(220,230);
Text addWordLabel = getText(35,10,"Edit Word",2);
Text promptWordLabel = getText(5,52,"Word: ",1);
final TextField addWordInput = getTextField(80, 50, 120);
Text promptSynLabel = getText(5,82,"Synonyms: ",1);
final TextField addSynInput = getTextField(80, 80, 120);
Text promptAntLabel = getText(5,112,"Antonyms: ",1);
final TextField addAntInput = getTextField(80, 110, 120);
Text promptCatLabel = getText(5,142,"Category: ",1);
final TextField addCatInput = getTextField(80, 140, 120);
Button confirmButton = new Button();
confirmButton.setText("Confirm");
confirmButton.relocate(25, 190);
confirmButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
String newWord = addWordInput.getText();
String oldWord = referenceWindow.getVisualisationRoot().getCurrentVertex().getWord();
if(!oldWord.equalsIgnoreCase(newWord)) {
referenceWindow.getVisualisationRoot().getCurrentParser().editVertex(oldWord, newWord);
}
referenceWindow.getVisualisationRoot().getCurrentParser().addVertex(newWord, addSynInput.getText(), addAntInput.getText(),"");
currentPopup.hide();
currentPopup = null;
}
});
Button cancelButton = new Button();
cancelButton.setText("Cancel");
cancelButton.relocate(105, 190);
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
currentPopup.hide();
currentPopup = null;
}
});
canvas.getChildren().addAll(addWordLabel, promptWordLabel,
addWordInput, promptSynLabel, addSynInput, promptAntLabel,
addAntInput, promptCatLabel, addCatInput, confirmButton, cancelButton);
canvas.setStyle(" -fx-background-color: #dfdfdf;"
+ "-fx-border-color: black;" + "-fx-border-width: 1px;" + "-fx-font-family: 'Arial';");
addWordInput.setText(referenceWindow.getVisualisationRoot().getCurrentVertex().getWord());
addSynInput.setText(convertCsv(referenceWindow.getVisualisationRoot().getCurrentVertex().getSynomyns()));
addAntInput.setText(convertCsv(referenceWindow.getVisualisationRoot().getCurrentVertex().getAntonyms()));
addCatInput.setText(convertCsv(referenceWindow.getVisualisationRoot().getCurrentVertex().getGroupings()));
return canvas;
}
| private Pane makeCanvasEdit() {
Pane canvas = getPane(220,230);
Text addWordLabel = getText(35,10,"Edit Word",2);
Text promptWordLabel = getText(5,52,"Word: ",1);
final TextField addWordInput = getTextField(80, 50, 120);
Text promptSynLabel = getText(5,82,"Synonyms: ",1);
final TextField addSynInput = getTextField(80, 80, 120);
Text promptAntLabel = getText(5,112,"Antonyms: ",1);
final TextField addAntInput = getTextField(80, 110, 120);
Text promptCatLabel = getText(5,142,"Category: ",1);
final TextField addCatInput = getTextField(80, 140, 120);
Button confirmButton = new Button();
confirmButton.setText("Confirm");
confirmButton.relocate(25, 190);
confirmButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
String newWord = addWordInput.getText();
String oldWord = referenceWindow.getVisualisationRoot().getCurrentVertex().getWord();
if(!oldWord.equalsIgnoreCase(newWord)) {
//referenceWindow.getVisualisationRoot().getCurrentParser().editVertex(oldWord, newWord);
}
referenceWindow.getVisualisationRoot().getCurrentParser().addVertex(newWord, addSynInput.getText(), addAntInput.getText(),"");
currentPopup.hide();
currentPopup = null;
}
});
Button cancelButton = new Button();
cancelButton.setText("Cancel");
cancelButton.relocate(105, 190);
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
currentPopup.hide();
currentPopup = null;
}
});
canvas.getChildren().addAll(addWordLabel, promptWordLabel,
addWordInput, promptSynLabel, addSynInput, promptAntLabel,
addAntInput, promptCatLabel, addCatInput, confirmButton, cancelButton);
canvas.setStyle(" -fx-background-color: #dfdfdf;"
+ "-fx-border-color: black;" + "-fx-border-width: 1px;" + "-fx-font-family: 'Arial';");
addWordInput.setText(referenceWindow.getVisualisationRoot().getCurrentVertex().getWord());
addSynInput.setText(convertCsv(referenceWindow.getVisualisationRoot().getCurrentVertex().getSynomyns()));
addAntInput.setText(convertCsv(referenceWindow.getVisualisationRoot().getCurrentVertex().getAntonyms()));
addCatInput.setText(convertCsv(referenceWindow.getVisualisationRoot().getCurrentVertex().getGroupings()));
return canvas;
}
|
diff --git a/svnkit-cli/src/org/tmatesoft/svn/cli2/SVNCommandLine.java b/svnkit-cli/src/org/tmatesoft/svn/cli2/SVNCommandLine.java
index 6748cf152..2a165039c 100644
--- a/svnkit-cli/src/org/tmatesoft/svn/cli2/SVNCommandLine.java
+++ b/svnkit-cli/src/org/tmatesoft/svn/cli2/SVNCommandLine.java
@@ -1,171 +1,170 @@
/*
* ====================================================================
* Copyright (c) 2004-2007 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.cli2;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.internal.util.SVNHashMap;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
/**
* @version 1.1.2
* @author TMate Software Ltd.
*/
public class SVNCommandLine {
private static final Map ourOptions = new SVNHashMap();
public static void registerOption(AbstractSVNOption option) {
if (option.getName() != null) {
ourOptions.put("--" + option.getName(), option);
}
if (option.getAlias() != null) {
ourOptions.put("-" + option.getAlias(), option);
}
}
private String myCommand;
private Collection myArguments;
private Collection myOptions;
private boolean myNeedsCommand;
public SVNCommandLine() {
this(true);
}
public SVNCommandLine(boolean needsCommand) {
myArguments = new LinkedList();
myOptions = new LinkedList();
myNeedsCommand = needsCommand;
}
public void init(String[] args) throws SVNException {
myInputArguments = args;
myArgumentPosition = 0;
myArgumentIndex = 0;
myArguments = new LinkedList();
myOptions = new LinkedList();
myCommand = null;
while (true) {
SVNOptionValue value = nextOption();
if (value != null) {
myOptions.add(value);
} else {
return;
}
}
}
private int myArgumentIndex;
private int myArgumentPosition;
private String[] myInputArguments;
private SVNOptionValue nextOption() throws SVNException {
if (myArgumentPosition == 0) {
while (myArgumentIndex < myInputArguments.length && !myInputArguments[myArgumentIndex].startsWith("-")) {
String argument = myInputArguments[myArgumentIndex];
// this is either command name or non-option argument.
if (myNeedsCommand && myCommand == null) {
myCommand = argument;
} else {
myArguments.add(argument);
}
myArgumentIndex++;
}
if (myArgumentIndex >= myInputArguments.length) {
return null;
}
// now we're in the beginning of option. parse option name first.
String argument = myInputArguments[myArgumentIndex];
if (argument.startsWith("--")) {
// it is long option, long option with '=value', or --long value set.
int valueIndex = argument.indexOf('=');
String optionName = valueIndex > 0 ? argument.substring(0, valueIndex) : argument;
AbstractSVNOption option = (AbstractSVNOption) ourOptions.get(optionName);
if (option == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "invalid option: {0}", optionName);
SVNErrorManager.error(err);
}
String value = null;
if (!option.isUnary()) {
if (valueIndex > 0) {
value = argument.substring(valueIndex + 1);
} else {
myArgumentIndex++;
value = myArgumentIndex < myInputArguments.length ? myInputArguments[myArgumentIndex] : null;
}
if (value == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "missing argument: {0}", optionName);
SVNErrorManager.error(err);
}
}
myArgumentIndex++;
return new SVNOptionValue(option, optionName, value);
}
myArgumentPosition = 1;
}
// set of short options or set of short options with '[=]value', or -shortset value
// process each option is set until binary one found. then process value.
String argument = myInputArguments[myArgumentIndex];
String optionName = "-" + argument.charAt(myArgumentPosition++);
AbstractSVNOption option = (AbstractSVNOption) ourOptions.get(optionName);
if (option == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "invalid option: {0}", optionName);
SVNErrorManager.error(err);
}
String value = null;
if (!option.isUnary()) {
if (myArgumentPosition < argument.length()) {
value = argument.substring(myArgumentPosition);
if (value.startsWith("=")) {
value = value.substring(1);
}
- myArgumentPosition = 0;
- myArgumentIndex++;
} else {
myArgumentIndex++;
- myArgumentPosition = 0;
value = myArgumentIndex < myInputArguments.length ? myInputArguments[myArgumentIndex] : null;
}
+ myArgumentPosition = 0;
+ myArgumentIndex++;
if (value == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "missing argument: {0}", optionName);
SVNErrorManager.error(err);
}
}
if (myArgumentPosition >= argument.length()) {
myArgumentPosition = 0;
myArgumentIndex++;
}
return new SVNOptionValue(option, optionName, value);
}
public Iterator optionValues() {
return myOptions.iterator();
}
public String getCommandName() {
return myCommand;
}
public Collection getArguments() {
return myArguments;
}
}
| false | true | private SVNOptionValue nextOption() throws SVNException {
if (myArgumentPosition == 0) {
while (myArgumentIndex < myInputArguments.length && !myInputArguments[myArgumentIndex].startsWith("-")) {
String argument = myInputArguments[myArgumentIndex];
// this is either command name or non-option argument.
if (myNeedsCommand && myCommand == null) {
myCommand = argument;
} else {
myArguments.add(argument);
}
myArgumentIndex++;
}
if (myArgumentIndex >= myInputArguments.length) {
return null;
}
// now we're in the beginning of option. parse option name first.
String argument = myInputArguments[myArgumentIndex];
if (argument.startsWith("--")) {
// it is long option, long option with '=value', or --long value set.
int valueIndex = argument.indexOf('=');
String optionName = valueIndex > 0 ? argument.substring(0, valueIndex) : argument;
AbstractSVNOption option = (AbstractSVNOption) ourOptions.get(optionName);
if (option == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "invalid option: {0}", optionName);
SVNErrorManager.error(err);
}
String value = null;
if (!option.isUnary()) {
if (valueIndex > 0) {
value = argument.substring(valueIndex + 1);
} else {
myArgumentIndex++;
value = myArgumentIndex < myInputArguments.length ? myInputArguments[myArgumentIndex] : null;
}
if (value == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "missing argument: {0}", optionName);
SVNErrorManager.error(err);
}
}
myArgumentIndex++;
return new SVNOptionValue(option, optionName, value);
}
myArgumentPosition = 1;
}
// set of short options or set of short options with '[=]value', or -shortset value
// process each option is set until binary one found. then process value.
String argument = myInputArguments[myArgumentIndex];
String optionName = "-" + argument.charAt(myArgumentPosition++);
AbstractSVNOption option = (AbstractSVNOption) ourOptions.get(optionName);
if (option == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "invalid option: {0}", optionName);
SVNErrorManager.error(err);
}
String value = null;
if (!option.isUnary()) {
if (myArgumentPosition < argument.length()) {
value = argument.substring(myArgumentPosition);
if (value.startsWith("=")) {
value = value.substring(1);
}
myArgumentPosition = 0;
myArgumentIndex++;
} else {
myArgumentIndex++;
myArgumentPosition = 0;
value = myArgumentIndex < myInputArguments.length ? myInputArguments[myArgumentIndex] : null;
}
if (value == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "missing argument: {0}", optionName);
SVNErrorManager.error(err);
}
}
if (myArgumentPosition >= argument.length()) {
myArgumentPosition = 0;
myArgumentIndex++;
}
return new SVNOptionValue(option, optionName, value);
}
| private SVNOptionValue nextOption() throws SVNException {
if (myArgumentPosition == 0) {
while (myArgumentIndex < myInputArguments.length && !myInputArguments[myArgumentIndex].startsWith("-")) {
String argument = myInputArguments[myArgumentIndex];
// this is either command name or non-option argument.
if (myNeedsCommand && myCommand == null) {
myCommand = argument;
} else {
myArguments.add(argument);
}
myArgumentIndex++;
}
if (myArgumentIndex >= myInputArguments.length) {
return null;
}
// now we're in the beginning of option. parse option name first.
String argument = myInputArguments[myArgumentIndex];
if (argument.startsWith("--")) {
// it is long option, long option with '=value', or --long value set.
int valueIndex = argument.indexOf('=');
String optionName = valueIndex > 0 ? argument.substring(0, valueIndex) : argument;
AbstractSVNOption option = (AbstractSVNOption) ourOptions.get(optionName);
if (option == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "invalid option: {0}", optionName);
SVNErrorManager.error(err);
}
String value = null;
if (!option.isUnary()) {
if (valueIndex > 0) {
value = argument.substring(valueIndex + 1);
} else {
myArgumentIndex++;
value = myArgumentIndex < myInputArguments.length ? myInputArguments[myArgumentIndex] : null;
}
if (value == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "missing argument: {0}", optionName);
SVNErrorManager.error(err);
}
}
myArgumentIndex++;
return new SVNOptionValue(option, optionName, value);
}
myArgumentPosition = 1;
}
// set of short options or set of short options with '[=]value', or -shortset value
// process each option is set until binary one found. then process value.
String argument = myInputArguments[myArgumentIndex];
String optionName = "-" + argument.charAt(myArgumentPosition++);
AbstractSVNOption option = (AbstractSVNOption) ourOptions.get(optionName);
if (option == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "invalid option: {0}", optionName);
SVNErrorManager.error(err);
}
String value = null;
if (!option.isUnary()) {
if (myArgumentPosition < argument.length()) {
value = argument.substring(myArgumentPosition);
if (value.startsWith("=")) {
value = value.substring(1);
}
} else {
myArgumentIndex++;
value = myArgumentIndex < myInputArguments.length ? myInputArguments[myArgumentIndex] : null;
}
myArgumentPosition = 0;
myArgumentIndex++;
if (value == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR, "missing argument: {0}", optionName);
SVNErrorManager.error(err);
}
}
if (myArgumentPosition >= argument.length()) {
myArgumentPosition = 0;
myArgumentIndex++;
}
return new SVNOptionValue(option, optionName, value);
}
|
diff --git a/src/main/java/com/pk/cwierkacz/controller/ErrorServlet.java b/src/main/java/com/pk/cwierkacz/controller/ErrorServlet.java
index 33929f0..2bdd1da 100644
--- a/src/main/java/com/pk/cwierkacz/controller/ErrorServlet.java
+++ b/src/main/java/com/pk/cwierkacz/controller/ErrorServlet.java
@@ -1,67 +1,67 @@
package com.pk.cwierkacz.controller;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.pk.cwierkacz.exception.ProcessingException;
import com.pk.cwierkacz.http.RequestBuilder;
import com.pk.cwierkacz.http.Status;
import com.pk.cwierkacz.http.response.Response;
import com.pk.cwierkacz.http.response.ResponseImpl;
import com.pk.cwierkacz.model.transformer.JsonTransformer;
public class ErrorServlet extends HttpServlet
{
private static final long serialVersionUID = -227196281703855928L;
@Override
protected void doPost( HttpServletRequest req, HttpServletResponse resp ) throws javax.servlet.ServletException,
IOException {
doGet(req, resp);
}
@Override
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws IOException {
Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
String token = null;
Cookie[] cookies = request.getCookies();
for ( Cookie cookie : cookies ) {
if ( cookie.getName().equals(RequestBuilder.TOKEN) ) {
token = cookie.getValue();
break;
}
}
Response responseResult = ResponseImpl.create(Status.ERROR,
- "Wystąpił wewnętrzy bład aplikacji." +
+ "Wystąpił wewnętrzny błąd aplikacji." +
throwable.getMessage(),
Long.parseLong(token));
String responseJson;
try {
responseJson = JsonTransformer.responseToJson(responseResult);
}
catch ( ProcessingException e ) {
responseJson = "Fail to creat JSON";
}
if ( request.getParameter("callback") != null ) {
responseJson = request.getParameter("callback") + "(" + responseJson + ");";
}
Cookie cookie = new Cookie("token", token);
cookie.setMaxAge(60 * 60);
response.addCookie(cookie);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setStatus(HttpServletResponse.SC_OK);
Writer out = response.getWriter();
out.write(responseJson);
}
}
| true | true | public void doGet( HttpServletRequest request, HttpServletResponse response ) throws IOException {
Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
String token = null;
Cookie[] cookies = request.getCookies();
for ( Cookie cookie : cookies ) {
if ( cookie.getName().equals(RequestBuilder.TOKEN) ) {
token = cookie.getValue();
break;
}
}
Response responseResult = ResponseImpl.create(Status.ERROR,
"Wystąpił wewnętrzy bład aplikacji." +
throwable.getMessage(),
Long.parseLong(token));
String responseJson;
try {
responseJson = JsonTransformer.responseToJson(responseResult);
}
catch ( ProcessingException e ) {
responseJson = "Fail to creat JSON";
}
if ( request.getParameter("callback") != null ) {
responseJson = request.getParameter("callback") + "(" + responseJson + ");";
}
Cookie cookie = new Cookie("token", token);
cookie.setMaxAge(60 * 60);
response.addCookie(cookie);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setStatus(HttpServletResponse.SC_OK);
Writer out = response.getWriter();
out.write(responseJson);
}
| public void doGet( HttpServletRequest request, HttpServletResponse response ) throws IOException {
Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
String token = null;
Cookie[] cookies = request.getCookies();
for ( Cookie cookie : cookies ) {
if ( cookie.getName().equals(RequestBuilder.TOKEN) ) {
token = cookie.getValue();
break;
}
}
Response responseResult = ResponseImpl.create(Status.ERROR,
"Wystąpił wewnętrzny błąd aplikacji." +
throwable.getMessage(),
Long.parseLong(token));
String responseJson;
try {
responseJson = JsonTransformer.responseToJson(responseResult);
}
catch ( ProcessingException e ) {
responseJson = "Fail to creat JSON";
}
if ( request.getParameter("callback") != null ) {
responseJson = request.getParameter("callback") + "(" + responseJson + ");";
}
Cookie cookie = new Cookie("token", token);
cookie.setMaxAge(60 * 60);
response.addCookie(cookie);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setStatus(HttpServletResponse.SC_OK);
Writer out = response.getWriter();
out.write(responseJson);
}
|
diff --git a/src/main/java/com/eli/web/action/MainSearch.java b/src/main/java/com/eli/web/action/MainSearch.java
index 8a3543a..a3c65be 100644
--- a/src/main/java/com/eli/web/action/MainSearch.java
+++ b/src/main/java/com/eli/web/action/MainSearch.java
@@ -1,94 +1,94 @@
package com.eli.web.action;
import com.eli.index.manager.MultiNRTSearcherAgent;
import com.eli.index.manager.ZhihuIndexManager;
import com.eli.web.BasicAction;
import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.util.Version;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainSearch extends BasicAction {
private static final Logger logger = Logger.getLogger(MainSearch.class);
private static Analyzer analyzer= new CJKAnalyzer(Version.LUCENE_36);
@Override
protected void execute() throws IOException {
- String token = super.getParam("q", "?");
+ String token = super.getParam("q", "");
int offset = Integer.parseInt(super.getParam("offset", "0"));
int limit = Integer.parseInt(super.getParam("limit", "20"));
super.put("query", token);
super.put("offset", offset);
super.put("limit", limit);
super.put("total", 0);
super.put("page", 0);
QueryParser qp = new QueryParser(Version.LUCENE_36, "content.NGRAM", analyzer);
QueryParser qp1 = new QueryParser(Version.LUCENE_36, "title.NGRAM", analyzer);
List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
MultiNRTSearcherAgent agent = ZhihuIndexManager.INSTANCE.acquire();
try{
IndexSearcher searcher = agent.getSearcher();
Query sub = qp.parse(token);
Query sub1 = qp1.parse(token);
BooleanQuery query = new BooleanQuery();
query.add(sub, BooleanClause.Occur.SHOULD);
query.add(sub1, BooleanClause.Occur.SHOULD);
TopDocs hits = searcher.search(query, offset + limit);
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"hi\">", "</span>"), new SimpleHTMLEncoder(), scorer);
highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer));
super.put("total", hits.totalHits);
super.put("page",((hits.totalHits+19)/20)+1);
for (int i = offset; i < hits.scoreDocs.length && i < offset + limit; i++) {
int docId = hits.scoreDocs[i].doc;
Document doc = searcher.doc(docId);
String content = doc.get("content.NGRAM");
String title = doc.get("title.NGRAM");
if (title == null)
title = "";
TokenStream stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "content.NGRAM", doc, analyzer );
content = highlighter.getBestFragment(stream, content);
stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "title.NGRAM", doc, analyzer );
title = highlighter.getBestFragment(stream, title);
if (title == null)
title = "无标题";
if (content == null)
content = "无内容";
String url = doc.get("url.None");
Map<String,String> map = new HashMap<String, String>();
map.put("content", content);
map.put("title", title);
map.put("url", url);
ret.add(map);
}
} catch (Exception e) {
logger.error(e);
} finally {
ZhihuIndexManager.INSTANCE.release(agent);
}
super.put("ret", ret);
}
}
| true | true | protected void execute() throws IOException {
String token = super.getParam("q", "?");
int offset = Integer.parseInt(super.getParam("offset", "0"));
int limit = Integer.parseInt(super.getParam("limit", "20"));
super.put("query", token);
super.put("offset", offset);
super.put("limit", limit);
super.put("total", 0);
super.put("page", 0);
QueryParser qp = new QueryParser(Version.LUCENE_36, "content.NGRAM", analyzer);
QueryParser qp1 = new QueryParser(Version.LUCENE_36, "title.NGRAM", analyzer);
List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
MultiNRTSearcherAgent agent = ZhihuIndexManager.INSTANCE.acquire();
try{
IndexSearcher searcher = agent.getSearcher();
Query sub = qp.parse(token);
Query sub1 = qp1.parse(token);
BooleanQuery query = new BooleanQuery();
query.add(sub, BooleanClause.Occur.SHOULD);
query.add(sub1, BooleanClause.Occur.SHOULD);
TopDocs hits = searcher.search(query, offset + limit);
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"hi\">", "</span>"), new SimpleHTMLEncoder(), scorer);
highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer));
super.put("total", hits.totalHits);
super.put("page",((hits.totalHits+19)/20)+1);
for (int i = offset; i < hits.scoreDocs.length && i < offset + limit; i++) {
int docId = hits.scoreDocs[i].doc;
Document doc = searcher.doc(docId);
String content = doc.get("content.NGRAM");
String title = doc.get("title.NGRAM");
if (title == null)
title = "";
TokenStream stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "content.NGRAM", doc, analyzer );
content = highlighter.getBestFragment(stream, content);
stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "title.NGRAM", doc, analyzer );
title = highlighter.getBestFragment(stream, title);
if (title == null)
title = "无标题";
if (content == null)
content = "无内容";
String url = doc.get("url.None");
Map<String,String> map = new HashMap<String, String>();
map.put("content", content);
map.put("title", title);
map.put("url", url);
ret.add(map);
}
} catch (Exception e) {
logger.error(e);
} finally {
ZhihuIndexManager.INSTANCE.release(agent);
}
super.put("ret", ret);
}
| protected void execute() throws IOException {
String token = super.getParam("q", "");
int offset = Integer.parseInt(super.getParam("offset", "0"));
int limit = Integer.parseInt(super.getParam("limit", "20"));
super.put("query", token);
super.put("offset", offset);
super.put("limit", limit);
super.put("total", 0);
super.put("page", 0);
QueryParser qp = new QueryParser(Version.LUCENE_36, "content.NGRAM", analyzer);
QueryParser qp1 = new QueryParser(Version.LUCENE_36, "title.NGRAM", analyzer);
List<Map<String, String>> ret = new ArrayList<Map<String, String>>();
MultiNRTSearcherAgent agent = ZhihuIndexManager.INSTANCE.acquire();
try{
IndexSearcher searcher = agent.getSearcher();
Query sub = qp.parse(token);
Query sub1 = qp1.parse(token);
BooleanQuery query = new BooleanQuery();
query.add(sub, BooleanClause.Occur.SHOULD);
query.add(sub1, BooleanClause.Occur.SHOULD);
TopDocs hits = searcher.search(query, offset + limit);
QueryScorer scorer = new QueryScorer(query);
Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"hi\">", "</span>"), new SimpleHTMLEncoder(), scorer);
highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer));
super.put("total", hits.totalHits);
super.put("page",((hits.totalHits+19)/20)+1);
for (int i = offset; i < hits.scoreDocs.length && i < offset + limit; i++) {
int docId = hits.scoreDocs[i].doc;
Document doc = searcher.doc(docId);
String content = doc.get("content.NGRAM");
String title = doc.get("title.NGRAM");
if (title == null)
title = "";
TokenStream stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "content.NGRAM", doc, analyzer );
content = highlighter.getBestFragment(stream, content);
stream = TokenSources.getAnyTokenStream(searcher.getIndexReader(), docId, "title.NGRAM", doc, analyzer );
title = highlighter.getBestFragment(stream, title);
if (title == null)
title = "无标题";
if (content == null)
content = "无内容";
String url = doc.get("url.None");
Map<String,String> map = new HashMap<String, String>();
map.put("content", content);
map.put("title", title);
map.put("url", url);
ret.add(map);
}
} catch (Exception e) {
logger.error(e);
} finally {
ZhihuIndexManager.INSTANCE.release(agent);
}
super.put("ret", ret);
}
|
diff --git a/src/jvm/clojure/lang/ProxyHandler.java b/src/jvm/clojure/lang/ProxyHandler.java
index 2e67d5b4..832deefa 100644
--- a/src/jvm/clojure/lang/ProxyHandler.java
+++ b/src/jvm/clojure/lang/ProxyHandler.java
@@ -1,60 +1,60 @@
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
* which can be found in the file CPL.TXT at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
/* rich Oct 4, 2007 */
package clojure.lang;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxyHandler implements InvocationHandler{
//method-name-string->fn
final IPersistentMap fns;
public ProxyHandler(IPersistentMap fns){
this.fns = fns;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
Class rt = method.getReturnType();
IFn fn = (IFn) fns.valAt(method.getName());
if(fn == null)
{
if(rt == Void.TYPE)
return null;
throw new UnsupportedOperationException();
}
Object ret = fn.applyTo(ArraySeq.create(args));
if(rt == Void.TYPE)
return null;
else if(rt.isPrimitive())
{
if(rt == Character.TYPE)
return ret;
else if(rt == Integer.TYPE)
return ((Number) ret).intValue();
else if(rt == Long.TYPE)
return ((Number) ret).longValue();
else if(rt == Float.TYPE)
return ((Number) ret).floatValue();
else if(rt == Double.TYPE)
return ((Number) ret).doubleValue();
- else if(rt == Boolean.TYPE)
+ else if(rt == Boolean.TYPE && !(ret instanceof Boolean))
return ret == null ? Boolean.FALSE : Boolean.TRUE;
else if(rt == Byte.TYPE)
return (byte) ((Number) ret).intValue();
else if(rt == Short.TYPE)
return (short) ((Number) ret).intValue();
}
return ret;
}
}
| true | true | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
Class rt = method.getReturnType();
IFn fn = (IFn) fns.valAt(method.getName());
if(fn == null)
{
if(rt == Void.TYPE)
return null;
throw new UnsupportedOperationException();
}
Object ret = fn.applyTo(ArraySeq.create(args));
if(rt == Void.TYPE)
return null;
else if(rt.isPrimitive())
{
if(rt == Character.TYPE)
return ret;
else if(rt == Integer.TYPE)
return ((Number) ret).intValue();
else if(rt == Long.TYPE)
return ((Number) ret).longValue();
else if(rt == Float.TYPE)
return ((Number) ret).floatValue();
else if(rt == Double.TYPE)
return ((Number) ret).doubleValue();
else if(rt == Boolean.TYPE)
return ret == null ? Boolean.FALSE : Boolean.TRUE;
else if(rt == Byte.TYPE)
return (byte) ((Number) ret).intValue();
else if(rt == Short.TYPE)
return (short) ((Number) ret).intValue();
}
return ret;
}
| public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
Class rt = method.getReturnType();
IFn fn = (IFn) fns.valAt(method.getName());
if(fn == null)
{
if(rt == Void.TYPE)
return null;
throw new UnsupportedOperationException();
}
Object ret = fn.applyTo(ArraySeq.create(args));
if(rt == Void.TYPE)
return null;
else if(rt.isPrimitive())
{
if(rt == Character.TYPE)
return ret;
else if(rt == Integer.TYPE)
return ((Number) ret).intValue();
else if(rt == Long.TYPE)
return ((Number) ret).longValue();
else if(rt == Float.TYPE)
return ((Number) ret).floatValue();
else if(rt == Double.TYPE)
return ((Number) ret).doubleValue();
else if(rt == Boolean.TYPE && !(ret instanceof Boolean))
return ret == null ? Boolean.FALSE : Boolean.TRUE;
else if(rt == Byte.TYPE)
return (byte) ((Number) ret).intValue();
else if(rt == Short.TYPE)
return (short) ((Number) ret).intValue();
}
return ret;
}
|
diff --git a/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelInsert.java b/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelInsert.java
index fe39c84..6f7e830 100644
--- a/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelInsert.java
+++ b/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelInsert.java
@@ -1,107 +1,107 @@
package ar.proyecto.gui;
import java.awt.FlowLayout;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;
import ar.proyecto.controller.ActionInsert;
public class MiddlePanelInsert extends MiddlePanel {
//Crear la ventana
private JLabel into;
private JLabel nroPatente;
private JFormattedTextField txtNroPatente;
private JLabel typo;
private JTextField txtTypo;
private JLabel modelo;
private JTextField txtModelo;
private JLabel ano;
private JFormattedTextField txtAno;
@SuppressWarnings("rawtypes")
private JComboBox cboxMarca;
private JButton ok;
//constructor
@SuppressWarnings({ "unchecked", "rawtypes" })
public MiddlePanelInsert(MainWindow gui) {
super(gui);
//Inicializar los Labeles
into = new JLabel("INTO Vehiculo :");
nroPatente = new JLabel("nro_patente =");
typo = new JLabel("typo =");
modelo = new JLabel("modelo =");
- ano = new JLabel("anos =");
+ ano = new JLabel("ano =");
//Inicializar los textFields
try {
txtNroPatente = new JFormattedTextField(new MaskFormatter("******"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtNroPatente = new JFormattedTextField();
}
txtNroPatente.setColumns(5);
txtTypo = new JTextField();
txtTypo.setColumns(4);
txtModelo = new JTextField();
txtModelo.setColumns(10);
NumberFormat AnoFormatter = NumberFormat.getIntegerInstance();
AnoFormatter.setGroupingUsed(false);
txtAno = new JFormattedTextField(AnoFormatter);
txtAno.setColumns(4);
//Inicializar el comboBox
String[] marcas = {"FIAT","FORD","RENAULT"};
cboxMarca = new JComboBox(marcas);
cboxMarca.setSelectedItem(2);
//Inicializar el Button
ok = new JButton(new ActionInsert(this,"OK"));
//Agregar todo al panel
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(into);
this.add(nroPatente);
this.add(txtNroPatente);
this.add(typo);
this.add(txtTypo);
this.add(cboxMarca);
this.add(modelo);
this.add(txtModelo);
this.add(ano);
this.add(txtAno);
this.add(ok);
}
public JFormattedTextField getTxtNroPatente() {
return txtNroPatente;
}
public JTextField getTxtTypo() {
return txtTypo;
}
public JTextField getTxtModelo() {
return txtModelo;
}
public JFormattedTextField getTxtAno() {
return txtAno;
}
public JComboBox getCboxMarca() {
return cboxMarca;
}
}
| true | true | public MiddlePanelInsert(MainWindow gui) {
super(gui);
//Inicializar los Labeles
into = new JLabel("INTO Vehiculo :");
nroPatente = new JLabel("nro_patente =");
typo = new JLabel("typo =");
modelo = new JLabel("modelo =");
ano = new JLabel("anos =");
//Inicializar los textFields
try {
txtNroPatente = new JFormattedTextField(new MaskFormatter("******"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtNroPatente = new JFormattedTextField();
}
txtNroPatente.setColumns(5);
txtTypo = new JTextField();
txtTypo.setColumns(4);
txtModelo = new JTextField();
txtModelo.setColumns(10);
NumberFormat AnoFormatter = NumberFormat.getIntegerInstance();
AnoFormatter.setGroupingUsed(false);
txtAno = new JFormattedTextField(AnoFormatter);
txtAno.setColumns(4);
//Inicializar el comboBox
String[] marcas = {"FIAT","FORD","RENAULT"};
cboxMarca = new JComboBox(marcas);
cboxMarca.setSelectedItem(2);
//Inicializar el Button
ok = new JButton(new ActionInsert(this,"OK"));
//Agregar todo al panel
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(into);
this.add(nroPatente);
this.add(txtNroPatente);
this.add(typo);
this.add(txtTypo);
this.add(cboxMarca);
this.add(modelo);
this.add(txtModelo);
this.add(ano);
this.add(txtAno);
this.add(ok);
}
| public MiddlePanelInsert(MainWindow gui) {
super(gui);
//Inicializar los Labeles
into = new JLabel("INTO Vehiculo :");
nroPatente = new JLabel("nro_patente =");
typo = new JLabel("typo =");
modelo = new JLabel("modelo =");
ano = new JLabel("ano =");
//Inicializar los textFields
try {
txtNroPatente = new JFormattedTextField(new MaskFormatter("******"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtNroPatente = new JFormattedTextField();
}
txtNroPatente.setColumns(5);
txtTypo = new JTextField();
txtTypo.setColumns(4);
txtModelo = new JTextField();
txtModelo.setColumns(10);
NumberFormat AnoFormatter = NumberFormat.getIntegerInstance();
AnoFormatter.setGroupingUsed(false);
txtAno = new JFormattedTextField(AnoFormatter);
txtAno.setColumns(4);
//Inicializar el comboBox
String[] marcas = {"FIAT","FORD","RENAULT"};
cboxMarca = new JComboBox(marcas);
cboxMarca.setSelectedItem(2);
//Inicializar el Button
ok = new JButton(new ActionInsert(this,"OK"));
//Agregar todo al panel
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(into);
this.add(nroPatente);
this.add(txtNroPatente);
this.add(typo);
this.add(txtTypo);
this.add(cboxMarca);
this.add(modelo);
this.add(txtModelo);
this.add(ano);
this.add(txtAno);
this.add(ok);
}
|
diff --git a/org/injustice/rawchicken/strategies/WalkBox.java b/org/injustice/rawchicken/strategies/WalkBox.java
index 96a4282..9dfbdb8 100644
--- a/org/injustice/rawchicken/strategies/WalkBox.java
+++ b/org/injustice/rawchicken/strategies/WalkBox.java
@@ -1,63 +1,63 @@
package org.injustice.rawchicken.strategies;
import org.injustice.rawchicken.util.Var;
import org.powerbot.core.script.job.state.Node;
import org.powerbot.game.api.methods.Calculations;
import org.powerbot.game.api.methods.Walking;
import org.powerbot.game.api.methods.interactive.Players;
import org.powerbot.game.api.methods.node.SceneEntities;
import org.powerbot.game.api.methods.tab.Inventory;
import org.powerbot.game.api.methods.widget.Camera;
import org.powerbot.game.api.wrappers.node.SceneObject;
/**
* Created with IntelliJ IDEA.
* User: Injustice
* Date: 29/03/13
* Time: 15:13
* To change this template use File | Settings | File Templates.
*/
public class WalkBox extends Node {
@Override
public boolean activate() {
return Inventory.isFull() && !Var.BANK_TILE.isOnScreen();
}
@Override
public void execute() {
SceneObject depositbox = SceneEntities.getNearest(Var.DEPOSIT_BOX_ID);
if (!Walking.isRunEnabled() && Walking.getEnergy() > 20) { // if run isn't enabled and energy is more than 20
Var.status = "Setting run"; // change status
Walking.setRun(true); // set run to on
}
out: // end if
if (Var.closedGate != null && // if gate is closed and
Players.getLocal().getLocation().getX() <= // player's x location
Var.closedGate.getLocation().getX()) { // is less than or equal to gate's x locatino
if (Var.closedGate.isOnScreen()) { // if closed gate is on screen
Var.status = "Opening gate"; // change status
if (Var.closedGate.interact("Open")) {
do sleep(500, 750); while (Players.getLocal().isMoving());
Walking.findPath(Var.BANK_TILE).traverse();
if (Calculations.distanceTo(depositbox) <= 15 && !depositbox.isOnScreen()) {
Camera.turnTo(depositbox);
}
}
- } else {
+ } else if (Var.CHICKEN_AREA.contains(Players.getLocal().getLocation())) {
Var.status = "Walking to gate";
Walking.walk(Var.GATE_TILE);
do sleep(500, 750); while (Players.getLocal().isMoving());
} // else walk to closed gate
} else { // else
Var.status = "Walking to bank"; // change status
Walking.findPath(Var.BANK_TILE).traverse(); // find a path to bank tile and walk it
if (Calculations.distanceTo(depositbox) <= 15 && !depositbox.isOnScreen()) {
Camera.turnTo(depositbox);
}
} // end if
}
}
/* -- Thanks to GeemanKan for helping me with some of this -- */
| true | true | public void execute() {
SceneObject depositbox = SceneEntities.getNearest(Var.DEPOSIT_BOX_ID);
if (!Walking.isRunEnabled() && Walking.getEnergy() > 20) { // if run isn't enabled and energy is more than 20
Var.status = "Setting run"; // change status
Walking.setRun(true); // set run to on
}
out: // end if
if (Var.closedGate != null && // if gate is closed and
Players.getLocal().getLocation().getX() <= // player's x location
Var.closedGate.getLocation().getX()) { // is less than or equal to gate's x locatino
if (Var.closedGate.isOnScreen()) { // if closed gate is on screen
Var.status = "Opening gate"; // change status
if (Var.closedGate.interact("Open")) {
do sleep(500, 750); while (Players.getLocal().isMoving());
Walking.findPath(Var.BANK_TILE).traverse();
if (Calculations.distanceTo(depositbox) <= 15 && !depositbox.isOnScreen()) {
Camera.turnTo(depositbox);
}
}
} else {
Var.status = "Walking to gate";
Walking.walk(Var.GATE_TILE);
do sleep(500, 750); while (Players.getLocal().isMoving());
} // else walk to closed gate
} else { // else
Var.status = "Walking to bank"; // change status
Walking.findPath(Var.BANK_TILE).traverse(); // find a path to bank tile and walk it
if (Calculations.distanceTo(depositbox) <= 15 && !depositbox.isOnScreen()) {
Camera.turnTo(depositbox);
}
} // end if
}
| public void execute() {
SceneObject depositbox = SceneEntities.getNearest(Var.DEPOSIT_BOX_ID);
if (!Walking.isRunEnabled() && Walking.getEnergy() > 20) { // if run isn't enabled and energy is more than 20
Var.status = "Setting run"; // change status
Walking.setRun(true); // set run to on
}
out: // end if
if (Var.closedGate != null && // if gate is closed and
Players.getLocal().getLocation().getX() <= // player's x location
Var.closedGate.getLocation().getX()) { // is less than or equal to gate's x locatino
if (Var.closedGate.isOnScreen()) { // if closed gate is on screen
Var.status = "Opening gate"; // change status
if (Var.closedGate.interact("Open")) {
do sleep(500, 750); while (Players.getLocal().isMoving());
Walking.findPath(Var.BANK_TILE).traverse();
if (Calculations.distanceTo(depositbox) <= 15 && !depositbox.isOnScreen()) {
Camera.turnTo(depositbox);
}
}
} else if (Var.CHICKEN_AREA.contains(Players.getLocal().getLocation())) {
Var.status = "Walking to gate";
Walking.walk(Var.GATE_TILE);
do sleep(500, 750); while (Players.getLocal().isMoving());
} // else walk to closed gate
} else { // else
Var.status = "Walking to bank"; // change status
Walking.findPath(Var.BANK_TILE).traverse(); // find a path to bank tile and walk it
if (Calculations.distanceTo(depositbox) <= 15 && !depositbox.isOnScreen()) {
Camera.turnTo(depositbox);
}
} // end if
}
|
diff --git a/src/chalmers/dax021308/ecosystem/view/OpenGLSimulationView.java b/src/chalmers/dax021308/ecosystem/view/OpenGLSimulationView.java
index 08df629..91395fd 100644
--- a/src/chalmers/dax021308/ecosystem/view/OpenGLSimulationView.java
+++ b/src/chalmers/dax021308/ecosystem/view/OpenGLSimulationView.java
@@ -1,435 +1,436 @@
package chalmers.dax021308.ecosystem.view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCanvas;
import javax.media.opengl.GLEventListener;
import javax.swing.JFrame;
import com.sun.opengl.util.FPSAnimator;
import chalmers.dax021308.ecosystem.model.agent.IAgent;
import chalmers.dax021308.ecosystem.model.environment.EcoWorld;
import chalmers.dax021308.ecosystem.model.environment.IModel;
import chalmers.dax021308.ecosystem.model.environment.IObstacle;
import chalmers.dax021308.ecosystem.model.population.AbstractPopulation;
import chalmers.dax021308.ecosystem.model.population.IPopulation;
import chalmers.dax021308.ecosystem.model.util.CircleShape;
import chalmers.dax021308.ecosystem.model.util.IShape;
import chalmers.dax021308.ecosystem.model.util.Log;
import chalmers.dax021308.ecosystem.model.util.Position;
import chalmers.dax021308.ecosystem.model.util.Vector;
/**
* OpenGL version of SimulationView.
* <p>
* Uses JOGL library.
* <p>
* Install instructions:
* <p>
* Download: http://download.java.net/media/jogl/builds/archive/jsr-231-1.1.1a/
* Select the version of your choice, i.e. windows-amd64.zip
* Extract the files to a folder.
* Add the extracted files jogl.jar and gluegen-rt.jar to build-path.
* Add path to jogl library to VM-argument in Run Configurations
* <p>
* For Javadoc add the Jogl Javadoc jar as Javadoc refernce to the selected JOGL jar.
* <p>
* @author Erik Ramqvist
*
*/
public class OpenGLSimulationView extends GLCanvas implements IView {
private static final long serialVersionUID = 1585638837620985591L;
private List<IPopulation> newPops = new ArrayList<IPopulation>();
private List<IObstacle> newObs = new ArrayList<IObstacle>();
private Timer fpsTimer;
private int updates;
private int lastFps;
private boolean showFPS;
private int newFps;
private Object fpsSync = new Object();
private Dimension size;
private JFrame frame;
private JOGLListener glListener;
//private GLCanvas canvas;
private IShape shape;
/**
* Create the panel.
*/
public OpenGLSimulationView(IModel model, Dimension size, boolean showFPS) {
this.size = size;
model.addObserver(this);
//setVisible(true);
//setSize(size);
//canvas = new GLCanvas();
//canvas.setSize(size);
//canvas.addGLEventListener(new JOGLListener());
glListener = new JOGLListener();
addGLEventListener(glListener);
FPSAnimator animator = new FPSAnimator(this, 60);
animator.start();
//add();
this.showFPS = showFPS;
if(showFPS) {
fpsTimer = new Timer();
fpsTimer.schedule(new TimerTask() {
@Override
public void run() {
int fps = getUpdate();
/*if(fps + lastFps != 0) {
fps = ( fps + lastFps ) / 2;
} */
setNewFps(fps);
lastFps = fps;
setUpdateValue(0);
}
}, 1000, 1000);
}
}
private int getUpdate() {
synchronized (OpenGLSimulationView.class) {
return updates;
}
}
private void setUpdateValue(int newValue) {
synchronized (OpenGLSimulationView.class) {
updates = newValue;
}
}
private int getNewFps() {
synchronized (fpsSync) {
return newFps;
}
}
private void setNewFps(int newValue) {
synchronized (fpsSync) {
newFps = newValue;
}
}
private void increaseUpdateValue() {
synchronized (OpenGLSimulationView.class) {
updates++;
}
}
@Override
public void propertyChange(PropertyChangeEvent event) {
String eventName = event.getPropertyName();
if(eventName == EcoWorld.EVENT_STOP) {
//Model has stopped. Maybe hide view?
//frame.setVisible(false);
} else if(eventName == EcoWorld.EVENT_TICK) {
//Tick notification recived from model. Do something with the data.
if(event.getNewValue() instanceof List<?>) {
this.newPops = AbstractPopulation.clonePopulationList((List<IPopulation>) event.getNewValue());
}
if(event.getOldValue() instanceof List<?>) {
this.newObs = (List<IObstacle>) event.getOldValue();
}
/*if(canvas != null) {
canvas.repaint();
}*/
//repaint();
//display();
//removeAll();
//repaint();
//revalidate();
} else if(eventName == EcoWorld.EVENT_DIMENSIONCHANGED) {
Object o = event.getNewValue();
if(o instanceof Dimension) {
this.size = (Dimension) o;
}
} else if(eventName == EcoWorld.EVENT_SHAPE_CHANGED) {
Object o = event.getNewValue();
if(o instanceof IShape) {
this.shape = (IShape) o;
}
}
}
/**
* Clones the given list with {@link IPopulation#clonePopulation()} method.
*/
/*private List<IPopulation> clonePopulationList(List<IPopulation> popList) {
List<IPopulation> list = new ArrayList<IPopulation>(popList.size());
for(IPopulation p : popList) {
list.add(p.clonePopulation());
}
return list;
}*/
/**
* Sets the FPS counter visible or not visible
*
* @param visible
*/
public void setFPSCounterVisible(boolean visible) {
if(showFPS && !visible) {
fpsTimer.cancel();
showFPS = visible;
} else if(!showFPS && visible) {
fpsTimer = new Timer();
fpsTimer.schedule(new TimerTask() {
@Override
public void run() {
newFps = getUpdate();
int temp = newFps;
if(newFps + lastFps != 0) {
newFps = ( newFps + lastFps ) / 2;
}
lastFps = temp;
setUpdateValue(0);
}
}, 1000, 1000);
showFPS = true;
}
}
/**
* JOGL Listener, listenes to commands from the GLCanvas.
*
* @author Erik
*
*/
private class JOGLListener implements GLEventListener {
//Number of edges in each created circle.
private final double VERTEXES_PER_CIRCLE = 6;
private final double PI_TIMES_TWO = 2*Math.PI;
private final double increment = PI_TIMES_TWO/VERTEXES_PER_CIRCLE;
private final float COLOR_FACTOR = (1.0f/255);
GL gl = getGL();
/**
* Called each frame to redraw all the 3D elements.
*
*/
@Override
public void display(GLAutoDrawable drawable) {
increaseUpdateValue();
long start = System.currentTimeMillis();
double frameHeight = (double)getHeight();
double frameWidth = (double)getWidth();
double scaleX = frameWidth / size.width;
double scaleY = frameHeight / size.height;
gl.glColor3d(0.9, 0.9, 0.9);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex2d(0, 0);
gl.glVertex2d(0, frameHeight);
gl.glVertex2d(frameWidth, frameHeight);
gl.glVertex2d(frameWidth, 0);
gl.glEnd();
if(shape != null && shape instanceof CircleShape) {
double increment = 2.0*Math.PI/50.0;
double cx = frameWidth / 2.0;
double cy = frameHeight/ 2.0;
double radius = cx;
gl.glColor3d(0.545098, 0.270588, 0.0745098);
for(double angle = 0; angle < 2.0*Math.PI; angle+=increment){
gl.glLineWidth(2.5F);
gl.glBegin(GL.GL_LINES);
gl.glVertex2d(cx + Math.cos(angle)* radius, cy + Math.sin(angle)*radius);
- radius = (frameWidth / 2.0) + Math.abs(Math.sin(angle+increment) * ( (frameHeight - frameWidth ) / 2.0));
+ radius = cx*cy/Math.sqrt((cy*Math.cos(angle+increment))*(cy*Math.cos(angle+increment)) +
+ (cx*Math.sin(angle+increment))*(cx*Math.sin(angle+increment)));
gl.glVertex2d(cx + Math.cos(angle + increment)*radius, cy + Math.sin(angle + increment)*radius);
gl.glEnd();
}
}
int popSize = newPops.size();
for(int i = 0; i < popSize; i ++) {
List<IAgent> agents = newPops.get(i).getAgents();
int size = agents.size();
IAgent a;
for(int j = 0; j < size; j++) {
a = agents.get(j);
Color c = a.getColor();
gl.glColor4f((1.0f/255)*c.getRed(), COLOR_FACTOR*c.getGreen(), COLOR_FACTOR*c.getBlue(), COLOR_FACTOR*c.getAlpha());
Position p = a.getPosition();
/*double cx = p.getX();
double cy = getHeight() - p.getY();
double radius = a.getWidth()/2 + 5;*/
double height = (double)a.getHeight();
double width = (double)a.getWidth();
double originalX = a.getVelocity().x;
double originalY = a.getVelocity().y;
double originalNorm = getNorm(originalX, originalY);
//if(v.getX() != 0 && v.getY() != 0) {
gl.glBegin(GL.GL_TRIANGLES);
double x = originalX * 2.0*height/(3.0*originalNorm);
double y = originalY * 2.0*height/(3.0*originalNorm);
//Vector bodyCenter = new Vector(p.getX(), p.getY());
double xBodyCenter = p.getX();
double yBodyCenter = p.getY();
//Vector nose = new Vector(x+xBodyCenter, y+yBodyCenter);
double noseX = x+xBodyCenter;
double noseY = y+yBodyCenter;
double bottomX = (originalX * -1.0*height/(3.0*originalNorm)) + xBodyCenter;
double bottomY = (originalY * -1.0*height/(3.0*originalNorm)) + yBodyCenter ;
//Vector legLengthVector = new Vector(-originalY/originalX,1);
double legLengthX1 = -originalY/originalX;
double legLengthY1 = 1;
double legLenthVectorNorm2 = width/(2*getNorm(legLengthX1,legLengthY1 ));
//legLengthVector = legLengthVector.multiply(legLenthVectorNorm2);
legLengthX1 = legLengthX1 * legLenthVectorNorm2;
legLengthY1 = legLengthY1 * legLenthVectorNorm2;
//Vector rightLeg = legLengthVector;
double rightLegX = legLengthX1 + bottomX;
double rightLegY = legLengthY1 + bottomY;
//v = new Vector(a.getVelocity());
double legLengthX2 = originalY/originalX * legLenthVectorNorm2;
double legLengthY2 = -1 * legLenthVectorNorm2;
//legLengthVector = new Vector(originalY/originalX,-1);
// legLengthVector = legLengthVector.multiply(legLenthVectorNorm2);
//Vector leftLeg = legLengthVector.add(bottom);
//Vector leftLeg = legLengthVector;
double leftLegX = legLengthX2 + bottomX;
double leftLegY = legLengthY2 + bottomY;
gl.glVertex2d(scaleX*noseX, frameHeight - scaleY*noseY);
gl.glVertex2d(scaleX*rightLegX, frameHeight - scaleY*rightLegY);
gl.glVertex2d(scaleX*leftLegX, frameHeight - scaleY*leftLegY);
gl.glEnd();
/*} else {
for(double angle = 0; angle < PI_TIMES_TWO; angle+=increment){
gl.glBegin(GL.GL_TRIANGLES);
gl.glVertex2d(cx, cy);
gl.glVertex2d(cx + Math.cos(angle)* radius, cy + Math.sin(angle)*radius);
gl.glVertex2d(cx + Math.cos(angle + increment)*radius, cy + Math.sin(angle + increment)*radius);
gl.glEnd();
}
}*/
}
}
//
// /* Information print, comment out to increase performance. */
// Long totalTime = System.currentTimeMillis() - start;
// StringBuffer sb = new StringBuffer("OpenGL Redraw! Fps: ");
// sb.append(getNewFps());
// //sb.append(" Rendertime in ms: ");
// //sb.append(totalTime);
// System.out.println(sb.toString());
/* End Information print. */
}
public double getNorm(double x, double y){
return Math.sqrt((x*x)+(y*y));
}
@Override
public void init(GLAutoDrawable drawable) {
// System.out.println("INIT CALLED");
//Projection mode is for setting camera
gl.glMatrixMode(GL.GL_PROJECTION);
//This will set the camera for orthographic projection and allow 2D view
//Our projection will be on 400 X 400 screen
gl.glLoadIdentity();
// Log.v("getWidth(): " + getWidth());
// Log.v("getHeight(): " + getHeight());
// Log.v("size.width: " + size.width);
// Log.v("size.height: " + size.height);
gl.glOrtho(0, getWidth(), getHeight(), 0, 0, 1);
//Modelview is for drawing
gl.glMatrixMode(GL.GL_MODELVIEW);
//Depth is disabled because we are drawing in 2D
gl.glDisable(GL.GL_DEPTH_TEST);
//Setting the clear color (in this case black)
//and clearing the buffer with this set clear color
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
//This defines how to blend when a transparent graphics
//is placed over another (here we have blended colors of
//two consecutively overlapping graphic objects)
gl.glBlendFunc (GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable (GL.GL_BLEND);
gl.glLoadIdentity();
//After this we start the drawing of object
//We want to draw a triangle which is a type of polygon
}
/**
* Called by the drawable during the first repaint after the component has been resized. The
* client can update the viewport and view volume of the window appropriately, for example by a
* call to GL.glViewport(int, int, int, int); note that for convenience the component has
* already called GL.glViewport(int, int, int, int)(x, y, width, height) when this method is
* called, so the client may not have to do anything in this method.
*
* @param gLDrawable The GLDrawable object.
* @param x The X Coordinate of the viewport rectangle.
* @param y The Y coordinate of the viewport rectanble.
* @param width The new width of the window.
* @param height The new height of the window.
*/
@Override
public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
int arg4) {
System.out.println("RESHAPE CALLED");
}
@Override
public void displayChanged(GLAutoDrawable arg0, boolean arg1,
boolean arg2) {
}
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public void addController(ActionListener controller) {
// TODO Auto-generated method stub
}
@Override
public void onTick() {
// TODO Auto-generated method stub
}
@Override
public void release() {
// TODO Auto-generated method stub
}
}
| true | true | public void display(GLAutoDrawable drawable) {
increaseUpdateValue();
long start = System.currentTimeMillis();
double frameHeight = (double)getHeight();
double frameWidth = (double)getWidth();
double scaleX = frameWidth / size.width;
double scaleY = frameHeight / size.height;
gl.glColor3d(0.9, 0.9, 0.9);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex2d(0, 0);
gl.glVertex2d(0, frameHeight);
gl.glVertex2d(frameWidth, frameHeight);
gl.glVertex2d(frameWidth, 0);
gl.glEnd();
if(shape != null && shape instanceof CircleShape) {
double increment = 2.0*Math.PI/50.0;
double cx = frameWidth / 2.0;
double cy = frameHeight/ 2.0;
double radius = cx;
gl.glColor3d(0.545098, 0.270588, 0.0745098);
for(double angle = 0; angle < 2.0*Math.PI; angle+=increment){
gl.glLineWidth(2.5F);
gl.glBegin(GL.GL_LINES);
gl.glVertex2d(cx + Math.cos(angle)* radius, cy + Math.sin(angle)*radius);
radius = (frameWidth / 2.0) + Math.abs(Math.sin(angle+increment) * ( (frameHeight - frameWidth ) / 2.0));
gl.glVertex2d(cx + Math.cos(angle + increment)*radius, cy + Math.sin(angle + increment)*radius);
gl.glEnd();
}
}
int popSize = newPops.size();
for(int i = 0; i < popSize; i ++) {
List<IAgent> agents = newPops.get(i).getAgents();
int size = agents.size();
IAgent a;
for(int j = 0; j < size; j++) {
a = agents.get(j);
Color c = a.getColor();
gl.glColor4f((1.0f/255)*c.getRed(), COLOR_FACTOR*c.getGreen(), COLOR_FACTOR*c.getBlue(), COLOR_FACTOR*c.getAlpha());
Position p = a.getPosition();
/*double cx = p.getX();
double cy = getHeight() - p.getY();
double radius = a.getWidth()/2 + 5;*/
double height = (double)a.getHeight();
double width = (double)a.getWidth();
double originalX = a.getVelocity().x;
double originalY = a.getVelocity().y;
double originalNorm = getNorm(originalX, originalY);
//if(v.getX() != 0 && v.getY() != 0) {
gl.glBegin(GL.GL_TRIANGLES);
double x = originalX * 2.0*height/(3.0*originalNorm);
double y = originalY * 2.0*height/(3.0*originalNorm);
//Vector bodyCenter = new Vector(p.getX(), p.getY());
double xBodyCenter = p.getX();
double yBodyCenter = p.getY();
//Vector nose = new Vector(x+xBodyCenter, y+yBodyCenter);
double noseX = x+xBodyCenter;
double noseY = y+yBodyCenter;
double bottomX = (originalX * -1.0*height/(3.0*originalNorm)) + xBodyCenter;
double bottomY = (originalY * -1.0*height/(3.0*originalNorm)) + yBodyCenter ;
//Vector legLengthVector = new Vector(-originalY/originalX,1);
double legLengthX1 = -originalY/originalX;
double legLengthY1 = 1;
double legLenthVectorNorm2 = width/(2*getNorm(legLengthX1,legLengthY1 ));
//legLengthVector = legLengthVector.multiply(legLenthVectorNorm2);
legLengthX1 = legLengthX1 * legLenthVectorNorm2;
legLengthY1 = legLengthY1 * legLenthVectorNorm2;
//Vector rightLeg = legLengthVector;
double rightLegX = legLengthX1 + bottomX;
double rightLegY = legLengthY1 + bottomY;
//v = new Vector(a.getVelocity());
double legLengthX2 = originalY/originalX * legLenthVectorNorm2;
double legLengthY2 = -1 * legLenthVectorNorm2;
//legLengthVector = new Vector(originalY/originalX,-1);
// legLengthVector = legLengthVector.multiply(legLenthVectorNorm2);
//Vector leftLeg = legLengthVector.add(bottom);
//Vector leftLeg = legLengthVector;
double leftLegX = legLengthX2 + bottomX;
double leftLegY = legLengthY2 + bottomY;
gl.glVertex2d(scaleX*noseX, frameHeight - scaleY*noseY);
gl.glVertex2d(scaleX*rightLegX, frameHeight - scaleY*rightLegY);
gl.glVertex2d(scaleX*leftLegX, frameHeight - scaleY*leftLegY);
gl.glEnd();
/*} else {
for(double angle = 0; angle < PI_TIMES_TWO; angle+=increment){
gl.glBegin(GL.GL_TRIANGLES);
gl.glVertex2d(cx, cy);
gl.glVertex2d(cx + Math.cos(angle)* radius, cy + Math.sin(angle)*radius);
gl.glVertex2d(cx + Math.cos(angle + increment)*radius, cy + Math.sin(angle + increment)*radius);
gl.glEnd();
}
}*/
}
}
| public void display(GLAutoDrawable drawable) {
increaseUpdateValue();
long start = System.currentTimeMillis();
double frameHeight = (double)getHeight();
double frameWidth = (double)getWidth();
double scaleX = frameWidth / size.width;
double scaleY = frameHeight / size.height;
gl.glColor3d(0.9, 0.9, 0.9);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex2d(0, 0);
gl.glVertex2d(0, frameHeight);
gl.glVertex2d(frameWidth, frameHeight);
gl.glVertex2d(frameWidth, 0);
gl.glEnd();
if(shape != null && shape instanceof CircleShape) {
double increment = 2.0*Math.PI/50.0;
double cx = frameWidth / 2.0;
double cy = frameHeight/ 2.0;
double radius = cx;
gl.glColor3d(0.545098, 0.270588, 0.0745098);
for(double angle = 0; angle < 2.0*Math.PI; angle+=increment){
gl.glLineWidth(2.5F);
gl.glBegin(GL.GL_LINES);
gl.glVertex2d(cx + Math.cos(angle)* radius, cy + Math.sin(angle)*radius);
radius = cx*cy/Math.sqrt((cy*Math.cos(angle+increment))*(cy*Math.cos(angle+increment)) +
(cx*Math.sin(angle+increment))*(cx*Math.sin(angle+increment)));
gl.glVertex2d(cx + Math.cos(angle + increment)*radius, cy + Math.sin(angle + increment)*radius);
gl.glEnd();
}
}
int popSize = newPops.size();
for(int i = 0; i < popSize; i ++) {
List<IAgent> agents = newPops.get(i).getAgents();
int size = agents.size();
IAgent a;
for(int j = 0; j < size; j++) {
a = agents.get(j);
Color c = a.getColor();
gl.glColor4f((1.0f/255)*c.getRed(), COLOR_FACTOR*c.getGreen(), COLOR_FACTOR*c.getBlue(), COLOR_FACTOR*c.getAlpha());
Position p = a.getPosition();
/*double cx = p.getX();
double cy = getHeight() - p.getY();
double radius = a.getWidth()/2 + 5;*/
double height = (double)a.getHeight();
double width = (double)a.getWidth();
double originalX = a.getVelocity().x;
double originalY = a.getVelocity().y;
double originalNorm = getNorm(originalX, originalY);
//if(v.getX() != 0 && v.getY() != 0) {
gl.glBegin(GL.GL_TRIANGLES);
double x = originalX * 2.0*height/(3.0*originalNorm);
double y = originalY * 2.0*height/(3.0*originalNorm);
//Vector bodyCenter = new Vector(p.getX(), p.getY());
double xBodyCenter = p.getX();
double yBodyCenter = p.getY();
//Vector nose = new Vector(x+xBodyCenter, y+yBodyCenter);
double noseX = x+xBodyCenter;
double noseY = y+yBodyCenter;
double bottomX = (originalX * -1.0*height/(3.0*originalNorm)) + xBodyCenter;
double bottomY = (originalY * -1.0*height/(3.0*originalNorm)) + yBodyCenter ;
//Vector legLengthVector = new Vector(-originalY/originalX,1);
double legLengthX1 = -originalY/originalX;
double legLengthY1 = 1;
double legLenthVectorNorm2 = width/(2*getNorm(legLengthX1,legLengthY1 ));
//legLengthVector = legLengthVector.multiply(legLenthVectorNorm2);
legLengthX1 = legLengthX1 * legLenthVectorNorm2;
legLengthY1 = legLengthY1 * legLenthVectorNorm2;
//Vector rightLeg = legLengthVector;
double rightLegX = legLengthX1 + bottomX;
double rightLegY = legLengthY1 + bottomY;
//v = new Vector(a.getVelocity());
double legLengthX2 = originalY/originalX * legLenthVectorNorm2;
double legLengthY2 = -1 * legLenthVectorNorm2;
//legLengthVector = new Vector(originalY/originalX,-1);
// legLengthVector = legLengthVector.multiply(legLenthVectorNorm2);
//Vector leftLeg = legLengthVector.add(bottom);
//Vector leftLeg = legLengthVector;
double leftLegX = legLengthX2 + bottomX;
double leftLegY = legLengthY2 + bottomY;
gl.glVertex2d(scaleX*noseX, frameHeight - scaleY*noseY);
gl.glVertex2d(scaleX*rightLegX, frameHeight - scaleY*rightLegY);
gl.glVertex2d(scaleX*leftLegX, frameHeight - scaleY*leftLegY);
gl.glEnd();
/*} else {
for(double angle = 0; angle < PI_TIMES_TWO; angle+=increment){
gl.glBegin(GL.GL_TRIANGLES);
gl.glVertex2d(cx, cy);
gl.glVertex2d(cx + Math.cos(angle)* radius, cy + Math.sin(angle)*radius);
gl.glVertex2d(cx + Math.cos(angle + increment)*radius, cy + Math.sin(angle + increment)*radius);
gl.glEnd();
}
}*/
}
}
|
diff --git a/src/shoddybattleclient/GameVisualisation.java b/src/shoddybattleclient/GameVisualisation.java
index c8990f5..216c28b 100644
--- a/src/shoddybattleclient/GameVisualisation.java
+++ b/src/shoddybattleclient/GameVisualisation.java
@@ -1,870 +1,872 @@
/*
* GameVisualisation.java
*
* Created on Apr 10, 2009, 2:13:23 PM
*
* This file is a part of Shoddy Battle.
* Copyright (C) 2009 Catherine Fitzpatrick and Benjamin Gwin
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, visit the Free Software Foundation, Inc.
* online at http://gnu.org.
*/
package shoddybattleclient;
import java.awt.AlphaComposite;
import shoddybattleclient.utils.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JToolTip;
import javax.swing.ToolTipManager;
import shoddybattleclient.shoddybattle.Pokemon;
import shoddybattleclient.shoddybattle.Pokemon.Gender;
import shoddybattleclient.shoddybattle.PokemonSpecies;
/**
*
* @author ben
*/
interface PokemonDelegate {
//Get a pokemon in a particular party and slot
public GameVisualisation.VisualPokemon getPokemonForSlot(int party, int slot);
}
public class GameVisualisation extends JLayeredPane implements PokemonDelegate {
private static class Pokeball extends JPanel {
private VisualPokemon m_pokemon;
public Pokeball(VisualPokemon p) {
setOpaque(false);
m_pokemon = p;
setToolTipText("asdf");
}
public Dimension getPreferredSize() {
return new Dimension(18, 18);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g.create();
//g2.scale(0.9, 0.9);
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int w = getPreferredSize().width - 2;
int h = getPreferredSize().height - 2;
if (m_pokemon.getState() == State.FAINTED) {
g2.setColor(Color.DARK_GRAY);
g2.fillArc(0, 0, w, h, 0, 360);
g2.dispose();
return;
}
g2.setColor(Color.BLACK);
g2.fillArc(0, 0, w, h, 0, 360);
g2.setColor(Color.WHITE);
g2.fillArc(1, 1, w - 2, h - 2, 0, 360);
g2.setColor(Color.RED);
g2.fillArc(1, 1, w - 2, h - 2, 0, 180);
g2.fillArc(1, h / 2 - 2, w - 2, h / 5, 0, -180);
g2.setColor(Color.BLACK);
g2.drawArc(1, h / 2 - 2, w - 2, h / 5, 0, -180);
g2.fillArc(w / 2 - 3, h/2 - 2, 6, 6, 0, 360);
g2.setColor(Color.WHITE);
g2.fillArc(w / 2 - 2, h/2 - 1, 4, 4, 0, 360);
if (m_pokemon.getState() != State.NORMAL) {
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
g2.setColor(Color.GRAY);
g2.fillArc(0, 0, w, h, 0, 360);
g2.setComposite(AlphaComposite.SrcOver);
g2.drawString(String.valueOf(m_pokemon.getState().ordinal()), w / 2, h / 2);
}
g2.dispose();
}
@Override
public JToolTip createToolTip() {
return new JCustomTooltip(this,
new VisualToolTip(m_pokemon, true));
}
}
private static class Sprite extends JPanel {
private boolean m_front;
private int m_frame = 0;
private Image m_image = null;
private Dimension m_size = new Dimension(84, 84);
private int m_party;
private int m_slot;
private PokemonDelegate m_delegate;
public Sprite(int party, int slot, boolean front,
PokemonDelegate delegate) {
setOpaque(false);
setToolTipText("");
m_front = front;
m_party = party;
m_slot = slot;
m_delegate = delegate;
}
public void setSprite(VisualPokemon p) {
if (p == null) {
m_image = null;
repaint();
return;
}
boolean male = Gender.GENDER_MALE.ordinal() == p.m_gender;
m_image = p.getImage(m_front, male);
if (m_image == null) {
repaint();
return;
}
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(m_image, 0);
try {
tracker.waitForAll();
} catch (Exception e) {
}
if (m_image != null) {
m_size = new Dimension(m_image.getWidth(this),
m_image.getHeight(this));
setSize(m_size);
}
repaint();
}
public Dimension getPreferredSize() {
return m_size;
}
public void paintComponent(Graphics g) {
g.drawImage(m_image, 0, 0, this);
}
@Override
public JToolTip createToolTip() {
VisualPokemon p = m_delegate.getPokemonForSlot(m_party, m_slot);
if (p == null) {
setToolTipText(null);
return new JToolTip();
}
return new JCustomTooltip(this, new VisualToolTip(p, true));
}
}
public static class StatusObject {
private String m_id;
private String m_name;
private int m_turns = -1;
private int m_count = 0;
public StatusObject(String id, String name) {
m_id = id;
m_name = name;
}
public StatusObject(String id, String name, int turns) {
m_id = id;
m_name = name;
m_turns = turns;
}
public String getId() {
return m_id;
}
public String getName() {
return m_name;
}
public String toString() {
return (m_turns > 0) ? m_name + " {" + m_turns + "}" : m_name;
}
public void addCount() {
++m_count;
}
public int decreaseCount() {
return --m_count;
}
}
public static class VisualPokemon {
private int m_id;
private String m_species;
private String m_name;
private int m_level;
private int m_gender;
private boolean m_shiny;
private List<StatusObject> m_statuses = new ArrayList<StatusObject>();
private int m_healthN = 48;
private int m_healthD = 48;
private int[] m_statLevels = new int[8];
private boolean m_visible = true;
private int m_slot = -1;
private boolean m_fainted = false;
private Pokemon m_pokemon = null;
private int m_frame = 1;
private State m_state = State.NORMAL;
private static Map<String, State> m_stateMap = new HashMap<String, State>();
static {
m_stateMap.put(Text.getText(6, 0), State.BURNED);
m_stateMap.put(Text.getText(8, 0), State.FROZEN);
m_stateMap.put(Text.getText(9, 0), State.PARALYSED);
m_stateMap.put(Text.getText(10, 0), State.SLEEPING);
m_stateMap.put(Text.getText(11, 0), State.POISONED);
}
public VisualPokemon(int id, int gender, int level, boolean shiny) {
m_id = id;
m_gender = gender;
m_level = level;
m_shiny = shiny;
}
public VisualPokemon() {
m_species = "???";
m_gender = 0;
m_level = 100;
m_shiny = false;
}
public String getSpecies() {
if (m_pokemon != null) {
return m_pokemon.species;
}
return m_species;
}
public void setName(String name) {
m_name = name;
}
public String getName() {
if (m_pokemon != null) {
return ("".equals(m_pokemon.nickname))
? m_pokemon.species : m_pokemon.nickname;
}
return m_name;
}
public Pokemon getPokemon() {
return m_pokemon;
}
public void setSpeciesId(int id) {
m_id = id;
}
public void setSpecies(String name) {
m_species = name;
}
public void setGender(int gender) {
m_gender = gender;
}
public int getGender() {
return m_gender;
}
public void setShiny(boolean shiny) {
m_shiny = shiny;
}
public boolean isShiny() {
return m_shiny;
}
public void setLevel(int level) {
m_level = level;
}
public int getLevel() {
return m_level;
}
public StatusObject updateStatus(String id, String status,
boolean applied) {
if (applied) {
return addStatus(id, status);
} else {
removeStatus(status);
return null;
}
}
public StatusObject addStatus(String id, String status) {
StatusObject obj = new StatusObject(id, status);
m_statuses.add(obj);
if (m_stateMap.containsKey(status)) {
m_state = m_stateMap.get(status);
}
return obj;
}
public void removeStatus(String status) {
Iterator<StatusObject> i = m_statuses.iterator();
while (i.hasNext()) {
StatusObject obj = i.next();
if (obj.getName().equals(status))
i.remove();
}
if (m_stateMap.containsKey(status)) {
m_state = State.NORMAL;
}
}
public List<StatusObject> getStatuses() {
return m_statuses;
}
public void setHealth(int num, int denom) {
m_healthN = num;
m_healthD = denom;
}
public int getNumerator() {
return m_healthN;
}
public int getDenominator() {
return m_healthD;
}
public void updateStatLevel(int i, int delta, boolean applied) {
int sign = (applied) ? 1 : -1;
m_statLevels[i] += sign * delta;
}
public int getStatLevel(int idx) {
return m_statLevels[idx];
}
public void setSlot(int slot) {
m_slot = slot;
}
public int getSlot() {
return m_slot;
}
public void faint() {
m_fainted = true;
}
public boolean isFainted() {
return m_fainted;
}
public State getState() {
if (m_fainted) {
return State.FAINTED;
} else {
return m_state;
}
}
public void setPokemon(Pokemon p) {
m_pokemon = p;
}
public void toggleFrame() {
m_frame = (m_frame == 1) ? 2 : 1;
}
public int getFrame() {
return m_frame;
}
public Image getImage(boolean front, boolean male) {
if (isFainted()) return null;
for (StatusObject status : m_statuses) {
if (status.getId().equals("SubstituteEffect")) {
return GameVisualisation.getSubstitute(front);
}
}
return GameVisualisation.getSprite(m_id, front, male, m_shiny);
}
}
public static enum State {
NORMAL,
PARALYSED,
BURNED,
FROZEN,
SLEEPING,
POISONED,
FAINTED;
}
private static final int BACKGROUND_COUNT = 23;
private static final int RADIUS_SINGLE = 0;
private static final int RADIUS_USER_PARTY = 1;
private static final int RADIUS_ENEMY_PARTY = 2;
private static final int RADIUS_GLOBAL = 3;
private Image m_background;
private VisualPokemon[][] m_active;
private VisualPokemon[][] m_parties;
private Pokeball[][] m_pokeballs;
private Sprite[][] m_sprites;
private int m_view;
private int m_selected = -1;
private int m_target = Integer.MAX_VALUE;
private Graphics2D m_mouseInput;
private static final IndexColorModel m_colours;
private final List<PokemonSpecies> m_speciesList;
private interface StringList extends List<String> {}
private List<String>[] m_partyStatuses = new StringList[2];
private Set<String> m_globalStatuses = new HashSet<String>();
private int m_n;
//max team length
private int m_length;
private int m_tooltipParty = Integer.MAX_VALUE;
private int m_tooltipPoke = Integer.MAX_VALUE;
static {
ToolTipManager.sharedInstance().setInitialDelay(200);
ToolTipManager.sharedInstance().setReshowDelay(200);
}
public static Image getImageFromResource(String file) {
return Toolkit.getDefaultToolkit()
.createImage(GameVisualisation.class.getResource("resources/" + file));
}
static {
byte[] r = new byte[4];
byte[] g = new byte[4];
byte[] b = new byte[4];
r[0] = g[0] = b[0] = 0;
r[1] = g[1] = b[1] = (byte)255;
g[2] = g[3] = 1;
b[2] = b[3] = 1;
r[2] = 0;
r[3] = 1;
m_colours = new IndexColorModel(4, r.length, r, g, b);
/*ToolTipManager manager = ToolTipManager.sharedInstance();
manager.setInitialDelay(0);
manager.setReshowDelay(0);*/
}
public GameVisualisation(int view, int n, int length, List<PokemonSpecies> speciesList) {
this.setLayout(null);
m_view = view;
m_active = new VisualPokemon[2][n];
m_parties = new VisualPokemon[2][length];
m_pokeballs = new Pokeball[2][length];
m_speciesList = speciesList;
int background = new Random().nextInt(BACKGROUND_COUNT) + 1;
m_background = getImageFromResource("backgrounds/background" + background + ".png");
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(m_background, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
- int rows = length / 3;
+ int rows = (int)Math.ceil(length / 3d);
for (int i = 0; i < m_parties.length; i++) {
for (int j = 0; j < m_parties[i].length; j++) {
VisualPokemon p = new VisualPokemon();
m_parties[i][j] = p;
Pokeball ball = new Pokeball(p);
m_pokeballs[i][j] = ball;
Dimension d = ball.getPreferredSize();
ball.setSize(d);
int x, y;
int w = m_background.getWidth(this);
int h = m_background.getHeight(this);
int row = j / 3;
int buff = 1;
x = (j - 3*row) * (d.width + buff) + 2;
y = (d.width + buff) * row + 2;
if (view == i) {
- x += w - 3 * (d.width + buff) - 2;
- y += h - rows * (d.width + buff);
+ int pokeballWidth = Math.min(m_parties[i].length, 3)
+ * (d.width + buff);
+ x += w - pokeballWidth - 2;
+ y += h - rows * (d.height + buff);
}
ball.setLocation(x, y);
this.add(ball);
}
}
m_n = n;
m_length = length;
m_sprites = new Sprite[2][n];
for (int i = 0; i < m_sprites.length; i++) {
for (int j = 0; j < m_sprites[i].length; j++) {
boolean us = (i == m_view);
Sprite s = new Sprite(i, j, !us, this);
s.setSize(s.getPreferredSize());
s.setLocation(getSpriteLocation(us, j, m_n, 0, 0));
m_sprites[i][j] = s;
this.add(s, new Integer(m_view * m_sprites[i].length + j));
}
}
setBorder(BorderFactory.createLineBorder(Color.GRAY));
Dimension d = getPreferredSize();
final BufferedImage image = new BufferedImage((int)d.getWidth(),
(int)d.getHeight(),
BufferedImage.TYPE_BYTE_BINARY,
m_colours);
m_mouseInput = image.createGraphics();
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if ((x > image.getWidth()) || (y > image.getHeight())) return;
Color c = new Color(image.getRGB(x, y));
if (c.equals(Color.WHITE)) {
setToolTipText(null);
return;
} else if (c.getGreen() == 1) {
//party
displayInformation(c.getRed(), -1);
} else if (c.equals(Color.BLACK)) {
//field
displayInformation(-1, -1);
}
}
});
}
public void setSpriteVisible(int party, int slot, boolean visible) {
m_active[party][slot].m_visible = visible;
}
public void updateHealth(int party, int slot, int total, int denominator) {
getPokemonForSlot(party, slot).setHealth(total, denominator);
}
public VisualPokemon getPokemon(int party, int index) {
return m_parties[party][index];
}
public void updateStatus(int party, int position, int radius,
String statusId, String msg, boolean applied) {
VisualPokemon p = getPokemon(party, position);
if (radius == RADIUS_USER_PARTY) {
if (applied) {
m_partyStatuses[party].add(msg);
} else {
m_partyStatuses[party].remove(msg);
}
return;
}
if (radius == RADIUS_ENEMY_PARTY) {
if (applied) {
m_partyStatuses[1 - party].add(msg);
} else {
m_partyStatuses[1 - party].remove(msg);
}
return;
}
if (radius == RADIUS_GLOBAL) {
if (applied) {
m_globalStatuses.add(msg);
} else {
m_globalStatuses.remove(msg);
}
return;
}
String[] parts = msg.split(";");
if (parts.length == 1) {
p.updateStatus(statusId, msg, applied);
} else {
if ("StatChangeEffect".equals(parts[0])) {
int stat = Integer.parseInt(parts[1]);
int delta = Integer.parseInt(parts[2]);
p.updateStatLevel(stat, delta, applied);
}
//todo: other cases with additional information
}
m_pokeballs[party][position].repaint();
}
void faint(int party, int slot) {
getPokemonForSlot(party, slot).faint();
repaint();
}
private void displayInformation(int party, int idx) {
m_tooltipParty = party;
m_tooltipPoke = idx;
List<String> effects;
if (party == -1) {
effects = new ArrayList<String>();
for (String eff : m_globalStatuses) {
effects.add(eff);
}
} else {
effects = m_partyStatuses[party];
}
if ((effects == null) || (effects.size() == 0)) {
setToolTipText(null);
return;
}
String text = FindPanel.join(effects, "<br>");
text = "<html>" + text + "</html>";
setToolTipText(text);
}
public void updateSprite(int party, int slot) {
Sprite s = m_sprites[party][slot];
s.setSprite(getPokemonForSlot(party, slot));
Dimension d = s.getPreferredSize();
s.setLocation(getSpriteLocation(party == m_view, slot, m_n,
d.width, d.height));
}
public VisualPokemon getPokemonForSlot(int party, int slot) {
for (int i = 0; i < m_parties[party].length; i++) {
if (m_parties[party][i].getSlot() == slot)
return m_parties[party][i];
}
return null;
}
public void setSpecies(int party, int slot, String species) {
VisualPokemon p = getPokemonForSlot(party, slot);
if (p != null) {
p.setSpecies(species);
}
}
public void sendOut(final int party, final int slot, int index,
int speciesId, String species, String name, int gender, int level) {
VisualPokemon p = getPokemonForSlot(party, slot);
if (p != null) {
p.setSlot(-1);
}
VisualPokemon newPoke = m_parties[party][index];
newPoke.setSlot(slot);
newPoke.setSpeciesId(speciesId);
newPoke.setSpecies(species);
newPoke.setName(name);
newPoke.setLevel(level);
newPoke.setGender(gender);
}
public void setPokemon(int party, int index, Pokemon p) {
m_parties[party][index].setPokemon(p);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(m_background.getWidth(this), m_background.getHeight(this));
}
public void setSelected(int i) {
m_selected = i;
repaint();
}
public void setTarget(int i) {
m_target = i;
repaint();
}
// returns the number of active pokemon in a party
public int getActiveCount(int party) {
VisualPokemon[] pokes = m_parties[party];
int active = 0;
for (VisualPokemon p : pokes) {
if (!p.m_fainted) active++;
}
return active;
}
@Override
public JToolTip createToolTip() {
if (m_tooltipParty == -1) {
return new JToolTip();
} else if (m_tooltipPoke == -1) {
return new JToolTip();
}
VisualPokemon p = m_parties[m_tooltipParty][m_tooltipPoke];
if (p == null) return new JToolTip();
// TODO: adjust final parameter for spectator support
VisualToolTip vt = new VisualToolTip(p, m_tooltipParty == m_view);
return new JCustomTooltip(this, vt);
}
private Point getSpriteLocation(boolean us, int slot, int n, int w, int h) {
int x = 0, y;
int hw = w /2 ;
Dimension d = this.getPreferredSize();
if (us) {
y = d.height - h;
if (n == 1) {
x = 50 - hw;
} else if (n == 2) {
x = (slot == 0) ? 30 - hw: 90 - hw;
} else if (n == 3) {
x = (slot == 0) ? 20 - hw : (slot == 1) ? 55 - hw : 90 - hw;
} else {
x = slot * 23;
}
} else {
y = 90 - h;
if (n == 1) {
x = 190 - hw;
} else if (n == 2) {
x = (slot == 0) ? 170 - hw : 220 - hw;
} else if (n == 3) {
x = (slot == 0) ? 160 - hw : (slot == 1) ? 190 - hw : 220 - hw;
} else {
x = 220 - n * 23 + 23 * slot;
y -= 5;
}
}
return new Point(x, y);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g.create();
m_mouseInput.setColor(Color.BLACK);
m_mouseInput.fillRect(0, 0, getWidth(), getHeight());
m_mouseInput.setColor(Color.WHITE);
m_mouseInput.fillRect(0, 0, 60, 36);
m_mouseInput.fillRect(getWidth() - 60, getHeight() - 36, 60, 36);
m_mouseInput.setColor(new Color(m_view, 1, 0));
m_mouseInput.fillRect(0, getHeight() - 60, 220, 60);
m_mouseInput.setColor(new Color(1 - m_view, 1, 0));
m_mouseInput.fillRect(70, 10, 220, 60);
g2.drawImage(m_background, 0, 0, this);
g2.dispose();
}
private static String createPath(String filename, boolean front,
boolean shiny, String repo, int frame) {
StringBuilder builder = new StringBuilder();
builder.append(Preference.getSpriteLocation());
builder.append(repo);
builder.append("/");
builder.append(front ? "front" : "back");
builder.append("/");
builder.append(shiny ? "shiny" : "normal");
builder.append(frame == 1 ? "" : String.valueOf(frame));
builder.append("/");
builder.append(filename);
return builder.toString();
}
private static String createPath(int number, boolean front, boolean male,
boolean shiny, String repo, int frame) {
StringBuilder builder = new StringBuilder();
builder.append(number);
builder.append(male ? "" : "f");
builder.append(".png");
return createPath(builder.toString(), front, shiny, repo, frame);
}
private static String getSpritePath(int number, boolean front, boolean male,
boolean shiny, String repo, int frame) {
//look for the correct sprite, then the opposite gender, then the first frames
File f = new File(createPath(number, front, male, shiny, repo, frame));
if (f.exists()) return f.toString();
f = new File(createPath(number, front, !male, shiny, repo, frame));
if (f.exists()) return f.toString();
f = new File(createPath(number, front, male, shiny, repo, 1));
if (f.exists()) return f.toString();
f = new File(createPath(number, front, !male, shiny, repo, 1));
if (f.exists()) return f.toString();
return null;
}
private static Image getSprite(String path, boolean front) {
if (path == null) {
String image = (front) ? "missingno_front.png" :
"missingno_back.png";
return GameVisualisation.getImageFromResource(image);
}
return Toolkit.getDefaultToolkit().createImage(path);
}
public static Image getSprite(int number, boolean front, boolean male,
boolean shiny, int frame) {
String qualified = null;
for (String repo : Preference.getSpriteDirectories()) {
qualified = getSpritePath(number, front, male, shiny, repo, frame);
if (qualified != null) break;
}
return getSprite(qualified, front);
}
public static Image getSprite(int number, boolean front, boolean male,
boolean shiny) {
return getSprite(number, front, male, shiny, 1);
}
public Image getSprite(String name, boolean front, boolean male,
boolean shiny, int frame) {
int number = PokemonSpecies.getIdFromName(m_speciesList, name);
return getSprite(number, front, male, shiny, frame);
}
public Image getSprite(String name, boolean front, boolean male, boolean shiny) {
return getSprite(name, front, male, shiny, 1);
}
public static Image getSubstitute(boolean front) {
String qualified = null;
for (String repo : Preference.getSpriteDirectories()) {
String path = createPath("substitute.png", front, false, repo, 1);
if (new File(path).exists()) {
qualified = path;
break;
}
}
return getSprite(qualified, front);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Visualisation test");
SpeciesListParser slp = new SpeciesListParser();
List<PokemonSpecies> species = slp.parseDocument(
GameVisualisation.class.getResource("resources/species.xml").toString());
GameVisualisation panel = new GameVisualisation(1, 2, 6, species);
frame.setSize(panel.getPreferredSize().width, panel.getPreferredSize().height + 20);
Random r = new java.util.Random();
VisualPokemon p1 = new VisualPokemon(1, 1, 100, false);
VisualPokemon p2 = new VisualPokemon(2, 1, 100, false);
VisualPokemon p3 = new VisualPokemon(3, 1, 100, false);
VisualPokemon p4 = new VisualPokemon(4, 1, 100, false);
/*VisualPokemon p5 = new VisualPokemon(r.nextInt(505), 1, 100, false);
VisualPokemon p6 = new VisualPokemon(r.nextInt(505), 1, 100, false);
VisualPokemon p7 = new VisualPokemon(r.nextInt(505), 1, 100, false);
VisualPokemon p8 = new VisualPokemon(r.nextInt(505), 1, 100, false);
VisualPokemon p9 = new VisualPokemon(r.nextInt(505), 1, 100, false);
VisualPokemon p10 = new VisualPokemon(r.nextInt(505), 1, 100, false);
VisualPokemon p11 = new VisualPokemon(r.nextInt(505), 1, 100, false);
VisualPokemon p12 = new VisualPokemon(r.nextInt(505), 1, 100, false);*/
panel.sendOut(0, 0, 0, p1.m_id, p1.getSpecies(), p1.getSpecies(),
p1.getGender(), p1.getLevel());
panel.sendOut(0, 1, 1, p2.m_id, p1.getSpecies(), p2.getSpecies(),
p2.getGender(), p2.getLevel());
panel.sendOut(1, 0, 0, p3.m_id, p1.getSpecies(), p3.getSpecies(),
p3.getGender(), p3.getLevel());
panel.sendOut(1, 1, 1, p4.m_id, p1.getSpecies(), p4.getSpecies(),
p4.getGender(), p4.getLevel());
panel.updateStatus(0, 0, 0, "SubstituteEffect", "Substitute", true);
panel.updateStatus(1, 1, 0, "SubstituteEffect", "Substitute", true);
panel.updateSprite(0, 0);
panel.updateSprite(0, 1);
panel.updateSprite(1, 0);
panel.updateSprite(1, 1);
frame.setSize(panel.getPreferredSize().width, panel.getPreferredSize().height + 20);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setVisible(true);
}
}
| false | true | public GameVisualisation(int view, int n, int length, List<PokemonSpecies> speciesList) {
this.setLayout(null);
m_view = view;
m_active = new VisualPokemon[2][n];
m_parties = new VisualPokemon[2][length];
m_pokeballs = new Pokeball[2][length];
m_speciesList = speciesList;
int background = new Random().nextInt(BACKGROUND_COUNT) + 1;
m_background = getImageFromResource("backgrounds/background" + background + ".png");
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(m_background, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
int rows = length / 3;
for (int i = 0; i < m_parties.length; i++) {
for (int j = 0; j < m_parties[i].length; j++) {
VisualPokemon p = new VisualPokemon();
m_parties[i][j] = p;
Pokeball ball = new Pokeball(p);
m_pokeballs[i][j] = ball;
Dimension d = ball.getPreferredSize();
ball.setSize(d);
int x, y;
int w = m_background.getWidth(this);
int h = m_background.getHeight(this);
int row = j / 3;
int buff = 1;
x = (j - 3*row) * (d.width + buff) + 2;
y = (d.width + buff) * row + 2;
if (view == i) {
x += w - 3 * (d.width + buff) - 2;
y += h - rows * (d.width + buff);
}
ball.setLocation(x, y);
this.add(ball);
}
}
m_n = n;
m_length = length;
m_sprites = new Sprite[2][n];
for (int i = 0; i < m_sprites.length; i++) {
for (int j = 0; j < m_sprites[i].length; j++) {
boolean us = (i == m_view);
Sprite s = new Sprite(i, j, !us, this);
s.setSize(s.getPreferredSize());
s.setLocation(getSpriteLocation(us, j, m_n, 0, 0));
m_sprites[i][j] = s;
this.add(s, new Integer(m_view * m_sprites[i].length + j));
}
}
setBorder(BorderFactory.createLineBorder(Color.GRAY));
Dimension d = getPreferredSize();
final BufferedImage image = new BufferedImage((int)d.getWidth(),
(int)d.getHeight(),
BufferedImage.TYPE_BYTE_BINARY,
m_colours);
m_mouseInput = image.createGraphics();
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if ((x > image.getWidth()) || (y > image.getHeight())) return;
Color c = new Color(image.getRGB(x, y));
if (c.equals(Color.WHITE)) {
setToolTipText(null);
return;
} else if (c.getGreen() == 1) {
//party
displayInformation(c.getRed(), -1);
} else if (c.equals(Color.BLACK)) {
//field
displayInformation(-1, -1);
}
}
});
}
| public GameVisualisation(int view, int n, int length, List<PokemonSpecies> speciesList) {
this.setLayout(null);
m_view = view;
m_active = new VisualPokemon[2][n];
m_parties = new VisualPokemon[2][length];
m_pokeballs = new Pokeball[2][length];
m_speciesList = speciesList;
int background = new Random().nextInt(BACKGROUND_COUNT) + 1;
m_background = getImageFromResource("backgrounds/background" + background + ".png");
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(m_background, 0);
try {
tracker.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
int rows = (int)Math.ceil(length / 3d);
for (int i = 0; i < m_parties.length; i++) {
for (int j = 0; j < m_parties[i].length; j++) {
VisualPokemon p = new VisualPokemon();
m_parties[i][j] = p;
Pokeball ball = new Pokeball(p);
m_pokeballs[i][j] = ball;
Dimension d = ball.getPreferredSize();
ball.setSize(d);
int x, y;
int w = m_background.getWidth(this);
int h = m_background.getHeight(this);
int row = j / 3;
int buff = 1;
x = (j - 3*row) * (d.width + buff) + 2;
y = (d.width + buff) * row + 2;
if (view == i) {
int pokeballWidth = Math.min(m_parties[i].length, 3)
* (d.width + buff);
x += w - pokeballWidth - 2;
y += h - rows * (d.height + buff);
}
ball.setLocation(x, y);
this.add(ball);
}
}
m_n = n;
m_length = length;
m_sprites = new Sprite[2][n];
for (int i = 0; i < m_sprites.length; i++) {
for (int j = 0; j < m_sprites[i].length; j++) {
boolean us = (i == m_view);
Sprite s = new Sprite(i, j, !us, this);
s.setSize(s.getPreferredSize());
s.setLocation(getSpriteLocation(us, j, m_n, 0, 0));
m_sprites[i][j] = s;
this.add(s, new Integer(m_view * m_sprites[i].length + j));
}
}
setBorder(BorderFactory.createLineBorder(Color.GRAY));
Dimension d = getPreferredSize();
final BufferedImage image = new BufferedImage((int)d.getWidth(),
(int)d.getHeight(),
BufferedImage.TYPE_BYTE_BINARY,
m_colours);
m_mouseInput = image.createGraphics();
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if ((x > image.getWidth()) || (y > image.getHeight())) return;
Color c = new Color(image.getRGB(x, y));
if (c.equals(Color.WHITE)) {
setToolTipText(null);
return;
} else if (c.getGreen() == 1) {
//party
displayInformation(c.getRed(), -1);
} else if (c.equals(Color.BLACK)) {
//field
displayInformation(-1, -1);
}
}
});
}
|
diff --git a/src/me/sinnoh/MasterPromote/MPConfig.java b/src/me/sinnoh/MasterPromote/MPConfig.java
index f504f8e..0eb8805 100644
--- a/src/me/sinnoh/MasterPromote/MPConfig.java
+++ b/src/me/sinnoh/MasterPromote/MPConfig.java
@@ -1,157 +1,157 @@
package me.sinnoh.MasterPromote;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MPConfig
{
public static MasterPromote plugin = MasterPromote.instance;
public static void createdefaults()
{
try
{
if(!plugin.configFile.exists())
{
plugin.configFile.getParentFile().mkdirs();
copy(plugin.getResource("config.yml"), plugin.configFile);
}
if(!plugin.messagesFile.exists())
{
plugin.messagesFile.getParentFile().mkdirs();
copy(plugin.getResource("messages.yml"), plugin.messagesFile);
}
if(!plugin.tokenFile.exists())
{
plugin.tokenFile.getParentFile().mkdirs();
copy(plugin.getResource("token.yml"), plugin.tokenFile);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void copy(InputStream in, File file)
{
try
{
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0)
{
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void loadYamls()
{
try {
plugin.config.load(plugin.configFile);
plugin.messages.load(plugin.messagesFile);
plugin.token.load(plugin.tokenFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void saveYamls()
{
try
{
plugin.config.save(plugin.configFile);
plugin.messages.save(plugin.messagesFile);
plugin.token.save(plugin.tokenFile);
} catch (IOException e)
{
e.printStackTrace();
}
}
public static void updateconfig()
{
- if(plugin.config.getString("configversion").equals(plugin.getDescription().getVersion()))
+ if(!plugin.config.getString("configversion").equals(plugin.getDescription().getVersion()))
{
plugin.config.set("configversion", plugin.getDescription().getVersion());
}
if(plugin.config.getString("Apply.Enabled") == null)
{
plugin.config.set("Apply.Enabled", true);
}
if(plugin.config.getString("Apply.Password") == null)
{
plugin.config.set("Apply.Password", "test");
}
if(plugin.config.getString("Apply.Defaultgroup") == null)
{
plugin.config.set("Apply.Defaultgroup", "default");
}
if(plugin.config.getString("Apply.Group") == null)
{
plugin.config.set("Apply.Group", "Member");
}
if(plugin.config.getString("Apply.Freeze") == null)
{
plugin.config.set("Apply.Freeze", false);
}
if(plugin.config.getString("Apply.Mute") == null)
{
plugin.config.set("Apply.Mute", false);
}
if(plugin.config.getString("Apply.KickWrongPW") == null)
{
plugin.config.set("Apply.KickWrongPW", true);
}
if(plugin.config.getString("Time.Enabled") == null)
{
plugin.config.set("Time.Enabled", false);
}
if(plugin.config.getString("Time.Group") == null)
{
plugin.config.set("Time.Group", "Member");
}
if(plugin.config.getString("Time.Time") == null)
{
plugin.config.set("Time.Time", 10);
}
if(plugin.config.getString("Time.CountOffline") == null)
{
plugin.config.set("Time.CountOffline", false);
}
if(plugin.config.getString("PromoteSyntax") == null)
{
plugin.config.set("PromoteSyntax", "none");
}
if(plugin.config.getString("token") != null)
{
for(String token : plugin.config.getConfigurationSection("token").getKeys(false))
{
String usage = plugin.config.getString("token." + token + ".usage");
String group = plugin.config.getString("token." + token + ".group");
plugin.token.set("token." + token + ".usage", usage);
plugin.token.set("token." + token + ".group", group);
}
plugin.config.set("token", null);
}
saveYamls();
}
}
| true | true | public static void updateconfig()
{
if(plugin.config.getString("configversion").equals(plugin.getDescription().getVersion()))
{
plugin.config.set("configversion", plugin.getDescription().getVersion());
}
if(plugin.config.getString("Apply.Enabled") == null)
{
plugin.config.set("Apply.Enabled", true);
}
if(plugin.config.getString("Apply.Password") == null)
{
plugin.config.set("Apply.Password", "test");
}
if(plugin.config.getString("Apply.Defaultgroup") == null)
{
plugin.config.set("Apply.Defaultgroup", "default");
}
if(plugin.config.getString("Apply.Group") == null)
{
plugin.config.set("Apply.Group", "Member");
}
if(plugin.config.getString("Apply.Freeze") == null)
{
plugin.config.set("Apply.Freeze", false);
}
if(plugin.config.getString("Apply.Mute") == null)
{
plugin.config.set("Apply.Mute", false);
}
if(plugin.config.getString("Apply.KickWrongPW") == null)
{
plugin.config.set("Apply.KickWrongPW", true);
}
if(plugin.config.getString("Time.Enabled") == null)
{
plugin.config.set("Time.Enabled", false);
}
if(plugin.config.getString("Time.Group") == null)
{
plugin.config.set("Time.Group", "Member");
}
if(plugin.config.getString("Time.Time") == null)
{
plugin.config.set("Time.Time", 10);
}
if(plugin.config.getString("Time.CountOffline") == null)
{
plugin.config.set("Time.CountOffline", false);
}
if(plugin.config.getString("PromoteSyntax") == null)
{
plugin.config.set("PromoteSyntax", "none");
}
if(plugin.config.getString("token") != null)
{
for(String token : plugin.config.getConfigurationSection("token").getKeys(false))
{
String usage = plugin.config.getString("token." + token + ".usage");
String group = plugin.config.getString("token." + token + ".group");
plugin.token.set("token." + token + ".usage", usage);
plugin.token.set("token." + token + ".group", group);
}
plugin.config.set("token", null);
}
saveYamls();
}
| public static void updateconfig()
{
if(!plugin.config.getString("configversion").equals(plugin.getDescription().getVersion()))
{
plugin.config.set("configversion", plugin.getDescription().getVersion());
}
if(plugin.config.getString("Apply.Enabled") == null)
{
plugin.config.set("Apply.Enabled", true);
}
if(plugin.config.getString("Apply.Password") == null)
{
plugin.config.set("Apply.Password", "test");
}
if(plugin.config.getString("Apply.Defaultgroup") == null)
{
plugin.config.set("Apply.Defaultgroup", "default");
}
if(plugin.config.getString("Apply.Group") == null)
{
plugin.config.set("Apply.Group", "Member");
}
if(plugin.config.getString("Apply.Freeze") == null)
{
plugin.config.set("Apply.Freeze", false);
}
if(plugin.config.getString("Apply.Mute") == null)
{
plugin.config.set("Apply.Mute", false);
}
if(plugin.config.getString("Apply.KickWrongPW") == null)
{
plugin.config.set("Apply.KickWrongPW", true);
}
if(plugin.config.getString("Time.Enabled") == null)
{
plugin.config.set("Time.Enabled", false);
}
if(plugin.config.getString("Time.Group") == null)
{
plugin.config.set("Time.Group", "Member");
}
if(plugin.config.getString("Time.Time") == null)
{
plugin.config.set("Time.Time", 10);
}
if(plugin.config.getString("Time.CountOffline") == null)
{
plugin.config.set("Time.CountOffline", false);
}
if(plugin.config.getString("PromoteSyntax") == null)
{
plugin.config.set("PromoteSyntax", "none");
}
if(plugin.config.getString("token") != null)
{
for(String token : plugin.config.getConfigurationSection("token").getKeys(false))
{
String usage = plugin.config.getString("token." + token + ".usage");
String group = plugin.config.getString("token." + token + ".group");
plugin.token.set("token." + token + ".usage", usage);
plugin.token.set("token." + token + ".group", group);
}
plugin.config.set("token", null);
}
saveYamls();
}
|
diff --git a/src/com/contoso/services/TodoServices.java b/src/com/contoso/services/TodoServices.java
index 1ee472a..a685d28 100644
--- a/src/com/contoso/services/TodoServices.java
+++ b/src/com/contoso/services/TodoServices.java
@@ -1,82 +1,82 @@
/* Todo service */
package com.contoso.services;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import com.google.gson.Gson;
/**
* Servlet implementation class TodoServices
*/
@WebServlet("/TodoServices")
public class TodoServices extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TodoServices() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
TodoList todoList = new TodoList();
todoList.name = "Personal";
- todoList.color = "blue";
+ todoList.color = "purple";
todoList.items = getTestItems();
String json = gson.toJson(todoList);
response.setContentType("application/json");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().write(json);
response.getWriter().flush();
}
private TodoItem[] getTestItems() {
List items = new ArrayList();
items.add(new TodoItem("Get tickets for the game"));
items.add(new TodoItem("Mail package"));
items.add(new TodoItem("Milk the cows"));
items.add(new TodoItem("Get a new engineering system for the company"));
return (TodoItem[])items.toArray(new TodoItem[items.size()]);
}
private static class TodoList {
public String name;
public String color;
public TodoItem[] items;
}
private static class TodoItem {
public TodoItem(String name) {
this.id = ((int)Math.random() * 12300) + "";
this.name = name;
this.createdAt = new Date();
}
public String id;
public String name;
public Date createdAt;
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
TodoList todoList = new TodoList();
todoList.name = "Personal";
todoList.color = "blue";
todoList.items = getTestItems();
String json = gson.toJson(todoList);
response.setContentType("application/json");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().write(json);
response.getWriter().flush();
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
TodoList todoList = new TodoList();
todoList.name = "Personal";
todoList.color = "purple";
todoList.items = getTestItems();
String json = gson.toJson(todoList);
response.setContentType("application/json");
response.setHeader("Access-Control-Allow-Origin", "*");
response.getWriter().write(json);
response.getWriter().flush();
}
|
diff --git a/geogebra/geogebra/kernel/AlgoSolveODE.java b/geogebra/geogebra/kernel/AlgoSolveODE.java
index 5ff758a40..62a811de5 100644
--- a/geogebra/geogebra/kernel/AlgoSolveODE.java
+++ b/geogebra/geogebra/kernel/AlgoSolveODE.java
@@ -1,209 +1,213 @@
package geogebra.kernel;
import geogebra.kernel.arithmetic.FunctionalNVar;
import java.util.ArrayList;
import org.apache.commons.math.ode.DerivativeException;
import org.apache.commons.math.ode.FirstOrderDifferentialEquations;
import org.apache.commons.math.ode.FirstOrderIntegrator;
import org.apache.commons.math.ode.IntegratorException;
import org.apache.commons.math.ode.nonstiff.ClassicalRungeKuttaIntegrator;
import org.apache.commons.math.ode.sampling.StepHandler;
import org.apache.commons.math.ode.sampling.StepInterpolator;
public class AlgoSolveODE extends AlgoElement {
private static final long serialVersionUID = 1L;
private FunctionalNVar f0, f1; // input
private GeoNumeric x, y, start, end, step; // input
//private GeoList g; // output
private GeoLocus locus; // output
private ArrayList<MyPoint> al;
public AlgoSolveODE(Construction cons, String label, FunctionalNVar f0, FunctionalNVar f1, GeoNumeric x, GeoNumeric y, GeoNumeric end, GeoNumeric step) {
super(cons);
this.f0 = f0;
this.f1 = f1;
this.x = x;
this.y = y;
this.end = end;
this.step = step;
//g = new GeoList(cons);
locus = new GeoLocus(cons);
setInputOutput(); // for AlgoElement
compute();
//g.setLabel(label);
locus.setLabel(label);
}
public String getClassName() {
return "AlgoSolveODE";
}
// for AlgoElement
protected void setInputOutput() {
input = new GeoElement[f1 == null ? 5 : 6];
int i = 0;
input[i++] = (GeoElement)f0;
if (f1 != null) input[i++] = (GeoElement)f1;
input[i++] = x;
input[i++] = y;
input[i++] = end;
input[i++] = step;
output = new GeoElement[1];
//output[0] = g;
output[0] = locus;
setDependencies(); // done by AlgoElement
}
public GeoLocus getResult() {
//return g;
return locus;
}
protected final void compute() {
if (!((GeoElement)f0).isDefined() || !x.isDefined() || !y.isDefined() || !step.isDefined() || !end.isDefined() || kernel.isZero(step.getDouble())) {
//g.setUndefined();
locus.setUndefined();
return;
}
//g.clear();
if (al == null) al = new ArrayList<MyPoint>();
else al.clear();
//FirstOrderIntegrator integrator = new DormandPrince853Integrator(1.0e-8, 100.0, 1.0e-10, 1.0e-10);
FirstOrderIntegrator integrator = new ClassicalRungeKuttaIntegrator(step.getDouble());
FirstOrderDifferentialEquations ode;
if (f1 == null) ode = new ODE(f0); else ode = new ODE2(f0,f1);
integrator.addStepHandler(stepHandler);
//boolean oldState = cons.isSuppressLabelsActive();
//cons.setSuppressLabelCreation(true);
//g.add(new GeoPoint(cons, null, x.getDouble(), y.getDouble(), 1.0));
al.add(new MyPoint(x.getDouble(), y.getDouble(), false));
//cons.setSuppressLabelCreation(oldState);
double[] yy = new double[] { y.getDouble() }; // initial state
double[] yy2 = new double[] { x.getDouble(), y.getDouble() }; // initial state
try {
if (f1 == null)
integrator.integrate(ode, x.getDouble(), yy, end.getDouble(), yy);
else
integrator.integrate(ode, 0.0, yy2, end.getDouble(), yy2);
} catch (DerivativeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
+ locus.setDefined(false);
+ return;
} catch (IntegratorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
+ locus.setDefined(false);
+ return;
} // now y contains final state at time t=16.0
//g.setDefined(true);
locus.setPoints(al);
locus.setDefined(true);
}
final public String toString() {
return getCommandDescription();
}
StepHandler stepHandler = new StepHandler() {
public void reset() {}
Construction cons = kernel.getConstruction();
public boolean requiresDenseOutput() { return false; }
public void handleStep(StepInterpolator interpolator, boolean isLast) throws DerivativeException {
double t = interpolator.getCurrentTime();
double[] y = interpolator.getInterpolatedState();
//System.out.println(t + " " + y[0]);
boolean oldState = cons.isSuppressLabelsActive();
cons.setSuppressLabelCreation(true);
if (f1 == null) {
//g.add(new GeoPoint(cons, null, t, y[0], 1.0));
al.add(new MyPoint(t, y[0], true));
}
else
{
//g.add(new GeoPoint(cons, null, y[0], y[1], 1.0));
al.add(new MyPoint(y[0], y[1], true));
}
cons.setSuppressLabelCreation(oldState);
}
};
//integrator.addStepHandler(stepHandler);
private static class ODE implements FirstOrderDifferentialEquations {
FunctionalNVar f;
public ODE(FunctionalNVar f) {
this.f = f;
}
public int getDimension() {
return 1;
}
public void computeDerivatives(double t, double[] y, double[] yDot) {
double input[] = {t, y[0]};
// special case for f(y)= (substitute y not x)
// eg SolveODE[y, x(A), y(A), 5, 0.1]
if (f instanceof GeoFunction && "y".equals(((GeoFunction)f).getFunction().getFunctionVariable().toString())) {
yDot[0] = ((GeoFunction)f).evaluate(y[0]);
} else
yDot[0] = f.evaluate(input);
}
}
private static class ODE2 implements FirstOrderDifferentialEquations {
FunctionalNVar y0, y1;
public ODE2(FunctionalNVar y, FunctionalNVar x) {
this.y0 = y;
this.y1 = x;
}
public int getDimension() {
return 2;
}
public void computeDerivatives(double t, double[] y, double[] yDot) {
double input[] = {y[0], y[1]};
// special case for f(y)= (substitute y not x)
// eg SolveODE[-y, x, x(A), y(A), 5, 0.1]
if (y1 instanceof GeoFunction && "y".equals(((GeoFunction)y1).getFunction().getFunctionVariable().toString())) {
yDot[0] = ((GeoFunction)y1).evaluate(y[1]);
} else
yDot[0] = y1.evaluate(input);
// special case for f(y)= (substitute y not x)
// eg SolveODE[-x, y, x(A), y(A), 5, 0.1]
if (y0 instanceof GeoFunction && "y".equals(((GeoFunction)y0).getFunction().getFunctionVariable().toString())) {
yDot[1] = ((GeoFunction)y0).evaluate(y[1]);
} else
yDot[1] = y0.evaluate(input);
}
}
}
| false | true | protected final void compute() {
if (!((GeoElement)f0).isDefined() || !x.isDefined() || !y.isDefined() || !step.isDefined() || !end.isDefined() || kernel.isZero(step.getDouble())) {
//g.setUndefined();
locus.setUndefined();
return;
}
//g.clear();
if (al == null) al = new ArrayList<MyPoint>();
else al.clear();
//FirstOrderIntegrator integrator = new DormandPrince853Integrator(1.0e-8, 100.0, 1.0e-10, 1.0e-10);
FirstOrderIntegrator integrator = new ClassicalRungeKuttaIntegrator(step.getDouble());
FirstOrderDifferentialEquations ode;
if (f1 == null) ode = new ODE(f0); else ode = new ODE2(f0,f1);
integrator.addStepHandler(stepHandler);
//boolean oldState = cons.isSuppressLabelsActive();
//cons.setSuppressLabelCreation(true);
//g.add(new GeoPoint(cons, null, x.getDouble(), y.getDouble(), 1.0));
al.add(new MyPoint(x.getDouble(), y.getDouble(), false));
//cons.setSuppressLabelCreation(oldState);
double[] yy = new double[] { y.getDouble() }; // initial state
double[] yy2 = new double[] { x.getDouble(), y.getDouble() }; // initial state
try {
if (f1 == null)
integrator.integrate(ode, x.getDouble(), yy, end.getDouble(), yy);
else
integrator.integrate(ode, 0.0, yy2, end.getDouble(), yy2);
} catch (DerivativeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IntegratorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // now y contains final state at time t=16.0
//g.setDefined(true);
locus.setPoints(al);
locus.setDefined(true);
}
| protected final void compute() {
if (!((GeoElement)f0).isDefined() || !x.isDefined() || !y.isDefined() || !step.isDefined() || !end.isDefined() || kernel.isZero(step.getDouble())) {
//g.setUndefined();
locus.setUndefined();
return;
}
//g.clear();
if (al == null) al = new ArrayList<MyPoint>();
else al.clear();
//FirstOrderIntegrator integrator = new DormandPrince853Integrator(1.0e-8, 100.0, 1.0e-10, 1.0e-10);
FirstOrderIntegrator integrator = new ClassicalRungeKuttaIntegrator(step.getDouble());
FirstOrderDifferentialEquations ode;
if (f1 == null) ode = new ODE(f0); else ode = new ODE2(f0,f1);
integrator.addStepHandler(stepHandler);
//boolean oldState = cons.isSuppressLabelsActive();
//cons.setSuppressLabelCreation(true);
//g.add(new GeoPoint(cons, null, x.getDouble(), y.getDouble(), 1.0));
al.add(new MyPoint(x.getDouble(), y.getDouble(), false));
//cons.setSuppressLabelCreation(oldState);
double[] yy = new double[] { y.getDouble() }; // initial state
double[] yy2 = new double[] { x.getDouble(), y.getDouble() }; // initial state
try {
if (f1 == null)
integrator.integrate(ode, x.getDouble(), yy, end.getDouble(), yy);
else
integrator.integrate(ode, 0.0, yy2, end.getDouble(), yy2);
} catch (DerivativeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
locus.setDefined(false);
return;
} catch (IntegratorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
locus.setDefined(false);
return;
} // now y contains final state at time t=16.0
//g.setDefined(true);
locus.setPoints(al);
locus.setDefined(true);
}
|
diff --git a/src/main/java/org/encog/ml/prg/train/PrgGenetic.java b/src/main/java/org/encog/ml/prg/train/PrgGenetic.java
index 70c3586d2..af89c5551 100644
--- a/src/main/java/org/encog/ml/prg/train/PrgGenetic.java
+++ b/src/main/java/org/encog/ml/prg/train/PrgGenetic.java
@@ -1,377 +1,377 @@
package org.encog.ml.prg.train;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.encog.Encog;
import org.encog.EncogError;
import org.encog.mathutil.randomize.factory.RandomFactory;
import org.encog.ml.MLMethod;
import org.encog.ml.TrainingImplementationType;
import org.encog.ml.data.MLDataSet;
import org.encog.ml.prg.EncogProgram;
import org.encog.ml.prg.EncogProgramContext;
import org.encog.ml.prg.EncogProgramVariables;
import org.encog.ml.prg.epl.EPLHolder;
import org.encog.ml.prg.train.crossover.PrgCrossover;
import org.encog.ml.prg.train.crossover.SubtreeCrossover;
import org.encog.ml.prg.train.mutate.PrgMutate;
import org.encog.ml.prg.train.mutate.SubtreeMutation;
import org.encog.ml.prg.train.selection.PrgSelection;
import org.encog.ml.prg.train.selection.TournamentSelection;
import org.encog.ml.prg.train.sort.MaximizeEffectiveScoreComp;
import org.encog.ml.prg.train.sort.MinimizeEffectiveScoreComp;
import org.encog.ml.train.MLTrain;
import org.encog.ml.train.strategy.Strategy;
import org.encog.neural.networks.training.CalculateScore;
import org.encog.neural.networks.training.TrainingSetScore;
import org.encog.neural.networks.training.propagation.TrainingContinuation;
import org.encog.util.concurrency.MultiThreadable;
public class PrgGenetic implements MLTrain, MultiThreadable {
private final EncogProgramContext context;
private final PrgPopulation population;
private final CalculateScore scoreFunction;
private PrgSelection selection;
private PrgMutate mutation;
private PrgCrossover crossover;
private EncogProgram bestGenome = null;
private Comparator<EncogProgram> compareScore;
private int threadCount;
private GeneticTrainWorker[] workers;
private int iterationNumber;
private int subIterationCounter;
private final Lock iterationLock = new ReentrantLock();
private RandomFactory randomNumberFactory = Encog.getInstance()
.getRandomFactory().factorFactory();
private Throwable currentError;
private final GeneticTrainingParams params = new GeneticTrainingParams();
/**
* Condition used to check if we are done.
*/
private final Condition iterationCondition = this.iterationLock
.newCondition();
public PrgGenetic(PrgPopulation thePopulation,
CalculateScore theScoreFunction) {
this.population = thePopulation;
this.context = population.getContext();
this.scoreFunction = theScoreFunction;
this.selection = new TournamentSelection(this, 4);
this.crossover = new SubtreeCrossover();
this.mutation = new SubtreeMutation(thePopulation.getContext(), 4);
if (theScoreFunction.shouldMinimize()) {
this.compareScore = new MinimizeEffectiveScoreComp();
} else {
this.compareScore = new MaximizeEffectiveScoreComp();
}
}
public PrgGenetic(PrgPopulation thePopulation, MLDataSet theTrainingSet) {
this(thePopulation, new TrainingSetScore(theTrainingSet));
}
public PrgPopulation getPopulation() {
return population;
}
public CalculateScore getScoreFunction() {
return scoreFunction;
}
public PrgSelection getSelection() {
return selection;
}
public void setSelection(PrgSelection selection) {
this.selection = selection;
}
public PrgMutate getMutation() {
return mutation;
}
public void setMutation(PrgMutate mutation) {
this.mutation = mutation;
}
public PrgCrossover getCrossover() {
return crossover;
}
public void setCrossover(PrgCrossover crossover) {
this.crossover = crossover;
}
@Override
public TrainingImplementationType getImplementationType() {
// TODO Auto-generated method stub
return TrainingImplementationType.Background;
}
@Override
public boolean isTrainingDone() {
// TODO Auto-generated method stub
return false;
}
@Override
public MLDataSet getTraining() {
// TODO Auto-generated method stub
return null;
}
private void startup() {
int actualThreadCount = Runtime.getRuntime().availableProcessors();
if (this.threadCount != 0) {
actualThreadCount = this.threadCount;
}
this.workers = new GeneticTrainWorker[actualThreadCount];
for (int i = 0; i < this.workers.length; i++) {
this.workers[i] = new GeneticTrainWorker(this);
this.workers[i].start();
}
}
@Override
public void iteration() {
if (this.workers == null) {
startup();
}
this.iterationLock.lock();
try {
this.iterationCondition.await();
if (this.currentError != null) {
throw new EncogError(this.currentError);
}
} catch (InterruptedException e) {
} finally {
this.iterationLock.unlock();
}
}
@Override
public double getError() {
return this.bestGenome.getScore();
}
@Override
public void finishTraining() {
for (int i = 0; i < this.workers.length; i++) {
this.workers[i].requestTerminate();
}
for (int i = 0; i < this.workers.length; i++) {
try {
this.workers[i].join();
} catch (InterruptedException e) {
throw new EncogError("Can't shut down training threads.");
}
}
this.workers = null;
}
@Override
public void iteration(int count) {
// TODO Auto-generated method stub
}
@Override
public int getIteration() {
return this.iterationNumber;
}
@Override
public boolean canContinue() {
// TODO Auto-generated method stub
return false;
}
@Override
public TrainingContinuation pause() {
// TODO Auto-generated method stub
return null;
}
@Override
public void resume(TrainingContinuation state) {
// TODO Auto-generated method stub
}
@Override
public void addStrategy(Strategy strategy) {
// TODO Auto-generated method stub
}
@Override
public MLMethod getMethod() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Strategy> getStrategies() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setError(double error) {
// TODO Auto-generated method stub
}
@Override
public void setIteration(int iteration) {
// TODO Auto-generated method stub
}
public Comparator<EncogProgram> getCompareScore() {
return compareScore;
}
public void setCompareScore(Comparator<EncogProgram> compareScore) {
this.compareScore = compareScore;
}
public void createRandomPopulation(int maxDepth) {
CreateRandom rnd = new CreateRandom(this.context, maxDepth);
Random random = this.randomNumberFactory.factor();
for (int i = 0; i < this.population.getMaxPopulation(); i++) {
EncogProgram prg = new EncogProgram(this.context, new EncogProgramVariables(), this.population.getHolder(), i);
this.population.getMembers()[i] = prg;
boolean done = false;
do {
prg.clear();
- rnd.createNode(random, this.population.getMembers()[i], maxDepth);
+ rnd.createNode(random, this.population.getMembers()[i], 0);
double score = this.scoreFunction.calculateScore(prg);
if (!Double.isInfinite(score) && !Double.isNaN(score)) {
prg.setScore(score);
done = true;
}
} while (!done);
evaluateBestGenome(prg);
this.population.rewrite(prg);
}
}
private void evaluateBestGenome(EncogProgram prg) {
calculateEffectiveScore(prg);
if (this.bestGenome == null || isGenomeBetter(prg, this.bestGenome)) {
this.bestGenome = prg;
}
}
public boolean isGenomeBetter(EncogProgram genome, EncogProgram betterThan) {
return this.compareScore.compare(genome, betterThan) < 0;
}
public EncogProgram getBestGenome() {
return this.bestGenome;
}
public void sort() {
Arrays.sort(this.getPopulation().getMembers(), this.compareScore);
}
public void addGenome(EncogProgram[] tempProgram, int index, int size) {
this.iterationLock.lock();
try {
for(int i=0;i<size;i++) {
int replaceIndex = selection.performAntiSelection();
this.population.getMembers()[replaceIndex] = tempProgram[index+i];
evaluateBestGenome(tempProgram[index+i]);
}
this.subIterationCounter++;
if (this.subIterationCounter > this.population.size()) {
this.subIterationCounter = 0;
this.iterationNumber++;
this.iterationCondition.signal();
}
} finally {
this.iterationLock.unlock();
}
}
@Override
public int getThreadCount() {
return this.threadCount;
}
@Override
public void setThreadCount(int numThreads) {
this.threadCount = numThreads;
}
/**
* @return the randomNumberFactory
*/
public RandomFactory getRandomNumberFactory() {
return randomNumberFactory;
}
/**
* @param randomNumberFactory
* the randomNumberFactory to set
*/
public void setRandomNumberFactory(RandomFactory randomNumberFactory) {
this.randomNumberFactory = randomNumberFactory;
}
public void reportError(Throwable t) {
this.iterationLock.lock();
try {
this.currentError = t;
this.iterationCondition.signal();
} finally {
this.iterationLock.unlock();
}
}
/**
* @return the params
*/
public GeneticTrainingParams getParams() {
return params;
}
public void calculateEffectiveScore(EncogProgram prg) {
double result = prg.getScore();
if (prg.size() > this.params.getComplexityPenaltyThreshold()) {
int over = prg.size() - this.params.getComplexityPenaltyThreshold();
int range = this.params.getComplexityPentaltyFullThreshold()
- this.params.getComplexityPenaltyThreshold();
double complexityPenalty = ((params.getComplexityFullPenalty() - this.params
.getComplexityPenalty()) / range) * over;
result += (result * complexityPenalty);
}
prg.setEffectiveScore(result);
}
}
| true | true | public void createRandomPopulation(int maxDepth) {
CreateRandom rnd = new CreateRandom(this.context, maxDepth);
Random random = this.randomNumberFactory.factor();
for (int i = 0; i < this.population.getMaxPopulation(); i++) {
EncogProgram prg = new EncogProgram(this.context, new EncogProgramVariables(), this.population.getHolder(), i);
this.population.getMembers()[i] = prg;
boolean done = false;
do {
prg.clear();
rnd.createNode(random, this.population.getMembers()[i], maxDepth);
double score = this.scoreFunction.calculateScore(prg);
if (!Double.isInfinite(score) && !Double.isNaN(score)) {
prg.setScore(score);
done = true;
}
} while (!done);
evaluateBestGenome(prg);
this.population.rewrite(prg);
}
}
| public void createRandomPopulation(int maxDepth) {
CreateRandom rnd = new CreateRandom(this.context, maxDepth);
Random random = this.randomNumberFactory.factor();
for (int i = 0; i < this.population.getMaxPopulation(); i++) {
EncogProgram prg = new EncogProgram(this.context, new EncogProgramVariables(), this.population.getHolder(), i);
this.population.getMembers()[i] = prg;
boolean done = false;
do {
prg.clear();
rnd.createNode(random, this.population.getMembers()[i], 0);
double score = this.scoreFunction.calculateScore(prg);
if (!Double.isInfinite(score) && !Double.isNaN(score)) {
prg.setScore(score);
done = true;
}
} while (!done);
evaluateBestGenome(prg);
this.population.rewrite(prg);
}
}
|
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/WordRecognizerWrapper.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/WordRecognizerWrapper.java
index ade95f556..ed4ca72d6 100644
--- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/WordRecognizerWrapper.java
+++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/layout/pdf/WordRecognizerWrapper.java
@@ -1,123 +1,126 @@
package org.eclipse.birt.report.engine.layout.pdf;
import java.util.Locale;
import org.eclipse.birt.report.engine.layout.pdf.hyphen.ICUWordRecognizer;
import org.eclipse.birt.report.engine.layout.pdf.hyphen.IWordRecognizer;
import org.eclipse.birt.report.engine.layout.pdf.hyphen.Word;
public class WordRecognizerWrapper implements IWordRecognizer
{
private String text;
private ICUWordRecognizer wr = null;
private Word currentWord = null;
private int start = 0;
private int end = 0;
private static final String KEEP_WITH_NEXT_CHARS = "(<{[(《«“$¥";
private static final String KEEP_WITH_LAST_CHARS = ")>}])》»”,.;:! ,。;:!";
//FIXME: for quotes across chunks, the algorithm has some problem.
private static final String KEEP_WITH_DEPENDS = "\"'";
private boolean leftQuote = true;
public WordRecognizerWrapper( String text, Locale locale )
{
this.text = text;
wr = new ICUWordRecognizer( text, locale );
}
public Word getNextWord( )
{
start = end;
if ( start == text.length( ) )
return null;
keepWithNext( );
keepWithLast( );
return new Word( text, start, end );
}
public int getLastWordEnd( )
{
return start;
}
private void keepWithNext( )
{
if ( !genCurrentICUWord( ) )
{
return;
}
// current word is a char must keep with next.
if (currentWord.getLength( ) == 1)
{
if ( KEEP_WITH_NEXT_CHARS.indexOf( currentWord.getValue( ) ) != -1 )
{
end = currentWord.getEnd( );
keepWithNext( );
}
else if ( KEEP_WITH_DEPENDS.indexOf( currentWord.getValue( ) ) != -1
&& leftQuote )
{
end = currentWord.getEnd( );
leftQuote = false;
keepWithNext( );
}
}
- end = currentWord.getEnd( );
+ if ( null != currentWord )
+ {
+ end = currentWord.getEnd( );
+ }
}
private void keepWithLast( )
{
if ( !genCurrentICUWord( ) )
{
return;
}
if ( currentWord.getLength( ) == 1 )
{
// current word is a char must keep with last
if ( KEEP_WITH_LAST_CHARS.indexOf( currentWord.getValue( ) ) != -1 )
{
end = currentWord.getEnd( );
keepWithLast( );
}
else if ( KEEP_WITH_DEPENDS.indexOf( currentWord.getValue( ) ) != -1
&& !leftQuote )
{
end = currentWord.getEnd( );
leftQuote = true;
keepWithLast( );
}
}
}
private boolean genCurrentICUWord( )
{
// the text has not be handled yet.
if ( null == currentWord )
{
currentWord = wr.getNextWord( );
if ( null == currentWord )
return false;
else
return true;
}
// last word has been eaten up.
if ( end == currentWord.getEnd( ) )
{
currentWord = wr.getNextWord( );
if ( null == currentWord )
return false;
else
return true;
}
// last word has already been generated, but has not been used.
return true;
}
}
| true | true | private void keepWithNext( )
{
if ( !genCurrentICUWord( ) )
{
return;
}
// current word is a char must keep with next.
if (currentWord.getLength( ) == 1)
{
if ( KEEP_WITH_NEXT_CHARS.indexOf( currentWord.getValue( ) ) != -1 )
{
end = currentWord.getEnd( );
keepWithNext( );
}
else if ( KEEP_WITH_DEPENDS.indexOf( currentWord.getValue( ) ) != -1
&& leftQuote )
{
end = currentWord.getEnd( );
leftQuote = false;
keepWithNext( );
}
}
end = currentWord.getEnd( );
}
| private void keepWithNext( )
{
if ( !genCurrentICUWord( ) )
{
return;
}
// current word is a char must keep with next.
if (currentWord.getLength( ) == 1)
{
if ( KEEP_WITH_NEXT_CHARS.indexOf( currentWord.getValue( ) ) != -1 )
{
end = currentWord.getEnd( );
keepWithNext( );
}
else if ( KEEP_WITH_DEPENDS.indexOf( currentWord.getValue( ) ) != -1
&& leftQuote )
{
end = currentWord.getEnd( );
leftQuote = false;
keepWithNext( );
}
}
if ( null != currentWord )
{
end = currentWord.getEnd( );
}
}
|
diff --git a/gamelib/test/game/configuration/ConfigurableTestA.java b/gamelib/test/game/configuration/ConfigurableTestA.java
index 0d1bc59..b6feb90 100644
--- a/gamelib/test/game/configuration/ConfigurableTestA.java
+++ b/gamelib/test/game/configuration/ConfigurableTestA.java
@@ -1,42 +1,42 @@
package game.configuration;
public class ConfigurableTestA extends Configurable {
public String optionA1;
public String optionA2;
public String optionA3;
public ConfigurableTestB optionA4;
public ConfigurableTestC optionA5;
private class StringLengthCheck implements ErrorCheck<String> {
private int minimumLength;
public StringLengthCheck(int minimumLength) {
this.minimumLength = minimumLength;
}
@Override
public String getError(String value) {
if (value.length() < minimumLength)
return "should have at least " + minimumLength + " characters";
else
return null;
}
}
public ConfigurableTestA() {
addOptionBinding("optionA1", "optionA4.optionB1", "optionA5.optionC1");
addOptionBinding("optionA2", "optionA4.optionB2");
addOptionBinding("optionA4.optionB3", "optionA5.optionC2");
- addOptionCheck("optionA3", new StringLengthCheck(20));
+ addOptionChecks("optionA3", new StringLengthCheck(20));
}
}
| true | true | public ConfigurableTestA() {
addOptionBinding("optionA1", "optionA4.optionB1", "optionA5.optionC1");
addOptionBinding("optionA2", "optionA4.optionB2");
addOptionBinding("optionA4.optionB3", "optionA5.optionC2");
addOptionCheck("optionA3", new StringLengthCheck(20));
}
| public ConfigurableTestA() {
addOptionBinding("optionA1", "optionA4.optionB1", "optionA5.optionC1");
addOptionBinding("optionA2", "optionA4.optionB2");
addOptionBinding("optionA4.optionB3", "optionA5.optionC2");
addOptionChecks("optionA3", new StringLengthCheck(20));
}
|
diff --git a/src/main/java/com/philihp/weblabora/action/BaseAction.java b/src/main/java/com/philihp/weblabora/action/BaseAction.java
index 77e1ca3..30ed01b 100644
--- a/src/main/java/com/philihp/weblabora/action/BaseAction.java
+++ b/src/main/java/com/philihp/weblabora/action/BaseAction.java
@@ -1,59 +1,62 @@
package com.philihp.weblabora.action;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.philihp.weblabora.jpa.User;
import com.philihp.weblabora.util.FacebookSignedRequest;
import com.philihp.weblabora.util.FacebookSignedRequestDeserializer;
import com.philihp.weblabora.util.FacebookUtil;
abstract public class BaseAction extends Action {
@SuppressWarnings("unchecked")
private static final Set<Object> PUBLIC_ACTIONS = new HashSet<Object>(Arrays.asList(ShowGame.class, ShowGameState.class, ShowLobby.class, Offline.class));
@Override
public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("Action: "+this.getClass().getCanonicalName());
EntityManager em = (EntityManager)request.getAttribute("em");
User user = (User)request.getSession().getAttribute("user");
- if(user != null) em.persist(user);
+ if(user != null) {
+ user = em.merge(user);
+ request.getSession().setAttribute("user", user);
+ }
//if still no user, restart authentication process
if(user == null && isActionPrivate()) {
throw new AuthenticationException();
}
return execute(mapping, actionForm, request, response, user);
}
abstract ActionForward execute(ActionMapping mapping, ActionForm actionForm,
HttpServletRequest request, HttpServletResponse response, User user)
throws AuthenticationException, Exception;
private boolean isActionPrivate() {
return PUBLIC_ACTIONS.contains(this.getClass()) == false;
}
}
| true | true | public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("Action: "+this.getClass().getCanonicalName());
EntityManager em = (EntityManager)request.getAttribute("em");
User user = (User)request.getSession().getAttribute("user");
if(user != null) em.persist(user);
//if still no user, restart authentication process
if(user == null && isActionPrivate()) {
throw new AuthenticationException();
}
return execute(mapping, actionForm, request, response, user);
}
| public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
System.out.println("Action: "+this.getClass().getCanonicalName());
EntityManager em = (EntityManager)request.getAttribute("em");
User user = (User)request.getSession().getAttribute("user");
if(user != null) {
user = em.merge(user);
request.getSession().setAttribute("user", user);
}
//if still no user, restart authentication process
if(user == null && isActionPrivate()) {
throw new AuthenticationException();
}
return execute(mapping, actionForm, request, response, user);
}
|
diff --git a/core/src/main/java/org/neociclo/odetteftp/netty/codec/CommandExchangeBufferBuilder.java b/core/src/main/java/org/neociclo/odetteftp/netty/codec/CommandExchangeBufferBuilder.java
index 27ad4b8..86488b9 100644
--- a/core/src/main/java/org/neociclo/odetteftp/netty/codec/CommandExchangeBufferBuilder.java
+++ b/core/src/main/java/org/neociclo/odetteftp/netty/codec/CommandExchangeBufferBuilder.java
@@ -1,151 +1,151 @@
/**
* Neociclo Accord, Open Source B2Bi Middleware
* Copyright (C) 2005-2010 Neociclo, http://www.neociclo.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* $Id$
*/
package org.neociclo.odetteftp.netty.codec;
import static org.neociclo.odetteftp.protocol.CommandExchangeBuffer.*;
import java.util.HashMap;
import java.util.Map;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.neociclo.odetteftp.protocol.CommandExchangeBuffer;
import org.neociclo.odetteftp.protocol.CommandFormat;
import org.neociclo.odetteftp.protocol.CommandFormat.Field;
import org.neociclo.odetteftp.util.ProtocolUtil;
/**
* @author Rafael Marins
* @version $Rev$ $Date$
*/
public class CommandExchangeBufferBuilder {
private static class ParamsRead {
public ParamsRead(int pos, int size) {
this.position = pos;
this.size = size;
}
private int position;
private int size;
}
public static CommandExchangeBuffer create(CommandFormat format, ChannelBuffer in) {
CommandExchangeBuffer command = new CommandExchangeBuffer(format);
Map<String, ParamsRead> fieldsRead = new HashMap<String, ParamsRead>();
int bufferLength = in.capacity();
for (String fieldName : format.getFieldNames()) {
Field field = format.getField(fieldName);
int pos = computePosition(field, fieldsRead);
int size = computeSize(field, fieldsRead, in);
fieldsRead.put(fieldName, new ParamsRead(pos, size));
if (size == 0) {
// empty field - skip
continue;
} else if ((bufferLength - pos) < size) {
// error - no remaining buffer to read field value
return command;
}
byte[] octets = new byte[size];
in.getBytes(pos, octets);
// raw bytes
if (field.getType() == Field.BINARY_TYPE) {
command.setAttribute(fieldName, octets);
}
// UTF-8 encoded text
else if (field.getType() == Field.ENCODED_TYPE) {
String encodedText = new String(octets, UTF8_ENCODED_PROTOCOL_CHARSET);
command.setAttribute(fieldName, encodedText);
}
// alphanumeric text
else {
String text = new String(octets, DEFAULT_PROTOCOL_CHARSET);
if (field.getType() == Field.ALPHANUMERIC_TYPE) {
// carriage return fields are settled as alphanumeric and shouldn't be trimmed
if (!"\r".equals(text) && !"\n".equals(text))
text = text.trim();
} else if (field.getType() == Field.NUMERIC_TYPE) {
- text = Integer.valueOf(text.trim()).toString();
+ text = text.trim();
}
command.setAttribute(field.getName(), text);
}
}
return command;
}
private static int computeSize(Field field, Map<String, ParamsRead> fieldsRead, ChannelBuffer in) {
int size = 0;
if (field.shouldComputeSize()) {
String lengthField = field.getLengthFieldName();
ParamsRead params = fieldsRead.get(lengthField);
// Compute binary value of field length when the target field type is Binary
if (field.getType() == Field.BINARY_TYPE) {
byte[] bin = new byte[params.size];
in.getBytes(params.position, bin);
size = ProtocolUtil.parseBinaryNumber(bin);
} else {
ChannelBuffer buf = ChannelBuffers.buffer(params.size);
in.getBytes(params.position, buf);
String lengthValue = buf.toString(DEFAULT_PROTOCOL_CHARSET);
size = Integer.parseInt(lengthValue);
}
} else {
size = field.getSize();
}
return size;
}
private static int computePosition(Field field, Map<String, ParamsRead> fieldsRead) {
int pos = 0;
if (field.shouldComputePosition()) {
String placeAfterField = field.getPositionAfterFieldName();
ParamsRead params = fieldsRead.get(placeAfterField);
pos = params.position + params.size;
} else {
pos = field.getPosition();
}
return pos;
}
}
| true | true | public static CommandExchangeBuffer create(CommandFormat format, ChannelBuffer in) {
CommandExchangeBuffer command = new CommandExchangeBuffer(format);
Map<String, ParamsRead> fieldsRead = new HashMap<String, ParamsRead>();
int bufferLength = in.capacity();
for (String fieldName : format.getFieldNames()) {
Field field = format.getField(fieldName);
int pos = computePosition(field, fieldsRead);
int size = computeSize(field, fieldsRead, in);
fieldsRead.put(fieldName, new ParamsRead(pos, size));
if (size == 0) {
// empty field - skip
continue;
} else if ((bufferLength - pos) < size) {
// error - no remaining buffer to read field value
return command;
}
byte[] octets = new byte[size];
in.getBytes(pos, octets);
// raw bytes
if (field.getType() == Field.BINARY_TYPE) {
command.setAttribute(fieldName, octets);
}
// UTF-8 encoded text
else if (field.getType() == Field.ENCODED_TYPE) {
String encodedText = new String(octets, UTF8_ENCODED_PROTOCOL_CHARSET);
command.setAttribute(fieldName, encodedText);
}
// alphanumeric text
else {
String text = new String(octets, DEFAULT_PROTOCOL_CHARSET);
if (field.getType() == Field.ALPHANUMERIC_TYPE) {
// carriage return fields are settled as alphanumeric and shouldn't be trimmed
if (!"\r".equals(text) && !"\n".equals(text))
text = text.trim();
} else if (field.getType() == Field.NUMERIC_TYPE) {
text = Integer.valueOf(text.trim()).toString();
}
command.setAttribute(field.getName(), text);
}
}
return command;
}
| public static CommandExchangeBuffer create(CommandFormat format, ChannelBuffer in) {
CommandExchangeBuffer command = new CommandExchangeBuffer(format);
Map<String, ParamsRead> fieldsRead = new HashMap<String, ParamsRead>();
int bufferLength = in.capacity();
for (String fieldName : format.getFieldNames()) {
Field field = format.getField(fieldName);
int pos = computePosition(field, fieldsRead);
int size = computeSize(field, fieldsRead, in);
fieldsRead.put(fieldName, new ParamsRead(pos, size));
if (size == 0) {
// empty field - skip
continue;
} else if ((bufferLength - pos) < size) {
// error - no remaining buffer to read field value
return command;
}
byte[] octets = new byte[size];
in.getBytes(pos, octets);
// raw bytes
if (field.getType() == Field.BINARY_TYPE) {
command.setAttribute(fieldName, octets);
}
// UTF-8 encoded text
else if (field.getType() == Field.ENCODED_TYPE) {
String encodedText = new String(octets, UTF8_ENCODED_PROTOCOL_CHARSET);
command.setAttribute(fieldName, encodedText);
}
// alphanumeric text
else {
String text = new String(octets, DEFAULT_PROTOCOL_CHARSET);
if (field.getType() == Field.ALPHANUMERIC_TYPE) {
// carriage return fields are settled as alphanumeric and shouldn't be trimmed
if (!"\r".equals(text) && !"\n".equals(text))
text = text.trim();
} else if (field.getType() == Field.NUMERIC_TYPE) {
text = text.trim();
}
command.setAttribute(field.getName(), text);
}
}
return command;
}
|
diff --git a/public/java/src/org/broadinstitute/sting/gatk/samples/SampleDB.java b/public/java/src/org/broadinstitute/sting/gatk/samples/SampleDB.java
index 9f00257d1..929ad41d1 100644
--- a/public/java/src/org/broadinstitute/sting/gatk/samples/SampleDB.java
+++ b/public/java/src/org/broadinstitute/sting/gatk/samples/SampleDB.java
@@ -1,195 +1,195 @@
package org.broadinstitute.sting.gatk.samples;
import net.sf.samtools.SAMReadGroupRecord;
import net.sf.samtools.SAMRecord;
import org.broadinstitute.sting.utils.exceptions.StingException;
import org.broadinstitute.sting.utils.variantcontext.Genotype;
import java.util.*;
/**
*
*/
public class SampleDB {
/**
* This is where Sample objects are stored. Samples are usually accessed by their ID, which is unique, so
* this is stored as a HashMap.
*/
private final HashMap<String, Sample> samples = new HashMap<String, Sample>();
/**
* Constructor takes both a SAM header and sample files because the two must be integrated.
*/
public SampleDB() {
}
/**
* Protected function to add a single sample to the database
*
* @param sample to be added
*/
protected SampleDB addSample(Sample sample) {
Sample prev = samples.get(sample.getID());
if ( prev != null )
sample = Sample.mergeSamples(prev, sample);
samples.put(sample.getID(), sample);
return this;
}
// --------------------------------------------------------------------------------
//
// Functions for getting a sample from the DB
//
// --------------------------------------------------------------------------------
/**
* Get a sample by its ID
* If an alias is passed in, return the main sample object
* @param id
* @return sample Object with this ID, or null if this does not exist
*/
public Sample getSample(String id) {
return samples.get(id);
}
/**
*
* @param read
* @return sample Object with this ID, or null if this does not exist
*/
public Sample getSample(final SAMRecord read) {
return getSample(read.getReadGroup());
}
/**
*
* @param rg
* @return sample Object with this ID, or null if this does not exist
*/
public Sample getSample(final SAMReadGroupRecord rg) {
return getSample(rg.getSample());
}
/**
* @param g Genotype
* @return sample Object with this ID, or null if this does not exist
*/
public Sample getSample(final Genotype g) {
return getSample(g.getSampleName());
}
// --------------------------------------------------------------------------------
//
// Functions for accessing samples in the DB
//
// --------------------------------------------------------------------------------
/**
* Get number of sample objects
* @return size of samples map
*/
public int sampleCount() {
return samples.size();
}
public Set<Sample> getSamples() {
return new HashSet<Sample>(samples.values());
}
public Collection<String> getSampleNames() {
return Collections.unmodifiableCollection(samples.keySet());
}
/**
* Takes a collection of sample names and returns their corresponding sample objects
* Note that, since a set is returned, if you pass in a list with duplicates names there will not be any duplicates in the returned set
* @param sampleNameList Set of sample names
* @return Corresponding set of samples
*/
public Set<Sample> getSamples(Collection<String> sampleNameList) {
HashSet<Sample> samples = new HashSet<Sample>();
for (String name : sampleNameList) {
try {
samples.add(getSample(name));
}
catch (Exception e) {
throw new StingException("Could not get sample with the following ID: " + name, e);
}
}
return samples;
}
// --------------------------------------------------------------------------------
//
// Higher level pedigree functions
//
// --------------------------------------------------------------------------------
/**
* Returns a sorted set of the family IDs in all samples (excluding null ids)
* @return
*/
public final Set<String> getFamilyIDs() {
return getFamilies().keySet();
}
/**
* Returns a map from family ID -> set of family members for all samples with
* non-null family ids
*
* @return
*/
public final Map<String, Set<Sample>> getFamilies() {
return getFamilies(null);
}
/**
* Returns a map from family ID -> set of family members for all samples in sampleIds with
* non-null family ids
*
* @param sampleIds - all samples to include. If null is passed then all samples are returned.
* @return
*/
public final Map<String, Set<Sample>> getFamilies(Collection<String> sampleIds) {
final Map<String, Set<Sample>> families = new TreeMap<String, Set<Sample>>();
for ( final Sample sample : samples.values() ) {
- if(sampleIds != null && sampleIds.contains(sample.getID())){
+ if(sampleIds == null || sampleIds.contains(sample.getID())){
final String famID = sample.getFamilyID();
if ( famID != null ) {
if ( ! families.containsKey(famID) )
families.put(famID, new TreeSet<Sample>());
families.get(famID).add(sample);
}
}
}
return families;
}
/**
* Return all samples with a given family ID
* @param familyId
* @return
*/
public Set<Sample> getFamily(String familyId) {
return getFamilies().get(familyId);
}
/**
* Returns all children of a given sample
* See note on the efficiency of getFamily() - since this depends on getFamily() it's also not efficient
* @param sample
* @return
*/
public Set<Sample> getChildren(Sample sample) {
final HashSet<Sample> children = new HashSet<Sample>();
for ( final Sample familyMember : getFamily(sample.getFamilyID())) {
if ( familyMember.getMother() == sample || familyMember.getFather() == sample ) {
children.add(familyMember);
}
}
return children;
}
}
| true | true | public final Map<String, Set<Sample>> getFamilies(Collection<String> sampleIds) {
final Map<String, Set<Sample>> families = new TreeMap<String, Set<Sample>>();
for ( final Sample sample : samples.values() ) {
if(sampleIds != null && sampleIds.contains(sample.getID())){
final String famID = sample.getFamilyID();
if ( famID != null ) {
if ( ! families.containsKey(famID) )
families.put(famID, new TreeSet<Sample>());
families.get(famID).add(sample);
}
}
}
return families;
}
| public final Map<String, Set<Sample>> getFamilies(Collection<String> sampleIds) {
final Map<String, Set<Sample>> families = new TreeMap<String, Set<Sample>>();
for ( final Sample sample : samples.values() ) {
if(sampleIds == null || sampleIds.contains(sample.getID())){
final String famID = sample.getFamilyID();
if ( famID != null ) {
if ( ! families.containsKey(famID) )
families.put(famID, new TreeSet<Sample>());
families.get(famID).add(sample);
}
}
}
return families;
}
|
diff --git a/src/com/android/contacts/quickcontact/QuickContactActivity.java b/src/com/android/contacts/quickcontact/QuickContactActivity.java
index 15e119bbe..c7d6e5169 100644
--- a/src/com/android/contacts/quickcontact/QuickContactActivity.java
+++ b/src/com/android/contacts/quickcontact/QuickContactActivity.java
@@ -1,766 +1,770 @@
/*
* 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.contacts.quickcontact;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ActivityNotFoundException;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.SipAddress;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.CommonDataKinds.Website;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.DisplayNameSources;
import android.provider.ContactsContract.Intents.Insert;
import android.provider.ContactsContract.Directory;
import android.provider.ContactsContract.QuickContact;
import android.provider.ContactsContract.RawContacts;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.contacts.ContactSaveService;
import com.android.contacts.common.Collapser;
import com.android.contacts.R;
import com.android.contacts.common.model.AccountTypeManager;
import com.android.contacts.model.Contact;
import com.android.contacts.model.ContactLoader;
import com.android.contacts.model.RawContact;
import com.android.contacts.common.model.account.AccountType;
import com.android.contacts.model.dataitem.DataItem;
import com.android.contacts.common.model.dataitem.DataKind;
import com.android.contacts.model.dataitem.EmailDataItem;
import com.android.contacts.model.dataitem.ImDataItem;
import com.android.contacts.common.util.Constants;
import com.android.contacts.common.util.UriUtils;
import com.android.contacts.util.DataStatus;
import com.android.contacts.util.ImageViewDrawableSetter;
import com.android.contacts.util.SchedulingUtils;
import com.android.contacts.common.util.StopWatch;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
// TODO: Save selected tab index during rotation
/**
* Mostly translucent {@link Activity} that shows QuickContact dialog. It loads
* data asynchronously, and then shows a popup with details centered around
* {@link Intent#getSourceBounds()}.
*/
public class QuickContactActivity extends Activity {
private static final String TAG = "QuickContact";
private static final boolean TRACE_LAUNCH = false;
private static final String TRACE_TAG = "quickcontact";
private static final int POST_DRAW_WAIT_DURATION = 60;
private static final boolean ENABLE_STOPWATCH = false;
@SuppressWarnings("deprecation")
private static final String LEGACY_AUTHORITY = android.provider.Contacts.AUTHORITY;
private Uri mLookupUri;
private String[] mExcludeMimes;
private List<String> mSortedActionMimeTypes = Lists.newArrayList();
private FloatingChildLayout mFloatingLayout;
private View mPhotoContainer;
private ViewGroup mTrack;
private HorizontalScrollView mTrackScroller;
private View mSelectedTabRectangle;
private View mLineAfterTrack;
private ImageView mPhotoView;
private ImageView mOpenDetailsOrAddContactImage;
private ImageView mStarImage;
private ViewPager mListPager;
private ViewPagerAdapter mPagerAdapter;
private Contact mContactData;
private ContactLoader mContactLoader;
private final ImageViewDrawableSetter mPhotoSetter = new ImageViewDrawableSetter();
/**
* Keeps the default action per mimetype. Empty if no default actions are set
*/
private HashMap<String, Action> mDefaultsMap = new HashMap<String, Action>();
/**
* Set of {@link Action} that are associated with the aggregate currently
* displayed by this dialog, represented as a map from {@link String}
* MIME-type to a list of {@link Action}.
*/
private ActionMultiMap mActions = new ActionMultiMap();
/**
* {@link #LEADING_MIMETYPES} and {@link #TRAILING_MIMETYPES} are used to sort MIME-types.
*
* <p>The MIME-types in {@link #LEADING_MIMETYPES} appear in the front of the dialog,
* in the order specified here.</p>
*
* <p>The ones in {@link #TRAILING_MIMETYPES} appear in the end of the dialog, in the order
* specified here.</p>
*
* <p>The rest go between them, in the order in the array.</p>
*/
private static final List<String> LEADING_MIMETYPES = Lists.newArrayList(
Phone.CONTENT_ITEM_TYPE, SipAddress.CONTENT_ITEM_TYPE, Email.CONTENT_ITEM_TYPE);
/** See {@link #LEADING_MIMETYPES}. */
private static final List<String> TRAILING_MIMETYPES = Lists.newArrayList(
StructuredPostal.CONTENT_ITEM_TYPE, Website.CONTENT_ITEM_TYPE);
/** Id for the background loader */
private static final int LOADER_ID = 0;
private StopWatch mStopWatch = ENABLE_STOPWATCH
? StopWatch.start("QuickContact") : StopWatch.getNullStopWatch();
final OnClickListener mOpenDetailsClickHandler = new OnClickListener() {
@Override
public void onClick(View v) {
final Intent intent = new Intent(Intent.ACTION_VIEW, mLookupUri);
mContactLoader.cacheResult();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);
close(false);
}
};
final OnClickListener mAddToContactsClickHandler = new OnClickListener() {
@Override
public void onClick(View v) {
if (mContactData == null) {
Log.e(TAG, "Empty contact data when trying to add to contact");
return;
}
final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType(Contacts.CONTENT_ITEM_TYPE);
// Only pre-fill the name field if the provided display name is an organization
// name or better (e.g. structured name, nickname)
if (mContactData.getDisplayNameSource() >= DisplayNameSources.ORGANIZATION) {
intent.putExtra(Insert.NAME, mContactData.getDisplayName());
}
intent.putExtra(Insert.DATA, mContactData.getContentValues());
startActivity(intent);
}
};
@Override
protected void onCreate(Bundle icicle) {
mStopWatch.lap("c"); // create start
super.onCreate(icicle);
mStopWatch.lap("sc"); // super.onCreate
if (TRACE_LAUNCH) android.os.Debug.startMethodTracing(TRACE_TAG);
// Parse intent
final Intent intent = getIntent();
Uri lookupUri = intent.getData();
// Check to see whether it comes from the old version.
if (lookupUri != null && LEGACY_AUTHORITY.equals(lookupUri.getAuthority())) {
final long rawContactId = ContentUris.parseId(lookupUri);
lookupUri = RawContacts.getContactLookupUri(getContentResolver(),
ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId));
}
mLookupUri = Preconditions.checkNotNull(lookupUri, "missing lookupUri");
mExcludeMimes = intent.getStringArrayExtra(QuickContact.EXTRA_EXCLUDE_MIMES);
mStopWatch.lap("i"); // intent parsed
mContactLoader = (ContactLoader) getLoaderManager().initLoader(
LOADER_ID, null, mLoaderCallbacks);
mStopWatch.lap("ld"); // loader started
// Show QuickContact in front of soft input
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
setContentView(R.layout.quickcontact_activity);
mStopWatch.lap("l"); // layout inflated
mFloatingLayout = (FloatingChildLayout) findViewById(R.id.floating_layout);
mTrack = (ViewGroup) findViewById(R.id.track);
mTrackScroller = (HorizontalScrollView) findViewById(R.id.track_scroller);
mOpenDetailsOrAddContactImage = (ImageView) findViewById(R.id.contact_details_image);
mStarImage = (ImageView) findViewById(R.id.quickcontact_star_button);
mListPager = (ViewPager) findViewById(R.id.item_list_pager);
mSelectedTabRectangle = findViewById(R.id.selected_tab_rectangle);
mLineAfterTrack = findViewById(R.id.line_after_track);
mFloatingLayout.setOnOutsideTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
handleOutsideTouch();
return true;
}
});
mOpenDetailsOrAddContactImage.setOnClickListener(mOpenDetailsClickHandler);
mPagerAdapter = new ViewPagerAdapter(getFragmentManager());
mListPager.setAdapter(mPagerAdapter);
mListPager.setOnPageChangeListener(new PageChangeListener());
final Rect sourceBounds = intent.getSourceBounds();
if (sourceBounds != null) {
mFloatingLayout.setChildTargetScreen(sourceBounds);
}
// find and prepare correct header view
mPhotoContainer = findViewById(R.id.photo_container);
setHeaderNameText(R.id.name, R.string.missing_name);
mPhotoView = (ImageView) mPhotoContainer.findViewById(R.id.photo);
mPhotoView.setOnClickListener(mOpenDetailsClickHandler);
mStopWatch.lap("v"); // view initialized
SchedulingUtils.doAfterLayout(mFloatingLayout, new Runnable() {
@Override
public void run() {
mFloatingLayout.fadeInBackground();
}
});
mStopWatch.lap("cf"); // onCreate finished
}
private void handleOutsideTouch() {
if (mFloatingLayout.isContentFullyVisible()) {
close(true);
}
}
private void close(boolean withAnimation) {
// cancel any pending queries
getLoaderManager().destroyLoader(LOADER_ID);
if (withAnimation) {
mFloatingLayout.fadeOutBackground();
final boolean animated = mFloatingLayout.hideContent(new Runnable() {
@Override
public void run() {
// Wait until the final animation frame has been drawn, otherwise
// there is jank as the framework transitions to the next Activity.
SchedulingUtils.doAfterDraw(mFloatingLayout, new Runnable() {
@Override
public void run() {
// Unfortunately, we need to also use postDelayed() to wait a moment
// for the frame to be drawn, else the framework's activity-transition
// animation will kick in before the final frame is available to it.
// This seems unavoidable. The problem isn't merely that there is no
// post-draw listener API; if that were so, it would be sufficient to
// call post() instead of postDelayed().
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, POST_DRAW_WAIT_DURATION);
}
});
}
});
if (!animated) {
// If we were in the wrong state, simply quit (this can happen for example
// if the user pushes BACK before anything has loaded)
finish();
}
} else {
finish();
}
}
@Override
public void onBackPressed() {
close(true);
}
/** Assign this string to the view if it is not empty. */
private void setHeaderNameText(int id, int resId) {
setHeaderNameText(id, getText(resId));
}
/** Assign this string to the view if it is not empty. */
private void setHeaderNameText(int id, CharSequence value) {
final View view = mPhotoContainer.findViewById(id);
if (view instanceof TextView) {
if (!TextUtils.isEmpty(value)) {
((TextView)view).setText(value);
}
}
}
/**
* Check if the given MIME-type appears in the list of excluded MIME-types
* that the most-recent caller requested.
*/
private boolean isMimeExcluded(String mimeType) {
if (mExcludeMimes == null) return false;
for (String excludedMime : mExcludeMimes) {
if (TextUtils.equals(excludedMime, mimeType)) {
return true;
}
}
return false;
}
/**
* Handle the result from the ContactLoader
*/
private void bindData(Contact data) {
mContactData = data;
final ResolveCache cache = ResolveCache.getInstance(this);
final Context context = this;
mOpenDetailsOrAddContactImage.setVisibility(isMimeExcluded(Contacts.CONTENT_ITEM_TYPE) ?
View.GONE : View.VISIBLE);
final boolean isStarred = data.getStarred();
if (isStarred) {
mStarImage.setImageResource(R.drawable.ic_favorite_on_lt);
+ mStarImage.setContentDescription(
+ getResources().getString(R.string.menu_removeStar));
} else {
mStarImage.setImageResource(R.drawable.ic_favorite_off_lt);
+ mStarImage.setContentDescription(
+ getResources().getString(R.string.menu_addStar));
}
final Uri lookupUri = data.getLookupUri();
// If this is a json encoded URI, there is no local contact to star
if (UriUtils.isEncodedContactUri(lookupUri)) {
mStarImage.setVisibility(View.GONE);
// If directory export support is not allowed, then don't allow the user to add
// to contacts
if (mContactData.getDirectoryExportSupport() == Directory.EXPORT_SUPPORT_NONE) {
configureHeaderClickActions(false);
} else {
configureHeaderClickActions(true);
}
} else {
configureHeaderClickActions(false);
mStarImage.setVisibility(View.VISIBLE);
mStarImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// Toggle "starred" state
// Make sure there is a contact
if (lookupUri != null) {
// Changes the state of the image already before sending updates to the
// database
if (isStarred) {
mStarImage.setImageResource(R.drawable.ic_favorite_off_lt);
} else {
mStarImage.setImageResource(R.drawable.ic_favorite_on_lt);
}
// Now perform the real save
final Intent intent = ContactSaveService.createSetStarredIntent(context,
lookupUri, !isStarred);
context.startService(intent);
}
}
});
}
mDefaultsMap.clear();
mStopWatch.lap("sph"); // Start photo setting
mPhotoSetter.setupContactPhoto(data, mPhotoView);
mStopWatch.lap("ph"); // Photo set
for (RawContact rawContact : data.getRawContacts()) {
for (DataItem dataItem : rawContact.getDataItems()) {
final String mimeType = dataItem.getMimeType();
final AccountType accountType = rawContact.getAccountType(this);
final DataKind dataKind = AccountTypeManager.getInstance(this)
.getKindOrFallback(accountType, mimeType);
// Skip this data item if MIME-type excluded
if (isMimeExcluded(mimeType)) continue;
final long dataId = dataItem.getId();
final boolean isPrimary = dataItem.isPrimary();
final boolean isSuperPrimary = dataItem.isSuperPrimary();
if (dataKind != null) {
// Build an action for this data entry, find a mapping to a UI
// element, build its summary from the cursor, and collect it
// along with all others of this MIME-type.
final Action action = new DataAction(context, dataItem, dataKind);
final boolean wasAdded = considerAdd(action, cache, isSuperPrimary);
if (wasAdded) {
// Remember the default
if (isSuperPrimary || (isPrimary && (mDefaultsMap.get(mimeType) == null))) {
mDefaultsMap.put(mimeType, action);
}
}
}
// Handle Email rows with presence data as Im entry
final DataStatus status = data.getStatuses().get(dataId);
if (status != null && dataItem instanceof EmailDataItem) {
final EmailDataItem email = (EmailDataItem) dataItem;
final ImDataItem im = ImDataItem.createFromEmail(email);
if (dataKind != null) {
final DataAction action = new DataAction(context, im, dataKind);
action.setPresence(status.getPresence());
considerAdd(action, cache, isSuperPrimary);
}
}
}
}
mStopWatch.lap("e"); // Entities inflated
// Collapse Action Lists (remove e.g. duplicate e-mail addresses from different sources)
for (List<Action> actionChildren : mActions.values()) {
Collapser.collapseList(actionChildren);
}
mStopWatch.lap("c"); // List collapsed
setHeaderNameText(R.id.name, data.getDisplayName());
// All the mime-types to add.
final Set<String> containedTypes = new HashSet<String>(mActions.keySet());
mSortedActionMimeTypes.clear();
// First, add LEADING_MIMETYPES, which are most common.
for (String mimeType : LEADING_MIMETYPES) {
if (containedTypes.contains(mimeType)) {
mSortedActionMimeTypes.add(mimeType);
containedTypes.remove(mimeType);
}
}
// Add all the remaining ones that are not TRAILING
for (String mimeType : containedTypes.toArray(new String[containedTypes.size()])) {
if (!TRAILING_MIMETYPES.contains(mimeType)) {
mSortedActionMimeTypes.add(mimeType);
containedTypes.remove(mimeType);
}
}
// Then, add TRAILING_MIMETYPES, which are least common.
for (String mimeType : TRAILING_MIMETYPES) {
if (containedTypes.contains(mimeType)) {
containedTypes.remove(mimeType);
mSortedActionMimeTypes.add(mimeType);
}
}
mPagerAdapter.notifyDataSetChanged();
mStopWatch.lap("mt"); // Mime types initialized
// Add buttons for each mimetype
mTrack.removeAllViews();
for (String mimeType : mSortedActionMimeTypes) {
final View actionView = inflateAction(mimeType, cache, mTrack, data.getDisplayName());
mTrack.addView(actionView);
}
mStopWatch.lap("mt"); // Buttons added
final boolean hasData = !mSortedActionMimeTypes.isEmpty();
mTrackScroller.setVisibility(hasData ? View.VISIBLE : View.GONE);
mSelectedTabRectangle.setVisibility(hasData ? View.VISIBLE : View.GONE);
mLineAfterTrack.setVisibility(hasData ? View.VISIBLE : View.GONE);
mListPager.setVisibility(hasData ? View.VISIBLE : View.GONE);
}
/**
* Consider adding the given {@link Action}, which will only happen if
* {@link PackageManager} finds an application to handle
* {@link Action#getIntent()}.
* @param action the action to handle
* @param resolveCache cache of applications that can handle actions
* @param front indicates whether to add the action to the front of the list
* @return true if action has been added
*/
private boolean considerAdd(Action action, ResolveCache resolveCache, boolean front) {
if (resolveCache.hasResolve(action)) {
mActions.put(action.getMimeType(), action, front);
return true;
}
return false;
}
/**
* Bind the correct image resource and click handlers to the header views
*
* @param canAdd Whether or not the user can directly add information in this quick contact
* to their local contacts
*/
private void configureHeaderClickActions(boolean canAdd) {
if (canAdd) {
mOpenDetailsOrAddContactImage.setImageResource(R.drawable.ic_add_contact_holo_dark);
mOpenDetailsOrAddContactImage.setOnClickListener(mAddToContactsClickHandler);
mPhotoView.setOnClickListener(mAddToContactsClickHandler);
} else {
mOpenDetailsOrAddContactImage.setImageResource(R.drawable.ic_contacts_holo_dark);
mOpenDetailsOrAddContactImage.setOnClickListener(mOpenDetailsClickHandler);
mPhotoView.setOnClickListener(mOpenDetailsClickHandler);
}
}
/**
* Inflate the in-track view for the action of the given MIME-type, collapsing duplicate values.
* Will use the icon provided by the {@link DataKind}.
*/
private View inflateAction(String mimeType, ResolveCache resolveCache,
ViewGroup root, String name) {
final CheckableImageView typeView = (CheckableImageView) getLayoutInflater().inflate(
R.layout.quickcontact_track_button, root, false);
List<Action> children = mActions.get(mimeType);
typeView.setTag(mimeType);
final Action firstInfo = children.get(0);
// Set icon and listen for clicks
final CharSequence descrip = resolveCache.getDescription(firstInfo, name);
final Drawable icon = resolveCache.getIcon(firstInfo);
typeView.setChecked(false);
typeView.setContentDescription(descrip);
typeView.setImageDrawable(icon);
typeView.setOnClickListener(mTypeViewClickListener);
return typeView;
}
private CheckableImageView getActionViewAt(int position) {
return (CheckableImageView) mTrack.getChildAt(position);
}
@Override
public void onAttachFragment(Fragment fragment) {
final QuickContactListFragment listFragment = (QuickContactListFragment) fragment;
listFragment.setListener(mListFragmentListener);
}
private LoaderCallbacks<Contact> mLoaderCallbacks =
new LoaderCallbacks<Contact>() {
@Override
public void onLoaderReset(Loader<Contact> loader) {
}
@Override
public void onLoadFinished(Loader<Contact> loader, Contact data) {
mStopWatch.lap("lf"); // onLoadFinished
if (isFinishing()) {
close(false);
return;
}
if (data.isError()) {
// This shouldn't ever happen, so throw an exception. The {@link ContactLoader}
// should log the actual exception.
throw new IllegalStateException("Failed to load contact", data.getException());
}
if (data.isNotFound()) {
Log.i(TAG, "No contact found: " + ((ContactLoader)loader).getLookupUri());
Toast.makeText(QuickContactActivity.this, R.string.invalidContactMessage,
Toast.LENGTH_LONG).show();
close(false);
return;
}
bindData(data);
mStopWatch.lap("bd"); // bindData finished
if (TRACE_LAUNCH) android.os.Debug.stopMethodTracing();
if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
Log.d(Constants.PERFORMANCE_TAG, "QuickContact shown");
}
// Data bound and ready, pull curtain to show. Put this on the Handler to ensure
// that the layout passes are completed
SchedulingUtils.doAfterLayout(mFloatingLayout, new Runnable() {
@Override
public void run() {
mFloatingLayout.showContent(new Runnable() {
@Override
public void run() {
mContactLoader.upgradeToFullContact();
}
});
}
});
mStopWatch.stopAndLog(TAG, 0);
mStopWatch = StopWatch.getNullStopWatch(); // We're done with it.
}
@Override
public Loader<Contact> onCreateLoader(int id, Bundle args) {
if (mLookupUri == null) {
Log.wtf(TAG, "Lookup uri wasn't initialized. Loader was started too early");
}
return new ContactLoader(getApplicationContext(), mLookupUri,
false /*loadGroupMetaData*/, false /*loadInvitableAccountTypes*/,
false /*postViewNotification*/, true /*computeFormattedPhoneNumber*/);
}
};
/** A type (e.g. Call/Addresses was clicked) */
private final OnClickListener mTypeViewClickListener = new OnClickListener() {
@Override
public void onClick(View view) {
final CheckableImageView actionView = (CheckableImageView)view;
final String mimeType = (String) actionView.getTag();
int index = mSortedActionMimeTypes.indexOf(mimeType);
mListPager.setCurrentItem(index, true);
}
};
private class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public Fragment getItem(int position) {
final String mimeType = mSortedActionMimeTypes.get(position);
QuickContactListFragment fragment = new QuickContactListFragment(mimeType);
final List<Action> actions = mActions.get(mimeType);
fragment.setActions(actions);
return fragment;
}
@Override
public int getCount() {
return mSortedActionMimeTypes.size();
}
@Override
public int getItemPosition(Object object) {
final QuickContactListFragment fragment = (QuickContactListFragment) object;
final String mimeType = fragment.getMimeType();
for (int i = 0; i < mSortedActionMimeTypes.size(); i++) {
if (mimeType.equals(mSortedActionMimeTypes.get(i))) {
return i;
}
}
return PagerAdapter.POSITION_NONE;
}
}
private class PageChangeListener extends SimpleOnPageChangeListener {
private int mScrollingState = ViewPager.SCROLL_STATE_IDLE;
@Override
public void onPageSelected(int position) {
final CheckableImageView actionView = getActionViewAt(position);
mTrackScroller.requestChildRectangleOnScreen(actionView,
new Rect(0, 0, actionView.getWidth(), actionView.getHeight()), false);
// Don't render rectangle if we are currently scrolling to prevent it from flickering
if (mScrollingState == ViewPager.SCROLL_STATE_IDLE) {
renderSelectedRectangle(position, 0);
}
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
mScrollingState = state;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
renderSelectedRectangle(position, positionOffset);
}
private void renderSelectedRectangle(int position, float positionOffset) {
final RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) mSelectedTabRectangle.getLayoutParams();
final int width = layoutParams.width;
layoutParams.setMarginStart((int) ((position + positionOffset) * width));
mSelectedTabRectangle.setLayoutParams(layoutParams);
}
}
private final QuickContactListFragment.Listener mListFragmentListener =
new QuickContactListFragment.Listener() {
@Override
public void onOutsideClick() {
// If there is no background, we want to dismiss, because to the user it seems
// like he had touched outside. If the ViewPager is solid however, those taps
// must be ignored
final boolean isTransparent = mListPager.getBackground() == null;
if (isTransparent) handleOutsideTouch();
}
@Override
public void onItemClicked(final Action action, final boolean alternate) {
final Runnable startAppRunnable = new Runnable() {
@Override
public void run() {
try {
startActivity(alternate ? action.getAlternateIntent() : action.getIntent());
} catch (ActivityNotFoundException e) {
Toast.makeText(QuickContactActivity.this, R.string.quickcontact_missing_app,
Toast.LENGTH_SHORT).show();
}
close(false);
}
};
// Defer the action to make the window properly repaint
new Handler().post(startAppRunnable);
}
};
}
| false | true | private void bindData(Contact data) {
mContactData = data;
final ResolveCache cache = ResolveCache.getInstance(this);
final Context context = this;
mOpenDetailsOrAddContactImage.setVisibility(isMimeExcluded(Contacts.CONTENT_ITEM_TYPE) ?
View.GONE : View.VISIBLE);
final boolean isStarred = data.getStarred();
if (isStarred) {
mStarImage.setImageResource(R.drawable.ic_favorite_on_lt);
} else {
mStarImage.setImageResource(R.drawable.ic_favorite_off_lt);
}
final Uri lookupUri = data.getLookupUri();
// If this is a json encoded URI, there is no local contact to star
if (UriUtils.isEncodedContactUri(lookupUri)) {
mStarImage.setVisibility(View.GONE);
// If directory export support is not allowed, then don't allow the user to add
// to contacts
if (mContactData.getDirectoryExportSupport() == Directory.EXPORT_SUPPORT_NONE) {
configureHeaderClickActions(false);
} else {
configureHeaderClickActions(true);
}
} else {
configureHeaderClickActions(false);
mStarImage.setVisibility(View.VISIBLE);
mStarImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// Toggle "starred" state
// Make sure there is a contact
if (lookupUri != null) {
// Changes the state of the image already before sending updates to the
// database
if (isStarred) {
mStarImage.setImageResource(R.drawable.ic_favorite_off_lt);
} else {
mStarImage.setImageResource(R.drawable.ic_favorite_on_lt);
}
// Now perform the real save
final Intent intent = ContactSaveService.createSetStarredIntent(context,
lookupUri, !isStarred);
context.startService(intent);
}
}
});
}
mDefaultsMap.clear();
mStopWatch.lap("sph"); // Start photo setting
mPhotoSetter.setupContactPhoto(data, mPhotoView);
mStopWatch.lap("ph"); // Photo set
for (RawContact rawContact : data.getRawContacts()) {
for (DataItem dataItem : rawContact.getDataItems()) {
final String mimeType = dataItem.getMimeType();
final AccountType accountType = rawContact.getAccountType(this);
final DataKind dataKind = AccountTypeManager.getInstance(this)
.getKindOrFallback(accountType, mimeType);
// Skip this data item if MIME-type excluded
if (isMimeExcluded(mimeType)) continue;
final long dataId = dataItem.getId();
final boolean isPrimary = dataItem.isPrimary();
final boolean isSuperPrimary = dataItem.isSuperPrimary();
if (dataKind != null) {
// Build an action for this data entry, find a mapping to a UI
// element, build its summary from the cursor, and collect it
// along with all others of this MIME-type.
final Action action = new DataAction(context, dataItem, dataKind);
final boolean wasAdded = considerAdd(action, cache, isSuperPrimary);
if (wasAdded) {
// Remember the default
if (isSuperPrimary || (isPrimary && (mDefaultsMap.get(mimeType) == null))) {
mDefaultsMap.put(mimeType, action);
}
}
}
// Handle Email rows with presence data as Im entry
final DataStatus status = data.getStatuses().get(dataId);
if (status != null && dataItem instanceof EmailDataItem) {
final EmailDataItem email = (EmailDataItem) dataItem;
final ImDataItem im = ImDataItem.createFromEmail(email);
if (dataKind != null) {
final DataAction action = new DataAction(context, im, dataKind);
action.setPresence(status.getPresence());
considerAdd(action, cache, isSuperPrimary);
}
}
}
}
mStopWatch.lap("e"); // Entities inflated
// Collapse Action Lists (remove e.g. duplicate e-mail addresses from different sources)
for (List<Action> actionChildren : mActions.values()) {
Collapser.collapseList(actionChildren);
}
mStopWatch.lap("c"); // List collapsed
setHeaderNameText(R.id.name, data.getDisplayName());
// All the mime-types to add.
final Set<String> containedTypes = new HashSet<String>(mActions.keySet());
mSortedActionMimeTypes.clear();
// First, add LEADING_MIMETYPES, which are most common.
for (String mimeType : LEADING_MIMETYPES) {
if (containedTypes.contains(mimeType)) {
mSortedActionMimeTypes.add(mimeType);
containedTypes.remove(mimeType);
}
}
// Add all the remaining ones that are not TRAILING
for (String mimeType : containedTypes.toArray(new String[containedTypes.size()])) {
if (!TRAILING_MIMETYPES.contains(mimeType)) {
mSortedActionMimeTypes.add(mimeType);
containedTypes.remove(mimeType);
}
}
// Then, add TRAILING_MIMETYPES, which are least common.
for (String mimeType : TRAILING_MIMETYPES) {
if (containedTypes.contains(mimeType)) {
containedTypes.remove(mimeType);
mSortedActionMimeTypes.add(mimeType);
}
}
mPagerAdapter.notifyDataSetChanged();
mStopWatch.lap("mt"); // Mime types initialized
// Add buttons for each mimetype
mTrack.removeAllViews();
for (String mimeType : mSortedActionMimeTypes) {
final View actionView = inflateAction(mimeType, cache, mTrack, data.getDisplayName());
mTrack.addView(actionView);
}
mStopWatch.lap("mt"); // Buttons added
final boolean hasData = !mSortedActionMimeTypes.isEmpty();
mTrackScroller.setVisibility(hasData ? View.VISIBLE : View.GONE);
mSelectedTabRectangle.setVisibility(hasData ? View.VISIBLE : View.GONE);
mLineAfterTrack.setVisibility(hasData ? View.VISIBLE : View.GONE);
mListPager.setVisibility(hasData ? View.VISIBLE : View.GONE);
}
| private void bindData(Contact data) {
mContactData = data;
final ResolveCache cache = ResolveCache.getInstance(this);
final Context context = this;
mOpenDetailsOrAddContactImage.setVisibility(isMimeExcluded(Contacts.CONTENT_ITEM_TYPE) ?
View.GONE : View.VISIBLE);
final boolean isStarred = data.getStarred();
if (isStarred) {
mStarImage.setImageResource(R.drawable.ic_favorite_on_lt);
mStarImage.setContentDescription(
getResources().getString(R.string.menu_removeStar));
} else {
mStarImage.setImageResource(R.drawable.ic_favorite_off_lt);
mStarImage.setContentDescription(
getResources().getString(R.string.menu_addStar));
}
final Uri lookupUri = data.getLookupUri();
// If this is a json encoded URI, there is no local contact to star
if (UriUtils.isEncodedContactUri(lookupUri)) {
mStarImage.setVisibility(View.GONE);
// If directory export support is not allowed, then don't allow the user to add
// to contacts
if (mContactData.getDirectoryExportSupport() == Directory.EXPORT_SUPPORT_NONE) {
configureHeaderClickActions(false);
} else {
configureHeaderClickActions(true);
}
} else {
configureHeaderClickActions(false);
mStarImage.setVisibility(View.VISIBLE);
mStarImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// Toggle "starred" state
// Make sure there is a contact
if (lookupUri != null) {
// Changes the state of the image already before sending updates to the
// database
if (isStarred) {
mStarImage.setImageResource(R.drawable.ic_favorite_off_lt);
} else {
mStarImage.setImageResource(R.drawable.ic_favorite_on_lt);
}
// Now perform the real save
final Intent intent = ContactSaveService.createSetStarredIntent(context,
lookupUri, !isStarred);
context.startService(intent);
}
}
});
}
mDefaultsMap.clear();
mStopWatch.lap("sph"); // Start photo setting
mPhotoSetter.setupContactPhoto(data, mPhotoView);
mStopWatch.lap("ph"); // Photo set
for (RawContact rawContact : data.getRawContacts()) {
for (DataItem dataItem : rawContact.getDataItems()) {
final String mimeType = dataItem.getMimeType();
final AccountType accountType = rawContact.getAccountType(this);
final DataKind dataKind = AccountTypeManager.getInstance(this)
.getKindOrFallback(accountType, mimeType);
// Skip this data item if MIME-type excluded
if (isMimeExcluded(mimeType)) continue;
final long dataId = dataItem.getId();
final boolean isPrimary = dataItem.isPrimary();
final boolean isSuperPrimary = dataItem.isSuperPrimary();
if (dataKind != null) {
// Build an action for this data entry, find a mapping to a UI
// element, build its summary from the cursor, and collect it
// along with all others of this MIME-type.
final Action action = new DataAction(context, dataItem, dataKind);
final boolean wasAdded = considerAdd(action, cache, isSuperPrimary);
if (wasAdded) {
// Remember the default
if (isSuperPrimary || (isPrimary && (mDefaultsMap.get(mimeType) == null))) {
mDefaultsMap.put(mimeType, action);
}
}
}
// Handle Email rows with presence data as Im entry
final DataStatus status = data.getStatuses().get(dataId);
if (status != null && dataItem instanceof EmailDataItem) {
final EmailDataItem email = (EmailDataItem) dataItem;
final ImDataItem im = ImDataItem.createFromEmail(email);
if (dataKind != null) {
final DataAction action = new DataAction(context, im, dataKind);
action.setPresence(status.getPresence());
considerAdd(action, cache, isSuperPrimary);
}
}
}
}
mStopWatch.lap("e"); // Entities inflated
// Collapse Action Lists (remove e.g. duplicate e-mail addresses from different sources)
for (List<Action> actionChildren : mActions.values()) {
Collapser.collapseList(actionChildren);
}
mStopWatch.lap("c"); // List collapsed
setHeaderNameText(R.id.name, data.getDisplayName());
// All the mime-types to add.
final Set<String> containedTypes = new HashSet<String>(mActions.keySet());
mSortedActionMimeTypes.clear();
// First, add LEADING_MIMETYPES, which are most common.
for (String mimeType : LEADING_MIMETYPES) {
if (containedTypes.contains(mimeType)) {
mSortedActionMimeTypes.add(mimeType);
containedTypes.remove(mimeType);
}
}
// Add all the remaining ones that are not TRAILING
for (String mimeType : containedTypes.toArray(new String[containedTypes.size()])) {
if (!TRAILING_MIMETYPES.contains(mimeType)) {
mSortedActionMimeTypes.add(mimeType);
containedTypes.remove(mimeType);
}
}
// Then, add TRAILING_MIMETYPES, which are least common.
for (String mimeType : TRAILING_MIMETYPES) {
if (containedTypes.contains(mimeType)) {
containedTypes.remove(mimeType);
mSortedActionMimeTypes.add(mimeType);
}
}
mPagerAdapter.notifyDataSetChanged();
mStopWatch.lap("mt"); // Mime types initialized
// Add buttons for each mimetype
mTrack.removeAllViews();
for (String mimeType : mSortedActionMimeTypes) {
final View actionView = inflateAction(mimeType, cache, mTrack, data.getDisplayName());
mTrack.addView(actionView);
}
mStopWatch.lap("mt"); // Buttons added
final boolean hasData = !mSortedActionMimeTypes.isEmpty();
mTrackScroller.setVisibility(hasData ? View.VISIBLE : View.GONE);
mSelectedTabRectangle.setVisibility(hasData ? View.VISIBLE : View.GONE);
mLineAfterTrack.setVisibility(hasData ? View.VISIBLE : View.GONE);
mListPager.setVisibility(hasData ? View.VISIBLE : View.GONE);
}
|
diff --git a/src/com/pentacog/mctracker/GetServerDataTask.java b/src/com/pentacog/mctracker/GetServerDataTask.java
index c39a63e..c0432eb 100644
--- a/src/com/pentacog/mctracker/GetServerDataTask.java
+++ b/src/com/pentacog/mctracker/GetServerDataTask.java
@@ -1,157 +1,157 @@
/*
* This work is licensed under the Creative Commons Attribution-NonCommercial 3.0 New Zealand License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by-nc/3.0/nz/ or send a
* letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
*/
package com.pentacog.mctracker;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import android.os.AsyncTask;
import android.util.Log;
/**
* @author Affian
*
*/
public class GetServerDataTask extends AsyncTask<Void, Void, String> {
private static final int SOCKET_TIMEOUT = 10000;
private Server server = null;
private ServerDataResultHandler handler = null;
/**
*
*/
public GetServerDataTask(Server server, ServerDataResultHandler handler) {
this.server = server;
this.handler = handler;
}
/**
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected String doInBackground(Void... params) {
String error = null;
String message = "";
short stringLen = -1;
try {
long requestTime = 0;
String[] parts = null;
byte[] bytes = new byte[256];
Socket sock = new Socket(server.address, server.port);
sock.setSoTimeout(SOCKET_TIMEOUT);
OutputStream os = sock.getOutputStream();
InputStream is = sock.getInputStream();
requestTime = System.currentTimeMillis();
os.write(MCServerTrackerActivity.PACKET_REQUEST_CODE);
is.read(bytes);
if (requestTime > SOCKET_TIMEOUT)
requestTime = System.currentTimeMillis() - requestTime;
ByteBuffer b = ByteBuffer.wrap(bytes);
b.get(); //remove first byte
stringLen = b.getShort();
byte[] stringData = new byte[Math.min(stringLen * 2, 253)];
b.get(stringData);
try {
message = new String(stringData, "UTF-16BE");
} catch (UnsupportedEncodingException e) {
//Nothing I can really do here
}
//Experimental multi-packet support
// while (is.read(bytes) != -1) {
// //if requestTime hasn't be calculated yet
// if (requestTime > SOCKET_TIMEOUT)
// requestTime = System.currentTimeMillis() - requestTime;
//
// ByteBuffer b = ByteBuffer.wrap(bytes);
// b.get(); //remove first byte
// short stringLen = b.getShort();
// byte[] stringData = new byte[stringLen * 2];
// b.get(stringData);
//
// try {
// message += new String(stringData, "UTF-16BE");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// }
sock.close();
parts = message.split("\u00A7");
if (parts.length == 3) {
server.motd = parts[0];
server.playerCount = Integer.parseInt(parts[1]);
server.maxPlayers = Integer.parseInt(parts[2]);
server.ping = (int)requestTime;
} else {
throw new IllegalArgumentException();
}
} catch (IOException e) {
if (e instanceof SocketTimeoutException) {
error = "Connection timed out";
} else if (e instanceof UnknownHostException) {
error = "Unable to resolve DNS";
} else if (e.getMessage().endsWith("Connection refused")) {
error = "Connection refused";
} else {
error = e.getMessage();
}
} catch (IllegalArgumentException e) {
error = "Communication error";
- Log.d("MCT", "Communication error: \"" + message + "\". Message Length: " + stringLen);
- Log.d("MCT", server.toString());
+// Log.d("MCT", "Communication error: \"" + message + "\". Message Length: " + stringLen);
+// Log.d("MCT", server.toString());
}
server.queried = true;
if (error != null) {
server.motd = MCServerTrackerActivity.ERROR_CHAR + error;
}
return error;
}
/**
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
handler.onServerDataResult(server, result);
super.onPostExecute(result);
}
public interface ServerDataResultHandler {
public void onServerDataResult(Server server, String result);
}
}
| true | true | protected String doInBackground(Void... params) {
String error = null;
String message = "";
short stringLen = -1;
try {
long requestTime = 0;
String[] parts = null;
byte[] bytes = new byte[256];
Socket sock = new Socket(server.address, server.port);
sock.setSoTimeout(SOCKET_TIMEOUT);
OutputStream os = sock.getOutputStream();
InputStream is = sock.getInputStream();
requestTime = System.currentTimeMillis();
os.write(MCServerTrackerActivity.PACKET_REQUEST_CODE);
is.read(bytes);
if (requestTime > SOCKET_TIMEOUT)
requestTime = System.currentTimeMillis() - requestTime;
ByteBuffer b = ByteBuffer.wrap(bytes);
b.get(); //remove first byte
stringLen = b.getShort();
byte[] stringData = new byte[Math.min(stringLen * 2, 253)];
b.get(stringData);
try {
message = new String(stringData, "UTF-16BE");
} catch (UnsupportedEncodingException e) {
//Nothing I can really do here
}
//Experimental multi-packet support
// while (is.read(bytes) != -1) {
// //if requestTime hasn't be calculated yet
// if (requestTime > SOCKET_TIMEOUT)
// requestTime = System.currentTimeMillis() - requestTime;
//
// ByteBuffer b = ByteBuffer.wrap(bytes);
// b.get(); //remove first byte
// short stringLen = b.getShort();
// byte[] stringData = new byte[stringLen * 2];
// b.get(stringData);
//
// try {
// message += new String(stringData, "UTF-16BE");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// }
sock.close();
parts = message.split("\u00A7");
if (parts.length == 3) {
server.motd = parts[0];
server.playerCount = Integer.parseInt(parts[1]);
server.maxPlayers = Integer.parseInt(parts[2]);
server.ping = (int)requestTime;
} else {
throw new IllegalArgumentException();
}
} catch (IOException e) {
if (e instanceof SocketTimeoutException) {
error = "Connection timed out";
} else if (e instanceof UnknownHostException) {
error = "Unable to resolve DNS";
} else if (e.getMessage().endsWith("Connection refused")) {
error = "Connection refused";
} else {
error = e.getMessage();
}
} catch (IllegalArgumentException e) {
error = "Communication error";
Log.d("MCT", "Communication error: \"" + message + "\". Message Length: " + stringLen);
Log.d("MCT", server.toString());
}
server.queried = true;
if (error != null) {
server.motd = MCServerTrackerActivity.ERROR_CHAR + error;
}
return error;
}
| protected String doInBackground(Void... params) {
String error = null;
String message = "";
short stringLen = -1;
try {
long requestTime = 0;
String[] parts = null;
byte[] bytes = new byte[256];
Socket sock = new Socket(server.address, server.port);
sock.setSoTimeout(SOCKET_TIMEOUT);
OutputStream os = sock.getOutputStream();
InputStream is = sock.getInputStream();
requestTime = System.currentTimeMillis();
os.write(MCServerTrackerActivity.PACKET_REQUEST_CODE);
is.read(bytes);
if (requestTime > SOCKET_TIMEOUT)
requestTime = System.currentTimeMillis() - requestTime;
ByteBuffer b = ByteBuffer.wrap(bytes);
b.get(); //remove first byte
stringLen = b.getShort();
byte[] stringData = new byte[Math.min(stringLen * 2, 253)];
b.get(stringData);
try {
message = new String(stringData, "UTF-16BE");
} catch (UnsupportedEncodingException e) {
//Nothing I can really do here
}
//Experimental multi-packet support
// while (is.read(bytes) != -1) {
// //if requestTime hasn't be calculated yet
// if (requestTime > SOCKET_TIMEOUT)
// requestTime = System.currentTimeMillis() - requestTime;
//
// ByteBuffer b = ByteBuffer.wrap(bytes);
// b.get(); //remove first byte
// short stringLen = b.getShort();
// byte[] stringData = new byte[stringLen * 2];
// b.get(stringData);
//
// try {
// message += new String(stringData, "UTF-16BE");
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
//
// }
sock.close();
parts = message.split("\u00A7");
if (parts.length == 3) {
server.motd = parts[0];
server.playerCount = Integer.parseInt(parts[1]);
server.maxPlayers = Integer.parseInt(parts[2]);
server.ping = (int)requestTime;
} else {
throw new IllegalArgumentException();
}
} catch (IOException e) {
if (e instanceof SocketTimeoutException) {
error = "Connection timed out";
} else if (e instanceof UnknownHostException) {
error = "Unable to resolve DNS";
} else if (e.getMessage().endsWith("Connection refused")) {
error = "Connection refused";
} else {
error = e.getMessage();
}
} catch (IllegalArgumentException e) {
error = "Communication error";
// Log.d("MCT", "Communication error: \"" + message + "\". Message Length: " + stringLen);
// Log.d("MCT", server.toString());
}
server.queried = true;
if (error != null) {
server.motd = MCServerTrackerActivity.ERROR_CHAR + error;
}
return error;
}
|
diff --git a/src/main/java/org/debox/photo/model/Photo.java b/src/main/java/org/debox/photo/model/Photo.java
index 3996aa3..7dac74e 100644
--- a/src/main/java/org/debox/photo/model/Photo.java
+++ b/src/main/java/org/debox/photo/model/Photo.java
@@ -1,108 +1,108 @@
/*
* #%L
* debox-photos
* %%
* Copyright (C) 2012 Debox
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.debox.photo.model;
import java.io.File;
import java.util.Objects;
/**
* @author Corentin Guy <[email protected]>
*/
public class Photo implements Comparable<Photo> {
protected String id;
protected String name;
protected String relativePath;
protected String albumId;
protected String thumbnailUrl;
protected String url;
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAlbumId() {
return albumId;
}
public void setAlbumId(String albumId) {
this.albumId = albumId;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRelativePath() {
return relativePath;
}
public void setRelativePath(String relativePath) {
this.relativePath = relativePath;
}
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof Photo) {
Photo photo = (Photo) object;
- return Objects.equals(this.relativePath + File.separatorChar + this.getId(), photo.getRelativePath() + File.separatorChar + photo.getId());
+ return Objects.equals(this.relativePath + File.separatorChar + this.getName(), photo.getRelativePath() + File.separatorChar + photo.getName());
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(this.relativePath);
}
@Override
public int compareTo(Photo photo) {
return this.getName().compareToIgnoreCase(photo.getName());
}
}
| true | true | public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof Photo) {
Photo photo = (Photo) object;
return Objects.equals(this.relativePath + File.separatorChar + this.getId(), photo.getRelativePath() + File.separatorChar + photo.getId());
}
return false;
}
| public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof Photo) {
Photo photo = (Photo) object;
return Objects.equals(this.relativePath + File.separatorChar + this.getName(), photo.getRelativePath() + File.separatorChar + photo.getName());
}
return false;
}
|
diff --git a/src/cells/Map.java b/src/cells/Map.java
index b3ceb50..03f3b4c 100644
--- a/src/cells/Map.java
+++ b/src/cells/Map.java
@@ -1,90 +1,90 @@
package cells;
import java.awt.Graphics;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import pxlJam.Crayon;
public class Map {
private Cell[][] tiles;
private Crayon character;
private int width;
private int height;
private File file;
public Map(String filename) {
file = new File(filename);
readMap();
}
public void readMap() {
try {
Scanner scan = new Scanner(file);
width = scan.nextInt();
height = scan.nextInt();
tiles = new Cell[width][height];
int tempInt;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (scan.hasNext()) {
tempInt = scan.nextInt();
- if (tempInt == 10)
+ if (tempInt == 2)
character = new Crayon(i * Cell.CELL_WIDTH, j * Cell.CELL_HEIGHT);
else {
- tiles[i][j] = getWalltype(scan.nextInt(), i * Cell.CELL_WIDTH, j * Cell.CELL_HEIGHT);
+ tiles[i][j] = getWalltype(tempInt, i * Cell.CELL_WIDTH, j * Cell.CELL_HEIGHT);
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public Cell getWalltype(int fileNum, int x, int y) {
Cell tempCell = null;
if (fileNum == 1)
tempCell = new Wall(x, y);
else if (fileNum == 2) {
// something else
} else if (fileNum == 0) {
tempCell = null;
}
return tempCell;
}
public void draw(Graphics g) {
for (int i = 0; i < tiles.length; i++)
for (int j = 0; j < tiles[i].length; j++) {
if (tiles[i][j] != null) {
tiles[i][j].draw(g);
}
}
if (character != null) {
character.draw(g);
}else{
System.out.println("Character is null");
}
}
public Crayon getCharacter() {
return character;
}
public void setCharacter(Crayon character) {
this.character = character;
}
public void setCell(int x, int y, Cell c){
tiles[x][y] = c;
}
}
| false | true | public void readMap() {
try {
Scanner scan = new Scanner(file);
width = scan.nextInt();
height = scan.nextInt();
tiles = new Cell[width][height];
int tempInt;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (scan.hasNext()) {
tempInt = scan.nextInt();
if (tempInt == 10)
character = new Crayon(i * Cell.CELL_WIDTH, j * Cell.CELL_HEIGHT);
else {
tiles[i][j] = getWalltype(scan.nextInt(), i * Cell.CELL_WIDTH, j * Cell.CELL_HEIGHT);
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
| public void readMap() {
try {
Scanner scan = new Scanner(file);
width = scan.nextInt();
height = scan.nextInt();
tiles = new Cell[width][height];
int tempInt;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (scan.hasNext()) {
tempInt = scan.nextInt();
if (tempInt == 2)
character = new Crayon(i * Cell.CELL_WIDTH, j * Cell.CELL_HEIGHT);
else {
tiles[i][j] = getWalltype(tempInt, i * Cell.CELL_WIDTH, j * Cell.CELL_HEIGHT);
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorCommentPart.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorCommentPart.java
index d69cfe778..1934921aa 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorCommentPart.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/TaskEditorCommentPart.java
@@ -1,560 +1,560 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
* Jingwen Ou - comment grouping
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.editors;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.tasks.core.TaskComment;
import org.eclipse.mylyn.internal.tasks.ui.editors.CommentGroupStrategy.CommentGroup;
import org.eclipse.mylyn.tasks.core.IRepositoryPerson;
import org.eclipse.mylyn.tasks.core.ITaskComment;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
import org.eclipse.mylyn.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.tasks.ui.editors.AbstractAttributeEditor;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
import org.eclipse.ui.forms.widgets.Section;
/**
* @author Robert Elves
* @author Steffen Pingel
* @author Jingwen Ou
*/
public class TaskEditorCommentPart extends AbstractTaskEditorPart {
private static final String KEY_EDITOR = "viewer";
private static final String LABEL_REPLY = "Reply";
/** Expandable composites are indented by 6 pixels by default. */
private static final int INDENT = -6;
protected Section section;
protected List<ExpandableComposite> commentComposites;
private List<TaskAttribute> comments;
private boolean hasIncoming;
private CommentGroupStrategy commentGroupStrategy;
private List<Section> subSections;
private boolean expandAllInProgress;
public TaskEditorCommentPart() {
setPartName("Comments");
}
protected void expandComment(FormToolkit toolkit, Composite composite, Composite toolBarComposite,
final TaskComment taskComment, boolean expanded) {
toolBarComposite.setVisible(expanded);
if (expanded && composite.getData(KEY_EDITOR) == null) {
// create viewer
TaskAttribute textAttribute = getTaskData().getAttributeMapper().getAssoctiatedAttribute(
taskComment.getTaskAttribute());
AbstractAttributeEditor editor = createAttributeEditor(textAttribute);
if (editor != null) {
editor.setDecorationEnabled(false);
editor.createControl(composite, toolkit);
editor.getControl().addMouseListener(new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
getTaskEditorPage().selectionChanged(taskComment);
}
});
composite.setData(KEY_EDITOR, editor);
getTaskEditorPage().getAttributeEditorToolkit().adapt(editor);
getTaskEditorPage().reflow();
}
} else if (!expanded && composite.getData(KEY_EDITOR) != null) {
// dispose viewer
AbstractAttributeEditor editor = (AbstractAttributeEditor) composite.getData(KEY_EDITOR);
editor.getControl().setMenu(null);
editor.getControl().dispose();
composite.setData(KEY_EDITOR, null);
getTaskEditorPage().reflow();
}
getTaskEditorPage().selectionChanged(taskComment);
}
private void initialize() {
comments = getTaskData().getAttributeMapper().getAttributesByType(getTaskData(), TaskAttribute.TYPE_COMMENT);
if (comments.size() > 0) {
for (TaskAttribute commentAttribute : comments) {
if (getModel().hasIncomingChanges(commentAttribute)) {
hasIncoming = true;
break;
}
}
}
}
@Override
public void createControl(Composite parent, final FormToolkit toolkit) {
initialize();
section = createSection(parent, toolkit, hasIncoming);
section.setText(section.getText() + " (" + comments.size() + ")");
if (comments.isEmpty()) {
section.setEnabled(false);
} else {
if (hasIncoming) {
commentComposites = new ArrayList<ExpandableComposite>();
expandSection(toolkit, section, comments);
} else {
section.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent event) {
if (commentComposites == null) {
try {
getTaskEditorPage().setReflow(false);
commentComposites = new ArrayList<ExpandableComposite>();
expandSection(toolkit, section, comments);
} finally {
getTaskEditorPage().setReflow(true);
}
getTaskEditorPage().reflow();
}
}
});
}
}
setSection(toolkit, section);
}
protected void expandSection(final FormToolkit toolkit, final Section section, List<TaskAttribute> commentAttributes) {
Composite composite = toolkit.createComposite(section);
section.setClient(composite);
GridLayout layout = new GridLayout();
layout.marginHeight = 0;
composite.setLayout(layout);
// group comments
List<ITaskComment> comments = new ArrayList<ITaskComment>();
for (TaskAttribute commentAttribute : commentAttributes) {
comments.add(convertToTaskComment(getModel(), commentAttribute));
}
String currentPersonId = getModel().getTaskRepository().getUserName();
List<CommentGroup> commentGroups = getCommentGroupStrategy().groupComments(comments, currentPersonId);
if (commentGroups.size() > 0) {
subSections = new ArrayList<Section>();
for (int i = 0; i < commentGroups.size() - 1; i++) {
createSubSection(toolkit, composite, commentGroups.get(i));
}
// last group is not rendered as subsection
CommentGroup lastGroup = commentGroups.get(commentGroups.size() - 1);
addComments(toolkit, composite, lastGroup.getCommentAttributes());
}
}
protected void addComments(final FormToolkit toolkit, final Composite composite, final List<TaskAttribute> comments) {
for (final TaskAttribute commentAttribute : comments) {
boolean hasIncomingChanges = getModel().hasIncomingChanges(commentAttribute);
final TaskComment taskComment = new TaskComment(getModel().getTaskRepository(), getModel().getTask(),
commentAttribute);
getTaskData().getAttributeMapper().updateTaskComment(taskComment, commentAttribute);
int style = ExpandableComposite.TREE_NODE | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT
| ExpandableComposite.COMPACT;
if (hasIncomingChanges || expandAllInProgress) {
style |= ExpandableComposite.EXPANDED;
}
final ExpandableComposite commentComposite = toolkit.createExpandableComposite(composite, style);
commentComposite.setLayout(new GridLayout());
commentComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
commentComposite.setTitleBarForeground(toolkit.getColors().getColor(IFormColors.TITLE));
commentComposites.add(commentComposite);
// always visible
Composite titleComposite = toolkit.createComposite(commentComposite);
commentComposite.setTextClient(titleComposite);
RowLayout rowLayout = new RowLayout();
rowLayout.pack = true;
rowLayout.marginLeft = 0;
rowLayout.marginBottom = 0;
rowLayout.marginTop = 0;
titleComposite.setLayout(rowLayout);
titleComposite.setBackground(null);
ImageHyperlink expandCommentHyperlink = createTitleHyperLink(toolkit, titleComposite, taskComment);
expandCommentHyperlink.setFont(commentComposite.getFont());
expandCommentHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
EditorUtil.toggleExpandableComposite(!commentComposite.isExpanded(), commentComposite);
}
});
// only visible when section is expanded
final Composite buttonComposite = toolkit.createComposite(titleComposite);
RowLayout buttonCompLayout = new RowLayout();
buttonCompLayout.marginBottom = 0;
buttonCompLayout.marginTop = 0;
buttonComposite.setLayout(buttonCompLayout);
buttonComposite.setBackground(null);
buttonComposite.setVisible(commentComposite.isExpanded());
createReplyHyperlink(buttonComposite, toolkit, taskComment);
final Composite commentTextComposite = toolkit.createComposite(commentComposite);
commentComposite.setClient(commentTextComposite);
commentTextComposite.setLayout(new FillWidthLayout(EditorUtil.getLayoutAdvisor(getTaskEditorPage()), 15, 0,
0, 3));
//commentTextComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
if (composite.getParent().getParent().getParent() instanceof Section) {
GridDataFactory.fillDefaults().grab(true, false).applyTo(commentComposite);
} else {
GridDataFactory.fillDefaults().grab(true, false).indent(INDENT, 0).applyTo(commentComposite);
}
commentComposite.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent event) {
expandComment(toolkit, commentTextComposite, buttonComposite, taskComment, event.getState());
}
});
if (hasIncomingChanges) {
commentComposite.setBackground(getTaskEditorPage().getAttributeEditorToolkit().getColorIncoming());
}
- if (commentComposite.isEnabled()) {
+ if (commentComposite.isExpanded()) {
expandComment(toolkit, commentTextComposite, buttonComposite, taskComment, true);
}
// for outline
EditorUtil.setMarker(commentComposite, commentAttribute.getId());
}
}
private ImageHyperlink createTitleHyperLink(final FormToolkit toolkit, final Composite toolbarComp,
final ITaskComment taskComment) {
ImageHyperlink formHyperlink = toolkit.createImageHyperlink(toolbarComp, SWT.NONE);
formHyperlink.setBackground(null);
formHyperlink.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
IRepositoryPerson author = taskComment.getAuthor();
if (author != null
&& author.getPersonId().equalsIgnoreCase(getTaskEditorPage().getTaskRepository().getUserName())) {
formHyperlink.setImage(CommonImages.getImage(CommonImages.PERSON_ME_NARROW));
} else {
formHyperlink.setImage(CommonImages.getImage(CommonImages.PERSON_NARROW));
}
StringBuilder sb = new StringBuilder();
if (taskComment.getNumber() >= 0) {
sb.append(taskComment.getNumber());
sb.append(": ");
}
if (author != null) {
if (author.getName() != null) {
sb.append(author.getName());
formHyperlink.setToolTipText(author.getPersonId());
} else {
sb.append(author.getPersonId());
}
}
if (taskComment.getCreationDate() != null) {
sb.append(", ");
sb.append(EditorUtil.formatDateTime(taskComment.getCreationDate()));
}
formHyperlink.setText(sb.toString());
formHyperlink.setEnabled(true);
formHyperlink.setUnderlined(false);
return formHyperlink;
}
protected ImageHyperlink createReplyHyperlink(Composite composite, FormToolkit toolkit,
final ITaskComment taskComment) {
final ImageHyperlink replyLink = new ImageHyperlink(composite, SWT.NULL);
toolkit.adapt(replyLink, false, false);
replyLink.setImage(CommonImages.getImage(TasksUiImages.COMMENT_REPLY));
replyLink.setToolTipText(LABEL_REPLY);
// no need for the background - transparency will take care of it
replyLink.setBackground(null);
// replyLink.setBackground(section.getTitleBarGradientBackground());
replyLink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
AbstractReplyToCommentAction.reply(getTaskEditorPage(), taskComment, taskComment.getText());
}
@Override
public void linkEntered(HyperlinkEvent e) {
replyLink.setUnderlined(true);
}
@Override
public void linkExited(HyperlinkEvent e) {
replyLink.setUnderlined(false);
}
});
return replyLink;
}
@Override
protected void fillToolBar(ToolBarManager barManager) {
if (comments.isEmpty()) {
return;
}
Action collapseAllAction = new Action("") {
@Override
public void run() {
hideAllComments();
}
};
collapseAllAction.setImageDescriptor(CommonImages.COLLAPSE_ALL_SMALL);
collapseAllAction.setToolTipText("Collapse All Comments");
barManager.add(collapseAllAction);
Action expandAllAction = new Action("") {
@Override
public void run() {
expandAllComments();
}
};
expandAllAction.setImageDescriptor(CommonImages.EXPAND_ALL_SMALL);
expandAllAction.setToolTipText("Expand All Comments");
barManager.add(expandAllAction);
}
private void hideAllComments() {
if (commentComposites != null) {
try {
getTaskEditorPage().setReflow(false);
for (ExpandableComposite composite : commentComposites) {
if (composite.isDisposed()) {
continue;
}
if (composite.isExpanded()) {
EditorUtil.toggleExpandableComposite(false, composite);
}
}
} finally {
getTaskEditorPage().setReflow(true);
}
getTaskEditorPage().reflow();
}
}
protected void expandAllComments() {
try {
expandAllInProgress = true;
getTaskEditorPage().setReflow(false);
if (section != null) {
EditorUtil.toggleExpandableComposite(true, section);
}
if (subSections != null) {
// first toggle on all subSections
if (section != null) {
EditorUtil.toggleExpandableComposite(true, section);
}
for (Section subSection : subSections) {
if (subSection.isDisposed()) {
continue;
}
EditorUtil.toggleExpandableComposite(true, subSection);
}
}
for (ExpandableComposite composite : commentComposites) {
if (composite.isDisposed()) {
continue;
}
if (!composite.isExpanded()) {
EditorUtil.toggleExpandableComposite(true, composite);
}
}
} finally {
expandAllInProgress = false;
getTaskEditorPage().setReflow(true);
}
getTaskEditorPage().reflow();
}
// private static void toggleChildren(Composite composite, boolean expended) {
// for (Control child : composite.getChildren()) {
// if (child instanceof ExpandableComposite && !child.isDisposed()) {
// EditorUtil.toggleExpandableComposite(expended, (ExpandableComposite) child);
// }
// if (child instanceof Composite) {
// toggleChildren((Composite) child, expended);
// }
// }
// }
private TaskComment convertToTaskComment(TaskDataModel taskDataModel, TaskAttribute commentAttribute) {
TaskComment taskComment = new TaskComment(taskDataModel.getTaskRepository(), taskDataModel.getTask(),
commentAttribute);
taskDataModel.getTaskData().getAttributeMapper().updateTaskComment(taskComment, commentAttribute);
return taskComment;
}
// private void createCurrentSubsectionToolBar(final FormToolkit toolkit, final Section section) {
// if (section == null) {
// return;
// }
//
// ToolBarManager toolBarManager = new ToolBarManager(SWT.FLAT);
//
// Action collapseAllAction = new Action("") {
// @Override
// public void run() {
// toggleSection(section, false);
// }
// };
// collapseAllAction.setImageDescriptor(CommonImages.COLLAPSE_ALL_SMALL);
// collapseAllAction.setToolTipText("Collapse All Current Comments");
// toolBarManager.add(collapseAllAction);
//
// Action expandAllAction = new Action("") {
// @Override
// public void run() {
// toggleSection(section, true);
// }
// };
// expandAllAction.setImageDescriptor(CommonImages.EXPAND_ALL_SMALL);
// expandAllAction.setToolTipText("Expand All Current Comments");
// toolBarManager.add(expandAllAction);
//
// Composite toolbarComposite = toolkit.createComposite(section);
// toolbarComposite.setBackground(null);
// RowLayout rowLayout = new RowLayout();
// rowLayout.marginTop = 0;
// rowLayout.marginBottom = 0;
// rowLayout.marginLeft = 0;
// rowLayout.marginRight = 0;
// toolbarComposite.setLayout(rowLayout);
//
// toolBarManager.createControl(toolbarComposite);
// section.setTextClient(toolbarComposite);
// }
private void createSubSection(final FormToolkit toolkit, final Composite parent, final CommentGroup commentGroup) {
int style = ExpandableComposite.TWISTIE | ExpandableComposite.SHORT_TITLE_BAR;
if (/*commentGroup.hasIncoming() || */expandAllInProgress) {
style |= ExpandableComposite.EXPANDED;
}
final Section groupSection = toolkit.createSection(parent, style);
if (commentGroup.hasIncoming()) {
groupSection.setBackground(getTaskEditorPage().getAttributeEditorToolkit().getColorIncoming());
}
groupSection.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
GridDataFactory.fillDefaults().grab(true, false).indent(2 * INDENT, 0).applyTo(groupSection);
groupSection.setText(commentGroup.getGroupName() + " (" + commentGroup.getCommentAttributes().size() + ")");
// create tool bar only for Current section
// if (commentGroup.getGroupName().equals("Current")) {
// createCurrentSubsectionToolBar(toolkit, groupSection);
// }
// only Current subsection will be expanded by default
if (groupSection.isExpanded()) {
expandSubSection(toolkit, commentGroup, groupSection);
} else {
groupSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
if (commentGroup.hasIncoming()) {
if (e.getState()) {
groupSection.setBackground(null);
} else {
// only decorate background with incoming color when collapsed, otherwise
// there is too much decoration in the editor
groupSection.setBackground(getTaskEditorPage().getAttributeEditorToolkit()
.getColorIncoming());
}
}
if (groupSection.getClient() == null) {
try {
getTaskEditorPage().setReflow(false);
expandSubSection(toolkit, commentGroup, groupSection);
} finally {
getTaskEditorPage().setReflow(true);
}
getTaskEditorPage().reflow();
}
}
});
}
subSections.add(groupSection);
}
private void expandSubSection(final FormToolkit toolkit, CommentGroup commentGroup, Section subSection) {
Composite composite = toolkit.createComposite(subSection);
subSection.setClient(composite);
GridLayout contentLayout = new GridLayout();
contentLayout.marginHeight = 0;
contentLayout.marginWidth = 0;
composite.setLayout(contentLayout);
addComments(toolkit, composite, commentGroup.getCommentAttributes());
}
private CommentGroupStrategy getCommentGroupStrategy() {
if (commentGroupStrategy == null) {
commentGroupStrategy = new CommentGroupStrategy() {
@Override
protected boolean hasIncomingChanges(ITaskComment taskComment) {
return getModel().hasIncomingChanges(taskComment.getTaskAttribute());
}
};
}
return commentGroupStrategy;
}
// private void toggleSection(Section section, boolean expended) {
// try {
// getTaskEditorPage().setReflow(false);
//
// if (expended && !section.isDisposed()) {
// EditorUtil.toggleExpandableComposite(true, section);
// }
//
// toggleChildren(section, expended);
// } finally {
// getTaskEditorPage().setReflow(true);
// }
// getTaskEditorPage().reflow();
// }
}
| true | true | protected void addComments(final FormToolkit toolkit, final Composite composite, final List<TaskAttribute> comments) {
for (final TaskAttribute commentAttribute : comments) {
boolean hasIncomingChanges = getModel().hasIncomingChanges(commentAttribute);
final TaskComment taskComment = new TaskComment(getModel().getTaskRepository(), getModel().getTask(),
commentAttribute);
getTaskData().getAttributeMapper().updateTaskComment(taskComment, commentAttribute);
int style = ExpandableComposite.TREE_NODE | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT
| ExpandableComposite.COMPACT;
if (hasIncomingChanges || expandAllInProgress) {
style |= ExpandableComposite.EXPANDED;
}
final ExpandableComposite commentComposite = toolkit.createExpandableComposite(composite, style);
commentComposite.setLayout(new GridLayout());
commentComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
commentComposite.setTitleBarForeground(toolkit.getColors().getColor(IFormColors.TITLE));
commentComposites.add(commentComposite);
// always visible
Composite titleComposite = toolkit.createComposite(commentComposite);
commentComposite.setTextClient(titleComposite);
RowLayout rowLayout = new RowLayout();
rowLayout.pack = true;
rowLayout.marginLeft = 0;
rowLayout.marginBottom = 0;
rowLayout.marginTop = 0;
titleComposite.setLayout(rowLayout);
titleComposite.setBackground(null);
ImageHyperlink expandCommentHyperlink = createTitleHyperLink(toolkit, titleComposite, taskComment);
expandCommentHyperlink.setFont(commentComposite.getFont());
expandCommentHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
EditorUtil.toggleExpandableComposite(!commentComposite.isExpanded(), commentComposite);
}
});
// only visible when section is expanded
final Composite buttonComposite = toolkit.createComposite(titleComposite);
RowLayout buttonCompLayout = new RowLayout();
buttonCompLayout.marginBottom = 0;
buttonCompLayout.marginTop = 0;
buttonComposite.setLayout(buttonCompLayout);
buttonComposite.setBackground(null);
buttonComposite.setVisible(commentComposite.isExpanded());
createReplyHyperlink(buttonComposite, toolkit, taskComment);
final Composite commentTextComposite = toolkit.createComposite(commentComposite);
commentComposite.setClient(commentTextComposite);
commentTextComposite.setLayout(new FillWidthLayout(EditorUtil.getLayoutAdvisor(getTaskEditorPage()), 15, 0,
0, 3));
//commentTextComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
if (composite.getParent().getParent().getParent() instanceof Section) {
GridDataFactory.fillDefaults().grab(true, false).applyTo(commentComposite);
} else {
GridDataFactory.fillDefaults().grab(true, false).indent(INDENT, 0).applyTo(commentComposite);
}
commentComposite.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent event) {
expandComment(toolkit, commentTextComposite, buttonComposite, taskComment, event.getState());
}
});
if (hasIncomingChanges) {
commentComposite.setBackground(getTaskEditorPage().getAttributeEditorToolkit().getColorIncoming());
}
if (commentComposite.isEnabled()) {
expandComment(toolkit, commentTextComposite, buttonComposite, taskComment, true);
}
// for outline
EditorUtil.setMarker(commentComposite, commentAttribute.getId());
}
}
| protected void addComments(final FormToolkit toolkit, final Composite composite, final List<TaskAttribute> comments) {
for (final TaskAttribute commentAttribute : comments) {
boolean hasIncomingChanges = getModel().hasIncomingChanges(commentAttribute);
final TaskComment taskComment = new TaskComment(getModel().getTaskRepository(), getModel().getTask(),
commentAttribute);
getTaskData().getAttributeMapper().updateTaskComment(taskComment, commentAttribute);
int style = ExpandableComposite.TREE_NODE | ExpandableComposite.LEFT_TEXT_CLIENT_ALIGNMENT
| ExpandableComposite.COMPACT;
if (hasIncomingChanges || expandAllInProgress) {
style |= ExpandableComposite.EXPANDED;
}
final ExpandableComposite commentComposite = toolkit.createExpandableComposite(composite, style);
commentComposite.setLayout(new GridLayout());
commentComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
commentComposite.setTitleBarForeground(toolkit.getColors().getColor(IFormColors.TITLE));
commentComposites.add(commentComposite);
// always visible
Composite titleComposite = toolkit.createComposite(commentComposite);
commentComposite.setTextClient(titleComposite);
RowLayout rowLayout = new RowLayout();
rowLayout.pack = true;
rowLayout.marginLeft = 0;
rowLayout.marginBottom = 0;
rowLayout.marginTop = 0;
titleComposite.setLayout(rowLayout);
titleComposite.setBackground(null);
ImageHyperlink expandCommentHyperlink = createTitleHyperLink(toolkit, titleComposite, taskComment);
expandCommentHyperlink.setFont(commentComposite.getFont());
expandCommentHyperlink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
EditorUtil.toggleExpandableComposite(!commentComposite.isExpanded(), commentComposite);
}
});
// only visible when section is expanded
final Composite buttonComposite = toolkit.createComposite(titleComposite);
RowLayout buttonCompLayout = new RowLayout();
buttonCompLayout.marginBottom = 0;
buttonCompLayout.marginTop = 0;
buttonComposite.setLayout(buttonCompLayout);
buttonComposite.setBackground(null);
buttonComposite.setVisible(commentComposite.isExpanded());
createReplyHyperlink(buttonComposite, toolkit, taskComment);
final Composite commentTextComposite = toolkit.createComposite(commentComposite);
commentComposite.setClient(commentTextComposite);
commentTextComposite.setLayout(new FillWidthLayout(EditorUtil.getLayoutAdvisor(getTaskEditorPage()), 15, 0,
0, 3));
//commentTextComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
if (composite.getParent().getParent().getParent() instanceof Section) {
GridDataFactory.fillDefaults().grab(true, false).applyTo(commentComposite);
} else {
GridDataFactory.fillDefaults().grab(true, false).indent(INDENT, 0).applyTo(commentComposite);
}
commentComposite.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent event) {
expandComment(toolkit, commentTextComposite, buttonComposite, taskComment, event.getState());
}
});
if (hasIncomingChanges) {
commentComposite.setBackground(getTaskEditorPage().getAttributeEditorToolkit().getColorIncoming());
}
if (commentComposite.isExpanded()) {
expandComment(toolkit, commentTextComposite, buttonComposite, taskComment, true);
}
// for outline
EditorUtil.setMarker(commentComposite, commentAttribute.getId());
}
}
|
diff --git a/net/sourceforge/pinemup/logic/NoteIO.java b/net/sourceforge/pinemup/logic/NoteIO.java
index dd1a56e..1a203bd 100755
--- a/net/sourceforge/pinemup/logic/NoteIO.java
+++ b/net/sourceforge/pinemup/logic/NoteIO.java
@@ -1,300 +1,298 @@
/*
* pin 'em up
*
* Copyright (C) 2007 by Mario Koedding
*
*
* 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.sourceforge.pinemup.logic;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.*;
import javax.swing.JOptionPane;
import javax.xml.stream.*;
public class NoteIO {
public static void writeCategoriesToFile(CategoryList c, UserSettings s) {
//write notes to xml file
try {
XMLOutputFactory myFactory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = myFactory.createXMLStreamWriter(new FileOutputStream(s.getNotesFile()),"UTF-8");
writer.writeStartDocument("UTF-8","1.0");
writer.writeStartElement("notesfile");
writer.writeAttribute("version","0.1");
CategoryList cl = c;
while (cl != null) {
if (cl.getCategory() != null) {
writer.writeStartElement("category");
writer.writeAttribute("name", cl.getCategory().getName());
writer.writeAttribute("default",String.valueOf(cl.getCategory().isDefaultCategory()));
NoteList nl = cl.getCategory().getNotes();
while (nl != null) {
if (nl.getNote() != null) {
writer.writeStartElement("note");
writer.writeAttribute("hidden", String.valueOf(nl.getNote().isHidden()));
writer.writeAttribute("alwaysontop", String.valueOf(nl.getNote().isAlwaysOnTop()));
writer.writeAttribute("xposition", String.valueOf(nl.getNote().getXPos()));
writer.writeAttribute("yposition", String.valueOf(nl.getNote().getYPos()));
writer.writeAttribute("width", String.valueOf(nl.getNote().getXSize()));
writer.writeAttribute("height", String.valueOf(nl.getNote().getYSize()));
writer.writeStartElement("text");
writer.writeAttribute("size", String.valueOf(nl.getNote().getFontSize()));
String noteText = nl.getNote().getText();
String[] textParts = noteText.split("\n");
for (int i = 0; i<textParts.length; i++) {
writer.writeCharacters(textParts[i]);
writer.writeEmptyElement("newline");
}
writer.writeEndElement();
writer.writeEndElement();
}
nl = nl.getNext();
}
writer.writeEndElement();
}
cl = cl.getNext();
}
writer.writeEndElement();
writer.writeEndDocument();
writer.close();
} catch (XMLStreamException e) {
JOptionPane.showMessageDialog(null, "Could save notes to file! Please check file-settings and free disk-space!", "pin 'em up - error", JOptionPane.ERROR_MESSAGE);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "Could save notes to file! Please check file-settings and free disk-space!", "pin 'em up - error", JOptionPane.ERROR_MESSAGE);
}
}
public static CategoryList readCategoriesFromFile(UserSettings s) {
CategoryList c = new CategoryList();
Category currentCategory = null;
Note currentNote = null;
boolean defaultNotAdded = true;
try {
InputStream in = new FileInputStream(s.getNotesFile());
XMLInputFactory myFactory = XMLInputFactory.newInstance();
- myFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.TRUE);
- myFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.TRUE);
XMLStreamReader parser = myFactory.createXMLStreamReader(in,"UTF-8");
int event;
while(parser.hasNext()) {
event = parser.next();
switch(event) {
case XMLStreamConstants.START_DOCUMENT:
// do nothing
break;
case XMLStreamConstants.END_DOCUMENT:
parser.close();
break;
case XMLStreamConstants.NAMESPACE:
// do nothing
break;
case XMLStreamConstants.START_ELEMENT:
String ename = parser.getLocalName();
if (ename.equals("notesfile")) {
//do nothing yet
} else if (ename.equals("category")) {
String name = "";
boolean def = false;
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("name")) {
name = parser.getAttributeValue(i);
} else if (parser.getAttributeLocalName(i).equals("default")) {
def = (parser.getAttributeValue(i).equals("true")) && defaultNotAdded;
if (def) {
defaultNotAdded = false;
}
}
}
currentCategory = new Category(name,new NoteList(),def);
c.add(currentCategory);
} else if (ename.equals("note")) {
currentNote = new Note("",s,c);
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("hidden")) {
boolean h = parser.getAttributeValue(i).equals("true");
currentNote.setHidden(h);
} else if (parser.getAttributeLocalName(i).equals("xposition")) {
short x = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(x, currentNote.getYPos());
} else if (parser.getAttributeLocalName(i).equals("yposition")) {
short y = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(currentNote.getXPos(), y);
} else if (parser.getAttributeLocalName(i).equals("width")) {
short w = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(w, currentNote.getYSize());
} else if (parser.getAttributeLocalName(i).equals("height")) {
short h = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(currentNote.getXSize(), h);
} else if (parser.getAttributeLocalName(i).equals("alwaysontop")) {
boolean a = parser.getAttributeValue(i).equals("true");
currentNote.setAlwaysOnTop(a);
}
}
if (currentCategory != null) {
currentCategory.getNotes().add(currentNote);
}
} else if (ename.equals("text")) {
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("size")) {
short fontSize = Short.parseShort(parser.getAttributeValue(i));
currentNote.setFontSize(fontSize);
}
}
} else if (ename.equals("newline")) {
currentNote.setText(currentNote.getText()+"\n");
}
break;
case XMLStreamConstants.CHARACTERS:
if(!parser.isWhiteSpace()) {
if (currentNote != null) {
String str = parser.getText();
currentNote.setText(currentNote.getText() + str);
}
}
break;
case XMLStreamConstants.END_ELEMENT:
// do nothing
break;
default:
break;
}
}
} catch (FileNotFoundException e) {
//neu erstellen
c.add(new Category("Home",new NoteList(),true));
c.add(new Category("Office",new NoteList(),false));
} catch (XMLStreamException e) {
//Meldung ausgeben
System.out.println("XML Error");
}
return c;
}
public static void getCategoriesFromFTP(UserSettings us) {
boolean downloaded = true;
try {
File f = new File(us.getNotesFile());
FileOutputStream fos = new FileOutputStream(f);
String filename = f.getName();
String ftpString = "ftp://" + us.getFtpUser() + ":"
+ us.getFtpPasswdString() + "@" + us.getFtpServer()
+ us.getFtpDir() + filename + ";type=i";
URL url = new URL(ftpString);
URLConnection urlc = url.openConnection();
InputStream is = urlc.getInputStream();
int nextByte = is.read();
while(nextByte != -1) {
fos.write(nextByte);
nextByte = is.read();
}
fos.close();
} catch (Exception e) {
downloaded = false;
JOptionPane.showMessageDialog(null, "Could not download file from FTP server!", "pin 'em up - error", JOptionPane.ERROR_MESSAGE);
}
if (downloaded) {
JOptionPane.showMessageDialog(null, "Notes successfully downloaded from FTP server!", "pin 'em up - information", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void writeCategoriesToFTP(UserSettings us) {
boolean uploaded = true;
try {
String completeFilename = us.getNotesFile();
File f = new File(completeFilename);
String filename = f.getName();
FileInputStream fis = new FileInputStream(f);
String ftpString = "ftp://" + us.getFtpUser() + ":"
+ us.getFtpPasswdString() + "@" + us.getFtpServer()
+ us.getFtpDir() + filename + ";type=i";
URL url = new URL(ftpString);
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream();
int nextByte = fis.read();
while (nextByte != -1) {
os.write(nextByte);
nextByte = fis.read();
}
os.close();
} catch (Exception e) {
uploaded = false;
JOptionPane.showMessageDialog(null, "Error! Notes could not be uploaded to FTP server!", "pin 'em up - error", JOptionPane.ERROR_MESSAGE);
}
if (uploaded) {
JOptionPane.showMessageDialog(null, "Notes successfully uploaded to FTP server!", "pin 'em up - information", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void exportCategoriesToTextFile(CategoryList c) {
File f = null;
PinEmUp.getFileDialog().setDialogTitle("Export notes to text-file");
PinEmUp.getFileDialog().setFileFilter(new MyFileFilter("TXT"));
if (PinEmUp.getFileDialog().showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
String name = NoteIO.checkAndAddExtension(PinEmUp.getFileDialog().getSelectedFile().getAbsolutePath(), ".txt");
f = new File(name);
}
if (f != null) {
try {
PrintWriter ostream = new PrintWriter(new BufferedWriter(new FileWriter(f)));
// write text of notes to file
while (c != null) {
ostream.println("Category: " + c.getCategory().getName());
ostream.println();
NoteList n = c.getCategory().getNotes();
while (n != null) {
if (n.getNote() != null) {
ostream.println(n.getNote().getText());
ostream.println();
ostream.println("---------------------");
ostream.println();
}
n = n.getNext();
}
ostream.println();
ostream.println("################################################################");
ostream.println();
c = c.getNext();
}
ostream.flush();
ostream.close();
}
catch ( IOException e ) {
System.out.println("IOERROR: " + e.getMessage() + "\n");
e.printStackTrace();
}
}
}
public static String checkAndAddExtension(String s, String xt) {
int len = s.length();
String ext = s.substring(len-4, len);
if (!ext.toLowerCase().equals(xt.toLowerCase())) {
s = s + xt.toLowerCase();
}
return s;
}
}
| true | true | public static CategoryList readCategoriesFromFile(UserSettings s) {
CategoryList c = new CategoryList();
Category currentCategory = null;
Note currentNote = null;
boolean defaultNotAdded = true;
try {
InputStream in = new FileInputStream(s.getNotesFile());
XMLInputFactory myFactory = XMLInputFactory.newInstance();
myFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.TRUE);
myFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.TRUE);
XMLStreamReader parser = myFactory.createXMLStreamReader(in,"UTF-8");
int event;
while(parser.hasNext()) {
event = parser.next();
switch(event) {
case XMLStreamConstants.START_DOCUMENT:
// do nothing
break;
case XMLStreamConstants.END_DOCUMENT:
parser.close();
break;
case XMLStreamConstants.NAMESPACE:
// do nothing
break;
case XMLStreamConstants.START_ELEMENT:
String ename = parser.getLocalName();
if (ename.equals("notesfile")) {
//do nothing yet
} else if (ename.equals("category")) {
String name = "";
boolean def = false;
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("name")) {
name = parser.getAttributeValue(i);
} else if (parser.getAttributeLocalName(i).equals("default")) {
def = (parser.getAttributeValue(i).equals("true")) && defaultNotAdded;
if (def) {
defaultNotAdded = false;
}
}
}
currentCategory = new Category(name,new NoteList(),def);
c.add(currentCategory);
} else if (ename.equals("note")) {
currentNote = new Note("",s,c);
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("hidden")) {
boolean h = parser.getAttributeValue(i).equals("true");
currentNote.setHidden(h);
} else if (parser.getAttributeLocalName(i).equals("xposition")) {
short x = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(x, currentNote.getYPos());
} else if (parser.getAttributeLocalName(i).equals("yposition")) {
short y = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(currentNote.getXPos(), y);
} else if (parser.getAttributeLocalName(i).equals("width")) {
short w = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(w, currentNote.getYSize());
} else if (parser.getAttributeLocalName(i).equals("height")) {
short h = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(currentNote.getXSize(), h);
} else if (parser.getAttributeLocalName(i).equals("alwaysontop")) {
boolean a = parser.getAttributeValue(i).equals("true");
currentNote.setAlwaysOnTop(a);
}
}
if (currentCategory != null) {
currentCategory.getNotes().add(currentNote);
}
} else if (ename.equals("text")) {
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("size")) {
short fontSize = Short.parseShort(parser.getAttributeValue(i));
currentNote.setFontSize(fontSize);
}
}
} else if (ename.equals("newline")) {
currentNote.setText(currentNote.getText()+"\n");
}
break;
case XMLStreamConstants.CHARACTERS:
if(!parser.isWhiteSpace()) {
if (currentNote != null) {
String str = parser.getText();
currentNote.setText(currentNote.getText() + str);
}
}
break;
case XMLStreamConstants.END_ELEMENT:
// do nothing
break;
default:
break;
}
}
} catch (FileNotFoundException e) {
//neu erstellen
c.add(new Category("Home",new NoteList(),true));
c.add(new Category("Office",new NoteList(),false));
} catch (XMLStreamException e) {
//Meldung ausgeben
System.out.println("XML Error");
}
return c;
}
| public static CategoryList readCategoriesFromFile(UserSettings s) {
CategoryList c = new CategoryList();
Category currentCategory = null;
Note currentNote = null;
boolean defaultNotAdded = true;
try {
InputStream in = new FileInputStream(s.getNotesFile());
XMLInputFactory myFactory = XMLInputFactory.newInstance();
XMLStreamReader parser = myFactory.createXMLStreamReader(in,"UTF-8");
int event;
while(parser.hasNext()) {
event = parser.next();
switch(event) {
case XMLStreamConstants.START_DOCUMENT:
// do nothing
break;
case XMLStreamConstants.END_DOCUMENT:
parser.close();
break;
case XMLStreamConstants.NAMESPACE:
// do nothing
break;
case XMLStreamConstants.START_ELEMENT:
String ename = parser.getLocalName();
if (ename.equals("notesfile")) {
//do nothing yet
} else if (ename.equals("category")) {
String name = "";
boolean def = false;
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("name")) {
name = parser.getAttributeValue(i);
} else if (parser.getAttributeLocalName(i).equals("default")) {
def = (parser.getAttributeValue(i).equals("true")) && defaultNotAdded;
if (def) {
defaultNotAdded = false;
}
}
}
currentCategory = new Category(name,new NoteList(),def);
c.add(currentCategory);
} else if (ename.equals("note")) {
currentNote = new Note("",s,c);
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("hidden")) {
boolean h = parser.getAttributeValue(i).equals("true");
currentNote.setHidden(h);
} else if (parser.getAttributeLocalName(i).equals("xposition")) {
short x = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(x, currentNote.getYPos());
} else if (parser.getAttributeLocalName(i).equals("yposition")) {
short y = Short.parseShort(parser.getAttributeValue(i));
currentNote.setPosition(currentNote.getXPos(), y);
} else if (parser.getAttributeLocalName(i).equals("width")) {
short w = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(w, currentNote.getYSize());
} else if (parser.getAttributeLocalName(i).equals("height")) {
short h = Short.parseShort(parser.getAttributeValue(i));
currentNote.setSize(currentNote.getXSize(), h);
} else if (parser.getAttributeLocalName(i).equals("alwaysontop")) {
boolean a = parser.getAttributeValue(i).equals("true");
currentNote.setAlwaysOnTop(a);
}
}
if (currentCategory != null) {
currentCategory.getNotes().add(currentNote);
}
} else if (ename.equals("text")) {
for (int i=0; i<parser.getAttributeCount(); i++) {
if (parser.getAttributeLocalName(i).equals("size")) {
short fontSize = Short.parseShort(parser.getAttributeValue(i));
currentNote.setFontSize(fontSize);
}
}
} else if (ename.equals("newline")) {
currentNote.setText(currentNote.getText()+"\n");
}
break;
case XMLStreamConstants.CHARACTERS:
if(!parser.isWhiteSpace()) {
if (currentNote != null) {
String str = parser.getText();
currentNote.setText(currentNote.getText() + str);
}
}
break;
case XMLStreamConstants.END_ELEMENT:
// do nothing
break;
default:
break;
}
}
} catch (FileNotFoundException e) {
//neu erstellen
c.add(new Category("Home",new NoteList(),true));
c.add(new Category("Office",new NoteList(),false));
} catch (XMLStreamException e) {
//Meldung ausgeben
System.out.println("XML Error");
}
return c;
}
|
diff --git a/location/src/main/java/org/jahia/modules/location/LocationService.java b/location/src/main/java/org/jahia/modules/location/LocationService.java
index 4519c7fa..13d52bc9 100644
--- a/location/src/main/java/org/jahia/modules/location/LocationService.java
+++ b/location/src/main/java/org/jahia/modules/location/LocationService.java
@@ -1,43 +1,43 @@
package org.jahia.modules.location;
import com.google.code.geocoder.Geocoder;
import com.google.code.geocoder.GeocoderRequestBuilder;
import com.google.code.geocoder.model.GeocodeResponse;
import com.google.code.geocoder.model.GeocoderRequest;
import com.google.code.geocoder.model.GeocoderResult;
import org.drools.spi.KnowledgeHelper;
import org.jahia.services.content.JCRNodeWrapper;
import org.jahia.services.content.rules.AddedNodeFact;
import javax.jcr.RepositoryException;
import java.util.List;
public class LocationService {
public void geocodeLocation(AddedNodeFact node, KnowledgeHelper drools) throws RepositoryException {
final Geocoder geocoder = new Geocoder();
JCRNodeWrapper nodeWrapper = node.getNode();
StringBuffer address = new StringBuffer();
address.append(nodeWrapper.getProperty("j:street").getString());
if (nodeWrapper.hasProperty("j:zipCode")) {
address.append(" ").append(nodeWrapper.getProperty("j:zipCode").getString());
}
if (nodeWrapper.hasProperty("j:town")) {
address.append(" ").append(nodeWrapper.getProperty("j:town").getString());
}
if (nodeWrapper.hasProperty("j:country")) {
address.append(" ").append(nodeWrapper.getProperty("j:country").getString());
}
- if (!nodeWrapper.isNodeType("jnt:location") && !nodeWrapper.isNodeType("jmix:locationAware")) {
- nodeWrapper.addMixin("jmix:locationAware");
+ if (!nodeWrapper.isNodeType("jnt:location") && !nodeWrapper.isNodeType("jmix:geotagged")) {
+ nodeWrapper.addMixin("jmix:geotagged");
}
GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress(address.toString()).getGeocoderRequest();
GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest);
List<GeocoderResult> results = geocoderResponse.getResults();
if (results.size() > 0) {
nodeWrapper.setProperty("j:latitude", results.get(0).getGeometry().getLocation().getLat().toString());
nodeWrapper.setProperty("j:longitude", results.get(0).getGeometry().getLocation().getLng().toString());
}
}
}
| true | true | public void geocodeLocation(AddedNodeFact node, KnowledgeHelper drools) throws RepositoryException {
final Geocoder geocoder = new Geocoder();
JCRNodeWrapper nodeWrapper = node.getNode();
StringBuffer address = new StringBuffer();
address.append(nodeWrapper.getProperty("j:street").getString());
if (nodeWrapper.hasProperty("j:zipCode")) {
address.append(" ").append(nodeWrapper.getProperty("j:zipCode").getString());
}
if (nodeWrapper.hasProperty("j:town")) {
address.append(" ").append(nodeWrapper.getProperty("j:town").getString());
}
if (nodeWrapper.hasProperty("j:country")) {
address.append(" ").append(nodeWrapper.getProperty("j:country").getString());
}
if (!nodeWrapper.isNodeType("jnt:location") && !nodeWrapper.isNodeType("jmix:locationAware")) {
nodeWrapper.addMixin("jmix:locationAware");
}
GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress(address.toString()).getGeocoderRequest();
GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest);
List<GeocoderResult> results = geocoderResponse.getResults();
if (results.size() > 0) {
nodeWrapper.setProperty("j:latitude", results.get(0).getGeometry().getLocation().getLat().toString());
nodeWrapper.setProperty("j:longitude", results.get(0).getGeometry().getLocation().getLng().toString());
}
}
| public void geocodeLocation(AddedNodeFact node, KnowledgeHelper drools) throws RepositoryException {
final Geocoder geocoder = new Geocoder();
JCRNodeWrapper nodeWrapper = node.getNode();
StringBuffer address = new StringBuffer();
address.append(nodeWrapper.getProperty("j:street").getString());
if (nodeWrapper.hasProperty("j:zipCode")) {
address.append(" ").append(nodeWrapper.getProperty("j:zipCode").getString());
}
if (nodeWrapper.hasProperty("j:town")) {
address.append(" ").append(nodeWrapper.getProperty("j:town").getString());
}
if (nodeWrapper.hasProperty("j:country")) {
address.append(" ").append(nodeWrapper.getProperty("j:country").getString());
}
if (!nodeWrapper.isNodeType("jnt:location") && !nodeWrapper.isNodeType("jmix:geotagged")) {
nodeWrapper.addMixin("jmix:geotagged");
}
GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setAddress(address.toString()).getGeocoderRequest();
GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest);
List<GeocoderResult> results = geocoderResponse.getResults();
if (results.size() > 0) {
nodeWrapper.setProperty("j:latitude", results.get(0).getGeometry().getLocation().getLat().toString());
nodeWrapper.setProperty("j:longitude", results.get(0).getGeometry().getLocation().getLng().toString());
}
}
|
diff --git a/jamwiki-web/src/main/java/org/jamwiki/servlets/SearchServlet.java b/jamwiki-web/src/main/java/org/jamwiki/servlets/SearchServlet.java
index d150ea42..85316208 100644
--- a/jamwiki-web/src/main/java/org/jamwiki/servlets/SearchServlet.java
+++ b/jamwiki-web/src/main/java/org/jamwiki/servlets/SearchServlet.java
@@ -1,97 +1,97 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* 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 (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.servlets;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.jamwiki.Environment;
import org.jamwiki.WikiBase;
import org.jamwiki.WikiConfiguration;
import org.jamwiki.WikiMessage;
import org.jamwiki.model.SearchResultEntry;
import org.jamwiki.utils.LinkUtil;
import org.jamwiki.utils.WikiLogger;
import org.springframework.web.servlet.ModelAndView;
/**
* Used to display search results.
*
* @see org.jamwiki.SearchEngine
*/
public class SearchServlet extends JAMWikiServlet {
private static final WikiLogger logger = WikiLogger.getLogger(SearchServlet.class.getName());
/** The name of the JSP file used to render the servlet output when searching. */
protected static final String JSP_SEARCH = "search.jsp";
/** The name of the JSP file used to render the servlet output when displaying search results. */
protected static final String JSP_SEARCH_RESULTS = "search-results.jsp";
/**
*
*/
protected ModelAndView handleJAMWikiRequest(HttpServletRequest request, HttpServletResponse response, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
if (request.getParameter("jumpto") == null) {
search(request, next, pageInfo);
} else {
jumpTo(request, next, pageInfo);
}
return next;
}
/**
*
*/
private void jumpTo(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String virtualWiki = pageInfo.getVirtualWikiName();
String topic = request.getParameter("text");
String targetTopic = LinkUtil.isExistingArticle(virtualWiki, topic);
if (targetTopic != null) {
ServletUtil.redirect(next, virtualWiki, targetTopic);
} else {
next.addObject("notopic", topic);
this.search(request, next, pageInfo);
}
}
/**
*
*/
private void search(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String virtualWiki = pageInfo.getVirtualWikiName();
String searchField = request.getParameter("text");
if (request.getParameter("text") == null) {
pageInfo.setPageTitle(new WikiMessage("search.title"));
} else {
pageInfo.setPageTitle(new WikiMessage("searchresult.title", searchField));
}
+ next.addObject("searchConfig", WikiConfiguration.getCurrentSearchConfiguration());
// forward back to the search page if the request is blank or null
if (StringUtils.isBlank(searchField)) {
pageInfo.setContentJsp(JSP_SEARCH);
pageInfo.setSpecial(true);
return;
}
- next.addObject("searchConfig", WikiConfiguration.getCurrentSearchConfiguration());
// grab search engine instance and find
List<SearchResultEntry> results = WikiBase.getSearchEngine().findResults(virtualWiki, searchField);
next.addObject("searchField", searchField);
next.addObject("results", results);
pageInfo.setContentJsp(JSP_SEARCH_RESULTS);
pageInfo.setSpecial(true);
}
}
| false | true | private void search(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String virtualWiki = pageInfo.getVirtualWikiName();
String searchField = request.getParameter("text");
if (request.getParameter("text") == null) {
pageInfo.setPageTitle(new WikiMessage("search.title"));
} else {
pageInfo.setPageTitle(new WikiMessage("searchresult.title", searchField));
}
// forward back to the search page if the request is blank or null
if (StringUtils.isBlank(searchField)) {
pageInfo.setContentJsp(JSP_SEARCH);
pageInfo.setSpecial(true);
return;
}
next.addObject("searchConfig", WikiConfiguration.getCurrentSearchConfiguration());
// grab search engine instance and find
List<SearchResultEntry> results = WikiBase.getSearchEngine().findResults(virtualWiki, searchField);
next.addObject("searchField", searchField);
next.addObject("results", results);
pageInfo.setContentJsp(JSP_SEARCH_RESULTS);
pageInfo.setSpecial(true);
}
| private void search(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String virtualWiki = pageInfo.getVirtualWikiName();
String searchField = request.getParameter("text");
if (request.getParameter("text") == null) {
pageInfo.setPageTitle(new WikiMessage("search.title"));
} else {
pageInfo.setPageTitle(new WikiMessage("searchresult.title", searchField));
}
next.addObject("searchConfig", WikiConfiguration.getCurrentSearchConfiguration());
// forward back to the search page if the request is blank or null
if (StringUtils.isBlank(searchField)) {
pageInfo.setContentJsp(JSP_SEARCH);
pageInfo.setSpecial(true);
return;
}
// grab search engine instance and find
List<SearchResultEntry> results = WikiBase.getSearchEngine().findResults(virtualWiki, searchField);
next.addObject("searchField", searchField);
next.addObject("results", results);
pageInfo.setContentJsp(JSP_SEARCH_RESULTS);
pageInfo.setSpecial(true);
}
|
diff --git a/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java b/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java
index 07bed72e5..98746809e 100644
--- a/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java
+++ b/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNCommitUtil.java
@@ -1,1070 +1,1072 @@
/*
* ====================================================================
* Copyright (c) 2004-2009 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.internal.wc;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import org.tmatesoft.svn.core.SVNCancelException;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.SVNProperty;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.util.SVNEncodingUtil;
import org.tmatesoft.svn.core.internal.util.SVNHashMap;
import org.tmatesoft.svn.core.internal.util.SVNHashSet;
import org.tmatesoft.svn.core.internal.util.SVNPathUtil;
import org.tmatesoft.svn.core.internal.util.SVNURLUtil;
import org.tmatesoft.svn.core.internal.wc.admin.SVNAdminArea;
import org.tmatesoft.svn.core.internal.wc.admin.SVNEntry;
import org.tmatesoft.svn.core.internal.wc.admin.SVNVersionedProperties;
import org.tmatesoft.svn.core.internal.wc.admin.SVNWCAccess;
import org.tmatesoft.svn.core.io.ISVNEditor;
import org.tmatesoft.svn.core.wc.ISVNCommitParameters;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNCommitItem;
import org.tmatesoft.svn.core.wc.SVNEvent;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNStatus;
import org.tmatesoft.svn.core.wc.SVNStatusClient;
import org.tmatesoft.svn.core.wc.SVNStatusType;
import org.tmatesoft.svn.core.wc.SVNTreeConflictDescription;
import org.tmatesoft.svn.core.wc.SVNWCUtil;
import org.tmatesoft.svn.util.SVNLogType;
/**
* @version 1.3
* @author TMate Software Ltd.
*/
public class SVNCommitUtil {
public static final Comparator FILE_COMPARATOR = new Comparator() {
public int compare(Object o1, Object o2) {
if (o1 == null) {
return -1;
} else if (o2 == null) {
return 1;
} else if (o1 == o2) {
return 0;
}
File f1 = (File) o1;
File f2 = (File) o2;
return f1.getPath().compareTo(f2.getPath());
}
};
public static void driveCommitEditor(ISVNCommitPathHandler handler, Collection paths, ISVNEditor editor, long revision) throws SVNException {
if (paths == null || paths.isEmpty() || handler == null || editor == null) {
return;
}
String[] pathsArray = (String[]) paths.toArray(new String[paths.size()]);
Arrays.sort(pathsArray, SVNPathUtil.PATH_COMPARATOR);
int index = 0;
int depth = 0;
String lastPath = null;
if ("".equals(pathsArray[index])) {
handler.handleCommitPath("", editor);
lastPath = pathsArray[index];
index++;
} else {
editor.openRoot(revision);
}
depth++;
for (; index < pathsArray.length; index++) {
String commitPath = pathsArray[index];
if (!SVNPathUtil.isCanonical(commitPath)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNKNOWN,
"Assertion failed in SVNCommitUtil.driveCommitEditor(): path ''{0}'' is not canonical",
commitPath);
SVNErrorManager.error(err, SVNLogType.DEFAULT);
}
String commonAncestor = lastPath == null || "".equals(lastPath) ? "" : SVNPathUtil.getCommonPathAncestor(commitPath, lastPath);
if (lastPath != null) {
while (!lastPath.equals(commonAncestor)) {
editor.closeDir();
depth--;
if (lastPath.lastIndexOf('/') >= 0) {
lastPath = lastPath.substring(0, lastPath.lastIndexOf('/'));
} else {
lastPath = "";
}
}
}
String relativeCommitPath = commitPath.substring(commonAncestor.length());
if (relativeCommitPath.startsWith("/")) {
relativeCommitPath = relativeCommitPath.substring(1);
}
for (StringTokenizer tokens = new StringTokenizer(
relativeCommitPath, "/"); tokens.hasMoreTokens();) {
String token = tokens.nextToken();
commonAncestor = "".equals(commonAncestor) ? token : commonAncestor + "/" + token;
if (!commonAncestor.equals(commitPath)) {
editor.openDir(commonAncestor, revision);
depth++;
} else {
break;
}
}
boolean closeDir = handler.handleCommitPath(commitPath, editor);
if (closeDir) {
lastPath = commitPath;
depth++;
} else {
if (index + 1 < pathsArray.length) {
lastPath = SVNPathUtil.removeTail(commitPath);
} else {
lastPath = commitPath;
}
}
}
while (depth > 0) {
editor.closeDir();
depth--;
}
}
public static SVNWCAccess createCommitWCAccess(File[] paths, SVNDepth depth, boolean force,
Collection relativePaths, final SVNStatusClient statusClient) throws SVNException {
String[] validatedPaths = new String[paths.length];
for (int i = 0; i < paths.length; i++) {
statusClient.checkCancelled();
File file = paths[i];
validatedPaths[i] = file.getAbsolutePath().replace(File.separatorChar, '/');
}
String rootPath = SVNPathUtil.condencePaths(validatedPaths, relativePaths, depth == SVNDepth.INFINITY);
if (rootPath == null) {
return null;
}
boolean lockAll = false;
if (depth == SVNDepth.FILES || depth == SVNDepth.IMMEDIATES) {
for (Iterator relPathsIter = relativePaths.iterator(); relPathsIter.hasNext();) {
String relPath = (String) relPathsIter.next();
if ("".equals(relPath)) {
lockAll = true;
break;
}
}
}
File baseDir = new File(rootPath).getAbsoluteFile();
rootPath = baseDir.getAbsolutePath().replace(File.separatorChar, '/');
Collection dirsToLock = new SVNHashSet(); // relative paths to lock.
Collection dirsToLockRecursively = new SVNHashSet();
if (relativePaths.isEmpty()) {
statusClient.checkCancelled();
String target = SVNWCManager.getActualTarget(baseDir);
if (!"".equals(target)) {
// we will have to lock target as well, not only base dir.
SVNFileType targetType = SVNFileType.getType(new File(rootPath));
relativePaths.add(target);
if (targetType == SVNFileType.DIRECTORY) {
// lock recursively if forced and copied...
if (depth == SVNDepth.INFINITY || depth == SVNDepth.IMMEDIATES ||
(force && isRecursiveCommitForced(baseDir))) {
// dir is copied, include children
dirsToLockRecursively.add(target);
} else {
dirsToLock.add(target);
}
}
baseDir = baseDir.getParentFile();
} else {
lockAll = true;
}
} else if (!lockAll) {
baseDir = adjustRelativePaths(baseDir, relativePaths);
// there are multiple paths.
for (Iterator targets = relativePaths.iterator(); targets.hasNext();) {
statusClient.checkCancelled();
String targetPath = (String) targets.next();
File targetFile = new File(baseDir, targetPath);
SVNFileType targetKind = SVNFileType.getType(targetFile);
if (targetKind == SVNFileType.DIRECTORY) {
if (depth == SVNDepth.INFINITY || depth == SVNDepth.IMMEDIATES ||
(force && isRecursiveCommitForced(targetFile))) {
dirsToLockRecursively.add(targetPath);
} else if (!targetFile.equals(baseDir)){
dirsToLock.add(targetPath);
}
}
if (!targetFile.equals(baseDir)) {
targetFile = targetFile.getParentFile();
targetPath = SVNPathUtil.removeTail(targetPath);
while (targetFile != null && !targetFile.equals(baseDir) && !dirsToLock.contains(targetPath)) {
dirsToLock.add(targetPath);
targetPath = SVNPathUtil.removeTail(targetPath);
targetFile = targetFile.getParentFile();
}
}
}
}
SVNWCAccess baseAccess = SVNWCAccess.newInstance(new ISVNEventHandler() {
public void handleEvent(SVNEvent event, double progress) throws SVNException {
}
public void checkCancelled() throws SVNCancelException {
statusClient.checkCancelled();
}
});
baseAccess.setOptions(statusClient.getOptions());
try {
baseAccess.open(baseDir, true, lockAll ? SVNWCAccess.INFINITE_DEPTH : 0);
statusClient.checkCancelled();
dirsToLock = new ArrayList(dirsToLock);
dirsToLockRecursively = new ArrayList(dirsToLockRecursively);
Collections.sort((List) dirsToLock, SVNPathUtil.PATH_COMPARATOR);
Collections.sort((List) dirsToLockRecursively, SVNPathUtil.PATH_COMPARATOR);
if (!lockAll) {
List uniqueDirsToLockRecursively = new ArrayList();
uniqueDirsToLockRecursively.addAll(dirsToLockRecursively);
Map processedPaths = new SVNHashMap();
for(Iterator ps = uniqueDirsToLockRecursively.iterator(); ps.hasNext();) {
String pathToLock = (String) ps.next();
if (processedPaths.containsKey(pathToLock)) {
//remove any duplicates
ps.remove();
continue;
}
processedPaths.put(pathToLock, pathToLock);
for(Iterator existing = dirsToLockRecursively.iterator(); existing.hasNext();) {
String existingPath = (String) existing.next();
if (pathToLock.startsWith(existingPath + "/")) {
// child of other path
ps.remove();
break;
}
}
}
Collections.sort(uniqueDirsToLockRecursively, SVNPathUtil.PATH_COMPARATOR);
dirsToLockRecursively = uniqueDirsToLockRecursively;
removeRedundantPaths(dirsToLockRecursively, dirsToLock);
for (Iterator nonRecusivePaths = dirsToLock.iterator(); nonRecusivePaths.hasNext();) {
statusClient.checkCancelled();
String path = (String) nonRecusivePaths.next();
File pathFile = new File(baseDir, path);
baseAccess.open(pathFile, true, 0);
}
for (Iterator recusivePaths = dirsToLockRecursively.iterator(); recusivePaths.hasNext();) {
statusClient.checkCancelled();
String path = (String) recusivePaths.next();
File pathFile = new File(baseDir, path);
baseAccess.open(pathFile, true, SVNWCAccess.INFINITE_DEPTH);
}
}
for(int i = 0; i < paths.length; i++) {
statusClient.checkCancelled();
File path = paths[i].getAbsoluteFile();
path = path.getAbsoluteFile();
try {
baseAccess.probeRetrieve(path);
} catch (SVNException e) {
SVNErrorMessage err = e.getErrorMessage().wrap("Are all the targets part of the same working copy?");
SVNErrorManager.error(err, SVNLogType.WC);
}
if (depth != SVNDepth.INFINITY && !force) {
if (SVNFileType.getType(path) == SVNFileType.DIRECTORY) {
// TODO replace with direct SVNStatusEditor call.
SVNStatus status = statusClient.doStatus(path, false);
if (status != null && (status.getContentsStatus() == SVNStatusType.STATUS_DELETED || status.getContentsStatus() == SVNStatusType.STATUS_REPLACED)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Cannot non-recursively commit a directory deletion");
SVNErrorManager.error(err, SVNLogType.WC);
}
}
}
}
// if commit is non-recursive and forced, remove those child dirs
// that were not explicitly added but are explicitly copied. ufff.
if (depth != SVNDepth.INFINITY && force) {
SVNAdminArea[] lockedDirs = baseAccess.getAdminAreas();
for (int i = 0; i < lockedDirs.length; i++) {
statusClient.checkCancelled();
SVNAdminArea dir = lockedDirs[i];
if (dir == null) {
// could be null for missing, but known dir.
continue;
}
SVNEntry rootEntry = baseAccess.getEntry(dir.getRoot(), true);
if (rootEntry.getCopyFromURL() != null) {
File dirRoot = dir.getRoot();
boolean keep = false;
for (int j = 0; j < paths.length; j++) {
if (dirRoot.equals(paths[j])) {
keep = true;
break;
}
}
if (!keep) {
baseAccess.closeAdminArea(dir.getRoot());
}
}
}
}
} catch (SVNException e) {
baseAccess.close();
throw e;
}
baseAccess.setAnchor(baseDir);
return baseAccess;
}
public static SVNWCAccess[] createCommitWCAccess2(File[] paths, SVNDepth depth, boolean force,
Map relativePathsMap, SVNStatusClient statusClient) throws SVNException {
Map rootsMap = new SVNHashMap(); // wc root file -> paths to be committed (paths).
Map localRootsCache = new SVNHashMap();
for (int i = 0; i < paths.length; i++) {
statusClient.checkCancelled();
File path = paths[i];
File rootPath = path;
if (rootPath.isFile()) {
rootPath = rootPath.getParentFile();
}
File wcRoot = localRootsCache.containsKey(rootPath) ? (File) localRootsCache.get(rootPath) : SVNWCUtil.getWorkingCopyRoot(rootPath, true);
localRootsCache.put(path, wcRoot);
if (!rootsMap.containsKey(wcRoot)) {
rootsMap.put(wcRoot, new ArrayList());
}
Collection wcPaths = (Collection) rootsMap.get(wcRoot);
wcPaths.add(path);
}
Collection result = new ArrayList();
try {
for (Iterator roots = rootsMap.keySet().iterator(); roots.hasNext();) {
statusClient.checkCancelled();
File root = (File) roots.next();
Collection filesList = (Collection) rootsMap.get(root);
File[] filesArray = (File[]) filesList.toArray(new File[filesList.size()]);
Collection relativePaths = new ArrayList();
SVNWCAccess wcAccess = createCommitWCAccess(filesArray, depth, force, relativePaths, statusClient);
relativePathsMap.put(wcAccess, relativePaths);
result.add(wcAccess);
}
} catch (SVNException e) {
for (Iterator wcAccesses = result.iterator(); wcAccesses.hasNext();) {
SVNWCAccess wcAccess = (SVNWCAccess) wcAccesses.next();
wcAccess.close();
}
throw e;
}
return (SVNWCAccess[]) result.toArray(new SVNWCAccess[result.size()]);
}
public static SVNCommitItem[] harvestCommitables(SVNWCAccess baseAccess, Collection paths, Map lockTokens,
boolean justLocked, SVNDepth depth, boolean force, Collection changelists,
ISVNCommitParameters params) throws SVNException {
Map commitables = new TreeMap(FILE_COMPARATOR);
Collection danglers = new SVNHashSet();
Iterator targets = paths.iterator();
boolean isRecursionForced = false;
do {
String target = targets.hasNext() ? (String) targets.next() : "";
baseAccess.checkCancelled();
// get entry for target
File targetFile = new File(baseAccess.getAnchor(), target);
String targetName = "".equals(target) ? "" : SVNPathUtil.tail(target);
String parentPath = SVNPathUtil.removeTail(target);
SVNAdminArea dir = baseAccess.probeRetrieve(targetFile);
SVNEntry entry = null;
try {
entry = baseAccess.getVersionedEntry(targetFile, false);
} catch (SVNException e) {
if (e.getErrorMessage() != null &&
e.getErrorMessage().getErrorCode() == SVNErrorCode.ENTRY_NOT_FOUND) {
SVNTreeConflictDescription tc = baseAccess.getTreeConflict(targetFile);
if (tc != null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT, "Aborting commit: ''{0}'' remains in conflict", targetFile);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
throw e;
}
String url = null;
if (entry.getURL() == null) {
// it could be missing directory.
if (!entry.isThisDir() && entry.getName() != null &&
entry.isDirectory() && !(entry.isScheduledForAddition() || entry.isScheduledForReplacement()) && SVNFileType.getType(targetFile) == SVNFileType.NONE) {
File parentDir = targetFile.getParentFile();
if (parentDir != null) {
SVNEntry parentEntry = baseAccess.getEntry(parentDir, false);
if (parentEntry != null) {
url = SVNPathUtil.append(parentEntry.getURL(), SVNEncodingUtil.uriEncode(entry.getName()));
}
}
}
if (url == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT, "Entry for ''{0}'' has no URL", targetFile);
SVNErrorManager.error(err, SVNLogType.WC);
}
} else {
url = entry.getURL();
}
SVNEntry parentEntry = null;
if (entry.isScheduledForAddition() || entry.isScheduledForReplacement()) {
// get parent (for file or dir-> get ""), otherwise open parent
// dir and get "".
try {
baseAccess.retrieve(targetFile.getParentFile());
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) {
baseAccess.open(targetFile.getParentFile(), true, 0);
} else {
throw e;
}
}
parentEntry = baseAccess.getEntry(targetFile.getParentFile(), false);
if (parentEntry == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT,
"''{0}'' is scheduled for addition within unversioned parent", targetFile);
SVNErrorManager.error(err, SVNLogType.WC);
} else if (parentEntry.isScheduledForAddition() || parentEntry.isScheduledForReplacement()) {
danglers.add(targetFile.getParentFile());
}
}
SVNDepth forcedDepth = depth;
if (entry.isCopied() && entry.getSchedule() == null) {
// if commit is forced => we could collect this entry, assuming
// that its parent is already included into commit
// it will be later removed from commit anyway.
if (!force) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET,
"Entry for ''{0}''"
+ " is marked as 'copied' but is not itself scheduled\n"
+ "for addition. Perhaps you're committing a target that is\n"
+ "inside an unversioned (or not-yet-versioned) directory?", targetFile);
SVNErrorManager.error(err, SVNLogType.WC);
} else {
// just do not process this item as in case of recursive
// commit.
continue;
}
} else if (entry.isCopied() && entry.isScheduledForAddition()) {
if (force) {
isRecursionForced = depth != SVNDepth.INFINITY;
forcedDepth = SVNDepth.INFINITY;
}
} else if (entry.isScheduledForDeletion() && force && depth != SVNDepth.INFINITY) {
// if parent is also deleted -> skip this entry
if (!"".equals(targetName)) {
parentEntry = dir.getEntry("", false);
} else {
File parentFile = targetFile.getParentFile();
try {
baseAccess.retrieve(parentFile);
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) {
baseAccess.open(targetFile.getParentFile(), true, 0);
} else {
throw e;
}
}
parentEntry = baseAccess.getEntry(parentFile, false);
}
if (parentEntry != null && parentEntry.isScheduledForDeletion() && paths.contains(parentPath)) {
continue;
}
// this recursion is not considered as "forced", all children should be
// deleted anyway.
forcedDepth = SVNDepth.INFINITY;
}
// check ancestors for tc.
File ancestorPath = dir.getRoot();
SVNWCAccess localAccess = SVNWCAccess.newInstance(null);
localAccess.open(ancestorPath, false, 0);
try {
while (true) {
boolean isRoot = localAccess.isWCRoot(ancestorPath);
if (isRoot) {
break;
}
File pPath = ancestorPath.getParentFile();
localAccess.open(pPath, false, 0);
if (localAccess.hasTreeConflict(ancestorPath)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT,
"Aborting commit: ''{0}'' remains in tree-conflict", ancestorPath);
SVNErrorManager.error(err, SVNLogType.WC);
}
ancestorPath = pPath;
}
} finally {
localAccess.close();
}
// String relativePath = entry.getKind() == SVNNodeKind.DIR ? target : SVNPathUtil.removeTail(target);
harvestCommitables(commitables, dir, targetFile, parentEntry, entry, url, null, false, false,
justLocked, lockTokens, forcedDepth, isRecursionForced, changelists, params, null);
} while (targets.hasNext());
for (Iterator ds = danglers.iterator(); ds.hasNext();) {
baseAccess.checkCancelled();
File file = (File) ds.next();
if (!commitables.containsKey(file)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.ILLEGAL_TARGET,
"''{0}'' is not under version control\n"
+ "and is not part of the commit, \n"
+ "yet its child is part of the commit", file);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
if (isRecursionForced) {
// if commit is non-recursive and forced and there are elements included into commit
// that not only 'copied' but also has local mods (modified or deleted), remove those items?
// or not?
for (Iterator items = commitables.values().iterator(); items.hasNext();) {
baseAccess.checkCancelled();
SVNCommitItem item = (SVNCommitItem) items.next();
if (item.isDeleted()) {
// to detect deleted copied items.
File file = item.getFile();
if (item.getKind() == SVNNodeKind.DIR) {
if (!file.exists()) {
continue;
}
} else {
String name = SVNPathUtil.tail(item.getPath());
SVNAdminArea dir = baseAccess.retrieve(item.getFile().getParentFile());
if (!dir.getBaseFile(name, false).exists()) {
continue;
}
}
}
if (item.isContentsModified() || item.isDeleted() || item.isPropertiesModified()) {
// if item was not explicitly included into commit, then just make it 'added'
// but do not remove that are marked as 'deleted'
String itemPath = item.getPath();
if (!paths.contains(itemPath)) {
items.remove();
}
}
}
}
return (SVNCommitItem[]) commitables.values().toArray(new SVNCommitItem[commitables.values().size()]);
}
public static SVNURL translateCommitables(SVNCommitItem[] items, Map decodedPaths) throws SVNException {
Map itemsMap = new SVNHashMap();
for (int i = 0; i < items.length; i++) {
SVNCommitItem item = items[i];
if (itemsMap.containsKey(item.getURL())) {
SVNCommitItem oldItem = (SVNCommitItem) itemsMap.get(item.getURL());
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_DUPLICATE_COMMIT_URL,
"Cannot commit both ''{0}'' and ''{1}'' as they refer to the same URL",
new Object[] {item.getFile(), oldItem.getFile()});
SVNErrorManager.error(err, SVNLogType.WC);
}
itemsMap.put(item.getURL(), item);
}
Iterator urls = itemsMap.keySet().iterator();
SVNURL baseURL = (SVNURL) urls.next();
while (urls.hasNext()) {
SVNURL url = (SVNURL) urls.next();
baseURL = SVNURLUtil.getCommonURLAncestor(baseURL, url);
}
if (itemsMap.containsKey(baseURL)) {
SVNCommitItem root = (SVNCommitItem) itemsMap.get(baseURL);
if (root.getKind() != SVNNodeKind.DIR) {
baseURL = baseURL.removePathTail();
} else if (root.getKind() == SVNNodeKind.DIR
&& (root.isAdded() || root.isDeleted() || root.isCopied() || root.isLocked())) {
baseURL = baseURL.removePathTail();
}
}
if (baseURL == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL,
"Cannot compute base URL for commit operation");
SVNErrorManager.error(err, SVNLogType.WC);
}
for (Iterator iterator = itemsMap.keySet().iterator(); iterator.hasNext();) {
SVNURL url = (SVNURL) iterator.next();
SVNCommitItem item = (SVNCommitItem) itemsMap.get(url);
String realPath = url.equals(baseURL) ? "" : SVNPathUtil.getRelativePath(baseURL.getPath(), url.getPath());
decodedPaths.put(realPath, item);
}
return baseURL;
}
public static Map translateLockTokens(Map lockTokens, String baseURL) {
Map translatedLocks = new TreeMap();
for (Iterator urls = lockTokens.keySet().iterator(); urls.hasNext();) {
String url = (String) urls.next();
String token = (String) lockTokens.get(url);
url = url.equals(baseURL) ? "" : url.substring(baseURL.length() + 1);
translatedLocks.put(SVNEncodingUtil.uriDecode(url), token);
}
lockTokens.clear();
lockTokens.putAll(translatedLocks);
return lockTokens;
}
public static void harvestCommitables(Map commitables, SVNAdminArea dir, File path, SVNEntry parentEntry,
SVNEntry entry, String url, String copyFromURL, boolean copyMode, boolean addsOnly,
boolean justLocked, Map lockTokens, SVNDepth depth, boolean forcedRecursion,
Collection changelists, ISVNCommitParameters params, Map pathsToExternalsProperties) throws SVNException {
if (commitables.containsKey(path)) {
return;
}
if (dir != null && dir.getWCAccess() != null) {
dir.getWCAccess().checkCancelled();
}
long cfRevision = entry.getCopyFromRevision();
String cfURL = null;
if (entry.getKind() != SVNNodeKind.DIR
&& entry.getKind() != SVNNodeKind.FILE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
SVNFileType fileType = SVNFileType.getType(path);
if (fileType == SVNFileType.UNKNOWN) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
String specialPropertyValue = dir.getProperties(entry.getName()).getStringPropertyValue(SVNProperty.SPECIAL);
boolean specialFile = fileType == SVNFileType.SYMLINK;
if (SVNFileType.isSymlinkSupportEnabled()) {
if (((specialPropertyValue == null && specialFile) || (SVNFileUtil.symlinksSupported() && specialPropertyValue != null && !specialFile))
&& fileType != SVNFileType.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNEXPECTED_KIND, "Entry ''{0}'' has unexpectedly changed special status", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
boolean propConflicts;
boolean textConflicts = false;
boolean treeConflicts = dir.hasTreeConflict(entry.getName());
SVNAdminArea entries = null;
if (entry.getKind() == SVNNodeKind.DIR) {
SVNAdminArea childDir = null;
try {
childDir = dir.getWCAccess().retrieve(dir.getFile(entry.getName()));
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) {
childDir = null;
} else {
throw e;
}
}
if (childDir != null && childDir.entries(true) != null) {
entries = childDir;
if (entries.getEntry("", false) != null) {
entry = entries.getEntry("", false);
dir = childDir;
}
}
propConflicts = dir.hasPropConflict(entry.getName());
Map tcs = entry.getTreeConflicts();
for (Iterator keys = tcs.keySet().iterator(); keys.hasNext();) {
File entryPath = (File) keys.next();
SVNTreeConflictDescription tc = (SVNTreeConflictDescription) tcs.get(entryPath);
if (tc.getNodeKind() == SVNNodeKind.DIR && depth == SVNDepth.FILES) {
continue;
}
SVNEntry conflictingEntry = null;
if (tc.getNodeKind() == SVNNodeKind.DIR) {
// get dir admin area and root entry
SVNAdminArea childConflictingDir = dir.getWCAccess().getAdminArea(entryPath);
if (childConflictingDir != null) {
conflictingEntry = childConflictingDir.getEntry("", true);
}
conflictingEntry = childDir.getEntry(entryPath.getName(), true);
} else {
conflictingEntry = dir.getEntry(entryPath.getName(), true);
}
if (changelists == null || changelists.isEmpty() ||
(conflictingEntry != null && SVNWCAccess.matchesChangeList(changelists, conflictingEntry))) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT,
"Aborting commit: ''{0}'' remains in conflict", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
} else {
propConflicts = dir.hasPropConflict(entry.getName());
textConflicts = dir.hasTextConflict(entry.getName());
}
if (propConflicts || textConflicts || treeConflicts) {
if (SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT,
"Aborting commit: ''{0}'' remains in conflict", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
if (entry.getURL() != null && !copyMode) {
url = entry.getURL();
}
boolean commitDeletion = !addsOnly
&& ((entry.isDeleted() && entry.getSchedule() == null) || entry.isScheduledForDeletion() || entry.isScheduledForReplacement());
if (!addsOnly && !commitDeletion && fileType == SVNFileType.NONE && params != null) {
ISVNCommitParameters.Action action =
entry.getKind() == SVNNodeKind.DIR ? params.onMissingDirectory(path) : params.onMissingFile(path);
if (action == ISVNCommitParameters.ERROR) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy file ''{0}'' is missing", path);
SVNErrorManager.error(err, SVNLogType.WC);
} else if (action == ISVNCommitParameters.DELETE) {
commitDeletion = true;
entry.scheduleForDeletion();
dir.saveEntries(false);
}
}
boolean commitAddition = false;
boolean commitCopy = false;
if (entry.isScheduledForAddition() || entry.isScheduledForReplacement()) {
commitAddition = true;
if (entry.getCopyFromURL() != null) {
cfURL = entry.getCopyFromURL();
addsOnly = false;
commitCopy = true;
} else {
addsOnly = true;
}
}
if ((entry.isCopied() || copyMode) && !entry.isDeleted() && entry.getSchedule() == null) {
long parentRevision = entry.getRevision() - 1;
boolean switched = false;
if (entry != null && parentEntry != null) {
switched = !entry.getURL().equals(SVNPathUtil.append(parentEntry.getURL(),
SVNEncodingUtil.uriEncode(path.getName())));
}
if (!switched && !dir.getWCAccess().isWCRoot(path)) {
if (parentEntry != null) {
parentRevision = parentEntry.getRevision();
}
} else if (!copyMode) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT,
"Did not expect ''{0}'' to be a working copy root", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
if (parentRevision != entry.getRevision()) {
commitAddition = true;
commitCopy = true;
addsOnly = false;
cfRevision = entry.getRevision();
if (copyMode) {
cfURL = entry.getURL();
} else if (copyFromURL != null) {
cfURL = copyFromURL;
} else {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL,
"Commit item ''{0}'' has copy flag but no copyfrom URL", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
}
boolean textModified = false;
boolean propsModified = false;
boolean commitLock;
if (commitAddition) {
SVNFileType addedFileType = SVNFileType.getType(path);
if (addedFileType == SVNFileType.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_PATH_NOT_FOUND,
"''{0}'' is scheduled for addition, but is missing", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
SVNVersionedProperties props = dir.getProperties(entry.getName());
SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName());
SVNProperties propDiff = null;
if (entry.isScheduledForReplacement()) {
propDiff = props.asMap();
} else {
propDiff = baseProps.compareTo(props).asMap();
}
boolean eolChanged = textModified = propDiff != null && propDiff.containsName(SVNProperty.EOL_STYLE);
boolean charsetChanged = propDiff != null && propDiff.containsName(SVNProperty.CHARSET);
textModified = eolChanged || charsetChanged;
if (entry.getKind() == SVNNodeKind.FILE) {
if (commitCopy) {
textModified = propDiff != null && (propDiff.containsName(SVNProperty.EOL_STYLE) || propDiff.containsName(SVNProperty.CHARSET));
if (!textModified) {
textModified = dir.hasTextModifications(entry.getName(), eolChanged);
}
} else {
textModified = true;
}
}
propsModified = propDiff != null && !propDiff.isEmpty();
} else if (!commitDeletion) {
SVNVersionedProperties props = dir.getProperties(entry.getName());
SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName());
SVNProperties propDiff = baseProps.compareTo(props).asMap();
boolean forceComparison = textModified = propDiff != null && (propDiff.containsName(SVNProperty.EOL_STYLE) || propDiff.containsName(SVNProperty.CHARSET));
propsModified = propDiff != null && !propDiff.isEmpty();
if (entry.getKind() == SVNNodeKind.FILE) {
textModified = dir.hasTextModifications(entry.getName(), forceComparison);
}
}
commitLock = entry.getLockToken() != null && (justLocked || textModified || propsModified
|| commitDeletion || commitAddition || commitCopy);
if (commitAddition || commitDeletion || textModified || propsModified
|| commitCopy || commitLock) {
if (SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNCommitItem item = new SVNCommitItem(path,
SVNURL.parseURIEncoded(url), cfURL != null ? SVNURL.parseURIEncoded(cfURL) : null, entry.getKind(),
SVNRevision.create(entry.getRevision()), SVNRevision.create(cfRevision),
commitAddition, commitDeletion, propsModified, textModified, commitCopy,
commitLock);
String itemPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor()));
if ("".equals(itemPath)) {
itemPath += entry.getName();
} else if (!"".equals(entry.getName())) {
itemPath += "/" + entry.getName();
}
item.setPath(itemPath);
commitables.put(path, item);
if (lockTokens != null && entry.getLockToken() != null) {
lockTokens.put(url, entry.getLockToken());
}
}
}
//collect externals properties
if (pathsToExternalsProperties != null && SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNVersionedProperties props = dir.getProperties(entry.getName());
String externalsProperty = props.getStringPropertyValue(SVNProperty.EXTERNALS);
if (externalsProperty != null) {
pathsToExternalsProperties.put(dir.getFile(entry.getName()), externalsProperty);
}
}
if (entries != null && SVNDepth.EMPTY.compareTo(depth) < 0 && (commitAddition || !commitDeletion)) {
// recurse.
for (Iterator ents = entries.entries(copyMode); ents.hasNext();) {
if (dir != null && dir.getWCAccess() != null) {
dir.getWCAccess().checkCancelled();
}
SVNEntry currentEntry = (SVNEntry) ents.next();
if (currentEntry.isThisDir()) {
continue;
}
// if recursion is forced and entry is explicitly copied, skip it.
if (forcedRecursion && currentEntry.isCopied() && currentEntry.getCopyFromURL() != null) {
continue;
}
if (currentEntry.getDepth() == SVNDepth.EXCLUDE) {
continue;
}
String currentCFURL = cfURL != null ? cfURL : copyFromURL;
if (currentCFURL != null) {
currentCFURL = SVNPathUtil.append(currentCFURL, SVNEncodingUtil.uriEncode(currentEntry.getName()));
}
String currentURL = currentEntry.getURL();
if (copyMode || currentEntry.getURL() == null) {
currentURL = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(currentEntry.getName()));
}
File currentFile = dir.getFile(currentEntry.getName());
SVNAdminArea childDir;
if (currentEntry.getKind() == SVNNodeKind.DIR) {
if (SVNDepth.FILES.compareTo(depth) >= 0) {
continue;
}
try {
childDir = dir.getWCAccess().retrieve(dir.getFile(currentEntry.getName()));
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) {
childDir = null;
} else {
throw e;
}
}
if (childDir == null) {
SVNFileType currentType = SVNFileType.getType(currentFile);
if (currentType == SVNFileType.NONE && currentEntry.isScheduledForDeletion()) {
if (SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNCommitItem item = new SVNCommitItem(currentFile,
SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(),
SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false,
false, false, false);
String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor()));
item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName()));
commitables.put(currentFile, item);
continue;
}
} else if (currentType != SVNFileType.NONE) {
// directory is not missing, but obstructed,
// or no special params are specified.
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile);
SVNErrorManager.error(err, SVNLogType.WC);
} else {
ISVNCommitParameters.Action action =
params != null ? params.onMissingDirectory(dir.getFile(currentEntry.getName())) : ISVNCommitParameters.ERROR;
if (action == ISVNCommitParameters.DELETE) {
SVNCommitItem item = new SVNCommitItem(currentFile,
SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(),
SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false,
false, false, false);
String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor()));
item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName()));
commitables.put(currentFile, item);
currentEntry.scheduleForDeletion();
entries.saveEntries(false);
continue;
- } else if (action != ISVNCommitParameters.SKIP) {
+ } else if (action == ISVNCommitParameters.ERROR) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile);
SVNErrorManager.error(err, SVNLogType.WC);
+ } else {
+ continue;
}
}
}
}
SVNDepth depthBelowHere = depth;
if (depth == SVNDepth.FILES || depth == SVNDepth.IMMEDIATES) {
depthBelowHere = SVNDepth.EMPTY;
}
harvestCommitables(commitables, dir, currentFile, entry, currentEntry, currentURL,
currentCFURL, copyMode, addsOnly, justLocked, lockTokens, depthBelowHere,
forcedRecursion, changelists, params, pathsToExternalsProperties);
}
}
if (lockTokens != null && entry.getKind() == SVNNodeKind.DIR && commitDeletion) {
// harvest lock tokens for deleted items.
collectLocks(dir, lockTokens);
}
}
private static void collectLocks(SVNAdminArea adminArea, Map lockTokens) throws SVNException {
for (Iterator ents = adminArea.entries(false); ents.hasNext();) {
SVNEntry entry = (SVNEntry) ents.next();
if (entry.getURL() != null && entry.getLockToken() != null) {
lockTokens.put(entry.getURL(), entry.getLockToken());
}
if (!adminArea.getThisDirName().equals(entry.getName()) && entry.isDirectory()) {
SVNAdminArea child;
try {
child = adminArea.getWCAccess().retrieve(adminArea.getFile(entry.getName()));
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) {
child = null;
} else {
throw e;
}
}
if (child != null) {
collectLocks(child, lockTokens);
}
}
}
adminArea.closeEntries();
}
private static void removeRedundantPaths(Collection dirsToLockRecursively, Collection dirsToLock) {
Map processedDirs = new SVNHashMap();
for (Iterator paths = dirsToLock.iterator(); paths.hasNext();) {
String path = (String) paths.next();
//check for path dublicates and remove them if any
if (processedDirs.containsKey(path)) {
paths.remove();
continue;
}
processedDirs.put(path, path);
if (dirsToLockRecursively.contains(path)) {
paths.remove();
} else {
for (Iterator recPaths = dirsToLockRecursively.iterator(); recPaths.hasNext();) {
String existingPath = (String) recPaths.next();
if (path.startsWith(existingPath + "/")) {
paths.remove();
break;
}
}
}
}
}
private static File adjustRelativePaths(File rootFile, Collection relativePaths) throws SVNException {
if (relativePaths.contains("")) {
String targetName = SVNWCManager.getActualTarget(rootFile);
if (!"".equals(targetName) && rootFile.getParentFile() != null) {
// there is a versioned parent.
rootFile = rootFile.getParentFile();
List result = new ArrayList();
for (Iterator paths = relativePaths.iterator(); paths.hasNext();) {
String path = (String) paths.next();
path = "".equals(path) ? targetName : SVNPathUtil.append(targetName, path);
if (!result.contains(path)) {
result.add(path);
}
}
relativePaths.clear();
Collections.sort(result);
relativePaths.addAll(result);
}
}
return rootFile;
}
private static boolean isRecursiveCommitForced(File directory) throws SVNException {
SVNWCAccess wcAccess = SVNWCAccess.newInstance(null);
try {
wcAccess.open(directory, false, 0);
SVNEntry targetEntry = wcAccess.getEntry(directory, false);
if (targetEntry != null) {
return targetEntry.isCopied() || targetEntry.isScheduledForDeletion() || targetEntry.isScheduledForReplacement();
}
} finally {
wcAccess.close();
}
return false;
}
public static String validateCommitMessage(String message) {
if (message == null) {
return message;
}
message = message.replaceAll("\r\n", "\n");
message = message.replace('\r', '\n');
return message;
}
}
| false | true | public static void harvestCommitables(Map commitables, SVNAdminArea dir, File path, SVNEntry parentEntry,
SVNEntry entry, String url, String copyFromURL, boolean copyMode, boolean addsOnly,
boolean justLocked, Map lockTokens, SVNDepth depth, boolean forcedRecursion,
Collection changelists, ISVNCommitParameters params, Map pathsToExternalsProperties) throws SVNException {
if (commitables.containsKey(path)) {
return;
}
if (dir != null && dir.getWCAccess() != null) {
dir.getWCAccess().checkCancelled();
}
long cfRevision = entry.getCopyFromRevision();
String cfURL = null;
if (entry.getKind() != SVNNodeKind.DIR
&& entry.getKind() != SVNNodeKind.FILE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
SVNFileType fileType = SVNFileType.getType(path);
if (fileType == SVNFileType.UNKNOWN) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
String specialPropertyValue = dir.getProperties(entry.getName()).getStringPropertyValue(SVNProperty.SPECIAL);
boolean specialFile = fileType == SVNFileType.SYMLINK;
if (SVNFileType.isSymlinkSupportEnabled()) {
if (((specialPropertyValue == null && specialFile) || (SVNFileUtil.symlinksSupported() && specialPropertyValue != null && !specialFile))
&& fileType != SVNFileType.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNEXPECTED_KIND, "Entry ''{0}'' has unexpectedly changed special status", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
boolean propConflicts;
boolean textConflicts = false;
boolean treeConflicts = dir.hasTreeConflict(entry.getName());
SVNAdminArea entries = null;
if (entry.getKind() == SVNNodeKind.DIR) {
SVNAdminArea childDir = null;
try {
childDir = dir.getWCAccess().retrieve(dir.getFile(entry.getName()));
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) {
childDir = null;
} else {
throw e;
}
}
if (childDir != null && childDir.entries(true) != null) {
entries = childDir;
if (entries.getEntry("", false) != null) {
entry = entries.getEntry("", false);
dir = childDir;
}
}
propConflicts = dir.hasPropConflict(entry.getName());
Map tcs = entry.getTreeConflicts();
for (Iterator keys = tcs.keySet().iterator(); keys.hasNext();) {
File entryPath = (File) keys.next();
SVNTreeConflictDescription tc = (SVNTreeConflictDescription) tcs.get(entryPath);
if (tc.getNodeKind() == SVNNodeKind.DIR && depth == SVNDepth.FILES) {
continue;
}
SVNEntry conflictingEntry = null;
if (tc.getNodeKind() == SVNNodeKind.DIR) {
// get dir admin area and root entry
SVNAdminArea childConflictingDir = dir.getWCAccess().getAdminArea(entryPath);
if (childConflictingDir != null) {
conflictingEntry = childConflictingDir.getEntry("", true);
}
conflictingEntry = childDir.getEntry(entryPath.getName(), true);
} else {
conflictingEntry = dir.getEntry(entryPath.getName(), true);
}
if (changelists == null || changelists.isEmpty() ||
(conflictingEntry != null && SVNWCAccess.matchesChangeList(changelists, conflictingEntry))) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT,
"Aborting commit: ''{0}'' remains in conflict", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
} else {
propConflicts = dir.hasPropConflict(entry.getName());
textConflicts = dir.hasTextConflict(entry.getName());
}
if (propConflicts || textConflicts || treeConflicts) {
if (SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT,
"Aborting commit: ''{0}'' remains in conflict", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
if (entry.getURL() != null && !copyMode) {
url = entry.getURL();
}
boolean commitDeletion = !addsOnly
&& ((entry.isDeleted() && entry.getSchedule() == null) || entry.isScheduledForDeletion() || entry.isScheduledForReplacement());
if (!addsOnly && !commitDeletion && fileType == SVNFileType.NONE && params != null) {
ISVNCommitParameters.Action action =
entry.getKind() == SVNNodeKind.DIR ? params.onMissingDirectory(path) : params.onMissingFile(path);
if (action == ISVNCommitParameters.ERROR) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy file ''{0}'' is missing", path);
SVNErrorManager.error(err, SVNLogType.WC);
} else if (action == ISVNCommitParameters.DELETE) {
commitDeletion = true;
entry.scheduleForDeletion();
dir.saveEntries(false);
}
}
boolean commitAddition = false;
boolean commitCopy = false;
if (entry.isScheduledForAddition() || entry.isScheduledForReplacement()) {
commitAddition = true;
if (entry.getCopyFromURL() != null) {
cfURL = entry.getCopyFromURL();
addsOnly = false;
commitCopy = true;
} else {
addsOnly = true;
}
}
if ((entry.isCopied() || copyMode) && !entry.isDeleted() && entry.getSchedule() == null) {
long parentRevision = entry.getRevision() - 1;
boolean switched = false;
if (entry != null && parentEntry != null) {
switched = !entry.getURL().equals(SVNPathUtil.append(parentEntry.getURL(),
SVNEncodingUtil.uriEncode(path.getName())));
}
if (!switched && !dir.getWCAccess().isWCRoot(path)) {
if (parentEntry != null) {
parentRevision = parentEntry.getRevision();
}
} else if (!copyMode) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT,
"Did not expect ''{0}'' to be a working copy root", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
if (parentRevision != entry.getRevision()) {
commitAddition = true;
commitCopy = true;
addsOnly = false;
cfRevision = entry.getRevision();
if (copyMode) {
cfURL = entry.getURL();
} else if (copyFromURL != null) {
cfURL = copyFromURL;
} else {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL,
"Commit item ''{0}'' has copy flag but no copyfrom URL", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
}
boolean textModified = false;
boolean propsModified = false;
boolean commitLock;
if (commitAddition) {
SVNFileType addedFileType = SVNFileType.getType(path);
if (addedFileType == SVNFileType.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_PATH_NOT_FOUND,
"''{0}'' is scheduled for addition, but is missing", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
SVNVersionedProperties props = dir.getProperties(entry.getName());
SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName());
SVNProperties propDiff = null;
if (entry.isScheduledForReplacement()) {
propDiff = props.asMap();
} else {
propDiff = baseProps.compareTo(props).asMap();
}
boolean eolChanged = textModified = propDiff != null && propDiff.containsName(SVNProperty.EOL_STYLE);
boolean charsetChanged = propDiff != null && propDiff.containsName(SVNProperty.CHARSET);
textModified = eolChanged || charsetChanged;
if (entry.getKind() == SVNNodeKind.FILE) {
if (commitCopy) {
textModified = propDiff != null && (propDiff.containsName(SVNProperty.EOL_STYLE) || propDiff.containsName(SVNProperty.CHARSET));
if (!textModified) {
textModified = dir.hasTextModifications(entry.getName(), eolChanged);
}
} else {
textModified = true;
}
}
propsModified = propDiff != null && !propDiff.isEmpty();
} else if (!commitDeletion) {
SVNVersionedProperties props = dir.getProperties(entry.getName());
SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName());
SVNProperties propDiff = baseProps.compareTo(props).asMap();
boolean forceComparison = textModified = propDiff != null && (propDiff.containsName(SVNProperty.EOL_STYLE) || propDiff.containsName(SVNProperty.CHARSET));
propsModified = propDiff != null && !propDiff.isEmpty();
if (entry.getKind() == SVNNodeKind.FILE) {
textModified = dir.hasTextModifications(entry.getName(), forceComparison);
}
}
commitLock = entry.getLockToken() != null && (justLocked || textModified || propsModified
|| commitDeletion || commitAddition || commitCopy);
if (commitAddition || commitDeletion || textModified || propsModified
|| commitCopy || commitLock) {
if (SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNCommitItem item = new SVNCommitItem(path,
SVNURL.parseURIEncoded(url), cfURL != null ? SVNURL.parseURIEncoded(cfURL) : null, entry.getKind(),
SVNRevision.create(entry.getRevision()), SVNRevision.create(cfRevision),
commitAddition, commitDeletion, propsModified, textModified, commitCopy,
commitLock);
String itemPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor()));
if ("".equals(itemPath)) {
itemPath += entry.getName();
} else if (!"".equals(entry.getName())) {
itemPath += "/" + entry.getName();
}
item.setPath(itemPath);
commitables.put(path, item);
if (lockTokens != null && entry.getLockToken() != null) {
lockTokens.put(url, entry.getLockToken());
}
}
}
//collect externals properties
if (pathsToExternalsProperties != null && SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNVersionedProperties props = dir.getProperties(entry.getName());
String externalsProperty = props.getStringPropertyValue(SVNProperty.EXTERNALS);
if (externalsProperty != null) {
pathsToExternalsProperties.put(dir.getFile(entry.getName()), externalsProperty);
}
}
if (entries != null && SVNDepth.EMPTY.compareTo(depth) < 0 && (commitAddition || !commitDeletion)) {
// recurse.
for (Iterator ents = entries.entries(copyMode); ents.hasNext();) {
if (dir != null && dir.getWCAccess() != null) {
dir.getWCAccess().checkCancelled();
}
SVNEntry currentEntry = (SVNEntry) ents.next();
if (currentEntry.isThisDir()) {
continue;
}
// if recursion is forced and entry is explicitly copied, skip it.
if (forcedRecursion && currentEntry.isCopied() && currentEntry.getCopyFromURL() != null) {
continue;
}
if (currentEntry.getDepth() == SVNDepth.EXCLUDE) {
continue;
}
String currentCFURL = cfURL != null ? cfURL : copyFromURL;
if (currentCFURL != null) {
currentCFURL = SVNPathUtil.append(currentCFURL, SVNEncodingUtil.uriEncode(currentEntry.getName()));
}
String currentURL = currentEntry.getURL();
if (copyMode || currentEntry.getURL() == null) {
currentURL = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(currentEntry.getName()));
}
File currentFile = dir.getFile(currentEntry.getName());
SVNAdminArea childDir;
if (currentEntry.getKind() == SVNNodeKind.DIR) {
if (SVNDepth.FILES.compareTo(depth) >= 0) {
continue;
}
try {
childDir = dir.getWCAccess().retrieve(dir.getFile(currentEntry.getName()));
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) {
childDir = null;
} else {
throw e;
}
}
if (childDir == null) {
SVNFileType currentType = SVNFileType.getType(currentFile);
if (currentType == SVNFileType.NONE && currentEntry.isScheduledForDeletion()) {
if (SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNCommitItem item = new SVNCommitItem(currentFile,
SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(),
SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false,
false, false, false);
String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor()));
item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName()));
commitables.put(currentFile, item);
continue;
}
} else if (currentType != SVNFileType.NONE) {
// directory is not missing, but obstructed,
// or no special params are specified.
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile);
SVNErrorManager.error(err, SVNLogType.WC);
} else {
ISVNCommitParameters.Action action =
params != null ? params.onMissingDirectory(dir.getFile(currentEntry.getName())) : ISVNCommitParameters.ERROR;
if (action == ISVNCommitParameters.DELETE) {
SVNCommitItem item = new SVNCommitItem(currentFile,
SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(),
SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false,
false, false, false);
String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor()));
item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName()));
commitables.put(currentFile, item);
currentEntry.scheduleForDeletion();
entries.saveEntries(false);
continue;
} else if (action != ISVNCommitParameters.SKIP) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
}
}
SVNDepth depthBelowHere = depth;
if (depth == SVNDepth.FILES || depth == SVNDepth.IMMEDIATES) {
depthBelowHere = SVNDepth.EMPTY;
}
harvestCommitables(commitables, dir, currentFile, entry, currentEntry, currentURL,
currentCFURL, copyMode, addsOnly, justLocked, lockTokens, depthBelowHere,
forcedRecursion, changelists, params, pathsToExternalsProperties);
}
}
if (lockTokens != null && entry.getKind() == SVNNodeKind.DIR && commitDeletion) {
// harvest lock tokens for deleted items.
collectLocks(dir, lockTokens);
}
}
| public static void harvestCommitables(Map commitables, SVNAdminArea dir, File path, SVNEntry parentEntry,
SVNEntry entry, String url, String copyFromURL, boolean copyMode, boolean addsOnly,
boolean justLocked, Map lockTokens, SVNDepth depth, boolean forcedRecursion,
Collection changelists, ISVNCommitParameters params, Map pathsToExternalsProperties) throws SVNException {
if (commitables.containsKey(path)) {
return;
}
if (dir != null && dir.getWCAccess() != null) {
dir.getWCAccess().checkCancelled();
}
long cfRevision = entry.getCopyFromRevision();
String cfURL = null;
if (entry.getKind() != SVNNodeKind.DIR
&& entry.getKind() != SVNNodeKind.FILE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
SVNFileType fileType = SVNFileType.getType(path);
if (fileType == SVNFileType.UNKNOWN) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNKNOWN_KIND, "Unknown entry kind for ''{0}''", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
String specialPropertyValue = dir.getProperties(entry.getName()).getStringPropertyValue(SVNProperty.SPECIAL);
boolean specialFile = fileType == SVNFileType.SYMLINK;
if (SVNFileType.isSymlinkSupportEnabled()) {
if (((specialPropertyValue == null && specialFile) || (SVNFileUtil.symlinksSupported() && specialPropertyValue != null && !specialFile))
&& fileType != SVNFileType.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.NODE_UNEXPECTED_KIND, "Entry ''{0}'' has unexpectedly changed special status", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
boolean propConflicts;
boolean textConflicts = false;
boolean treeConflicts = dir.hasTreeConflict(entry.getName());
SVNAdminArea entries = null;
if (entry.getKind() == SVNNodeKind.DIR) {
SVNAdminArea childDir = null;
try {
childDir = dir.getWCAccess().retrieve(dir.getFile(entry.getName()));
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) {
childDir = null;
} else {
throw e;
}
}
if (childDir != null && childDir.entries(true) != null) {
entries = childDir;
if (entries.getEntry("", false) != null) {
entry = entries.getEntry("", false);
dir = childDir;
}
}
propConflicts = dir.hasPropConflict(entry.getName());
Map tcs = entry.getTreeConflicts();
for (Iterator keys = tcs.keySet().iterator(); keys.hasNext();) {
File entryPath = (File) keys.next();
SVNTreeConflictDescription tc = (SVNTreeConflictDescription) tcs.get(entryPath);
if (tc.getNodeKind() == SVNNodeKind.DIR && depth == SVNDepth.FILES) {
continue;
}
SVNEntry conflictingEntry = null;
if (tc.getNodeKind() == SVNNodeKind.DIR) {
// get dir admin area and root entry
SVNAdminArea childConflictingDir = dir.getWCAccess().getAdminArea(entryPath);
if (childConflictingDir != null) {
conflictingEntry = childConflictingDir.getEntry("", true);
}
conflictingEntry = childDir.getEntry(entryPath.getName(), true);
} else {
conflictingEntry = dir.getEntry(entryPath.getName(), true);
}
if (changelists == null || changelists.isEmpty() ||
(conflictingEntry != null && SVNWCAccess.matchesChangeList(changelists, conflictingEntry))) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT,
"Aborting commit: ''{0}'' remains in conflict", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
} else {
propConflicts = dir.hasPropConflict(entry.getName());
textConflicts = dir.hasTextConflict(entry.getName());
}
if (propConflicts || textConflicts || treeConflicts) {
if (SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_FOUND_CONFLICT,
"Aborting commit: ''{0}'' remains in conflict", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
if (entry.getURL() != null && !copyMode) {
url = entry.getURL();
}
boolean commitDeletion = !addsOnly
&& ((entry.isDeleted() && entry.getSchedule() == null) || entry.isScheduledForDeletion() || entry.isScheduledForReplacement());
if (!addsOnly && !commitDeletion && fileType == SVNFileType.NONE && params != null) {
ISVNCommitParameters.Action action =
entry.getKind() == SVNNodeKind.DIR ? params.onMissingDirectory(path) : params.onMissingFile(path);
if (action == ISVNCommitParameters.ERROR) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy file ''{0}'' is missing", path);
SVNErrorManager.error(err, SVNLogType.WC);
} else if (action == ISVNCommitParameters.DELETE) {
commitDeletion = true;
entry.scheduleForDeletion();
dir.saveEntries(false);
}
}
boolean commitAddition = false;
boolean commitCopy = false;
if (entry.isScheduledForAddition() || entry.isScheduledForReplacement()) {
commitAddition = true;
if (entry.getCopyFromURL() != null) {
cfURL = entry.getCopyFromURL();
addsOnly = false;
commitCopy = true;
} else {
addsOnly = true;
}
}
if ((entry.isCopied() || copyMode) && !entry.isDeleted() && entry.getSchedule() == null) {
long parentRevision = entry.getRevision() - 1;
boolean switched = false;
if (entry != null && parentEntry != null) {
switched = !entry.getURL().equals(SVNPathUtil.append(parentEntry.getURL(),
SVNEncodingUtil.uriEncode(path.getName())));
}
if (!switched && !dir.getWCAccess().isWCRoot(path)) {
if (parentEntry != null) {
parentRevision = parentEntry.getRevision();
}
} else if (!copyMode) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_CORRUPT,
"Did not expect ''{0}'' to be a working copy root", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
if (parentRevision != entry.getRevision()) {
commitAddition = true;
commitCopy = true;
addsOnly = false;
cfRevision = entry.getRevision();
if (copyMode) {
cfURL = entry.getURL();
} else if (copyFromURL != null) {
cfURL = copyFromURL;
} else {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.BAD_URL,
"Commit item ''{0}'' has copy flag but no copyfrom URL", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
}
}
boolean textModified = false;
boolean propsModified = false;
boolean commitLock;
if (commitAddition) {
SVNFileType addedFileType = SVNFileType.getType(path);
if (addedFileType == SVNFileType.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_PATH_NOT_FOUND,
"''{0}'' is scheduled for addition, but is missing", path);
SVNErrorManager.error(err, SVNLogType.WC);
}
SVNVersionedProperties props = dir.getProperties(entry.getName());
SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName());
SVNProperties propDiff = null;
if (entry.isScheduledForReplacement()) {
propDiff = props.asMap();
} else {
propDiff = baseProps.compareTo(props).asMap();
}
boolean eolChanged = textModified = propDiff != null && propDiff.containsName(SVNProperty.EOL_STYLE);
boolean charsetChanged = propDiff != null && propDiff.containsName(SVNProperty.CHARSET);
textModified = eolChanged || charsetChanged;
if (entry.getKind() == SVNNodeKind.FILE) {
if (commitCopy) {
textModified = propDiff != null && (propDiff.containsName(SVNProperty.EOL_STYLE) || propDiff.containsName(SVNProperty.CHARSET));
if (!textModified) {
textModified = dir.hasTextModifications(entry.getName(), eolChanged);
}
} else {
textModified = true;
}
}
propsModified = propDiff != null && !propDiff.isEmpty();
} else if (!commitDeletion) {
SVNVersionedProperties props = dir.getProperties(entry.getName());
SVNVersionedProperties baseProps = dir.getBaseProperties(entry.getName());
SVNProperties propDiff = baseProps.compareTo(props).asMap();
boolean forceComparison = textModified = propDiff != null && (propDiff.containsName(SVNProperty.EOL_STYLE) || propDiff.containsName(SVNProperty.CHARSET));
propsModified = propDiff != null && !propDiff.isEmpty();
if (entry.getKind() == SVNNodeKind.FILE) {
textModified = dir.hasTextModifications(entry.getName(), forceComparison);
}
}
commitLock = entry.getLockToken() != null && (justLocked || textModified || propsModified
|| commitDeletion || commitAddition || commitCopy);
if (commitAddition || commitDeletion || textModified || propsModified
|| commitCopy || commitLock) {
if (SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNCommitItem item = new SVNCommitItem(path,
SVNURL.parseURIEncoded(url), cfURL != null ? SVNURL.parseURIEncoded(cfURL) : null, entry.getKind(),
SVNRevision.create(entry.getRevision()), SVNRevision.create(cfRevision),
commitAddition, commitDeletion, propsModified, textModified, commitCopy,
commitLock);
String itemPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor()));
if ("".equals(itemPath)) {
itemPath += entry.getName();
} else if (!"".equals(entry.getName())) {
itemPath += "/" + entry.getName();
}
item.setPath(itemPath);
commitables.put(path, item);
if (lockTokens != null && entry.getLockToken() != null) {
lockTokens.put(url, entry.getLockToken());
}
}
}
//collect externals properties
if (pathsToExternalsProperties != null && SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNVersionedProperties props = dir.getProperties(entry.getName());
String externalsProperty = props.getStringPropertyValue(SVNProperty.EXTERNALS);
if (externalsProperty != null) {
pathsToExternalsProperties.put(dir.getFile(entry.getName()), externalsProperty);
}
}
if (entries != null && SVNDepth.EMPTY.compareTo(depth) < 0 && (commitAddition || !commitDeletion)) {
// recurse.
for (Iterator ents = entries.entries(copyMode); ents.hasNext();) {
if (dir != null && dir.getWCAccess() != null) {
dir.getWCAccess().checkCancelled();
}
SVNEntry currentEntry = (SVNEntry) ents.next();
if (currentEntry.isThisDir()) {
continue;
}
// if recursion is forced and entry is explicitly copied, skip it.
if (forcedRecursion && currentEntry.isCopied() && currentEntry.getCopyFromURL() != null) {
continue;
}
if (currentEntry.getDepth() == SVNDepth.EXCLUDE) {
continue;
}
String currentCFURL = cfURL != null ? cfURL : copyFromURL;
if (currentCFURL != null) {
currentCFURL = SVNPathUtil.append(currentCFURL, SVNEncodingUtil.uriEncode(currentEntry.getName()));
}
String currentURL = currentEntry.getURL();
if (copyMode || currentEntry.getURL() == null) {
currentURL = SVNPathUtil.append(url, SVNEncodingUtil.uriEncode(currentEntry.getName()));
}
File currentFile = dir.getFile(currentEntry.getName());
SVNAdminArea childDir;
if (currentEntry.getKind() == SVNNodeKind.DIR) {
if (SVNDepth.FILES.compareTo(depth) >= 0) {
continue;
}
try {
childDir = dir.getWCAccess().retrieve(dir.getFile(currentEntry.getName()));
} catch (SVNException e) {
if (e.getErrorMessage().getErrorCode() == SVNErrorCode.WC_NOT_LOCKED) {
childDir = null;
} else {
throw e;
}
}
if (childDir == null) {
SVNFileType currentType = SVNFileType.getType(currentFile);
if (currentType == SVNFileType.NONE && currentEntry.isScheduledForDeletion()) {
if (SVNWCAccess.matchesChangeList(changelists, entry)) {
SVNCommitItem item = new SVNCommitItem(currentFile,
SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(),
SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false,
false, false, false);
String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor()));
item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName()));
commitables.put(currentFile, item);
continue;
}
} else if (currentType != SVNFileType.NONE) {
// directory is not missing, but obstructed,
// or no special params are specified.
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile);
SVNErrorManager.error(err, SVNLogType.WC);
} else {
ISVNCommitParameters.Action action =
params != null ? params.onMissingDirectory(dir.getFile(currentEntry.getName())) : ISVNCommitParameters.ERROR;
if (action == ISVNCommitParameters.DELETE) {
SVNCommitItem item = new SVNCommitItem(currentFile,
SVNURL.parseURIEncoded(currentURL), null, currentEntry.getKind(),
SVNRevision.UNDEFINED, SVNRevision.UNDEFINED, false, true, false,
false, false, false);
String dirPath = dir.getRelativePath(dir.getWCAccess().retrieve(dir.getWCAccess().getAnchor()));
item.setPath(SVNPathUtil.append(dirPath, currentEntry.getName()));
commitables.put(currentFile, item);
currentEntry.scheduleForDeletion();
entries.saveEntries(false);
continue;
} else if (action == ISVNCommitParameters.ERROR) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_NOT_LOCKED, "Working copy ''{0}'' is missing or not locked", currentFile);
SVNErrorManager.error(err, SVNLogType.WC);
} else {
continue;
}
}
}
}
SVNDepth depthBelowHere = depth;
if (depth == SVNDepth.FILES || depth == SVNDepth.IMMEDIATES) {
depthBelowHere = SVNDepth.EMPTY;
}
harvestCommitables(commitables, dir, currentFile, entry, currentEntry, currentURL,
currentCFURL, copyMode, addsOnly, justLocked, lockTokens, depthBelowHere,
forcedRecursion, changelists, params, pathsToExternalsProperties);
}
}
if (lockTokens != null && entry.getKind() == SVNNodeKind.DIR && commitDeletion) {
// harvest lock tokens for deleted items.
collectLocks(dir, lockTokens);
}
}
|
diff --git a/src_new/org/argouml/ui/AboutBox.java b/src_new/org/argouml/ui/AboutBox.java
index 4bb7eb8..ed0f397 100644
--- a/src_new/org/argouml/ui/AboutBox.java
+++ b/src_new/org/argouml/ui/AboutBox.java
@@ -1,294 +1,297 @@
// Copyright (c) 1996-99 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.ui;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import javax.swing.plaf.metal.MetalLookAndFeel;
public class AboutBox extends JFrame {
////////////////////////////////////////////////////////////////
// instance varaibles
JTabbedPane _tabs = new JTabbedPane();
JLabel _splashButton = new JLabel("");
JTextArea _version = new JTextArea();
JTextArea _credits = new JTextArea();
JTextArea _contact = new JTextArea();
JTextArea _legal = new JTextArea();
////////////////////////////////////////////////////////////////
// constructor
public AboutBox() {
super("About Argo/UML");
String iconName = "Splash";
ImageIcon splashImage = loadIconResource(iconName, iconName);
int imgWidth = splashImage.getIconWidth();
int imgHeight = splashImage.getIconHeight();
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(scrSize.width/2 - imgWidth/2,
scrSize.height/2 - imgHeight/2);
//setSize(new Dimension(imgWidth + 10, imgHeight + 40));
getContentPane().setLayout(new BorderLayout(0, 0));
//_splashButton.setMargin(new Insets(0, 0, 0, 0));
_splashButton.setIcon(splashImage);
Font ctrlFont = MetalLookAndFeel.getControlTextFont();
// _version.setFont(ctrlFont);
// _credits.setFont(ctrlFont);
// _legal.setFont(ctrlFont);
// _contact.setFont(ctrlFont);
StringBuffer versionBuf = new StringBuffer(
- "ArgoUML Version 0.9.0\n"+
- "Built on 18/09/2000\n"+
+ "ArgoUML Version 0.9.1\n"+
+ "Built on March 2nd of 2001\n"+
"\n"+
"Needed:\n"+
" GEF (Graph Editing Framework)\n"+
" GIF generation code from www.acme.com (comes with GEF)\n"+
"\n"+
"Intended for use with:\n"+
" JDK 1.2 only plus\n"+
" A JAXP 1.0.1 compatible parser\n" +
" [Xerces-J 1.2.2 or later recommended, (xml.apache.org)]\n"+
- " Novosoft's NSUML 0.4.17 or higher (nsuml.sourceforge.net)\n"+
+ " Novosoft's NSUML 0.4.19 or higher (nsuml.sourceforge.net)\n"+
" Frank Finger's (TU-Dresden) OCL-Compiler (dresden-ocl.sourceforge.net)\n"+
"\n");
try {
String factoryClass = javax.xml.parsers.SAXParserFactory.newInstance().getClass().getName();
if(factoryClass.indexOf("org.apache.") >= 0) {
versionBuf.append("This product includes software developed by the\n");
versionBuf.append("Apache Software Foundation (http://www.apache.org/).\n");
}
}
catch(Exception e) {}
versionBuf.append("\n--- Generated version information: ---\n");
versionBuf.append(getVersionInfo(packageList));
String saxFactory = System.getProperty("javax.xml.parsers.SAXParserFactory");
if(saxFactory != null) {
versionBuf.append("SAX Parser Factory " + saxFactory+ " specified using system property\n");
}
try {
versionBuf.append("SAX Parser Factory " +
javax.xml.parsers.SAXParserFactory.newInstance().getClass().getName() + " will be used.\n");
}
catch(Exception ex) {
versionBuf.append("Error determining SAX Parser Factory\n.");
}
_version.setText(versionBuf.toString());
_credits.setText("ArgoUML was developed by the following:\n"+
"Project Lead:\n"+
" Jason Robbins (Collab.net)\n"+
" \n"+
- "Version 0.8 release manager:\n"+
+ "Version 0.9 release managers:\n"+
" Toby Baier (University of Hamburg, Germany)\n"+
" Marko Boger (GentleWare)\n"+
" \n"+
"Module Owners (contact these people for contributions):\n"+
" GEF: Edwin Park ([email protected])\n"+
" UML Diagrams: Marko Boger ([email protected])\n"+
" UML Metamodel, XMI: Toby Baier ([email protected])\n"+
" Plugin-support: Sean Chen ([email protected])\n"+
" Java RE: Andreas Rueckert ([email protected])\n"+
" Knowledge support: Jason Robbins ([email protected])\n"+
" User manual: Philippe Vanpeperstraete ([email protected])\n"+
" \n"+
"Contributing Developers (in no special order):\n"+
" Jim Holt\n"+
" Thomas Schaumburg\n"+
" David Glaser\n"+
" Toby Baier\n"+
" Eugenio Alvarez\n"+
" Clemens Eichler\n"+
" Curt Arnold\n"+
" Andreas Rueckert\n"+
" Frank Finger\n"+
" Stuart Zakon\n"+
" Frank Wienberg\n"+
"\n"+
"Credits for previous versions:\n"+
"\nResearchers: \n"+
" Jason Robbins\n"+
" David Redmiles\n"+
" David Hilbert\n"+
"\nDevelopers and Testers: \n"+
" Jason Robbins\n"+
" Adam Gauthier\n"+
" Adam Bonner\n"+
" David Hilbert\n"+
" ICS 125 team Spring 1996\n"+
" ICS 125 teams Spring 1998\n"+
"\nContributing Developers:\n"+
" Scott Guyer\n"+
" Piotr Kaminski\n"+
" Nick Santucci\n"+
" Eric Lefevre\n"+
" Sean Chen\n" +
" Jim Holt\n" +
" Steve Poole\n"
);
_contact.setText("For more information on the Argo project:\n"+
" + Visit our web site:\n"+
" http://www.ArgoUML.org\n"+
" + Send email to Jason Robbins at:\n"+
" [email protected]\n"+
+ " + Send email to the developers mailing-list at:\n"+
+ " [email protected]\n"+
+ " (subscribe by sending a message to [email protected]\n"+
" + Read our conference and journal papers:\n"+
" (list of publications: KBSE'96, IUI'98, ICSE'98, etc.)"
);
String s = "";
s+="Copyright (c) 1996-99 The Regents of the University of California.\n";
s+="All Rights Reserved. Permission to use, copy, modify, and distribute\n";
s+="this software and its documentation without fee, and without a written\n";
s+="agreement is hereby granted, provided that the above copyright notice\n";
s+="and this paragraph appear in all copies. This software program and\n";
s+="documentation are copyrighted by The Regents of the University of\n";
s+="California. The software program and documentation are supplied ''as\n";
s+="is'', without any accompanying services from The Regents. The Regents\n";
s+="do not warrant that the operation of the program will be uninterrupted\n";
s+="or error-free. The end-user understands that the program was\n";
s+="developed for research purposes and is advised not to rely exclusively\n";
s+="on the program for any reason. IN NO EVENT SHALL THE UNIVERSITY OF\n";
s+="CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,\n";
s+="INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING\n";
s+="OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE\n";
s+="UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n";
s+="DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n";
s+="WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n";
s+="MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n";
s+="PROVIDED HEREUNDER IS ON AN ''AS IS'' BASIS, AND THE UNIVERSITY OF\n";
s+="CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n";
s+="UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n";
_legal.setText(s);
_tabs.addTab("Splash", _splashButton);
_tabs.addTab("Version", new JScrollPane(_version));
_tabs.addTab("Credits", new JScrollPane(_credits));
_tabs.addTab("Contact Info", new JScrollPane(_contact));
_tabs.addTab("Legal", new JScrollPane(_legal));
getContentPane().setLayout(new BorderLayout(0, 0));
getContentPane().add(_tabs, BorderLayout.CENTER);
// add preloading progress bar?
setSize(imgWidth + 20, imgHeight + 50);
//pack();
}
////////////////////////////////////////////////////////////////
// static methods
static String packageList[] = new String[]{"org.argouml.application","ru.novosoft.uml","org.tigris.gef.base","org.xml.sax","java.lang"};
static String getVersionInfo(String packageList[])
{
String in = "";
StringBuffer sb = new StringBuffer();
for(int i=0;i<packageList.length;i++)
{
sb.append("Package: ");
sb.append(packageList[i]);
sb.append('\n');
Package pkg = Package.getPackage(packageList[i]);
if(pkg == null)
{
sb.append("-- No Versioning Information --\nMaybe you don't use the jar?\n\n");
continue;
}
in = pkg.getImplementationTitle();
if(in!=null)
{
sb.append("Component: ");
sb.append(in);
}
in = pkg.getImplementationVendor();
if(in!=null)
{
sb.append(", by: ");
sb.append(in);
}
in = pkg.getImplementationVersion();
if(in!=null)
{
sb.append(", version: ");
sb.append(in);
sb.append('\n');
}
sb.append('\n');
}
sb.append("Operation System is: ");
sb.append(System.getProperty("os.name", "unknown"));
sb.append('\n');
sb.append("Operation System Version: ");
sb.append(System.getProperty("os.version", "unknown"));
sb.append('\n');
return sb.toString();
}
protected static ImageIcon loadIconResource(String imgName, String desc) {
ImageIcon res = null;
try {
java.net.URL imgURL = AboutBox.class.getResource(imageName(imgName));
if (imgURL == null) return null;
//System.out.println(imgName);
//System.out.println(imgURL);
return new ImageIcon(imgURL, desc);
}
catch (Exception ex) {
System.out.println("Exception in loadIconResource");
ex.printStackTrace();
return new ImageIcon(desc);
}
}
protected static String imageName(String name) {
return "/org/argouml/Images/" + stripJunk(name) + ".gif";
}
protected static String stripJunk(String s) {
String res = "";
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (Character.isJavaIdentifierPart(c)) res += c;
}
return res;
}
} /* end class AboutBox */
| false | true | public AboutBox() {
super("About Argo/UML");
String iconName = "Splash";
ImageIcon splashImage = loadIconResource(iconName, iconName);
int imgWidth = splashImage.getIconWidth();
int imgHeight = splashImage.getIconHeight();
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(scrSize.width/2 - imgWidth/2,
scrSize.height/2 - imgHeight/2);
//setSize(new Dimension(imgWidth + 10, imgHeight + 40));
getContentPane().setLayout(new BorderLayout(0, 0));
//_splashButton.setMargin(new Insets(0, 0, 0, 0));
_splashButton.setIcon(splashImage);
Font ctrlFont = MetalLookAndFeel.getControlTextFont();
// _version.setFont(ctrlFont);
// _credits.setFont(ctrlFont);
// _legal.setFont(ctrlFont);
// _contact.setFont(ctrlFont);
StringBuffer versionBuf = new StringBuffer(
"ArgoUML Version 0.9.0\n"+
"Built on 18/09/2000\n"+
"\n"+
"Needed:\n"+
" GEF (Graph Editing Framework)\n"+
" GIF generation code from www.acme.com (comes with GEF)\n"+
"\n"+
"Intended for use with:\n"+
" JDK 1.2 only plus\n"+
" A JAXP 1.0.1 compatible parser\n" +
" [Xerces-J 1.2.2 or later recommended, (xml.apache.org)]\n"+
" Novosoft's NSUML 0.4.17 or higher (nsuml.sourceforge.net)\n"+
" Frank Finger's (TU-Dresden) OCL-Compiler (dresden-ocl.sourceforge.net)\n"+
"\n");
try {
String factoryClass = javax.xml.parsers.SAXParserFactory.newInstance().getClass().getName();
if(factoryClass.indexOf("org.apache.") >= 0) {
versionBuf.append("This product includes software developed by the\n");
versionBuf.append("Apache Software Foundation (http://www.apache.org/).\n");
}
}
catch(Exception e) {}
versionBuf.append("\n--- Generated version information: ---\n");
versionBuf.append(getVersionInfo(packageList));
String saxFactory = System.getProperty("javax.xml.parsers.SAXParserFactory");
if(saxFactory != null) {
versionBuf.append("SAX Parser Factory " + saxFactory+ " specified using system property\n");
}
try {
versionBuf.append("SAX Parser Factory " +
javax.xml.parsers.SAXParserFactory.newInstance().getClass().getName() + " will be used.\n");
}
catch(Exception ex) {
versionBuf.append("Error determining SAX Parser Factory\n.");
}
_version.setText(versionBuf.toString());
_credits.setText("ArgoUML was developed by the following:\n"+
"Project Lead:\n"+
" Jason Robbins (Collab.net)\n"+
" \n"+
"Version 0.8 release manager:\n"+
" Toby Baier (University of Hamburg, Germany)\n"+
" Marko Boger (GentleWare)\n"+
" \n"+
"Module Owners (contact these people for contributions):\n"+
" GEF: Edwin Park ([email protected])\n"+
" UML Diagrams: Marko Boger ([email protected])\n"+
" UML Metamodel, XMI: Toby Baier ([email protected])\n"+
" Plugin-support: Sean Chen ([email protected])\n"+
" Java RE: Andreas Rueckert ([email protected])\n"+
" Knowledge support: Jason Robbins ([email protected])\n"+
" User manual: Philippe Vanpeperstraete ([email protected])\n"+
" \n"+
"Contributing Developers (in no special order):\n"+
" Jim Holt\n"+
" Thomas Schaumburg\n"+
" David Glaser\n"+
" Toby Baier\n"+
" Eugenio Alvarez\n"+
" Clemens Eichler\n"+
" Curt Arnold\n"+
" Andreas Rueckert\n"+
" Frank Finger\n"+
" Stuart Zakon\n"+
" Frank Wienberg\n"+
"\n"+
"Credits for previous versions:\n"+
"\nResearchers: \n"+
" Jason Robbins\n"+
" David Redmiles\n"+
" David Hilbert\n"+
"\nDevelopers and Testers: \n"+
" Jason Robbins\n"+
" Adam Gauthier\n"+
" Adam Bonner\n"+
" David Hilbert\n"+
" ICS 125 team Spring 1996\n"+
" ICS 125 teams Spring 1998\n"+
"\nContributing Developers:\n"+
" Scott Guyer\n"+
" Piotr Kaminski\n"+
" Nick Santucci\n"+
" Eric Lefevre\n"+
" Sean Chen\n" +
" Jim Holt\n" +
" Steve Poole\n"
);
_contact.setText("For more information on the Argo project:\n"+
" + Visit our web site:\n"+
" http://www.ArgoUML.org\n"+
" + Send email to Jason Robbins at:\n"+
" [email protected]\n"+
" + Read our conference and journal papers:\n"+
" (list of publications: KBSE'96, IUI'98, ICSE'98, etc.)"
);
String s = "";
s+="Copyright (c) 1996-99 The Regents of the University of California.\n";
s+="All Rights Reserved. Permission to use, copy, modify, and distribute\n";
s+="this software and its documentation without fee, and without a written\n";
s+="agreement is hereby granted, provided that the above copyright notice\n";
s+="and this paragraph appear in all copies. This software program and\n";
s+="documentation are copyrighted by The Regents of the University of\n";
s+="California. The software program and documentation are supplied ''as\n";
s+="is'', without any accompanying services from The Regents. The Regents\n";
s+="do not warrant that the operation of the program will be uninterrupted\n";
s+="or error-free. The end-user understands that the program was\n";
s+="developed for research purposes and is advised not to rely exclusively\n";
s+="on the program for any reason. IN NO EVENT SHALL THE UNIVERSITY OF\n";
s+="CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,\n";
s+="INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING\n";
s+="OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE\n";
s+="UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n";
s+="DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n";
s+="WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n";
s+="MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n";
s+="PROVIDED HEREUNDER IS ON AN ''AS IS'' BASIS, AND THE UNIVERSITY OF\n";
s+="CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n";
s+="UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n";
_legal.setText(s);
_tabs.addTab("Splash", _splashButton);
_tabs.addTab("Version", new JScrollPane(_version));
_tabs.addTab("Credits", new JScrollPane(_credits));
_tabs.addTab("Contact Info", new JScrollPane(_contact));
_tabs.addTab("Legal", new JScrollPane(_legal));
getContentPane().setLayout(new BorderLayout(0, 0));
getContentPane().add(_tabs, BorderLayout.CENTER);
// add preloading progress bar?
setSize(imgWidth + 20, imgHeight + 50);
//pack();
}
| public AboutBox() {
super("About Argo/UML");
String iconName = "Splash";
ImageIcon splashImage = loadIconResource(iconName, iconName);
int imgWidth = splashImage.getIconWidth();
int imgHeight = splashImage.getIconHeight();
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation(scrSize.width/2 - imgWidth/2,
scrSize.height/2 - imgHeight/2);
//setSize(new Dimension(imgWidth + 10, imgHeight + 40));
getContentPane().setLayout(new BorderLayout(0, 0));
//_splashButton.setMargin(new Insets(0, 0, 0, 0));
_splashButton.setIcon(splashImage);
Font ctrlFont = MetalLookAndFeel.getControlTextFont();
// _version.setFont(ctrlFont);
// _credits.setFont(ctrlFont);
// _legal.setFont(ctrlFont);
// _contact.setFont(ctrlFont);
StringBuffer versionBuf = new StringBuffer(
"ArgoUML Version 0.9.1\n"+
"Built on March 2nd of 2001\n"+
"\n"+
"Needed:\n"+
" GEF (Graph Editing Framework)\n"+
" GIF generation code from www.acme.com (comes with GEF)\n"+
"\n"+
"Intended for use with:\n"+
" JDK 1.2 only plus\n"+
" A JAXP 1.0.1 compatible parser\n" +
" [Xerces-J 1.2.2 or later recommended, (xml.apache.org)]\n"+
" Novosoft's NSUML 0.4.19 or higher (nsuml.sourceforge.net)\n"+
" Frank Finger's (TU-Dresden) OCL-Compiler (dresden-ocl.sourceforge.net)\n"+
"\n");
try {
String factoryClass = javax.xml.parsers.SAXParserFactory.newInstance().getClass().getName();
if(factoryClass.indexOf("org.apache.") >= 0) {
versionBuf.append("This product includes software developed by the\n");
versionBuf.append("Apache Software Foundation (http://www.apache.org/).\n");
}
}
catch(Exception e) {}
versionBuf.append("\n--- Generated version information: ---\n");
versionBuf.append(getVersionInfo(packageList));
String saxFactory = System.getProperty("javax.xml.parsers.SAXParserFactory");
if(saxFactory != null) {
versionBuf.append("SAX Parser Factory " + saxFactory+ " specified using system property\n");
}
try {
versionBuf.append("SAX Parser Factory " +
javax.xml.parsers.SAXParserFactory.newInstance().getClass().getName() + " will be used.\n");
}
catch(Exception ex) {
versionBuf.append("Error determining SAX Parser Factory\n.");
}
_version.setText(versionBuf.toString());
_credits.setText("ArgoUML was developed by the following:\n"+
"Project Lead:\n"+
" Jason Robbins (Collab.net)\n"+
" \n"+
"Version 0.9 release managers:\n"+
" Toby Baier (University of Hamburg, Germany)\n"+
" Marko Boger (GentleWare)\n"+
" \n"+
"Module Owners (contact these people for contributions):\n"+
" GEF: Edwin Park ([email protected])\n"+
" UML Diagrams: Marko Boger ([email protected])\n"+
" UML Metamodel, XMI: Toby Baier ([email protected])\n"+
" Plugin-support: Sean Chen ([email protected])\n"+
" Java RE: Andreas Rueckert ([email protected])\n"+
" Knowledge support: Jason Robbins ([email protected])\n"+
" User manual: Philippe Vanpeperstraete ([email protected])\n"+
" \n"+
"Contributing Developers (in no special order):\n"+
" Jim Holt\n"+
" Thomas Schaumburg\n"+
" David Glaser\n"+
" Toby Baier\n"+
" Eugenio Alvarez\n"+
" Clemens Eichler\n"+
" Curt Arnold\n"+
" Andreas Rueckert\n"+
" Frank Finger\n"+
" Stuart Zakon\n"+
" Frank Wienberg\n"+
"\n"+
"Credits for previous versions:\n"+
"\nResearchers: \n"+
" Jason Robbins\n"+
" David Redmiles\n"+
" David Hilbert\n"+
"\nDevelopers and Testers: \n"+
" Jason Robbins\n"+
" Adam Gauthier\n"+
" Adam Bonner\n"+
" David Hilbert\n"+
" ICS 125 team Spring 1996\n"+
" ICS 125 teams Spring 1998\n"+
"\nContributing Developers:\n"+
" Scott Guyer\n"+
" Piotr Kaminski\n"+
" Nick Santucci\n"+
" Eric Lefevre\n"+
" Sean Chen\n" +
" Jim Holt\n" +
" Steve Poole\n"
);
_contact.setText("For more information on the Argo project:\n"+
" + Visit our web site:\n"+
" http://www.ArgoUML.org\n"+
" + Send email to Jason Robbins at:\n"+
" [email protected]\n"+
" + Send email to the developers mailing-list at:\n"+
" [email protected]\n"+
" (subscribe by sending a message to [email protected]\n"+
" + Read our conference and journal papers:\n"+
" (list of publications: KBSE'96, IUI'98, ICSE'98, etc.)"
);
String s = "";
s+="Copyright (c) 1996-99 The Regents of the University of California.\n";
s+="All Rights Reserved. Permission to use, copy, modify, and distribute\n";
s+="this software and its documentation without fee, and without a written\n";
s+="agreement is hereby granted, provided that the above copyright notice\n";
s+="and this paragraph appear in all copies. This software program and\n";
s+="documentation are copyrighted by The Regents of the University of\n";
s+="California. The software program and documentation are supplied ''as\n";
s+="is'', without any accompanying services from The Regents. The Regents\n";
s+="do not warrant that the operation of the program will be uninterrupted\n";
s+="or error-free. The end-user understands that the program was\n";
s+="developed for research purposes and is advised not to rely exclusively\n";
s+="on the program for any reason. IN NO EVENT SHALL THE UNIVERSITY OF\n";
s+="CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,\n";
s+="INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING\n";
s+="OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE\n";
s+="UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH\n";
s+="DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n";
s+="WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n";
s+="MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n";
s+="PROVIDED HEREUNDER IS ON AN ''AS IS'' BASIS, AND THE UNIVERSITY OF\n";
s+="CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n";
s+="UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n";
_legal.setText(s);
_tabs.addTab("Splash", _splashButton);
_tabs.addTab("Version", new JScrollPane(_version));
_tabs.addTab("Credits", new JScrollPane(_credits));
_tabs.addTab("Contact Info", new JScrollPane(_contact));
_tabs.addTab("Legal", new JScrollPane(_legal));
getContentPane().setLayout(new BorderLayout(0, 0));
getContentPane().add(_tabs, BorderLayout.CENTER);
// add preloading progress bar?
setSize(imgWidth + 20, imgHeight + 50);
//pack();
}
|
diff --git a/src/main/java/org/atlasapi/remotesite/seesaw/SeesawItemContentExtractor.java b/src/main/java/org/atlasapi/remotesite/seesaw/SeesawItemContentExtractor.java
index 6f74c98f7..11162efef 100644
--- a/src/main/java/org/atlasapi/remotesite/seesaw/SeesawItemContentExtractor.java
+++ b/src/main/java/org/atlasapi/remotesite/seesaw/SeesawItemContentExtractor.java
@@ -1,200 +1,202 @@
package org.atlasapi.remotesite.seesaw;
import java.util.Currency;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.atlasapi.genres.GenreMap;
import org.atlasapi.media.TransportType;
import org.atlasapi.media.entity.Countries;
import org.atlasapi.media.entity.Encoding;
import org.atlasapi.media.entity.Episode;
import org.atlasapi.media.entity.Location;
import org.atlasapi.media.entity.Policy;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.media.entity.Version;
import org.atlasapi.media.entity.Policy.RevenueContract;
import org.atlasapi.remotesite.ContentExtractor;
import org.atlasapi.remotesite.html.HtmlNavigator;
import org.jaxen.JaxenException;
import org.jdom.Element;
import com.google.common.collect.Sets;
import com.metabroadcast.common.currency.Price;
public class SeesawItemContentExtractor implements ContentExtractor<HtmlNavigator, Episode> {
static final Log LOG = LogFactory.getLog(SeesawItemContentExtractor.class);
private final Pattern poundsPricePattern = Pattern.compile(".*\\u00A3([0-9]+)\\.([0-9]{2})");
private final Pattern pencePricePattern = Pattern.compile(".*([0-9]{2})p");
private final Pattern seriesPattern = Pattern.compile("^.*Series (\\d+).*$");
private final Pattern imagePattern = Pattern.compile("(/i/ccp/\\d+/\\d+.JPG)", Pattern.CASE_INSENSITIVE);
private final GenreMap genreMap = new SeesawGenreMap();
@Override
public Episode extract(HtmlNavigator source) {
try {
Episode episode = new Episode();
episode.setPublisher(Publisher.SEESAW);
Version version = new Version();
version.setProvider(Publisher.SEESAW);
Encoding encoding = new Encoding();
Location linkLocation = new Location();
linkLocation.setTransportType(TransportType.LINK);
linkLocation.setAvailable(true);
linkLocation.setPolicy(ukPolicy());
encoding.addAvailableAt(linkLocation);
version.addManifestedAs(encoding);
episode.addVersion(version);
Element infoElem = source.firstElementOrNull("//div[@class='information']");
List<Element> headers = source.allElementsMatching("h3", infoElem);
String seriesText = null;
String episodeText;
String title = headers.get(0).getText();
if (headers.size() > 1) {
if (headers.size() > 2) {
seriesText = headers.get(1).getText();
episodeText = headers.get(2).getText();
}
else {
episodeText = headers.get(1).getText();
}
if (seriesText != null) {
Matcher matcher = seriesPattern.matcher(seriesText);
if (matcher.find()) {
episode.setSeriesNumber(Integer.valueOf(matcher.group(1)));
} else {
LOG.warn("Unable to parse series number: "+seriesText);
}
}
if (episodeText.startsWith("Episode ")) {
try {
String numberString = episodeText.substring("Episode ".length());
if (numberString.contains(":")) {
numberString = numberString.substring(0, numberString.indexOf(""));
}
if (numberString.contains(" - ")) {
numberString = numberString.substring(0, numberString.indexOf(" - "));
}
int episodeNumber = Integer.parseInt(episodeText.substring("Episode ".length(),
episodeText.contains(":") ? episodeText.indexOf(":") : episodeText.length()));
episode.setEpisodeNumber(episodeNumber);
}
catch (NumberFormatException e) {
LOG.warn("Unable to parse episode number: "+episodeText, e);
}
}
if (episodeText.contains(": ")) {
String episodeTitle = episodeText.substring(episodeText.indexOf(": ") + 2, episodeText.length());
episode.setTitle(episodeTitle);
} else if (episode.getEpisodeNumber() != null){
episode.setTitle("Episode "+episode.getEpisodeNumber());
+ } else {
+ episode.setTitle(episodeText);
}
}
if (episode.getTitle() == null) {
episode.setTitle(title);
}
Element playerInfoElem = source.firstElementOrNull("//*[@class='programInfo']");
if (playerInfoElem != null) {
String info = SeesawHelper.getAllTextContent(playerInfoElem);
Pattern pattern = Pattern.compile(".*\\((\\d+) mins\\).*", Pattern.DOTALL);
Matcher matcher = pattern.matcher(info);
if (matcher.matches()) {
try {
Integer duration = Integer.valueOf(matcher.group(1)) * 60;
version.setPublishedDuration(duration);
}
catch (NumberFormatException e) {
LOG.debug("Exception when trying to parse duration: ", e);
}
}
}
Element programmeInfoElem = source.firstElementOrNull("//*[text()='About this programme:']/following-sibling::*", infoElem);
if (programmeInfoElem != null) {
String progDesc = SeesawHelper.getFirstTextContent(programmeInfoElem).trim();
episode.setDescription(progDesc);
}
Element dateElem = source.firstElementOrNull("//*[text()='Date: ']/following-sibling::*", infoElem);
if (dateElem != null) {
@SuppressWarnings("unused")
String date = SeesawHelper.getFirstTextContent(dateElem).trim();
}
Element categoryElem = source.firstElementOrNull("//*[text()='Categories: ']/following-sibling::*", infoElem);
if (categoryElem != null) {
//String category = SeesawHelper.getFirstTextContent(categoryElem).trim();
String categoryLink = SeesawHelper.getFirstLinkUri(categoryElem);
episode.setGenres(genreMap.map(Sets.newHashSet(categoryLink)));
}
Element externalLinksElem = source.firstElementOrNull("//*[text()='External Links']/following-sibling::*", infoElem);
if (externalLinksElem != null) {
// TODO: use external links as aliases
@SuppressWarnings("unused")
List<String> links = SeesawHelper.getAllLinkUris(externalLinksElem);
}
List<Element> scriptElements = source.allElementsMatching("//script");
for (Element scriptElement: scriptElements) {
Matcher matcher = imagePattern.matcher(scriptElement.getValue());
if (matcher.find()) {
episode.setImage("http://www.seesaw.com"+matcher.group(1));
}
}
Element priceElem = source.firstElementOrNull("//*[@id='episodePriceSpan']");
if (priceElem != null) {
linkLocation.getPolicy().setRevenueContract(RevenueContract.PAY_TO_RENT);
Integer amount = null;
Matcher poundsMatcher = poundsPricePattern.matcher(priceElem.getText());
Matcher penceMatcher = pencePricePattern.matcher(priceElem.getText());
if (poundsMatcher.matches()) {
amount = (Integer.valueOf(poundsMatcher.group(1)) * 100) + Integer.valueOf(poundsMatcher.group(2));
}
else if (penceMatcher.matches()) {
amount = Integer.valueOf(penceMatcher.group(1));
}
if (amount != null) {
linkLocation.getPolicy().setPrice(new Price(Currency.getInstance("GBP"), amount));
}
else {
LOG.debug("Could not find price of rentable content");
}
}
else {
linkLocation.getPolicy().setRevenueContract(RevenueContract.FREE_TO_VIEW);
}
return episode;
} catch (JaxenException e) {
LOG.warn("Error extracting seesaw item", e);
}
return null;
}
private Policy ukPolicy() {
Policy policy = new Policy();
policy.addAvailableCountry(Countries.GB);
return policy;
}
}
| true | true | public Episode extract(HtmlNavigator source) {
try {
Episode episode = new Episode();
episode.setPublisher(Publisher.SEESAW);
Version version = new Version();
version.setProvider(Publisher.SEESAW);
Encoding encoding = new Encoding();
Location linkLocation = new Location();
linkLocation.setTransportType(TransportType.LINK);
linkLocation.setAvailable(true);
linkLocation.setPolicy(ukPolicy());
encoding.addAvailableAt(linkLocation);
version.addManifestedAs(encoding);
episode.addVersion(version);
Element infoElem = source.firstElementOrNull("//div[@class='information']");
List<Element> headers = source.allElementsMatching("h3", infoElem);
String seriesText = null;
String episodeText;
String title = headers.get(0).getText();
if (headers.size() > 1) {
if (headers.size() > 2) {
seriesText = headers.get(1).getText();
episodeText = headers.get(2).getText();
}
else {
episodeText = headers.get(1).getText();
}
if (seriesText != null) {
Matcher matcher = seriesPattern.matcher(seriesText);
if (matcher.find()) {
episode.setSeriesNumber(Integer.valueOf(matcher.group(1)));
} else {
LOG.warn("Unable to parse series number: "+seriesText);
}
}
if (episodeText.startsWith("Episode ")) {
try {
String numberString = episodeText.substring("Episode ".length());
if (numberString.contains(":")) {
numberString = numberString.substring(0, numberString.indexOf(""));
}
if (numberString.contains(" - ")) {
numberString = numberString.substring(0, numberString.indexOf(" - "));
}
int episodeNumber = Integer.parseInt(episodeText.substring("Episode ".length(),
episodeText.contains(":") ? episodeText.indexOf(":") : episodeText.length()));
episode.setEpisodeNumber(episodeNumber);
}
catch (NumberFormatException e) {
LOG.warn("Unable to parse episode number: "+episodeText, e);
}
}
if (episodeText.contains(": ")) {
String episodeTitle = episodeText.substring(episodeText.indexOf(": ") + 2, episodeText.length());
episode.setTitle(episodeTitle);
} else if (episode.getEpisodeNumber() != null){
episode.setTitle("Episode "+episode.getEpisodeNumber());
}
}
if (episode.getTitle() == null) {
episode.setTitle(title);
}
Element playerInfoElem = source.firstElementOrNull("//*[@class='programInfo']");
if (playerInfoElem != null) {
String info = SeesawHelper.getAllTextContent(playerInfoElem);
Pattern pattern = Pattern.compile(".*\\((\\d+) mins\\).*", Pattern.DOTALL);
Matcher matcher = pattern.matcher(info);
if (matcher.matches()) {
try {
Integer duration = Integer.valueOf(matcher.group(1)) * 60;
version.setPublishedDuration(duration);
}
catch (NumberFormatException e) {
LOG.debug("Exception when trying to parse duration: ", e);
}
}
}
Element programmeInfoElem = source.firstElementOrNull("//*[text()='About this programme:']/following-sibling::*", infoElem);
if (programmeInfoElem != null) {
String progDesc = SeesawHelper.getFirstTextContent(programmeInfoElem).trim();
episode.setDescription(progDesc);
}
Element dateElem = source.firstElementOrNull("//*[text()='Date: ']/following-sibling::*", infoElem);
if (dateElem != null) {
@SuppressWarnings("unused")
String date = SeesawHelper.getFirstTextContent(dateElem).trim();
}
Element categoryElem = source.firstElementOrNull("//*[text()='Categories: ']/following-sibling::*", infoElem);
if (categoryElem != null) {
//String category = SeesawHelper.getFirstTextContent(categoryElem).trim();
String categoryLink = SeesawHelper.getFirstLinkUri(categoryElem);
episode.setGenres(genreMap.map(Sets.newHashSet(categoryLink)));
}
Element externalLinksElem = source.firstElementOrNull("//*[text()='External Links']/following-sibling::*", infoElem);
if (externalLinksElem != null) {
// TODO: use external links as aliases
@SuppressWarnings("unused")
List<String> links = SeesawHelper.getAllLinkUris(externalLinksElem);
}
List<Element> scriptElements = source.allElementsMatching("//script");
for (Element scriptElement: scriptElements) {
Matcher matcher = imagePattern.matcher(scriptElement.getValue());
if (matcher.find()) {
episode.setImage("http://www.seesaw.com"+matcher.group(1));
}
}
Element priceElem = source.firstElementOrNull("//*[@id='episodePriceSpan']");
if (priceElem != null) {
linkLocation.getPolicy().setRevenueContract(RevenueContract.PAY_TO_RENT);
Integer amount = null;
Matcher poundsMatcher = poundsPricePattern.matcher(priceElem.getText());
Matcher penceMatcher = pencePricePattern.matcher(priceElem.getText());
if (poundsMatcher.matches()) {
amount = (Integer.valueOf(poundsMatcher.group(1)) * 100) + Integer.valueOf(poundsMatcher.group(2));
}
else if (penceMatcher.matches()) {
amount = Integer.valueOf(penceMatcher.group(1));
}
if (amount != null) {
linkLocation.getPolicy().setPrice(new Price(Currency.getInstance("GBP"), amount));
}
else {
LOG.debug("Could not find price of rentable content");
}
}
else {
linkLocation.getPolicy().setRevenueContract(RevenueContract.FREE_TO_VIEW);
}
return episode;
} catch (JaxenException e) {
LOG.warn("Error extracting seesaw item", e);
}
return null;
}
| public Episode extract(HtmlNavigator source) {
try {
Episode episode = new Episode();
episode.setPublisher(Publisher.SEESAW);
Version version = new Version();
version.setProvider(Publisher.SEESAW);
Encoding encoding = new Encoding();
Location linkLocation = new Location();
linkLocation.setTransportType(TransportType.LINK);
linkLocation.setAvailable(true);
linkLocation.setPolicy(ukPolicy());
encoding.addAvailableAt(linkLocation);
version.addManifestedAs(encoding);
episode.addVersion(version);
Element infoElem = source.firstElementOrNull("//div[@class='information']");
List<Element> headers = source.allElementsMatching("h3", infoElem);
String seriesText = null;
String episodeText;
String title = headers.get(0).getText();
if (headers.size() > 1) {
if (headers.size() > 2) {
seriesText = headers.get(1).getText();
episodeText = headers.get(2).getText();
}
else {
episodeText = headers.get(1).getText();
}
if (seriesText != null) {
Matcher matcher = seriesPattern.matcher(seriesText);
if (matcher.find()) {
episode.setSeriesNumber(Integer.valueOf(matcher.group(1)));
} else {
LOG.warn("Unable to parse series number: "+seriesText);
}
}
if (episodeText.startsWith("Episode ")) {
try {
String numberString = episodeText.substring("Episode ".length());
if (numberString.contains(":")) {
numberString = numberString.substring(0, numberString.indexOf(""));
}
if (numberString.contains(" - ")) {
numberString = numberString.substring(0, numberString.indexOf(" - "));
}
int episodeNumber = Integer.parseInt(episodeText.substring("Episode ".length(),
episodeText.contains(":") ? episodeText.indexOf(":") : episodeText.length()));
episode.setEpisodeNumber(episodeNumber);
}
catch (NumberFormatException e) {
LOG.warn("Unable to parse episode number: "+episodeText, e);
}
}
if (episodeText.contains(": ")) {
String episodeTitle = episodeText.substring(episodeText.indexOf(": ") + 2, episodeText.length());
episode.setTitle(episodeTitle);
} else if (episode.getEpisodeNumber() != null){
episode.setTitle("Episode "+episode.getEpisodeNumber());
} else {
episode.setTitle(episodeText);
}
}
if (episode.getTitle() == null) {
episode.setTitle(title);
}
Element playerInfoElem = source.firstElementOrNull("//*[@class='programInfo']");
if (playerInfoElem != null) {
String info = SeesawHelper.getAllTextContent(playerInfoElem);
Pattern pattern = Pattern.compile(".*\\((\\d+) mins\\).*", Pattern.DOTALL);
Matcher matcher = pattern.matcher(info);
if (matcher.matches()) {
try {
Integer duration = Integer.valueOf(matcher.group(1)) * 60;
version.setPublishedDuration(duration);
}
catch (NumberFormatException e) {
LOG.debug("Exception when trying to parse duration: ", e);
}
}
}
Element programmeInfoElem = source.firstElementOrNull("//*[text()='About this programme:']/following-sibling::*", infoElem);
if (programmeInfoElem != null) {
String progDesc = SeesawHelper.getFirstTextContent(programmeInfoElem).trim();
episode.setDescription(progDesc);
}
Element dateElem = source.firstElementOrNull("//*[text()='Date: ']/following-sibling::*", infoElem);
if (dateElem != null) {
@SuppressWarnings("unused")
String date = SeesawHelper.getFirstTextContent(dateElem).trim();
}
Element categoryElem = source.firstElementOrNull("//*[text()='Categories: ']/following-sibling::*", infoElem);
if (categoryElem != null) {
//String category = SeesawHelper.getFirstTextContent(categoryElem).trim();
String categoryLink = SeesawHelper.getFirstLinkUri(categoryElem);
episode.setGenres(genreMap.map(Sets.newHashSet(categoryLink)));
}
Element externalLinksElem = source.firstElementOrNull("//*[text()='External Links']/following-sibling::*", infoElem);
if (externalLinksElem != null) {
// TODO: use external links as aliases
@SuppressWarnings("unused")
List<String> links = SeesawHelper.getAllLinkUris(externalLinksElem);
}
List<Element> scriptElements = source.allElementsMatching("//script");
for (Element scriptElement: scriptElements) {
Matcher matcher = imagePattern.matcher(scriptElement.getValue());
if (matcher.find()) {
episode.setImage("http://www.seesaw.com"+matcher.group(1));
}
}
Element priceElem = source.firstElementOrNull("//*[@id='episodePriceSpan']");
if (priceElem != null) {
linkLocation.getPolicy().setRevenueContract(RevenueContract.PAY_TO_RENT);
Integer amount = null;
Matcher poundsMatcher = poundsPricePattern.matcher(priceElem.getText());
Matcher penceMatcher = pencePricePattern.matcher(priceElem.getText());
if (poundsMatcher.matches()) {
amount = (Integer.valueOf(poundsMatcher.group(1)) * 100) + Integer.valueOf(poundsMatcher.group(2));
}
else if (penceMatcher.matches()) {
amount = Integer.valueOf(penceMatcher.group(1));
}
if (amount != null) {
linkLocation.getPolicy().setPrice(new Price(Currency.getInstance("GBP"), amount));
}
else {
LOG.debug("Could not find price of rentable content");
}
}
else {
linkLocation.getPolicy().setRevenueContract(RevenueContract.FREE_TO_VIEW);
}
return episode;
} catch (JaxenException e) {
LOG.warn("Error extracting seesaw item", e);
}
return null;
}
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java
index cbf72103e..931663b06 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipServletRequestImpl.java
@@ -1,1586 +1,1586 @@
/*
* 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.mobicents.servlet.sip.message;
import gov.nist.javax.sip.DialogExt;
import gov.nist.javax.sip.header.ims.PathHeader;
import gov.nist.javax.sip.message.MessageExt;
import gov.nist.javax.sip.stack.SIPTransaction;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Vector;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.sip.Address;
import javax.servlet.sip.AuthInfo;
import javax.servlet.sip.B2buaHelper;
import javax.servlet.sip.Parameterable;
import javax.servlet.sip.Proxy;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipURI;
import javax.servlet.sip.TooManyHopsException;
import javax.servlet.sip.URI;
import javax.servlet.sip.SipSession.State;
import javax.servlet.sip.ar.SipApplicationRouterInfo;
import javax.servlet.sip.ar.SipApplicationRoutingDirective;
import javax.servlet.sip.ar.SipApplicationRoutingRegion;
import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.DialogState;
import javax.sip.ServerTransaction;
import javax.sip.SipException;
import javax.sip.SipProvider;
import javax.sip.Transaction;
import javax.sip.address.TelURL;
import javax.sip.header.AuthorizationHeader;
import javax.sip.header.ContactHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.ProxyAuthenticateHeader;
import javax.sip.header.RecordRouteHeader;
import javax.sip.header.RouteHeader;
import javax.sip.header.SubscriptionStateHeader;
import javax.sip.header.ToHeader;
import javax.sip.header.ViaHeader;
import javax.sip.header.WWWAuthenticateHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.SipFactories;
import org.mobicents.servlet.sip.address.AddressImpl;
import org.mobicents.servlet.sip.address.SipURIImpl;
import org.mobicents.servlet.sip.address.TelURLImpl;
import org.mobicents.servlet.sip.address.URIImpl;
import org.mobicents.servlet.sip.core.ApplicationRoutingHeaderComposer;
import org.mobicents.servlet.sip.core.RoutingState;
import org.mobicents.servlet.sip.core.SipNetworkInterfaceManager;
import org.mobicents.servlet.sip.core.dispatchers.MessageDispatcher;
import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession;
import org.mobicents.servlet.sip.core.session.MobicentsSipSession;
import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey;
import org.mobicents.servlet.sip.core.session.SipRequestDispatcher;
import org.mobicents.servlet.sip.core.session.SipSessionKey;
import org.mobicents.servlet.sip.proxy.ProxyImpl;
import org.mobicents.servlet.sip.security.AuthInfoEntry;
import org.mobicents.servlet.sip.security.AuthInfoImpl;
import org.mobicents.servlet.sip.security.authentication.DigestAuthenticator;
import org.mobicents.servlet.sip.startup.loading.SipServletImpl;
public class SipServletRequestImpl extends SipServletMessageImpl implements
SipServletRequest {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(SipServletRequestImpl.class);
private static final String EXCEPTION_MESSAGE = "The context does not allow you to modify this request !";
public static final Set<String> NON_INITIAL_SIP_REQUEST_METHODS = new HashSet<String>();
static {
NON_INITIAL_SIP_REQUEST_METHODS.add("CANCEL");
NON_INITIAL_SIP_REQUEST_METHODS.add("BYE");
NON_INITIAL_SIP_REQUEST_METHODS.add("PRACK");
NON_INITIAL_SIP_REQUEST_METHODS.add("ACK");
NON_INITIAL_SIP_REQUEST_METHODS.add("UPDATE");
NON_INITIAL_SIP_REQUEST_METHODS.add("INFO");
};
/* Linked request (for b2bua) */
private SipServletRequestImpl linkedRequest;
private boolean createDialog;
/*
* Popped route header - when we are the UAS we pop and keep the route
* header
*/
private AddressImpl poppedRoute;
private RouteHeader poppedRouteHeader;
/* Cache the application routing directive in the record route header */
private SipApplicationRoutingDirective routingDirective = SipApplicationRoutingDirective.NEW;
private RoutingState routingState;
private transient SipServletResponse lastFinalResponse;
private transient SipServletResponse lastInformationalResponse;
/**
* Routing region.
*/
private SipApplicationRoutingRegion routingRegion;
private transient URI subscriberURI;
private boolean isInitial;
private boolean isFinalResponseGenerated;
private boolean is1xxResponseGenerated;
private transient boolean isReadOnly;
public SipServletRequestImpl(Request request, SipFactoryImpl sipFactoryImpl,
MobicentsSipSession sipSession, Transaction transaction, Dialog dialog,
boolean createDialog) {
super(request, sipFactoryImpl, transaction, sipSession, dialog);
this.createDialog = createDialog;
routingState = checkRoutingState(this, dialog);
if(RoutingState.INITIAL.equals(routingState)) {
isInitial = true;
}
isFinalResponseGenerated = false;
}
@Override
public boolean isSystemHeader(String headerName) {
String hName = getFullHeaderName(headerName);
/*
* Contact is a system header field in messages other than REGISTER
* requests and responses, 3xx and 485 responses, and 200/OPTIONS
* responses so it is not contained in system headers and as such
* as a special treatment
*/
boolean isSystemHeader = JainSipUtils.SYSTEM_HEADERS.contains(hName);
if (isSystemHeader)
return isSystemHeader;
boolean isContactSystem = false;
Request request = (Request) this.message;
String method = request.getMethod();
if (method.equals(Request.REGISTER)) {
isContactSystem = false;
} else {
isContactSystem = true;
}
if (isContactSystem && hName.equals(ContactHeader.NAME)) {
isSystemHeader = true;
} else {
isSystemHeader = false;
}
return isSystemHeader;
}
public SipServletRequest createCancel() {
checkReadOnly();
if (!((Request) message).getMethod().equals(Request.INVITE)) {
throw new IllegalStateException(
"Cannot create CANCEL for non inivte");
}
if (super.getTransaction() == null
|| super.getTransaction() instanceof ServerTransaction)
throw new IllegalStateException("No client transaction found!");
if(RoutingState.FINAL_RESPONSE_SENT.equals(routingState) || lastFinalResponse != null) {
throw new IllegalStateException("final response already sent!");
}
try {
Request request = (Request) super.message;
String transport = JainSipUtils.findTransport(request);
SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(transport, false).getSipProvider();
Request cancelRequest = ((ClientTransaction) getTransaction())
.createCancel();
ClientTransaction clientTransaction = sipProvider
.getNewClientTransaction(cancelRequest);
clientTransaction.setRetransmitTimer(sipFactoryImpl.getSipApplicationDispatcher().getBaseTimerInterval());
SipServletRequest newRequest = new SipServletRequestImpl(
cancelRequest, sipFactoryImpl, getSipSession(),
clientTransaction, getTransaction().getDialog(), false);
return newRequest;
} catch (SipException ex) {
throw new IllegalStateException("Could not create cancel", ex);
}
}
/*
* (non-Javadoc)
*
* @see javax.servlet.sip.SipServletRequest#createResponse(int)
*/
public SipServletResponse createResponse(int statusCode) {
return createResponse(statusCode, null);
}
public SipServletResponse createResponse(final int statusCode, final String reasonPhrase) {
return createResponse(statusCode, reasonPhrase, true);
}
public SipServletResponse createResponse(final int statusCode, final String reasonPhrase, boolean validate) {
checkReadOnly();
final Transaction transaction = getTransaction();
if(RoutingState.CANCELLED.equals(routingState)) {
throw new IllegalStateException("Cannot create a response for the invite, a CANCEL has been received and the INVITE was replied with a 487!");
}
if (transaction == null
|| transaction instanceof ClientTransaction) {
if(validate) {
throw new IllegalStateException(
"Cannot create a response - not a server transaction");
}
}
try {
final Request request = transaction.getRequest();
final Response response = SipFactories.messageFactory.createResponse(
statusCode, request);
if(reasonPhrase!=null) {
response.setReasonPhrase(reasonPhrase);
}
final MobicentsSipSession session = getSipSession();
final String requestMethod = getMethod();
//add a To tag for all responses except Trying (or trying too if it's a subsequent request)
if((statusCode > Response.TRYING || !isInitial()) && statusCode <= Response.SESSION_NOT_ACCEPTABLE) {
final ToHeader toHeader = (ToHeader) response
.getHeader(ToHeader.NAME);
// If we already have a to tag, dont create new
if (toHeader.getTag() == null) {
// if a dialog has already been created
// reuse local tag
final Dialog dialog = transaction.getDialog();
if(dialog != null && dialog.getLocalTag() != null && dialog.getLocalTag().length() > 0) {
toHeader.setTag(dialog.getLocalTag());
} else if(session != null && session.getSipApplicationSession() != null) {
final SipApplicationSessionKey sipAppSessionKey = session.getSipApplicationSession().getKey();
final SipSessionKey sipSessionKey = session.getKey();
// Fix for Issue 1044 : javax.sip.SipException: Tag mismatch dialogTag during process B2B response
// make sure not to generate a new tag
synchronized (this) {
String toTag = sipSessionKey.getToTag();
if(toTag == null) {
toTag = ApplicationRoutingHeaderComposer.getHash(sipFactoryImpl.getSipApplicationDispatcher(),sipSessionKey.getApplicationName(), sipAppSessionKey.getId());
session.getKey().setToTag(toTag);
}
toHeader.setTag(toTag);
}
} else {
//if the sessions are null, it means it is a cancel response
toHeader.setTag(Integer.toString(new Random().nextInt(10000000)));
}
}
// Following restrictions in JSR 289 Section 4.1.3 Contact Header Field
boolean setContactHeader = true;
if ((statusCode >= 300 && statusCode < 400) || statusCode == 485 || Request.REGISTER.equals(requestMethod) || Request.OPTIONS.equals(requestMethod)) {
// don't set the contact header in those case
setContactHeader = false;
}
if(setContactHeader) {
SipURI outboundInterface = null;
if(session != null) {
outboundInterface = session.getOutboundInterface();
}
// Add the contact header for the dialog.
final ContactHeader contactHeader = JainSipUtils.createContactHeader(
super.sipFactoryImpl.getSipNetworkInterfaceManager(), request, null, outboundInterface);
if(logger.isDebugEnabled()) {
logger.debug("We're adding this contact header to our new response: '" + contactHeader + ", transport=" + JainSipUtils.findTransport(request));
}
response.setHeader(contactHeader);
}
}
// Application Routing : Adding the recorded route headers as route headers
final ListIterator<RecordRouteHeader> recordRouteHeaders = request.getHeaders(RecordRouteHeader.NAME);
while (recordRouteHeaders.hasNext()) {
RecordRouteHeader recordRouteHeader = (RecordRouteHeader) recordRouteHeaders
.next();
RouteHeader routeHeader = SipFactories.headerFactory.createRouteHeader(recordRouteHeader.getAddress());
response.addHeader(routeHeader);
}
final SipServletResponseImpl newSipServletResponse = new SipServletResponseImpl(response, super.sipFactoryImpl,
validate ? (ServerTransaction) transaction : transaction, session, getDialog(), false);
newSipServletResponse.setOriginalRequest(this);
if(!Request.PRACK.equals(requestMethod) && statusCode >= Response.OK &&
statusCode <= Response.SESSION_NOT_ACCEPTABLE) {
isFinalResponseGenerated = true;
}
if(statusCode >= Response.TRYING &&
statusCode < Response.OK) {
is1xxResponseGenerated = true;
}
return newSipServletResponse;
} catch (ParseException ex) {
throw new IllegalArgumentException("Bad status code" + statusCode,
ex);
}
}
public B2buaHelper getB2buaHelper() {
checkReadOnly();
final MobicentsSipSession session = getSipSession();
if (session.getProxy() != null)
throw new IllegalStateException("Proxy already present");
B2buaHelperImpl b2buaHelper = session.getB2buaHelper();
if (b2buaHelper != null)
return b2buaHelper;
try {
b2buaHelper = new B2buaHelperImpl();
b2buaHelper.setSipFactoryImpl(sipFactoryImpl);
b2buaHelper.setSipManager(session.getSipApplicationSession().getSipContext().getSipManager());
Request request = (Request) super.message;
if (this.getTransaction() != null
&& this.getTransaction().getDialog() == null
&& JainSipUtils.DIALOG_CREATING_METHODS.contains(request.getMethod())) {
String transport = JainSipUtils.findTransport(request);
SipProvider sipProvider = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(
transport, false).getSipProvider();
Dialog dialog = sipProvider.getNewDialog(this
.getTransaction());
((DialogExt)dialog).disableSequenceNumberValidation();
session.setSessionCreatingDialog(dialog);
dialog.setApplicationData( this.transactionApplicationData);
}
if(JainSipUtils.DIALOG_CREATING_METHODS.contains(request.getMethod())) {
this.createDialog = true; // flag that we want to create a dialog for outgoing request.
}
session.setB2buaHelper(b2buaHelper);
return b2buaHelper;
} catch (SipException ex) {
throw new IllegalStateException("Cannot get B2BUAHelper", ex);
}
}
public ServletInputStream getInputStream() throws IOException {
return null;
}
public int getMaxForwards() {
return ((MaxForwardsHeader) ((Request) message)
.getHeader(MaxForwardsHeader.NAME)).getMaxForwards();
}
/*
* (non-Javadoc)
*
* @see javax.servlet.sip.SipServletRequest#getPoppedRoute()
*/
public Address getPoppedRoute() {
if((this.poppedRoute == null && poppedRouteHeader != null) ||
(poppedRoute != null && poppedRouteHeader != null && !poppedRoute.getAddress().equals(poppedRouteHeader.getAddress()))) {
this.poppedRoute = new AddressImpl(poppedRouteHeader.getAddress(), null, getTransaction() == null ? true : false);
}
return poppedRoute;
}
public RouteHeader getPoppedRouteHeader() {
return poppedRouteHeader;
}
/**
* Set the popped route
*
* @param routeHeader
* the popped route header to set
*/
public void setPoppedRoute(RouteHeader routeHeader) {
this.poppedRouteHeader = routeHeader;
}
/**
* {@inheritDoc}
*/
public Proxy getProxy() throws TooManyHopsException {
checkReadOnly();
final MobicentsSipSession session = getSipSession();
if (session.getB2buaHelper() != null ) throw new IllegalStateException("Cannot proxy request");
return getProxy(true);
}
/**
* {@inheritDoc}
*/
public Proxy getProxy(boolean create) throws TooManyHopsException {
checkReadOnly();
final MobicentsSipSession session = getSipSession();
if (session.getB2buaHelper() != null ) throw new IllegalStateException("Cannot proxy request");
final MaxForwardsHeader mfHeader = (MaxForwardsHeader)this.message.getHeader(MaxForwardsHeader.NAME);
if(mfHeader.getMaxForwards()<=0) {
try {
this.createResponse(Response.TOO_MANY_HOPS, "Too many hops").send();
} catch (IOException e) {
throw new RuntimeException("could not send the Too many hops response out !", e);
}
throw new TooManyHopsException();
}
// For requests like PUBLISH dialogs(sessions) do not exist, but some clients
// attempt to send them in sequence as if they support dialogs and when such a subsequent request
// comes in it gets assigned to the previous request session where the proxy is destroyed.
// In this case we must create a new proxy. And we recoginze this case by additionally checking
// if this request is initial. TODO: Consider deleting the session contents too? JSR 289 says
// the session is keyed against the headers, not against initial/non-initial...
if (create) {
ProxyImpl proxy = session.getProxy();
boolean createNewProxy = false;
if(isInitial() && proxy != null && proxy.getOriginalRequest() == null) {
createNewProxy = true;
}
if(proxy == null || createNewProxy) {
session.setProxy(new ProxyImpl(this, super.sipFactoryImpl));
}
}
return session.getProxy();
}
/**
* {@inheritDoc}
*/
public BufferedReader getReader() throws IOException {
return null;
}
/**
* {@inheritDoc}
*/
public URI getRequestURI() {
Request request = (Request) super.message;
if (request.getRequestURI() instanceof javax.sip.address.SipURI)
return new SipURIImpl((javax.sip.address.SipURI) request
.getRequestURI());
else if (request.getRequestURI() instanceof javax.sip.address.TelURL)
return new TelURLImpl((javax.sip.address.TelURL) request
.getRequestURI());
else
throw new UnsupportedOperationException("Unsupported scheme");
}
/**
* {@inheritDoc}
*/
public boolean isInitial() {
return isInitial;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletMessage#isCommitted()
*/
public boolean isCommitted() {
//the message is an incoming request for which a final response has been generated
if(getTransaction() instanceof ServerTransaction &&
(RoutingState.FINAL_RESPONSE_SENT.equals(routingState) || isFinalResponseGenerated)) {
return true;
}
//the message is an outgoing request which has been sent
if(getTransaction() instanceof ClientTransaction && this.isMessageSent) {
return true;
}
/*
if(Request.ACK.equals((((Request)message).getMethod()))) {
return true;
}*/
return false;
}
protected void checkMessageState() {
if(isMessageSent || getTransaction() instanceof ServerTransaction) {
throw new IllegalStateException("Message already sent or incoming message");
}
}
/**
* {@inheritDoc}
*/
public void pushPath(Address uri) {
checkReadOnly();
if(!Request.REGISTER.equalsIgnoreCase(((Request)message).getMethod())) {
throw new IllegalStateException("Cannot push a Path on a non REGISTER request !");
}
if(uri.getURI() instanceof TelURL) {
throw new IllegalArgumentException("Cannot push a TelUrl as a path !");
}
if (logger.isDebugEnabled())
logger.debug("Pushing path into message of value [" + uri + "]");
try {
javax.sip.header.Header p = SipFactories.headerFactory
.createHeader(PathHeader.NAME, uri.toString());
this.message.addFirst(p);
} catch (Exception e) {
logger.error("Error while pushing path [" + uri + "]");
throw new IllegalArgumentException("Error pushing path ", e);
}
}
/**
* {@inheritDoc}
*/
public void pushRoute(Address address) {
checkReadOnly();
if(address.getURI() instanceof TelURL) {
throw new IllegalArgumentException("Cannot push a TelUrl as a route !");
}
javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) ((AddressImpl) address)
.getAddress().getURI();
pushRoute(sipUri);
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletRequest#pushRoute(javax.servlet.sip.SipURI)
*/
public void pushRoute(SipURI uri) {
checkReadOnly();
javax.sip.address.SipURI sipUri = ((SipURIImpl) uri).getSipURI();
sipUri.setLrParam();
pushRoute(sipUri);
}
/**
* Pushes a route header on initial request based on the jain sip sipUri given on parameter
* @param sipUri the jain sip sip uri to use to construct the route header to push on the request
*/
private void pushRoute(javax.sip.address.SipURI sipUri) {
if(isInitial()) {
if (logger.isDebugEnabled())
logger.debug("Pushing route into message of value [" + sipUri
+ "]");
sipUri.setLrParam();
try {
javax.sip.header.Header p = SipFactories.headerFactory
.createRouteHeader(SipFactories.addressFactory
.createAddress(sipUri));
this.message.addFirst(p);
} catch (SipException e) {
logger.error("Error while pushing route [" + sipUri + "]");
throw new IllegalArgumentException("Error pushing route ", e);
}
} else {
//as per JSR 289 Section 11.1.3 Pushing Route Header Field Values
// pushRoute can only be done on the initial requests.
// Subsequent requests within a dialog follow the route set.
// Any attempt to do a pushRoute on a subsequent request in a dialog
// MUST throw and IllegalStateException.
throw new IllegalStateException("Cannot push route on subsequent requests, only intial ones");
}
}
public void setMaxForwards(int n) {
checkReadOnly();
MaxForwardsHeader mfh = (MaxForwardsHeader) this.message
.getHeader(MaxForwardsHeader.NAME);
try {
if (mfh != null) {
mfh.setMaxForwards(n);
}
} catch (Exception ex) {
String s = "Error while setting max forwards";
logger.error(s, ex);
throw new IllegalArgumentException(s, ex);
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletRequest#setRequestURI(javax.servlet.sip.URI)
*/
public void setRequestURI(URI uri) {
checkReadOnly();
Request request = (Request) message;
URIImpl uriImpl = (URIImpl) uri;
javax.sip.address.URI wrappedUri = uriImpl.getURI();
request.setRequestURI(wrappedUri);
//TODO look through all contacts of the user and change them depending of if STUN is enabled
//and the request is aimed to the local network or outside
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletRequest#setRoutingDirective(javax.servlet.sip.SipApplicationRoutingDirective, javax.servlet.sip.SipServletRequest)
*/
public void setRoutingDirective(SipApplicationRoutingDirective directive,
SipServletRequest origRequest) throws IllegalStateException {
checkReadOnly();
SipServletRequestImpl origRequestImpl = (SipServletRequestImpl) origRequest;
final MobicentsSipSession session = getSipSession();
//@jean.deruelle Commenting this out, why origRequestImpl.isCommitted() is needed ?
// if ((directive == SipApplicationRoutingDirective.REVERSE || directive == SipApplicationRoutingDirective.CONTINUE)
// && (!origRequestImpl.isInitial() || origRequestImpl.isCommitted())) {
// If directive is CONTINUE or REVERSE, the parameter origRequest must be an
//initial request dispatched by the container to this application,
//i.e. origRequest.isInitial() must be true
if ((directive == SipApplicationRoutingDirective.REVERSE ||
directive == SipApplicationRoutingDirective.CONTINUE)){
if(origRequestImpl == null ||
!origRequestImpl.isInitial()) {
if(logger.isDebugEnabled()) {
logger.debug("directive to set : " + directive);
logger.debug("Original Request Routing State : " + origRequestImpl.getRoutingState());
}
throw new IllegalStateException(
"Bad state -- cannot set routing directive");
} else {
//set AR State Info from previous request
session.setStateInfo(origRequestImpl.getSipSession().getStateInfo());
//needed for application composition
currentApplicationName = origRequestImpl.getCurrentApplicationName();
//linking the requests
//FIXME one request can be linked to many more as for B2BUA
origRequestImpl.setLinkedRequest(this);
setLinkedRequest(origRequestImpl);
}
} else {
//This request must be a request created in a new SipSession
//or from an initial request, and must not have been sent.
//If any one of these preconditions are not met, the method throws an IllegalStateException.
Set<Transaction> ongoingTransactions = session.getOngoingTransactions();
if(!State.INITIAL.equals(session.getState()) && ongoingTransactions != null && ongoingTransactions.size() > 0) {
if(logger.isDebugEnabled()) {
logger.debug("session state : " + session.getState());
logger.debug("numbers of ongoing transactions : " + ongoingTransactions.size());
}
throw new IllegalStateException(
"Bad state -- cannot set routing directive");
}
}
routingDirective = directive;
linkedRequest = origRequestImpl;
//@jean.deruelle Commenting this out, is this really needed ?
// RecordRouteHeader rrh = (RecordRouteHeader) request
// .getHeader(RecordRouteHeader.NAME);
// javax.sip.address.SipURI sipUri = (javax.sip.address.SipURI) rrh
// .getAddress().getURI();
//
// try {
// if (directive == SipApplicationRoutingDirective.NEW) {
// sipUri.setParameter("rd", "NEW");
// } else if (directive == SipApplicationRoutingDirective.REVERSE) {
// sipUri.setParameter("rd", "REVERSE");
// } else if (directive == SipApplicationRoutingDirective.CONTINUE) {
// sipUri.setParameter("rd", "CONTINUE");
// }
//
// } catch (Exception ex) {
// String s = "error while setting routing directive";
// logger.error(s, ex);
// throw new IllegalArgumentException(s, ex);
// }
}
/*
* (non-Javadoc)
*
* @see javax.servlet.ServletRequest#getLocalName()
*/
public String getLocalName() {
// TODO Auto-generated method stub
return null;
}
public Locale getLocale() {
// TODO Auto-generated method stub
return null;
}
public Enumeration getLocales() {
// TODO Auto-generated method stub
return null;
}
/*
* (non-Javadoc)
*
* @see javax.servlet.ServletRequest#getParameter(java.lang.String)
*/
public String getParameter(String name) {
// JSR 289 Section 5.6.1 Parameters :
// For initial requests where a preloaded Route header specified the application to be invoked, the parameters are those of the SIP or SIPS URI in that Route header.
// For initial requests where the application is invoked the parameters are those present on the request URI,
// if this is a SIP or a SIPS URI. For other URI schemes, the parameter set is undefined.
// For subsequent requests in a dialog, the parameters presented to the application are those that the application itself
// set on the Record-Route header for the initial request or response (see 10.4 Record-Route Parameters).
// These will typically be the URI parameters of the top Route header field but if the upstream SIP element is a
// "strict router" they may be returned in the request URI (see RFC 3261).
// It is the containers responsibility to recognize whether the upstream element is a strict router and determine the right parameter set accordingly.
if(this.getPoppedRoute() != null) {
return this.getPoppedRoute().getURI().getParameter(name);
} else {
return this.getRequestURI().getParameter(name);
}
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletRequest#getParameterMap()
*/
public Map<String, String> getParameterMap() {
// JSR 289 Section 5.6.1 Parameters :
// For initial requests where a preloaded Route header specified the application to be invoked, the parameters are those of the SIP or SIPS URI in that Route header.
// For initial requests where the application is invoked the parameters are those present on the request URI,
// if this is a SIP or a SIPS URI. For other URI schemes, the parameter set is undefined.
// For subsequent requests in a dialog, the parameters presented to the application are those that the application itself
// set on the Record-Route header for the initial request or response (see 10.4 Record-Route Parameters).
// These will typically be the URI parameters of the top Route header field but if the upstream SIP element is a
// "strict router" they may be returned in the request URI (see RFC 3261).
// It is the containers responsibility to recognize whether the upstream element is a strict router and determine the right parameter set accordingly.
HashMap<String, String> retval = new HashMap<String, String>();
if(this.getPoppedRoute() != null) {
Iterator<String> parameterNamesIt = this.getPoppedRoute().getURI().getParameterNames();
while (parameterNamesIt.hasNext()) {
String parameterName = parameterNamesIt.next();
retval.put(parameterName, this.getPoppedRoute().getURI().getParameter(parameterName));
}
} else {
Iterator<String> parameterNamesIt = this.getRequestURI().getParameterNames();
while (parameterNamesIt.hasNext()) {
String parameterName = parameterNamesIt.next();
retval.put(parameterName, this.getRequestURI().getParameter(parameterName));
}
}
return retval;
}
/*
* (non-Javadoc)
* @see javax.servlet.ServletRequest#getParameterNames()
*/
public Enumeration<String> getParameterNames() {
// JSR 289 Section 5.6.1 Parameters :
// For initial requests where a preloaded Route header specified the application to be invoked, the parameters are those of the SIP or SIPS URI in that Route header.
// For initial requests where the application is invoked the parameters are those present on the request URI,
// if this is a SIP or a SIPS URI. For other URI schemes, the parameter set is undefined.
// For subsequent requests in a dialog, the parameters presented to the application are those that the application itself
// set on the Record-Route header for the initial request or response (see 10.4 Record-Route Parameters).
// These will typically be the URI parameters of the top Route header field but if the upstream SIP element is a
// "strict router" they may be returned in the request URI (see RFC 3261).
// It is the containers responsibility to recognize whether the upstream element is a strict router and determine the right parameter set accordingly.
Vector<String> retval = new Vector<String>();
if(this.getPoppedRoute() != null) {
Iterator<String> parameterNamesIt = this.getPoppedRoute().getURI().getParameterNames();
while (parameterNamesIt.hasNext()) {
String parameterName = parameterNamesIt.next();
retval.add(parameterName);
}
} else {
Iterator<String> parameterNamesIt = this.getRequestURI().getParameterNames();
while (parameterNamesIt.hasNext()) {
String parameterName = parameterNamesIt.next();
retval.add(parameterName);
}
}
return retval.elements();
}
/*
* (non-Javadoc)
*
* @see javax.servlet.ServletRequest#getParameterValues(java.lang.String)
*/
public String[] getParameterValues(String name) {
// JSR 289 Section 5.6.1 Parameters :
// The getParameterValues method returns an array of String objects containing all the parameter values associated with a parameter name.
// The value returned from the getParameter method must always equal the first value in the array of String objects returned by getParameterValues.
// Note:Support for multi-valued parameters is defined mainly for HTTP because HTML forms may contain multi-valued parameters in form submissions.
return new String[] {getParameter(name)};
}
public String getRealPath(String arg0) {
// TODO Auto-generated method stub
return null;
}
public String getRemoteHost() {
// TODO Auto-generated method stub
return null;
}
/**
* {@inheritDoc}
*/
public RequestDispatcher getRequestDispatcher(String handler) {
SipServletImpl sipServletImpl = (SipServletImpl)
getSipSession().getSipApplicationSession().getSipContext().getChildrenMap().get(handler);
if(sipServletImpl == null) {
throw new IllegalArgumentException(handler + " is not a valid servlet name");
}
return new SipRequestDispatcher(sipServletImpl);
}
public String getScheme() {
return ((Request)message).getRequestURI().getScheme();
}
public String getServerName() {
// TODO Auto-generated method stub
return null;
}
public int getServerPort() {
// TODO Auto-generated method stub
return 0;
}
/**
* @return the routingDirective
*/
public SipApplicationRoutingDirective getRoutingDirective() {
if(!isInitial()) {
throw new IllegalStateException("the request is not initial");
}
return routingDirective;
}
/*
* (non-Javadoc)
*
* @see org.mobicents.servlet.sip.message.SipServletMessageImpl#send()
*/
@Override
public void send() {
checkReadOnly();
final Request request = (Request) super.message;
final MobicentsSipSession session = getSipSession();
try {
ProxyImpl proxy = null;
if(session != null) {
proxy = session.getProxy();
}
final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactoryImpl.getSipNetworkInterfaceManager();
((MessageExt)message).setApplicationData(null);
ViaHeader viaHeader = (ViaHeader) message.getHeader(ViaHeader.NAME);
//Issue 112 fix by folsson
if(!getMethod().equalsIgnoreCase(Request.CANCEL) && viaHeader == null) {
boolean addViaHeader = false;
if(proxy == null) {
addViaHeader = true;
} else if(isInitial) {
if(proxy.getRecordRoute()) {
addViaHeader = true;
}
} else if(proxy.getFinalBranchForSubsequentRequests() != null && proxy.getFinalBranchForSubsequentRequests().getRecordRoute()) {
addViaHeader = true;
}
if(addViaHeader) {
if(logger.isDebugEnabled()) {
logger.debug("Adding via Header");
}
// Issue
viaHeader = JainSipUtils.createViaHeader(
sipNetworkInterfaceManager, request, null, session.getOutboundInterface());
message.addHeader(viaHeader);
}
}
final String transport = JainSipUtils.findTransport(request);
if(logger.isDebugEnabled()) {
logger.debug("The found transport for sending request is '" + transport + "'");
}
final String requestMethod = getMethod();
if(Request.ACK.equals(requestMethod)) {
session.getSessionCreatingDialog().sendAck(request);
return;
}
//Added for initial requests only (that are not REGISTER) not for subsequent requests
if(isInitial() && !Request.REGISTER.equalsIgnoreCase(requestMethod)) {
// Additional checks for https://sip-servlets.dev.java.net/issues/show_bug.cgi?id=29
// if(session.getProxy() != null &&
// session.getProxy().getRecordRoute()) // If the app is proxying it already does that
// {
// if(logger.isDebugEnabled()) {
// logger.debug("Add a record route header for app composition ");
// }
// getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions();
// //Add a record route header for app composition
// addAppCompositionRRHeader();
// }
final SipApplicationRouterInfo routerInfo = sipFactoryImpl.getNextInterestedApplication(this);
if(routerInfo.getNextApplicationName() != null) {
if(logger.isDebugEnabled()) {
logger.debug("routing back to the container " +
"since the following app is interested " + routerInfo.getNextApplicationName());
}
//add a route header to direct the request back to the container
//to check if there is any other apps interested in it
addInfoForRoutingBackToContainer(routerInfo, session.getSipApplicationSession().getKey().getId(), session.getKey().getApplicationName());
} else {
if(logger.isDebugEnabled()) {
logger.debug("routing outside the container " +
"since no more apps are interested.");
}
//Adding Route Header for LB if we are in a HA configuration
if(sipFactoryImpl.isUseLoadBalancer() && isInitial) {
sipFactoryImpl.addLoadBalancerRouteHeader(request);
if(logger.isDebugEnabled()) {
logger.debug("adding route to Load Balancer since we are in a HA configuration " +
" and no more apps are interested.");
}
}
}
}
final MobicentsSipApplicationSession sipApplicationSession = session.getSipApplicationSession();
if(viaHeader.getBranch() == null) {
final String branch = JainSipUtils.createBranch(sipApplicationSession.getKey().getId(), sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(session.getKey().getApplicationName()));
viaHeader.setBranch(branch);
}
if(logger.isDebugEnabled()) {
getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions();
}
if (super.getTransaction() == null) {
ContactHeader contactHeader = (ContactHeader)request.getHeader(ContactHeader.NAME);
- if(contactHeader == null && JainSipUtils.CONTACT_HEADER_METHODS.contains(requestMethod) && proxy == null) {
+ if(contactHeader == null && !Request.REGISTER.equalsIgnoreCase(requestMethod) && JainSipUtils.CONTACT_HEADER_METHODS.contains(requestMethod) && proxy == null) {
final FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
final javax.sip.address.URI fromUri = fromHeader.getAddress().getURI();
String fromName = null;
if(fromUri instanceof javax.sip.address.SipURI) {
fromName = ((javax.sip.address.SipURI)fromUri).getUser();
}
// Create the contact name address.
contactHeader =
JainSipUtils.createContactHeader(sipNetworkInterfaceManager, request, fromName, session.getOutboundInterface());
request.addHeader(contactHeader);
}
if(logger.isDebugEnabled()) {
logger.debug("Getting new Client Tx for request " + request);
}
final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint(
transport, false).getSipProvider();
final ClientTransaction ctx = sipProvider
.getNewClientTransaction(request);
ctx.setRetransmitTimer(sipFactoryImpl.getSipApplicationDispatcher().getBaseTimerInterval());
session.setSessionCreatingTransaction(ctx);
Dialog dialog = ctx.getDialog();
if(session.getProxy() != null) dialog = null;
if (dialog == null && this.createDialog) {
dialog = sipProvider.getNewDialog(ctx);
((DialogExt)dialog).disableSequenceNumberValidation();
session.setSessionCreatingDialog(dialog);
if(logger.isDebugEnabled()) {
logger.debug("new Dialog for request " + request + ", ref = " + dialog);
}
}
//Keeping the transactions mapping in application data for CANCEL handling
if(linkedRequest != null) {
final Transaction linkedTransaction = linkedRequest.getTransaction();
final Dialog linkedDialog = linkedRequest.getDialog();
//keeping the client transaction in the server transaction's application data
((TransactionApplicationData)linkedTransaction.getApplicationData()).setTransaction(ctx);
if(linkedDialog != null && linkedDialog.getApplicationData() != null) {
((TransactionApplicationData)linkedDialog.getApplicationData()).setTransaction(ctx);
}
//keeping the server transaction in the client transaction's application data
this.transactionApplicationData.setTransaction(linkedTransaction);
if(dialog!= null && dialog.getApplicationData() != null) {
((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedTransaction);
}
}
// Make the dialog point here so that when the dialog event
// comes in we can find the session quickly.
if (dialog != null) {
dialog.setApplicationData(this.transactionApplicationData);
}
// SIP Request is ALWAYS pointed to by the client tx.
// Notice that the tx appplication data is cached in the request
// copied over to the tx so it can be quickly accessed when response
// arrives.
ctx.setApplicationData(this.transactionApplicationData);
super.setTransaction(ctx);
} else if (Request.PRACK.equals(request.getMethod())) {
final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint(
transport, false).getSipProvider();
final ClientTransaction ctx = sipProvider.getNewClientTransaction(request);
//Keeping the transactions mapping in application data for CANCEL handling
if(linkedRequest != null) {
//keeping the client transaction in the server transaction's application data
((TransactionApplicationData)linkedRequest.getTransaction().getApplicationData()).setTransaction(ctx);
if(linkedRequest.getDialog() != null && linkedRequest.getDialog().getApplicationData() != null) {
((TransactionApplicationData)linkedRequest.getDialog().getApplicationData()).setTransaction(ctx);
}
//keeping the server transaction in the client transaction's application data
this.transactionApplicationData.setTransaction(linkedRequest.getTransaction());
if(dialog!= null && dialog.getApplicationData() != null) {
((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedRequest.getTransaction());
}
}
// SIP Request is ALWAYS pointed to by the client tx.
// Notice that the tx appplication data is cached in the request
// copied over to the tx so it can be quickly accessed when response
// arrives.
ctx.setApplicationData(this.transactionApplicationData);
setTransaction(ctx);
}
//tells the application dispatcher to stop routing the linked request
// (in this case it would be the original request) since it has been relayed
if(linkedRequest != null &&
!SipApplicationRoutingDirective.NEW.equals(routingDirective)) {
if(!RoutingState.PROXIED.equals(linkedRequest.getRoutingState())) {
linkedRequest.setRoutingState(RoutingState.RELAYED);
}
}
session.addOngoingTransaction(getTransaction());
// Update Session state
session.updateStateOnSubsequentRequest(this, false);
if(Request.NOTIFY.equals(getMethod())) {
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
getMessage().getHeader(SubscriptionStateHeader.NAME);
// RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates
// a new subscription and a new dialog (unless they have already been
// created by a matching response, as described above).
if (subscriptionStateHeader != null &&
(SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) ||
SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
session.addSubscription(this);
}
// A subscription is destroyed when a notifier sends a NOTIFY request
// with a "Subscription-State" of "terminated".
if (subscriptionStateHeader != null &&
SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState())) {
session.removeSubscription(this);
}
}
//updating the last accessed times
session.access();
sipApplicationSession.access();
Dialog dialog = getDialog();
if(session.getProxy() != null) dialog = null;
// If dialog does not exist or has no state.
if (dialog == null || dialog.getState() == null
|| (dialog.getState() == DialogState.EARLY && !Request.PRACK.equals(requestMethod))) {
if(logger.isInfoEnabled()) {
logger.info("Sending the request " + request);
}
((ClientTransaction) super.getTransaction()).sendRequest();
} else {
// This is a subsequent (an in-dialog) request.
// we don't redirect it to the container for now
if(logger.isInfoEnabled()) {
logger.info("Sending the in dialog request " + request);
}
dialog.sendRequest((ClientTransaction) getTransaction());
}
isMessageSent = true;
} catch (Exception ex) {
throw new IllegalStateException("Error sending request " + request,ex);
}
}
/**
* Add a route header to route back to the container
* @param applicationName the application name that was chosen by the AR to route the request
* @throws ParseException
* @throws SipException
* @throws NullPointerException
*/
public void addInfoForRoutingBackToContainer(SipApplicationRouterInfo routerInfo, String applicationSessionId, String applicationName) throws ParseException, SipException {
final Request request = (Request) super.message;
final javax.sip.address.SipURI sipURI = JainSipUtils.createRecordRouteURI(
sipFactoryImpl.getSipNetworkInterfaceManager(),
request);
sipURI.setLrParam();
sipURI.setParameter(MessageDispatcher.ROUTE_PARAM_DIRECTIVE,
routingDirective.toString());
if(sipSession.getRegionInternal() != null) {
sipURI.setParameter(MessageDispatcher.ROUTE_PARAM_REGION_LABEL,
sipSession.getRegionInternal().getLabel());
sipURI.setParameter(MessageDispatcher.ROUTE_PARAM_REGION_TYPE,
sipSession.getRegionInternal().getType().toString());
}
sipURI.setParameter(MessageDispatcher.ROUTE_PARAM_PREV_APPLICATION_NAME,
applicationName);
sipURI.setParameter(MessageDispatcher.ROUTE_PARAM_PREV_APP_ID,
applicationSessionId);
final javax.sip.address.Address routeAddress =
SipFactories.addressFactory.createAddress(sipURI);
final RouteHeader routeHeader =
SipFactories.headerFactory.createRouteHeader(routeAddress);
request.addFirst(routeHeader);
// adding the application router info to avoid calling the AppRouter twice
// See Issue 791 : http://code.google.com/p/mobicents/issues/detail?id=791
final MobicentsSipSession session = getSipSession();
session.setNextSipApplicationRouterInfo(routerInfo);
}
/**
* Add a record route header for app composition
* @throws ParseException if anything goes wrong while creating the record route header
* @throws SipException
* @throws NullPointerException
*/
public void addAppCompositionRRHeader()
throws ParseException, SipException {
final Request request = (Request) super.message;
final MobicentsSipSession session = getSipSession();
javax.sip.address.SipURI sipURI = JainSipUtils.createRecordRouteURI(
sipFactoryImpl.getSipNetworkInterfaceManager(),
request);
sipURI.setParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME, session.getKey().getApplicationName());
sipURI.setLrParam();
javax.sip.address.Address recordRouteAddress =
SipFactories.addressFactory.createAddress(sipURI);
RecordRouteHeader recordRouteHeader =
SipFactories.headerFactory.createRecordRouteHeader(recordRouteAddress);
request.addFirst(recordRouteHeader);
}
public void setLinkedRequest(SipServletRequestImpl linkedRequest) {
this.linkedRequest = linkedRequest;
}
public SipServletRequestImpl getLinkedRequest() {
return this.linkedRequest;
}
/**
* @return the routingState
*/
public RoutingState getRoutingState() {
return routingState;
}
/**
* @param routingState the routingState to set
*/
public void setRoutingState(RoutingState routingState) throws IllegalStateException {
//JSR 289 Section 11.2.3 && 10.2.6
if(routingState.equals(RoutingState.CANCELLED) &&
(this.routingState.equals(RoutingState.FINAL_RESPONSE_SENT) ||
this.routingState.equals(RoutingState.PROXIED))) {
throw new IllegalStateException("Cannot cancel final response already sent!");
}
if((routingState.equals(RoutingState.FINAL_RESPONSE_SENT)||
routingState.equals(RoutingState.PROXIED)) && this.routingState.equals(RoutingState.CANCELLED)) {
throw new IllegalStateException("Cancel received and already replied with a 487!");
}
if(routingState.equals(RoutingState.SUBSEQUENT)) {
isInitial = false;
}
this.routingState = routingState;
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletRequest#addAuthHeader(javax.servlet.sip.SipServletResponse, javax.servlet.sip.AuthInfo)
*/
public void addAuthHeader(SipServletResponse challengeResponse,
AuthInfo authInfo) {
checkReadOnly();
AuthInfoImpl authInfoImpl = (AuthInfoImpl) authInfo;
SipServletResponseImpl challengeResponseImpl =
(SipServletResponseImpl) challengeResponse;
Response response = (Response) challengeResponseImpl.getMessage();
// First check for WWWAuthentication headers
ListIterator authHeaderIterator =
response.getHeaders(WWWAuthenticateHeader.NAME);
while(authHeaderIterator.hasNext()) {
WWWAuthenticateHeader wwwAuthHeader =
(WWWAuthenticateHeader) authHeaderIterator.next();
// String uri = wwwAuthHeader.getParameter("uri");
AuthInfoEntry authInfoEntry = authInfoImpl.getAuthInfo(wwwAuthHeader.getRealm());
if(authInfoEntry == null) throw new SecurityException(
"Cannot add authorization header. No credentials for the following realm: " + wwwAuthHeader.getRealm());
addChallengeResponse(wwwAuthHeader,
authInfoEntry.getUserName(),
authInfoEntry.getPassword(),
this.getRequestURI().toString());
}
// Now check for Proxy-Authentication
authHeaderIterator =
response.getHeaders(ProxyAuthenticateHeader.NAME);
while(authHeaderIterator.hasNext()) {
ProxyAuthenticateHeader wwwAuthHeader =
(ProxyAuthenticateHeader) authHeaderIterator.next();
// String uri = wwwAuthHeader.getParameter("uri");
AuthInfoEntry authInfoEntry = authInfoImpl.getAuthInfo(wwwAuthHeader.getRealm());
if(authInfoEntry == null) throw new SecurityException(
"No credentials for the following realm: " + wwwAuthHeader.getRealm());
addChallengeResponse(wwwAuthHeader,
authInfoEntry.getUserName(),
authInfoEntry.getPassword(),
this.getRequestURI().toString());
}
}
/*
* (non-Javadoc)
* @see javax.servlet.sip.SipServletRequest#addAuthHeader(javax.servlet.sip.SipServletResponse, java.lang.String, java.lang.String)
*/
public void addAuthHeader(SipServletResponse challengeResponse,
String username, String password) {
checkReadOnly();
SipServletResponseImpl challengeResponseImpl =
(SipServletResponseImpl) challengeResponse;
Response response = (Response) challengeResponseImpl.getMessage();
ListIterator authHeaderIterator =
response.getHeaders(WWWAuthenticateHeader.NAME);
// First
while(authHeaderIterator.hasNext()) {
WWWAuthenticateHeader wwwAuthHeader =
(WWWAuthenticateHeader) authHeaderIterator.next();
// String uri = wwwAuthHeader.getParameter("uri");
addChallengeResponse(wwwAuthHeader, username, password, this.getRequestURI().toString());
}
authHeaderIterator =
response.getHeaders(ProxyAuthenticateHeader.NAME);
while(authHeaderIterator.hasNext()) {
ProxyAuthenticateHeader wwwAuthHeader =
(ProxyAuthenticateHeader) authHeaderIterator.next();
String uri = wwwAuthHeader.getParameter("uri");
if(uri == null) uri = this.getRequestURI().toString();
addChallengeResponse(wwwAuthHeader, username, password, uri);
}
}
private void addChallengeResponse(
WWWAuthenticateHeader wwwAuthHeader,
String username,
String password,
String uri) {
AuthorizationHeader authorization = DigestAuthenticator.getAuthorizationHeader(
getMethod(),
uri,
"", // TODO: What is this entity-body?
wwwAuthHeader,
username,
password);
message.addHeader(authorization);
}
/**
* @return the finalResponse
*/
public SipServletResponse getLastFinalResponse() {
return lastFinalResponse;
}
/**
* @param finalResponse the finalResponse to set
*/
public void setResponse(SipServletResponse response) {
if(response.getStatus() >= 200 &&
(lastFinalResponse == null || lastFinalResponse.getStatus() < response.getStatus())) {
this.lastFinalResponse = response;
}
if((response.getStatus() > 100 && response.getStatus() < 200) &&
(lastInformationalResponse == null || lastInformationalResponse.getStatus() < response.getStatus())) {
this.lastInformationalResponse = response;
}
}
/**
* {@inheritDoc}
*/
public Address getInitialPoppedRoute() {
return transactionApplicationData.getInitialPoppedRoute();
}
/**
* {@inheritDoc}
*/
public SipApplicationRoutingRegion getRegion() {
return routingRegion;
}
/**
* This method allows the application to set the region that the application
* is in with respect to this SipSession
* @param routingRegion the region that the application is in
*/
public void setRoutingRegion(SipApplicationRoutingRegion routingRegion) {
this.routingRegion = routingRegion;
}
/**
* {@inheritDoc}
*/
public URI getSubscriberURI() {
return subscriberURI;
}
public void setSubscriberURI(URI uri) {
this.subscriberURI = uri;
}
/**
* Method checking whether or not the sip servlet request in parameter is initial
* according to algorithm defined in JSR289 Appendix B
* @param sipServletRequest the sip servlet request to check
* @param dialog the dialog associated with this request
* @return true if the request is initial false otherwise
*/
private static RoutingState checkRoutingState(SipServletRequestImpl sipServletRequest, Dialog dialog) {
// 2. Ongoing Transaction Detection - Employ methods of Section 17.2.3 in RFC 3261
//to see if the request matches an existing transaction.
//If it does, stop. The request is not an initial request.
if(dialog != null && DialogState.CONFIRMED.equals(dialog.getState())) {
return RoutingState.SUBSEQUENT;
}
// 3. Examine Request Method. If it is CANCEL, BYE, PRACK or ACK, stop.
//The request is not an initial request for which application selection occurs.
if(NON_INITIAL_SIP_REQUEST_METHODS.contains(sipServletRequest.getMethod())) {
return RoutingState.SUBSEQUENT;
}
// 4. Existing Dialog Detection - If the request has a tag in the To header field,
// the container computes the dialog identifier (as specified in section 12 of RFC 3261)
// corresponding to the request and compares it with existing dialogs.
// If it matches an existing dialog, stop. The request is not an initial request.
// The request is a subsequent request and must be routed to the application path
// associated with the existing dialog.
// If the request has a tag in the To header field,
// but the dialog identifier does not match any existing dialogs,
// the container must reject the request with a 481 (Call/Transaction Does Not Exist).
// Note: When this occurs, RFC 3261 says either the UAS has crashed or the request was misrouted.
// In the latter case, the misrouted request is best handled by rejecting the request.
// For the Sip Servlet environment, a UAS crash may mean either an application crashed
// or the container itself crashed. In either case, it is impossible to route the request
// as a subsequent request and it is inappropriate to route it as an initial request.
// Therefore, the only viable approach is to reject the request.
if(dialog != null && !DialogState.EARLY.equals(dialog.getState())) {
return RoutingState.SUBSEQUENT;
}
// 6. Detection of Requests Sent to Encoded URIs -
// Requests may be sent to a container instance addressed to a URI obtained by calling
// the encodeURI() method of a SipApplicationSession managed by this container instance.
// When a container receives such a request, stop. This request is not an initial request.
// Refer to section 15.11.1 Session Targeting and Application Selection
//for more information on how a request sent to an encoded URI is handled by the container.
//This part will be done in routeIntialRequest since this is where the Session Targeting retrieval is done
return RoutingState.INITIAL;
}
/**
* @return the is1xxResponseGenerated
*/
public boolean is1xxResponseGenerated() {
return is1xxResponseGenerated;
}
/**
* @return the isFinalResponseGenerated
*/
public boolean isFinalResponseGenerated() {
return isFinalResponseGenerated;
}
/**
* @return the lastInformationalResponse
*/
public SipServletResponse getLastInformationalResponse() {
return lastInformationalResponse;
}
public void setReadOnly(boolean isReadOnly) {
this.isReadOnly = isReadOnly;
}
protected void checkReadOnly() {
if(isReadOnly) {
throw new IllegalStateException(EXCEPTION_MESSAGE);
}
}
@Override
public void addAcceptLanguage(Locale locale) {
checkReadOnly();
super.addAcceptLanguage(locale);
}
@Override
public void addAddressHeader(String name, Address addr, boolean first)
throws IllegalArgumentException {
checkReadOnly();
super.addAddressHeader(name, addr, first);
}
@Override
public void addHeader(String name, String value) {
checkReadOnly();
super.addHeader(name, value);
}
@Override
public void addParameterableHeader(String name, Parameterable param,
boolean first) {
checkReadOnly();
super.addParameterableHeader(name, param, first);
}
@Override
public void removeAttribute(String name) {
checkReadOnly();
super.removeAttribute(name);
}
@Override
public void removeHeader(String name) {
checkReadOnly();
super.removeHeader(name);
}
@Override
public void setAcceptLanguage(Locale locale) {
checkReadOnly();
super.setAcceptLanguage(locale);
}
@Override
public void setAddressHeader(String name, Address addr) {
checkReadOnly();
super.setAddressHeader(name, addr);
}
@Override
public void setAttribute(String name, Object o) {
checkReadOnly();
super.setAttribute(name, o);
}
@Override
public void setCharacterEncoding(String enc)
throws UnsupportedEncodingException {
checkReadOnly();
super.setCharacterEncoding(enc);
}
@Override
public void setContent(Object content, String contentType)
throws UnsupportedEncodingException {
checkReadOnly();
super.setContent(content, contentType);
}
@Override
public void setContentLanguage(Locale locale) {
checkReadOnly();
super.setContentLanguage(locale);
}
@Override
public void setContentType(String type) {
checkReadOnly();
super.setContentType(type);
}
@Override
public void setExpires(int seconds) {
checkReadOnly();
super.setExpires(seconds);
}
@Override
public void setHeader(String name, String value) {
checkReadOnly();
super.setHeader(name, value);
}
@Override
public void setHeaderForm(HeaderForm form) {
checkReadOnly();
super.setHeaderForm(form);
}
@Override
public void setParameterableHeader(String name, Parameterable param) {
checkReadOnly();
super.setParameterableHeader(name, param);
}
/**
* {@inheritDoc}
*/
public String getInitialRemoteAddr() {
if(((SIPTransaction)getTransaction()).getPeerPacketSourceAddress() != null) {
return ((SIPTransaction)getTransaction()).getPeerPacketSourceAddress().getHostAddress();
} else {
return ((SIPTransaction)getTransaction()).getPeerAddress();
}
}
/**
* {@inheritDoc}
*/
public int getInitialRemotePort() {
if(((SIPTransaction)getTransaction()).getPeerPacketSourceAddress() != null) {
return ((SIPTransaction)getTransaction()).getPeerPacketSourcePort();
} else {
return ((SIPTransaction)getTransaction()).getPeerPort();
}
}
/**
* {@inheritDoc}
*/
public String getInitialTransport() {
return ((SIPTransaction)getTransaction()).getTransport();
}
}
| true | true | public void send() {
checkReadOnly();
final Request request = (Request) super.message;
final MobicentsSipSession session = getSipSession();
try {
ProxyImpl proxy = null;
if(session != null) {
proxy = session.getProxy();
}
final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactoryImpl.getSipNetworkInterfaceManager();
((MessageExt)message).setApplicationData(null);
ViaHeader viaHeader = (ViaHeader) message.getHeader(ViaHeader.NAME);
//Issue 112 fix by folsson
if(!getMethod().equalsIgnoreCase(Request.CANCEL) && viaHeader == null) {
boolean addViaHeader = false;
if(proxy == null) {
addViaHeader = true;
} else if(isInitial) {
if(proxy.getRecordRoute()) {
addViaHeader = true;
}
} else if(proxy.getFinalBranchForSubsequentRequests() != null && proxy.getFinalBranchForSubsequentRequests().getRecordRoute()) {
addViaHeader = true;
}
if(addViaHeader) {
if(logger.isDebugEnabled()) {
logger.debug("Adding via Header");
}
// Issue
viaHeader = JainSipUtils.createViaHeader(
sipNetworkInterfaceManager, request, null, session.getOutboundInterface());
message.addHeader(viaHeader);
}
}
final String transport = JainSipUtils.findTransport(request);
if(logger.isDebugEnabled()) {
logger.debug("The found transport for sending request is '" + transport + "'");
}
final String requestMethod = getMethod();
if(Request.ACK.equals(requestMethod)) {
session.getSessionCreatingDialog().sendAck(request);
return;
}
//Added for initial requests only (that are not REGISTER) not for subsequent requests
if(isInitial() && !Request.REGISTER.equalsIgnoreCase(requestMethod)) {
// Additional checks for https://sip-servlets.dev.java.net/issues/show_bug.cgi?id=29
// if(session.getProxy() != null &&
// session.getProxy().getRecordRoute()) // If the app is proxying it already does that
// {
// if(logger.isDebugEnabled()) {
// logger.debug("Add a record route header for app composition ");
// }
// getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions();
// //Add a record route header for app composition
// addAppCompositionRRHeader();
// }
final SipApplicationRouterInfo routerInfo = sipFactoryImpl.getNextInterestedApplication(this);
if(routerInfo.getNextApplicationName() != null) {
if(logger.isDebugEnabled()) {
logger.debug("routing back to the container " +
"since the following app is interested " + routerInfo.getNextApplicationName());
}
//add a route header to direct the request back to the container
//to check if there is any other apps interested in it
addInfoForRoutingBackToContainer(routerInfo, session.getSipApplicationSession().getKey().getId(), session.getKey().getApplicationName());
} else {
if(logger.isDebugEnabled()) {
logger.debug("routing outside the container " +
"since no more apps are interested.");
}
//Adding Route Header for LB if we are in a HA configuration
if(sipFactoryImpl.isUseLoadBalancer() && isInitial) {
sipFactoryImpl.addLoadBalancerRouteHeader(request);
if(logger.isDebugEnabled()) {
logger.debug("adding route to Load Balancer since we are in a HA configuration " +
" and no more apps are interested.");
}
}
}
}
final MobicentsSipApplicationSession sipApplicationSession = session.getSipApplicationSession();
if(viaHeader.getBranch() == null) {
final String branch = JainSipUtils.createBranch(sipApplicationSession.getKey().getId(), sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(session.getKey().getApplicationName()));
viaHeader.setBranch(branch);
}
if(logger.isDebugEnabled()) {
getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions();
}
if (super.getTransaction() == null) {
ContactHeader contactHeader = (ContactHeader)request.getHeader(ContactHeader.NAME);
if(contactHeader == null && JainSipUtils.CONTACT_HEADER_METHODS.contains(requestMethod) && proxy == null) {
final FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
final javax.sip.address.URI fromUri = fromHeader.getAddress().getURI();
String fromName = null;
if(fromUri instanceof javax.sip.address.SipURI) {
fromName = ((javax.sip.address.SipURI)fromUri).getUser();
}
// Create the contact name address.
contactHeader =
JainSipUtils.createContactHeader(sipNetworkInterfaceManager, request, fromName, session.getOutboundInterface());
request.addHeader(contactHeader);
}
if(logger.isDebugEnabled()) {
logger.debug("Getting new Client Tx for request " + request);
}
final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint(
transport, false).getSipProvider();
final ClientTransaction ctx = sipProvider
.getNewClientTransaction(request);
ctx.setRetransmitTimer(sipFactoryImpl.getSipApplicationDispatcher().getBaseTimerInterval());
session.setSessionCreatingTransaction(ctx);
Dialog dialog = ctx.getDialog();
if(session.getProxy() != null) dialog = null;
if (dialog == null && this.createDialog) {
dialog = sipProvider.getNewDialog(ctx);
((DialogExt)dialog).disableSequenceNumberValidation();
session.setSessionCreatingDialog(dialog);
if(logger.isDebugEnabled()) {
logger.debug("new Dialog for request " + request + ", ref = " + dialog);
}
}
//Keeping the transactions mapping in application data for CANCEL handling
if(linkedRequest != null) {
final Transaction linkedTransaction = linkedRequest.getTransaction();
final Dialog linkedDialog = linkedRequest.getDialog();
//keeping the client transaction in the server transaction's application data
((TransactionApplicationData)linkedTransaction.getApplicationData()).setTransaction(ctx);
if(linkedDialog != null && linkedDialog.getApplicationData() != null) {
((TransactionApplicationData)linkedDialog.getApplicationData()).setTransaction(ctx);
}
//keeping the server transaction in the client transaction's application data
this.transactionApplicationData.setTransaction(linkedTransaction);
if(dialog!= null && dialog.getApplicationData() != null) {
((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedTransaction);
}
}
// Make the dialog point here so that when the dialog event
// comes in we can find the session quickly.
if (dialog != null) {
dialog.setApplicationData(this.transactionApplicationData);
}
// SIP Request is ALWAYS pointed to by the client tx.
// Notice that the tx appplication data is cached in the request
// copied over to the tx so it can be quickly accessed when response
// arrives.
ctx.setApplicationData(this.transactionApplicationData);
super.setTransaction(ctx);
} else if (Request.PRACK.equals(request.getMethod())) {
final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint(
transport, false).getSipProvider();
final ClientTransaction ctx = sipProvider.getNewClientTransaction(request);
//Keeping the transactions mapping in application data for CANCEL handling
if(linkedRequest != null) {
//keeping the client transaction in the server transaction's application data
((TransactionApplicationData)linkedRequest.getTransaction().getApplicationData()).setTransaction(ctx);
if(linkedRequest.getDialog() != null && linkedRequest.getDialog().getApplicationData() != null) {
((TransactionApplicationData)linkedRequest.getDialog().getApplicationData()).setTransaction(ctx);
}
//keeping the server transaction in the client transaction's application data
this.transactionApplicationData.setTransaction(linkedRequest.getTransaction());
if(dialog!= null && dialog.getApplicationData() != null) {
((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedRequest.getTransaction());
}
}
// SIP Request is ALWAYS pointed to by the client tx.
// Notice that the tx appplication data is cached in the request
// copied over to the tx so it can be quickly accessed when response
// arrives.
ctx.setApplicationData(this.transactionApplicationData);
setTransaction(ctx);
}
//tells the application dispatcher to stop routing the linked request
// (in this case it would be the original request) since it has been relayed
if(linkedRequest != null &&
!SipApplicationRoutingDirective.NEW.equals(routingDirective)) {
if(!RoutingState.PROXIED.equals(linkedRequest.getRoutingState())) {
linkedRequest.setRoutingState(RoutingState.RELAYED);
}
}
session.addOngoingTransaction(getTransaction());
// Update Session state
session.updateStateOnSubsequentRequest(this, false);
if(Request.NOTIFY.equals(getMethod())) {
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
getMessage().getHeader(SubscriptionStateHeader.NAME);
// RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates
// a new subscription and a new dialog (unless they have already been
// created by a matching response, as described above).
if (subscriptionStateHeader != null &&
(SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) ||
SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
session.addSubscription(this);
}
// A subscription is destroyed when a notifier sends a NOTIFY request
// with a "Subscription-State" of "terminated".
if (subscriptionStateHeader != null &&
SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState())) {
session.removeSubscription(this);
}
}
//updating the last accessed times
session.access();
sipApplicationSession.access();
Dialog dialog = getDialog();
if(session.getProxy() != null) dialog = null;
// If dialog does not exist or has no state.
if (dialog == null || dialog.getState() == null
|| (dialog.getState() == DialogState.EARLY && !Request.PRACK.equals(requestMethod))) {
if(logger.isInfoEnabled()) {
logger.info("Sending the request " + request);
}
((ClientTransaction) super.getTransaction()).sendRequest();
} else {
// This is a subsequent (an in-dialog) request.
// we don't redirect it to the container for now
if(logger.isInfoEnabled()) {
logger.info("Sending the in dialog request " + request);
}
dialog.sendRequest((ClientTransaction) getTransaction());
}
isMessageSent = true;
} catch (Exception ex) {
throw new IllegalStateException("Error sending request " + request,ex);
}
}
| public void send() {
checkReadOnly();
final Request request = (Request) super.message;
final MobicentsSipSession session = getSipSession();
try {
ProxyImpl proxy = null;
if(session != null) {
proxy = session.getProxy();
}
final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactoryImpl.getSipNetworkInterfaceManager();
((MessageExt)message).setApplicationData(null);
ViaHeader viaHeader = (ViaHeader) message.getHeader(ViaHeader.NAME);
//Issue 112 fix by folsson
if(!getMethod().equalsIgnoreCase(Request.CANCEL) && viaHeader == null) {
boolean addViaHeader = false;
if(proxy == null) {
addViaHeader = true;
} else if(isInitial) {
if(proxy.getRecordRoute()) {
addViaHeader = true;
}
} else if(proxy.getFinalBranchForSubsequentRequests() != null && proxy.getFinalBranchForSubsequentRequests().getRecordRoute()) {
addViaHeader = true;
}
if(addViaHeader) {
if(logger.isDebugEnabled()) {
logger.debug("Adding via Header");
}
// Issue
viaHeader = JainSipUtils.createViaHeader(
sipNetworkInterfaceManager, request, null, session.getOutboundInterface());
message.addHeader(viaHeader);
}
}
final String transport = JainSipUtils.findTransport(request);
if(logger.isDebugEnabled()) {
logger.debug("The found transport for sending request is '" + transport + "'");
}
final String requestMethod = getMethod();
if(Request.ACK.equals(requestMethod)) {
session.getSessionCreatingDialog().sendAck(request);
return;
}
//Added for initial requests only (that are not REGISTER) not for subsequent requests
if(isInitial() && !Request.REGISTER.equalsIgnoreCase(requestMethod)) {
// Additional checks for https://sip-servlets.dev.java.net/issues/show_bug.cgi?id=29
// if(session.getProxy() != null &&
// session.getProxy().getRecordRoute()) // If the app is proxying it already does that
// {
// if(logger.isDebugEnabled()) {
// logger.debug("Add a record route header for app composition ");
// }
// getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions();
// //Add a record route header for app composition
// addAppCompositionRRHeader();
// }
final SipApplicationRouterInfo routerInfo = sipFactoryImpl.getNextInterestedApplication(this);
if(routerInfo.getNextApplicationName() != null) {
if(logger.isDebugEnabled()) {
logger.debug("routing back to the container " +
"since the following app is interested " + routerInfo.getNextApplicationName());
}
//add a route header to direct the request back to the container
//to check if there is any other apps interested in it
addInfoForRoutingBackToContainer(routerInfo, session.getSipApplicationSession().getKey().getId(), session.getKey().getApplicationName());
} else {
if(logger.isDebugEnabled()) {
logger.debug("routing outside the container " +
"since no more apps are interested.");
}
//Adding Route Header for LB if we are in a HA configuration
if(sipFactoryImpl.isUseLoadBalancer() && isInitial) {
sipFactoryImpl.addLoadBalancerRouteHeader(request);
if(logger.isDebugEnabled()) {
logger.debug("adding route to Load Balancer since we are in a HA configuration " +
" and no more apps are interested.");
}
}
}
}
final MobicentsSipApplicationSession sipApplicationSession = session.getSipApplicationSession();
if(viaHeader.getBranch() == null) {
final String branch = JainSipUtils.createBranch(sipApplicationSession.getKey().getId(), sipFactoryImpl.getSipApplicationDispatcher().getHashFromApplicationName(session.getKey().getApplicationName()));
viaHeader.setBranch(branch);
}
if(logger.isDebugEnabled()) {
getSipSession().getSipApplicationSession().getSipContext().getSipManager().dumpSipSessions();
}
if (super.getTransaction() == null) {
ContactHeader contactHeader = (ContactHeader)request.getHeader(ContactHeader.NAME);
if(contactHeader == null && !Request.REGISTER.equalsIgnoreCase(requestMethod) && JainSipUtils.CONTACT_HEADER_METHODS.contains(requestMethod) && proxy == null) {
final FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
final javax.sip.address.URI fromUri = fromHeader.getAddress().getURI();
String fromName = null;
if(fromUri instanceof javax.sip.address.SipURI) {
fromName = ((javax.sip.address.SipURI)fromUri).getUser();
}
// Create the contact name address.
contactHeader =
JainSipUtils.createContactHeader(sipNetworkInterfaceManager, request, fromName, session.getOutboundInterface());
request.addHeader(contactHeader);
}
if(logger.isDebugEnabled()) {
logger.debug("Getting new Client Tx for request " + request);
}
final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint(
transport, false).getSipProvider();
final ClientTransaction ctx = sipProvider
.getNewClientTransaction(request);
ctx.setRetransmitTimer(sipFactoryImpl.getSipApplicationDispatcher().getBaseTimerInterval());
session.setSessionCreatingTransaction(ctx);
Dialog dialog = ctx.getDialog();
if(session.getProxy() != null) dialog = null;
if (dialog == null && this.createDialog) {
dialog = sipProvider.getNewDialog(ctx);
((DialogExt)dialog).disableSequenceNumberValidation();
session.setSessionCreatingDialog(dialog);
if(logger.isDebugEnabled()) {
logger.debug("new Dialog for request " + request + ", ref = " + dialog);
}
}
//Keeping the transactions mapping in application data for CANCEL handling
if(linkedRequest != null) {
final Transaction linkedTransaction = linkedRequest.getTransaction();
final Dialog linkedDialog = linkedRequest.getDialog();
//keeping the client transaction in the server transaction's application data
((TransactionApplicationData)linkedTransaction.getApplicationData()).setTransaction(ctx);
if(linkedDialog != null && linkedDialog.getApplicationData() != null) {
((TransactionApplicationData)linkedDialog.getApplicationData()).setTransaction(ctx);
}
//keeping the server transaction in the client transaction's application data
this.transactionApplicationData.setTransaction(linkedTransaction);
if(dialog!= null && dialog.getApplicationData() != null) {
((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedTransaction);
}
}
// Make the dialog point here so that when the dialog event
// comes in we can find the session quickly.
if (dialog != null) {
dialog.setApplicationData(this.transactionApplicationData);
}
// SIP Request is ALWAYS pointed to by the client tx.
// Notice that the tx appplication data is cached in the request
// copied over to the tx so it can be quickly accessed when response
// arrives.
ctx.setApplicationData(this.transactionApplicationData);
super.setTransaction(ctx);
} else if (Request.PRACK.equals(request.getMethod())) {
final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint(
transport, false).getSipProvider();
final ClientTransaction ctx = sipProvider.getNewClientTransaction(request);
//Keeping the transactions mapping in application data for CANCEL handling
if(linkedRequest != null) {
//keeping the client transaction in the server transaction's application data
((TransactionApplicationData)linkedRequest.getTransaction().getApplicationData()).setTransaction(ctx);
if(linkedRequest.getDialog() != null && linkedRequest.getDialog().getApplicationData() != null) {
((TransactionApplicationData)linkedRequest.getDialog().getApplicationData()).setTransaction(ctx);
}
//keeping the server transaction in the client transaction's application data
this.transactionApplicationData.setTransaction(linkedRequest.getTransaction());
if(dialog!= null && dialog.getApplicationData() != null) {
((TransactionApplicationData)dialog.getApplicationData()).setTransaction(linkedRequest.getTransaction());
}
}
// SIP Request is ALWAYS pointed to by the client tx.
// Notice that the tx appplication data is cached in the request
// copied over to the tx so it can be quickly accessed when response
// arrives.
ctx.setApplicationData(this.transactionApplicationData);
setTransaction(ctx);
}
//tells the application dispatcher to stop routing the linked request
// (in this case it would be the original request) since it has been relayed
if(linkedRequest != null &&
!SipApplicationRoutingDirective.NEW.equals(routingDirective)) {
if(!RoutingState.PROXIED.equals(linkedRequest.getRoutingState())) {
linkedRequest.setRoutingState(RoutingState.RELAYED);
}
}
session.addOngoingTransaction(getTransaction());
// Update Session state
session.updateStateOnSubsequentRequest(this, false);
if(Request.NOTIFY.equals(getMethod())) {
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
getMessage().getHeader(SubscriptionStateHeader.NAME);
// RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates
// a new subscription and a new dialog (unless they have already been
// created by a matching response, as described above).
if (subscriptionStateHeader != null &&
(SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) ||
SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
session.addSubscription(this);
}
// A subscription is destroyed when a notifier sends a NOTIFY request
// with a "Subscription-State" of "terminated".
if (subscriptionStateHeader != null &&
SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState())) {
session.removeSubscription(this);
}
}
//updating the last accessed times
session.access();
sipApplicationSession.access();
Dialog dialog = getDialog();
if(session.getProxy() != null) dialog = null;
// If dialog does not exist or has no state.
if (dialog == null || dialog.getState() == null
|| (dialog.getState() == DialogState.EARLY && !Request.PRACK.equals(requestMethod))) {
if(logger.isInfoEnabled()) {
logger.info("Sending the request " + request);
}
((ClientTransaction) super.getTransaction()).sendRequest();
} else {
// This is a subsequent (an in-dialog) request.
// we don't redirect it to the container for now
if(logger.isInfoEnabled()) {
logger.info("Sending the in dialog request " + request);
}
dialog.sendRequest((ClientTransaction) getTransaction());
}
isMessageSent = true;
} catch (Exception ex) {
throw new IllegalStateException("Error sending request " + request,ex);
}
}
|
diff --git a/src/main/java/org/dynmap/kzedmap/ZoomedTileRenderer.java b/src/main/java/org/dynmap/kzedmap/ZoomedTileRenderer.java
index 908f1fbf..552e9d21 100644
--- a/src/main/java/org/dynmap/kzedmap/ZoomedTileRenderer.java
+++ b/src/main/java/org/dynmap/kzedmap/ZoomedTileRenderer.java
@@ -1,84 +1,85 @@
package org.dynmap.kzedmap;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.imageio.ImageIO;
import org.dynmap.debug.Debug;
public class ZoomedTileRenderer {
public ZoomedTileRenderer(Map<String, Object> configuration) {
}
public void render(KzedZoomedMapTile zt, File outputPath) {
KzedMapTile originalTile = zt.originalTile;
int px = originalTile.px;
int py = originalTile.py;
int zpx = zt.getTileX();
int zpy = zt.getTileY();
BufferedImage image = null;
try {
image = ImageIO.read(originalTile.file);
} catch (IOException e) {
} catch (IndexOutOfBoundsException e) {
}
if (image == null) {
Debug.debug("Could not load original tile, won't render zoom-out tile.");
return;
}
BufferedImage zIm = null;
File zoomFile = outputPath;
try {
zIm = ImageIO.read(zoomFile);
} catch (IOException e) {
+ } catch (IndexOutOfBoundsException e) {
}
if (zIm == null) {
/* create new one */
zIm = new BufferedImage(KzedMap.tileWidth, KzedMap.tileHeight, BufferedImage.TYPE_INT_RGB);
Debug.debug("New zoom-out tile created " + zt.getFilename());
} else {
Debug.debug("Loaded zoom-out tile from " + zt.getFilename());
}
/* update zoom-out tile */
/* scaled size */
int scw = KzedMap.tileWidth / 2;
int sch = KzedMap.tileHeight / 2;
/* origin in zoomed-out tile */
int ox = 0;
int oy = 0;
if (zpx != px)
ox = scw;
if (zpy != py)
oy = sch;
/* blit scaled rendered tile onto zoom-out tile */
// WritableRaster zr = zIm.getRaster();
Graphics2D g2 = zIm.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(image, ox, oy, scw, sch, null);
image.flush();
/* save zoom-out tile */
try {
ImageIO.write(zIm, "png", zoomFile);
Debug.debug("Saved zoom-out tile at " + zoomFile.getName());
} catch (IOException e) {
Debug.error("Failed to save zoom-out tile: " + zoomFile.getName(), e);
} catch (java.lang.NullPointerException e) {
Debug.error("Failed to save zoom-out tile (NullPointerException): " + zoomFile.getName(), e);
}
zIm.flush();
}
}
| true | true | public void render(KzedZoomedMapTile zt, File outputPath) {
KzedMapTile originalTile = zt.originalTile;
int px = originalTile.px;
int py = originalTile.py;
int zpx = zt.getTileX();
int zpy = zt.getTileY();
BufferedImage image = null;
try {
image = ImageIO.read(originalTile.file);
} catch (IOException e) {
} catch (IndexOutOfBoundsException e) {
}
if (image == null) {
Debug.debug("Could not load original tile, won't render zoom-out tile.");
return;
}
BufferedImage zIm = null;
File zoomFile = outputPath;
try {
zIm = ImageIO.read(zoomFile);
} catch (IOException e) {
}
if (zIm == null) {
/* create new one */
zIm = new BufferedImage(KzedMap.tileWidth, KzedMap.tileHeight, BufferedImage.TYPE_INT_RGB);
Debug.debug("New zoom-out tile created " + zt.getFilename());
} else {
Debug.debug("Loaded zoom-out tile from " + zt.getFilename());
}
/* update zoom-out tile */
/* scaled size */
int scw = KzedMap.tileWidth / 2;
int sch = KzedMap.tileHeight / 2;
/* origin in zoomed-out tile */
int ox = 0;
int oy = 0;
if (zpx != px)
ox = scw;
if (zpy != py)
oy = sch;
/* blit scaled rendered tile onto zoom-out tile */
// WritableRaster zr = zIm.getRaster();
Graphics2D g2 = zIm.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(image, ox, oy, scw, sch, null);
image.flush();
/* save zoom-out tile */
try {
ImageIO.write(zIm, "png", zoomFile);
Debug.debug("Saved zoom-out tile at " + zoomFile.getName());
} catch (IOException e) {
Debug.error("Failed to save zoom-out tile: " + zoomFile.getName(), e);
} catch (java.lang.NullPointerException e) {
Debug.error("Failed to save zoom-out tile (NullPointerException): " + zoomFile.getName(), e);
}
zIm.flush();
}
| public void render(KzedZoomedMapTile zt, File outputPath) {
KzedMapTile originalTile = zt.originalTile;
int px = originalTile.px;
int py = originalTile.py;
int zpx = zt.getTileX();
int zpy = zt.getTileY();
BufferedImage image = null;
try {
image = ImageIO.read(originalTile.file);
} catch (IOException e) {
} catch (IndexOutOfBoundsException e) {
}
if (image == null) {
Debug.debug("Could not load original tile, won't render zoom-out tile.");
return;
}
BufferedImage zIm = null;
File zoomFile = outputPath;
try {
zIm = ImageIO.read(zoomFile);
} catch (IOException e) {
} catch (IndexOutOfBoundsException e) {
}
if (zIm == null) {
/* create new one */
zIm = new BufferedImage(KzedMap.tileWidth, KzedMap.tileHeight, BufferedImage.TYPE_INT_RGB);
Debug.debug("New zoom-out tile created " + zt.getFilename());
} else {
Debug.debug("Loaded zoom-out tile from " + zt.getFilename());
}
/* update zoom-out tile */
/* scaled size */
int scw = KzedMap.tileWidth / 2;
int sch = KzedMap.tileHeight / 2;
/* origin in zoomed-out tile */
int ox = 0;
int oy = 0;
if (zpx != px)
ox = scw;
if (zpy != py)
oy = sch;
/* blit scaled rendered tile onto zoom-out tile */
// WritableRaster zr = zIm.getRaster();
Graphics2D g2 = zIm.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(image, ox, oy, scw, sch, null);
image.flush();
/* save zoom-out tile */
try {
ImageIO.write(zIm, "png", zoomFile);
Debug.debug("Saved zoom-out tile at " + zoomFile.getName());
} catch (IOException e) {
Debug.error("Failed to save zoom-out tile: " + zoomFile.getName(), e);
} catch (java.lang.NullPointerException e) {
Debug.error("Failed to save zoom-out tile (NullPointerException): " + zoomFile.getName(), e);
}
zIm.flush();
}
|
diff --git a/framework/src/play/test/Fixtures.java b/framework/src/play/test/Fixtures.java
index a9f43fe2..63d13236 100644
--- a/framework/src/play/test/Fixtures.java
+++ b/framework/src/play/test/Fixtures.java
@@ -1,451 +1,448 @@
package play.test;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor;
import org.yaml.snakeyaml.introspector.BeanAccess;
import org.yaml.snakeyaml.scanner.ScannerException;
import play.Logger;
import play.Play;
import play.PlayPlugin;
import play.classloading.ApplicationClasses;
import play.data.binding.Binder;
import play.data.binding.types.DateBinder;
import play.db.DB;
import play.db.DBPlugin;
import play.db.Model;
import play.exceptions.UnexpectedException;
import play.exceptions.YAMLException;
import play.templates.TemplateLoader;
import play.vfs.VirtualFile;
public class Fixtures {
static Pattern keyPattern = Pattern.compile("([^(]+)\\(([^)]+)\\)");
static Map<String, Object> idCache = new HashMap<String, Object>();
/**
* Delete all Model instances for the given types using the underlying persistance mechanisms
* @param types Types to delete
*/
public static void delete(Class<? extends Model>... types) {
idCache.clear();
disableForeignKeyConstraints();
for (Class<? extends Model> type : types) {
Model.Manager.factoryFor(type).deleteAll();
}
enableForeignKeyConstraints();
Play.pluginCollection.afterFixtureLoad();
}
/**
* Delete all Model instances for the given types using the underlying persistance mechanisms
* @param types Types to delete
*/
public static void delete(List<Class<? extends Model>> classes) {
@SuppressWarnings("unchecked")
Class<? extends Model>[] types = new Class[classes.size()];
for (int i = 0; i < types.length; i++) {
types[i] = classes.get(i);
}
delete(types);
}
/**
* Delete all Model instances for the all available types using the underlying persistance mechanisms
*/
@SuppressWarnings("unchecked")
public static void deleteAllModels() {
List<Class<? extends Model>> classes = new ArrayList<Class<? extends Model>>();
for (ApplicationClasses.ApplicationClass c : Play.classes.getAssignableClasses(Model.class)) {
classes.add((Class<? extends Model>)c.javaClass);
}
Fixtures.delete(classes);
}
/**
* Use deleteDatabase() instead
* @deprecated
*/
@Deprecated
public static void deleteAll() {
deleteDatabase();
}
static String[] dontDeleteTheseTables = new String[] {"play_evolutions"};
/**
* Flush the entire JDBC database
*/
public static void deleteDatabase() {
try {
idCache.clear();
List<String> names = new ArrayList<String>();
ResultSet rs = DB.getConnection().getMetaData().getTables(null, null, null, new String[]{"TABLE"});
while (rs.next()) {
String name = rs.getString("TABLE_NAME");
names.add(name);
}
disableForeignKeyConstraints();
for (String name : names) {
if(Arrays.binarySearch(dontDeleteTheseTables, name) < 0) {
Logger.trace("Dropping content of table %s", name);
DB.execute(getDeleteTableStmt(name) + ";");
}
}
enableForeignKeyConstraints();
Play.pluginCollection.afterFixtureLoad();
} catch (Exception e) {
throw new RuntimeException("Cannot delete all table data : " + e.getMessage(), e);
}
}
/**
* User loadModels(String name) instead
* @param name
* @deprecated
*/
@Deprecated
public static void load(String name) {
loadModels(name);
}
/**
* Load Model instancs from a YAML file and persist them using the underlying persistance mechanism.
* The format of the YAML file is constained, see the Fixtures manual page
* @param name Name of a yaml file somewhere in the classpath (or conf/)
*/
public static void loadModels(String name) {
VirtualFile yamlFile = null;
try {
for (VirtualFile vf : Play.javaPath) {
yamlFile = vf.child(name);
if (yamlFile != null && yamlFile.exists()) {
break;
}
}
if (yamlFile == null) {
throw new RuntimeException("Cannot load fixture " + name + ", the file was not found");
}
// Render yaml file with
String renderedYaml = TemplateLoader.load(yamlFile).render();
Yaml yaml = new Yaml();
Object o = yaml.load(renderedYaml);
if (o instanceof LinkedHashMap<?, ?>) {
@SuppressWarnings("unchecked") LinkedHashMap<Object, Map<?, ?>> objects = (LinkedHashMap<Object, Map<?, ?>>) o;
for (Object key : objects.keySet()) {
Matcher matcher = keyPattern.matcher(key.toString().trim());
if (matcher.matches()) {
String type = matcher.group(1);
String id = matcher.group(2);
if (!type.startsWith("models.")) {
type = "models." + type;
}
if (idCache.containsKey(type + "-" + id)) {
throw new RuntimeException("Cannot load fixture " + name + ", duplicate id '" + id + "' for type " + type);
}
Map<String, String[]> params = new HashMap<String, String[]>();
if (objects.get(key) == null) {
objects.put(key, new HashMap<Object, Object>());
}
serialize(objects.get(key), "object", params);
@SuppressWarnings("unchecked")
Class<Model> cType = (Class<Model>)Play.classloader.loadClass(type);
resolveDependencies(cType, params);
Model model = (Model)Binder.bind("object", cType, cType, null, params);
for(Field f : model.getClass().getFields()) {
- //this approach works better for byte[] / binary
- Object value = objects.get(key).get(f.getName());
- if( value != null){
- try{
- f.set(model, value);
- }catch(Exception e){
- Logger.debug("Unable to set value from yaml-file into for property " + f, e);
- }
+ if (f.getType().isAssignableFrom(Map.class)) {
+ f.set(model, objects.get(key).get(f.getName()));
+ }
+ if (f.getType().equals(byte[].class)) {
+ f.set(model, objects.get(key).get(f.getName()));
}
}
model._save();
Class<?> tType = cType;
while (!tType.equals(Object.class)) {
idCache.put(tType.getName() + "-" + id, Model.Manager.factoryFor(cType).keyValue(model));
tType = tType.getSuperclass();
}
}
}
}
// Most persistence engine will need to clear their state
Play.pluginCollection.afterFixtureLoad();
} catch (ClassNotFoundException e) {
throw new RuntimeException("Class " + e.getMessage() + " was not found", e);
} catch (ScannerException e) {
throw new YAMLException(e, yamlFile);
} catch (Throwable e) {
throw new RuntimeException("Cannot load fixture " + name + ": " + e.getMessage(), e);
}
}
/**
* User loadModels instead
* @deprecated
*/
@Deprecated
public static void load(String... names) {
for (String name : names) {
loadModels(name);
}
}
/**
* @see loadModels(String name)
*/
public static void loadModels(String... names) {
for (String name : names) {
loadModels(name);
}
}
/**
* User loadModels instead
* @deprecated
*/
public static void load(List<String> names) {
loadModels(names);
}
/**
* @see loadModels(String name)
*/
public static void loadModels(List<String> names) {
String[] tNames = new String[names.size()];
for (int i = 0; i < tNames.length; i++) {
tNames[i] = names.get(i);
}
load(tNames);
}
/**
* Load and parse a plain YAML file and returns the corresponding Java objects.
* The YAML parser used is SnakeYAML (http://code.google.com/p/snakeyaml/)
* @param name Name of a yaml file somewhere in the classpath (or conf/)me
* @return Java objects
*/
public static Object loadYaml(String name) {
return loadYaml(name, Object.class);
}
public static List<?> loadYamlAsList(String name) {
return (List<?>)loadYaml(name);
}
public static Map<?,?> loadYamlAsMap(String name) {
return (Map<?,?>)loadYaml(name);
}
@SuppressWarnings("unchecked")
public static <T> T loadYaml(String name, Class<T> clazz) {
Yaml yaml = new Yaml(new CustomClassLoaderConstructor(clazz, Play.classloader));
yaml.setBeanAccess(BeanAccess.FIELD);
return (T)loadYaml(name, yaml);
}
@SuppressWarnings("unchecked")
public static <T> T loadYaml(String name, Yaml yaml) {
VirtualFile yamlFile = null;
try {
for (VirtualFile vf : Play.javaPath) {
yamlFile = vf.child(name);
if (yamlFile != null && yamlFile.exists()) {
break;
}
}
InputStream is = Play.classloader.getResourceAsStream(name);
if (is == null) {
throw new RuntimeException("Cannot load fixture " + name + ", the file was not found");
}
Object o = yaml.load(is);
return (T)o;
} catch (ScannerException e) {
throw new YAMLException(e, yamlFile);
} catch (Throwable e) {
throw new RuntimeException("Cannot load fixture " + name + ": " + e.getMessage(), e);
}
}
/**
* Delete a directory recursively
* @param path relative path of the directory to delete
*/
public static void deleteDirectory(String path) {
try {
FileUtils.deleteDirectory(Play.getFile(path));
} catch (IOException ex) {
throw new UnexpectedException(ex);
}
}
// Private
static void serialize(Map<?, ?> values, String prefix, Map<String, String[]> serialized) {
for (Object key : values.keySet()) {
Object value = values.get(key);
if (value == null) {
continue;
}
if (value instanceof Map<?, ?>) {
serialize((Map<?, ?>) value, prefix + "." + key, serialized);
} else if (value instanceof Date) {
serialized.put(prefix + "." + key.toString(), new String[]{new SimpleDateFormat(DateBinder.ISO8601).format(((Date) value))});
} else if (value instanceof List<?>) {
List<?> l = (List<?>) value;
String[] r = new String[l.size()];
int i = 0;
for (Object el : l) {
r[i++] = el.toString();
}
serialized.put(prefix + "." + key.toString(), r);
} else if (value instanceof String && value.toString().matches("<<<\\s*\\{[^}]+}\\s*")) {
Matcher m = Pattern.compile("<<<\\s*\\{([^}]+)}\\s*").matcher(value.toString());
m.find();
String file = m.group(1);
VirtualFile f = Play.getVirtualFile(file);
if (f != null && f.exists()) {
serialized.put(prefix + "." + key.toString(), new String[]{f.contentAsString()});
}
} else {
serialized.put(prefix + "." + key.toString(), new String[]{value.toString()});
}
}
}
@SuppressWarnings("unchecked")
static void resolveDependencies(Class<Model> type, Map<String, String[]> serialized) {
Set<Field> fields = new HashSet<Field>();
Class<?> clazz = type;
while (!clazz.equals(Object.class)) {
Collections.addAll(fields, clazz.getDeclaredFields());
clazz = clazz.getSuperclass();
}
for (Model.Property field : Model.Manager.factoryFor(type).listProperties()) {
if (field.isRelation) {
String[] ids = serialized.get("object." + field.name);
if (ids != null) {
for (int i = 0; i < ids.length; i++) {
String id = ids[i];
id = field.relationType.getName() + "-" + id;
if (!idCache.containsKey(id)) {
throw new RuntimeException("No previous reference found for object of type " + field.name + " with key " + ids[i]);
}
ids[i] = idCache.get(id).toString();
}
}
serialized.remove("object." + field.name);
serialized.put("object." + field.name + "." + Model.Manager.factoryFor((Class<? extends Model>)field.relationType).keyName(), ids);
}
}
}
private static void disableForeignKeyConstraints() {
if (DBPlugin.url.startsWith("jdbc:oracle:")) {
DB.execute("begin\n" +
"for i in (select constraint_name, table_name from user_constraints where constraint_type ='R'\n" +
"and status = 'ENABLED') LOOP\n" +
"execute immediate 'alter table '||i.table_name||' disable constraint '||i.constraint_name||'';\n" +
"end loop;\n" +
"end;");
return;
}
if (DBPlugin.url.startsWith("jdbc:hsqldb:")) {
DB.execute("SET REFERENTIAL_INTEGRITY FALSE");
return;
}
if (DBPlugin.url.startsWith("jdbc:h2:")) {
DB.execute("SET REFERENTIAL_INTEGRITY FALSE");
return;
}
if (DBPlugin.url.startsWith("jdbc:mysql:")) {
DB.execute("SET foreign_key_checks = 0;");
return;
}
if (DBPlugin.url.startsWith("jdbc:postgresql:")) {
DB.execute("SET CONSTRAINTS ALL DEFERRED");
return;
}
// Maybe Log a WARN for unsupported DB ?
Logger.warn("Fixtures : unable to disable constraints, unsupported database : " + DBPlugin.url);
}
private static void enableForeignKeyConstraints() {
if (DBPlugin.url.startsWith("jdbc:oracle:")) {
DB.execute("begin\n" +
"for i in (select constraint_name, table_name from user_constraints where constraint_type ='R'\n" +
"and status = 'DISABLED') LOOP\n" +
"execute immediate 'alter table '||i.table_name||' enable constraint '||i.constraint_name||'';\n" +
"end loop;\n" +
"end;");
return;
}
if (DBPlugin.url.startsWith("jdbc:hsqldb:")) {
DB.execute("SET REFERENTIAL_INTEGRITY TRUE");
return;
}
if (DBPlugin.url.startsWith("jdbc:h2:")) {
DB.execute("SET REFERENTIAL_INTEGRITY TRUE");
return;
}
if (DBPlugin.url.startsWith("jdbc:mysql:")) {
DB.execute("SET foreign_key_checks = 1;");
return;
}
if (DBPlugin.url.startsWith("jdbc:postgresql:")) {
return;
}
// Maybe Log a WARN for unsupported DB ?
Logger.warn("Fixtures : unable to enable constraints, unsupported database : " + DBPlugin.url);
}
static String getDeleteTableStmt(String name) {
if (DBPlugin.url.startsWith("jdbc:mysql:") ) {
return "TRUNCATE TABLE " + name;
} else if (DBPlugin.url.startsWith("jdbc:postgresql:")) {
return "TRUNCATE TABLE " + name + " cascade";
} else if (DBPlugin.url.startsWith("jdbc:oracle:")) {
return "TRUNCATE TABLE " + name;
}
return "DELETE FROM " + name;
}
}
| true | true | public static void loadModels(String name) {
VirtualFile yamlFile = null;
try {
for (VirtualFile vf : Play.javaPath) {
yamlFile = vf.child(name);
if (yamlFile != null && yamlFile.exists()) {
break;
}
}
if (yamlFile == null) {
throw new RuntimeException("Cannot load fixture " + name + ", the file was not found");
}
// Render yaml file with
String renderedYaml = TemplateLoader.load(yamlFile).render();
Yaml yaml = new Yaml();
Object o = yaml.load(renderedYaml);
if (o instanceof LinkedHashMap<?, ?>) {
@SuppressWarnings("unchecked") LinkedHashMap<Object, Map<?, ?>> objects = (LinkedHashMap<Object, Map<?, ?>>) o;
for (Object key : objects.keySet()) {
Matcher matcher = keyPattern.matcher(key.toString().trim());
if (matcher.matches()) {
String type = matcher.group(1);
String id = matcher.group(2);
if (!type.startsWith("models.")) {
type = "models." + type;
}
if (idCache.containsKey(type + "-" + id)) {
throw new RuntimeException("Cannot load fixture " + name + ", duplicate id '" + id + "' for type " + type);
}
Map<String, String[]> params = new HashMap<String, String[]>();
if (objects.get(key) == null) {
objects.put(key, new HashMap<Object, Object>());
}
serialize(objects.get(key), "object", params);
@SuppressWarnings("unchecked")
Class<Model> cType = (Class<Model>)Play.classloader.loadClass(type);
resolveDependencies(cType, params);
Model model = (Model)Binder.bind("object", cType, cType, null, params);
for(Field f : model.getClass().getFields()) {
//this approach works better for byte[] / binary
Object value = objects.get(key).get(f.getName());
if( value != null){
try{
f.set(model, value);
}catch(Exception e){
Logger.debug("Unable to set value from yaml-file into for property " + f, e);
}
}
}
model._save();
Class<?> tType = cType;
while (!tType.equals(Object.class)) {
idCache.put(tType.getName() + "-" + id, Model.Manager.factoryFor(cType).keyValue(model));
tType = tType.getSuperclass();
}
}
}
}
// Most persistence engine will need to clear their state
Play.pluginCollection.afterFixtureLoad();
} catch (ClassNotFoundException e) {
throw new RuntimeException("Class " + e.getMessage() + " was not found", e);
} catch (ScannerException e) {
throw new YAMLException(e, yamlFile);
} catch (Throwable e) {
throw new RuntimeException("Cannot load fixture " + name + ": " + e.getMessage(), e);
}
}
| public static void loadModels(String name) {
VirtualFile yamlFile = null;
try {
for (VirtualFile vf : Play.javaPath) {
yamlFile = vf.child(name);
if (yamlFile != null && yamlFile.exists()) {
break;
}
}
if (yamlFile == null) {
throw new RuntimeException("Cannot load fixture " + name + ", the file was not found");
}
// Render yaml file with
String renderedYaml = TemplateLoader.load(yamlFile).render();
Yaml yaml = new Yaml();
Object o = yaml.load(renderedYaml);
if (o instanceof LinkedHashMap<?, ?>) {
@SuppressWarnings("unchecked") LinkedHashMap<Object, Map<?, ?>> objects = (LinkedHashMap<Object, Map<?, ?>>) o;
for (Object key : objects.keySet()) {
Matcher matcher = keyPattern.matcher(key.toString().trim());
if (matcher.matches()) {
String type = matcher.group(1);
String id = matcher.group(2);
if (!type.startsWith("models.")) {
type = "models." + type;
}
if (idCache.containsKey(type + "-" + id)) {
throw new RuntimeException("Cannot load fixture " + name + ", duplicate id '" + id + "' for type " + type);
}
Map<String, String[]> params = new HashMap<String, String[]>();
if (objects.get(key) == null) {
objects.put(key, new HashMap<Object, Object>());
}
serialize(objects.get(key), "object", params);
@SuppressWarnings("unchecked")
Class<Model> cType = (Class<Model>)Play.classloader.loadClass(type);
resolveDependencies(cType, params);
Model model = (Model)Binder.bind("object", cType, cType, null, params);
for(Field f : model.getClass().getFields()) {
if (f.getType().isAssignableFrom(Map.class)) {
f.set(model, objects.get(key).get(f.getName()));
}
if (f.getType().equals(byte[].class)) {
f.set(model, objects.get(key).get(f.getName()));
}
}
model._save();
Class<?> tType = cType;
while (!tType.equals(Object.class)) {
idCache.put(tType.getName() + "-" + id, Model.Manager.factoryFor(cType).keyValue(model));
tType = tType.getSuperclass();
}
}
}
}
// Most persistence engine will need to clear their state
Play.pluginCollection.afterFixtureLoad();
} catch (ClassNotFoundException e) {
throw new RuntimeException("Class " + e.getMessage() + " was not found", e);
} catch (ScannerException e) {
throw new YAMLException(e, yamlFile);
} catch (Throwable e) {
throw new RuntimeException("Cannot load fixture " + name + ": " + e.getMessage(), e);
}
}
|
diff --git a/src/projectmayhem/MainMenu.java b/src/projectmayhem/MainMenu.java
index e7c139a..b8386ac 100644
--- a/src/projectmayhem/MainMenu.java
+++ b/src/projectmayhem/MainMenu.java
@@ -1,42 +1,42 @@
package projectmayhem;
import misc.Button;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class MainMenu extends BasicGameState{
public static int ID;
int playButtonState;
Button play;
public MainMenu(int ID){
this.ID = ID;
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
playButtonState = 0;
- play = new Button(new Image("graphics/buttons/playbutton.png"), new Image("graphics/buttons/playbuttonhover.png"), Button.LEFTBOT(), Button.LEFTBOT(), gc);
+ play = new Button(new Image("graphics/buttons/textplaybutton.png"), new Image("graphics/buttons/textplaybuttonhover.png"), Button.MID(), Button.MID(), gc);
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
play.getGraphics().draw(play.getX(), play.getY());
}
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
}
public int getID(){
return ID;
}
}
| true | true | public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
playButtonState = 0;
play = new Button(new Image("graphics/buttons/playbutton.png"), new Image("graphics/buttons/playbuttonhover.png"), Button.LEFTBOT(), Button.LEFTBOT(), gc);
}
| public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
playButtonState = 0;
play = new Button(new Image("graphics/buttons/textplaybutton.png"), new Image("graphics/buttons/textplaybuttonhover.png"), Button.MID(), Button.MID(), gc);
}
|
diff --git a/src/main/java/hudson/remoting/Which.java b/src/main/java/hudson/remoting/Which.java
index c2196246..35e37510 100644
--- a/src/main/java/hudson/remoting/Which.java
+++ b/src/main/java/hudson/remoting/Which.java
@@ -1,221 +1,227 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Ullrich Hafner
*
* 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 hudson.remoting;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.net.JarURLConnection;
import java.lang.reflect.Field;
import java.util.zip.ZipFile;
import java.util.jar.JarFile;
import java.util.logging.Logger;
import java.util.logging.Level;
/**
* Locates where a given class is loaded from.
*
* @author Kohsuke Kawaguchi
*/
public class Which {
/**
* Locates the jar file that contains the given class.
*
* @throws IllegalArgumentException
* if failed to determine.
*/
public static URL jarURL(Class clazz) throws IOException {
ClassLoader cl = clazz.getClassLoader();
if(cl==null)
cl = ClassLoader.getSystemClassLoader();
URL res = cl.getResource(clazz.getName().replace('.', '/') + ".class");
if(res==null)
throw new IllegalArgumentException("Unable to locate class file for "+clazz);
return res;
}
/**
* Locates the jar file that contains the given class.
*
* <p>
* Note that jar files are not always loaded from {@link File},
* so for diagnostics purposes {@link #jarURL(Class)} is preferrable.
*
* @throws IllegalArgumentException
* if failed to determine.
*/
public static File jarFile(Class clazz) throws IOException {
URL res = jarURL(clazz);
String resURL = res.toExternalForm();
String originalURL = resURL;
if(resURL.startsWith("jar:file:") || resURL.startsWith("wsjar:file:"))
return fromJarUrlToFile(resURL);
if(resURL.startsWith("code-source:/")) {
// OC4J apparently uses this. See http://www.nabble.com/Hudson-on-OC4J-tt16702113.html
resURL = resURL.substring("code-source:/".length(), resURL.lastIndexOf('!')); // cut off jar: and the file name portion
return new File(decode(new URL("file:/"+resURL).getPath()));
}
if(resURL.startsWith("zip:")){
// weblogic uses this. See http://www.nabble.com/patch-to-get-Hudson-working-on-weblogic-td23997258.html
// also see http://www.nabble.com/Re%3A-Hudson-on-Weblogic-10.3-td25038378.html#a25043415
resURL = resURL.substring("zip:".length(), resURL.lastIndexOf('!')); // cut off zip: and the file name portion
return new File(decode(new URL("file:"+resURL).getPath()));
}
if(resURL.startsWith("file:")) {
// unpackaged classes
int n = clazz.getName().split("\\.").length; // how many slashes do wo need to cut?
for( ; n>0; n-- ) {
int idx = Math.max(resURL.lastIndexOf('/'), resURL.lastIndexOf('\\'));
if(idx<0) throw new IllegalArgumentException(originalURL + " - " + resURL);
resURL = resURL.substring(0,idx);
}
// won't work if res URL contains ' '
// return new File(new URI(null,new URL(res).toExternalForm(),null));
// won't work if res URL contains '%20'
// return new File(new URL(res).toURI());
return new File(decode(new URL(resURL).getPath()));
}
if(resURL.startsWith("vfszip:")) {
// JBoss5
InputStream is = res.openStream();
try {
Object delegate = is;
while (delegate.getClass().getEnclosingClass()!=ZipFile.class) {
Field f = is.getClass().getDeclaredField("delegate");
f.setAccessible(true);
delegate = f.get(is);
+ //JENKINS-5922 - workaround for CertificateReaderInputStream; JBoss 5.0.0, EAP 5.0 and EAP 5.1
+ if(delegate.getClass().getName().equals("java.util.jar.JarVerifier$VerifierStream")){
+ f = delegate.getClass().getDeclaredField("is");
+ f.setAccessible(true);
+ delegate = f.get(delegate);
+ }
}
Field f = delegate.getClass().getDeclaredField("this$0");
f.setAccessible(true);
ZipFile zipFile = (ZipFile)f.get(delegate);
return new File(zipFile.getName());
} catch (NoSuchFieldException e) {
// something must have changed in JBoss5. fall through
LOGGER.log(Level.FINE, "Failed to resolve vfszip into a jar location",e);
} catch (IllegalAccessException e) {
// something must have changed in JBoss5. fall through
LOGGER.log(Level.FINE, "Failed to resolve vfszip into a jar location",e);
} finally {
is.close();
}
}
if(resURL.startsWith("vfs:")) {
// JBoss6
String dotdot="";
for (int i=clazz.getName().split("\\.").length; i>1; i--)
dotdot+="../";
try {
URL jar = new URL(res,dotdot);
String path = jar.getPath();
if (path.endsWith("/")) path=path.substring(0,path.length()-1);
// obtain the file name portion
String fileName = path.substring(path.lastIndexOf('/')+1);
Object vfs = new URL(jar,"..").getContent(); // a VirtualFile object pointing to the parent of the jar
File dir = (File)vfs.getClass().getMethod("getPhysicalFile").invoke(vfs);
File jarFile = new File(dir,fileName);
if (jarFile.exists()) return jarFile;
} catch (Exception e) {
LOGGER.log(Level.FINE, "Failed to resolve vfs file into a location",e);
}
}
URLConnection con = res.openConnection();
if (con instanceof JarURLConnection) {
JarURLConnection jcon = (JarURLConnection) con;
JarFile jarFile = jcon.getJarFile();
if (jarFile!=null) {
String n = jarFile.getName();
if(n.length()>0) {// JDK6u10 needs this
return new File(n);
} else {
// JDK6u10 apparently starts hiding the real jar file name,
// so this just keeps getting tricker and trickier...
try {
Field f = ZipFile.class.getDeclaredField("name");
f.setAccessible(true);
return new File((String) f.get(jarFile));
} catch (NoSuchFieldException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
} catch (IllegalAccessException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
}
}
}
}
throw new IllegalArgumentException(originalURL + " - " + resURL);
}
public static File jarFile(URL resource) throws IOException {
return fromJarUrlToFile(resource.toExternalForm());
}
private static File fromJarUrlToFile(String resURL) throws MalformedURLException {
resURL = resURL.substring(resURL.indexOf(':')+1, resURL.lastIndexOf('!')); // cut off "scheme:" and the file name portion
return new File(decode(new URL(resURL).getPath()));
}
/**
* Decode '%HH'.
*/
private static String decode(String s) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for( int i=0; i<s.length();i++ ) {
char ch = s.charAt(i);
if(ch=='%') {
baos.write(hexToInt(s.charAt(i+1))*16 + hexToInt(s.charAt(i+2)));
i+=2;
continue;
}
baos.write(ch);
}
try {
return new String(baos.toByteArray(),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error(e); // impossible
}
}
private static int hexToInt(int ch) {
return Character.getNumericValue(ch);
}
private static final Logger LOGGER = Logger.getLogger(Which.class.getName());
}
| true | true | public static File jarFile(Class clazz) throws IOException {
URL res = jarURL(clazz);
String resURL = res.toExternalForm();
String originalURL = resURL;
if(resURL.startsWith("jar:file:") || resURL.startsWith("wsjar:file:"))
return fromJarUrlToFile(resURL);
if(resURL.startsWith("code-source:/")) {
// OC4J apparently uses this. See http://www.nabble.com/Hudson-on-OC4J-tt16702113.html
resURL = resURL.substring("code-source:/".length(), resURL.lastIndexOf('!')); // cut off jar: and the file name portion
return new File(decode(new URL("file:/"+resURL).getPath()));
}
if(resURL.startsWith("zip:")){
// weblogic uses this. See http://www.nabble.com/patch-to-get-Hudson-working-on-weblogic-td23997258.html
// also see http://www.nabble.com/Re%3A-Hudson-on-Weblogic-10.3-td25038378.html#a25043415
resURL = resURL.substring("zip:".length(), resURL.lastIndexOf('!')); // cut off zip: and the file name portion
return new File(decode(new URL("file:"+resURL).getPath()));
}
if(resURL.startsWith("file:")) {
// unpackaged classes
int n = clazz.getName().split("\\.").length; // how many slashes do wo need to cut?
for( ; n>0; n-- ) {
int idx = Math.max(resURL.lastIndexOf('/'), resURL.lastIndexOf('\\'));
if(idx<0) throw new IllegalArgumentException(originalURL + " - " + resURL);
resURL = resURL.substring(0,idx);
}
// won't work if res URL contains ' '
// return new File(new URI(null,new URL(res).toExternalForm(),null));
// won't work if res URL contains '%20'
// return new File(new URL(res).toURI());
return new File(decode(new URL(resURL).getPath()));
}
if(resURL.startsWith("vfszip:")) {
// JBoss5
InputStream is = res.openStream();
try {
Object delegate = is;
while (delegate.getClass().getEnclosingClass()!=ZipFile.class) {
Field f = is.getClass().getDeclaredField("delegate");
f.setAccessible(true);
delegate = f.get(is);
}
Field f = delegate.getClass().getDeclaredField("this$0");
f.setAccessible(true);
ZipFile zipFile = (ZipFile)f.get(delegate);
return new File(zipFile.getName());
} catch (NoSuchFieldException e) {
// something must have changed in JBoss5. fall through
LOGGER.log(Level.FINE, "Failed to resolve vfszip into a jar location",e);
} catch (IllegalAccessException e) {
// something must have changed in JBoss5. fall through
LOGGER.log(Level.FINE, "Failed to resolve vfszip into a jar location",e);
} finally {
is.close();
}
}
if(resURL.startsWith("vfs:")) {
// JBoss6
String dotdot="";
for (int i=clazz.getName().split("\\.").length; i>1; i--)
dotdot+="../";
try {
URL jar = new URL(res,dotdot);
String path = jar.getPath();
if (path.endsWith("/")) path=path.substring(0,path.length()-1);
// obtain the file name portion
String fileName = path.substring(path.lastIndexOf('/')+1);
Object vfs = new URL(jar,"..").getContent(); // a VirtualFile object pointing to the parent of the jar
File dir = (File)vfs.getClass().getMethod("getPhysicalFile").invoke(vfs);
File jarFile = new File(dir,fileName);
if (jarFile.exists()) return jarFile;
} catch (Exception e) {
LOGGER.log(Level.FINE, "Failed to resolve vfs file into a location",e);
}
}
URLConnection con = res.openConnection();
if (con instanceof JarURLConnection) {
JarURLConnection jcon = (JarURLConnection) con;
JarFile jarFile = jcon.getJarFile();
if (jarFile!=null) {
String n = jarFile.getName();
if(n.length()>0) {// JDK6u10 needs this
return new File(n);
} else {
// JDK6u10 apparently starts hiding the real jar file name,
// so this just keeps getting tricker and trickier...
try {
Field f = ZipFile.class.getDeclaredField("name");
f.setAccessible(true);
return new File((String) f.get(jarFile));
} catch (NoSuchFieldException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
} catch (IllegalAccessException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
}
}
}
}
throw new IllegalArgumentException(originalURL + " - " + resURL);
}
| public static File jarFile(Class clazz) throws IOException {
URL res = jarURL(clazz);
String resURL = res.toExternalForm();
String originalURL = resURL;
if(resURL.startsWith("jar:file:") || resURL.startsWith("wsjar:file:"))
return fromJarUrlToFile(resURL);
if(resURL.startsWith("code-source:/")) {
// OC4J apparently uses this. See http://www.nabble.com/Hudson-on-OC4J-tt16702113.html
resURL = resURL.substring("code-source:/".length(), resURL.lastIndexOf('!')); // cut off jar: and the file name portion
return new File(decode(new URL("file:/"+resURL).getPath()));
}
if(resURL.startsWith("zip:")){
// weblogic uses this. See http://www.nabble.com/patch-to-get-Hudson-working-on-weblogic-td23997258.html
// also see http://www.nabble.com/Re%3A-Hudson-on-Weblogic-10.3-td25038378.html#a25043415
resURL = resURL.substring("zip:".length(), resURL.lastIndexOf('!')); // cut off zip: and the file name portion
return new File(decode(new URL("file:"+resURL).getPath()));
}
if(resURL.startsWith("file:")) {
// unpackaged classes
int n = clazz.getName().split("\\.").length; // how many slashes do wo need to cut?
for( ; n>0; n-- ) {
int idx = Math.max(resURL.lastIndexOf('/'), resURL.lastIndexOf('\\'));
if(idx<0) throw new IllegalArgumentException(originalURL + " - " + resURL);
resURL = resURL.substring(0,idx);
}
// won't work if res URL contains ' '
// return new File(new URI(null,new URL(res).toExternalForm(),null));
// won't work if res URL contains '%20'
// return new File(new URL(res).toURI());
return new File(decode(new URL(resURL).getPath()));
}
if(resURL.startsWith("vfszip:")) {
// JBoss5
InputStream is = res.openStream();
try {
Object delegate = is;
while (delegate.getClass().getEnclosingClass()!=ZipFile.class) {
Field f = is.getClass().getDeclaredField("delegate");
f.setAccessible(true);
delegate = f.get(is);
//JENKINS-5922 - workaround for CertificateReaderInputStream; JBoss 5.0.0, EAP 5.0 and EAP 5.1
if(delegate.getClass().getName().equals("java.util.jar.JarVerifier$VerifierStream")){
f = delegate.getClass().getDeclaredField("is");
f.setAccessible(true);
delegate = f.get(delegate);
}
}
Field f = delegate.getClass().getDeclaredField("this$0");
f.setAccessible(true);
ZipFile zipFile = (ZipFile)f.get(delegate);
return new File(zipFile.getName());
} catch (NoSuchFieldException e) {
// something must have changed in JBoss5. fall through
LOGGER.log(Level.FINE, "Failed to resolve vfszip into a jar location",e);
} catch (IllegalAccessException e) {
// something must have changed in JBoss5. fall through
LOGGER.log(Level.FINE, "Failed to resolve vfszip into a jar location",e);
} finally {
is.close();
}
}
if(resURL.startsWith("vfs:")) {
// JBoss6
String dotdot="";
for (int i=clazz.getName().split("\\.").length; i>1; i--)
dotdot+="../";
try {
URL jar = new URL(res,dotdot);
String path = jar.getPath();
if (path.endsWith("/")) path=path.substring(0,path.length()-1);
// obtain the file name portion
String fileName = path.substring(path.lastIndexOf('/')+1);
Object vfs = new URL(jar,"..").getContent(); // a VirtualFile object pointing to the parent of the jar
File dir = (File)vfs.getClass().getMethod("getPhysicalFile").invoke(vfs);
File jarFile = new File(dir,fileName);
if (jarFile.exists()) return jarFile;
} catch (Exception e) {
LOGGER.log(Level.FINE, "Failed to resolve vfs file into a location",e);
}
}
URLConnection con = res.openConnection();
if (con instanceof JarURLConnection) {
JarURLConnection jcon = (JarURLConnection) con;
JarFile jarFile = jcon.getJarFile();
if (jarFile!=null) {
String n = jarFile.getName();
if(n.length()>0) {// JDK6u10 needs this
return new File(n);
} else {
// JDK6u10 apparently starts hiding the real jar file name,
// so this just keeps getting tricker and trickier...
try {
Field f = ZipFile.class.getDeclaredField("name");
f.setAccessible(true);
return new File((String) f.get(jarFile));
} catch (NoSuchFieldException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
} catch (IllegalAccessException e) {
LOGGER.log(Level.INFO, "Failed to obtain the local cache file name of "+clazz, e);
}
}
}
}
throw new IllegalArgumentException(originalURL + " - " + resURL);
}
|
diff --git a/src/org/openstreetmap/josm/actions/OpenLocationAction.java b/src/org/openstreetmap/josm/actions/OpenLocationAction.java
index 43713245..1f4e8c09 100644
--- a/src/org/openstreetmap/josm/actions/OpenLocationAction.java
+++ b/src/org/openstreetmap/josm/actions/OpenLocationAction.java
@@ -1,62 +1,63 @@
// License: GPL. Copyright 2007 by Immanuel Scholz and others
package org.openstreetmap.josm.actions;
import static org.openstreetmap.josm.tools.I18n.tr;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
import org.openstreetmap.josm.gui.ExtendedDialog;
import org.openstreetmap.josm.tools.GBC;
import org.openstreetmap.josm.tools.Shortcut;
/**
* Open an URL input dialog and load data from the given URL.
*
* @author imi
*/
public class OpenLocationAction extends JosmAction {
/**
* Create an open action. The name is "Open a file".
*/
public OpenLocationAction() {
super(tr("Open Location..."), "openlocation", tr("Open an URL."),
Shortcut.registerShortcut("system:open_location", tr("File: {0}", tr("Open Location...")), KeyEvent.VK_L, Shortcut.GROUP_MENU), true);
}
public void actionPerformed(ActionEvent e) {
JCheckBox layer = new JCheckBox(tr("Separate Layer"));
layer.setSelected(Main.pref.getBoolean("download.newlayer"));
JPanel all = new JPanel(new GridBagLayout());
all.add(new JLabel(tr("Enter URL to download:")), GBC.eol());
JTextField urltext = new JTextField(40);
all.add(urltext, GBC.eol());
all.add(layer, GBC.eol());
ExtendedDialog dialog = new ExtendedDialog(Main.parent,
tr("Download Location"),
new String[] {tr("Download URL"), tr("Cancel")}
);
dialog.setContent(all);
dialog.setButtonIcons(new String[] {"download.png", "cancel.png"});
+ dialog.showDialog();
if (dialog.getValue() != 1) return;
openUrl(layer.isSelected(), urltext.getText());
}
/**
* Open the given file.
*/
public void openUrl(boolean new_layer, String url) {
new DownloadOsmTask().loadUrl(new_layer, url);
}
}
| true | true | public void actionPerformed(ActionEvent e) {
JCheckBox layer = new JCheckBox(tr("Separate Layer"));
layer.setSelected(Main.pref.getBoolean("download.newlayer"));
JPanel all = new JPanel(new GridBagLayout());
all.add(new JLabel(tr("Enter URL to download:")), GBC.eol());
JTextField urltext = new JTextField(40);
all.add(urltext, GBC.eol());
all.add(layer, GBC.eol());
ExtendedDialog dialog = new ExtendedDialog(Main.parent,
tr("Download Location"),
new String[] {tr("Download URL"), tr("Cancel")}
);
dialog.setContent(all);
dialog.setButtonIcons(new String[] {"download.png", "cancel.png"});
if (dialog.getValue() != 1) return;
openUrl(layer.isSelected(), urltext.getText());
}
| public void actionPerformed(ActionEvent e) {
JCheckBox layer = new JCheckBox(tr("Separate Layer"));
layer.setSelected(Main.pref.getBoolean("download.newlayer"));
JPanel all = new JPanel(new GridBagLayout());
all.add(new JLabel(tr("Enter URL to download:")), GBC.eol());
JTextField urltext = new JTextField(40);
all.add(urltext, GBC.eol());
all.add(layer, GBC.eol());
ExtendedDialog dialog = new ExtendedDialog(Main.parent,
tr("Download Location"),
new String[] {tr("Download URL"), tr("Cancel")}
);
dialog.setContent(all);
dialog.setButtonIcons(new String[] {"download.png", "cancel.png"});
dialog.showDialog();
if (dialog.getValue() != 1) return;
openUrl(layer.isSelected(), urltext.getText());
}
|
diff --git a/org.envirocar.app/src/org/envirocar/app/activity/MainActivity.java b/org.envirocar.app/src/org/envirocar/app/activity/MainActivity.java
index 163a714d..28f9f383 100644
--- a/org.envirocar.app/src/org/envirocar/app/activity/MainActivity.java
+++ b/org.envirocar.app/src/org/envirocar/app/activity/MainActivity.java
@@ -1,721 +1,721 @@
/*
* enviroCar 2013
* Copyright (C) 2013
* Martin Dueren, Jakob Moellers, Gerald Pape, Christopher Stephan
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package org.envirocar.app.activity;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.envirocar.app.R;
import org.envirocar.app.activity.StartStopButtonUtil.OnTrackModeChangeListener;
import org.envirocar.app.activity.preference.CarSelectionPreference;
import org.envirocar.app.application.CarManager;
import org.envirocar.app.application.ECApplication;
import org.envirocar.app.application.NavMenuItem;
import org.envirocar.app.application.UserManager;
import org.envirocar.app.application.service.AbstractBackgroundServiceStateReceiver;
import org.envirocar.app.application.service.AbstractBackgroundServiceStateReceiver.ServiceState;
import org.envirocar.app.application.service.BackgroundServiceImpl;
import org.envirocar.app.application.service.DeviceInRangeService;
import org.envirocar.app.logging.Logger;
import org.envirocar.app.network.RestClient;
import org.envirocar.app.storage.DbAdapterImpl;
import org.envirocar.app.util.Util;
import org.envirocar.app.views.TypefaceEC;
import org.envirocar.app.views.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.loopj.android.http.JsonHttpResponseHandler;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
/**
* Main UI application that cares about the auto-upload, auto-connect and global
* UI elements
*
* @author jakob
* @author gerald
*
* @param <AndroidAlarmService>
*/
public class MainActivity<AndroidAlarmService> extends SherlockFragmentActivity implements OnItemClickListener {
public static final int TRACK_MODE_SINGLE = 0;
public static final int TRACK_MODE_AUTO = 1;
private int actionBarTitleID = 0;
private ActionBar actionBar;
public ECApplication application;
private FragmentManager manager;
//Navigation Drawer
private DrawerLayout drawer;
private ListView drawerList;
private NavAdapter navDrawerAdapter;
// Menu Items
private NavMenuItem[] navDrawerItems;
static final int DASHBOARD = 0;
static final int LOGIN = 1;
static final int MY_TRACKS = 2;
static final int START_STOP_MEASUREMENT = 3;
static final int SETTINGS = 4;
static final int HELP = 5;
static final int SEND_LOG = 6;
static final String DASHBOARD_TAG = "DASHBOARD";
static final String LOGIN_TAG = "LOGIN";
static final String MY_TRACKS_TAG = "MY_TRACKS";
static final String HELP_TAG = "HELP";
static final String SEND_LOG_TAG = "SEND_LOG";
public static final int REQUEST_MY_GARAGE = 1336;
public static final int REQUEST_REDIRECT_TO_GARAGE = 1337;
private static final Logger logger = Logger.getLogger(MainActivity.class);
private static final String SERVICE_STATE = "serviceState";
private static final String TRACK_MODE = "trackMode";
// Include settings for auto upload and auto-connect
private SharedPreferences preferences = null;
boolean alwaysUpload = false;
boolean uploadOnlyInWlan = true;
private BroadcastReceiver serviceStateReceiver;
private OnSharedPreferenceChangeListener settingsReceiver;
protected ServiceState serviceState = ServiceState.SERVICE_STOPPED;
private BroadcastReceiver bluetoothStateReceiver;
private int trackMode = TRACK_MODE_SINGLE;
private Runnable remainingTimeThread;
private long targetTime;
private Handler remainingTimeHandler;
private BroadcastReceiver deviceInRangReceiver;
private boolean deviceDiscoveryActive;
private void prepareNavDrawerItems(){
if(this.navDrawerItems == null){
navDrawerItems = new NavMenuItem[7];
navDrawerItems[LOGIN] = new NavMenuItem(LOGIN, getResources().getString(R.string.menu_login),R.drawable.device_access_accounts);
navDrawerItems[SETTINGS] = new NavMenuItem(SETTINGS, getResources().getString(R.string.menu_settings),R.drawable.action_settings);
navDrawerItems[START_STOP_MEASUREMENT] = new NavMenuItem(START_STOP_MEASUREMENT, getResources().getString(R.string.menu_start),R.drawable.av_play);
navDrawerItems[DASHBOARD] = new NavMenuItem(DASHBOARD, getResources().getString(R.string.dashboard), R.drawable.dashboard);
navDrawerItems[MY_TRACKS] = new NavMenuItem(MY_TRACKS, getResources().getString(R.string.my_tracks),R.drawable.device_access_storage);
navDrawerItems[HELP] = new NavMenuItem(HELP, getResources().getString(R.string.menu_help), R.drawable.action_help);
navDrawerItems[SEND_LOG] = new NavMenuItem(SEND_LOG, getResources().getString(R.string.menu_send_log), R.drawable.action_report);
}
if (UserManager.instance().isLoggedIn()) {
navDrawerItems[LOGIN].setTitle(getResources().getString(R.string.menu_logout));
navDrawerItems[LOGIN].setSubtitle(String.format(getResources().getString(R.string.logged_in_as),UserManager.instance().getUser().getUsername()));
} else {
navDrawerItems[LOGIN].setTitle(getResources().getString(R.string.menu_login));
navDrawerItems[LOGIN].setSubtitle("");
}
navDrawerAdapter.notifyDataSetChanged();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
readSavedState(savedInstanceState);
this.setContentView(R.layout.main_layout);
application = ((ECApplication) getApplication());
preferences = PreferenceManager.getDefaultSharedPreferences(this);
alwaysUpload = preferences.getBoolean(SettingsActivity.ALWAYS_UPLOAD, false);
uploadOnlyInWlan = preferences.getBoolean(SettingsActivity.WIFI_UPLOAD, true);
checkKeepScreenOn();
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("");
// font stuff
actionBarTitleID = Utils.getActionBarId();
if (Utils.getActionBarId() != 0) {
((TextView) this.findViewById(actionBarTitleID))
.setTypeface(TypefaceEC.Newscycle(this));
}
actionBar.setLogo(getResources().getDrawable(R.drawable.actionbarlogo_with_padding));
manager = getSupportFragmentManager();
DashboardFragment initialFragment = new DashboardFragment();
manager.beginTransaction().replace(R.id.content_frame, initialFragment, DASHBOARD_TAG)
.commit();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerAdapter = new NavAdapter();
prepareNavDrawerItems();
updateStartStopButton();
drawerList.setAdapter(navDrawerAdapter);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
this, drawer, R.drawable.ic_drawer, R.string.open_drawer,
R.string.close_drawer) {
@Override
public void onDrawerOpened(View drawerView) {
prepareNavDrawerItems();
super.onDrawerOpened(drawerView);
}
};
drawer.setDrawerListener(actionBarDrawerToggle);
drawerList.setOnItemClickListener(this);
manager.executePendingTransactions();
serviceStateReceiver = new AbstractBackgroundServiceStateReceiver() {
@Override
public void onStateChanged(ServiceState state) {
serviceState = state;
if (serviceState == ServiceState.SERVICE_STOPPED && trackMode == TRACK_MODE_AUTO) {
/*
* lets see if we need to start the DeviceInRangeService
*/
synchronized (MainActivity.this) {
if (!deviceDiscoveryActive) {
application.startDeviceDiscoveryService();
deviceDiscoveryActive = true;
}
}
}
else if (serviceState == ServiceState.SERVICE_STARTED ||
serviceState == ServiceState.SERVICE_STARTING) {
/*
* we are currently connected, disable
* deviceDiscoverey related stuff
*/
deviceDiscoveryActive = false;
}
updateStartStopButton();
}
};
registerReceiver(serviceStateReceiver, new IntentFilter(AbstractBackgroundServiceStateReceiver.SERVICE_STATE));
bluetoothStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateStartStopButton();
}
};
deviceInRangReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
targetTime = intent.getLongExtra(DeviceInRangeService.TARGET_CONNECTION_TIME, 0);
invokeRemainingTimeThread();
createStartStopUtil().updateStartStopButtonOnServiceStateChange(navDrawerItems[START_STOP_MEASUREMENT]);
}
};
registerReceiver(deviceInRangReceiver, new IntentFilter(DeviceInRangeService.TARGET_CONNECTION_TIME));
registerReceiver(bluetoothStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
settingsReceiver = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (key.equals(SettingsActivity.BLUETOOTH_NAME)) {
updateStartStopButton();
}
- else if (key.equals(CarManager.PREF_KEY_SENSOR_ID)) {
+ else if (key.equals(SettingsActivity.CAR)) {
updateStartStopButton();
}
}
};
preferences.registerOnSharedPreferenceChangeListener(settingsReceiver);
if(isConnectedToInternet()){
getCarsFromServer();
}
}
private void getCarsFromServer() {
RestClient.downloadSensors(new JsonHttpResponseHandler() {
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
Toast.makeText(
MainActivity.this,
MainActivity.this
.getString(R.string.error_host_not_found),
Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(JSONObject response) {
super.onSuccess(response);
JSONArray res;
try {
res = response.getJSONArray("sensors");
} catch (JSONException e) {
logger.warn(e.getMessage(), e);
// TODO i18n
Toast.makeText(MainActivity.this,
"Could not retrieve cars from server",
Toast.LENGTH_SHORT).show();
return;
}
JSONArray cars = new JSONArray();
for (int i = 0; i < res.length(); i++) {
String typeString;
try {
typeString = ((JSONObject) res.get(i)).optString(
"type", "none");
if (typeString
.equals(CarSelectionPreference.SENSOR_TYPE)) {
cars.put(res.get(i));
}
} catch (JSONException e) {
logger.warn(e.getMessage(), e);
continue;
}
}
saveCarsToExternalStorage(cars);
}
});
}
private void saveCarsToExternalStorage(JSONArray cars) {
try {
File carCacheFile = Util
.createFileOnExternalStorage(CarManager.CAR_CACHE_FILE_NAME);
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(
carCacheFile));
bufferedWriter.write(cars.toString());
bufferedWriter.close();
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
}
private void readSavedState(Bundle savedInstanceState) {
if (savedInstanceState == null) return;
this.serviceState = (ServiceState) savedInstanceState.getSerializable(SERVICE_STATE);
this.trackMode = savedInstanceState.getInt(TRACK_MODE);
BackgroundServiceImpl.requestServiceStateBroadcast(getApplicationContext());
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(SERVICE_STATE, serviceState);
outState.putInt(TRACK_MODE, trackMode);
}
protected void updateStartStopButton() {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null && adapter.isEnabled()) { // was requirementsFulfilled
createStartStopUtil().updateStartStopButtonOnServiceStateChange(navDrawerItems[START_STOP_MEASUREMENT]);
} else {
createStartStopUtil().defineButtonContents(navDrawerItems[START_STOP_MEASUREMENT],
false, R.drawable.not_available, getString(R.string.pref_bluetooth_disabled),
getString(R.string.menu_start));
}
navDrawerAdapter.notifyDataSetChanged();
}
/**
* start a thread that updates the UI until the device was
* discovered
*/
private void invokeRemainingTimeThread() {
if (remainingTimeThread == null || targetTime > System.currentTimeMillis()) {
remainingTimeHandler = new Handler();
remainingTimeThread = new Runnable() {
@Override
public void run() {
final long deltaSec = (targetTime - System.currentTimeMillis()) / 1000;
final long minutes = deltaSec / 60;
final long secs = deltaSec - (minutes*60);
if (deviceDiscoveryActive && deltaSec > 0) {
runOnUiThread(new Runnable() {
@Override
public void run() {
navDrawerItems[START_STOP_MEASUREMENT].setSubtitle(
String.format(getString(R.string.device_discovery_next_try),
String.format("%02d", minutes), String.format("%02d", secs)
));
navDrawerAdapter.notifyDataSetChanged();
}
});
remainingTimeHandler.postDelayed(remainingTimeThread, 1000);
} else {
logger.info("NOT SHOWING!");
}
}
};
remainingTimeHandler.post(remainingTimeThread);
}
}
private class NavAdapter extends BaseAdapter {
@Override
public boolean isEnabled(int position) {
//to allow things like start bluetooth or go to settings from "disabled" action
return (position == START_STOP_MEASUREMENT ? true : navDrawerItems[position].isEnabled());
}
@Override
public int getCount() {
return navDrawerItems.length;
}
@Override
public Object getItem(int position) {
return navDrawerItems[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
NavMenuItem currentItem = ((NavMenuItem) getItem(position));
View item;
if(currentItem.getSubtitle().equals("")){
item = View.inflate(MainActivity.this,R.layout.nav_item_1, null);
} else {
item = View.inflate(MainActivity.this,R.layout.nav_item_2, null);
TextView textView2 = (TextView) item.findViewById(android.R.id.text2);
textView2.setText(currentItem.getSubtitle());
if(!currentItem.isEnabled()) textView2.setTextColor(Color.GRAY);
}
ImageView icon = ((ImageView) item.findViewById(R.id.nav_item_icon));
icon.setImageResource(currentItem.getIconRes());
TextView textView = (TextView) item.findViewById(android.R.id.text1);
textView.setText(currentItem.getTitle());
if(!currentItem.isEnabled()){
textView.setTextColor(Color.GRAY);
icon.setColorFilter(Color.GRAY);
}
TypefaceEC.applyCustomFont((ViewGroup) item, TypefaceEC.Raleway(MainActivity.this));
return item;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
openFragment(position);
}
private void openFragment(int position) {
FragmentManager manager = getSupportFragmentManager();
switch (position) {
// Go to the dashboard
case DASHBOARD:
if(isFragmentVisible(DASHBOARD_TAG)){
break;
}
Fragment dashboardFragment = getSupportFragmentManager().findFragmentByTag(DASHBOARD_TAG);
if (dashboardFragment == null) {
dashboardFragment = new DashboardFragment();
}
manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
manager.beginTransaction().replace(R.id.content_frame, dashboardFragment, DASHBOARD_TAG).commit();
break;
//Start the Login activity
case LOGIN:
if(UserManager.instance().isLoggedIn()){
UserManager.instance().logOut();
ListTracksFragment listMeasurementsFragment = (ListTracksFragment) getSupportFragmentManager().findFragmentByTag("MY_TRACKS");
// check if this fragment is initialized
if (listMeasurementsFragment != null) {
listMeasurementsFragment.clearRemoteTracks();
}else{
//the remote tracks need to be removed in any case
DbAdapterImpl.instance().deleteAllRemoteTracks();
}
Crouton.makeText(this, R.string.bye_bye, Style.CONFIRM).show();
} else {
if(isFragmentVisible(LOGIN_TAG)){
break;
}
LoginFragment loginFragment = new LoginFragment();
manager.beginTransaction().replace(R.id.content_frame, loginFragment, LOGIN_TAG).addToBackStack(null).commit();
}
break;
// Go to the settings
case SETTINGS:
Intent configIntent = new Intent(this, SettingsActivity.class);
startActivity(configIntent);
break;
// Go to the track list
case MY_TRACKS:
if(isFragmentVisible(MY_TRACKS_TAG)){
break;
}
ListTracksFragment listMeasurementFragment = new ListTracksFragment();
manager.beginTransaction().replace(R.id.content_frame, listMeasurementFragment, MY_TRACKS_TAG).addToBackStack(null).commit();
break;
// Start or stop the measurement process
case START_STOP_MEASUREMENT:
if (!navDrawerItems[position].isEnabled()) return;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
String remoteDevice = preferences.getString(org.envirocar.app.activity.SettingsActivity.BLUETOOTH_KEY,null);
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter != null && adapter.isEnabled() && remoteDevice != null) {
if(CarManager.instance().getCar() == null){
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
} else {
/*
* We are good to go. process the state and stuff
*/
OnTrackModeChangeListener trackModeListener = new OnTrackModeChangeListener() {
@Override
public void onTrackModeChange(int tm) {
trackMode = tm;
}
};
createStartStopUtil().processButtonClick(trackModeListener);
}
} else {
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
}
break;
case HELP:
if(isFragmentVisible(HELP_TAG)){
break;
}
HelpFragment helpFragment = new HelpFragment();
manager.beginTransaction().replace(R.id.content_frame, helpFragment, HELP_TAG).addToBackStack(null).commit();
break;
case SEND_LOG:
if(isFragmentVisible(SEND_LOG_TAG)){
break;
}
SendLogFileFragment logFragment = new SendLogFileFragment();
manager.beginTransaction().replace(R.id.content_frame, logFragment, SEND_LOG_TAG).addToBackStack(null).commit();
default:
break;
}
drawer.closeDrawer(drawerList);
}
private StartStopButtonUtil createStartStopUtil() {
return new StartStopButtonUtil(application, this, trackMode, serviceState, deviceDiscoveryActive);
}
/**
* This method checks, whether a Fragment with a certain tag is visible.
* @param tag The tag of the Fragment.
* @return True if the Fragment is visible, false if not.
*/
public boolean isFragmentVisible(String tag){
Fragment tmpFragment = getSupportFragmentManager().findFragmentByTag(tag);
if(tmpFragment != null && tmpFragment.isVisible()){
logger.info("Fragment with tag: " + tag + " is already visible.");
return true;
}
return false;
}
@Override
protected void onDestroy() {
super.onDestroy();
// Close db connection
// application.closeDb();
// Remove the services etc.
// application.destroyStuff();
Crouton.cancelAllCroutons();
// this.unregisterReceiver(application.getBluetoothChangeReceiver());
}
@Override
protected void onResume() {
super.onResume();
drawer.closeDrawer(drawerList);
//first init
firstInit();
application.setActivity(this);
checkKeepScreenOn();
alwaysUpload = preferences.getBoolean(SettingsActivity.ALWAYS_UPLOAD, false);
uploadOnlyInWlan = preferences.getBoolean(SettingsActivity.WIFI_UPLOAD, true);
}
private void checkKeepScreenOn() {
if (preferences.getBoolean(SettingsActivity.DISPLAY_STAYS_ACTIV, false)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
/**
* Determine what the menu buttons do
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (drawer.isDrawerOpen(drawerList)) {
drawer.closeDrawer(drawerList);
} else {
drawer.openDrawer(drawerList);
}
return true;
}
return false;
}
private void firstInit(){
if(!preferences.contains("first_init")){
drawer.openDrawer(drawerList);
Editor e = preferences.edit();
e.putString("first_init", "seen");
e.putBoolean("pref_privacy", true);
e.commit();
}
}
public boolean isConnectedToInternet() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
readSavedState(savedInstanceState);
this.setContentView(R.layout.main_layout);
application = ((ECApplication) getApplication());
preferences = PreferenceManager.getDefaultSharedPreferences(this);
alwaysUpload = preferences.getBoolean(SettingsActivity.ALWAYS_UPLOAD, false);
uploadOnlyInWlan = preferences.getBoolean(SettingsActivity.WIFI_UPLOAD, true);
checkKeepScreenOn();
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("");
// font stuff
actionBarTitleID = Utils.getActionBarId();
if (Utils.getActionBarId() != 0) {
((TextView) this.findViewById(actionBarTitleID))
.setTypeface(TypefaceEC.Newscycle(this));
}
actionBar.setLogo(getResources().getDrawable(R.drawable.actionbarlogo_with_padding));
manager = getSupportFragmentManager();
DashboardFragment initialFragment = new DashboardFragment();
manager.beginTransaction().replace(R.id.content_frame, initialFragment, DASHBOARD_TAG)
.commit();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerAdapter = new NavAdapter();
prepareNavDrawerItems();
updateStartStopButton();
drawerList.setAdapter(navDrawerAdapter);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
this, drawer, R.drawable.ic_drawer, R.string.open_drawer,
R.string.close_drawer) {
@Override
public void onDrawerOpened(View drawerView) {
prepareNavDrawerItems();
super.onDrawerOpened(drawerView);
}
};
drawer.setDrawerListener(actionBarDrawerToggle);
drawerList.setOnItemClickListener(this);
manager.executePendingTransactions();
serviceStateReceiver = new AbstractBackgroundServiceStateReceiver() {
@Override
public void onStateChanged(ServiceState state) {
serviceState = state;
if (serviceState == ServiceState.SERVICE_STOPPED && trackMode == TRACK_MODE_AUTO) {
/*
* lets see if we need to start the DeviceInRangeService
*/
synchronized (MainActivity.this) {
if (!deviceDiscoveryActive) {
application.startDeviceDiscoveryService();
deviceDiscoveryActive = true;
}
}
}
else if (serviceState == ServiceState.SERVICE_STARTED ||
serviceState == ServiceState.SERVICE_STARTING) {
/*
* we are currently connected, disable
* deviceDiscoverey related stuff
*/
deviceDiscoveryActive = false;
}
updateStartStopButton();
}
};
registerReceiver(serviceStateReceiver, new IntentFilter(AbstractBackgroundServiceStateReceiver.SERVICE_STATE));
bluetoothStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateStartStopButton();
}
};
deviceInRangReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
targetTime = intent.getLongExtra(DeviceInRangeService.TARGET_CONNECTION_TIME, 0);
invokeRemainingTimeThread();
createStartStopUtil().updateStartStopButtonOnServiceStateChange(navDrawerItems[START_STOP_MEASUREMENT]);
}
};
registerReceiver(deviceInRangReceiver, new IntentFilter(DeviceInRangeService.TARGET_CONNECTION_TIME));
registerReceiver(bluetoothStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
settingsReceiver = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (key.equals(SettingsActivity.BLUETOOTH_NAME)) {
updateStartStopButton();
}
else if (key.equals(CarManager.PREF_KEY_SENSOR_ID)) {
updateStartStopButton();
}
}
};
preferences.registerOnSharedPreferenceChangeListener(settingsReceiver);
if(isConnectedToInternet()){
getCarsFromServer();
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
readSavedState(savedInstanceState);
this.setContentView(R.layout.main_layout);
application = ((ECApplication) getApplication());
preferences = PreferenceManager.getDefaultSharedPreferences(this);
alwaysUpload = preferences.getBoolean(SettingsActivity.ALWAYS_UPLOAD, false);
uploadOnlyInWlan = preferences.getBoolean(SettingsActivity.WIFI_UPLOAD, true);
checkKeepScreenOn();
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("");
// font stuff
actionBarTitleID = Utils.getActionBarId();
if (Utils.getActionBarId() != 0) {
((TextView) this.findViewById(actionBarTitleID))
.setTypeface(TypefaceEC.Newscycle(this));
}
actionBar.setLogo(getResources().getDrawable(R.drawable.actionbarlogo_with_padding));
manager = getSupportFragmentManager();
DashboardFragment initialFragment = new DashboardFragment();
manager.beginTransaction().replace(R.id.content_frame, initialFragment, DASHBOARD_TAG)
.commit();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerAdapter = new NavAdapter();
prepareNavDrawerItems();
updateStartStopButton();
drawerList.setAdapter(navDrawerAdapter);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
this, drawer, R.drawable.ic_drawer, R.string.open_drawer,
R.string.close_drawer) {
@Override
public void onDrawerOpened(View drawerView) {
prepareNavDrawerItems();
super.onDrawerOpened(drawerView);
}
};
drawer.setDrawerListener(actionBarDrawerToggle);
drawerList.setOnItemClickListener(this);
manager.executePendingTransactions();
serviceStateReceiver = new AbstractBackgroundServiceStateReceiver() {
@Override
public void onStateChanged(ServiceState state) {
serviceState = state;
if (serviceState == ServiceState.SERVICE_STOPPED && trackMode == TRACK_MODE_AUTO) {
/*
* lets see if we need to start the DeviceInRangeService
*/
synchronized (MainActivity.this) {
if (!deviceDiscoveryActive) {
application.startDeviceDiscoveryService();
deviceDiscoveryActive = true;
}
}
}
else if (serviceState == ServiceState.SERVICE_STARTED ||
serviceState == ServiceState.SERVICE_STARTING) {
/*
* we are currently connected, disable
* deviceDiscoverey related stuff
*/
deviceDiscoveryActive = false;
}
updateStartStopButton();
}
};
registerReceiver(serviceStateReceiver, new IntentFilter(AbstractBackgroundServiceStateReceiver.SERVICE_STATE));
bluetoothStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateStartStopButton();
}
};
deviceInRangReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
targetTime = intent.getLongExtra(DeviceInRangeService.TARGET_CONNECTION_TIME, 0);
invokeRemainingTimeThread();
createStartStopUtil().updateStartStopButtonOnServiceStateChange(navDrawerItems[START_STOP_MEASUREMENT]);
}
};
registerReceiver(deviceInRangReceiver, new IntentFilter(DeviceInRangeService.TARGET_CONNECTION_TIME));
registerReceiver(bluetoothStateReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
settingsReceiver = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
if (key.equals(SettingsActivity.BLUETOOTH_NAME)) {
updateStartStopButton();
}
else if (key.equals(SettingsActivity.CAR)) {
updateStartStopButton();
}
}
};
preferences.registerOnSharedPreferenceChangeListener(settingsReceiver);
if(isConnectedToInternet()){
getCarsFromServer();
}
}
|
diff --git a/src/com/madalla/service/blog/BlogService.java b/src/com/madalla/service/blog/BlogService.java
index e0f75651..7b6991cc 100644
--- a/src/com/madalla/service/blog/BlogService.java
+++ b/src/com/madalla/service/blog/BlogService.java
@@ -1,121 +1,121 @@
package com.madalla.service.blog;
import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.jcr.RepositoryException;
import javax.swing.tree.TreeModel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.madalla.dao.blog.BlogDao;
import com.madalla.service.cms.IContentService;
import com.madalla.util.ui.CalendarUtils;
import com.madalla.webapp.cms.Content;
public class BlogService implements IBlogService, Serializable{
private static final long serialVersionUID = 1L;
private static final String BLOG_PREFIX = "blog";
//TODO refactor to allow multiple blogs per site
private static final String BLOG_NAME = "mainBlog";
private BlogDao dao;
private IContentService contentService;
private Log log = LogFactory.getLog(this.getClass());
public List getBlogCategories(){
return dao.getBlogCategories();
}
public int saveBlogEntry(BlogEntry blogEntry) {
int blogId;
if (blogEntry.getId() == 0){
log.debug("saveBlogEntry - inserting "+blogEntry);
blogId = dao.insertBlogEntry(blogEntry);
} else {
log.debug("saveBlogEntry - updating "+blogEntry);
dao.saveBlogEntry(blogEntry);
blogId = blogEntry.getId();
}
//save content to CMS
Content content = new Content();
- content.setClassName(dao.getSite());
+ content.setClassName(BLOG_NAME);
content.setContentId(getBlogId(blogId));
content.setText(blogEntry.getText());
try {
log.debug("saveBlogEntry - saving Content "+content);
contentService.setContent(content);
} catch (RepositoryException e) {
log.error("saveBlogEntry - ", e);
}
return blogId;
}
public BlogEntry getBlogEntry(int id) {
BlogEntry blogEntry = dao.getBlogEntry(id);
populateContentFromCMS(blogEntry);
return blogEntry;
}
public List getBlogEntriesForCategory(int categoryId) {
List list = dao.getBlogEntriesForCategory(categoryId);
return getBlogEntries(list);
}
public List getBlogEntries() {
//get Metadata from database
List list = dao.getBlogEntriesForSite();
return getBlogEntries(list);
}
public TreeModel getBlogEntriesAsTree(){
List list = getBlogEntries();
return CalendarUtils.createMonthlyTree("Blog Archive", list);
}
public void deleteBlogEntry(int id){
dao.deleteBlogEntry(id);
}
private void populateContentFromCMS(BlogEntry blogEntry){
log.debug("populateContent - before Content :"+blogEntry);
String id = getBlogId(blogEntry.getId());
log.debug("populateContent - retrieve content from CMS for node="+BLOG_NAME+" id="+id);
String content = contentService.getContentData(BLOG_NAME, id);
log.debug("populateContent - content="+content);
blogEntry.setText(content);
}
private String getBlogId(int id){
return BLOG_PREFIX + Integer.toString(id);
}
/**
* Content from CMS repository and sorts it
* @param list
* @return
*/
private List getBlogEntries(List list){
for (Iterator iter = list.iterator(); iter.hasNext();) {
BlogEntry blogEntry = (BlogEntry) iter.next();
populateContentFromCMS(blogEntry);
}
Collections.sort(list);
return list;
}
public void setDao(BlogDao dao) {
this.dao = dao;
}
public void setContentService(IContentService contentService) {
this.contentService = contentService;
}
}
| true | true | public int saveBlogEntry(BlogEntry blogEntry) {
int blogId;
if (blogEntry.getId() == 0){
log.debug("saveBlogEntry - inserting "+blogEntry);
blogId = dao.insertBlogEntry(blogEntry);
} else {
log.debug("saveBlogEntry - updating "+blogEntry);
dao.saveBlogEntry(blogEntry);
blogId = blogEntry.getId();
}
//save content to CMS
Content content = new Content();
content.setClassName(dao.getSite());
content.setContentId(getBlogId(blogId));
content.setText(blogEntry.getText());
try {
log.debug("saveBlogEntry - saving Content "+content);
contentService.setContent(content);
} catch (RepositoryException e) {
log.error("saveBlogEntry - ", e);
}
return blogId;
}
| public int saveBlogEntry(BlogEntry blogEntry) {
int blogId;
if (blogEntry.getId() == 0){
log.debug("saveBlogEntry - inserting "+blogEntry);
blogId = dao.insertBlogEntry(blogEntry);
} else {
log.debug("saveBlogEntry - updating "+blogEntry);
dao.saveBlogEntry(blogEntry);
blogId = blogEntry.getId();
}
//save content to CMS
Content content = new Content();
content.setClassName(BLOG_NAME);
content.setContentId(getBlogId(blogId));
content.setText(blogEntry.getText());
try {
log.debug("saveBlogEntry - saving Content "+content);
contentService.setContent(content);
} catch (RepositoryException e) {
log.error("saveBlogEntry - ", e);
}
return blogId;
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/parser/ManualGreqlLexer.java b/src/de/uni_koblenz/jgralab/greql2/parser/ManualGreqlLexer.java
index 65df15bb5..dd8637545 100644
--- a/src/de/uni_koblenz/jgralab/greql2/parser/ManualGreqlLexer.java
+++ b/src/de/uni_koblenz/jgralab/greql2/parser/ManualGreqlLexer.java
@@ -1,358 +1,358 @@
package de.uni_koblenz.jgralab.greql2.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import de.uni_koblenz.jgralab.greql2.exception.ParsingException;
public class ManualGreqlLexer {
protected static Map<TokenTypes, String> fixedTokens;
{
fixedTokens = new HashMap<TokenTypes, String>();
fixedTokens.put(TokenTypes.T, "T");
fixedTokens.put(TokenTypes.AND, "and");
fixedTokens.put(TokenTypes.FALSE, "false");
fixedTokens.put(TokenTypes.NOT, "not");
fixedTokens.put(TokenTypes.NULL_VALUE, "null");
fixedTokens.put(TokenTypes.OR, "or");
fixedTokens.put(TokenTypes.TRUE, "true");
fixedTokens.put(TokenTypes.XOR, "xor");
fixedTokens.put(TokenTypes.AS, "as");
fixedTokens.put(TokenTypes.BAG, "bag");
fixedTokens.put(TokenTypes.MAP, "map");
fixedTokens.put(TokenTypes.E, "E");
fixedTokens.put(TokenTypes.ESUBGRAPH, "eSubgraph");
fixedTokens.put(TokenTypes.EXISTS_ONE, "exists!");
fixedTokens.put(TokenTypes.EXISTS, "exists");
fixedTokens.put(TokenTypes.END, "end");
fixedTokens.put(TokenTypes.FORALL, "forall");
fixedTokens.put(TokenTypes.FROM, "from");
fixedTokens.put(TokenTypes.IN, "in");
fixedTokens.put(TokenTypes.LET, "let");
fixedTokens.put(TokenTypes.LIST, "list");
fixedTokens.put(TokenTypes.PATH, "pathconstruction");
fixedTokens.put(TokenTypes.PATHSYSTEM, "pathsystemconstruction");
fixedTokens.put(TokenTypes.REC, "rec");
fixedTokens.put(TokenTypes.REPORT, "report");
fixedTokens.put(TokenTypes.REPORTSET, "reportSet");
fixedTokens.put(TokenTypes.REPORTBAG, "reportBag");
fixedTokens.put(TokenTypes.REPORTTABLE, "reportTable");
fixedTokens.put(TokenTypes.REPORTMAP, "reportMap");
fixedTokens.put(TokenTypes.STORE, "store");
fixedTokens.put(TokenTypes.SET, "set");
fixedTokens.put(TokenTypes.TUP, "tup");
fixedTokens.put(TokenTypes.USING, "using");
fixedTokens.put(TokenTypes.V, "V");
fixedTokens.put(TokenTypes.VSUBGRAPH, "vSubgraph");
fixedTokens.put(TokenTypes.WHERE, "where");
fixedTokens.put(TokenTypes.WITH, "with");
fixedTokens.put(TokenTypes.QUESTION, "?");
fixedTokens.put(TokenTypes.EXCL, "!");
fixedTokens.put(TokenTypes.COLON, ":");
fixedTokens.put(TokenTypes.COMMA, ",");
fixedTokens.put(TokenTypes.DOT, ".");
fixedTokens.put(TokenTypes.DOTDOT, "..");
fixedTokens.put(TokenTypes.AT, "@");
fixedTokens.put(TokenTypes.LPAREN, "(");
fixedTokens.put(TokenTypes.RPAREN, ")");
fixedTokens.put(TokenTypes.LBRACK, "[");
fixedTokens.put(TokenTypes.RBRACK, "]");
fixedTokens.put(TokenTypes.LCURLY, "{");
fixedTokens.put(TokenTypes.RCURLY, "}");
fixedTokens.put(TokenTypes.EDGESTART, "<-");
fixedTokens.put(TokenTypes.EDGEEND, "->");
fixedTokens.put(TokenTypes.EDGE, "--");
fixedTokens.put(TokenTypes.RARROW, "-->");
fixedTokens.put(TokenTypes.LARROW, "<--");
fixedTokens.put(TokenTypes.ARROW, "<->");
fixedTokens.put(TokenTypes.ASSIGN, ":=");
fixedTokens.put(TokenTypes.EQUAL, "=");
fixedTokens.put(TokenTypes.MATCH, "=~");
fixedTokens.put(TokenTypes.NOT_EQUAL, "<>");
fixedTokens.put(TokenTypes.LE, "<=");
fixedTokens.put(TokenTypes.GE, ">=");
fixedTokens.put(TokenTypes.L_T, "<");
fixedTokens.put(TokenTypes.G_T, ">");
fixedTokens.put(TokenTypes.DIV, "/");
fixedTokens.put(TokenTypes.PLUS, "+");
fixedTokens.put(TokenTypes.MINUS, "-");
fixedTokens.put(TokenTypes.STAR, "*");
fixedTokens.put(TokenTypes.MOD, "%");
fixedTokens.put(TokenTypes.PLUSPLUS, "++");
fixedTokens.put(TokenTypes.SEMI, ";");
fixedTokens.put(TokenTypes.CARET, "^");
fixedTokens.put(TokenTypes.BOR, "|");
fixedTokens.put(TokenTypes.AMP, "&");
fixedTokens.put(TokenTypes.SMILEY, ":-)");
fixedTokens.put(TokenTypes.HASH, "#");
fixedTokens.put(TokenTypes.OUTAGGREGATION, "<>--");
fixedTokens.put(TokenTypes.INAGGREGATION, "--<>");
fixedTokens.put(TokenTypes.PATHSYSTEMSTART, "-<");
fixedTokens.put(TokenTypes.IMPORT, "import");
}
protected String query = null;
protected int position = 0;
public ManualGreqlLexer(String source) {
this.query = source;
if (query == null) {
throw new NullPointerException(
"Cannot parse nullpointer as GReQL query");
}
}
public static String getTokenString(TokenTypes token) {
return fixedTokens.get(token);
}
private final static boolean isSeparator(int c) {
return (c == ';') || (c == '<') || (c == '>') || (c == '(')
|| (c == ')') || (c == '{') || (c == '}') || (c == ':')
|| (c == '[') || (c == ']') || (c == ',') || (c == ' ')
|| (c == '\n') || (c == '\t') || (c == '.') || (c == '-')
|| (c == '+') || (c == '*') || (c == '/') || (c == '%')
|| (c == '=') || (c == '?') || (c == '^')
|| (c == '|') || (c == '!') || (c == '@');
}
public Token getNextToken() {
TokenTypes recognizedTokenType = null;
Token recognizedToken = null;
int bml = 0; // best match length
skipWs();
// recognize fixed tokens
for (Entry<TokenTypes, String> currentEntry : fixedTokens.entrySet()) {
String currentString = currentEntry.getValue();
int currLen = currentString.length();
if (bml > currLen) {
continue;
}
if (query.regionMatches(position, currentString, 0, currLen)) {
if (((position + currLen) == query.length())
|| isSeparator(query.charAt(position + currLen - 1))
|| isSeparator(query.charAt(position + currLen))) {
bml = currLen;
recognizedTokenType = currentEntry.getKey();
}
}
}
// recognize strings and identifiers
if (recognizedTokenType == null) {
if (query.charAt(position) == '\"') { // String
position++;
int start = position;
StringBuilder sb = new StringBuilder();
while ((position < query.length())
&& (query.charAt(position) != '\"')) {
if (query.charAt(position) == '\\') {
if (position == query.length()) {
throw new ParsingException(
"String started at position " + start
+ " but is not closed in query",
query.substring(start, position), start,
position - start, query);
}
if ((query.charAt(position + 1) == '\"')
|| (query.charAt(position + 1) == '\\')) {
position++;
}
}
sb.append(query.charAt(position));
position++;
}
if ((position >= query.length())
|| (query.charAt(position) != '\"')) {
throw new ParsingException("String started at position "
+ start + " but is not closed in query", sb
.toString(), start, position - start, query);
}
recognizedTokenType = TokenTypes.STRING;
recognizedToken = new ComplexToken(recognizedTokenType, start,
position, sb.toString());
position++;
} else {
// identifier and literals
StringBuffer nextPossibleToken = new StringBuffer();
int start = position;
while ((query.length() > position)
&& (!isSeparator(query.charAt(position)))) {
nextPossibleToken.append(query.charAt(position++));
}
- if (query.length() <= position) {
+ if (query.length() < position) {
return new SimpleToken(TokenTypes.EOF, start, 0);
}
String tokenText = nextPossibleToken.toString();
if (tokenText.equals("thisVertex")) {
recognizedToken = new ComplexToken(TokenTypes.THISVERTEX,
start, position - start, tokenText);
} else if (tokenText.equals("thisEdge")) {
recognizedToken = new ComplexToken(TokenTypes.THISEDGE,
start, position - start, tokenText);
} else if (startsWithNumber(tokenText)) {
recognizedToken = matchNumericToken(start,
position - start, tokenText);
} else {
recognizedToken = new ComplexToken(TokenTypes.IDENTIFIER,
start, position - start, tokenText);
}
}
} else {
recognizedToken = new SimpleToken(recognizedTokenType, position,
bml);
position += bml;
}
if (recognizedToken == null) {
throw new ParsingException(
"Error while scanning query at position", null, position,
position, query);
}
return recognizedToken;
}
private final boolean startsWithNumber(String text) {
char c = text.charAt(0);
return (c >= Character.valueOf('0')) && (c <= Character.valueOf('9'));
}
// TODO: Exponenten
private final Token matchNumericToken(int start, int end, String text) {
int value = 0;
int decValue = 0;
TokenTypes type = null;
if ((text.charAt(0) == '0') && (text.charAt(text.length() - 1) != 'f')
&& (text.charAt(text.length() - 1) != 'F')
&& (text.charAt(text.length() - 1) != 'd')
&& (text.charAt(text.length() - 1) != 'D')) {
if (text.length() == 1) {
type = TokenTypes.INTLITERAL;
value = 0;
} else if ((text.charAt(1) == 'x') || (text.charAt(1) == 'X')) {
type = TokenTypes.HEXLITERAL;
try {
value = Integer.parseInt(text.substring(2), 16);
} catch (NumberFormatException ex) {
throw new ParsingException("Not a valid hex number", text,
start, end - start, query);
}
} else {
type = TokenTypes.OCTLITERAL;
try {
value = Integer.parseInt(text.substring(1), 8);
decValue = Integer.parseInt(text);
} catch (NumberFormatException ex) {
throw new ParsingException("Not a valid octal number",
text, start, end - start, query);
}
}
} else {
switch (text.charAt(text.length() - 1)) {
case 'h':
type = TokenTypes.HEXLITERAL;
try {
value = Integer.parseInt(text.substring(0,
text.length() - 1), 16);
} catch (NumberFormatException ex) {
throw new ParsingException("Not a valid hex number", text,
start, end - start, query);
}
break;
case 'd':
case 'D':
case 'f':
case 'F':
type = TokenTypes.REALLITERAL;
try {
String tokenString = text.substring(0, text.length() - 1);
System.out.println("TokenString: " + tokenString);
return new RealToken(type, start, end - start, Double
.parseDouble(tokenString));
} catch (NumberFormatException ex) {
throw new ParsingException("Not a valid float number",
text, start, end - start, query);
}
default:
type = TokenTypes.INTLITERAL;
try {
value = Integer.parseInt(text);
} catch (NumberFormatException ex) {
throw new ParsingException("Not a valid integer number",
text, start, end - start, query);
}
}
}
if (type != TokenTypes.OCTLITERAL) {
decValue = value;
}
return new IntegerToken(type, start, end - start, value, decValue);
}
public boolean hasNextToken() {
skipWs();
return (position < query.length());
}
private final static boolean isWs(int c) {
return (c == ' ') || (c == '\n') || (c == '\t') || (c == '\r');
}
private final void skipWs() {
// skip whitespace and consecutive single line comments
do {
// skip whitespace
while ((position < query.length()) && isWs(query.charAt(position))) {
position++;
}
// skip single line comments
if ((position < query.length() - 2)
&& (query.substring(position, position + 2).equals("//"))) {
position++;
while ((position < query.length())
&& (query.charAt(position) != '\n')) {
position++;
}
if ((position < query.length()) && (query.charAt(position) == '\n')) {
position++;
}
}
//skip multiline comments
if ((position < query.length() - 4)
&& (query.substring(position, position + 2).equals("/*"))) {
position++;
while ((position < query.length()-1)
&& (query.substring(position, position + 2).equals("*/"))) {
position++;
}
if ((position < query.length()) && (query.substring(position, position + 2).equals("*/"))) {
position+=2;
}
}
} while (
((position < query.length()) && (isWs(query.charAt(position))))
|| ((position < query.length() - 2) && (query.substring(position, position + 2).equals("//")))
|| ((position < query.length() - 4) && (query.substring(position, position + 2).equals("/*")))
);
}
public static List<Token> scan(String query) {
List<Token> list = new ArrayList<Token>();
ManualGreqlLexer lexer = new ManualGreqlLexer(query);
while (lexer.hasNextToken()) {
Token nextToken = lexer.getNextToken();
list.add(nextToken);
}
if (list.isEmpty() || (list.get(list.size()-1).type != TokenTypes.EOF)) {
list.add(new SimpleToken(TokenTypes.EOF, lexer.position, 0));
}
return list;
}
}
| true | true | public Token getNextToken() {
TokenTypes recognizedTokenType = null;
Token recognizedToken = null;
int bml = 0; // best match length
skipWs();
// recognize fixed tokens
for (Entry<TokenTypes, String> currentEntry : fixedTokens.entrySet()) {
String currentString = currentEntry.getValue();
int currLen = currentString.length();
if (bml > currLen) {
continue;
}
if (query.regionMatches(position, currentString, 0, currLen)) {
if (((position + currLen) == query.length())
|| isSeparator(query.charAt(position + currLen - 1))
|| isSeparator(query.charAt(position + currLen))) {
bml = currLen;
recognizedTokenType = currentEntry.getKey();
}
}
}
// recognize strings and identifiers
if (recognizedTokenType == null) {
if (query.charAt(position) == '\"') { // String
position++;
int start = position;
StringBuilder sb = new StringBuilder();
while ((position < query.length())
&& (query.charAt(position) != '\"')) {
if (query.charAt(position) == '\\') {
if (position == query.length()) {
throw new ParsingException(
"String started at position " + start
+ " but is not closed in query",
query.substring(start, position), start,
position - start, query);
}
if ((query.charAt(position + 1) == '\"')
|| (query.charAt(position + 1) == '\\')) {
position++;
}
}
sb.append(query.charAt(position));
position++;
}
if ((position >= query.length())
|| (query.charAt(position) != '\"')) {
throw new ParsingException("String started at position "
+ start + " but is not closed in query", sb
.toString(), start, position - start, query);
}
recognizedTokenType = TokenTypes.STRING;
recognizedToken = new ComplexToken(recognizedTokenType, start,
position, sb.toString());
position++;
} else {
// identifier and literals
StringBuffer nextPossibleToken = new StringBuffer();
int start = position;
while ((query.length() > position)
&& (!isSeparator(query.charAt(position)))) {
nextPossibleToken.append(query.charAt(position++));
}
if (query.length() <= position) {
return new SimpleToken(TokenTypes.EOF, start, 0);
}
String tokenText = nextPossibleToken.toString();
if (tokenText.equals("thisVertex")) {
recognizedToken = new ComplexToken(TokenTypes.THISVERTEX,
start, position - start, tokenText);
} else if (tokenText.equals("thisEdge")) {
recognizedToken = new ComplexToken(TokenTypes.THISEDGE,
start, position - start, tokenText);
} else if (startsWithNumber(tokenText)) {
recognizedToken = matchNumericToken(start,
position - start, tokenText);
} else {
recognizedToken = new ComplexToken(TokenTypes.IDENTIFIER,
start, position - start, tokenText);
}
}
} else {
recognizedToken = new SimpleToken(recognizedTokenType, position,
bml);
position += bml;
}
if (recognizedToken == null) {
throw new ParsingException(
"Error while scanning query at position", null, position,
position, query);
}
return recognizedToken;
}
| public Token getNextToken() {
TokenTypes recognizedTokenType = null;
Token recognizedToken = null;
int bml = 0; // best match length
skipWs();
// recognize fixed tokens
for (Entry<TokenTypes, String> currentEntry : fixedTokens.entrySet()) {
String currentString = currentEntry.getValue();
int currLen = currentString.length();
if (bml > currLen) {
continue;
}
if (query.regionMatches(position, currentString, 0, currLen)) {
if (((position + currLen) == query.length())
|| isSeparator(query.charAt(position + currLen - 1))
|| isSeparator(query.charAt(position + currLen))) {
bml = currLen;
recognizedTokenType = currentEntry.getKey();
}
}
}
// recognize strings and identifiers
if (recognizedTokenType == null) {
if (query.charAt(position) == '\"') { // String
position++;
int start = position;
StringBuilder sb = new StringBuilder();
while ((position < query.length())
&& (query.charAt(position) != '\"')) {
if (query.charAt(position) == '\\') {
if (position == query.length()) {
throw new ParsingException(
"String started at position " + start
+ " but is not closed in query",
query.substring(start, position), start,
position - start, query);
}
if ((query.charAt(position + 1) == '\"')
|| (query.charAt(position + 1) == '\\')) {
position++;
}
}
sb.append(query.charAt(position));
position++;
}
if ((position >= query.length())
|| (query.charAt(position) != '\"')) {
throw new ParsingException("String started at position "
+ start + " but is not closed in query", sb
.toString(), start, position - start, query);
}
recognizedTokenType = TokenTypes.STRING;
recognizedToken = new ComplexToken(recognizedTokenType, start,
position, sb.toString());
position++;
} else {
// identifier and literals
StringBuffer nextPossibleToken = new StringBuffer();
int start = position;
while ((query.length() > position)
&& (!isSeparator(query.charAt(position)))) {
nextPossibleToken.append(query.charAt(position++));
}
if (query.length() < position) {
return new SimpleToken(TokenTypes.EOF, start, 0);
}
String tokenText = nextPossibleToken.toString();
if (tokenText.equals("thisVertex")) {
recognizedToken = new ComplexToken(TokenTypes.THISVERTEX,
start, position - start, tokenText);
} else if (tokenText.equals("thisEdge")) {
recognizedToken = new ComplexToken(TokenTypes.THISEDGE,
start, position - start, tokenText);
} else if (startsWithNumber(tokenText)) {
recognizedToken = matchNumericToken(start,
position - start, tokenText);
} else {
recognizedToken = new ComplexToken(TokenTypes.IDENTIFIER,
start, position - start, tokenText);
}
}
} else {
recognizedToken = new SimpleToken(recognizedTokenType, position,
bml);
position += bml;
}
if (recognizedToken == null) {
throw new ParsingException(
"Error while scanning query at position", null, position,
position, query);
}
return recognizedToken;
}
|
diff --git a/src/java/org/apache/log4j/xml/XMLLayout.java b/src/java/org/apache/log4j/xml/XMLLayout.java
index 20504e37..8162a4d0 100644
--- a/src/java/org/apache/log4j/xml/XMLLayout.java
+++ b/src/java/org/apache/log4j/xml/XMLLayout.java
@@ -1,169 +1,169 @@
/*
* Copyright 1999-2005 The Apache Software Foundation.
*
* 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.
*/
// Contributors: Mathias Bogaert
package org.apache.log4j.xml;
import org.apache.log4j.Layout;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.DateLayout;
import org.apache.log4j.helpers.Transform;
/**
* The output of the XMLLayout consists of a series of log4j:event
* elements as defined in the <a
* href="doc-files/log4j.dtd">log4j.dtd</a>. It does not output a
* complete well-formed XML file. The output is designed to be
* included as an <em>external entity</em> in a separate file to form
* a correct XML file.
*
* <p>For example, if <code>abc</code> is the name of the file where
* the XMLLayout ouput goes, then a well-formed XML file would be:
*
<pre>
<?xml version="1.0" ?>
<!DOCTYPE log4j:eventSet SYSTEM "log4j.dtd" [<!ENTITY data SYSTEM "abc">]>
<log4j:eventSet version="1.2" xmlns:log4j="http://jakarta.apache.org/log4j/">
&data;
</log4j:eventSet>
</pre>
* <p>This approach enforces the independence of the XMLLayout and the
* appender where it is embedded.
*
* <p>The <code>version</code> attribute helps components to correctly
* intrepret output generated by XMLLayout. The value of this
* attribute should be "1.1" for output generated by log4j versions
* prior to log4j 1.2 (final release) and "1.2" for relase 1.2 and
* later.
*
* @author Ceki Gülcü
* @since 0.9.0
* */
public class XMLLayout extends Layout {
private final int DEFAULT_SIZE = 256;
private final int UPPER_LIMIT = 2048;
private StringBuffer buf = new StringBuffer(DEFAULT_SIZE);
private boolean locationInfo = false;
/**
* The <b>LocationInfo</b> option takes a boolean value. By default,
* it is set to false which means there will be no location
* information output by this layout. If the the option is set to
* true, then the file name and line number of the statement at the
* origin of the log statement will be output.
*
* <p>If you are embedding this layout within an {@link
* org.apache.log4j.net.SMTPAppender} then make sure to set the
* <b>LocationInfo</b> option of that appender as well.
* */
public void setLocationInfo(boolean flag) {
locationInfo = flag;
}
/**
Returns the current value of the <b>LocationInfo</b> option.
*/
public boolean getLocationInfo() {
return locationInfo;
}
/** No options to activate. */
public void activateOptions() {
}
/**
* Formats a {@link LoggingEvent} in conformance with the log4j.dtd.
* */
public String format(LoggingEvent event) {
// Reset working buffer. If the buffer is too large, then we need a new
// one in order to avoid the penalty of creating a large array.
if(buf.capacity() > UPPER_LIMIT) {
buf = new StringBuffer(DEFAULT_SIZE);
} else {
buf.setLength(0);
}
// We yield to the \r\n heresy.
buf.append("<log4j:event logger=\"");
buf.append(event.getLoggerName());
buf.append("\" timestamp=\"");
buf.append(event.timeStamp);
buf.append("\" level=\"");
buf.append(event.getLevel());
buf.append("\" thread=\"");
buf.append(event.getThreadName());
buf.append("\">\r\n");
buf.append("<log4j:message><![CDATA[");
// Append the rendered message. Also make sure to escape any
// existing CDATA sections.
Transform.appendEscapingCDATA(buf, event.getRenderedMessage());
buf.append("]]></log4j:message>\r\n");
String ndc = event.getNDC();
if(ndc != null) {
buf.append("<log4j:NDC><![CDATA[");
buf.append(ndc);
buf.append("]]></log4j:NDC>\r\n");
}
String[] s = event.getThrowableStrRep();
if(s != null) {
buf.append("<log4j:throwable><![CDATA[");
for(int i = 0; i < s.length; i++) {
buf.append(s[i]);
buf.append("\r\n");
}
buf.append("]]></log4j:throwable>\r\n");
}
if(locationInfo) {
LocationInfo locationInfo = event.getLocationInformation();
buf.append("<log4j:locationInfo class=\"");
- buf.append(locationInfo.getClassName());
+ buf.append(Transform.escapeTags(locationInfo.getClassName()));
buf.append("\" method=\"");
buf.append(Transform.escapeTags(locationInfo.getMethodName()));
buf.append("\" file=\"");
buf.append(locationInfo.getFileName());
buf.append("\" line=\"");
buf.append(locationInfo.getLineNumber());
buf.append("\"/>\r\n");
}
buf.append("</log4j:event>\r\n\r\n");
return buf.toString();
}
/**
The XMLLayout prints and does not ignore exceptions. Hence the
return value <code>false</code>.
*/
public boolean ignoresThrowable() {
return false;
}
}
| true | true | public String format(LoggingEvent event) {
// Reset working buffer. If the buffer is too large, then we need a new
// one in order to avoid the penalty of creating a large array.
if(buf.capacity() > UPPER_LIMIT) {
buf = new StringBuffer(DEFAULT_SIZE);
} else {
buf.setLength(0);
}
// We yield to the \r\n heresy.
buf.append("<log4j:event logger=\"");
buf.append(event.getLoggerName());
buf.append("\" timestamp=\"");
buf.append(event.timeStamp);
buf.append("\" level=\"");
buf.append(event.getLevel());
buf.append("\" thread=\"");
buf.append(event.getThreadName());
buf.append("\">\r\n");
buf.append("<log4j:message><![CDATA[");
// Append the rendered message. Also make sure to escape any
// existing CDATA sections.
Transform.appendEscapingCDATA(buf, event.getRenderedMessage());
buf.append("]]></log4j:message>\r\n");
String ndc = event.getNDC();
if(ndc != null) {
buf.append("<log4j:NDC><![CDATA[");
buf.append(ndc);
buf.append("]]></log4j:NDC>\r\n");
}
String[] s = event.getThrowableStrRep();
if(s != null) {
buf.append("<log4j:throwable><![CDATA[");
for(int i = 0; i < s.length; i++) {
buf.append(s[i]);
buf.append("\r\n");
}
buf.append("]]></log4j:throwable>\r\n");
}
if(locationInfo) {
LocationInfo locationInfo = event.getLocationInformation();
buf.append("<log4j:locationInfo class=\"");
buf.append(locationInfo.getClassName());
buf.append("\" method=\"");
buf.append(Transform.escapeTags(locationInfo.getMethodName()));
buf.append("\" file=\"");
buf.append(locationInfo.getFileName());
buf.append("\" line=\"");
buf.append(locationInfo.getLineNumber());
buf.append("\"/>\r\n");
}
buf.append("</log4j:event>\r\n\r\n");
return buf.toString();
}
| public String format(LoggingEvent event) {
// Reset working buffer. If the buffer is too large, then we need a new
// one in order to avoid the penalty of creating a large array.
if(buf.capacity() > UPPER_LIMIT) {
buf = new StringBuffer(DEFAULT_SIZE);
} else {
buf.setLength(0);
}
// We yield to the \r\n heresy.
buf.append("<log4j:event logger=\"");
buf.append(event.getLoggerName());
buf.append("\" timestamp=\"");
buf.append(event.timeStamp);
buf.append("\" level=\"");
buf.append(event.getLevel());
buf.append("\" thread=\"");
buf.append(event.getThreadName());
buf.append("\">\r\n");
buf.append("<log4j:message><![CDATA[");
// Append the rendered message. Also make sure to escape any
// existing CDATA sections.
Transform.appendEscapingCDATA(buf, event.getRenderedMessage());
buf.append("]]></log4j:message>\r\n");
String ndc = event.getNDC();
if(ndc != null) {
buf.append("<log4j:NDC><![CDATA[");
buf.append(ndc);
buf.append("]]></log4j:NDC>\r\n");
}
String[] s = event.getThrowableStrRep();
if(s != null) {
buf.append("<log4j:throwable><![CDATA[");
for(int i = 0; i < s.length; i++) {
buf.append(s[i]);
buf.append("\r\n");
}
buf.append("]]></log4j:throwable>\r\n");
}
if(locationInfo) {
LocationInfo locationInfo = event.getLocationInformation();
buf.append("<log4j:locationInfo class=\"");
buf.append(Transform.escapeTags(locationInfo.getClassName()));
buf.append("\" method=\"");
buf.append(Transform.escapeTags(locationInfo.getMethodName()));
buf.append("\" file=\"");
buf.append(locationInfo.getFileName());
buf.append("\" line=\"");
buf.append(locationInfo.getLineNumber());
buf.append("\"/>\r\n");
}
buf.append("</log4j:event>\r\n\r\n");
return buf.toString();
}
|
diff --git a/asakusa-test-moderator/src/main/java/com/asakusafw/testdriver/file/FileImporterPreparator.java b/asakusa-test-moderator/src/main/java/com/asakusafw/testdriver/file/FileImporterPreparator.java
index 54d2e1872..00a52111c 100644
--- a/asakusa-test-moderator/src/main/java/com/asakusafw/testdriver/file/FileImporterPreparator.java
+++ b/asakusa-test-moderator/src/main/java/com/asakusafw/testdriver/file/FileImporterPreparator.java
@@ -1,179 +1,179 @@
/**
* Copyright 2011 Asakusa Framework Team.
*
* 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.asakusafw.testdriver.file;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asakusafw.runtime.io.ModelOutput;
import com.asakusafw.runtime.util.VariableTable;
import com.asakusafw.testdriver.core.BaseImporterPreparator;
import com.asakusafw.testdriver.core.DataModelDefinition;
import com.asakusafw.testdriver.core.ImporterPreparator;
import com.asakusafw.testdriver.core.TestContext;
import com.asakusafw.testdriver.hadoop.ConfigurationFactory;
import com.asakusafw.vocabulary.external.FileImporterDescription;
/**
* Implementation of {@link ImporterPreparator} for {@link FileImporterDescription}s.
* @since 0.2.0
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class FileImporterPreparator extends BaseImporterPreparator<FileImporterDescription> {
static final Logger LOG = LoggerFactory.getLogger(FileImporterPreparator.class);
private final ConfigurationFactory configurations;
/**
* Creates a new instance with default configurations.
*/
public FileImporterPreparator() {
this(ConfigurationFactory.getDefault());
}
/**
* Creates a new instance.
* @param configurations the configuration factory
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public FileImporterPreparator(ConfigurationFactory configurations) {
if (configurations == null) {
throw new IllegalArgumentException("configurations must not be null"); //$NON-NLS-1$
}
this.configurations = configurations;
}
@Override
public void truncate(FileImporterDescription description, TestContext context) throws IOException {
LOG.info("インポート元をクリアしています: {}", description);
VariableTable variables = createVariables(context);
Configuration config = configurations.newInstance();
FileSystem fs = FileSystem.get(config);
for (String path : description.getPaths()) {
String resolved = variables.parse(path, false);
Path target = fs.makeQualified(new Path(resolved));
LOG.debug("ファイルを削除しています: {}", target);
boolean succeed = fs.delete(target, true);
LOG.debug("ファイルを削除しました (succeed={}): {}", succeed, target);
}
}
@Override
public <V> ModelOutput<V> createOutput(
DataModelDefinition<V> definition,
FileImporterDescription description,
TestContext context) throws IOException {
LOG.info("インポート元の初期値を設定します: {}", description);
checkType(definition, description);
Set<String> path = description.getPaths();
if (path.isEmpty()) {
return new ModelOutput<V>() {
@Override
public void close() throws IOException {
return;
}
@Override
public void write(V model) throws IOException {
return;
}
};
}
VariableTable variables = createVariables(context);
- String destination = path.iterator().next();
+ String destination = path.iterator().next().replace('*', '_');
String resolved = variables.parse(destination, false);
Configuration conf = configurations.newInstance();
FileOutputFormat output = getOpposite(conf, description.getInputFormat());
FileDeployer deployer = new FileDeployer(conf);
return deployer.openOutput(definition, resolved, output);
}
private VariableTable createVariables(TestContext context) {
assert context != null;
VariableTable result = new VariableTable();
result.defineVariables(context.getArguments());
return result;
}
private <V> void checkType(DataModelDefinition<V> definition,
FileImporterDescription description) throws IOException {
if (definition.getModelClass() != description.getModelType()) {
throw new IOException(MessageFormat.format(
"型が一致しません: モデルの型={0}, インポータの型={1} ({2})",
definition.getModelClass().getName(),
description.getModelType().getName(),
description));
}
}
private FileOutputFormat getOpposite(Configuration conf, Class<?> inputFormat) throws IOException {
assert conf != null;
assert inputFormat != null;
LOG.debug("Finding opposite OutputFormat: {}", inputFormat.getName());
String inputFormatName = inputFormat.getName();
String outputFormatName = infer(inputFormatName);
if (outputFormatName == null) {
throw new IOException(MessageFormat.format(
"Failed to infer opposite OutputFormat: {0}",
inputFormat.getName()));
}
LOG.debug("Inferred oppsite OutputFormat: {}", outputFormatName);
try {
Class<?> loaded = inputFormat.getClassLoader().loadClass(outputFormatName);
FileOutputFormat instance = (FileOutputFormat) ReflectionUtils.newInstance(loaded, conf);
if (instance instanceof Configurable) {
((Configurable) instance).setConf(conf);
}
return instance;
} catch (Exception e) {
throw new IOException(MessageFormat.format(
"Failed to create opposite OutputFormat: {0}",
inputFormat.getName()), e);
}
}
private static final Pattern INPUT = Pattern.compile("\\binput\\b|Input(?![a-z])");
private String infer(String inputFormatName) {
assert inputFormatName != null;
Matcher matcher = INPUT.matcher(inputFormatName);
StringBuilder buf = new StringBuilder();
int start = 0;
while (matcher.find()) {
String group = matcher.group();
buf.append(inputFormatName.substring(start, matcher.start()));
if (group.equals("input")) {
buf.append("output");
} else {
buf.append("Output");
}
start = matcher.end();
}
buf.append(inputFormatName.substring(start));
return buf.toString();
}
}
| true | true | public <V> ModelOutput<V> createOutput(
DataModelDefinition<V> definition,
FileImporterDescription description,
TestContext context) throws IOException {
LOG.info("インポート元の初期値を設定します: {}", description);
checkType(definition, description);
Set<String> path = description.getPaths();
if (path.isEmpty()) {
return new ModelOutput<V>() {
@Override
public void close() throws IOException {
return;
}
@Override
public void write(V model) throws IOException {
return;
}
};
}
VariableTable variables = createVariables(context);
String destination = path.iterator().next();
String resolved = variables.parse(destination, false);
Configuration conf = configurations.newInstance();
FileOutputFormat output = getOpposite(conf, description.getInputFormat());
FileDeployer deployer = new FileDeployer(conf);
return deployer.openOutput(definition, resolved, output);
}
| public <V> ModelOutput<V> createOutput(
DataModelDefinition<V> definition,
FileImporterDescription description,
TestContext context) throws IOException {
LOG.info("インポート元の初期値を設定します: {}", description);
checkType(definition, description);
Set<String> path = description.getPaths();
if (path.isEmpty()) {
return new ModelOutput<V>() {
@Override
public void close() throws IOException {
return;
}
@Override
public void write(V model) throws IOException {
return;
}
};
}
VariableTable variables = createVariables(context);
String destination = path.iterator().next().replace('*', '_');
String resolved = variables.parse(destination, false);
Configuration conf = configurations.newInstance();
FileOutputFormat output = getOpposite(conf, description.getInputFormat());
FileDeployer deployer = new FileDeployer(conf);
return deployer.openOutput(definition, resolved, output);
}
|
diff --git a/src/uk/co/uwcs/choob/modules/PluginModule.java b/src/uk/co/uwcs/choob/modules/PluginModule.java
index e5d0004..5c10a24 100644
--- a/src/uk/co/uwcs/choob/modules/PluginModule.java
+++ b/src/uk/co/uwcs/choob/modules/PluginModule.java
@@ -1,364 +1,364 @@
/*
* PluginModule.java
*
* Created on June 16, 2005, 2:36 PM
*/
package uk.co.uwcs.choob.modules;
import uk.co.uwcs.choob.plugins.*;
import uk.co.uwcs.choob.support.*;
import uk.co.uwcs.choob.support.events.*;
import uk.co.uwcs.choob.*;
import java.lang.*;
import java.util.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.sql.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.AccessControlException;
/**
* Module that performs functions relating to the plugin architecture of the bot.
* @author sadiq
*/
public final class PluginModule
{
private Map pluginMap;
private DbConnectionBroker broker;
private Modules mods;
private ChoobPluginManager hsPlugMan;
private ChoobPluginManager dPlugMan;
private ChoobPluginManager jsPlugMan;
private Choob bot;
/**
* Creates a new instance of the PluginModule.
* @param pluginMap Map containing currently loaded plugins.
*/
PluginModule(Map pluginMap, DbConnectionBroker broker, Modules mods, IRCInterface irc, Choob bot) throws ChoobException {
this.pluginMap = pluginMap;
this.broker = broker;
this.mods = mods;
this.hsPlugMan = new HaxSunPluginManager(mods, irc);
this.dPlugMan = new ChoobDistributingPluginManager();
this.jsPlugMan = new JavaScriptPluginManager(mods, irc);
this.bot=bot;
}
public ChoobPluginManager getPlugMan()
{
// XXX Need better permission name.
AccessController.checkPermission(new ChoobPermission("getPluginManager"));
return dPlugMan;
}
/**
* Adds a plugin to the loaded plugin map but first unloads any plugin already there.
*
* This method also calls the create() method on any new plugin.
* @param URL URL to the source of the plugin.
* @param pluginName Name for the class of the new plugin.
* @throws ChoobException Thrown if there's a syntactical error in the plugin's source.
*/
public void addPlugin(String pluginName, String URL) throws ChoobException {
URL srcURL;
try
{
srcURL = new URL(URL);
}
catch (MalformedURLException e)
{
throw new ChoobException("URL " + URL + " is malformed: " + e);
}
boolean existed;
if (srcURL.getFile().endsWith(".js"))
existed = jsPlugMan.loadPlugin(pluginName, srcURL);
else
existed = hsPlugMan.loadPlugin(pluginName, srcURL);
// Inform plugins, if they want to know.
if (existed)
bot.onPluginReLoaded(pluginName);
else
bot.onPluginLoaded(pluginName);
addPluginToDb(pluginName, URL);
}
/**
* Reloads a plugin which has been loaded previously, but may not be loaded currently.
*
* This method simply looks up the last source URL for the plugin, and calls addPlugin with it.
* @param pluginName Name of the plugin to reload.
* @throws ChoobException Thrown if there's a syntactical error in the plugin's source.
*/
public void reloadPlugin(String pluginName) throws ChoobException {
String URL = getPluginURL(pluginName);
if (URL == null)
throw new ChoobNoSuchPluginException(pluginName);
addPlugin(pluginName, URL);
}
/**
* Calmly stops a loaded plugin from queuing any further tasks. Existing tasks will run until they finish.
* @param pluginName Name of the plugin to reload.
* @throws ChoobNoSuchPluginException Thrown if the plugin doesn't exist.
*/
public void detachPlugin(String pluginName) throws ChoobNoSuchPluginException {
dPlugMan.unloadPlugin(pluginName);
bot.onPluginUnLoaded(pluginName);
}
/**
* Calmly stops a loaded plugin from queuing any further tasks. Existing tasks will run until they finish.
* @param pluginName Name of the plugin to reload.
* @throws ChoobNoSuchPluginException Thrown if the plugin doesn't exist.
*/
public void setCorePlugin(String pluginName, boolean isCore) throws ChoobNoSuchPluginException {
AccessController.checkPermission(new ChoobPermission("plugin.core"));
setCoreStatus(pluginName, isCore);
}
/**
* Call the API subroutine of name name on plugin pluginName and return the result.
* @param pluginName The name of the plugin to call.
* @param APIString The name of the routine to call.
* @param params Parameters to pass to the routine.
* @throws ChoobNoSuchCallException If the call could not be resolved.
* @throws ChoobInvocationError If the call threw an exception.
*/
public Object callAPI(final String pluginName, String APIString, Object... params) throws ChoobNoSuchCallException
{
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ChoobThread.pushPluginStatic(pluginName);
return null;
}
});
try
{
return dPlugMan.doAPI(pluginName, APIString, params);
}
finally
{
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ChoobThread.popPluginStatic();
return null;
}
});
}
}
/**
* Call the generic subroutine of type type and name name on plugin pluginName and return the result.
* @param pluginName The name of the plugin to call.
* @param type The type of the routine to call.
* @param name The name of the routine to call.
* @param params Parameters to pass to the routine.
* @throws ChoobNoSuchCallException If the call could not be resolved.
* @throws ChoobInvocationError If the call threw an exception.
*/
public Object callGeneric(final String pluginName, String type, String name, Object... params) throws ChoobNoSuchCallException
{
AccessController.checkPermission(new ChoobPermission("generic." + type));
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ChoobThread.pushPluginStatic(pluginName);
return null;
}
});
try
{
return dPlugMan.doGeneric(pluginName, type, name, params);
}
finally
{
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ChoobThread.popPluginStatic();
return null;
}
});
}
}
/**
* Cause a command of plugin pluginName to be queued for execution.
* @param pluginName The name of the plugin to call.
* @param command The name of the command to call.
* @param mes The message to pass to the routing
* @throws ChoobNoSuchCallException If the call could not be resolved.
*/
public void queueCommand(String pluginName, String command, Message mes) throws ChoobNoSuchCallException
{
AccessController.checkPermission(new ChoobPermission("generic.command"));
ChoobTask task = dPlugMan.commandTask(pluginName, command, mes);
if (task != null)
ChoobThreadManager.queueTask(task);
else
throw new ChoobNoSuchCallException(pluginName, "command " + command);
}
public String exceptionReply(Throwable e, String pluginName)
{
if (pluginName == null)
{
if (e instanceof ChoobException || e instanceof ChoobError)
return "A plugin went wrong: " + e.getMessage();
else if (e instanceof AccessControlException)
return "D'oh! A plugin needs permission " + ChoobAuthError.getPermissionText(((AccessControlException)e).getPermission()) + "!";
else
return "The plugin author was too lazy to trap the exception: " + e;
}
else
{
if (e instanceof ChoobException || e instanceof ChoobError)
return "Plugin " + pluginName + " went wrong: " + e.getMessage();
else if (e instanceof AccessControlException)
return "D'oh! Plugin " + pluginName + " needs permission " + ChoobAuthError.getPermissionText(((AccessControlException)e).getPermission()) + "!";
else
return "The author of plugin " + pluginName + " was too lazy to trap the exception: " + e;
}
}
/**
* Get a task to run the interval handler in a plugin.
* @param plugin The name of the plugin to run the interval on.
* @param param The parameter to pass to the interval handler.
* @return A ChoobTask that will run the handler.
*/
public ChoobTask doInterval(String plugin, Object param)
{
AccessController.checkPermission(new ChoobPermission("interval"));
return dPlugMan.intervalTask(plugin, param);
}
/**
* Get a list of loaded plugins.
* @return Names of all loaded plugins.
*/
public String[] getLoadedPlugins()
{
return dPlugMan.plugins();
}
/**
* Get a list of loaded plugins.
* @param pluginName plugin name to query
* @return Names of all commands in the plugin.
*/
public String[] getPluginCommands(String pluginName) throws ChoobNoSuchPluginException
{
String[] commands = dPlugMan.commands(pluginName);
if (commands == null)
throw new ChoobNoSuchPluginException(pluginName);
return commands;
}
/**
* Get a list of known plugins.
* @param onlyCore whether to only return known core plugins
* @return Names of all loaded plugins.
*/
public String[] getAllPlugins(boolean onlyCore)
{
return getPluginList(onlyCore);
}
private void setCoreStatus(String pluginName, boolean isCore) throws ChoobNoSuchPluginException {
Connection dbCon = null;
try {
dbCon = broker.getConnection();
PreparedStatement sqlSetCore = dbCon.prepareStatement("UPDATE Plugins SET CorePlugin = ? WHERE PluginName = ?");
sqlSetCore.setInt(1, isCore ? 1 : 0);
sqlSetCore.setString(2, pluginName);
if (sqlSetCore.executeUpdate() == 0)
throw new ChoobNoSuchPluginException(pluginName);
} catch (SQLException e) {
e.printStackTrace();
throw new ChoobInternalError("SQL Exception while setting core status on the plugin.");
} finally {
if (dbCon != null)
broker.freeConnection(dbCon);
}
}
private String[] getPluginList(boolean onlyCore) {
Connection dbCon = null;
try {
dbCon = broker.getConnection();
PreparedStatement sqlPlugins;
if (onlyCore)
sqlPlugins = dbCon.prepareStatement("SELECT PluginName FROM Plugins WHERE CorePlugin = 1");
else
sqlPlugins = dbCon.prepareStatement("SELECT PluginName FROM Plugins");
ResultSet names = sqlPlugins.executeQuery();
String[] plugins = new String[0];
- if (names.first())
+ if (!names.first())
return plugins;
List<String> plugList = new ArrayList<String>();
do
{
plugList.add(names.getString(1));
}
while(names.next());
return plugList.toArray(plugins);
} catch (SQLException e) {
e.printStackTrace();
throw new ChoobInternalError("SQL Exception while setting core status on the plugin.");
} finally {
if (dbCon != null)
broker.freeConnection(dbCon);
}
}
private String getPluginURL(String pluginName) throws ChoobNoSuchPluginException {
Connection dbCon = null;
try {
dbCon = broker.getConnection();
PreparedStatement sqlGetURL = dbCon.prepareStatement("SELECT URL FROM Plugins WHERE PluginName = ?");
sqlGetURL.setString(1, pluginName);
ResultSet url = sqlGetURL.executeQuery();
if (!url.first())
throw new ChoobNoSuchPluginException(pluginName);
return url.getString("URL");
} catch (SQLException e) {
e.printStackTrace();
throw new ChoobInternalError("SQL Exception while finding the plugin in the database.");
} finally {
if (dbCon != null)
broker.freeConnection(dbCon);
}
}
private void addPluginToDb(String pluginName, String URL) {
Connection dbCon = null;
try {
dbCon = broker.getConnection();
PreparedStatement pluginReplace = dbCon.prepareStatement("INSERT IGNORE Plugins (PluginName, URL) VALUES (?, ?)");
pluginReplace.setString(1, pluginName);
pluginReplace.setString(2, URL);
pluginReplace.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
throw new ChoobInternalError("SQL Exception while adding the plugin to the database...");
} finally {
broker.freeConnection(dbCon);
}
}
}
| true | true | private String[] getPluginList(boolean onlyCore) {
Connection dbCon = null;
try {
dbCon = broker.getConnection();
PreparedStatement sqlPlugins;
if (onlyCore)
sqlPlugins = dbCon.prepareStatement("SELECT PluginName FROM Plugins WHERE CorePlugin = 1");
else
sqlPlugins = dbCon.prepareStatement("SELECT PluginName FROM Plugins");
ResultSet names = sqlPlugins.executeQuery();
String[] plugins = new String[0];
if (names.first())
return plugins;
List<String> plugList = new ArrayList<String>();
do
{
plugList.add(names.getString(1));
}
while(names.next());
return plugList.toArray(plugins);
} catch (SQLException e) {
e.printStackTrace();
throw new ChoobInternalError("SQL Exception while setting core status on the plugin.");
} finally {
if (dbCon != null)
broker.freeConnection(dbCon);
}
}
| private String[] getPluginList(boolean onlyCore) {
Connection dbCon = null;
try {
dbCon = broker.getConnection();
PreparedStatement sqlPlugins;
if (onlyCore)
sqlPlugins = dbCon.prepareStatement("SELECT PluginName FROM Plugins WHERE CorePlugin = 1");
else
sqlPlugins = dbCon.prepareStatement("SELECT PluginName FROM Plugins");
ResultSet names = sqlPlugins.executeQuery();
String[] plugins = new String[0];
if (!names.first())
return plugins;
List<String> plugList = new ArrayList<String>();
do
{
plugList.add(names.getString(1));
}
while(names.next());
return plugList.toArray(plugins);
} catch (SQLException e) {
e.printStackTrace();
throw new ChoobInternalError("SQL Exception while setting core status on the plugin.");
} finally {
if (dbCon != null)
broker.freeConnection(dbCon);
}
}
|
diff --git a/org/xbill/DNS/Name.java b/org/xbill/DNS/Name.java
index d7bc3c7..51ff97e 100644
--- a/org/xbill/DNS/Name.java
+++ b/org/xbill/DNS/Name.java
@@ -1,825 +1,825 @@
// Copyright (c) 1999 Brian Wellington ([email protected])
package org.xbill.DNS;
import java.io.*;
import java.text.*;
import org.xbill.DNS.utils.*;
/**
* A representation of a domain name. It may either be absolute (fully
* qualified) or relative.
*
* @author Brian Wellington
*/
public class Name implements Comparable {
private static final int LABEL_NORMAL = 0;
private static final int LABEL_COMPRESSION = 0xC0;
private static final int LABEL_MASK = 0xC0;
/* The name data */
private byte [] name;
/*
* Effectively an 8 byte array, where the low order byte stores the number
* of labels and the 7 higher order bytes store per-label offsets.
*/
private long offsets;
/* Precomputed hashcode. */
private int hashcode;
private static final byte [] emptyLabel = new byte[] {(byte)0};
private static final byte [] wildLabel = new byte[] {(byte)1, (byte)'*'};
/** The root name */
public static final Name root;
/** The maximum length of a Name */
private static final int MAXNAME = 255;
/** The maximum length of a label a Name */
private static final int MAXLABEL = 63;
/** The maximum number of labels in a Name */
private static final int MAXLABELS = 128;
/** The maximum number of cached offsets */
private static final int MAXOFFSETS = 7;
/* Used for printing non-printable characters */
private static final DecimalFormat byteFormat = new DecimalFormat();
/* Used to efficiently convert bytes to lowercase */
private static final byte lowercase[] = new byte[256];
/* Used in wildcard names. */
private static final Name wild;
static {
byteFormat.setMinimumIntegerDigits(3);
for (int i = 0; i < lowercase.length; i++) {
if (i < 'A' || i > 'Z')
lowercase[i] = (byte)i;
else
lowercase[i] = (byte)(i - 'A' + 'a');
}
root = new Name();
wild = new Name();
root.appendSafe(emptyLabel, 0, 1);
wild.appendSafe(wildLabel, 0, 1);
}
private
Name() {
}
private final void
dump(String prefix) {
String s;
try {
s = toString();
} catch (Exception e) {
s = "<unprintable>";
}
System.out.println(prefix + ": " + s);
byte labels = labels();
for (int i = 0; i < labels; i++)
System.out.print(offset(i) + " ");
System.out.println("");
for (int i = 0; name != null && i < name.length; i++)
System.out.print((name[i] & 0xFF) + " ");
System.out.println("");
}
private final void
setoffset(int n, int offset) {
if (n >= MAXOFFSETS)
return;
int shift = 8 * (7 - n);
offsets &= (~(0xFFL << shift));
offsets |= ((long)offset << shift);
}
private final int
offset(int n) {
if (n < 0 || n >= getlabels())
throw new IllegalArgumentException("label out of range");
if (n < MAXOFFSETS) {
int shift = 8 * (7 - n);
return ((int)(offsets >>> shift) & 0xFF);
} else {
int pos = offset(MAXOFFSETS - 1);
for (int i = MAXOFFSETS - 1; i < n; i++)
pos += (name[pos] + 1);
return (pos);
}
}
private final void
setlabels(byte labels) {
offsets &= ~(0xFF);
offsets |= labels;
}
private final byte
getlabels() {
return (byte)(offsets & 0xFF);
}
private static final void
copy(Name src, Name dst) {
dst.name = src.name;
dst.offsets = src.offsets;
}
private final void
append(byte [] array, int start, int n) throws NameTooLongException {
int length = (name == null ? 0 : (name.length - offset(0)));
int alength = 0;
for (int i = 0, pos = start; i < n; i++) {
int len = array[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
len++;
pos += len;
alength += len;
}
int newlength = length + alength;
if (newlength > MAXNAME)
throw new NameTooLongException();
byte labels = getlabels();
int newlabels = labels + n;
if (newlabels > MAXLABELS)
throw new IllegalStateException("too many labels");
byte [] newname = new byte[newlength];
if (length != 0)
System.arraycopy(name, offset(0), newname, 0, length);
System.arraycopy(array, start, newname, length, alength);
name = newname;
for (int i = 0, pos = length; i < n; i++) {
setoffset(labels + i, pos);
pos += (newname[pos] + 1);
}
setlabels((byte) newlabels);
}
private static TextParseException
parseException(String str, String message) {
return new TextParseException("'" + str + "': " + message);
}
private final void
appendFromString(String fullName, byte [] array, int start, int n)
throws TextParseException
{
try {
append(array, start, n);
}
catch (NameTooLongException e) {
throw parseException(fullName, "Name too long");
}
}
private final void
appendSafe(byte [] array, int start, int n) {
try {
append(array, start, n);
}
catch (NameTooLongException e) {
}
}
/**
* Create a new name from a string and an origin
* @param s The string to be converted
* @param origin If the name is not absolute, the origin to be appended
* @deprecated As of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s, Name origin) {
Name n;
try {
n = Name.fromString(s, origin);
}
catch (TextParseException e) {
StringBuffer sb = new StringBuffer(s);
if (origin != null)
sb.append("." + origin);
sb.append(": "+ e.getMessage());
System.err.println(sb.toString());
return;
}
if (!n.isAbsolute() && !Options.check("pqdn") &&
n.getlabels() > 1 && n.getlabels() < MAXLABELS - 1)
{
/*
* This isn't exactly right, but it's close.
* Partially qualified names are evil.
*/
n.appendSafe(emptyLabel, 0, 1);
}
copy(n, this);
}
/**
* Create a new name from a string
* @param s The string to be converted
* @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>.
*/
public
Name(String s) {
this (s, null);
}
/**
* Create a new name from a string and an origin. This does not automatically
* make the name absolute; it will be absolute if it has a trailing dot or an
* absolute origin is appended.
* @param s The string to be converted
* @param origin If the name is not absolute, the origin to be appended.
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
if (s.equals(""))
throw parseException(s, "empty name");
else if (s.equals("@")) {
if (origin == null)
return name;
return origin;
} else if (s.equals("."))
return (root);
int labelstart = -1;
int pos = 1;
byte [] label = new byte[MAXLABEL + 1];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean absolute = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10;
intval += (b - '0');
if (intval > 255)
throw parseException(s, "bad escape");
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw parseException(s, "bad escape");
- if (pos >= MAXLABEL)
+ if (pos > MAXLABEL)
throw parseException(s, "label too long");
labelstart = pos;
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw parseException(s, "invalid empty label");
label[0] = (byte)(pos - 1);
name.appendFromString(s, label, 0, 1);
labelstart = -1;
pos = 1;
} else {
if (labelstart == -1)
labelstart = i;
- if (pos >= MAXLABEL)
+ if (pos > MAXLABEL)
throw parseException(s, "label too long");
label[pos++] = b;
}
}
if (digits > 0 && digits < 3)
throw parseException(s, "bad escape");
if (labelstart == -1) {
name.appendFromString(s, emptyLabel, 0, 1);
absolute = true;
} else {
label[0] = (byte)(pos - 1);
name.appendFromString(s, label, 0, 1);
}
if (origin != null && !absolute)
name.appendFromString(s, origin.name, 0, origin.getlabels());
return (name);
}
/**
* Create a new name from a string. This does not automatically make the name
* absolute; it will be absolute if it has a trailing dot.
* @param s The string to be converted
* @throws TextParseException The name is invalid.
*/
public static Name
fromString(String s) throws TextParseException {
return fromString(s, null);
}
/**
* Create a new name from a constant string. This should only be used when
the name is known to be good - that is, when it is constant.
* @param s The string to be converted
* @throws IllegalArgumentException The name is invalid.
*/
public static Name
fromConstantString(String s) {
try {
return fromString(s, null);
}
catch (TextParseException e) {
throw new IllegalArgumentException("Invalid name '" + s + "'");
}
}
/**
* Create a new name from DNS wire format
* @param in A stream containing the wire format of the Name.
*/
Name(DataByteInputStream in) throws IOException {
int len, pos, currentpos;
Name name2;
boolean done = false;
byte [] label = new byte[MAXLABEL + 1];
int savedpos = -1;
while (!done) {
len = in.readUnsignedByte();
switch (len & LABEL_MASK) {
case LABEL_NORMAL:
if (getlabels() >= MAXLABELS)
throw new WireParseException("too many labels");
if (len == 0) {
append(emptyLabel, 0, 1);
done = true;
} else {
label[0] = (byte)len;
in.readArray(label, 1, len);
append(label, 0, 1);
}
break;
case LABEL_COMPRESSION:
pos = in.readUnsignedByte();
pos += ((len & ~LABEL_MASK) << 8);
if (Options.check("verbosecompression"))
System.err.println("currently " + in.getPos() +
", pointer to " + pos);
currentpos = in.getPos();
if (pos >= currentpos)
throw new WireParseException("bad compression");
if (savedpos == -1)
savedpos = currentpos;
in.setPos(pos);
if (Options.check("verbosecompression"))
System.err.println("current name '" + this +
"', seeking to " + pos);
continue;
}
}
if (savedpos != -1)
in.setPos(savedpos);
}
/**
* Create a new name from DNS wire format
* @param b A byte array containing the wire format of the name.
*/
public
Name(byte [] b) throws IOException {
this(new DataByteInputStream(b));
}
/**
* Create a new name by removing labels from the beginning of an existing Name
* @param src An existing Name
* @param n The number of labels to remove from the beginning in the copy
*/
public
Name(Name src, int n) {
byte slabels = src.labels();
if (n > slabels)
throw new IllegalArgumentException("attempted to remove too " +
"many labels");
name = src.name;
setlabels((byte)(slabels - n));
for (int i = 0; i < MAXOFFSETS && i < slabels - n; i++)
setoffset(i, src.offset(i + n));
}
/**
* Creates a new name by concatenating two existing names.
* @param prefix The prefix name.
* @param suffix The suffix name.
* @return The concatenated name.
* @throws NameTooLongException The name is too long.
*/
public static Name
concatenate(Name prefix, Name suffix) throws NameTooLongException {
if (prefix.isAbsolute())
return (prefix);
Name newname = new Name();
copy(prefix, newname);
newname.append(suffix.name, suffix.offset(0), suffix.getlabels());
return newname;
}
/**
* If this name is a subdomain of origin, return a new name relative to
* origin with the same value. Otherwise, return the existing name.
* @param origin The origin to remove.
* @return The possibly relativized name.
*/
public Name
relativize(Name origin) {
if (origin == null || !subdomain(origin))
return this;
Name newname = new Name();
copy(this, newname);
int length = length() - origin.length();
int labels = newname.labels() - origin.labels();
newname.setlabels((byte)labels);
newname.name = new byte[length];
System.arraycopy(name, offset(0), newname.name, 0, length);
return newname;
}
/**
* Generates a new Name with the first n labels replaced by a wildcard
* @return The wildcard name
*/
public Name
wild(int n) {
if (n < 1)
throw new IllegalArgumentException("must replace 1 or more " +
"labels");
try {
Name newname = new Name();
copy(wild, newname);
newname.append(name, offset(n), getlabels() - n);
return newname;
}
catch (NameTooLongException e) {
throw new IllegalStateException
("Name.wild: concatenate failed");
}
}
/**
* Generates a new Name to be used when following a DNAME.
* @param dname The DNAME record to follow.
* @return The constructed name.
* @throws NameTooLongException The resulting name is too long.
*/
public Name
fromDNAME(DNAMERecord dname) throws NameTooLongException {
Name dnameowner = dname.getName();
Name dnametarget = dname.getTarget();
if (!subdomain(dnameowner))
return null;
int plabels = labels() - dnameowner.labels();
int plength = length() - dnameowner.length();
int pstart = offset(0);
int dlabels = dnametarget.labels();
int dlength = dnametarget.length();
if (plength + dlength > MAXNAME)
throw new NameTooLongException();
Name newname = new Name();
newname.setlabels((byte)(plabels + dlabels));
newname.name = new byte[plength + dlength];
System.arraycopy(name, pstart, newname.name, 0, plength);
System.arraycopy(dnametarget.name, 0, newname.name, plength, dlength);
for (int i = 0, pos = 0; i < MAXOFFSETS && i < plabels + dlabels; i++) {
newname.setoffset(i, pos);
pos += (newname.name[pos] + 1);
}
return newname;
}
/**
* Is this name a wildcard?
*/
public boolean
isWild() {
if (labels() == 0)
return false;
return (name[0] == (byte)1 && name[1] == (byte)'*');
}
/**
* Is this name fully qualified (that is, absolute)?
* @deprecated As of dnsjava 1.3.0, replaced by <code>isAbsolute</code>.
*/
public boolean
isQualified() {
return (isAbsolute());
}
/**
* Is this name absolute?
*/
public boolean
isAbsolute() {
if (labels() == 0)
return false;
return (name[name.length - 1] == 0);
}
/**
* The length of the name.
*/
public short
length() {
return (short)(name.length - offset(0));
}
/**
* The number of labels in the name.
*/
public byte
labels() {
return getlabels();
}
/**
* Is the current Name a subdomain of the specified name?
*/
public boolean
subdomain(Name domain) {
byte labels = labels();
byte dlabels = domain.labels();
if (dlabels > labels)
return false;
if (dlabels == labels)
return equals(domain);
return domain.equals(name, offset(labels - dlabels));
}
private String
byteString(byte [] array, int pos) {
StringBuffer sb = new StringBuffer();
int len = array[pos++];
for (int i = pos; i < pos + len; i++) {
short b = (short)(array[i] & 0xFF);
if (b <= 0x20 || b >= 0x7f) {
sb.append('\\');
sb.append(byteFormat.format(b));
}
else if (b == '"' || b == '(' || b == ')' || b == '.' ||
b == ';' || b == '\\' || b == '@' || b == '$')
{
sb.append('\\');
sb.append((char)b);
}
else
sb.append((char)b);
}
return sb.toString();
}
/**
* Convert Name to a String
*/
public String
toString() {
byte labels = labels();
if (labels == 0)
return "@";
else if (labels == 1 && name[offset(0)] == 0)
return ".";
StringBuffer sb = new StringBuffer();
for (int i = 0, pos = offset(0); i < labels; i++) {
int len = name[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
if (len == 0)
break;
sb.append(byteString(name, pos));
sb.append('.');
pos += (1 + len);
}
if (!isAbsolute())
sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}
/**
* Convert the nth label in a Name to a String
* @param n The label to be converted to a String. The first label is 0.
*/
public byte []
getLabel(int n) {
int pos = offset(n);
byte len = (byte)(name[pos] + 1);
byte [] label = new byte[len];
System.arraycopy(name, pos, label, 0, len);
return label;
}
/**
* Convert the nth label in a Name to a String
* @param n The label to be converted to a String. The first label is 0.
*/
public String
getLabelString(int n) {
int pos = offset(n);
return byteString(name, pos);
}
/**
* Convert Name to DNS wire format
* @param out The output stream containing the DNS message.
* @param c The compression context, or null of no compression is desired.
* @throws IllegalArgumentException The name is not absolute.
*/
void
toWire(DataByteOutputStream out, Compression c) {
if (!isAbsolute())
throw new IllegalArgumentException("toWire() called on " +
"non-absolute name");
byte labels = labels();
for (int i = 0; i < labels - 1; i++) {
Name tname;
if (i == 0)
tname = this;
else
tname = new Name(this, i);
int pos = -1;
if (c != null)
pos = c.get(tname);
if (pos >= 0) {
pos |= (LABEL_MASK << 8);
out.writeShort(pos);
return;
} else {
if (c != null)
c.add(out.getPos(), tname);
out.writeString(name, offset(i));
}
}
out.writeByte(0);
}
/**
* Convert Name to DNS wire format
* @throws IllegalArgumentException The name is not absolute.
*/
public byte []
toWire() {
DataByteOutputStream out = new DataByteOutputStream();
toWire(out, null);
return out.toByteArray();
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
* @param out The output stream to which the message is written.
*/
void
toWireCanonical(DataByteOutputStream out) {
byte [] b = toWireCanonical();
out.writeArray(b);
}
/**
* Convert Name to canonical DNS wire format (all lowercase)
*/
public byte []
toWireCanonical() {
byte labels = labels();
if (labels == 0)
return (new byte[0]);
byte [] b = new byte[name.length - offset(0)];
for (int i = 0, pos = offset(0); i < labels; i++) {
int len = name[pos];
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
b[pos] = name[pos++];
for (int j = 0; j < len; j++)
b[pos] = lowercase[(name[pos++] & 0xFF)];
}
return b;
}
/**
* Convert Name to DNS wire format
* @param out The output stream containing the DNS message.
* @param c The compression context, or null of no compression is desired.
* @throws IllegalArgumentException The name is not absolute.
*/
void
toWire(DataByteOutputStream out, Compression c, boolean canonical) {
if (canonical)
toWireCanonical(out);
else
toWire(out, c);
}
private final boolean
equals(byte [] b, int bpos) {
byte labels = labels();
for (int i = 0, pos = offset(0); i < labels; i++) {
if (name[pos] != b[bpos])
return false;
int len = name[pos++];
bpos++;
if (len > MAXLABEL)
throw new IllegalStateException("invalid label");
for (int j = 0; j < len; j++)
if (lowercase[(name[pos++] & 0xFF)] !=
lowercase[(b[bpos++] & 0xFF)])
return false;
}
return true;
}
/**
* Are these two Names equivalent?
*/
public boolean
equals(Object arg) {
if (arg == this)
return true;
if (arg == null || !(arg instanceof Name))
return false;
Name d = (Name) arg;
if (d.hashcode == 0)
d.hashCode();
if (hashcode == 0)
hashCode();
if (d.hashcode != hashcode)
return false;
if (d.labels() != labels())
return false;
return equals(d.name, d.offset(0));
}
/**
* Computes a hashcode based on the value
*/
public int
hashCode() {
if (hashcode != 0)
return (hashcode);
int code = 0;
for (int i = offset(0); i < name.length; i++)
code += ((code << 3) + lowercase[(name[i] & 0xFF)]);
hashcode = code;
return hashcode;
}
/**
* Compares this Name to another Object.
* @param o The Object to be compared.
* @return The value 0 if the argument is a name equivalent to this name;
* a value less than 0 if the argument is less than this name in the canonical
* ordering, and a value greater than 0 if the argument is greater than this
* name in the canonical ordering.
* @throws ClassCastException if the argument is not a Name.
*/
public int
compareTo(Object o) {
Name arg = (Name) o;
if (this == arg)
return (0);
byte labels = labels();
byte alabels = arg.labels();
int compares = labels > alabels ? alabels : labels;
for (int i = 1; i <= compares; i++) {
int start = offset(labels - i);
int astart = arg.offset(alabels - i);
int length = name[start];
int alength = arg.name[astart];
for (int j = 0; j < length && j < alength; j++) {
int n = lowercase[(name[j + start + 1]) & 0xFF] -
lowercase[(arg.name[j + astart + 1]) & 0xFF];
if (n != 0)
return (n);
}
if (length != alength)
return (length - alength);
}
return (labels - alabels);
}
}
| false | true | public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
if (s.equals(""))
throw parseException(s, "empty name");
else if (s.equals("@")) {
if (origin == null)
return name;
return origin;
} else if (s.equals("."))
return (root);
int labelstart = -1;
int pos = 1;
byte [] label = new byte[MAXLABEL + 1];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean absolute = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10;
intval += (b - '0');
if (intval > 255)
throw parseException(s, "bad escape");
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw parseException(s, "bad escape");
if (pos >= MAXLABEL)
throw parseException(s, "label too long");
labelstart = pos;
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw parseException(s, "invalid empty label");
label[0] = (byte)(pos - 1);
name.appendFromString(s, label, 0, 1);
labelstart = -1;
pos = 1;
} else {
if (labelstart == -1)
labelstart = i;
if (pos >= MAXLABEL)
throw parseException(s, "label too long");
label[pos++] = b;
}
}
if (digits > 0 && digits < 3)
throw parseException(s, "bad escape");
if (labelstart == -1) {
name.appendFromString(s, emptyLabel, 0, 1);
absolute = true;
} else {
label[0] = (byte)(pos - 1);
name.appendFromString(s, label, 0, 1);
}
if (origin != null && !absolute)
name.appendFromString(s, origin.name, 0, origin.getlabels());
return (name);
}
| public static Name
fromString(String s, Name origin) throws TextParseException {
Name name = new Name();
if (s.equals(""))
throw parseException(s, "empty name");
else if (s.equals("@")) {
if (origin == null)
return name;
return origin;
} else if (s.equals("."))
return (root);
int labelstart = -1;
int pos = 1;
byte [] label = new byte[MAXLABEL + 1];
boolean escaped = false;
int digits = 0;
int intval = 0;
boolean absolute = false;
for (int i = 0; i < s.length(); i++) {
byte b = (byte) s.charAt(i);
if (escaped) {
if (b >= '0' && b <= '9' && digits < 3) {
digits++;
intval *= 10;
intval += (b - '0');
if (intval > 255)
throw parseException(s, "bad escape");
if (digits < 3)
continue;
b = (byte) intval;
}
else if (digits > 0 && digits < 3)
throw parseException(s, "bad escape");
if (pos > MAXLABEL)
throw parseException(s, "label too long");
labelstart = pos;
label[pos++] = b;
escaped = false;
} else if (b == '\\') {
escaped = true;
digits = 0;
intval = 0;
} else if (b == '.') {
if (labelstart == -1)
throw parseException(s, "invalid empty label");
label[0] = (byte)(pos - 1);
name.appendFromString(s, label, 0, 1);
labelstart = -1;
pos = 1;
} else {
if (labelstart == -1)
labelstart = i;
if (pos > MAXLABEL)
throw parseException(s, "label too long");
label[pos++] = b;
}
}
if (digits > 0 && digits < 3)
throw parseException(s, "bad escape");
if (labelstart == -1) {
name.appendFromString(s, emptyLabel, 0, 1);
absolute = true;
} else {
label[0] = (byte)(pos - 1);
name.appendFromString(s, label, 0, 1);
}
if (origin != null && !absolute)
name.appendFromString(s, origin.name, 0, origin.getlabels());
return (name);
}
|
diff --git a/src/gtna/plot/ConfidenceData1.java b/src/gtna/plot/ConfidenceData1.java
index bf9876f8..d3b0e15e 100644
--- a/src/gtna/plot/ConfidenceData1.java
+++ b/src/gtna/plot/ConfidenceData1.java
@@ -1,85 +1,85 @@
/* ===========================================================
* GTNA : Graph-Theoretic Network Analyzer
* ===========================================================
*
* (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt)
* and Contributors
*
* Project Info: http://www.p2p.tu-darmstadt.de/research/gtna/
*
* GTNA 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.
*
* GTNA 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/>.
*
* ---------------------------------------
* ConfidenceData.java
* ---------------------------------------
* (C) Copyright 2009-2011, by Benjamin Schiller (P2P, TU Darmstadt)
* and Contributors
*
* Original Author: benni;
* Contributors: -;
*
* Changes since 2011-05-17
* ---------------------------------------
*
*/
package gtna.plot;
import gtna.plot.Gnuplot.Style;
/**
* @author benni
*
*/
public class ConfidenceData1 extends Data {
public ConfidenceData1(String data, Style style, String title) {
super(data, style, title);
}
@Override
public boolean isStyleValid() {
return this.style.equals(Style.candlesticks);
}
@Override
public String getEntry(int lt, int lw, double offsetX, double offsetY) {
StringBuffer buff = new StringBuffer();
// 2 avg
// 3 med
// 4 min
// 5 max
// 6 var
// 7 varLow
// 8 varUp
// 9 confLow
// 10 confUp
// X Min 1stQuartile Median 3rdQuartile Max
buff.append("'" + this.data + "' using ($1 + " + offsetX + "):($9 + "
- + offsetY + "):$(4 + " + offsetY + "):($5 + " + offsetY
+ + offsetY + "):($4 + " + offsetY + "):($5 + " + offsetY
+ "):($10 + " + offsetY + ") with " + this.style);
buff.append(" lt " + lt + " lw " + lw);
buff.append(title == null ? " notitle" : " title \"" + this.title
+ "\"");
buff.append(",\\\n");
buff.append("'' using ($1 + " + offsetX + "):($2 + " + offsetY
+ ") with " + Style.lines + " lt " + lt + " lw " + lw
+ " notitle");
return buff.toString();
}
public String[] getConfig() {
return new String[] { "set style fill solid", "set boxwidth 0.2" };
}
}
| true | true | public String getEntry(int lt, int lw, double offsetX, double offsetY) {
StringBuffer buff = new StringBuffer();
// 2 avg
// 3 med
// 4 min
// 5 max
// 6 var
// 7 varLow
// 8 varUp
// 9 confLow
// 10 confUp
// X Min 1stQuartile Median 3rdQuartile Max
buff.append("'" + this.data + "' using ($1 + " + offsetX + "):($9 + "
+ offsetY + "):$(4 + " + offsetY + "):($5 + " + offsetY
+ "):($10 + " + offsetY + ") with " + this.style);
buff.append(" lt " + lt + " lw " + lw);
buff.append(title == null ? " notitle" : " title \"" + this.title
+ "\"");
buff.append(",\\\n");
buff.append("'' using ($1 + " + offsetX + "):($2 + " + offsetY
+ ") with " + Style.lines + " lt " + lt + " lw " + lw
+ " notitle");
return buff.toString();
}
| public String getEntry(int lt, int lw, double offsetX, double offsetY) {
StringBuffer buff = new StringBuffer();
// 2 avg
// 3 med
// 4 min
// 5 max
// 6 var
// 7 varLow
// 8 varUp
// 9 confLow
// 10 confUp
// X Min 1stQuartile Median 3rdQuartile Max
buff.append("'" + this.data + "' using ($1 + " + offsetX + "):($9 + "
+ offsetY + "):($4 + " + offsetY + "):($5 + " + offsetY
+ "):($10 + " + offsetY + ") with " + this.style);
buff.append(" lt " + lt + " lw " + lw);
buff.append(title == null ? " notitle" : " title \"" + this.title
+ "\"");
buff.append(",\\\n");
buff.append("'' using ($1 + " + offsetX + "):($2 + " + offsetY
+ ") with " + Style.lines + " lt " + lt + " lw " + lw
+ " notitle");
return buff.toString();
}
|
diff --git a/services/java/com/android/server/NotificationManagerService.java b/services/java/com/android/server/NotificationManagerService.java
index fdc6c2e7..6f61629c 100755
--- a/services/java/com/android/server/NotificationManagerService.java
+++ b/services/java/com/android/server/NotificationManagerService.java
@@ -1,1626 +1,1628 @@
/*
* 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.server;
import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
import static org.xmlpull.v1.XmlPullParser.END_TAG;
import static org.xmlpull.v1.XmlPullParser.START_TAG;
import android.app.ActivityManagerNative;
import android.app.IActivityManager;
import android.app.INotificationManager;
import android.app.ITransientNotification;
import android.app.Notification;
import android.app.NotificationGroup;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Profile;
import android.app.ProfileGroup;
import android.app.ProfileManager;
import android.app.StatusBarManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.media.AudioManager;
import android.media.IAudioService;
import android.media.IRingtonePlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.UserId;
import android.os.Vibrator;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.EventLog;
import android.util.Log;
import android.util.Slog;
import android.util.Xml;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.widget.Toast;
import com.android.internal.os.AtomicFile;
import com.android.internal.statusbar.StatusBarNotification;
import com.android.internal.util.FastXmlSerializer;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Calendar;
import java.util.Map;
import libcore.io.IoUtils;
/** {@hide} */
public class NotificationManagerService extends INotificationManager.Stub
{
private static final String TAG = "NotificationService";
private static final boolean DBG = false;
private static final int MAX_PACKAGE_NOTIFICATIONS = 50;
// message codes
private static final int MESSAGE_TIMEOUT = 2;
private static final int LONG_DELAY = 3500; // 3.5 seconds
private static final int SHORT_DELAY = 2000; // 2 seconds
private static final long[] DEFAULT_VIBRATE_PATTERN = {0, 250, 250, 250};
private static final int DEFAULT_STREAM_TYPE = AudioManager.STREAM_NOTIFICATION;
private static final boolean SCORE_ONGOING_HIGHER = false;
private static final int JUNK_SCORE = -1000;
private static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10;
private static final int SCORE_DISPLAY_THRESHOLD = Notification.PRIORITY_MIN * NOTIFICATION_PRIORITY_MULTIPLIER;
private static final boolean ENABLE_BLOCKED_NOTIFICATIONS = true;
private static final boolean ENABLE_BLOCKED_TOASTS = true;
final Context mContext;
final IActivityManager mAm;
final IBinder mForegroundToken = new Binder();
private WorkerHandler mHandler;
private StatusBarManagerService mStatusBar;
private LightsService.Light mNotificationLight;
private LightsService.Light mAttentionLight;
private int mDefaultNotificationColor;
private int mDefaultNotificationLedOn;
private int mDefaultNotificationLedOff;
private boolean mSystemReady;
private int mDisabledNotifications;
private NotificationRecord mSoundNotification;
private NotificationRecord mVibrateNotification;
private IAudioService mAudioService;
private Vibrator mVibrator;
// for enabling and disabling notification pulse behaviour
private boolean mScreenOn = true;
private boolean mWasScreenOn = false;
private boolean mInCall = false;
private boolean mNotificationPulseEnabled;
private HashMap<String, NotificationLedValues> mNotificationPulseCustomLedValues;
private Map<String, String> mPackageNameMappings;
private final ArrayList<NotificationRecord> mNotificationList =
new ArrayList<NotificationRecord>();
private ArrayList<ToastRecord> mToastQueue;
private ArrayList<NotificationRecord> mLights = new ArrayList<NotificationRecord>();
private NotificationRecord mLedNotification;
private boolean mQuietHoursEnabled = false;
// Minutes from midnight when quiet hours begin.
private int mQuietHoursStart = 0;
// Minutes from midnight when quiet hours end.
private int mQuietHoursEnd = 0;
// Don't play sounds.
private boolean mQuietHoursMute = true;
// Don't vibrate.
private boolean mQuietHoursStill = true;
// Dim LED if hardware supports it.
private boolean mQuietHoursDim = true;
// Notification control database. For now just contains disabled packages.
private AtomicFile mPolicyFile;
private HashSet<String> mBlockedPackages = new HashSet<String>();
private static final int DB_VERSION = 1;
private static final String TAG_BODY = "notification-policy";
private static final String ATTR_VERSION = "version";
private static final String TAG_BLOCKED_PKGS = "blocked-packages";
private static final String TAG_PACKAGE = "package";
private static final String ATTR_NAME = "name";
private void loadBlockDb() {
synchronized(mBlockedPackages) {
if (mPolicyFile == null) {
File dir = new File("/data/system");
mPolicyFile = new AtomicFile(new File(dir, "notification_policy.xml"));
mBlockedPackages.clear();
FileInputStream infile = null;
try {
infile = mPolicyFile.openRead();
final XmlPullParser parser = Xml.newPullParser();
parser.setInput(infile, null);
int type;
String tag;
int version = DB_VERSION;
while ((type = parser.next()) != END_DOCUMENT) {
tag = parser.getName();
if (type == START_TAG) {
if (TAG_BODY.equals(tag)) {
version = Integer.parseInt(parser.getAttributeValue(null, ATTR_VERSION));
} else if (TAG_BLOCKED_PKGS.equals(tag)) {
while ((type = parser.next()) != END_DOCUMENT) {
tag = parser.getName();
if (TAG_PACKAGE.equals(tag)) {
mBlockedPackages.add(parser.getAttributeValue(null, ATTR_NAME));
} else if (TAG_BLOCKED_PKGS.equals(tag) && type == END_TAG) {
break;
}
}
}
}
}
} catch (FileNotFoundException e) {
// No data yet
} catch (IOException e) {
Log.wtf(TAG, "Unable to read blocked notifications database", e);
} catch (NumberFormatException e) {
Log.wtf(TAG, "Unable to parse blocked notifications database", e);
} catch (XmlPullParserException e) {
Log.wtf(TAG, "Unable to parse blocked notifications database", e);
} finally {
IoUtils.closeQuietly(infile);
}
}
}
}
private void writeBlockDb() {
synchronized(mBlockedPackages) {
FileOutputStream outfile = null;
try {
outfile = mPolicyFile.startWrite();
XmlSerializer out = new FastXmlSerializer();
out.setOutput(outfile, "utf-8");
out.startDocument(null, true);
out.startTag(null, TAG_BODY); {
out.attribute(null, ATTR_VERSION, String.valueOf(DB_VERSION));
out.startTag(null, TAG_BLOCKED_PKGS); {
// write all known network policies
for (String pkg : mBlockedPackages) {
out.startTag(null, TAG_PACKAGE); {
out.attribute(null, ATTR_NAME, pkg);
} out.endTag(null, TAG_PACKAGE);
}
} out.endTag(null, TAG_BLOCKED_PKGS);
} out.endTag(null, TAG_BODY);
out.endDocument();
mPolicyFile.finishWrite(outfile);
} catch (IOException e) {
if (outfile != null) {
mPolicyFile.failWrite(outfile);
}
}
}
}
public boolean areNotificationsEnabledForPackage(String pkg) {
checkCallerIsSystem();
return areNotificationsEnabledForPackageInt(pkg);
}
// Unchecked. Not exposed via Binder, but can be called in the course of enqueue*().
private boolean areNotificationsEnabledForPackageInt(String pkg) {
final boolean enabled = !mBlockedPackages.contains(pkg);
if (DBG) {
Slog.v(TAG, "notifications are " + (enabled?"en":"dis") + "abled for " + pkg);
}
return enabled;
}
public void setNotificationsEnabledForPackage(String pkg, boolean enabled) {
checkCallerIsSystem();
if (DBG) {
Slog.v(TAG, (enabled?"en":"dis") + "abling notifications for " + pkg);
}
if (enabled) {
mBlockedPackages.remove(pkg);
} else {
mBlockedPackages.add(pkg);
// Now, cancel any outstanding notifications that are part of a just-disabled app
if (ENABLE_BLOCKED_NOTIFICATIONS) {
synchronized (mNotificationList) {
final int N = mNotificationList.size();
for (int i=0; i<N; i++) {
final NotificationRecord r = mNotificationList.get(i);
if (r.pkg.equals(pkg)) {
cancelNotificationLocked(r, false);
}
}
}
}
// Don't bother canceling toasts, they'll go away soon enough.
}
writeBlockDb();
}
private static String idDebugString(Context baseContext, String packageName, int id) {
Context c = null;
if (packageName != null) {
try {
c = baseContext.createPackageContext(packageName, 0);
} catch (NameNotFoundException e) {
c = baseContext;
}
} else {
c = baseContext;
}
String pkg;
String type;
String name;
Resources r = c.getResources();
try {
return r.getResourceName(id);
} catch (Resources.NotFoundException e) {
return "<name unknown>";
}
}
private static final class NotificationRecord
{
final String pkg;
final String tag;
final int id;
final int uid;
final int initialPid;
final Notification notification;
final int score;
IBinder statusBarKey;
NotificationRecord(String pkg, String tag, int id, int uid, int initialPid, int score, Notification notification)
{
this.pkg = pkg;
this.tag = tag;
this.id = id;
this.uid = uid;
this.initialPid = initialPid;
this.score = score;
this.notification = notification;
}
void dump(PrintWriter pw, String prefix, Context baseContext) {
pw.println(prefix + this);
pw.println(prefix + " icon=0x" + Integer.toHexString(notification.icon)
+ " / " + idDebugString(baseContext, this.pkg, notification.icon));
pw.println(prefix + " pri=" + notification.priority);
pw.println(prefix + " score=" + this.score);
pw.println(prefix + " contentIntent=" + notification.contentIntent);
pw.println(prefix + " deleteIntent=" + notification.deleteIntent);
pw.println(prefix + " tickerText=" + notification.tickerText);
pw.println(prefix + " contentView=" + notification.contentView);
pw.println(prefix + " uid=" + uid);
pw.println(prefix + " defaults=0x" + Integer.toHexString(notification.defaults));
pw.println(prefix + " flags=0x" + Integer.toHexString(notification.flags));
pw.println(prefix + " sound=" + notification.sound);
pw.println(prefix + " vibrate=" + Arrays.toString(notification.vibrate));
pw.println(prefix + " ledARGB=0x" + Integer.toHexString(notification.ledARGB)
+ " ledOnMS=" + notification.ledOnMS
+ " ledOffMS=" + notification.ledOffMS);
}
@Override
public final String toString()
{
return "NotificationRecord{"
+ Integer.toHexString(System.identityHashCode(this))
+ " pkg=" + pkg
+ " id=" + Integer.toHexString(id)
+ " tag=" + tag
+ " score=" + score
+ "}";
}
}
private static final class ToastRecord
{
final int pid;
final String pkg;
final ITransientNotification callback;
int duration;
ToastRecord(int pid, String pkg, ITransientNotification callback, int duration)
{
this.pid = pid;
this.pkg = pkg;
this.callback = callback;
this.duration = duration;
}
void update(int duration) {
this.duration = duration;
}
void dump(PrintWriter pw, String prefix) {
pw.println(prefix + this);
}
@Override
public final String toString()
{
return "ToastRecord{"
+ Integer.toHexString(System.identityHashCode(this))
+ " pkg=" + pkg
+ " callback=" + callback
+ " duration=" + duration;
}
}
class NotificationLedValues {
public int color;
public int onMS;
public int offMS;
}
private StatusBarManagerService.NotificationCallbacks mNotificationCallbacks
= new StatusBarManagerService.NotificationCallbacks() {
public void onSetDisabled(int status) {
synchronized (mNotificationList) {
mDisabledNotifications = status;
if ((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
// cancel whatever's going on
long identity = Binder.clearCallingIdentity();
try {
final IRingtonePlayer player = mAudioService.getRingtonePlayer();
if (player != null) {
player.stopAsync();
}
} catch (RemoteException e) {
} finally {
Binder.restoreCallingIdentity(identity);
}
identity = Binder.clearCallingIdentity();
try {
mVibrator.cancel();
} finally {
Binder.restoreCallingIdentity(identity);
}
}
}
}
public void onClearAll() {
cancelAll();
}
public void onNotificationClick(String pkg, String tag, int id) {
cancelNotification(pkg, tag, id, Notification.FLAG_AUTO_CANCEL,
Notification.FLAG_FOREGROUND_SERVICE, false);
}
public void onNotificationClear(String pkg, String tag, int id) {
cancelNotification(pkg, tag, id, 0,
Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
true);
}
public void onPanelRevealed() {
synchronized (mNotificationList) {
// sound
mSoundNotification = null;
long identity = Binder.clearCallingIdentity();
try {
final IRingtonePlayer player = mAudioService.getRingtonePlayer();
if (player != null) {
player.stopAsync();
}
} catch (RemoteException e) {
} finally {
Binder.restoreCallingIdentity(identity);
}
// vibrate
mVibrateNotification = null;
identity = Binder.clearCallingIdentity();
try {
mVibrator.cancel();
} finally {
Binder.restoreCallingIdentity(identity);
}
// light
mLights.clear();
mLedNotification = null;
updateLightsLocked();
}
}
public void onNotificationError(String pkg, String tag, int id,
int uid, int initialPid, String message) {
Slog.d(TAG, "onNotification error pkg=" + pkg + " tag=" + tag + " id=" + id
+ "; will crashApplication(uid=" + uid + ", pid=" + initialPid + ")");
cancelNotification(pkg, tag, id, 0, 0, false);
long ident = Binder.clearCallingIdentity();
try {
ActivityManagerNative.getDefault().crashApplication(uid, initialPid, pkg,
"Bad notification posted from package " + pkg
+ ": " + message);
} catch (RemoteException e) {
}
Binder.restoreCallingIdentity(ident);
}
};
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
boolean queryRestart = false;
boolean packageChanged = false;
if (action.equals(Intent.ACTION_PACKAGE_REMOVED)
|| action.equals(Intent.ACTION_PACKAGE_RESTARTED)
|| (packageChanged=action.equals(Intent.ACTION_PACKAGE_CHANGED))
|| (queryRestart=action.equals(Intent.ACTION_QUERY_PACKAGE_RESTART))
|| action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
String pkgList[] = null;
if (action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
} else if (queryRestart) {
pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
} else {
Uri uri = intent.getData();
if (uri == null) {
return;
}
String pkgName = uri.getSchemeSpecificPart();
if (pkgName == null) {
return;
}
if (packageChanged) {
// We cancel notifications for packages which have just been disabled
final int enabled = mContext.getPackageManager()
.getApplicationEnabledSetting(pkgName);
if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
|| enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
return;
}
}
pkgList = new String[]{pkgName};
}
if (pkgList != null && (pkgList.length > 0)) {
for (String pkgName : pkgList) {
cancelAllNotificationsInt(pkgName, 0, 0, !queryRestart);
}
}
} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
// Keep track of screen on/off state, but do not turn off the notification light
// until user passes through the lock screen or views the notification.
mScreenOn = true;
} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
mScreenOn = false;
mWasScreenOn = true;
updateLightsLocked();
} else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
mInCall = (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_OFFHOOK));
updateNotificationPulse();
} else if (action.equals(Intent.ACTION_USER_PRESENT)) {
// turn off LED when user passes through lock screen
mNotificationLight.turnOff();
}
}
};
class LEDSettingsObserver extends ContentObserver {
LEDSettingsObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.NOTIFICATION_LIGHT_PULSE), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.NOTIFICATION_LIGHT_PULSE_DEFAULT_COLOR), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.NOTIFICATION_LIGHT_PULSE_DEFAULT_LED_ON), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.NOTIFICATION_LIGHT_PULSE_DEFAULT_LED_OFF), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.NOTIFICATION_LIGHT_PULSE_CUSTOM_ENABLE), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.NOTIFICATION_LIGHT_PULSE_CUSTOM_VALUES), false, this);
update();
}
@Override public void onChange(boolean selfChange) {
update();
updateNotificationPulse();
}
public void update() {
ContentResolver resolver = mContext.getContentResolver();
// LED enabled
mNotificationPulseEnabled = Settings.System.getInt(resolver,
Settings.System.NOTIFICATION_LIGHT_PULSE, 0) != 0;
// LED default color
mDefaultNotificationColor = Settings.System.getInt(resolver,
Settings.System.NOTIFICATION_LIGHT_PULSE_DEFAULT_COLOR, mDefaultNotificationColor);
// LED default on MS
mDefaultNotificationLedOn = Settings.System.getInt(resolver,
Settings.System.NOTIFICATION_LIGHT_PULSE_DEFAULT_LED_ON, mDefaultNotificationLedOn);
// LED default off MS
mDefaultNotificationLedOff = Settings.System.getInt(resolver,
Settings.System.NOTIFICATION_LIGHT_PULSE_DEFAULT_LED_OFF, mDefaultNotificationLedOff);
// LED custom notification colors
mNotificationPulseCustomLedValues.clear();
if (Settings.System.getInt(resolver,
Settings.System.NOTIFICATION_LIGHT_PULSE_CUSTOM_ENABLE, 0) != 0) {
parseNotificationPulseCustomValuesString(Settings.System.getString(resolver,
Settings.System.NOTIFICATION_LIGHT_PULSE_CUSTOM_VALUES));
}
}
}
class QuietHoursSettingsObserver extends ContentObserver {
QuietHoursSettingsObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.QUIET_HOURS_ENABLED), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.QUIET_HOURS_START), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.QUIET_HOURS_END), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.QUIET_HOURS_MUTE), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.QUIET_HOURS_STILL), false, this);
resolver.registerContentObserver(Settings.System.getUriFor(
Settings.System.QUIET_HOURS_DIM), false, this);
update();
}
@Override public void onChange(boolean selfChange) {
update();
updateNotificationPulse();
}
public void update() {
ContentResolver resolver = mContext.getContentResolver();
mQuietHoursEnabled = Settings.System.getInt(resolver,
Settings.System.QUIET_HOURS_ENABLED, 0) != 0;
mQuietHoursStart = Settings.System.getInt(resolver,
Settings.System.QUIET_HOURS_START, 0);
mQuietHoursEnd = Settings.System.getInt(resolver,
Settings.System.QUIET_HOURS_END, 0);
mQuietHoursMute = Settings.System.getInt(resolver,
Settings.System.QUIET_HOURS_MUTE, 0) != 0;
mQuietHoursStill = Settings.System.getInt(resolver,
Settings.System.QUIET_HOURS_STILL, 0) != 0;
mQuietHoursDim = Settings.System.getInt(resolver,
Settings.System.QUIET_HOURS_DIM, 0) != 0;
}
}
NotificationManagerService(Context context, StatusBarManagerService statusBar,
LightsService lights)
{
super();
mContext = context;
mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
mAm = ActivityManagerNative.getDefault();
mToastQueue = new ArrayList<ToastRecord>();
mHandler = new WorkerHandler();
loadBlockDb();
mStatusBar = statusBar;
statusBar.setNotificationCallbacks(mNotificationCallbacks);
mNotificationLight = lights.getLight(LightsService.LIGHT_ID_NOTIFICATIONS);
mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
Resources resources = mContext.getResources();
mDefaultNotificationColor = resources.getColor(
com.android.internal.R.color.config_defaultNotificationColor);
mDefaultNotificationLedOn = resources.getInteger(
com.android.internal.R.integer.config_defaultNotificationLedOn);
mDefaultNotificationLedOff = resources.getInteger(
com.android.internal.R.integer.config_defaultNotificationLedOff);
mNotificationPulseCustomLedValues = new HashMap<String, NotificationLedValues>();
mPackageNameMappings = new HashMap<String, String>();
for(String mapping : resources.getStringArray(
com.android.internal.R.array.notification_light_package_mapping)) {
String[] map = mapping.split("\\|");
mPackageNameMappings.put(map[0], map[1]);
}
// Don't start allowing notifications until the setup wizard has run once.
// After that, including subsequent boots, init with notifications turned on.
// This works on the first boot because the setup wizard will toggle this
// flag at least once and we'll go back to 0 after that.
if (0 == Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.DEVICE_PROVISIONED, 0)) {
mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
}
// register for various Intents
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction(Intent.ACTION_USER_PRESENT);
mContext.registerReceiver(mIntentReceiver, filter);
IntentFilter pkgFilter = new IntentFilter();
pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
pkgFilter.addDataScheme("package");
mContext.registerReceiver(mIntentReceiver, pkgFilter);
IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
mContext.registerReceiver(mIntentReceiver, sdFilter);
LEDSettingsObserver ledObserver = new LEDSettingsObserver(mHandler);
ledObserver.observe();
QuietHoursSettingsObserver qhObserver = new QuietHoursSettingsObserver(mHandler);
qhObserver.observe();
}
void systemReady() {
mAudioService = IAudioService.Stub.asInterface(
ServiceManager.getService(Context.AUDIO_SERVICE));
// no beeping until we're basically done booting
mSystemReady = true;
}
// Toasts
// ============================================================================
public void enqueueToast(String pkg, ITransientNotification callback, int duration)
{
if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);
if (pkg == null || callback == null) {
Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
return ;
}
final boolean isSystemToast = ("android".equals(pkg));
if (ENABLE_BLOCKED_TOASTS && !isSystemToast && !areNotificationsEnabledForPackageInt(pkg)) {
Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
return;
}
synchronized (mToastQueue) {
int callingPid = Binder.getCallingPid();
long callingId = Binder.clearCallingIdentity();
try {
ToastRecord record;
int index = indexOfToastLocked(pkg, callback);
// If it's already in the queue, we update it in place, we don't
// move it to the end of the queue.
if (index >= 0) {
record = mToastQueue.get(index);
record.update(duration);
} else {
// Limit the number of toasts that any given package except the android
// package can enqueue. Prevents DOS attacks and deals with leaks.
if (!isSystemToast) {
int count = 0;
final int N = mToastQueue.size();
for (int i=0; i<N; i++) {
final ToastRecord r = mToastQueue.get(i);
if (r.pkg.equals(pkg)) {
count++;
if (count >= MAX_PACKAGE_NOTIFICATIONS) {
Slog.e(TAG, "Package has already posted " + count
+ " toasts. Not showing more. Package=" + pkg);
return;
}
}
}
}
record = new ToastRecord(callingPid, pkg, callback, duration);
mToastQueue.add(record);
index = mToastQueue.size() - 1;
keepProcessAliveLocked(callingPid);
}
// If it's at index 0, it's the current toast. It doesn't matter if it's
// new or just been updated. Call back and tell it to show itself.
// If the callback fails, this will remove it from the list, so don't
// assume that it's valid after this.
if (index == 0) {
showNextToastLocked();
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
}
public void cancelToast(String pkg, ITransientNotification callback) {
Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
if (pkg == null || callback == null) {
Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
return ;
}
synchronized (mToastQueue) {
long callingId = Binder.clearCallingIdentity();
try {
int index = indexOfToastLocked(pkg, callback);
if (index >= 0) {
cancelToastLocked(index);
} else {
Slog.w(TAG, "Toast already cancelled. pkg=" + pkg + " callback=" + callback);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
}
private void showNextToastLocked() {
ToastRecord record = mToastQueue.get(0);
while (record != null) {
if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
try {
record.callback.show();
scheduleTimeoutLocked(record, false);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Object died trying to show notification " + record.callback
+ " in package " + record.pkg);
// remove it from the list and let the process die
int index = mToastQueue.indexOf(record);
if (index >= 0) {
mToastQueue.remove(index);
}
keepProcessAliveLocked(record.pid);
if (mToastQueue.size() > 0) {
record = mToastQueue.get(0);
} else {
record = null;
}
}
}
}
private void cancelToastLocked(int index) {
ToastRecord record = mToastQueue.get(index);
try {
record.callback.hide();
} catch (RemoteException e) {
Slog.w(TAG, "Object died trying to hide notification " + record.callback
+ " in package " + record.pkg);
// don't worry about this, we're about to remove it from
// the list anyway
}
mToastQueue.remove(index);
keepProcessAliveLocked(record.pid);
if (mToastQueue.size() > 0) {
// Show the next one. If the callback fails, this will remove
// it from the list, so don't assume that the list hasn't changed
// after this point.
showNextToastLocked();
}
}
private void scheduleTimeoutLocked(ToastRecord r, boolean immediate)
{
Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
mHandler.removeCallbacksAndMessages(r);
mHandler.sendMessageDelayed(m, delay);
}
private void handleTimeout(ToastRecord record)
{
if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
synchronized (mToastQueue) {
int index = indexOfToastLocked(record.pkg, record.callback);
if (index >= 0) {
cancelToastLocked(index);
}
}
}
// lock on mToastQueue
private int indexOfToastLocked(String pkg, ITransientNotification callback)
{
IBinder cbak = callback.asBinder();
ArrayList<ToastRecord> list = mToastQueue;
int len = list.size();
for (int i=0; i<len; i++) {
ToastRecord r = list.get(i);
if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
return i;
}
}
return -1;
}
// lock on mToastQueue
private void keepProcessAliveLocked(int pid)
{
int toastCount = 0; // toasts from this pid
ArrayList<ToastRecord> list = mToastQueue;
int N = list.size();
for (int i=0; i<N; i++) {
ToastRecord r = list.get(i);
if (r.pid == pid) {
toastCount++;
}
}
try {
mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
} catch (RemoteException e) {
// Shouldn't happen.
}
}
private final class WorkerHandler extends Handler
{
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MESSAGE_TIMEOUT:
handleTimeout((ToastRecord)msg.obj);
break;
}
}
}
// Notifications
// ============================================================================
@Deprecated
public void enqueueNotification(String pkg, int id, Notification notification, int[] idOut)
{
enqueueNotificationWithTag(pkg, null /* tag */, id, notification, idOut);
}
public void enqueueNotificationWithTag(String pkg, String tag, int id, Notification notification,
int[] idOut)
{
enqueueNotificationInternal(pkg, Binder.getCallingUid(), Binder.getCallingPid(),
tag, id, notification, idOut);
}
private final static int clamp(int x, int low, int high) {
return (x < low) ? low : ((x > high) ? high : x);
}
// Not exposed via Binder; for system use only (otherwise malicious apps could spoof the
// uid/pid of another application)
public void enqueueNotificationInternal(String pkg, int callingUid, int callingPid,
String tag, int id, Notification notification, int[] idOut)
{
if (DBG) {
Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id + " notification=" + notification);
}
checkCallerIsSystemOrSameApp(pkg);
final boolean isSystemNotification = ("android".equals(pkg));
// Limit the number of notifications that any given package except the android
// package can enqueue. Prevents DOS attacks and deals with leaks.
if (!isSystemNotification) {
synchronized (mNotificationList) {
int count = 0;
final int N = mNotificationList.size();
for (int i=0; i<N; i++) {
final NotificationRecord r = mNotificationList.get(i);
if (r.pkg.equals(pkg)) {
count++;
if (count >= MAX_PACKAGE_NOTIFICATIONS) {
Slog.e(TAG, "Package has already posted " + count
+ " notifications. Not showing more. package=" + pkg);
return;
}
}
}
}
}
// This conditional is a dirty hack to limit the logging done on
// behalf of the download manager without affecting other apps.
if (!pkg.equals("com.android.providers.downloads")
|| Log.isLoggable("DownloadManager", Log.VERBOSE)) {
EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag,
notification.toString());
}
if (pkg == null || notification == null) {
throw new IllegalArgumentException("null not allowed: pkg=" + pkg
+ " id=" + id + " notification=" + notification);
}
if (notification.icon != 0) {
if (notification.contentView == null) {
throw new IllegalArgumentException("contentView required: pkg=" + pkg
+ " id=" + id + " notification=" + notification);
}
}
// === Scoring ===
// 0. Sanitize inputs
notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN, Notification.PRIORITY_MAX);
// Migrate notification flags to scores
if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
if (notification.priority < Notification.PRIORITY_MAX) notification.priority = Notification.PRIORITY_MAX;
} else if (SCORE_ONGOING_HIGHER && 0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
if (notification.priority < Notification.PRIORITY_HIGH) notification.priority = Notification.PRIORITY_HIGH;
}
// 1. initial score: buckets of 10, around the app
int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
// 2. Consult external heuristics (TBD)
// 3. Apply local rules
// blocked apps
if (ENABLE_BLOCKED_NOTIFICATIONS && !isSystemNotification && !areNotificationsEnabledForPackageInt(pkg)) {
score = JUNK_SCORE;
Slog.e(TAG, "Suppressing notification from package " + pkg + " by user request.");
}
if (DBG) {
Slog.v(TAG, "Assigned score=" + score + " to " + notification);
}
if (score < SCORE_DISPLAY_THRESHOLD) {
// Notification will be blocked because the score is too low.
return;
}
synchronized (mNotificationList) {
final boolean inQuietHours = inQuietHours();
NotificationRecord r = new NotificationRecord(pkg, tag, id,
callingUid, callingPid,
score,
notification);
NotificationRecord old = null;
int index = indexOfNotificationLocked(pkg, tag, id);
if (index < 0) {
mNotificationList.add(r);
} else {
old = mNotificationList.remove(index);
mNotificationList.add(index, r);
// Make sure we don't lose the foreground service state.
if (old != null) {
notification.flags |=
old.notification.flags&Notification.FLAG_FOREGROUND_SERVICE;
}
}
// Ensure if this is a foreground service that the proper additional
// flags are set.
if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
notification.flags |= Notification.FLAG_ONGOING_EVENT
| Notification.FLAG_NO_CLEAR;
}
if (notification.icon != 0) {
StatusBarNotification n = new StatusBarNotification(pkg, id, tag,
r.uid, r.initialPid, score, notification);
if (old != null && old.statusBarKey != null) {
r.statusBarKey = old.statusBarKey;
long identity = Binder.clearCallingIdentity();
try {
mStatusBar.updateNotification(r.statusBarKey, n);
}
finally {
Binder.restoreCallingIdentity(identity);
}
} else {
long identity = Binder.clearCallingIdentity();
try {
r.statusBarKey = mStatusBar.addNotification(n);
if ((n.notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0) {
mAttentionLight.pulse();
}
}
finally {
Binder.restoreCallingIdentity(identity);
}
}
sendAccessibilityEvent(notification, pkg);
} else {
Slog.e(TAG, "Ignoring notification with icon==0: " + notification);
if (old != null && old.statusBarKey != null) {
long identity = Binder.clearCallingIdentity();
try {
mStatusBar.removeNotification(old.statusBarKey);
}
finally {
Binder.restoreCallingIdentity(identity);
}
}
}
try {
final ProfileManager profileManager =
(ProfileManager) mContext.getSystemService(Context.PROFILE_SERVICE);
ProfileGroup group = profileManager.getActiveProfileGroup(pkg);
- notification = group.processNotification(notification);
+ if (group != null) {
+ notification = group.processNotification(notification);
+ }
} catch(Throwable th) {
Log.e(TAG, "An error occurred profiling the notification.", th);
}
// If we're not supposed to beep, vibrate, etc. then don't.
if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
&& (!(old != null
&& (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
&& mSystemReady) {
final AudioManager audioManager = (AudioManager) mContext
.getSystemService(Context.AUDIO_SERVICE);
// sound
final boolean useDefaultSound =
(notification.defaults & Notification.DEFAULT_SOUND) != 0;
if (!(inQuietHours && mQuietHoursMute)
&& (useDefaultSound || notification.sound != null)) {
Uri uri;
if (useDefaultSound) {
uri = Settings.System.DEFAULT_NOTIFICATION_URI;
} else {
uri = notification.sound;
}
boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0;
int audioStreamType;
if (notification.audioStreamType >= 0) {
audioStreamType = notification.audioStreamType;
} else {
audioStreamType = DEFAULT_STREAM_TYPE;
}
mSoundNotification = r;
// do not play notifications if stream volume is 0
// (typically because ringer mode is silent).
if (audioManager.getStreamVolume(audioStreamType) != 0) {
final long identity = Binder.clearCallingIdentity();
try {
final IRingtonePlayer player = mAudioService.getRingtonePlayer();
if (player != null) {
player.playAsync(uri, looping, audioStreamType);
}
} catch (RemoteException e) {
} finally {
Binder.restoreCallingIdentity(identity);
}
}
}
// vibrate
final boolean useDefaultVibrate =
(notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
if (!(inQuietHours && mQuietHoursStill)
&& (useDefaultVibrate || notification.vibrate != null)
&& !(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT)) {
mVibrateNotification = r;
mVibrator.vibrate(useDefaultVibrate ? DEFAULT_VIBRATE_PATTERN
: notification.vibrate,
((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
}
}
// this option doesn't shut off the lights
// light
// the most recent thing gets the light
mLights.remove(old);
if (mLedNotification == old) {
mLedNotification = null;
}
//Slog.i(TAG, "notification.lights="
// + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS) != 0));
if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0) {
mLights.add(r);
updateLightsLocked();
} else {
if (old != null
&& ((old.notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0)) {
updateLightsLocked();
}
}
}
idOut[0] = id;
}
private boolean inQuietHours() {
if (mQuietHoursEnabled && (mQuietHoursStart != mQuietHoursEnd)) {
// Get the date in "quiet hours" format.
Calendar calendar = Calendar.getInstance();
int minutes = calendar.get(Calendar.HOUR_OF_DAY) * 60 + calendar.get(Calendar.MINUTE);
if (mQuietHoursEnd < mQuietHoursStart) {
// Starts at night, ends in the morning.
return (minutes > mQuietHoursStart) || (minutes < mQuietHoursEnd);
} else {
return (minutes > mQuietHoursStart) && (minutes < mQuietHoursEnd);
}
}
return false;
}
private void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
if (!manager.isEnabled()) {
return;
}
AccessibilityEvent event =
AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
event.setPackageName(packageName);
event.setClassName(Notification.class.getName());
event.setParcelableData(notification);
CharSequence tickerText = notification.tickerText;
if (!TextUtils.isEmpty(tickerText)) {
event.getText().add(tickerText);
}
manager.sendAccessibilityEvent(event);
}
private void cancelNotificationLocked(NotificationRecord r, boolean sendDelete) {
// tell the app
if (sendDelete) {
if (r.notification.deleteIntent != null) {
try {
r.notification.deleteIntent.send();
} catch (PendingIntent.CanceledException ex) {
// do nothing - there's no relevant way to recover, and
// no reason to let this propagate
Slog.w(TAG, "canceled PendingIntent for " + r.pkg, ex);
}
}
}
// status bar
if (r.notification.icon != 0) {
long identity = Binder.clearCallingIdentity();
try {
mStatusBar.removeNotification(r.statusBarKey);
}
finally {
Binder.restoreCallingIdentity(identity);
}
r.statusBarKey = null;
}
// sound
if (mSoundNotification == r) {
mSoundNotification = null;
final long identity = Binder.clearCallingIdentity();
try {
final IRingtonePlayer player = mAudioService.getRingtonePlayer();
if (player != null) {
player.stopAsync();
}
} catch (RemoteException e) {
} finally {
Binder.restoreCallingIdentity(identity);
}
}
// vibrate
if (mVibrateNotification == r) {
mVibrateNotification = null;
long identity = Binder.clearCallingIdentity();
try {
mVibrator.cancel();
}
finally {
Binder.restoreCallingIdentity(identity);
}
}
// light
mLights.remove(r);
if (mLedNotification == r) {
mLedNotification = null;
}
}
/**
* Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
* and none of the {@code mustNotHaveFlags}.
*/
private void cancelNotification(String pkg, String tag, int id, int mustHaveFlags,
int mustNotHaveFlags, boolean sendDelete) {
EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, tag,
mustHaveFlags, mustNotHaveFlags);
synchronized (mNotificationList) {
int index = indexOfNotificationLocked(pkg, tag, id);
if (index >= 0) {
NotificationRecord r = mNotificationList.get(index);
if ((r.notification.flags & mustHaveFlags) != mustHaveFlags) {
return;
}
if ((r.notification.flags & mustNotHaveFlags) != 0) {
return;
}
mNotificationList.remove(index);
cancelNotificationLocked(r, sendDelete);
updateLightsLocked();
}
}
}
/**
* Cancels all notifications from a given package that have all of the
* {@code mustHaveFlags}.
*/
boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
int mustNotHaveFlags, boolean doit) {
EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, mustHaveFlags,
mustNotHaveFlags);
synchronized (mNotificationList) {
final int N = mNotificationList.size();
boolean canceledSomething = false;
for (int i = N-1; i >= 0; --i) {
NotificationRecord r = mNotificationList.get(i);
if ((r.notification.flags & mustHaveFlags) != mustHaveFlags) {
continue;
}
if ((r.notification.flags & mustNotHaveFlags) != 0) {
continue;
}
if (!r.pkg.equals(pkg)) {
continue;
}
canceledSomething = true;
if (!doit) {
return true;
}
mNotificationList.remove(i);
cancelNotificationLocked(r, false);
}
if (canceledSomething) {
updateLightsLocked();
}
return canceledSomething;
}
}
@Deprecated
public void cancelNotification(String pkg, int id) {
cancelNotificationWithTag(pkg, null /* tag */, id);
}
public void cancelNotificationWithTag(String pkg, String tag, int id) {
checkCallerIsSystemOrSameApp(pkg);
// Don't allow client applications to cancel foreground service notis.
cancelNotification(pkg, tag, id, 0,
Binder.getCallingUid() == Process.SYSTEM_UID
? 0 : Notification.FLAG_FOREGROUND_SERVICE, false);
}
public void cancelAllNotifications(String pkg) {
checkCallerIsSystemOrSameApp(pkg);
// Calling from user space, don't allow the canceling of actively
// running foreground services.
cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true);
}
void checkCallerIsSystem() {
int uid = Binder.getCallingUid();
if (uid == Process.SYSTEM_UID || uid == 0) {
return;
}
throw new SecurityException("Disallowed call for uid " + uid);
}
void checkCallerIsSystemOrSameApp(String pkg) {
int uid = Binder.getCallingUid();
if (uid == Process.SYSTEM_UID || uid == 0) {
return;
}
try {
ApplicationInfo ai = mContext.getPackageManager().getApplicationInfo(
pkg, 0);
if (!UserId.isSameApp(ai.uid, uid)) {
throw new SecurityException("Calling uid " + uid + " gave package"
+ pkg + " which is owned by uid " + ai.uid);
}
} catch (PackageManager.NameNotFoundException e) {
throw new SecurityException("Unknown package " + pkg);
}
}
void cancelAll() {
synchronized (mNotificationList) {
final int N = mNotificationList.size();
for (int i=N-1; i>=0; i--) {
NotificationRecord r = mNotificationList.get(i);
if ((r.notification.flags & (Notification.FLAG_ONGOING_EVENT
| Notification.FLAG_NO_CLEAR)) == 0) {
mNotificationList.remove(i);
cancelNotificationLocked(r, true);
}
}
updateLightsLocked();
}
}
// lock on mNotificationList
private void updateLightsLocked()
{
// handle notification lights
if (mLedNotification == null) {
// get next notification, if any
int n = mLights.size();
if (n > 0) {
mLedNotification = mLights.get(n-1);
}
}
boolean wasScreenOn = mWasScreenOn;
mWasScreenOn = false;
if (mLedNotification == null) {
mNotificationLight.turnOff();
return;
}
// We can assume that if the user turned the screen off while there was
// still an active notification then they wanted to keep the notification
// for later. In this case we shouldn't flash the notification light.
// For special notifications that automatically turn the screen on (such
// as missed calls), we use this flag to force the notification light
// even if the screen was turned off.
boolean forceWithScreenOff = (mLedNotification.notification.flags &
Notification.FLAG_FORCE_LED_SCREEN_OFF) != 0;
// Don't flash while we are in a call, screen is on or we are in quiet hours with light dimmed
if (mInCall || mScreenOn || (inQuietHours() && mQuietHoursDim) || (wasScreenOn && !forceWithScreenOff)) {
mNotificationLight.turnOff();
} else {
int ledARGB;
int ledOnMS;
int ledOffMS;
NotificationLedValues ledValues = getLedValuesForNotification(mLedNotification);
if (ledValues != null) {
ledARGB = ledValues.color != 0 ? ledValues.color : mDefaultNotificationColor;
ledOnMS = ledValues.onMS >= 0 ? ledValues.onMS : mDefaultNotificationLedOn;
ledOffMS = ledValues.offMS >= 0 ? ledValues.offMS : mDefaultNotificationLedOn;
} else {
if ((mLedNotification.notification.defaults & Notification.DEFAULT_LIGHTS) != 0) {
ledARGB = mDefaultNotificationColor;
ledOnMS = mDefaultNotificationLedOn;
ledOffMS = mDefaultNotificationLedOff;
} else {
ledARGB = mLedNotification.notification.ledARGB;
ledOnMS = mLedNotification.notification.ledOnMS;
ledOffMS = mLedNotification.notification.ledOffMS;
}
}
if (mNotificationPulseEnabled) {
// pulse repeatedly
mNotificationLight.setFlashing(ledARGB, LightsService.LIGHT_FLASH_TIMED,
ledOnMS, ledOffMS);
}
}
}
private void parseNotificationPulseCustomValuesString(String customLedValuesString) {
if (TextUtils.isEmpty(customLedValuesString)) {
return;
}
for (String packageValuesString : customLedValuesString.split("\\|")) {
String[] packageValues = packageValuesString.split("=");
if (packageValues.length != 2) {
Log.e(TAG, "Error parsing custom led values for unknown package");
continue;
}
String packageName = packageValues[0];
String[] values = packageValues[1].split(";");
if (values.length != 3) {
Log.e(TAG, "Error parsing custom led values '" + packageValues[1] + "' for " + packageName);
continue;
}
NotificationLedValues ledValues = new NotificationLedValues();
try {
ledValues.color = Integer.parseInt(values[0]);
ledValues.onMS = Integer.parseInt(values[1]);
ledValues.offMS = Integer.parseInt(values[2]);
} catch (Exception e) {
Log.e(TAG, "Error parsing custom led values '" + packageValues[1] + "' for " + packageName);
continue;
}
mNotificationPulseCustomLedValues.put(packageName, ledValues);
}
}
private NotificationLedValues getLedValuesForNotification(NotificationRecord ledNotification) {
return mNotificationPulseCustomLedValues.get(mapPackage(ledNotification.pkg));
}
private String mapPackage(String pkg) {
if(!mPackageNameMappings.containsKey(pkg)) {
return pkg;
}
return mPackageNameMappings.get(pkg);
}
// lock on mNotificationList
private int indexOfNotificationLocked(String pkg, String tag, int id)
{
ArrayList<NotificationRecord> list = mNotificationList;
final int len = list.size();
for (int i=0; i<len; i++) {
NotificationRecord r = list.get(i);
if (tag == null) {
if (r.tag != null) {
continue;
}
} else {
if (!tag.equals(r.tag)) {
continue;
}
}
if (r.id == id && r.pkg.equals(pkg)) {
return i;
}
}
return -1;
}
private void updateNotificationPulse() {
synchronized (mNotificationList) {
updateLightsLocked();
}
}
// ======================================================================
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
!= PackageManager.PERMISSION_GRANTED) {
pw.println("Permission Denial: can't dump NotificationManager from from pid="
+ Binder.getCallingPid()
+ ", uid=" + Binder.getCallingUid());
return;
}
pw.println("Current Notification Manager state:");
int N;
synchronized (mToastQueue) {
N = mToastQueue.size();
if (N > 0) {
pw.println(" Toast Queue:");
for (int i=0; i<N; i++) {
mToastQueue.get(i).dump(pw, " ");
}
pw.println(" ");
}
}
synchronized (mNotificationList) {
N = mNotificationList.size();
if (N > 0) {
pw.println(" Notification List:");
for (int i=0; i<N; i++) {
mNotificationList.get(i).dump(pw, " ", mContext);
}
pw.println(" ");
}
N = mLights.size();
if (N > 0) {
pw.println(" Lights List:");
for (int i=0; i<N; i++) {
mLights.get(i).dump(pw, " ", mContext);
}
pw.println(" ");
}
pw.println(" mSoundNotification=" + mSoundNotification);
pw.println(" mVibrateNotification=" + mVibrateNotification);
pw.println(" mDisabledNotifications=0x" + Integer.toHexString(mDisabledNotifications));
pw.println(" mSystemReady=" + mSystemReady);
}
}
}
| true | true | public void enqueueNotificationInternal(String pkg, int callingUid, int callingPid,
String tag, int id, Notification notification, int[] idOut)
{
if (DBG) {
Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id + " notification=" + notification);
}
checkCallerIsSystemOrSameApp(pkg);
final boolean isSystemNotification = ("android".equals(pkg));
// Limit the number of notifications that any given package except the android
// package can enqueue. Prevents DOS attacks and deals with leaks.
if (!isSystemNotification) {
synchronized (mNotificationList) {
int count = 0;
final int N = mNotificationList.size();
for (int i=0; i<N; i++) {
final NotificationRecord r = mNotificationList.get(i);
if (r.pkg.equals(pkg)) {
count++;
if (count >= MAX_PACKAGE_NOTIFICATIONS) {
Slog.e(TAG, "Package has already posted " + count
+ " notifications. Not showing more. package=" + pkg);
return;
}
}
}
}
}
// This conditional is a dirty hack to limit the logging done on
// behalf of the download manager without affecting other apps.
if (!pkg.equals("com.android.providers.downloads")
|| Log.isLoggable("DownloadManager", Log.VERBOSE)) {
EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag,
notification.toString());
}
if (pkg == null || notification == null) {
throw new IllegalArgumentException("null not allowed: pkg=" + pkg
+ " id=" + id + " notification=" + notification);
}
if (notification.icon != 0) {
if (notification.contentView == null) {
throw new IllegalArgumentException("contentView required: pkg=" + pkg
+ " id=" + id + " notification=" + notification);
}
}
// === Scoring ===
// 0. Sanitize inputs
notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN, Notification.PRIORITY_MAX);
// Migrate notification flags to scores
if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
if (notification.priority < Notification.PRIORITY_MAX) notification.priority = Notification.PRIORITY_MAX;
} else if (SCORE_ONGOING_HIGHER && 0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
if (notification.priority < Notification.PRIORITY_HIGH) notification.priority = Notification.PRIORITY_HIGH;
}
// 1. initial score: buckets of 10, around the app
int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
// 2. Consult external heuristics (TBD)
// 3. Apply local rules
// blocked apps
if (ENABLE_BLOCKED_NOTIFICATIONS && !isSystemNotification && !areNotificationsEnabledForPackageInt(pkg)) {
score = JUNK_SCORE;
Slog.e(TAG, "Suppressing notification from package " + pkg + " by user request.");
}
if (DBG) {
Slog.v(TAG, "Assigned score=" + score + " to " + notification);
}
if (score < SCORE_DISPLAY_THRESHOLD) {
// Notification will be blocked because the score is too low.
return;
}
synchronized (mNotificationList) {
final boolean inQuietHours = inQuietHours();
NotificationRecord r = new NotificationRecord(pkg, tag, id,
callingUid, callingPid,
score,
notification);
NotificationRecord old = null;
int index = indexOfNotificationLocked(pkg, tag, id);
if (index < 0) {
mNotificationList.add(r);
} else {
old = mNotificationList.remove(index);
mNotificationList.add(index, r);
// Make sure we don't lose the foreground service state.
if (old != null) {
notification.flags |=
old.notification.flags&Notification.FLAG_FOREGROUND_SERVICE;
}
}
// Ensure if this is a foreground service that the proper additional
// flags are set.
if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
notification.flags |= Notification.FLAG_ONGOING_EVENT
| Notification.FLAG_NO_CLEAR;
}
if (notification.icon != 0) {
StatusBarNotification n = new StatusBarNotification(pkg, id, tag,
r.uid, r.initialPid, score, notification);
if (old != null && old.statusBarKey != null) {
r.statusBarKey = old.statusBarKey;
long identity = Binder.clearCallingIdentity();
try {
mStatusBar.updateNotification(r.statusBarKey, n);
}
finally {
Binder.restoreCallingIdentity(identity);
}
} else {
long identity = Binder.clearCallingIdentity();
try {
r.statusBarKey = mStatusBar.addNotification(n);
if ((n.notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0) {
mAttentionLight.pulse();
}
}
finally {
Binder.restoreCallingIdentity(identity);
}
}
sendAccessibilityEvent(notification, pkg);
} else {
Slog.e(TAG, "Ignoring notification with icon==0: " + notification);
if (old != null && old.statusBarKey != null) {
long identity = Binder.clearCallingIdentity();
try {
mStatusBar.removeNotification(old.statusBarKey);
}
finally {
Binder.restoreCallingIdentity(identity);
}
}
}
try {
final ProfileManager profileManager =
(ProfileManager) mContext.getSystemService(Context.PROFILE_SERVICE);
ProfileGroup group = profileManager.getActiveProfileGroup(pkg);
notification = group.processNotification(notification);
} catch(Throwable th) {
Log.e(TAG, "An error occurred profiling the notification.", th);
}
// If we're not supposed to beep, vibrate, etc. then don't.
if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
&& (!(old != null
&& (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
&& mSystemReady) {
final AudioManager audioManager = (AudioManager) mContext
.getSystemService(Context.AUDIO_SERVICE);
// sound
final boolean useDefaultSound =
(notification.defaults & Notification.DEFAULT_SOUND) != 0;
if (!(inQuietHours && mQuietHoursMute)
&& (useDefaultSound || notification.sound != null)) {
Uri uri;
if (useDefaultSound) {
uri = Settings.System.DEFAULT_NOTIFICATION_URI;
} else {
uri = notification.sound;
}
boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0;
int audioStreamType;
if (notification.audioStreamType >= 0) {
audioStreamType = notification.audioStreamType;
} else {
audioStreamType = DEFAULT_STREAM_TYPE;
}
mSoundNotification = r;
// do not play notifications if stream volume is 0
// (typically because ringer mode is silent).
if (audioManager.getStreamVolume(audioStreamType) != 0) {
final long identity = Binder.clearCallingIdentity();
try {
final IRingtonePlayer player = mAudioService.getRingtonePlayer();
if (player != null) {
player.playAsync(uri, looping, audioStreamType);
}
} catch (RemoteException e) {
} finally {
Binder.restoreCallingIdentity(identity);
}
}
}
// vibrate
final boolean useDefaultVibrate =
(notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
if (!(inQuietHours && mQuietHoursStill)
&& (useDefaultVibrate || notification.vibrate != null)
&& !(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT)) {
mVibrateNotification = r;
mVibrator.vibrate(useDefaultVibrate ? DEFAULT_VIBRATE_PATTERN
: notification.vibrate,
((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
}
}
// this option doesn't shut off the lights
// light
// the most recent thing gets the light
mLights.remove(old);
if (mLedNotification == old) {
mLedNotification = null;
}
//Slog.i(TAG, "notification.lights="
// + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS) != 0));
if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0) {
mLights.add(r);
updateLightsLocked();
} else {
if (old != null
&& ((old.notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0)) {
updateLightsLocked();
}
}
}
idOut[0] = id;
}
| public void enqueueNotificationInternal(String pkg, int callingUid, int callingPid,
String tag, int id, Notification notification, int[] idOut)
{
if (DBG) {
Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id + " notification=" + notification);
}
checkCallerIsSystemOrSameApp(pkg);
final boolean isSystemNotification = ("android".equals(pkg));
// Limit the number of notifications that any given package except the android
// package can enqueue. Prevents DOS attacks and deals with leaks.
if (!isSystemNotification) {
synchronized (mNotificationList) {
int count = 0;
final int N = mNotificationList.size();
for (int i=0; i<N; i++) {
final NotificationRecord r = mNotificationList.get(i);
if (r.pkg.equals(pkg)) {
count++;
if (count >= MAX_PACKAGE_NOTIFICATIONS) {
Slog.e(TAG, "Package has already posted " + count
+ " notifications. Not showing more. package=" + pkg);
return;
}
}
}
}
}
// This conditional is a dirty hack to limit the logging done on
// behalf of the download manager without affecting other apps.
if (!pkg.equals("com.android.providers.downloads")
|| Log.isLoggable("DownloadManager", Log.VERBOSE)) {
EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag,
notification.toString());
}
if (pkg == null || notification == null) {
throw new IllegalArgumentException("null not allowed: pkg=" + pkg
+ " id=" + id + " notification=" + notification);
}
if (notification.icon != 0) {
if (notification.contentView == null) {
throw new IllegalArgumentException("contentView required: pkg=" + pkg
+ " id=" + id + " notification=" + notification);
}
}
// === Scoring ===
// 0. Sanitize inputs
notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN, Notification.PRIORITY_MAX);
// Migrate notification flags to scores
if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
if (notification.priority < Notification.PRIORITY_MAX) notification.priority = Notification.PRIORITY_MAX;
} else if (SCORE_ONGOING_HIGHER && 0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
if (notification.priority < Notification.PRIORITY_HIGH) notification.priority = Notification.PRIORITY_HIGH;
}
// 1. initial score: buckets of 10, around the app
int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
// 2. Consult external heuristics (TBD)
// 3. Apply local rules
// blocked apps
if (ENABLE_BLOCKED_NOTIFICATIONS && !isSystemNotification && !areNotificationsEnabledForPackageInt(pkg)) {
score = JUNK_SCORE;
Slog.e(TAG, "Suppressing notification from package " + pkg + " by user request.");
}
if (DBG) {
Slog.v(TAG, "Assigned score=" + score + " to " + notification);
}
if (score < SCORE_DISPLAY_THRESHOLD) {
// Notification will be blocked because the score is too low.
return;
}
synchronized (mNotificationList) {
final boolean inQuietHours = inQuietHours();
NotificationRecord r = new NotificationRecord(pkg, tag, id,
callingUid, callingPid,
score,
notification);
NotificationRecord old = null;
int index = indexOfNotificationLocked(pkg, tag, id);
if (index < 0) {
mNotificationList.add(r);
} else {
old = mNotificationList.remove(index);
mNotificationList.add(index, r);
// Make sure we don't lose the foreground service state.
if (old != null) {
notification.flags |=
old.notification.flags&Notification.FLAG_FOREGROUND_SERVICE;
}
}
// Ensure if this is a foreground service that the proper additional
// flags are set.
if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
notification.flags |= Notification.FLAG_ONGOING_EVENT
| Notification.FLAG_NO_CLEAR;
}
if (notification.icon != 0) {
StatusBarNotification n = new StatusBarNotification(pkg, id, tag,
r.uid, r.initialPid, score, notification);
if (old != null && old.statusBarKey != null) {
r.statusBarKey = old.statusBarKey;
long identity = Binder.clearCallingIdentity();
try {
mStatusBar.updateNotification(r.statusBarKey, n);
}
finally {
Binder.restoreCallingIdentity(identity);
}
} else {
long identity = Binder.clearCallingIdentity();
try {
r.statusBarKey = mStatusBar.addNotification(n);
if ((n.notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0) {
mAttentionLight.pulse();
}
}
finally {
Binder.restoreCallingIdentity(identity);
}
}
sendAccessibilityEvent(notification, pkg);
} else {
Slog.e(TAG, "Ignoring notification with icon==0: " + notification);
if (old != null && old.statusBarKey != null) {
long identity = Binder.clearCallingIdentity();
try {
mStatusBar.removeNotification(old.statusBarKey);
}
finally {
Binder.restoreCallingIdentity(identity);
}
}
}
try {
final ProfileManager profileManager =
(ProfileManager) mContext.getSystemService(Context.PROFILE_SERVICE);
ProfileGroup group = profileManager.getActiveProfileGroup(pkg);
if (group != null) {
notification = group.processNotification(notification);
}
} catch(Throwable th) {
Log.e(TAG, "An error occurred profiling the notification.", th);
}
// If we're not supposed to beep, vibrate, etc. then don't.
if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
&& (!(old != null
&& (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
&& mSystemReady) {
final AudioManager audioManager = (AudioManager) mContext
.getSystemService(Context.AUDIO_SERVICE);
// sound
final boolean useDefaultSound =
(notification.defaults & Notification.DEFAULT_SOUND) != 0;
if (!(inQuietHours && mQuietHoursMute)
&& (useDefaultSound || notification.sound != null)) {
Uri uri;
if (useDefaultSound) {
uri = Settings.System.DEFAULT_NOTIFICATION_URI;
} else {
uri = notification.sound;
}
boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0;
int audioStreamType;
if (notification.audioStreamType >= 0) {
audioStreamType = notification.audioStreamType;
} else {
audioStreamType = DEFAULT_STREAM_TYPE;
}
mSoundNotification = r;
// do not play notifications if stream volume is 0
// (typically because ringer mode is silent).
if (audioManager.getStreamVolume(audioStreamType) != 0) {
final long identity = Binder.clearCallingIdentity();
try {
final IRingtonePlayer player = mAudioService.getRingtonePlayer();
if (player != null) {
player.playAsync(uri, looping, audioStreamType);
}
} catch (RemoteException e) {
} finally {
Binder.restoreCallingIdentity(identity);
}
}
}
// vibrate
final boolean useDefaultVibrate =
(notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
if (!(inQuietHours && mQuietHoursStill)
&& (useDefaultVibrate || notification.vibrate != null)
&& !(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT)) {
mVibrateNotification = r;
mVibrator.vibrate(useDefaultVibrate ? DEFAULT_VIBRATE_PATTERN
: notification.vibrate,
((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
}
}
// this option doesn't shut off the lights
// light
// the most recent thing gets the light
mLights.remove(old);
if (mLedNotification == old) {
mLedNotification = null;
}
//Slog.i(TAG, "notification.lights="
// + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS) != 0));
if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0) {
mLights.add(r);
updateLightsLocked();
} else {
if (old != null
&& ((old.notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0)) {
updateLightsLocked();
}
}
}
idOut[0] = id;
}
|
diff --git a/src/main/java/cc/twittertools/corpus/data/Status.java b/src/main/java/cc/twittertools/corpus/data/Status.java
index 0a47ece..ff7adc8 100644
--- a/src/main/java/cc/twittertools/corpus/data/Status.java
+++ b/src/main/java/cc/twittertools/corpus/data/Status.java
@@ -1,133 +1,133 @@
package cc.twittertools.corpus.data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* Object representing a status.
*/
public class Status {
private static final JsonParser JSON_PARSER = new JsonParser();
private static final String DATE_FORMAT = "EEE MMM d k:m:s ZZZZZ yyyy"; //"Fri Mar 29 11:03:41 +0000 2013";
private long id;
private String screenname;
private String createdAt;
private long epoch;
private String text;
private JsonObject jsonObject;
private String jsonString;
private String lang;
private int followersCount;
private int friendsCount;
private int statusesCount;
protected Status() {}
public long getId() {
return id;
}
public String getScreenname() {
return screenname;
}
public String getCreatedAt() {
return createdAt;
}
public long getEpoch() {
return epoch;
}
public String getText() {
return text;
}
public JsonObject getJsonObject() {
return jsonObject;
}
public String getJsonString() {
return jsonString;
}
public String getLang() {
return lang;
}
public int getFollowersCount() {
return followersCount;
}
public int getFriendsCount() {
return friendsCount;
}
public int getStatusesCount() {
return statusesCount;
}
public static Status fromJson(String json) {
JsonObject obj = null;
try {
obj = (JsonObject) JSON_PARSER.parse(json);
} catch (Exception e) {
e.printStackTrace();
// Catch any malformed JSON.
return null;
}
if (obj.get("text") == null) {
return null;
}
Status status = new Status();
status.text = obj.get("text").getAsString();
status.id = obj.get("id").getAsLong();
status.screenname = obj.get("user").getAsJsonObject().get("screen_name").getAsString();
status.createdAt = obj.get("created_at").getAsString();
try {
status.epoch = (new SimpleDateFormat(DATE_FORMAT)).parse(status.createdAt).getTime() / 1000;
} catch (ParseException e) {
status.epoch = -1L;
}
- status.lang = obj.get("lang").getAsString();
+ status.lang = obj.get("user").getAsJsonObject().get("lang").getAsString();
status.followersCount = obj.get("user").getAsJsonObject().get("followers_count").getAsInt();
status.friendsCount = obj.get("user").getAsJsonObject().get("friends_count").getAsInt();
status.statusesCount = obj.get("user").getAsJsonObject().get("statuses_count").getAsInt();
status.jsonObject = obj;
status.jsonString = json;
return status;
}
public static Status fromTSV(String tsv) {
String[] columns = tsv.split("\t");
if (columns.length < 4) {
System.err.println("error parsing: " + tsv);
return null;
}
Status status = new Status();
status.id = Long.parseLong(columns[0]);
status.screenname = columns[1];
status.createdAt = columns[2];
StringBuilder b = new StringBuilder();
for (int i = 3; i < columns.length; i++) {
b.append(columns[i] + " ");
}
status.text = b.toString().trim();
return status;
}
}
| true | true | public static Status fromJson(String json) {
JsonObject obj = null;
try {
obj = (JsonObject) JSON_PARSER.parse(json);
} catch (Exception e) {
e.printStackTrace();
// Catch any malformed JSON.
return null;
}
if (obj.get("text") == null) {
return null;
}
Status status = new Status();
status.text = obj.get("text").getAsString();
status.id = obj.get("id").getAsLong();
status.screenname = obj.get("user").getAsJsonObject().get("screen_name").getAsString();
status.createdAt = obj.get("created_at").getAsString();
try {
status.epoch = (new SimpleDateFormat(DATE_FORMAT)).parse(status.createdAt).getTime() / 1000;
} catch (ParseException e) {
status.epoch = -1L;
}
status.lang = obj.get("lang").getAsString();
status.followersCount = obj.get("user").getAsJsonObject().get("followers_count").getAsInt();
status.friendsCount = obj.get("user").getAsJsonObject().get("friends_count").getAsInt();
status.statusesCount = obj.get("user").getAsJsonObject().get("statuses_count").getAsInt();
status.jsonObject = obj;
status.jsonString = json;
return status;
}
| public static Status fromJson(String json) {
JsonObject obj = null;
try {
obj = (JsonObject) JSON_PARSER.parse(json);
} catch (Exception e) {
e.printStackTrace();
// Catch any malformed JSON.
return null;
}
if (obj.get("text") == null) {
return null;
}
Status status = new Status();
status.text = obj.get("text").getAsString();
status.id = obj.get("id").getAsLong();
status.screenname = obj.get("user").getAsJsonObject().get("screen_name").getAsString();
status.createdAt = obj.get("created_at").getAsString();
try {
status.epoch = (new SimpleDateFormat(DATE_FORMAT)).parse(status.createdAt).getTime() / 1000;
} catch (ParseException e) {
status.epoch = -1L;
}
status.lang = obj.get("user").getAsJsonObject().get("lang").getAsString();
status.followersCount = obj.get("user").getAsJsonObject().get("followers_count").getAsInt();
status.friendsCount = obj.get("user").getAsJsonObject().get("friends_count").getAsInt();
status.statusesCount = obj.get("user").getAsJsonObject().get("statuses_count").getAsInt();
status.jsonObject = obj;
status.jsonString = json;
return status;
}
|
diff --git a/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java b/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java
index 65fed17f2..5bd803500 100644
--- a/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java
+++ b/src/jogl/classes/com/jogamp/opengl/util/FPSAnimator.java
@@ -1,361 +1,367 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Copyright (c) 2010 JogAmp Community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
* MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
* ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
* DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
* DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
* SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use
* in the design, construction, operation or maintenance of any nuclear
* facility.
*
* Sun gratefully acknowledges that this software was originally authored
* and developed by Kenneth Bradley Russell and Christopher John Kline.
*/
package com.jogamp.opengl.util;
import java.util.Timer;
import java.util.TimerTask;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLException;
/**
* An Animator subclass which attempts to achieve a target
* frames-per-second rate to avoid using all CPU time. The target FPS
* is only an estimate and is not guaranteed.
* <p>
* The Animator execution thread does not run as a daemon thread,
* so it is able to keep an application from terminating.<br>
* Call {@link #stop() } to terminate the animation and it's execution thread.
* </p>
*/
public class FPSAnimator extends AnimatorBase {
private Timer timer = null;
private MainTask task = null;
private int fps;
private final boolean scheduleAtFixedRate;
private boolean isAnimating; // MainTask feedback
private volatile boolean shouldRun; // MainTask trigger
private volatile boolean shouldStop; // MainTask trigger
@Override
protected String getBaseName(String prefix) {
return "FPS" + prefix + "Animator" ;
}
/** Creates an FPSAnimator with a given target frames-per-second
value. Equivalent to <code>FPSAnimator(null, fps)</code>. */
public FPSAnimator(int fps) {
this(null, fps);
}
/** Creates an FPSAnimator with a given target frames-per-second
value and a flag indicating whether to use fixed-rate
scheduling. Equivalent to <code>FPSAnimator(null, fps,
scheduleAtFixedRate)</code>. */
public FPSAnimator(int fps, boolean scheduleAtFixedRate) {
this(null, fps, scheduleAtFixedRate);
}
/** Creates an FPSAnimator with a given target frames-per-second
value and an initial drawable to animate. Equivalent to
<code>FPSAnimator(null, fps, false)</code>. */
public FPSAnimator(GLAutoDrawable drawable, int fps) {
this(drawable, fps, false);
}
/** Creates an FPSAnimator with a given target frames-per-second
value, an initial drawable to animate, and a flag indicating
whether to use fixed-rate scheduling. */
public FPSAnimator(GLAutoDrawable drawable, int fps, boolean scheduleAtFixedRate) {
super();
this.fps = fps;
if (drawable != null) {
add(drawable);
}
this.scheduleAtFixedRate = scheduleAtFixedRate;
}
/**
* @param fps
* @throws GLException if the animator has already been started
*/
public final synchronized void setFPS(int fps) throws GLException {
if ( isStarted() ) {
throw new GLException("Animator already started.");
}
this.fps = fps;
}
public final int getFPS() { return fps; }
class MainTask extends TimerTask {
private boolean justStarted;
private boolean alreadyStopped;
private boolean alreadyPaused;
public MainTask() {
}
public void start(Timer timer) {
fpsCounter.resetFPSCounter();
shouldRun = true;
shouldStop = false;
justStarted = true;
alreadyStopped = false;
alreadyPaused = false;
final long period = 0 < fps ? (long) (1000.0f / fps) : 1; // 0 -> 1: IllegalArgumentException: Non-positive period
if (scheduleAtFixedRate) {
timer.scheduleAtFixedRate(this, 0, period);
} else {
timer.schedule(this, 0, period);
}
}
public boolean isActive() { return !alreadyStopped && !alreadyPaused; }
@Override
public final String toString() {
return "Task[thread "+animThread+", stopped "+alreadyStopped+", paused "+alreadyPaused+" shouldRun "+shouldRun+", shouldStop "+shouldStop+" -- started "+isStarted()+", animating "+isAnimatingImpl()+", paused "+isPaused()+", drawable "+drawables.size()+", drawablesEmpty "+drawablesEmpty+"]";
}
@Override
public void run() {
if( justStarted ) {
justStarted = false;
synchronized (FPSAnimator.this) {
animThread = Thread.currentThread();
if(DEBUG) {
System.err.println("FPSAnimator start/resume:" + Thread.currentThread() + ": " + toString());
}
isAnimating = true;
if( drawablesEmpty ) {
shouldRun = false; // isAnimating:=false @ pause below
} else {
shouldRun = true;
setDrawablesExclCtxState(exclusiveContext);
FPSAnimator.this.notifyAll();
}
- System.err.println("FPSAnimator P1:" + Thread.currentThread() + ": " + toString());
+ if(DEBUG) {
+ System.err.println("FPSAnimator P1:" + Thread.currentThread() + ": " + toString());
+ }
}
}
if( shouldRun ) {
display();
} else if( shouldStop ) { // STOP
- System.err.println("FPSAnimator P4: "+alreadyStopped+", "+ Thread.currentThread() + ": " + toString());
+ if(DEBUG) {
+ System.err.println("FPSAnimator P4: "+alreadyStopped+", "+ Thread.currentThread() + ": " + toString());
+ }
this.cancel();
if( !alreadyStopped ) {
alreadyStopped = true;
if( exclusiveContext && !drawablesEmpty ) {
setDrawablesExclCtxState(false);
display(); // propagate exclusive change!
}
synchronized (FPSAnimator.this) {
if(DEBUG) {
System.err.println("FPSAnimator stop " + Thread.currentThread() + ": " + toString());
}
animThread = null;
isAnimating = false;
FPSAnimator.this.notifyAll();
}
}
} else {
- System.err.println("FPSAnimator P5: "+alreadyPaused+", "+ Thread.currentThread() + ": " + toString());
+ if(DEBUG) {
+ System.err.println("FPSAnimator P5: "+alreadyPaused+", "+ Thread.currentThread() + ": " + toString());
+ }
this.cancel();
if( !alreadyPaused ) { // PAUSE
alreadyPaused = true;
if( exclusiveContext && !drawablesEmpty ) {
setDrawablesExclCtxState(false);
display(); // propagate exclusive change!
}
synchronized (FPSAnimator.this) {
if(DEBUG) {
System.err.println("FPSAnimator pause " + Thread.currentThread() + ": " + toString());
}
isAnimating = false;
FPSAnimator.this.notifyAll();
}
}
}
}
}
private final boolean isAnimatingImpl() {
return animThread != null && isAnimating ;
}
@Override
public final synchronized boolean isAnimating() {
return animThread != null && isAnimating ;
}
@Override
public final synchronized boolean isPaused() {
return animThread != null && ( !shouldRun && !shouldStop ) ;
}
static int timerNo = 0;
@Override
public final synchronized boolean start() {
if ( null != timer || null != task || isStarted() ) {
return false;
}
timer = new Timer( getThreadName()+"-"+baseName+"-Timer"+(timerNo++) );
task = new MainTask();
if(DEBUG) {
System.err.println("FPSAnimator.start() START: "+task+", "+ Thread.currentThread() + ": " + toString());
}
task.start(timer);
final boolean res = finishLifecycleAction( drawablesEmpty ? waitForStartedEmptyCondition : waitForStartedAddedCondition,
POLLP_WAIT_FOR_FINISH_LIFECYCLE_ACTION);
if(DEBUG) {
System.err.println("FPSAnimator.start() END: "+task+", "+ Thread.currentThread() + ": " + toString());
}
if( drawablesEmpty ) {
task.cancel();
task = null;
}
return res;
}
private final Condition waitForStartedAddedCondition = new Condition() {
@Override
public boolean eval() {
return !isStarted() || !isAnimating ;
} };
private final Condition waitForStartedEmptyCondition = new Condition() {
@Override
public boolean eval() {
return !isStarted() || isAnimating ;
} };
/** Stops this FPSAnimator. Due to the implementation of the
FPSAnimator it is not guaranteed that the FPSAnimator will be
completely stopped by the time this method returns. */
@Override
public final synchronized boolean stop() {
if ( null == timer || !isStarted() ) {
return false;
}
if(DEBUG) {
System.err.println("FPSAnimator.stop() START: "+task+", "+ Thread.currentThread() + ": " + toString());
}
final boolean res;
if( null == task ) {
// start/resume case w/ drawablesEmpty
res = true;
} else {
shouldRun = false;
shouldStop = true;
res = finishLifecycleAction(waitForStoppedCondition, POLLP_WAIT_FOR_FINISH_LIFECYCLE_ACTION);
}
if(DEBUG) {
System.err.println("FPSAnimator.stop() END: "+task+", "+ Thread.currentThread() + ": " + toString());
}
if(null != task) {
task.cancel();
task = null;
}
if(null != timer) {
timer.cancel();
timer = null;
}
animThread = null;
return res;
}
private final Condition waitForStoppedCondition = new Condition() {
@Override
public boolean eval() {
return isStarted();
} };
@Override
public final synchronized boolean pause() {
if ( !isStarted() || ( null != task && isPaused() ) ) {
return false;
}
if(DEBUG) {
System.err.println("FPSAnimator.pause() START: "+task+", "+ Thread.currentThread() + ": " + toString());
}
final boolean res;
if( null == task ) {
// start/resume case w/ drawablesEmpty
res = true;
} else {
shouldRun = false;
res = finishLifecycleAction(waitForPausedCondition, POLLP_WAIT_FOR_FINISH_LIFECYCLE_ACTION);
}
if(DEBUG) {
System.err.println("FPSAnimator.pause() END: "+task+", "+ Thread.currentThread() + ": " + toString());
}
if(null != task) {
task.cancel();
task = null;
}
return res;
}
private final Condition waitForPausedCondition = new Condition() {
@Override
public boolean eval() {
// end waiting if stopped as well
return isAnimating && isStarted();
} };
@Override
public final synchronized boolean resume() {
if ( null != task || !isStarted() || !isPaused() ) {
return false;
}
if(DEBUG) {
System.err.println("FPSAnimator.resume() START: "+ Thread.currentThread() + ": " + toString());
}
final boolean res;
if( drawablesEmpty ) {
res = true;
} else {
task = new MainTask();
task.start(timer);
res = finishLifecycleAction(waitForResumeCondition, POLLP_WAIT_FOR_FINISH_LIFECYCLE_ACTION);
}
if(DEBUG) {
System.err.println("FPSAnimator.resume() END: "+task+", "+ Thread.currentThread() + ": " + toString());
}
return res;
}
private final Condition waitForResumeCondition = new Condition() {
@Override
public boolean eval() {
// end waiting if stopped as well
return !drawablesEmpty && !isAnimating && isStarted();
} };
}
| false | true | public void run() {
if( justStarted ) {
justStarted = false;
synchronized (FPSAnimator.this) {
animThread = Thread.currentThread();
if(DEBUG) {
System.err.println("FPSAnimator start/resume:" + Thread.currentThread() + ": " + toString());
}
isAnimating = true;
if( drawablesEmpty ) {
shouldRun = false; // isAnimating:=false @ pause below
} else {
shouldRun = true;
setDrawablesExclCtxState(exclusiveContext);
FPSAnimator.this.notifyAll();
}
System.err.println("FPSAnimator P1:" + Thread.currentThread() + ": " + toString());
}
}
if( shouldRun ) {
display();
} else if( shouldStop ) { // STOP
System.err.println("FPSAnimator P4: "+alreadyStopped+", "+ Thread.currentThread() + ": " + toString());
this.cancel();
if( !alreadyStopped ) {
alreadyStopped = true;
if( exclusiveContext && !drawablesEmpty ) {
setDrawablesExclCtxState(false);
display(); // propagate exclusive change!
}
synchronized (FPSAnimator.this) {
if(DEBUG) {
System.err.println("FPSAnimator stop " + Thread.currentThread() + ": " + toString());
}
animThread = null;
isAnimating = false;
FPSAnimator.this.notifyAll();
}
}
} else {
System.err.println("FPSAnimator P5: "+alreadyPaused+", "+ Thread.currentThread() + ": " + toString());
this.cancel();
if( !alreadyPaused ) { // PAUSE
alreadyPaused = true;
if( exclusiveContext && !drawablesEmpty ) {
setDrawablesExclCtxState(false);
display(); // propagate exclusive change!
}
synchronized (FPSAnimator.this) {
if(DEBUG) {
System.err.println("FPSAnimator pause " + Thread.currentThread() + ": " + toString());
}
isAnimating = false;
FPSAnimator.this.notifyAll();
}
}
}
}
| public void run() {
if( justStarted ) {
justStarted = false;
synchronized (FPSAnimator.this) {
animThread = Thread.currentThread();
if(DEBUG) {
System.err.println("FPSAnimator start/resume:" + Thread.currentThread() + ": " + toString());
}
isAnimating = true;
if( drawablesEmpty ) {
shouldRun = false; // isAnimating:=false @ pause below
} else {
shouldRun = true;
setDrawablesExclCtxState(exclusiveContext);
FPSAnimator.this.notifyAll();
}
if(DEBUG) {
System.err.println("FPSAnimator P1:" + Thread.currentThread() + ": " + toString());
}
}
}
if( shouldRun ) {
display();
} else if( shouldStop ) { // STOP
if(DEBUG) {
System.err.println("FPSAnimator P4: "+alreadyStopped+", "+ Thread.currentThread() + ": " + toString());
}
this.cancel();
if( !alreadyStopped ) {
alreadyStopped = true;
if( exclusiveContext && !drawablesEmpty ) {
setDrawablesExclCtxState(false);
display(); // propagate exclusive change!
}
synchronized (FPSAnimator.this) {
if(DEBUG) {
System.err.println("FPSAnimator stop " + Thread.currentThread() + ": " + toString());
}
animThread = null;
isAnimating = false;
FPSAnimator.this.notifyAll();
}
}
} else {
if(DEBUG) {
System.err.println("FPSAnimator P5: "+alreadyPaused+", "+ Thread.currentThread() + ": " + toString());
}
this.cancel();
if( !alreadyPaused ) { // PAUSE
alreadyPaused = true;
if( exclusiveContext && !drawablesEmpty ) {
setDrawablesExclCtxState(false);
display(); // propagate exclusive change!
}
synchronized (FPSAnimator.this) {
if(DEBUG) {
System.err.println("FPSAnimator pause " + Thread.currentThread() + ": " + toString());
}
isAnimating = false;
FPSAnimator.this.notifyAll();
}
}
}
}
|
diff --git a/src/jvm/clojure/lang/BigNum.java b/src/jvm/clojure/lang/BigNum.java
index 4b36160f..d159335c 100644
--- a/src/jvm/clojure/lang/BigNum.java
+++ b/src/jvm/clojure/lang/BigNum.java
@@ -1,250 +1,250 @@
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
* which can be found in the file CPL.TXT at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
/* rich Mar 28, 2006 10:08:33 AM */
package clojure.lang;
import java.math.BigInteger;
public class BigNum extends IntegerNum{
public BigInteger val;
public boolean equals(Object arg0){
return arg0 != null
&& arg0 instanceof BigNum
- && ((BigNum) arg0).val == val;
+ && ((BigNum) arg0).val.equals(val);
}
public int hashCode(){
return val.hashCode();
}
public String toString(){
return val.toString();
}
public BigNum(long val){
this.val = BigInteger.valueOf(val);
}
public BigNum(BigInteger val){
this.val = val;
}
public double doubleValue(){
return val.doubleValue();
}
public float floatValue(){
return val.floatValue();
}
public int intValue(){
return val.intValue();
}
public long longValue(){
return val.longValue();
}
public boolean equiv(Num rhs){
return rhs.equivTo(val);
}
public boolean equivTo(BigInteger x){
return x.equals(val);
}
public boolean equivTo(int x){
//must be outside of range of int or would be one itself
return false;
}
public boolean equivTo(RatioNum x){
//wouldn't still be a RatioNum if it was an integer
return false;
}
public boolean lt(Num rhs){
return rhs.gt(val);
}
public boolean gt(BigInteger x){
return x.compareTo(val) < 0;
}
public boolean gt(int x){
return BigInteger.valueOf(x).compareTo(val) < 0;
}
public boolean gt(RatioNum x){
return x.numerator.lt(x.denominator.multiply(val));
}
public Num add(Num rhs){
return rhs.addTo(val);
}
public Num addTo(BigInteger x){
return Num.from(x.add(val));
}
public Num addTo(int x){
return Num.from(val.add(BigInteger.valueOf(x)));
}
public Num addTo(RatioNum x){
return x.addTo(val);
}
public Num subtractFrom(Num x){
return x.addTo(val.negate());
}
public Num multiplyBy(Num rhs){
return rhs.multiply(val);
}
public Num multiply(BigInteger x){
return Num.from(x.multiply(val));
}
public Num multiply(int x){
return Num.from(val.multiply(BigInteger.valueOf(x)));
}
public Num multiply(RatioNum x){
return x.multiply(val);
}
public Num divideBy(Num rhs){
return rhs.divide(val);
}
public Num divide(BigInteger n){
return Num.divide(n, val);
}
public Num divide(int n){
return Num.divide(BigInteger.valueOf(n), val);
}
public Num divide(RatioNum x){
return Num.divide(x.numerator, x.denominator.multiply(val));
}
public Object[] truncateDivide(Num num){
return num.truncateBy(val);
}
public Object[] truncateBy(int div){
return Num.truncateBigints(val, BigInteger.valueOf(div));
}
public Object[] truncateBy(BigInteger div){
return Num.truncateBigints(val, div);
}
public Object[] truncateBy(RatioNum div){
Num q = (Num) Num.truncate(div.denominator.multiply(val), div.numerator)[0];
return RT.setValues(q, q.multiplyBy(div).subtractFrom(this));
}
public Num negate(){
return Num.from(val.negate());
}
public boolean minusp(){
return val.signum() < 0;
}
public boolean plusp(){
return val.signum() > 0;
}
public boolean zerop(){
return val.compareTo(BigInteger.ZERO) == 0;
}
public Num oneMinus(){
return Num.from(val.subtract(BigInteger.ONE));
}
public Num onePlus(){
return Num.from(val.add(BigInteger.ONE));
}
public Num bitXorBy(IntegerNum rhs){
return rhs.bitXor(val);
}
public Num bitXor(BigInteger y){
return Num.from(val.xor(y));
}
public Num bitXor(int y){
return Num.from(val.xor(BigInteger.valueOf(y)));
}
public Num bitAndBy(IntegerNum rhs){
return rhs.bitAnd(val);
}
public Num bitAnd(int y){
return Num.from(val.and(BigInteger.valueOf(y)));
}
public Num bitAnd(BigInteger y){
return Num.from(val.and(y));
}
public Num bitOrBy(IntegerNum rhs){
return rhs.bitOr(val);
}
public Num bitOr(int y){
return Num.from(val.or(BigInteger.valueOf(y)));
}
public Num bitOr(BigInteger y){
return Num.from(val.or(y));
}
public Num bitNot(){
return Num.from(val.not());
}
public Num shiftLeftBy(IntegerNum rhs){
return rhs.shiftLeft(val);
}
public Num shiftLeft(BigInteger y){
return Num.from(val.shiftLeft(y.intValue()));
}
public Num shiftLeft(int y){
return Num.from(val.shiftLeft(y));
}
public Num shiftRightBy(IntegerNum rhs){
return rhs.shiftRight(val);
}
public Num shiftRight(BigInteger y){
return Num.from(val.shiftRight(y.intValue()));
}
public Num shiftRight(int y){
return Num.from(val.shiftRight(y));
}
}
| true | true | public boolean equals(Object arg0){
return arg0 != null
&& arg0 instanceof BigNum
&& ((BigNum) arg0).val == val;
}
| public boolean equals(Object arg0){
return arg0 != null
&& arg0 instanceof BigNum
&& ((BigNum) arg0).val.equals(val);
}
|
diff --git a/src/test/groovy/security/SecurityTestSupport.java b/src/test/groovy/security/SecurityTestSupport.java
index ade59005a..03ee4c933 100644
--- a/src/test/groovy/security/SecurityTestSupport.java
+++ b/src/test/groovy/security/SecurityTestSupport.java
@@ -1,285 +1,285 @@
package groovy.security;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;
import groovy.lang.Script;
import groovy.util.GroovyTestCase;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.Permission;
import java.security.Policy;
import java.security.PrivilegedAction;
import java.util.Enumeration;
import junit.framework.TestCase;
import junit.framework.TestFailure;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import junit.textui.ResultPrinter;
import org.codehaus.groovy.runtime.InvokerHelper;
/**
* @author Steve Goetze
*/
public class SecurityTestSupport extends GroovyTestCase {
private static int counter = 0;
private static boolean securityDisabled;
private static boolean securityAvailable;
private static boolean securityChecked = false;
static {
if (System.getProperty("groovy.security.disabled") != null) {
securityAvailable = false;
securityDisabled = true;
} else {
securityDisabled = false;
String groovyLibDir = System.getProperty("groovy.lib");
if (groovyLibDir == null) {
//Try to find maven repository in the default user.home location
groovyLibDir = System.getProperty("user.home") + "/" + ".maven/repository";
}
if (groovyLibDir == null) {
//Try at user.dir/lib
groovyLibDir = "lib";
}
if (new File(groovyLibDir).exists()) {
securityAvailable = true;
System.setProperty("groovy.lib", groovyLibDir);
System.setProperty("java.security.policy", "=security/groovy.policy");
} else {
securityAvailable = false;
}
}
}
public static boolean isSecurityAvailable() {
return securityAvailable;
}
public static boolean isSecurityDisabled() {
return securityDisabled;
}
public static void resetSecurityPolicy(String policyFileURL) {
System.setProperty("java.security.policy", policyFileURL);
Policy.getPolicy().refresh();
}
protected class SecurityTestResultPrinter extends ResultPrinter {
public SecurityTestResultPrinter(PrintStream stream) {
super(stream);
}
public void print(TestResult result) {
getWriter().println("Security testing on a groovy test failed:");
printErrors(result);
printFailures(result);
printFooter(result);
}
}
protected GroovyClassLoader loader = (GroovyClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new GroovyClassLoader(SecurityTestSupport.class.getClassLoader());
}
});
private SecurityManager securityManager;
private ClassLoader currentClassLoader;
public SecurityTestSupport() {
}
/*
* Check SecuritySupport to see if security is properly configured. If not, fail the first
* test that runs. All remaining tests will run, but not do any security checking.
*/
private boolean checkSecurity() {
if (!securityChecked) {
securityChecked = true;
if (!isSecurityAvailable()) {
fail("Security is not available - skipping security tests. Ensure that groovy.lib is set and points to the groovy dependency jars.");
}
}
return isSecurityAvailable();
}
//Prepare for each security test. First, check to see if groovy.lib can be determined via
//a call to checkSecurity(). If not, fail() the first test. Establish a security manager
//and make the GroovyClassLoader the initiating class loader (ala GroovyShell) to compile AND
//invoke the test scripts. This handles cases where multiple .groovy scripts are involved in a
//test case: a.groovy depends on b.groovy; a.groovy is parsed (and in the process the gcl
//loads b.groovy via findClass). Note that b.groovy is only available in the groovy class loader.
//See
protected void setUp() {
if (checkSecurity()) {
securityManager = System.getSecurityManager();
if (securityManager == null) {
System.setSecurityManager(new SecurityManager());
}
}
currentClassLoader = Thread.currentThread().getContextClassLoader();
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
Thread.currentThread().setContextClassLoader(loader);
return null;
}
});
}
protected void tearDown() {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
System.setSecurityManager(securityManager);
Thread.currentThread().setContextClassLoader(currentClassLoader);
return null;
}
});
}
protected synchronized String generateClassName() {
return "testSecurity" + (++counter);
}
/*
* Execute the groovy script contained in file. If missingPermission
* is non-null, then this invocation expects an AccessControlException with missingPermission
* as the reason. If missingPermission is null, the script is expected to execute successfully.
*/
protected Class parseClass(File file) {
GroovyCodeSource gcs = null;
try {
gcs = new GroovyCodeSource(file);
} catch (FileNotFoundException fnfe) {
fail(fnfe.toString());
}
return parseClass(gcs);
}
/*
* Parse the Groovy code contained in the GroovyCodeSource as a privileged operation (i.e. do not
* require the code source to have specific compile time permissions) and return the resulting class.
*/
protected Class parseClass(final GroovyCodeSource gcs) {
Class clazz = null;
try {
clazz = loader.parseClass(gcs);
} catch (Exception e) {
fail(e.toString());
}
return clazz;
}
/*
* Parse the script contained in the GroovyCodeSource as a privileged operation (i.e. do not
* require the code source to have specific compile time permissions). If the class produced is a
* TestCase, run the test in a suite and evaluate against the missingPermission.
* Otherwise, run the class as a groovy script and evaluate against the missingPermission.
*/
private void parseAndExecute(final GroovyCodeSource gcs, Permission missingPermission) {
Class clazz = null;
try {
clazz = loader.parseClass(gcs);
} catch (Exception e) {
fail(e.toString());
}
if (TestCase.class.isAssignableFrom(clazz)) {
executeTest(clazz, missingPermission);
} else {
executeScript(clazz, missingPermission);
}
}
protected void executeTest(Class test, Permission missingPermission) {
TestSuite suite = new TestSuite();
suite.addTestSuite(test);
TestResult result = new TestResult();
suite.run(result);
if (result.wasSuccessful()) {
if (missingPermission == null) {
return;
} else {
fail("Security test expected an AccessControlException on " + missingPermission + ", but did not receive one");
}
} else {
if (missingPermission == null) {
new SecurityTestResultPrinter(System.out).print(result);
fail("Security test was expected to run successfully, but failed (results on System.out)");
} else {
//There may be more than 1 failure: iterate to ensure that they all match the missingPermission.
boolean otherFailure = false;
for (Enumeration e = result.errors(); e.hasMoreElements(); ) {
TestFailure failure = (TestFailure) e.nextElement();
if (failure.thrownException() instanceof AccessControlException) {
AccessControlException ace = (AccessControlException) failure.thrownException();
if (missingPermission.implies(ace.getPermission())) {
continue;
}
}
otherFailure = true;
}
if (otherFailure) {
new SecurityTestResultPrinter(System.out).print(result);
- fail("Security test expected an AccessControlException on " + missingPermission + ", but failed for other reasons (results on System.out)");
+ fail("Security test expected an AccessControlException on " + missingPermission + ", but failed for other reasons (results on System.out)");
}
}
}
}
protected void executeScript(Class scriptClass, Permission missingPermission) {
try {
Script script = InvokerHelper.createScript(scriptClass, new Binding());
script.run();
//InvokerHelper.runScript(scriptClass, null);
} catch (AccessControlException ace) {
if (missingPermission != null && missingPermission.implies(ace.getPermission())) {
return;
} else {
fail(ace.toString());
}
}
if (missingPermission != null) {
fail("Should catch an AccessControlException");
}
}
/*
* Execute the groovy script contained in file. If missingPermission
* is non-null, then this invocation expects an AccessControlException with missingPermission
* as the reason. If missingPermission is null, the script is expected to execute successfully.
*/
protected void assertExecute(File file, Permission missingPermission) {
if (!isSecurityAvailable()) {
return;
}
GroovyCodeSource gcs = null;
try {
gcs = new GroovyCodeSource(file);
} catch (FileNotFoundException fnfe) {
fail(fnfe.toString());
}
parseAndExecute(gcs, missingPermission);
}
/*
* Execute the script represented by scriptStr using the supplied codebase. If missingPermission
* is non-null, then this invocation expects an AccessControlException with missingPermission
* as the reason. If missingPermission is null, the script is expected to execute successfully.
*/
protected void assertExecute(String scriptStr, String codeBase, Permission missingPermission) {
if (!isSecurityAvailable()) {
return;
}
if (codeBase == null) {
codeBase = "/groovy/security/test";
}
parseAndExecute(new GroovyCodeSource(scriptStr, generateClassName(), codeBase), missingPermission);
}
}
| true | true | protected void executeTest(Class test, Permission missingPermission) {
TestSuite suite = new TestSuite();
suite.addTestSuite(test);
TestResult result = new TestResult();
suite.run(result);
if (result.wasSuccessful()) {
if (missingPermission == null) {
return;
} else {
fail("Security test expected an AccessControlException on " + missingPermission + ", but did not receive one");
}
} else {
if (missingPermission == null) {
new SecurityTestResultPrinter(System.out).print(result);
fail("Security test was expected to run successfully, but failed (results on System.out)");
} else {
//There may be more than 1 failure: iterate to ensure that they all match the missingPermission.
boolean otherFailure = false;
for (Enumeration e = result.errors(); e.hasMoreElements(); ) {
TestFailure failure = (TestFailure) e.nextElement();
if (failure.thrownException() instanceof AccessControlException) {
AccessControlException ace = (AccessControlException) failure.thrownException();
if (missingPermission.implies(ace.getPermission())) {
continue;
}
}
otherFailure = true;
}
if (otherFailure) {
new SecurityTestResultPrinter(System.out).print(result);
fail("Security test expected an AccessControlException on " + missingPermission + ", but failed for other reasons (results on System.out)");
}
}
}
}
| protected void executeTest(Class test, Permission missingPermission) {
TestSuite suite = new TestSuite();
suite.addTestSuite(test);
TestResult result = new TestResult();
suite.run(result);
if (result.wasSuccessful()) {
if (missingPermission == null) {
return;
} else {
fail("Security test expected an AccessControlException on " + missingPermission + ", but did not receive one");
}
} else {
if (missingPermission == null) {
new SecurityTestResultPrinter(System.out).print(result);
fail("Security test was expected to run successfully, but failed (results on System.out)");
} else {
//There may be more than 1 failure: iterate to ensure that they all match the missingPermission.
boolean otherFailure = false;
for (Enumeration e = result.errors(); e.hasMoreElements(); ) {
TestFailure failure = (TestFailure) e.nextElement();
if (failure.thrownException() instanceof AccessControlException) {
AccessControlException ace = (AccessControlException) failure.thrownException();
if (missingPermission.implies(ace.getPermission())) {
continue;
}
}
otherFailure = true;
}
if (otherFailure) {
new SecurityTestResultPrinter(System.out).print(result);
fail("Security test expected an AccessControlException on " + missingPermission + ", but failed for other reasons (results on System.out)");
}
}
}
}
|
diff --git a/src/uk/ac/ebi/sampletab/STLoader.java b/src/uk/ac/ebi/sampletab/STLoader.java
index 49e2764..caeeac6 100644
--- a/src/uk/ac/ebi/sampletab/STLoader.java
+++ b/src/uk/ac/ebi/sampletab/STLoader.java
@@ -1,422 +1,422 @@
package uk.ac.ebi.sampletab;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import uk.ac.ebi.age.admin.shared.Constants;
import uk.ac.ebi.age.admin.shared.SubmissionConstants;
import uk.ac.ebi.age.ext.submission.Status;
import com.pri.util.StringUtils;
import com.pri.util.stream.StreamPump;
public class STLoader
{
static final String usage = "java -jar STLoader.jar [options...] <input file/dir> [ ... <input file/dir> ]";
/**
* @param args
*/
public static void main(String[] args)
{
Options options = new Options();
CmdLineParser parser = new CmdLineParser(options);
try
{
parser.parseArgument(args);
}
catch(CmdLineException e)
{
System.err.println(e.getMessage());
System.err.println(usage);
parser.printUsage(System.err);
return;
}
if( options.getDirs() == null || options.getDirs().size() == 0 )
{
System.err.println(usage);
parser.printUsage(System.err);
return;
}
List<File> infiles = new ArrayList<File>();
for( String outf : options.getDirs() )
{
File in = new File( outf );
if( in.isDirectory() )
infiles.addAll( Arrays.asList( in.listFiles() ) );
else if( in.isFile() )
infiles.add( in );
else
{
System.err.println("Input file/directory '"+in.getAbsolutePath()+"' doesn't exist");
return;
}
}
if( infiles.size() == 0 )
{
System.err.println("No files to process");
return;
}
boolean remote = options.isLoad() || options.isStore();
if( options.getOutDir() == null )
{
System.err.println("Output directory is not specified");
return;
}
File outfile = new File( options.getOutDir() );
if( outfile.isFile() )
{
System.err.println("Output path should point to a directory");
return;
}
if( ! outfile.exists() && ! outfile.mkdirs() )
{
System.err.println("Can't create output directory");
return;
}
String sessionKey = null;
DefaultHttpClient httpclient = null;
PrintWriter log = null;
try
{
log = new PrintWriter( new File(outfile,".log") );
}
catch(FileNotFoundException e1)
{
System.err.println("Can't create log file: "+new File(outfile,".log").getAbsolutePath());
return;
}
if( remote )
{
if( options.getDatabaseURL() == null )
{
System.err.println("Database URI is required for remote operations");
return;
}
else if( ! options.getDatabaseURL().endsWith("/") )
options.setDatabaseURI( options.getDatabaseURL()+"/" );
if( options.getUser() == null )
{
System.err.println("User name is required for remote operations");
return;
}
boolean ok = false;
try
{
httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(options.getDatabaseURL()+"Login");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", options.getUser() ));
nvps.add(new BasicNameValuePair("password", options.getPassword()!=null?options.getPassword():""));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
log.println("Trying to login onto the server");
HttpResponse response = httpclient.execute(httpost);
if( response.getStatusLine().getStatusCode() != HttpStatus.SC_OK )
{
log.println("Server response code is: "+response.getStatusLine().getStatusCode());
return;
}
HttpEntity ent = response.getEntity();
String respStr = EntityUtils.toString( ent ).trim();
if( respStr.startsWith("OK:") )
{
System.out.println("Login successful");
log.println("Login successful");
sessionKey = respStr.substring(3);
}
else
{
log.println("Login failed: "+respStr);
return;
}
EntityUtils.consume(ent);
ok=true;
}
catch(Exception e)
{
log.println("ERROR: Login failed: "+e.getMessage());
log.close();
return;
}
finally
{
if( ! ok )
{
httpclient.getConnectionManager().shutdown();
System.err.println("Login failed");
}
}
}
File atDir = null;
if( ( ! remote ) || options.isSave() )
{
atDir = new File(outfile,"age-tab");
atDir.mkdir();
}
File respDir = null;
if( remote && options.isSaveResponse() )
{
respDir = new File(outfile,"server");
respDir.mkdir();
}
try
{
for(File stfile : infiles)
{
Submission s = null;
long time = System.currentTimeMillis();
System.out.println("Parsing file: " + stfile);
log.println("Parsing file: " + stfile);
String stContent = null;
try
{
stContent = StringUtils.readUnicodeFile(stfile);
s = STParser3.readST(stContent);
}
catch(Exception e)
{
System.out.println("ERROR. See log file for details");
log.println("File parsing error: " + e.getMessage());
e.printStackTrace();
continue;
}
log.println("Parsing success. " + (System.currentTimeMillis() - time) + "ms");
time = System.currentTimeMillis();
System.out.println("Converting to AGE-TAB");
log.println("Converting to AGE-TAB");
ByteArrayOutputStream atOut = new ByteArrayOutputStream();
try
{
ATWriter.writeAgeTab(s, atOut);
atOut.close();
}
catch(IOException e)
{
}
byte[] atContent =atOut.toByteArray();
atOut=null;
if((!remote) || options.isSave())
{
File atOutFile = new File(atDir, stfile.getName() + ".age.txt");
try
{
FileOutputStream fos = new FileOutputStream(atOutFile);
StreamPump.doPump(new ByteArrayInputStream(atContent), fos, true);
}
catch(IOException e)
{
log.println("ERROR: Can't write AGE-TAB file: "+atOutFile.getAbsolutePath()+" Reason: "+e.getMessage());
return;
}
}
HttpPost post = new HttpPost( options.getDatabaseURL()+"upload?"+Constants.sessionKey+"="+sessionKey );
String key = String.valueOf(System.currentTimeMillis());
if(remote)
{
MultipartEntity reqEntity = new MultipartEntity();
String sbmId = s.getAnnotation(Definitions.SUBMISSIONIDENTIFIER).getValue();
try
{
Status sts;
if( options.isNewSubmissions() )
sts = Status.NEW;
else if( options.isUpdateSubmissions() )
sts = Status.UPDATE;
else
sts = Status.UPDATEORNEW;
- reqEntity.addPart(Constants.uploadHandlerParameter, new StringBody(SubmissionConstants.SUBMISSON_COMMAND));
+ reqEntity.addPart(Constants.uploadHandlerParameter, new StringBody(Constants.SUBMISSON_COMMAND));
reqEntity.addPart(SubmissionConstants.SUBMISSON_KEY, new StringBody(key));
reqEntity.addPart(SubmissionConstants.SUBMISSON_STATUS, new StringBody(sts.name()) );
if(sbmId != null)
{
reqEntity.addPart(SubmissionConstants.SUBMISSON_ID,
new StringBody(sbmId));
reqEntity.addPart(SubmissionConstants.MODULE_ID+"1", new StringBody(sbmId+"_MOD") );
}
else
sbmId = key;
if(!options.isStore())
reqEntity.addPart(SubmissionConstants.VERIFY_ONLY, new StringBody("on"));
String descr = s.getAnnotation(Definitions.SUBMISSIONDESCRIPTION).getValue();
if(descr != null)
reqEntity.addPart(SubmissionConstants.SUBMISSON_DESCR, new StringBody(descr));
reqEntity.addPart(SubmissionConstants.MODULE_DESCRIPTION + "1", new StringBody("AGE-TAB file"));
reqEntity.addPart(SubmissionConstants.MODULE_STATUS + "1", new StringBody(sts.name()));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_DESC + "2", new StringBody("SAMPLE-TAB file"));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_STATUS + "2", new StringBody(sts.name()));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_ID + "2", new StringBody("SAMPLE-TAB"));
reqEntity.addPart(SubmissionConstants.MODULE_FILE + "1", new ByteArrayBody(atContent,
"text/plain; charset=UTF-8", sbmId + ".age.txt"));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_FILE + "2", new ByteArrayBody(stContent.getBytes("UTF-8"),
"text/plain; charset=UTF-8", sbmId + ".sampletab.txt"));
}
catch(UnsupportedEncodingException e)
{
log.println("ERROR: UnsupportedEncodingException: " + e.getMessage());
return;
}
post.setEntity(reqEntity);
HttpResponse response;
try
{
response = httpclient.execute(post);
if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
{
log.println("Server response code is: " + response.getStatusLine().getStatusCode());
return;
}
HttpEntity ent = response.getEntity();
String respStr = EntityUtils.toString(ent);
int pos = respStr.indexOf("OK-" + key);
if(pos == -1)
{
log.println("ERROR: Invalid server response : " + respStr);
continue;
}
pos = pos + key.length() + 5;
String respStat = respStr.substring(pos, respStr.indexOf(']', pos));
log.println("Submission status: " + respStat);
System.out.println("Submission status: " + respStat);
if(options.isSaveResponse())
{
log.println("Writing response");
File rspf = new File(respDir, stfile.getName() + '.' + respStat);
PrintWriter pw = new PrintWriter(rspf, "UTF-8");
pw.write(respStr);
pw.close();
}
EntityUtils.consume(ent);
}
catch(Exception e)
{
log.println("ERROR: IO error: " + e.getMessage());
return;
}
}
log.println("File '"+stfile.getName()+ "' done");
System.out.println("File '"+stfile.getName()+ "' done");
}
}
finally
{
if(httpclient != null)
httpclient.getConnectionManager().shutdown();
log.close();
}
}
}
| true | true | public static void main(String[] args)
{
Options options = new Options();
CmdLineParser parser = new CmdLineParser(options);
try
{
parser.parseArgument(args);
}
catch(CmdLineException e)
{
System.err.println(e.getMessage());
System.err.println(usage);
parser.printUsage(System.err);
return;
}
if( options.getDirs() == null || options.getDirs().size() == 0 )
{
System.err.println(usage);
parser.printUsage(System.err);
return;
}
List<File> infiles = new ArrayList<File>();
for( String outf : options.getDirs() )
{
File in = new File( outf );
if( in.isDirectory() )
infiles.addAll( Arrays.asList( in.listFiles() ) );
else if( in.isFile() )
infiles.add( in );
else
{
System.err.println("Input file/directory '"+in.getAbsolutePath()+"' doesn't exist");
return;
}
}
if( infiles.size() == 0 )
{
System.err.println("No files to process");
return;
}
boolean remote = options.isLoad() || options.isStore();
if( options.getOutDir() == null )
{
System.err.println("Output directory is not specified");
return;
}
File outfile = new File( options.getOutDir() );
if( outfile.isFile() )
{
System.err.println("Output path should point to a directory");
return;
}
if( ! outfile.exists() && ! outfile.mkdirs() )
{
System.err.println("Can't create output directory");
return;
}
String sessionKey = null;
DefaultHttpClient httpclient = null;
PrintWriter log = null;
try
{
log = new PrintWriter( new File(outfile,".log") );
}
catch(FileNotFoundException e1)
{
System.err.println("Can't create log file: "+new File(outfile,".log").getAbsolutePath());
return;
}
if( remote )
{
if( options.getDatabaseURL() == null )
{
System.err.println("Database URI is required for remote operations");
return;
}
else if( ! options.getDatabaseURL().endsWith("/") )
options.setDatabaseURI( options.getDatabaseURL()+"/" );
if( options.getUser() == null )
{
System.err.println("User name is required for remote operations");
return;
}
boolean ok = false;
try
{
httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(options.getDatabaseURL()+"Login");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", options.getUser() ));
nvps.add(new BasicNameValuePair("password", options.getPassword()!=null?options.getPassword():""));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
log.println("Trying to login onto the server");
HttpResponse response = httpclient.execute(httpost);
if( response.getStatusLine().getStatusCode() != HttpStatus.SC_OK )
{
log.println("Server response code is: "+response.getStatusLine().getStatusCode());
return;
}
HttpEntity ent = response.getEntity();
String respStr = EntityUtils.toString( ent ).trim();
if( respStr.startsWith("OK:") )
{
System.out.println("Login successful");
log.println("Login successful");
sessionKey = respStr.substring(3);
}
else
{
log.println("Login failed: "+respStr);
return;
}
EntityUtils.consume(ent);
ok=true;
}
catch(Exception e)
{
log.println("ERROR: Login failed: "+e.getMessage());
log.close();
return;
}
finally
{
if( ! ok )
{
httpclient.getConnectionManager().shutdown();
System.err.println("Login failed");
}
}
}
File atDir = null;
if( ( ! remote ) || options.isSave() )
{
atDir = new File(outfile,"age-tab");
atDir.mkdir();
}
File respDir = null;
if( remote && options.isSaveResponse() )
{
respDir = new File(outfile,"server");
respDir.mkdir();
}
try
{
for(File stfile : infiles)
{
Submission s = null;
long time = System.currentTimeMillis();
System.out.println("Parsing file: " + stfile);
log.println("Parsing file: " + stfile);
String stContent = null;
try
{
stContent = StringUtils.readUnicodeFile(stfile);
s = STParser3.readST(stContent);
}
catch(Exception e)
{
System.out.println("ERROR. See log file for details");
log.println("File parsing error: " + e.getMessage());
e.printStackTrace();
continue;
}
log.println("Parsing success. " + (System.currentTimeMillis() - time) + "ms");
time = System.currentTimeMillis();
System.out.println("Converting to AGE-TAB");
log.println("Converting to AGE-TAB");
ByteArrayOutputStream atOut = new ByteArrayOutputStream();
try
{
ATWriter.writeAgeTab(s, atOut);
atOut.close();
}
catch(IOException e)
{
}
byte[] atContent =atOut.toByteArray();
atOut=null;
if((!remote) || options.isSave())
{
File atOutFile = new File(atDir, stfile.getName() + ".age.txt");
try
{
FileOutputStream fos = new FileOutputStream(atOutFile);
StreamPump.doPump(new ByteArrayInputStream(atContent), fos, true);
}
catch(IOException e)
{
log.println("ERROR: Can't write AGE-TAB file: "+atOutFile.getAbsolutePath()+" Reason: "+e.getMessage());
return;
}
}
HttpPost post = new HttpPost( options.getDatabaseURL()+"upload?"+Constants.sessionKey+"="+sessionKey );
String key = String.valueOf(System.currentTimeMillis());
if(remote)
{
MultipartEntity reqEntity = new MultipartEntity();
String sbmId = s.getAnnotation(Definitions.SUBMISSIONIDENTIFIER).getValue();
try
{
Status sts;
if( options.isNewSubmissions() )
sts = Status.NEW;
else if( options.isUpdateSubmissions() )
sts = Status.UPDATE;
else
sts = Status.UPDATEORNEW;
reqEntity.addPart(Constants.uploadHandlerParameter, new StringBody(SubmissionConstants.SUBMISSON_COMMAND));
reqEntity.addPart(SubmissionConstants.SUBMISSON_KEY, new StringBody(key));
reqEntity.addPart(SubmissionConstants.SUBMISSON_STATUS, new StringBody(sts.name()) );
if(sbmId != null)
{
reqEntity.addPart(SubmissionConstants.SUBMISSON_ID,
new StringBody(sbmId));
reqEntity.addPart(SubmissionConstants.MODULE_ID+"1", new StringBody(sbmId+"_MOD") );
}
else
sbmId = key;
if(!options.isStore())
reqEntity.addPart(SubmissionConstants.VERIFY_ONLY, new StringBody("on"));
String descr = s.getAnnotation(Definitions.SUBMISSIONDESCRIPTION).getValue();
if(descr != null)
reqEntity.addPart(SubmissionConstants.SUBMISSON_DESCR, new StringBody(descr));
reqEntity.addPart(SubmissionConstants.MODULE_DESCRIPTION + "1", new StringBody("AGE-TAB file"));
reqEntity.addPart(SubmissionConstants.MODULE_STATUS + "1", new StringBody(sts.name()));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_DESC + "2", new StringBody("SAMPLE-TAB file"));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_STATUS + "2", new StringBody(sts.name()));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_ID + "2", new StringBody("SAMPLE-TAB"));
reqEntity.addPart(SubmissionConstants.MODULE_FILE + "1", new ByteArrayBody(atContent,
"text/plain; charset=UTF-8", sbmId + ".age.txt"));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_FILE + "2", new ByteArrayBody(stContent.getBytes("UTF-8"),
"text/plain; charset=UTF-8", sbmId + ".sampletab.txt"));
}
catch(UnsupportedEncodingException e)
{
log.println("ERROR: UnsupportedEncodingException: " + e.getMessage());
return;
}
post.setEntity(reqEntity);
HttpResponse response;
try
{
response = httpclient.execute(post);
if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
{
log.println("Server response code is: " + response.getStatusLine().getStatusCode());
return;
}
HttpEntity ent = response.getEntity();
String respStr = EntityUtils.toString(ent);
int pos = respStr.indexOf("OK-" + key);
if(pos == -1)
{
log.println("ERROR: Invalid server response : " + respStr);
continue;
}
pos = pos + key.length() + 5;
String respStat = respStr.substring(pos, respStr.indexOf(']', pos));
log.println("Submission status: " + respStat);
System.out.println("Submission status: " + respStat);
if(options.isSaveResponse())
{
log.println("Writing response");
File rspf = new File(respDir, stfile.getName() + '.' + respStat);
PrintWriter pw = new PrintWriter(rspf, "UTF-8");
pw.write(respStr);
pw.close();
}
EntityUtils.consume(ent);
}
catch(Exception e)
{
log.println("ERROR: IO error: " + e.getMessage());
return;
}
}
log.println("File '"+stfile.getName()+ "' done");
System.out.println("File '"+stfile.getName()+ "' done");
}
}
finally
{
if(httpclient != null)
httpclient.getConnectionManager().shutdown();
log.close();
}
}
| public static void main(String[] args)
{
Options options = new Options();
CmdLineParser parser = new CmdLineParser(options);
try
{
parser.parseArgument(args);
}
catch(CmdLineException e)
{
System.err.println(e.getMessage());
System.err.println(usage);
parser.printUsage(System.err);
return;
}
if( options.getDirs() == null || options.getDirs().size() == 0 )
{
System.err.println(usage);
parser.printUsage(System.err);
return;
}
List<File> infiles = new ArrayList<File>();
for( String outf : options.getDirs() )
{
File in = new File( outf );
if( in.isDirectory() )
infiles.addAll( Arrays.asList( in.listFiles() ) );
else if( in.isFile() )
infiles.add( in );
else
{
System.err.println("Input file/directory '"+in.getAbsolutePath()+"' doesn't exist");
return;
}
}
if( infiles.size() == 0 )
{
System.err.println("No files to process");
return;
}
boolean remote = options.isLoad() || options.isStore();
if( options.getOutDir() == null )
{
System.err.println("Output directory is not specified");
return;
}
File outfile = new File( options.getOutDir() );
if( outfile.isFile() )
{
System.err.println("Output path should point to a directory");
return;
}
if( ! outfile.exists() && ! outfile.mkdirs() )
{
System.err.println("Can't create output directory");
return;
}
String sessionKey = null;
DefaultHttpClient httpclient = null;
PrintWriter log = null;
try
{
log = new PrintWriter( new File(outfile,".log") );
}
catch(FileNotFoundException e1)
{
System.err.println("Can't create log file: "+new File(outfile,".log").getAbsolutePath());
return;
}
if( remote )
{
if( options.getDatabaseURL() == null )
{
System.err.println("Database URI is required for remote operations");
return;
}
else if( ! options.getDatabaseURL().endsWith("/") )
options.setDatabaseURI( options.getDatabaseURL()+"/" );
if( options.getUser() == null )
{
System.err.println("User name is required for remote operations");
return;
}
boolean ok = false;
try
{
httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(options.getDatabaseURL()+"Login");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", options.getUser() ));
nvps.add(new BasicNameValuePair("password", options.getPassword()!=null?options.getPassword():""));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
log.println("Trying to login onto the server");
HttpResponse response = httpclient.execute(httpost);
if( response.getStatusLine().getStatusCode() != HttpStatus.SC_OK )
{
log.println("Server response code is: "+response.getStatusLine().getStatusCode());
return;
}
HttpEntity ent = response.getEntity();
String respStr = EntityUtils.toString( ent ).trim();
if( respStr.startsWith("OK:") )
{
System.out.println("Login successful");
log.println("Login successful");
sessionKey = respStr.substring(3);
}
else
{
log.println("Login failed: "+respStr);
return;
}
EntityUtils.consume(ent);
ok=true;
}
catch(Exception e)
{
log.println("ERROR: Login failed: "+e.getMessage());
log.close();
return;
}
finally
{
if( ! ok )
{
httpclient.getConnectionManager().shutdown();
System.err.println("Login failed");
}
}
}
File atDir = null;
if( ( ! remote ) || options.isSave() )
{
atDir = new File(outfile,"age-tab");
atDir.mkdir();
}
File respDir = null;
if( remote && options.isSaveResponse() )
{
respDir = new File(outfile,"server");
respDir.mkdir();
}
try
{
for(File stfile : infiles)
{
Submission s = null;
long time = System.currentTimeMillis();
System.out.println("Parsing file: " + stfile);
log.println("Parsing file: " + stfile);
String stContent = null;
try
{
stContent = StringUtils.readUnicodeFile(stfile);
s = STParser3.readST(stContent);
}
catch(Exception e)
{
System.out.println("ERROR. See log file for details");
log.println("File parsing error: " + e.getMessage());
e.printStackTrace();
continue;
}
log.println("Parsing success. " + (System.currentTimeMillis() - time) + "ms");
time = System.currentTimeMillis();
System.out.println("Converting to AGE-TAB");
log.println("Converting to AGE-TAB");
ByteArrayOutputStream atOut = new ByteArrayOutputStream();
try
{
ATWriter.writeAgeTab(s, atOut);
atOut.close();
}
catch(IOException e)
{
}
byte[] atContent =atOut.toByteArray();
atOut=null;
if((!remote) || options.isSave())
{
File atOutFile = new File(atDir, stfile.getName() + ".age.txt");
try
{
FileOutputStream fos = new FileOutputStream(atOutFile);
StreamPump.doPump(new ByteArrayInputStream(atContent), fos, true);
}
catch(IOException e)
{
log.println("ERROR: Can't write AGE-TAB file: "+atOutFile.getAbsolutePath()+" Reason: "+e.getMessage());
return;
}
}
HttpPost post = new HttpPost( options.getDatabaseURL()+"upload?"+Constants.sessionKey+"="+sessionKey );
String key = String.valueOf(System.currentTimeMillis());
if(remote)
{
MultipartEntity reqEntity = new MultipartEntity();
String sbmId = s.getAnnotation(Definitions.SUBMISSIONIDENTIFIER).getValue();
try
{
Status sts;
if( options.isNewSubmissions() )
sts = Status.NEW;
else if( options.isUpdateSubmissions() )
sts = Status.UPDATE;
else
sts = Status.UPDATEORNEW;
reqEntity.addPart(Constants.uploadHandlerParameter, new StringBody(Constants.SUBMISSON_COMMAND));
reqEntity.addPart(SubmissionConstants.SUBMISSON_KEY, new StringBody(key));
reqEntity.addPart(SubmissionConstants.SUBMISSON_STATUS, new StringBody(sts.name()) );
if(sbmId != null)
{
reqEntity.addPart(SubmissionConstants.SUBMISSON_ID,
new StringBody(sbmId));
reqEntity.addPart(SubmissionConstants.MODULE_ID+"1", new StringBody(sbmId+"_MOD") );
}
else
sbmId = key;
if(!options.isStore())
reqEntity.addPart(SubmissionConstants.VERIFY_ONLY, new StringBody("on"));
String descr = s.getAnnotation(Definitions.SUBMISSIONDESCRIPTION).getValue();
if(descr != null)
reqEntity.addPart(SubmissionConstants.SUBMISSON_DESCR, new StringBody(descr));
reqEntity.addPart(SubmissionConstants.MODULE_DESCRIPTION + "1", new StringBody("AGE-TAB file"));
reqEntity.addPart(SubmissionConstants.MODULE_STATUS + "1", new StringBody(sts.name()));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_DESC + "2", new StringBody("SAMPLE-TAB file"));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_STATUS + "2", new StringBody(sts.name()));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_ID + "2", new StringBody("SAMPLE-TAB"));
reqEntity.addPart(SubmissionConstants.MODULE_FILE + "1", new ByteArrayBody(atContent,
"text/plain; charset=UTF-8", sbmId + ".age.txt"));
reqEntity.addPart(SubmissionConstants.ATTACHMENT_FILE + "2", new ByteArrayBody(stContent.getBytes("UTF-8"),
"text/plain; charset=UTF-8", sbmId + ".sampletab.txt"));
}
catch(UnsupportedEncodingException e)
{
log.println("ERROR: UnsupportedEncodingException: " + e.getMessage());
return;
}
post.setEntity(reqEntity);
HttpResponse response;
try
{
response = httpclient.execute(post);
if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
{
log.println("Server response code is: " + response.getStatusLine().getStatusCode());
return;
}
HttpEntity ent = response.getEntity();
String respStr = EntityUtils.toString(ent);
int pos = respStr.indexOf("OK-" + key);
if(pos == -1)
{
log.println("ERROR: Invalid server response : " + respStr);
continue;
}
pos = pos + key.length() + 5;
String respStat = respStr.substring(pos, respStr.indexOf(']', pos));
log.println("Submission status: " + respStat);
System.out.println("Submission status: " + respStat);
if(options.isSaveResponse())
{
log.println("Writing response");
File rspf = new File(respDir, stfile.getName() + '.' + respStat);
PrintWriter pw = new PrintWriter(rspf, "UTF-8");
pw.write(respStr);
pw.close();
}
EntityUtils.consume(ent);
}
catch(Exception e)
{
log.println("ERROR: IO error: " + e.getMessage());
return;
}
}
log.println("File '"+stfile.getName()+ "' done");
System.out.println("File '"+stfile.getName()+ "' done");
}
}
finally
{
if(httpclient != null)
httpclient.getConnectionManager().shutdown();
log.close();
}
}
|
diff --git a/util/src/main/java/com/psddev/dari/util/IoUtils.java b/util/src/main/java/com/psddev/dari/util/IoUtils.java
index 35b2f74e..096be555 100644
--- a/util/src/main/java/com/psddev/dari/util/IoUtils.java
+++ b/util/src/main/java/com/psddev/dari/util/IoUtils.java
@@ -1,350 +1,350 @@
package com.psddev.dari.util;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
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.net.URLConnection;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** IO utility methods. */
public final class IoUtils {
private static final int BUFFER_SIZE = 0x1000;
private static final Logger LOGGER = LoggerFactory.getLogger(IoUtils.class);
/**
* Closes the given {@code closeable}.
*
* @param closeable If {@code null}, does nothing.
* @param suppressError If {@code true}, logs the error instead of throwing it.
*/
public static void close(Closeable closeable, boolean suppressError) throws IOException {
if (closeable == null) {
return;
}
try {
closeable.close();
} catch (IOException error) {
if (suppressError) {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Can't close [" + closeable + "]!", error);
}
} else {
throw error;
}
}
}
/**
* Closes the given {@code closeable}, logging any errors that occur
* instead of throwing them.
*
* @param closeable If {@code null}, does nothing.
*/
public static void closeQuietly(Closeable closeable) {
try {
close(closeable, true);
} catch (IOException error) {
// This should never trigger with #close(suppressError = true).
}
}
/**
* Copies from the given {@code source} to the given {@code destination}.
* Doesn't close either streams.
*
* @param source Can't be {@code null}.
* @param destination Can't be {@code null}.
* @return Number of bytes copied.
*/
public static long copy(InputStream source, OutputStream destination) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
long total = 0L;
for (int read; (read = source.read(buffer)) > -1; ) {
destination.write(buffer, 0, read);
total += read;
}
return total;
}
/**
* Copies the given {@code source} to the given {@code destination}.
*
* @param source Can't be {@code null}.
* @param destination Can't be {@code null}.
* @return Number of bytes copied.
*/
public static long copy(File source, File destination) throws IOException {
createFile(destination);
FileInputStream sourceInput = new FileInputStream(source);
try {
FileOutputStream destinationOutput = new FileOutputStream(destination);
try {
return copy(sourceInput, destinationOutput);
} finally {
destinationOutput.close();
}
} finally {
sourceInput.close();
}
}
/**
* Returns all bytes from the given {@code input}. Doesn't close
* the stream.
*
* @param input Can't be {@code null}.
* @return Never {@code null}.
*/
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
/**
* Returns all bytes from the given {@code file}.
*
* @param file Can't be {@code null}.
* @return Never {@code null}.
*/
public static byte[] toByteArray(File file) throws IOException {
InputStream input = new FileInputStream(file);
try {
return toByteArray(input);
} finally {
closeQuietly(input);
}
}
/**
* Returns all bytes from the given {@code url}.
*
* @param url Can't be {@code null}.
* @return Never {@code null}.
*/
public static byte[] toByteArray(URL url) throws IOException {
InputStream input = url.openStream();
try {
return toByteArray(input);
} finally {
closeQuietly(input);
}
}
/**
* Returns a file equivalent to the given {@code url}.
*
* @param url Can be {@code null}.
* @param charset Can't be {@code null}.
* @return {@code null} if the given {@code url} is {@code null} or
* doesn't point to a file.
*/
public static File toFile(URL url, Charset charset) {
if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) {
return null;
}
byte[] encoded = url.getFile().replace('/', File.separatorChar).getBytes(StringUtils.US_ASCII);
int length = encoded.length;
byte[] decoded = new byte[length];
int decodedIndex = 0;
for (int i = 0; i < length; ++ i) {
byte letter = encoded[i];
if (letter == '%') {
++ i;
if (i < length) {
byte hex1 = HEX_TO_BYTE[encoded[i]];
if (hex1 >= 0) {
++ i;
if (i < length) {
byte hex2 = HEX_TO_BYTE[encoded[i]];
if (hex2 >= 0) {
decoded[decodedIndex] = (byte) (hex1 << 4 | hex2);
++ decodedIndex;
continue;
}
}
-- i;
}
}
-- i;
}
decoded[decodedIndex] = letter;
++ decodedIndex;
}
- return new File(new String(decoded, charset));
+ return new File(new String(decoded, 0, decodedIndex, charset));
}
private static final byte[] HEX_TO_BYTE;
static {
int length = Byte.MAX_VALUE - Byte.MIN_VALUE;
HEX_TO_BYTE = new byte[length];
for (int i = 0; i < length; ++ i) {
HEX_TO_BYTE[i] = -1;
}
for (int i = 0; i < 0x10; ++ i) {
HEX_TO_BYTE[Integer.toHexString(i).charAt(0)] = (byte) i;
}
}
/**
* Reads all bytes from the given {@code input} and converts them
* into a string using the given {@code charset}.
*
* @param input Can't be {@code null}.
* @param charset Can't be {@code null}.
* @return Never {@code null}.
*/
public static String toString(InputStream input, Charset charset) throws IOException {
return new String(toByteArray(input), charset);
}
/**
* Reads all bytes from the given {@code file} and converts them
* into a string using the given {@code charset}.
*
* @param file Can't be {@code null}.
* @param charset Can't be {@code null}.
* @return Never {@code null}.
*/
public static String toString(File file, Charset charset) throws IOException {
return new String(toByteArray(file), charset);
}
/**
* Reads all bytes from the given {@code url} and converts them
* into a string using the response content encoding. If the encoding
* isn't provided, uses {@link StringUtils#UTF_8} instead.
*
* @param url Can't be {@code null}.
* @return Never {@code null}.
*/
public static String toString(URL url) throws IOException {
URLConnection connection = url.openConnection();
InputStream input = connection.getInputStream();
try {
String encoding = connection.getContentEncoding();
Charset charset;
if (encoding == null) {
charset = StringUtils.UTF_8;
} else {
try {
charset = Charset.forName(encoding);
} catch (IllegalCharsetNameException error) {
throw new IOException(error);
}
}
return new String(toByteArray(input), charset);
} finally {
closeQuietly(input);
}
}
/**
* Creates all directories leading up to and including the given
* {@code directory} if any of them doesn't exist.
*
* @param directory Can't be {@code null}.
* @throws IOException If any of the directories couldn't be created.
*/
public static void createDirectories(File directory) throws IOException {
if (directory.exists() && !directory.isDirectory()) {
throw new IOException("[" + directory + "] already exists but isn't a directory!");
} else if (!directory.mkdirs() && !directory.isDirectory()) {
throw new IOException("Can't create [" + directory + "] directory!");
}
}
/**
* Creates all the parent directories leading up to the given
* {@code fileOrDirectory} if any of them doesn't exist.
*
* @param fileOrDirectory Can't be {@code null}.
* @throws IOException If any of the parent directories couldn't be
* created.
*/
public static void createParentDirectories(File fileOrDirectory) throws IOException {
createDirectories(fileOrDirectory.getParentFile());
}
/**
* Creates the given {@code file} if it doesn't exist. This method will
* also create all the parent directories leading up to the given
* {@code file} using {@link #createParentDirectories}.
*
* @param file Can't be {@code null}.
* @throws IOException If the given {@code file} couldn't be created.
*/
public static void createFile(File file) throws IOException {
createParentDirectories(file);
if (!file.createNewFile() &&
!file.isFile()) {
throw new IOException("[" + file + "] already exists but isn't a file!");
}
}
/**
* Renames the given {@code source} to {@code destination}.
*
* @param source Can't be {@code null}.
* @param destination Can't be {@code null}.
* @throws IOException If the given {@code source} couldn't be renamed.
*/
public static void rename(File source, File destination) throws IOException {
if (!source.renameTo(destination)) {
throw new IOException("[" + source + "] can't be renamed to [" + destination + "]!");
}
}
/**
* Deletes the given {@code fileOrDirectory} if it exists.
*
* @param fileOrDirectory If {@code null}, does nothing.
* @throws IOException If the given {@code file} couldn't be deleted.
*/
public static void delete(File fileOrDirectory) throws IOException {
if (fileOrDirectory != null &&
fileOrDirectory.exists() &&
!fileOrDirectory.delete() &&
fileOrDirectory.exists()) {
throw new IOException("Can't delete [" + fileOrDirectory + "]!");
}
}
}
| true | true | public static File toFile(URL url, Charset charset) {
if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) {
return null;
}
byte[] encoded = url.getFile().replace('/', File.separatorChar).getBytes(StringUtils.US_ASCII);
int length = encoded.length;
byte[] decoded = new byte[length];
int decodedIndex = 0;
for (int i = 0; i < length; ++ i) {
byte letter = encoded[i];
if (letter == '%') {
++ i;
if (i < length) {
byte hex1 = HEX_TO_BYTE[encoded[i]];
if (hex1 >= 0) {
++ i;
if (i < length) {
byte hex2 = HEX_TO_BYTE[encoded[i]];
if (hex2 >= 0) {
decoded[decodedIndex] = (byte) (hex1 << 4 | hex2);
++ decodedIndex;
continue;
}
}
-- i;
}
}
-- i;
}
decoded[decodedIndex] = letter;
++ decodedIndex;
}
return new File(new String(decoded, charset));
}
| public static File toFile(URL url, Charset charset) {
if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) {
return null;
}
byte[] encoded = url.getFile().replace('/', File.separatorChar).getBytes(StringUtils.US_ASCII);
int length = encoded.length;
byte[] decoded = new byte[length];
int decodedIndex = 0;
for (int i = 0; i < length; ++ i) {
byte letter = encoded[i];
if (letter == '%') {
++ i;
if (i < length) {
byte hex1 = HEX_TO_BYTE[encoded[i]];
if (hex1 >= 0) {
++ i;
if (i < length) {
byte hex2 = HEX_TO_BYTE[encoded[i]];
if (hex2 >= 0) {
decoded[decodedIndex] = (byte) (hex1 << 4 | hex2);
++ decodedIndex;
continue;
}
}
-- i;
}
}
-- i;
}
decoded[decodedIndex] = letter;
++ decodedIndex;
}
return new File(new String(decoded, 0, decodedIndex, charset));
}
|
diff --git a/src/com/sabayrean/hangman/TextResult.java b/src/com/sabayrean/hangman/TextResult.java
index b860500..dcb42c0 100644
--- a/src/com/sabayrean/hangman/TextResult.java
+++ b/src/com/sabayrean/hangman/TextResult.java
@@ -1,19 +1,19 @@
package com.sabayrean.hangman;
import java.util.ArrayList;
import java.util.List;
public class TextResult extends Text {
public TextResult(String text){
this.setText(text);
}
public List<Integer> getIndexes(char c){
List<Integer> indexes = new ArrayList<Integer>();
for(int i = 0; i < this.getText().length(); i++){
- indexes.add(i);
+ if(this.getText().charAt(i) == c) indexes.add(i);
}
return indexes;
}
}
| true | true | public List<Integer> getIndexes(char c){
List<Integer> indexes = new ArrayList<Integer>();
for(int i = 0; i < this.getText().length(); i++){
indexes.add(i);
}
return indexes;
}
| public List<Integer> getIndexes(char c){
List<Integer> indexes = new ArrayList<Integer>();
for(int i = 0; i < this.getText().length(); i++){
if(this.getText().charAt(i) == c) indexes.add(i);
}
return indexes;
}
|
diff --git a/src/Semester.java b/src/Semester.java
index b115616..69919ba 100644
--- a/src/Semester.java
+++ b/src/Semester.java
@@ -1,325 +1,330 @@
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class Semester implements PrimaryKeyManager, Serializable, Comparable<Semester>{
private static final long serialVersionUID = 1L;
// Attributes
public static int pk = 1;
private int id;
private String name;
private HashMap<Integer, Course> courses;
// Constructors
public Semester(String name) {
this.id = pk;
autoIncrement(this.id);
this.name = name;
this.courses = new HashMap<Integer, Course>();
}
// Getters and Setter
public int getID() { return id; }
public String getName() { return name; }
public HashMap<Integer, Course> getCourses() { return courses; }
public void setID(int id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setCourses(HashMap<Integer, Course> courses) { this.courses = courses; }
// Specific methods.
public Course getCourse(int id) throws KeyErrorException {
if (courses.containsKey(id)) return courses.get(id);
else throw new KeyErrorException(String.format("Course ID %d does not exists in current semester", id));
}
public void addCourse(Course course) throws DuplicateKeyException {
if (courses.containsKey(course.getID()))
throw new DuplicateKeyException(String.format("Course ID %d has already been added.", course.getID()));
else {
Course copyCourse = new Course(course);
copyCourse.setSemester(this);
courses.put(copyCourse.getID(), copyCourse);
}
}
public void rmCourse(Course course) throws KeyErrorException {
if (courses.containsKey(course.getID())) {
courses.remove(course.getID());
}
else throw new KeyErrorException(String.format("Course ID %d has not yet been added.", course.getID()));
}
public void endSemester(School school, SaveData data) throws EndSemesterException {
// Check if all grades have been input.
// At the same time calculate all GPA and CGPA
Grade grade = null;
Course newCourse = null;
for (Course course : getCourses().values()) {
for (Student student : course.getGroups().getStudents()) {
try {
grade = student.getGrade(course);
grade.calcGPA();
student.calcCGPA();
} catch (KeyErrorException e){
throw new EndSemesterException(
String.format(
"Student %d, %s have no grades in Course %d, %s",
student.getID(), student.getName(),
course.getID(), course.getName()));
}
}
// Shallow copy all courses in semester for archiving.
// By replacing courses in school with new ones.
newCourse = new Course(course);
try {
school.rmCourse(course);
school.addCourse(newCourse);
} catch (Exception e) {
//Pass
}
// Clear all registered students in school's courses.
newCourse.setGroups(new CourseGroup(course, course.getGroups().getCapacity()));
}
data.setCurrentSemester(0);
}
@Override
public void autoIncrement(int id) {
if (id < pk) return;
pk = ++id;
}
@Override
public void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
stream.defaultReadObject();
autoIncrement(this.id);
}
@Override
public int compareTo(Semester sem) {
// Reverse sorting
return sem.getID() - this.getID();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Semester)) return false;
Semester temp = (Semester) obj;
if (this.id == temp.getID()) return true;
if (this.getName().equals(temp.getName())) return true;
return false;
}
public static void main(School school, SaveData data, Scanner scan) {
// Declarations
int choice = 0;
boolean done = false;
String stringInput = null;
Semester sem = null;
if (data.getCurrentSemester() != null) {
done = true;
Semester.main(data.getCurrentSemester(), school, data, scan);
}
while(!done) {
System.out.println("Semester Manager.");
System.out.println("\t1. Start a new semester.");
System.out.println("\t0. Go back to previous menu.");
System.out.print("Choice: ");
choice = scan.nextInt(); scan.nextLine();
switch (choice) {
case 0:
done = true;
break;
case 1:
System.out.print("Please input semester name: ");
stringInput = scan.nextLine();
try {
sem = new Semester(stringInput);
data.addSemester(sem);
data.setCurrentSemester(sem.getID());
done = true;
Semester.main(sem, school, data, scan);
} catch (DuplicateKeyException e) {
System.out.println(e.getMessage());
}
break;
default:
System.out.print("Error: Invalid input.");
break;
}
}
}
public static void main(Semester sem, School school, SaveData data, Scanner scan) {
int choice = 0;
int studentID = 0;
int courseID = 0;
boolean done = false;
while(!done) {
System.out.println("Semester Registration Manager.");
System.out.println("\t1. Add a course to current semester.");
System.out.println("\t2. Add all courses to current semester.");
System.out.println("\t3. Remove a course from current semester.");
System.out.println("\t4. Remove all courses from current semester.");
System.out.println("\t5. Register a student to a course.");
System.out.println("\t6. Edit student's group in a course.");
System.out.println("\t7. Manage grades for a student of a course.");
System.out.println("\t8. Unregister a student from a course.");
System.out.println("\t9. Unregister all students from a course.");
System.out.println("\t10. End current semester.");
System.out.println("\t0. Go back to previous menu.");
System.out.print("Choice: ");
choice = scan.nextInt(); scan.nextLine();
switch (choice) {
case 0:
done = true;
break;
case 1:
System.out.print("Please input course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
sem.addCourse(school.getCourse(courseID));
+ school.getCourse(courseID.setSemester(sem));
System.out.printf("Course ID %d added successfully.\n", courseID);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
} catch (DuplicateKeyException f) {
System.out.println(f.getMessage());
}
break;
case 2:
sem.setCourses(school.getCourses());
break;
case 3:
System.out.print("Please input course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
+ sem.getCourse(courseID).setSemester((Semester)null);
sem.rmCourse(sem.getCourse(courseID));
System.out.printf("Course ID %d removed successfully.\n", courseID);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
break;
case 4:
+ for (Course course: school.getCourses().values()) {
+ course.setSemester((Semester)null);
+ }
sem.setCourses(new HashMap<Integer, Course>());
break;
case 5:
case 6:
System.out.print("Please input student ID: ");
studentID = scan.nextInt(); scan.nextLine();
System.out.print("Please input Course ID: ");
courseID = scan.nextInt(); scan.nextLine();
HashMap<CourseType, Integer> oriGroupIDs = null;
CourseGroup groups = null;
try {
Student student = school.getStudent(studentID);
Course course = sem.getCourse(courseID);
groups = course.getGroups();
HashMap<CourseType, Integer> groupIDs = new HashMap<CourseType, Integer>();
if (choice == 6) {
oriGroupIDs = groups.getGroups(student);
groups.rmStudent(student);
}
System.out.println(groups.print(""));
if (groups.getLecture() != null) {
System.out.print("Please input Lecture group: ");
groupIDs.put(CourseType.LECTURE, scan.nextInt());
}
if (groups.getTutorials() != null) {
System.out.print("Please input Tutorial group: ");
groupIDs.put(CourseType.TUTORIAL, scan.nextInt());
}
if (groups.getLabs() != null) {
System.out.print("Please input Lab group: ");
groupIDs.put(CourseType.LAB, scan.nextInt());
}
groups.addStudent(student, groupIDs);
student.addCourse(course);
System.out.printf("Course ID %d removed successfully.\n", courseID);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
} catch (MaxCapacityException f) {
System.out.println(f.getMessage());
} catch (DuplicateKeyException g) {
System.out.println(g.getMessage());
} finally {
if (choice == 6 && oriGroupIDs != null) {
try {
groups.addStudent(school.getStudent(studentID), oriGroupIDs);
} catch (Exception e) {
// pass
}
}
}
break;
case 7:
System.out.print("Please input student ID: ");
studentID = scan.nextInt(); scan.nextLine();
System.out.print("Please input Course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
Grade.main(school.getStudent(studentID),
sem.getCourse(courseID),
scan);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
break;
case 8:
System.out.print("Please input student ID: ");
studentID = scan.nextInt(); scan.nextLine();
System.out.print("Please input Course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
// Remove student from course
sem.getCourse(courseID)
.getGroups()
.rmStudent(school.getStudent(studentID));
// Remove course from student
school.getStudent(studentID).rmCourse(sem.getCourse(courseID));
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
break;
case 9:
System.out.print("Are you sure? (Y/N): ");
choice = scan.nextLine().toUpperCase().charAt(0);
if (choice == 'Y') {
System.out.print("Please input course ID: ");
choice = scan.nextInt(); scan.nextLine();
HashSet<Student> students = null;
CourseGroup courseGroup = null;
try {
courseGroup = sem.getCourse(courseID).getGroups();
students = courseGroup.getStudents();
for (Student stud : students) {
courseGroup.rmStudent(stud);
}
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
}
break;
case 10:
try {
sem.endSemester(school, data);
done = true;
} catch (EndSemesterException e) {
System.out.println(e.getMessage());
}
break;
default:
System.out.println("Error: Invalid choice.");
break;
}
}
}
}
| false | true | public static void main(Semester sem, School school, SaveData data, Scanner scan) {
int choice = 0;
int studentID = 0;
int courseID = 0;
boolean done = false;
while(!done) {
System.out.println("Semester Registration Manager.");
System.out.println("\t1. Add a course to current semester.");
System.out.println("\t2. Add all courses to current semester.");
System.out.println("\t3. Remove a course from current semester.");
System.out.println("\t4. Remove all courses from current semester.");
System.out.println("\t5. Register a student to a course.");
System.out.println("\t6. Edit student's group in a course.");
System.out.println("\t7. Manage grades for a student of a course.");
System.out.println("\t8. Unregister a student from a course.");
System.out.println("\t9. Unregister all students from a course.");
System.out.println("\t10. End current semester.");
System.out.println("\t0. Go back to previous menu.");
System.out.print("Choice: ");
choice = scan.nextInt(); scan.nextLine();
switch (choice) {
case 0:
done = true;
break;
case 1:
System.out.print("Please input course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
sem.addCourse(school.getCourse(courseID));
System.out.printf("Course ID %d added successfully.\n", courseID);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
} catch (DuplicateKeyException f) {
System.out.println(f.getMessage());
}
break;
case 2:
sem.setCourses(school.getCourses());
break;
case 3:
System.out.print("Please input course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
sem.rmCourse(sem.getCourse(courseID));
System.out.printf("Course ID %d removed successfully.\n", courseID);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
break;
case 4:
sem.setCourses(new HashMap<Integer, Course>());
break;
case 5:
case 6:
System.out.print("Please input student ID: ");
studentID = scan.nextInt(); scan.nextLine();
System.out.print("Please input Course ID: ");
courseID = scan.nextInt(); scan.nextLine();
HashMap<CourseType, Integer> oriGroupIDs = null;
CourseGroup groups = null;
try {
Student student = school.getStudent(studentID);
Course course = sem.getCourse(courseID);
groups = course.getGroups();
HashMap<CourseType, Integer> groupIDs = new HashMap<CourseType, Integer>();
if (choice == 6) {
oriGroupIDs = groups.getGroups(student);
groups.rmStudent(student);
}
System.out.println(groups.print(""));
if (groups.getLecture() != null) {
System.out.print("Please input Lecture group: ");
groupIDs.put(CourseType.LECTURE, scan.nextInt());
}
if (groups.getTutorials() != null) {
System.out.print("Please input Tutorial group: ");
groupIDs.put(CourseType.TUTORIAL, scan.nextInt());
}
if (groups.getLabs() != null) {
System.out.print("Please input Lab group: ");
groupIDs.put(CourseType.LAB, scan.nextInt());
}
groups.addStudent(student, groupIDs);
student.addCourse(course);
System.out.printf("Course ID %d removed successfully.\n", courseID);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
} catch (MaxCapacityException f) {
System.out.println(f.getMessage());
} catch (DuplicateKeyException g) {
System.out.println(g.getMessage());
} finally {
if (choice == 6 && oriGroupIDs != null) {
try {
groups.addStudent(school.getStudent(studentID), oriGroupIDs);
} catch (Exception e) {
// pass
}
}
}
break;
case 7:
System.out.print("Please input student ID: ");
studentID = scan.nextInt(); scan.nextLine();
System.out.print("Please input Course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
Grade.main(school.getStudent(studentID),
sem.getCourse(courseID),
scan);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
break;
case 8:
System.out.print("Please input student ID: ");
studentID = scan.nextInt(); scan.nextLine();
System.out.print("Please input Course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
// Remove student from course
sem.getCourse(courseID)
.getGroups()
.rmStudent(school.getStudent(studentID));
// Remove course from student
school.getStudent(studentID).rmCourse(sem.getCourse(courseID));
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
break;
case 9:
System.out.print("Are you sure? (Y/N): ");
choice = scan.nextLine().toUpperCase().charAt(0);
if (choice == 'Y') {
System.out.print("Please input course ID: ");
choice = scan.nextInt(); scan.nextLine();
HashSet<Student> students = null;
CourseGroup courseGroup = null;
try {
courseGroup = sem.getCourse(courseID).getGroups();
students = courseGroup.getStudents();
for (Student stud : students) {
courseGroup.rmStudent(stud);
}
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
}
break;
case 10:
try {
sem.endSemester(school, data);
done = true;
} catch (EndSemesterException e) {
System.out.println(e.getMessage());
}
break;
default:
System.out.println("Error: Invalid choice.");
break;
}
}
}
| public static void main(Semester sem, School school, SaveData data, Scanner scan) {
int choice = 0;
int studentID = 0;
int courseID = 0;
boolean done = false;
while(!done) {
System.out.println("Semester Registration Manager.");
System.out.println("\t1. Add a course to current semester.");
System.out.println("\t2. Add all courses to current semester.");
System.out.println("\t3. Remove a course from current semester.");
System.out.println("\t4. Remove all courses from current semester.");
System.out.println("\t5. Register a student to a course.");
System.out.println("\t6. Edit student's group in a course.");
System.out.println("\t7. Manage grades for a student of a course.");
System.out.println("\t8. Unregister a student from a course.");
System.out.println("\t9. Unregister all students from a course.");
System.out.println("\t10. End current semester.");
System.out.println("\t0. Go back to previous menu.");
System.out.print("Choice: ");
choice = scan.nextInt(); scan.nextLine();
switch (choice) {
case 0:
done = true;
break;
case 1:
System.out.print("Please input course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
sem.addCourse(school.getCourse(courseID));
school.getCourse(courseID.setSemester(sem));
System.out.printf("Course ID %d added successfully.\n", courseID);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
} catch (DuplicateKeyException f) {
System.out.println(f.getMessage());
}
break;
case 2:
sem.setCourses(school.getCourses());
break;
case 3:
System.out.print("Please input course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
sem.getCourse(courseID).setSemester((Semester)null);
sem.rmCourse(sem.getCourse(courseID));
System.out.printf("Course ID %d removed successfully.\n", courseID);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
break;
case 4:
for (Course course: school.getCourses().values()) {
course.setSemester((Semester)null);
}
sem.setCourses(new HashMap<Integer, Course>());
break;
case 5:
case 6:
System.out.print("Please input student ID: ");
studentID = scan.nextInt(); scan.nextLine();
System.out.print("Please input Course ID: ");
courseID = scan.nextInt(); scan.nextLine();
HashMap<CourseType, Integer> oriGroupIDs = null;
CourseGroup groups = null;
try {
Student student = school.getStudent(studentID);
Course course = sem.getCourse(courseID);
groups = course.getGroups();
HashMap<CourseType, Integer> groupIDs = new HashMap<CourseType, Integer>();
if (choice == 6) {
oriGroupIDs = groups.getGroups(student);
groups.rmStudent(student);
}
System.out.println(groups.print(""));
if (groups.getLecture() != null) {
System.out.print("Please input Lecture group: ");
groupIDs.put(CourseType.LECTURE, scan.nextInt());
}
if (groups.getTutorials() != null) {
System.out.print("Please input Tutorial group: ");
groupIDs.put(CourseType.TUTORIAL, scan.nextInt());
}
if (groups.getLabs() != null) {
System.out.print("Please input Lab group: ");
groupIDs.put(CourseType.LAB, scan.nextInt());
}
groups.addStudent(student, groupIDs);
student.addCourse(course);
System.out.printf("Course ID %d removed successfully.\n", courseID);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
} catch (MaxCapacityException f) {
System.out.println(f.getMessage());
} catch (DuplicateKeyException g) {
System.out.println(g.getMessage());
} finally {
if (choice == 6 && oriGroupIDs != null) {
try {
groups.addStudent(school.getStudent(studentID), oriGroupIDs);
} catch (Exception e) {
// pass
}
}
}
break;
case 7:
System.out.print("Please input student ID: ");
studentID = scan.nextInt(); scan.nextLine();
System.out.print("Please input Course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
Grade.main(school.getStudent(studentID),
sem.getCourse(courseID),
scan);
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
break;
case 8:
System.out.print("Please input student ID: ");
studentID = scan.nextInt(); scan.nextLine();
System.out.print("Please input Course ID: ");
courseID = scan.nextInt(); scan.nextLine();
try {
// Remove student from course
sem.getCourse(courseID)
.getGroups()
.rmStudent(school.getStudent(studentID));
// Remove course from student
school.getStudent(studentID).rmCourse(sem.getCourse(courseID));
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
break;
case 9:
System.out.print("Are you sure? (Y/N): ");
choice = scan.nextLine().toUpperCase().charAt(0);
if (choice == 'Y') {
System.out.print("Please input course ID: ");
choice = scan.nextInt(); scan.nextLine();
HashSet<Student> students = null;
CourseGroup courseGroup = null;
try {
courseGroup = sem.getCourse(courseID).getGroups();
students = courseGroup.getStudents();
for (Student stud : students) {
courseGroup.rmStudent(stud);
}
} catch (KeyErrorException e) {
System.out.println(e.getMessage());
}
}
break;
case 10:
try {
sem.endSemester(school, data);
done = true;
} catch (EndSemesterException e) {
System.out.println(e.getMessage());
}
break;
default:
System.out.println("Error: Invalid choice.");
break;
}
}
}
|
diff --git a/src/main/java/org/basex/query/expr/CElem.java b/src/main/java/org/basex/query/expr/CElem.java
index 5cbf811c8..d4b50e636 100644
--- a/src/main/java/org/basex/query/expr/CElem.java
+++ b/src/main/java/org/basex/query/expr/CElem.java
@@ -1,173 +1,173 @@
package org.basex.query.expr;
import static org.basex.query.QueryTokens.*;
import static org.basex.util.Token.*;
import java.io.IOException;
import org.basex.data.Serializer;
import org.basex.query.QueryContext;
import org.basex.query.QueryException;
import org.basex.query.QueryTokens;
import org.basex.query.item.FElem;
import org.basex.query.item.Item;
import org.basex.query.item.ANode;
import org.basex.query.item.NodeType;
import org.basex.query.item.QNm;
import static org.basex.query.util.Err.*;
import org.basex.query.util.NSGlobal;
import org.basex.query.util.Var;
import org.basex.util.Atts;
import org.basex.util.InputInfo;
import org.basex.util.Token;
/**
* Element fragment.
*
* @author BaseX Team 2005-11, BSD License
* @author Christian Gruen
*/
public final class CElem extends CFrag {
/** Namespaces. */
private final Atts nsp;
/** Tag name. */
private Expr tag;
/** Computed constructor. */
private final boolean comp;
/**
* Constructor.
* @param ii input info
* @param t tag tag
* @param c computed constructor
* @param cont element content
* @param ns namespaces
*/
public CElem(final InputInfo ii, final Expr t, final Atts ns,
final boolean c, final Expr... cont) {
super(ii, cont);
tag = t;
nsp = ns;
comp = c;
}
@Override
public CElem comp(final QueryContext ctx) throws QueryException {
final int s = ctx.ns.size();
addNS(ctx);
super.comp(ctx);
tag = checkUp(tag, ctx).comp(ctx);
ctx.ns.size(s);
return this;
}
/**
* Adds namespaces to the current context.
* @param ctx query context
* @throws QueryException query exception
*/
private void addNS(final QueryContext ctx) throws QueryException {
for(int n = nsp.size - 1; n >= 0; n--) {
ctx.ns.add(new QNm(concat(XMLNSC, nsp.key[n]), nsp.val[n]), input);
}
}
/**
* Checks the element name for illegal prefixes or URIs.
* @param name element name
* @return checked name
* @throws QueryException XQDY0096, if invalid namespace was found
*/
private QNm checkNS(final QNm name) throws QueryException {
final byte[] pre = name.pref(), uri = name.uri().atom();
if(eq(pre, XMLNS) || eq(uri, XMLNSURI) || eq(pre, XML) ^ eq(uri, XMLURI))
CEINS.thrw(input, pre, uri);
return name;
}
@Override
public FElem item(final QueryContext ctx, final InputInfo ii)
throws QueryException {
final Item it = checkItem(tag, ctx);
final int s = ctx.ns.size();
addNS(ctx);
// clone namespaces for context sensitive operations
final Atts nsc = new Atts();
for(int i = 0; i < nsp.size; ++i) nsc.add(nsp.key[i], nsp.val[i]);
final QNm tname = checkNS(qname(ctx, it, false, ii));
final byte[] pref = tname.pref();
if(!eq(pref, XML)) {
byte[] uri = ctx.ns.find(pref);
if(uri == null) uri = NSGlobal.uri(pref);
if(tname.hasUri()) {
final byte[] muri = tname.uri().atom();
if(uri == null || !eq(uri, muri)) {
ctx.ns.add(new QNm(tname.pref(), tname.uri()), ii);
nsc.add(pref, muri);
- } else if(!eq(pref, EMPTY) && !eq(pref, XML) && !nsc.contains(pref)) {
+ } else if(!nsc.contains(pref) && !(eq(pref, EMPTY) && eq(uri, EMPTY))) {
nsc.add(pref, uri);
}
} else if(uri != null) {
tname.uri(uri);
}
}
final Constr c = new Constr(ii, ctx, expr);
if(c.errAtt) NOATTALL.thrw(input);
if(c.duplAtt != null) (comp ? CATTDUPL : ATTDUPL).thrw(input, c.duplAtt);
final FElem node = new FElem(tname, c.children, c.atts, c.base, nsc, null);
for(int n = 0; n < c.children.size(); ++n) c.children.get(n).parent(node);
for(int n = 0; n < c.atts.size(); ++n) {
final ANode att = c.atts.get(n);
final QNm name = att.qname();
if(name.ns() && name.hasUri()) {
final byte[] apre = name.pref(), auri = name.uri().atom();
final int pos = nsc.get(apre);
if(pos == -1) {
nsc.add(apre, auri);
} else if(!eq(nsc.val[pos], auri)) {
// [LK][CG] XQuery/Namespaces: create new prefix
}
}
att.parent(node);
}
ctx.ns.size(s);
return node;
}
@Override
public Expr remove(final Var v) {
tag = tag.remove(v);
return super.remove(v);
}
@Override
public boolean uses(final Use u) {
return tag.uses(u) || super.uses(u);
}
@Override
public int count(final Var v) {
return tag.count(v) + super.count(v);
}
@Override
public void plan(final Serializer ser) throws IOException {
ser.openElement(this);
tag.plan(ser);
for(final Expr e : expr) e.plan(ser);
ser.closeElement();
}
@Override
public String desc() {
return info(QueryTokens.ELEMENT);
}
@Override
public String toString() {
return toString(Token.string(NodeType.ELM.nam) + " { " + tag + " }");
}
}
| true | true | public FElem item(final QueryContext ctx, final InputInfo ii)
throws QueryException {
final Item it = checkItem(tag, ctx);
final int s = ctx.ns.size();
addNS(ctx);
// clone namespaces for context sensitive operations
final Atts nsc = new Atts();
for(int i = 0; i < nsp.size; ++i) nsc.add(nsp.key[i], nsp.val[i]);
final QNm tname = checkNS(qname(ctx, it, false, ii));
final byte[] pref = tname.pref();
if(!eq(pref, XML)) {
byte[] uri = ctx.ns.find(pref);
if(uri == null) uri = NSGlobal.uri(pref);
if(tname.hasUri()) {
final byte[] muri = tname.uri().atom();
if(uri == null || !eq(uri, muri)) {
ctx.ns.add(new QNm(tname.pref(), tname.uri()), ii);
nsc.add(pref, muri);
} else if(!eq(pref, EMPTY) && !eq(pref, XML) && !nsc.contains(pref)) {
nsc.add(pref, uri);
}
} else if(uri != null) {
tname.uri(uri);
}
}
final Constr c = new Constr(ii, ctx, expr);
if(c.errAtt) NOATTALL.thrw(input);
if(c.duplAtt != null) (comp ? CATTDUPL : ATTDUPL).thrw(input, c.duplAtt);
final FElem node = new FElem(tname, c.children, c.atts, c.base, nsc, null);
for(int n = 0; n < c.children.size(); ++n) c.children.get(n).parent(node);
for(int n = 0; n < c.atts.size(); ++n) {
final ANode att = c.atts.get(n);
final QNm name = att.qname();
if(name.ns() && name.hasUri()) {
final byte[] apre = name.pref(), auri = name.uri().atom();
final int pos = nsc.get(apre);
if(pos == -1) {
nsc.add(apre, auri);
} else if(!eq(nsc.val[pos], auri)) {
// [LK][CG] XQuery/Namespaces: create new prefix
}
}
att.parent(node);
}
ctx.ns.size(s);
return node;
}
| public FElem item(final QueryContext ctx, final InputInfo ii)
throws QueryException {
final Item it = checkItem(tag, ctx);
final int s = ctx.ns.size();
addNS(ctx);
// clone namespaces for context sensitive operations
final Atts nsc = new Atts();
for(int i = 0; i < nsp.size; ++i) nsc.add(nsp.key[i], nsp.val[i]);
final QNm tname = checkNS(qname(ctx, it, false, ii));
final byte[] pref = tname.pref();
if(!eq(pref, XML)) {
byte[] uri = ctx.ns.find(pref);
if(uri == null) uri = NSGlobal.uri(pref);
if(tname.hasUri()) {
final byte[] muri = tname.uri().atom();
if(uri == null || !eq(uri, muri)) {
ctx.ns.add(new QNm(tname.pref(), tname.uri()), ii);
nsc.add(pref, muri);
} else if(!nsc.contains(pref) && !(eq(pref, EMPTY) && eq(uri, EMPTY))) {
nsc.add(pref, uri);
}
} else if(uri != null) {
tname.uri(uri);
}
}
final Constr c = new Constr(ii, ctx, expr);
if(c.errAtt) NOATTALL.thrw(input);
if(c.duplAtt != null) (comp ? CATTDUPL : ATTDUPL).thrw(input, c.duplAtt);
final FElem node = new FElem(tname, c.children, c.atts, c.base, nsc, null);
for(int n = 0; n < c.children.size(); ++n) c.children.get(n).parent(node);
for(int n = 0; n < c.atts.size(); ++n) {
final ANode att = c.atts.get(n);
final QNm name = att.qname();
if(name.ns() && name.hasUri()) {
final byte[] apre = name.pref(), auri = name.uri().atom();
final int pos = nsc.get(apre);
if(pos == -1) {
nsc.add(apre, auri);
} else if(!eq(nsc.val[pos], auri)) {
// [LK][CG] XQuery/Namespaces: create new prefix
}
}
att.parent(node);
}
ctx.ns.size(s);
return node;
}
|
diff --git a/src/java/macromedia/asc/parser/Scanner.java b/src/java/macromedia/asc/parser/Scanner.java
index eb1ba99..8e38a8b 100644
--- a/src/java/macromedia/asc/parser/Scanner.java
+++ b/src/java/macromedia/asc/parser/Scanner.java
@@ -1,1619 +1,1619 @@
////////////////////////////////////////////////////////////////////////////////
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2004-2007 Adobe Systems Incorporated
// All Rights Reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file
// in accordance with the terms of the license agreement accompanying it.
//
////////////////////////////////////////////////////////////////////////////////
/*
* Written by Jeff Dyer
* Copyright (c) 1998-2003 Mountain View Compiler Company
* All rights reserved.
*/
package macromedia.asc.parser;
//import java.util.concurrent.*;
import java.util.HashMap;
import macromedia.asc.util.*;
import macromedia.asc.embedding.ErrorConstants;
import java.io.InputStream;
import static macromedia.asc.parser.Tokens.*;
import static macromedia.asc.parser.States.*;
import static macromedia.asc.parser.CharacterClasses.*;
import static macromedia.asc.embedding.avmplus.Features.*;
/**
* Partitions input character stream into tokens.
*
* @author Jeff Dyer
*/
public final class Scanner implements ErrorConstants
{
private static final boolean debug = false;
/*
* Scanner maintains a notion of a single current token
* The Token.java class is not used anymore. It might get repurposed as a enum of token names.
* We should also upgrade a Token to contain source seekpos,line,column information, so we can throw away the line table,
* which would mean we also dont need to buffer source after scanning, since we could reread it if an error/warning/info
* line print was requested.
*/
private class Tok {
int id;
String text;
}
private Tok currentToken;
private boolean isFirstTokenOnLine;
private boolean save_comments;
private Context ctx;
public InputBuffer input;
private static final HashMap<String,Integer> reservedWord;
static {
reservedWord = new HashMap<String,Integer>(64);
reservedWord.put("as",AS_TOKEN); // ??? predicated on HAS_ASOPERATOR
reservedWord.put("break",BREAK_TOKEN);
reservedWord.put("case",CASE_TOKEN);
reservedWord.put("catch",CATCH_TOKEN);
reservedWord.put("class",CLASS_TOKEN);
reservedWord.put("const",CONST_TOKEN);
reservedWord.put("continue",CONTINUE_TOKEN);
reservedWord.put("default",DEFAULT_TOKEN);
reservedWord.put("delete",DELETE_TOKEN);
reservedWord.put("do",DO_TOKEN);
reservedWord.put("else",ELSE_TOKEN);
reservedWord.put("extends",EXTENDS_TOKEN);
reservedWord.put("false",FALSE_TOKEN);
reservedWord.put("finally",FINALLY_TOKEN);
reservedWord.put("for",FOR_TOKEN);
reservedWord.put("function",FUNCTION_TOKEN);
reservedWord.put("get",GET_TOKEN);
reservedWord.put("if",IF_TOKEN);
reservedWord.put("implements",IMPLEMENTS_TOKEN);
reservedWord.put("import",IMPORT_TOKEN);
reservedWord.put("in",IN_TOKEN);
reservedWord.put("include",INCLUDE_TOKEN);
reservedWord.put("instanceof",INSTANCEOF_TOKEN);
reservedWord.put("interface",INTERFACE_TOKEN);
reservedWord.put("is",IS_TOKEN); //??? predicated on HAS_ISOPERATOR
reservedWord.put("namespace",NAMESPACE_TOKEN);
reservedWord.put("new",NEW_TOKEN);
reservedWord.put("null",NULL_TOKEN);
reservedWord.put("package",PACKAGE_TOKEN);
reservedWord.put("private",PRIVATE_TOKEN);
reservedWord.put("protected",PROTECTED_TOKEN);
reservedWord.put("public",PUBLIC_TOKEN);
reservedWord.put("return",RETURN_TOKEN);
reservedWord.put("set",SET_TOKEN);
reservedWord.put("super",SUPER_TOKEN);
reservedWord.put("switch",SWITCH_TOKEN);
reservedWord.put("this",THIS_TOKEN);
reservedWord.put("throw",THROW_TOKEN);
reservedWord.put("true",TRUE_TOKEN);
reservedWord.put("try",TRY_TOKEN);
reservedWord.put("typeof",TYPEOF_TOKEN);
reservedWord.put("use",USE_TOKEN);
reservedWord.put("var",VAR_TOKEN);
reservedWord.put("void",VOID_TOKEN);
reservedWord.put("while",WHILE_TOKEN);
reservedWord.put("with",WITH_TOKEN);
}
/*
* Scanner constructors.
*/
private void init(Context cx, boolean save_comments)
{
ctx = cx;
state = start_state;
level = 0;
inXML = 0;
states = new IntList();
levels = new IntList();
this.save_comments = save_comments;
currentToken = new Tok();
}
public Scanner(Context cx, InputStream in, String encoding, String origin){this(cx,in,encoding,origin,true);}
public Scanner(Context cx, InputStream in, String encoding, String origin, boolean save_comments)
{
init(cx,save_comments);
this.input = new InputBuffer(in, encoding, origin);
cx.input = this.input;
}
public Scanner(Context cx, String in, String origin){this(cx,in,origin,true);}
public Scanner(Context cx, String in, String origin, boolean save_comments)
{
init(cx,save_comments);
this.input = new InputBuffer(in, origin);
cx.input = this.input; // FIXME: how nicely external state altering.
}
/**
* This contructor is used by Flex direct AST generation. It
* allows Flex to pass in a specialized InputBuffer.
*/
public Scanner(Context cx, InputBuffer input)
{
init(cx,true);
this.input = input;
cx.input = input; // so now we get to look around to find out who does this...
}
/**
* nextchar() --just fetch the next char
*/
private char nextchar()
{
return (char) input.nextchar();
}
/*
* retract() --
* Causes one character of input to be 'put back' onto the
* queue. [Test whether this works for comments and white space.]
*/
public void retract()
{
input.retract();
}
/**
* @return makeToken( +1 from current char pos in InputBuffer
*/
private int pos()
{
return input.textPos();
}
/**
* set mark position
*/
private void mark()
{
input.textMark();
}
private final int makeToken(int id, String text)
{
currentToken.id = id;
currentToken.text = text;
return id;
}
private final int makeToken(int id)
{
currentToken.id = id;
currentToken.text = null;
return id;
}
/*
* Get the text of the current token
*/
public String getCurrentTokenText()
{
if (currentToken.text == null)
{
error("Scanner internal: current token not a pseudo-terminal");
}
return currentToken.text;
}
/*
* A slightly confusing hack, returns the current token text or the text of the token type (Class)
* Gets used in generating error messages or strings used in later concatenations.
*/
public String getCurrentTokenTextOrTypeText(int id)
{
if (currentToken.text != null)
{
return currentToken.text;
}
return Token.getTokenClassName(id);
}
/*
* Strips quotes and returns text of literal string token as well as info about whether it was single quoted or not
* Makes me wonder if leaving the quotes on strings is ever used...if not we could save what the quoting was and strip these up front.
*/
public String getCurrentStringTokenText(boolean[] is_single_quoted )
{
if (currentToken.id != STRINGLITERAL_TOKEN || currentToken.text==null)
{
error("internal: string token expected.");
}
String fulltext = currentToken.text;
is_single_quoted[0] = (fulltext.charAt(0) == '\'' ? true : false);
String enclosedText = fulltext.substring(1, fulltext.length() - 1);
return enclosedText;
}
/*
* Record an error.
*/
private void error(int kind, String arg)
{
StringBuilder out = new StringBuilder();
String origin = this.input.origin;
int errPos = input.positionOfMark(); // note use of source adjusted position
int ln = input.getLnNum(errPos);
int col = input.getColPos(errPos);
String msg = (ContextStatics.useVerboseErrors ? "[Compiler] Error #" + kind + ": " : "") + ctx.errorString(kind);
if(debug)
{
msg = "[Scanner] " + msg;
}
int nextLoc = Context.replaceStringArg(out, msg, 0, arg);
if (nextLoc != -1) // append msg remainder after replacement point, if any
out.append(msg.substring(nextLoc, msg.length()));
ctx.localizedError(origin,ln,col,out.toString(),input.getLineText(errPos), kind);
skiperror(kind);
}
private void error(String msg)
{
ctx.internalError(msg);
error(kError_Lexical_General, msg);
}
private void error(int kind)
{
error(kind, "");
}
/*
* skip ahead after an error is detected. this simply goes until the next
* whitespace or end of input.
*/
private void skiperror()
{
skiperror(kError_Lexical_General);
}
private void skiperror(int kind)
{
//Debugger::trace("skipping error\n");
switch (kind)
{
case kError_Lexical_General:
return;
case kError_Lexical_LineTerminatorInSingleQuotedStringLiteral:
case kError_Lexical_LineTerminatorInDoubleQuotedStringLiteral:
while (true)
{
char nc = nextchar();
if (nc == '\'' || nc == 0)
{
return;
}
}
case kError_Lexical_SyntaxError:
default:
while (true)
{
char nc = nextchar();
if (nc == ';' || nc == '\n' || nc == '\r' || nc == 0)
{
return;
}
}
}
}
/*
*
*
*/
public boolean followsLineTerminator()
{
if (debug)
{
System.out.println("isFirstTokenOnLine = " + isFirstTokenOnLine);
}
return isFirstTokenOnLine;
}
/*
*
*
*/
public int state;
private int level;
private int inXML = 0;
private IntList states;
private IntList levels;
public void pushState()
{
states.add(state);
levels.add(level);
state = start_state;
level = 0;
inXML++;
}
public void popState()
{
state = states.removeLast();
level = levels.removeLast();
if ( inXML > 0) inXML--;
}
private StringBuilder getDocTextBuffer(String doctagname)
{
StringBuilder doctextbuf = new StringBuilder();
doctextbuf.append("<").append(doctagname).append("><![CDATA[");
return doctextbuf;
}
public void clearUnusedBuffers()
{
input.clearUnusedBuffers();
input = null;
}
/*
*
*
*/
public int nexttoken(boolean resetState)
{
String doctagname = "description";
StringBuilder doctextbuf = null;
int startofxml = pos();
StringBuilder blockcommentbuf = null;
char regexp_flags = 0; // used to track option flags encountered in a regexp expression. Initialized in regexp_state
boolean maybe_reserved = false;
char c = 0;
if (resetState)
{
isFirstTokenOnLine = false;
}
while (true)
{
if (debug)
{
System.out.println("state = " + state + ", next = " + pos());
}
switch (state)
{
case start_state:
{
c = nextchar();
mark();
switch (c)
{
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
maybe_reserved = true;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
case '_': case '$':
state = A_state;
continue;
case 0xffef: // could not have worked...case 0xffffffef: // ??? not in Character type range ???
if (nextchar()==0xffffffbb &&
nextchar()==0xffffffbf)
{
// ISSUE: set encoding scheme to utf-8, and implement support for utf8
state = start_state;
}
else
{
state = error_state;
}
continue;
case '@':
return makeToken( ATSIGN_TOKEN );
case '\'':
case '\"':
{
char startquote = (char) c;
boolean needs_escape = false;
while ( (c=nextchar()) != startquote )
{
if ( c == '\\' )
{
needs_escape = true;
c = nextchar();
// special case: escaped eol strips crlf or lf
if ( c == '\r' )
c = nextchar();
if ( c == '\n' )
continue;
}
else if ( c == '\r' || c == '\n' )
{
if ( startquote == '\'' )
error(kError_Lexical_LineTerminatorInSingleQuotedStringLiteral);
else
error(kError_Lexical_LineTerminatorInDoubleQuotedStringLiteral);
break;
}
else if ( c == 0 )
{
error(kError_Lexical_EndOfStreamInStringLiteral);
return makeToken( EOS_TOKEN );
}
}
return makeToken(STRINGLITERAL_TOKEN, input.copyReplaceStringEscapes(needs_escape));
}
case '-': // tokens: -- -= -
switch (nextchar())
{
case '-':
return makeToken( MINUSMINUS_TOKEN );
case '=':
return makeToken( MINUSASSIGN_TOKEN );
default:
retract();
return makeToken( MINUS_TOKEN );
}
case '!': // tokens: ! != !===
if (nextchar()=='=')
{
if (nextchar()=='=')
return makeToken( STRICTNOTEQUALS_TOKEN );
retract();
return makeToken( NOTEQUALS_TOKEN );
}
retract();
return makeToken( NOT_TOKEN );
case '%': // tokens: % %=
switch (nextchar())
{
case '=':
return makeToken( MODULUSASSIGN_TOKEN );
default:
retract();
return makeToken( MODULUS_TOKEN );
}
case '&': // tokens: & &= && &&=
c = nextchar();
if (c=='=')
return makeToken( BITWISEANDASSIGN_TOKEN );
if (c=='&')
{
if (nextchar()=='=')
return makeToken( LOGICALANDASSIGN_TOKEN );
retract();
return makeToken( LOGICALAND_TOKEN );
}
retract();
return makeToken( BITWISEAND_TOKEN );
case '#': // # is short for use
if (HAS_HASHPRAGMAS)
{
return makeToken( USE_TOKEN );
}
state = error_state;
continue;
case '(':
return makeToken( LEFTPAREN_TOKEN );
case ')':
return makeToken( RIGHTPAREN_TOKEN );
case '*': // tokens: *= *
if (nextchar()=='=')
return makeToken( MULTASSIGN_TOKEN );
retract();
return makeToken( MULT_TOKEN );
case ',':
return makeToken( COMMA_TOKEN );
case '.':
state = dot_state;
continue;
case '/':
state = slash_state;
continue;
case ':': // tokens: : ::
if (nextchar()==':')
{
return makeToken( DOUBLECOLON_TOKEN );
}
retract();
return makeToken( COLON_TOKEN );
case ';':
return makeToken( SEMICOLON_TOKEN );
case '?':
return makeToken( QUESTIONMARK_TOKEN );
case '[':
return makeToken( LEFTBRACKET_TOKEN );
case ']':
return makeToken( RIGHTBRACKET_TOKEN );
case '^': // tokens: ^= ^
if (nextchar()=='=')
return makeToken( BITWISEXORASSIGN_TOKEN );
retract();
return makeToken( BITWISEXOR_TOKEN );
case '{':
return makeToken( LEFTBRACE_TOKEN );
case '|': // tokens: | |= || ||=
c = nextchar();
if (c=='=')
return makeToken( BITWISEORASSIGN_TOKEN );
if (c=='|')
{
if (nextchar()=='=')
return makeToken( LOGICALORASSIGN_TOKEN );
retract();
return makeToken( LOGICALOR_TOKEN );
}
retract();
return makeToken( BITWISEOR_TOKEN );
case '}':
return makeToken( RIGHTBRACE_TOKEN );
case '~':
return makeToken( BITWISENOT_TOKEN );
case '+': // tokens: ++ += +
c = nextchar();
if (c=='+')
return makeToken( PLUSPLUS_TOKEN );
if (c=='=')
return makeToken( PLUSASSIGN_TOKEN );
retract();
return makeToken( PLUS_TOKEN );
case '<':
switch (nextchar())
{
case '<': // tokens: << <<=
if (nextchar()=='=')
return makeToken( LEFTSHIFTASSIGN_TOKEN );
retract();
return makeToken( LEFTSHIFT_TOKEN );
case '=':
return makeToken( LESSTHANOREQUALS_TOKEN );
case '/':
return makeToken( XMLTAGSTARTEND_TOKEN );
case '!':
state = xmlcommentorcdatastart_state;
continue;
case '?':
state = xmlpi_state;
continue;
}
retract();
return makeToken( LESSTHAN_TOKEN );
case '=': // tokens: === == =
if (nextchar()=='=')
{
if (nextchar()=='=')
return makeToken( STRICTEQUALS_TOKEN );
retract();
return makeToken( EQUALS_TOKEN );
}
retract();
return makeToken( ASSIGN_TOKEN );
case '>': // tokens: > >= >> >>= >>> >>>=
state = start_state;
switch ( nextchar() )
{
case '>':
switch (nextchar())
{
case '>':
if (nextchar()=='=')
return makeToken( UNSIGNEDRIGHTSHIFTASSIGN_TOKEN );
retract();
return makeToken( UNSIGNEDRIGHTSHIFT_TOKEN );
case '=':
return makeToken( RIGHTSHIFTASSIGN_TOKEN );
default:
retract();
return makeToken( RIGHTSHIFT_TOKEN );
}
case '=':
return makeToken( GREATERTHANOREQUALS_TOKEN );
}
retract();
return makeToken( GREATERTHAN_TOKEN );
case '0':
state = zero_state;
continue;
case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimalinteger_state;
continue;
case ' ': // ascii range white space
case '\t':
case 0x000b:
case 0x000c:
case 0x0085:
case 0x00a0:
continue;
case '\n': // ascii line terminators.
case '\r':
isFirstTokenOnLine = true;
continue;
case 0:
return makeToken( EOS_TOKEN );
default:
switch (input.nextcharClass((char)c,true))
{
case Lu: case Ll: case Lt: case Lm: case Lo: case Nl:
maybe_reserved = false;
state = A_state;
continue;
case Zs:// unicode whitespace and control-characters
case Cc:
case Cf:
continue;
case Zl:// unicode line terminators
case Zp:
isFirstTokenOnLine = true;
continue;
default:
state = error_state;
continue;
}
}
}
/*
* prefix: <letter>
*/
case A_state:
{
boolean needs_escape = c == '\\'; // ??? really should only be true if the word started with a backslash
while ( true ){
c = nextchar();
if ( c >= 'a' && c <= 'z' )
{
continue;
}
if ( (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '$' || c == '_' ){
maybe_reserved = false;
continue;
}
if ( c <= 0x7f ) // in ascii range & mostly not a valid char
{
if ( c == '\\' )
{
needs_escape = true; // close enough, we just want to minimize rescans for unicode escapes
}
else {
retract();
break;
}
}
// else outside ascii range (or an escape sequence )
switch (input.nextcharClass(c,false))
{
case Lu: case Ll: case Lt: case Lm: case Lo: case Nl: case Mn: case Mc: case Nd: case Pc:
maybe_reserved = false;
input.nextcharClass(c,true); // advance input cursor
continue;
}
retract();
break;
}
state = start_state;
String s = input.copyReplaceUnicodeEscapes(needs_escape);
if ( maybe_reserved )
{
Integer i = reservedWord.get(s);
if ( i != null )
return makeToken( (int) i );
}
return makeToken(IDENTIFIER_TOKEN,s);
}
/*
* prefix: 0
* accepts: 0x... | 0X... | 01... | 0... | 0
*/
case zero_state:
switch (nextchar())
{
case 'x':
case 'X':
switch(nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F':
state = hexinteger_state;
break;
default:
state = start_state;
error(kError_Lexical_General);
}
continue;
case '.':
state = decimal_state;
continue;
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimalinteger_state;
continue;
case 'E':
case 'e':
state = exponentstart_state;
continue;
case 'd':
case 'm':
case 'i':
case 'u':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: 0x<hex digits>
* accepts: 0x123f
*/
case hexinteger_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F':
state = hexinteger_state;
continue;
case 'u':
case 'i':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken( NUMBERLITERAL_TOKEN, input.copy() );
default:
retract();
state = start_state;
return makeToken( NUMBERLITERAL_TOKEN, input.copy() );
}
/*
* prefix: .
* accepts: .123 | .
*/
case dot_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimal_state;
continue;
case '.':
state = start_state;
if (nextchar()=='.')
return makeToken( TRIPLEDOT_TOKEN );
retract();
return makeToken( DOUBLEDOT_TOKEN );
case '<':
state = start_state;
return makeToken( DOTLESSTHAN_TOKEN );
default:
retract();
state = start_state;
return makeToken( DOT_TOKEN );
}
/*
* prefix: N
* accepts: 0.123 | 1.23 | 123 | 1e23 | 1e-23
*/
case decimalinteger_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimalinteger_state;
continue;
case '.':
state = decimal_state;
continue;
case 'd':
case 'm':
case 'u':
case 'i':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
case 'E':
case 'e':
state = exponentstart_state;
continue;
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: N.
* accepts: 0.1 | 1e23 | 1e-23
*/
case decimal_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimal_state;
continue;
case 'd':
case 'm':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
case 'E':
case 'e':
state = exponentstart_state;
continue;
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: ..e
* accepts: ..eN | ..e+N | ..e-N
*/
case exponentstart_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
case '+':
case '-':
state = exponent_state;
continue;
default:
error(kError_Lexical_General);
state = start_state;
continue;
// Issue: needs specific error here.
}
/*
* prefix: ..e
* accepts: ..eN | ..e+N | ..e-N
*/
case exponent_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = exponent_state;
continue;
case 'd':
case 'm':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: /
*/
case slash_state:
{
c = nextchar();
switch (c)
{
case '/': // line comment
state = start_state;
line_comment:
while ( (c=nextchar()) != 0)
{
if ( c == '\r' || c == '\n' )
{
isFirstTokenOnLine = true;
if (save_comments == false)
{
break line_comment;
}
retract(); // don't include newline in line comment. (Sec 7.3)
return makeToken( SLASHSLASHCOMMENT_TOKEN, input.copyReplaceUnicodeEscapes() );
}
}
continue;
case '*':
if (save_comments == false)
{
block_comment:
while ( (c=nextchar()) != 0)
{
if ( c == '\r' || c == '\n' )
isFirstTokenOnLine = true;
if (c == '*')
{
c = nextchar();
if (c == '/' )
{
break block_comment;
}
retract();
}
}
state = start_state;
}
else
{
if (blockcommentbuf == null)
blockcommentbuf = new StringBuilder();
blockcommentbuf.append("/*");
state = blockcommentstart_state;
}
continue;
case '>':
- if ( inXML > 0) // ignore this if outside an XML context
+ // FIXME: Not exactly right???if ( inXML > 0) // ignore this if outside an XML context
{
state = start_state;
return makeToken( XMLTAGENDEND_TOKEN );
}
// FALL THROUGH
default:
// If the last token read is any of these, then the '/' must start a div or div_assign...
int lb = currentToken.id;
if ( lb == IDENTIFIER_TOKEN || lb == NUMBERLITERAL_TOKEN || lb == RIGHTPAREN_TOKEN ||
lb == RIGHTBRACE_TOKEN || lb == RIGHTBRACKET_TOKEN )
{
/*
* tokens: /= /
*/
state = start_state;
if (c=='=')
return makeToken( DIVASSIGN_TOKEN );
retract();
return makeToken( DIV_TOKEN );
}
state = slashregexp_state;
retract();
continue;
}
}
/*
* tokens: /<regexpbody>/<regexpflags>
*/
case slashregexp_state:
switch (nextchar())
{
case '\\':
nextchar();
continue;
case '/':
regexp_flags = 0;
state = regexp_state;
continue;
case 0:
case '\n':
case '\r':
error(kError_Lexical_General);
state = start_state;
continue;
default:
state = slashregexp_state;
continue;
}
/*
* tokens: g | i | m | s | x . Note that s and x are custom extentions to match perl's functionality
* Also note we handle this via an array of boolean flags intead of state change logic.
* (5,1) + (5,2) + (5,3) + (5,4) + (5,5) is just too many states to handle this via state logic
*/
case regexp_state:
c = nextchar();
switch ( c )
{
case 'g':
if ((regexp_flags & 0x01) == 0)
{
regexp_flags |= 0x01;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 'i':
if ((regexp_flags & 0x02) == 0)
{
regexp_flags |= 0x02;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 'm':
if ((regexp_flags & 0x04) == 0)
{
regexp_flags |= 0x04;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 's':
if ((regexp_flags & 0x08) == 0)
{
regexp_flags |= 0x08;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 'x':
if ((regexp_flags & 0x10) == 0)
{
regexp_flags |= 0x10;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
default:
if (Character.isJavaIdentifierPart(c))
{
error(kError_Lexical_General);
state = start_state;
continue;
}
retract();
state = start_state;
return makeToken( REGEXPLITERAL_TOKEN, input.copyReplaceUnicodeEscapes());
}
/*
* prefix: <!
*/
case xmlcommentorcdatastart_state:
switch ( nextchar() )
{
case '[':
if (nextchar()=='C' &&
nextchar()=='D' &&
nextchar()=='A' &&
nextchar()=='T' &&
nextchar()=='A' &&
nextchar()=='[')
{
state = xmlcdata_state;
continue;
}
break; // error
case '-':
if (nextchar()=='-')
{
state = xmlcomment_state;
continue;
}
}
error(kError_Lexical_General);
state = start_state;
continue;
case xmlcdata_state:
switch ( nextchar() )
{
case ']':
if (nextchar()==']' && nextchar()=='>')
{
state = start_state;
return makeToken(XMLMARKUP_TOKEN,input.substringReplaceUnicodeEscapes(startofxml,pos()));
}
continue;
case 0:
error(kError_Lexical_General);
state = start_state;
}
continue;
case xmlcomment_state:
while ( (c=nextchar()) != '-' && c != 0 )
;
if (c=='-' && nextchar() != '-')
{
continue;
}
// got -- if next is > ok else error
if ( nextchar()=='>')
{
state = start_state;
return makeToken(XMLMARKUP_TOKEN,input.substringReplaceUnicodeEscapes(startofxml,pos()));
}
error(kError_Lexical_General);
state = start_state;
continue;
case xmlpi_state:
while ( (c=nextchar()) != '?' && c != 0 )
;
if (c=='?' && nextchar() == '>')
{
state = start_state;
return makeToken(XMLMARKUP_TOKEN,input.substringReplaceUnicodeEscapes(startofxml,pos()));
}
if (c==0)
{
error(kError_Lexical_General);
state = start_state;
}
continue;
case xmltext_state:
{
switch(nextchar())
{
case '<': case '{':
{
retract();
String xmltext = input.substringReplaceUnicodeEscapes(startofxml,pos());
if( xmltext != null )
{
state = start_state;
return makeToken(XMLTEXT_TOKEN,xmltext);
}
else // if there is no leading text, then just return punctuation token to avoid empty text tokens
{
switch(nextchar())
{
case '<':
switch( nextchar() )
{
case '/': state = start_state; return makeToken( XMLTAGSTARTEND_TOKEN );
case '!': state = xmlcommentorcdatastart_state; continue;
case '?': state = xmlpi_state; continue;
default: retract(); state = start_state; return makeToken( LESSTHAN_TOKEN );
}
case '{':
state = start_state;
return makeToken( LEFTBRACE_TOKEN );
}
}
}
case 0:
state = start_state;
return makeToken( EOS_TOKEN );
}
continue;
}
case xmlliteral_state:
switch (nextchar())
{
case '{': // return makeToken( XMLPART_TOKEN
return makeToken(XMLPART_TOKEN, input.substringReplaceUnicodeEscapes(startofxml, pos()-1));
case '<':
if (nextchar()=='/')
{
--level;
nextchar();
mark();
retract();
state = endxmlname_state;
}
else
{
++level;
state = xmlliteral_state;
}
continue;
case '/':
if (nextchar()=='>')
{
--level;
if (level == 0)
{
state = start_state;
return makeToken(XMLLITERAL_TOKEN, input.substringReplaceUnicodeEscapes(startofxml, pos()+1));
}
}
continue;
case 0:
retract();
error(kError_Lexical_NoMatchingTag);
state = start_state;
continue;
default:
continue;
}
case endxmlname_state:
c = nextchar();
if (Character.isJavaIdentifierPart(c)||c==':')
{
continue;
}
switch(c)
{
case '{': // return makeToken( XMLPART_TOKEN
{
String xmltext = input.substringReplaceUnicodeEscapes(startofxml, pos()-1);
return makeToken(XMLPART_TOKEN, xmltext);
}
case '>':
retract();
nextchar();
if (level == 0)
{
String xmltext = input.substringReplaceUnicodeEscapes(startofxml, pos()+1);
state = start_state;
return makeToken(XMLLITERAL_TOKEN, xmltext);
}
state = xmlliteral_state;
continue;
default:
state = xmlliteral_state;
continue;
}
/*
* prefix: /*
*/
case blockcommentstart_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '*':
if ( nextchar() == '/' ){
state = start_state;
return makeToken( BLOCKCOMMENT_TOKEN, new String());
}
retract();
state = doccomment_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
case '\n':
case '\r':
isFirstTokenOnLine = true;
default:
state = blockcomment_state;
continue;
}
}
/*
* prefix: /**
*/
case doccomment_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '*':
state = doccommentstar_state;
continue;
case '@':
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
if( doctagname.length() > 0 )
{
doctextbuf.append("]]></").append(doctagname).append(">");
}
doctagname = "";
state = doccommenttag_state;
continue;
case '\r':
case '\n':
isFirstTokenOnLine = true;
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
doctextbuf.append('\n');
state = doccomment_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
doctextbuf.append((char)(c));
state = doccomment_state;
continue;
}
}
case doccommentstar_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '/':
{
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
if( doctagname.length() > 0 )
{
doctextbuf.append("]]></").append(doctagname).append(">");
}
String doctext = doctextbuf.toString(); // ??? does this needs escape conversion ???
state = start_state;
return makeToken(DOCCOMMENT_TOKEN,doctext);
}
case '*':
state = doccommentstar_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
state = doccomment_state;
continue;
// if not a slash, then keep looking for an end comment.
}
}
/*
* prefix: @
*/
case doccommenttag_state:
{
c = nextchar();
switch ( c )
{
case '*':
state = doccommentstar_state;
continue;
case ' ': case '\t': case '\r': case '\n':
{
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
// skip extra whitespace --fixes bug on tag text parsing
// --but really, the problem is not here, it's in whatever reads asdoc output..
// --So if that gets fixed, feel free to delete the following.
while ( (c=nextchar()) == ' ' || c == '\t' )
;
retract();
if( doctagname.length() > 0 )
{
doctextbuf.append("\n<").append(doctagname).append("><![CDATA[");
}
state = doccomment_state;
continue;
}
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
doctagname += (char)(c);
continue;
}
}
/*
* prefix: /**
*/
case doccommentvalue_state:
switch ( nextchar() )
{
case '*':
state = doccommentstar_state;
continue;
case '@':
state = doccommenttag_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
state = doccomment_state;
continue;
}
/*
* prefix: /*
*/
case blockcomment_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '*': state = blockcommentstar_state; continue;
case '\r': case '\n': isFirstTokenOnLine = true;
state = blockcomment_state; continue;
case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue;
default: state = blockcomment_state; continue;
}
}
case blockcommentstar_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '/':
{
state = start_state;
String blocktext = blockcommentbuf.toString(); // ??? needs escape conversion
return makeToken( BLOCKCOMMENT_TOKEN, blocktext );
}
case '*': state = blockcommentstar_state; continue;
case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue;
default: state = blockcomment_state; continue;
// if not a slash, then keep looking for an end comment.
}
}
/*
* skip error
*/
case error_state:
error(kError_Lexical_General);
skiperror();
state = start_state;
continue;
default:
error("invalid scanner state");
state = start_state;
return makeToken(EOS_TOKEN);
}
}
}
}
| true | true | public int nexttoken(boolean resetState)
{
String doctagname = "description";
StringBuilder doctextbuf = null;
int startofxml = pos();
StringBuilder blockcommentbuf = null;
char regexp_flags = 0; // used to track option flags encountered in a regexp expression. Initialized in regexp_state
boolean maybe_reserved = false;
char c = 0;
if (resetState)
{
isFirstTokenOnLine = false;
}
while (true)
{
if (debug)
{
System.out.println("state = " + state + ", next = " + pos());
}
switch (state)
{
case start_state:
{
c = nextchar();
mark();
switch (c)
{
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
maybe_reserved = true;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
case '_': case '$':
state = A_state;
continue;
case 0xffef: // could not have worked...case 0xffffffef: // ??? not in Character type range ???
if (nextchar()==0xffffffbb &&
nextchar()==0xffffffbf)
{
// ISSUE: set encoding scheme to utf-8, and implement support for utf8
state = start_state;
}
else
{
state = error_state;
}
continue;
case '@':
return makeToken( ATSIGN_TOKEN );
case '\'':
case '\"':
{
char startquote = (char) c;
boolean needs_escape = false;
while ( (c=nextchar()) != startquote )
{
if ( c == '\\' )
{
needs_escape = true;
c = nextchar();
// special case: escaped eol strips crlf or lf
if ( c == '\r' )
c = nextchar();
if ( c == '\n' )
continue;
}
else if ( c == '\r' || c == '\n' )
{
if ( startquote == '\'' )
error(kError_Lexical_LineTerminatorInSingleQuotedStringLiteral);
else
error(kError_Lexical_LineTerminatorInDoubleQuotedStringLiteral);
break;
}
else if ( c == 0 )
{
error(kError_Lexical_EndOfStreamInStringLiteral);
return makeToken( EOS_TOKEN );
}
}
return makeToken(STRINGLITERAL_TOKEN, input.copyReplaceStringEscapes(needs_escape));
}
case '-': // tokens: -- -= -
switch (nextchar())
{
case '-':
return makeToken( MINUSMINUS_TOKEN );
case '=':
return makeToken( MINUSASSIGN_TOKEN );
default:
retract();
return makeToken( MINUS_TOKEN );
}
case '!': // tokens: ! != !===
if (nextchar()=='=')
{
if (nextchar()=='=')
return makeToken( STRICTNOTEQUALS_TOKEN );
retract();
return makeToken( NOTEQUALS_TOKEN );
}
retract();
return makeToken( NOT_TOKEN );
case '%': // tokens: % %=
switch (nextchar())
{
case '=':
return makeToken( MODULUSASSIGN_TOKEN );
default:
retract();
return makeToken( MODULUS_TOKEN );
}
case '&': // tokens: & &= && &&=
c = nextchar();
if (c=='=')
return makeToken( BITWISEANDASSIGN_TOKEN );
if (c=='&')
{
if (nextchar()=='=')
return makeToken( LOGICALANDASSIGN_TOKEN );
retract();
return makeToken( LOGICALAND_TOKEN );
}
retract();
return makeToken( BITWISEAND_TOKEN );
case '#': // # is short for use
if (HAS_HASHPRAGMAS)
{
return makeToken( USE_TOKEN );
}
state = error_state;
continue;
case '(':
return makeToken( LEFTPAREN_TOKEN );
case ')':
return makeToken( RIGHTPAREN_TOKEN );
case '*': // tokens: *= *
if (nextchar()=='=')
return makeToken( MULTASSIGN_TOKEN );
retract();
return makeToken( MULT_TOKEN );
case ',':
return makeToken( COMMA_TOKEN );
case '.':
state = dot_state;
continue;
case '/':
state = slash_state;
continue;
case ':': // tokens: : ::
if (nextchar()==':')
{
return makeToken( DOUBLECOLON_TOKEN );
}
retract();
return makeToken( COLON_TOKEN );
case ';':
return makeToken( SEMICOLON_TOKEN );
case '?':
return makeToken( QUESTIONMARK_TOKEN );
case '[':
return makeToken( LEFTBRACKET_TOKEN );
case ']':
return makeToken( RIGHTBRACKET_TOKEN );
case '^': // tokens: ^= ^
if (nextchar()=='=')
return makeToken( BITWISEXORASSIGN_TOKEN );
retract();
return makeToken( BITWISEXOR_TOKEN );
case '{':
return makeToken( LEFTBRACE_TOKEN );
case '|': // tokens: | |= || ||=
c = nextchar();
if (c=='=')
return makeToken( BITWISEORASSIGN_TOKEN );
if (c=='|')
{
if (nextchar()=='=')
return makeToken( LOGICALORASSIGN_TOKEN );
retract();
return makeToken( LOGICALOR_TOKEN );
}
retract();
return makeToken( BITWISEOR_TOKEN );
case '}':
return makeToken( RIGHTBRACE_TOKEN );
case '~':
return makeToken( BITWISENOT_TOKEN );
case '+': // tokens: ++ += +
c = nextchar();
if (c=='+')
return makeToken( PLUSPLUS_TOKEN );
if (c=='=')
return makeToken( PLUSASSIGN_TOKEN );
retract();
return makeToken( PLUS_TOKEN );
case '<':
switch (nextchar())
{
case '<': // tokens: << <<=
if (nextchar()=='=')
return makeToken( LEFTSHIFTASSIGN_TOKEN );
retract();
return makeToken( LEFTSHIFT_TOKEN );
case '=':
return makeToken( LESSTHANOREQUALS_TOKEN );
case '/':
return makeToken( XMLTAGSTARTEND_TOKEN );
case '!':
state = xmlcommentorcdatastart_state;
continue;
case '?':
state = xmlpi_state;
continue;
}
retract();
return makeToken( LESSTHAN_TOKEN );
case '=': // tokens: === == =
if (nextchar()=='=')
{
if (nextchar()=='=')
return makeToken( STRICTEQUALS_TOKEN );
retract();
return makeToken( EQUALS_TOKEN );
}
retract();
return makeToken( ASSIGN_TOKEN );
case '>': // tokens: > >= >> >>= >>> >>>=
state = start_state;
switch ( nextchar() )
{
case '>':
switch (nextchar())
{
case '>':
if (nextchar()=='=')
return makeToken( UNSIGNEDRIGHTSHIFTASSIGN_TOKEN );
retract();
return makeToken( UNSIGNEDRIGHTSHIFT_TOKEN );
case '=':
return makeToken( RIGHTSHIFTASSIGN_TOKEN );
default:
retract();
return makeToken( RIGHTSHIFT_TOKEN );
}
case '=':
return makeToken( GREATERTHANOREQUALS_TOKEN );
}
retract();
return makeToken( GREATERTHAN_TOKEN );
case '0':
state = zero_state;
continue;
case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimalinteger_state;
continue;
case ' ': // ascii range white space
case '\t':
case 0x000b:
case 0x000c:
case 0x0085:
case 0x00a0:
continue;
case '\n': // ascii line terminators.
case '\r':
isFirstTokenOnLine = true;
continue;
case 0:
return makeToken( EOS_TOKEN );
default:
switch (input.nextcharClass((char)c,true))
{
case Lu: case Ll: case Lt: case Lm: case Lo: case Nl:
maybe_reserved = false;
state = A_state;
continue;
case Zs:// unicode whitespace and control-characters
case Cc:
case Cf:
continue;
case Zl:// unicode line terminators
case Zp:
isFirstTokenOnLine = true;
continue;
default:
state = error_state;
continue;
}
}
}
/*
* prefix: <letter>
*/
case A_state:
{
boolean needs_escape = c == '\\'; // ??? really should only be true if the word started with a backslash
while ( true ){
c = nextchar();
if ( c >= 'a' && c <= 'z' )
{
continue;
}
if ( (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '$' || c == '_' ){
maybe_reserved = false;
continue;
}
if ( c <= 0x7f ) // in ascii range & mostly not a valid char
{
if ( c == '\\' )
{
needs_escape = true; // close enough, we just want to minimize rescans for unicode escapes
}
else {
retract();
break;
}
}
// else outside ascii range (or an escape sequence )
switch (input.nextcharClass(c,false))
{
case Lu: case Ll: case Lt: case Lm: case Lo: case Nl: case Mn: case Mc: case Nd: case Pc:
maybe_reserved = false;
input.nextcharClass(c,true); // advance input cursor
continue;
}
retract();
break;
}
state = start_state;
String s = input.copyReplaceUnicodeEscapes(needs_escape);
if ( maybe_reserved )
{
Integer i = reservedWord.get(s);
if ( i != null )
return makeToken( (int) i );
}
return makeToken(IDENTIFIER_TOKEN,s);
}
/*
* prefix: 0
* accepts: 0x... | 0X... | 01... | 0... | 0
*/
case zero_state:
switch (nextchar())
{
case 'x':
case 'X':
switch(nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F':
state = hexinteger_state;
break;
default:
state = start_state;
error(kError_Lexical_General);
}
continue;
case '.':
state = decimal_state;
continue;
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimalinteger_state;
continue;
case 'E':
case 'e':
state = exponentstart_state;
continue;
case 'd':
case 'm':
case 'i':
case 'u':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: 0x<hex digits>
* accepts: 0x123f
*/
case hexinteger_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F':
state = hexinteger_state;
continue;
case 'u':
case 'i':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken( NUMBERLITERAL_TOKEN, input.copy() );
default:
retract();
state = start_state;
return makeToken( NUMBERLITERAL_TOKEN, input.copy() );
}
/*
* prefix: .
* accepts: .123 | .
*/
case dot_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimal_state;
continue;
case '.':
state = start_state;
if (nextchar()=='.')
return makeToken( TRIPLEDOT_TOKEN );
retract();
return makeToken( DOUBLEDOT_TOKEN );
case '<':
state = start_state;
return makeToken( DOTLESSTHAN_TOKEN );
default:
retract();
state = start_state;
return makeToken( DOT_TOKEN );
}
/*
* prefix: N
* accepts: 0.123 | 1.23 | 123 | 1e23 | 1e-23
*/
case decimalinteger_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimalinteger_state;
continue;
case '.':
state = decimal_state;
continue;
case 'd':
case 'm':
case 'u':
case 'i':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
case 'E':
case 'e':
state = exponentstart_state;
continue;
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: N.
* accepts: 0.1 | 1e23 | 1e-23
*/
case decimal_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimal_state;
continue;
case 'd':
case 'm':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
case 'E':
case 'e':
state = exponentstart_state;
continue;
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: ..e
* accepts: ..eN | ..e+N | ..e-N
*/
case exponentstart_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
case '+':
case '-':
state = exponent_state;
continue;
default:
error(kError_Lexical_General);
state = start_state;
continue;
// Issue: needs specific error here.
}
/*
* prefix: ..e
* accepts: ..eN | ..e+N | ..e-N
*/
case exponent_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = exponent_state;
continue;
case 'd':
case 'm':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: /
*/
case slash_state:
{
c = nextchar();
switch (c)
{
case '/': // line comment
state = start_state;
line_comment:
while ( (c=nextchar()) != 0)
{
if ( c == '\r' || c == '\n' )
{
isFirstTokenOnLine = true;
if (save_comments == false)
{
break line_comment;
}
retract(); // don't include newline in line comment. (Sec 7.3)
return makeToken( SLASHSLASHCOMMENT_TOKEN, input.copyReplaceUnicodeEscapes() );
}
}
continue;
case '*':
if (save_comments == false)
{
block_comment:
while ( (c=nextchar()) != 0)
{
if ( c == '\r' || c == '\n' )
isFirstTokenOnLine = true;
if (c == '*')
{
c = nextchar();
if (c == '/' )
{
break block_comment;
}
retract();
}
}
state = start_state;
}
else
{
if (blockcommentbuf == null)
blockcommentbuf = new StringBuilder();
blockcommentbuf.append("/*");
state = blockcommentstart_state;
}
continue;
case '>':
if ( inXML > 0) // ignore this if outside an XML context
{
state = start_state;
return makeToken( XMLTAGENDEND_TOKEN );
}
// FALL THROUGH
default:
// If the last token read is any of these, then the '/' must start a div or div_assign...
int lb = currentToken.id;
if ( lb == IDENTIFIER_TOKEN || lb == NUMBERLITERAL_TOKEN || lb == RIGHTPAREN_TOKEN ||
lb == RIGHTBRACE_TOKEN || lb == RIGHTBRACKET_TOKEN )
{
/*
* tokens: /= /
*/
state = start_state;
if (c=='=')
return makeToken( DIVASSIGN_TOKEN );
retract();
return makeToken( DIV_TOKEN );
}
state = slashregexp_state;
retract();
continue;
}
}
/*
* tokens: /<regexpbody>/<regexpflags>
*/
case slashregexp_state:
switch (nextchar())
{
case '\\':
nextchar();
continue;
case '/':
regexp_flags = 0;
state = regexp_state;
continue;
case 0:
case '\n':
case '\r':
error(kError_Lexical_General);
state = start_state;
continue;
default:
state = slashregexp_state;
continue;
}
/*
* tokens: g | i | m | s | x . Note that s and x are custom extentions to match perl's functionality
* Also note we handle this via an array of boolean flags intead of state change logic.
* (5,1) + (5,2) + (5,3) + (5,4) + (5,5) is just too many states to handle this via state logic
*/
case regexp_state:
c = nextchar();
switch ( c )
{
case 'g':
if ((regexp_flags & 0x01) == 0)
{
regexp_flags |= 0x01;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 'i':
if ((regexp_flags & 0x02) == 0)
{
regexp_flags |= 0x02;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 'm':
if ((regexp_flags & 0x04) == 0)
{
regexp_flags |= 0x04;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 's':
if ((regexp_flags & 0x08) == 0)
{
regexp_flags |= 0x08;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 'x':
if ((regexp_flags & 0x10) == 0)
{
regexp_flags |= 0x10;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
default:
if (Character.isJavaIdentifierPart(c))
{
error(kError_Lexical_General);
state = start_state;
continue;
}
retract();
state = start_state;
return makeToken( REGEXPLITERAL_TOKEN, input.copyReplaceUnicodeEscapes());
}
/*
* prefix: <!
*/
case xmlcommentorcdatastart_state:
switch ( nextchar() )
{
case '[':
if (nextchar()=='C' &&
nextchar()=='D' &&
nextchar()=='A' &&
nextchar()=='T' &&
nextchar()=='A' &&
nextchar()=='[')
{
state = xmlcdata_state;
continue;
}
break; // error
case '-':
if (nextchar()=='-')
{
state = xmlcomment_state;
continue;
}
}
error(kError_Lexical_General);
state = start_state;
continue;
case xmlcdata_state:
switch ( nextchar() )
{
case ']':
if (nextchar()==']' && nextchar()=='>')
{
state = start_state;
return makeToken(XMLMARKUP_TOKEN,input.substringReplaceUnicodeEscapes(startofxml,pos()));
}
continue;
case 0:
error(kError_Lexical_General);
state = start_state;
}
continue;
case xmlcomment_state:
while ( (c=nextchar()) != '-' && c != 0 )
;
if (c=='-' && nextchar() != '-')
{
continue;
}
// got -- if next is > ok else error
if ( nextchar()=='>')
{
state = start_state;
return makeToken(XMLMARKUP_TOKEN,input.substringReplaceUnicodeEscapes(startofxml,pos()));
}
error(kError_Lexical_General);
state = start_state;
continue;
case xmlpi_state:
while ( (c=nextchar()) != '?' && c != 0 )
;
if (c=='?' && nextchar() == '>')
{
state = start_state;
return makeToken(XMLMARKUP_TOKEN,input.substringReplaceUnicodeEscapes(startofxml,pos()));
}
if (c==0)
{
error(kError_Lexical_General);
state = start_state;
}
continue;
case xmltext_state:
{
switch(nextchar())
{
case '<': case '{':
{
retract();
String xmltext = input.substringReplaceUnicodeEscapes(startofxml,pos());
if( xmltext != null )
{
state = start_state;
return makeToken(XMLTEXT_TOKEN,xmltext);
}
else // if there is no leading text, then just return punctuation token to avoid empty text tokens
{
switch(nextchar())
{
case '<':
switch( nextchar() )
{
case '/': state = start_state; return makeToken( XMLTAGSTARTEND_TOKEN );
case '!': state = xmlcommentorcdatastart_state; continue;
case '?': state = xmlpi_state; continue;
default: retract(); state = start_state; return makeToken( LESSTHAN_TOKEN );
}
case '{':
state = start_state;
return makeToken( LEFTBRACE_TOKEN );
}
}
}
case 0:
state = start_state;
return makeToken( EOS_TOKEN );
}
continue;
}
case xmlliteral_state:
switch (nextchar())
{
case '{': // return makeToken( XMLPART_TOKEN
return makeToken(XMLPART_TOKEN, input.substringReplaceUnicodeEscapes(startofxml, pos()-1));
case '<':
if (nextchar()=='/')
{
--level;
nextchar();
mark();
retract();
state = endxmlname_state;
}
else
{
++level;
state = xmlliteral_state;
}
continue;
case '/':
if (nextchar()=='>')
{
--level;
if (level == 0)
{
state = start_state;
return makeToken(XMLLITERAL_TOKEN, input.substringReplaceUnicodeEscapes(startofxml, pos()+1));
}
}
continue;
case 0:
retract();
error(kError_Lexical_NoMatchingTag);
state = start_state;
continue;
default:
continue;
}
case endxmlname_state:
c = nextchar();
if (Character.isJavaIdentifierPart(c)||c==':')
{
continue;
}
switch(c)
{
case '{': // return makeToken( XMLPART_TOKEN
{
String xmltext = input.substringReplaceUnicodeEscapes(startofxml, pos()-1);
return makeToken(XMLPART_TOKEN, xmltext);
}
case '>':
retract();
nextchar();
if (level == 0)
{
String xmltext = input.substringReplaceUnicodeEscapes(startofxml, pos()+1);
state = start_state;
return makeToken(XMLLITERAL_TOKEN, xmltext);
}
state = xmlliteral_state;
continue;
default:
state = xmlliteral_state;
continue;
}
/*
* prefix: /*
*/
case blockcommentstart_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '*':
if ( nextchar() == '/' ){
state = start_state;
return makeToken( BLOCKCOMMENT_TOKEN, new String());
}
retract();
state = doccomment_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
case '\n':
case '\r':
isFirstTokenOnLine = true;
default:
state = blockcomment_state;
continue;
}
}
/*
* prefix: /**
*/
case doccomment_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '*':
state = doccommentstar_state;
continue;
case '@':
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
if( doctagname.length() > 0 )
{
doctextbuf.append("]]></").append(doctagname).append(">");
}
doctagname = "";
state = doccommenttag_state;
continue;
case '\r':
case '\n':
isFirstTokenOnLine = true;
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
doctextbuf.append('\n');
state = doccomment_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
doctextbuf.append((char)(c));
state = doccomment_state;
continue;
}
}
case doccommentstar_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '/':
{
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
if( doctagname.length() > 0 )
{
doctextbuf.append("]]></").append(doctagname).append(">");
}
String doctext = doctextbuf.toString(); // ??? does this needs escape conversion ???
state = start_state;
return makeToken(DOCCOMMENT_TOKEN,doctext);
}
case '*':
state = doccommentstar_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
state = doccomment_state;
continue;
// if not a slash, then keep looking for an end comment.
}
}
/*
* prefix: @
*/
case doccommenttag_state:
{
c = nextchar();
switch ( c )
{
case '*':
state = doccommentstar_state;
continue;
case ' ': case '\t': case '\r': case '\n':
{
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
// skip extra whitespace --fixes bug on tag text parsing
// --but really, the problem is not here, it's in whatever reads asdoc output..
// --So if that gets fixed, feel free to delete the following.
while ( (c=nextchar()) == ' ' || c == '\t' )
;
retract();
if( doctagname.length() > 0 )
{
doctextbuf.append("\n<").append(doctagname).append("><![CDATA[");
}
state = doccomment_state;
continue;
}
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
doctagname += (char)(c);
continue;
}
}
/*
* prefix: /**
*/
case doccommentvalue_state:
switch ( nextchar() )
{
case '*':
state = doccommentstar_state;
continue;
case '@':
state = doccommenttag_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
state = doccomment_state;
continue;
}
/*
* prefix: /*
*/
case blockcomment_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '*': state = blockcommentstar_state; continue;
case '\r': case '\n': isFirstTokenOnLine = true;
state = blockcomment_state; continue;
case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue;
default: state = blockcomment_state; continue;
}
}
case blockcommentstar_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '/':
{
state = start_state;
String blocktext = blockcommentbuf.toString(); // ??? needs escape conversion
return makeToken( BLOCKCOMMENT_TOKEN, blocktext );
}
case '*': state = blockcommentstar_state; continue;
case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue;
default: state = blockcomment_state; continue;
// if not a slash, then keep looking for an end comment.
}
}
/*
* skip error
*/
case error_state:
error(kError_Lexical_General);
skiperror();
state = start_state;
continue;
default:
error("invalid scanner state");
state = start_state;
return makeToken(EOS_TOKEN);
}
}
}
| public int nexttoken(boolean resetState)
{
String doctagname = "description";
StringBuilder doctextbuf = null;
int startofxml = pos();
StringBuilder blockcommentbuf = null;
char regexp_flags = 0; // used to track option flags encountered in a regexp expression. Initialized in regexp_state
boolean maybe_reserved = false;
char c = 0;
if (resetState)
{
isFirstTokenOnLine = false;
}
while (true)
{
if (debug)
{
System.out.println("state = " + state + ", next = " + pos());
}
switch (state)
{
case start_state:
{
c = nextchar();
mark();
switch (c)
{
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j':
case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
maybe_reserved = true;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J':
case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
case '_': case '$':
state = A_state;
continue;
case 0xffef: // could not have worked...case 0xffffffef: // ??? not in Character type range ???
if (nextchar()==0xffffffbb &&
nextchar()==0xffffffbf)
{
// ISSUE: set encoding scheme to utf-8, and implement support for utf8
state = start_state;
}
else
{
state = error_state;
}
continue;
case '@':
return makeToken( ATSIGN_TOKEN );
case '\'':
case '\"':
{
char startquote = (char) c;
boolean needs_escape = false;
while ( (c=nextchar()) != startquote )
{
if ( c == '\\' )
{
needs_escape = true;
c = nextchar();
// special case: escaped eol strips crlf or lf
if ( c == '\r' )
c = nextchar();
if ( c == '\n' )
continue;
}
else if ( c == '\r' || c == '\n' )
{
if ( startquote == '\'' )
error(kError_Lexical_LineTerminatorInSingleQuotedStringLiteral);
else
error(kError_Lexical_LineTerminatorInDoubleQuotedStringLiteral);
break;
}
else if ( c == 0 )
{
error(kError_Lexical_EndOfStreamInStringLiteral);
return makeToken( EOS_TOKEN );
}
}
return makeToken(STRINGLITERAL_TOKEN, input.copyReplaceStringEscapes(needs_escape));
}
case '-': // tokens: -- -= -
switch (nextchar())
{
case '-':
return makeToken( MINUSMINUS_TOKEN );
case '=':
return makeToken( MINUSASSIGN_TOKEN );
default:
retract();
return makeToken( MINUS_TOKEN );
}
case '!': // tokens: ! != !===
if (nextchar()=='=')
{
if (nextchar()=='=')
return makeToken( STRICTNOTEQUALS_TOKEN );
retract();
return makeToken( NOTEQUALS_TOKEN );
}
retract();
return makeToken( NOT_TOKEN );
case '%': // tokens: % %=
switch (nextchar())
{
case '=':
return makeToken( MODULUSASSIGN_TOKEN );
default:
retract();
return makeToken( MODULUS_TOKEN );
}
case '&': // tokens: & &= && &&=
c = nextchar();
if (c=='=')
return makeToken( BITWISEANDASSIGN_TOKEN );
if (c=='&')
{
if (nextchar()=='=')
return makeToken( LOGICALANDASSIGN_TOKEN );
retract();
return makeToken( LOGICALAND_TOKEN );
}
retract();
return makeToken( BITWISEAND_TOKEN );
case '#': // # is short for use
if (HAS_HASHPRAGMAS)
{
return makeToken( USE_TOKEN );
}
state = error_state;
continue;
case '(':
return makeToken( LEFTPAREN_TOKEN );
case ')':
return makeToken( RIGHTPAREN_TOKEN );
case '*': // tokens: *= *
if (nextchar()=='=')
return makeToken( MULTASSIGN_TOKEN );
retract();
return makeToken( MULT_TOKEN );
case ',':
return makeToken( COMMA_TOKEN );
case '.':
state = dot_state;
continue;
case '/':
state = slash_state;
continue;
case ':': // tokens: : ::
if (nextchar()==':')
{
return makeToken( DOUBLECOLON_TOKEN );
}
retract();
return makeToken( COLON_TOKEN );
case ';':
return makeToken( SEMICOLON_TOKEN );
case '?':
return makeToken( QUESTIONMARK_TOKEN );
case '[':
return makeToken( LEFTBRACKET_TOKEN );
case ']':
return makeToken( RIGHTBRACKET_TOKEN );
case '^': // tokens: ^= ^
if (nextchar()=='=')
return makeToken( BITWISEXORASSIGN_TOKEN );
retract();
return makeToken( BITWISEXOR_TOKEN );
case '{':
return makeToken( LEFTBRACE_TOKEN );
case '|': // tokens: | |= || ||=
c = nextchar();
if (c=='=')
return makeToken( BITWISEORASSIGN_TOKEN );
if (c=='|')
{
if (nextchar()=='=')
return makeToken( LOGICALORASSIGN_TOKEN );
retract();
return makeToken( LOGICALOR_TOKEN );
}
retract();
return makeToken( BITWISEOR_TOKEN );
case '}':
return makeToken( RIGHTBRACE_TOKEN );
case '~':
return makeToken( BITWISENOT_TOKEN );
case '+': // tokens: ++ += +
c = nextchar();
if (c=='+')
return makeToken( PLUSPLUS_TOKEN );
if (c=='=')
return makeToken( PLUSASSIGN_TOKEN );
retract();
return makeToken( PLUS_TOKEN );
case '<':
switch (nextchar())
{
case '<': // tokens: << <<=
if (nextchar()=='=')
return makeToken( LEFTSHIFTASSIGN_TOKEN );
retract();
return makeToken( LEFTSHIFT_TOKEN );
case '=':
return makeToken( LESSTHANOREQUALS_TOKEN );
case '/':
return makeToken( XMLTAGSTARTEND_TOKEN );
case '!':
state = xmlcommentorcdatastart_state;
continue;
case '?':
state = xmlpi_state;
continue;
}
retract();
return makeToken( LESSTHAN_TOKEN );
case '=': // tokens: === == =
if (nextchar()=='=')
{
if (nextchar()=='=')
return makeToken( STRICTEQUALS_TOKEN );
retract();
return makeToken( EQUALS_TOKEN );
}
retract();
return makeToken( ASSIGN_TOKEN );
case '>': // tokens: > >= >> >>= >>> >>>=
state = start_state;
switch ( nextchar() )
{
case '>':
switch (nextchar())
{
case '>':
if (nextchar()=='=')
return makeToken( UNSIGNEDRIGHTSHIFTASSIGN_TOKEN );
retract();
return makeToken( UNSIGNEDRIGHTSHIFT_TOKEN );
case '=':
return makeToken( RIGHTSHIFTASSIGN_TOKEN );
default:
retract();
return makeToken( RIGHTSHIFT_TOKEN );
}
case '=':
return makeToken( GREATERTHANOREQUALS_TOKEN );
}
retract();
return makeToken( GREATERTHAN_TOKEN );
case '0':
state = zero_state;
continue;
case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimalinteger_state;
continue;
case ' ': // ascii range white space
case '\t':
case 0x000b:
case 0x000c:
case 0x0085:
case 0x00a0:
continue;
case '\n': // ascii line terminators.
case '\r':
isFirstTokenOnLine = true;
continue;
case 0:
return makeToken( EOS_TOKEN );
default:
switch (input.nextcharClass((char)c,true))
{
case Lu: case Ll: case Lt: case Lm: case Lo: case Nl:
maybe_reserved = false;
state = A_state;
continue;
case Zs:// unicode whitespace and control-characters
case Cc:
case Cf:
continue;
case Zl:// unicode line terminators
case Zp:
isFirstTokenOnLine = true;
continue;
default:
state = error_state;
continue;
}
}
}
/*
* prefix: <letter>
*/
case A_state:
{
boolean needs_escape = c == '\\'; // ??? really should only be true if the word started with a backslash
while ( true ){
c = nextchar();
if ( c >= 'a' && c <= 'z' )
{
continue;
}
if ( (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '$' || c == '_' ){
maybe_reserved = false;
continue;
}
if ( c <= 0x7f ) // in ascii range & mostly not a valid char
{
if ( c == '\\' )
{
needs_escape = true; // close enough, we just want to minimize rescans for unicode escapes
}
else {
retract();
break;
}
}
// else outside ascii range (or an escape sequence )
switch (input.nextcharClass(c,false))
{
case Lu: case Ll: case Lt: case Lm: case Lo: case Nl: case Mn: case Mc: case Nd: case Pc:
maybe_reserved = false;
input.nextcharClass(c,true); // advance input cursor
continue;
}
retract();
break;
}
state = start_state;
String s = input.copyReplaceUnicodeEscapes(needs_escape);
if ( maybe_reserved )
{
Integer i = reservedWord.get(s);
if ( i != null )
return makeToken( (int) i );
}
return makeToken(IDENTIFIER_TOKEN,s);
}
/*
* prefix: 0
* accepts: 0x... | 0X... | 01... | 0... | 0
*/
case zero_state:
switch (nextchar())
{
case 'x':
case 'X':
switch(nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F':
state = hexinteger_state;
break;
default:
state = start_state;
error(kError_Lexical_General);
}
continue;
case '.':
state = decimal_state;
continue;
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimalinteger_state;
continue;
case 'E':
case 'e':
state = exponentstart_state;
continue;
case 'd':
case 'm':
case 'i':
case 'u':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: 0x<hex digits>
* accepts: 0x123f
*/
case hexinteger_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F':
state = hexinteger_state;
continue;
case 'u':
case 'i':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken( NUMBERLITERAL_TOKEN, input.copy() );
default:
retract();
state = start_state;
return makeToken( NUMBERLITERAL_TOKEN, input.copy() );
}
/*
* prefix: .
* accepts: .123 | .
*/
case dot_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimal_state;
continue;
case '.':
state = start_state;
if (nextchar()=='.')
return makeToken( TRIPLEDOT_TOKEN );
retract();
return makeToken( DOUBLEDOT_TOKEN );
case '<':
state = start_state;
return makeToken( DOTLESSTHAN_TOKEN );
default:
retract();
state = start_state;
return makeToken( DOT_TOKEN );
}
/*
* prefix: N
* accepts: 0.123 | 1.23 | 123 | 1e23 | 1e-23
*/
case decimalinteger_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimalinteger_state;
continue;
case '.':
state = decimal_state;
continue;
case 'd':
case 'm':
case 'u':
case 'i':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
case 'E':
case 'e':
state = exponentstart_state;
continue;
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: N.
* accepts: 0.1 | 1e23 | 1e-23
*/
case decimal_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = decimal_state;
continue;
case 'd':
case 'm':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
case 'E':
case 'e':
state = exponentstart_state;
continue;
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: ..e
* accepts: ..eN | ..e+N | ..e-N
*/
case exponentstart_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
case '+':
case '-':
state = exponent_state;
continue;
default:
error(kError_Lexical_General);
state = start_state;
continue;
// Issue: needs specific error here.
}
/*
* prefix: ..e
* accepts: ..eN | ..e+N | ..e-N
*/
case exponent_state:
switch (nextchar())
{
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
state = exponent_state;
continue;
case 'd':
case 'm':
if (!ctx.statics.es4_numerics)
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
default:
retract();
state = start_state;
return makeToken(NUMBERLITERAL_TOKEN, input.copy());
}
/*
* prefix: /
*/
case slash_state:
{
c = nextchar();
switch (c)
{
case '/': // line comment
state = start_state;
line_comment:
while ( (c=nextchar()) != 0)
{
if ( c == '\r' || c == '\n' )
{
isFirstTokenOnLine = true;
if (save_comments == false)
{
break line_comment;
}
retract(); // don't include newline in line comment. (Sec 7.3)
return makeToken( SLASHSLASHCOMMENT_TOKEN, input.copyReplaceUnicodeEscapes() );
}
}
continue;
case '*':
if (save_comments == false)
{
block_comment:
while ( (c=nextchar()) != 0)
{
if ( c == '\r' || c == '\n' )
isFirstTokenOnLine = true;
if (c == '*')
{
c = nextchar();
if (c == '/' )
{
break block_comment;
}
retract();
}
}
state = start_state;
}
else
{
if (blockcommentbuf == null)
blockcommentbuf = new StringBuilder();
blockcommentbuf.append("/*");
state = blockcommentstart_state;
}
continue;
case '>':
// FIXME: Not exactly right???if ( inXML > 0) // ignore this if outside an XML context
{
state = start_state;
return makeToken( XMLTAGENDEND_TOKEN );
}
// FALL THROUGH
default:
// If the last token read is any of these, then the '/' must start a div or div_assign...
int lb = currentToken.id;
if ( lb == IDENTIFIER_TOKEN || lb == NUMBERLITERAL_TOKEN || lb == RIGHTPAREN_TOKEN ||
lb == RIGHTBRACE_TOKEN || lb == RIGHTBRACKET_TOKEN )
{
/*
* tokens: /= /
*/
state = start_state;
if (c=='=')
return makeToken( DIVASSIGN_TOKEN );
retract();
return makeToken( DIV_TOKEN );
}
state = slashregexp_state;
retract();
continue;
}
}
/*
* tokens: /<regexpbody>/<regexpflags>
*/
case slashregexp_state:
switch (nextchar())
{
case '\\':
nextchar();
continue;
case '/':
regexp_flags = 0;
state = regexp_state;
continue;
case 0:
case '\n':
case '\r':
error(kError_Lexical_General);
state = start_state;
continue;
default:
state = slashregexp_state;
continue;
}
/*
* tokens: g | i | m | s | x . Note that s and x are custom extentions to match perl's functionality
* Also note we handle this via an array of boolean flags intead of state change logic.
* (5,1) + (5,2) + (5,3) + (5,4) + (5,5) is just too many states to handle this via state logic
*/
case regexp_state:
c = nextchar();
switch ( c )
{
case 'g':
if ((regexp_flags & 0x01) == 0)
{
regexp_flags |= 0x01;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 'i':
if ((regexp_flags & 0x02) == 0)
{
regexp_flags |= 0x02;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 'm':
if ((regexp_flags & 0x04) == 0)
{
regexp_flags |= 0x04;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 's':
if ((regexp_flags & 0x08) == 0)
{
regexp_flags |= 0x08;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
case 'x':
if ((regexp_flags & 0x10) == 0)
{
regexp_flags |= 0x10;
continue;
}
error(kError_Lexical_General);
state = start_state;
continue;
default:
if (Character.isJavaIdentifierPart(c))
{
error(kError_Lexical_General);
state = start_state;
continue;
}
retract();
state = start_state;
return makeToken( REGEXPLITERAL_TOKEN, input.copyReplaceUnicodeEscapes());
}
/*
* prefix: <!
*/
case xmlcommentorcdatastart_state:
switch ( nextchar() )
{
case '[':
if (nextchar()=='C' &&
nextchar()=='D' &&
nextchar()=='A' &&
nextchar()=='T' &&
nextchar()=='A' &&
nextchar()=='[')
{
state = xmlcdata_state;
continue;
}
break; // error
case '-':
if (nextchar()=='-')
{
state = xmlcomment_state;
continue;
}
}
error(kError_Lexical_General);
state = start_state;
continue;
case xmlcdata_state:
switch ( nextchar() )
{
case ']':
if (nextchar()==']' && nextchar()=='>')
{
state = start_state;
return makeToken(XMLMARKUP_TOKEN,input.substringReplaceUnicodeEscapes(startofxml,pos()));
}
continue;
case 0:
error(kError_Lexical_General);
state = start_state;
}
continue;
case xmlcomment_state:
while ( (c=nextchar()) != '-' && c != 0 )
;
if (c=='-' && nextchar() != '-')
{
continue;
}
// got -- if next is > ok else error
if ( nextchar()=='>')
{
state = start_state;
return makeToken(XMLMARKUP_TOKEN,input.substringReplaceUnicodeEscapes(startofxml,pos()));
}
error(kError_Lexical_General);
state = start_state;
continue;
case xmlpi_state:
while ( (c=nextchar()) != '?' && c != 0 )
;
if (c=='?' && nextchar() == '>')
{
state = start_state;
return makeToken(XMLMARKUP_TOKEN,input.substringReplaceUnicodeEscapes(startofxml,pos()));
}
if (c==0)
{
error(kError_Lexical_General);
state = start_state;
}
continue;
case xmltext_state:
{
switch(nextchar())
{
case '<': case '{':
{
retract();
String xmltext = input.substringReplaceUnicodeEscapes(startofxml,pos());
if( xmltext != null )
{
state = start_state;
return makeToken(XMLTEXT_TOKEN,xmltext);
}
else // if there is no leading text, then just return punctuation token to avoid empty text tokens
{
switch(nextchar())
{
case '<':
switch( nextchar() )
{
case '/': state = start_state; return makeToken( XMLTAGSTARTEND_TOKEN );
case '!': state = xmlcommentorcdatastart_state; continue;
case '?': state = xmlpi_state; continue;
default: retract(); state = start_state; return makeToken( LESSTHAN_TOKEN );
}
case '{':
state = start_state;
return makeToken( LEFTBRACE_TOKEN );
}
}
}
case 0:
state = start_state;
return makeToken( EOS_TOKEN );
}
continue;
}
case xmlliteral_state:
switch (nextchar())
{
case '{': // return makeToken( XMLPART_TOKEN
return makeToken(XMLPART_TOKEN, input.substringReplaceUnicodeEscapes(startofxml, pos()-1));
case '<':
if (nextchar()=='/')
{
--level;
nextchar();
mark();
retract();
state = endxmlname_state;
}
else
{
++level;
state = xmlliteral_state;
}
continue;
case '/':
if (nextchar()=='>')
{
--level;
if (level == 0)
{
state = start_state;
return makeToken(XMLLITERAL_TOKEN, input.substringReplaceUnicodeEscapes(startofxml, pos()+1));
}
}
continue;
case 0:
retract();
error(kError_Lexical_NoMatchingTag);
state = start_state;
continue;
default:
continue;
}
case endxmlname_state:
c = nextchar();
if (Character.isJavaIdentifierPart(c)||c==':')
{
continue;
}
switch(c)
{
case '{': // return makeToken( XMLPART_TOKEN
{
String xmltext = input.substringReplaceUnicodeEscapes(startofxml, pos()-1);
return makeToken(XMLPART_TOKEN, xmltext);
}
case '>':
retract();
nextchar();
if (level == 0)
{
String xmltext = input.substringReplaceUnicodeEscapes(startofxml, pos()+1);
state = start_state;
return makeToken(XMLLITERAL_TOKEN, xmltext);
}
state = xmlliteral_state;
continue;
default:
state = xmlliteral_state;
continue;
}
/*
* prefix: /*
*/
case blockcommentstart_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '*':
if ( nextchar() == '/' ){
state = start_state;
return makeToken( BLOCKCOMMENT_TOKEN, new String());
}
retract();
state = doccomment_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
case '\n':
case '\r':
isFirstTokenOnLine = true;
default:
state = blockcomment_state;
continue;
}
}
/*
* prefix: /**
*/
case doccomment_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '*':
state = doccommentstar_state;
continue;
case '@':
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
if( doctagname.length() > 0 )
{
doctextbuf.append("]]></").append(doctagname).append(">");
}
doctagname = "";
state = doccommenttag_state;
continue;
case '\r':
case '\n':
isFirstTokenOnLine = true;
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
doctextbuf.append('\n');
state = doccomment_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
doctextbuf.append((char)(c));
state = doccomment_state;
continue;
}
}
case doccommentstar_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '/':
{
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
if( doctagname.length() > 0 )
{
doctextbuf.append("]]></").append(doctagname).append(">");
}
String doctext = doctextbuf.toString(); // ??? does this needs escape conversion ???
state = start_state;
return makeToken(DOCCOMMENT_TOKEN,doctext);
}
case '*':
state = doccommentstar_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
state = doccomment_state;
continue;
// if not a slash, then keep looking for an end comment.
}
}
/*
* prefix: @
*/
case doccommenttag_state:
{
c = nextchar();
switch ( c )
{
case '*':
state = doccommentstar_state;
continue;
case ' ': case '\t': case '\r': case '\n':
{
if (doctextbuf == null)
doctextbuf = getDocTextBuffer(doctagname);
// skip extra whitespace --fixes bug on tag text parsing
// --but really, the problem is not here, it's in whatever reads asdoc output..
// --So if that gets fixed, feel free to delete the following.
while ( (c=nextchar()) == ' ' || c == '\t' )
;
retract();
if( doctagname.length() > 0 )
{
doctextbuf.append("\n<").append(doctagname).append("><![CDATA[");
}
state = doccomment_state;
continue;
}
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
doctagname += (char)(c);
continue;
}
}
/*
* prefix: /**
*/
case doccommentvalue_state:
switch ( nextchar() )
{
case '*':
state = doccommentstar_state;
continue;
case '@':
state = doccommenttag_state;
continue;
case 0:
error(kError_BlockCommentNotTerminated);
state = start_state;
continue;
default:
state = doccomment_state;
continue;
}
/*
* prefix: /*
*/
case blockcomment_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '*': state = blockcommentstar_state; continue;
case '\r': case '\n': isFirstTokenOnLine = true;
state = blockcomment_state; continue;
case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue;
default: state = blockcomment_state; continue;
}
}
case blockcommentstar_state:
{
c = nextchar();
blockcommentbuf.append(c);
switch ( c )
{
case '/':
{
state = start_state;
String blocktext = blockcommentbuf.toString(); // ??? needs escape conversion
return makeToken( BLOCKCOMMENT_TOKEN, blocktext );
}
case '*': state = blockcommentstar_state; continue;
case 0: error(kError_BlockCommentNotTerminated); state = start_state; continue;
default: state = blockcomment_state; continue;
// if not a slash, then keep looking for an end comment.
}
}
/*
* skip error
*/
case error_state:
error(kError_Lexical_General);
skiperror();
state = start_state;
continue;
default:
error("invalid scanner state");
state = start_state;
return makeToken(EOS_TOKEN);
}
}
}
|
diff --git a/plugins/org.eclipse.graphiti.ui/src/org/eclipse/graphiti/ui/internal/services/impl/UiService.java b/plugins/org.eclipse.graphiti.ui/src/org/eclipse/graphiti/ui/internal/services/impl/UiService.java
index 3a9da266..cf4459c3 100644
--- a/plugins/org.eclipse.graphiti.ui/src/org/eclipse/graphiti/ui/internal/services/impl/UiService.java
+++ b/plugins/org.eclipse.graphiti.ui/src/org/eclipse/graphiti/ui/internal/services/impl/UiService.java
@@ -1,254 +1,254 @@
/*******************************************************************************
* <copyright>
*
* Copyright (c) 2005, 2010 SAP AG.
* 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:
* SAP AG - initial API, implementation and documentation
*
* </copyright>
*
*******************************************************************************/
package org.eclipse.graphiti.ui.internal.services.impl;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.graphiti.internal.util.T;
import org.eclipse.graphiti.mm.pictograms.Diagram;
import org.eclipse.graphiti.ui.internal.platform.ExtensionManager;
import org.eclipse.graphiti.ui.internal.services.GraphitiUiInternal;
import org.eclipse.graphiti.ui.internal.services.IUiService;
import org.eclipse.graphiti.ui.internal.util.ui.print.ExportDiagramDialog;
import org.eclipse.graphiti.ui.internal.util.ui.print.IDiagramsExporter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.ImageLoader;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
/**
* A collection of static helper methods regarding Draw2d.
*
* @noinstantiate This class is not intended to be instantiated by clients.
* @noextend This class is not intended to be subclassed by clients.
*/
public class UiService implements IUiService {
public byte[] createImage(Image image, int format) throws Exception {
ByteArrayOutputStream result = new ByteArrayOutputStream();
try {
ImageData imDat = null;
// at the moment saving as GIF is only working if not more than 256
// colors are used in the figure
if (format == SWT.IMAGE_GIF) {
imDat = create8BitIndexedPaletteImage(image);
}
if (imDat == null)
imDat = image.getImageData();
ImageLoader imageLoader = new ImageLoader();
imageLoader.data = new ImageData[] { imDat };
try {
imageLoader.save(result, format);
} catch (SWTException e) {
String error = "Depth: " + Integer.toString(image.getImageData().depth) + "\n" + "X: " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ Integer.toString(image.getImageData().x)
+ "\n" + "Y: " + Integer.toString(image.getImageData().y); //$NON-NLS-1$ //$NON-NLS-2$
throw new IllegalStateException(error, e);
}
} finally {
image.dispose();
}
return result.toByteArray();
}
public ImageData create8BitIndexedPaletteImage(Image image) throws Exception {
int upperboundWidth = image.getBounds().width;
int upperboundHeight = image.getBounds().height;
ImageData imageData = image.getImageData();
// determine number of used colors
ArrayList<Integer> colors = new ArrayList<Integer>();
for (int x = 0; x < upperboundWidth; x++) {
for (int y = 0; y < upperboundHeight; y++) {
int color = imageData.getPixel(x, y);
Integer colorInteger = new Integer(color);
if (!colors.contains(colorInteger))
colors.add(colorInteger);
}
}
// at the moment this is only working if not more than 256 colors are
// used in the image
if (colors.size() > 256)
throw new Exception(
"Image contains more than 256 colors. \n Automated color reduction is currently not supported."); //$NON-NLS-1$
// create an indexed palette
RGB[] rgbs = new RGB[256];
for (int i = 0; i < 256; i++)
rgbs[i] = new RGB(255, 255, 255);
for (int i = 0; i < colors.size(); i++) {
int pixelValue = ((colors.get(i))).intValue();
int red = (pixelValue & imageData.palette.redMask) >>> Math.abs(imageData.palette.redShift);
int green = (pixelValue & imageData.palette.greenMask) >>> Math.abs(imageData.palette.greenShift);
int blue = (pixelValue & imageData.palette.blueMask) >>> Math.abs(imageData.palette.blueShift);
rgbs[i] = new RGB(red, green, blue);
}
// create new imageData
PaletteData palette = new PaletteData(rgbs);
ImageData newImageData = new ImageData(imageData.width, imageData.height, 8, palette);
// adjust imageData with regard to the palette
for (int x = 0; x < upperboundWidth; x++) {
for (int y = 0; y < upperboundHeight; y++) {
int color = imageData.getPixel(x, y);
newImageData.setPixel(x, y, colors.indexOf(new Integer(color)));
}
}
return newImageData;
}
public void startSaveAsImageDialog(GraphicalViewer graphicalViewer) {
final String METHOD = "startSaveAsImageDialog(graphicalViewer)"; //$NON-NLS-1$
// check extension point for exporters
Map<String, Boolean> diagramExporterTypes = ExtensionManager.getSingleton().getDiagramExporterTypes();
// configure dialog with exporters and open dialog
final Shell shell = GraphitiUiInternal.getWorkbenchService().getShell();
final ExportDiagramDialog saveAsImageDialog = new ExportDiagramDialog(shell, graphicalViewer);
saveAsImageDialog.addExporters(diagramExporterTypes);
saveAsImageDialog.open();
if (saveAsImageDialog.getReturnCode() == Window.CANCEL)
return;
// select filename with file-dialog
FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);
String fileExtensions[] = new String[] { "*." + saveAsImageDialog.getFormattedFileExtension() }; //$NON-NLS-1$
fileDialog.setFilterExtensions(fileExtensions);
String name = ((Diagram) graphicalViewer.getContents().getModel()).getName();
fileDialog.setFileName(name);
String filename = fileDialog.open();
if (filename != null) {
try {
// add extension to filename (if none exists)
IPath path = new Path(filename);
if (path.getFileExtension() == null)
filename = filename + "." + saveAsImageDialog.getFormattedFileExtension(); //$NON-NLS-1$
final String file = filename;
final Image im = saveAsImageDialog.getScaledImage();
String imageExtension = saveAsImageDialog.getFileExtension();
IRunnableWithProgress operation;
// if the exporter is non-standard, i.e. registered via
// extension point, we need to call the registered exporter.
if (diagramExporterTypes.containsKey(imageExtension)) {
final IDiagramsExporter exporter = ExtensionManager.getSingleton().getDiagramExporterForType(
imageExtension);
Assert.isNotNull(exporter);
operation = getExportOp(METHOD, shell, saveAsImageDialog, file, im, exporter);
new ProgressMonitorDialog(shell).run(false, false, operation);
} else {
int imageFormat = saveAsImageDialog.getImageFormat();
byte image[] = createImage(im, imageFormat);
operation = getSaveToFileOp(shell, file, image);
}
new ProgressMonitorDialog(shell).run(false, false, operation);
} catch (Exception e) {
- String message = "Can not save image: "; //$NON-NLS-1$
- MessageDialog.openError(shell, "Can not save image", message + e.getMessage()); //$NON-NLS-1$
+ String message = "Cannot save image: "; //$NON-NLS-1$
+ MessageDialog.openError(shell, "Cannot save image", message + e.getMessage()); //$NON-NLS-1$
T.racer()
.error(METHOD, message + "\nDetails: " + GraphitiUiInternal.getTraceService().getStacktrace(e)); //$NON-NLS-1$
e.printStackTrace();
}
}
}
private IRunnableWithProgress getExportOp(final String METHOD, final Shell shell,
final ExportDiagramDialog saveAsImageDialog, final String file, final Image im,
final IDiagramsExporter exporter) {
IRunnableWithProgress operation;
operation = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) {
try {
exporter.export(im, saveAsImageDialog.getFigure(), file, saveAsImageDialog.getImageScaleFactor());
} catch (Exception e) {
handleException(shell, e);
}
}
};
return operation;
}
private void handleException(final Shell shell, Exception e) {
String message = "Can not export diagram: "; //$NON-NLS-1$
MessageDialog.openError(shell, "Can not export diagram", message + e.getMessage()); //$NON-NLS-1$
e.printStackTrace();
}
/**
* Returns an IRunnableWithProgress, which saves the given contents to a
* File with the given filename.
*
* @param shell
*
* @param filename
* The name of the file, where to save the contents.
* @param contents
* The contents to save into the file.
* @throws Exception
* On any errors that occur.
*/
private IRunnableWithProgress getSaveToFileOp(final Shell shell, final String filename, final byte contents[])
throws Exception {
IRunnableWithProgress operation = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(filename);
outputStream.write(contents);
} catch (Exception e) {
handleException(shell, e);
} finally {
try {
outputStream.close();
} catch (Exception x) {
T.racer().error("close output stream failed", x); //$NON-NLS-1$
}
}
}
};
return operation;
}
}
| true | true | public void startSaveAsImageDialog(GraphicalViewer graphicalViewer) {
final String METHOD = "startSaveAsImageDialog(graphicalViewer)"; //$NON-NLS-1$
// check extension point for exporters
Map<String, Boolean> diagramExporterTypes = ExtensionManager.getSingleton().getDiagramExporterTypes();
// configure dialog with exporters and open dialog
final Shell shell = GraphitiUiInternal.getWorkbenchService().getShell();
final ExportDiagramDialog saveAsImageDialog = new ExportDiagramDialog(shell, graphicalViewer);
saveAsImageDialog.addExporters(diagramExporterTypes);
saveAsImageDialog.open();
if (saveAsImageDialog.getReturnCode() == Window.CANCEL)
return;
// select filename with file-dialog
FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);
String fileExtensions[] = new String[] { "*." + saveAsImageDialog.getFormattedFileExtension() }; //$NON-NLS-1$
fileDialog.setFilterExtensions(fileExtensions);
String name = ((Diagram) graphicalViewer.getContents().getModel()).getName();
fileDialog.setFileName(name);
String filename = fileDialog.open();
if (filename != null) {
try {
// add extension to filename (if none exists)
IPath path = new Path(filename);
if (path.getFileExtension() == null)
filename = filename + "." + saveAsImageDialog.getFormattedFileExtension(); //$NON-NLS-1$
final String file = filename;
final Image im = saveAsImageDialog.getScaledImage();
String imageExtension = saveAsImageDialog.getFileExtension();
IRunnableWithProgress operation;
// if the exporter is non-standard, i.e. registered via
// extension point, we need to call the registered exporter.
if (diagramExporterTypes.containsKey(imageExtension)) {
final IDiagramsExporter exporter = ExtensionManager.getSingleton().getDiagramExporterForType(
imageExtension);
Assert.isNotNull(exporter);
operation = getExportOp(METHOD, shell, saveAsImageDialog, file, im, exporter);
new ProgressMonitorDialog(shell).run(false, false, operation);
} else {
int imageFormat = saveAsImageDialog.getImageFormat();
byte image[] = createImage(im, imageFormat);
operation = getSaveToFileOp(shell, file, image);
}
new ProgressMonitorDialog(shell).run(false, false, operation);
} catch (Exception e) {
String message = "Can not save image: "; //$NON-NLS-1$
MessageDialog.openError(shell, "Can not save image", message + e.getMessage()); //$NON-NLS-1$
T.racer()
.error(METHOD, message + "\nDetails: " + GraphitiUiInternal.getTraceService().getStacktrace(e)); //$NON-NLS-1$
e.printStackTrace();
}
}
}
| public void startSaveAsImageDialog(GraphicalViewer graphicalViewer) {
final String METHOD = "startSaveAsImageDialog(graphicalViewer)"; //$NON-NLS-1$
// check extension point for exporters
Map<String, Boolean> diagramExporterTypes = ExtensionManager.getSingleton().getDiagramExporterTypes();
// configure dialog with exporters and open dialog
final Shell shell = GraphitiUiInternal.getWorkbenchService().getShell();
final ExportDiagramDialog saveAsImageDialog = new ExportDiagramDialog(shell, graphicalViewer);
saveAsImageDialog.addExporters(diagramExporterTypes);
saveAsImageDialog.open();
if (saveAsImageDialog.getReturnCode() == Window.CANCEL)
return;
// select filename with file-dialog
FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);
String fileExtensions[] = new String[] { "*." + saveAsImageDialog.getFormattedFileExtension() }; //$NON-NLS-1$
fileDialog.setFilterExtensions(fileExtensions);
String name = ((Diagram) graphicalViewer.getContents().getModel()).getName();
fileDialog.setFileName(name);
String filename = fileDialog.open();
if (filename != null) {
try {
// add extension to filename (if none exists)
IPath path = new Path(filename);
if (path.getFileExtension() == null)
filename = filename + "." + saveAsImageDialog.getFormattedFileExtension(); //$NON-NLS-1$
final String file = filename;
final Image im = saveAsImageDialog.getScaledImage();
String imageExtension = saveAsImageDialog.getFileExtension();
IRunnableWithProgress operation;
// if the exporter is non-standard, i.e. registered via
// extension point, we need to call the registered exporter.
if (diagramExporterTypes.containsKey(imageExtension)) {
final IDiagramsExporter exporter = ExtensionManager.getSingleton().getDiagramExporterForType(
imageExtension);
Assert.isNotNull(exporter);
operation = getExportOp(METHOD, shell, saveAsImageDialog, file, im, exporter);
new ProgressMonitorDialog(shell).run(false, false, operation);
} else {
int imageFormat = saveAsImageDialog.getImageFormat();
byte image[] = createImage(im, imageFormat);
operation = getSaveToFileOp(shell, file, image);
}
new ProgressMonitorDialog(shell).run(false, false, operation);
} catch (Exception e) {
String message = "Cannot save image: "; //$NON-NLS-1$
MessageDialog.openError(shell, "Cannot save image", message + e.getMessage()); //$NON-NLS-1$
T.racer()
.error(METHOD, message + "\nDetails: " + GraphitiUiInternal.getTraceService().getStacktrace(e)); //$NON-NLS-1$
e.printStackTrace();
}
}
}
|
diff --git a/src/com/fernferret/wolfpound/WPPlayerListener.java b/src/com/fernferret/wolfpound/WPPlayerListener.java
index a19b55c..65bca5a 100644
--- a/src/com/fernferret/wolfpound/WPPlayerListener.java
+++ b/src/com/fernferret/wolfpound/WPPlayerListener.java
@@ -1,72 +1,72 @@
package com.fernferret.wolfpound;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.craftbukkit.block.CraftSign;
import com.earth2me.essentials.User;
import com.nijiko.coelho.iConomy.iConomy;
public class WPPlayerListener extends PlayerListener {
private final WolfPound plugin;
public WPPlayerListener(final WolfPound plugin) {
this.plugin = plugin;
}
@Override
public void onPlayerInteract(PlayerInteractEvent event) {
Player p = event.getPlayer();
- if (event.getClickedBlock().getState() instanceof Sign && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
+ if (event.hasBlock() && event.getClickedBlock().getState() instanceof Sign && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (plugin.blockIsValidWolfSign(event.getClickedBlock()) && plugin.hasPermission(p, "wolfpound.use")) {
// We have a valid pound!
double price = getPriceFromBlock(event.getClickedBlock(), 1);
if (price == 0 || (!WolfPound.useiConomy && !WolfPound.useEssentials)) {
plugin.spawnWolf(p);
} else if (WolfPound.useiConomy) {
if (iConomy.getBank().getAccount(p.getName()).hasEnough(price)) {
iConomy.getBank().getAccount(p.getName()).subtract(price);
p.sendMessage(ChatColor.WHITE + "[WolfPound]" + ChatColor.RED
+ " You have been charged " + price + " "
+ iConomy.getBank().getCurrency());
plugin.spawnWolf(p);
} else {
userIsTooPoor(p);
return;
}
} else if (WolfPound.useEssentials) {
User user = User.get(event.getPlayer());
if (user.getMoney() >= price) {
user.takeMoney(price);
plugin.spawnWolf(p);
} else {
userIsTooPoor(p);
return;
}
}
}
}
}
private Double getPriceFromBlock(Block b, int i) {
try {
Sign s = new CraftSign(b);
return Double.parseDouble(s.getLine(i).replaceAll("\\D", ""));
} catch (NumberFormatException e) {
// We'll return the default
}
return 0.0;
}
private void userIsTooPoor(Player p) {
p.sendMessage("Sorry but you do not have the required funds for a wolf");
}
}
| true | true | public void onPlayerInteract(PlayerInteractEvent event) {
Player p = event.getPlayer();
if (event.getClickedBlock().getState() instanceof Sign && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (plugin.blockIsValidWolfSign(event.getClickedBlock()) && plugin.hasPermission(p, "wolfpound.use")) {
// We have a valid pound!
double price = getPriceFromBlock(event.getClickedBlock(), 1);
if (price == 0 || (!WolfPound.useiConomy && !WolfPound.useEssentials)) {
plugin.spawnWolf(p);
} else if (WolfPound.useiConomy) {
if (iConomy.getBank().getAccount(p.getName()).hasEnough(price)) {
iConomy.getBank().getAccount(p.getName()).subtract(price);
p.sendMessage(ChatColor.WHITE + "[WolfPound]" + ChatColor.RED
+ " You have been charged " + price + " "
+ iConomy.getBank().getCurrency());
plugin.spawnWolf(p);
} else {
userIsTooPoor(p);
return;
}
} else if (WolfPound.useEssentials) {
User user = User.get(event.getPlayer());
if (user.getMoney() >= price) {
user.takeMoney(price);
plugin.spawnWolf(p);
} else {
userIsTooPoor(p);
return;
}
}
}
}
}
| public void onPlayerInteract(PlayerInteractEvent event) {
Player p = event.getPlayer();
if (event.hasBlock() && event.getClickedBlock().getState() instanceof Sign && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (plugin.blockIsValidWolfSign(event.getClickedBlock()) && plugin.hasPermission(p, "wolfpound.use")) {
// We have a valid pound!
double price = getPriceFromBlock(event.getClickedBlock(), 1);
if (price == 0 || (!WolfPound.useiConomy && !WolfPound.useEssentials)) {
plugin.spawnWolf(p);
} else if (WolfPound.useiConomy) {
if (iConomy.getBank().getAccount(p.getName()).hasEnough(price)) {
iConomy.getBank().getAccount(p.getName()).subtract(price);
p.sendMessage(ChatColor.WHITE + "[WolfPound]" + ChatColor.RED
+ " You have been charged " + price + " "
+ iConomy.getBank().getCurrency());
plugin.spawnWolf(p);
} else {
userIsTooPoor(p);
return;
}
} else if (WolfPound.useEssentials) {
User user = User.get(event.getPlayer());
if (user.getMoney() >= price) {
user.takeMoney(price);
plugin.spawnWolf(p);
} else {
userIsTooPoor(p);
return;
}
}
}
}
}
|
diff --git a/src/com/epam/memegen/MemesServlet.java b/src/com/epam/memegen/MemesServlet.java
index a6d542f..bac1ea7 100644
--- a/src/com/epam/memegen/MemesServlet.java
+++ b/src/com/epam/memegen/MemesServlet.java
@@ -1,30 +1,30 @@
package com.epam.memegen;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class MemesServlet extends HttpServlet {
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(MemesServlet.class.getName());
private final MemeDao memeDao = new MemeDao();
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
resp.setHeader("X-Chrome-Exponential-Throttling", "disable");
String filter = req.getParameter("filter");
- if (filter.isEmpty()) {
+ if (Util.isNullOrEmpty(filter)) {
filter = "popular";
}
String json = memeDao.getAllAsJson(req, filter);
resp.getWriter().write(json);
}
}
| true | true | public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
resp.setHeader("X-Chrome-Exponential-Throttling", "disable");
String filter = req.getParameter("filter");
if (filter.isEmpty()) {
filter = "popular";
}
String json = memeDao.getAllAsJson(req, filter);
resp.getWriter().write(json);
}
| public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
resp.setHeader("X-Chrome-Exponential-Throttling", "disable");
String filter = req.getParameter("filter");
if (Util.isNullOrEmpty(filter)) {
filter = "popular";
}
String json = memeDao.getAllAsJson(req, filter);
resp.getWriter().write(json);
}
|
diff --git a/library/src/main/java/net/sourceforge/cilib/entity/operators/crossover/real/UnimodalNormalDistributionCrossoverStrategy.java b/library/src/main/java/net/sourceforge/cilib/entity/operators/crossover/real/UnimodalNormalDistributionCrossoverStrategy.java
index dc499e50..b01f0c97 100644
--- a/library/src/main/java/net/sourceforge/cilib/entity/operators/crossover/real/UnimodalNormalDistributionCrossoverStrategy.java
+++ b/library/src/main/java/net/sourceforge/cilib/entity/operators/crossover/real/UnimodalNormalDistributionCrossoverStrategy.java
@@ -1,226 +1,226 @@
/** __ __
* _____ _/ /_/ /_ Computational Intelligence Library (CIlib)
* / ___/ / / / __ \ (c) CIRG @ UP
* / /__/ / / / /_/ / http://cilib.net
* \___/_/_/_/_.___/
*/
package net.sourceforge.cilib.entity.operators.crossover.real;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.collect.Lists;
import fj.P1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.sourceforge.cilib.controlparameter.ConstantControlParameter;
import net.sourceforge.cilib.controlparameter.ControlParameter;
import net.sourceforge.cilib.entity.Entity;
import net.sourceforge.cilib.entity.operators.crossover.CrossoverStrategy;
import net.sourceforge.cilib.math.random.GaussianDistribution;
import net.sourceforge.cilib.math.random.UniformDistribution;
import net.sourceforge.cilib.type.types.container.Vector;
import net.sourceforge.cilib.util.Vectors;
import net.sourceforge.cilib.util.functions.Entities;
/**
* <p> Parent Centric Crossover Strategy </p>
*
* <p> References: </p>
*
* <p> Ono, I. & Kobayashi, S. A Real-coded Genetic
* Algorithm for Function Optimization Using Unimodal Normal Distribution
* Crossover. Proceedings of the Seventh International Conference on Genetic
* Algorithms ICGA97 14, 246-253 (1997). </p>
*
* <p> The code is based on the MOEA
* Framework under the LGPL license: http://www.moeaframework.org </p>
*/
public class UnimodalNormalDistributionCrossoverStrategy implements CrossoverStrategy {
private ControlParameter numberOfParents;
private ControlParameter numberOfOffspring;
private ControlParameter sigma1;
private ControlParameter sigma2;
private final GaussianDistribution random;
private boolean useIndividualProviders;
/**
* Default constructor.
*/
public UnimodalNormalDistributionCrossoverStrategy() {
this.numberOfParents = ConstantControlParameter.of(3);
this.numberOfOffspring = ConstantControlParameter.of(1);
this.sigma1 = ConstantControlParameter.of(0.1);
this.sigma2 = ConstantControlParameter.of(0.1);
this.random = new GaussianDistribution();
this.useIndividualProviders = true;
}
/**
* Copy constructor.
*
* @param copy
*/
public UnimodalNormalDistributionCrossoverStrategy(UnimodalNormalDistributionCrossoverStrategy copy) {
this.numberOfOffspring = copy.numberOfOffspring;
this.sigma1 = copy.sigma1.getClone();
this.sigma2 = copy.sigma2.getClone();
this.random = copy.random;
this.useIndividualProviders = copy.useIndividualProviders;
this.numberOfParents = copy.numberOfParents;
}
/**
* {@inheritDoc}
*/
@Override
public UnimodalNormalDistributionCrossoverStrategy getClone() {
return new UnimodalNormalDistributionCrossoverStrategy(this);
}
/**
* {@inheritDoc}
*/
@Override
public <E extends Entity> List<E> crossover(List<E> parentCollection) {
checkState(parentCollection.size() >= 3, "There must be a minimum of three parents to perform UNDX crossover.");
checkState(numberOfOffspring.getParameter() > 0, "At least one offspring must be generated. Check 'numberOfOffspring'.");
List<Vector> solutions = Entities.<Vector, E>getCandidateSolutions(parentCollection);
List<E> offspring = Lists.newArrayListWithCapacity((int) numberOfOffspring.getParameter());
UniformDistribution randomParent = new UniformDistribution();
final int k = solutions.size();
final int n = solutions.get(0).size();
for (int os = 0; os < numberOfOffspring.getParameter(); os++) {
//get index of main parent and put its solution at the end of the list
int parent = (int) randomParent.getRandomNumber(0.0, k);
Collections.swap(solutions, parent, k - 1);
List<Vector> e_zeta = new ArrayList<>();
//calculate mean of parents except main parent
Vector g = Vectors.mean(fj.data.List.iterableList(solutions.subList(0, k - 1))).valueE("Error in getting mean");
// basis vectors defined by parents
for (int i = 0; i < k - 1; i++) {
Vector d = solutions.get(i).subtract(g);
if (!d.isZero()) {
double dbar = d.length();
Vector e = d.orthogonalize(e_zeta);
if (!e.isZero()) {
e_zeta.add(e.normalize().multiply(dbar));
}
}
}
final double D = solutions.get(k - 1).subtract(g).length();
// create the remaining basis vectors
fj.data.List<Vector> e_eta = fj.data.List.nil();
- e_eta.snoc(solutions.get(k - 1).subtract(g));
+ e_eta = e_eta.snoc(solutions.get(k - 1).subtract(g));
for (int i = 0; i < n - e_zeta.size() - 1; i++) {
Vector d = Vector.newBuilder().copyOf(g).buildRandom();
- e_eta.snoc(d);
+ e_eta = e_eta.snoc(d);
}
e_eta = Vectors.orthonormalize(fj.data.List.iterableList(e_eta));
// construct the offspring
Vector variables = Vector.copyOf(g);
if (!useIndividualProviders) {
for (int i = 0; i < e_zeta.size(); i++) {
variables = variables.plus(e_zeta.get(i).multiply(random.getRandomNumber(0.0, sigma1.getParameter())));
}
for (int i = 0; i < e_eta.length(); i++) {
variables = variables.plus(e_eta.index(i).multiply(D * random.getRandomNumber(0.0, sigma2.getParameter() / Math.sqrt(n))));
}
} else {
for (int i = 0; i < e_zeta.size(); i++) {
variables = variables.plus(e_zeta.get(i).multiply(new P1<Number>() {
@Override
public Number _1() {
return random.getRandomNumber(0.0, sigma1.getParameter());
}
}));
}
for (int i = 0; i < e_eta.length(); i++) {
variables = variables.plus(e_eta.index(i).multiply(new P1<Number>() {
@Override
public Number _1() {
return D * random.getRandomNumber(0.0, sigma2.getParameter() / Math.sqrt(n));
}
}));
}
}
E child = (E) parentCollection.get(parent).getClone();
child.setCandidateSolution(variables);
offspring.add(child);
}
return offspring;
}
/**
* Sets the deviation for the first Gaussian number
*
* @param dev The deviation to use
*/
public void setSigma1(ControlParameter dev) {
this.sigma1 = dev;
}
/**
* Sets the deviation for the second Gaussian number
*
* @param dev The deviation to use
*/
public void setSigma2(ControlParameter dev) {
this.sigma2 = dev;
}
/**
* Sets the number of offspring to calculate
*
* @param numberOfOffspring The number of offspring required
*/
public void setNumberOfOffspring(ControlParameter numberOfOffspring) {
this.numberOfOffspring = numberOfOffspring;
}
/**
* Sets whether to use different random numbers for different dimensions.
*
* @param useIndividualProviders
*/
public void setUseIndividualProviders(boolean useIndividualProviders) {
this.useIndividualProviders = useIndividualProviders;
}
@Override
public int getNumberOfParents() {
return (int) numberOfParents.getParameter();
}
public void setNumberOfParents(ControlParameter numberOfParents) {
this.numberOfParents = numberOfParents;
}
@Override
public void setCrossoverPointProbability(double crossoverPointProbability) {
throw new UnsupportedOperationException("Not applicable");
}
@Override
public ControlParameter getCrossoverPointProbability() {
throw new UnsupportedOperationException("Not applicable");
}
}
| false | true | public <E extends Entity> List<E> crossover(List<E> parentCollection) {
checkState(parentCollection.size() >= 3, "There must be a minimum of three parents to perform UNDX crossover.");
checkState(numberOfOffspring.getParameter() > 0, "At least one offspring must be generated. Check 'numberOfOffspring'.");
List<Vector> solutions = Entities.<Vector, E>getCandidateSolutions(parentCollection);
List<E> offspring = Lists.newArrayListWithCapacity((int) numberOfOffspring.getParameter());
UniformDistribution randomParent = new UniformDistribution();
final int k = solutions.size();
final int n = solutions.get(0).size();
for (int os = 0; os < numberOfOffspring.getParameter(); os++) {
//get index of main parent and put its solution at the end of the list
int parent = (int) randomParent.getRandomNumber(0.0, k);
Collections.swap(solutions, parent, k - 1);
List<Vector> e_zeta = new ArrayList<>();
//calculate mean of parents except main parent
Vector g = Vectors.mean(fj.data.List.iterableList(solutions.subList(0, k - 1))).valueE("Error in getting mean");
// basis vectors defined by parents
for (int i = 0; i < k - 1; i++) {
Vector d = solutions.get(i).subtract(g);
if (!d.isZero()) {
double dbar = d.length();
Vector e = d.orthogonalize(e_zeta);
if (!e.isZero()) {
e_zeta.add(e.normalize().multiply(dbar));
}
}
}
final double D = solutions.get(k - 1).subtract(g).length();
// create the remaining basis vectors
fj.data.List<Vector> e_eta = fj.data.List.nil();
e_eta.snoc(solutions.get(k - 1).subtract(g));
for (int i = 0; i < n - e_zeta.size() - 1; i++) {
Vector d = Vector.newBuilder().copyOf(g).buildRandom();
e_eta.snoc(d);
}
e_eta = Vectors.orthonormalize(fj.data.List.iterableList(e_eta));
// construct the offspring
Vector variables = Vector.copyOf(g);
if (!useIndividualProviders) {
for (int i = 0; i < e_zeta.size(); i++) {
variables = variables.plus(e_zeta.get(i).multiply(random.getRandomNumber(0.0, sigma1.getParameter())));
}
for (int i = 0; i < e_eta.length(); i++) {
variables = variables.plus(e_eta.index(i).multiply(D * random.getRandomNumber(0.0, sigma2.getParameter() / Math.sqrt(n))));
}
} else {
for (int i = 0; i < e_zeta.size(); i++) {
variables = variables.plus(e_zeta.get(i).multiply(new P1<Number>() {
@Override
public Number _1() {
return random.getRandomNumber(0.0, sigma1.getParameter());
}
}));
}
for (int i = 0; i < e_eta.length(); i++) {
variables = variables.plus(e_eta.index(i).multiply(new P1<Number>() {
@Override
public Number _1() {
return D * random.getRandomNumber(0.0, sigma2.getParameter() / Math.sqrt(n));
}
}));
}
}
E child = (E) parentCollection.get(parent).getClone();
child.setCandidateSolution(variables);
offspring.add(child);
}
return offspring;
}
| public <E extends Entity> List<E> crossover(List<E> parentCollection) {
checkState(parentCollection.size() >= 3, "There must be a minimum of three parents to perform UNDX crossover.");
checkState(numberOfOffspring.getParameter() > 0, "At least one offspring must be generated. Check 'numberOfOffspring'.");
List<Vector> solutions = Entities.<Vector, E>getCandidateSolutions(parentCollection);
List<E> offspring = Lists.newArrayListWithCapacity((int) numberOfOffspring.getParameter());
UniformDistribution randomParent = new UniformDistribution();
final int k = solutions.size();
final int n = solutions.get(0).size();
for (int os = 0; os < numberOfOffspring.getParameter(); os++) {
//get index of main parent and put its solution at the end of the list
int parent = (int) randomParent.getRandomNumber(0.0, k);
Collections.swap(solutions, parent, k - 1);
List<Vector> e_zeta = new ArrayList<>();
//calculate mean of parents except main parent
Vector g = Vectors.mean(fj.data.List.iterableList(solutions.subList(0, k - 1))).valueE("Error in getting mean");
// basis vectors defined by parents
for (int i = 0; i < k - 1; i++) {
Vector d = solutions.get(i).subtract(g);
if (!d.isZero()) {
double dbar = d.length();
Vector e = d.orthogonalize(e_zeta);
if (!e.isZero()) {
e_zeta.add(e.normalize().multiply(dbar));
}
}
}
final double D = solutions.get(k - 1).subtract(g).length();
// create the remaining basis vectors
fj.data.List<Vector> e_eta = fj.data.List.nil();
e_eta = e_eta.snoc(solutions.get(k - 1).subtract(g));
for (int i = 0; i < n - e_zeta.size() - 1; i++) {
Vector d = Vector.newBuilder().copyOf(g).buildRandom();
e_eta = e_eta.snoc(d);
}
e_eta = Vectors.orthonormalize(fj.data.List.iterableList(e_eta));
// construct the offspring
Vector variables = Vector.copyOf(g);
if (!useIndividualProviders) {
for (int i = 0; i < e_zeta.size(); i++) {
variables = variables.plus(e_zeta.get(i).multiply(random.getRandomNumber(0.0, sigma1.getParameter())));
}
for (int i = 0; i < e_eta.length(); i++) {
variables = variables.plus(e_eta.index(i).multiply(D * random.getRandomNumber(0.0, sigma2.getParameter() / Math.sqrt(n))));
}
} else {
for (int i = 0; i < e_zeta.size(); i++) {
variables = variables.plus(e_zeta.get(i).multiply(new P1<Number>() {
@Override
public Number _1() {
return random.getRandomNumber(0.0, sigma1.getParameter());
}
}));
}
for (int i = 0; i < e_eta.length(); i++) {
variables = variables.plus(e_eta.index(i).multiply(new P1<Number>() {
@Override
public Number _1() {
return D * random.getRandomNumber(0.0, sigma2.getParameter() / Math.sqrt(n));
}
}));
}
}
E child = (E) parentCollection.get(parent).getClone();
child.setCandidateSolution(variables);
offspring.add(child);
}
return offspring;
}
|
diff --git a/src/ru/leks13/jabbertimer/UserCommand.java b/src/ru/leks13/jabbertimer/UserCommand.java
index 601b1c5..bb916d4 100644
--- a/src/ru/leks13/jabbertimer/UserCommand.java
+++ b/src/ru/leks13/jabbertimer/UserCommand.java
@@ -1,186 +1,186 @@
/*
* Leks13
* GPL v3
*/
package ru.leks13.jabbertimer;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
public class UserCommand {
public static String muc;
public static Boolean doUserCommand(String command, String jid, String admin) throws XMPPException, IOException, NumberFormatException, ClassNotFoundException, SQLException, ParseException {
Boolean ans = false;
String msg = null;
if (command.startsWith("!report") && !ans) {
command = new StringBuffer(command).delete(0, 7).toString();
msg = command + " - " + jid;
XmppNet.sendMessage(admin, msg);
ans = true;
}
if (command.startsWith("!list") && !ans) {
java.util.Date today = new java.util.Date();
long time = (System.currentTimeMillis());
msg = Sql.listOfTimer(jid);
XmppNet.sendMessage(jid, msg);
ans = true;
}
if (command.startsWith("!remind") && !ans) {
command = command.replaceAll("!remind ", "");
java.util.Date today = new java.util.Date();
long time = (System.currentTimeMillis());
StringTokenizer st = new StringTokenizer(command, "@");
String noteU = "";
while (st.hasMoreTokens()) {
command = st.nextToken();
if (!st.hasMoreElements()) {
NullNoteEx(jid);
}
noteU = st.nextToken();
}
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
Date dt = null;
try {
dt = sdf.parse(command);
} catch (ParseException e) {
msg = "Wrong date!";
XmppNet.sendMessage(jid, msg);
ans = true;
}
long dt1 = dt.getTime() / 1000;
if (!ans) {
if (dt1 > (time / 1000)) {
Sql.add(dt1, jid, Main.id, noteU);
msg = "Timer is set!";
} else {
msg = "Wrong date";
}
}
XmppNet.sendMessage(jid, msg);
ans = true;
Main.id++;
}
if (command.startsWith("!note") && !ans) {
command = command.replaceAll("!note ", "");
Long time = 0L;
if (!ans) {
Sql.add(time, jid, Main.id, command);
}
ans = true;
msg = "Writed!";
XmppNet.sendMessage(jid, msg);
Main.id++;
}
if (command.startsWith("!my") && !ans) {
msg = Sql.listOfNote(jid);
ans = true;
XmppNet.sendMessage(jid, msg);
Main.id++;
}
if (command.startsWith("!del") && !ans) {
command = command.replaceAll("!del #", "");
if (!ans) {
Sql.deleteNote(jid, command);
}
ans = true;
msg = "Command complete";
XmppNet.sendMessage(jid, msg);
Main.id++;
}
try {
if (command.startsWith("!timer") && !ans) {
command = command.replaceAll("!timer ", "");
java.util.Date today = new java.util.Date();
long time = (System.currentTimeMillis());
StringTokenizer st = new StringTokenizer(command, "@");
String noteU = "";
while (st.hasMoreTokens()) {
command = st.nextToken();
if (!st.hasMoreElements()) {
NullNoteEx(jid);
}
noteU = st.nextToken();
}
if (Long.parseLong(command) < 1 || Long.parseLong(command) > 120) {
throw new NumberFormatException();
}
long timeDo = ((time + Long.parseLong(command) * 1000 * 60) / 1000L);
if (!ans) {
Sql.add(timeDo, jid, Main.id, noteU);
}
ans = true;
msg = "Timer is set!";
XmppNet.sendMessage(jid, msg);
Main.id++;
}
} catch (NumberFormatException ex1) {
ans = true;
XmppNet.sendMessage(jid, "Wrong timer interval \n"
+ "The permissible range of 1 to 120 minutes.");
}
if (command.startsWith("!off") && !ans && jid.contains(admin)) {
XmppNet.disconnect();
ans = true;
}
if (command.startsWith("!roster") && !ans && jid.contains(admin)) {
msg = XmppNet.getXmppRoster();
XmppNet.sendMessage(jid, msg);
ans = true;
}
if (command.startsWith("!status") && !ans && jid.contains(admin)) {
command = new StringBuffer(command).delete(0, 8).toString();
String status = command;
Presence presence = new Presence(Presence.Type.available);
presence.setStatus(status);
XmppNet.connection.sendPacket(presence);
ans = true;
}
if (command.equals("!help")) {
msg = "Commands: \n"
+ "!report <message> - send <message> to admin \n \n"
- + "!remind <dd.mm.yyy HH:mm>@<remind> - set a reminder on this date \n"
+ + "!remind <dd.mm.yyyy HH:mm>@<remind> - set a reminder on this date \n"
+ " For example !remind 03.10.2012 18:51@Hello \n \n"
+ "!timer <minutes>@<remind> - set timer. \n"
+ " For example '!timer 2@Hello' send after 2 minutes 'Hello' \n \n"
+ "!list - list of installed timers \n \n"
+ "Notes: \n"
+ "!my - list of notes \n"
+ "!note 'text' - write note \n"
+ "!del #1234567890 - delete note with number #1234567890 \n";
XmppNet.sendMessage(jid, msg);
ans = true;
}
return ans;
}
private static void NullNoteEx(String jid) throws XMPPException {
XmppNet.sendMessage(jid, "Blank or invalid string reminder!");
}
}
| true | true | public static Boolean doUserCommand(String command, String jid, String admin) throws XMPPException, IOException, NumberFormatException, ClassNotFoundException, SQLException, ParseException {
Boolean ans = false;
String msg = null;
if (command.startsWith("!report") && !ans) {
command = new StringBuffer(command).delete(0, 7).toString();
msg = command + " - " + jid;
XmppNet.sendMessage(admin, msg);
ans = true;
}
if (command.startsWith("!list") && !ans) {
java.util.Date today = new java.util.Date();
long time = (System.currentTimeMillis());
msg = Sql.listOfTimer(jid);
XmppNet.sendMessage(jid, msg);
ans = true;
}
if (command.startsWith("!remind") && !ans) {
command = command.replaceAll("!remind ", "");
java.util.Date today = new java.util.Date();
long time = (System.currentTimeMillis());
StringTokenizer st = new StringTokenizer(command, "@");
String noteU = "";
while (st.hasMoreTokens()) {
command = st.nextToken();
if (!st.hasMoreElements()) {
NullNoteEx(jid);
}
noteU = st.nextToken();
}
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
Date dt = null;
try {
dt = sdf.parse(command);
} catch (ParseException e) {
msg = "Wrong date!";
XmppNet.sendMessage(jid, msg);
ans = true;
}
long dt1 = dt.getTime() / 1000;
if (!ans) {
if (dt1 > (time / 1000)) {
Sql.add(dt1, jid, Main.id, noteU);
msg = "Timer is set!";
} else {
msg = "Wrong date";
}
}
XmppNet.sendMessage(jid, msg);
ans = true;
Main.id++;
}
if (command.startsWith("!note") && !ans) {
command = command.replaceAll("!note ", "");
Long time = 0L;
if (!ans) {
Sql.add(time, jid, Main.id, command);
}
ans = true;
msg = "Writed!";
XmppNet.sendMessage(jid, msg);
Main.id++;
}
if (command.startsWith("!my") && !ans) {
msg = Sql.listOfNote(jid);
ans = true;
XmppNet.sendMessage(jid, msg);
Main.id++;
}
if (command.startsWith("!del") && !ans) {
command = command.replaceAll("!del #", "");
if (!ans) {
Sql.deleteNote(jid, command);
}
ans = true;
msg = "Command complete";
XmppNet.sendMessage(jid, msg);
Main.id++;
}
try {
if (command.startsWith("!timer") && !ans) {
command = command.replaceAll("!timer ", "");
java.util.Date today = new java.util.Date();
long time = (System.currentTimeMillis());
StringTokenizer st = new StringTokenizer(command, "@");
String noteU = "";
while (st.hasMoreTokens()) {
command = st.nextToken();
if (!st.hasMoreElements()) {
NullNoteEx(jid);
}
noteU = st.nextToken();
}
if (Long.parseLong(command) < 1 || Long.parseLong(command) > 120) {
throw new NumberFormatException();
}
long timeDo = ((time + Long.parseLong(command) * 1000 * 60) / 1000L);
if (!ans) {
Sql.add(timeDo, jid, Main.id, noteU);
}
ans = true;
msg = "Timer is set!";
XmppNet.sendMessage(jid, msg);
Main.id++;
}
} catch (NumberFormatException ex1) {
ans = true;
XmppNet.sendMessage(jid, "Wrong timer interval \n"
+ "The permissible range of 1 to 120 minutes.");
}
if (command.startsWith("!off") && !ans && jid.contains(admin)) {
XmppNet.disconnect();
ans = true;
}
if (command.startsWith("!roster") && !ans && jid.contains(admin)) {
msg = XmppNet.getXmppRoster();
XmppNet.sendMessage(jid, msg);
ans = true;
}
if (command.startsWith("!status") && !ans && jid.contains(admin)) {
command = new StringBuffer(command).delete(0, 8).toString();
String status = command;
Presence presence = new Presence(Presence.Type.available);
presence.setStatus(status);
XmppNet.connection.sendPacket(presence);
ans = true;
}
if (command.equals("!help")) {
msg = "Commands: \n"
+ "!report <message> - send <message> to admin \n \n"
+ "!remind <dd.mm.yyy HH:mm>@<remind> - set a reminder on this date \n"
+ " For example !remind 03.10.2012 18:51@Hello \n \n"
+ "!timer <minutes>@<remind> - set timer. \n"
+ " For example '!timer 2@Hello' send after 2 minutes 'Hello' \n \n"
+ "!list - list of installed timers \n \n"
+ "Notes: \n"
+ "!my - list of notes \n"
+ "!note 'text' - write note \n"
+ "!del #1234567890 - delete note with number #1234567890 \n";
XmppNet.sendMessage(jid, msg);
ans = true;
}
return ans;
}
| public static Boolean doUserCommand(String command, String jid, String admin) throws XMPPException, IOException, NumberFormatException, ClassNotFoundException, SQLException, ParseException {
Boolean ans = false;
String msg = null;
if (command.startsWith("!report") && !ans) {
command = new StringBuffer(command).delete(0, 7).toString();
msg = command + " - " + jid;
XmppNet.sendMessage(admin, msg);
ans = true;
}
if (command.startsWith("!list") && !ans) {
java.util.Date today = new java.util.Date();
long time = (System.currentTimeMillis());
msg = Sql.listOfTimer(jid);
XmppNet.sendMessage(jid, msg);
ans = true;
}
if (command.startsWith("!remind") && !ans) {
command = command.replaceAll("!remind ", "");
java.util.Date today = new java.util.Date();
long time = (System.currentTimeMillis());
StringTokenizer st = new StringTokenizer(command, "@");
String noteU = "";
while (st.hasMoreTokens()) {
command = st.nextToken();
if (!st.hasMoreElements()) {
NullNoteEx(jid);
}
noteU = st.nextToken();
}
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
Date dt = null;
try {
dt = sdf.parse(command);
} catch (ParseException e) {
msg = "Wrong date!";
XmppNet.sendMessage(jid, msg);
ans = true;
}
long dt1 = dt.getTime() / 1000;
if (!ans) {
if (dt1 > (time / 1000)) {
Sql.add(dt1, jid, Main.id, noteU);
msg = "Timer is set!";
} else {
msg = "Wrong date";
}
}
XmppNet.sendMessage(jid, msg);
ans = true;
Main.id++;
}
if (command.startsWith("!note") && !ans) {
command = command.replaceAll("!note ", "");
Long time = 0L;
if (!ans) {
Sql.add(time, jid, Main.id, command);
}
ans = true;
msg = "Writed!";
XmppNet.sendMessage(jid, msg);
Main.id++;
}
if (command.startsWith("!my") && !ans) {
msg = Sql.listOfNote(jid);
ans = true;
XmppNet.sendMessage(jid, msg);
Main.id++;
}
if (command.startsWith("!del") && !ans) {
command = command.replaceAll("!del #", "");
if (!ans) {
Sql.deleteNote(jid, command);
}
ans = true;
msg = "Command complete";
XmppNet.sendMessage(jid, msg);
Main.id++;
}
try {
if (command.startsWith("!timer") && !ans) {
command = command.replaceAll("!timer ", "");
java.util.Date today = new java.util.Date();
long time = (System.currentTimeMillis());
StringTokenizer st = new StringTokenizer(command, "@");
String noteU = "";
while (st.hasMoreTokens()) {
command = st.nextToken();
if (!st.hasMoreElements()) {
NullNoteEx(jid);
}
noteU = st.nextToken();
}
if (Long.parseLong(command) < 1 || Long.parseLong(command) > 120) {
throw new NumberFormatException();
}
long timeDo = ((time + Long.parseLong(command) * 1000 * 60) / 1000L);
if (!ans) {
Sql.add(timeDo, jid, Main.id, noteU);
}
ans = true;
msg = "Timer is set!";
XmppNet.sendMessage(jid, msg);
Main.id++;
}
} catch (NumberFormatException ex1) {
ans = true;
XmppNet.sendMessage(jid, "Wrong timer interval \n"
+ "The permissible range of 1 to 120 minutes.");
}
if (command.startsWith("!off") && !ans && jid.contains(admin)) {
XmppNet.disconnect();
ans = true;
}
if (command.startsWith("!roster") && !ans && jid.contains(admin)) {
msg = XmppNet.getXmppRoster();
XmppNet.sendMessage(jid, msg);
ans = true;
}
if (command.startsWith("!status") && !ans && jid.contains(admin)) {
command = new StringBuffer(command).delete(0, 8).toString();
String status = command;
Presence presence = new Presence(Presence.Type.available);
presence.setStatus(status);
XmppNet.connection.sendPacket(presence);
ans = true;
}
if (command.equals("!help")) {
msg = "Commands: \n"
+ "!report <message> - send <message> to admin \n \n"
+ "!remind <dd.mm.yyyy HH:mm>@<remind> - set a reminder on this date \n"
+ " For example !remind 03.10.2012 18:51@Hello \n \n"
+ "!timer <minutes>@<remind> - set timer. \n"
+ " For example '!timer 2@Hello' send after 2 minutes 'Hello' \n \n"
+ "!list - list of installed timers \n \n"
+ "Notes: \n"
+ "!my - list of notes \n"
+ "!note 'text' - write note \n"
+ "!del #1234567890 - delete note with number #1234567890 \n";
XmppNet.sendMessage(jid, msg);
ans = true;
}
return ans;
}
|
diff --git a/WebService/src/edu/cmu/ebiz/task8/formbean/SimpleSearchForm.java b/WebService/src/edu/cmu/ebiz/task8/formbean/SimpleSearchForm.java
index 712a052..642b1ae 100644
--- a/WebService/src/edu/cmu/ebiz/task8/formbean/SimpleSearchForm.java
+++ b/WebService/src/edu/cmu/ebiz/task8/formbean/SimpleSearchForm.java
@@ -1,67 +1,67 @@
package edu.cmu.ebiz.task8.formbean;
import java.util.ArrayList;
import java.util.List;
import org.mybeans.form.FormBean;
public class SimpleSearchForm extends FormBean{
private String searchPlaces;
private String placeTypes;
private String longitude;
private String latitude;
private String searchLocation;
public List<String> getValidationErrors() {
List<String> errors = new ArrayList<String>();
//System.out.println(longitude);
return errors;
}
public String getSearchPlaces() {
return searchPlaces;
}
public void setSearchPlaces(String searchPlaces) {
this.searchPlaces = trimAndConvert(searchPlaces.trim(), "<>\"");
}
public String getPlaceTypes() {
return placeTypes;
}
public void setPlaceTypes(String placeTypes) {
this.placeTypes = placeTypes;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = trimAndConvert(longitude.trim(), "<>\"");
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = trimAndConvert(latitude.trim(), "<>\"");
}
public String getSearchLocation() {
return searchLocation;
}
public void setSearchLocation(String searchLocation) {
this.searchLocation = trimAndConvert(searchLocation.trim(), "<>\"");
String[] tmp = searchLocation.split(" ");
for (String term : tmp){
- this.searchLocation += term;
+ this.searchLocation += "%20" + term ;
}
}
}
| true | true | public void setSearchLocation(String searchLocation) {
this.searchLocation = trimAndConvert(searchLocation.trim(), "<>\"");
String[] tmp = searchLocation.split(" ");
for (String term : tmp){
this.searchLocation += term;
}
}
| public void setSearchLocation(String searchLocation) {
this.searchLocation = trimAndConvert(searchLocation.trim(), "<>\"");
String[] tmp = searchLocation.split(" ");
for (String term : tmp){
this.searchLocation += "%20" + term ;
}
}
|
diff --git a/content/src/org/riotfamily/pages/mapping/PageResolver.java b/content/src/org/riotfamily/pages/mapping/PageResolver.java
index 6978f69f9..caa9c3877 100644
--- a/content/src/org/riotfamily/pages/mapping/PageResolver.java
+++ b/content/src/org/riotfamily/pages/mapping/PageResolver.java
@@ -1,149 +1,149 @@
/* 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.riotfamily.pages.mapping;
import javax.servlet.http.HttpServletRequest;
import org.riotfamily.common.util.FormatUtils;
import org.riotfamily.common.web.support.ServletUtils;
import org.riotfamily.components.support.EditModeUtils;
import org.riotfamily.pages.config.SystemPageType;
import org.riotfamily.pages.model.ContentPage;
import org.riotfamily.pages.model.Page;
import org.riotfamily.pages.model.Site;
/**
* @author Carsten Woelk [cwoelk at neteye dot de]
* @author Felix Gnass [fgnass at neteye dot de]
* @since 7.0
*/
public final class PageResolver {
public static final String SITE_ATTRIBUTE = PageResolver.class.getName() + ".site";
public static final String PAGE_ATTRIBUTE = PageResolver.class.getName() + ".page";
private static final Object NOT_FOUND = new Object();
private PageResolver() {
}
/**
* Returns the first Site that matches the given request. The PathCompleter
* is used to strip the servlet mapping from the request URI.
* @return The first matching Site, or <code>null</code> if no match is found
*/
public static Site getSite(HttpServletRequest request) {
Object site = request.getAttribute(SITE_ATTRIBUTE);
if (site == null) {
site = resolveSite(request);
exposeSite((Site) site, request);
}
if (site == null || site == NOT_FOUND) {
return null;
}
Site result = (Site) site;
result.refreshIfDetached();
return result;
}
protected static void exposeSite(Site site, HttpServletRequest request) {
expose(site, request, SITE_ATTRIBUTE);
}
/**
* Returns the Page for the given request.
*/
public static Page getPage(HttpServletRequest request) {
Object page = request.getAttribute(PAGE_ATTRIBUTE);
if (page == null) {
page = resolvePage(request);
exposePage((Page) page, request);
}
if (page == null || page == NOT_FOUND) {
return null;
}
return (Page) page;
}
public static Page resolvePage(Site site, String type, Object object) {
return site.getSchema().getPageType(type).getPage(site, object);
}
protected static void exposePage(Page page, HttpServletRequest request) {
expose(page, request, PAGE_ATTRIBUTE);
}
private static Site resolveSite(HttpServletRequest request) {
String hostName = request.getServerName();
return Site.loadByHostName(hostName);
}
private static Page resolvePage(HttpServletRequest request) {
Site site = getSite(request);
if (site == null) {
return null;
}
String lookupPath = getLookupPath(request);
Page page = ContentPage.loadBySiteAndPath(site, lookupPath);
if (page == null) {
page = resolveVirtualChildPage(site, lookupPath);
}
- if (page == null ||
- (!page.getContentContainer().isPublished() &&
- !EditModeUtils.isPreview(request, null))) {
+ if (page == null || ((!site.isEnabled() ||
+ !page.getContentContainer().isPublished()) &&
+ !EditModeUtils.isPreview(request, null))) {
return null;
}
return page;
}
private static Page resolveVirtualChildPage(Site site, String lookupPath) {
for (ContentPage parent : ContentPage.findByTypesAndSite(site.getSchema().getVirtualParents(), site)) {
String parentPath = parent.getPath();
if (lookupPath.startsWith(parentPath)) {
String tail = lookupPath.substring(parent.getPath().length());
if (tail.startsWith("/")) {
SystemPageType parentType = (SystemPageType) parent.getPageType();
return parentType.getVirtualChildType().resolve(parent, tail);
}
}
}
return null;
}
public static String getLookupPath(HttpServletRequest request) {
String s = FormatUtils.stripExtension(FormatUtils.stripTrailingSlash(
ServletUtils.getPathWithinApplication(request)));
return s.length() > 0 ? s : "/";
}
private static void expose(Object object, HttpServletRequest request,
String attributeName) {
if (object == null) {
object = NOT_FOUND;
}
request.setAttribute(attributeName, object);
}
/**
* Resets all internally used attributes.
* @param request
*/
public static void resetAttributes(HttpServletRequest request) {
request.removeAttribute(SITE_ATTRIBUTE);
request.removeAttribute(PAGE_ATTRIBUTE);
}
}
| true | true | private static Page resolvePage(HttpServletRequest request) {
Site site = getSite(request);
if (site == null) {
return null;
}
String lookupPath = getLookupPath(request);
Page page = ContentPage.loadBySiteAndPath(site, lookupPath);
if (page == null) {
page = resolveVirtualChildPage(site, lookupPath);
}
if (page == null ||
(!page.getContentContainer().isPublished() &&
!EditModeUtils.isPreview(request, null))) {
return null;
}
return page;
}
| private static Page resolvePage(HttpServletRequest request) {
Site site = getSite(request);
if (site == null) {
return null;
}
String lookupPath = getLookupPath(request);
Page page = ContentPage.loadBySiteAndPath(site, lookupPath);
if (page == null) {
page = resolveVirtualChildPage(site, lookupPath);
}
if (page == null || ((!site.isEnabled() ||
!page.getContentContainer().isPublished()) &&
!EditModeUtils.isPreview(request, null))) {
return null;
}
return page;
}
|
diff --git a/src/org/intellij/plugins/ceylon/psi/CeylonFile.java b/src/org/intellij/plugins/ceylon/psi/CeylonFile.java
index 1d8e7cd6..0920be7e 100644
--- a/src/org/intellij/plugins/ceylon/psi/CeylonFile.java
+++ b/src/org/intellij/plugins/ceylon/psi/CeylonFile.java
@@ -1,72 +1,72 @@
package org.intellij.plugins.ceylon.psi;
import com.intellij.extapi.psi.PsiFileBase;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.FileViewProvider;
import com.intellij.util.indexing.IndexingDataKeys;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import org.intellij.plugins.ceylon.CeylonFileType;
import org.intellij.plugins.ceylon.CeylonLanguage;
import org.intellij.plugins.ceylon.parser.CeylonIdeaParser;
import org.intellij.plugins.ceylon.parser.MyTree;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class CeylonFile extends PsiFileBase {
private final MyTree myTree = new MyTree();
private String packageName; // TODO should be updated if the file is moved, package is renamed etc.
public CeylonFile(@NotNull FileViewProvider viewProvider) {
super(viewProvider, CeylonLanguage.INSTANCE);
}
public MyTree getMyTree() {
return myTree;
}
@NotNull
@Override
public FileType getFileType() {
return CeylonFileType.INSTANCE;
}
public String getPackageName() {
if (packageName != null) {
return packageName;
}
Node userData = getNode().getUserData(CeylonIdeaParser.CEYLON_NODE_KEY);
if (!(userData instanceof Tree.CompilationUnit)) {
return null;// TODO is always null :(
}
final List<Tree.PackageDescriptor> packageDescriptors = ((Tree.CompilationUnit) userData).getPackageDescriptors();
- final Tree.PackageDescriptor packageDescriptor = packageDescriptors.get(0); // todo! empty, null?
+ final Tree.PackageDescriptor packageDescriptor = packageDescriptors.isEmpty() ? null : packageDescriptors.get(0);
if (packageDescriptor != null) {
packageName = packageDescriptor.getImportPath().getText();
} else {
VirtualFile virtualFile = getVirtualFile();
if (virtualFile == null) {
virtualFile = getOriginalFile().getVirtualFile();
}
if (virtualFile == null) {
virtualFile = getContainingFile().getUserData(IndexingDataKeys.VIRTUAL_FILE);
}
if (virtualFile != null) {
packageName = ProjectRootManager.getInstance(getProject()).getFileIndex().getPackageNameByDirectory(virtualFile.getParent());
} else {
System.out.println("Can't detect VirtualFile for " + getName());
}
}
return packageName;
}
}
| true | true | public String getPackageName() {
if (packageName != null) {
return packageName;
}
Node userData = getNode().getUserData(CeylonIdeaParser.CEYLON_NODE_KEY);
if (!(userData instanceof Tree.CompilationUnit)) {
return null;// TODO is always null :(
}
final List<Tree.PackageDescriptor> packageDescriptors = ((Tree.CompilationUnit) userData).getPackageDescriptors();
final Tree.PackageDescriptor packageDescriptor = packageDescriptors.get(0); // todo! empty, null?
if (packageDescriptor != null) {
packageName = packageDescriptor.getImportPath().getText();
} else {
VirtualFile virtualFile = getVirtualFile();
if (virtualFile == null) {
virtualFile = getOriginalFile().getVirtualFile();
}
if (virtualFile == null) {
virtualFile = getContainingFile().getUserData(IndexingDataKeys.VIRTUAL_FILE);
}
if (virtualFile != null) {
packageName = ProjectRootManager.getInstance(getProject()).getFileIndex().getPackageNameByDirectory(virtualFile.getParent());
} else {
System.out.println("Can't detect VirtualFile for " + getName());
}
}
return packageName;
}
| public String getPackageName() {
if (packageName != null) {
return packageName;
}
Node userData = getNode().getUserData(CeylonIdeaParser.CEYLON_NODE_KEY);
if (!(userData instanceof Tree.CompilationUnit)) {
return null;// TODO is always null :(
}
final List<Tree.PackageDescriptor> packageDescriptors = ((Tree.CompilationUnit) userData).getPackageDescriptors();
final Tree.PackageDescriptor packageDescriptor = packageDescriptors.isEmpty() ? null : packageDescriptors.get(0);
if (packageDescriptor != null) {
packageName = packageDescriptor.getImportPath().getText();
} else {
VirtualFile virtualFile = getVirtualFile();
if (virtualFile == null) {
virtualFile = getOriginalFile().getVirtualFile();
}
if (virtualFile == null) {
virtualFile = getContainingFile().getUserData(IndexingDataKeys.VIRTUAL_FILE);
}
if (virtualFile != null) {
packageName = ProjectRootManager.getInstance(getProject()).getFileIndex().getPackageNameByDirectory(virtualFile.getParent());
} else {
System.out.println("Can't detect VirtualFile for " + getName());
}
}
return packageName;
}
|
diff --git a/src/main/java/org/bonitasoft/theme/css/impl/CSSPropertiesImpl.java b/src/main/java/org/bonitasoft/theme/css/impl/CSSPropertiesImpl.java
index 2791dd9..27322d4 100644
--- a/src/main/java/org/bonitasoft/theme/css/impl/CSSPropertiesImpl.java
+++ b/src/main/java/org/bonitasoft/theme/css/impl/CSSPropertiesImpl.java
@@ -1,265 +1,265 @@
/**
* Copyright (C) 2011 BonitaSoft S.A.
* BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble
*
* 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.0 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 org.bonitasoft.theme.css.impl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.bonitasoft.theme.builder.impl.ThemeDescriptorBuilderImpl;
import org.bonitasoft.theme.css.CSSProperties;
import org.bonitasoft.theme.css.CSSRule;
import org.bonitasoft.theme.exception.CSSFileIsEmpty;
import org.bonitasoft.theme.exception.CSSFileNotFoundException;
/**
* @author Romain Bioteau
*
*/
public class CSSPropertiesImpl implements CSSProperties {
/**
* the regex of removing the comments and paramContent in the CSS file
*/
public static final String COMMENTS_REGEX = "/\\*(?:.|[\\n\\r])*?\\*/";
public static final String PARAM_REGEX = "@(?:.|[\\n\\r])*?;";
public static final String MEDIA_REGEX = "@media.*\\{(?:(?:[^\\}]|[\\r\\n])*?\\{(?:[^\\}]|[\\r\\n])*?\\}(?:[^\\}]|[\\r\\n])*?)*?\\}";
/**
* new line character
*/
public static final String NEWLINE = "\n";
/**
* TAB character
*/
public static final String TAB = "\t";
/**
* Logger
*/
protected static Logger LOGGER = Logger.getLogger(ThemeDescriptorBuilderImpl.class.getName());
/**
* map to cache the CSS file rules
*/
private final List<CSSRule> rules = new ArrayList<CSSRule>();
@Override
public void load(final InputStream input) throws IOException {
if (input == null) {
throw new IOException("Input is null");
}
rules.clear();
String cssContent = getCSSContent(input);
// remove media sections are they are not handled by the theme parser
- cssContent.replaceAll(MEDIA_REGEX, "");
+ cssContent = cssContent.replaceAll(MEDIA_REGEX, "");
while (cssContent.trim().length() != 0) {
if (cssContent.indexOf("{") < 0) {
break;
}
final String ruleAndComment = cssContent.substring(0, cssContent.indexOf("{")).trim();
final String ruleName = ruleAndComment.replaceAll(COMMENTS_REGEX, "").replaceAll(PARAM_REGEX, "").trim();
final String comment = ruleAndComment.replace(ruleName, "").trim();
final CSSRule rule = new CSSRuleImpl(ruleName, comment);
final String value = cssContent.substring(cssContent.indexOf("{") + 1, cssContent.indexOf("}")).trim();
if (!"".equals(value.trim())) {
final String[] temp = value.replaceAll(COMMENTS_REGEX, "").replaceAll(PARAM_REGEX, "").split(";");
for (int i = 0; i < temp.length; i++) {
final String[] temps = temp[i].trim().split(":");
if (temps.length > 1) {
rule.put(temps[0].trim(), temps[1].trim());
}
}
}
cssContent = cssContent.substring(cssContent.indexOf("}") + 1);
rules.add(rule);
}
}
@Override
public List<String> getAllRules() {
return toRuleNameList(rules);
}
@Override
public void addRule(final String rule, final String comment) {
CSSRule r = getRuleByName(rules, rule);
if (r == null) {
r = new CSSRuleImpl(rule, comment);
rules.add(r);
} else {
r.setComment(comment);
}
}
@Override
public void put(final String rule, final String key, final String value) {
CSSRule r = getRuleByName(rules, rule);
if (r == null) {
r = new CSSRuleImpl(rule, null);
rules.add(r);
}
if (key != null) {
r.put(key, value);
} else {
r.remove(key);
}
}
@Override
public String get(final String rule, final String key) {
final CSSRule r = getRuleByName(rules, rule);
if (r != null) {
return r.get(key);
}
return null;
}
@Override
public void removeRule(final String rule) {
final CSSRule r = getRuleByName(rules, rule);
if (r != null) {
rules.remove(r);
}
}
@Override
public void save(final OutputStream output) throws IOException {
if (output == null) {
throw new IOException("Output is null");
}
final StringBuffer cssContent = new StringBuffer("");
for (final CSSRule rule : rules) {
final String ruleName = rule.getName();
final Map<String, String> cssProperties = rule.getAllProperties();
if (rule.getComment() != null && !rule.getComment().isEmpty()) {
cssContent.append(rule.getComment() + NEWLINE);
}
cssContent.append(ruleName + " {" + NEWLINE);
for (final String propertyName : cssProperties.keySet()) {
final String propertieValue = cssProperties.get(propertyName);
if (propertieValue != null) {
cssContent.append(TAB + propertyName + ": " + propertieValue + ";" + NEWLINE);
}
}
cssContent.append("}");
cssContent.append(NEWLINE);
cssContent.append(NEWLINE);
}
updateCssContentToFile(cssContent.toString(), output);
}
/**
* get the content of CSS file
*
* @param filePath
* path of CSS file
* @return result css content which is converted into a string
* @throws IOException
* @throws CSSFileNotFoundException
* @throws CSSFileIsEmpty
*/
private String getCSSContent(final InputStream in) throws IOException {
final StringBuffer result = new StringBuffer();
final InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
final BufferedReader bufReader = new BufferedReader(inReader);
try {
String s;
while ((s = bufReader.readLine()) != null) {
result.append(s + NEWLINE);
}
} finally {
inReader.close();
bufReader.close();
}
return result.toString();
}
private List<String> toRuleNameList(final List<CSSRule> ruleList) {
final List<String> result = new ArrayList<String>();
final Iterator<CSSRule> iterator = ruleList.iterator();
while (iterator.hasNext()) {
final CSSRule rule = iterator.next();
result.add(rule.getName());
}
Collections.sort(result);
return result;
}
private CSSRule getRuleByName(final List<CSSRule> ruleList, final String rule) {
final Iterator<CSSRule> it = ruleList.iterator();
while (it.hasNext()) {
final CSSRule cssRule = it.next();
if (cssRule.getName().equals(rule)) {
return cssRule;
}
}
return null;
}
/**
* write the changed CSS content to File
*
* @param content
* the changed CSS content which has to write into CSS file
* @param filePath
* path of CSS file
* @throws CSSFileNotFoundException
*/
private void updateCssContentToFile(final String content, final OutputStream output) throws IOException {
PrintWriter writer = null;
try {
writer = new PrintWriter(output);
writer.write(content);
writer.flush();
} finally {
if (writer != null) {
writer.close();
writer = null;
}
}
}
@Override
public String getComment(final String rule) {
final CSSRule r = getRuleByName(rules, rule);
if (r != null) {
return r.getComment();
}
return null;
}
}
| true | true | public void load(final InputStream input) throws IOException {
if (input == null) {
throw new IOException("Input is null");
}
rules.clear();
String cssContent = getCSSContent(input);
// remove media sections are they are not handled by the theme parser
cssContent.replaceAll(MEDIA_REGEX, "");
while (cssContent.trim().length() != 0) {
if (cssContent.indexOf("{") < 0) {
break;
}
final String ruleAndComment = cssContent.substring(0, cssContent.indexOf("{")).trim();
final String ruleName = ruleAndComment.replaceAll(COMMENTS_REGEX, "").replaceAll(PARAM_REGEX, "").trim();
final String comment = ruleAndComment.replace(ruleName, "").trim();
final CSSRule rule = new CSSRuleImpl(ruleName, comment);
final String value = cssContent.substring(cssContent.indexOf("{") + 1, cssContent.indexOf("}")).trim();
if (!"".equals(value.trim())) {
final String[] temp = value.replaceAll(COMMENTS_REGEX, "").replaceAll(PARAM_REGEX, "").split(";");
for (int i = 0; i < temp.length; i++) {
final String[] temps = temp[i].trim().split(":");
if (temps.length > 1) {
rule.put(temps[0].trim(), temps[1].trim());
}
}
}
cssContent = cssContent.substring(cssContent.indexOf("}") + 1);
rules.add(rule);
}
}
| public void load(final InputStream input) throws IOException {
if (input == null) {
throw new IOException("Input is null");
}
rules.clear();
String cssContent = getCSSContent(input);
// remove media sections are they are not handled by the theme parser
cssContent = cssContent.replaceAll(MEDIA_REGEX, "");
while (cssContent.trim().length() != 0) {
if (cssContent.indexOf("{") < 0) {
break;
}
final String ruleAndComment = cssContent.substring(0, cssContent.indexOf("{")).trim();
final String ruleName = ruleAndComment.replaceAll(COMMENTS_REGEX, "").replaceAll(PARAM_REGEX, "").trim();
final String comment = ruleAndComment.replace(ruleName, "").trim();
final CSSRule rule = new CSSRuleImpl(ruleName, comment);
final String value = cssContent.substring(cssContent.indexOf("{") + 1, cssContent.indexOf("}")).trim();
if (!"".equals(value.trim())) {
final String[] temp = value.replaceAll(COMMENTS_REGEX, "").replaceAll(PARAM_REGEX, "").split(";");
for (int i = 0; i < temp.length; i++) {
final String[] temps = temp[i].trim().split(":");
if (temps.length > 1) {
rule.put(temps[0].trim(), temps[1].trim());
}
}
}
cssContent = cssContent.substring(cssContent.indexOf("}") + 1);
rules.add(rule);
}
}
|
diff --git a/proxy/src/main/java/net/md_5/bungee/EntityMap.java b/proxy/src/main/java/net/md_5/bungee/EntityMap.java
index 50b06f9d..518a59fe 100644
--- a/proxy/src/main/java/net/md_5/bungee/EntityMap.java
+++ b/proxy/src/main/java/net/md_5/bungee/EntityMap.java
@@ -1,164 +1,175 @@
package net.md_5.bungee;
/**
* Class to rewrite integers within packets.
*/
public class EntityMap
{
public final static int[][] entityIds = new int[ 256 ][];
static
{
entityIds[0x05] = new int[]
{
1
};
entityIds[0x07] = new int[]
{
1, 5
};
entityIds[0x11] = new int[]
{
1
};
entityIds[0x12] = new int[]
{
1
};
entityIds[0x13] = new int[]
{
1
};
entityIds[0x14] = new int[]
{
1
};
entityIds[0x16] = new int[]
{
1, 5
};
entityIds[0x17] = new int[]
{
1 //, 20
};
entityIds[0x18] = new int[]
{
1
};
entityIds[0x19] = new int[]
{
1
};
entityIds[0x1A] = new int[]
{
1
};
entityIds[0x1C] = new int[]
{
1
};
entityIds[0x1E] = new int[]
{
1
};
entityIds[0x1F] = new int[]
{
1
};
entityIds[0x20] = new int[]
{
1
};
entityIds[0x21] = new int[]
{
1
};
entityIds[0x22] = new int[]
{
1
};
entityIds[0x23] = new int[]
{
1
};
entityIds[0x26] = new int[]
{
1
};
entityIds[0x27] = new int[]
{
1, 5
};
entityIds[0x28] = new int[]
{
1
};
entityIds[0x29] = new int[]
{
1
};
entityIds[0x2A] = new int[]
{
1
};
entityIds[0x37] = new int[]
{
1
};
entityIds[0x47] = new int[]
{
1
};
}
public static void rewrite(byte[] packet, int oldId, int newId)
{
int packetId = packet[0] & 0xFF;
if ( packetId == 0x1D )
{ // bulk entity
for ( int pos = 2; pos < packet.length; pos += 4 )
{
int readId = readInt( packet, pos );
if ( readId == oldId )
{
setInt( packet, pos, newId );
} else if ( readId == newId )
{
setInt( packet, pos, oldId );
}
}
} else
{
int[] idArray = entityIds[packetId];
if ( idArray != null )
{
for ( int pos : idArray )
{
int readId = readInt( packet, pos );
if ( readId == oldId )
{
setInt( packet, pos, newId );
} else if ( readId == newId )
{
setInt( packet, pos, oldId );
}
}
}
}
+ if ( packetId == 0x17 )
+ {
+ int type = packet[5] & 0xFF;
+ if ( ( type >= 60 && type <= 62 ) || type == 90 )
+ {
+ if ( readInt( packet, 20 ) == oldId )
+ {
+ setInt( packet, 20, newId );
+ }
+ }
+ }
}
private static void setInt(byte[] buf, int pos, int i)
{
buf[pos] = (byte) ( i >> 24 );
buf[pos + 1] = (byte) ( i >> 16 );
buf[pos + 2] = (byte) ( i >> 8 );
buf[pos + 3] = (byte) i;
}
private static int readInt(byte[] buf, int pos)
{
return ( ( ( buf[pos] & 0xFF ) << 24 ) | ( ( buf[pos + 1] & 0xFF ) << 16 ) | ( ( buf[pos + 2] & 0xFF ) << 8 ) | buf[pos + 3] & 0xFF );
}
}
| true | true | public static void rewrite(byte[] packet, int oldId, int newId)
{
int packetId = packet[0] & 0xFF;
if ( packetId == 0x1D )
{ // bulk entity
for ( int pos = 2; pos < packet.length; pos += 4 )
{
int readId = readInt( packet, pos );
if ( readId == oldId )
{
setInt( packet, pos, newId );
} else if ( readId == newId )
{
setInt( packet, pos, oldId );
}
}
} else
{
int[] idArray = entityIds[packetId];
if ( idArray != null )
{
for ( int pos : idArray )
{
int readId = readInt( packet, pos );
if ( readId == oldId )
{
setInt( packet, pos, newId );
} else if ( readId == newId )
{
setInt( packet, pos, oldId );
}
}
}
}
}
| public static void rewrite(byte[] packet, int oldId, int newId)
{
int packetId = packet[0] & 0xFF;
if ( packetId == 0x1D )
{ // bulk entity
for ( int pos = 2; pos < packet.length; pos += 4 )
{
int readId = readInt( packet, pos );
if ( readId == oldId )
{
setInt( packet, pos, newId );
} else if ( readId == newId )
{
setInt( packet, pos, oldId );
}
}
} else
{
int[] idArray = entityIds[packetId];
if ( idArray != null )
{
for ( int pos : idArray )
{
int readId = readInt( packet, pos );
if ( readId == oldId )
{
setInt( packet, pos, newId );
} else if ( readId == newId )
{
setInt( packet, pos, oldId );
}
}
}
}
if ( packetId == 0x17 )
{
int type = packet[5] & 0xFF;
if ( ( type >= 60 && type <= 62 ) || type == 90 )
{
if ( readInt( packet, 20 ) == oldId )
{
setInt( packet, 20, newId );
}
}
}
}
|
diff --git a/src/com/android/im/app/SimpleInputActivity.java b/src/com/android/im/app/SimpleInputActivity.java
index 84e3bad..d4e239e 100644
--- a/src/com/android/im/app/SimpleInputActivity.java
+++ b/src/com/android/im/app/SimpleInputActivity.java
@@ -1,98 +1,98 @@
/*
* Copyright (C) 2007 Esmertec AG.
* 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.im.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.im.R;
public class SimpleInputActivity extends Activity {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_PROMPT = "prompt";
public static final String EXTRA_DEFAULT_CONTENT = "content";
public static final String EXTRA_OK_BUTTON_TEXT = "button_ok";
TextView mPrompt;
EditText mEdit;
Button mBtnOk;
Button mBtnCancel;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setTheme(android.R.style.Theme_Dialog);
setContentView(R.layout.simple_input_activity);
Bundle extras = getIntent().getExtras();
CharSequence title = extras.getCharSequence(EXTRA_TITLE);
if (title != null) {
setTitle(title);
} else {
setTitle(R.string.default_input_title);
}
CharSequence prompt = extras.getCharSequence(EXTRA_PROMPT);
mPrompt = (TextView) findViewById(R.id.prompt);
if (prompt != null) {
mPrompt.setText(prompt);
} else {
mPrompt.setVisibility(View.GONE);
}
mEdit = (EditText) findViewById(R.id.edit);
CharSequence defaultText = extras.getCharSequence(EXTRA_DEFAULT_CONTENT);
if (defaultText != null) {
mEdit.setText(defaultText);
}
mBtnOk = (Button) findViewById(R.id.btnOk);
mBtnOk.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK,
(new Intent()).setAction(mEdit.getText().toString()));
finish();
}
});
CharSequence okText = extras.getCharSequence(EXTRA_OK_BUTTON_TEXT);
if (okText != null) {
mBtnOk.setText(okText);
}
mBtnCancel = (Button) findViewById(R.id.btnCancel);
mBtnCancel.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
finish();
}
});
- // XXX Hack from GoogleLogin.java. The android:layout_width="fill_parent"
+ // XXX Hack from GoogleLogin.java. The android:layout_width="match_parent"
// defined in the layout xml doesn't seem to work for LinearLayout.
- getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
+ getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
}
| false | true | public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setTheme(android.R.style.Theme_Dialog);
setContentView(R.layout.simple_input_activity);
Bundle extras = getIntent().getExtras();
CharSequence title = extras.getCharSequence(EXTRA_TITLE);
if (title != null) {
setTitle(title);
} else {
setTitle(R.string.default_input_title);
}
CharSequence prompt = extras.getCharSequence(EXTRA_PROMPT);
mPrompt = (TextView) findViewById(R.id.prompt);
if (prompt != null) {
mPrompt.setText(prompt);
} else {
mPrompt.setVisibility(View.GONE);
}
mEdit = (EditText) findViewById(R.id.edit);
CharSequence defaultText = extras.getCharSequence(EXTRA_DEFAULT_CONTENT);
if (defaultText != null) {
mEdit.setText(defaultText);
}
mBtnOk = (Button) findViewById(R.id.btnOk);
mBtnOk.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK,
(new Intent()).setAction(mEdit.getText().toString()));
finish();
}
});
CharSequence okText = extras.getCharSequence(EXTRA_OK_BUTTON_TEXT);
if (okText != null) {
mBtnOk.setText(okText);
}
mBtnCancel = (Button) findViewById(R.id.btnCancel);
mBtnCancel.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
finish();
}
});
// XXX Hack from GoogleLogin.java. The android:layout_width="fill_parent"
// defined in the layout xml doesn't seem to work for LinearLayout.
getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
}
| public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setTheme(android.R.style.Theme_Dialog);
setContentView(R.layout.simple_input_activity);
Bundle extras = getIntent().getExtras();
CharSequence title = extras.getCharSequence(EXTRA_TITLE);
if (title != null) {
setTitle(title);
} else {
setTitle(R.string.default_input_title);
}
CharSequence prompt = extras.getCharSequence(EXTRA_PROMPT);
mPrompt = (TextView) findViewById(R.id.prompt);
if (prompt != null) {
mPrompt.setText(prompt);
} else {
mPrompt.setVisibility(View.GONE);
}
mEdit = (EditText) findViewById(R.id.edit);
CharSequence defaultText = extras.getCharSequence(EXTRA_DEFAULT_CONTENT);
if (defaultText != null) {
mEdit.setText(defaultText);
}
mBtnOk = (Button) findViewById(R.id.btnOk);
mBtnOk.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK,
(new Intent()).setAction(mEdit.getText().toString()));
finish();
}
});
CharSequence okText = extras.getCharSequence(EXTRA_OK_BUTTON_TEXT);
if (okText != null) {
mBtnOk.setText(okText);
}
mBtnCancel = (Button) findViewById(R.id.btnCancel);
mBtnCancel.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
finish();
}
});
// XXX Hack from GoogleLogin.java. The android:layout_width="match_parent"
// defined in the layout xml doesn't seem to work for LinearLayout.
getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
|
diff --git a/src/com/modcrafting/ultrabans/commands/Fine.java b/src/com/modcrafting/ultrabans/commands/Fine.java
index 0227473..bdef342 100644
--- a/src/com/modcrafting/ultrabans/commands/Fine.java
+++ b/src/com/modcrafting/ultrabans/commands/Fine.java
@@ -1,125 +1,130 @@
package com.modcrafting.ultrabans.commands;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import com.modcrafting.ultrabans.UltraBan;
import com.nijikokun.bukkit.Permissions.Permissions;
public class Fine implements CommandExecutor{
public net.milkbowl.vault.economy.Economy economy = null;
public static final Logger log = Logger.getLogger("Minecraft");
UltraBan plugin;
public Fine(UltraBan ultraBan) {
this.plugin = ultraBan;
}
public boolean autoComplete;
public String expandName(String p) {
int m = 0;
String Result = "";
for (int n = 0; n < plugin.getServer().getOnlinePlayers().length; n++) {
String str = plugin.getServer().getOnlinePlayers()[n].getName();
if (str.matches("(?i).*" + p + ".*")) {
m++;
Result = str;
if(m==2) {
return null;
}
}
if (str.equalsIgnoreCase(p))
return str;
}
if (m == 1)
return Result;
if (m > 1) {
return null;
}
if (m < 1) {
return p;
}
return p;
}
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
boolean auth = false;
Player player = null;
String admin = "server";
String perms = "ultraban.fine";
if (sender instanceof Player){
player = (Player)sender;
//new permissions test before reconstruct
if (Permissions.Security.permission(player, perms)){
auth = true;
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = args[0];
if(autoComplete) p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
boolean broadcast = true;
String amt = args[1]; //set string amount to argument
//Going loud
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
amt = combineSplit(2, args, " ");
}else{
amt = combineSplit(1, args, " ");
}
}
if(victim != null){
if(!broadcast){ //If silent wake his ass up
victim.sendMessage(admin + " has fined you for: " + amt);
}
if(setupEconomy()){
- double amtd = Double.valueOf(amt.trim()); //Covert + Take Whitespace if any
- economy.withdrawPlayer(victim.getName(), amtd); //Amount Absolute Value
+ double bal = economy.getBalance(p);
+ double amtd = Double.valueOf(amt.trim());
+ if(amtd > bal){
+ economy.withdrawPlayer(victim.getName(), bal);
+ }else{
+ economy.withdrawPlayer(victim.getName(), amtd);
+ }
}
log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + ".");
plugin.db.addPlayer(p, amt, admin, 0, 4);
if(broadcast){
plugin.getServer().broadcastMessage(ChatColor.BLUE + p + ChatColor.GRAY + " was fined by " +
ChatColor.DARK_GRAY + admin + ChatColor.GRAY + " for: " + amt);
return true;
}
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
public String combineSplit(int startIndex, String[] string, String seperator) {
StringBuilder builder = new StringBuilder();
for (int i = startIndex; i < string.length; i++) {
builder.append(string[i]);
builder.append(seperator);
}
builder.deleteCharAt(builder.length() - seperator.length()); // remove
return builder.toString();
}
public boolean setupEconomy(){
RegisteredServiceProvider<net.milkbowl.vault.economy.Economy> economyProvider = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}
return (economy != null);
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
boolean auth = false;
Player player = null;
String admin = "server";
String perms = "ultraban.fine";
if (sender instanceof Player){
player = (Player)sender;
//new permissions test before reconstruct
if (Permissions.Security.permission(player, perms)){
auth = true;
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = args[0];
if(autoComplete) p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
boolean broadcast = true;
String amt = args[1]; //set string amount to argument
//Going loud
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
amt = combineSplit(2, args, " ");
}else{
amt = combineSplit(1, args, " ");
}
}
if(victim != null){
if(!broadcast){ //If silent wake his ass up
victim.sendMessage(admin + " has fined you for: " + amt);
}
if(setupEconomy()){
double amtd = Double.valueOf(amt.trim()); //Covert + Take Whitespace if any
economy.withdrawPlayer(victim.getName(), amtd); //Amount Absolute Value
}
log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + ".");
plugin.db.addPlayer(p, amt, admin, 0, 4);
if(broadcast){
plugin.getServer().broadcastMessage(ChatColor.BLUE + p + ChatColor.GRAY + " was fined by " +
ChatColor.DARK_GRAY + admin + ChatColor.GRAY + " for: " + amt);
return true;
}
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
boolean auth = false;
Player player = null;
String admin = "server";
String perms = "ultraban.fine";
if (sender instanceof Player){
player = (Player)sender;
//new permissions test before reconstruct
if (Permissions.Security.permission(player, perms)){
auth = true;
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
if (args.length < 1) return false;
String p = args[0];
if(autoComplete) p = expandName(p);
Player victim = plugin.getServer().getPlayer(p);
boolean broadcast = true;
String amt = args[1]; //set string amount to argument
//Going loud
if(args.length > 1){
if(args[1].equalsIgnoreCase("-s")){
broadcast = false;
amt = combineSplit(2, args, " ");
}else{
amt = combineSplit(1, args, " ");
}
}
if(victim != null){
if(!broadcast){ //If silent wake his ass up
victim.sendMessage(admin + " has fined you for: " + amt);
}
if(setupEconomy()){
double bal = economy.getBalance(p);
double amtd = Double.valueOf(amt.trim());
if(amtd > bal){
economy.withdrawPlayer(victim.getName(), bal);
}else{
economy.withdrawPlayer(victim.getName(), amtd);
}
}
log.log(Level.INFO, "[UltraBan] " + admin + " fined player " + p + " amount of " + amt + ".");
plugin.db.addPlayer(p, amt, admin, 0, 4);
if(broadcast){
plugin.getServer().broadcastMessage(ChatColor.BLUE + p + ChatColor.GRAY + " was fined by " +
ChatColor.DARK_GRAY + admin + ChatColor.GRAY + " for: " + amt);
return true;
}
return true;
}else{
sender.sendMessage(ChatColor.GRAY + "Player must be online!");
return true;
}
}
|
diff --git a/src/id.java b/src/id.java
index 7938b6f..36ae603 100644
--- a/src/id.java
+++ b/src/id.java
@@ -1,1110 +1,1110 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.server.MinecraftServer;
public class id extends ej
implements ef {
public static Logger a = Logger.getLogger("Minecraft");
public bb b;
public boolean c = false;
private MinecraftServer d;
private ea e;
private int f = 0;
private double g;
private double h;
private double i;
private boolean j = true;
private gp k = null;
private List<String> onlyOneUseKits = new ArrayList<String>();
public id(MinecraftServer paramMinecraftServer, bb parambb, ea paramea) {
this.d = paramMinecraftServer;
this.b = parambb;
parambb.a(this);
this.e = paramea;
paramea.a = this;
}
public void a() {
this.b.a();
if (this.f++ % 20 == 0) {
this.b.a(new iz());
}
}
public void c(String paramString) {
this.b.a(new io(paramString));
this.b.c();
this.d.f.c(this.e);
this.c = true;
}
public void a(gf paramgf) {
double d1;
if (!this.j) {
d1 = paramgf.b - this.h;
if ((paramgf.a == this.g) && (d1 * d1 < 0.01D) && (paramgf.c == this.i)) {
this.j = true;
}
}
if (this.j) {
this.g = this.e.l;
this.h = this.e.m;
this.i = this.e.n;
d1 = this.e.l;
double d2 = this.e.m;
double d3 = this.e.n;
float f1 = this.e.r;
float f2 = this.e.s;
if (paramgf.h) {
d1 = paramgf.a;
d2 = paramgf.b;
d3 = paramgf.c;
double d4 = paramgf.d - paramgf.b;
if ((d4 > 1.65D) || (d4 < 0.1D)) {
c("Illegal stance");
a.warning(this.e.aq + " had an illegal stance: " + d4);
}
this.e.ai = paramgf.d;
}
if (paramgf.i) {
f1 = paramgf.e;
f2 = paramgf.f;
}
this.e.i();
this.e.M = 0.0F;
this.e.b(this.g, this.h, this.i, f1, f2);
double d4 = d1 - this.e.l;
double d5 = d2 - this.e.m;
double d6 = d3 - this.e.n;
float f3 = 0.0625F;
int m = this.d.e.a(this.e, this.e.v.b().e(f3, f3, f3)).size() == 0 ? 1 : 0;
this.e.c(d4, d5, d6);
d4 = d1 - this.e.l;
d5 = d2 - this.e.m;
if ((d5 > -0.5D) || (d5 < 0.5D)) {
d5 = 0.0D;
}
d6 = d3 - this.e.n;
double d7 = d4 * d4 + d5 * d5 + d6 * d6;
int n = 0;
if (d7 > 0.0625D) {
n = 1;
a.warning(this.e.aq + " moved wrongly!");
}
this.e.b(d1, d2, d3, f1, f2);
int i1 = this.d.e.a(this.e, this.e.v.b().e(f3, f3, f3)).size() == 0 ? 1 : 0;
if ((m != 0) && ((n != 0) || (i1 == 0))) {
a(this.g, this.h, this.i, f1, f2);
return;
}
this.e.w = paramgf.g;
this.d.f.b(this.e);
}
}
public void a(double paramDouble1, double paramDouble2, double paramDouble3, float paramFloat1, float paramFloat2) {
this.j = false;
this.g = paramDouble1;
this.h = paramDouble2;
this.i = paramDouble3;
this.e.b(paramDouble1, paramDouble2, paramDouble3, paramFloat1, paramFloat2);
this.e.a.b(new dq(paramDouble1, paramDouble2 + 1.620000004768372D, paramDouble2, paramDouble3, paramFloat1, paramFloat2, false));
}
public void a(hd paramhd) {
this.e.aj.a[this.e.aj.d] = this.k;
boolean bool = this.d.e.z = this.d.f.g(this.e.aq);
int m = 0;
if (paramhd.e == 0) {
m = 1;
}
if (paramhd.e == 1) {
m = 1;
}
if (m != 0) {
double d1 = this.e.m;
this.e.m = this.e.ai;
fr localfr = this.e.a(4.0D, 1.0F);
this.e.m = d1;
if (localfr == null) {
return;
}
if ((localfr.b != paramhd.a) || (localfr.c != paramhd.b) || (localfr.d != paramhd.c) || (localfr.e != paramhd.d)) {
return;
}
}
int n = paramhd.a;
int i1 = paramhd.b;
int i2 = paramhd.c;
int i3 = paramhd.d;
int i4 = (int) gj.e(n - this.d.e.n);
int i5 = (int) gj.e(i2 - this.d.e.p);
if (i4 > i5) {
i5 = i4;
}
if (paramhd.e == 0) {
if ((i5 > 16) || (bool)) {
this.e.ad.a(n, i1, i2);
}
} else if (paramhd.e == 2) {
this.e.ad.a();
} else if (paramhd.e == 1) {
if ((i5 > 16) || (bool)) {
this.e.ad.a(n, i1, i2, i3);
}
} else if (paramhd.e == 3) {
double d2 = this.e.l - (n + 0.5D);
double d3 = this.e.m - (i1 + 0.5D);
double d4 = this.e.n - (i2 + 0.5D);
double d5 = d2 * d2 + d3 * d3 + d4 * d4;
if (d5 < 256.0D) {
this.e.a.b(new et(n, i1, i2, this.d.e));
}
}
this.d.e.z = false;
}
public void a(fe paramfe) {
boolean bool = this.d.e.z = this.d.f.g(this.e.aq);
int m = paramfe.b;
int n = paramfe.c;
int i1 = paramfe.d;
int i2 = paramfe.e;
int i3 = (int) gj.e(m - this.d.e.n);
int i4 = (int) gj.e(i1 - this.d.e.p);
if (i3 > i4) {
i4 = i3;
}
if ((i4 > 16) || (bool)) {
gp localgp = paramfe.a >= 0 ? new gp(paramfe.a) : null;
this.e.ad.a(this.e, this.d.e, localgp, m, n, i1, i2);
}
this.e.a.b(new et(m, n, i1, this.d.e));
this.d.e.z = false;
}
/*public void a(hd paramhd) {
if (!etc.getInstance().canBuild(e)) {
return;
}
this.e.aj.a[this.e.aj.d] = this.k;
boolean bool = this.d.f.g(this.e.aq) || etc.getInstance().isAdmin(e);
this.d.e.x = true;
int m = 0;
if (paramhd.e == 0) {
m = 1;
}
if (paramhd.e == 1) {
m = 1;
}
if (m != 0) {
double d1 = this.e.m;
this.e.m = this.e.ai;
fr localfr = this.e.a(4.0D, 1.0F);
this.e.m = d1;
if (localfr == null) {
return;
}
//TODO: Figure out what this is. They're accessing private variables, so wtf?
//if ((localfr.b != paramhd.a) || (localfr.c != paramhd.b) || (localfr.d != paramhd.c) || (localfr.e != paramhd.d)) {
//return;
//}
}
int n = paramhd.a;
int i1 = paramhd.b;
int i2 = paramhd.c;
int i3 = paramhd.d;
int i4 = (int) gj.e(n - this.d.e.n);
int i5 = (int) gj.e(i2 - this.d.e.p);
if (i4 > i5) {
i5 = i4;
}
if (paramhd.e == 0) {
if (i5 > etc.getInstance().spawnProtectionSize || bool) {
this.e.ad.a(n, i1, i2);
}
} else if (paramhd.e == 2) {
this.e.ad.a();
} else if (paramhd.e == 1) {
if (i5 > etc.getInstance().spawnProtectionSize || bool) {
this.e.ad.a(n, i1, i2, i3);
}
} else if (paramhd.e == 3) {
double d2 = this.e.l - (n + 0.5D);
double d3 = this.e.m - (i1 + 0.5D);
double d4 = this.e.n - (i2 + 0.5D);
double d5 = d2 * d2 + d3 * d3 + d4 * d4;
if (d5 < 256.0D) {
this.e.a.b(new et(n, i1, i2, this.d.e));
}
}
this.d.e.z = false;
}
public void a(fe paramfe) {
if (!etc.getInstance().canBuild(e)) {
return;
}
boolean bool = this.d.f.g(this.e.aq) || etc.getInstance().isAdmin(e);
this.d.e.z = true;
int m = paramfe.b;
int n = paramfe.c;
int i1 = paramfe.d;
int i2 = paramfe.e;
int i3 = (int) gj.e(m - this.d.e.n);
int i4 = (int) gj.e(i1 - this.d.e.p);
if (i3 > i4) {
i4 = i3;
}
if (i4 > etc.getInstance().spawnProtectionSize || bool) {
gp localgp = paramfe.a >= 0 ? new gp(paramfe.a) : null;
if (localgp != null) {
if (!etc.getInstance().isOnItemBlacklist(localgp.c) || bool) {
this.e.ad.a(this.e, this.d.e, localgp, m, n, i1, i2);
}
} else {
// is this right?
this.e.ad.a(this.e, this.d.e, localgp, m, n, i1, i2);
}
}
this.e.a.b(new et(m, n, i1, this.d.e));
this.d.e.z = false;
}*/
public void a(String paramString) {
a.info(this.e.aq + " lost connection: " + paramString);
this.d.f.c(this.e);
this.c = true;
}
public void a(hp paramhp) {
a.warning(getClass() + " wasn't prepared to deal with a " + paramhp.getClass());
c("Protocol error, unexpected packet");
}
public void b(hp paramhp) {
this.b.a(paramhp);
}
public void a(fv paramfv) {
int m = paramfv.b;
this.e.aj.d = (this.e.aj.a.length - 1);
if (m == 0) {
this.k = null;
} else {
this.k = new gp(m);
}
this.e.aj.a[this.e.aj.d] = this.k;
this.d.k.a(this.e, new fv(this.e.c, m));
}
public void a(k paramk) {
double d1 = paramk.b / 32.0D;
double d2 = paramk.c / 32.0D;
double d3 = paramk.d / 32.0D;
fn localfn = new fn(this.d.e, d1, d2, d3, new gp(paramk.h, paramk.i));
localfn.o = (paramk.e / 128.0D);
localfn.p = (paramk.f / 128.0D);
localfn.q = (paramk.g / 128.0D);
localfn.ad = 10;
this.d.e.a(localfn);
}
public void a(ba paramba) {
String str = paramba.a;
if (str.length() > 100) {
b("Chat message too long");
return;
}
str = str.trim();
for (int k = 0; k < str.length(); ++k) {
if (" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_'abcdefghijklmnopqrstuvwxyz{|}~¦ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»".indexOf(str.charAt(k)) < 0) {
b("Illegal characters in chat");
return;
}
}
if (str.startsWith("/")) {
d(str);
} else {
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
String message = "<" + etc.getInstance().getUserColor(e.aq) + this.e.aq + Colors.White + "> " + str;
a.log(Level.INFO, "<" + e.aq + "> " + str);
this.d.f.a(new ba(message));
}
}
private ea match(String name) {
ea player = null;
boolean found = false;
if (("`" + this.d.f.c().toUpperCase() + "`").split(name.toUpperCase()).length == 2) {
for (int i = 0; i < this.d.f.b.size() && !found; ++i) {
ea localea = (ea) this.d.f.b.get(i);
if (("`" + localea.aq.toUpperCase() + "`").split(name.toUpperCase()).length == 2) {
player = localea;
found = true;
}
}
} else if (("`" + this.d.f.c() + "`").split(name).length > 2) {
// Too many partial matches.
for (int i = 0; i < this.d.f.b.size() && !found; ++i) {
ea localea = (ea) this.d.f.b.get(i);
if (localea.aq.equalsIgnoreCase(name)) {
player = localea;
found = true;
}
}
}
return player;
}
public static String combineSplit(int startIndex, String[] string, String seperator) {
StringBuilder builder = new StringBuilder();
for (int i = startIndex; i < string.length; i++) {
builder.append(string[i]);
builder.append(seperator);
}
builder.deleteCharAt(builder.length() - seperator.length()); // remove the extra
// seperator
return builder.toString();
}
public boolean hasControlOver(ea player) {
boolean isInGroup = false;
if (etc.getInstance().getUser(player.aq) != null) {
for (String str : etc.getInstance().getUser(player.aq).Groups) {
if (etc.getInstance().isUserInGroup(e, str)) {
isInGroup = true;
}
}
} else {
return true;
}
return isInGroup;
}
public void msg(String msg) {
b(new ba(msg));
}
private void d(String paramString) {
try {
String[] split = paramString.split(" ");
if (!etc.getInstance().canUseCommand(e.aq, split[0]) && !split[0].startsWith("/#")) {
msg(Colors.Rose + "Unknown command.");
return;
}
if (split[0].equalsIgnoreCase("/help")) {
//Meh, not the greatest way, but not the worst either.
List<String> availableCommands = new ArrayList<String>();
for (Entry<String, String> entry : etc.getInstance().commands.entrySet()) {
if (etc.getInstance().canUseCommand(e.aq, entry.getKey())) {
if (entry.getKey().equals("/kit") && !etc.getInstance().getDataSource().hasKits()) {
continue;
}
if (entry.getKey().equals("/listwarps") && !etc.getInstance().getDataSource().hasWarps()) {
continue;
}
availableCommands.add(entry.getKey() + " " + entry.getValue());
}
}
msg(Colors.Blue + "Available commands (Page " + (split.length == 2 ? split[1] : "1") + " of " + (int) Math.ceil((double) availableCommands.size() / (double) 7) + ") [] = required <> = optional:");
if (split.length == 2) {
try {
int amount = Integer.parseInt(split[1]);
if (amount > 0) {
amount = (amount - 1) * 7;
} else {
amount = 0;
}
for (int i = amount; i < amount + 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
} catch (NumberFormatException ex) {
msg(Colors.Rose + "Not a valid page number.");
}
} else {
for (int i = 0; i < 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
}
} else if (split[0].equalsIgnoreCase("/reload")) {
etc.getInstance().load();
etc.getInstance().loadData();
a.info("Reloaded config");
msg("Successfuly reloaded config");
} else if ((split[0].equalsIgnoreCase("/modify") || split[0].equalsIgnoreCase("/mp"))) {
if (split.length < 4) {
msg(Colors.Rose + "Usage is: /modify [player] [key] [value]");
msg(Colors.Rose + "Keys:");
msg(Colors.Rose + "prefix: only the letter the color represents");
msg(Colors.Rose + "commands: list seperated by comma");
msg(Colors.Rose + "groups: list seperated by comma");
msg(Colors.Rose + "ignoresrestrictions: true or false");
msg(Colors.Rose + "admin: true or false");
msg(Colors.Rose + "modworld: true or false");
return;
}
ea player = match(split[1]);
if (player == null) {
msg(Colors.Rose + "Player does not exist.");
return;
}
String key = split[2];
String value = split[3];
User user = etc.getInstance().getUser(split[1]);
boolean newUser = false;
if (user == null) {
if (!key.equalsIgnoreCase("groups") && !key.equalsIgnoreCase("g")) {
msg(Colors.Rose + "When adding a new user, set their group(s) first.");
return;
}
msg(Colors.Rose + "Adding new user.");
newUser = true;
user = new User();
user.Name = split[1];
user.Administrator = false;
user.CanModifyWorld = true;
user.IgnoreRestrictions = false;
user.Commands = new String[]{""};
user.Prefix = "";
}
if (key.equalsIgnoreCase("prefix") || key.equalsIgnoreCase("p")) {
user.Prefix = value;
} else if (key.equalsIgnoreCase("commands") || key.equalsIgnoreCase("c")) {
user.Commands = value.split(",");
} else if (key.equalsIgnoreCase("groups") || key.equalsIgnoreCase("g")) {
user.Groups = value.split(",");
} else if (key.equalsIgnoreCase("ignoresrestrictions") || key.equalsIgnoreCase("ir")) {
user.IgnoreRestrictions = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("admin") || key.equalsIgnoreCase("a")) {
user.Administrator = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("modworld") || key.equalsIgnoreCase("mw")) {
user.CanModifyWorld = value.equalsIgnoreCase("true") || value.equals("1");
}
if (newUser) {
etc.getInstance().getDataSource().addUser(user);
} else {
etc.getInstance().getDataSource().modifyUser(user);
}
msg(Colors.Rose + "Modified user.");
a.info("Modifed user " + split[1] + ". " + key + " => " + value + " by " + e.aq);
} else if (split[0].equalsIgnoreCase("/whitelist")) {
if (split.length != 3) {
msg(Colors.Rose + "whitelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToWhitelist(split[2]);
msg(Colors.Rose + split[2] + " added to whitelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromWhitelist(split[2]);
msg(Colors.Rose + split[2] + " removed from whitelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/reservelist")) {
if (split.length != 3) {
msg(Colors.Rose + "reservelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToReserveList(split[2]);
msg(Colors.Rose + split[2] + " added to reservelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromReserveList(split[2]);
msg(Colors.Rose + split[2] + " removed from reservelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/mute")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /mute [player]");
return;
}
ea player = match(split[1]);
if (player != null) {
if (etc.getInstance().toggleMute(player)) {
msg(Colors.Rose + "player was muted");
} else {
msg(Colors.Rose + "player was unmuted");
}
} else {
msg(Colors.Rose + "Can't find player " + split[1]);
}
} else if ((split[0].equalsIgnoreCase("/msg") || split[0].equalsIgnoreCase("/tell")) || split[0].equalsIgnoreCase("/m")) {
if (split.length < 3) {
msg(Colors.Rose + "Correct usage is: /msg [player] [message]");
return;
}
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (player.aq.equals(e.aq)) {
msg(Colors.Rose + "You can't message yourself!");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
player.a.msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
} else {
msg(Colors.Rose + "Couldn't find player " + split[1]);
}
} else if (split[0].equalsIgnoreCase("/kit") && etc.getInstance().getDataSource().hasKits()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available kits: " + Colors.White + etc.getInstance().getDataSource().getKitNames(e.aq));
return;
}
ea toGive = e;
if (split.length > 2 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[1]);
}
Kit kit = etc.getInstance().getDataSource().getKit(split[1]);
if (toGive != null) {
if (kit != null) {
if (!etc.getInstance().isUserInGroup(e, kit.Group) && !kit.Group.equals("")) {
msg(Colors.Rose + "That kit does not exist.");
} else if (onlyOneUseKits.contains(kit.Name)) {
msg(Colors.Rose + "You can only get this kit once per login.");
} else if (MinecraftServer.b.containsKey(this.e.aq + " " + kit.Name)) {
msg(Colors.Rose + "You can't get this kit again for a while.");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
if (kit.Delay >= 0) {
MinecraftServer.b.put(this.e.aq + " " + kit.Name, kit.Delay);
} else {
onlyOneUseKits.add(kit.Name);
}
}
a.info(this.e.aq + " got a kit!");
toGive.a.msg(Colors.Rose + "Enjoy this kit!");
for (Map.Entry<String, Integer> entry : kit.IDs.entrySet()) {
try {
int itemId = 0;
try {
itemId = Integer.parseInt(entry.getKey());
} catch (NumberFormatException n) {
itemId = etc.getInstance().getDataSource().getItem(entry.getKey());
}
int temp = kit.IDs.get(entry.getKey());
do {
if (temp - 64 >= 64) {
- toGive.a(new gn(itemId, 64));
+ toGive.a(new gp(itemId, 64));
} else {
- toGive.a(new gn(itemId, temp));
+ toGive.a(new gp(itemId, temp));
}
temp -= 64;
} while (temp >= 64);
} catch (Exception e1) {
a.info("Got an exception while giving out a kit (Kit name \"" + kit.Name + "\"). Are you sure all the Ids are numbers?");
msg(Colors.Rose + "The server encountered a problem while giving the kit :(");
}
}
}
} else {
msg(Colors.Rose + "That kit does not exist.");
}
} else {
msg(Colors.Rose + "That user does not exist.");
}
} else if (split[0].equalsIgnoreCase("/tp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tp [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
- msg(Colors.Rose + "You're alreaea here!");
+ msg(Colors.Rose + "You're already here!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported to " + player.aq);
a(player.l, player.m, player.n, player.r, player.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if ((split[0].equalsIgnoreCase("/tphere") || split[0].equalsIgnoreCase("/s"))) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tphere [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "Wow look at that! You teleported yourself to yourself!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported " + player.aq + " to their self.");
player.a.a(e.l, e.m, e.n, e.r, e.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/playerlist") || split[0].equalsIgnoreCase("/who")) {
msg(Colors.Rose + "Player list (" + d.f.b.size() + "/" + etc.getInstance().playerLimit + "): " + Colors.White + d.f.c());
} else if (split[0].equalsIgnoreCase("/item") || split[0].equalsIgnoreCase("/i") || split[0].equalsIgnoreCase("/give")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount> <player> (optional)");
} else {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount>");
}
return;
}
ea toGive = e;
if (split.length == 4 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[3]);
}
if (toGive != null) {
try {
int i2 = 0;
try {
i2 = Integer.parseInt(split[1]);
} catch (NumberFormatException n) {
i2 = etc.getInstance().getDataSource().getItem(split[1]);
}
int i3 = 1;
if (split.length > 2) {
i3 = Integer.parseInt(split[2]);
}
String i2str = Integer.toString(i2);
if (i3 <= 0) {
i3 = 1;
}
if (i3 > 64 && !etc.getInstance().canIgnoreRestrictions(this.e)) {
i3 = 64;
}
boolean allowedItem = false;
if (!etc.getInstance().allowedItems[0].equals("") && (!etc.getInstance().canIgnoreRestrictions(this.e))) {
for (String str : etc.getInstance().allowedItems) {
if (i2str.equals(str)) {
allowedItem = true;
}
}
} else {
allowedItem = true;
}
if (!etc.getInstance().disallowedItems[0].equals("") && !etc.getInstance().canIgnoreRestrictions(this.e)) {
for (String str : etc.getInstance().disallowedItems) {
if (i2str.equals(str)) {
allowedItem = false;
}
}
}
if (i2 < ff.n.length) {
if (ff.n[i2] != null && (allowedItem || etc.getInstance().canIgnoreRestrictions(this.e))) {
a.log(Level.INFO, "Giving " + toGive.aq + " some " + i2);
int temp = i3;
do {
if (temp - 64 >= 64) {
- toGive.a(new gn(i2, 64));
+ toGive.a(new gp(i2, 64));
} else {
- toGive.a(new gn(i2, temp));
+ toGive.a(new gp(i2, temp));
}
temp -= 64;
} while (temp >= 64);
if (toGive == this.e) {
msg(Colors.Rose + "There you go c:");
} else {
msg(Colors.Rose + "Gift given! :D");
toGive.a.msg(Colors.Rose + "Enjoy your gift! :D");
}
} else if ((!allowedItem) && (ff.n[i2] != null) && !etc.getInstance().canIgnoreRestrictions(this.e)) {
msg(Colors.Rose + "You are not allowed to spawn that item.");
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} catch (NumberFormatException localNumberFormatException) {
msg(Colors.Rose + "Improper ID and/or amount.");
}
} else {
msg(Colors.Rose + "Can't find user " + split[3]);
}
} else if (split[0].equalsIgnoreCase("/banlist")) {
byte type = 0;
if (split.length == 2) {
if (split[1].equalsIgnoreCase("ips")) {
type = 1;
}
}
if (type == 0) { //Regular user bans
msg(Colors.Blue + "Ban list:" + Colors.White + " " + d.f.getBans());
} else { //IP bans
msg(Colors.Blue + "IP Ban list:" + Colors.White + " " + d.f.getBans());
}
} else if (split[0].equalsIgnoreCase("/banip")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /banip [player] <reason> (optional) NOTE: this permabans IPs.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.c(player.a.b.b().toString());
a.log(Level.INFO, "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
msg(Colors.Rose + "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
if (split.length > 2) {
player.a.c("IP Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("IP Banned by " + e.aq + ".");
}
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/ban")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /ban [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.a(player.aq);
if (split.length > 2) {
player.a.c("Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Banned by " + e.aq + ".");
}
a.log(Level.INFO, "Banning " + player.aq);
msg(Colors.Rose + "Banning " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/unban")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unban [player]");
return;
}
this.d.f.b(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/unbanip")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unbanip [ip]");
return;
}
this.d.f.d(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/kick")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /kick [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't kick that user.");
return;
}
if (split.length > 2) {
player.a.c("Kicked by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Kicked by " + e.aq + ".");
}
a.log(Level.INFO, "Kicking " + player.aq);
msg(Colors.Rose + "Kicking " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/me")) {
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
String paramString2 = "* " + prefix + this.e.aq + Colors.White + " " + paramString.substring(paramString.indexOf(" ")).trim();
a.info("* " + this.e.aq + " " + paramString.substring(paramString.indexOf(" ")).trim());
this.d.f.a(new ba(paramString2));
} else if (split[0].equalsIgnoreCase("/sethome")) {
// player.k, player.l, player.m
// x, y, z
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp home = new Warp();
home.Location = loc;
home.Group = ""; //no group neccessary, lol.
home.Name = e.aq;
etc.getInstance().changeHome(home);
msg(Colors.Rose + "Your home has been set.");
} else if (split[0].equalsIgnoreCase("/spawn")) {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
} else if (split[0].equalsIgnoreCase("/setspawn")) {
this.d.e.n = (int) Math.ceil(e.l);
//Too lazy to actually update this considering it's not even used anyways.
//this.d.e.n = (int) Math.ceil(e.m); //Not that the Y axis really matters since it tries to get the highest point iirc.
this.d.e.p = (int) Math.ceil(e.n);
a.info("Spawn position changed.");
msg(Colors.Rose + "You have set the spawn to your current position.");
} else if (split[0].equalsIgnoreCase("/home")) {
a.info(this.e.aq + " returned home");
Warp home = etc.getInstance().getDataSource().getHome(e.aq);
if (home != null) {
a(home.Location.x, home.Location.y, home.Location.z, home.Location.rotX, home.Location.rotY);
} else {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
}
} else if (split[0].equalsIgnoreCase("/warp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /warp [warpname]");
return;
}
ea toWarp = e;
Warp warp = null;
if (split.length == 3 && etc.getInstance().canIgnoreRestrictions(e)) {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
toWarp = match(split[2]);
} else {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
}
if (toWarp != null) {
if (warp != null) {
if (!etc.getInstance().isUserInGroup(e, warp.Group) && !warp.Group.equals("")) {
msg(Colors.Rose + "Warp not found.");
} else {
toWarp.a.a(warp.Location.x, warp.Location.y, warp.Location.z, warp.Location.rotX, warp.Location.rotY);
toWarp.a.msg(Colors.Rose + "Woosh!");
}
} else {
msg(Colors.Rose + "Warp not found");
}
} else {
msg(Colors.Rose + "Player not found.");
}
} else if (split[0].equalsIgnoreCase("/listwarps") && etc.getInstance().getDataSource().hasWarps()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available warps: " + Colors.White + etc.getInstance().getDataSource().getWarpNames(e.aq));
return;
}
} else if (split[0].equalsIgnoreCase("/setwarp")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname] [group]");
} else {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname]");
}
return;
}
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp warp = new Warp();
warp.Name = split[1];
warp.Location = loc;
if (split.length == 3) {
warp.Group = split[2];
} else {
warp.Group = "";
}
etc.getInstance().setWarp(warp);
msg(Colors.Rose + "Created warp point " + split[1] + ".");
} else if (split[0].equalsIgnoreCase("/lighter")) {
if (MinecraftServer.b.containsKey(this.e.aq + " lighter")) {
a.info(this.e.aq + " failed to iron!");
msg(Colors.Rose + "You can't create another lighter again so soon");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
MinecraftServer.b.put(this.e.aq + " lighter", Integer.valueOf(6000));
}
a.info(this.e.aq + " created a lighter!");
this.e.a(new gp(259, 1));
}
} else if ((paramString.startsWith("/#")) && (this.d.f.g(this.e.aq))) {
String str = paramString.substring(2);
a.info(this.e.aq + " issued server command: " + str);
this.d.a(str, this);
} else if (split[0].equalsIgnoreCase("/time")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /time [time|day|night]");
return;
}
if (split[1].equalsIgnoreCase("day")) {
this.d.e.c = 0; //morning.
} else if (split[1].equalsIgnoreCase("night")) {
this.d.e.c = 500000; //approx value for midnight basically
} else {
try {
this.d.e.c = Long.parseLong(split[1]);
} catch (NumberFormatException e) {
msg(Colors.Rose + "Please enter numbers, not letters.");
}
}
} else if (split[0].equalsIgnoreCase("/getpos")) {
msg("Pos X: " + e.k + " Y: " + e.l + " Z " + e.m);
msg("Rotation X: " + e.q + " Y: " + e.r);
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg("Compass: " + etc.getCompassPointForDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
} else if (split[0].equalsIgnoreCase("/compass")) {
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg(Colors.Rose + "Compass: " + etc.getCompassPointForDirection(degreeRotation));
} else if (split[0].equalsIgnoreCase("/motd")) {
for (String str : etc.getInstance().motd) {
msg(str);
}
} else {
a.info(this.e.aq + " tried command " + paramString);
msg(Colors.Rose + "Unknown command");
}
} catch (Exception ex) {
a.log(Level.SEVERE, "Exception in command handler (Report this to hey0 unless you did something dumb like enter letters as numbers):", ex);
if (etc.getInstance().isAdmin(e)) {
msg(Colors.Rose + "Exception occured. Check the server for more info.");
}
}
}
public void a(o paramo) {
if (paramo.b == 1) {
this.e.y();
}
}
public void a(io paramio) {
this.b.a("Quitting");
}
public int b() {
return this.b.d();
}
public void b(String paramString) {
b(new ba("§7" + paramString));
}
public String c() {
return this.e.aq;
}
public void a(r paramr) {
if (paramr.a == -1) {
this.e.aj.a = paramr.b;
}
if (paramr.a == -2) {
this.e.aj.c = paramr.b;
}
if (paramr.a == -3) {
this.e.aj.b = paramr.b;
}
}
public void d() {
this.b.a(new r(-1, this.e.aj.a));
this.b.a(new r(-2, this.e.aj.c));
this.b.a(new r(-3, this.e.aj.b));
}
public void a(ib paramib) {
as localas = this.d.e.k(paramib.a, paramib.b, paramib.c);
if (localas != null) {
localas.a(paramib.e);
localas.c();
}
}
}
| false | true | private void d(String paramString) {
try {
String[] split = paramString.split(" ");
if (!etc.getInstance().canUseCommand(e.aq, split[0]) && !split[0].startsWith("/#")) {
msg(Colors.Rose + "Unknown command.");
return;
}
if (split[0].equalsIgnoreCase("/help")) {
//Meh, not the greatest way, but not the worst either.
List<String> availableCommands = new ArrayList<String>();
for (Entry<String, String> entry : etc.getInstance().commands.entrySet()) {
if (etc.getInstance().canUseCommand(e.aq, entry.getKey())) {
if (entry.getKey().equals("/kit") && !etc.getInstance().getDataSource().hasKits()) {
continue;
}
if (entry.getKey().equals("/listwarps") && !etc.getInstance().getDataSource().hasWarps()) {
continue;
}
availableCommands.add(entry.getKey() + " " + entry.getValue());
}
}
msg(Colors.Blue + "Available commands (Page " + (split.length == 2 ? split[1] : "1") + " of " + (int) Math.ceil((double) availableCommands.size() / (double) 7) + ") [] = required <> = optional:");
if (split.length == 2) {
try {
int amount = Integer.parseInt(split[1]);
if (amount > 0) {
amount = (amount - 1) * 7;
} else {
amount = 0;
}
for (int i = amount; i < amount + 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
} catch (NumberFormatException ex) {
msg(Colors.Rose + "Not a valid page number.");
}
} else {
for (int i = 0; i < 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
}
} else if (split[0].equalsIgnoreCase("/reload")) {
etc.getInstance().load();
etc.getInstance().loadData();
a.info("Reloaded config");
msg("Successfuly reloaded config");
} else if ((split[0].equalsIgnoreCase("/modify") || split[0].equalsIgnoreCase("/mp"))) {
if (split.length < 4) {
msg(Colors.Rose + "Usage is: /modify [player] [key] [value]");
msg(Colors.Rose + "Keys:");
msg(Colors.Rose + "prefix: only the letter the color represents");
msg(Colors.Rose + "commands: list seperated by comma");
msg(Colors.Rose + "groups: list seperated by comma");
msg(Colors.Rose + "ignoresrestrictions: true or false");
msg(Colors.Rose + "admin: true or false");
msg(Colors.Rose + "modworld: true or false");
return;
}
ea player = match(split[1]);
if (player == null) {
msg(Colors.Rose + "Player does not exist.");
return;
}
String key = split[2];
String value = split[3];
User user = etc.getInstance().getUser(split[1]);
boolean newUser = false;
if (user == null) {
if (!key.equalsIgnoreCase("groups") && !key.equalsIgnoreCase("g")) {
msg(Colors.Rose + "When adding a new user, set their group(s) first.");
return;
}
msg(Colors.Rose + "Adding new user.");
newUser = true;
user = new User();
user.Name = split[1];
user.Administrator = false;
user.CanModifyWorld = true;
user.IgnoreRestrictions = false;
user.Commands = new String[]{""};
user.Prefix = "";
}
if (key.equalsIgnoreCase("prefix") || key.equalsIgnoreCase("p")) {
user.Prefix = value;
} else if (key.equalsIgnoreCase("commands") || key.equalsIgnoreCase("c")) {
user.Commands = value.split(",");
} else if (key.equalsIgnoreCase("groups") || key.equalsIgnoreCase("g")) {
user.Groups = value.split(",");
} else if (key.equalsIgnoreCase("ignoresrestrictions") || key.equalsIgnoreCase("ir")) {
user.IgnoreRestrictions = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("admin") || key.equalsIgnoreCase("a")) {
user.Administrator = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("modworld") || key.equalsIgnoreCase("mw")) {
user.CanModifyWorld = value.equalsIgnoreCase("true") || value.equals("1");
}
if (newUser) {
etc.getInstance().getDataSource().addUser(user);
} else {
etc.getInstance().getDataSource().modifyUser(user);
}
msg(Colors.Rose + "Modified user.");
a.info("Modifed user " + split[1] + ". " + key + " => " + value + " by " + e.aq);
} else if (split[0].equalsIgnoreCase("/whitelist")) {
if (split.length != 3) {
msg(Colors.Rose + "whitelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToWhitelist(split[2]);
msg(Colors.Rose + split[2] + " added to whitelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromWhitelist(split[2]);
msg(Colors.Rose + split[2] + " removed from whitelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/reservelist")) {
if (split.length != 3) {
msg(Colors.Rose + "reservelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToReserveList(split[2]);
msg(Colors.Rose + split[2] + " added to reservelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromReserveList(split[2]);
msg(Colors.Rose + split[2] + " removed from reservelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/mute")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /mute [player]");
return;
}
ea player = match(split[1]);
if (player != null) {
if (etc.getInstance().toggleMute(player)) {
msg(Colors.Rose + "player was muted");
} else {
msg(Colors.Rose + "player was unmuted");
}
} else {
msg(Colors.Rose + "Can't find player " + split[1]);
}
} else if ((split[0].equalsIgnoreCase("/msg") || split[0].equalsIgnoreCase("/tell")) || split[0].equalsIgnoreCase("/m")) {
if (split.length < 3) {
msg(Colors.Rose + "Correct usage is: /msg [player] [message]");
return;
}
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (player.aq.equals(e.aq)) {
msg(Colors.Rose + "You can't message yourself!");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
player.a.msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
} else {
msg(Colors.Rose + "Couldn't find player " + split[1]);
}
} else if (split[0].equalsIgnoreCase("/kit") && etc.getInstance().getDataSource().hasKits()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available kits: " + Colors.White + etc.getInstance().getDataSource().getKitNames(e.aq));
return;
}
ea toGive = e;
if (split.length > 2 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[1]);
}
Kit kit = etc.getInstance().getDataSource().getKit(split[1]);
if (toGive != null) {
if (kit != null) {
if (!etc.getInstance().isUserInGroup(e, kit.Group) && !kit.Group.equals("")) {
msg(Colors.Rose + "That kit does not exist.");
} else if (onlyOneUseKits.contains(kit.Name)) {
msg(Colors.Rose + "You can only get this kit once per login.");
} else if (MinecraftServer.b.containsKey(this.e.aq + " " + kit.Name)) {
msg(Colors.Rose + "You can't get this kit again for a while.");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
if (kit.Delay >= 0) {
MinecraftServer.b.put(this.e.aq + " " + kit.Name, kit.Delay);
} else {
onlyOneUseKits.add(kit.Name);
}
}
a.info(this.e.aq + " got a kit!");
toGive.a.msg(Colors.Rose + "Enjoy this kit!");
for (Map.Entry<String, Integer> entry : kit.IDs.entrySet()) {
try {
int itemId = 0;
try {
itemId = Integer.parseInt(entry.getKey());
} catch (NumberFormatException n) {
itemId = etc.getInstance().getDataSource().getItem(entry.getKey());
}
int temp = kit.IDs.get(entry.getKey());
do {
if (temp - 64 >= 64) {
toGive.a(new gn(itemId, 64));
} else {
toGive.a(new gn(itemId, temp));
}
temp -= 64;
} while (temp >= 64);
} catch (Exception e1) {
a.info("Got an exception while giving out a kit (Kit name \"" + kit.Name + "\"). Are you sure all the Ids are numbers?");
msg(Colors.Rose + "The server encountered a problem while giving the kit :(");
}
}
}
} else {
msg(Colors.Rose + "That kit does not exist.");
}
} else {
msg(Colors.Rose + "That user does not exist.");
}
} else if (split[0].equalsIgnoreCase("/tp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tp [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "You're alreaea here!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported to " + player.aq);
a(player.l, player.m, player.n, player.r, player.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if ((split[0].equalsIgnoreCase("/tphere") || split[0].equalsIgnoreCase("/s"))) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tphere [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "Wow look at that! You teleported yourself to yourself!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported " + player.aq + " to their self.");
player.a.a(e.l, e.m, e.n, e.r, e.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/playerlist") || split[0].equalsIgnoreCase("/who")) {
msg(Colors.Rose + "Player list (" + d.f.b.size() + "/" + etc.getInstance().playerLimit + "): " + Colors.White + d.f.c());
} else if (split[0].equalsIgnoreCase("/item") || split[0].equalsIgnoreCase("/i") || split[0].equalsIgnoreCase("/give")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount> <player> (optional)");
} else {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount>");
}
return;
}
ea toGive = e;
if (split.length == 4 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[3]);
}
if (toGive != null) {
try {
int i2 = 0;
try {
i2 = Integer.parseInt(split[1]);
} catch (NumberFormatException n) {
i2 = etc.getInstance().getDataSource().getItem(split[1]);
}
int i3 = 1;
if (split.length > 2) {
i3 = Integer.parseInt(split[2]);
}
String i2str = Integer.toString(i2);
if (i3 <= 0) {
i3 = 1;
}
if (i3 > 64 && !etc.getInstance().canIgnoreRestrictions(this.e)) {
i3 = 64;
}
boolean allowedItem = false;
if (!etc.getInstance().allowedItems[0].equals("") && (!etc.getInstance().canIgnoreRestrictions(this.e))) {
for (String str : etc.getInstance().allowedItems) {
if (i2str.equals(str)) {
allowedItem = true;
}
}
} else {
allowedItem = true;
}
if (!etc.getInstance().disallowedItems[0].equals("") && !etc.getInstance().canIgnoreRestrictions(this.e)) {
for (String str : etc.getInstance().disallowedItems) {
if (i2str.equals(str)) {
allowedItem = false;
}
}
}
if (i2 < ff.n.length) {
if (ff.n[i2] != null && (allowedItem || etc.getInstance().canIgnoreRestrictions(this.e))) {
a.log(Level.INFO, "Giving " + toGive.aq + " some " + i2);
int temp = i3;
do {
if (temp - 64 >= 64) {
toGive.a(new gn(i2, 64));
} else {
toGive.a(new gn(i2, temp));
}
temp -= 64;
} while (temp >= 64);
if (toGive == this.e) {
msg(Colors.Rose + "There you go c:");
} else {
msg(Colors.Rose + "Gift given! :D");
toGive.a.msg(Colors.Rose + "Enjoy your gift! :D");
}
} else if ((!allowedItem) && (ff.n[i2] != null) && !etc.getInstance().canIgnoreRestrictions(this.e)) {
msg(Colors.Rose + "You are not allowed to spawn that item.");
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} catch (NumberFormatException localNumberFormatException) {
msg(Colors.Rose + "Improper ID and/or amount.");
}
} else {
msg(Colors.Rose + "Can't find user " + split[3]);
}
} else if (split[0].equalsIgnoreCase("/banlist")) {
byte type = 0;
if (split.length == 2) {
if (split[1].equalsIgnoreCase("ips")) {
type = 1;
}
}
if (type == 0) { //Regular user bans
msg(Colors.Blue + "Ban list:" + Colors.White + " " + d.f.getBans());
} else { //IP bans
msg(Colors.Blue + "IP Ban list:" + Colors.White + " " + d.f.getBans());
}
} else if (split[0].equalsIgnoreCase("/banip")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /banip [player] <reason> (optional) NOTE: this permabans IPs.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.c(player.a.b.b().toString());
a.log(Level.INFO, "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
msg(Colors.Rose + "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
if (split.length > 2) {
player.a.c("IP Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("IP Banned by " + e.aq + ".");
}
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/ban")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /ban [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.a(player.aq);
if (split.length > 2) {
player.a.c("Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Banned by " + e.aq + ".");
}
a.log(Level.INFO, "Banning " + player.aq);
msg(Colors.Rose + "Banning " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/unban")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unban [player]");
return;
}
this.d.f.b(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/unbanip")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unbanip [ip]");
return;
}
this.d.f.d(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/kick")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /kick [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't kick that user.");
return;
}
if (split.length > 2) {
player.a.c("Kicked by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Kicked by " + e.aq + ".");
}
a.log(Level.INFO, "Kicking " + player.aq);
msg(Colors.Rose + "Kicking " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/me")) {
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
String paramString2 = "* " + prefix + this.e.aq + Colors.White + " " + paramString.substring(paramString.indexOf(" ")).trim();
a.info("* " + this.e.aq + " " + paramString.substring(paramString.indexOf(" ")).trim());
this.d.f.a(new ba(paramString2));
} else if (split[0].equalsIgnoreCase("/sethome")) {
// player.k, player.l, player.m
// x, y, z
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp home = new Warp();
home.Location = loc;
home.Group = ""; //no group neccessary, lol.
home.Name = e.aq;
etc.getInstance().changeHome(home);
msg(Colors.Rose + "Your home has been set.");
} else if (split[0].equalsIgnoreCase("/spawn")) {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
} else if (split[0].equalsIgnoreCase("/setspawn")) {
this.d.e.n = (int) Math.ceil(e.l);
//Too lazy to actually update this considering it's not even used anyways.
//this.d.e.n = (int) Math.ceil(e.m); //Not that the Y axis really matters since it tries to get the highest point iirc.
this.d.e.p = (int) Math.ceil(e.n);
a.info("Spawn position changed.");
msg(Colors.Rose + "You have set the spawn to your current position.");
} else if (split[0].equalsIgnoreCase("/home")) {
a.info(this.e.aq + " returned home");
Warp home = etc.getInstance().getDataSource().getHome(e.aq);
if (home != null) {
a(home.Location.x, home.Location.y, home.Location.z, home.Location.rotX, home.Location.rotY);
} else {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
}
} else if (split[0].equalsIgnoreCase("/warp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /warp [warpname]");
return;
}
ea toWarp = e;
Warp warp = null;
if (split.length == 3 && etc.getInstance().canIgnoreRestrictions(e)) {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
toWarp = match(split[2]);
} else {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
}
if (toWarp != null) {
if (warp != null) {
if (!etc.getInstance().isUserInGroup(e, warp.Group) && !warp.Group.equals("")) {
msg(Colors.Rose + "Warp not found.");
} else {
toWarp.a.a(warp.Location.x, warp.Location.y, warp.Location.z, warp.Location.rotX, warp.Location.rotY);
toWarp.a.msg(Colors.Rose + "Woosh!");
}
} else {
msg(Colors.Rose + "Warp not found");
}
} else {
msg(Colors.Rose + "Player not found.");
}
} else if (split[0].equalsIgnoreCase("/listwarps") && etc.getInstance().getDataSource().hasWarps()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available warps: " + Colors.White + etc.getInstance().getDataSource().getWarpNames(e.aq));
return;
}
} else if (split[0].equalsIgnoreCase("/setwarp")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname] [group]");
} else {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname]");
}
return;
}
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp warp = new Warp();
warp.Name = split[1];
warp.Location = loc;
if (split.length == 3) {
warp.Group = split[2];
} else {
warp.Group = "";
}
etc.getInstance().setWarp(warp);
msg(Colors.Rose + "Created warp point " + split[1] + ".");
} else if (split[0].equalsIgnoreCase("/lighter")) {
if (MinecraftServer.b.containsKey(this.e.aq + " lighter")) {
a.info(this.e.aq + " failed to iron!");
msg(Colors.Rose + "You can't create another lighter again so soon");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
MinecraftServer.b.put(this.e.aq + " lighter", Integer.valueOf(6000));
}
a.info(this.e.aq + " created a lighter!");
this.e.a(new gp(259, 1));
}
} else if ((paramString.startsWith("/#")) && (this.d.f.g(this.e.aq))) {
String str = paramString.substring(2);
a.info(this.e.aq + " issued server command: " + str);
this.d.a(str, this);
} else if (split[0].equalsIgnoreCase("/time")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /time [time|day|night]");
return;
}
if (split[1].equalsIgnoreCase("day")) {
this.d.e.c = 0; //morning.
} else if (split[1].equalsIgnoreCase("night")) {
this.d.e.c = 500000; //approx value for midnight basically
} else {
try {
this.d.e.c = Long.parseLong(split[1]);
} catch (NumberFormatException e) {
msg(Colors.Rose + "Please enter numbers, not letters.");
}
}
} else if (split[0].equalsIgnoreCase("/getpos")) {
msg("Pos X: " + e.k + " Y: " + e.l + " Z " + e.m);
msg("Rotation X: " + e.q + " Y: " + e.r);
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg("Compass: " + etc.getCompassPointForDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
} else if (split[0].equalsIgnoreCase("/compass")) {
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg(Colors.Rose + "Compass: " + etc.getCompassPointForDirection(degreeRotation));
} else if (split[0].equalsIgnoreCase("/motd")) {
for (String str : etc.getInstance().motd) {
msg(str);
}
} else {
a.info(this.e.aq + " tried command " + paramString);
msg(Colors.Rose + "Unknown command");
}
} catch (Exception ex) {
a.log(Level.SEVERE, "Exception in command handler (Report this to hey0 unless you did something dumb like enter letters as numbers):", ex);
if (etc.getInstance().isAdmin(e)) {
msg(Colors.Rose + "Exception occured. Check the server for more info.");
}
}
}
| private void d(String paramString) {
try {
String[] split = paramString.split(" ");
if (!etc.getInstance().canUseCommand(e.aq, split[0]) && !split[0].startsWith("/#")) {
msg(Colors.Rose + "Unknown command.");
return;
}
if (split[0].equalsIgnoreCase("/help")) {
//Meh, not the greatest way, but not the worst either.
List<String> availableCommands = new ArrayList<String>();
for (Entry<String, String> entry : etc.getInstance().commands.entrySet()) {
if (etc.getInstance().canUseCommand(e.aq, entry.getKey())) {
if (entry.getKey().equals("/kit") && !etc.getInstance().getDataSource().hasKits()) {
continue;
}
if (entry.getKey().equals("/listwarps") && !etc.getInstance().getDataSource().hasWarps()) {
continue;
}
availableCommands.add(entry.getKey() + " " + entry.getValue());
}
}
msg(Colors.Blue + "Available commands (Page " + (split.length == 2 ? split[1] : "1") + " of " + (int) Math.ceil((double) availableCommands.size() / (double) 7) + ") [] = required <> = optional:");
if (split.length == 2) {
try {
int amount = Integer.parseInt(split[1]);
if (amount > 0) {
amount = (amount - 1) * 7;
} else {
amount = 0;
}
for (int i = amount; i < amount + 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
} catch (NumberFormatException ex) {
msg(Colors.Rose + "Not a valid page number.");
}
} else {
for (int i = 0; i < 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
}
} else if (split[0].equalsIgnoreCase("/reload")) {
etc.getInstance().load();
etc.getInstance().loadData();
a.info("Reloaded config");
msg("Successfuly reloaded config");
} else if ((split[0].equalsIgnoreCase("/modify") || split[0].equalsIgnoreCase("/mp"))) {
if (split.length < 4) {
msg(Colors.Rose + "Usage is: /modify [player] [key] [value]");
msg(Colors.Rose + "Keys:");
msg(Colors.Rose + "prefix: only the letter the color represents");
msg(Colors.Rose + "commands: list seperated by comma");
msg(Colors.Rose + "groups: list seperated by comma");
msg(Colors.Rose + "ignoresrestrictions: true or false");
msg(Colors.Rose + "admin: true or false");
msg(Colors.Rose + "modworld: true or false");
return;
}
ea player = match(split[1]);
if (player == null) {
msg(Colors.Rose + "Player does not exist.");
return;
}
String key = split[2];
String value = split[3];
User user = etc.getInstance().getUser(split[1]);
boolean newUser = false;
if (user == null) {
if (!key.equalsIgnoreCase("groups") && !key.equalsIgnoreCase("g")) {
msg(Colors.Rose + "When adding a new user, set their group(s) first.");
return;
}
msg(Colors.Rose + "Adding new user.");
newUser = true;
user = new User();
user.Name = split[1];
user.Administrator = false;
user.CanModifyWorld = true;
user.IgnoreRestrictions = false;
user.Commands = new String[]{""};
user.Prefix = "";
}
if (key.equalsIgnoreCase("prefix") || key.equalsIgnoreCase("p")) {
user.Prefix = value;
} else if (key.equalsIgnoreCase("commands") || key.equalsIgnoreCase("c")) {
user.Commands = value.split(",");
} else if (key.equalsIgnoreCase("groups") || key.equalsIgnoreCase("g")) {
user.Groups = value.split(",");
} else if (key.equalsIgnoreCase("ignoresrestrictions") || key.equalsIgnoreCase("ir")) {
user.IgnoreRestrictions = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("admin") || key.equalsIgnoreCase("a")) {
user.Administrator = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("modworld") || key.equalsIgnoreCase("mw")) {
user.CanModifyWorld = value.equalsIgnoreCase("true") || value.equals("1");
}
if (newUser) {
etc.getInstance().getDataSource().addUser(user);
} else {
etc.getInstance().getDataSource().modifyUser(user);
}
msg(Colors.Rose + "Modified user.");
a.info("Modifed user " + split[1] + ". " + key + " => " + value + " by " + e.aq);
} else if (split[0].equalsIgnoreCase("/whitelist")) {
if (split.length != 3) {
msg(Colors.Rose + "whitelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToWhitelist(split[2]);
msg(Colors.Rose + split[2] + " added to whitelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromWhitelist(split[2]);
msg(Colors.Rose + split[2] + " removed from whitelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/reservelist")) {
if (split.length != 3) {
msg(Colors.Rose + "reservelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToReserveList(split[2]);
msg(Colors.Rose + split[2] + " added to reservelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromReserveList(split[2]);
msg(Colors.Rose + split[2] + " removed from reservelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/mute")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /mute [player]");
return;
}
ea player = match(split[1]);
if (player != null) {
if (etc.getInstance().toggleMute(player)) {
msg(Colors.Rose + "player was muted");
} else {
msg(Colors.Rose + "player was unmuted");
}
} else {
msg(Colors.Rose + "Can't find player " + split[1]);
}
} else if ((split[0].equalsIgnoreCase("/msg") || split[0].equalsIgnoreCase("/tell")) || split[0].equalsIgnoreCase("/m")) {
if (split.length < 3) {
msg(Colors.Rose + "Correct usage is: /msg [player] [message]");
return;
}
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (player.aq.equals(e.aq)) {
msg(Colors.Rose + "You can't message yourself!");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
player.a.msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
} else {
msg(Colors.Rose + "Couldn't find player " + split[1]);
}
} else if (split[0].equalsIgnoreCase("/kit") && etc.getInstance().getDataSource().hasKits()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available kits: " + Colors.White + etc.getInstance().getDataSource().getKitNames(e.aq));
return;
}
ea toGive = e;
if (split.length > 2 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[1]);
}
Kit kit = etc.getInstance().getDataSource().getKit(split[1]);
if (toGive != null) {
if (kit != null) {
if (!etc.getInstance().isUserInGroup(e, kit.Group) && !kit.Group.equals("")) {
msg(Colors.Rose + "That kit does not exist.");
} else if (onlyOneUseKits.contains(kit.Name)) {
msg(Colors.Rose + "You can only get this kit once per login.");
} else if (MinecraftServer.b.containsKey(this.e.aq + " " + kit.Name)) {
msg(Colors.Rose + "You can't get this kit again for a while.");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
if (kit.Delay >= 0) {
MinecraftServer.b.put(this.e.aq + " " + kit.Name, kit.Delay);
} else {
onlyOneUseKits.add(kit.Name);
}
}
a.info(this.e.aq + " got a kit!");
toGive.a.msg(Colors.Rose + "Enjoy this kit!");
for (Map.Entry<String, Integer> entry : kit.IDs.entrySet()) {
try {
int itemId = 0;
try {
itemId = Integer.parseInt(entry.getKey());
} catch (NumberFormatException n) {
itemId = etc.getInstance().getDataSource().getItem(entry.getKey());
}
int temp = kit.IDs.get(entry.getKey());
do {
if (temp - 64 >= 64) {
toGive.a(new gp(itemId, 64));
} else {
toGive.a(new gp(itemId, temp));
}
temp -= 64;
} while (temp >= 64);
} catch (Exception e1) {
a.info("Got an exception while giving out a kit (Kit name \"" + kit.Name + "\"). Are you sure all the Ids are numbers?");
msg(Colors.Rose + "The server encountered a problem while giving the kit :(");
}
}
}
} else {
msg(Colors.Rose + "That kit does not exist.");
}
} else {
msg(Colors.Rose + "That user does not exist.");
}
} else if (split[0].equalsIgnoreCase("/tp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tp [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "You're already here!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported to " + player.aq);
a(player.l, player.m, player.n, player.r, player.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if ((split[0].equalsIgnoreCase("/tphere") || split[0].equalsIgnoreCase("/s"))) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tphere [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "Wow look at that! You teleported yourself to yourself!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported " + player.aq + " to their self.");
player.a.a(e.l, e.m, e.n, e.r, e.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/playerlist") || split[0].equalsIgnoreCase("/who")) {
msg(Colors.Rose + "Player list (" + d.f.b.size() + "/" + etc.getInstance().playerLimit + "): " + Colors.White + d.f.c());
} else if (split[0].equalsIgnoreCase("/item") || split[0].equalsIgnoreCase("/i") || split[0].equalsIgnoreCase("/give")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount> <player> (optional)");
} else {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount>");
}
return;
}
ea toGive = e;
if (split.length == 4 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[3]);
}
if (toGive != null) {
try {
int i2 = 0;
try {
i2 = Integer.parseInt(split[1]);
} catch (NumberFormatException n) {
i2 = etc.getInstance().getDataSource().getItem(split[1]);
}
int i3 = 1;
if (split.length > 2) {
i3 = Integer.parseInt(split[2]);
}
String i2str = Integer.toString(i2);
if (i3 <= 0) {
i3 = 1;
}
if (i3 > 64 && !etc.getInstance().canIgnoreRestrictions(this.e)) {
i3 = 64;
}
boolean allowedItem = false;
if (!etc.getInstance().allowedItems[0].equals("") && (!etc.getInstance().canIgnoreRestrictions(this.e))) {
for (String str : etc.getInstance().allowedItems) {
if (i2str.equals(str)) {
allowedItem = true;
}
}
} else {
allowedItem = true;
}
if (!etc.getInstance().disallowedItems[0].equals("") && !etc.getInstance().canIgnoreRestrictions(this.e)) {
for (String str : etc.getInstance().disallowedItems) {
if (i2str.equals(str)) {
allowedItem = false;
}
}
}
if (i2 < ff.n.length) {
if (ff.n[i2] != null && (allowedItem || etc.getInstance().canIgnoreRestrictions(this.e))) {
a.log(Level.INFO, "Giving " + toGive.aq + " some " + i2);
int temp = i3;
do {
if (temp - 64 >= 64) {
toGive.a(new gp(i2, 64));
} else {
toGive.a(new gp(i2, temp));
}
temp -= 64;
} while (temp >= 64);
if (toGive == this.e) {
msg(Colors.Rose + "There you go c:");
} else {
msg(Colors.Rose + "Gift given! :D");
toGive.a.msg(Colors.Rose + "Enjoy your gift! :D");
}
} else if ((!allowedItem) && (ff.n[i2] != null) && !etc.getInstance().canIgnoreRestrictions(this.e)) {
msg(Colors.Rose + "You are not allowed to spawn that item.");
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} catch (NumberFormatException localNumberFormatException) {
msg(Colors.Rose + "Improper ID and/or amount.");
}
} else {
msg(Colors.Rose + "Can't find user " + split[3]);
}
} else if (split[0].equalsIgnoreCase("/banlist")) {
byte type = 0;
if (split.length == 2) {
if (split[1].equalsIgnoreCase("ips")) {
type = 1;
}
}
if (type == 0) { //Regular user bans
msg(Colors.Blue + "Ban list:" + Colors.White + " " + d.f.getBans());
} else { //IP bans
msg(Colors.Blue + "IP Ban list:" + Colors.White + " " + d.f.getBans());
}
} else if (split[0].equalsIgnoreCase("/banip")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /banip [player] <reason> (optional) NOTE: this permabans IPs.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.c(player.a.b.b().toString());
a.log(Level.INFO, "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
msg(Colors.Rose + "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
if (split.length > 2) {
player.a.c("IP Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("IP Banned by " + e.aq + ".");
}
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/ban")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /ban [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.a(player.aq);
if (split.length > 2) {
player.a.c("Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Banned by " + e.aq + ".");
}
a.log(Level.INFO, "Banning " + player.aq);
msg(Colors.Rose + "Banning " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/unban")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unban [player]");
return;
}
this.d.f.b(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/unbanip")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unbanip [ip]");
return;
}
this.d.f.d(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/kick")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /kick [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't kick that user.");
return;
}
if (split.length > 2) {
player.a.c("Kicked by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Kicked by " + e.aq + ".");
}
a.log(Level.INFO, "Kicking " + player.aq);
msg(Colors.Rose + "Kicking " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/me")) {
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
String paramString2 = "* " + prefix + this.e.aq + Colors.White + " " + paramString.substring(paramString.indexOf(" ")).trim();
a.info("* " + this.e.aq + " " + paramString.substring(paramString.indexOf(" ")).trim());
this.d.f.a(new ba(paramString2));
} else if (split[0].equalsIgnoreCase("/sethome")) {
// player.k, player.l, player.m
// x, y, z
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp home = new Warp();
home.Location = loc;
home.Group = ""; //no group neccessary, lol.
home.Name = e.aq;
etc.getInstance().changeHome(home);
msg(Colors.Rose + "Your home has been set.");
} else if (split[0].equalsIgnoreCase("/spawn")) {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
} else if (split[0].equalsIgnoreCase("/setspawn")) {
this.d.e.n = (int) Math.ceil(e.l);
//Too lazy to actually update this considering it's not even used anyways.
//this.d.e.n = (int) Math.ceil(e.m); //Not that the Y axis really matters since it tries to get the highest point iirc.
this.d.e.p = (int) Math.ceil(e.n);
a.info("Spawn position changed.");
msg(Colors.Rose + "You have set the spawn to your current position.");
} else if (split[0].equalsIgnoreCase("/home")) {
a.info(this.e.aq + " returned home");
Warp home = etc.getInstance().getDataSource().getHome(e.aq);
if (home != null) {
a(home.Location.x, home.Location.y, home.Location.z, home.Location.rotX, home.Location.rotY);
} else {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
}
} else if (split[0].equalsIgnoreCase("/warp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /warp [warpname]");
return;
}
ea toWarp = e;
Warp warp = null;
if (split.length == 3 && etc.getInstance().canIgnoreRestrictions(e)) {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
toWarp = match(split[2]);
} else {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
}
if (toWarp != null) {
if (warp != null) {
if (!etc.getInstance().isUserInGroup(e, warp.Group) && !warp.Group.equals("")) {
msg(Colors.Rose + "Warp not found.");
} else {
toWarp.a.a(warp.Location.x, warp.Location.y, warp.Location.z, warp.Location.rotX, warp.Location.rotY);
toWarp.a.msg(Colors.Rose + "Woosh!");
}
} else {
msg(Colors.Rose + "Warp not found");
}
} else {
msg(Colors.Rose + "Player not found.");
}
} else if (split[0].equalsIgnoreCase("/listwarps") && etc.getInstance().getDataSource().hasWarps()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available warps: " + Colors.White + etc.getInstance().getDataSource().getWarpNames(e.aq));
return;
}
} else if (split[0].equalsIgnoreCase("/setwarp")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname] [group]");
} else {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname]");
}
return;
}
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp warp = new Warp();
warp.Name = split[1];
warp.Location = loc;
if (split.length == 3) {
warp.Group = split[2];
} else {
warp.Group = "";
}
etc.getInstance().setWarp(warp);
msg(Colors.Rose + "Created warp point " + split[1] + ".");
} else if (split[0].equalsIgnoreCase("/lighter")) {
if (MinecraftServer.b.containsKey(this.e.aq + " lighter")) {
a.info(this.e.aq + " failed to iron!");
msg(Colors.Rose + "You can't create another lighter again so soon");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
MinecraftServer.b.put(this.e.aq + " lighter", Integer.valueOf(6000));
}
a.info(this.e.aq + " created a lighter!");
this.e.a(new gp(259, 1));
}
} else if ((paramString.startsWith("/#")) && (this.d.f.g(this.e.aq))) {
String str = paramString.substring(2);
a.info(this.e.aq + " issued server command: " + str);
this.d.a(str, this);
} else if (split[0].equalsIgnoreCase("/time")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /time [time|day|night]");
return;
}
if (split[1].equalsIgnoreCase("day")) {
this.d.e.c = 0; //morning.
} else if (split[1].equalsIgnoreCase("night")) {
this.d.e.c = 500000; //approx value for midnight basically
} else {
try {
this.d.e.c = Long.parseLong(split[1]);
} catch (NumberFormatException e) {
msg(Colors.Rose + "Please enter numbers, not letters.");
}
}
} else if (split[0].equalsIgnoreCase("/getpos")) {
msg("Pos X: " + e.k + " Y: " + e.l + " Z " + e.m);
msg("Rotation X: " + e.q + " Y: " + e.r);
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg("Compass: " + etc.getCompassPointForDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
} else if (split[0].equalsIgnoreCase("/compass")) {
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg(Colors.Rose + "Compass: " + etc.getCompassPointForDirection(degreeRotation));
} else if (split[0].equalsIgnoreCase("/motd")) {
for (String str : etc.getInstance().motd) {
msg(str);
}
} else {
a.info(this.e.aq + " tried command " + paramString);
msg(Colors.Rose + "Unknown command");
}
} catch (Exception ex) {
a.log(Level.SEVERE, "Exception in command handler (Report this to hey0 unless you did something dumb like enter letters as numbers):", ex);
if (etc.getInstance().isAdmin(e)) {
msg(Colors.Rose + "Exception occured. Check the server for more info.");
}
}
}
|
diff --git a/src/main/java/edu/northwestern/bioinformatics/studycalendar/dao/ChangeableDao.java b/src/main/java/edu/northwestern/bioinformatics/studycalendar/dao/ChangeableDao.java
index 5ae27c449..eb1482813 100644
--- a/src/main/java/edu/northwestern/bioinformatics/studycalendar/dao/ChangeableDao.java
+++ b/src/main/java/edu/northwestern/bioinformatics/studycalendar/dao/ChangeableDao.java
@@ -1,34 +1,34 @@
package edu.northwestern.bioinformatics.studycalendar.dao;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Changeable;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Nataliya Shurupova
*/
@Transactional(readOnly = true)
public abstract class ChangeableDao<T extends Changeable> extends StudyCalendarMutableDomainObjectDao<T>
implements DeletableDomainObjectDao<T> {
@SuppressWarnings("unchecked")
protected void deleteOrphans(String className, String parentName, String classNameDelta, String parentDeltaTypeCode) {
List<T> listOfOrphans = getHibernateTemplate().find("from "+ className +
" orphan where orphan." + parentName + " is null " +
- "AND not exists(select 'y' from Remove r join r.delta d where d.class=" + classNameDelta+ " and r.childIdText=orphan.id) " +
- "AND not exists (select 'x' from Add a join a.delta d where d.class=" + classNameDelta+ " and a.childIdText=orphan.id)");
+ "AND not exists(select 'y' from Remove r join r.delta d where d.class=" + classNameDelta+ " and orphan.id=cast(r.childIdText as int)) " +
+ "AND not exists (select 'x' from Add a join a.delta d where d.class=" + classNameDelta+ " and orphan.id=cast(a.childIdText as int))");
if (listOfOrphans!=null && listOfOrphans.size()>0) {
for (T orphan: listOfOrphans) {
delete(orphan);
}
}
}
public abstract void deleteOrphans();
}
| true | true | protected void deleteOrphans(String className, String parentName, String classNameDelta, String parentDeltaTypeCode) {
List<T> listOfOrphans = getHibernateTemplate().find("from "+ className +
" orphan where orphan." + parentName + " is null " +
"AND not exists(select 'y' from Remove r join r.delta d where d.class=" + classNameDelta+ " and r.childIdText=orphan.id) " +
"AND not exists (select 'x' from Add a join a.delta d where d.class=" + classNameDelta+ " and a.childIdText=orphan.id)");
if (listOfOrphans!=null && listOfOrphans.size()>0) {
for (T orphan: listOfOrphans) {
delete(orphan);
}
}
}
| protected void deleteOrphans(String className, String parentName, String classNameDelta, String parentDeltaTypeCode) {
List<T> listOfOrphans = getHibernateTemplate().find("from "+ className +
" orphan where orphan." + parentName + " is null " +
"AND not exists(select 'y' from Remove r join r.delta d where d.class=" + classNameDelta+ " and orphan.id=cast(r.childIdText as int)) " +
"AND not exists (select 'x' from Add a join a.delta d where d.class=" + classNameDelta+ " and orphan.id=cast(a.childIdText as int))");
if (listOfOrphans!=null && listOfOrphans.size()>0) {
for (T orphan: listOfOrphans) {
delete(orphan);
}
}
}
|
diff --git a/flume-core/src/main/java/com/cloudera/flume/core/EventImpl.java b/flume-core/src/main/java/com/cloudera/flume/core/EventImpl.java
index 63f1996..42c0365 100644
--- a/flume-core/src/main/java/com/cloudera/flume/core/EventImpl.java
+++ b/flume-core/src/main/java/com/cloudera/flume/core/EventImpl.java
@@ -1,207 +1,207 @@
/**
* Licensed to Cloudera, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Cloudera, Inc. 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.cloudera.flume.core;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.apache.commons.lang.StringEscapeUtils;
import com.cloudera.flume.conf.FlumeConfiguration;
import com.cloudera.util.Clock;
import com.cloudera.util.NetUtils;
import com.google.common.base.Preconditions;
/**
* A simple in memory implementation of an event.
*
* I'm limiting a message to be at most 32k
*/
public class EventImpl extends EventBaseImpl {
byte[] body;
long timestamp;
Priority pri;
long nanos;
String host;
final static long MAX_BODY_SIZE = FlumeConfiguration.get()
.getEventMaxSizeBytes();
/**
* Reflection based tools (like Avro) require a null constructor
*/
public EventImpl() {
this(new byte[0], 0, Priority.INFO, 0, "");
}
/**
* Copy constructor for converting events into EventImpl (required for
* reflection/Avro)
*/
public EventImpl(Event e) {
this(e.getBody(), e.getTimestamp(), e.getPriority(), e.getNanos(), e
.getHost(), new HashMap<String, byte[]>(e.getAttrs()));
}
/**
* Constructs a new event wrapping (not copying!) the provided byte array
*/
public EventImpl(byte[] s) {
this(s, Clock.unixTime(), Priority.INFO, Clock.nanos(), NetUtils
.localhost());
}
/**
* Constructs a new event wrapping (not copying!) the provided byte array
*/
public EventImpl(byte[] s, Priority pri) {
this(s, Clock.unixTime(), pri, Clock.nanos(), NetUtils.localhost());
}
/**
* Constructs a new event wrapping (not copying!) the provided byte array
*/
public EventImpl(byte[] s, long timestamp, Priority pri, long nanoTime,
String host) {
this(s, timestamp, pri, nanoTime, host, new HashMap<String, byte[]>());
}
/**
* Constructs a new event wrapping (not copying!) the provided byte array
*/
public EventImpl(byte[] s, long timestamp, Priority pri, long nanoTime,
String host, Map<String, byte[]> fields) {
super(fields);
Preconditions.checkNotNull(s,
"Failed when attempting to create event with null body");
Preconditions.checkArgument(s.length <= MAX_BODY_SIZE, "Failed when "
+ "attempting to create event with body with length (" + s.length
+ ") > max body size (" + MAX_BODY_SIZE + "). You may want to "
+ "increase flume.event.max.size.bytes in your flume-site.xml file");
// this string construction took ~5% of exec time!
// , "byte length is " + s.length + " which is not < " + MAX_BODY_SIZE);
- Preconditions.checkNotNull(pri, "Failed when atttempt to "
+ Preconditions.checkNotNull(pri, "Failed when atttempting to "
+ "create event with null priority");
this.body = s;
this.timestamp = timestamp;
this.pri = pri;
this.nanos = nanoTime;
this.host = host;
}
/**
* Returns reference to mutable body of event. NOTE: the contents of the
* returned byte array should not be modified.
*/
public byte[] getBody() {
return body;
}
public Priority getPriority() {
return pri;
}
protected void setPriority(Priority p) {
this.pri = p;
}
/**
* Returns unix time stamp in millis
*/
public long getTimestamp() {
return timestamp;
}
/**
* Set unix time stamp in millis
*/
protected void setTimestamp(long stamp) {
this.timestamp = stamp;
}
public String toString() {
String mbody = StringEscapeUtils.escapeJava(new String(getBody()));
StringBuilder attrs = new StringBuilder();
SortedMap<String, byte[]> sorted = new TreeMap<String, byte[]>(this.fields);
for (Entry<String, byte[]> e : sorted.entrySet()) {
attrs.append("{ " + e.getKey() + " : ");
String o = Attributes.toString(this, e.getKey());
attrs.append(o + " } ");
}
return getHost() + " [" + getPriority().toString() + " "
+ new Date(getTimestamp()) + "] " + attrs.toString() + mbody;
}
@Override
public long getNanos() {
return nanos;
}
@Override
public String getHost() {
return host;
}
/**
* This takes an event and a list of attribute names. It returns a new event
* that has the same core event values but *only * the attributes specified by
* the list.
*/
public static Event select(Event e, String... attrs) {
Event e2 = new EventImpl(e.getBody(), e.getTimestamp(), e.getPriority(),
e.getNanos(), e.getHost());
for (String a : attrs) {
byte[] data = e.get(a);
if (data == null) {
continue;
}
e2.set(a, data);
}
return e2;
}
/**
* This takes an event and a list of attribute names. It returns a new event
* that has the same core event values and all of the attribute/values
* *except* for those attributes specified by the list.
*/
public static Event unselect(Event e, String... attrs) {
Event e2 = new EventImpl(e.getBody(), e.getTimestamp(), e.getPriority(),
e.getNanos(), e.getHost());
List<String> as = Arrays.asList(attrs);
for (Entry<String, byte[]> ent : e.getAttrs().entrySet()) {
String a = ent.getKey();
if (as.contains(a)) {
continue; // don't add it if it is in the unselect list.
}
byte[] data = e.get(a);
e2.set(a, data);
}
return e2;
}
}
| true | true | public EventImpl(byte[] s, long timestamp, Priority pri, long nanoTime,
String host, Map<String, byte[]> fields) {
super(fields);
Preconditions.checkNotNull(s,
"Failed when attempting to create event with null body");
Preconditions.checkArgument(s.length <= MAX_BODY_SIZE, "Failed when "
+ "attempting to create event with body with length (" + s.length
+ ") > max body size (" + MAX_BODY_SIZE + "). You may want to "
+ "increase flume.event.max.size.bytes in your flume-site.xml file");
// this string construction took ~5% of exec time!
// , "byte length is " + s.length + " which is not < " + MAX_BODY_SIZE);
Preconditions.checkNotNull(pri, "Failed when atttempt to "
+ "create event with null priority");
this.body = s;
this.timestamp = timestamp;
this.pri = pri;
this.nanos = nanoTime;
this.host = host;
}
| public EventImpl(byte[] s, long timestamp, Priority pri, long nanoTime,
String host, Map<String, byte[]> fields) {
super(fields);
Preconditions.checkNotNull(s,
"Failed when attempting to create event with null body");
Preconditions.checkArgument(s.length <= MAX_BODY_SIZE, "Failed when "
+ "attempting to create event with body with length (" + s.length
+ ") > max body size (" + MAX_BODY_SIZE + "). You may want to "
+ "increase flume.event.max.size.bytes in your flume-site.xml file");
// this string construction took ~5% of exec time!
// , "byte length is " + s.length + " which is not < " + MAX_BODY_SIZE);
Preconditions.checkNotNull(pri, "Failed when atttempting to "
+ "create event with null priority");
this.body = s;
this.timestamp = timestamp;
this.pri = pri;
this.nanos = nanoTime;
this.host = host;
}
|
diff --git a/src/haven/LocalMiniMap.java b/src/haven/LocalMiniMap.java
index d5eb58db..8b469d49 100644
--- a/src/haven/LocalMiniMap.java
+++ b/src/haven/LocalMiniMap.java
@@ -1,129 +1,129 @@
/*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <[email protected]>, and
* Björn Johannessen <[email protected]>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* 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.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import static haven.MCache.cmaps;
import static haven.MCache.tilesz;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.*;
public class LocalMiniMap extends Widget {
public final MapView mv;
Tex mapimg = null;
Coord ultile = null, cgrid = null;
private final BufferedImage[] texes = new BufferedImage[256];
private BufferedImage tileimg(int t) {
BufferedImage img = texes[t];
if(img == null) {
Resource r = ui.sess.glob.map.sets[t];
if(r == null)
return(null);
Resource.Image ir = r.layer(Resource.imgc);
if(ir == null)
return(null);
img = ir.img;
texes[t] = img;
}
return(img);
}
public BufferedImage drawmap(Coord ul, Coord sz) {
MCache m = ui.sess.glob.map;
BufferedImage buf = TexI.mkbuf(sz);
Coord c = new Coord();
for(c.y = 0; c.y < sz.y; c.y++) {
for(c.x = 0; c.x < sz.x; c.x++) {
int t = m.gettile(ul.add(c));
BufferedImage tex = tileimg(t);
if(tex != null)
buf.setRGB(c.x, c.y, tex.getRGB(Utils.floormod(c.x + ul.x, tex.getWidth()),
Utils.floormod(c.y + ul.y, tex.getHeight())));
}
}
for(c.y = 0; c.y < sz.y; c.y++) {
for(c.x = 0; c.x < sz.x; c.x++) {
int t = m.gettile(ul.add(c));
if((m.gettile(ul.add(c).add(-1, 0)) > t) ||
(m.gettile(ul.add(c).add( 1, 0)) > t) ||
(m.gettile(ul.add(c).add(0, -1)) > t) ||
(m.gettile(ul.add(c).add(0, 1)) > t))
buf.setRGB(c.x, c.y, Color.BLACK.getRGB());
}
}
return(buf);
}
public LocalMiniMap(Coord c, Coord sz, Widget parent, MapView mv) {
super(c, sz, parent);
this.mv = mv;
}
public void draw(GOut g) {
Gob pl = ui.sess.glob.oc.getgob(mv.plgob);
if(pl == null)
return;
Coord plt = pl.rc.div(tilesz);
Coord plg = plt.div(cmaps);
if((cgrid == null) || !plg.equals(cgrid)) {
try {
Coord ul = plg.mul(cmaps).sub(cmaps).add(1, 1);
Tex prev = this.mapimg;
this.mapimg = new TexI(drawmap(ul, cmaps.mul(3).sub(2, 2)));
this.ultile = ul;
this.cgrid = plg;
if(prev != null)
prev.dispose();
} catch(Loading l) {}
}
if(mapimg != null) {
- GOut g2 = g.reclip(Window.swbox.tloff(), sz.sub(Window.swbox.bisz()));
+ GOut g2 = g.reclip(Window.wbox.tloff(), sz.sub(Window.wbox.bisz()));
g2.image(mapimg, ultile.sub(plt).add(sz.div(2)));
- Window.swbox.draw(g, Coord.z, sz);
+ Window.wbox.draw(g, Coord.z, sz);
try {
synchronized(ui.sess.glob.party.memb) {
for(Party.Member m : ui.sess.glob.party.memb.values()) {
Coord ptc;
try {
ptc = m.getc();
} catch(MCache.LoadingMap e) {
ptc = null;
}
if(ptc == null)
continue;
ptc = ptc.div(tilesz).sub(plt).add(sz.div(2));
g2.chcolor(m.col.getRed(), m.col.getGreen(), m.col.getBlue(), 128);
g2.image(MiniMap.plx.layer(Resource.imgc).tex(), ptc.add(MiniMap.plx.layer(Resource.negc).cc.inv()));
g2.chcolor();
}
}
} catch(Loading l) {}
}
}
}
| false | true | public void draw(GOut g) {
Gob pl = ui.sess.glob.oc.getgob(mv.plgob);
if(pl == null)
return;
Coord plt = pl.rc.div(tilesz);
Coord plg = plt.div(cmaps);
if((cgrid == null) || !plg.equals(cgrid)) {
try {
Coord ul = plg.mul(cmaps).sub(cmaps).add(1, 1);
Tex prev = this.mapimg;
this.mapimg = new TexI(drawmap(ul, cmaps.mul(3).sub(2, 2)));
this.ultile = ul;
this.cgrid = plg;
if(prev != null)
prev.dispose();
} catch(Loading l) {}
}
if(mapimg != null) {
GOut g2 = g.reclip(Window.swbox.tloff(), sz.sub(Window.swbox.bisz()));
g2.image(mapimg, ultile.sub(plt).add(sz.div(2)));
Window.swbox.draw(g, Coord.z, sz);
try {
synchronized(ui.sess.glob.party.memb) {
for(Party.Member m : ui.sess.glob.party.memb.values()) {
Coord ptc;
try {
ptc = m.getc();
} catch(MCache.LoadingMap e) {
ptc = null;
}
if(ptc == null)
continue;
ptc = ptc.div(tilesz).sub(plt).add(sz.div(2));
g2.chcolor(m.col.getRed(), m.col.getGreen(), m.col.getBlue(), 128);
g2.image(MiniMap.plx.layer(Resource.imgc).tex(), ptc.add(MiniMap.plx.layer(Resource.negc).cc.inv()));
g2.chcolor();
}
}
} catch(Loading l) {}
}
}
| public void draw(GOut g) {
Gob pl = ui.sess.glob.oc.getgob(mv.plgob);
if(pl == null)
return;
Coord plt = pl.rc.div(tilesz);
Coord plg = plt.div(cmaps);
if((cgrid == null) || !plg.equals(cgrid)) {
try {
Coord ul = plg.mul(cmaps).sub(cmaps).add(1, 1);
Tex prev = this.mapimg;
this.mapimg = new TexI(drawmap(ul, cmaps.mul(3).sub(2, 2)));
this.ultile = ul;
this.cgrid = plg;
if(prev != null)
prev.dispose();
} catch(Loading l) {}
}
if(mapimg != null) {
GOut g2 = g.reclip(Window.wbox.tloff(), sz.sub(Window.wbox.bisz()));
g2.image(mapimg, ultile.sub(plt).add(sz.div(2)));
Window.wbox.draw(g, Coord.z, sz);
try {
synchronized(ui.sess.glob.party.memb) {
for(Party.Member m : ui.sess.glob.party.memb.values()) {
Coord ptc;
try {
ptc = m.getc();
} catch(MCache.LoadingMap e) {
ptc = null;
}
if(ptc == null)
continue;
ptc = ptc.div(tilesz).sub(plt).add(sz.div(2));
g2.chcolor(m.col.getRed(), m.col.getGreen(), m.col.getBlue(), 128);
g2.image(MiniMap.plx.layer(Resource.imgc).tex(), ptc.add(MiniMap.plx.layer(Resource.negc).cc.inv()));
g2.chcolor();
}
}
} catch(Loading l) {}
}
}
|
diff --git a/jabox-persistence/src/main/java/org/jabox/environment/Environment.java b/jabox-persistence/src/main/java/org/jabox/environment/Environment.java
index ddbfa0e6..fa7bf434 100644
--- a/jabox-persistence/src/main/java/org/jabox/environment/Environment.java
+++ b/jabox-persistence/src/main/java/org/jabox/environment/Environment.java
@@ -1,97 +1,97 @@
/*
* Jabox Open Source Version
* Copyright (C) 2009-2010 Dimitris Kapanidis
*
* This file is part of Jabox
*
* 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 org.jabox.environment;
import java.io.File;
public class Environment {
private static final String JABOX_ENV = "JABOX_HOME";
private static final String JABOX_PROPERTY = "JABOX_HOME";
private static final String HUDSON_ENV = "HUDSON_HOME";
private static final String HUDSON_PROPERTY = "HUDSON_HOME";
private static final String HUDSON_DIR = ".hudson";
private static final String CUSTOM_MAVEN_DIR = ".m2";
public static String getBaseDir() {
return getHomeDir();
}
public static File getBaseDirFile() {
return new File(getBaseDir());
}
public static File getCustomMavenHomeDir() {
File m2Dir = new File(getBaseDirFile(), CUSTOM_MAVEN_DIR);
if (!m2Dir.exists()) {
m2Dir.mkdirs();
}
return m2Dir;
}
public static String getHudsonHomeDir() {
String env = System.getenv(HUDSON_ENV);
String property = System.getProperty(HUDSON_PROPERTY);
if (env != null) {
return env;
} else if (property != null) {
return property;
} else {
return Environment.getBaseDir() + HUDSON_DIR;
}
}
public static File getTmpDirFile() {
File tmpDir = new File(getBaseDirFile(), "tmp");
if (!tmpDir.exists()) {
tmpDir.mkdirs();
}
return tmpDir;
}
protected static String getHomeDir() {
String env = System.getenv(JABOX_ENV);
String property = System.getProperty(JABOX_PROPERTY);
if (env != null) {
- return env;
+ return env + File.separatorChar;
} else if (property != null) {
- return property;
+ return property + File.separatorChar;
}
String homeDir = System.getProperty("user.home") + File.separatorChar
+ ".jabox" + File.separatorChar;
System.setProperty(JABOX_PROPERTY, homeDir);
return homeDir;
}
public static void configureEnvironmentVariables() {
configBaseDir(HUDSON_ENV, HUDSON_PROPERTY, HUDSON_DIR);
configBaseDir("ARTIFACTORY_HOME", "artifactory.home", ".artifactory/");
configBaseDir("NEXUS_HOME", "plexus.nexus-work", ".nexus/");
}
private static void configBaseDir(final String env, final String property,
final String subdir) {
if (System.getenv(env) == null && System.getProperty(property) == null) {
System.setProperty(property, Environment.getBaseDir() + subdir);
}
}
}
| false | true | protected static String getHomeDir() {
String env = System.getenv(JABOX_ENV);
String property = System.getProperty(JABOX_PROPERTY);
if (env != null) {
return env;
} else if (property != null) {
return property;
}
String homeDir = System.getProperty("user.home") + File.separatorChar
+ ".jabox" + File.separatorChar;
System.setProperty(JABOX_PROPERTY, homeDir);
return homeDir;
}
| protected static String getHomeDir() {
String env = System.getenv(JABOX_ENV);
String property = System.getProperty(JABOX_PROPERTY);
if (env != null) {
return env + File.separatorChar;
} else if (property != null) {
return property + File.separatorChar;
}
String homeDir = System.getProperty("user.home") + File.separatorChar
+ ".jabox" + File.separatorChar;
System.setProperty(JABOX_PROPERTY, homeDir);
return homeDir;
}
|
diff --git a/asm/src/org/objectweb/asm/optimizer/JarOptimizer.java b/asm/src/org/objectweb/asm/optimizer/JarOptimizer.java
index ac32692c..a754a4ad 100644
--- a/asm/src/org/objectweb/asm/optimizer/JarOptimizer.java
+++ b/asm/src/org/objectweb/asm/optimizer/JarOptimizer.java
@@ -1,88 +1,89 @@
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2004 INRIA, France Telecom
* 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 the copyright holders 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 COPYRIGHT OWNER 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.objectweb.asm.optimizer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* A Jar file optimizer.
*
* @author Eric Bruneton
*/
public class JarOptimizer {
public static void main (final String[] args) throws IOException {
File f = new File(args[0]);
optimize(f);
}
static void optimize (final File f) throws IOException {
if (f.isDirectory()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; ++i) {
optimize(files[i]);
}
} else if (f.getName().endsWith(".jar")) {
File g = new File(f.getParentFile(), f.getName() + ".new");
ZipFile zf = new ZipFile(f);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(g));
Enumeration e = zf.entries();
byte[] buf = new byte[10000];
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry)e.nextElement();
if (ze.isDirectory()) {
continue;
}
out.putNextEntry(ze);
InputStream is = zf.getInputStream(ze);
int n;
do {
n = is.read(buf, 0, buf.length);
if (n != -1) {
out.write(buf, 0, n);
}
} while (n != -1);
out.closeEntry();
}
out.close();
+ zf.close();
f.delete();
g.renameTo(f);
}
}
}
| true | true | static void optimize (final File f) throws IOException {
if (f.isDirectory()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; ++i) {
optimize(files[i]);
}
} else if (f.getName().endsWith(".jar")) {
File g = new File(f.getParentFile(), f.getName() + ".new");
ZipFile zf = new ZipFile(f);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(g));
Enumeration e = zf.entries();
byte[] buf = new byte[10000];
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry)e.nextElement();
if (ze.isDirectory()) {
continue;
}
out.putNextEntry(ze);
InputStream is = zf.getInputStream(ze);
int n;
do {
n = is.read(buf, 0, buf.length);
if (n != -1) {
out.write(buf, 0, n);
}
} while (n != -1);
out.closeEntry();
}
out.close();
f.delete();
g.renameTo(f);
}
}
| static void optimize (final File f) throws IOException {
if (f.isDirectory()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; ++i) {
optimize(files[i]);
}
} else if (f.getName().endsWith(".jar")) {
File g = new File(f.getParentFile(), f.getName() + ".new");
ZipFile zf = new ZipFile(f);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(g));
Enumeration e = zf.entries();
byte[] buf = new byte[10000];
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry)e.nextElement();
if (ze.isDirectory()) {
continue;
}
out.putNextEntry(ze);
InputStream is = zf.getInputStream(ze);
int n;
do {
n = is.read(buf, 0, buf.length);
if (n != -1) {
out.write(buf, 0, n);
}
} while (n != -1);
out.closeEntry();
}
out.close();
zf.close();
f.delete();
g.renameTo(f);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.